_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
c40f9b2c2bcec568513b5a8853a474282a97809535a234f3c1a70806f086d201
imitator-model-checker/imitator
OCamlUtilities.mli
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * IMITATOR * * Laboratoire Spécification et Vérification ( ENS Cachan & CNRS , France ) * Université Paris 13 , LIPN , CNRS , France * * Module description : Useful OCaml functions * * File contributors : * Created : 2014/10/24 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * IMITATOR * * Laboratoire Spécification et Vérification (ENS Cachan & CNRS, France) * Université Paris 13, LIPN, CNRS, France * * Module description: Useful OCaml functions * * File contributors : Étienne André * Created : 2014/10/24 * ************************************************************) (************************************************************) (** Useful functions on integers *) (************************************************************) * Check if an integer is a power of two , i.e. , n = 2^m , with m > = 1 val is_a_power_of_2 : int -> bool (************************************************************) (** Useful functions on float *) (************************************************************) * Round a float with 1 digit after comma , and convert to string val round1_float : float -> string * Round a float with 3 digits after comma , and convert to string val round3_float : float -> string (************************************************************) (** Useful functions on options *) (************************************************************) * Get the value of an ' a option that is assumed to be different from None , or raise NoneException otherwise val a_of_a_option : 'a option -> 'a (************************************************************) (** Useful lambda functions *) (************************************************************) val identity : 'a -> 'a (************************************************************) (** Useful functions on tuples *) (************************************************************) val first_of_tuple : 'a * 'b -> 'a val second_of_tuple : 'a * 'b -> 'b (************************************************************) (** Useful functions on lists *) (************************************************************) (** Check if a list is empty *) val list_empty : 'a list -> bool (** Return a random element in a list *) val random_element : 'a list -> 'a (** list_of_interval a b Create a fresh new list filled with elements [a, a+1, ..., b-1, b] *) val list_of_interval : int -> int -> int list * Intersection of 2 lists ( keeps the order of the elements as in l1 ) val list_inter : 'a list -> 'a list -> 'a list * Union of 2 lists val list_union : 'a list -> 'a list -> 'a list * Difference of 2 lists val list_diff : 'a list -> 'a list-> 'a list (** Tail-recursive function for 'append' *) val list_append : 'a list -> 'a list -> 'a list * Returns the last element of the list , or raise Empty_list if the list is empty . This function takes linear time val list_last : 'a list -> 'a * Returns the list without its last element ; raises Empty_list if the list is empty val list_without_last : 'a list -> 'a list * Returns a pair ( the list without its last element , the last element of the list ) , or raise Empty_list if the list is empty . val list_split_last : 'a list -> 'a list * 'a (** Return a list where every element only appears once *) val list_only_once : 'a list -> 'a list (** Filter the elements appearing several times in the list *) val elements_existing_several_times : 'a list -> 'a list * Remove the first occurence of element e in list l ; return the list unchanged if not found val list_remove_first_occurence : 'a -> 'a list -> 'a list (** Remove the ith element of a list *) val list_delete_at : int -> 'a list -> 'a list (** Replace the ith element of a list *) val list_set_nth : int -> 'a -> 'a list -> 'a list * Get combination of two list * val list_combination : 'a list -> 'a list -> ('a * 'a) list (* Check if predicate is true for all arrangement of list *) val for_all_in_arrangement : ('a -> 'a -> bool) -> 'a list -> bool (** Select the sublist of a list from position i to position j *) val sublist : int -> int -> 'a list -> 'a list (* Partition list by grouping elements by keys in a list of tuples *) val group_by : ('a -> 'b) -> 'a list -> ('b * 'a list) list (* Partition list by grouping elements by keys in a list of tuples *) (* and map values associated by keys according to valueSelector function *) val group_by_and_map : ('a -> 'b) -> ('a -> 'c) -> 'a list -> ('b * 'c list) list (* Type used for partition map *) type ('a, 'b) my_either = My_left of 'a | My_right of 'b (* Partition and map list *) val partition_map : ('a -> ('b, 'c) my_either) -> 'a list -> ('b list * 'c list) (* Partition list by grouping elements by keys in a hashtable *) val hashtbl_group_by : ('a -> 'b) -> 'a list -> ('b, 'a list) Hashtbl.t (* Create an hashtbl from a list of tuples *) Raise an error if two pairs have the same key val hashtbl_of_tuples : ('a * 'b) list -> ('a, 'b) Hashtbl.t (************************************************************) (** Useful functions on arrays *) (************************************************************) (* Check if an element belongs to an array *) val in_array : 'a -> 'a array -> bool Returns the ( first ) index of an element in an array , or raise Not_found if not found val index_of : 'a -> 'a array -> int (* Return the list of the indexes whose value is true *) val true_indexes : bool array -> int list (* Shuffle an array *) (* val shuffle_array : 'a array -> unit *) * exists p { a1 ; ... ; an } checks if at least one element of the Array satisfies the predicate p. That is , it returns ( p a1 ) || ( p a2 ) || ... || ( p an ) . val array_exists : ('a -> bool) -> 'a array -> bool (** Shuffles the values of an array *) val array_shuffle : 'a array -> unit * Perform the substraction of 2 NumConst array of same size * val sub_array : NumConst.t array -> NumConst.t array -> NumConst.t array (************************************************************) (** Useful functions on dynamic arrays *) (************************************************************) exists p { a1 ; ... ; an } checks if at least one element of the DynArray satisfies the predicate p. That is , it returns ( p a1 ) || ( p a2 ) || ... || ( p an ) . val dynArray_exists : ('a -> bool) -> 'a DynArray.t -> bool (************************************************************) (** Useful functions on hash tables *) (************************************************************) (** Get all bound keys in an hash table; multiple bindings yield multiple (identical) keys *) (*** NOTE: indeed, in our setting, we only use hashtbl with a single binding ***) val hashtbl_get_all_keys : ('a , 'b) Hashtbl.t -> 'a list (** Get the binding associated to a key, or the default binding if key is not associated to any binding *) val hashtbl_get_or_default : ('a , 'b) Hashtbl.t -> 'a -> 'b -> 'b (** function to filter hash table with a predicate on keys *) val hashtbl_filter : ('a -> bool) -> ('a,'b) Hashtbl.t -> unit (************************************************************) (** Useful functions on string *) (************************************************************) (** Returns a fresh string made of 'n' times 's' *) val string_n_times : int -> string -> string (* Convert an array of string into a string *) val string_of_array_of_string : string array -> string (* Convert a list of string into a string *) val string_of_list_of_string : string list -> string (* Convert an array of string into a string with separators *) val string_of_array_of_string_with_sep : string -> string array -> string (* Convert an array of string into a string with separators removing empty strings *) val string_of_array_of_string_with_sep_without_empty_strings : string -> string array -> string (** Convert a list of string into a string with separators (uses an internal conversion to array) *) val string_of_list_of_string_with_sep : string -> string list -> string (** Convert a list of string into a string with separators removing empty strings *) val string_of_list_of_string_with_sep_without_empty_strings : string -> string list -> string (* Add \t identation of string according to the given level *) val indent_paragraph : int -> string -> string (** Convert a list of int into a string with , separator *) val string_of_list_of_int : int list -> string (* Returns a list of substrings splitted using sep *) (*** WARNING: the behavior of this function is odd (when sep=";;" or "£"; bug hidden here? ***) val split : string -> string -> string list * ' s_of_int i ' Return " s " if i > 1 , " " otherwise val s_of_int : int -> string * ' waswere_of_int i ' Return " were " if i > 1 , " was " otherwise val waswere_of_int : int -> string (** Escape \n & > for use in dot *) val escape_string_for_dot : string -> string (************************************************************) (** Useful functions on booleans *) (************************************************************) (* Evaluate both part of an 'and' comparison and return the conjunction *) val evaluate_and : bool -> bool -> bool (* Evaluate both part of an 'or' comparison and return the disjunction *) val evaluate_or : bool -> bool -> bool (* XOR: returns true if both are different *) val xor : bool -> bool -> bool (* XNOR: returns true if both are true or both are false, i.e., when both are equal to each other *) val xnor : bool -> bool -> bool (************************************************************) (** Date functions *) (************************************************************) (** Print the current date and time under the form of a string *) val now : unit -> string (**************************************************) (** System functions *) (**************************************************) * Read the first line of a file and convert to string val read_first_line_from_file : string -> string (** Read a file and convert to string *) val read_from_file : string -> string (** `write_to_file file_name file_content` will create a file `file_name` with content `file_content` *) val write_to_file : string -> string -> unit (* pow of x by e *) val pow : Int32.t -> Int32.t -> Int32.t (* pow of int of x by e *) val pow_int : int -> int -> int val modulo : Int32.t -> Int32.t -> Int32.t (* Render a beautiful and cute json from an ugly horrible json *) val prettify_json : string -> string equivalent to List.filter_map of OCaml 4.08 , but reverse the list val rev_filter_map : ('a -> 'b option) -> 'a list -> 'b list val list_to_string_set : string list -> CustomModules.StringSet.t val string_set_to_list : CustomModules.StringSet.t -> string list (* Convert list to array *) val array_of_list : 'a list -> 'a array (* Convert array to list *) val list_of_array : 'a array -> 'a list
null
https://raw.githubusercontent.com/imitator-model-checker/imitator/105408ae2bd8c3e3291f286e4d127defd492a58b/src/OCamlUtilities.mli
ocaml
********************************************************** * Useful functions on integers ********************************************************** ********************************************************** * Useful functions on float ********************************************************** ********************************************************** * Useful functions on options ********************************************************** ********************************************************** * Useful lambda functions ********************************************************** ********************************************************** * Useful functions on tuples ********************************************************** ********************************************************** * Useful functions on lists ********************************************************** * Check if a list is empty * Return a random element in a list * list_of_interval a b Create a fresh new list filled with elements [a, a+1, ..., b-1, b] * Tail-recursive function for 'append' * Return a list where every element only appears once * Filter the elements appearing several times in the list * Remove the ith element of a list * Replace the ith element of a list Check if predicate is true for all arrangement of list * Select the sublist of a list from position i to position j Partition list by grouping elements by keys in a list of tuples Partition list by grouping elements by keys in a list of tuples and map values associated by keys according to valueSelector function Type used for partition map Partition and map list Partition list by grouping elements by keys in a hashtable Create an hashtbl from a list of tuples ********************************************************** * Useful functions on arrays ********************************************************** Check if an element belongs to an array Return the list of the indexes whose value is true Shuffle an array val shuffle_array : 'a array -> unit * Shuffles the values of an array ********************************************************** * Useful functions on dynamic arrays ********************************************************** ********************************************************** * Useful functions on hash tables ********************************************************** * Get all bound keys in an hash table; multiple bindings yield multiple (identical) keys ** NOTE: indeed, in our setting, we only use hashtbl with a single binding ** * Get the binding associated to a key, or the default binding if key is not associated to any binding * function to filter hash table with a predicate on keys ********************************************************** * Useful functions on string ********************************************************** * Returns a fresh string made of 'n' times 's' Convert an array of string into a string Convert a list of string into a string Convert an array of string into a string with separators Convert an array of string into a string with separators removing empty strings * Convert a list of string into a string with separators (uses an internal conversion to array) * Convert a list of string into a string with separators removing empty strings Add \t identation of string according to the given level * Convert a list of int into a string with , separator Returns a list of substrings splitted using sep ** WARNING: the behavior of this function is odd (when sep=";;" or "£"; bug hidden here? ** * Escape \n & > for use in dot ********************************************************** * Useful functions on booleans ********************************************************** Evaluate both part of an 'and' comparison and return the conjunction Evaluate both part of an 'or' comparison and return the disjunction XOR: returns true if both are different XNOR: returns true if both are true or both are false, i.e., when both are equal to each other ********************************************************** * Date functions ********************************************************** * Print the current date and time under the form of a string ************************************************ * System functions ************************************************ * Read a file and convert to string * `write_to_file file_name file_content` will create a file `file_name` with content `file_content` pow of x by e pow of int of x by e Render a beautiful and cute json from an ugly horrible json Convert list to array Convert array to list
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * IMITATOR * * Laboratoire Spécification et Vérification ( ENS Cachan & CNRS , France ) * Université Paris 13 , LIPN , CNRS , France * * Module description : Useful OCaml functions * * File contributors : * Created : 2014/10/24 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * IMITATOR * * Laboratoire Spécification et Vérification (ENS Cachan & CNRS, France) * Université Paris 13, LIPN, CNRS, France * * Module description: Useful OCaml functions * * File contributors : Étienne André * Created : 2014/10/24 * ************************************************************) * Check if an integer is a power of two , i.e. , n = 2^m , with m > = 1 val is_a_power_of_2 : int -> bool * Round a float with 1 digit after comma , and convert to string val round1_float : float -> string * Round a float with 3 digits after comma , and convert to string val round3_float : float -> string * Get the value of an ' a option that is assumed to be different from None , or raise NoneException otherwise val a_of_a_option : 'a option -> 'a val identity : 'a -> 'a val first_of_tuple : 'a * 'b -> 'a val second_of_tuple : 'a * 'b -> 'b val list_empty : 'a list -> bool val random_element : 'a list -> 'a val list_of_interval : int -> int -> int list * Intersection of 2 lists ( keeps the order of the elements as in l1 ) val list_inter : 'a list -> 'a list -> 'a list * Union of 2 lists val list_union : 'a list -> 'a list -> 'a list * Difference of 2 lists val list_diff : 'a list -> 'a list-> 'a list val list_append : 'a list -> 'a list -> 'a list * Returns the last element of the list , or raise Empty_list if the list is empty . This function takes linear time val list_last : 'a list -> 'a * Returns the list without its last element ; raises Empty_list if the list is empty val list_without_last : 'a list -> 'a list * Returns a pair ( the list without its last element , the last element of the list ) , or raise Empty_list if the list is empty . val list_split_last : 'a list -> 'a list * 'a val list_only_once : 'a list -> 'a list val elements_existing_several_times : 'a list -> 'a list * Remove the first occurence of element e in list l ; return the list unchanged if not found val list_remove_first_occurence : 'a -> 'a list -> 'a list val list_delete_at : int -> 'a list -> 'a list val list_set_nth : int -> 'a -> 'a list -> 'a list * Get combination of two list * val list_combination : 'a list -> 'a list -> ('a * 'a) list val for_all_in_arrangement : ('a -> 'a -> bool) -> 'a list -> bool val sublist : int -> int -> 'a list -> 'a list val group_by : ('a -> 'b) -> 'a list -> ('b * 'a list) list val group_by_and_map : ('a -> 'b) -> ('a -> 'c) -> 'a list -> ('b * 'c list) list type ('a, 'b) my_either = My_left of 'a | My_right of 'b val partition_map : ('a -> ('b, 'c) my_either) -> 'a list -> ('b list * 'c list) val hashtbl_group_by : ('a -> 'b) -> 'a list -> ('b, 'a list) Hashtbl.t Raise an error if two pairs have the same key val hashtbl_of_tuples : ('a * 'b) list -> ('a, 'b) Hashtbl.t val in_array : 'a -> 'a array -> bool Returns the ( first ) index of an element in an array , or raise Not_found if not found val index_of : 'a -> 'a array -> int val true_indexes : bool array -> int list * exists p { a1 ; ... ; an } checks if at least one element of the Array satisfies the predicate p. That is , it returns ( p a1 ) || ( p a2 ) || ... || ( p an ) . val array_exists : ('a -> bool) -> 'a array -> bool val array_shuffle : 'a array -> unit * Perform the substraction of 2 NumConst array of same size * val sub_array : NumConst.t array -> NumConst.t array -> NumConst.t array exists p { a1 ; ... ; an } checks if at least one element of the DynArray satisfies the predicate p. That is , it returns ( p a1 ) || ( p a2 ) || ... || ( p an ) . val dynArray_exists : ('a -> bool) -> 'a DynArray.t -> bool val hashtbl_get_all_keys : ('a , 'b) Hashtbl.t -> 'a list val hashtbl_get_or_default : ('a , 'b) Hashtbl.t -> 'a -> 'b -> 'b val hashtbl_filter : ('a -> bool) -> ('a,'b) Hashtbl.t -> unit val string_n_times : int -> string -> string val string_of_array_of_string : string array -> string val string_of_list_of_string : string list -> string val string_of_array_of_string_with_sep : string -> string array -> string val string_of_array_of_string_with_sep_without_empty_strings : string -> string array -> string val string_of_list_of_string_with_sep : string -> string list -> string val string_of_list_of_string_with_sep_without_empty_strings : string -> string list -> string val indent_paragraph : int -> string -> string val string_of_list_of_int : int list -> string val split : string -> string -> string list * ' s_of_int i ' Return " s " if i > 1 , " " otherwise val s_of_int : int -> string * ' waswere_of_int i ' Return " were " if i > 1 , " was " otherwise val waswere_of_int : int -> string val escape_string_for_dot : string -> string val evaluate_and : bool -> bool -> bool val evaluate_or : bool -> bool -> bool val xor : bool -> bool -> bool val xnor : bool -> bool -> bool val now : unit -> string * Read the first line of a file and convert to string val read_first_line_from_file : string -> string val read_from_file : string -> string val write_to_file : string -> string -> unit val pow : Int32.t -> Int32.t -> Int32.t val pow_int : int -> int -> int val modulo : Int32.t -> Int32.t -> Int32.t val prettify_json : string -> string equivalent to List.filter_map of OCaml 4.08 , but reverse the list val rev_filter_map : ('a -> 'b option) -> 'a list -> 'b list val list_to_string_set : string list -> CustomModules.StringSet.t val string_set_to_list : CustomModules.StringSet.t -> string list val array_of_list : 'a list -> 'a array val list_of_array : 'a array -> 'a list
7df21ea8aa5ccd6084b02b9c62a410b15beaf40c676c9d9a9b33e9f00b7015b1
falgon/htcc
Var.hs
| Module : Htcc . . AST.Var Description : Data types and type synonyms used during AST construction Copyright : ( c ) roki , 2019 License : MIT Maintainer : Stability : experimental Portability : POSIX Data types and type synonyms used during AST construction Module : Htcc.Parser.AST.Var Description : Data types and type synonyms used during AST construction Copyright : (c) roki, 2019 License : MIT Maintainer : Stability : experimental Portability : POSIX Data types and type synonyms used during AST construction -} module Htcc.Parser.AST.Var ( module Htcc.Parser.AST.Var.Init ) where import Htcc.Parser.AST.Var.Init
null
https://raw.githubusercontent.com/falgon/htcc/3cef6fc362b00d4bc0ae261cba567bfd9c69b3c5/src/Htcc/Parser/AST/Var.hs
haskell
| Module : Htcc . . AST.Var Description : Data types and type synonyms used during AST construction Copyright : ( c ) roki , 2019 License : MIT Maintainer : Stability : experimental Portability : POSIX Data types and type synonyms used during AST construction Module : Htcc.Parser.AST.Var Description : Data types and type synonyms used during AST construction Copyright : (c) roki, 2019 License : MIT Maintainer : Stability : experimental Portability : POSIX Data types and type synonyms used during AST construction -} module Htcc.Parser.AST.Var ( module Htcc.Parser.AST.Var.Init ) where import Htcc.Parser.AST.Var.Init
08d937a022f3a07c7ae6a42a190b0ec02c14e6b32a7d469272f7cddda44b8d92
ocaml-flambda/ocaml-jst
transl_list_comprehension.ml
open Lambda open Typedtree open Asttypes open Transl_comprehension_utils open Lambda_utils.Constants * List comprehensions are compiled in terms of " reversed difference lists " . A difference list in general is a function from lists to lists ; by " reversed " , we mean that these lists are stored backwards , and need to be reversed at the end . We make both these choices for the usual efficiency reasons ; difference lists allow for efficient concatenation ; they can also be viewed as based on passing around accumulators , which allows us to make our functions tail - recursive , at the cost of building our lists up backwards . An additional choice we make is to build all these intermediate data structures on the stack ( i.e. , make them [ local _ ] ) ; again , this is for efficiency , as it means we do n't need to get the structure of these difference lists involved with the garbage collector . Since we can currently only generate global lists with list comprehensions ( see the comment " What modes should comprehensions use ? " in [ typecore.ml ] ) , we need a type that is spine - local but element - global ; we thus define a custom type of such snoc lists , and define our difference lists in terms of that , in the internal module [ CamlinternalComprehension ] : { [ type ' a rev_list = | Nil | Snoc of { init : ' a rev_list ; global _ last : ' a } type ' a rev_dlist = local _ ' a rev_list - > local _ ' a rev_list ] } We then work exclusively in terms of [ local _ ' a rev_dlist ] values , reversing them into a global [ list ] only at the very end . We desugar each iterator of a list comprehension into the application of a tail - recursive higher - order function analogous to ` concat_map ` , whose type is of the following form : { [ ... iterator arguments ... - > local _ ( ' elt - > local _ ' res rev_dlist ) - > local _ ' res rev_dlist ] } Here , the [ ... iterator arguments ... ] define the sequence of values to be iterated over ( the [ seq ] of a [ for pat in seq ] iterator , or the [ start ] and [ end ] of a [ for x = start to / downto end ] iterator ) ; the function argument is then to be called once for each item . What goes in the function ? It will be the next iterator , desugared in the same way . At any time , a [ when ] clause might intervene , which is simply desugared into a conditional that gates entering the next phase of the translation . Eventually , we reach the body , which is placed into the body of the innermost translated function ; it produces the single - item reversed difference list ( alternatively , snocs its generated value onto the accumulator ) . Because each function is analogous to ` concat_map ` , this builds up the correct list in the end . The whole thing is then passed into a reversal function , building the final list . For example , consider the following list comprehension : { [ [ x+y for x = 1 to 3 when x < > 2 for y in [ 10*x ; 100*x ] ] ( * = [ 11 ; 101 ; 33 ; 303 ] difference list in general is a function from lists to lists; by "reversed", we mean that these lists are stored backwards, and need to be reversed at the end. We make both these choices for the usual efficiency reasons; difference lists allow for efficient concatenation; they can also be viewed as based on passing around accumulators, which allows us to make our functions tail-recursive, at the cost of building our lists up backwards. An additional choice we make is to build all these intermediate data structures on the stack (i.e., make them [local_]); again, this is for efficiency, as it means we don't need to get the structure of these difference lists involved with the garbage collector. Since we can currently only generate global lists with list comprehensions (see the comment "What modes should comprehensions use?" in [typecore.ml]), we need a type that is spine-local but element-global; we thus define a custom type of such snoc lists, and define our difference lists in terms of that, in the internal module [CamlinternalComprehension]: {[ type 'a rev_list = | Nil | Snoc of { init : 'a rev_list; global_ last : 'a } type 'a rev_dlist = local_ 'a rev_list -> local_ 'a rev_list ]} We then work exclusively in terms of [local_ 'a rev_dlist] values, reversing them into a global [list] only at the very end. We desugar each iterator of a list comprehension into the application of a tail-recursive higher-order function analogous to `concat_map`, whose type is of the following form: {[ ...iterator arguments... -> local_ ('elt -> local_ 'res rev_dlist) -> local_ 'res rev_dlist ]} Here, the [...iterator arguments...] define the sequence of values to be iterated over (the [seq] of a [for pat in seq] iterator, or the [start] and [end] of a [for x = start to/downto end] iterator); the function argument is then to be called once for each item. What goes in the function? It will be the next iterator, desugared in the same way. At any time, a [when] clause might intervene, which is simply desugared into a conditional that gates entering the next phase of the translation. Eventually, we reach the body, which is placed into the body of the innermost translated function; it produces the single-item reversed difference list (alternatively, snocs its generated value onto the accumulator). Because each function is analogous to `concat_map`, this builds up the correct list in the end. The whole thing is then passed into a reversal function, building the final list. For example, consider the following list comprehension: {[ [x+y for x = 1 to 3 when x <> 2 for y in [10*x; 100*x]] (* = [11; 101; 33; 303] *) ]} This translates to the (Lambda equivalent of) the following: {[ (* Convert the result to a normal list *) CamlinternalComprehension.rev_list_to_list ( for x = 1 to 3 let start = 1 in let stop = 3 in CamlinternalComprehension.rev_dlist_concat_iterate_up start stop (fun x acc_x -> local_ when x < > 2 if x <> 2 then for y in [ 10*x ; 100*x ] let iter_list = [10*x; 100*x] in CamlinternalComprehension.rev_dlist_concat_map iter_list (fun y acc_y -> local_ (* The body: x+y *) Snoc { init = acc_y; last = x*y }) acc_x else acc_x) Nil) ]} See [CamlinternalComprehension] the types and functions we desugar to, along with some more documentation. *) (** An implementation note: Many of the functions in this file need to translate expressions from Typedtree to Lambda; to avoid strange dependency ordering, we parameterize those functions by [Translcore.transl_exp], and pass it in as a labeled argument, along with the necessary [scopes] labeled argument that it requires. *) (* CR aspectorzabusky: I couldn't get this to build if these were run as soon as this file was processed *) * The functions that are required to build the results of list comprehensions ; see the documentation for [ CamlinternalComprehension ] for more details . see the documentation for [CamlinternalComprehension] for more details. *) let ( rev_list_to_list , rev_dlist_concat_map , rev_dlist_concat_iterate_up , rev_dlist_concat_iterate_down ) = let transl name = lazy (Lambda.transl_prim "CamlinternalComprehension" name) in ( transl "rev_list_to_list" , transl "rev_dlist_concat_map" , transl "rev_dlist_concat_iterate_up" , transl "rev_dlist_concat_iterate_down" ) ;; * The [ local _ ] form of the [ CamlinternalComprehension . ] constructor , for building the intermediate restults of list comprehensions ; see the documentation for [ CamlinternalComprehension.rev_list ] for more details . building the intermediate restults of list comprehensions; see the documentation for [CamlinternalComprehension.rev_list] for more details. *) let rev_list_snoc_local ~loc ~init ~last = Lprim(Pmakeblock(0, Immutable, None, alloc_local), [init; last], loc) (** The [CamlinternalComprehension.Nil] constructor, for building the intermediate restults of list comprehensions; see the documentation for [CamlinternalComprehension.rev_list] for more details. *) let rev_list_nil = int 0 (** The information needed to translate a single iterator from a [for ... and ...] clause (i.e., [x = e1 (down)to e2] or [for pat in xs]). *) type translated_iterator = { builder : lambda Lazy.t (** The function that does the appropriate iteration (counting up, counting down, or iterating over a list). As discussed at the start of this file, this function is expected to have a type of the following form: {[ ...iterator arguments... -> local_ ('elt -> local_ 'res rev_dlist) -> local_ 'res rev_dlist ]} Once the "iterator arguments", which vary depending on the iterator, are applied to this function (see [arg_lets]), then it is simply waiting for the body of the iterator (the final function argument). *) ; arg_lets : Let_binding.t list * The first - class let bindings that bind the arguments to the [ builder ] function that actually does the iteration . These let bindings need to be collected separately so that they can all be bound at once before the whole [ for ... and ... ] clause , so that iterators in such a clause do n't have their side effects performed multiple times in relation to each other . Every variable bound by one of these let bindings will be passed to [ builder ] , filling in the [ ... iterator arguments ... ] in its type . function that actually does the iteration. These let bindings need to be collected separately so that they can all be bound at once before the whole [for ... and ...] clause, so that iterators in such a clause don't have their side effects performed multiple times in relation to each other. Every variable bound by one of these let bindings will be passed to [builder], filling in the [...iterator arguments...] in its type. *) ; element : Ident.t (** The name given to the values we're iterating over; needs to be a fresh name for [for]-[in] iterators in case the user specifies a complex pattern. *) ; element_kind : layout (** The [layout] of the values we're iterating over. *) ; add_bindings : lambda -> lambda (** Any extra bindings that should be present in the body of this iterator, for use by nested pieces of the translation; used if the user specifies a complex pattern in a [for]-[in] iterator. *) } * Translates an iterator ( [ Typedtree.comprehension_iterator ] ) , one piece of a [ for ... and ... and ... ] expression , into Lambda . This translation is into a [ translated_iterator ] , not just a Lambda term , because the iterator desugars into a higher - order function which is applied to another function containing the body of the iteration ; that body function ca n't be filled in until the rest of the translations have been done . [for ... and ... and ...] expression, into Lambda. This translation is into a [translated_iterator], not just a Lambda term, because the iterator desugars into a higher-order function which is applied to another function containing the body of the iteration; that body function can't be filled in until the rest of the translations have been done. *) let iterator ~transl_exp ~scopes = function | Texp_comp_range { ident; pattern = _; start; stop; direction } -> (* We have to let-bind [start] and [stop] so that they're evaluated in the correct (i.e., left-to-right) order *) let transl_bound var bound = Let_binding.make (Immutable Strict) (Pvalue Pintval) var (transl_exp ~scopes bound) in let start = transl_bound "start" start in let stop = transl_bound "stop" stop in { builder = (match direction with | Upto -> rev_dlist_concat_iterate_up | Downto -> rev_dlist_concat_iterate_down) ; arg_lets = [start; stop] ; element = ident ; element_kind = Pvalue Pintval ; add_bindings = Fun.id } | Texp_comp_in { pattern; sequence } -> let iter_list = Let_binding.make (Immutable Strict) (Pvalue Pgenval) "iter_list" (transl_exp ~scopes sequence) in (* Create a fresh variable to use as the function argument *) let element = Ident.create_local "element" in { builder = rev_dlist_concat_map ; arg_lets = [iter_list] ; element ; element_kind = Typeopt.layout pattern.pat_env pattern.pat_type ; add_bindings = CR aspectorzabusky : This has to be at [ value_kind ] [ ] , right , since we do n't know more specifically ? right, since we don't know more specifically? *) Matching.for_let ~scopes pattern.pat_loc (Lvar element) pattern (Pvalue Pgenval) } (** Translates a list comprehension binding ([Typedtree.comprehension_clause_binding]) into Lambda. At parse time, iterators don't include patterns and bindings do; however, in the typedtree representation, the patterns have been moved into the iterators (so that range iterators can just have an [Ident.t], for translation into for loops), so bindings are just like iterators with a possible annotation. As a result, this function is essentially the same as [iterator], which see. *) let binding ~transl_exp ~scopes { comp_cb_iterator; comp_cb_attributes = _ } = (* CR aspectorzabusky: What do we do with attributes here? *) iterator ~transl_exp ~scopes comp_cb_iterator * Translate all the bindings of a single [ for ... and ... ] clause ( the contents of a [ Typedtree . Texp_comp_for ] ) into a pair of ( 1 ) a list of let bindings that are in force for the translation ; and ( 2 ) a single Lambda term of type [ ' res rev_dlist ] , assuming we know how to translate everything that ought to be nested within it ( the [ inner_body ] , a function awaiting the most nested accumulator as a labeled argument which will produce the body of the iterations ) and have a name for the accumulator of the current [ rev_dlist ] ( [ accumulator ] , which changes at every recursive step ) . It folds together all the [ translated_iterator]s by connecting their [ body_func]tions to each other , and bottoms out at the [ inner_body ] . contents of a [Typedtree.Texp_comp_for]) into a pair of (1) a list of let bindings that are in force for the translation; and (2) a single Lambda term of type ['res rev_dlist], assuming we know how to translate everything that ought to be nested within it (the [inner_body], a function awaiting the most nested accumulator as a labeled argument which will produce the body of the iterations) and have a name for the accumulator of the current [rev_dlist] ([accumulator], which changes at every recursive step). It folds together all the [translated_iterator]s by connecting their [body_func]tions to each other, and bottoms out at the [inner_body]. *) let rec translate_bindings ~transl_exp ~scopes ~loc ~inner_body ~accumulator = function | cur_binding :: bindings -> let { builder; arg_lets; element; element_kind; add_bindings } = binding ~transl_exp ~scopes cur_binding in let inner_acc = Ident.create_local "accumulator" in let body_arg_lets, body = translate_bindings ~transl_exp ~scopes ~loc ~inner_body ~accumulator:(Lvar inner_acc) bindings in let body_func = Lambda.lfunction ~kind:(Curried { nlocal = 2 }) (* Only the accumulator is local, but since the function itself is local, [nlocal] has to be equal to the number of parameters *) ~params:[element, element_kind; inner_acc, Pvalue Pgenval] ~return:(Pvalue Pgenval) ~attr:default_function_attribute ~loc ~mode:alloc_local One region per iterator , like for loops ~body:(add_bindings body) in let result = Lambda_utils.apply ~loc ~mode:alloc_local (Lazy.force builder) (List.map (fun Let_binding.{id; _} -> Lvar id) arg_lets @ [body_func; accumulator]) ~result_layout:(Pvalue Pgenval) in arg_lets @ body_arg_lets, result | [] -> [], inner_body ~accumulator * Translate a single clause , either [ for ... and ... ] or [ when ... ] ( [ Typedtree.comprehension_clause ] ) , into a single Lambda term of type [ ' res rev_dlist ] , assuming we know how to translate everything that ought to be nested within it ( the [ comprehension_body ] , a a function awaiting the most nested accumulator as a labeled argument which will produce the body of the iterations ) and have a name for the accumulator of the current [ rev_dlist ] ( [ accumulator ] , which changes at every recursive step ) . ([Typedtree.comprehension_clause]), into a single Lambda term of type ['res rev_dlist], assuming we know how to translate everything that ought to be nested within it (the [comprehension_body], a a function awaiting the most nested accumulator as a labeled argument which will produce the body of the iterations) and have a name for the accumulator of the current [rev_dlist] ([accumulator], which changes at every recursive step). *) let rec translate_clauses ~transl_exp ~scopes ~loc ~comprehension_body ~accumulator = function | clause :: clauses -> let body ~accumulator = translate_clauses ~transl_exp ~scopes ~loc ~comprehension_body ~accumulator clauses in begin match clause with | Texp_comp_for bindings -> let arg_lets, bindings = translate_bindings ~transl_exp ~scopes ~loc ~inner_body:body ~accumulator bindings in Let_binding.let_all arg_lets bindings | Texp_comp_when cond -> Lifthenelse(transl_exp ~scopes cond, body ~accumulator, accumulator, (Pvalue Pgenval) (* [list]s have the standard representation *)) end | [] -> comprehension_body ~accumulator let comprehension ~transl_exp ~scopes ~loc { comp_body; comp_clauses } = let rev_comprehension = translate_clauses ~transl_exp ~scopes ~loc ~comprehension_body:(fun ~accumulator -> rev_list_snoc_local ~loc ~init:accumulator ~last:(transl_exp ~scopes comp_body)) ~accumulator:rev_list_nil comp_clauses in Lambda_utils.apply ~loc ~mode:alloc_heap (Lazy.force rev_list_to_list) [rev_comprehension] ~result_layout:(Pvalue Pgenval)
null
https://raw.githubusercontent.com/ocaml-flambda/ocaml-jst/7e5a626e4b4e12f1e9106564e1baba4d0ef6309a/lambda/transl_list_comprehension.ml
ocaml
= [11; 101; 33; 303] Convert the result to a normal list The body: x+y * An implementation note: Many of the functions in this file need to translate expressions from Typedtree to Lambda; to avoid strange dependency ordering, we parameterize those functions by [Translcore.transl_exp], and pass it in as a labeled argument, along with the necessary [scopes] labeled argument that it requires. CR aspectorzabusky: I couldn't get this to build if these were run as soon as this file was processed * The [CamlinternalComprehension.Nil] constructor, for building the intermediate restults of list comprehensions; see the documentation for [CamlinternalComprehension.rev_list] for more details. * The information needed to translate a single iterator from a [for ... and ...] clause (i.e., [x = e1 (down)to e2] or [for pat in xs]). * The function that does the appropriate iteration (counting up, counting down, or iterating over a list). As discussed at the start of this file, this function is expected to have a type of the following form: {[ ...iterator arguments... -> local_ ('elt -> local_ 'res rev_dlist) -> local_ 'res rev_dlist ]} Once the "iterator arguments", which vary depending on the iterator, are applied to this function (see [arg_lets]), then it is simply waiting for the body of the iterator (the final function argument). * The name given to the values we're iterating over; needs to be a fresh name for [for]-[in] iterators in case the user specifies a complex pattern. * The [layout] of the values we're iterating over. * Any extra bindings that should be present in the body of this iterator, for use by nested pieces of the translation; used if the user specifies a complex pattern in a [for]-[in] iterator. We have to let-bind [start] and [stop] so that they're evaluated in the correct (i.e., left-to-right) order Create a fresh variable to use as the function argument * Translates a list comprehension binding ([Typedtree.comprehension_clause_binding]) into Lambda. At parse time, iterators don't include patterns and bindings do; however, in the typedtree representation, the patterns have been moved into the iterators (so that range iterators can just have an [Ident.t], for translation into for loops), so bindings are just like iterators with a possible annotation. As a result, this function is essentially the same as [iterator], which see. CR aspectorzabusky: What do we do with attributes here? Only the accumulator is local, but since the function itself is local, [nlocal] has to be equal to the number of parameters [list]s have the standard representation
open Lambda open Typedtree open Asttypes open Transl_comprehension_utils open Lambda_utils.Constants * List comprehensions are compiled in terms of " reversed difference lists " . A difference list in general is a function from lists to lists ; by " reversed " , we mean that these lists are stored backwards , and need to be reversed at the end . We make both these choices for the usual efficiency reasons ; difference lists allow for efficient concatenation ; they can also be viewed as based on passing around accumulators , which allows us to make our functions tail - recursive , at the cost of building our lists up backwards . An additional choice we make is to build all these intermediate data structures on the stack ( i.e. , make them [ local _ ] ) ; again , this is for efficiency , as it means we do n't need to get the structure of these difference lists involved with the garbage collector . Since we can currently only generate global lists with list comprehensions ( see the comment " What modes should comprehensions use ? " in [ typecore.ml ] ) , we need a type that is spine - local but element - global ; we thus define a custom type of such snoc lists , and define our difference lists in terms of that , in the internal module [ CamlinternalComprehension ] : { [ type ' a rev_list = | Nil | Snoc of { init : ' a rev_list ; global _ last : ' a } type ' a rev_dlist = local _ ' a rev_list - > local _ ' a rev_list ] } We then work exclusively in terms of [ local _ ' a rev_dlist ] values , reversing them into a global [ list ] only at the very end . We desugar each iterator of a list comprehension into the application of a tail - recursive higher - order function analogous to ` concat_map ` , whose type is of the following form : { [ ... iterator arguments ... - > local _ ( ' elt - > local _ ' res rev_dlist ) - > local _ ' res rev_dlist ] } Here , the [ ... iterator arguments ... ] define the sequence of values to be iterated over ( the [ seq ] of a [ for pat in seq ] iterator , or the [ start ] and [ end ] of a [ for x = start to / downto end ] iterator ) ; the function argument is then to be called once for each item . What goes in the function ? It will be the next iterator , desugared in the same way . At any time , a [ when ] clause might intervene , which is simply desugared into a conditional that gates entering the next phase of the translation . Eventually , we reach the body , which is placed into the body of the innermost translated function ; it produces the single - item reversed difference list ( alternatively , snocs its generated value onto the accumulator ) . Because each function is analogous to ` concat_map ` , this builds up the correct list in the end . The whole thing is then passed into a reversal function , building the final list . For example , consider the following list comprehension : { [ [ x+y for x = 1 to 3 when x < > 2 for y in [ 10*x ; 100*x ] ] ( * = [ 11 ; 101 ; 33 ; 303 ] difference list in general is a function from lists to lists; by "reversed", we mean that these lists are stored backwards, and need to be reversed at the end. We make both these choices for the usual efficiency reasons; difference lists allow for efficient concatenation; they can also be viewed as based on passing around accumulators, which allows us to make our functions tail-recursive, at the cost of building our lists up backwards. An additional choice we make is to build all these intermediate data structures on the stack (i.e., make them [local_]); again, this is for efficiency, as it means we don't need to get the structure of these difference lists involved with the garbage collector. Since we can currently only generate global lists with list comprehensions (see the comment "What modes should comprehensions use?" in [typecore.ml]), we need a type that is spine-local but element-global; we thus define a custom type of such snoc lists, and define our difference lists in terms of that, in the internal module [CamlinternalComprehension]: {[ type 'a rev_list = | Nil | Snoc of { init : 'a rev_list; global_ last : 'a } type 'a rev_dlist = local_ 'a rev_list -> local_ 'a rev_list ]} We then work exclusively in terms of [local_ 'a rev_dlist] values, reversing them into a global [list] only at the very end. We desugar each iterator of a list comprehension into the application of a tail-recursive higher-order function analogous to `concat_map`, whose type is of the following form: {[ ...iterator arguments... -> local_ ('elt -> local_ 'res rev_dlist) -> local_ 'res rev_dlist ]} Here, the [...iterator arguments...] define the sequence of values to be iterated over (the [seq] of a [for pat in seq] iterator, or the [start] and [end] of a [for x = start to/downto end] iterator); the function argument is then to be called once for each item. What goes in the function? It will be the next iterator, desugared in the same way. At any time, a [when] clause might intervene, which is simply desugared into a conditional that gates entering the next phase of the translation. Eventually, we reach the body, which is placed into the body of the innermost translated function; it produces the single-item reversed difference list (alternatively, snocs its generated value onto the accumulator). Because each function is analogous to `concat_map`, this builds up the correct list in the end. The whole thing is then passed into a reversal function, building the final list. For example, consider the following list comprehension: {[ [x+y for x = 1 to 3 when x <> 2 for y in [10*x; 100*x]] ]} This translates to the (Lambda equivalent of) the following: {[ CamlinternalComprehension.rev_list_to_list ( for x = 1 to 3 let start = 1 in let stop = 3 in CamlinternalComprehension.rev_dlist_concat_iterate_up start stop (fun x acc_x -> local_ when x < > 2 if x <> 2 then for y in [ 10*x ; 100*x ] let iter_list = [10*x; 100*x] in CamlinternalComprehension.rev_dlist_concat_map iter_list (fun y acc_y -> local_ Snoc { init = acc_y; last = x*y }) acc_x else acc_x) Nil) ]} See [CamlinternalComprehension] the types and functions we desugar to, along with some more documentation. *) * The functions that are required to build the results of list comprehensions ; see the documentation for [ CamlinternalComprehension ] for more details . see the documentation for [CamlinternalComprehension] for more details. *) let ( rev_list_to_list , rev_dlist_concat_map , rev_dlist_concat_iterate_up , rev_dlist_concat_iterate_down ) = let transl name = lazy (Lambda.transl_prim "CamlinternalComprehension" name) in ( transl "rev_list_to_list" , transl "rev_dlist_concat_map" , transl "rev_dlist_concat_iterate_up" , transl "rev_dlist_concat_iterate_down" ) ;; * The [ local _ ] form of the [ CamlinternalComprehension . ] constructor , for building the intermediate restults of list comprehensions ; see the documentation for [ CamlinternalComprehension.rev_list ] for more details . building the intermediate restults of list comprehensions; see the documentation for [CamlinternalComprehension.rev_list] for more details. *) let rev_list_snoc_local ~loc ~init ~last = Lprim(Pmakeblock(0, Immutable, None, alloc_local), [init; last], loc) let rev_list_nil = int 0 type translated_iterator = { builder : lambda Lazy.t ; arg_lets : Let_binding.t list * The first - class let bindings that bind the arguments to the [ builder ] function that actually does the iteration . These let bindings need to be collected separately so that they can all be bound at once before the whole [ for ... and ... ] clause , so that iterators in such a clause do n't have their side effects performed multiple times in relation to each other . Every variable bound by one of these let bindings will be passed to [ builder ] , filling in the [ ... iterator arguments ... ] in its type . function that actually does the iteration. These let bindings need to be collected separately so that they can all be bound at once before the whole [for ... and ...] clause, so that iterators in such a clause don't have their side effects performed multiple times in relation to each other. Every variable bound by one of these let bindings will be passed to [builder], filling in the [...iterator arguments...] in its type. *) ; element : Ident.t ; element_kind : layout ; add_bindings : lambda -> lambda } * Translates an iterator ( [ Typedtree.comprehension_iterator ] ) , one piece of a [ for ... and ... and ... ] expression , into Lambda . This translation is into a [ translated_iterator ] , not just a Lambda term , because the iterator desugars into a higher - order function which is applied to another function containing the body of the iteration ; that body function ca n't be filled in until the rest of the translations have been done . [for ... and ... and ...] expression, into Lambda. This translation is into a [translated_iterator], not just a Lambda term, because the iterator desugars into a higher-order function which is applied to another function containing the body of the iteration; that body function can't be filled in until the rest of the translations have been done. *) let iterator ~transl_exp ~scopes = function | Texp_comp_range { ident; pattern = _; start; stop; direction } -> let transl_bound var bound = Let_binding.make (Immutable Strict) (Pvalue Pintval) var (transl_exp ~scopes bound) in let start = transl_bound "start" start in let stop = transl_bound "stop" stop in { builder = (match direction with | Upto -> rev_dlist_concat_iterate_up | Downto -> rev_dlist_concat_iterate_down) ; arg_lets = [start; stop] ; element = ident ; element_kind = Pvalue Pintval ; add_bindings = Fun.id } | Texp_comp_in { pattern; sequence } -> let iter_list = Let_binding.make (Immutable Strict) (Pvalue Pgenval) "iter_list" (transl_exp ~scopes sequence) in let element = Ident.create_local "element" in { builder = rev_dlist_concat_map ; arg_lets = [iter_list] ; element ; element_kind = Typeopt.layout pattern.pat_env pattern.pat_type ; add_bindings = CR aspectorzabusky : This has to be at [ value_kind ] [ ] , right , since we do n't know more specifically ? right, since we don't know more specifically? *) Matching.for_let ~scopes pattern.pat_loc (Lvar element) pattern (Pvalue Pgenval) } let binding ~transl_exp ~scopes { comp_cb_iterator; comp_cb_attributes = _ } = iterator ~transl_exp ~scopes comp_cb_iterator * Translate all the bindings of a single [ for ... and ... ] clause ( the contents of a [ Typedtree . Texp_comp_for ] ) into a pair of ( 1 ) a list of let bindings that are in force for the translation ; and ( 2 ) a single Lambda term of type [ ' res rev_dlist ] , assuming we know how to translate everything that ought to be nested within it ( the [ inner_body ] , a function awaiting the most nested accumulator as a labeled argument which will produce the body of the iterations ) and have a name for the accumulator of the current [ rev_dlist ] ( [ accumulator ] , which changes at every recursive step ) . It folds together all the [ translated_iterator]s by connecting their [ body_func]tions to each other , and bottoms out at the [ inner_body ] . contents of a [Typedtree.Texp_comp_for]) into a pair of (1) a list of let bindings that are in force for the translation; and (2) a single Lambda term of type ['res rev_dlist], assuming we know how to translate everything that ought to be nested within it (the [inner_body], a function awaiting the most nested accumulator as a labeled argument which will produce the body of the iterations) and have a name for the accumulator of the current [rev_dlist] ([accumulator], which changes at every recursive step). It folds together all the [translated_iterator]s by connecting their [body_func]tions to each other, and bottoms out at the [inner_body]. *) let rec translate_bindings ~transl_exp ~scopes ~loc ~inner_body ~accumulator = function | cur_binding :: bindings -> let { builder; arg_lets; element; element_kind; add_bindings } = binding ~transl_exp ~scopes cur_binding in let inner_acc = Ident.create_local "accumulator" in let body_arg_lets, body = translate_bindings ~transl_exp ~scopes ~loc ~inner_body ~accumulator:(Lvar inner_acc) bindings in let body_func = Lambda.lfunction ~kind:(Curried { nlocal = 2 }) ~params:[element, element_kind; inner_acc, Pvalue Pgenval] ~return:(Pvalue Pgenval) ~attr:default_function_attribute ~loc ~mode:alloc_local One region per iterator , like for loops ~body:(add_bindings body) in let result = Lambda_utils.apply ~loc ~mode:alloc_local (Lazy.force builder) (List.map (fun Let_binding.{id; _} -> Lvar id) arg_lets @ [body_func; accumulator]) ~result_layout:(Pvalue Pgenval) in arg_lets @ body_arg_lets, result | [] -> [], inner_body ~accumulator * Translate a single clause , either [ for ... and ... ] or [ when ... ] ( [ Typedtree.comprehension_clause ] ) , into a single Lambda term of type [ ' res rev_dlist ] , assuming we know how to translate everything that ought to be nested within it ( the [ comprehension_body ] , a a function awaiting the most nested accumulator as a labeled argument which will produce the body of the iterations ) and have a name for the accumulator of the current [ rev_dlist ] ( [ accumulator ] , which changes at every recursive step ) . ([Typedtree.comprehension_clause]), into a single Lambda term of type ['res rev_dlist], assuming we know how to translate everything that ought to be nested within it (the [comprehension_body], a a function awaiting the most nested accumulator as a labeled argument which will produce the body of the iterations) and have a name for the accumulator of the current [rev_dlist] ([accumulator], which changes at every recursive step). *) let rec translate_clauses ~transl_exp ~scopes ~loc ~comprehension_body ~accumulator = function | clause :: clauses -> let body ~accumulator = translate_clauses ~transl_exp ~scopes ~loc ~comprehension_body ~accumulator clauses in begin match clause with | Texp_comp_for bindings -> let arg_lets, bindings = translate_bindings ~transl_exp ~scopes ~loc ~inner_body:body ~accumulator bindings in Let_binding.let_all arg_lets bindings | Texp_comp_when cond -> Lifthenelse(transl_exp ~scopes cond, body ~accumulator, accumulator, end | [] -> comprehension_body ~accumulator let comprehension ~transl_exp ~scopes ~loc { comp_body; comp_clauses } = let rev_comprehension = translate_clauses ~transl_exp ~scopes ~loc ~comprehension_body:(fun ~accumulator -> rev_list_snoc_local ~loc ~init:accumulator ~last:(transl_exp ~scopes comp_body)) ~accumulator:rev_list_nil comp_clauses in Lambda_utils.apply ~loc ~mode:alloc_heap (Lazy.force rev_list_to_list) [rev_comprehension] ~result_layout:(Pvalue Pgenval)
c569f9ec814dd35aa9b9b984d2e73c0e45562653a86494dfbf87531f4479bbf6
mojombo/yaws
wiki_plugin_backlinks.erl
%%% File : wiki_plugin_backlinks.erl Author : < > %%% Description : This plugin can show the list of backlinks inline Created : 20 Oct 2003 by %%% <> -module(wiki_plugin_backlinks). -export([run/2]). -include("yaws.hrl"). %% Needed only if you want to manipulate %% Yaws configuration run(Page, ArgList) -> TODO : This is working if there is only one virtual server . %% A way to handle this cleanly is needed. {ok, Gconf, [[Sconf|Others]]} = yaws_api:getconf(), Root = Sconf#sconf.docroot, AllRefs = wiki_utils:getallrefs(Page, Root), lists:map(fun(F) -> [wiki_to_html:format_link(F, Root),"<br>"] end, AllRefs).
null
https://raw.githubusercontent.com/mojombo/yaws/f75fde80f1e35a87335f21d0983e3285eb665f17/applications/wiki/src/wiki_plugin_backlinks.erl
erlang
File : wiki_plugin_backlinks.erl Description : This plugin can show the list of backlinks inline <> Needed only if you want to manipulate Yaws configuration A way to handle this cleanly is needed.
Author : < > Created : 20 Oct 2003 by -module(wiki_plugin_backlinks). -export([run/2]). run(Page, ArgList) -> TODO : This is working if there is only one virtual server . {ok, Gconf, [[Sconf|Others]]} = yaws_api:getconf(), Root = Sconf#sconf.docroot, AllRefs = wiki_utils:getallrefs(Page, Root), lists:map(fun(F) -> [wiki_to_html:format_link(F, Root),"<br>"] end, AllRefs).
571191c069dd1a87a2782cbe096c87ea40faa6e7f0d8cbaf8558a58c4faf117b
cpsc411/cpsc411-pub
v1.rkt
#lang at-exp racket/base (require cpsc411/compiler-lib cpsc411/info-lib scribble/bettergrammar racket/contract (for-label cpsc411/compiler-lib) (for-label cpsc411/info-lib) (for-label racket/contract) "redex-gen.rkt" (submod "base.rkt" interp)) (provide (all-defined-out)) @define-grammar/pred[paren-x64-v1 #:literals (int64? int32?) #:datum-literals (begin set! * + rsp rbp rax rbx rcx rdx rsi rdi r8 r9 r10 r11 r12 r13 r14 r15) [p (begin s ...)] [s (set! reg int64) (set! reg reg) (set! reg_1 (binop reg_1 int32)) (set! reg_1 (binop reg_1 reg))] [reg rsp rbp rax rbx rcx rdx rsi rdi r8 r9 r10 r11 r12 r13 r14 r15] [binop * +] [int64 int64?] [int32 int32?] ] (define (interp-paren-x64-v1 x) (modulo (interp-base `(module (begin ,x (halt rax)))) 256))
null
https://raw.githubusercontent.com/cpsc411/cpsc411-pub/757ececf84d54d86cfa0c2c6c84f1456c8765db9/cpsc411-lib/cpsc411/langs/v1.rkt
racket
#lang at-exp racket/base (require cpsc411/compiler-lib cpsc411/info-lib scribble/bettergrammar racket/contract (for-label cpsc411/compiler-lib) (for-label cpsc411/info-lib) (for-label racket/contract) "redex-gen.rkt" (submod "base.rkt" interp)) (provide (all-defined-out)) @define-grammar/pred[paren-x64-v1 #:literals (int64? int32?) #:datum-literals (begin set! * + rsp rbp rax rbx rcx rdx rsi rdi r8 r9 r10 r11 r12 r13 r14 r15) [p (begin s ...)] [s (set! reg int64) (set! reg reg) (set! reg_1 (binop reg_1 int32)) (set! reg_1 (binop reg_1 reg))] [reg rsp rbp rax rbx rcx rdx rsi rdi r8 r9 r10 r11 r12 r13 r14 r15] [binop * +] [int64 int64?] [int32 int32?] ] (define (interp-paren-x64-v1 x) (modulo (interp-base `(module (begin ,x (halt rax)))) 256))
ed678679c044042159ae511fb5db12f72c4f364b458d079f7ef865a73b7923cb
unclebob/clojureOrbit
vector.clj
(ns physics.vector (:refer-clojure :exclude (vector)) (:require [physics.position :as position]) (:import physics.position.position)) (defn make ([] (position. 0 0)) ([x y] (position. x y))) (defn zero_mag? [v] (position/origin? v)) (def add position/add) (def subtract position/subtract) (defn scale [v s] (make (* (:x v) s) (* (:y v) s))) (defn magnitude [v] (Math/sqrt (+ (Math/pow (:x v) 2) (Math/pow (:y v) 2)))) (defn unit [v] (scale v (/ 1 (magnitude v)))) (defn rotate90 [{x :x y :y}] (make (- y) x)) (defn equal [{x1 :x y1 :y} {x2 :x y2 :y}] (and (== x1 x2) (== y1 y2)))
null
https://raw.githubusercontent.com/unclebob/clojureOrbit/82d59297dc8c54fccb37b92725f0547def0d6157/src/physics/vector.clj
clojure
(ns physics.vector (:refer-clojure :exclude (vector)) (:require [physics.position :as position]) (:import physics.position.position)) (defn make ([] (position. 0 0)) ([x y] (position. x y))) (defn zero_mag? [v] (position/origin? v)) (def add position/add) (def subtract position/subtract) (defn scale [v s] (make (* (:x v) s) (* (:y v) s))) (defn magnitude [v] (Math/sqrt (+ (Math/pow (:x v) 2) (Math/pow (:y v) 2)))) (defn unit [v] (scale v (/ 1 (magnitude v)))) (defn rotate90 [{x :x y :y}] (make (- y) x)) (defn equal [{x1 :x y1 :y} {x2 :x y2 :y}] (and (== x1 x2) (== y1 y2)))
76c0b9baf038ee0d9bea4b2f71c45b5f4be50a32ede7c92b50d2ddfac1734548
dym/movitz
vmware-vga.lisp
;;;; vmware.lisp Basic VMWare video driver based upon the one from idyllaos Martin Bealby 2007 ;;;; Currently supports changing video mode only Acceleration functions left to implement ( need ) (require :x86-pc/package) (provide :tmp/vmware) (in-package muerte.x86-pc) (defconstant +vmware-card-ids+ '((#x15AD #x0405 "VMWare Video (v2)"))) (defconstant +vmware-magic-version-2+ #x90000002) (defconstant +vmware-magic-version-1+ #x90000001) (defconstant +vmware-register-id+ 0) (defconstant +vmware-register-enable+ 1) (defconstant +vmware-register-width+ 2) (defconstant +vmware-register-height+ 3) (defconstant +vmware-register-max-width+ 4) (defconstant +vmware-register-max-height+ 5) (defconstant +vmware-register-depth+ 6) (defconstant +vmware-register-bits-per-pixel+ 7) (defconstant +vmware-register-pseudocolor+ 8) (defconstant +vmware-register-red-mask+ 9) (defconstant +vmware-register-green-mask+ 10) (defconstant +vmware-register-blue-mask+ 11) (defconstant +vmware-register-bytes-per-line+ 12) (defconstant +vmware-register-fb-start+ 13) (defconstant +vmware-register-fb-offset+ 14) (defconstant +vmware-register-vram-size+ 15) (defconstant +vmware-register-fb-size+ 16) (defconstant +vmware-register-capabilities+ 17) (defconstant +vmware-register-mem-start+ 18) (defconstant +vmware-register-mem-size+ 19) (defconstant +vmware-register-config-done+ 20) (defconstant +vmware-register-sync+ 21) (defconstant +vmware-register-busy+ 22) (defconstant +vmware-register-guest-id+ 23) (defconstant +vmware-register-cursor-id+ 24) (defconstant +vmware-register-cursor-x+ 25) (defconstant +vmware-register-cursor-y+ 26) (defconstant +vmware-register-cursor-on+ 27) (defconstant +vmware-register-host-bits-per-pixel+ 28) (defconstant +vmware-register-top+ 30) (defconstant +vmware-svga-palette-base+ 1024) 32 bits (defvar vmware-svga-index 0) (defvar vmware-svga-value 0) (defvar vmware-framebuffer-location 0) (defvar vmware-framebuffer-size 0) (defvar vmware-framebuffer-width 0) (defvar vmware-framebuffer-height 0) (defvar vmware-framebuffer-bpp 0) (defvar vmware-fifo-location 0) (defvar vmware-fifo-size 0) ; ; internal functions ; (defmethod vmware-attach (&key io &allow-other-keys) "Attach the driver to a VMWare device." (setf (vmware-svga-index) io) (setf (vmware-svga-value) (+ 1 io))) (defmethod vmware-register-write (index value) "Write to the VMWare video register." (setf (io-port (vmware-svga-index) :unsigned-byte32) index) (setf (io-port (vmware-svga-value) :unsigned-byte32) value)) (defmethod vmware-register-read (index) "Read from the VMWare video register." (setf (io-port (vmware-svga-index) :unsigned-byte32) index) (io-port (vmware-svga-value) :unsigned-byte32)) ;; ;; Public methods ;; (defmethod initialise () "Initialise the vmware driver." (loop for i in +vmware-card-ids+ do (multiple-value-bind (bus device function) (find-pci-device (car i) (car (cdr i))) (apply #'attach (list pci-device-address-maps bus device function))))) (defmethod get-framebuffer () "Return a pointer to the framebuffer." (return vmware-framebuffer-location)) (defmethod set-resolution (width height bpp) "Sets the current display resolution." test for vmware version 2 ( only supported version at the moment ) (vmware-register-write +vmware-register-id+ +vmware-magic-version-2+) (if (equal (vmware-register-read +vmware-register-id+) +vmware-magic-version-2+) (progn (setf vmware-framebuffer-location (vmware-register-read +vmware-register-fb-start+)) (setf vmware-framebuffer-size (vmware-register-read +vmware-register-fb-size+)) (setf vmware-fifo-location (vmware-register-read +vmware-register-mem-start+)) (setf vmware-fifo-size (vmware-register-read +vmware-register-mem-size+)) (setf vmware-framebuffer-width (vmware-register-write +vmware-register-width+ width)) (setf vmware-framebuffer-height (vmware-register-write +vmware-register-height+ height)) (vmware-register-write +vmware-register-bits-per-pixel+ bpp) (vmware-register-read +vmware-register-fb-offset+) (vmware-register-read +vmware-register-bytes-per-line+) (vmware-register-read +vmware-register-depth+) (vmware-register-read +vmware-register-pseudocolor+) (vmware-register-read +vmware-register-red-mask+) (vmware-register-read +vmware-register-green-mask+) (vmware-register-read +vmware-register-blue-mask+) (vmware-register-write +vmware-register-enable+ #x1)) (error "Bad Magic - Not VMware version 2 graphics."))) (defmethod update-region (x y width height) "Update a region on screen. With no parameters it updates the whole screen." (if (= width 0) (progn (vmware-fifo-push +vmware-cmd-update+) (vmware-fifo-push 0) (vmware-fifo-push 0) (vmware-fifo-push vmware-framebuffer-width) (vmware-fifo-push vmware-framebuffer-height)) (progn (vmware-fifo-push +vmware-cmd-update+) (vmware-fifo-push x) (vmware-fifo-push y) (vmware-fifo-push width) (vmware-fifo-push height)))) ;; VMWare fifo functions ;; (defun initialise-fifo () "Initialise the VMware fifo command stream." (setf vmware-fifo-pointer-min (* 4 +vmware-fifo-command-size+)) (setf vmware-fifo-pointer-max (+ 16 (* 10 1024))) (setf vmware-fifo-pointer-next-command vmware-fifo-min) (setf vmware-fifo-pointer-stop vmware-fifo-min) (vmware-register-write +vmware-register-config-done+ 1) (vmware-register-read +vmware-register-config-done+)) (defun vmware-fifo-sync () "Sync the fifo buffer." (vmware-register-write +vmware-register-sync+ 1) (loop until (= 0 (vmware-register-read +vmware-register-busy+)))) (defun vmware-fifo-push (data) "Write a piece of data to the VMWare fifo pipe." (if (vmware-fifo-full-p) (vmware-fifo-sync)) ;; TODO: actual append to fifo buffer ;) ) (defun vmware-fifo-full-p () "Test for a full fifo buffer." (cond (= (+ vmware-fifo-pointer-next-command +vmware-fifo-command-size+) vmware-fifo-pointer-stop) (t) (and (= vmware-fifo-pointer-next-command (- vmware-fifo-pointer-max +vmware-fifo-command-size+)) (= vmware-fifo-pointer-stop vmware-fifo-pointer-min)) (t) (t) (nil)))
null
https://raw.githubusercontent.com/dym/movitz/56176e1ebe3eabc15c768df92eca7df3c197cb3d/losp/tmp/vmware-vga.lisp
lisp
vmware.lisp Currently supports changing video mode only internal functions Public methods TODO: actual append to fifo buffer ;)
Basic VMWare video driver based upon the one from idyllaos Martin Bealby 2007 Acceleration functions left to implement ( need ) (require :x86-pc/package) (provide :tmp/vmware) (in-package muerte.x86-pc) (defconstant +vmware-card-ids+ '((#x15AD #x0405 "VMWare Video (v2)"))) (defconstant +vmware-magic-version-2+ #x90000002) (defconstant +vmware-magic-version-1+ #x90000001) (defconstant +vmware-register-id+ 0) (defconstant +vmware-register-enable+ 1) (defconstant +vmware-register-width+ 2) (defconstant +vmware-register-height+ 3) (defconstant +vmware-register-max-width+ 4) (defconstant +vmware-register-max-height+ 5) (defconstant +vmware-register-depth+ 6) (defconstant +vmware-register-bits-per-pixel+ 7) (defconstant +vmware-register-pseudocolor+ 8) (defconstant +vmware-register-red-mask+ 9) (defconstant +vmware-register-green-mask+ 10) (defconstant +vmware-register-blue-mask+ 11) (defconstant +vmware-register-bytes-per-line+ 12) (defconstant +vmware-register-fb-start+ 13) (defconstant +vmware-register-fb-offset+ 14) (defconstant +vmware-register-vram-size+ 15) (defconstant +vmware-register-fb-size+ 16) (defconstant +vmware-register-capabilities+ 17) (defconstant +vmware-register-mem-start+ 18) (defconstant +vmware-register-mem-size+ 19) (defconstant +vmware-register-config-done+ 20) (defconstant +vmware-register-sync+ 21) (defconstant +vmware-register-busy+ 22) (defconstant +vmware-register-guest-id+ 23) (defconstant +vmware-register-cursor-id+ 24) (defconstant +vmware-register-cursor-x+ 25) (defconstant +vmware-register-cursor-y+ 26) (defconstant +vmware-register-cursor-on+ 27) (defconstant +vmware-register-host-bits-per-pixel+ 28) (defconstant +vmware-register-top+ 30) (defconstant +vmware-svga-palette-base+ 1024) 32 bits (defvar vmware-svga-index 0) (defvar vmware-svga-value 0) (defvar vmware-framebuffer-location 0) (defvar vmware-framebuffer-size 0) (defvar vmware-framebuffer-width 0) (defvar vmware-framebuffer-height 0) (defvar vmware-framebuffer-bpp 0) (defvar vmware-fifo-location 0) (defvar vmware-fifo-size 0) (defmethod vmware-attach (&key io &allow-other-keys) "Attach the driver to a VMWare device." (setf (vmware-svga-index) io) (setf (vmware-svga-value) (+ 1 io))) (defmethod vmware-register-write (index value) "Write to the VMWare video register." (setf (io-port (vmware-svga-index) :unsigned-byte32) index) (setf (io-port (vmware-svga-value) :unsigned-byte32) value)) (defmethod vmware-register-read (index) "Read from the VMWare video register." (setf (io-port (vmware-svga-index) :unsigned-byte32) index) (io-port (vmware-svga-value) :unsigned-byte32)) (defmethod initialise () "Initialise the vmware driver." (loop for i in +vmware-card-ids+ do (multiple-value-bind (bus device function) (find-pci-device (car i) (car (cdr i))) (apply #'attach (list pci-device-address-maps bus device function))))) (defmethod get-framebuffer () "Return a pointer to the framebuffer." (return vmware-framebuffer-location)) (defmethod set-resolution (width height bpp) "Sets the current display resolution." test for vmware version 2 ( only supported version at the moment ) (vmware-register-write +vmware-register-id+ +vmware-magic-version-2+) (if (equal (vmware-register-read +vmware-register-id+) +vmware-magic-version-2+) (progn (setf vmware-framebuffer-location (vmware-register-read +vmware-register-fb-start+)) (setf vmware-framebuffer-size (vmware-register-read +vmware-register-fb-size+)) (setf vmware-fifo-location (vmware-register-read +vmware-register-mem-start+)) (setf vmware-fifo-size (vmware-register-read +vmware-register-mem-size+)) (setf vmware-framebuffer-width (vmware-register-write +vmware-register-width+ width)) (setf vmware-framebuffer-height (vmware-register-write +vmware-register-height+ height)) (vmware-register-write +vmware-register-bits-per-pixel+ bpp) (vmware-register-read +vmware-register-fb-offset+) (vmware-register-read +vmware-register-bytes-per-line+) (vmware-register-read +vmware-register-depth+) (vmware-register-read +vmware-register-pseudocolor+) (vmware-register-read +vmware-register-red-mask+) (vmware-register-read +vmware-register-green-mask+) (vmware-register-read +vmware-register-blue-mask+) (vmware-register-write +vmware-register-enable+ #x1)) (error "Bad Magic - Not VMware version 2 graphics."))) (defmethod update-region (x y width height) "Update a region on screen. With no parameters it updates the whole screen." (if (= width 0) (progn (vmware-fifo-push +vmware-cmd-update+) (vmware-fifo-push 0) (vmware-fifo-push 0) (vmware-fifo-push vmware-framebuffer-width) (vmware-fifo-push vmware-framebuffer-height)) (progn (vmware-fifo-push +vmware-cmd-update+) (vmware-fifo-push x) (vmware-fifo-push y) (vmware-fifo-push width) (vmware-fifo-push height)))) VMWare fifo functions (defun initialise-fifo () "Initialise the VMware fifo command stream." (setf vmware-fifo-pointer-min (* 4 +vmware-fifo-command-size+)) (setf vmware-fifo-pointer-max (+ 16 (* 10 1024))) (setf vmware-fifo-pointer-next-command vmware-fifo-min) (setf vmware-fifo-pointer-stop vmware-fifo-min) (vmware-register-write +vmware-register-config-done+ 1) (vmware-register-read +vmware-register-config-done+)) (defun vmware-fifo-sync () "Sync the fifo buffer." (vmware-register-write +vmware-register-sync+ 1) (loop until (= 0 (vmware-register-read +vmware-register-busy+)))) (defun vmware-fifo-push (data) "Write a piece of data to the VMWare fifo pipe." (if (vmware-fifo-full-p) (vmware-fifo-sync)) ) (defun vmware-fifo-full-p () "Test for a full fifo buffer." (cond (= (+ vmware-fifo-pointer-next-command +vmware-fifo-command-size+) vmware-fifo-pointer-stop) (t) (and (= vmware-fifo-pointer-next-command (- vmware-fifo-pointer-max +vmware-fifo-command-size+)) (= vmware-fifo-pointer-stop vmware-fifo-pointer-min)) (t) (t) (nil)))
7f0007bdb588979faba2e6e3f377937dd40861779a8a57bded158b1fe7a8040a
McCLIM/McCLIM
xpm.lisp
;;; --------------------------------------------------------------------------- ;;; License: LGPL-2.1+ (See file 'Copyright' for details). ;;; --------------------------------------------------------------------------- ;;; ( c ) Copyright 2003 by < > ( c ) Copyright 2006 by < > ;;; ;;; --------------------------------------------------------------------------- ;;; ;;; (in-package #:clim-internals) Notes This is essentially a rewrite / transliteration of 's original code , ;;; modified to improve performance. This is achieved primarily by using ;;; read-sequence into an (unsigned-byte 8) array and parsing directly ;;; from this array (the original code read a list of strings using read-line ;;; and further divided these into substrings in various places. It is ;;; substantially faster than the original code, but there are opportunities ;;; to further improve performance by perhaps several times, including: ;;; - Use an array rather than hash table to resolve color tokens ;;; (I avoided doing this for now due to a pathological case of a file with a small palette but high CPP and sparse color tokens ) ;;; - Stricter type declarations (some but not all of the code assumes cpp<3) ;;; - In the worst case (photographs), we spent most of our time parsing the palette ( it may have thousands or millions of entries ) . ;;; - For the above case, we should be generating an RGB or RGBA image rather than an indexed - pattern ( and consing a ton of color objects ) . - People who save photographs in XPM format are morons , so it is n't ;;; worth optimizing. 's Notes : - We lose when the XPM image only specifies colors for say the mono ;; visual. ;; ;; - We need a little refactoring: ;; . The list of colors below is now actually the second place we have ;; that. ;; ;; . Parsing of #rgb style colors is now the upteens place we have ;; that in general. ;; ;; => Put that in utils.lisp and document its interface. ;; - The ASCII - centric approach of XPM makes it suitable for embedding ;; it into sources files. I want a macro which takes a list of strings according the XPM format and turns it into a make - pattern ;; call. ;; ;; - This needs to be incorporated into READ-BITMAP-FILE or what ever ;; that is called. ;; ;; - We might be interested in the hot spot also. ;; --GB 2003 - 05 - 25 ;;;; Summary of the File Format [ as of the XPM-3.4i documentation by Arnaud Le Hors ] . ;; | The XPM Format ;; | | The XPM format presents a C syntax , in order to provide the ability to | include XPM files in C and C++ programs . It is in fact an array of | strings composed of six different sections as follows : ;; | ;; | /* XPM */ ;; | static char* <variable_name>[] = { ;; | <Values> ;; | <Colors> ;; | <Pixels> ;; | <Extensions> ;; | }; ;; | ;; | The words are separated by a white space which can be composed of ;; | space and tabulation characters. The <Values> section is a string | containing four or six integers in base 10 that correspond to : the ;; | pixmap width and height, the number of colors, the number of ;; | characters per pixel (so there is no limit on the number of colors), ;; | and, optionally the hotspot coordinates and the XPMEXT tag if there is ;; | any extension following the <Pixels> section. ;; | ;; | <width> <height> <ncolors> <cpp> [<x_hotspot> <y_hotspot>] [XPMEXT] ;; | ;; | The Colors section contains as many strings as there are colors, and ;; | each string is as follows: ;; | | < chars > { < key > < color>}+ ;; | ;; | Where <chars> is the <chars_per_pixel> length string (not surrounded ;; | by anything) representing the pixels, <color> is the specified color, ;; | and <key> is a keyword describing in which context this color should ;; | be used. Currently the keys may have the following values: ;; | ;; | m for mono visual ;; | s for symbolic name | g4 for 4 - level grayscale | g for grayscale with more than 4 levels ;; | c for color visual ;; | ;; | Colors can be specified by giving the colorname, a # followed by the | RGB code in hexadecimal , or a % followed by the HSV code ( not ;; | implemented). The symbolic name provides the ability of specifying the ;; | colors at load time and not to hardcode them in the file. ;; | ;; | Also the string None can be given as a colorname to mean | ` ` transparent '' . Transparency is supported by the XPM library by ;; | providing a masking bitmap in addition to the pixmap. This mask can | then be used either as a clip - mask of , or a shape - mask of a | window using the X11 Nonrectangular Window Shape Extension [ XShape ] . ;; | The <Pixels> section is composed by <height> strings of <width> * ;; | <chars_per_pixel> characters, where every <chars_per_pixel> length ;; | string must be one of the previously defined groups in the <Colors> ;; | section. ;; | ;; | Then follows the <Extensions> section which must be labeled, if not ;; | empty, in the <Values> section as previously described. This section | may be composed by several < Extension > subsections which may be of two ;; | types: ;; | | . one stand alone string composed as follows : ;; | ;; | XPMEXT <extension-name> <extension-data> ;; | ;; | . or a block composed by several strings: ;; | ;; | XPMEXT <extension-name> ;; | <related extension-data composed of several strings> ;; | ;; | Finally, if not empty, this section must end by the following string: ;; | ;; | XPMENDEXT ;; | ;; | Extensions can be used to store any type of data one might want to ;; | store along with a pixmap, as long as they are properly encoded so ;; | they do not conflict with the general syntax. To avoid possible ;; | conflicts with extension names in shared files, they should be ;; | prefixed by the name of the company. This would ensure uniqueness. ;; | (deftype xpm-data-array () `(simple-array (unsigned-byte 8) 1)) (deftype array-index () #-sbcl '(integer 0 #.array-dimension-limit) #+sbcl 'sb-int:index) (deftype xpm-pixcode () `(unsigned-byte 24)) ; Bogus upper limit for speed.. =/ (defmacro xpm-over-array ((arrayform elt0 idx0 elt1 idx1 start) &body body) (let ((arraysym (gensym)) (lengthsym (gensym))) `(let* ((,arraysym ,arrayform) (,lengthsym (length ,arraysym))) (declare (type xpm-data-array ,arraysym) (optimize (speed 3))) (loop for ,idx0 of-type array-index from ,start below (1- ,lengthsym) as ,idx1 of-type array-index = (1+ ,idx0) as ,elt0 = (aref ,arraysym ,idx0) as ,elt1 = (aref ,arraysym ,idx1) do (progn ,@body))))) (declaim (inline xpm-whitespace-p) (ftype (function ((unsigned-byte 8)) t) xpm-whitespace-p)) (defun xpm-white-space-p (code) (declare (type (unsigned-byte 8) code) (optimize (speed 3))) (or (= code 32) ; #\Space # \Tab (= code 10))) ; #\Newline (defun xpm-token-terminator-p (code) (declare (type (unsigned-byte 8) code)) (or (xpm-white-space-p code) (= code 34))) ; #\" (defun xpm-token-bounds (data start) (xpm-over-array (data b0 start b1 i1 start) (when (not (xpm-white-space-p b0)) (xpm-over-array (data b0 end b1 i1 start) (when (xpm-token-terminator-p b0) (return-from xpm-token-bounds (values start end)))) (error "Unbounded token"))) (error "Missing token")) (defun xpm-extract-color-token (data start end) (declare (type xpm-data-array data) (type array-index start end) (optimize (speed 3))) (let ((x 0)) (declare (type xpm-pixcode x)) ; Bah, this didn't help. (loop for i from start below end do (setf x (+ (ash x 8) (elt data i)))) x)) (defun xpm-parse-color (data cpp index) (declare (type xpm-data-array data) (type (integer 1 4) cpp) ; ??? =p (type array-index index) (optimize (speed 3) (safety 0))) (let* ((color-token-end (the array-index (+ index cpp))) (code (xpm-extract-color-token data index color-token-end)) (string-end (1- (xpm-exit-string data color-token-end))) (color (xpm-parse-color-spec data color-token-end string-end))) (declare (type array-index color-token-end string-end) (type xpm-pixcode code)) (unless color (error "Color ~S does not parse." (map 'string #'code-char (subseq data color-token-end string-end)))) (values code color (1+ string-end)))) (declaim (inline xpm-key-p)) (defun xpm-key-p (x) (or (= x 109) (= x 115) (= x 103) (= x 99))) (defun xpm-parse-color-spec (data start end) says : ;; > Lossage! ;; > There exist files which say e.g. "c light yellow". ;; > How am I supposed to parse that? ;; > > It seems that the C code just parse everything until one of keys . ;; > That is we do the same although it is quite stupid. ( declare ( optimize ( debug 3 ) ( safety 3 ) ) ) (declare (optimize (speed 3) (space 0) (safety 0)) (type xpm-data-array data) (type array-index start end)) (let ((original-start start) key last-was-key color-token-start color-token-end) (declare (type (or null array-index) color-token-start color-token-end) (type (or null (unsigned-byte 8)) key)) (flet ((find-token (start end) (let* ((p1 (position-if-not #'xpm-white-space-p data :start start :end end)) (p2 (and p1 (or (position-if #'xpm-white-space-p data :start p1 :end end) end)))) (values p1 p2))) (quux (key color-token-start color-token-end) (let ((ink (xpm-parse-single-color key data color-token-start color-token-end))) (when ink (return-from xpm-parse-color-spec ink)))) (stringize () (map 'string #'code-char (subseq data original-start end)))) (loop (multiple-value-bind (p1 p2) (find-token start end) (unless p1 (when last-was-key (error "Premature end of color line (no color present after key): ~S." (stringize))) (when color-token-start (quux key color-token-start color-token-end)) (error "We failed to parse a color out of ~S." (stringize))) (cond (last-was-key (setf last-was-key nil color-token-start p1 color-token-end p2)) ((xpm-key-p (elt data p1)) (when color-token-start (quux key color-token-start color-token-end)) (setf last-was-key t color-token-start nil color-token-end nil key (elt data p1))) (t (when (null color-token-start) (error "Color not prefixed by a key: ~S." (stringize))) (setf last-was-key nil) (setf color-token-end p2))) (setf start p2)))))) (defun xpm-subvector-eql-p (data start end vector) ; FIXME: Guarantee type of input 'vector' and strengthen declaration (declare (type xpm-data-array data) (type array-index start end) (type simple-array vector) (optimize (speed 3))) (and (= (length vector) (- end start)) (loop for i from start below end do (unless (= (elt data i) (elt vector (- i start))) (return nil)) return t))) (defun xpm-parse-single-color (key data start end) (declare (type xpm-data-array data) (type array-index start end) (type (unsigned-byte 8) key) (optimize (speed 3))) (cond ((and (= key 115) (or (xpm-subvector-eql-p data start end #|"None"|# #(78 111 110 101)) (xpm-subvector-eql-p data start end #|"background"|# #(98 97 99 107 103 114 111 117 110 100)))) clim:+transparent-ink+) ((= key 99) (xpm-parse-single-color-2 data start end)) (t (error "Unimplemented key type ~A" key)))) (declaim (ftype (function ((unsigned-byte 8)) t) xpm-hex-digit-p)) (defun xpm-hex-digit-p (byte) (declare (type (unsigned-byte 8) byte) (optimize (speed 3))) (or (<= 48 byte 57) (<= 65 byte 70) (<= 97 byte 102))) (defun xpm-parse-integer-hex (data start end) (declare (type xpm-data-array data) (type array-index start end) (optimize (speed 3))) (let ((accumulator 0)) ; stupid optimizer.. (loop for index from start below end as byte = (elt data index) do (setf accumulator (+ (ash accumulator 4) (cond ((<= 48 byte 57) (- byte 48)) ((<= 65 byte 70) (- byte 65 -10)) ((<= 97 byte 102) (- byte 97 -10)) (t (error "Unknown hex digit ~A, this should be impossible." byte))))) finally (return accumulator)))) (defun xpm-parse-single-color-2 (data start end) (declare (type xpm-data-array data) (type array-index start end) (optimize (speed 3))) 35 = # \ # (= 0 (mod (- end start 1) 3)) (loop for i from (1+ start) below end do (unless (xpm-hex-digit-p (elt data i)) (return nil)) finally (return t)) (let* ((n (- end start 1)) (w (* 4 (/ n 3))) (m (1- (expt 2 w))) (x (xpm-parse-integer-hex data (1+ start) end))) (clim:make-rgb-color (/ (ldb (byte w (* 2 w)) x) m) (/ (ldb (byte w (* 1 w)) x) m) (/ (ldb (byte w (* 0 w)) x) m)))) (xpm-find-named-color (map 'string #'code-char (subseq data start end))))) (defun xpm-parse-header (data &optional (index 0)) (setf index (xpm-find-next-c-string data index)) (flet ((token (name) (multiple-value-bind (p1 p2) (xpm-token-bounds data index) (unless p1 (error "~A field missing in header." name)) (setf index p2) (parse-integer (map 'string #'code-char (subseq data p1 p2)) :radix 10 :junk-allowed nil)))) (values (token "width") (token "height") (token "ncolors") (token "cpp") (xpm-exit-string data index)))) (defun xpm-parse* (data) (declare (type xpm-data-array data)) (multiple-value-bind (width height ncolors cpp index) (xpm-parse-header data) (let ((color-hash (make-hash-table :test #'eql)) (designs (make-array ncolors)) (j 0)) (dotimes (i ncolors) (multiple-value-bind (code ink post-index) (xpm-parse-color data cpp (xpm-find-next-c-string data index)) (setf (aref designs j) ink (gethash code color-hash) j index post-index) (incf j))) ;; It is considerably faster still to make the array below of element type '(unsigned-byte 8), but this would be wrong by failing to load many legal XPM files . To support both , most ;; of this file would have to be compiled twice for the different types, which is more ;; trouble than its worth. =( (let ((res (make-array (list height width) #|:element-type '(unsigned-byte 8)|#))) ( line - start ( xpm - find - next - c - string data index ) ) (setf index (xpm-find-next-c-string data index)) (dotimes (y height) (dotimes (x width) (when (= 34 (elt data index)) ; Reached closing quote for this line of pixels? (setf index (xpm-find-next-c-string data (1+ index)))) (setf (aref res y x) (or (gethash (xpm-extract-color-token data index (+ index cpp)) color-hash) (error "Color code ~S not defined." (subseq data index (+ index cpp))))) (incf index cpp))) (values res designs))))) (declaim (ftype (function (xpm-data-array array-index) array-index) xpm-scan-comment)) (defun xpm-scan-comment (data start) (declare (optimize (speed 3))) (xpm-over-array (data b0 i0 b1 i1 start) (when (and (= b0 42) (= b1 47)) (return-from xpm-scan-comment (1+ i1)))) (error "Unterminated comment starting at byte ~A" (- start 2))) (defun xpm-find-next-c-string (data start) (declare (optimize (speed 3)) (type array-index start)) (xpm-over-array (data b0 i0 b1 i1 start) (cond 47 = # \/ (= b1 42)) ; 42 = #\* (setf i0 (1- (xpm-scan-comment data (1+ i1))))) ((= b0 34) (return i1))))) (declaim (ftype (function (xpm-data-array array-index) array-index) xpm-exit-string)) (defun xpm-exit-string (data start) (declare (optimize (speed 3))) (xpm-over-array (data byte index next-byte next-index start) (when (= byte 34) (return-from xpm-exit-string next-index)) ; 34 = #\" (when (= byte 92) (incf index))) ; 92 = #\\ (escape sequence) (error "Unterminated string")) ;(loop for index of-type array-index from start below length ; as byte = (elt data index) ; do (cond ( ; 42 = # \ * ( incf index 2 ) ; ;; a comment ; (do ((c1 0 c2) ; (c2 (elt data index) (elt data index))) ( and (= c1 42 ) (= c2 (defun xpm-parse-stream (input) ;; For not needing to parse an actual subset of C, we take a very lazy approach. We just seek out for the first # \ " and parse a C string from there . (let ((data (make-array (file-length input) :element-type '(unsigned-byte 8) :adjustable nil :fill-pointer nil))) (read-sequence data input) (xpm-parse* data))) (defun xpm-parse-file (pathname) (with-open-file (input pathname :element-type '(unsigned-byte 8)) (xpm-parse-stream input))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; X11 Colors ;;; (defparameter *xpm-x11-colors* '((255 250 250 "snow") (248 248 255 "ghost white") (248 248 255 "GhostWhite") (245 245 245 "white smoke") (245 245 245 "WhiteSmoke") (220 220 220 "gainsboro") (255 250 240 "floral white") (255 250 240 "FloralWhite") (253 245 230 "old lace") (253 245 230 "OldLace") (250 240 230 "linen") (250 235 215 "antique white") (250 235 215 "AntiqueWhite") (255 239 213 "papaya whip") (255 239 213 "PapayaWhip") (255 235 205 "blanched almond") (255 235 205 "BlanchedAlmond") (255 228 196 "bisque") (255 218 185 "peach puff") (255 218 185 "PeachPuff") (255 222 173 "navajo white") (255 222 173 "NavajoWhite") (255 228 181 "moccasin") (255 248 220 "cornsilk") (255 255 240 "ivory") (255 250 205 "lemon chiffon") (255 250 205 "LemonChiffon") (255 245 238 "seashell") (240 255 240 "honeydew") (245 255 250 "mint cream") (245 255 250 "MintCream") (240 255 255 "azure") (240 248 255 "alice blue") (240 248 255 "AliceBlue") (230 230 250 "lavender") (255 240 245 "lavender blush") (255 240 245 "LavenderBlush") (255 228 225 "misty rose") (255 228 225 "MistyRose") (255 255 255 "white") ( 0 0 0 "black") ( 47 79 79 "dark slate gray") ( 47 79 79 "DarkSlateGray") ( 47 79 79 "dark slate grey") ( 47 79 79 "DarkSlateGrey") (105 105 105 "dim gray") (105 105 105 "DimGray") (105 105 105 "dim grey") (105 105 105 "DimGrey") (112 128 144 "slate gray") (112 128 144 "SlateGray") (112 128 144 "slate grey") (112 128 144 "SlateGrey") (119 136 153 "light slate gray") (119 136 153 "LightSlateGray") (119 136 153 "light slate grey") (119 136 153 "LightSlateGrey") (190 190 190 "gray") (190 190 190 "grey") (211 211 211 "light grey") (211 211 211 "LightGrey") (211 211 211 "light gray") (211 211 211 "LightGray") ( 25 25 112 "midnight blue") ( 25 25 112 "MidnightBlue") ( 0 0 128 "navy") ( 0 0 128 "navy blue") ( 0 0 128 "NavyBlue") (100 149 237 "cornflower blue") (100 149 237 "CornflowerBlue") ( 72 61 139 "dark slate blue") ( 72 61 139 "DarkSlateBlue") (106 90 205 "slate blue") (106 90 205 "SlateBlue") (123 104 238 "medium slate blue") (123 104 238 "MediumSlateBlue") (132 112 255 "light slate blue") (132 112 255 "LightSlateBlue") ( 0 0 205 "medium blue") ( 0 0 205 "MediumBlue") ( 65 105 225 "royal blue") ( 65 105 225 "RoyalBlue") ( 0 0 255 "blue") ( 30 144 255 "dodger blue") ( 30 144 255 "DodgerBlue") ( 0 191 255 "deep sky blue") ( 0 191 255 "DeepSkyBlue") (135 206 235 "sky blue") (135 206 235 "SkyBlue") (135 206 250 "light sky blue") (135 206 250 "LightSkyBlue") ( 70 130 180 "steel blue") ( 70 130 180 "SteelBlue") (176 196 222 "light steel blue") (176 196 222 "LightSteelBlue") (173 216 230 "light blue") (173 216 230 "LightBlue") (176 224 230 "powder blue") (176 224 230 "PowderBlue") (175 238 238 "pale turquoise") (175 238 238 "PaleTurquoise") ( 0 206 209 "dark turquoise") ( 0 206 209 "DarkTurquoise") ( 72 209 204 "medium turquoise") ( 72 209 204 "MediumTurquoise") ( 64 224 208 "turquoise") ( 0 255 255 "cyan") (224 255 255 "light cyan") (224 255 255 "LightCyan") ( 95 158 160 "cadet blue") ( 95 158 160 "CadetBlue") (102 205 170 "medium aquamarine") (102 205 170 "MediumAquamarine") (127 255 212 "aquamarine") ( 0 100 0 "dark green") ( 0 100 0 "DarkGreen") ( 85 107 47 "dark olive green") ( 85 107 47 "DarkOliveGreen") (143 188 143 "dark sea green") (143 188 143 "DarkSeaGreen") ( 46 139 87 "sea green") ( 46 139 87 "SeaGreen") ( 60 179 113 "medium sea green") ( 60 179 113 "MediumSeaGreen") ( 32 178 170 "light sea green") ( 32 178 170 "LightSeaGreen") (152 251 152 "pale green") (152 251 152 "PaleGreen") ( 0 255 127 "spring green") ( 0 255 127 "SpringGreen") (124 252 0 "lawn green") (124 252 0 "LawnGreen") ( 0 255 0 "green") (127 255 0 "chartreuse") ( 0 250 154 "medium spring green") ( 0 250 154 "MediumSpringGreen") (173 255 47 "green yellow") (173 255 47 "GreenYellow") ( 50 205 50 "lime green") ( 50 205 50 "LimeGreen") (154 205 50 "yellow green") (154 205 50 "YellowGreen") ( 34 139 34 "forest green") ( 34 139 34 "ForestGreen") (107 142 35 "olive drab") (107 142 35 "OliveDrab") (189 183 107 "dark khaki") (189 183 107 "DarkKhaki") (240 230 140 "khaki") (238 232 170 "pale goldenrod") (238 232 170 "PaleGoldenrod") (250 250 210 "light goldenrod yellow") (250 250 210 "LightGoldenrodYellow") (255 255 224 "light yellow") (255 255 224 "LightYellow") (255 255 0 "yellow") (255 215 0 "gold") (238 221 130 "light goldenrod") (238 221 130 "LightGoldenrod") (218 165 32 "goldenrod") (184 134 11 "dark goldenrod") (184 134 11 "DarkGoldenrod") (188 143 143 "rosy brown") (188 143 143 "RosyBrown") (205 92 92 "indian red") (205 92 92 "IndianRed") (139 69 19 "saddle brown") (139 69 19 "SaddleBrown") (160 82 45 "sienna") (205 133 63 "peru") (222 184 135 "burlywood") (245 245 220 "beige") (245 222 179 "wheat") (244 164 96 "sandy brown") (244 164 96 "SandyBrown") (210 180 140 "tan") (210 105 30 "chocolate") (178 34 34 "firebrick") (165 42 42 "brown") (233 150 122 "dark salmon") (233 150 122 "DarkSalmon") (250 128 114 "salmon") (255 160 122 "light salmon") (255 160 122 "LightSalmon") (255 165 0 "orange") (255 140 0 "dark orange") (255 140 0 "DarkOrange") (255 127 80 "coral") (240 128 128 "light coral") (240 128 128 "LightCoral") (255 99 71 "tomato") (255 69 0 "orange red") (255 69 0 "OrangeRed") (255 0 0 "red") (255 105 180 "hot pink") (255 105 180 "HotPink") (255 20 147 "deep pink") (255 20 147 "DeepPink") (255 192 203 "pink") (255 182 193 "light pink") (255 182 193 "LightPink") (219 112 147 "pale violet red") (219 112 147 "PaleVioletRed") (176 48 96 "maroon") (199 21 133 "medium violet red") (199 21 133 "MediumVioletRed") (208 32 144 "violet red") (208 32 144 "VioletRed") (255 0 255 "magenta") (238 130 238 "violet") (221 160 221 "plum") (218 112 214 "orchid") (186 85 211 "medium orchid") (186 85 211 "MediumOrchid") (153 50 204 "dark orchid") (153 50 204 "DarkOrchid") (148 0 211 "dark violet") (148 0 211 "DarkViolet") (138 43 226 "blue violet") (138 43 226 "BlueViolet") (160 32 240 "purple") (147 112 219 "medium purple") (147 112 219 "MediumPurple") (216 191 216 "thistle") (255 250 250 "snow1") (238 233 233 "snow2") (205 201 201 "snow3") (139 137 137 "snow4") (255 245 238 "seashell1") (238 229 222 "seashell2") (205 197 191 "seashell3") (139 134 130 "seashell4") (255 239 219 "AntiqueWhite1") (238 223 204 "AntiqueWhite2") (205 192 176 "AntiqueWhite3") (139 131 120 "AntiqueWhite4") (255 228 196 "bisque1") (238 213 183 "bisque2") (205 183 158 "bisque3") (139 125 107 "bisque4") (255 218 185 "PeachPuff1") (238 203 173 "PeachPuff2") (205 175 149 "PeachPuff3") (139 119 101 "PeachPuff4") (255 222 173 "NavajoWhite1") (238 207 161 "NavajoWhite2") (205 179 139 "NavajoWhite3") (139 121 94 "NavajoWhite4") (255 250 205 "LemonChiffon1") (238 233 191 "LemonChiffon2") (205 201 165 "LemonChiffon3") (139 137 112 "LemonChiffon4") (255 248 220 "cornsilk1") (238 232 205 "cornsilk2") (205 200 177 "cornsilk3") (139 136 120 "cornsilk4") (255 255 240 "ivory1") (238 238 224 "ivory2") (205 205 193 "ivory3") (139 139 131 "ivory4") (240 255 240 "honeydew1") (224 238 224 "honeydew2") (193 205 193 "honeydew3") (131 139 131 "honeydew4") (255 240 245 "LavenderBlush1") (238 224 229 "LavenderBlush2") (205 193 197 "LavenderBlush3") (139 131 134 "LavenderBlush4") (255 228 225 "MistyRose1") (238 213 210 "MistyRose2") (205 183 181 "MistyRose3") (139 125 123 "MistyRose4") (240 255 255 "azure1") (224 238 238 "azure2") (193 205 205 "azure3") (131 139 139 "azure4") (131 111 255 "SlateBlue1") (122 103 238 "SlateBlue2") (105 89 205 "SlateBlue3") ( 71 60 139 "SlateBlue4") ( 72 118 255 "RoyalBlue1") ( 67 110 238 "RoyalBlue2") ( 58 95 205 "RoyalBlue3") ( 39 64 139 "RoyalBlue4") ( 0 0 255 "blue1") ( 0 0 238 "blue2") ( 0 0 205 "blue3") ( 0 0 139 "blue4") ( 30 144 255 "DodgerBlue1") ( 28 134 238 "DodgerBlue2") ( 24 116 205 "DodgerBlue3") ( 16 78 139 "DodgerBlue4") ( 99 184 255 "SteelBlue1") ( 92 172 238 "SteelBlue2") ( 79 148 205 "SteelBlue3") ( 54 100 139 "SteelBlue4") ( 0 191 255 "DeepSkyBlue1") ( 0 178 238 "DeepSkyBlue2") ( 0 154 205 "DeepSkyBlue3") ( 0 104 139 "DeepSkyBlue4") (135 206 255 "SkyBlue1") (126 192 238 "SkyBlue2") (108 166 205 "SkyBlue3") ( 74 112 139 "SkyBlue4") (176 226 255 "LightSkyBlue1") (164 211 238 "LightSkyBlue2") (141 182 205 "LightSkyBlue3") ( 96 123 139 "LightSkyBlue4") (198 226 255 "SlateGray1") (185 211 238 "SlateGray2") (159 182 205 "SlateGray3") (108 123 139 "SlateGray4") (202 225 255 "LightSteelBlue1") (188 210 238 "LightSteelBlue2") (162 181 205 "LightSteelBlue3") (110 123 139 "LightSteelBlue4") (191 239 255 "LightBlue1") (178 223 238 "LightBlue2") (154 192 205 "LightBlue3") (104 131 139 "LightBlue4") (224 255 255 "LightCyan1") (209 238 238 "LightCyan2") (180 205 205 "LightCyan3") (122 139 139 "LightCyan4") (187 255 255 "PaleTurquoise1") (174 238 238 "PaleTurquoise2") (150 205 205 "PaleTurquoise3") (102 139 139 "PaleTurquoise4") (152 245 255 "CadetBlue1") (142 229 238 "CadetBlue2") (122 197 205 "CadetBlue3") ( 83 134 139 "CadetBlue4") ( 0 245 255 "turquoise1") ( 0 229 238 "turquoise2") ( 0 197 205 "turquoise3") ( 0 134 139 "turquoise4") ( 0 255 255 "cyan1") ( 0 238 238 "cyan2") ( 0 205 205 "cyan3") ( 0 139 139 "cyan4") (151 255 255 "DarkSlateGray1") (141 238 238 "DarkSlateGray2") (121 205 205 "DarkSlateGray3") ( 82 139 139 "DarkSlateGray4") (127 255 212 "aquamarine1") (118 238 198 "aquamarine2") (102 205 170 "aquamarine3") ( 69 139 116 "aquamarine4") (193 255 193 "DarkSeaGreen1") (180 238 180 "DarkSeaGreen2") (155 205 155 "DarkSeaGreen3") (105 139 105 "DarkSeaGreen4") ( 84 255 159 "SeaGreen1") ( 78 238 148 "SeaGreen2") ( 67 205 128 "SeaGreen3") ( 46 139 87 "SeaGreen4") (154 255 154 "PaleGreen1") (144 238 144 "PaleGreen2") (124 205 124 "PaleGreen3") ( 84 139 84 "PaleGreen4") ( 0 255 127 "SpringGreen1") ( 0 238 118 "SpringGreen2") ( 0 205 102 "SpringGreen3") ( 0 139 69 "SpringGreen4") ( 0 255 0 "green1") ( 0 238 0 "green2") ( 0 205 0 "green3") ( 0 139 0 "green4") (127 255 0 "chartreuse1") (118 238 0 "chartreuse2") (102 205 0 "chartreuse3") ( 69 139 0 "chartreuse4") (192 255 62 "OliveDrab1") (179 238 58 "OliveDrab2") (154 205 50 "OliveDrab3") (105 139 34 "OliveDrab4") (202 255 112 "DarkOliveGreen1") (188 238 104 "DarkOliveGreen2") (162 205 90 "DarkOliveGreen3") (110 139 61 "DarkOliveGreen4") (255 246 143 "khaki1") (238 230 133 "khaki2") (205 198 115 "khaki3") (139 134 78 "khaki4") (255 236 139 "LightGoldenrod1") (238 220 130 "LightGoldenrod2") (205 190 112 "LightGoldenrod3") (139 129 76 "LightGoldenrod4") (255 255 224 "LightYellow1") (238 238 209 "LightYellow2") (205 205 180 "LightYellow3") (139 139 122 "LightYellow4") (255 255 0 "yellow1") (238 238 0 "yellow2") (205 205 0 "yellow3") (139 139 0 "yellow4") (255 215 0 "gold1") (238 201 0 "gold2") (205 173 0 "gold3") (139 117 0 "gold4") (255 193 37 "goldenrod1") (238 180 34 "goldenrod2") (205 155 29 "goldenrod3") (139 105 20 "goldenrod4") (255 185 15 "DarkGoldenrod1") (238 173 14 "DarkGoldenrod2") (205 149 12 "DarkGoldenrod3") (139 101 8 "DarkGoldenrod4") (255 193 193 "RosyBrown1") (238 180 180 "RosyBrown2") (205 155 155 "RosyBrown3") (139 105 105 "RosyBrown4") (255 106 106 "IndianRed1") (238 99 99 "IndianRed2") (205 85 85 "IndianRed3") (139 58 58 "IndianRed4") (255 130 71 "sienna1") (238 121 66 "sienna2") (205 104 57 "sienna3") (139 71 38 "sienna4") (255 211 155 "burlywood1") (238 197 145 "burlywood2") (205 170 125 "burlywood3") (139 115 85 "burlywood4") (255 231 186 "wheat1") (238 216 174 "wheat2") (205 186 150 "wheat3") (139 126 102 "wheat4") (255 165 79 "tan1") (238 154 73 "tan2") (205 133 63 "tan3") (139 90 43 "tan4") (255 127 36 "chocolate1") (238 118 33 "chocolate2") (205 102 29 "chocolate3") (139 69 19 "chocolate4") (255 48 48 "firebrick1") (238 44 44 "firebrick2") (205 38 38 "firebrick3") (139 26 26 "firebrick4") (255 64 64 "brown1") (238 59 59 "brown2") (205 51 51 "brown3") (139 35 35 "brown4") (255 140 105 "salmon1") (238 130 98 "salmon2") (205 112 84 "salmon3") (139 76 57 "salmon4") (255 160 122 "LightSalmon1") (238 149 114 "LightSalmon2") (205 129 98 "LightSalmon3") (139 87 66 "LightSalmon4") (255 165 0 "orange1") (238 154 0 "orange2") (205 133 0 "orange3") (139 90 0 "orange4") (255 127 0 "DarkOrange1") (238 118 0 "DarkOrange2") (205 102 0 "DarkOrange3") (139 69 0 "DarkOrange4") (255 114 86 "coral1") (238 106 80 "coral2") (205 91 69 "coral3") (139 62 47 "coral4") (255 99 71 "tomato1") (238 92 66 "tomato2") (205 79 57 "tomato3") (139 54 38 "tomato4") (255 69 0 "OrangeRed1") (238 64 0 "OrangeRed2") (205 55 0 "OrangeRed3") (139 37 0 "OrangeRed4") (255 0 0 "red1") (238 0 0 "red2") (205 0 0 "red3") (139 0 0 "red4") (255 20 147 "DeepPink1") (238 18 137 "DeepPink2") (205 16 118 "DeepPink3") (139 10 80 "DeepPink4") (255 110 180 "HotPink1") (238 106 167 "HotPink2") (205 96 144 "HotPink3") (139 58 98 "HotPink4") (255 181 197 "pink1") (238 169 184 "pink2") (205 145 158 "pink3") (139 99 108 "pink4") (255 174 185 "LightPink1") (238 162 173 "LightPink2") (205 140 149 "LightPink3") (139 95 101 "LightPink4") (255 130 171 "PaleVioletRed1") (238 121 159 "PaleVioletRed2") (205 104 137 "PaleVioletRed3") (139 71 93 "PaleVioletRed4") (255 52 179 "maroon1") (238 48 167 "maroon2") (205 41 144 "maroon3") (139 28 98 "maroon4") (255 62 150 "VioletRed1") (238 58 140 "VioletRed2") (205 50 120 "VioletRed3") (139 34 82 "VioletRed4") (255 0 255 "magenta1") (238 0 238 "magenta2") (205 0 205 "magenta3") (139 0 139 "magenta4") (255 131 250 "orchid1") (238 122 233 "orchid2") (205 105 201 "orchid3") (139 71 137 "orchid4") (255 187 255 "plum1") (238 174 238 "plum2") (205 150 205 "plum3") (139 102 139 "plum4") (224 102 255 "MediumOrchid1") (209 95 238 "MediumOrchid2") (180 82 205 "MediumOrchid3") (122 55 139 "MediumOrchid4") (191 62 255 "DarkOrchid1") (178 58 238 "DarkOrchid2") (154 50 205 "DarkOrchid3") (104 34 139 "DarkOrchid4") (155 48 255 "purple1") (145 44 238 "purple2") (125 38 205 "purple3") ( 85 26 139 "purple4") (171 130 255 "MediumPurple1") (159 121 238 "MediumPurple2") (137 104 205 "MediumPurple3") ( 93 71 139 "MediumPurple4") (255 225 255 "thistle1") (238 210 238 "thistle2") (205 181 205 "thistle3") (139 123 139 "thistle4") ( 0 0 0 "gray0") ( 0 0 0 "grey0") ( 3 3 3 "gray1") ( 3 3 3 "grey1") ( 5 5 5 "gray2") ( 5 5 5 "grey2") ( 8 8 8 "gray3") ( 8 8 8 "grey3") ( 10 10 10 "gray4") ( 10 10 10 "grey4") ( 13 13 13 "gray5") ( 13 13 13 "grey5") ( 15 15 15 "gray6") ( 15 15 15 "grey6") ( 18 18 18 "gray7") ( 18 18 18 "grey7") ( 20 20 20 "gray8") ( 20 20 20 "grey8") ( 23 23 23 "gray9") ( 23 23 23 "grey9") ( 26 26 26 "gray10") ( 26 26 26 "grey10") ( 28 28 28 "gray11") ( 28 28 28 "grey11") ( 31 31 31 "gray12") ( 31 31 31 "grey12") ( 33 33 33 "gray13") ( 33 33 33 "grey13") ( 36 36 36 "gray14") ( 36 36 36 "grey14") ( 38 38 38 "gray15") ( 38 38 38 "grey15") ( 41 41 41 "gray16") ( 41 41 41 "grey16") ( 43 43 43 "gray17") ( 43 43 43 "grey17") ( 46 46 46 "gray18") ( 46 46 46 "grey18") ( 48 48 48 "gray19") ( 48 48 48 "grey19") ( 51 51 51 "gray20") ( 51 51 51 "grey20") ( 54 54 54 "gray21") ( 54 54 54 "grey21") ( 56 56 56 "gray22") ( 56 56 56 "grey22") ( 59 59 59 "gray23") ( 59 59 59 "grey23") ( 61 61 61 "gray24") ( 61 61 61 "grey24") ( 64 64 64 "gray25") ( 64 64 64 "grey25") ( 66 66 66 "gray26") ( 66 66 66 "grey26") ( 69 69 69 "gray27") ( 69 69 69 "grey27") ( 71 71 71 "gray28") ( 71 71 71 "grey28") ( 74 74 74 "gray29") ( 74 74 74 "grey29") ( 77 77 77 "gray30") ( 77 77 77 "grey30") ( 79 79 79 "gray31") ( 79 79 79 "grey31") ( 82 82 82 "gray32") ( 82 82 82 "grey32") ( 84 84 84 "gray33") ( 84 84 84 "grey33") ( 87 87 87 "gray34") ( 87 87 87 "grey34") ( 89 89 89 "gray35") ( 89 89 89 "grey35") ( 92 92 92 "gray36") ( 92 92 92 "grey36") ( 94 94 94 "gray37") ( 94 94 94 "grey37") ( 97 97 97 "gray38") ( 97 97 97 "grey38") ( 99 99 99 "gray39") ( 99 99 99 "grey39") (102 102 102 "gray40") (102 102 102 "grey40") (105 105 105 "gray41") (105 105 105 "grey41") (107 107 107 "gray42") (107 107 107 "grey42") (110 110 110 "gray43") (110 110 110 "grey43") (112 112 112 "gray44") (112 112 112 "grey44") (115 115 115 "gray45") (115 115 115 "grey45") (117 117 117 "gray46") (117 117 117 "grey46") (120 120 120 "gray47") (120 120 120 "grey47") (122 122 122 "gray48") (122 122 122 "grey48") (125 125 125 "gray49") (125 125 125 "grey49") (127 127 127 "gray50") (127 127 127 "grey50") (130 130 130 "gray51") (130 130 130 "grey51") (133 133 133 "gray52") (133 133 133 "grey52") (135 135 135 "gray53") (135 135 135 "grey53") (138 138 138 "gray54") (138 138 138 "grey54") (140 140 140 "gray55") (140 140 140 "grey55") (143 143 143 "gray56") (143 143 143 "grey56") (145 145 145 "gray57") (145 145 145 "grey57") (148 148 148 "gray58") (148 148 148 "grey58") (150 150 150 "gray59") (150 150 150 "grey59") (153 153 153 "gray60") (153 153 153 "grey60") (156 156 156 "gray61") (156 156 156 "grey61") (158 158 158 "gray62") (158 158 158 "grey62") (161 161 161 "gray63") (161 161 161 "grey63") (163 163 163 "gray64") (163 163 163 "grey64") (166 166 166 "gray65") (166 166 166 "grey65") (168 168 168 "gray66") (168 168 168 "grey66") (171 171 171 "gray67") (171 171 171 "grey67") (173 173 173 "gray68") (173 173 173 "grey68") (176 176 176 "gray69") (176 176 176 "grey69") (179 179 179 "gray70") (179 179 179 "grey70") (181 181 181 "gray71") (181 181 181 "grey71") (184 184 184 "gray72") (184 184 184 "grey72") (186 186 186 "gray73") (186 186 186 "grey73") (189 189 189 "gray74") (189 189 189 "grey74") (191 191 191 "gray75") (191 191 191 "grey75") (194 194 194 "gray76") (194 194 194 "grey76") (196 196 196 "gray77") (196 196 196 "grey77") (199 199 199 "gray78") (199 199 199 "grey78") (201 201 201 "gray79") (201 201 201 "grey79") (204 204 204 "gray80") (204 204 204 "grey80") (207 207 207 "gray81") (207 207 207 "grey81") (209 209 209 "gray82") (209 209 209 "grey82") (212 212 212 "gray83") (212 212 212 "grey83") (214 214 214 "gray84") (214 214 214 "grey84") (217 217 217 "gray85") (217 217 217 "grey85") (219 219 219 "gray86") (219 219 219 "grey86") (222 222 222 "gray87") (222 222 222 "grey87") (224 224 224 "gray88") (224 224 224 "grey88") (227 227 227 "gray89") (227 227 227 "grey89") (229 229 229 "gray90") (229 229 229 "grey90") (232 232 232 "gray91") (232 232 232 "grey91") (235 235 235 "gray92") (235 235 235 "grey92") (237 237 237 "gray93") (237 237 237 "grey93") (240 240 240 "gray94") (240 240 240 "grey94") (242 242 242 "gray95") (242 242 242 "grey95") (245 245 245 "gray96") (245 245 245 "grey96") (247 247 247 "gray97") (247 247 247 "grey97") (250 250 250 "gray98") (250 250 250 "grey98") (252 252 252 "gray99") (252 252 252 "grey99") (255 255 255 "gray100") (255 255 255 "grey100") (169 169 169 "dark grey") (169 169 169 "DarkGrey") (169 169 169 "dark gray") (169 169 169 "DarkGray") (0 0 139 "dark blue") (0 0 139 "DarkBlue") (0 139 139 "dark cyan") (0 139 139 "DarkCyan") (139 0 139 "dark magenta") (139 0 139 "DarkMagenta") (139 0 0 "dark red") (139 0 0 "DarkRed") (144 238 144 "light green") (144 238 144 "LightGreen"))) (defun xpm-find-named-color (name) (if (string-equal name "None") clim:+transparent-ink+ (let ((q (find name *xpm-x11-colors* :key #'fourth :test #'string-equal))) (and q (clim:make-rgb-color (/ (first q) 255) (/ (second q) 255) (/ (third q) 255))))))
null
https://raw.githubusercontent.com/McCLIM/McCLIM/c079691b0913f8306ceff2620b045b6e24e2f745/Extensions/bitmap-formats/xpm.lisp
lisp
--------------------------------------------------------------------------- License: LGPL-2.1+ (See file 'Copyright' for details). --------------------------------------------------------------------------- --------------------------------------------------------------------------- modified to improve performance. This is achieved primarily by using read-sequence into an (unsigned-byte 8) array and parsing directly from this array (the original code read a list of strings using read-line and further divided these into substrings in various places. It is substantially faster than the original code, but there are opportunities to further improve performance by perhaps several times, including: - Use an array rather than hash table to resolve color tokens (I avoided doing this for now due to a pathological case of a file - Stricter type declarations (some but not all of the code assumes cpp<3) - In the worst case (photographs), we spent most of our time parsing - For the above case, we should be generating an RGB or RGBA image worth optimizing. visual. - We need a little refactoring: that. . Parsing of #rgb style colors is now the upteens place we have that in general. => Put that in utils.lisp and document its interface. it into sources files. I want a macro which takes a list of call. - This needs to be incorporated into READ-BITMAP-FILE or what ever that is called. - We might be interested in the hot spot also. Summary of the File Format | The XPM Format | | | /* XPM */ | static char* <variable_name>[] = { | <Values> | <Colors> | <Pixels> | <Extensions> | }; | | The words are separated by a white space which can be composed of | space and tabulation characters. The <Values> section is a string | pixmap width and height, the number of colors, the number of | characters per pixel (so there is no limit on the number of colors), | and, optionally the hotspot coordinates and the XPMEXT tag if there is | any extension following the <Pixels> section. | | <width> <height> <ncolors> <cpp> [<x_hotspot> <y_hotspot>] [XPMEXT] | | The Colors section contains as many strings as there are colors, and | each string is as follows: | | | Where <chars> is the <chars_per_pixel> length string (not surrounded | by anything) representing the pixels, <color> is the specified color, | and <key> is a keyword describing in which context this color should | be used. Currently the keys may have the following values: | | m for mono visual | s for symbolic name | c for color visual | | Colors can be specified by giving the colorname, a # followed by the | implemented). The symbolic name provides the ability of specifying the | colors at load time and not to hardcode them in the file. | | Also the string None can be given as a colorname to mean | providing a masking bitmap in addition to the pixmap. This mask can | The <Pixels> section is composed by <height> strings of <width> * | <chars_per_pixel> characters, where every <chars_per_pixel> length | string must be one of the previously defined groups in the <Colors> | section. | | Then follows the <Extensions> section which must be labeled, if not | empty, in the <Values> section as previously described. This section | types: | | | XPMEXT <extension-name> <extension-data> | | . or a block composed by several strings: | | XPMEXT <extension-name> | <related extension-data composed of several strings> | | Finally, if not empty, this section must end by the following string: | | XPMENDEXT | | Extensions can be used to store any type of data one might want to | store along with a pixmap, as long as they are properly encoded so | they do not conflict with the general syntax. To avoid possible | conflicts with extension names in shared files, they should be | prefixed by the name of the company. This would ensure uniqueness. | Bogus upper limit for speed.. =/ #\Space #\Newline #\" Bah, this didn't help. ??? =p > Lossage! > There exist files which say e.g. "c light yellow". > How am I supposed to parse that? > > That is we do the same although it is quite stupid. FIXME: Guarantee type of input 'vector' and strengthen declaration "None" "background" stupid optimizer.. It is considerably faster still to make the array below of element type '(unsigned-byte 8), of this file would have to be compiled twice for the different types, which is more trouble than its worth. =( :element-type '(unsigned-byte 8) Reached closing quote for this line of pixels? 42 = #\* 34 = #\" 92 = #\\ (escape sequence) (loop for index of-type array-index from start below length as byte = (elt data index) do (cond 42 = # \ * ;; a comment (do ((c1 0 c2) (c2 (elt data index) (elt data index))) For not needing to parse an actual subset of C, we take a very lazy approach. X11 Colors
( c ) Copyright 2003 by < > ( c ) Copyright 2006 by < > (in-package #:clim-internals) Notes This is essentially a rewrite / transliteration of 's original code , with a small palette but high CPP and sparse color tokens ) the palette ( it may have thousands or millions of entries ) . rather than an indexed - pattern ( and consing a ton of color objects ) . - People who save photographs in XPM format are morons , so it is n't 's Notes : - We lose when the XPM image only specifies colors for say the mono . The list of colors below is now actually the second place we have - The ASCII - centric approach of XPM makes it suitable for embedding strings according the XPM format and turns it into a make - pattern --GB 2003 - 05 - 25 [ as of the XPM-3.4i documentation by Arnaud Le Hors ] . | The XPM format presents a C syntax , in order to provide the ability to | include XPM files in C and C++ programs . It is in fact an array of | strings composed of six different sections as follows : | containing four or six integers in base 10 that correspond to : the | < chars > { < key > < color>}+ | g4 for 4 - level grayscale | g for grayscale with more than 4 levels | RGB code in hexadecimal , or a % followed by the HSV code ( not | ` ` transparent '' . Transparency is supported by the XPM library by | then be used either as a clip - mask of , or a shape - mask of a | window using the X11 Nonrectangular Window Shape Extension [ XShape ] . | may be composed by several < Extension > subsections which may be of two | . one stand alone string composed as follows : (deftype xpm-data-array () `(simple-array (unsigned-byte 8) 1)) (deftype array-index () #-sbcl '(integer 0 #.array-dimension-limit) #+sbcl 'sb-int:index) (defmacro xpm-over-array ((arrayform elt0 idx0 elt1 idx1 start) &body body) (let ((arraysym (gensym)) (lengthsym (gensym))) `(let* ((,arraysym ,arrayform) (,lengthsym (length ,arraysym))) (declare (type xpm-data-array ,arraysym) (optimize (speed 3))) (loop for ,idx0 of-type array-index from ,start below (1- ,lengthsym) as ,idx1 of-type array-index = (1+ ,idx0) as ,elt0 = (aref ,arraysym ,idx0) as ,elt1 = (aref ,arraysym ,idx1) do (progn ,@body))))) (declaim (inline xpm-whitespace-p) (ftype (function ((unsigned-byte 8)) t) xpm-whitespace-p)) (defun xpm-white-space-p (code) (declare (type (unsigned-byte 8) code) (optimize (speed 3))) # \Tab (defun xpm-token-terminator-p (code) (declare (type (unsigned-byte 8) code)) (or (xpm-white-space-p code) (defun xpm-token-bounds (data start) (xpm-over-array (data b0 start b1 i1 start) (when (not (xpm-white-space-p b0)) (xpm-over-array (data b0 end b1 i1 start) (when (xpm-token-terminator-p b0) (return-from xpm-token-bounds (values start end)))) (error "Unbounded token"))) (error "Missing token")) (defun xpm-extract-color-token (data start end) (declare (type xpm-data-array data) (type array-index start end) (optimize (speed 3))) (let ((x 0)) (loop for i from start below end do (setf x (+ (ash x 8) (elt data i)))) x)) (defun xpm-parse-color (data cpp index) (declare (type xpm-data-array data) (type array-index index) (optimize (speed 3) (safety 0))) (let* ((color-token-end (the array-index (+ index cpp))) (code (xpm-extract-color-token data index color-token-end)) (string-end (1- (xpm-exit-string data color-token-end))) (color (xpm-parse-color-spec data color-token-end string-end))) (declare (type array-index color-token-end string-end) (type xpm-pixcode code)) (unless color (error "Color ~S does not parse." (map 'string #'code-char (subseq data color-token-end string-end)))) (values code color (1+ string-end)))) (declaim (inline xpm-key-p)) (defun xpm-key-p (x) (or (= x 109) (= x 115) (= x 103) (= x 99))) (defun xpm-parse-color-spec (data start end) says : > It seems that the C code just parse everything until one of keys . ( declare ( optimize ( debug 3 ) ( safety 3 ) ) ) (declare (optimize (speed 3) (space 0) (safety 0)) (type xpm-data-array data) (type array-index start end)) (let ((original-start start) key last-was-key color-token-start color-token-end) (declare (type (or null array-index) color-token-start color-token-end) (type (or null (unsigned-byte 8)) key)) (flet ((find-token (start end) (let* ((p1 (position-if-not #'xpm-white-space-p data :start start :end end)) (p2 (and p1 (or (position-if #'xpm-white-space-p data :start p1 :end end) end)))) (values p1 p2))) (quux (key color-token-start color-token-end) (let ((ink (xpm-parse-single-color key data color-token-start color-token-end))) (when ink (return-from xpm-parse-color-spec ink)))) (stringize () (map 'string #'code-char (subseq data original-start end)))) (loop (multiple-value-bind (p1 p2) (find-token start end) (unless p1 (when last-was-key (error "Premature end of color line (no color present after key): ~S." (stringize))) (when color-token-start (quux key color-token-start color-token-end)) (error "We failed to parse a color out of ~S." (stringize))) (cond (last-was-key (setf last-was-key nil color-token-start p1 color-token-end p2)) ((xpm-key-p (elt data p1)) (when color-token-start (quux key color-token-start color-token-end)) (setf last-was-key t color-token-start nil color-token-end nil key (elt data p1))) (t (when (null color-token-start) (error "Color not prefixed by a key: ~S." (stringize))) (setf last-was-key nil) (setf color-token-end p2))) (setf start p2)))))) (declare (type xpm-data-array data) (type array-index start end) (type simple-array vector) (optimize (speed 3))) (and (= (length vector) (- end start)) (loop for i from start below end do (unless (= (elt data i) (elt vector (- i start))) (return nil)) return t))) (defun xpm-parse-single-color (key data start end) (declare (type xpm-data-array data) (type array-index start end) (type (unsigned-byte 8) key) (optimize (speed 3))) (cond ((and (= key 115) (or clim:+transparent-ink+) ((= key 99) (xpm-parse-single-color-2 data start end)) (t (error "Unimplemented key type ~A" key)))) (declaim (ftype (function ((unsigned-byte 8)) t) xpm-hex-digit-p)) (defun xpm-hex-digit-p (byte) (declare (type (unsigned-byte 8) byte) (optimize (speed 3))) (or (<= 48 byte 57) (<= 65 byte 70) (<= 97 byte 102))) (defun xpm-parse-integer-hex (data start end) (declare (type xpm-data-array data) (type array-index start end) (optimize (speed 3))) (loop for index from start below end as byte = (elt data index) do (setf accumulator (+ (ash accumulator 4) (cond ((<= 48 byte 57) (- byte 48)) ((<= 65 byte 70) (- byte 65 -10)) ((<= 97 byte 102) (- byte 97 -10)) (t (error "Unknown hex digit ~A, this should be impossible." byte))))) finally (return accumulator)))) (defun xpm-parse-single-color-2 (data start end) (declare (type xpm-data-array data) (type array-index start end) (optimize (speed 3))) 35 = # \ # (= 0 (mod (- end start 1) 3)) (loop for i from (1+ start) below end do (unless (xpm-hex-digit-p (elt data i)) (return nil)) finally (return t)) (let* ((n (- end start 1)) (w (* 4 (/ n 3))) (m (1- (expt 2 w))) (x (xpm-parse-integer-hex data (1+ start) end))) (clim:make-rgb-color (/ (ldb (byte w (* 2 w)) x) m) (/ (ldb (byte w (* 1 w)) x) m) (/ (ldb (byte w (* 0 w)) x) m)))) (xpm-find-named-color (map 'string #'code-char (subseq data start end))))) (defun xpm-parse-header (data &optional (index 0)) (setf index (xpm-find-next-c-string data index)) (flet ((token (name) (multiple-value-bind (p1 p2) (xpm-token-bounds data index) (unless p1 (error "~A field missing in header." name)) (setf index p2) (parse-integer (map 'string #'code-char (subseq data p1 p2)) :radix 10 :junk-allowed nil)))) (values (token "width") (token "height") (token "ncolors") (token "cpp") (xpm-exit-string data index)))) (defun xpm-parse* (data) (declare (type xpm-data-array data)) (multiple-value-bind (width height ncolors cpp index) (xpm-parse-header data) (let ((color-hash (make-hash-table :test #'eql)) (designs (make-array ncolors)) (j 0)) (dotimes (i ncolors) (multiple-value-bind (code ink post-index) (xpm-parse-color data cpp (xpm-find-next-c-string data index)) (setf (aref designs j) ink (gethash code color-hash) j index post-index) (incf j))) but this would be wrong by failing to load many legal XPM files . To support both , most ( line - start ( xpm - find - next - c - string data index ) ) (setf index (xpm-find-next-c-string data index)) (dotimes (y height) (dotimes (x width) (setf index (xpm-find-next-c-string data (1+ index)))) (setf (aref res y x) (or (gethash (xpm-extract-color-token data index (+ index cpp)) color-hash) (error "Color code ~S not defined." (subseq data index (+ index cpp))))) (incf index cpp))) (values res designs))))) (declaim (ftype (function (xpm-data-array array-index) array-index) xpm-scan-comment)) (defun xpm-scan-comment (data start) (declare (optimize (speed 3))) (xpm-over-array (data b0 i0 b1 i1 start) (when (and (= b0 42) (= b1 47)) (return-from xpm-scan-comment (1+ i1)))) (error "Unterminated comment starting at byte ~A" (- start 2))) (defun xpm-find-next-c-string (data start) (declare (optimize (speed 3)) (type array-index start)) (xpm-over-array (data b0 i0 b1 i1 start) (cond 47 = # \/ (setf i0 (1- (xpm-scan-comment data (1+ i1))))) ((= b0 34) (return i1))))) (declaim (ftype (function (xpm-data-array array-index) array-index) xpm-exit-string)) (defun xpm-exit-string (data start) (declare (optimize (speed 3))) (xpm-over-array (data byte index next-byte next-index start) (error "Unterminated string")) ( incf index 2 ) ( and (= c1 42 ) (= c2 (defun xpm-parse-stream (input) We just seek out for the first # \ " and parse a C string from there . (let ((data (make-array (file-length input) :element-type '(unsigned-byte 8) :adjustable nil :fill-pointer nil))) (read-sequence data input) (xpm-parse* data))) (defun xpm-parse-file (pathname) (with-open-file (input pathname :element-type '(unsigned-byte 8)) (xpm-parse-stream input))) (defparameter *xpm-x11-colors* '((255 250 250 "snow") (248 248 255 "ghost white") (248 248 255 "GhostWhite") (245 245 245 "white smoke") (245 245 245 "WhiteSmoke") (220 220 220 "gainsboro") (255 250 240 "floral white") (255 250 240 "FloralWhite") (253 245 230 "old lace") (253 245 230 "OldLace") (250 240 230 "linen") (250 235 215 "antique white") (250 235 215 "AntiqueWhite") (255 239 213 "papaya whip") (255 239 213 "PapayaWhip") (255 235 205 "blanched almond") (255 235 205 "BlanchedAlmond") (255 228 196 "bisque") (255 218 185 "peach puff") (255 218 185 "PeachPuff") (255 222 173 "navajo white") (255 222 173 "NavajoWhite") (255 228 181 "moccasin") (255 248 220 "cornsilk") (255 255 240 "ivory") (255 250 205 "lemon chiffon") (255 250 205 "LemonChiffon") (255 245 238 "seashell") (240 255 240 "honeydew") (245 255 250 "mint cream") (245 255 250 "MintCream") (240 255 255 "azure") (240 248 255 "alice blue") (240 248 255 "AliceBlue") (230 230 250 "lavender") (255 240 245 "lavender blush") (255 240 245 "LavenderBlush") (255 228 225 "misty rose") (255 228 225 "MistyRose") (255 255 255 "white") ( 0 0 0 "black") ( 47 79 79 "dark slate gray") ( 47 79 79 "DarkSlateGray") ( 47 79 79 "dark slate grey") ( 47 79 79 "DarkSlateGrey") (105 105 105 "dim gray") (105 105 105 "DimGray") (105 105 105 "dim grey") (105 105 105 "DimGrey") (112 128 144 "slate gray") (112 128 144 "SlateGray") (112 128 144 "slate grey") (112 128 144 "SlateGrey") (119 136 153 "light slate gray") (119 136 153 "LightSlateGray") (119 136 153 "light slate grey") (119 136 153 "LightSlateGrey") (190 190 190 "gray") (190 190 190 "grey") (211 211 211 "light grey") (211 211 211 "LightGrey") (211 211 211 "light gray") (211 211 211 "LightGray") ( 25 25 112 "midnight blue") ( 25 25 112 "MidnightBlue") ( 0 0 128 "navy") ( 0 0 128 "navy blue") ( 0 0 128 "NavyBlue") (100 149 237 "cornflower blue") (100 149 237 "CornflowerBlue") ( 72 61 139 "dark slate blue") ( 72 61 139 "DarkSlateBlue") (106 90 205 "slate blue") (106 90 205 "SlateBlue") (123 104 238 "medium slate blue") (123 104 238 "MediumSlateBlue") (132 112 255 "light slate blue") (132 112 255 "LightSlateBlue") ( 0 0 205 "medium blue") ( 0 0 205 "MediumBlue") ( 65 105 225 "royal blue") ( 65 105 225 "RoyalBlue") ( 0 0 255 "blue") ( 30 144 255 "dodger blue") ( 30 144 255 "DodgerBlue") ( 0 191 255 "deep sky blue") ( 0 191 255 "DeepSkyBlue") (135 206 235 "sky blue") (135 206 235 "SkyBlue") (135 206 250 "light sky blue") (135 206 250 "LightSkyBlue") ( 70 130 180 "steel blue") ( 70 130 180 "SteelBlue") (176 196 222 "light steel blue") (176 196 222 "LightSteelBlue") (173 216 230 "light blue") (173 216 230 "LightBlue") (176 224 230 "powder blue") (176 224 230 "PowderBlue") (175 238 238 "pale turquoise") (175 238 238 "PaleTurquoise") ( 0 206 209 "dark turquoise") ( 0 206 209 "DarkTurquoise") ( 72 209 204 "medium turquoise") ( 72 209 204 "MediumTurquoise") ( 64 224 208 "turquoise") ( 0 255 255 "cyan") (224 255 255 "light cyan") (224 255 255 "LightCyan") ( 95 158 160 "cadet blue") ( 95 158 160 "CadetBlue") (102 205 170 "medium aquamarine") (102 205 170 "MediumAquamarine") (127 255 212 "aquamarine") ( 0 100 0 "dark green") ( 0 100 0 "DarkGreen") ( 85 107 47 "dark olive green") ( 85 107 47 "DarkOliveGreen") (143 188 143 "dark sea green") (143 188 143 "DarkSeaGreen") ( 46 139 87 "sea green") ( 46 139 87 "SeaGreen") ( 60 179 113 "medium sea green") ( 60 179 113 "MediumSeaGreen") ( 32 178 170 "light sea green") ( 32 178 170 "LightSeaGreen") (152 251 152 "pale green") (152 251 152 "PaleGreen") ( 0 255 127 "spring green") ( 0 255 127 "SpringGreen") (124 252 0 "lawn green") (124 252 0 "LawnGreen") ( 0 255 0 "green") (127 255 0 "chartreuse") ( 0 250 154 "medium spring green") ( 0 250 154 "MediumSpringGreen") (173 255 47 "green yellow") (173 255 47 "GreenYellow") ( 50 205 50 "lime green") ( 50 205 50 "LimeGreen") (154 205 50 "yellow green") (154 205 50 "YellowGreen") ( 34 139 34 "forest green") ( 34 139 34 "ForestGreen") (107 142 35 "olive drab") (107 142 35 "OliveDrab") (189 183 107 "dark khaki") (189 183 107 "DarkKhaki") (240 230 140 "khaki") (238 232 170 "pale goldenrod") (238 232 170 "PaleGoldenrod") (250 250 210 "light goldenrod yellow") (250 250 210 "LightGoldenrodYellow") (255 255 224 "light yellow") (255 255 224 "LightYellow") (255 255 0 "yellow") (255 215 0 "gold") (238 221 130 "light goldenrod") (238 221 130 "LightGoldenrod") (218 165 32 "goldenrod") (184 134 11 "dark goldenrod") (184 134 11 "DarkGoldenrod") (188 143 143 "rosy brown") (188 143 143 "RosyBrown") (205 92 92 "indian red") (205 92 92 "IndianRed") (139 69 19 "saddle brown") (139 69 19 "SaddleBrown") (160 82 45 "sienna") (205 133 63 "peru") (222 184 135 "burlywood") (245 245 220 "beige") (245 222 179 "wheat") (244 164 96 "sandy brown") (244 164 96 "SandyBrown") (210 180 140 "tan") (210 105 30 "chocolate") (178 34 34 "firebrick") (165 42 42 "brown") (233 150 122 "dark salmon") (233 150 122 "DarkSalmon") (250 128 114 "salmon") (255 160 122 "light salmon") (255 160 122 "LightSalmon") (255 165 0 "orange") (255 140 0 "dark orange") (255 140 0 "DarkOrange") (255 127 80 "coral") (240 128 128 "light coral") (240 128 128 "LightCoral") (255 99 71 "tomato") (255 69 0 "orange red") (255 69 0 "OrangeRed") (255 0 0 "red") (255 105 180 "hot pink") (255 105 180 "HotPink") (255 20 147 "deep pink") (255 20 147 "DeepPink") (255 192 203 "pink") (255 182 193 "light pink") (255 182 193 "LightPink") (219 112 147 "pale violet red") (219 112 147 "PaleVioletRed") (176 48 96 "maroon") (199 21 133 "medium violet red") (199 21 133 "MediumVioletRed") (208 32 144 "violet red") (208 32 144 "VioletRed") (255 0 255 "magenta") (238 130 238 "violet") (221 160 221 "plum") (218 112 214 "orchid") (186 85 211 "medium orchid") (186 85 211 "MediumOrchid") (153 50 204 "dark orchid") (153 50 204 "DarkOrchid") (148 0 211 "dark violet") (148 0 211 "DarkViolet") (138 43 226 "blue violet") (138 43 226 "BlueViolet") (160 32 240 "purple") (147 112 219 "medium purple") (147 112 219 "MediumPurple") (216 191 216 "thistle") (255 250 250 "snow1") (238 233 233 "snow2") (205 201 201 "snow3") (139 137 137 "snow4") (255 245 238 "seashell1") (238 229 222 "seashell2") (205 197 191 "seashell3") (139 134 130 "seashell4") (255 239 219 "AntiqueWhite1") (238 223 204 "AntiqueWhite2") (205 192 176 "AntiqueWhite3") (139 131 120 "AntiqueWhite4") (255 228 196 "bisque1") (238 213 183 "bisque2") (205 183 158 "bisque3") (139 125 107 "bisque4") (255 218 185 "PeachPuff1") (238 203 173 "PeachPuff2") (205 175 149 "PeachPuff3") (139 119 101 "PeachPuff4") (255 222 173 "NavajoWhite1") (238 207 161 "NavajoWhite2") (205 179 139 "NavajoWhite3") (139 121 94 "NavajoWhite4") (255 250 205 "LemonChiffon1") (238 233 191 "LemonChiffon2") (205 201 165 "LemonChiffon3") (139 137 112 "LemonChiffon4") (255 248 220 "cornsilk1") (238 232 205 "cornsilk2") (205 200 177 "cornsilk3") (139 136 120 "cornsilk4") (255 255 240 "ivory1") (238 238 224 "ivory2") (205 205 193 "ivory3") (139 139 131 "ivory4") (240 255 240 "honeydew1") (224 238 224 "honeydew2") (193 205 193 "honeydew3") (131 139 131 "honeydew4") (255 240 245 "LavenderBlush1") (238 224 229 "LavenderBlush2") (205 193 197 "LavenderBlush3") (139 131 134 "LavenderBlush4") (255 228 225 "MistyRose1") (238 213 210 "MistyRose2") (205 183 181 "MistyRose3") (139 125 123 "MistyRose4") (240 255 255 "azure1") (224 238 238 "azure2") (193 205 205 "azure3") (131 139 139 "azure4") (131 111 255 "SlateBlue1") (122 103 238 "SlateBlue2") (105 89 205 "SlateBlue3") ( 71 60 139 "SlateBlue4") ( 72 118 255 "RoyalBlue1") ( 67 110 238 "RoyalBlue2") ( 58 95 205 "RoyalBlue3") ( 39 64 139 "RoyalBlue4") ( 0 0 255 "blue1") ( 0 0 238 "blue2") ( 0 0 205 "blue3") ( 0 0 139 "blue4") ( 30 144 255 "DodgerBlue1") ( 28 134 238 "DodgerBlue2") ( 24 116 205 "DodgerBlue3") ( 16 78 139 "DodgerBlue4") ( 99 184 255 "SteelBlue1") ( 92 172 238 "SteelBlue2") ( 79 148 205 "SteelBlue3") ( 54 100 139 "SteelBlue4") ( 0 191 255 "DeepSkyBlue1") ( 0 178 238 "DeepSkyBlue2") ( 0 154 205 "DeepSkyBlue3") ( 0 104 139 "DeepSkyBlue4") (135 206 255 "SkyBlue1") (126 192 238 "SkyBlue2") (108 166 205 "SkyBlue3") ( 74 112 139 "SkyBlue4") (176 226 255 "LightSkyBlue1") (164 211 238 "LightSkyBlue2") (141 182 205 "LightSkyBlue3") ( 96 123 139 "LightSkyBlue4") (198 226 255 "SlateGray1") (185 211 238 "SlateGray2") (159 182 205 "SlateGray3") (108 123 139 "SlateGray4") (202 225 255 "LightSteelBlue1") (188 210 238 "LightSteelBlue2") (162 181 205 "LightSteelBlue3") (110 123 139 "LightSteelBlue4") (191 239 255 "LightBlue1") (178 223 238 "LightBlue2") (154 192 205 "LightBlue3") (104 131 139 "LightBlue4") (224 255 255 "LightCyan1") (209 238 238 "LightCyan2") (180 205 205 "LightCyan3") (122 139 139 "LightCyan4") (187 255 255 "PaleTurquoise1") (174 238 238 "PaleTurquoise2") (150 205 205 "PaleTurquoise3") (102 139 139 "PaleTurquoise4") (152 245 255 "CadetBlue1") (142 229 238 "CadetBlue2") (122 197 205 "CadetBlue3") ( 83 134 139 "CadetBlue4") ( 0 245 255 "turquoise1") ( 0 229 238 "turquoise2") ( 0 197 205 "turquoise3") ( 0 134 139 "turquoise4") ( 0 255 255 "cyan1") ( 0 238 238 "cyan2") ( 0 205 205 "cyan3") ( 0 139 139 "cyan4") (151 255 255 "DarkSlateGray1") (141 238 238 "DarkSlateGray2") (121 205 205 "DarkSlateGray3") ( 82 139 139 "DarkSlateGray4") (127 255 212 "aquamarine1") (118 238 198 "aquamarine2") (102 205 170 "aquamarine3") ( 69 139 116 "aquamarine4") (193 255 193 "DarkSeaGreen1") (180 238 180 "DarkSeaGreen2") (155 205 155 "DarkSeaGreen3") (105 139 105 "DarkSeaGreen4") ( 84 255 159 "SeaGreen1") ( 78 238 148 "SeaGreen2") ( 67 205 128 "SeaGreen3") ( 46 139 87 "SeaGreen4") (154 255 154 "PaleGreen1") (144 238 144 "PaleGreen2") (124 205 124 "PaleGreen3") ( 84 139 84 "PaleGreen4") ( 0 255 127 "SpringGreen1") ( 0 238 118 "SpringGreen2") ( 0 205 102 "SpringGreen3") ( 0 139 69 "SpringGreen4") ( 0 255 0 "green1") ( 0 238 0 "green2") ( 0 205 0 "green3") ( 0 139 0 "green4") (127 255 0 "chartreuse1") (118 238 0 "chartreuse2") (102 205 0 "chartreuse3") ( 69 139 0 "chartreuse4") (192 255 62 "OliveDrab1") (179 238 58 "OliveDrab2") (154 205 50 "OliveDrab3") (105 139 34 "OliveDrab4") (202 255 112 "DarkOliveGreen1") (188 238 104 "DarkOliveGreen2") (162 205 90 "DarkOliveGreen3") (110 139 61 "DarkOliveGreen4") (255 246 143 "khaki1") (238 230 133 "khaki2") (205 198 115 "khaki3") (139 134 78 "khaki4") (255 236 139 "LightGoldenrod1") (238 220 130 "LightGoldenrod2") (205 190 112 "LightGoldenrod3") (139 129 76 "LightGoldenrod4") (255 255 224 "LightYellow1") (238 238 209 "LightYellow2") (205 205 180 "LightYellow3") (139 139 122 "LightYellow4") (255 255 0 "yellow1") (238 238 0 "yellow2") (205 205 0 "yellow3") (139 139 0 "yellow4") (255 215 0 "gold1") (238 201 0 "gold2") (205 173 0 "gold3") (139 117 0 "gold4") (255 193 37 "goldenrod1") (238 180 34 "goldenrod2") (205 155 29 "goldenrod3") (139 105 20 "goldenrod4") (255 185 15 "DarkGoldenrod1") (238 173 14 "DarkGoldenrod2") (205 149 12 "DarkGoldenrod3") (139 101 8 "DarkGoldenrod4") (255 193 193 "RosyBrown1") (238 180 180 "RosyBrown2") (205 155 155 "RosyBrown3") (139 105 105 "RosyBrown4") (255 106 106 "IndianRed1") (238 99 99 "IndianRed2") (205 85 85 "IndianRed3") (139 58 58 "IndianRed4") (255 130 71 "sienna1") (238 121 66 "sienna2") (205 104 57 "sienna3") (139 71 38 "sienna4") (255 211 155 "burlywood1") (238 197 145 "burlywood2") (205 170 125 "burlywood3") (139 115 85 "burlywood4") (255 231 186 "wheat1") (238 216 174 "wheat2") (205 186 150 "wheat3") (139 126 102 "wheat4") (255 165 79 "tan1") (238 154 73 "tan2") (205 133 63 "tan3") (139 90 43 "tan4") (255 127 36 "chocolate1") (238 118 33 "chocolate2") (205 102 29 "chocolate3") (139 69 19 "chocolate4") (255 48 48 "firebrick1") (238 44 44 "firebrick2") (205 38 38 "firebrick3") (139 26 26 "firebrick4") (255 64 64 "brown1") (238 59 59 "brown2") (205 51 51 "brown3") (139 35 35 "brown4") (255 140 105 "salmon1") (238 130 98 "salmon2") (205 112 84 "salmon3") (139 76 57 "salmon4") (255 160 122 "LightSalmon1") (238 149 114 "LightSalmon2") (205 129 98 "LightSalmon3") (139 87 66 "LightSalmon4") (255 165 0 "orange1") (238 154 0 "orange2") (205 133 0 "orange3") (139 90 0 "orange4") (255 127 0 "DarkOrange1") (238 118 0 "DarkOrange2") (205 102 0 "DarkOrange3") (139 69 0 "DarkOrange4") (255 114 86 "coral1") (238 106 80 "coral2") (205 91 69 "coral3") (139 62 47 "coral4") (255 99 71 "tomato1") (238 92 66 "tomato2") (205 79 57 "tomato3") (139 54 38 "tomato4") (255 69 0 "OrangeRed1") (238 64 0 "OrangeRed2") (205 55 0 "OrangeRed3") (139 37 0 "OrangeRed4") (255 0 0 "red1") (238 0 0 "red2") (205 0 0 "red3") (139 0 0 "red4") (255 20 147 "DeepPink1") (238 18 137 "DeepPink2") (205 16 118 "DeepPink3") (139 10 80 "DeepPink4") (255 110 180 "HotPink1") (238 106 167 "HotPink2") (205 96 144 "HotPink3") (139 58 98 "HotPink4") (255 181 197 "pink1") (238 169 184 "pink2") (205 145 158 "pink3") (139 99 108 "pink4") (255 174 185 "LightPink1") (238 162 173 "LightPink2") (205 140 149 "LightPink3") (139 95 101 "LightPink4") (255 130 171 "PaleVioletRed1") (238 121 159 "PaleVioletRed2") (205 104 137 "PaleVioletRed3") (139 71 93 "PaleVioletRed4") (255 52 179 "maroon1") (238 48 167 "maroon2") (205 41 144 "maroon3") (139 28 98 "maroon4") (255 62 150 "VioletRed1") (238 58 140 "VioletRed2") (205 50 120 "VioletRed3") (139 34 82 "VioletRed4") (255 0 255 "magenta1") (238 0 238 "magenta2") (205 0 205 "magenta3") (139 0 139 "magenta4") (255 131 250 "orchid1") (238 122 233 "orchid2") (205 105 201 "orchid3") (139 71 137 "orchid4") (255 187 255 "plum1") (238 174 238 "plum2") (205 150 205 "plum3") (139 102 139 "plum4") (224 102 255 "MediumOrchid1") (209 95 238 "MediumOrchid2") (180 82 205 "MediumOrchid3") (122 55 139 "MediumOrchid4") (191 62 255 "DarkOrchid1") (178 58 238 "DarkOrchid2") (154 50 205 "DarkOrchid3") (104 34 139 "DarkOrchid4") (155 48 255 "purple1") (145 44 238 "purple2") (125 38 205 "purple3") ( 85 26 139 "purple4") (171 130 255 "MediumPurple1") (159 121 238 "MediumPurple2") (137 104 205 "MediumPurple3") ( 93 71 139 "MediumPurple4") (255 225 255 "thistle1") (238 210 238 "thistle2") (205 181 205 "thistle3") (139 123 139 "thistle4") ( 0 0 0 "gray0") ( 0 0 0 "grey0") ( 3 3 3 "gray1") ( 3 3 3 "grey1") ( 5 5 5 "gray2") ( 5 5 5 "grey2") ( 8 8 8 "gray3") ( 8 8 8 "grey3") ( 10 10 10 "gray4") ( 10 10 10 "grey4") ( 13 13 13 "gray5") ( 13 13 13 "grey5") ( 15 15 15 "gray6") ( 15 15 15 "grey6") ( 18 18 18 "gray7") ( 18 18 18 "grey7") ( 20 20 20 "gray8") ( 20 20 20 "grey8") ( 23 23 23 "gray9") ( 23 23 23 "grey9") ( 26 26 26 "gray10") ( 26 26 26 "grey10") ( 28 28 28 "gray11") ( 28 28 28 "grey11") ( 31 31 31 "gray12") ( 31 31 31 "grey12") ( 33 33 33 "gray13") ( 33 33 33 "grey13") ( 36 36 36 "gray14") ( 36 36 36 "grey14") ( 38 38 38 "gray15") ( 38 38 38 "grey15") ( 41 41 41 "gray16") ( 41 41 41 "grey16") ( 43 43 43 "gray17") ( 43 43 43 "grey17") ( 46 46 46 "gray18") ( 46 46 46 "grey18") ( 48 48 48 "gray19") ( 48 48 48 "grey19") ( 51 51 51 "gray20") ( 51 51 51 "grey20") ( 54 54 54 "gray21") ( 54 54 54 "grey21") ( 56 56 56 "gray22") ( 56 56 56 "grey22") ( 59 59 59 "gray23") ( 59 59 59 "grey23") ( 61 61 61 "gray24") ( 61 61 61 "grey24") ( 64 64 64 "gray25") ( 64 64 64 "grey25") ( 66 66 66 "gray26") ( 66 66 66 "grey26") ( 69 69 69 "gray27") ( 69 69 69 "grey27") ( 71 71 71 "gray28") ( 71 71 71 "grey28") ( 74 74 74 "gray29") ( 74 74 74 "grey29") ( 77 77 77 "gray30") ( 77 77 77 "grey30") ( 79 79 79 "gray31") ( 79 79 79 "grey31") ( 82 82 82 "gray32") ( 82 82 82 "grey32") ( 84 84 84 "gray33") ( 84 84 84 "grey33") ( 87 87 87 "gray34") ( 87 87 87 "grey34") ( 89 89 89 "gray35") ( 89 89 89 "grey35") ( 92 92 92 "gray36") ( 92 92 92 "grey36") ( 94 94 94 "gray37") ( 94 94 94 "grey37") ( 97 97 97 "gray38") ( 97 97 97 "grey38") ( 99 99 99 "gray39") ( 99 99 99 "grey39") (102 102 102 "gray40") (102 102 102 "grey40") (105 105 105 "gray41") (105 105 105 "grey41") (107 107 107 "gray42") (107 107 107 "grey42") (110 110 110 "gray43") (110 110 110 "grey43") (112 112 112 "gray44") (112 112 112 "grey44") (115 115 115 "gray45") (115 115 115 "grey45") (117 117 117 "gray46") (117 117 117 "grey46") (120 120 120 "gray47") (120 120 120 "grey47") (122 122 122 "gray48") (122 122 122 "grey48") (125 125 125 "gray49") (125 125 125 "grey49") (127 127 127 "gray50") (127 127 127 "grey50") (130 130 130 "gray51") (130 130 130 "grey51") (133 133 133 "gray52") (133 133 133 "grey52") (135 135 135 "gray53") (135 135 135 "grey53") (138 138 138 "gray54") (138 138 138 "grey54") (140 140 140 "gray55") (140 140 140 "grey55") (143 143 143 "gray56") (143 143 143 "grey56") (145 145 145 "gray57") (145 145 145 "grey57") (148 148 148 "gray58") (148 148 148 "grey58") (150 150 150 "gray59") (150 150 150 "grey59") (153 153 153 "gray60") (153 153 153 "grey60") (156 156 156 "gray61") (156 156 156 "grey61") (158 158 158 "gray62") (158 158 158 "grey62") (161 161 161 "gray63") (161 161 161 "grey63") (163 163 163 "gray64") (163 163 163 "grey64") (166 166 166 "gray65") (166 166 166 "grey65") (168 168 168 "gray66") (168 168 168 "grey66") (171 171 171 "gray67") (171 171 171 "grey67") (173 173 173 "gray68") (173 173 173 "grey68") (176 176 176 "gray69") (176 176 176 "grey69") (179 179 179 "gray70") (179 179 179 "grey70") (181 181 181 "gray71") (181 181 181 "grey71") (184 184 184 "gray72") (184 184 184 "grey72") (186 186 186 "gray73") (186 186 186 "grey73") (189 189 189 "gray74") (189 189 189 "grey74") (191 191 191 "gray75") (191 191 191 "grey75") (194 194 194 "gray76") (194 194 194 "grey76") (196 196 196 "gray77") (196 196 196 "grey77") (199 199 199 "gray78") (199 199 199 "grey78") (201 201 201 "gray79") (201 201 201 "grey79") (204 204 204 "gray80") (204 204 204 "grey80") (207 207 207 "gray81") (207 207 207 "grey81") (209 209 209 "gray82") (209 209 209 "grey82") (212 212 212 "gray83") (212 212 212 "grey83") (214 214 214 "gray84") (214 214 214 "grey84") (217 217 217 "gray85") (217 217 217 "grey85") (219 219 219 "gray86") (219 219 219 "grey86") (222 222 222 "gray87") (222 222 222 "grey87") (224 224 224 "gray88") (224 224 224 "grey88") (227 227 227 "gray89") (227 227 227 "grey89") (229 229 229 "gray90") (229 229 229 "grey90") (232 232 232 "gray91") (232 232 232 "grey91") (235 235 235 "gray92") (235 235 235 "grey92") (237 237 237 "gray93") (237 237 237 "grey93") (240 240 240 "gray94") (240 240 240 "grey94") (242 242 242 "gray95") (242 242 242 "grey95") (245 245 245 "gray96") (245 245 245 "grey96") (247 247 247 "gray97") (247 247 247 "grey97") (250 250 250 "gray98") (250 250 250 "grey98") (252 252 252 "gray99") (252 252 252 "grey99") (255 255 255 "gray100") (255 255 255 "grey100") (169 169 169 "dark grey") (169 169 169 "DarkGrey") (169 169 169 "dark gray") (169 169 169 "DarkGray") (0 0 139 "dark blue") (0 0 139 "DarkBlue") (0 139 139 "dark cyan") (0 139 139 "DarkCyan") (139 0 139 "dark magenta") (139 0 139 "DarkMagenta") (139 0 0 "dark red") (139 0 0 "DarkRed") (144 238 144 "light green") (144 238 144 "LightGreen"))) (defun xpm-find-named-color (name) (if (string-equal name "None") clim:+transparent-ink+ (let ((q (find name *xpm-x11-colors* :key #'fourth :test #'string-equal))) (and q (clim:make-rgb-color (/ (first q) 255) (/ (second q) 255) (/ (third q) 255))))))
e28040da90f3239a1bf1f6dd65846f32250ce8c0b44e00980c8ef9a84d7a295c
jordanthayer/ocaml-search
one_offs.ml
* @author jtd7 @since 2010 - 06 - 28 Some once off scripts that will be nice to have around @author jtd7 @since 2010-06-28 Some once off scripts that will be nice to have around *) let array_to_point_arrays ar = Array.init (Array.length ar) (fun i -> Geometry.point_of_array [| float_of_int i; ar.(i);|]) let get_window_series ?(ykey = "iteration") dset = dset is now a list on inst Array.of_list (List.map (fun ds -> (array_to_point_arrays (Dataset.get_column_vector float_of_string [| ykey |] ds).(0))) dset) let arrays_collection_to_linerr ~names arrays = let next_color = Dataset_to_spt.make_color_factory true and next_dash = Factories.make_dash_factory [|[||]|] () in let next_style = (Dataset_to_spt.make_or_use_line_err_factory next_dash None) in List.map2 (fun name l -> Num_by_num.line_errbar_dataset (next_style ()) ~line_width:(Length.Pt 2.) ?color:(Some (next_color ())) ~name l) names arrays let grids algs = let data = List.map (fun (dsnm,plnm,yk) -> get_window_series ~ykey:yk ((Jtd7_helpers.load_wrap Load_dataset.standard_unit_4_grids) (dsnm,plnm,[]))) algs in let dset = arrays_collection_to_linerr ~names:(List.map (fun (a,b,c) -> b) algs) data in let plot = (Num_by_num.plot ~legend_loc:Legend.Upper_left ~title:"Grid Problem" ~xlabel:"Iteration" ~ylabel:"Window Size" dset) in plot#display EOF
null
https://raw.githubusercontent.com/jordanthayer/ocaml-search/57cfc85417aa97ee5d8fbcdb84c333aae148175f/spt_plot/scripts/jtd7/one_offs.ml
ocaml
* @author jtd7 @since 2010 - 06 - 28 Some once off scripts that will be nice to have around @author jtd7 @since 2010-06-28 Some once off scripts that will be nice to have around *) let array_to_point_arrays ar = Array.init (Array.length ar) (fun i -> Geometry.point_of_array [| float_of_int i; ar.(i);|]) let get_window_series ?(ykey = "iteration") dset = dset is now a list on inst Array.of_list (List.map (fun ds -> (array_to_point_arrays (Dataset.get_column_vector float_of_string [| ykey |] ds).(0))) dset) let arrays_collection_to_linerr ~names arrays = let next_color = Dataset_to_spt.make_color_factory true and next_dash = Factories.make_dash_factory [|[||]|] () in let next_style = (Dataset_to_spt.make_or_use_line_err_factory next_dash None) in List.map2 (fun name l -> Num_by_num.line_errbar_dataset (next_style ()) ~line_width:(Length.Pt 2.) ?color:(Some (next_color ())) ~name l) names arrays let grids algs = let data = List.map (fun (dsnm,plnm,yk) -> get_window_series ~ykey:yk ((Jtd7_helpers.load_wrap Load_dataset.standard_unit_4_grids) (dsnm,plnm,[]))) algs in let dset = arrays_collection_to_linerr ~names:(List.map (fun (a,b,c) -> b) algs) data in let plot = (Num_by_num.plot ~legend_loc:Legend.Upper_left ~title:"Grid Problem" ~xlabel:"Iteration" ~ylabel:"Window Size" dset) in plot#display EOF
43a618e73f03ead153c2f2b9948c5a69e28a688c8eeb934966dad500f2a0481a
LPCIC/matita
print_grammar.mli
Copyright ( C ) 2005 , HELM Team . * * This file is part of HELM , an Hypertextual , Electronic * Library of Mathematics , developed at the Computer Science * Department , University of Bologna , Italy . * * is free software ; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation ; either version 2 * of the License , or ( at your option ) any later version . * * is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License * along with HELM ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , * MA 02111 - 1307 , USA . * * For details , see the HELM World - Wide - Web page , * / * * This file is part of HELM, an Hypertextual, Electronic * Library of Mathematics, developed at the Computer Science * Department, University of Bologna, Italy. * * HELM 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. * * HELM 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 HELM; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. * * For details, see the HELM World-Wide-Web page, * / *) (* $Id: print_grammar.ml 6977 2006-10-25 12:41:21Z sacerdot $ *) val ebnf_of_term: #GrafiteParser.status -> string
null
https://raw.githubusercontent.com/LPCIC/matita/794ed25e6e608b2136ce7fa2963bca4115c7e175/matita/components/grafite_parser/print_grammar.mli
ocaml
$Id: print_grammar.ml 6977 2006-10-25 12:41:21Z sacerdot $
Copyright ( C ) 2005 , HELM Team . * * This file is part of HELM , an Hypertextual , Electronic * Library of Mathematics , developed at the Computer Science * Department , University of Bologna , Italy . * * is free software ; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation ; either version 2 * of the License , or ( at your option ) any later version . * * is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License * along with HELM ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , * MA 02111 - 1307 , USA . * * For details , see the HELM World - Wide - Web page , * / * * This file is part of HELM, an Hypertextual, Electronic * Library of Mathematics, developed at the Computer Science * Department, University of Bologna, Italy. * * HELM 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. * * HELM 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 HELM; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. * * For details, see the HELM World-Wide-Web page, * / *) val ebnf_of_term: #GrafiteParser.status -> string
dbe82a55b1019274bffa3da0d7500012d2f03d39a0c1304233f0b7fda562a445
timgilbert/haunting-refrain-posh
spotify.cljs
(ns haunting-refrain.fx.spotify (:require [re-frame.core :refer [reg-event-fx reg-event-db]] [haunting-refrain.datascript.spotify :as sp] [cemerick.url :as url] [shodan.console :as console])) ;; -api/search-item/ (defn- spotify-search-url "Return the route to a foursquare API endpoint" [search & [search-type]] (let [base (url/url "") full (assoc base :query {:q search :type (or search-type "track")})] (str full))) (defn search-by-track "Persist an object into localStorage at the given key." [_ [_ track]] {:dispatch [:http/request {:method :get :endpoint :spotify/search-by-track :url (spotify-search-url (-> track :track/seed :seed/datum)) :on-success [:spotify/search-success track] :on-failure [:spotify/search-failure track]}]}) (reg-event-fx :spotify/search-by-track search-by-track) (reg-event-db :spotify/search-failure (fn [db [_ seed body status]] (console/warn "Oh noes! Spotify search for" (:seed/datum seed) " returned " status ", body:" body) db)) (reg-event-fx :spotify/search-success (fn [{:keys [db]} [_ track body]] (console/log "Search for" (-> track :track/seed :seed/datum) "found" (get-in body [:tracks :total]) "tracks!") (sp/parse-songs! (:ds/conn db) (:track/seed track) body) (sp/select-random-song! (:ds/conn db) track) {:db db}))
null
https://raw.githubusercontent.com/timgilbert/haunting-refrain-posh/99a7daafe54c5905a3d1b0eff691b5c602ad6d8d/src/cljs/haunting_refrain/fx/spotify.cljs
clojure
-api/search-item/
(ns haunting-refrain.fx.spotify (:require [re-frame.core :refer [reg-event-fx reg-event-db]] [haunting-refrain.datascript.spotify :as sp] [cemerick.url :as url] [shodan.console :as console])) (defn- spotify-search-url "Return the route to a foursquare API endpoint" [search & [search-type]] (let [base (url/url "") full (assoc base :query {:q search :type (or search-type "track")})] (str full))) (defn search-by-track "Persist an object into localStorage at the given key." [_ [_ track]] {:dispatch [:http/request {:method :get :endpoint :spotify/search-by-track :url (spotify-search-url (-> track :track/seed :seed/datum)) :on-success [:spotify/search-success track] :on-failure [:spotify/search-failure track]}]}) (reg-event-fx :spotify/search-by-track search-by-track) (reg-event-db :spotify/search-failure (fn [db [_ seed body status]] (console/warn "Oh noes! Spotify search for" (:seed/datum seed) " returned " status ", body:" body) db)) (reg-event-fx :spotify/search-success (fn [{:keys [db]} [_ track body]] (console/log "Search for" (-> track :track/seed :seed/datum) "found" (get-in body [:tracks :total]) "tracks!") (sp/parse-songs! (:ds/conn db) (:track/seed track) body) (sp/select-random-song! (:ds/conn db) track) {:db db}))
6e46d8a69abe9aa85db3cedad7dc23f80caeb39460b27844a31ed6ee550c9c8d
kepler16/next.cljs
app.cljs
(ns example.app (:require ["react" :as r])) (defn ^:export init [] (js/console.log "sdf"))
null
https://raw.githubusercontent.com/kepler16/next.cljs/93ba1a1e759eedc4fd98adc5b59d055f07ee3c5d/example/src/example/app.cljs
clojure
(ns example.app (:require ["react" :as r])) (defn ^:export init [] (js/console.log "sdf"))
bd71229728177a67581ea844dcc0de0f732d340d782daa128bc652c15a0c4b1c
marigold-dev/deku
eval.ml
open Values open Types open Instance open Ast open Source (* Errors *) module Link = Error.Make () module Trap = Error.Make () module Crash = Error.Make () module Exhaustion = Error.Make () exception Link = Link.Error exception Trap = Trap.Error exception Crash = Crash.Error (* failure that cannot happen in valid code *) exception Exhaustion = Exhaustion.Error let table_error at = function | Table.Bounds -> "out of bounds table access" | Table.SizeOverflow -> "table size overflow" | Table.SizeLimit -> "table size limit reached" | Table.Type -> Crash.error at "type mismatch at table access" | exn -> raise exn let memory_error at = function | Memory.Bounds -> "out of bounds memory access" | Memory.SizeOverflow -> "memory size overflow" | Memory.SizeLimit -> "memory size limit reached" | Memory.Type -> Crash.error at "type mismatch at memory access" | exn -> raise exn let numeric_error at = function | Ixx.Overflow -> "integer overflow" | Ixx.DivideByZero -> "integer divide by zero" | Ixx.InvalidConversion -> "invalid conversion to integer" | Values.TypeError (i, v, t) -> Crash.error at ("type error, expected " ^ Types.string_of_num_type t ^ " as operand " ^ string_of_int i ^ ", got " ^ Types.string_of_num_type (type_of_num v)) | exn -> raise exn Administrative Expressions & Configurations type 'a stack = 'a list type frame = { inst : module_inst; locals : value ref list } type code = value stack * admin_instr list and admin_instr = admin_instr' phrase and admin_instr' = | Plain of instr' | Refer of ref_ | Invoke of func_inst | Trapping of string | Returning of value stack | Breaking of int32 * value stack | Label of int32 * instr list * code | Frame of int32 * frame * code type config = { frame : frame; code : code; budget : int; (* to model stack overflow *) } let frame inst locals = { inst; locals } let config inst vs es = { frame = frame inst []; code = (vs, es); budget = 300 } let plain e = Plain e.it @@ e.at let lookup category list x = try Lib.List32.nth list x.it with Failure _ -> Crash.error x.at ("undefined " ^ category ^ " " ^ Int32.to_string x.it) let type_ (inst : module_inst) x = lookup "type" inst.types x let func (inst : module_inst) x = lookup "function" inst.funcs x let table (inst : module_inst) x = lookup "table" inst.tables x let memory (inst : module_inst) x = lookup "memory" inst.memories x let global (inst : module_inst) x = lookup "global" inst.globals x let elem (inst : module_inst) x = lookup "element segment" inst.elems x let data (inst : module_inst) x = lookup "data segment" inst.datas x let local (frame : frame) x = lookup "local" frame.locals x let inst frame = frame.inst let any_ref inst x i at = try Table.load (table inst x) i with Table.Bounds -> Trap.error at ("undefined element " ^ Int32.to_string i) let func_ref inst x i at = match any_ref inst x i at with | FuncRef f -> f | NullRef _ -> Trap.error at ("uninitialized element " ^ Int32.to_string i) | _ -> Crash.error at ("type mismatch for element " ^ Int32.to_string i) let func_type_of = function | Func.AstFunc (t, inst, f) -> t | Func.HostFunc (t, _) -> t let block_type inst bt = match bt with | VarBlockType x -> type_ inst x | ValBlockType None -> FuncType ([], []) | ValBlockType (Some t) -> FuncType ([], [ t ]) let take n (vs : 'a stack) at = try Lib.List32.take n vs with Failure _ -> Crash.error at "stack underflow" let drop n (vs : 'a stack) at = try Lib.List32.drop n vs with Failure _ -> Crash.error at "stack underflow" (* Evaluation *) (* * Conventions: * e : instr * v : value * es : instr list * vs : value stack * c : config *) let mem_oob frame x i n = I64.gt_u (I64.add (I64_convert.extend_i32_u i) (I64_convert.extend_i32_u n)) (Memory.bound (memory frame.inst x)) let data_oob frame x i n = I64.gt_u (I64.add (I64_convert.extend_i32_u i) (I64_convert.extend_i32_u n)) (I64.of_int_u (String.length !(data frame.inst x))) let table_oob frame x i n = I64.gt_u (I64.add (I64_convert.extend_i32_u i) (I64_convert.extend_i32_u n)) (I64_convert.extend_i32_u (Table.size (table frame.inst x))) let elem_oob frame x i n = I64.gt_u (I64.add (I64_convert.extend_i32_u i) (I64_convert.extend_i32_u n)) (I64.of_int_u (List.length !(elem frame.inst x))) let rec step (c : config) : config = let { frame; code = vs, es; _ } = c in Instance.burn_gas (inst frame) 100L; let e = List.hd es in let vs', es' = match (e.it, vs) with | Plain e', vs -> ( match (e', vs) with | Unreachable, vs -> (vs, [ Trapping "unreachable executed" @@ e.at ]) | Nop, vs -> (vs, []) | Block (bt, es'), vs -> let (FuncType (ts1, ts2)) = block_type frame.inst bt in let n1 = Lib.List32.length ts1 in let n2 = Lib.List32.length ts2 in let args, vs' = (take n1 vs e.at, drop n1 vs e.at) in (vs', [ Label (n2, [], (args, List.map plain es')) @@ e.at ]) | Loop (bt, es'), vs -> let (FuncType (ts1, ts2)) = block_type frame.inst bt in let n1 = Lib.List32.length ts1 in let args, vs' = (take n1 vs e.at, drop n1 vs e.at) in ( vs', [ Label (n1, [ e' @@ e.at ], (args, List.map plain es')) @@ e.at ] ) | If (bt, es1, es2), Num (I32 i) :: vs' -> if i = 0l then (vs', [ Plain (Block (bt, es2)) @@ e.at ]) else (vs', [ Plain (Block (bt, es1)) @@ e.at ]) | Br x, vs -> ([], [ Breaking (x.it, vs) @@ e.at ]) | BrIf x, Num (I32 i) :: vs' -> if i = 0l then (vs', []) else (vs', [ Plain (Br x) @@ e.at ]) | BrTable (xs, x), Num (I32 i) :: vs' -> if I32.ge_u i (Lib.List32.length xs) then (vs', [ Plain (Br x) @@ e.at ]) else (vs', [ Plain (Br (Lib.List32.nth xs i)) @@ e.at ]) | Return, vs -> ([], [ Returning vs @@ e.at ]) | Call x, vs -> (vs, [ Invoke (func frame.inst x) @@ e.at ]) | CallIndirect (x, y), Num (I32 i) :: vs -> let func = func_ref frame.inst x i e.at in if type_ frame.inst y <> Func.type_of func then (vs, [ Trapping "indirect call type mismatch" @@ e.at ]) else (vs, [ Invoke func @@ e.at ]) | Drop, v :: vs' -> (vs', []) | Select _, Num (I32 i) :: v2 :: v1 :: vs' -> if i = 0l then (v2 :: vs', []) else (v1 :: vs', []) | LocalGet x, vs -> (!(local frame x) :: vs, []) | LocalSet x, v :: vs' -> local frame x := v; (vs', []) | LocalTee x, v :: vs' -> local frame x := v; (v :: vs', []) | GlobalGet x, vs -> (Global.load (global frame.inst x) :: vs, []) | GlobalSet x, v :: vs' -> ( try Global.store (global frame.inst x) v; (vs', []) with | Global.NotMutable -> Crash.error e.at "write to immutable global" | Global.Type -> Crash.error e.at "type mismatch at global write") | TableGet x, Num (I32 i) :: vs' -> ( try (Ref (Table.load (table frame.inst x) i) :: vs', []) with exn -> (vs', [ Trapping (table_error e.at exn) @@ e.at ])) | TableSet x, Ref r :: Num (I32 i) :: vs' -> ( try Table.store (table frame.inst x) i r; (vs', []) with exn -> (vs', [ Trapping (table_error e.at exn) @@ e.at ])) | TableSize x, vs -> (Num (I32 (Table.size (table frame.inst x))) :: vs, []) | TableGrow x, Num (I32 delta) :: Ref r :: vs' -> let tab = table frame.inst x in let old_size = Table.size tab in let result = try Table.grow tab delta r; old_size with Table.SizeOverflow | Table.SizeLimit | Table.OutOfMemory -> -1l in (Num (I32 result) :: vs', []) | TableFill x, Num (I32 n) :: Ref r :: Num (I32 i) :: vs' -> if table_oob frame x i n then (vs', [ Trapping (table_error e.at Table.Bounds) @@ e.at ]) else if n = 0l then (vs', []) else let _ = assert (I32.lt_u i 0xffff_ffffl) in ( vs', List.map (at e.at) [ Plain (Const (I32 i @@ e.at)); Refer r; Plain (TableSet x); Plain (Const (I32 (I32.add i 1l) @@ e.at)); Refer r; Plain (Const (I32 (I32.sub n 1l) @@ e.at)); Plain (TableFill x); ] ) | TableCopy (x, y), Num (I32 n) :: Num (I32 s) :: Num (I32 d) :: vs' -> if table_oob frame x d n || table_oob frame y s n then (vs', [ Trapping (table_error e.at Table.Bounds) @@ e.at ]) else if n = 0l then (vs', []) else if I32.le_u d s then ( vs', List.map (at e.at) [ Plain (Const (I32 d @@ e.at)); Plain (Const (I32 s @@ e.at)); Plain (TableGet y); Plain (TableSet x); Plain (Const (I32 (I32.add d 1l) @@ e.at)); Plain (Const (I32 (I32.add s 1l) @@ e.at)); Plain (Const (I32 (I32.sub n 1l) @@ e.at)); Plain (TableCopy (x, y)); ] ) else (* d > s *) ( vs', List.map (at e.at) [ Plain (Const (I32 (I32.add d 1l) @@ e.at)); Plain (Const (I32 (I32.add s 1l) @@ e.at)); Plain (Const (I32 (I32.sub n 1l) @@ e.at)); Plain (TableCopy (x, y)); Plain (Const (I32 d @@ e.at)); Plain (Const (I32 s @@ e.at)); Plain (TableGet y); Plain (TableSet x); ] ) | TableInit (x, y), Num (I32 n) :: Num (I32 s) :: Num (I32 d) :: vs' -> if table_oob frame x d n || elem_oob frame y s n then (vs', [ Trapping (table_error e.at Table.Bounds) @@ e.at ]) else if n = 0l then (vs', []) else let seg = !(elem frame.inst y) in ( vs', List.map (at e.at) [ Plain (Const (I32 d @@ e.at)); Refer (List.nth seg (Int32.to_int s)); Plain (TableSet x); Plain (Const (I32 (I32.add d 1l) @@ e.at)); Plain (Const (I32 (I32.add s 1l) @@ e.at)); Plain (Const (I32 (I32.sub n 1l) @@ e.at)); Plain (TableInit (x, y)); ] ) | ElemDrop x, vs -> let seg = elem frame.inst x in seg := []; (vs, []) | Load { offset; ty; pack; _ }, Num (I32 i) :: vs' -> ( let mem = memory frame.inst (0l @@ e.at) in let a = I64_convert.extend_i32_u i in try let n = match pack with | None -> Memory.load_num mem a offset ty | Some (sz, ext) -> Memory.load_num_packed sz ext mem a offset ty in (Num n :: vs', []) with exn -> (vs', [ Trapping (memory_error e.at exn) @@ e.at ])) | Store { offset; pack; _ }, Num n :: Num (I32 i) :: vs' -> ( let mem = memory frame.inst (0l @@ e.at) in let a = I64_convert.extend_i32_u i in try (match pack with | None -> Memory.store_num mem a offset n | Some sz -> Memory.store_num_packed sz mem a offset n); (vs', []) with exn -> (vs', [ Trapping (memory_error e.at exn) @@ e.at ])) | VecLoad { offset; ty; pack; _ }, Num (I32 i) :: vs' -> ( let mem = memory frame.inst (0l @@ e.at) in let addr = I64_convert.extend_i32_u i in try let v = match pack with | None -> Memory.load_vec mem addr offset ty | Some (sz, ext) -> Memory.load_vec_packed sz ext mem addr offset ty in (Vec v :: vs', []) with exn -> (vs', [ Trapping (memory_error e.at exn) @@ e.at ])) | VecStore { offset; _ }, Vec v :: Num (I32 i) :: vs' -> ( let mem = memory frame.inst (0l @@ e.at) in let addr = I64_convert.extend_i32_u i in try Memory.store_vec mem addr offset v; (vs', []) with exn -> (vs', [ Trapping (memory_error e.at exn) @@ e.at ])) | ( VecLoadLane ({ offset; ty; pack; _ }, j), Vec (V128 v) :: Num (I32 i) :: vs' ) -> ( let mem = memory frame.inst (0l @@ e.at) in let addr = I64_convert.extend_i32_u i in try let v = match pack with | Pack8 -> V128.I8x16.replace_lane j v (I32Num.of_num 0 (Memory.load_num_packed Pack8 SX mem addr offset I32Type)) | Pack16 -> V128.I16x8.replace_lane j v (I32Num.of_num 0 (Memory.load_num_packed Pack16 SX mem addr offset I32Type)) | Pack32 -> V128.I32x4.replace_lane j v (I32Num.of_num 0 (Memory.load_num mem addr offset I32Type)) | Pack64 -> V128.I64x2.replace_lane j v (I64Num.of_num 0 (Memory.load_num mem addr offset I64Type)) in (Vec (V128 v) :: vs', []) with exn -> (vs', [ Trapping (memory_error e.at exn) @@ e.at ])) | ( VecStoreLane ({ offset; ty; pack; _ }, j), Vec (V128 v) :: Num (I32 i) :: vs' ) -> ( let mem = memory frame.inst (0l @@ e.at) in let addr = I64_convert.extend_i32_u i in try (match pack with | Pack8 -> Memory.store_num_packed Pack8 mem addr offset (I32 (V128.I8x16.extract_lane_s j v)) | Pack16 -> Memory.store_num_packed Pack16 mem addr offset (I32 (V128.I16x8.extract_lane_s j v)) | Pack32 -> Memory.store_num mem addr offset (I32 (V128.I32x4.extract_lane_s j v)) | Pack64 -> Memory.store_num mem addr offset (I64 (V128.I64x2.extract_lane_s j v))); (vs', []) with exn -> (vs', [ Trapping (memory_error e.at exn) @@ e.at ])) | MemorySize, vs -> let mem = memory frame.inst (0l @@ e.at) in (Num (I32 (Memory.size mem)) :: vs, []) | MemoryGrow, Num (I32 delta) :: vs' -> let mem = memory frame.inst (0l @@ e.at) in let old_size = Memory.size mem in let result = try Memory.grow mem delta; old_size with | Memory.SizeOverflow | Memory.SizeLimit | Memory.OutOfMemory -> -1l in (Num (I32 result) :: vs', []) | MemoryFill, Num (I32 n) :: Num k :: Num (I32 i) :: vs' -> if mem_oob frame (0l @@ e.at) i n then (vs', [ Trapping (memory_error e.at Memory.Bounds) @@ e.at ]) else if n = 0l then (vs', []) else ( vs', List.map (at e.at) [ Plain (Const (I32 i @@ e.at)); Plain (Const (k @@ e.at)); Plain (Store { ty = I32Type; align = 0; offset = 0l; pack = Some Pack8; }); Plain (Const (I32 (I32.add i 1l) @@ e.at)); Plain (Const (k @@ e.at)); Plain (Const (I32 (I32.sub n 1l) @@ e.at)); Plain MemoryFill; ] ) | MemoryCopy, Num (I32 n) :: Num (I32 s) :: Num (I32 d) :: vs' -> if mem_oob frame (0l @@ e.at) s n || mem_oob frame (0l @@ e.at) d n then (vs', [ Trapping (memory_error e.at Memory.Bounds) @@ e.at ]) else if n = 0l then (vs', []) else if I32.le_u d s then ( vs', List.map (at e.at) [ Plain (Const (I32 d @@ e.at)); Plain (Const (I32 s @@ e.at)); Plain (Load { ty = I32Type; align = 0; offset = 0l; pack = Some (Pack8, ZX); }); Plain (Store { ty = I32Type; align = 0; offset = 0l; pack = Some Pack8; }); Plain (Const (I32 (I32.add d 1l) @@ e.at)); Plain (Const (I32 (I32.add s 1l) @@ e.at)); Plain (Const (I32 (I32.sub n 1l) @@ e.at)); Plain MemoryCopy; ] ) else (* d > s *) ( vs', List.map (at e.at) [ Plain (Const (I32 (I32.add d 1l) @@ e.at)); Plain (Const (I32 (I32.add s 1l) @@ e.at)); Plain (Const (I32 (I32.sub n 1l) @@ e.at)); Plain MemoryCopy; Plain (Const (I32 d @@ e.at)); Plain (Const (I32 s @@ e.at)); Plain (Load { ty = I32Type; align = 0; offset = 0l; pack = Some (Pack8, ZX); }); Plain (Store { ty = I32Type; align = 0; offset = 0l; pack = Some Pack8; }); ] ) | MemoryInit x, Num (I32 n) :: Num (I32 s) :: Num (I32 d) :: vs' -> if mem_oob frame (0l @@ e.at) d n || data_oob frame x s n then (vs', [ Trapping (memory_error e.at Memory.Bounds) @@ e.at ]) else if n = 0l then (vs', []) else let seg = !(data frame.inst x) in let b = Int32.of_int (Char.code seg.[Int32.to_int s]) in ( vs', List.map (at e.at) [ Plain (Const (I32 d @@ e.at)); Plain (Const (I32 b @@ e.at)); Plain (Store { ty = I32Type; align = 0; offset = 0l; pack = Some Pack8; }); Plain (Const (I32 (I32.add d 1l) @@ e.at)); Plain (Const (I32 (I32.add s 1l) @@ e.at)); Plain (Const (I32 (I32.sub n 1l) @@ e.at)); Plain (MemoryInit x); ] ) | DataDrop x, vs -> let seg = data frame.inst x in seg := ""; (vs, []) | RefNull t, vs' -> (Ref (NullRef t) :: vs', []) | RefIsNull, Ref r :: vs' -> ( match r with | NullRef _ -> (Num (I32 1l) :: vs', []) | _ -> (Num (I32 0l) :: vs', [])) | RefFunc x, vs' -> let f = func frame.inst x in (Ref (FuncRef f) :: vs', []) | Const n, vs -> (Num n.it :: vs, []) | Test testop, Num n :: vs' -> ( try (value_of_bool (Eval_num.eval_testop testop n) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | Compare relop, Num n2 :: Num n1 :: vs' -> ( try (value_of_bool (Eval_num.eval_relop relop n1 n2) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | Unary unop, Num n :: vs' -> ( try (Num (Eval_num.eval_unop unop n) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | Binary binop, Num n2 :: Num n1 :: vs' -> ( try (Num (Eval_num.eval_binop binop n1 n2) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | Convert cvtop, Num n :: vs' -> ( try (Num (Eval_num.eval_cvtop cvtop n) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecConst v, vs -> (Vec v.it :: vs, []) | VecTest testop, Vec n :: vs' -> ( try (value_of_bool (Eval_vec.eval_testop testop n) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecUnary unop, Vec n :: vs' -> ( try (Vec (Eval_vec.eval_unop unop n) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecBinary binop, Vec n2 :: Vec n1 :: vs' -> ( try (Vec (Eval_vec.eval_binop binop n1 n2) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecCompare relop, Vec n2 :: Vec n1 :: vs' -> ( try (Vec (Eval_vec.eval_relop relop n1 n2) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecConvert cvtop, Vec n :: vs' -> ( try (Vec (Eval_vec.eval_cvtop cvtop n) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecShift shiftop, Num s :: Vec v :: vs' -> ( try (Vec (Eval_vec.eval_shiftop shiftop v s) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecBitmask bitmaskop, Vec v :: vs' -> ( try (Num (Eval_vec.eval_bitmaskop bitmaskop v) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecTestBits vtestop, Vec n :: vs' -> ( try (value_of_bool (Eval_vec.eval_vtestop vtestop n) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecUnaryBits vunop, Vec n :: vs' -> ( try (Vec (Eval_vec.eval_vunop vunop n) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecBinaryBits vbinop, Vec n2 :: Vec n1 :: vs' -> ( try (Vec (Eval_vec.eval_vbinop vbinop n1 n2) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecTernaryBits vternop, Vec v3 :: Vec v2 :: Vec v1 :: vs' -> ( try (Vec (Eval_vec.eval_vternop vternop v1 v2 v3) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecSplat splatop, Num n :: vs' -> ( try (Vec (Eval_vec.eval_splatop splatop n) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecExtract extractop, Vec v :: vs' -> ( try (Num (Eval_vec.eval_extractop extractop v) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecReplace replaceop, Num r :: Vec v :: vs' -> ( try (Vec (Eval_vec.eval_replaceop replaceop v r) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | _ -> let s1 = string_of_values (List.rev vs) in let s2 = string_of_value_types (List.map type_of_value (List.rev vs)) in Crash.error e.at ("missing or ill-typed operand on stack (" ^ s1 ^ " : " ^ s2 ^ ")") ) | Refer r, vs -> (Ref r :: vs, []) | Trapping msg, vs -> assert false | Returning vs', vs -> Crash.error e.at "undefined frame" | Breaking (k, vs'), vs -> Crash.error e.at "undefined label" | Label (n, es0, (vs', [])), vs -> (vs' @ vs, []) | Label (n, es0, (vs', { it = Trapping msg; at } :: es')), vs -> (vs, [ Trapping msg @@ at ]) | Label (n, es0, (vs', { it = Returning vs0; at } :: es')), vs -> (vs, [ Returning vs0 @@ at ]) | Label (n, es0, (vs', { it = Breaking (0l, vs0); at } :: es')), vs -> (take n vs0 e.at @ vs, List.map plain es0) | Label (n, es0, (vs', { it = Breaking (k, vs0); at } :: es')), vs -> (vs, [ Breaking (Int32.sub k 1l, vs0) @@ at ]) | Label (n, es0, code'), vs -> let c' = step { c with code = code' } in (vs, [ Label (n, es0, c'.code) @@ e.at ]) | Frame (n, frame', (vs', [])), vs -> (vs' @ vs, []) | Frame (n, frame', (vs', { it = Trapping msg; at } :: es')), vs -> (vs, [ Trapping msg @@ at ]) | Frame (n, frame', (vs', { it = Returning vs0; at } :: es')), vs -> (take n vs0 e.at @ vs, []) | Frame (n, frame', code'), vs -> let c' = step { frame = frame'; code = code'; budget = c.budget - 1 } in (vs, [ Frame (n, c'.frame, c'.code) @@ e.at ]) | Invoke func, vs when c.budget = 0 -> Exhaustion.error e.at "call stack exhausted" | Invoke func, vs -> ( let (FuncType (ins, out)) = func_type_of func in let n1, n2 = (Lib.List32.length ins, Lib.List32.length out) in let args, vs' = (take n1 vs e.at, drop n1 vs e.at) in match func with | Func.AstFunc (t, inst', f) -> let locals' = List.rev args @ List.map default_value f.it.locals in let frame' = { inst = !inst'; locals = List.map ref locals' } in let instr' = [ Label (n2, [], ([], List.map plain f.it.body)) @@ f.at ] in (vs', [ Frame (n2, frame', ([], instr')) @@ e.at ]) | Func.HostFunc (t, f) -> ( try (List.rev (f (ref (inst frame)) (List.rev args)) @ vs', []) with Crash (_, msg) -> Crash.error e.at msg)) in { c with code = (vs', es' @ List.tl es) } let rec eval (c : config) : value stack = match c.code with | vs, [] -> vs | vs, { it = Trapping msg; at } :: _ -> Trap.error at msg | vs, es -> eval (step c) (* Functions & Constants *) let invoke (func : func_inst) (vs : value list) : value list = let at = match func with Func.AstFunc (_, inst, f) -> f.at | _ -> no_region in let gas = match func with | Func.AstFunc (_, inst, _) -> Instance.get_gas_limit !inst | _ -> Int64.max_int in let (FuncType (ins, out)) = Func.type_of func in if List.length vs <> List.length ins then Crash.error at "wrong number of arguments"; if not (List.for_all2 (fun v -> ( = ) (type_of_value v)) vs ins) then Crash.error at "wrong types of arguments"; let c = config { empty_module_inst with gas_limit = gas } (List.rev vs) [ Invoke func @@ at ] in try List.rev (eval c) with Stack_overflow -> Exhaustion.error at "call stack exhausted" let eval_const (inst : module_inst) (const : const) : value = let c = config inst [] (List.map plain const.it) in match eval c with | [ v ] -> v | vs -> Crash.error const.at "wrong number of results on stack" (* Modules *) let create_func (inst : module_inst) (f : func) : func_inst = Func.alloc (type_ inst f.it.ftype) (ref inst) f let create_table (inst : module_inst) (tab : table) : table_inst = let { ttype } = tab.it in let (TableType (_lim, t)) = ttype in Table.alloc ttype (NullRef t) let create_memory (inst : module_inst) (mem : memory) : memory_inst = let { mtype } = mem.it in Memory.alloc mtype let create_global (inst : module_inst) (glob : global) : global_inst = let { gtype; ginit } = glob.it in let v = eval_const inst ginit in Global.alloc gtype v let create_export (inst : module_inst) (ex : export) : export_inst = let { name; edesc } = ex.it in let ext = match edesc.it with | FuncExport x -> ExternFunc (func inst x) | TableExport x -> ExternTable (table inst x) | MemoryExport x -> ExternMemory (memory inst x) | GlobalExport x -> ExternGlobal (global inst x) in (name, ext) let create_elem (inst : module_inst) (seg : elem_segment) : elem_inst = let { etype; einit; _ } = seg.it in ref (List.map (fun c -> as_ref (eval_const inst c)) einit) let create_data (inst : module_inst) (seg : data_segment) : data_inst = let { dinit; _ } = seg.it in ref dinit module State = struct module Indexed = Map.Make (Int) type _ kind = | Table : table_inst -> table_inst kind | Func : func_inst -> func_inst kind | Memory : memory_inst -> memory_inst kind | Global : global_inst -> global_inst kind type t = { mutable funcs : func_inst Indexed.t; mutable tables : table_inst Indexed.t; mutable memories : memory_inst Indexed.t; mutable globals : global_inst Indexed.t; } let empty = { funcs = Indexed.empty; tables = Indexed.empty; memories = Indexed.empty; globals = Indexed.empty; } let add (type a) (t : t) idx (kind : a kind) = match kind with | Table x -> t.tables <- Indexed.add idx x t.tables | Func x -> t.funcs <- Indexed.add idx x t.funcs | Memory x -> t.memories <- Indexed.add idx x t.memories | Global x -> t.globals <- Indexed.add idx x t.globals let finalize ({ tables; memories; funcs; globals } : t) = let final x = Indexed.to_seq x |> Seq.map snd |> List.of_seq in (final tables, final memories, final funcs, final globals) end module Name_map = Map.Make (Utf8) let add_imports (m : module_) (exts : (Utf8.t * extern) list) (im : import list) (inst : module_inst) : module_inst = let named_map = Name_map.of_seq (List.to_seq im |> Seq.mapi (fun idx ({ it = x; at = _ } as y) -> (x.item_name, (y, idx))) ) in let state = State.empty in let () = List.iter (fun (ext_name, ext) -> let item = Name_map.find_opt ext_name named_map in let im, idx = match item with | Some x -> x | None -> Link.error Source.no_region (Format.sprintf "Redundant host function provided: %s\n" (Utf8.encode ext_name)) in if not (match_extern_type (extern_type_of ext) (import_type m im)) then Link.error im.at ("incompatible import type for " ^ "\"" ^ Utf8.encode im.it.module_name ^ "\" " ^ "\"" ^ Utf8.encode im.it.item_name ^ "\": " ^ "expected " ^ Types.string_of_extern_type (import_type m im) ^ ", got " ^ Types.string_of_extern_type (extern_type_of ext)); match ext with | ExternFunc func -> State.add state idx (State.Func func) | ExternTable tab -> State.add state idx (State.Table tab) | ExternMemory mem -> State.add state idx (State.Memory mem) | ExternGlobal glob -> State.add state idx (State.Global glob)) exts in let tables, memories, funcs, globals = State.finalize state in { inst with funcs; globals; memories; tables } let init_func (inst : module_inst) (func : func_inst) = match func with | Func.AstFunc (_, inst_ref, _) -> inst_ref := inst | _ -> assert false let run_elem i elem = let at = elem.it.emode.at in let x = i @@ at in match elem.it.emode.it with | Passive -> [] | Active { index; offset } -> offset.it @ [ Const (I32 0l @@ at) @@ at; Const (I32 (Lib.List32.length elem.it.einit) @@ at) @@ at; TableInit (index, x) @@ at; ElemDrop x @@ at; ] | Declarative -> [ ElemDrop x @@ at ] let run_data i data = let at = data.it.dmode.at in let x = i @@ at in match data.it.dmode.it with | Passive -> [] | Active { index; offset } -> assert (index.it = 0l); offset.it @ [ Const (I32 0l @@ at) @@ at; Const (I32 (Int32.of_int (String.length data.it.dinit)) @@ at) @@ at; MemoryInit x @@ at; DataDrop x @@ at; ] | Declarative -> assert false let run_start start = [ Call start.it.sfunc @@ start.at ] let init (m : module_) (exts : (Utf8.t * extern) list) ~gas_limit : module_inst = let { imports; tables; memories; globals; funcs; types; exports; elems; datas; start; } = m.it in if exts < > imports then Link.error m.at " wrong number of imports provided for initialisation " ; Link.error m.at "wrong number of imports provided for initialisation"; *) let inst0 = { (add_imports m exts imports empty_module_inst) with types = List.map (fun type_ -> type_.it) types; gas_limit; } in let fs = List.map (create_func inst0) funcs in let inst1 = { inst0 with funcs = inst0.funcs @ fs } in let inst2 = { inst1 with tables = inst1.tables @ List.map (create_table inst1) tables; memories = inst1.memories @ List.map (create_memory inst1) memories; globals = inst1.globals @ List.map (create_global inst1) globals; } in let inst = { inst2 with exports = List.map (create_export inst2) exports; elems = List.map (create_elem inst2) elems; datas = List.map (create_data inst2) datas; } in List.iter (init_func inst) fs; let es_elem = List.concat (Lib.List32.mapi run_elem elems) in let es_data = List.concat (Lib.List32.mapi run_data datas) in let es_start = Lib.Option.get (Lib.Option.map run_start start) [] in ignore (eval (config inst [] (List.map plain (es_elem @ es_data @ es_start)))); inst
null
https://raw.githubusercontent.com/marigold-dev/deku/a26f31e0560ad12fd86cf7fa4667bb147247c7ef/deku-c/interpreter/exec/eval.ml
ocaml
Errors failure that cannot happen in valid code to model stack overflow Evaluation * Conventions: * e : instr * v : value * es : instr list * vs : value stack * c : config d > s d > s Functions & Constants Modules
open Values open Types open Instance open Ast open Source module Link = Error.Make () module Trap = Error.Make () module Crash = Error.Make () module Exhaustion = Error.Make () exception Link = Link.Error exception Trap = Trap.Error exception Exhaustion = Exhaustion.Error let table_error at = function | Table.Bounds -> "out of bounds table access" | Table.SizeOverflow -> "table size overflow" | Table.SizeLimit -> "table size limit reached" | Table.Type -> Crash.error at "type mismatch at table access" | exn -> raise exn let memory_error at = function | Memory.Bounds -> "out of bounds memory access" | Memory.SizeOverflow -> "memory size overflow" | Memory.SizeLimit -> "memory size limit reached" | Memory.Type -> Crash.error at "type mismatch at memory access" | exn -> raise exn let numeric_error at = function | Ixx.Overflow -> "integer overflow" | Ixx.DivideByZero -> "integer divide by zero" | Ixx.InvalidConversion -> "invalid conversion to integer" | Values.TypeError (i, v, t) -> Crash.error at ("type error, expected " ^ Types.string_of_num_type t ^ " as operand " ^ string_of_int i ^ ", got " ^ Types.string_of_num_type (type_of_num v)) | exn -> raise exn Administrative Expressions & Configurations type 'a stack = 'a list type frame = { inst : module_inst; locals : value ref list } type code = value stack * admin_instr list and admin_instr = admin_instr' phrase and admin_instr' = | Plain of instr' | Refer of ref_ | Invoke of func_inst | Trapping of string | Returning of value stack | Breaking of int32 * value stack | Label of int32 * instr list * code | Frame of int32 * frame * code type config = { frame : frame; code : code; } let frame inst locals = { inst; locals } let config inst vs es = { frame = frame inst []; code = (vs, es); budget = 300 } let plain e = Plain e.it @@ e.at let lookup category list x = try Lib.List32.nth list x.it with Failure _ -> Crash.error x.at ("undefined " ^ category ^ " " ^ Int32.to_string x.it) let type_ (inst : module_inst) x = lookup "type" inst.types x let func (inst : module_inst) x = lookup "function" inst.funcs x let table (inst : module_inst) x = lookup "table" inst.tables x let memory (inst : module_inst) x = lookup "memory" inst.memories x let global (inst : module_inst) x = lookup "global" inst.globals x let elem (inst : module_inst) x = lookup "element segment" inst.elems x let data (inst : module_inst) x = lookup "data segment" inst.datas x let local (frame : frame) x = lookup "local" frame.locals x let inst frame = frame.inst let any_ref inst x i at = try Table.load (table inst x) i with Table.Bounds -> Trap.error at ("undefined element " ^ Int32.to_string i) let func_ref inst x i at = match any_ref inst x i at with | FuncRef f -> f | NullRef _ -> Trap.error at ("uninitialized element " ^ Int32.to_string i) | _ -> Crash.error at ("type mismatch for element " ^ Int32.to_string i) let func_type_of = function | Func.AstFunc (t, inst, f) -> t | Func.HostFunc (t, _) -> t let block_type inst bt = match bt with | VarBlockType x -> type_ inst x | ValBlockType None -> FuncType ([], []) | ValBlockType (Some t) -> FuncType ([], [ t ]) let take n (vs : 'a stack) at = try Lib.List32.take n vs with Failure _ -> Crash.error at "stack underflow" let drop n (vs : 'a stack) at = try Lib.List32.drop n vs with Failure _ -> Crash.error at "stack underflow" let mem_oob frame x i n = I64.gt_u (I64.add (I64_convert.extend_i32_u i) (I64_convert.extend_i32_u n)) (Memory.bound (memory frame.inst x)) let data_oob frame x i n = I64.gt_u (I64.add (I64_convert.extend_i32_u i) (I64_convert.extend_i32_u n)) (I64.of_int_u (String.length !(data frame.inst x))) let table_oob frame x i n = I64.gt_u (I64.add (I64_convert.extend_i32_u i) (I64_convert.extend_i32_u n)) (I64_convert.extend_i32_u (Table.size (table frame.inst x))) let elem_oob frame x i n = I64.gt_u (I64.add (I64_convert.extend_i32_u i) (I64_convert.extend_i32_u n)) (I64.of_int_u (List.length !(elem frame.inst x))) let rec step (c : config) : config = let { frame; code = vs, es; _ } = c in Instance.burn_gas (inst frame) 100L; let e = List.hd es in let vs', es' = match (e.it, vs) with | Plain e', vs -> ( match (e', vs) with | Unreachable, vs -> (vs, [ Trapping "unreachable executed" @@ e.at ]) | Nop, vs -> (vs, []) | Block (bt, es'), vs -> let (FuncType (ts1, ts2)) = block_type frame.inst bt in let n1 = Lib.List32.length ts1 in let n2 = Lib.List32.length ts2 in let args, vs' = (take n1 vs e.at, drop n1 vs e.at) in (vs', [ Label (n2, [], (args, List.map plain es')) @@ e.at ]) | Loop (bt, es'), vs -> let (FuncType (ts1, ts2)) = block_type frame.inst bt in let n1 = Lib.List32.length ts1 in let args, vs' = (take n1 vs e.at, drop n1 vs e.at) in ( vs', [ Label (n1, [ e' @@ e.at ], (args, List.map plain es')) @@ e.at ] ) | If (bt, es1, es2), Num (I32 i) :: vs' -> if i = 0l then (vs', [ Plain (Block (bt, es2)) @@ e.at ]) else (vs', [ Plain (Block (bt, es1)) @@ e.at ]) | Br x, vs -> ([], [ Breaking (x.it, vs) @@ e.at ]) | BrIf x, Num (I32 i) :: vs' -> if i = 0l then (vs', []) else (vs', [ Plain (Br x) @@ e.at ]) | BrTable (xs, x), Num (I32 i) :: vs' -> if I32.ge_u i (Lib.List32.length xs) then (vs', [ Plain (Br x) @@ e.at ]) else (vs', [ Plain (Br (Lib.List32.nth xs i)) @@ e.at ]) | Return, vs -> ([], [ Returning vs @@ e.at ]) | Call x, vs -> (vs, [ Invoke (func frame.inst x) @@ e.at ]) | CallIndirect (x, y), Num (I32 i) :: vs -> let func = func_ref frame.inst x i e.at in if type_ frame.inst y <> Func.type_of func then (vs, [ Trapping "indirect call type mismatch" @@ e.at ]) else (vs, [ Invoke func @@ e.at ]) | Drop, v :: vs' -> (vs', []) | Select _, Num (I32 i) :: v2 :: v1 :: vs' -> if i = 0l then (v2 :: vs', []) else (v1 :: vs', []) | LocalGet x, vs -> (!(local frame x) :: vs, []) | LocalSet x, v :: vs' -> local frame x := v; (vs', []) | LocalTee x, v :: vs' -> local frame x := v; (v :: vs', []) | GlobalGet x, vs -> (Global.load (global frame.inst x) :: vs, []) | GlobalSet x, v :: vs' -> ( try Global.store (global frame.inst x) v; (vs', []) with | Global.NotMutable -> Crash.error e.at "write to immutable global" | Global.Type -> Crash.error e.at "type mismatch at global write") | TableGet x, Num (I32 i) :: vs' -> ( try (Ref (Table.load (table frame.inst x) i) :: vs', []) with exn -> (vs', [ Trapping (table_error e.at exn) @@ e.at ])) | TableSet x, Ref r :: Num (I32 i) :: vs' -> ( try Table.store (table frame.inst x) i r; (vs', []) with exn -> (vs', [ Trapping (table_error e.at exn) @@ e.at ])) | TableSize x, vs -> (Num (I32 (Table.size (table frame.inst x))) :: vs, []) | TableGrow x, Num (I32 delta) :: Ref r :: vs' -> let tab = table frame.inst x in let old_size = Table.size tab in let result = try Table.grow tab delta r; old_size with Table.SizeOverflow | Table.SizeLimit | Table.OutOfMemory -> -1l in (Num (I32 result) :: vs', []) | TableFill x, Num (I32 n) :: Ref r :: Num (I32 i) :: vs' -> if table_oob frame x i n then (vs', [ Trapping (table_error e.at Table.Bounds) @@ e.at ]) else if n = 0l then (vs', []) else let _ = assert (I32.lt_u i 0xffff_ffffl) in ( vs', List.map (at e.at) [ Plain (Const (I32 i @@ e.at)); Refer r; Plain (TableSet x); Plain (Const (I32 (I32.add i 1l) @@ e.at)); Refer r; Plain (Const (I32 (I32.sub n 1l) @@ e.at)); Plain (TableFill x); ] ) | TableCopy (x, y), Num (I32 n) :: Num (I32 s) :: Num (I32 d) :: vs' -> if table_oob frame x d n || table_oob frame y s n then (vs', [ Trapping (table_error e.at Table.Bounds) @@ e.at ]) else if n = 0l then (vs', []) else if I32.le_u d s then ( vs', List.map (at e.at) [ Plain (Const (I32 d @@ e.at)); Plain (Const (I32 s @@ e.at)); Plain (TableGet y); Plain (TableSet x); Plain (Const (I32 (I32.add d 1l) @@ e.at)); Plain (Const (I32 (I32.add s 1l) @@ e.at)); Plain (Const (I32 (I32.sub n 1l) @@ e.at)); Plain (TableCopy (x, y)); ] ) else ( vs', List.map (at e.at) [ Plain (Const (I32 (I32.add d 1l) @@ e.at)); Plain (Const (I32 (I32.add s 1l) @@ e.at)); Plain (Const (I32 (I32.sub n 1l) @@ e.at)); Plain (TableCopy (x, y)); Plain (Const (I32 d @@ e.at)); Plain (Const (I32 s @@ e.at)); Plain (TableGet y); Plain (TableSet x); ] ) | TableInit (x, y), Num (I32 n) :: Num (I32 s) :: Num (I32 d) :: vs' -> if table_oob frame x d n || elem_oob frame y s n then (vs', [ Trapping (table_error e.at Table.Bounds) @@ e.at ]) else if n = 0l then (vs', []) else let seg = !(elem frame.inst y) in ( vs', List.map (at e.at) [ Plain (Const (I32 d @@ e.at)); Refer (List.nth seg (Int32.to_int s)); Plain (TableSet x); Plain (Const (I32 (I32.add d 1l) @@ e.at)); Plain (Const (I32 (I32.add s 1l) @@ e.at)); Plain (Const (I32 (I32.sub n 1l) @@ e.at)); Plain (TableInit (x, y)); ] ) | ElemDrop x, vs -> let seg = elem frame.inst x in seg := []; (vs, []) | Load { offset; ty; pack; _ }, Num (I32 i) :: vs' -> ( let mem = memory frame.inst (0l @@ e.at) in let a = I64_convert.extend_i32_u i in try let n = match pack with | None -> Memory.load_num mem a offset ty | Some (sz, ext) -> Memory.load_num_packed sz ext mem a offset ty in (Num n :: vs', []) with exn -> (vs', [ Trapping (memory_error e.at exn) @@ e.at ])) | Store { offset; pack; _ }, Num n :: Num (I32 i) :: vs' -> ( let mem = memory frame.inst (0l @@ e.at) in let a = I64_convert.extend_i32_u i in try (match pack with | None -> Memory.store_num mem a offset n | Some sz -> Memory.store_num_packed sz mem a offset n); (vs', []) with exn -> (vs', [ Trapping (memory_error e.at exn) @@ e.at ])) | VecLoad { offset; ty; pack; _ }, Num (I32 i) :: vs' -> ( let mem = memory frame.inst (0l @@ e.at) in let addr = I64_convert.extend_i32_u i in try let v = match pack with | None -> Memory.load_vec mem addr offset ty | Some (sz, ext) -> Memory.load_vec_packed sz ext mem addr offset ty in (Vec v :: vs', []) with exn -> (vs', [ Trapping (memory_error e.at exn) @@ e.at ])) | VecStore { offset; _ }, Vec v :: Num (I32 i) :: vs' -> ( let mem = memory frame.inst (0l @@ e.at) in let addr = I64_convert.extend_i32_u i in try Memory.store_vec mem addr offset v; (vs', []) with exn -> (vs', [ Trapping (memory_error e.at exn) @@ e.at ])) | ( VecLoadLane ({ offset; ty; pack; _ }, j), Vec (V128 v) :: Num (I32 i) :: vs' ) -> ( let mem = memory frame.inst (0l @@ e.at) in let addr = I64_convert.extend_i32_u i in try let v = match pack with | Pack8 -> V128.I8x16.replace_lane j v (I32Num.of_num 0 (Memory.load_num_packed Pack8 SX mem addr offset I32Type)) | Pack16 -> V128.I16x8.replace_lane j v (I32Num.of_num 0 (Memory.load_num_packed Pack16 SX mem addr offset I32Type)) | Pack32 -> V128.I32x4.replace_lane j v (I32Num.of_num 0 (Memory.load_num mem addr offset I32Type)) | Pack64 -> V128.I64x2.replace_lane j v (I64Num.of_num 0 (Memory.load_num mem addr offset I64Type)) in (Vec (V128 v) :: vs', []) with exn -> (vs', [ Trapping (memory_error e.at exn) @@ e.at ])) | ( VecStoreLane ({ offset; ty; pack; _ }, j), Vec (V128 v) :: Num (I32 i) :: vs' ) -> ( let mem = memory frame.inst (0l @@ e.at) in let addr = I64_convert.extend_i32_u i in try (match pack with | Pack8 -> Memory.store_num_packed Pack8 mem addr offset (I32 (V128.I8x16.extract_lane_s j v)) | Pack16 -> Memory.store_num_packed Pack16 mem addr offset (I32 (V128.I16x8.extract_lane_s j v)) | Pack32 -> Memory.store_num mem addr offset (I32 (V128.I32x4.extract_lane_s j v)) | Pack64 -> Memory.store_num mem addr offset (I64 (V128.I64x2.extract_lane_s j v))); (vs', []) with exn -> (vs', [ Trapping (memory_error e.at exn) @@ e.at ])) | MemorySize, vs -> let mem = memory frame.inst (0l @@ e.at) in (Num (I32 (Memory.size mem)) :: vs, []) | MemoryGrow, Num (I32 delta) :: vs' -> let mem = memory frame.inst (0l @@ e.at) in let old_size = Memory.size mem in let result = try Memory.grow mem delta; old_size with | Memory.SizeOverflow | Memory.SizeLimit | Memory.OutOfMemory -> -1l in (Num (I32 result) :: vs', []) | MemoryFill, Num (I32 n) :: Num k :: Num (I32 i) :: vs' -> if mem_oob frame (0l @@ e.at) i n then (vs', [ Trapping (memory_error e.at Memory.Bounds) @@ e.at ]) else if n = 0l then (vs', []) else ( vs', List.map (at e.at) [ Plain (Const (I32 i @@ e.at)); Plain (Const (k @@ e.at)); Plain (Store { ty = I32Type; align = 0; offset = 0l; pack = Some Pack8; }); Plain (Const (I32 (I32.add i 1l) @@ e.at)); Plain (Const (k @@ e.at)); Plain (Const (I32 (I32.sub n 1l) @@ e.at)); Plain MemoryFill; ] ) | MemoryCopy, Num (I32 n) :: Num (I32 s) :: Num (I32 d) :: vs' -> if mem_oob frame (0l @@ e.at) s n || mem_oob frame (0l @@ e.at) d n then (vs', [ Trapping (memory_error e.at Memory.Bounds) @@ e.at ]) else if n = 0l then (vs', []) else if I32.le_u d s then ( vs', List.map (at e.at) [ Plain (Const (I32 d @@ e.at)); Plain (Const (I32 s @@ e.at)); Plain (Load { ty = I32Type; align = 0; offset = 0l; pack = Some (Pack8, ZX); }); Plain (Store { ty = I32Type; align = 0; offset = 0l; pack = Some Pack8; }); Plain (Const (I32 (I32.add d 1l) @@ e.at)); Plain (Const (I32 (I32.add s 1l) @@ e.at)); Plain (Const (I32 (I32.sub n 1l) @@ e.at)); Plain MemoryCopy; ] ) else ( vs', List.map (at e.at) [ Plain (Const (I32 (I32.add d 1l) @@ e.at)); Plain (Const (I32 (I32.add s 1l) @@ e.at)); Plain (Const (I32 (I32.sub n 1l) @@ e.at)); Plain MemoryCopy; Plain (Const (I32 d @@ e.at)); Plain (Const (I32 s @@ e.at)); Plain (Load { ty = I32Type; align = 0; offset = 0l; pack = Some (Pack8, ZX); }); Plain (Store { ty = I32Type; align = 0; offset = 0l; pack = Some Pack8; }); ] ) | MemoryInit x, Num (I32 n) :: Num (I32 s) :: Num (I32 d) :: vs' -> if mem_oob frame (0l @@ e.at) d n || data_oob frame x s n then (vs', [ Trapping (memory_error e.at Memory.Bounds) @@ e.at ]) else if n = 0l then (vs', []) else let seg = !(data frame.inst x) in let b = Int32.of_int (Char.code seg.[Int32.to_int s]) in ( vs', List.map (at e.at) [ Plain (Const (I32 d @@ e.at)); Plain (Const (I32 b @@ e.at)); Plain (Store { ty = I32Type; align = 0; offset = 0l; pack = Some Pack8; }); Plain (Const (I32 (I32.add d 1l) @@ e.at)); Plain (Const (I32 (I32.add s 1l) @@ e.at)); Plain (Const (I32 (I32.sub n 1l) @@ e.at)); Plain (MemoryInit x); ] ) | DataDrop x, vs -> let seg = data frame.inst x in seg := ""; (vs, []) | RefNull t, vs' -> (Ref (NullRef t) :: vs', []) | RefIsNull, Ref r :: vs' -> ( match r with | NullRef _ -> (Num (I32 1l) :: vs', []) | _ -> (Num (I32 0l) :: vs', [])) | RefFunc x, vs' -> let f = func frame.inst x in (Ref (FuncRef f) :: vs', []) | Const n, vs -> (Num n.it :: vs, []) | Test testop, Num n :: vs' -> ( try (value_of_bool (Eval_num.eval_testop testop n) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | Compare relop, Num n2 :: Num n1 :: vs' -> ( try (value_of_bool (Eval_num.eval_relop relop n1 n2) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | Unary unop, Num n :: vs' -> ( try (Num (Eval_num.eval_unop unop n) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | Binary binop, Num n2 :: Num n1 :: vs' -> ( try (Num (Eval_num.eval_binop binop n1 n2) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | Convert cvtop, Num n :: vs' -> ( try (Num (Eval_num.eval_cvtop cvtop n) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecConst v, vs -> (Vec v.it :: vs, []) | VecTest testop, Vec n :: vs' -> ( try (value_of_bool (Eval_vec.eval_testop testop n) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecUnary unop, Vec n :: vs' -> ( try (Vec (Eval_vec.eval_unop unop n) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecBinary binop, Vec n2 :: Vec n1 :: vs' -> ( try (Vec (Eval_vec.eval_binop binop n1 n2) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecCompare relop, Vec n2 :: Vec n1 :: vs' -> ( try (Vec (Eval_vec.eval_relop relop n1 n2) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecConvert cvtop, Vec n :: vs' -> ( try (Vec (Eval_vec.eval_cvtop cvtop n) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecShift shiftop, Num s :: Vec v :: vs' -> ( try (Vec (Eval_vec.eval_shiftop shiftop v s) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecBitmask bitmaskop, Vec v :: vs' -> ( try (Num (Eval_vec.eval_bitmaskop bitmaskop v) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecTestBits vtestop, Vec n :: vs' -> ( try (value_of_bool (Eval_vec.eval_vtestop vtestop n) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecUnaryBits vunop, Vec n :: vs' -> ( try (Vec (Eval_vec.eval_vunop vunop n) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecBinaryBits vbinop, Vec n2 :: Vec n1 :: vs' -> ( try (Vec (Eval_vec.eval_vbinop vbinop n1 n2) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecTernaryBits vternop, Vec v3 :: Vec v2 :: Vec v1 :: vs' -> ( try (Vec (Eval_vec.eval_vternop vternop v1 v2 v3) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecSplat splatop, Num n :: vs' -> ( try (Vec (Eval_vec.eval_splatop splatop n) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecExtract extractop, Vec v :: vs' -> ( try (Num (Eval_vec.eval_extractop extractop v) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | VecReplace replaceop, Num r :: Vec v :: vs' -> ( try (Vec (Eval_vec.eval_replaceop replaceop v r) :: vs', []) with exn -> (vs', [ Trapping (numeric_error e.at exn) @@ e.at ])) | _ -> let s1 = string_of_values (List.rev vs) in let s2 = string_of_value_types (List.map type_of_value (List.rev vs)) in Crash.error e.at ("missing or ill-typed operand on stack (" ^ s1 ^ " : " ^ s2 ^ ")") ) | Refer r, vs -> (Ref r :: vs, []) | Trapping msg, vs -> assert false | Returning vs', vs -> Crash.error e.at "undefined frame" | Breaking (k, vs'), vs -> Crash.error e.at "undefined label" | Label (n, es0, (vs', [])), vs -> (vs' @ vs, []) | Label (n, es0, (vs', { it = Trapping msg; at } :: es')), vs -> (vs, [ Trapping msg @@ at ]) | Label (n, es0, (vs', { it = Returning vs0; at } :: es')), vs -> (vs, [ Returning vs0 @@ at ]) | Label (n, es0, (vs', { it = Breaking (0l, vs0); at } :: es')), vs -> (take n vs0 e.at @ vs, List.map plain es0) | Label (n, es0, (vs', { it = Breaking (k, vs0); at } :: es')), vs -> (vs, [ Breaking (Int32.sub k 1l, vs0) @@ at ]) | Label (n, es0, code'), vs -> let c' = step { c with code = code' } in (vs, [ Label (n, es0, c'.code) @@ e.at ]) | Frame (n, frame', (vs', [])), vs -> (vs' @ vs, []) | Frame (n, frame', (vs', { it = Trapping msg; at } :: es')), vs -> (vs, [ Trapping msg @@ at ]) | Frame (n, frame', (vs', { it = Returning vs0; at } :: es')), vs -> (take n vs0 e.at @ vs, []) | Frame (n, frame', code'), vs -> let c' = step { frame = frame'; code = code'; budget = c.budget - 1 } in (vs, [ Frame (n, c'.frame, c'.code) @@ e.at ]) | Invoke func, vs when c.budget = 0 -> Exhaustion.error e.at "call stack exhausted" | Invoke func, vs -> ( let (FuncType (ins, out)) = func_type_of func in let n1, n2 = (Lib.List32.length ins, Lib.List32.length out) in let args, vs' = (take n1 vs e.at, drop n1 vs e.at) in match func with | Func.AstFunc (t, inst', f) -> let locals' = List.rev args @ List.map default_value f.it.locals in let frame' = { inst = !inst'; locals = List.map ref locals' } in let instr' = [ Label (n2, [], ([], List.map plain f.it.body)) @@ f.at ] in (vs', [ Frame (n2, frame', ([], instr')) @@ e.at ]) | Func.HostFunc (t, f) -> ( try (List.rev (f (ref (inst frame)) (List.rev args)) @ vs', []) with Crash (_, msg) -> Crash.error e.at msg)) in { c with code = (vs', es' @ List.tl es) } let rec eval (c : config) : value stack = match c.code with | vs, [] -> vs | vs, { it = Trapping msg; at } :: _ -> Trap.error at msg | vs, es -> eval (step c) let invoke (func : func_inst) (vs : value list) : value list = let at = match func with Func.AstFunc (_, inst, f) -> f.at | _ -> no_region in let gas = match func with | Func.AstFunc (_, inst, _) -> Instance.get_gas_limit !inst | _ -> Int64.max_int in let (FuncType (ins, out)) = Func.type_of func in if List.length vs <> List.length ins then Crash.error at "wrong number of arguments"; if not (List.for_all2 (fun v -> ( = ) (type_of_value v)) vs ins) then Crash.error at "wrong types of arguments"; let c = config { empty_module_inst with gas_limit = gas } (List.rev vs) [ Invoke func @@ at ] in try List.rev (eval c) with Stack_overflow -> Exhaustion.error at "call stack exhausted" let eval_const (inst : module_inst) (const : const) : value = let c = config inst [] (List.map plain const.it) in match eval c with | [ v ] -> v | vs -> Crash.error const.at "wrong number of results on stack" let create_func (inst : module_inst) (f : func) : func_inst = Func.alloc (type_ inst f.it.ftype) (ref inst) f let create_table (inst : module_inst) (tab : table) : table_inst = let { ttype } = tab.it in let (TableType (_lim, t)) = ttype in Table.alloc ttype (NullRef t) let create_memory (inst : module_inst) (mem : memory) : memory_inst = let { mtype } = mem.it in Memory.alloc mtype let create_global (inst : module_inst) (glob : global) : global_inst = let { gtype; ginit } = glob.it in let v = eval_const inst ginit in Global.alloc gtype v let create_export (inst : module_inst) (ex : export) : export_inst = let { name; edesc } = ex.it in let ext = match edesc.it with | FuncExport x -> ExternFunc (func inst x) | TableExport x -> ExternTable (table inst x) | MemoryExport x -> ExternMemory (memory inst x) | GlobalExport x -> ExternGlobal (global inst x) in (name, ext) let create_elem (inst : module_inst) (seg : elem_segment) : elem_inst = let { etype; einit; _ } = seg.it in ref (List.map (fun c -> as_ref (eval_const inst c)) einit) let create_data (inst : module_inst) (seg : data_segment) : data_inst = let { dinit; _ } = seg.it in ref dinit module State = struct module Indexed = Map.Make (Int) type _ kind = | Table : table_inst -> table_inst kind | Func : func_inst -> func_inst kind | Memory : memory_inst -> memory_inst kind | Global : global_inst -> global_inst kind type t = { mutable funcs : func_inst Indexed.t; mutable tables : table_inst Indexed.t; mutable memories : memory_inst Indexed.t; mutable globals : global_inst Indexed.t; } let empty = { funcs = Indexed.empty; tables = Indexed.empty; memories = Indexed.empty; globals = Indexed.empty; } let add (type a) (t : t) idx (kind : a kind) = match kind with | Table x -> t.tables <- Indexed.add idx x t.tables | Func x -> t.funcs <- Indexed.add idx x t.funcs | Memory x -> t.memories <- Indexed.add idx x t.memories | Global x -> t.globals <- Indexed.add idx x t.globals let finalize ({ tables; memories; funcs; globals } : t) = let final x = Indexed.to_seq x |> Seq.map snd |> List.of_seq in (final tables, final memories, final funcs, final globals) end module Name_map = Map.Make (Utf8) let add_imports (m : module_) (exts : (Utf8.t * extern) list) (im : import list) (inst : module_inst) : module_inst = let named_map = Name_map.of_seq (List.to_seq im |> Seq.mapi (fun idx ({ it = x; at = _ } as y) -> (x.item_name, (y, idx))) ) in let state = State.empty in let () = List.iter (fun (ext_name, ext) -> let item = Name_map.find_opt ext_name named_map in let im, idx = match item with | Some x -> x | None -> Link.error Source.no_region (Format.sprintf "Redundant host function provided: %s\n" (Utf8.encode ext_name)) in if not (match_extern_type (extern_type_of ext) (import_type m im)) then Link.error im.at ("incompatible import type for " ^ "\"" ^ Utf8.encode im.it.module_name ^ "\" " ^ "\"" ^ Utf8.encode im.it.item_name ^ "\": " ^ "expected " ^ Types.string_of_extern_type (import_type m im) ^ ", got " ^ Types.string_of_extern_type (extern_type_of ext)); match ext with | ExternFunc func -> State.add state idx (State.Func func) | ExternTable tab -> State.add state idx (State.Table tab) | ExternMemory mem -> State.add state idx (State.Memory mem) | ExternGlobal glob -> State.add state idx (State.Global glob)) exts in let tables, memories, funcs, globals = State.finalize state in { inst with funcs; globals; memories; tables } let init_func (inst : module_inst) (func : func_inst) = match func with | Func.AstFunc (_, inst_ref, _) -> inst_ref := inst | _ -> assert false let run_elem i elem = let at = elem.it.emode.at in let x = i @@ at in match elem.it.emode.it with | Passive -> [] | Active { index; offset } -> offset.it @ [ Const (I32 0l @@ at) @@ at; Const (I32 (Lib.List32.length elem.it.einit) @@ at) @@ at; TableInit (index, x) @@ at; ElemDrop x @@ at; ] | Declarative -> [ ElemDrop x @@ at ] let run_data i data = let at = data.it.dmode.at in let x = i @@ at in match data.it.dmode.it with | Passive -> [] | Active { index; offset } -> assert (index.it = 0l); offset.it @ [ Const (I32 0l @@ at) @@ at; Const (I32 (Int32.of_int (String.length data.it.dinit)) @@ at) @@ at; MemoryInit x @@ at; DataDrop x @@ at; ] | Declarative -> assert false let run_start start = [ Call start.it.sfunc @@ start.at ] let init (m : module_) (exts : (Utf8.t * extern) list) ~gas_limit : module_inst = let { imports; tables; memories; globals; funcs; types; exports; elems; datas; start; } = m.it in if exts < > imports then Link.error m.at " wrong number of imports provided for initialisation " ; Link.error m.at "wrong number of imports provided for initialisation"; *) let inst0 = { (add_imports m exts imports empty_module_inst) with types = List.map (fun type_ -> type_.it) types; gas_limit; } in let fs = List.map (create_func inst0) funcs in let inst1 = { inst0 with funcs = inst0.funcs @ fs } in let inst2 = { inst1 with tables = inst1.tables @ List.map (create_table inst1) tables; memories = inst1.memories @ List.map (create_memory inst1) memories; globals = inst1.globals @ List.map (create_global inst1) globals; } in let inst = { inst2 with exports = List.map (create_export inst2) exports; elems = List.map (create_elem inst2) elems; datas = List.map (create_data inst2) datas; } in List.iter (init_func inst) fs; let es_elem = List.concat (Lib.List32.mapi run_elem elems) in let es_data = List.concat (Lib.List32.mapi run_data datas) in let es_start = Lib.Option.get (Lib.Option.map run_start start) [] in ignore (eval (config inst [] (List.map plain (es_elem @ es_data @ es_start)))); inst
d0fc61ba554bc2f5929321c1b79bfd60330a9be4ef6cd639e1e9d26c4ad0ad3b
sol/v8
Disposable.hs
{-# LANGUAGE DeriveDataTypeable #-} module Foreign.JavaScript.V8.Disposable ( Disposable (..) , AlreadyDisposed (..) , Finalizer , finalizerNew , finalizerAdd , finalize ) where import Control.Applicative import Control.Monad import Data.IORef import qualified Control.Exception as E import Data.Typeable data AlreadyDisposed = AlreadyDisposed deriving (Eq, Show, Typeable) instance E.Exception AlreadyDisposed newtype Finalizer = Finalizer (IORef (IO ())) -- | Create empty finalizer. finalizerNew :: IO Finalizer finalizerNew = Finalizer <$> newIORef (pure ()) -- | Add action to finalizer. finalizerAdd :: Finalizer -> IO () -> IO () finalizerAdd (Finalizer fin) action = modifyIORef fin (>> action) -- | Run finalizer. finalize :: Finalizer -> IO () finalize (Finalizer fin) = do join (readIORef fin) writeIORef fin (E.throwIO AlreadyDisposed) class Disposable a where dispose :: a -> IO () instance Disposable Finalizer where dispose = finalize
null
https://raw.githubusercontent.com/sol/v8/0ff1b23588cf3c0a8f55a4ec557971dabb104d73/src/Foreign/JavaScript/V8/Disposable.hs
haskell
# LANGUAGE DeriveDataTypeable # | Create empty finalizer. | Add action to finalizer. | Run finalizer.
module Foreign.JavaScript.V8.Disposable ( Disposable (..) , AlreadyDisposed (..) , Finalizer , finalizerNew , finalizerAdd , finalize ) where import Control.Applicative import Control.Monad import Data.IORef import qualified Control.Exception as E import Data.Typeable data AlreadyDisposed = AlreadyDisposed deriving (Eq, Show, Typeable) instance E.Exception AlreadyDisposed newtype Finalizer = Finalizer (IORef (IO ())) finalizerNew :: IO Finalizer finalizerNew = Finalizer <$> newIORef (pure ()) finalizerAdd :: Finalizer -> IO () -> IO () finalizerAdd (Finalizer fin) action = modifyIORef fin (>> action) finalize :: Finalizer -> IO () finalize (Finalizer fin) = do join (readIORef fin) writeIORef fin (E.throwIO AlreadyDisposed) class Disposable a where dispose :: a -> IO () instance Disposable Finalizer where dispose = finalize
c739e4307e16ea22de8e0a2906aafc6f8ff6e43ae65097b324b8f1e1b5c6e58c
OCamlPro/ocp-indent
js-comment1.ml
type foo = int (* just in case *) These two should n't be indented differently , but are . type z = [ `Bar of foo (* a comment [expected to apply to `Foo as below] *) | `Foo ] type z = [ `Bar (* a comment *) | `Foo ] On second thought , I kind of like this way of thinking about this indentation , even though it is kind of parasyntactic : indentation, even though it is kind of parasyntactic: *) type z = (* Applies to "[" or `Bar. *) [ `Bar of foo (* Applies to "|" or `Foo. Indented too much. *) | `Foo ] type z = (* Applies to "[" or `Bar. *) [ `Bar (* Applies to "|" or `Foo. *) | `Foo ] (* The way we write code, that will line up more nicely. *) let _ = (foo (* This is indented too far to the left *) (bar)) (* It looks to me like we generally want the comment to apply to the following line in most circumstances, including this one. The default indent for an empty line after a function application that isn't terminated with a ";" or something would probably also be in a bit, in anticipation of an argument, although I don't think that's crucial. *) let _ = foo quux (* about bar *) bar (* about baz *) baz * Trying lists within comments : - this is a multi - line element of a list . - and this is a one - liner - this has many more lines - and this is indented like a sub - list - but is n't one at -all this is outside of the list though . - and this is - another list - and another one the end - this is a multi-line element of a list. - and this is a one-liner - this has many more lines - and this is indented like a sub-list - but isn't one at -all this is outside of the list though. - and this is - another list - and another one the end *) There is an issue with toplevel sessions : # expr1 ; ; - : type1 = value1 # expr2 ; ; - : type2 = value2 Comment . # expr1;; - : type1 = value1 # expr2;; - : type2 = value2 Comment. *) (* Comment: - [code]; - {[ code ]} *)
null
https://raw.githubusercontent.com/OCamlPro/ocp-indent/9e26c0a2699b7076cebc04ece59fb354eb84c11c/tests/passing/js-comment1.ml
ocaml
just in case a comment [expected to apply to `Foo as below] a comment Applies to "[" or `Bar. Applies to "|" or `Foo. Indented too much. Applies to "[" or `Bar. Applies to "|" or `Foo. The way we write code, that will line up more nicely. This is indented too far to the left It looks to me like we generally want the comment to apply to the following line in most circumstances, including this one. The default indent for an empty line after a function application that isn't terminated with a ";" or something would probably also be in a bit, in anticipation of an argument, although I don't think that's crucial. about bar about baz Comment: - [code]; - {[ code ]}
These two should n't be indented differently , but are . type z = [ `Bar of foo | `Foo ] type z = [ `Bar | `Foo ] On second thought , I kind of like this way of thinking about this indentation , even though it is kind of parasyntactic : indentation, even though it is kind of parasyntactic: *) type z = [ `Bar of foo | `Foo ] type z = [ `Bar | `Foo ] let _ = (foo (bar)) let _ = foo quux bar baz * Trying lists within comments : - this is a multi - line element of a list . - and this is a one - liner - this has many more lines - and this is indented like a sub - list - but is n't one at -all this is outside of the list though . - and this is - another list - and another one the end - this is a multi-line element of a list. - and this is a one-liner - this has many more lines - and this is indented like a sub-list - but isn't one at -all this is outside of the list though. - and this is - another list - and another one the end *) There is an issue with toplevel sessions : # expr1 ; ; - : type1 = value1 # expr2 ; ; - : type2 = value2 Comment . # expr1;; - : type1 = value1 # expr2;; - : type2 = value2 Comment. *)
abdba7817692327d0a4ce13f139527c0ca94cc990e9944a7f0a422efc85badec
Kakadu/fp2022
relation.mli
* Copyright 2021 - 2022 , and contributors * SPDX - License - Identifier : LGPL-3.0 - or - later open Meta module Tuple : sig type t type element = | Int of int | String of string val from_string_list : string list -> table -> t val to_string_list : t -> string list val nth : int -> t -> element val nth_as_int : int -> t -> int val nth_as_string : int -> t -> string val of_list : element list -> t val length : t -> int val join : t -> t -> t end type t val to_tuple_list : t -> Tuple.t list val to_csv : t -> Csv.t val filter : (Tuple.t -> bool) -> t -> t val map : (Tuple.t -> Tuple.t) -> t -> t val cross_product : t -> t -> t val join : (Tuple.t -> Tuple.t -> bool) -> t -> t -> t module AccessManager : sig type storage val load_db : database -> catalog -> storage val get_active_db : storage -> database val unset_active : storage option -> catalog -> unit val set_active : database -> storage option -> catalog -> storage val get_rel : table -> storage -> t val make_db_from : string -> catalog -> catalog end
null
https://raw.githubusercontent.com/Kakadu/fp2022/6881f083160713ebdf4876025016ccfa6fff4492/SQL/lib/relation.mli
ocaml
* Copyright 2021 - 2022 , and contributors * SPDX - License - Identifier : LGPL-3.0 - or - later open Meta module Tuple : sig type t type element = | Int of int | String of string val from_string_list : string list -> table -> t val to_string_list : t -> string list val nth : int -> t -> element val nth_as_int : int -> t -> int val nth_as_string : int -> t -> string val of_list : element list -> t val length : t -> int val join : t -> t -> t end type t val to_tuple_list : t -> Tuple.t list val to_csv : t -> Csv.t val filter : (Tuple.t -> bool) -> t -> t val map : (Tuple.t -> Tuple.t) -> t -> t val cross_product : t -> t -> t val join : (Tuple.t -> Tuple.t -> bool) -> t -> t -> t module AccessManager : sig type storage val load_db : database -> catalog -> storage val get_active_db : storage -> database val unset_active : storage option -> catalog -> unit val set_active : database -> storage option -> catalog -> storage val get_rel : table -> storage -> t val make_db_from : string -> catalog -> catalog end
fb5b2212db003685aa7c398238aed5ec7e2347b134ca0728948969588103e851
ahrefs/atd
atdj_trans.ml
open Atd.Import open Atdj_names open Atdj_env open Atdj_util module A = Atd.Ast Calculate the JSON representation of an ATD type . * * Values of sum types t are encoded as either Strings or two - element * JSONArrays , depending upon the arity of the particular constructor . * A nullary constructor C is denoted by the " C " , whilst * an application of a unary constructor C to an ATD value v is denoted by the * JSONArray [ " C " , < v > ] , where < v > is the JSON representation of v. * * Option types other than in optional fields ( e.g. ' ? foo : int option ' ) * are not supported . * * Values of sum types t are encoded as either Strings or two-element * JSONArrays, depending upon the arity of the particular constructor. * A nullary constructor C is denoted by the String "C", whilst * an application of a unary constructor C to an ATD value v is denoted by the * JSONArray ["C", <v>], where <v> is the JSON representation of v. * * Option types other than in optional fields (e.g. '?foo: int option') * are not supported. *) let json_of_atd env atd_ty = let atd_ty = norm_ty ~unwrap_option:true env atd_ty in match atd_ty with Either a String or a two element JSONArray | Record _ -> "JSONObject" | List _ -> "JSONArray" | Name (_, (_, ty, _), _) -> (match ty with | "bool" -> "boolean" | "int" -> "int" | "float" -> "double" | "string" -> "String" | _ -> type_not_supported atd_ty ) | x -> type_not_supported x Calculate the method name required to extract the JSON representation of an * ATD value from either a JSONObject or a JSONArray ( " get " , " opt " , * " getInt " , " optInt " , ... ) * ATD value from either a JSONObject or a JSONArray ("get", "opt", * "getInt", "optInt", ...) *) let get env atd_ty opt = let atd_ty = norm_ty ~unwrap_option:true env atd_ty in let prefix = if opt then "opt" else "get" in let suffix = match atd_ty with | Sum _ -> "" | _ -> String.capitalize_ascii (json_of_atd env atd_ty) in prefix ^ suffix let extract_from_edgy_brackets s = Re.Str.global_replace (Re.Str.regexp "^[^<]*<\\|>[^>]*$") "" s (* extract_from_edgy_brackets "ab<cd<e>>f";; - : string = "cd<e>" *) Assignment with translation . Suppose that atd_ty is an ATD type , with * corresponding Java and ( ) JSON types java_ty and json_ty . Then this * function assigns to a variable ` dst ' of type java_ty from a variable ` src ' of * type ` json_ty ' . * corresponding Java and (Javafied) JSON types java_ty and json_ty. Then this * function assigns to a variable `dst' of type java_ty from a variable `src' of * type `json_ty'. *) let rec assign env opt_dst src java_ty atd_ty indent = let atd_ty = norm_ty env atd_ty in match opt_dst with | None -> (match atd_ty with | Sum _ -> sprintf "new %s(%s)" java_ty src | Record _ -> sprintf "new %s(%s)" java_ty src | Name (_, (_, ty, _), _) -> (match ty with | "bool" | "int" | "float" | "string" -> src | _ -> type_not_supported atd_ty ) | x -> type_not_supported x ) | Some dst -> (match atd_ty with | Sum _ -> sprintf "%s%s = new %s(%s);\n" indent dst java_ty src | Record _ -> sprintf "%s%s = new %s(%s);\n" indent dst java_ty src | List (_, sub_ty, _) -> let java_sub_ty = (*ahem*) extract_from_edgy_brackets java_ty in let sub_expr = assign env None "_tmp" java_sub_ty sub_ty "" in sprintf "%s%s = new %s();\n" indent dst java_ty ^ sprintf "%sfor (int _i = 0; _i < %s.length(); ++_i) {\n" indent src ^ sprintf "%s %s _tmp = %s.%s(_i);\n" indent (json_of_atd env sub_ty) src (get env sub_ty false) ^ sprintf "%s %s.add(%s);\n" indent dst sub_expr ^ sprintf "%s}\n" indent | Name (_, (_, ty, _), _) -> (match ty with | "bool" | "int" | "float" | "string" -> sprintf "%s%s = %s;\n" indent dst src | _ -> type_not_supported atd_ty ) | x -> type_not_supported x ) Assign from an object field , with support for optional fields . The are two * kinds of optional fields : ` With_default ( ~ ) and ` Optional ( ? ) . For both * kinds , we return the following values if the field is absent : * * bool - > false * int - > 0 * float - > 0.0 * string - > " " * list - > [ ] * option - > None * * Optional fields of record and sum types are not supported . They are * treated as required fields . * * Fields of the ` Optional kind extend this behaviour by automatically lifting * values of type t to option t by wrapping within a ` Some ' . * Hence ` Optional may only be applied to fields of type option t. * Note that absent fields are still * assigned ` None ' , as before . * * For ` With_default fields , of types bool , int , float , string and list , we use * the org.json opt methods to extract the field . These methods already return * the appropriate defaults if field is absent . For option types , we manually * check for the field and manually create a default . If the field is present , * then we wrap its values as necessary . * kinds of optional fields: `With_default (~) and `Optional (?). For both * kinds, we return the following values if the field is absent: * * bool -> false * int -> 0 * float -> 0.0 * string -> "" * list -> [] * option -> None * * Optional fields of record and sum types are not supported. They are * treated as required fields. * * Fields of the `Optional kind extend this behaviour by automatically lifting * values of type t to option t by wrapping within a `Some'. * Hence `Optional may only be applied to fields of type option t. * Note that absent fields are still * assigned `None', as before. * * For `With_default fields, of types bool, int, float, string and list, we use * the org.json opt methods to extract the field. These methods already return * the appropriate defaults if field is absent. For option types, we manually * check for the field and manually create a default. If the field is present, * then we wrap its values as necessary. *) let assign_field env (`Field (_, (atd_field_name, kind, annots), atd_ty)) java_ty = let json_field_name = get_json_field_name atd_field_name annots in let field_name = get_java_field_name atd_field_name annots in (* Check whether the field is optional *) let is_opt = match kind with | A.Optional | With_default -> true | Required -> false in let src = sprintf "jo.%s(\"%s\")" (get env atd_ty is_opt) json_field_name in if not is_opt then assign env (Some field_name) src java_ty atd_ty " " else let mk_else = function | Some default -> sprintf " } else {\n %s = %s;\n }\n" field_name default | None -> " }\n" in let opt_set_default = match kind with | A.With_default -> (match norm_ty ~unwrap_option:true env atd_ty with | Name (_, (_, name, _), _) -> (match name with | "bool" -> mk_else (Some "false") | "int" -> mk_else (Some "0") | "float" -> mk_else (Some "0.0") | "string" -> mk_else (Some "\"\"") | _ -> mk_else None (* TODO: fail if no default is provided *) ) | List _ -> java_ty is supposed to be of the form " ArrayList < ... > " mk_else (Some (sprintf "new %s()" java_ty)) | _ -> mk_else None (* TODO: fail if no default is provided *) ) | _ -> mk_else None in let atd_ty = norm_ty ~unwrap_option:true env atd_ty in sprintf " if (jo.has(\"%s\")) {\n" json_field_name ^ assign env (Some field_name) src java_ty atd_ty " " ^ opt_set_default (* Generate a toJsonBuffer command *) let rec to_string env id atd_ty indent = let atd_ty = norm_ty env atd_ty in match atd_ty with | List (_, atd_sub_ty, _) -> sprintf "%s_out.append(\"[\");\n" indent ^ sprintf "%sfor (int i = 0; i < %s.size(); ++i) {\n" indent id ^ to_string env (id ^ ".get(i)") atd_sub_ty (indent ^ " ") ^ sprintf "%s if (i < %s.size() - 1)\n" indent id ^ sprintf "%s _out.append(\",\");\n" indent ^ sprintf "%s}\n" indent ^ sprintf "%s_out.append(\"]\");\n" indent | Name (_, (_, "string", _), _) -> (* TODO Check that this is the correct behaviour *) sprintf "%sUtil.writeJsonString(_out, %s);\n" indent id | Name _ -> sprintf "%s_out.append(String.valueOf(%s));\n" indent id | _ -> sprintf "%s%s.toJsonBuffer(_out);\n" indent id (* Generate a toJsonBuffer command for a record field. *) let to_string_field env = function | (`Field (_, (atd_field_name, kind, annots), atd_ty)) -> let json_field_name = get_json_field_name atd_field_name annots in let field_name = get_java_field_name atd_field_name annots in let atd_ty = norm_ty ~unwrap_option:true env atd_ty in (* In the case of an optional field, create a predicate to test whether * the field has its default value. *) let if_part = sprintf " if (%s != null) { if (_isFirst) _isFirst = false; else _out.append(\",\"); _out.append(\"\\\"%s\\\":\"); %s } " field_name json_field_name (to_string env field_name atd_ty " ") in let else_part = let is_opt = match kind with | A.Optional | With_default -> true | Required -> false in if is_opt then "" else sprintf " \ else throw new JSONException(\"Uninitialized field %s\"); " field_name in if_part ^ else_part (* Generate a javadoc comment *) let javadoc loc annots indent = let from_inline_text text = indent ^ " * " ^ text ^ "\n" in (* Assume that code is the name of a field that is defined in the same class *) let from_inline_code code = indent ^ " * {@link #" ^ code ^ "}\n" in let from_doc_para = List.fold_left (fun acc -> function | Atd.Doc.Text text -> (from_inline_text text) :: acc | Code code -> (from_inline_code code) :: acc ) in let from_doc = List.fold_left (fun acc -> function | Atd.Doc.Paragraph para -> from_doc_para acc para | Pre _ -> failwith "Preformatted doc blocks are not supported" ) [] in (match Atd.Doc.get_doc loc annots with | Some doc -> let header = indent ^ "/**\n" in let footer = indent ^ " */\n" in let body = String.concat "" (List.rev (from_doc doc)) in header ^ body ^ footer | None -> "" ) (* ------------------------------------------------------------------------- *) Translation of ATD types into Java types For option , sum and record types , we generate a Java class . Each such class * implements the following interface : * * interface Atdj { * String toJson ( ) throws JSONException ; * void toJsonBuffer(StringBuilder out ) throws JSONException ; * } * * The ( ) method outputs a JSON representation of the * associated value . * * Each class also has a constructor for a JSON string as well as a * constructor from the corresponding org.json type ( see json_of_atd , above ) . * * We do not generate classes for types bool , int , float , string and list ; * instead we ` inline ' these types directly into the class in which they * occur . We do this so that the Java programmer can access such values * directly , thereby avoiding the overhead of having to manually unbox each such * value upon access . * implements the following interface: * * interface Atdj { * String toJson() throws JSONException; * void toJsonBuffer(StringBuilder out) throws JSONException; * } * * The toJson() method outputs a JSON representation of the * associated value. * * Each class also has a String constructor for a JSON string as well as a * constructor from the corresponding org.json type (see json_of_atd, above). * * We do not generate classes for types bool, int, float, string and list; * instead we `inline' these types directly into the class in which they * occur. We do this so that the Java programmer can access such values * directly, thereby avoiding the overhead of having to manually unbox each such * value upon access. *) let open_class env cname = let out = open_out (env.package_dir ^ "/" ^ cname ^ ".java") in fprintf out "\ // Automatically generated; do not edit package %s; import org.json.*; " env.package; out let rec trans_module env items = List.fold_left trans_outer env items and trans_outer env (A.Type (_, (name, _, _), atd_ty)) = match unwrap atd_ty with | Sum (loc, v, a) -> trans_sum name env (loc, v, a) | Record (loc, v, a) -> trans_record name env (loc, v, a) | Name (_, (_, _name, _), _) -> (* Don't translate primitive types at the top-level *) env | x -> type_not_supported x Translation of sum types . For a sum type * * type ty = Foo | Bar of whatever * * we generate a class implemented in Ty.java and an enum defined * in a separate file TyTag.java . * * type ty = Foo | Bar of whatever * * we generate a class Ty implemented in Ty.java and an enum TyEnum defined * in a separate file TyTag.java. *) and trans_sum my_name env (_, vars, _) = let class_name = Atdj_names.to_class_name my_name in let cases = List.map (fun (x : A.variant) -> match x with | Variant (_, (atd_name, an), opt_ty) -> let json_name = get_json_variant_name atd_name an in let func_name, enum_name, field_name = get_java_variant_names atd_name an in let opt_java_ty = opt_ty |> Option.map (fun ty -> let (java_ty, _) = trans_inner env (unwrap_option env ty) in (ty, java_ty) ) in (json_name, func_name, enum_name, field_name, opt_java_ty) | Inherit _ -> assert false ) vars in let tags = List.map (fun (_, _, enum_name, _, _) -> enum_name) cases in let out = open_class env class_name in fprintf out "\ /** * Construct objects of type %s. */ public class %s { Tag t = null; public %s() { } public Tag tag() { return t; } " my_name class_name class_name; fprintf out " /** * Define tags for sum type %s. */ public enum Tag { %s } " my_name (String.concat ", " tags); fprintf out " public %s(Object o) throws JSONException { String tag = Util.extractTag(o); %a throw new JSONException(\"Invalid tag: \" + tag); } " class_name (fun out l -> List.iter (fun (json_name, _func_name, enum_name, field_name, opt_ty) -> match opt_ty with | None -> fprintf out " \ if (tag.equals(\"%s\")) t = Tag.%s; else" TODO : java - string - escape this enum_name | Some (atd_ty, java_ty) -> let src = sprintf "((JSONArray)o).%s(1)" (get env atd_ty false) in let set_value = assign env (Some ("field_" ^ field_name)) src java_ty atd_ty " " in fprintf out " \ if (tag.equals(\"%s\")) { %s t = Tag.%s; } else" TODO : java - string - escape this set_value enum_name ) l ) cases; List.iter (fun (_, func_name, enum_name, field_name, opt_ty) -> match opt_ty with | None -> fprintf out " public void set%s() { /* TODO: clear previously-set field and avoid memory leak */ t = Tag.%s; } " func_name enum_name; | Some (_atd_ty, java_ty) -> fprintf out " %s field_%s = null; public void set%s(%s x) { /* TODO: clear previously-set field in order to avoid memory leak */ t = Tag.%s; field_%s = x; } public %s get%s() { if (t == Tag.%s) return field_%s; else return null; } " java_ty field_name func_name java_ty enum_name field_name java_ty func_name enum_name field_name; ) cases; fprintf out " public void toJsonBuffer(StringBuilder _out) throws JSONException { if (t == null) throw new JSONException(\"Uninitialized %s\"); else { switch(t) {%a default: break; /* unused; keeps compiler happy */ } } } public String toJson() throws JSONException { StringBuilder out = new StringBuilder(128); toJsonBuffer(out); return out.toString(); } " class_name (fun out l -> List.iter (fun (json_name, _func_name, enum_name, field_name, opt_ty) -> match opt_ty with | None -> fprintf out " case %s: _out.append(\"\\\"%s\\\"\"); break;" enum_name TODO : java - string - escape | Some (atd_ty, _) -> fprintf out " case %s: _out.append(\"[\\\"%s\\\",\"); %s _out.append(\"]\"); break;" enum_name json_name (to_string env ("field_" ^ field_name) atd_ty " ") ) l ) cases; fprintf out "}\n"; close_out out; env Translate a record into a Java class . Each record field becomes a field * within the class . * within the class. *) and trans_record my_name env (loc, fields, annots) = (* Remove `Inherit values *) let fields = List.map (function | `Field _ as f -> f | `Inherit _ -> assert false ) fields in (* Translate field types *) let (java_tys, env) = List.fold_left (fun (java_tys, env) -> function | `Field (_, (field_name, _, annots), atd_ty) -> let field_name = get_java_field_name field_name annots in let (java_ty, env) = trans_inner env (unwrap_option env atd_ty) in ((field_name, java_ty) :: java_tys, env) ) ([], env) fields in let java_tys = List.rev java_tys in (* Output Java class *) let class_name = Atdj_names.to_class_name my_name in let out = open_class env class_name in Javadoc output_string out (javadoc loc annots ""); fprintf out "\ public class %s implements Atdj { /** * Construct from a fresh record with null fields. */ public %s() { } /** * Construct from a JSON string. */ public %s(String s) throws JSONException { this(new JSONObject(s)); } %s(JSONObject jo) throws JSONException { " class_name class_name class_name class_name; let env = List.fold_left (fun env (`Field (_, (field_name, _, annots), _) as field) -> let field_name = get_java_field_name field_name annots in let cmd = assign_field env field (List.assoc_exn field_name java_tys) in fprintf out "%s" cmd; env ) env fields in fprintf out "\n \ } public void toJsonBuffer(StringBuilder _out) throws JSONException { boolean _isFirst = true; _out.append(\"{\");%a _out.append(\"}\"); } public String toJson() throws JSONException { StringBuilder out = new StringBuilder(128); toJsonBuffer(out); return out.toString(); } " (fun out l -> List.iter (fun field -> output_string out (to_string_field env field) ) l; ) fields; List.iter (function `Field (loc, (field_name, _, annots), _) -> let field_name = get_java_field_name field_name annots in let java_ty = List.assoc_exn field_name java_tys in output_string out (javadoc loc annots " "); fprintf out " public %s %s;\n" java_ty field_name) fields; fprintf out "}\n"; close_out out; env Translate an ` inner ' type i.e. a type that occurs within a record or sum and trans_inner env atd_ty = match atd_ty with | Name (_, (_, name1, _), _) -> (match norm_ty env atd_ty with | Name (_, (_, name2, _), _) -> (* It's a primitive type e.g. int *) (Atdj_names.to_class_name name2, env) | _ -> (Atdj_names.to_class_name name1, env) ) | List (_, sub_atd_ty, _) -> let (ty', env) = trans_inner env sub_atd_ty in ("java.util.ArrayList<" ^ ty' ^ ">", env) | x -> type_not_supported x
null
https://raw.githubusercontent.com/ahrefs/atd/a3964362b9632ab70a5d17df5fcf337bcac3a294/atdj/src/atdj_trans.ml
ocaml
extract_from_edgy_brackets "ab<cd<e>>f";; - : string = "cd<e>" ahem Check whether the field is optional TODO: fail if no default is provided TODO: fail if no default is provided Generate a toJsonBuffer command TODO Check that this is the correct behaviour Generate a toJsonBuffer command for a record field. In the case of an optional field, create a predicate to test whether * the field has its default value. Generate a javadoc comment Assume that code is the name of a field that is defined in the same class ------------------------------------------------------------------------- Don't translate primitive types at the top-level Remove `Inherit values Translate field types Output Java class It's a primitive type e.g. int
open Atd.Import open Atdj_names open Atdj_env open Atdj_util module A = Atd.Ast Calculate the JSON representation of an ATD type . * * Values of sum types t are encoded as either Strings or two - element * JSONArrays , depending upon the arity of the particular constructor . * A nullary constructor C is denoted by the " C " , whilst * an application of a unary constructor C to an ATD value v is denoted by the * JSONArray [ " C " , < v > ] , where < v > is the JSON representation of v. * * Option types other than in optional fields ( e.g. ' ? foo : int option ' ) * are not supported . * * Values of sum types t are encoded as either Strings or two-element * JSONArrays, depending upon the arity of the particular constructor. * A nullary constructor C is denoted by the String "C", whilst * an application of a unary constructor C to an ATD value v is denoted by the * JSONArray ["C", <v>], where <v> is the JSON representation of v. * * Option types other than in optional fields (e.g. '?foo: int option') * are not supported. *) let json_of_atd env atd_ty = let atd_ty = norm_ty ~unwrap_option:true env atd_ty in match atd_ty with Either a String or a two element JSONArray | Record _ -> "JSONObject" | List _ -> "JSONArray" | Name (_, (_, ty, _), _) -> (match ty with | "bool" -> "boolean" | "int" -> "int" | "float" -> "double" | "string" -> "String" | _ -> type_not_supported atd_ty ) | x -> type_not_supported x Calculate the method name required to extract the JSON representation of an * ATD value from either a JSONObject or a JSONArray ( " get " , " opt " , * " getInt " , " optInt " , ... ) * ATD value from either a JSONObject or a JSONArray ("get", "opt", * "getInt", "optInt", ...) *) let get env atd_ty opt = let atd_ty = norm_ty ~unwrap_option:true env atd_ty in let prefix = if opt then "opt" else "get" in let suffix = match atd_ty with | Sum _ -> "" | _ -> String.capitalize_ascii (json_of_atd env atd_ty) in prefix ^ suffix let extract_from_edgy_brackets s = Re.Str.global_replace (Re.Str.regexp "^[^<]*<\\|>[^>]*$") "" s Assignment with translation . Suppose that atd_ty is an ATD type , with * corresponding Java and ( ) JSON types java_ty and json_ty . Then this * function assigns to a variable ` dst ' of type java_ty from a variable ` src ' of * type ` json_ty ' . * corresponding Java and (Javafied) JSON types java_ty and json_ty. Then this * function assigns to a variable `dst' of type java_ty from a variable `src' of * type `json_ty'. *) let rec assign env opt_dst src java_ty atd_ty indent = let atd_ty = norm_ty env atd_ty in match opt_dst with | None -> (match atd_ty with | Sum _ -> sprintf "new %s(%s)" java_ty src | Record _ -> sprintf "new %s(%s)" java_ty src | Name (_, (_, ty, _), _) -> (match ty with | "bool" | "int" | "float" | "string" -> src | _ -> type_not_supported atd_ty ) | x -> type_not_supported x ) | Some dst -> (match atd_ty with | Sum _ -> sprintf "%s%s = new %s(%s);\n" indent dst java_ty src | Record _ -> sprintf "%s%s = new %s(%s);\n" indent dst java_ty src | List (_, sub_ty, _) -> let sub_expr = assign env None "_tmp" java_sub_ty sub_ty "" in sprintf "%s%s = new %s();\n" indent dst java_ty ^ sprintf "%sfor (int _i = 0; _i < %s.length(); ++_i) {\n" indent src ^ sprintf "%s %s _tmp = %s.%s(_i);\n" indent (json_of_atd env sub_ty) src (get env sub_ty false) ^ sprintf "%s %s.add(%s);\n" indent dst sub_expr ^ sprintf "%s}\n" indent | Name (_, (_, ty, _), _) -> (match ty with | "bool" | "int" | "float" | "string" -> sprintf "%s%s = %s;\n" indent dst src | _ -> type_not_supported atd_ty ) | x -> type_not_supported x ) Assign from an object field , with support for optional fields . The are two * kinds of optional fields : ` With_default ( ~ ) and ` Optional ( ? ) . For both * kinds , we return the following values if the field is absent : * * bool - > false * int - > 0 * float - > 0.0 * string - > " " * list - > [ ] * option - > None * * Optional fields of record and sum types are not supported . They are * treated as required fields . * * Fields of the ` Optional kind extend this behaviour by automatically lifting * values of type t to option t by wrapping within a ` Some ' . * Hence ` Optional may only be applied to fields of type option t. * Note that absent fields are still * assigned ` None ' , as before . * * For ` With_default fields , of types bool , int , float , string and list , we use * the org.json opt methods to extract the field . These methods already return * the appropriate defaults if field is absent . For option types , we manually * check for the field and manually create a default . If the field is present , * then we wrap its values as necessary . * kinds of optional fields: `With_default (~) and `Optional (?). For both * kinds, we return the following values if the field is absent: * * bool -> false * int -> 0 * float -> 0.0 * string -> "" * list -> [] * option -> None * * Optional fields of record and sum types are not supported. They are * treated as required fields. * * Fields of the `Optional kind extend this behaviour by automatically lifting * values of type t to option t by wrapping within a `Some'. * Hence `Optional may only be applied to fields of type option t. * Note that absent fields are still * assigned `None', as before. * * For `With_default fields, of types bool, int, float, string and list, we use * the org.json opt methods to extract the field. These methods already return * the appropriate defaults if field is absent. For option types, we manually * check for the field and manually create a default. If the field is present, * then we wrap its values as necessary. *) let assign_field env (`Field (_, (atd_field_name, kind, annots), atd_ty)) java_ty = let json_field_name = get_json_field_name atd_field_name annots in let field_name = get_java_field_name atd_field_name annots in let is_opt = match kind with | A.Optional | With_default -> true | Required -> false in let src = sprintf "jo.%s(\"%s\")" (get env atd_ty is_opt) json_field_name in if not is_opt then assign env (Some field_name) src java_ty atd_ty " " else let mk_else = function | Some default -> sprintf " } else {\n %s = %s;\n }\n" field_name default | None -> " }\n" in let opt_set_default = match kind with | A.With_default -> (match norm_ty ~unwrap_option:true env atd_ty with | Name (_, (_, name, _), _) -> (match name with | "bool" -> mk_else (Some "false") | "int" -> mk_else (Some "0") | "float" -> mk_else (Some "0.0") | "string" -> mk_else (Some "\"\"") ) | List _ -> java_ty is supposed to be of the form " ArrayList < ... > " mk_else (Some (sprintf "new %s()" java_ty)) | _ -> ) | _ -> mk_else None in let atd_ty = norm_ty ~unwrap_option:true env atd_ty in sprintf " if (jo.has(\"%s\")) {\n" json_field_name ^ assign env (Some field_name) src java_ty atd_ty " " ^ opt_set_default let rec to_string env id atd_ty indent = let atd_ty = norm_ty env atd_ty in match atd_ty with | List (_, atd_sub_ty, _) -> sprintf "%s_out.append(\"[\");\n" indent ^ sprintf "%sfor (int i = 0; i < %s.size(); ++i) {\n" indent id ^ to_string env (id ^ ".get(i)") atd_sub_ty (indent ^ " ") ^ sprintf "%s if (i < %s.size() - 1)\n" indent id ^ sprintf "%s _out.append(\",\");\n" indent ^ sprintf "%s}\n" indent ^ sprintf "%s_out.append(\"]\");\n" indent | Name (_, (_, "string", _), _) -> sprintf "%sUtil.writeJsonString(_out, %s);\n" indent id | Name _ -> sprintf "%s_out.append(String.valueOf(%s));\n" indent id | _ -> sprintf "%s%s.toJsonBuffer(_out);\n" indent id let to_string_field env = function | (`Field (_, (atd_field_name, kind, annots), atd_ty)) -> let json_field_name = get_json_field_name atd_field_name annots in let field_name = get_java_field_name atd_field_name annots in let atd_ty = norm_ty ~unwrap_option:true env atd_ty in let if_part = sprintf " if (%s != null) { if (_isFirst) _isFirst = false; else _out.append(\",\"); _out.append(\"\\\"%s\\\":\"); %s } " field_name json_field_name (to_string env field_name atd_ty " ") in let else_part = let is_opt = match kind with | A.Optional | With_default -> true | Required -> false in if is_opt then "" else sprintf " \ else throw new JSONException(\"Uninitialized field %s\"); " field_name in if_part ^ else_part let javadoc loc annots indent = let from_inline_text text = indent ^ " * " ^ text ^ "\n" in let from_inline_code code = indent ^ " * {@link #" ^ code ^ "}\n" in let from_doc_para = List.fold_left (fun acc -> function | Atd.Doc.Text text -> (from_inline_text text) :: acc | Code code -> (from_inline_code code) :: acc ) in let from_doc = List.fold_left (fun acc -> function | Atd.Doc.Paragraph para -> from_doc_para acc para | Pre _ -> failwith "Preformatted doc blocks are not supported" ) [] in (match Atd.Doc.get_doc loc annots with | Some doc -> let header = indent ^ "/**\n" in let footer = indent ^ " */\n" in let body = String.concat "" (List.rev (from_doc doc)) in header ^ body ^ footer | None -> "" ) Translation of ATD types into Java types For option , sum and record types , we generate a Java class . Each such class * implements the following interface : * * interface Atdj { * String toJson ( ) throws JSONException ; * void toJsonBuffer(StringBuilder out ) throws JSONException ; * } * * The ( ) method outputs a JSON representation of the * associated value . * * Each class also has a constructor for a JSON string as well as a * constructor from the corresponding org.json type ( see json_of_atd , above ) . * * We do not generate classes for types bool , int , float , string and list ; * instead we ` inline ' these types directly into the class in which they * occur . We do this so that the Java programmer can access such values * directly , thereby avoiding the overhead of having to manually unbox each such * value upon access . * implements the following interface: * * interface Atdj { * String toJson() throws JSONException; * void toJsonBuffer(StringBuilder out) throws JSONException; * } * * The toJson() method outputs a JSON representation of the * associated value. * * Each class also has a String constructor for a JSON string as well as a * constructor from the corresponding org.json type (see json_of_atd, above). * * We do not generate classes for types bool, int, float, string and list; * instead we `inline' these types directly into the class in which they * occur. We do this so that the Java programmer can access such values * directly, thereby avoiding the overhead of having to manually unbox each such * value upon access. *) let open_class env cname = let out = open_out (env.package_dir ^ "/" ^ cname ^ ".java") in fprintf out "\ // Automatically generated; do not edit package %s; import org.json.*; " env.package; out let rec trans_module env items = List.fold_left trans_outer env items and trans_outer env (A.Type (_, (name, _, _), atd_ty)) = match unwrap atd_ty with | Sum (loc, v, a) -> trans_sum name env (loc, v, a) | Record (loc, v, a) -> trans_record name env (loc, v, a) | Name (_, (_, _name, _), _) -> env | x -> type_not_supported x Translation of sum types . For a sum type * * type ty = Foo | Bar of whatever * * we generate a class implemented in Ty.java and an enum defined * in a separate file TyTag.java . * * type ty = Foo | Bar of whatever * * we generate a class Ty implemented in Ty.java and an enum TyEnum defined * in a separate file TyTag.java. *) and trans_sum my_name env (_, vars, _) = let class_name = Atdj_names.to_class_name my_name in let cases = List.map (fun (x : A.variant) -> match x with | Variant (_, (atd_name, an), opt_ty) -> let json_name = get_json_variant_name atd_name an in let func_name, enum_name, field_name = get_java_variant_names atd_name an in let opt_java_ty = opt_ty |> Option.map (fun ty -> let (java_ty, _) = trans_inner env (unwrap_option env ty) in (ty, java_ty) ) in (json_name, func_name, enum_name, field_name, opt_java_ty) | Inherit _ -> assert false ) vars in let tags = List.map (fun (_, _, enum_name, _, _) -> enum_name) cases in let out = open_class env class_name in fprintf out "\ /** * Construct objects of type %s. */ public class %s { Tag t = null; public %s() { } public Tag tag() { return t; } " my_name class_name class_name; fprintf out " /** * Define tags for sum type %s. */ public enum Tag { %s } " my_name (String.concat ", " tags); fprintf out " public %s(Object o) throws JSONException { String tag = Util.extractTag(o); %a throw new JSONException(\"Invalid tag: \" + tag); } " class_name (fun out l -> List.iter (fun (json_name, _func_name, enum_name, field_name, opt_ty) -> match opt_ty with | None -> fprintf out " \ if (tag.equals(\"%s\")) t = Tag.%s; else" TODO : java - string - escape this enum_name | Some (atd_ty, java_ty) -> let src = sprintf "((JSONArray)o).%s(1)" (get env atd_ty false) in let set_value = assign env (Some ("field_" ^ field_name)) src java_ty atd_ty " " in fprintf out " \ if (tag.equals(\"%s\")) { %s t = Tag.%s; } else" TODO : java - string - escape this set_value enum_name ) l ) cases; List.iter (fun (_, func_name, enum_name, field_name, opt_ty) -> match opt_ty with | None -> fprintf out " public void set%s() { /* TODO: clear previously-set field and avoid memory leak */ t = Tag.%s; } " func_name enum_name; | Some (_atd_ty, java_ty) -> fprintf out " %s field_%s = null; public void set%s(%s x) { /* TODO: clear previously-set field in order to avoid memory leak */ t = Tag.%s; field_%s = x; } public %s get%s() { if (t == Tag.%s) return field_%s; else return null; } " java_ty field_name func_name java_ty enum_name field_name java_ty func_name enum_name field_name; ) cases; fprintf out " public void toJsonBuffer(StringBuilder _out) throws JSONException { if (t == null) throw new JSONException(\"Uninitialized %s\"); else { switch(t) {%a default: break; /* unused; keeps compiler happy */ } } } public String toJson() throws JSONException { StringBuilder out = new StringBuilder(128); toJsonBuffer(out); return out.toString(); } " class_name (fun out l -> List.iter (fun (json_name, _func_name, enum_name, field_name, opt_ty) -> match opt_ty with | None -> fprintf out " case %s: _out.append(\"\\\"%s\\\"\"); break;" enum_name TODO : java - string - escape | Some (atd_ty, _) -> fprintf out " case %s: _out.append(\"[\\\"%s\\\",\"); %s _out.append(\"]\"); break;" enum_name json_name (to_string env ("field_" ^ field_name) atd_ty " ") ) l ) cases; fprintf out "}\n"; close_out out; env Translate a record into a Java class . Each record field becomes a field * within the class . * within the class. *) and trans_record my_name env (loc, fields, annots) = let fields = List.map (function | `Field _ as f -> f | `Inherit _ -> assert false ) fields in let (java_tys, env) = List.fold_left (fun (java_tys, env) -> function | `Field (_, (field_name, _, annots), atd_ty) -> let field_name = get_java_field_name field_name annots in let (java_ty, env) = trans_inner env (unwrap_option env atd_ty) in ((field_name, java_ty) :: java_tys, env) ) ([], env) fields in let java_tys = List.rev java_tys in let class_name = Atdj_names.to_class_name my_name in let out = open_class env class_name in Javadoc output_string out (javadoc loc annots ""); fprintf out "\ public class %s implements Atdj { /** * Construct from a fresh record with null fields. */ public %s() { } /** * Construct from a JSON string. */ public %s(String s) throws JSONException { this(new JSONObject(s)); } %s(JSONObject jo) throws JSONException { " class_name class_name class_name class_name; let env = List.fold_left (fun env (`Field (_, (field_name, _, annots), _) as field) -> let field_name = get_java_field_name field_name annots in let cmd = assign_field env field (List.assoc_exn field_name java_tys) in fprintf out "%s" cmd; env ) env fields in fprintf out "\n \ } public void toJsonBuffer(StringBuilder _out) throws JSONException { boolean _isFirst = true; _out.append(\"{\");%a _out.append(\"}\"); } public String toJson() throws JSONException { StringBuilder out = new StringBuilder(128); toJsonBuffer(out); return out.toString(); } " (fun out l -> List.iter (fun field -> output_string out (to_string_field env field) ) l; ) fields; List.iter (function `Field (loc, (field_name, _, annots), _) -> let field_name = get_java_field_name field_name annots in let java_ty = List.assoc_exn field_name java_tys in output_string out (javadoc loc annots " "); fprintf out " public %s %s;\n" java_ty field_name) fields; fprintf out "}\n"; close_out out; env Translate an ` inner ' type i.e. a type that occurs within a record or sum and trans_inner env atd_ty = match atd_ty with | Name (_, (_, name1, _), _) -> (match norm_ty env atd_ty with | Name (_, (_, name2, _), _) -> (Atdj_names.to_class_name name2, env) | _ -> (Atdj_names.to_class_name name1, env) ) | List (_, sub_atd_ty, _) -> let (ty', env) = trans_inner env sub_atd_ty in ("java.util.ArrayList<" ^ ty' ^ ">", env) | x -> type_not_supported x
c0980ea6f4d4d79f27698f6bdf02996b6e505d56b0273813a95fc134bf87a6dc
haskell-compat/deriving-compat
Internal.hs
| Module : Data . Ix . Deriving . Internal Copyright : ( C ) 2015 - 2017 License : BSD - style ( see the file LICENSE ) Maintainer : Portability : Template Haskell Exports functions to mechanically derive ' Ix ' instances . Note : this is an internal module , and as such , the API presented here is not guaranteed to be stable , even between minor releases of this library . Module: Data.Ix.Deriving.Internal Copyright: (C) 2015-2017 Ryan Scott License: BSD-style (see the file LICENSE) Maintainer: Ryan Scott Portability: Template Haskell Exports functions to mechanically derive 'Ix' instances. Note: this is an internal module, and as such, the API presented here is not guaranteed to be stable, even between minor releases of this library. -} module Data.Ix.Deriving.Internal ( -- * 'Ix' deriveIx , makeRange , makeUnsafeIndex , makeInRange ) where import Data.Deriving.Internal import Language.Haskell.TH.Datatype import Language.Haskell.TH.Lib import Language.Haskell.TH.Syntax ------------------------------------------------------------------------------- -- Code generation ------------------------------------------------------------------------------- -- | Generates a 'Ix' instance declaration for the given data type or data -- family instance. deriveIx :: Name -> Q [Dec] deriveIx name = do info <- reifyDatatype name case info of DatatypeInfo { datatypeContext = ctxt , datatypeName = parentName , datatypeInstTypes = instTypes , datatypeVariant = variant , datatypeCons = cons } -> do (instanceCxt, instanceType) <- buildTypeInstance IxClass parentName ctxt instTypes variant (:[]) `fmap` instanceD (return instanceCxt) (return instanceType) (ixFunDecs parentName instanceType cons) -- | Generates a lambda expression which behaves like 'range' (without -- requiring an 'Ix' instance). makeRange :: Name -> Q Exp makeRange = makeIxFun Range -- | Generates a lambda expression which behaves like 'unsafeIndex' (without -- requiring an 'Ix' instance). makeUnsafeIndex :: Name -> Q Exp makeUnsafeIndex = makeIxFun UnsafeIndex -- | Generates a lambda expression which behaves like 'inRange' (without -- requiring an 'Ix' instance). makeInRange :: Name -> Q Exp makeInRange = makeIxFun InRange -- | Generates method declarations for an 'Ix' instance. ixFunDecs :: Name -> Type -> [ConstructorInfo] -> [Q Dec] ixFunDecs tyName ty cons = [ makeFunD Range , makeFunD UnsafeIndex , makeFunD InRange ] where makeFunD :: IxFun -> Q Dec makeFunD ixf = funD (ixFunName ixf) [ clause [] (normalB $ makeIxFunForCons ixf tyName ty cons) [] ] | Generates a lambda expression which behaves like the IxFun argument . makeIxFun :: IxFun -> Name -> Q Exp makeIxFun ixf name = do info <- reifyDatatype name case info of DatatypeInfo { datatypeContext = ctxt , datatypeName = parentName , datatypeInstTypes = instTypes , datatypeVariant = variant , datatypeCons = cons } -> do (_, instanceType) <- buildTypeInstance IxClass parentName ctxt instTypes variant makeIxFunForCons ixf parentName instanceType cons -- | Generates a lambda expression for an 'Ix' method for the -- given constructors. All constructors must be from the same type. makeIxFunForCons :: IxFun -> Name -> Type -> [ConstructorInfo] -> Q Exp makeIxFunForCons _ _ _ [] = noConstructorsError makeIxFunForCons ixf tyName ty cons | not (isProduct || isEnumeration) = enumerationOrProductError $ nameBase tyName | isEnumeration = case ixf of Range -> do a <- newName "a" aHash <- newName "a#" b <- newName "b" bHash <- newName "b#" lamE [tupP [varP a, varP b]] $ untagExpr [(a, aHash)] $ untagExpr [(b, bHash)] $ appE (varE mapValName `appE` tag2Con) $ enumFromToExpr (conE iHashDataName `appE` varE aHash) (conE iHashDataName `appE` varE bHash) UnsafeIndex -> do a <- newName "a" aHash <- newName "a#" c <- newName "c" cHash <- newName "c#" dHash <- newName "d#" lamE [tupP [varP a, wildP], varP c] $ untagExpr [(a, aHash)] $ untagExpr [(c, cHash)] $ caseE (infixApp (varE cHash) (varE minusIntHashValName) (varE aHash)) [ match (varP dHash) (normalB $ conE iHashDataName `appE` varE dHash) [] ] InRange -> do a <- newName "a" aHash <- newName "a#" b <- newName "b" bHash <- newName "b#" c <- newName "c" cHash <- newName "c#" lamE [tupP [varP a, varP b], varP c] $ untagExpr [(a, aHash)] $ untagExpr [(b, bHash)] $ untagExpr [(c, cHash)] $ appsE [ varE andValName , primOpAppExpr (varE cHash) geIntHashValName (varE aHash) , primOpAppExpr (varE cHash) leIntHashValName (varE bHash) ] | otherwise -- It's a product type = do let con :: ConstructorInfo con = head cons conName :: Name conName = constructorName con conFields :: Int conFields = conArity con as <- newNameList "a" conFields bs <- newNameList "b" conFields cs <- newNameList "c" conFields let conPat :: [Name] -> Q Pat conPat = conP conName . map varP conExpr :: Q Exp conExpr = appsE $ conE conName : map varE cs case ixf of Range -> lamE [tupP [conPat as, conPat bs]] $ compE $ stmts ++ [noBindS conExpr] where stmts :: [Q Stmt] stmts = zipWith3 mkQual as bs cs mkQual :: Name -> Name -> Name -> Q Stmt mkQual a b c = bindS (varP c) $ varE rangeValName `appE` tupE [varE a, varE b] UnsafeIndex -> lamE [tupP [conPat as, conPat bs], conPat cs] $ mkUnsafeIndex $ reverse $ zip3 as bs cs where mkUnsafeIndex :: [(Name, Name, Name)] -> Q Exp mkUnsafeIndex [] = integerE 0 mkUnsafeIndex [(l, u, i)] = mkOne l u i mkUnsafeIndex ((l, u, i):rest) = infixApp (mkOne l u i) (varE plusValName) (infixApp (varE unsafeRangeSizeValName `appE` tupE [varE l, varE u]) (varE timesValName) (mkUnsafeIndex rest)) mkOne :: Name -> Name -> Name -> Q Exp mkOne l u i = varE unsafeIndexValName `appE` tupE [varE l, varE u] `appE` varE i InRange -> lamE [tupP [conPat as, conPat bs], conPat cs] $ if conFields == 0 then conE trueDataName else foldl1 andExpr $ zipWith3 mkInRange as bs cs where andExpr :: Q Exp -> Q Exp -> Q Exp andExpr a b = infixApp a (varE andValName) b mkInRange :: Name -> Name -> Name -> Q Exp mkInRange a b c = varE inRangeValName `appE` tupE [varE a, varE b] `appE` varE c where isProduct, isEnumeration :: Bool isProduct = isProductType cons isEnumeration = isEnumerationType cons tag2Con :: Q Exp tag2Con = tag2ConExpr $ removeClassApp ty ------------------------------------------------------------------------------- -- Class-specific constants ------------------------------------------------------------------------------- There 's only one Ix variant ! data IxClass = IxClass instance ClassRep IxClass where arity _ = 0 allowExQuant _ = True fullClassName _ = ixTypeName classConstraint _ 0 = Just ixTypeName classConstraint _ _ = Nothing -- | A representation of which function is being generated. data IxFun = Range | UnsafeIndex | InRange deriving Show ixFunName :: IxFun -> Name ixFunName Range = rangeValName ixFunName UnsafeIndex = unsafeIndexValName ixFunName InRange = inRangeValName
null
https://raw.githubusercontent.com/haskell-compat/deriving-compat/23e62c003325258e925e6c2fe7e46fafdeaf199a/src/Data/Ix/Deriving/Internal.hs
haskell
* 'Ix' ----------------------------------------------------------------------------- Code generation ----------------------------------------------------------------------------- | Generates a 'Ix' instance declaration for the given data type or data family instance. | Generates a lambda expression which behaves like 'range' (without requiring an 'Ix' instance). | Generates a lambda expression which behaves like 'unsafeIndex' (without requiring an 'Ix' instance). | Generates a lambda expression which behaves like 'inRange' (without requiring an 'Ix' instance). | Generates method declarations for an 'Ix' instance. | Generates a lambda expression for an 'Ix' method for the given constructors. All constructors must be from the same type. It's a product type ----------------------------------------------------------------------------- Class-specific constants ----------------------------------------------------------------------------- | A representation of which function is being generated.
| Module : Data . Ix . Deriving . Internal Copyright : ( C ) 2015 - 2017 License : BSD - style ( see the file LICENSE ) Maintainer : Portability : Template Haskell Exports functions to mechanically derive ' Ix ' instances . Note : this is an internal module , and as such , the API presented here is not guaranteed to be stable , even between minor releases of this library . Module: Data.Ix.Deriving.Internal Copyright: (C) 2015-2017 Ryan Scott License: BSD-style (see the file LICENSE) Maintainer: Ryan Scott Portability: Template Haskell Exports functions to mechanically derive 'Ix' instances. Note: this is an internal module, and as such, the API presented here is not guaranteed to be stable, even between minor releases of this library. -} module Data.Ix.Deriving.Internal ( deriveIx , makeRange , makeUnsafeIndex , makeInRange ) where import Data.Deriving.Internal import Language.Haskell.TH.Datatype import Language.Haskell.TH.Lib import Language.Haskell.TH.Syntax deriveIx :: Name -> Q [Dec] deriveIx name = do info <- reifyDatatype name case info of DatatypeInfo { datatypeContext = ctxt , datatypeName = parentName , datatypeInstTypes = instTypes , datatypeVariant = variant , datatypeCons = cons } -> do (instanceCxt, instanceType) <- buildTypeInstance IxClass parentName ctxt instTypes variant (:[]) `fmap` instanceD (return instanceCxt) (return instanceType) (ixFunDecs parentName instanceType cons) makeRange :: Name -> Q Exp makeRange = makeIxFun Range makeUnsafeIndex :: Name -> Q Exp makeUnsafeIndex = makeIxFun UnsafeIndex makeInRange :: Name -> Q Exp makeInRange = makeIxFun InRange ixFunDecs :: Name -> Type -> [ConstructorInfo] -> [Q Dec] ixFunDecs tyName ty cons = [ makeFunD Range , makeFunD UnsafeIndex , makeFunD InRange ] where makeFunD :: IxFun -> Q Dec makeFunD ixf = funD (ixFunName ixf) [ clause [] (normalB $ makeIxFunForCons ixf tyName ty cons) [] ] | Generates a lambda expression which behaves like the IxFun argument . makeIxFun :: IxFun -> Name -> Q Exp makeIxFun ixf name = do info <- reifyDatatype name case info of DatatypeInfo { datatypeContext = ctxt , datatypeName = parentName , datatypeInstTypes = instTypes , datatypeVariant = variant , datatypeCons = cons } -> do (_, instanceType) <- buildTypeInstance IxClass parentName ctxt instTypes variant makeIxFunForCons ixf parentName instanceType cons makeIxFunForCons :: IxFun -> Name -> Type -> [ConstructorInfo] -> Q Exp makeIxFunForCons _ _ _ [] = noConstructorsError makeIxFunForCons ixf tyName ty cons | not (isProduct || isEnumeration) = enumerationOrProductError $ nameBase tyName | isEnumeration = case ixf of Range -> do a <- newName "a" aHash <- newName "a#" b <- newName "b" bHash <- newName "b#" lamE [tupP [varP a, varP b]] $ untagExpr [(a, aHash)] $ untagExpr [(b, bHash)] $ appE (varE mapValName `appE` tag2Con) $ enumFromToExpr (conE iHashDataName `appE` varE aHash) (conE iHashDataName `appE` varE bHash) UnsafeIndex -> do a <- newName "a" aHash <- newName "a#" c <- newName "c" cHash <- newName "c#" dHash <- newName "d#" lamE [tupP [varP a, wildP], varP c] $ untagExpr [(a, aHash)] $ untagExpr [(c, cHash)] $ caseE (infixApp (varE cHash) (varE minusIntHashValName) (varE aHash)) [ match (varP dHash) (normalB $ conE iHashDataName `appE` varE dHash) [] ] InRange -> do a <- newName "a" aHash <- newName "a#" b <- newName "b" bHash <- newName "b#" c <- newName "c" cHash <- newName "c#" lamE [tupP [varP a, varP b], varP c] $ untagExpr [(a, aHash)] $ untagExpr [(b, bHash)] $ untagExpr [(c, cHash)] $ appsE [ varE andValName , primOpAppExpr (varE cHash) geIntHashValName (varE aHash) , primOpAppExpr (varE cHash) leIntHashValName (varE bHash) ] = do let con :: ConstructorInfo con = head cons conName :: Name conName = constructorName con conFields :: Int conFields = conArity con as <- newNameList "a" conFields bs <- newNameList "b" conFields cs <- newNameList "c" conFields let conPat :: [Name] -> Q Pat conPat = conP conName . map varP conExpr :: Q Exp conExpr = appsE $ conE conName : map varE cs case ixf of Range -> lamE [tupP [conPat as, conPat bs]] $ compE $ stmts ++ [noBindS conExpr] where stmts :: [Q Stmt] stmts = zipWith3 mkQual as bs cs mkQual :: Name -> Name -> Name -> Q Stmt mkQual a b c = bindS (varP c) $ varE rangeValName `appE` tupE [varE a, varE b] UnsafeIndex -> lamE [tupP [conPat as, conPat bs], conPat cs] $ mkUnsafeIndex $ reverse $ zip3 as bs cs where mkUnsafeIndex :: [(Name, Name, Name)] -> Q Exp mkUnsafeIndex [] = integerE 0 mkUnsafeIndex [(l, u, i)] = mkOne l u i mkUnsafeIndex ((l, u, i):rest) = infixApp (mkOne l u i) (varE plusValName) (infixApp (varE unsafeRangeSizeValName `appE` tupE [varE l, varE u]) (varE timesValName) (mkUnsafeIndex rest)) mkOne :: Name -> Name -> Name -> Q Exp mkOne l u i = varE unsafeIndexValName `appE` tupE [varE l, varE u] `appE` varE i InRange -> lamE [tupP [conPat as, conPat bs], conPat cs] $ if conFields == 0 then conE trueDataName else foldl1 andExpr $ zipWith3 mkInRange as bs cs where andExpr :: Q Exp -> Q Exp -> Q Exp andExpr a b = infixApp a (varE andValName) b mkInRange :: Name -> Name -> Name -> Q Exp mkInRange a b c = varE inRangeValName `appE` tupE [varE a, varE b] `appE` varE c where isProduct, isEnumeration :: Bool isProduct = isProductType cons isEnumeration = isEnumerationType cons tag2Con :: Q Exp tag2Con = tag2ConExpr $ removeClassApp ty There 's only one Ix variant ! data IxClass = IxClass instance ClassRep IxClass where arity _ = 0 allowExQuant _ = True fullClassName _ = ixTypeName classConstraint _ 0 = Just ixTypeName classConstraint _ _ = Nothing data IxFun = Range | UnsafeIndex | InRange deriving Show ixFunName :: IxFun -> Name ixFunName Range = rangeValName ixFunName UnsafeIndex = unsafeIndexValName ixFunName InRange = inRangeValName
8db44ef3a94f2c6686de2f195e44fc7ccde469e72af7a8a82f78d9f0e25d8757
keechma/keechma
history_router.cljs
(ns keechma.app-state.history-router (:require [keechma.app-state.core :as core :refer [IRouter]] [router.core :as router] [goog.events :as events] [goog.history.EventType :as EventType] [cljs.core.async :refer [put!]] [clojure.string :as str]) (:import goog.history.Event goog.history.Html5History goog.Uri)) (def supported-redirect-actions #{:push :replace :back}) (defn get-redirect-action [action] (if (contains? supported-redirect-actions action) action :push)) (defn make-urlchange-dispatcher [] (let [handlers (atom []) main-handler (fn [_] (doseq [h @handlers] (h (.-href js/location)))) bind-main-handler (fn [] (when (= 1 (count @handlers)) (.addEventListener js/window "popstate" main-handler))) unbind-main-handler (fn [] (when (zero? (count @handlers)) (.removeEventListener js/window "popstate" main-handler)))] {:handlers-count #(count @handlers) :bind (fn [handler] (swap! handlers conj handler) (bind-main-handler)) :unbind (fn [handler] (swap! handlers (fn [h] (filter #(not= handler %) h))) (unbind-main-handler)) :replace (fn [href] (.replaceState js/history nil "" href) (doseq [h @handlers] (h href))) :push (fn [href] (.pushState js/history nil "" href) (doseq [h @handlers] (h href)))})) (def urlchange-dispatcher (make-urlchange-dispatcher)) (defn url-prefix [base-href] (str (.-origin js/location) base-href)) (defn route-url [url base-href] (let [prefix (url-prefix base-href)] (first (str/split (subs url (count prefix) (count url)) #"#")))) (defn link? [el] (and (.-href el) (= "a" (str/lower-case (.-tagName el))))) (defn link-el [el] (loop [current-el el] (if (link? current-el) current-el (when-let [parent (.-parentNode current-el)] (recur parent))))) (defn current-target-self? [el] (contains? #{"" "_self"} (.-target el))) (defn left-button-clicked? [e] (= 0 (.-button e))) (defn mod-key-pressed? [e] (or (.-altKey e) (.-shiftKey e) (.-ctrlKey e) (.-metaKey e))) (defn link-has-prefixed-url? [el base-href] (str/starts-with? (.-href el) (url-prefix base-href))) (defn same-href? [el] (= (.-href el) (.-href js/location))) (defn should-href-pass-through? [href] (let [[current current-hash] (str/split (.-href js/location) #"#") [next next-hash] (str/split href #"#")] (and (= current next) (not= current-hash next-hash)))) (defn make-url [routes base-href params] (let [hash (.-hash js/location)] (str base-href (router/map->url routes params) hash))) (defn add-trailing-slash [base-href] (if (str/ends-with? base-href "/") base-href (str base-href "/"))) (defn add-leading-slash [base-href] (if (str/starts-with? base-href "/") base-href (str "/" base-href))) (defn process-base-href [base-href] (-> base-href (add-trailing-slash) (add-leading-slash))) (defn link-has-data-replace-state? [el] (and (link? el) (boolean (.getAttribute el "data-replace-state")))) (defrecord HistoryRouter [routes routes-chan base-href app-db] IRouter (start! [this] (let [handler (fn [href] (put! routes-chan (router/url->map routes (route-url href base-href))))] ((:bind urlchange-dispatcher) handler) (swap! app-db assoc :route (router/url->map routes (route-url (.-href js/location) base-href))) (assoc this :urlchange-handler handler))) (stop! [this] ((:unbind urlchange-dispatcher) (:urlchange-handler this))) (redirect! [this params] (core/redirect! this params :push)) (redirect! [this params action] (let [redirect-action (get-redirect-action action)] (if (= :back redirect-action) (.back js/history) (let [redirect-fn (get urlchange-dispatcher redirect-action)] (redirect-fn (str (.-origin js/location) (make-url routes base-href params))))))) (wrap-component [this] (let [click-handler (fn [e] (when-let [el (link-el (.-target e))] (let [href (.-href el)] (when (and (current-target-self? el) (left-button-clicked? e) (not (mod-key-pressed? e)) (link-has-prefixed-url? el base-href)) (when-not (should-href-pass-through? href) (let [redirect-fn (get urlchange-dispatcher (if (link-has-data-replace-state? el) :replace :push))] (redirect-fn href) (.preventDefault e) (.stopPropagation e)))))))] (fn [& children] (into [:div {:on-click click-handler}] children)))) (url [this params] (make-url routes base-href params)) (linkable? [this] true)) (defn constructor [routes routes-chan state] (let [base-href (process-base-href (or (:base-href state) "/"))] (core/start! (->HistoryRouter (router/expand-routes routes) routes-chan base-href (:app-db state)))))
null
https://raw.githubusercontent.com/keechma/keechma/8996bf401495e1e0d89bbab8c3c3b9fe43f32116/src/keechma/app_state/history_router.cljs
clojure
(ns keechma.app-state.history-router (:require [keechma.app-state.core :as core :refer [IRouter]] [router.core :as router] [goog.events :as events] [goog.history.EventType :as EventType] [cljs.core.async :refer [put!]] [clojure.string :as str]) (:import goog.history.Event goog.history.Html5History goog.Uri)) (def supported-redirect-actions #{:push :replace :back}) (defn get-redirect-action [action] (if (contains? supported-redirect-actions action) action :push)) (defn make-urlchange-dispatcher [] (let [handlers (atom []) main-handler (fn [_] (doseq [h @handlers] (h (.-href js/location)))) bind-main-handler (fn [] (when (= 1 (count @handlers)) (.addEventListener js/window "popstate" main-handler))) unbind-main-handler (fn [] (when (zero? (count @handlers)) (.removeEventListener js/window "popstate" main-handler)))] {:handlers-count #(count @handlers) :bind (fn [handler] (swap! handlers conj handler) (bind-main-handler)) :unbind (fn [handler] (swap! handlers (fn [h] (filter #(not= handler %) h))) (unbind-main-handler)) :replace (fn [href] (.replaceState js/history nil "" href) (doseq [h @handlers] (h href))) :push (fn [href] (.pushState js/history nil "" href) (doseq [h @handlers] (h href)))})) (def urlchange-dispatcher (make-urlchange-dispatcher)) (defn url-prefix [base-href] (str (.-origin js/location) base-href)) (defn route-url [url base-href] (let [prefix (url-prefix base-href)] (first (str/split (subs url (count prefix) (count url)) #"#")))) (defn link? [el] (and (.-href el) (= "a" (str/lower-case (.-tagName el))))) (defn link-el [el] (loop [current-el el] (if (link? current-el) current-el (when-let [parent (.-parentNode current-el)] (recur parent))))) (defn current-target-self? [el] (contains? #{"" "_self"} (.-target el))) (defn left-button-clicked? [e] (= 0 (.-button e))) (defn mod-key-pressed? [e] (or (.-altKey e) (.-shiftKey e) (.-ctrlKey e) (.-metaKey e))) (defn link-has-prefixed-url? [el base-href] (str/starts-with? (.-href el) (url-prefix base-href))) (defn same-href? [el] (= (.-href el) (.-href js/location))) (defn should-href-pass-through? [href] (let [[current current-hash] (str/split (.-href js/location) #"#") [next next-hash] (str/split href #"#")] (and (= current next) (not= current-hash next-hash)))) (defn make-url [routes base-href params] (let [hash (.-hash js/location)] (str base-href (router/map->url routes params) hash))) (defn add-trailing-slash [base-href] (if (str/ends-with? base-href "/") base-href (str base-href "/"))) (defn add-leading-slash [base-href] (if (str/starts-with? base-href "/") base-href (str "/" base-href))) (defn process-base-href [base-href] (-> base-href (add-trailing-slash) (add-leading-slash))) (defn link-has-data-replace-state? [el] (and (link? el) (boolean (.getAttribute el "data-replace-state")))) (defrecord HistoryRouter [routes routes-chan base-href app-db] IRouter (start! [this] (let [handler (fn [href] (put! routes-chan (router/url->map routes (route-url href base-href))))] ((:bind urlchange-dispatcher) handler) (swap! app-db assoc :route (router/url->map routes (route-url (.-href js/location) base-href))) (assoc this :urlchange-handler handler))) (stop! [this] ((:unbind urlchange-dispatcher) (:urlchange-handler this))) (redirect! [this params] (core/redirect! this params :push)) (redirect! [this params action] (let [redirect-action (get-redirect-action action)] (if (= :back redirect-action) (.back js/history) (let [redirect-fn (get urlchange-dispatcher redirect-action)] (redirect-fn (str (.-origin js/location) (make-url routes base-href params))))))) (wrap-component [this] (let [click-handler (fn [e] (when-let [el (link-el (.-target e))] (let [href (.-href el)] (when (and (current-target-self? el) (left-button-clicked? e) (not (mod-key-pressed? e)) (link-has-prefixed-url? el base-href)) (when-not (should-href-pass-through? href) (let [redirect-fn (get urlchange-dispatcher (if (link-has-data-replace-state? el) :replace :push))] (redirect-fn href) (.preventDefault e) (.stopPropagation e)))))))] (fn [& children] (into [:div {:on-click click-handler}] children)))) (url [this params] (make-url routes base-href params)) (linkable? [this] true)) (defn constructor [routes routes-chan state] (let [base-href (process-base-href (or (:base-href state) "/"))] (core/start! (->HistoryRouter (router/expand-routes routes) routes-chan base-href (:app-db state)))))
ccbea9d7f32deb4d0c3c2c4501b471cecf4d8465391df9f703d832aa7aefc323
unclebob/AdventOfCode2022
core_spec.clj
(ns day8-treetop-tree-house.core-spec (:require [speclj.core :refer :all] [day8-treetop-tree-house.core :refer :all])) (describe "parsing the forest file" (it "parses nothing" (should= [[]] (parse-forest ""))) (it "parses a simple forest" (should= [[1 2] [3 4]] (parse-forest "12\n34"))) ) (describe "part 1 utilities -- finding hidden trees" (it "counts trees" (should= 9 (count-trees [[1 1 1] [1 1 1] [1 1 1]]))) (it "rotates the forest" (should= [[1 3] [2 4]] (rotate-forest [[1 2] [3 4]]))) (it "finds hidden trees in a row" (should= #{1 2} (hidden-from-left [3 2 3 5])) (should= #{0 1 2} (hidden-from-right [3 1 2 5])) (should= #{1 2} (hidden-in-row [3 1 2 5])) (should= #{} (hidden-in-row [1 5 1]))) (it "finds hidden trees" (should= #{[1 0] [1 1] [1 2]} (find-hidden-trees-by-row [[1 1 1] [1 0 1] [1 1 1]])) (should= #{[0 1] [1 1] [2 1]} (find-hidden-trees-by-column [[1 1 1] [1 0 1] [1 1 1]])) (should= #{[1 1]} (find-hidden-trees [[1 1 1] [1 0 1] [1 1 1]])))) (describe "part 1 solution" (it "should solve test-input" (should= 21 (count-visible-trees "test-input"))) (it "should solve input" (should= 1803 (count-visible-trees "input")))) (describe "Part 2 utilities, measuring visibility" (it "creates four rays" (should= #{[[2 1] [2 2] [2 3] [2 4]] [[2 1] [2 0]] [[2 1] [3 1] [4 1]] [[2 1] [1 1] [0 1]]} (create-rays [5 5] [2 1])) (should= #{[[0 0]] [[0 0] [1 0] [2 0] [3 0] [4 0]] [[0 0] [0 1] [0 2] [0 3] [0 4]]} (create-rays [5 5] [0 0])) (should= #{[[4 4]] [[4 4] [3 4] [2 4] [1 4] [0 4]] [[4 4] [4 3] [4 2] [4 1] [4 0]]} (create-rays [5 5] [4 4]))) (it "gets a tree from a coordinate" (let [forest [[1 2 3] [4 5 6] [7 8 9]]] (should= 1 (get-tree forest [0 0])) (should= 5 (get-tree forest [1 1])) (should= 9 (get-tree forest [2 2])))) (it "calculates scenic score of ray" (let [forest (parse-forest (slurp "test-input"))] (should= 2 (get-scenic-score-of-ray forest [[2 3] [2 2] [2 1] [2 0]])) (should= 2 (get-scenic-score-of-ray forest [[2 3] [1 3] [0 3]])) (should= 1 (get-scenic-score-of-ray forest [[2 3] [2 4]])) (should= 2 (get-scenic-score-of-ray forest [[2 3] [3 3] [4 3]])))) (it "calculates scenic score of tree" (let [forest (parse-forest (slurp "test-input"))] (should= 8 (get-scenic-score-of-tree forest [2 3]))))) (describe "Part 2 solution" (it "solves test data" (should= 8 (find-best-scenic-score "test-input"))) (it "solves input" (should= 268912 (find-best-scenic-score "input"))))
null
https://raw.githubusercontent.com/unclebob/AdventOfCode2022/f2bf8a1257a21e7b055365224a9ed193489eec7d/day8-treetop-tree-house/spec/day8_treetop_tree_house/core_spec.clj
clojure
(ns day8-treetop-tree-house.core-spec (:require [speclj.core :refer :all] [day8-treetop-tree-house.core :refer :all])) (describe "parsing the forest file" (it "parses nothing" (should= [[]] (parse-forest ""))) (it "parses a simple forest" (should= [[1 2] [3 4]] (parse-forest "12\n34"))) ) (describe "part 1 utilities -- finding hidden trees" (it "counts trees" (should= 9 (count-trees [[1 1 1] [1 1 1] [1 1 1]]))) (it "rotates the forest" (should= [[1 3] [2 4]] (rotate-forest [[1 2] [3 4]]))) (it "finds hidden trees in a row" (should= #{1 2} (hidden-from-left [3 2 3 5])) (should= #{0 1 2} (hidden-from-right [3 1 2 5])) (should= #{1 2} (hidden-in-row [3 1 2 5])) (should= #{} (hidden-in-row [1 5 1]))) (it "finds hidden trees" (should= #{[1 0] [1 1] [1 2]} (find-hidden-trees-by-row [[1 1 1] [1 0 1] [1 1 1]])) (should= #{[0 1] [1 1] [2 1]} (find-hidden-trees-by-column [[1 1 1] [1 0 1] [1 1 1]])) (should= #{[1 1]} (find-hidden-trees [[1 1 1] [1 0 1] [1 1 1]])))) (describe "part 1 solution" (it "should solve test-input" (should= 21 (count-visible-trees "test-input"))) (it "should solve input" (should= 1803 (count-visible-trees "input")))) (describe "Part 2 utilities, measuring visibility" (it "creates four rays" (should= #{[[2 1] [2 2] [2 3] [2 4]] [[2 1] [2 0]] [[2 1] [3 1] [4 1]] [[2 1] [1 1] [0 1]]} (create-rays [5 5] [2 1])) (should= #{[[0 0]] [[0 0] [1 0] [2 0] [3 0] [4 0]] [[0 0] [0 1] [0 2] [0 3] [0 4]]} (create-rays [5 5] [0 0])) (should= #{[[4 4]] [[4 4] [3 4] [2 4] [1 4] [0 4]] [[4 4] [4 3] [4 2] [4 1] [4 0]]} (create-rays [5 5] [4 4]))) (it "gets a tree from a coordinate" (let [forest [[1 2 3] [4 5 6] [7 8 9]]] (should= 1 (get-tree forest [0 0])) (should= 5 (get-tree forest [1 1])) (should= 9 (get-tree forest [2 2])))) (it "calculates scenic score of ray" (let [forest (parse-forest (slurp "test-input"))] (should= 2 (get-scenic-score-of-ray forest [[2 3] [2 2] [2 1] [2 0]])) (should= 2 (get-scenic-score-of-ray forest [[2 3] [1 3] [0 3]])) (should= 1 (get-scenic-score-of-ray forest [[2 3] [2 4]])) (should= 2 (get-scenic-score-of-ray forest [[2 3] [3 3] [4 3]])))) (it "calculates scenic score of tree" (let [forest (parse-forest (slurp "test-input"))] (should= 8 (get-scenic-score-of-tree forest [2 3]))))) (describe "Part 2 solution" (it "solves test data" (should= 8 (find-best-scenic-score "test-input"))) (it "solves input" (should= 268912 (find-best-scenic-score "input"))))
3e42d42c104fd7097399e983dd27c0804775b46655a9c8d07626e631826a17e0
Octachron/codept
stdlib_408.ml
let modules= let open Module in let open Sig in Dict.of_list [("Arg",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Arg";namespace=["Stdlib"]}};path={name="Arg";namespace=["Stdlib"]}}; signature=empty})); ("Array",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Array";namespace=["Stdlib"]}};path={name="Array";namespace=["Stdlib"]}}; signature=of_list [("Floatarray",Sig ({origin=Submodule; signature=empty}))]})); ("ArrayLabels",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="ArrayLabels";namespace=["Stdlib"]}};path={name="ArrayLabels";namespace=["Stdlib"]}}; signature=of_list [("Floatarray",Sig ({origin=Submodule; signature=empty}))]})); ("Bigarray",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Bigarray";namespace=["Stdlib"]}};path={name="Bigarray";namespace=["Stdlib"]}}; signature=of_list [("Array0",Sig ({origin=Submodule; signature=empty})); ("Array1",Sig ({origin=Submodule; signature=empty})); ("Array2",Sig ({origin=Submodule; signature=empty})); ("Array3",Sig ({origin=Submodule; signature=empty})); ("Genarray",Sig ({origin=Submodule; signature=empty}))]})); ("Bool",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Bool";namespace=["Stdlib"]}};path={name="Bool";namespace=["Stdlib"]}}; signature=empty})); ("Buffer",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Buffer";namespace=["Stdlib"]}};path={name="Buffer";namespace=["Stdlib"]}}; signature=empty})); ("Bytes",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Bytes";namespace=["Stdlib"]}};path={name="Bytes";namespace=["Stdlib"]}}; signature=empty})); ("BytesLabels",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="BytesLabels";namespace=["Stdlib"]}};path={name="BytesLabels";namespace=["Stdlib"]}}; signature=empty})); ("Callback",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Callback";namespace=["Stdlib"]}};path={name="Callback";namespace=["Stdlib"]}}; signature=empty})); ("CamlinternalFormat",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="CamlinternalFormat";namespace=["Stdlib"]}};path={name="CamlinternalFormat";namespace=["Stdlib"]}}; signature=empty})); ("CamlinternalFormatBasics",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="CamlinternalFormatBasics";namespace=["Stdlib"]}};path={name="CamlinternalFormatBasics";namespace=["Stdlib"]}}; signature=empty})); ("CamlinternalLazy",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="CamlinternalLazy";namespace=["Stdlib"]}};path={name="CamlinternalLazy";namespace=["Stdlib"]}}; signature=empty})); ("CamlinternalMod",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="CamlinternalMod";namespace=["Stdlib"]}};path={name="CamlinternalMod";namespace=["Stdlib"]}}; signature=empty})); ("CamlinternalOO",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="CamlinternalOO";namespace=["Stdlib"]}};path={name="CamlinternalOO";namespace=["Stdlib"]}}; signature=empty})); ("Char",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Char";namespace=["Stdlib"]}};path={name="Char";namespace=["Stdlib"]}}; signature=empty})); ("Complex",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Complex";namespace=["Stdlib"]}};path={name="Complex";namespace=["Stdlib"]}}; signature=empty})); ("Digest",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Digest";namespace=["Stdlib"]}};path={name="Digest";namespace=["Stdlib"]}}; signature=empty})); ("Ephemeron",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Ephemeron";namespace=["Stdlib"]}};path={name="Ephemeron";namespace=["Stdlib"]}}; signature= (merge (of_list [("GenHashTable",Sig ({origin=Submodule; signature=of_list [("MakeSeeded",Fun (Some {name=Some "H";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty})))]})); ("K1",Sig ({origin=Submodule; signature=of_list [("Make",Fun (Some {name=Some "H";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty}))); ("MakeSeeded",Fun (Some {name=Some "H";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty})))]})); ("K2",Sig ({origin=Submodule; signature=of_list [("Make",Fun (Some {name=Some "H1";signature=Sig ( {origin=Submodule; signature=empty})},Fun (Some {name=Some "H2";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty})))); ("MakeSeeded",Fun (Some {name=Some "H1";signature=Sig ( {origin=Submodule; signature=empty})},Fun (Some {name=Some "H2";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty}))))]})); ("Kn",Sig ({origin=Submodule; signature=of_list [("Make",Fun (Some {name=Some "H";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty}))); ("MakeSeeded",Fun (Some {name=Some "H";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty})))]}))]) (of_list_type [("S",Sig ({origin=Submodule; signature=empty})); ("SeededS",Sig ({origin=Submodule; signature=empty}))]) )})); ("Filename",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Filename";namespace=["Stdlib"]}};path={name="Filename";namespace=["Stdlib"]}}; signature=empty})); ("Float",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Float";namespace=["Stdlib"]}};path={name="Float";namespace=["Stdlib"]}}; signature=of_list [("Array",Sig ({origin=Submodule; signature=empty})); ("ArrayLabels",Sig ({origin=Submodule; signature=empty}))]})); ("Format",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Format";namespace=["Stdlib"]}};path={name="Format";namespace=["Stdlib"]}}; signature=empty})); ("Fun",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Fun";namespace=["Stdlib"]}};path={name="Fun";namespace=["Stdlib"]}}; signature=empty})); ("Gc",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Gc";namespace=["Stdlib"]}};path={name="Gc";namespace=["Stdlib"]}}; signature=empty})); ("Genlex",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Genlex";namespace=["Stdlib"]}};path={name="Genlex";namespace=["Stdlib"]}}; signature=empty})); ("Hashtbl",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Hashtbl";namespace=["Stdlib"]}};path={name="Hashtbl";namespace=["Stdlib"]}}; signature= (merge (of_list [("Make",Fun (Some {name=Some "H";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty}))); ("MakeSeeded",Fun (Some {name=Some "H";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty})))]) (of_list_type [("HashedType",Sig ({origin=Submodule; signature=empty})); ("S",Sig ({origin=Submodule; signature=empty})); ("SeededHashedType",Sig ({origin=Submodule; signature=empty})); ("SeededS",Sig ({origin=Submodule; signature=empty}))]) )})); ("Int",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Int";namespace=["Stdlib"]}};path={name="Int";namespace=["Stdlib"]}}; signature=empty})); ("Int32",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Int32";namespace=["Stdlib"]}};path={name="Int32";namespace=["Stdlib"]}}; signature=empty})); ("Int64",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Int64";namespace=["Stdlib"]}};path={name="Int64";namespace=["Stdlib"]}}; signature=empty})); ("Lazy",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Lazy";namespace=["Stdlib"]}};path={name="Lazy";namespace=["Stdlib"]}}; signature=empty})); ("Lexing",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Lexing";namespace=["Stdlib"]}};path={name="Lexing";namespace=["Stdlib"]}}; signature=empty})); ("List",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="List";namespace=["Stdlib"]}};path={name="List";namespace=["Stdlib"]}}; signature=empty})); ("ListLabels",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="ListLabels";namespace=["Stdlib"]}};path={name="ListLabels";namespace=["Stdlib"]}}; signature=empty})); ("Map",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Map";namespace=["Stdlib"]}};path={name="Map";namespace=["Stdlib"]}}; signature= (merge (of_list [("Make",Fun (Some {name=Some "Ord";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty})))]) (of_list_type [("OrderedType",Sig ({origin=Submodule; signature=empty})); ("S",Sig ({origin=Submodule; signature=empty}))]) )})); ("Marshal",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Marshal";namespace=["Stdlib"]}};path={name="Marshal";namespace=["Stdlib"]}}; signature=empty})); ("MoreLabels",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="MoreLabels";namespace=["Stdlib"]}};path={name="MoreLabels";namespace=["Stdlib"]}}; signature=of_list [("Hashtbl",Sig ({origin=Submodule; signature= (merge (of_list [("Make",Fun (Some {name=Some "H";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty}))); ("MakeSeeded",Fun (Some {name=Some "H";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty})))]) (of_list_type [("HashedType",Sig ( {origin=Submodule; signature=empty})); ("S",Sig ({origin=Submodule; signature=empty})); ("SeededHashedType",Sig ( {origin=Submodule; signature=empty})); ("SeededS",Sig ({origin=Submodule; signature=empty}))]) )})); ("Map",Sig ({origin=Submodule; signature= (merge (of_list [("Make",Fun (Some {name=Some "Ord";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty})))]) (of_list_type [("OrderedType",Sig ( {origin=Submodule; signature=empty})); ("S",Sig ({origin=Submodule; signature=empty}))]) )})); ("Set",Sig ({origin=Submodule; signature= (merge (of_list [("Make",Fun (Some {name=Some "Ord";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty})))]) (of_list_type [("OrderedType",Sig ( {origin=Submodule; signature=empty})); ("S",Sig ({origin=Submodule; signature=empty}))]) )}))]})); ("Nativeint",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Nativeint";namespace=["Stdlib"]}};path={name="Nativeint";namespace=["Stdlib"]}}; signature=empty})); ("Obj",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Obj";namespace=["Stdlib"]}};path={name="Obj";namespace=["Stdlib"]}}; signature=of_list [("Ephemeron",Sig ({origin=Submodule; signature=empty})); ("Extension_constructor",Sig ({origin=Submodule; signature=empty}))]})); ("Oo",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Oo";namespace=["Stdlib"]}};path={name="Oo";namespace=["Stdlib"]}}; signature=empty})); ("Option",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Option";namespace=["Stdlib"]}};path={name="Option";namespace=["Stdlib"]}}; signature=empty})); ("Parsing",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Parsing";namespace=["Stdlib"]}};path={name="Parsing";namespace=["Stdlib"]}}; signature=empty})); ("Printexc",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Printexc";namespace=["Stdlib"]}};path={name="Printexc";namespace=["Stdlib"]}}; signature=of_list [("Slot",Sig ({origin=Submodule; signature=empty}))]})); ("Printf",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Printf";namespace=["Stdlib"]}};path={name="Printf";namespace=["Stdlib"]}}; signature=empty})); ("Queue",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Queue";namespace=["Stdlib"]}};path={name="Queue";namespace=["Stdlib"]}}; signature=empty})); ("Random",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Random";namespace=["Stdlib"]}};path={name="Random";namespace=["Stdlib"]}}; signature=of_list [("State",Sig ({origin=Submodule; signature=empty}))]})); ("Result",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Result";namespace=["Stdlib"]}};path={name="Result";namespace=["Stdlib"]}}; signature=empty})); ("Scanf",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Scanf";namespace=["Stdlib"]}};path={name="Scanf";namespace=["Stdlib"]}}; signature=of_list [("Scanning",Sig ({origin=Submodule; signature=empty}))]})); ("Seq",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Seq";namespace=["Stdlib"]}};path={name="Seq";namespace=["Stdlib"]}}; signature=empty})); ("Set",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Set";namespace=["Stdlib"]}};path={name="Set";namespace=["Stdlib"]}}; signature= (merge (of_list [("Make",Fun (Some {name=Some "Ord";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty})))]) (of_list_type [("OrderedType",Sig ({origin=Submodule; signature=empty})); ("S",Sig ({origin=Submodule; signature=empty}))]) )})); ("Spacetime",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Spacetime";namespace=["Stdlib"]}};path={name="Spacetime";namespace=["Stdlib"]}}; signature=of_list [("Series",Sig ({origin=Submodule; signature=empty})); ("Snapshot",Sig ({origin=Submodule; signature=empty}))]})); ("Stack",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Stack";namespace=["Stdlib"]}};path={name="Stack";namespace=["Stdlib"]}}; signature=empty})); ("StdLabels",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="StdLabels";namespace=["Stdlib"]}};path={name="StdLabels";namespace=["Stdlib"]}}; signature=of_list [("Array",Alias {path=Namespaced.make "ArrayLabels";phantom=None}); ("Bytes",Alias {path=Namespaced.make "BytesLabels";phantom=None}); ("List",Alias {path=Namespaced.make "ListLabels";phantom=None}); ("String",Alias {path=Namespaced.make "StringLabels";phantom=None})]})); ("Stream",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Stream";namespace=["Stdlib"]}};path={name="Stream";namespace=["Stdlib"]}}; signature=empty})); ("String",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="String";namespace=["Stdlib"]}};path={name="String";namespace=["Stdlib"]}}; signature=empty})); ("StringLabels",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="StringLabels";namespace=["Stdlib"]}};path={name="StringLabels";namespace=["Stdlib"]}}; signature=empty})); ("Sys",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Sys";namespace=["Stdlib"]}};path={name="Sys";namespace=["Stdlib"]}}; signature=empty})); ("Uchar",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Uchar";namespace=["Stdlib"]}};path={name="Uchar";namespace=["Stdlib"]}}; signature=empty})); ("Unit",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Unit";namespace=["Stdlib"]}};path={name="Unit";namespace=["Stdlib"]}}; signature=empty})); ("Weak",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Weak";namespace=["Stdlib"]}};path={name="Weak";namespace=["Stdlib"]}}; signature= (merge (of_list [("Make",Fun (Some {name=Some "H";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty})))]) (of_list_type [("S",Sig ({origin=Submodule; signature=empty}))]) )}))]
null
https://raw.githubusercontent.com/Octachron/codept/1ecb2389a9a936dd937624e79970d4d6f112f16b/tests/bundle_refs/stdlib_408.ml
ocaml
let modules= let open Module in let open Sig in Dict.of_list [("Arg",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Arg";namespace=["Stdlib"]}};path={name="Arg";namespace=["Stdlib"]}}; signature=empty})); ("Array",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Array";namespace=["Stdlib"]}};path={name="Array";namespace=["Stdlib"]}}; signature=of_list [("Floatarray",Sig ({origin=Submodule; signature=empty}))]})); ("ArrayLabels",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="ArrayLabels";namespace=["Stdlib"]}};path={name="ArrayLabels";namespace=["Stdlib"]}}; signature=of_list [("Floatarray",Sig ({origin=Submodule; signature=empty}))]})); ("Bigarray",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Bigarray";namespace=["Stdlib"]}};path={name="Bigarray";namespace=["Stdlib"]}}; signature=of_list [("Array0",Sig ({origin=Submodule; signature=empty})); ("Array1",Sig ({origin=Submodule; signature=empty})); ("Array2",Sig ({origin=Submodule; signature=empty})); ("Array3",Sig ({origin=Submodule; signature=empty})); ("Genarray",Sig ({origin=Submodule; signature=empty}))]})); ("Bool",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Bool";namespace=["Stdlib"]}};path={name="Bool";namespace=["Stdlib"]}}; signature=empty})); ("Buffer",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Buffer";namespace=["Stdlib"]}};path={name="Buffer";namespace=["Stdlib"]}}; signature=empty})); ("Bytes",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Bytes";namespace=["Stdlib"]}};path={name="Bytes";namespace=["Stdlib"]}}; signature=empty})); ("BytesLabels",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="BytesLabels";namespace=["Stdlib"]}};path={name="BytesLabels";namespace=["Stdlib"]}}; signature=empty})); ("Callback",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Callback";namespace=["Stdlib"]}};path={name="Callback";namespace=["Stdlib"]}}; signature=empty})); ("CamlinternalFormat",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="CamlinternalFormat";namespace=["Stdlib"]}};path={name="CamlinternalFormat";namespace=["Stdlib"]}}; signature=empty})); ("CamlinternalFormatBasics",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="CamlinternalFormatBasics";namespace=["Stdlib"]}};path={name="CamlinternalFormatBasics";namespace=["Stdlib"]}}; signature=empty})); ("CamlinternalLazy",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="CamlinternalLazy";namespace=["Stdlib"]}};path={name="CamlinternalLazy";namespace=["Stdlib"]}}; signature=empty})); ("CamlinternalMod",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="CamlinternalMod";namespace=["Stdlib"]}};path={name="CamlinternalMod";namespace=["Stdlib"]}}; signature=empty})); ("CamlinternalOO",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="CamlinternalOO";namespace=["Stdlib"]}};path={name="CamlinternalOO";namespace=["Stdlib"]}}; signature=empty})); ("Char",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Char";namespace=["Stdlib"]}};path={name="Char";namespace=["Stdlib"]}}; signature=empty})); ("Complex",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Complex";namespace=["Stdlib"]}};path={name="Complex";namespace=["Stdlib"]}}; signature=empty})); ("Digest",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Digest";namespace=["Stdlib"]}};path={name="Digest";namespace=["Stdlib"]}}; signature=empty})); ("Ephemeron",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Ephemeron";namespace=["Stdlib"]}};path={name="Ephemeron";namespace=["Stdlib"]}}; signature= (merge (of_list [("GenHashTable",Sig ({origin=Submodule; signature=of_list [("MakeSeeded",Fun (Some {name=Some "H";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty})))]})); ("K1",Sig ({origin=Submodule; signature=of_list [("Make",Fun (Some {name=Some "H";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty}))); ("MakeSeeded",Fun (Some {name=Some "H";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty})))]})); ("K2",Sig ({origin=Submodule; signature=of_list [("Make",Fun (Some {name=Some "H1";signature=Sig ( {origin=Submodule; signature=empty})},Fun (Some {name=Some "H2";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty})))); ("MakeSeeded",Fun (Some {name=Some "H1";signature=Sig ( {origin=Submodule; signature=empty})},Fun (Some {name=Some "H2";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty}))))]})); ("Kn",Sig ({origin=Submodule; signature=of_list [("Make",Fun (Some {name=Some "H";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty}))); ("MakeSeeded",Fun (Some {name=Some "H";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty})))]}))]) (of_list_type [("S",Sig ({origin=Submodule; signature=empty})); ("SeededS",Sig ({origin=Submodule; signature=empty}))]) )})); ("Filename",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Filename";namespace=["Stdlib"]}};path={name="Filename";namespace=["Stdlib"]}}; signature=empty})); ("Float",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Float";namespace=["Stdlib"]}};path={name="Float";namespace=["Stdlib"]}}; signature=of_list [("Array",Sig ({origin=Submodule; signature=empty})); ("ArrayLabels",Sig ({origin=Submodule; signature=empty}))]})); ("Format",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Format";namespace=["Stdlib"]}};path={name="Format";namespace=["Stdlib"]}}; signature=empty})); ("Fun",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Fun";namespace=["Stdlib"]}};path={name="Fun";namespace=["Stdlib"]}}; signature=empty})); ("Gc",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Gc";namespace=["Stdlib"]}};path={name="Gc";namespace=["Stdlib"]}}; signature=empty})); ("Genlex",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Genlex";namespace=["Stdlib"]}};path={name="Genlex";namespace=["Stdlib"]}}; signature=empty})); ("Hashtbl",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Hashtbl";namespace=["Stdlib"]}};path={name="Hashtbl";namespace=["Stdlib"]}}; signature= (merge (of_list [("Make",Fun (Some {name=Some "H";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty}))); ("MakeSeeded",Fun (Some {name=Some "H";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty})))]) (of_list_type [("HashedType",Sig ({origin=Submodule; signature=empty})); ("S",Sig ({origin=Submodule; signature=empty})); ("SeededHashedType",Sig ({origin=Submodule; signature=empty})); ("SeededS",Sig ({origin=Submodule; signature=empty}))]) )})); ("Int",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Int";namespace=["Stdlib"]}};path={name="Int";namespace=["Stdlib"]}}; signature=empty})); ("Int32",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Int32";namespace=["Stdlib"]}};path={name="Int32";namespace=["Stdlib"]}}; signature=empty})); ("Int64",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Int64";namespace=["Stdlib"]}};path={name="Int64";namespace=["Stdlib"]}}; signature=empty})); ("Lazy",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Lazy";namespace=["Stdlib"]}};path={name="Lazy";namespace=["Stdlib"]}}; signature=empty})); ("Lexing",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Lexing";namespace=["Stdlib"]}};path={name="Lexing";namespace=["Stdlib"]}}; signature=empty})); ("List",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="List";namespace=["Stdlib"]}};path={name="List";namespace=["Stdlib"]}}; signature=empty})); ("ListLabels",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="ListLabels";namespace=["Stdlib"]}};path={name="ListLabels";namespace=["Stdlib"]}}; signature=empty})); ("Map",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Map";namespace=["Stdlib"]}};path={name="Map";namespace=["Stdlib"]}}; signature= (merge (of_list [("Make",Fun (Some {name=Some "Ord";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty})))]) (of_list_type [("OrderedType",Sig ({origin=Submodule; signature=empty})); ("S",Sig ({origin=Submodule; signature=empty}))]) )})); ("Marshal",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Marshal";namespace=["Stdlib"]}};path={name="Marshal";namespace=["Stdlib"]}}; signature=empty})); ("MoreLabels",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="MoreLabels";namespace=["Stdlib"]}};path={name="MoreLabels";namespace=["Stdlib"]}}; signature=of_list [("Hashtbl",Sig ({origin=Submodule; signature= (merge (of_list [("Make",Fun (Some {name=Some "H";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty}))); ("MakeSeeded",Fun (Some {name=Some "H";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty})))]) (of_list_type [("HashedType",Sig ( {origin=Submodule; signature=empty})); ("S",Sig ({origin=Submodule; signature=empty})); ("SeededHashedType",Sig ( {origin=Submodule; signature=empty})); ("SeededS",Sig ({origin=Submodule; signature=empty}))]) )})); ("Map",Sig ({origin=Submodule; signature= (merge (of_list [("Make",Fun (Some {name=Some "Ord";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty})))]) (of_list_type [("OrderedType",Sig ( {origin=Submodule; signature=empty})); ("S",Sig ({origin=Submodule; signature=empty}))]) )})); ("Set",Sig ({origin=Submodule; signature= (merge (of_list [("Make",Fun (Some {name=Some "Ord";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty})))]) (of_list_type [("OrderedType",Sig ( {origin=Submodule; signature=empty})); ("S",Sig ({origin=Submodule; signature=empty}))]) )}))]})); ("Nativeint",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Nativeint";namespace=["Stdlib"]}};path={name="Nativeint";namespace=["Stdlib"]}}; signature=empty})); ("Obj",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Obj";namespace=["Stdlib"]}};path={name="Obj";namespace=["Stdlib"]}}; signature=of_list [("Ephemeron",Sig ({origin=Submodule; signature=empty})); ("Extension_constructor",Sig ({origin=Submodule; signature=empty}))]})); ("Oo",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Oo";namespace=["Stdlib"]}};path={name="Oo";namespace=["Stdlib"]}}; signature=empty})); ("Option",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Option";namespace=["Stdlib"]}};path={name="Option";namespace=["Stdlib"]}}; signature=empty})); ("Parsing",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Parsing";namespace=["Stdlib"]}};path={name="Parsing";namespace=["Stdlib"]}}; signature=empty})); ("Printexc",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Printexc";namespace=["Stdlib"]}};path={name="Printexc";namespace=["Stdlib"]}}; signature=of_list [("Slot",Sig ({origin=Submodule; signature=empty}))]})); ("Printf",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Printf";namespace=["Stdlib"]}};path={name="Printf";namespace=["Stdlib"]}}; signature=empty})); ("Queue",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Queue";namespace=["Stdlib"]}};path={name="Queue";namespace=["Stdlib"]}}; signature=empty})); ("Random",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Random";namespace=["Stdlib"]}};path={name="Random";namespace=["Stdlib"]}}; signature=of_list [("State",Sig ({origin=Submodule; signature=empty}))]})); ("Result",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Result";namespace=["Stdlib"]}};path={name="Result";namespace=["Stdlib"]}}; signature=empty})); ("Scanf",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Scanf";namespace=["Stdlib"]}};path={name="Scanf";namespace=["Stdlib"]}}; signature=of_list [("Scanning",Sig ({origin=Submodule; signature=empty}))]})); ("Seq",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Seq";namespace=["Stdlib"]}};path={name="Seq";namespace=["Stdlib"]}}; signature=empty})); ("Set",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Set";namespace=["Stdlib"]}};path={name="Set";namespace=["Stdlib"]}}; signature= (merge (of_list [("Make",Fun (Some {name=Some "Ord";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty})))]) (of_list_type [("OrderedType",Sig ({origin=Submodule; signature=empty})); ("S",Sig ({origin=Submodule; signature=empty}))]) )})); ("Spacetime",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Spacetime";namespace=["Stdlib"]}};path={name="Spacetime";namespace=["Stdlib"]}}; signature=of_list [("Series",Sig ({origin=Submodule; signature=empty})); ("Snapshot",Sig ({origin=Submodule; signature=empty}))]})); ("Stack",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Stack";namespace=["Stdlib"]}};path={name="Stack";namespace=["Stdlib"]}}; signature=empty})); ("StdLabels",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="StdLabels";namespace=["Stdlib"]}};path={name="StdLabels";namespace=["Stdlib"]}}; signature=of_list [("Array",Alias {path=Namespaced.make "ArrayLabels";phantom=None}); ("Bytes",Alias {path=Namespaced.make "BytesLabels";phantom=None}); ("List",Alias {path=Namespaced.make "ListLabels";phantom=None}); ("String",Alias {path=Namespaced.make "StringLabels";phantom=None})]})); ("Stream",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Stream";namespace=["Stdlib"]}};path={name="Stream";namespace=["Stdlib"]}}; signature=empty})); ("String",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="String";namespace=["Stdlib"]}};path={name="String";namespace=["Stdlib"]}}; signature=empty})); ("StringLabels",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="StringLabels";namespace=["Stdlib"]}};path={name="StringLabels";namespace=["Stdlib"]}}; signature=empty})); ("Sys",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Sys";namespace=["Stdlib"]}};path={name="Sys";namespace=["Stdlib"]}}; signature=empty})); ("Uchar",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Uchar";namespace=["Stdlib"]}};path={name="Uchar";namespace=["Stdlib"]}}; signature=empty})); ("Unit",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Unit";namespace=["Stdlib"]}};path={name="Unit";namespace=["Stdlib"]}}; signature=empty})); ("Weak",Sig ({origin=Unit {source={source=Special "stdlib"; file={name="Weak";namespace=["Stdlib"]}};path={name="Weak";namespace=["Stdlib"]}}; signature= (merge (of_list [("Make",Fun (Some {name=Some "H";signature=Sig ( {origin=Submodule; signature=empty})},Sig ( {origin=Submodule; signature=empty})))]) (of_list_type [("S",Sig ({origin=Submodule; signature=empty}))]) )}))]
29ede3a751d20a91efd94fb7187c76d674d69c0505c6a481e823d6ac649cf8d1
EligiusSantori/L2Apf
gg_reply.scm
(module system racket/base (provide login-server-packet/gg-reply) (require "../../packet.scm") (define (login-server-packet/gg-reply buffer) TODO ) )
null
https://raw.githubusercontent.com/EligiusSantori/L2Apf/30ffe0828e8a401f58d39984efd862c8aeab8c30/packet/login/server/gg_reply.scm
scheme
(module system racket/base (provide login-server-packet/gg-reply) (require "../../packet.scm") (define (login-server-packet/gg-reply buffer) TODO ) )
a0bf5212f3cf338454a983c8516d899427a02597aad0b507c68513d9ec1697f1
dmitryvk/sbcl-win32-threads
entry.lisp
;;;; Code in this file handles VM-independent details of run-time ;;;; function representation that primarily concern IR2 conversion and ;;;; the dumper/loader. This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the ;;;; public domain. The software is in the public domain and is ;;;; provided with absolutely no warranty. See the COPYING and CREDITS ;;;; files for more information. (in-package "SB!C") This phase runs before IR2 conversion , initializing each XEP 's ;;; ENTRY-INFO structure. We call the VM-supplied ;;; SELECT-COMPONENT-FORMAT function to make VM-dependent ;;; initializations in the IR2-COMPONENT. This includes setting the ;;; IR2-COMPONENT-KIND and allocating fixed implementation overhead in ;;; the constant pool. If there was a forward reference to a function, ;;; then the ENTRY-INFO will already exist, but will be uninitialized. (defun entry-analyze (component) (let ((2comp (component-info component))) (dolist (fun (component-lambdas component)) (when (xep-p fun) (let ((info (or (leaf-info fun) (setf (leaf-info fun) (make-entry-info))))) (compute-entry-info fun info) (push info (ir2-component-entries 2comp)))))) (select-component-format component) (values)) Initialize INFO structure to correspond to the XEP LAMBDA FUN . (defun compute-entry-info (fun info) (declare (type clambda fun) (type entry-info info)) (let ((bind (lambda-bind fun)) (internal-fun (functional-entry-fun fun))) (setf (entry-info-closure-tn info) (if (physenv-closure (lambda-physenv fun)) (make-normal-tn *backend-t-primitive-type*) nil)) (setf (entry-info-offset info) (gen-label)) (setf (entry-info-name info) (leaf-debug-name internal-fun)) (let ((doc (functional-documentation internal-fun)) (xrefs (pack-xref-data (functional-xref internal-fun)))) (setf (entry-info-info info) (if (and doc xrefs) (cons doc xrefs) (or doc xrefs)))) (when (policy bind (>= debug 1)) (let ((args (functional-arg-documentation internal-fun))) (aver (not (eq args :unspecified))) ;; When the component is dumped, the arglists of the entry ;; points will be dumped. If they contain values that need ;; make-load-form processing then we need to do it now (bug ;; 310132). (setf (entry-info-arguments info) (constant-value (find-constant args)))) (setf (entry-info-type info) (type-specifier (leaf-type internal-fun))))) (values)) ;;; Replace all references to COMPONENT's non-closure XEPs that appear ;;; in top level or externally-referenced components, changing to ;;; :TOPLEVEL-XEP FUNCTIONALs. If the cross-component ref is not in a : TOPLEVEL / externally - referenced component , or is to a closure , ;;; then substitution is suppressed. ;;; ;;; When a cross-component ref is not substituted, we return T to ;;; indicate that early deletion of this component's IR1 should not be ;;; done. We also return T if this component contains : TOPLEVEL / externally - referenced ( though it is not a ;;; :TOPLEVEL component.) ;;; ;;; We deliberately don't use the normal reference deletion, since we ;;; don't want to trigger deletion of the XEP (although it shouldn't ;;; hurt, since this is called after COMPONENT is compiled.) Instead, we just clobber the REF - LEAF . (defun replace-toplevel-xeps (component) (let ((res nil)) (dolist (lambda (component-lambdas component)) (case (functional-kind lambda) (:external (unless (lambda-has-external-references-p lambda) (let* ((ef (functional-entry-fun lambda)) (new (make-functional :kind :toplevel-xep :info (leaf-info lambda) :%source-name (functional-%source-name ef) :%debug-name (functional-%debug-name ef) :lexenv (make-null-lexenv))) (closure (physenv-closure (lambda-physenv (main-entry ef))))) (dolist (ref (leaf-refs lambda)) (let ((ref-component (node-component ref))) (cond ((eq ref-component component)) ((or (not (component-toplevelish-p ref-component)) closure) (setq res t)) (t (setf (ref-leaf ref) new) (push ref (leaf-refs new)) (setf (leaf-refs lambda) (delq ref (leaf-refs lambda)))))))))) (:toplevel (setq res t)))) res))
null
https://raw.githubusercontent.com/dmitryvk/sbcl-win32-threads/5abfd64b00a0937ba2df2919f177697d1d91bde4/src/compiler/entry.lisp
lisp
Code in this file handles VM-independent details of run-time function representation that primarily concern IR2 conversion and the dumper/loader. more information. public domain. The software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information. ENTRY-INFO structure. We call the VM-supplied SELECT-COMPONENT-FORMAT function to make VM-dependent initializations in the IR2-COMPONENT. This includes setting the IR2-COMPONENT-KIND and allocating fixed implementation overhead in the constant pool. If there was a forward reference to a function, then the ENTRY-INFO will already exist, but will be uninitialized. When the component is dumped, the arglists of the entry points will be dumped. If they contain values that need make-load-form processing then we need to do it now (bug 310132). Replace all references to COMPONENT's non-closure XEPs that appear in top level or externally-referenced components, changing to :TOPLEVEL-XEP FUNCTIONALs. If the cross-component ref is not in a then substitution is suppressed. When a cross-component ref is not substituted, we return T to indicate that early deletion of this component's IR1 should not be done. We also return T if this component contains :TOPLEVEL component.) We deliberately don't use the normal reference deletion, since we don't want to trigger deletion of the XEP (although it shouldn't hurt, since this is called after COMPONENT is compiled.) Instead,
This software is part of the SBCL system . See the README file for This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the (in-package "SB!C") This phase runs before IR2 conversion , initializing each XEP 's (defun entry-analyze (component) (let ((2comp (component-info component))) (dolist (fun (component-lambdas component)) (when (xep-p fun) (let ((info (or (leaf-info fun) (setf (leaf-info fun) (make-entry-info))))) (compute-entry-info fun info) (push info (ir2-component-entries 2comp)))))) (select-component-format component) (values)) Initialize INFO structure to correspond to the XEP LAMBDA FUN . (defun compute-entry-info (fun info) (declare (type clambda fun) (type entry-info info)) (let ((bind (lambda-bind fun)) (internal-fun (functional-entry-fun fun))) (setf (entry-info-closure-tn info) (if (physenv-closure (lambda-physenv fun)) (make-normal-tn *backend-t-primitive-type*) nil)) (setf (entry-info-offset info) (gen-label)) (setf (entry-info-name info) (leaf-debug-name internal-fun)) (let ((doc (functional-documentation internal-fun)) (xrefs (pack-xref-data (functional-xref internal-fun)))) (setf (entry-info-info info) (if (and doc xrefs) (cons doc xrefs) (or doc xrefs)))) (when (policy bind (>= debug 1)) (let ((args (functional-arg-documentation internal-fun))) (aver (not (eq args :unspecified))) (setf (entry-info-arguments info) (constant-value (find-constant args)))) (setf (entry-info-type info) (type-specifier (leaf-type internal-fun))))) (values)) : TOPLEVEL / externally - referenced component , or is to a closure , : TOPLEVEL / externally - referenced ( though it is not a we just clobber the REF - LEAF . (defun replace-toplevel-xeps (component) (let ((res nil)) (dolist (lambda (component-lambdas component)) (case (functional-kind lambda) (:external (unless (lambda-has-external-references-p lambda) (let* ((ef (functional-entry-fun lambda)) (new (make-functional :kind :toplevel-xep :info (leaf-info lambda) :%source-name (functional-%source-name ef) :%debug-name (functional-%debug-name ef) :lexenv (make-null-lexenv))) (closure (physenv-closure (lambda-physenv (main-entry ef))))) (dolist (ref (leaf-refs lambda)) (let ((ref-component (node-component ref))) (cond ((eq ref-component component)) ((or (not (component-toplevelish-p ref-component)) closure) (setq res t)) (t (setf (ref-leaf ref) new) (push ref (leaf-refs new)) (setf (leaf-refs lambda) (delq ref (leaf-refs lambda)))))))))) (:toplevel (setq res t)))) res))
1bdf603a44750e70e0fde3b5514992912c2a54859eb932ba0749d22c074415c9
shayan-najd/NativeMetaprogramming
KeepingIntermediates.hs
module Options.KeepingIntermediates where import Types keepingIntermediatesOptions :: [Flag] keepingIntermediatesOptions = [ flag { flagName = "-keep-hc-file, -keep-hc-files" , flagDescription = "Retain intermediate ``.hc`` files." , flagType = DynamicFlag } , flag { flagName = "-keep-hi-files" , flagDescription = "Retain intermediate ``.hi`` files (the default)." , flagType = DynamicFlag , flagReverse = "-no-keep-hi-files" } , flag { flagName = "-keep-llvm-file, -keep-llvm-files" , flagDescription = "Retain intermediate LLVM ``.ll`` files. "++ "Implies :ghc-flag:`-fllvm`." , flagType = DynamicFlag } , flag { flagName = "-keep-o-files" , flagDescription = "Retain intermediate ``.o`` files (the default)." , flagType = DynamicFlag , flagReverse = "-no-keep-o-files" } , flag { flagName = "-keep-s-file, -keep-s-files" , flagDescription = "Retain intermediate ``.s`` files." , flagType = DynamicFlag } , flag { flagName = "-keep-tmp-files" , flagDescription = "Retain all intermediate temporary files." , flagType = DynamicFlag } ]
null
https://raw.githubusercontent.com/shayan-najd/NativeMetaprogramming/24e5f85990642d3f0b0044be4327b8f52fce2ba3/utils/mkUserGuidePart/Options/KeepingIntermediates.hs
haskell
module Options.KeepingIntermediates where import Types keepingIntermediatesOptions :: [Flag] keepingIntermediatesOptions = [ flag { flagName = "-keep-hc-file, -keep-hc-files" , flagDescription = "Retain intermediate ``.hc`` files." , flagType = DynamicFlag } , flag { flagName = "-keep-hi-files" , flagDescription = "Retain intermediate ``.hi`` files (the default)." , flagType = DynamicFlag , flagReverse = "-no-keep-hi-files" } , flag { flagName = "-keep-llvm-file, -keep-llvm-files" , flagDescription = "Retain intermediate LLVM ``.ll`` files. "++ "Implies :ghc-flag:`-fllvm`." , flagType = DynamicFlag } , flag { flagName = "-keep-o-files" , flagDescription = "Retain intermediate ``.o`` files (the default)." , flagType = DynamicFlag , flagReverse = "-no-keep-o-files" } , flag { flagName = "-keep-s-file, -keep-s-files" , flagDescription = "Retain intermediate ``.s`` files." , flagType = DynamicFlag } , flag { flagName = "-keep-tmp-files" , flagDescription = "Retain all intermediate temporary files." , flagType = DynamicFlag } ]
dd41243130a8aa8f538df16018c40a9747baa51d2ff77d452a457bb6c95ca8dc
pauleve/pint
ph_machine.mli
module P2Map : Map.S with type key = Ph_types.process * Ph_types.process type env = (Ph_types.PSet.t * Ph_types.rate * Ph_types.PSet.t) list P2Map.t * Create a new execution environment from the given Process Hitting . val create_env : Ph_types.ph -> env (** Initialize random generators used by the machine *) val init_random : unit -> unit (** Function to plot at the given time the presence of the given process. *) type plotter = (float -> Ph_types.process -> unit) (** [execute env init duration plotter] simulates the environment [env] from the initial state [init] and calls [plotter t p] each time the process [p] appears at time [t]. The simulation stops either when a fix point has been reached, or after [duration] units of time. Returns the resulting state. *) val execute : env -> Ph_types.state -> float -> plotter -> Ph_types.state
null
https://raw.githubusercontent.com/pauleve/pint/7cf943ec60afcf285c368950925fd45f59f66f4a/phlib/ph_machine.mli
ocaml
* Initialize random generators used by the machine * Function to plot at the given time the presence of the given process. * [execute env init duration plotter] simulates the environment [env] from the initial state [init] and calls [plotter t p] each time the process [p] appears at time [t]. The simulation stops either when a fix point has been reached, or after [duration] units of time. Returns the resulting state.
module P2Map : Map.S with type key = Ph_types.process * Ph_types.process type env = (Ph_types.PSet.t * Ph_types.rate * Ph_types.PSet.t) list P2Map.t * Create a new execution environment from the given Process Hitting . val create_env : Ph_types.ph -> env val init_random : unit -> unit type plotter = (float -> Ph_types.process -> unit) val execute : env -> Ph_types.state -> float -> plotter -> Ph_types.state
c402fa1127c2e6899bd7fa267f8308cf0a6dbc4bfbb38fd85af9f29dc6869470
falsetru/htdp
43.1.6.scm
#lang racket (define (list-3-averages xs) (build-list (- (length xs) 2) (lambda (i) (/ (+ (list-ref xs (+ i 0)) (list-ref xs (+ i 1)) (list-ref xs (+ i 2))) 3)))) (define (vector-3-averages xs) (build-vector (- (vector-length xs) 2) (lambda (i) (/ (+ (vector-ref xs (+ i 0)) (vector-ref xs (+ i 1)) (vector-ref xs (+ i 2))) 3)))) (define (vector-3-averages! xs result) (local ((define (avg-aux i) (cond [(>= i (vector-length result)) (void)] [else (begin (vector-set! result i (/ (+ (vector-ref xs (+ i 0)) (vector-ref xs (+ i 1)) (vector-ref xs (+ i 2))) 3)) (avg-aux (add1 i))) ]) )) (avg-aux 0))) (require rackunit) (require rackunit/text-ui) (define average-tests (test-suite "Test for average" (test-case "list-3-averages" (define numbers '(110/100 112/100 108/100 109/100 111/100)) (check-equal? (list-3-averages numbers) '(110/100 329/300 82/75)) ) (test-case "vector-3-averages" (define numbers '#(110/100 112/100 108/100 109/100 111/100)) (check-equal? (vector-3-averages numbers) '#(110/100 329/300 82/75)) ) (test-case "vector-3-averages!" (define numbers '#(110/100 112/100 108/100 109/100 111/100)) (define result (make-vector (- (vector-length numbers)2) 0)) (vector-3-averages! numbers result) (check-equal? result '#(110/100 329/300 82/75)) ) )) (exit (run-tests average-tests))
null
https://raw.githubusercontent.com/falsetru/htdp/4cdad3b999f19b89ff4fa7561839cbcbaad274df/43/43.1.6.scm
scheme
#lang racket (define (list-3-averages xs) (build-list (- (length xs) 2) (lambda (i) (/ (+ (list-ref xs (+ i 0)) (list-ref xs (+ i 1)) (list-ref xs (+ i 2))) 3)))) (define (vector-3-averages xs) (build-vector (- (vector-length xs) 2) (lambda (i) (/ (+ (vector-ref xs (+ i 0)) (vector-ref xs (+ i 1)) (vector-ref xs (+ i 2))) 3)))) (define (vector-3-averages! xs result) (local ((define (avg-aux i) (cond [(>= i (vector-length result)) (void)] [else (begin (vector-set! result i (/ (+ (vector-ref xs (+ i 0)) (vector-ref xs (+ i 1)) (vector-ref xs (+ i 2))) 3)) (avg-aux (add1 i))) ]) )) (avg-aux 0))) (require rackunit) (require rackunit/text-ui) (define average-tests (test-suite "Test for average" (test-case "list-3-averages" (define numbers '(110/100 112/100 108/100 109/100 111/100)) (check-equal? (list-3-averages numbers) '(110/100 329/300 82/75)) ) (test-case "vector-3-averages" (define numbers '#(110/100 112/100 108/100 109/100 111/100)) (check-equal? (vector-3-averages numbers) '#(110/100 329/300 82/75)) ) (test-case "vector-3-averages!" (define numbers '#(110/100 112/100 108/100 109/100 111/100)) (define result (make-vector (- (vector-length numbers)2) 0)) (vector-3-averages! numbers result) (check-equal? result '#(110/100 329/300 82/75)) ) )) (exit (run-tests average-tests))
efb407bf636f9d29477e181d68e4000fcb77ebda26e259b8b930ab4c82ae57b8
GaloisInc/ivory
PublicPrivate.hs
# OPTIONS_GHC -fno - warn - orphans # # LANGUAGE DataKinds # # LANGUAGE TypeOperators # # LANGUAGE QuasiQuotes # # LANGUAGE FlexibleInstances # {-# LANGUAGE OverloadedStrings #-} -- | Example of a private struct, defined as a global memory area, with a public -- access function. module PublicPrivate where import Ivory.Language import Ivory.Compile.C.CmdlineFrontend [ivory| struct Foo { foo_i :: Stored Sint32 ; foo_cnt :: Stored Uint32 } |] privateFoo :: MemArea ('Struct "Foo") privateFoo = area "private_foo" $ Just (istruct [foo_i .= ival 0, foo_cnt .= ival 0]) privUpdate :: Def ('[Sint32] ':-> ()) privUpdate = proc "privUpdate" $ \v -> body $ do let foo = addrOf privateFoo curr <- deref (foo ~> foo_cnt) store (foo ~> foo_i) v store (foo~> foo_cnt) (curr+1) pubUpdate :: Def ('[Sint32] ':-> ()) pubUpdate = proc "pubUpdate" $ \v -> body $ do call_ privUpdate v cmodule :: Module cmodule = package "PublicPrivate" $ do private $ do defStruct (Proxy :: Proxy "Foo") defMemArea privateFoo incl privUpdate public $ do incl pubUpdate runPublicPrivate :: IO () runPublicPrivate = runCompiler [cmodule] [] initialOpts { outDir = Nothing, constFold = True }
null
https://raw.githubusercontent.com/GaloisInc/ivory/53a0795b4fbeb0b7da0f6cdaccdde18849a78cd6/ivory-examples/examples/PublicPrivate.hs
haskell
# LANGUAGE OverloadedStrings # | Example of a private struct, defined as a global memory area, with a public access function.
# OPTIONS_GHC -fno - warn - orphans # # LANGUAGE DataKinds # # LANGUAGE TypeOperators # # LANGUAGE QuasiQuotes # # LANGUAGE FlexibleInstances # module PublicPrivate where import Ivory.Language import Ivory.Compile.C.CmdlineFrontend [ivory| struct Foo { foo_i :: Stored Sint32 ; foo_cnt :: Stored Uint32 } |] privateFoo :: MemArea ('Struct "Foo") privateFoo = area "private_foo" $ Just (istruct [foo_i .= ival 0, foo_cnt .= ival 0]) privUpdate :: Def ('[Sint32] ':-> ()) privUpdate = proc "privUpdate" $ \v -> body $ do let foo = addrOf privateFoo curr <- deref (foo ~> foo_cnt) store (foo ~> foo_i) v store (foo~> foo_cnt) (curr+1) pubUpdate :: Def ('[Sint32] ':-> ()) pubUpdate = proc "pubUpdate" $ \v -> body $ do call_ privUpdate v cmodule :: Module cmodule = package "PublicPrivate" $ do private $ do defStruct (Proxy :: Proxy "Foo") defMemArea privateFoo incl privUpdate public $ do incl pubUpdate runPublicPrivate :: IO () runPublicPrivate = runCompiler [cmodule] [] initialOpts { outDir = Nothing, constFold = True }
cfdc80f60cf7cda7df70684397e45e30121c1e2fc71bddd7d89aa4a0b02b9ddf
Idorobots/spartan
rt.rkt
#lang racket ;; The runtime. (require "closures.rkt") (require "continuations.rkt") (require "delimited.rkt") (require "processes.rkt") (require "actor.rkt") (require "scheduler.rkt") (require "monitor.rkt") (require "exceptions.rkt") (require "modules.rkt") (require "bootstrap.rkt") (provide (all-from-out "closures.rkt")) (provide (all-from-out "continuations.rkt")) (provide (all-from-out "delimited.rkt")) (provide (all-from-out "processes.rkt")) (provide (all-from-out "actor.rkt")) (provide (all-from-out "scheduler.rkt")) (provide (all-from-out "monitor.rkt")) (provide (all-from-out "exceptions.rkt")) (provide (all-from-out "modules.rkt")) (provide (all-from-out "bootstrap.rkt")) ;; Also part of the runtime primops: (require "../rete/rete.rkt") (provide (all-from-out "../rete/rete.rkt")) (require "../compiler/utils/refs.rkt") (provide ref deref assign!)
null
https://raw.githubusercontent.com/Idorobots/spartan/ef3b032906655585d284f1c9a33a58f1e35cb180/src/runtime/rt.rkt
racket
The runtime. Also part of the runtime primops:
#lang racket (require "closures.rkt") (require "continuations.rkt") (require "delimited.rkt") (require "processes.rkt") (require "actor.rkt") (require "scheduler.rkt") (require "monitor.rkt") (require "exceptions.rkt") (require "modules.rkt") (require "bootstrap.rkt") (provide (all-from-out "closures.rkt")) (provide (all-from-out "continuations.rkt")) (provide (all-from-out "delimited.rkt")) (provide (all-from-out "processes.rkt")) (provide (all-from-out "actor.rkt")) (provide (all-from-out "scheduler.rkt")) (provide (all-from-out "monitor.rkt")) (provide (all-from-out "exceptions.rkt")) (provide (all-from-out "modules.rkt")) (provide (all-from-out "bootstrap.rkt")) (require "../rete/rete.rkt") (provide (all-from-out "../rete/rete.rkt")) (require "../compiler/utils/refs.rkt") (provide ref deref assign!)
09e582656d146d5ee85bb196eaf7b46823035900d79b92af63c0b1a55b278e20
nbloomf/webdriver-w3c
Types.hs
| Module : Web . Api . WebDriver . Types Description : Typed arguments for WebDriver endpoints . Copyright : 2018 , Automattic , Inc. License : GPL-3 Maintainer : ( ) Stability : experimental Portability : POSIX The WebDriver protocol involves passing several different kinds of JSON objects . We can encode these as /types/ to make our DSL more robust ; this module is a grab bag of these types . For each one we need ` ToJSON ` and ` FromJSON ` instances , and sometimes also a default value . Note that while the WebDriver spec defines some JSON objects , in general a given WebDriver server can accept additional properties on any given object . Our types here will be limited to the " spec " object signatures , but our API will need to be user extensible . Module : Web.Api.WebDriver.Types Description : Typed arguments for WebDriver endpoints. Copyright : 2018, Automattic, Inc. License : GPL-3 Maintainer : Nathan Bloomfield () Stability : experimental Portability : POSIX The WebDriver protocol involves passing several different kinds of JSON objects. We can encode these as /types/ to make our DSL more robust; this module is a grab bag of these types. For each one we need `ToJSON` and `FromJSON` instances, and sometimes also a default value. Note that while the WebDriver spec defines some JSON objects, in general a given WebDriver server can accept additional properties on any given object. Our types here will be limited to the "spec" object signatures, but our API will need to be user extensible. -} # LANGUAGE OverloadedStrings , RecordWildCards , BangPatterns , CPP # module Web.Api.WebDriver.Types ( -- * Stringy Types SessionId , ElementRef(..) , ContextId(..) , ContextType(..) , Selector , AttributeName , PropertyName , AriaRole , AriaLabel , Script , CookieName , CssPropertyName , FrameReference(..) -- * Capabilities , Capabilities(..) , BrowserName(..) , PlatformName(..) , emptyCapabilities , defaultFirefoxCapabilities , headlessFirefoxCapabilities , defaultChromeCapabilities , LogLevel(..) , FirefoxOptions(..) , FirefoxLog(..) , defaultFirefoxOptions , ChromeOptions(..) , defaultChromeOptions -- * Proxy , ProxyConfig(..) , emptyProxyConfig , ProxyType(..) , HostAndOptionalPort(..) -- * Timeout , TimeoutConfig(..) , emptyTimeoutConfig -- * Input and Actions , InputSource(..) , PointerSubtype(..) , InputSourceParameter(..) , Action(..) , emptyAction , ActionType(..) , ActionItem(..) , emptyActionItem -- * Print , PrintOptions(..) , defaultPrintOptions , Orientation(..) , Scale(..) , Page(..) , defaultPage , Margin(..) , defaultMargin , PageRange(..) , Base64EncodedPdf(..) , decodeBase64EncodedPdf , writeBase64EncodedPdf -- * Misc , LocationStrategy(..) , Rect(..) , emptyRect , PromptHandler(..) , Cookie(..) , cookie , emptyCookie -- * Error Responses , ResponseErrorCode(..) ) where #if MIN_VERSION_base(4,9,0) import Prelude hiding (fail) #endif import Control.Monad.IO.Class import qualified Data.ByteString as SB import qualified Data.ByteString.Base64 as B64 import Data.Maybe ( catMaybes ) import Data.Scientific ( Scientific, scientific ) import Data.String ( IsString(..) ) import Data.HashMap.Strict ( HashMap, fromList ) import Data.Aeson.Types ( ToJSON(..), FromJSON(..), Value(..), KeyValue , Pair, (.:?), (.:), (.=), object, typeMismatch ) import Data.Text ( Text, pack, unpack ) import qualified Data.Text as T import Data.Text.Encoding ( encodeUtf8 ) import Test.QuickCheck ( Arbitrary(..), arbitraryBoundedEnum, Gen, NonNegative(..) ) import Test.QuickCheck.Gen ( listOf, oneof, elements ) import Text.Read ( readMaybe ) Transitional MonadFail implementation #if MIN_VERSION_base(4,9,0) import Control.Monad.Fail #endif aeson 2.0.0.0 introduced over #if MIN_VERSION_aeson(2,0,0) import Data.Aeson.Key (fromText) #endif import Web.Api.WebDriver.Uri unrecognizedValue :: (MonadFail m) => Text -> Text -> m a unrecognizedValue !name !string = fail $ unpack $ "Unrecognized value for type " <> name <> ": " <> string malformedValue :: (MonadFail m) => Text -> Text -> m a malformedValue !name !value = fail $ unpack $ "Malformed value for type " <> name <> ": " <> value object_ :: [Maybe Pair] -> Value object_ = object . filter (\(_, v) -> v /= Null) . catMaybes (.==) :: (ToJSON v, KeyValue kv) => Text -> v -> Maybe kv (.==) key value = #if MIN_VERSION_aeson(2,0,0) = lookup ( fromText key ) obj #else Just (key .= value) #endif (.=?) :: (ToJSON v, KeyValue kv) => Text -> Maybe v -> Maybe kv (.=?) key = #if MIN_VERSION_aeson(2,0,0) fmap ((fromText key) .=) #else fmap (key .=) #endif -- | See <-spec.html#dfn-session-id>. type SessionId = Text -- | See <-spec.html#dfn-web-element-reference>. newtype ElementRef = ElementRef { theElementRef :: Text } deriving Eq instance Show ElementRef where show (ElementRef str) = unpack str instance IsString ElementRef where fromString = ElementRef . pack -- | Identifier for a /browsing context/; see <-spec.html#dfn-current-browsing-context>. newtype ContextId = ContextId { theContextId :: Text } deriving Eq instance Show ContextId where show (ContextId str) = unpack str instance IsString ContextId where fromString = ContextId . pack instance FromJSON ContextId where parseJSON (String x) = return $ ContextId x parseJSON invalid = typeMismatch "ContextType" invalid instance ToJSON ContextId where toJSON (ContextId x) = String x instance Arbitrary ContextId where arbitrary = (ContextId . pack) <$> arbitrary -- | Type of a /top level browsing context/; see </#top-level-browsing-context>. data ContextType = WindowContext | TabContext deriving (Eq, Enum, Bounded) instance Show ContextType where show t = case t of WindowContext -> "window" TabContext -> "tab" instance FromJSON ContextType where parseJSON (String x) = case x of "window" -> return WindowContext "tab" -> return TabContext _ -> unrecognizedValue "ContextType" x parseJSON invalid = typeMismatch "ContextType" invalid instance ToJSON ContextType where toJSON WindowContext = String "window" toJSON TabContext = String "tab" instance Arbitrary ContextType where arbitrary = arbitraryBoundedEnum -- | For use with a /Locator Strategy/. See <-spec.html#locator-strategies>. type Selector = Text -- | Used with `getElementAttribute`. type AttributeName = Text | Used with ` getElementProperty ` . type PropertyName = Text | Used with ` getComputedRole ` type AriaRole = Text -- | Used with `getComputedLabel` type AriaLabel = Text -- | Javascript type Script = Text -- | Used with `getNamedCookie`. type CookieName = Text -- | Used with `getElementCssValue`. type CssPropertyName = Text -- | Possible frame references; see <-spec.html#switch-to-frame>. data FrameReference = TopLevelFrame | FrameNumber Int | FrameContainingElement ElementRef deriving (Eq, Show) -- | Semantic HTTP error responses. See <-spec.html#locator-strategies>. data ResponseErrorCode = ElementClickIntercepted | ElementNotSelectable | ElementNotInteractable | InsecureCertificate | InvalidArgument | InvalidCookieDomain | InvalidCoordinates | InvalidElementState | InvalidSelector | InvalidSessionId | JavaScriptError | MoveTargetOutOfBounds | NoSuchAlert | NoSuchCookie | NoSuchElement | NoSuchFrame | NoSuchWindow | ScriptTimeout | SessionNotCreated | StaleElementReference | Timeout | UnableToSetCookie | UnableToCaptureScreen | UnexpectedAlertOpen | UnknownCommand | UnknownError | UnknownMethod | UnsupportedOperation -- | Just in case! | UnhandledErrorCode Text deriving (Eq, Show) instance FromJSON ResponseErrorCode where parseJSON (String x) = case x of "element click intercepted" -> return ElementClickIntercepted "element not selectable" -> return ElementNotSelectable "element not interactable" -> return ElementNotInteractable "insecure certificate" -> return InsecureCertificate "invalid argument" -> return InvalidArgument "invalid cookie domain" -> return InvalidCookieDomain "invalid coordinates" -> return InvalidCoordinates "invalid element state" -> return InvalidElementState "invalid selector" -> return InvalidSelector "invalid session id" -> return InvalidSessionId "javascript error" -> return JavaScriptError "move target out of bounds" -> return MoveTargetOutOfBounds "no such alert" -> return NoSuchAlert "no such cookie" -> return NoSuchCookie "no such element" -> return NoSuchElement "no such frame" -> return NoSuchFrame "no such window" -> return NoSuchWindow "script timeout" -> return ScriptTimeout "session not created" -> return SessionNotCreated "stale element reference" -> return StaleElementReference "timeout" -> return Timeout "unable to set cookie" -> return UnableToSetCookie "unable to capture screen" -> return UnableToCaptureScreen "unexpected alert open" -> return UnexpectedAlertOpen "unknown command" -> return UnknownCommand "unknown error" -> return UnknownError "unknown method" -> return UnknownMethod "unsupported operation" -> return UnsupportedOperation text -> return $ UnhandledErrorCode text parseJSON invalid = typeMismatch "ResponseErrorCode" invalid instance ToJSON ResponseErrorCode where toJSON x = case x of ElementClickIntercepted -> String "element click intercepted" ElementNotSelectable -> String "element not selectable" ElementNotInteractable -> String "element not interactable" InsecureCertificate -> String "insecure certificate" InvalidArgument -> String "invalid argument" InvalidCookieDomain -> String "invalid cookie domain" InvalidCoordinates -> String "invalid coordinates" InvalidElementState -> String "invalid element state" InvalidSelector -> String "invalid selector" InvalidSessionId -> String "invalid session id" JavaScriptError -> String "javascript error" MoveTargetOutOfBounds -> String "move target out of bounds" NoSuchAlert -> String "no such alert" NoSuchCookie -> String "no such cookie" NoSuchElement -> String "no such element" NoSuchFrame -> String "no such frame" NoSuchWindow -> String "no such window" ScriptTimeout -> String "script timeout" SessionNotCreated -> String "session not created" StaleElementReference -> String "stale element reference" Timeout -> String "timeout" UnableToSetCookie -> String "unable to set cookie" UnableToCaptureScreen -> String "unable to capture screen" UnexpectedAlertOpen -> String "unexpected alert open" UnknownCommand -> String "unknown command" UnknownError -> String "unknown error" UnknownMethod -> String "unknown method" UnsupportedOperation -> String "unsupported operation" UnhandledErrorCode msg -> String msg instance Arbitrary ResponseErrorCode where arbitrary = oneof $ map return [ ElementClickIntercepted , ElementNotSelectable , ElementNotInteractable , InsecureCertificate , InvalidArgument , InvalidCookieDomain , InvalidCoordinates , InvalidElementState , InvalidSelector , InvalidSessionId , JavaScriptError , MoveTargetOutOfBounds , NoSuchAlert , NoSuchCookie , NoSuchElement , NoSuchFrame , NoSuchWindow , ScriptTimeout , SessionNotCreated , StaleElementReference , Timeout , UnableToSetCookie , UnableToCaptureScreen , UnexpectedAlertOpen , UnknownCommand , UnknownError , UnknownMethod , UnsupportedOperation ] -- | See <-spec.html#capabilities>. data Capabilities = Capabilities { _browserName :: Maybe BrowserName -- ^ @browserName@ , _browserVersion :: Maybe Text -- ^ @browserVersion@ , _platformName :: Maybe PlatformName -- ^ @platformName@ , _acceptInsecureCerts :: Maybe Bool -- ^ @acceptInsecureCerts@ , _pageLoadStrategy :: Maybe Text -- ^ @pageLoadStrategy@ , _proxy :: Maybe ProxyConfig -- ^ @proxy@ , _setWindowRect :: Maybe Bool -- ^ @setWindowRect@ , _timeouts :: Maybe TimeoutConfig -- ^ @timeouts@ ^ @unhandledPromptBehavior@ -- | Optional extension, but very common. , _chromeOptions :: Maybe ChromeOptions -- ^ @chromeOptions@ -- | Optional extension, but very common. , _firefoxOptions :: Maybe FirefoxOptions -- ^ @moz:firefoxOptions@ } deriving (Eq, Show) instance FromJSON Capabilities where parseJSON (Object v) = Capabilities <$> v .:? "browserName" <*> v .:? "browserVersion" <*> v .:? "platformName" <*> v .:? "acceptInsecureCerts" <*> v .:? "pageLoadStrategy" <*> v .:? "proxy" <*> v .:? "setWindowRect" <*> v .:? "timeouts" <*> v .:? "unhandledPromptBehavior" <*> v .:? "goog:chromeOptions" <*> v .:? "moz:firefoxOptions" parseJSON invalid = typeMismatch "Capabilities" invalid instance ToJSON Capabilities where toJSON Capabilities{..} = object_ [ "browserName" .=? (toJSON <$> _browserName) , "browserVersion" .=? (toJSON <$> _browserVersion) , "platformName" .=? (toJSON <$> _platformName) , "acceptInsecureCerts" .=? (toJSON <$> _acceptInsecureCerts) , "pageLoadStrategy" .=? (toJSON <$> _pageLoadStrategy) , "proxy" .=? (toJSON <$> _proxy) , "setWindowRect" .=? (toJSON <$> _setWindowRect) , "timeouts" .=? (toJSON <$> _timeouts) , "unhandledPromptBehavior" .=? (toJSON <$> _unhandledPromptBehavior) , "goog:chromeOptions" .=? (toJSON <$> _chromeOptions) , "moz:firefoxOptions" .=? (toJSON <$> _firefoxOptions) ] instance Arbitrary Capabilities where arbitrary = Capabilities <$> arbitrary <*> (fmap (fmap T.pack) arbitrary) <*> arbitrary <*> arbitrary <*> (fmap (fmap T.pack) arbitrary) <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary -- | `Capabilities` with all members set to `Nothing`. emptyCapabilities :: Capabilities emptyCapabilities = Capabilities { _browserName = Nothing , _browserVersion = Nothing , _platformName = Nothing , _acceptInsecureCerts = Nothing , _pageLoadStrategy = Nothing , _proxy = Nothing , _setWindowRect = Nothing , _timeouts = Nothing , _unhandledPromptBehavior = Nothing , _chromeOptions = Nothing , _firefoxOptions = Nothing } -- | All members set to `Nothing` except `_browserName`, which is @Just Firefox@. defaultFirefoxCapabilities :: Capabilities defaultFirefoxCapabilities = emptyCapabilities { _browserName = Just Firefox } | Passing the " -headless " parameter to Firefox . headlessFirefoxCapabilities :: Capabilities headlessFirefoxCapabilities = defaultFirefoxCapabilities { _firefoxOptions = Just $ defaultFirefoxOptions { _firefoxArgs = Just ["-headless"] } } -- | All members set to `Nothing` except `_browserName`, which is @Just Chrome@. defaultChromeCapabilities :: Capabilities defaultChromeCapabilities = emptyCapabilities { _browserName = Just Chrome } -- | Used in `Capabilities`. data BrowserName = Firefox | Chrome | Safari deriving (Eq, Show, Enum, Bounded) instance FromJSON BrowserName where parseJSON (String x) = case x of "firefox" -> return Firefox "chrome" -> return Chrome "safari" -> return Safari _ -> unrecognizedValue "BrowserName" x parseJSON invalid = typeMismatch "BrowserName" invalid instance ToJSON BrowserName where toJSON Firefox = String "firefox" toJSON Chrome = String "chrome" toJSON Safari = String "safari" instance Arbitrary BrowserName where arbitrary = arbitraryBoundedEnum -- | Used in `Capabilities`. data PlatformName = Mac deriving (Eq, Show, Enum, Bounded) instance FromJSON PlatformName where parseJSON (String x) = case unpack x of "mac" -> return Mac _ -> unrecognizedValue "PlaformName" x parseJSON invalid = typeMismatch "PlatformName" invalid instance ToJSON PlatformName where toJSON Mac = String "mac" instance Arbitrary PlatformName where arbitrary = arbitraryBoundedEnum -- | See <>. data ChromeOptions = ChromeOptions { _chromeBinary :: Maybe FilePath -- ^ @binary@ , _chromeArgs :: Maybe [Text] -- ^ @args@ , _chromePrefs :: Maybe (HashMap Text Value) -- ^ @prefs@ } deriving (Eq, Show) instance FromJSON ChromeOptions where parseJSON (Object v) = ChromeOptions <$> v .:? "binary" <*> v .:? "args" <*> v .:? "prefs" parseJSON invalid = typeMismatch "ChromeOptions" invalid instance ToJSON ChromeOptions where toJSON ChromeOptions{..} = object_ [ "binary" .=? (toJSON <$> _chromeBinary) , "args" .=? (toJSON <$> _chromeArgs) , "prefs" .=? (toJSON <$> _chromePrefs) ] instance Arbitrary ChromeOptions where arbitrary = ChromeOptions <$> arbitrary <*> (fmap (fmap (fmap T.pack)) arbitrary) <*> arbHashMap -- | All members set to `Nothing`. defaultChromeOptions :: ChromeOptions defaultChromeOptions = ChromeOptions { _chromeBinary = Nothing , _chromeArgs = Nothing , _chromePrefs = Nothing } -- | See <#firefox-capabilities>. data FirefoxOptions = FirefoxOptions { _firefoxBinary :: Maybe FilePath -- ^ @binary@ , _firefoxArgs :: Maybe [Text] -- ^ @args@ , _firefoxLog :: Maybe FirefoxLog , _firefoxPrefs :: Maybe (HashMap Text Value) -- ^ @prefs@ } deriving (Eq, Show) instance FromJSON FirefoxOptions where parseJSON (Object v) = FirefoxOptions <$> v .:? "binary" <*> v .:? "args" <*> v .:? "log" <*> v .:? "prefs" parseJSON invalid = typeMismatch "FirefoxOptions" invalid instance ToJSON FirefoxOptions where toJSON FirefoxOptions{..} = object_ [ "binary" .=? (toJSON <$> _firefoxBinary) , "args" .=? (toJSON <$> _firefoxArgs) , "log" .=? (toJSON <$> _firefoxLog) , "prefs" .=? (toJSON <$> _firefoxPrefs) ] instance Arbitrary FirefoxOptions where arbitrary = FirefoxOptions <$> arbitrary <*> (fmap (fmap (fmap T.pack)) arbitrary) <*> arbitrary <*> arbHashMap arbHashMap :: Gen (Maybe (HashMap Text Value)) arbHashMap = do p <- arbitrary if p then return Nothing else do m <- fromList <$> listOf (mPair arbKey arbPrefVal) return $ Just m arbKey :: Gen Text arbKey = pack <$> ('k':) <$> arbitrary arbText :: Gen Text arbText = pack <$> arbitrary arbPrefVal :: Gen Value arbPrefVal = do k <- arbitrary :: Gen Int case k`mod`3 of 0 -> Bool <$> arbitrary 1 -> String <$> arbText _ -> Number <$> arbScientific mPair :: (Monad m) => m a -> m b -> m (a,b) mPair ga gb = do a <- ga b <- gb return (a,b) -- | All members set to `Nothing`. defaultFirefoxOptions :: FirefoxOptions defaultFirefoxOptions = FirefoxOptions { _firefoxBinary = Nothing , _firefoxArgs = Nothing , _firefoxLog = Nothing , _firefoxPrefs = Nothing } -- | See <#log-object>. newtype FirefoxLog = FirefoxLog { _firefoxLogLevel :: Maybe LogLevel } deriving (Eq, Show) instance FromJSON FirefoxLog where parseJSON (Object v) = FirefoxLog <$> v .:? "level" parseJSON invalid = typeMismatch "FirefoxLog" invalid instance ToJSON FirefoxLog where toJSON FirefoxLog{..} = object_ [ "level" .=? (toJSON <$> _firefoxLogLevel) ] instance Arbitrary FirefoxLog where arbitrary = FirefoxLog <$> arbitrary -- | See <#log-object>. data LogLevel = LogTrace | LogDebug | LogConfig | LogInfo | LogWarn | LogError | LogFatal deriving (Eq, Show, Enum, Bounded) instance FromJSON LogLevel where parseJSON (String x) = case x of "trace" -> return LogTrace "debug" -> return LogDebug "config" -> return LogConfig "info" -> return LogInfo "warn" -> return LogWarn "error" -> return LogError "fatal" -> return LogFatal _ -> unrecognizedValue "LogLevel" x parseJSON invalid = typeMismatch "LogLevel" invalid instance ToJSON LogLevel where toJSON x = case x of LogTrace -> String "trace" LogDebug -> String "debug" LogConfig -> String "config" LogInfo -> String "info" LogWarn -> String "warn" LogError -> String "error" LogFatal -> String "fatal" instance Arbitrary LogLevel where arbitrary = arbitraryBoundedEnum -- | See <-spec.html#proxy>. data ProxyConfig = ProxyConfig { _proxyType :: Maybe ProxyType -- ^ @proxyType@ , _proxyAutoconfigUrl :: Maybe Text -- ^ @proxyAutoconfigUrl@ ^ , _httpProxy :: Maybe HostAndOptionalPort -- ^ @httpProxy@ ^ @noProxy@ , _sslProxy :: Maybe HostAndOptionalPort -- ^ @sslProxy@ ^ @socksProxy@ , _socksVersion :: Maybe Int -- ^ @socksVersion@ } deriving (Eq, Show) instance FromJSON ProxyConfig where parseJSON (Object v) = ProxyConfig <$> v .:? "proxyType" <*> v .:? "proxyAutoconfigUrl" <*> v .:? "ftpProxy" <*> v .:? "httpProxy" <*> v .:? "noProxy" <*> v .:? "sslProxy" <*> v .:? "socksProxy" <*> v .:? "socksVersion" parseJSON invalid = typeMismatch "ProxyConfig" invalid instance ToJSON ProxyConfig where toJSON ProxyConfig{..} = object_ [ "proxyType" .=? (toJSON <$> _proxyType) , "proxyAutoconfigUrl" .=? (toJSON <$> _proxyAutoconfigUrl) , "ftpProxy" .=? (toJSON <$> _ftpProxy) , "httpProxy" .=? (toJSON <$> _httpProxy) , "noProxy" .=? (toJSON <$> _noProxy) , "sslProxy" .=? (toJSON <$> _sslProxy) , "socksProxy" .=? (toJSON <$> _socksProxy) , "socksVersion" .=? (toJSON <$> _socksVersion) ] instance Arbitrary ProxyConfig where arbitrary = ProxyConfig <$> arbitrary <*> (fmap (fmap T.pack) arbitrary) <*> arbitrary <*> arbitrary <*> (fmap (fmap (fmap T.pack)) arbitrary) <*> arbitrary <*> arbitrary <*> arbitrary | ` ` object with all members set to ` Nothing ` . emptyProxyConfig :: ProxyConfig emptyProxyConfig = ProxyConfig { _proxyType = Nothing , _proxyAutoconfigUrl = Nothing , _ftpProxy = Nothing , _httpProxy = Nothing , _noProxy = Nothing , _sslProxy = Nothing , _socksProxy = Nothing , _socksVersion = Nothing } -- | See <-spec.html#dfn-host-and-optional-port>. data HostAndOptionalPort = HostAndOptionalPort { _urlHost :: Host , _urlPort :: Maybe Port } deriving (Eq, Show) instance FromJSON HostAndOptionalPort where parseJSON (String string) = let (as,bs') = T.span (/= ':') string in if T.null as then malformedValue "Host" string else case T.uncons bs' of Nothing -> case mkHost as of Nothing -> malformedValue "Host" string Just h -> return HostAndOptionalPort { _urlHost = h , _urlPort = Nothing } Just (c,bs) -> if c /= ':' then malformedValue "Host" string else if T.null bs then malformedValue "Port" string else case mkHost as of Nothing -> malformedValue "Host" string Just h -> case mkPort bs of Nothing -> malformedValue "Port" bs Just p -> return HostAndOptionalPort { _urlHost = h , _urlPort = Just p } parseJSON invalid = typeMismatch "HostAndOptionalPort" invalid instance ToJSON HostAndOptionalPort where toJSON HostAndOptionalPort{..} = case _urlPort of Nothing -> String $ pack $ show _urlHost Just pt -> String $ pack $ concat [show _urlHost, ":", show pt] instance Arbitrary HostAndOptionalPort where arbitrary = HostAndOptionalPort <$> arbitrary <*> arbitrary -- | See <-spec.html#dfn-proxytype>. data ProxyType = ProxyPac -- ^ @pac@ ^ @direct@ | ProxyAutodetect -- ^ @autodetect@ | ProxySystem -- ^ @system@ | ProxyManual -- ^ @manual@ deriving (Eq, Show, Enum, Bounded) instance FromJSON ProxyType where parseJSON (String x) = case x of "pac" -> return ProxyPac "direct" -> return ProxyDirect "autodetect" -> return ProxyAutodetect "system" -> return ProxySystem "manual" -> return ProxyManual _ -> unrecognizedValue "ProxyType" x parseJSON invalid = typeMismatch "ProxyType" invalid instance ToJSON ProxyType where toJSON x = case x of ProxyPac -> String "pac" ProxyDirect -> String "direct" ProxyAutodetect -> String "autodetect" ProxySystem -> String "system" ProxyManual -> String "manual" instance Arbitrary ProxyType where arbitrary = arbitraryBoundedEnum -- | See <-spec.html#dfn-timeouts>. data TimeoutConfig = TimeoutConfig { _script :: Maybe Int -- ^ @script@ , _pageLoad :: Maybe Int -- ^ @pageLoad@ , _implicit :: Maybe Int -- ^ @implicit@ } deriving (Eq, Show) instance FromJSON TimeoutConfig where parseJSON (Object v) = TimeoutConfig <$> v .:? "script" <*> v .:? "pageLoad" <*> v .:? "implicit" parseJSON invalid = typeMismatch "TimeoutConfig" invalid instance ToJSON TimeoutConfig where toJSON TimeoutConfig{..} = object_ [ "script" .== (toJSON <$> _script) , "pageLoad" .== (toJSON <$> _pageLoad) , "implicit" .== (toJSON <$> _implicit) ] instance Arbitrary TimeoutConfig where arbitrary = TimeoutConfig <$> arbitrary <*> arbitrary <*> arbitrary -- | `TimeoutConfig` object with all members set to `Nothing`. emptyTimeoutConfig :: TimeoutConfig emptyTimeoutConfig = TimeoutConfig { _script = Nothing , _pageLoad = Nothing , _implicit = Nothing } -- | See <-spec.html#dfn-table-of-location-strategies>. data LocationStrategy = CssSelector -- ^ @css selector@ | LinkTextSelector -- ^ @link text@ | PartialLinkTextSelector -- ^ @partial link text@ | TagName -- ^ @tag name@ ^ @xpath@ deriving (Eq, Show, Enum, Bounded) instance FromJSON LocationStrategy where parseJSON (String x) = case x of "css selector" -> return CssSelector "link text" -> return LinkTextSelector "partial link text" -> return PartialLinkTextSelector "tag name" -> return TagName "xpath" -> return XPathSelector _ -> unrecognizedValue "LocationStrategy" x parseJSON invalid = typeMismatch "LocationStrategy" invalid instance ToJSON LocationStrategy where toJSON x = case x of CssSelector -> String "css selector" LinkTextSelector -> String "link text" PartialLinkTextSelector -> String "partial link text" TagName -> String "tag name" XPathSelector -> String "xpath" instance Arbitrary LocationStrategy where arbitrary = arbitraryBoundedEnum -- | See <-spec.html#dfn-input-sources>. data InputSource = NullInputSource -- ^ @null@ | KeyInputSource -- ^ @key@ | PointerInputSource -- ^ @pointer@ deriving (Eq, Show, Enum, Bounded) instance FromJSON InputSource where parseJSON (String x) = case x of "null" -> return NullInputSource "key" -> return KeyInputSource "pointer" -> return PointerInputSource _ -> unrecognizedValue "InputSource" x parseJSON invalid = typeMismatch "InputSource" invalid instance ToJSON InputSource where toJSON x = case x of NullInputSource -> String "null" KeyInputSource -> String "key" PointerInputSource -> String "pointer" instance Arbitrary InputSource where arbitrary = arbitraryBoundedEnum -- | See <-spec.html#dfn-pointer-input-state>. data PointerSubtype = PointerMouse -- ^ @mouse@ ^ @pen@ | PointerTouch -- ^ @touch@ deriving (Eq, Show, Enum, Bounded) instance FromJSON PointerSubtype where parseJSON (String x) = case x of "mouse" -> return PointerMouse "pen" -> return PointerPen "touch" -> return PointerTouch _ -> unrecognizedValue "PointerSubtype" x parseJSON invalid = typeMismatch "PointerSubtype" invalid instance ToJSON PointerSubtype where toJSON x = case x of PointerMouse -> String "mouse" PointerPen -> String "pen" PointerTouch -> String "touch" instance Arbitrary PointerSubtype where arbitrary = arbitraryBoundedEnum -- | See <-spec.html#processing-actions-requests>. data Action = Action { _inputSourceType :: Maybe InputSource -- ^ @type@ , _inputSourceId :: Maybe Text -- ^ @id@ , _inputSourceParameters :: Maybe InputSourceParameter -- ^ @parameters@ , _actionItems :: [ActionItem] -- ^ @actions@ } deriving (Eq, Show) instance FromJSON Action where parseJSON (Object v) = Action <$> v .:? "type" <*> v .:? "id" <*> v .:? "parameters" <*> v .: "actions" parseJSON invalid = typeMismatch "Action" invalid instance ToJSON Action where toJSON Action{..} = object_ [ "type" .=? (toJSON <$> _inputSourceType) , "id" .=? (toJSON <$> _inputSourceId) , "parameters" .=? (toJSON <$> _inputSourceParameters) , "actions" .== (toJSON <$> _actionItems) ] instance Arbitrary Action where arbitrary = Action <$> arbitrary <*> (fmap (fmap T.pack) arbitrary) <*> arbitrary <*> arbitrary | All members set to ` Nothing ` except ` _ actionItems ` , which is the empty list . emptyAction :: Action emptyAction = Action { _inputSourceType = Nothing , _inputSourceId = Nothing , _inputSourceParameters = Nothing , _actionItems = [] } -- | See <-spec.html#terminology-0>. data ActionType = PauseAction -- ^ @pause@ | KeyUpAction -- ^ @keyUp@ | KeyDownAction -- ^ @keyDown@ | PointerDownAction -- ^ @pointerDown@ | PointerUpAction -- ^ @pointerUp@ | PointerMoveAction -- ^ @pointerMove@ | PointerCancelAction -- ^ @pointerCancel@ deriving (Eq, Show, Enum, Bounded) instance FromJSON ActionType where parseJSON (String x) = case x of "pause" -> return PauseAction "keyUp" -> return KeyUpAction "keyDown" -> return KeyDownAction "pointerDown" -> return PointerDownAction "pointerUp" -> return PointerUpAction "pointerMove" -> return PointerMoveAction "pointerCancel" -> return PointerCancelAction _ -> unrecognizedValue "ActionType" x parseJSON invalid = typeMismatch "ActionType" invalid instance ToJSON ActionType where toJSON x = case x of PauseAction -> String "pause" KeyUpAction -> String "keyUp" KeyDownAction -> String "keyDown" PointerDownAction -> String "pointerDown" PointerUpAction -> String "pointerUp" PointerMoveAction -> String "pointerMove" PointerCancelAction -> String "pointerCancel" instance Arbitrary ActionType where arbitrary = arbitraryBoundedEnum -- | See <-spec.html#dfn-pointer-input-state>. newtype InputSourceParameter = InputSourceParameter { _pointerSubtype :: Maybe PointerSubtype -- ^ @subtype@ } deriving (Eq, Show) instance FromJSON InputSourceParameter where parseJSON (Object v) = InputSourceParameter <$> v .:? "subtype" parseJSON invalid = typeMismatch "InputSourceParameter" invalid instance ToJSON InputSourceParameter where toJSON InputSourceParameter{..} = object_ [ "subtype" .=? (toJSON <$> _pointerSubtype) ] instance Arbitrary InputSourceParameter where arbitrary = InputSourceParameter <$> arbitrary -- | See <-spec.html#dfn-process-an-input-source-action-sequence>. data ActionItem = ActionItem { _actionType :: Maybe ActionType -- ^ @type@ , _actionDuration :: Maybe Int -- ^ @duration@ , _actionOrigin :: Maybe Text -- ^ @origin@ , _actionValue :: Maybe Text -- ^ @value@ , _actionButton :: Maybe Int -- ^ @button@ , _actionX :: Maybe Int -- ^ @x@ , _actionY :: Maybe Int -- ^ @y@ } deriving (Eq, Show) instance FromJSON ActionItem where parseJSON (Object v) = ActionItem <$> v .:? "type" <*> v .:? "duration" <*> v .:? "origin" <*> v .:? "value" <*> v .:? "button" <*> v .:? "x" <*> v .:? "y" parseJSON invalid = typeMismatch "ActionItem" invalid instance ToJSON ActionItem where toJSON ActionItem{..} = object_ [ "type" .=? (toJSON <$> _actionType) , "duration" .=? (toJSON <$> _actionDuration) , "origin" .=? (toJSON <$> _actionOrigin) , "value" .=? (toJSON <$> _actionValue) , "button" .=? (toJSON <$> _actionButton) , "x" .=? (toJSON <$> _actionX) , "y" .=? (toJSON <$> _actionY) ] instance Arbitrary ActionItem where arbitrary = ActionItem <$> arbitrary <*> arbitrary <*> (fmap (fmap T.pack) arbitrary) <*> (fmap (fmap T.pack) arbitrary) <*> arbitrary <*> arbitrary <*> arbitrary -- | All members set to `Nothing`. emptyActionItem :: ActionItem emptyActionItem = ActionItem { _actionType = Nothing , _actionDuration = Nothing , _actionOrigin = Nothing , _actionValue = Nothing , _actionButton = Nothing , _actionX = Nothing , _actionY = Nothing } -- | See <-spec.html#get-element-rect>. data Rect = Rect { _rectX :: Scientific -- ^ @x@ , _rectY :: Scientific -- ^ @y@ , _rectWidth :: Scientific -- ^ @width@ , _rectHeight :: Scientific -- ^ @height@ } deriving (Eq, Show) instance ToJSON Rect where toJSON Rect{..} = object [ "x" .= toJSON _rectX , "y" .= toJSON _rectY , "width" .= toJSON _rectWidth , "height" .= toJSON _rectHeight ] instance FromJSON Rect where parseJSON (Object v) = Rect <$> v .: "x" <*> v .: "y" <*> v .: "width" <*> v .: "height" parseJSON invalid = typeMismatch "Rect" invalid arbScientific :: Gen Scientific arbScientific = scientific <$> arbitrary <*> arbitrary instance Arbitrary Rect where arbitrary = Rect <$> arbScientific <*> arbScientific <*> arbScientific <*> arbScientific -- | All members set to `0`. emptyRect :: Rect emptyRect = Rect { _rectX = 0 , _rectY = 0 , _rectWidth = 0 , _rectHeight = 0 } -- | See <-spec.html#dfn-known-prompt-handling-approaches-table>. data PromptHandler = DismissPrompts -- ^ @dismiss@ | AcceptPrompts -- ^ @accept@ | DismissPromptsAndNotify -- ^ @dismiss and notify@ | AcceptPromptsAndNotify -- ^ @accept and notify@ | IgnorePrompts -- ^ @ignore@ deriving (Eq, Show, Enum, Bounded) instance FromJSON PromptHandler where parseJSON (String x) = case x of "dismiss" -> return DismissPrompts "accept" -> return AcceptPrompts "dismiss and notify" -> return DismissPromptsAndNotify "accept and notify" -> return AcceptPromptsAndNotify "ignore" -> return IgnorePrompts _ -> unrecognizedValue "PromptHandler" x parseJSON invalid = typeMismatch "PromptHandler" invalid instance ToJSON PromptHandler where toJSON x = case x of DismissPrompts -> String "dismiss" AcceptPrompts -> String "accept" DismissPromptsAndNotify -> String "dismiss and notify" AcceptPromptsAndNotify -> String "accept and notify" IgnorePrompts -> String "ignore" instance Arbitrary PromptHandler where arbitrary = arbitraryBoundedEnum -- | See <-spec.html#dfn-table-for-cookie-conversion>. data Cookie = Cookie { _cookieName :: Maybe Text -- ^ @name@ , _cookieValue :: Maybe Text -- ^ @value@ , _cookiePath :: Maybe Text -- ^ @path@ , _cookieDomain :: Maybe Text -- ^ @domain@ , _cookieSecure :: Maybe Bool -- ^ @secure@ , _cookieHttpOnly :: Maybe Bool -- ^ @httpOnly@ ^ @expiryTime@ } deriving (Eq, Show) instance ToJSON Cookie where toJSON Cookie{..} = object_ [ "name" .=? (toJSON <$> _cookieName) , "value" .=? (toJSON <$> _cookieValue) , "path" .=? (toJSON <$> _cookiePath) , "domain" .=? (toJSON <$> _cookieDomain) , "secure" .=? (toJSON <$> _cookieSecure) , "httpOnly" .=? (toJSON <$> _cookieHttpOnly) , "expiryTime" .=? (toJSON <$> _cookieExpiryTime) ] instance FromJSON Cookie where parseJSON (Object v) = Cookie <$> v .:? "name" <*> v .:? "value" <*> v .:? "path" <*> v .:? "domain" <*> v .:? "secure" <*> v .:? "httpOnly" <*> v .:? "expiryTime" parseJSON invalid = typeMismatch "Cookie" invalid instance Arbitrary Cookie where arbitrary = Cookie <$> (fmap (fmap T.pack) arbitrary) <*> (fmap (fmap T.pack) arbitrary) <*> (fmap (fmap T.pack) arbitrary) <*> (fmap (fmap T.pack) arbitrary) <*> arbitrary <*> arbitrary <*> (fmap (fmap T.pack) arbitrary) -- | All members set to `Nothing`. emptyCookie :: Cookie emptyCookie = Cookie { _cookieName = Nothing , _cookieValue = Nothing , _cookiePath = Nothing , _cookieDomain = Nothing , _cookieSecure = Nothing , _cookieHttpOnly = Nothing , _cookieExpiryTime = Nothing } -- | All members other than @name@ and @value@ set to `Nothing`. cookie :: Text -- ^ @name@ -> Text -- ^ @value@ -> Cookie cookie name value = emptyCookie { _cookieName = Just name , _cookieValue = Just value } -- | See </#print-page> data PrintOptions = PrintOptions { _orientation :: Maybe Orientation -- ^ @orientation@ , _scale :: Maybe Scale -- ^ @scale@ , _background :: Maybe Bool -- ^ @background@ , _page :: Maybe Page -- ^ @page@ , _margin :: Maybe Margin -- ^ @margin@ , _shrinkToFit :: Maybe Bool -- ^ @shrinkToFit@ , _pageRanges :: Maybe [PageRange] -- ^ @pageRanges@ } deriving (Eq, Show) defaultPrintOptions :: PrintOptions defaultPrintOptions = PrintOptions { _orientation = Nothing , _scale = Nothing , _background = Nothing , _page = Nothing , _margin = Nothing , _shrinkToFit = Nothing , _pageRanges = Nothing } instance ToJSON PrintOptions where toJSON PrintOptions{..} = object_ [ "orientation" .=? (toJSON <$> _orientation) , "scale" .=? (toJSON <$> _scale) , "background" .=? (toJSON <$> _background) , "page" .=? (toJSON <$> _page) , "margin" .=? (toJSON <$> _margin) , "shrinkToFit" .=? (toJSON <$> _shrinkToFit) , "pageRanges" .=? (toJSON <$> _pageRanges) ] instance FromJSON PrintOptions where parseJSON (Object v) = PrintOptions <$> v .:? "orientation" <*> v .:? "scale" <*> v .:? "background" <*> v .:? "page" <*> v .:? "margin" <*> v .:? "shrinkToFit" <*> v .:? "pageRanges" parseJSON invalid = typeMismatch "PrintOptions" invalid instance Arbitrary PrintOptions where arbitrary = PrintOptions <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary data Orientation = Landscape | Portrait deriving (Eq, Show, Enum, Bounded) instance FromJSON Orientation where parseJSON (String x) = case x of "landscape" -> return Landscape "portrait" -> return Portrait _ -> unrecognizedValue "Orientation" x parseJSON invalid = typeMismatch "Orientation" invalid instance ToJSON Orientation where toJSON x = case x of Landscape -> String "landscape" Portrait -> String "portrait" instance Arbitrary Orientation where arbitrary = arbitraryBoundedEnum newtype Scale = Scale Scientific deriving (Eq, Show) instance ToJSON Scale where toJSON (Scale x) = toJSON x instance FromJSON Scale where parseJSON = fmap Scale . parseJSON TODO : fix this arbitrary = Scale <$> elements [ 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 , 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0 ] data Page = Page { _pageWidth :: Maybe Scientific -- ^ @pageWidth@ , _pageHeight :: Maybe Scientific -- ^ @pageHeight@ } deriving (Eq, Show) defaultPage :: Page defaultPage = Page { _pageWidth = Nothing , _pageHeight = Nothing } instance ToJSON Page where toJSON Page{..} = object_ [ "pageWidth" .=? (toJSON <$> _pageWidth) , "pageHeight" .=? (toJSON <$> _pageHeight) ] instance FromJSON Page where parseJSON (Object v) = Page <$> v .:? "pageWidth" <*> v .:? "pageHeight" parseJSON invalid = typeMismatch "Page" invalid instance Arbitrary Page where arbitrary = let margins = map negate [ 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9 , 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9 ] in Page <$> oneof [ return Nothing, Just <$> elements (map (27.94 +) margins) ] <*> oneof [ return Nothing, Just <$> elements (map (21.59 +) margins) ] data Margin = Margin { _marginTop :: Maybe Scientific -- ^ @marginTop@ , _marginBottom :: Maybe Scientific -- ^ @marginBottom@ , _marginLeft :: Maybe Scientific -- ^ @marginLeft@ , _marginRight :: Maybe Scientific -- ^ @marginRight@ } deriving (Eq, Show) defaultMargin :: Margin defaultMargin = Margin { _marginTop = Nothing , _marginBottom = Nothing , _marginLeft = Nothing , _marginRight = Nothing } instance ToJSON Margin where toJSON Margin{..} = object_ [ "marginTop" .=? (toJSON <$> _marginTop) , "marginBottom" .=? (toJSON <$> _marginBottom) , "marginLeft" .=? (toJSON <$> _marginLeft) , "marginRight" .=? (toJSON <$> _marginRight) ] instance FromJSON Margin where parseJSON (Object v) = Margin <$> v .:? "marginTop" <*> v .:? "marginBottom" <*> v .:? "marginLeft" <*> v .:? "marginRight" parseJSON invalid = typeMismatch "Margin" invalid instance Arbitrary Margin where arbitrary = let margins = [ 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9 , 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9 ] in Margin <$> oneof [ return Nothing, Just <$> elements margins ] <*> oneof [ return Nothing, Just <$> elements margins ] <*> oneof [ return Nothing, Just <$> elements margins ] <*> oneof [ return Nothing, Just <$> elements margins ] data PageRange = OnePage Int | PageRange Int Int deriving (Eq, Show) instance ToJSON PageRange where toJSON x = case x of OnePage k -> String $ pack $ show k PageRange a b -> String $ mconcat [ pack $ show a, "-", pack $ show b ] instance FromJSON PageRange where parseJSON (String str) = let (as, bs') = T.break (== '-') str in case T.uncons bs' of Nothing -> case readMaybe $ unpack as of Just k -> return $ OnePage k Nothing -> malformedValue "page range" str Just (_,bs) -> if (T.null as) || (T.null bs) then malformedValue "page range" str else case (readMaybe $ unpack as, readMaybe $ unpack bs) of (Just a, Just b) -> return $ PageRange a b _ -> malformedValue "page range" str parseJSON invalid = typeMismatch "PageRange" invalid instance Arbitrary PageRange where arbitrary = do NonNegative a <- fmap (fmap (`mod` 100)) arbitrary oneof [ return $ OnePage a , do NonNegative b <- fmap (fmap (`mod` 100)) arbitrary return $ PageRange (min a b) (max a b) ] newtype Base64EncodedPdf = Base64EncodedPdf SB.ByteString deriving (Eq, Show) instance FromJSON Base64EncodedPdf where parseJSON (String s) = return $ Base64EncodedPdf $ encodeUtf8 s parseJSON invalid = typeMismatch "Base64EncodedPdf" invalid decodeBase64EncodedPdf :: Base64EncodedPdf -> SB.ByteString decodeBase64EncodedPdf (Base64EncodedPdf bytes) = B64.decodeLenient bytes writeBase64EncodedPdf :: ( MonadIO m ) => FilePath -> Base64EncodedPdf -> m () writeBase64EncodedPdf path pdf = liftIO $ SB.writeFile path $ decodeBase64EncodedPdf pdf
null
https://raw.githubusercontent.com/nbloomf/webdriver-w3c/45628198887d221375a110857d045ed183221d63/src/Web/Api/WebDriver/Types.hs
haskell
* Stringy Types * Capabilities * Proxy * Timeout * Input and Actions * Print * Misc * Error Responses | See <-spec.html#dfn-session-id>. | See <-spec.html#dfn-web-element-reference>. | Identifier for a /browsing context/; see <-spec.html#dfn-current-browsing-context>. | Type of a /top level browsing context/; see </#top-level-browsing-context>. | For use with a /Locator Strategy/. See <-spec.html#locator-strategies>. | Used with `getElementAttribute`. | Used with `getComputedLabel` | Javascript | Used with `getNamedCookie`. | Used with `getElementCssValue`. | Possible frame references; see <-spec.html#switch-to-frame>. | Semantic HTTP error responses. See <-spec.html#locator-strategies>. | Just in case! | See <-spec.html#capabilities>. ^ @browserName@ ^ @browserVersion@ ^ @platformName@ ^ @acceptInsecureCerts@ ^ @pageLoadStrategy@ ^ @proxy@ ^ @setWindowRect@ ^ @timeouts@ | Optional extension, but very common. ^ @chromeOptions@ | Optional extension, but very common. ^ @moz:firefoxOptions@ | `Capabilities` with all members set to `Nothing`. | All members set to `Nothing` except `_browserName`, which is @Just Firefox@. | All members set to `Nothing` except `_browserName`, which is @Just Chrome@. | Used in `Capabilities`. | Used in `Capabilities`. | See <>. ^ @binary@ ^ @args@ ^ @prefs@ | All members set to `Nothing`. | See <#firefox-capabilities>. ^ @binary@ ^ @args@ ^ @prefs@ | All members set to `Nothing`. | See <#log-object>. | See <#log-object>. | See <-spec.html#proxy>. ^ @proxyType@ ^ @proxyAutoconfigUrl@ ^ @httpProxy@ ^ @sslProxy@ ^ @socksVersion@ | See <-spec.html#dfn-host-and-optional-port>. | See <-spec.html#dfn-proxytype>. ^ @pac@ ^ @autodetect@ ^ @system@ ^ @manual@ | See <-spec.html#dfn-timeouts>. ^ @script@ ^ @pageLoad@ ^ @implicit@ | `TimeoutConfig` object with all members set to `Nothing`. | See <-spec.html#dfn-table-of-location-strategies>. ^ @css selector@ ^ @link text@ ^ @partial link text@ ^ @tag name@ | See <-spec.html#dfn-input-sources>. ^ @null@ ^ @key@ ^ @pointer@ | See <-spec.html#dfn-pointer-input-state>. ^ @mouse@ ^ @touch@ | See <-spec.html#processing-actions-requests>. ^ @type@ ^ @id@ ^ @parameters@ ^ @actions@ | See <-spec.html#terminology-0>. ^ @pause@ ^ @keyUp@ ^ @keyDown@ ^ @pointerDown@ ^ @pointerUp@ ^ @pointerMove@ ^ @pointerCancel@ | See <-spec.html#dfn-pointer-input-state>. ^ @subtype@ | See <-spec.html#dfn-process-an-input-source-action-sequence>. ^ @type@ ^ @duration@ ^ @origin@ ^ @value@ ^ @button@ ^ @x@ ^ @y@ | All members set to `Nothing`. | See <-spec.html#get-element-rect>. ^ @x@ ^ @y@ ^ @width@ ^ @height@ | All members set to `0`. | See <-spec.html#dfn-known-prompt-handling-approaches-table>. ^ @dismiss@ ^ @accept@ ^ @dismiss and notify@ ^ @accept and notify@ ^ @ignore@ | See <-spec.html#dfn-table-for-cookie-conversion>. ^ @name@ ^ @value@ ^ @path@ ^ @domain@ ^ @secure@ ^ @httpOnly@ | All members set to `Nothing`. | All members other than @name@ and @value@ set to `Nothing`. ^ @name@ ^ @value@ | See </#print-page> ^ @orientation@ ^ @scale@ ^ @background@ ^ @page@ ^ @margin@ ^ @shrinkToFit@ ^ @pageRanges@ ^ @pageWidth@ ^ @pageHeight@ ^ @marginTop@ ^ @marginBottom@ ^ @marginLeft@ ^ @marginRight@
| Module : Web . Api . WebDriver . Types Description : Typed arguments for WebDriver endpoints . Copyright : 2018 , Automattic , Inc. License : GPL-3 Maintainer : ( ) Stability : experimental Portability : POSIX The WebDriver protocol involves passing several different kinds of JSON objects . We can encode these as /types/ to make our DSL more robust ; this module is a grab bag of these types . For each one we need ` ToJSON ` and ` FromJSON ` instances , and sometimes also a default value . Note that while the WebDriver spec defines some JSON objects , in general a given WebDriver server can accept additional properties on any given object . Our types here will be limited to the " spec " object signatures , but our API will need to be user extensible . Module : Web.Api.WebDriver.Types Description : Typed arguments for WebDriver endpoints. Copyright : 2018, Automattic, Inc. License : GPL-3 Maintainer : Nathan Bloomfield () Stability : experimental Portability : POSIX The WebDriver protocol involves passing several different kinds of JSON objects. We can encode these as /types/ to make our DSL more robust; this module is a grab bag of these types. For each one we need `ToJSON` and `FromJSON` instances, and sometimes also a default value. Note that while the WebDriver spec defines some JSON objects, in general a given WebDriver server can accept additional properties on any given object. Our types here will be limited to the "spec" object signatures, but our API will need to be user extensible. -} # LANGUAGE OverloadedStrings , RecordWildCards , BangPatterns , CPP # module Web.Api.WebDriver.Types ( SessionId , ElementRef(..) , ContextId(..) , ContextType(..) , Selector , AttributeName , PropertyName , AriaRole , AriaLabel , Script , CookieName , CssPropertyName , FrameReference(..) , Capabilities(..) , BrowserName(..) , PlatformName(..) , emptyCapabilities , defaultFirefoxCapabilities , headlessFirefoxCapabilities , defaultChromeCapabilities , LogLevel(..) , FirefoxOptions(..) , FirefoxLog(..) , defaultFirefoxOptions , ChromeOptions(..) , defaultChromeOptions , ProxyConfig(..) , emptyProxyConfig , ProxyType(..) , HostAndOptionalPort(..) , TimeoutConfig(..) , emptyTimeoutConfig , InputSource(..) , PointerSubtype(..) , InputSourceParameter(..) , Action(..) , emptyAction , ActionType(..) , ActionItem(..) , emptyActionItem , PrintOptions(..) , defaultPrintOptions , Orientation(..) , Scale(..) , Page(..) , defaultPage , Margin(..) , defaultMargin , PageRange(..) , Base64EncodedPdf(..) , decodeBase64EncodedPdf , writeBase64EncodedPdf , LocationStrategy(..) , Rect(..) , emptyRect , PromptHandler(..) , Cookie(..) , cookie , emptyCookie , ResponseErrorCode(..) ) where #if MIN_VERSION_base(4,9,0) import Prelude hiding (fail) #endif import Control.Monad.IO.Class import qualified Data.ByteString as SB import qualified Data.ByteString.Base64 as B64 import Data.Maybe ( catMaybes ) import Data.Scientific ( Scientific, scientific ) import Data.String ( IsString(..) ) import Data.HashMap.Strict ( HashMap, fromList ) import Data.Aeson.Types ( ToJSON(..), FromJSON(..), Value(..), KeyValue , Pair, (.:?), (.:), (.=), object, typeMismatch ) import Data.Text ( Text, pack, unpack ) import qualified Data.Text as T import Data.Text.Encoding ( encodeUtf8 ) import Test.QuickCheck ( Arbitrary(..), arbitraryBoundedEnum, Gen, NonNegative(..) ) import Test.QuickCheck.Gen ( listOf, oneof, elements ) import Text.Read ( readMaybe ) Transitional MonadFail implementation #if MIN_VERSION_base(4,9,0) import Control.Monad.Fail #endif aeson 2.0.0.0 introduced over #if MIN_VERSION_aeson(2,0,0) import Data.Aeson.Key (fromText) #endif import Web.Api.WebDriver.Uri unrecognizedValue :: (MonadFail m) => Text -> Text -> m a unrecognizedValue !name !string = fail $ unpack $ "Unrecognized value for type " <> name <> ": " <> string malformedValue :: (MonadFail m) => Text -> Text -> m a malformedValue !name !value = fail $ unpack $ "Malformed value for type " <> name <> ": " <> value object_ :: [Maybe Pair] -> Value object_ = object . filter (\(_, v) -> v /= Null) . catMaybes (.==) :: (ToJSON v, KeyValue kv) => Text -> v -> Maybe kv (.==) key value = #if MIN_VERSION_aeson(2,0,0) = lookup ( fromText key ) obj #else Just (key .= value) #endif (.=?) :: (ToJSON v, KeyValue kv) => Text -> Maybe v -> Maybe kv (.=?) key = #if MIN_VERSION_aeson(2,0,0) fmap ((fromText key) .=) #else fmap (key .=) #endif type SessionId = Text newtype ElementRef = ElementRef { theElementRef :: Text } deriving Eq instance Show ElementRef where show (ElementRef str) = unpack str instance IsString ElementRef where fromString = ElementRef . pack newtype ContextId = ContextId { theContextId :: Text } deriving Eq instance Show ContextId where show (ContextId str) = unpack str instance IsString ContextId where fromString = ContextId . pack instance FromJSON ContextId where parseJSON (String x) = return $ ContextId x parseJSON invalid = typeMismatch "ContextType" invalid instance ToJSON ContextId where toJSON (ContextId x) = String x instance Arbitrary ContextId where arbitrary = (ContextId . pack) <$> arbitrary data ContextType = WindowContext | TabContext deriving (Eq, Enum, Bounded) instance Show ContextType where show t = case t of WindowContext -> "window" TabContext -> "tab" instance FromJSON ContextType where parseJSON (String x) = case x of "window" -> return WindowContext "tab" -> return TabContext _ -> unrecognizedValue "ContextType" x parseJSON invalid = typeMismatch "ContextType" invalid instance ToJSON ContextType where toJSON WindowContext = String "window" toJSON TabContext = String "tab" instance Arbitrary ContextType where arbitrary = arbitraryBoundedEnum type Selector = Text type AttributeName = Text | Used with ` getElementProperty ` . type PropertyName = Text | Used with ` getComputedRole ` type AriaRole = Text type AriaLabel = Text type Script = Text type CookieName = Text type CssPropertyName = Text data FrameReference = TopLevelFrame | FrameNumber Int | FrameContainingElement ElementRef deriving (Eq, Show) data ResponseErrorCode = ElementClickIntercepted | ElementNotSelectable | ElementNotInteractable | InsecureCertificate | InvalidArgument | InvalidCookieDomain | InvalidCoordinates | InvalidElementState | InvalidSelector | InvalidSessionId | JavaScriptError | MoveTargetOutOfBounds | NoSuchAlert | NoSuchCookie | NoSuchElement | NoSuchFrame | NoSuchWindow | ScriptTimeout | SessionNotCreated | StaleElementReference | Timeout | UnableToSetCookie | UnableToCaptureScreen | UnexpectedAlertOpen | UnknownCommand | UnknownError | UnknownMethod | UnsupportedOperation | UnhandledErrorCode Text deriving (Eq, Show) instance FromJSON ResponseErrorCode where parseJSON (String x) = case x of "element click intercepted" -> return ElementClickIntercepted "element not selectable" -> return ElementNotSelectable "element not interactable" -> return ElementNotInteractable "insecure certificate" -> return InsecureCertificate "invalid argument" -> return InvalidArgument "invalid cookie domain" -> return InvalidCookieDomain "invalid coordinates" -> return InvalidCoordinates "invalid element state" -> return InvalidElementState "invalid selector" -> return InvalidSelector "invalid session id" -> return InvalidSessionId "javascript error" -> return JavaScriptError "move target out of bounds" -> return MoveTargetOutOfBounds "no such alert" -> return NoSuchAlert "no such cookie" -> return NoSuchCookie "no such element" -> return NoSuchElement "no such frame" -> return NoSuchFrame "no such window" -> return NoSuchWindow "script timeout" -> return ScriptTimeout "session not created" -> return SessionNotCreated "stale element reference" -> return StaleElementReference "timeout" -> return Timeout "unable to set cookie" -> return UnableToSetCookie "unable to capture screen" -> return UnableToCaptureScreen "unexpected alert open" -> return UnexpectedAlertOpen "unknown command" -> return UnknownCommand "unknown error" -> return UnknownError "unknown method" -> return UnknownMethod "unsupported operation" -> return UnsupportedOperation text -> return $ UnhandledErrorCode text parseJSON invalid = typeMismatch "ResponseErrorCode" invalid instance ToJSON ResponseErrorCode where toJSON x = case x of ElementClickIntercepted -> String "element click intercepted" ElementNotSelectable -> String "element not selectable" ElementNotInteractable -> String "element not interactable" InsecureCertificate -> String "insecure certificate" InvalidArgument -> String "invalid argument" InvalidCookieDomain -> String "invalid cookie domain" InvalidCoordinates -> String "invalid coordinates" InvalidElementState -> String "invalid element state" InvalidSelector -> String "invalid selector" InvalidSessionId -> String "invalid session id" JavaScriptError -> String "javascript error" MoveTargetOutOfBounds -> String "move target out of bounds" NoSuchAlert -> String "no such alert" NoSuchCookie -> String "no such cookie" NoSuchElement -> String "no such element" NoSuchFrame -> String "no such frame" NoSuchWindow -> String "no such window" ScriptTimeout -> String "script timeout" SessionNotCreated -> String "session not created" StaleElementReference -> String "stale element reference" Timeout -> String "timeout" UnableToSetCookie -> String "unable to set cookie" UnableToCaptureScreen -> String "unable to capture screen" UnexpectedAlertOpen -> String "unexpected alert open" UnknownCommand -> String "unknown command" UnknownError -> String "unknown error" UnknownMethod -> String "unknown method" UnsupportedOperation -> String "unsupported operation" UnhandledErrorCode msg -> String msg instance Arbitrary ResponseErrorCode where arbitrary = oneof $ map return [ ElementClickIntercepted , ElementNotSelectable , ElementNotInteractable , InsecureCertificate , InvalidArgument , InvalidCookieDomain , InvalidCoordinates , InvalidElementState , InvalidSelector , InvalidSessionId , JavaScriptError , MoveTargetOutOfBounds , NoSuchAlert , NoSuchCookie , NoSuchElement , NoSuchFrame , NoSuchWindow , ScriptTimeout , SessionNotCreated , StaleElementReference , Timeout , UnableToSetCookie , UnableToCaptureScreen , UnexpectedAlertOpen , UnknownCommand , UnknownError , UnknownMethod , UnsupportedOperation ] data Capabilities = Capabilities ^ @unhandledPromptBehavior@ } deriving (Eq, Show) instance FromJSON Capabilities where parseJSON (Object v) = Capabilities <$> v .:? "browserName" <*> v .:? "browserVersion" <*> v .:? "platformName" <*> v .:? "acceptInsecureCerts" <*> v .:? "pageLoadStrategy" <*> v .:? "proxy" <*> v .:? "setWindowRect" <*> v .:? "timeouts" <*> v .:? "unhandledPromptBehavior" <*> v .:? "goog:chromeOptions" <*> v .:? "moz:firefoxOptions" parseJSON invalid = typeMismatch "Capabilities" invalid instance ToJSON Capabilities where toJSON Capabilities{..} = object_ [ "browserName" .=? (toJSON <$> _browserName) , "browserVersion" .=? (toJSON <$> _browserVersion) , "platformName" .=? (toJSON <$> _platformName) , "acceptInsecureCerts" .=? (toJSON <$> _acceptInsecureCerts) , "pageLoadStrategy" .=? (toJSON <$> _pageLoadStrategy) , "proxy" .=? (toJSON <$> _proxy) , "setWindowRect" .=? (toJSON <$> _setWindowRect) , "timeouts" .=? (toJSON <$> _timeouts) , "unhandledPromptBehavior" .=? (toJSON <$> _unhandledPromptBehavior) , "goog:chromeOptions" .=? (toJSON <$> _chromeOptions) , "moz:firefoxOptions" .=? (toJSON <$> _firefoxOptions) ] instance Arbitrary Capabilities where arbitrary = Capabilities <$> arbitrary <*> (fmap (fmap T.pack) arbitrary) <*> arbitrary <*> arbitrary <*> (fmap (fmap T.pack) arbitrary) <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary emptyCapabilities :: Capabilities emptyCapabilities = Capabilities { _browserName = Nothing , _browserVersion = Nothing , _platformName = Nothing , _acceptInsecureCerts = Nothing , _pageLoadStrategy = Nothing , _proxy = Nothing , _setWindowRect = Nothing , _timeouts = Nothing , _unhandledPromptBehavior = Nothing , _chromeOptions = Nothing , _firefoxOptions = Nothing } defaultFirefoxCapabilities :: Capabilities defaultFirefoxCapabilities = emptyCapabilities { _browserName = Just Firefox } | Passing the " -headless " parameter to Firefox . headlessFirefoxCapabilities :: Capabilities headlessFirefoxCapabilities = defaultFirefoxCapabilities { _firefoxOptions = Just $ defaultFirefoxOptions { _firefoxArgs = Just ["-headless"] } } defaultChromeCapabilities :: Capabilities defaultChromeCapabilities = emptyCapabilities { _browserName = Just Chrome } data BrowserName = Firefox | Chrome | Safari deriving (Eq, Show, Enum, Bounded) instance FromJSON BrowserName where parseJSON (String x) = case x of "firefox" -> return Firefox "chrome" -> return Chrome "safari" -> return Safari _ -> unrecognizedValue "BrowserName" x parseJSON invalid = typeMismatch "BrowserName" invalid instance ToJSON BrowserName where toJSON Firefox = String "firefox" toJSON Chrome = String "chrome" toJSON Safari = String "safari" instance Arbitrary BrowserName where arbitrary = arbitraryBoundedEnum data PlatformName = Mac deriving (Eq, Show, Enum, Bounded) instance FromJSON PlatformName where parseJSON (String x) = case unpack x of "mac" -> return Mac _ -> unrecognizedValue "PlaformName" x parseJSON invalid = typeMismatch "PlatformName" invalid instance ToJSON PlatformName where toJSON Mac = String "mac" instance Arbitrary PlatformName where arbitrary = arbitraryBoundedEnum data ChromeOptions = ChromeOptions } deriving (Eq, Show) instance FromJSON ChromeOptions where parseJSON (Object v) = ChromeOptions <$> v .:? "binary" <*> v .:? "args" <*> v .:? "prefs" parseJSON invalid = typeMismatch "ChromeOptions" invalid instance ToJSON ChromeOptions where toJSON ChromeOptions{..} = object_ [ "binary" .=? (toJSON <$> _chromeBinary) , "args" .=? (toJSON <$> _chromeArgs) , "prefs" .=? (toJSON <$> _chromePrefs) ] instance Arbitrary ChromeOptions where arbitrary = ChromeOptions <$> arbitrary <*> (fmap (fmap (fmap T.pack)) arbitrary) <*> arbHashMap defaultChromeOptions :: ChromeOptions defaultChromeOptions = ChromeOptions { _chromeBinary = Nothing , _chromeArgs = Nothing , _chromePrefs = Nothing } data FirefoxOptions = FirefoxOptions , _firefoxLog :: Maybe FirefoxLog } deriving (Eq, Show) instance FromJSON FirefoxOptions where parseJSON (Object v) = FirefoxOptions <$> v .:? "binary" <*> v .:? "args" <*> v .:? "log" <*> v .:? "prefs" parseJSON invalid = typeMismatch "FirefoxOptions" invalid instance ToJSON FirefoxOptions where toJSON FirefoxOptions{..} = object_ [ "binary" .=? (toJSON <$> _firefoxBinary) , "args" .=? (toJSON <$> _firefoxArgs) , "log" .=? (toJSON <$> _firefoxLog) , "prefs" .=? (toJSON <$> _firefoxPrefs) ] instance Arbitrary FirefoxOptions where arbitrary = FirefoxOptions <$> arbitrary <*> (fmap (fmap (fmap T.pack)) arbitrary) <*> arbitrary <*> arbHashMap arbHashMap :: Gen (Maybe (HashMap Text Value)) arbHashMap = do p <- arbitrary if p then return Nothing else do m <- fromList <$> listOf (mPair arbKey arbPrefVal) return $ Just m arbKey :: Gen Text arbKey = pack <$> ('k':) <$> arbitrary arbText :: Gen Text arbText = pack <$> arbitrary arbPrefVal :: Gen Value arbPrefVal = do k <- arbitrary :: Gen Int case k`mod`3 of 0 -> Bool <$> arbitrary 1 -> String <$> arbText _ -> Number <$> arbScientific mPair :: (Monad m) => m a -> m b -> m (a,b) mPair ga gb = do a <- ga b <- gb return (a,b) defaultFirefoxOptions :: FirefoxOptions defaultFirefoxOptions = FirefoxOptions { _firefoxBinary = Nothing , _firefoxArgs = Nothing , _firefoxLog = Nothing , _firefoxPrefs = Nothing } newtype FirefoxLog = FirefoxLog { _firefoxLogLevel :: Maybe LogLevel } deriving (Eq, Show) instance FromJSON FirefoxLog where parseJSON (Object v) = FirefoxLog <$> v .:? "level" parseJSON invalid = typeMismatch "FirefoxLog" invalid instance ToJSON FirefoxLog where toJSON FirefoxLog{..} = object_ [ "level" .=? (toJSON <$> _firefoxLogLevel) ] instance Arbitrary FirefoxLog where arbitrary = FirefoxLog <$> arbitrary data LogLevel = LogTrace | LogDebug | LogConfig | LogInfo | LogWarn | LogError | LogFatal deriving (Eq, Show, Enum, Bounded) instance FromJSON LogLevel where parseJSON (String x) = case x of "trace" -> return LogTrace "debug" -> return LogDebug "config" -> return LogConfig "info" -> return LogInfo "warn" -> return LogWarn "error" -> return LogError "fatal" -> return LogFatal _ -> unrecognizedValue "LogLevel" x parseJSON invalid = typeMismatch "LogLevel" invalid instance ToJSON LogLevel where toJSON x = case x of LogTrace -> String "trace" LogDebug -> String "debug" LogConfig -> String "config" LogInfo -> String "info" LogWarn -> String "warn" LogError -> String "error" LogFatal -> String "fatal" instance Arbitrary LogLevel where arbitrary = arbitraryBoundedEnum data ProxyConfig = ProxyConfig ^ ^ @noProxy@ ^ @socksProxy@ } deriving (Eq, Show) instance FromJSON ProxyConfig where parseJSON (Object v) = ProxyConfig <$> v .:? "proxyType" <*> v .:? "proxyAutoconfigUrl" <*> v .:? "ftpProxy" <*> v .:? "httpProxy" <*> v .:? "noProxy" <*> v .:? "sslProxy" <*> v .:? "socksProxy" <*> v .:? "socksVersion" parseJSON invalid = typeMismatch "ProxyConfig" invalid instance ToJSON ProxyConfig where toJSON ProxyConfig{..} = object_ [ "proxyType" .=? (toJSON <$> _proxyType) , "proxyAutoconfigUrl" .=? (toJSON <$> _proxyAutoconfigUrl) , "ftpProxy" .=? (toJSON <$> _ftpProxy) , "httpProxy" .=? (toJSON <$> _httpProxy) , "noProxy" .=? (toJSON <$> _noProxy) , "sslProxy" .=? (toJSON <$> _sslProxy) , "socksProxy" .=? (toJSON <$> _socksProxy) , "socksVersion" .=? (toJSON <$> _socksVersion) ] instance Arbitrary ProxyConfig where arbitrary = ProxyConfig <$> arbitrary <*> (fmap (fmap T.pack) arbitrary) <*> arbitrary <*> arbitrary <*> (fmap (fmap (fmap T.pack)) arbitrary) <*> arbitrary <*> arbitrary <*> arbitrary | ` ` object with all members set to ` Nothing ` . emptyProxyConfig :: ProxyConfig emptyProxyConfig = ProxyConfig { _proxyType = Nothing , _proxyAutoconfigUrl = Nothing , _ftpProxy = Nothing , _httpProxy = Nothing , _noProxy = Nothing , _sslProxy = Nothing , _socksProxy = Nothing , _socksVersion = Nothing } data HostAndOptionalPort = HostAndOptionalPort { _urlHost :: Host , _urlPort :: Maybe Port } deriving (Eq, Show) instance FromJSON HostAndOptionalPort where parseJSON (String string) = let (as,bs') = T.span (/= ':') string in if T.null as then malformedValue "Host" string else case T.uncons bs' of Nothing -> case mkHost as of Nothing -> malformedValue "Host" string Just h -> return HostAndOptionalPort { _urlHost = h , _urlPort = Nothing } Just (c,bs) -> if c /= ':' then malformedValue "Host" string else if T.null bs then malformedValue "Port" string else case mkHost as of Nothing -> malformedValue "Host" string Just h -> case mkPort bs of Nothing -> malformedValue "Port" bs Just p -> return HostAndOptionalPort { _urlHost = h , _urlPort = Just p } parseJSON invalid = typeMismatch "HostAndOptionalPort" invalid instance ToJSON HostAndOptionalPort where toJSON HostAndOptionalPort{..} = case _urlPort of Nothing -> String $ pack $ show _urlHost Just pt -> String $ pack $ concat [show _urlHost, ":", show pt] instance Arbitrary HostAndOptionalPort where arbitrary = HostAndOptionalPort <$> arbitrary <*> arbitrary data ProxyType ^ @direct@ deriving (Eq, Show, Enum, Bounded) instance FromJSON ProxyType where parseJSON (String x) = case x of "pac" -> return ProxyPac "direct" -> return ProxyDirect "autodetect" -> return ProxyAutodetect "system" -> return ProxySystem "manual" -> return ProxyManual _ -> unrecognizedValue "ProxyType" x parseJSON invalid = typeMismatch "ProxyType" invalid instance ToJSON ProxyType where toJSON x = case x of ProxyPac -> String "pac" ProxyDirect -> String "direct" ProxyAutodetect -> String "autodetect" ProxySystem -> String "system" ProxyManual -> String "manual" instance Arbitrary ProxyType where arbitrary = arbitraryBoundedEnum data TimeoutConfig = TimeoutConfig } deriving (Eq, Show) instance FromJSON TimeoutConfig where parseJSON (Object v) = TimeoutConfig <$> v .:? "script" <*> v .:? "pageLoad" <*> v .:? "implicit" parseJSON invalid = typeMismatch "TimeoutConfig" invalid instance ToJSON TimeoutConfig where toJSON TimeoutConfig{..} = object_ [ "script" .== (toJSON <$> _script) , "pageLoad" .== (toJSON <$> _pageLoad) , "implicit" .== (toJSON <$> _implicit) ] instance Arbitrary TimeoutConfig where arbitrary = TimeoutConfig <$> arbitrary <*> arbitrary <*> arbitrary emptyTimeoutConfig :: TimeoutConfig emptyTimeoutConfig = TimeoutConfig { _script = Nothing , _pageLoad = Nothing , _implicit = Nothing } data LocationStrategy ^ @xpath@ deriving (Eq, Show, Enum, Bounded) instance FromJSON LocationStrategy where parseJSON (String x) = case x of "css selector" -> return CssSelector "link text" -> return LinkTextSelector "partial link text" -> return PartialLinkTextSelector "tag name" -> return TagName "xpath" -> return XPathSelector _ -> unrecognizedValue "LocationStrategy" x parseJSON invalid = typeMismatch "LocationStrategy" invalid instance ToJSON LocationStrategy where toJSON x = case x of CssSelector -> String "css selector" LinkTextSelector -> String "link text" PartialLinkTextSelector -> String "partial link text" TagName -> String "tag name" XPathSelector -> String "xpath" instance Arbitrary LocationStrategy where arbitrary = arbitraryBoundedEnum data InputSource deriving (Eq, Show, Enum, Bounded) instance FromJSON InputSource where parseJSON (String x) = case x of "null" -> return NullInputSource "key" -> return KeyInputSource "pointer" -> return PointerInputSource _ -> unrecognizedValue "InputSource" x parseJSON invalid = typeMismatch "InputSource" invalid instance ToJSON InputSource where toJSON x = case x of NullInputSource -> String "null" KeyInputSource -> String "key" PointerInputSource -> String "pointer" instance Arbitrary InputSource where arbitrary = arbitraryBoundedEnum data PointerSubtype ^ @pen@ deriving (Eq, Show, Enum, Bounded) instance FromJSON PointerSubtype where parseJSON (String x) = case x of "mouse" -> return PointerMouse "pen" -> return PointerPen "touch" -> return PointerTouch _ -> unrecognizedValue "PointerSubtype" x parseJSON invalid = typeMismatch "PointerSubtype" invalid instance ToJSON PointerSubtype where toJSON x = case x of PointerMouse -> String "mouse" PointerPen -> String "pen" PointerTouch -> String "touch" instance Arbitrary PointerSubtype where arbitrary = arbitraryBoundedEnum data Action = Action } deriving (Eq, Show) instance FromJSON Action where parseJSON (Object v) = Action <$> v .:? "type" <*> v .:? "id" <*> v .:? "parameters" <*> v .: "actions" parseJSON invalid = typeMismatch "Action" invalid instance ToJSON Action where toJSON Action{..} = object_ [ "type" .=? (toJSON <$> _inputSourceType) , "id" .=? (toJSON <$> _inputSourceId) , "parameters" .=? (toJSON <$> _inputSourceParameters) , "actions" .== (toJSON <$> _actionItems) ] instance Arbitrary Action where arbitrary = Action <$> arbitrary <*> (fmap (fmap T.pack) arbitrary) <*> arbitrary <*> arbitrary | All members set to ` Nothing ` except ` _ actionItems ` , which is the empty list . emptyAction :: Action emptyAction = Action { _inputSourceType = Nothing , _inputSourceId = Nothing , _inputSourceParameters = Nothing , _actionItems = [] } data ActionType deriving (Eq, Show, Enum, Bounded) instance FromJSON ActionType where parseJSON (String x) = case x of "pause" -> return PauseAction "keyUp" -> return KeyUpAction "keyDown" -> return KeyDownAction "pointerDown" -> return PointerDownAction "pointerUp" -> return PointerUpAction "pointerMove" -> return PointerMoveAction "pointerCancel" -> return PointerCancelAction _ -> unrecognizedValue "ActionType" x parseJSON invalid = typeMismatch "ActionType" invalid instance ToJSON ActionType where toJSON x = case x of PauseAction -> String "pause" KeyUpAction -> String "keyUp" KeyDownAction -> String "keyDown" PointerDownAction -> String "pointerDown" PointerUpAction -> String "pointerUp" PointerMoveAction -> String "pointerMove" PointerCancelAction -> String "pointerCancel" instance Arbitrary ActionType where arbitrary = arbitraryBoundedEnum newtype InputSourceParameter = InputSourceParameter } deriving (Eq, Show) instance FromJSON InputSourceParameter where parseJSON (Object v) = InputSourceParameter <$> v .:? "subtype" parseJSON invalid = typeMismatch "InputSourceParameter" invalid instance ToJSON InputSourceParameter where toJSON InputSourceParameter{..} = object_ [ "subtype" .=? (toJSON <$> _pointerSubtype) ] instance Arbitrary InputSourceParameter where arbitrary = InputSourceParameter <$> arbitrary data ActionItem = ActionItem } deriving (Eq, Show) instance FromJSON ActionItem where parseJSON (Object v) = ActionItem <$> v .:? "type" <*> v .:? "duration" <*> v .:? "origin" <*> v .:? "value" <*> v .:? "button" <*> v .:? "x" <*> v .:? "y" parseJSON invalid = typeMismatch "ActionItem" invalid instance ToJSON ActionItem where toJSON ActionItem{..} = object_ [ "type" .=? (toJSON <$> _actionType) , "duration" .=? (toJSON <$> _actionDuration) , "origin" .=? (toJSON <$> _actionOrigin) , "value" .=? (toJSON <$> _actionValue) , "button" .=? (toJSON <$> _actionButton) , "x" .=? (toJSON <$> _actionX) , "y" .=? (toJSON <$> _actionY) ] instance Arbitrary ActionItem where arbitrary = ActionItem <$> arbitrary <*> arbitrary <*> (fmap (fmap T.pack) arbitrary) <*> (fmap (fmap T.pack) arbitrary) <*> arbitrary <*> arbitrary <*> arbitrary emptyActionItem :: ActionItem emptyActionItem = ActionItem { _actionType = Nothing , _actionDuration = Nothing , _actionOrigin = Nothing , _actionValue = Nothing , _actionButton = Nothing , _actionX = Nothing , _actionY = Nothing } data Rect = Rect } deriving (Eq, Show) instance ToJSON Rect where toJSON Rect{..} = object [ "x" .= toJSON _rectX , "y" .= toJSON _rectY , "width" .= toJSON _rectWidth , "height" .= toJSON _rectHeight ] instance FromJSON Rect where parseJSON (Object v) = Rect <$> v .: "x" <*> v .: "y" <*> v .: "width" <*> v .: "height" parseJSON invalid = typeMismatch "Rect" invalid arbScientific :: Gen Scientific arbScientific = scientific <$> arbitrary <*> arbitrary instance Arbitrary Rect where arbitrary = Rect <$> arbScientific <*> arbScientific <*> arbScientific <*> arbScientific emptyRect :: Rect emptyRect = Rect { _rectX = 0 , _rectY = 0 , _rectWidth = 0 , _rectHeight = 0 } data PromptHandler deriving (Eq, Show, Enum, Bounded) instance FromJSON PromptHandler where parseJSON (String x) = case x of "dismiss" -> return DismissPrompts "accept" -> return AcceptPrompts "dismiss and notify" -> return DismissPromptsAndNotify "accept and notify" -> return AcceptPromptsAndNotify "ignore" -> return IgnorePrompts _ -> unrecognizedValue "PromptHandler" x parseJSON invalid = typeMismatch "PromptHandler" invalid instance ToJSON PromptHandler where toJSON x = case x of DismissPrompts -> String "dismiss" AcceptPrompts -> String "accept" DismissPromptsAndNotify -> String "dismiss and notify" AcceptPromptsAndNotify -> String "accept and notify" IgnorePrompts -> String "ignore" instance Arbitrary PromptHandler where arbitrary = arbitraryBoundedEnum data Cookie = Cookie ^ @expiryTime@ } deriving (Eq, Show) instance ToJSON Cookie where toJSON Cookie{..} = object_ [ "name" .=? (toJSON <$> _cookieName) , "value" .=? (toJSON <$> _cookieValue) , "path" .=? (toJSON <$> _cookiePath) , "domain" .=? (toJSON <$> _cookieDomain) , "secure" .=? (toJSON <$> _cookieSecure) , "httpOnly" .=? (toJSON <$> _cookieHttpOnly) , "expiryTime" .=? (toJSON <$> _cookieExpiryTime) ] instance FromJSON Cookie where parseJSON (Object v) = Cookie <$> v .:? "name" <*> v .:? "value" <*> v .:? "path" <*> v .:? "domain" <*> v .:? "secure" <*> v .:? "httpOnly" <*> v .:? "expiryTime" parseJSON invalid = typeMismatch "Cookie" invalid instance Arbitrary Cookie where arbitrary = Cookie <$> (fmap (fmap T.pack) arbitrary) <*> (fmap (fmap T.pack) arbitrary) <*> (fmap (fmap T.pack) arbitrary) <*> (fmap (fmap T.pack) arbitrary) <*> arbitrary <*> arbitrary <*> (fmap (fmap T.pack) arbitrary) emptyCookie :: Cookie emptyCookie = Cookie { _cookieName = Nothing , _cookieValue = Nothing , _cookiePath = Nothing , _cookieDomain = Nothing , _cookieSecure = Nothing , _cookieHttpOnly = Nothing , _cookieExpiryTime = Nothing } cookie -> Cookie cookie name value = emptyCookie { _cookieName = Just name , _cookieValue = Just value } data PrintOptions = PrintOptions } deriving (Eq, Show) defaultPrintOptions :: PrintOptions defaultPrintOptions = PrintOptions { _orientation = Nothing , _scale = Nothing , _background = Nothing , _page = Nothing , _margin = Nothing , _shrinkToFit = Nothing , _pageRanges = Nothing } instance ToJSON PrintOptions where toJSON PrintOptions{..} = object_ [ "orientation" .=? (toJSON <$> _orientation) , "scale" .=? (toJSON <$> _scale) , "background" .=? (toJSON <$> _background) , "page" .=? (toJSON <$> _page) , "margin" .=? (toJSON <$> _margin) , "shrinkToFit" .=? (toJSON <$> _shrinkToFit) , "pageRanges" .=? (toJSON <$> _pageRanges) ] instance FromJSON PrintOptions where parseJSON (Object v) = PrintOptions <$> v .:? "orientation" <*> v .:? "scale" <*> v .:? "background" <*> v .:? "page" <*> v .:? "margin" <*> v .:? "shrinkToFit" <*> v .:? "pageRanges" parseJSON invalid = typeMismatch "PrintOptions" invalid instance Arbitrary PrintOptions where arbitrary = PrintOptions <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary data Orientation = Landscape | Portrait deriving (Eq, Show, Enum, Bounded) instance FromJSON Orientation where parseJSON (String x) = case x of "landscape" -> return Landscape "portrait" -> return Portrait _ -> unrecognizedValue "Orientation" x parseJSON invalid = typeMismatch "Orientation" invalid instance ToJSON Orientation where toJSON x = case x of Landscape -> String "landscape" Portrait -> String "portrait" instance Arbitrary Orientation where arbitrary = arbitraryBoundedEnum newtype Scale = Scale Scientific deriving (Eq, Show) instance ToJSON Scale where toJSON (Scale x) = toJSON x instance FromJSON Scale where parseJSON = fmap Scale . parseJSON TODO : fix this arbitrary = Scale <$> elements [ 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 , 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0 ] data Page = Page } deriving (Eq, Show) defaultPage :: Page defaultPage = Page { _pageWidth = Nothing , _pageHeight = Nothing } instance ToJSON Page where toJSON Page{..} = object_ [ "pageWidth" .=? (toJSON <$> _pageWidth) , "pageHeight" .=? (toJSON <$> _pageHeight) ] instance FromJSON Page where parseJSON (Object v) = Page <$> v .:? "pageWidth" <*> v .:? "pageHeight" parseJSON invalid = typeMismatch "Page" invalid instance Arbitrary Page where arbitrary = let margins = map negate [ 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9 , 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9 ] in Page <$> oneof [ return Nothing, Just <$> elements (map (27.94 +) margins) ] <*> oneof [ return Nothing, Just <$> elements (map (21.59 +) margins) ] data Margin = Margin } deriving (Eq, Show) defaultMargin :: Margin defaultMargin = Margin { _marginTop = Nothing , _marginBottom = Nothing , _marginLeft = Nothing , _marginRight = Nothing } instance ToJSON Margin where toJSON Margin{..} = object_ [ "marginTop" .=? (toJSON <$> _marginTop) , "marginBottom" .=? (toJSON <$> _marginBottom) , "marginLeft" .=? (toJSON <$> _marginLeft) , "marginRight" .=? (toJSON <$> _marginRight) ] instance FromJSON Margin where parseJSON (Object v) = Margin <$> v .:? "marginTop" <*> v .:? "marginBottom" <*> v .:? "marginLeft" <*> v .:? "marginRight" parseJSON invalid = typeMismatch "Margin" invalid instance Arbitrary Margin where arbitrary = let margins = [ 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9 , 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9 ] in Margin <$> oneof [ return Nothing, Just <$> elements margins ] <*> oneof [ return Nothing, Just <$> elements margins ] <*> oneof [ return Nothing, Just <$> elements margins ] <*> oneof [ return Nothing, Just <$> elements margins ] data PageRange = OnePage Int | PageRange Int Int deriving (Eq, Show) instance ToJSON PageRange where toJSON x = case x of OnePage k -> String $ pack $ show k PageRange a b -> String $ mconcat [ pack $ show a, "-", pack $ show b ] instance FromJSON PageRange where parseJSON (String str) = let (as, bs') = T.break (== '-') str in case T.uncons bs' of Nothing -> case readMaybe $ unpack as of Just k -> return $ OnePage k Nothing -> malformedValue "page range" str Just (_,bs) -> if (T.null as) || (T.null bs) then malformedValue "page range" str else case (readMaybe $ unpack as, readMaybe $ unpack bs) of (Just a, Just b) -> return $ PageRange a b _ -> malformedValue "page range" str parseJSON invalid = typeMismatch "PageRange" invalid instance Arbitrary PageRange where arbitrary = do NonNegative a <- fmap (fmap (`mod` 100)) arbitrary oneof [ return $ OnePage a , do NonNegative b <- fmap (fmap (`mod` 100)) arbitrary return $ PageRange (min a b) (max a b) ] newtype Base64EncodedPdf = Base64EncodedPdf SB.ByteString deriving (Eq, Show) instance FromJSON Base64EncodedPdf where parseJSON (String s) = return $ Base64EncodedPdf $ encodeUtf8 s parseJSON invalid = typeMismatch "Base64EncodedPdf" invalid decodeBase64EncodedPdf :: Base64EncodedPdf -> SB.ByteString decodeBase64EncodedPdf (Base64EncodedPdf bytes) = B64.decodeLenient bytes writeBase64EncodedPdf :: ( MonadIO m ) => FilePath -> Base64EncodedPdf -> m () writeBase64EncodedPdf path pdf = liftIO $ SB.writeFile path $ decodeBase64EncodedPdf pdf
3e0d1c5872581cf6ccf0d92552564f7255ea1b2c18cc006bff67d885b473ff6f
spurious/sagittarius-scheme-mirror
peval.scm
PEVAL -- A simple partial evaluator for Scheme , written by . ;------------------------------------------------------------------------------ Utilities (define (every? pred? l) (let loop ((l l)) (or (null? l) (and (pred? (car l)) (loop (cdr l)))))) (define (some? pred? l) (let loop ((l l)) (if (null? l) #f (or (pred? (car l)) (loop (cdr l)))))) (define (map2 f l1 l2) (let loop ((l1 l1) (l2 l2)) (if (pair? l1) (cons (f (car l1) (car l2)) (loop (cdr l1) (cdr l2))) '()))) (define (get-last-pair l) (let loop ((l l)) (let ((x (cdr l))) (if (pair? x) (loop x) l)))) ;------------------------------------------------------------------------------ ; ; The partial evaluator. (define (partial-evaluate proc args) (peval (alphatize proc '()) args)) (define (alphatize exp env) ; return a copy of 'exp' where each bound var has (define (alpha exp) ; been renamed (to prevent aliasing problems) (cond ((const-expr? exp) (quot (const-value exp))) ((symbol? exp) (let ((x (assq exp env))) (if x (cdr x) exp))) ((or (eq? (car exp) 'if) (eq? (car exp) 'begin)) (cons (car exp) (map alpha (cdr exp)))) ((or (eq? (car exp) 'let) (eq? (car exp) 'letrec)) (let ((new-env (new-variables (map car (cadr exp)) env))) (list (car exp) (map (lambda (x) (list (cdr (assq (car x) new-env)) (if (eq? (car exp) 'let) (alpha (cadr x)) (alphatize (cadr x) new-env)))) (cadr exp)) (alphatize (caddr exp) new-env)))) ((eq? (car exp) 'lambda) (let ((new-env (new-variables (cadr exp) env))) (list 'lambda (map (lambda (x) (cdr (assq x new-env))) (cadr exp)) (alphatize (caddr exp) new-env)))) (else (map alpha exp)))) (alpha exp)) (define (const-expr? expr) ; is 'expr' a constant expression? (and (not (symbol? expr)) (or (not (pair? expr)) (eq? (car expr) 'quote)))) (define (const-value expr) ; return the value of a constant expression (if (pair? expr) ; then it must be a quoted constant (cadr expr) expr)) (define (quot val) ; make a quoted constant whose value is 'val' (list 'quote val)) (define (new-variables parms env) (append (map (lambda (x) (cons x (new-variable x))) parms) env)) (define *current-num* 0) (define (new-variable name) (set! *current-num* (+ *current-num* 1)) (string->symbol (string-append (symbol->string name) "_" (number->string *current-num*)))) ;------------------------------------------------------------------------------ ; ; (peval proc args) will transform a procedure that is known to be called ; with constants as some of its arguments into a specialized procedure that ; is 'equivalent' but accepts only the non-constant parameters. 'proc' is the ; list representation of a lambda-expression and 'args' is a list of values, ; one for each parameter of the lambda-expression. A special value (i.e. ; 'not-constant') is used to indicate an argument that is not a constant. ; The returned procedure is one that has as parameters the parameters of the ; original procedure which are NOT passed constants. Constants will have been ; substituted for the constant parameters that are referenced in the body ; of the procedure. ; ; For example: ; ; (peval ; '(lambda (x y z) (f z x y)) ; the procedure ( list 1 not - constant # t ) ) ; the knowledge about x , y and z ; ; will return: (lambda (y) (f '#t '1 y)) (define (peval proc args) (simplify! (let ((parms (cadr proc)) ; get the parameter list (body (caddr proc))) ; get the body of the procedure (list 'lambda (remove-constant parms args) ; remove the constant parameters (beta-subst ; in the body, replace variable refs to the constant body ; parameters by the corresponding constant (map2 (lambda (x y) (if (not-constant? y) '(()) (cons x (quot y)))) parms args)))))) (define not-constant (list '?)) ; special value indicating non-constant parms. (define (not-constant? x) (eq? x not-constant)) (define (remove-constant l a) ; remove from list 'l' all elements whose (cond ((null? l) ; corresponding element in 'a' is a constant '()) ((not-constant? (car a)) (cons (car l) (remove-constant (cdr l) (cdr a)))) (else (remove-constant (cdr l) (cdr a))))) (define (extract-constant l a) ; extract from list 'l' all elements whose (cond ((null? l) ; corresponding element in 'a' is a constant '()) ((not-constant? (car a)) (extract-constant (cdr l) (cdr a))) (else (cons (car l) (extract-constant (cdr l) (cdr a)))))) (define (beta-subst exp env) ; return a modified 'exp' where each var named in (define (bs exp) ; 'env' is replaced by the corresponding expr (it (cond ((const-expr? exp) ; is assumed that the code has been alphatized) (quot (const-value exp))) ((symbol? exp) (let ((x (assq exp env))) (if x (cdr x) exp))) ((or (eq? (car exp) 'if) (eq? (car exp) 'begin)) (cons (car exp) (map bs (cdr exp)))) ((or (eq? (car exp) 'let) (eq? (car exp) 'letrec)) (list (car exp) (map (lambda (x) (list (car x) (bs (cadr x)))) (cadr exp)) (bs (caddr exp)))) ((eq? (car exp) 'lambda) (list 'lambda (cadr exp) (bs (caddr exp)))) (else (map bs exp)))) (bs exp)) ;------------------------------------------------------------------------------ ; ; The expression simplifier. (define (simplify! exp) ; simplify the expression 'exp' destructively (it ; is assumed that the code has been alphatized) (define (simp! where env) (define (s! where) (let ((exp (car where))) (cond ((const-expr? exp)) ; leave constants the way they are ((symbol? exp)) ; leave variable references the way they are ((eq? (car exp) 'if) ; dead code removal for conditionals (s! (cdr exp)) ; simplify the predicate (if (const-expr? (cadr exp)) ; is the predicate a constant? (begin (set-car! where (if (memq (const-value (cadr exp)) '(#f ())) ; false? (if (= (length exp) 3) ''() (cadddr exp)) (caddr exp))) (s! where)) (for-each! s! (cddr exp)))) ; simplify consequent and alt. ((eq? (car exp) 'begin) (for-each! s! (cdr exp)) (let loop ((exps exp)) ; remove all useless expressions (if (not (null? (cddr exps))) ; not last expression? (let ((x (cadr exps))) (loop (if (or (const-expr? x) (symbol? x) (and (pair? x) (eq? (car x) 'lambda))) (begin (set-cdr! exps (cddr exps)) exps) (cdr exps)))))) only one expression in the begin ? (set-car! where (cadr exp)))) ((or (eq? (car exp) 'let) (eq? (car exp) 'letrec)) (let ((new-env (cons exp env))) (define (keep i) (if (>= i (length (cadar where))) '() (let* ((var (car (list-ref (cadar where) i))) (val (cadr (assq var (cadar where)))) (refs (ref-count (car where) var)) (self-refs (ref-count val var)) (total-refs (- (car refs) (car self-refs))) (oper-refs (- (cadr refs) (cadr self-refs)))) (cond ((= total-refs 0) (keep (+ i 1))) ((or (const-expr? val) (symbol? val) (and (pair? val) (eq? (car val) 'lambda) (= total-refs 1) (= oper-refs 1) (= (car self-refs) 0)) (and (caddr refs) (= total-refs 1))) (set-car! where (beta-subst (car where) (list (cons var val)))) (keep (+ i 1))) (else (cons var (keep (+ i 1)))))))) (simp! (cddr exp) new-env) (for-each! (lambda (x) (simp! (cdar x) new-env)) (cadr exp)) (let ((to-keep (keep 0))) (if (< (length to-keep) (length (cadar where))) (begin (if (null? to-keep) (set-car! where (caddar where)) (set-car! (cdar where) (map (lambda (v) (assq v (cadar where))) to-keep))) (s! where)) (if (null? to-keep) (set-car! where (caddar where))))))) ((eq? (car exp) 'lambda) (simp! (cddr exp) (cons exp env))) (else (for-each! s! exp) (cond ((symbol? (car exp)) ; is the operator position a var ref? (let ((frame (binding-frame (car exp) env))) (if frame ; is it a bound variable? (let ((proc (bound-expr (car exp) frame))) (if (and (pair? proc) (eq? (car proc) 'lambda) (some? const-expr? (cdr exp))) (let* ((args (arg-pattern (cdr exp))) (new-proc (peval proc args)) (new-args (remove-constant (cdr exp) args))) (set-car! where (cons (add-binding new-proc frame (car exp)) new-args))))) (set-car! where (constant-fold-global (car exp) (cdr exp)))))) ((not (pair? (car exp)))) ((eq? (caar exp) 'lambda) (set-car! where (list 'let (map2 list (cadar exp) (cdr exp)) (caddar exp))) (s! where))))))) (s! where)) (define (remove-empty-calls! where env) (define (rec! where) (let ((exp (car where))) (cond ((const-expr? exp)) ((symbol? exp)) ((eq? (car exp) 'if) (rec! (cdr exp)) (rec! (cddr exp)) (rec! (cdddr exp))) ((eq? (car exp) 'begin) (for-each! rec! (cdr exp))) ((or (eq? (car exp) 'let) (eq? (car exp) 'letrec)) (let ((new-env (cons exp env))) (remove-empty-calls! (cddr exp) new-env) (for-each! (lambda (x) (remove-empty-calls! (cdar x) new-env)) (cadr exp)))) ((eq? (car exp) 'lambda) (rec! (cddr exp))) (else (for-each! rec! (cdr exp)) (if (and (null? (cdr exp)) (symbol? (car exp))) (let ((frame (binding-frame (car exp) env))) (if frame ; is it a bound variable? (let ((proc (bound-expr (car exp) frame))) (if (and (pair? proc) (eq? (car proc) 'lambda)) (begin (set! changed? #t) (set-car! where (caddr proc)))))))))))) (rec! where)) (define changed? #f) (let ((x (list exp))) (let loop () (set! changed? #f) (simp! x '()) (remove-empty-calls! x '()) (if changed? (loop) (car x))))) (define (ref-count exp var) ; compute how many references to variable 'var' (let ((total 0) ; are contained in 'exp' (oper 0) (always-evaled #t)) (define (rc exp ae) (cond ((const-expr? exp)) ((symbol? exp) (if (eq? exp var) (begin (set! total (+ total 1)) (set! always-evaled (and ae always-evaled))))) ((eq? (car exp) 'if) (rc (cadr exp) ae) (for-each (lambda (x) (rc x #f)) (cddr exp))) ((eq? (car exp) 'begin) (for-each (lambda (x) (rc x ae)) (cdr exp))) ((or (eq? (car exp) 'let) (eq? (car exp) 'letrec)) (for-each (lambda (x) (rc (cadr x) ae)) (cadr exp)) (rc (caddr exp) ae)) ((eq? (car exp) 'lambda) (rc (caddr exp) #f)) (else (for-each (lambda (x) (rc x ae)) exp) (if (symbol? (car exp)) (if (eq? (car exp) var) (set! oper (+ oper 1))))))) (rc exp #t) (list total oper always-evaled))) (define (binding-frame var env) (cond ((null? env) #f) ((or (eq? (caar env) 'let) (eq? (caar env) 'letrec)) (if (assq var (cadar env)) (car env) (binding-frame var (cdr env)))) ((eq? (caar env) 'lambda) (if (memq var (cadar env)) (car env) (binding-frame var (cdr env)))) (else (fatal-error "ill-formed environment")))) (define (bound-expr var frame) (cond ((or (eq? (car frame) 'let) (eq? (car frame) 'letrec)) (cadr (assq var (cadr frame)))) ((eq? (car frame) 'lambda) not-constant) (else (fatal-error "ill-formed frame")))) (define (add-binding val frame name) (define (find-val val bindings) (cond ((null? bindings) #f) ((equal? val (cadar bindings)) ; *kludge* equal? is not exactly what (caar bindings)) ; we want... (else (find-val val (cdr bindings))))) (or (find-val val (cadr frame)) (let ((var (new-variable name))) (set-cdr! (get-last-pair (cadr frame)) (list (list var val))) var))) (define (for-each! proc! l) ; call proc! on each CONS CELL in the list 'l' (if (not (null? l)) (begin (proc! l) (for-each! proc! (cdr l))))) (define (arg-pattern exps) ; return the argument pattern (i.e. the list of (if (null? exps) ; constants in 'exps' but with the not-constant '() ; value wherever the corresponding expression in (cons (if (const-expr? (car exps)) ; 'exps' is not a constant) (const-value (car exps)) not-constant) (arg-pattern (cdr exps))))) ;------------------------------------------------------------------------------ ; ; Knowledge about primitive procedures. (define *primitives* (list (cons 'car (lambda (args) (and (= (length args) 1) (pair? (car args)) (quot (car (car args)))))) (cons 'cdr (lambda (args) (and (= (length args) 1) (pair? (car args)) (quot (cdr (car args)))))) (cons '+ (lambda (args) (and (every? number? args) (quot (sum args 0))))) (cons '* (lambda (args) (and (every? number? args) (quot (product args 1))))) (cons '- (lambda (args) (and (> (length args) 0) (every? number? args) (quot (if (null? (cdr args)) (- (car args)) (- (car args) (sum (cdr args) 0))))))) (cons '/ (lambda (args) (and (> (length args) 1) (every? number? args) (quot (if (null? (cdr args)) (/ (car args)) (/ (car args) (product (cdr args) 1))))))) (cons '< (lambda (args) (and (= (length args) 2) (every? number? args) (quot (< (car args) (cadr args)))))) (cons '= (lambda (args) (and (= (length args) 2) (every? number? args) (quot (= (car args) (cadr args)))))) (cons '> (lambda (args) (and (= (length args) 2) (every? number? args) (quot (> (car args) (cadr args)))))) (cons 'eq? (lambda (args) (and (= (length args) 2) (quot (eq? (car args) (cadr args)))))) (cons 'not (lambda (args) (and (= (length args) 1) (quot (not (car args)))))) (cons 'null? (lambda (args) (and (= (length args) 1) (quot (null? (car args)))))) (cons 'pair? (lambda (args) (and (= (length args) 1) (quot (pair? (car args)))))) (cons 'symbol? (lambda (args) (and (= (length args) 1) (quot (symbol? (car args)))))) ) ) (define (sum lst n) (if (null? lst) n (sum (cdr lst) (+ n (car lst))))) (define (product lst n) (if (null? lst) n (product (cdr lst) (* n (car lst))))) (define (reduce-global name args) (let ((x (assq name *primitives*))) (and x ((cdr x) args)))) (define (constant-fold-global name exprs) (define (flatten args op) (cond ((null? args) '()) ((and (pair? (car args)) (eq? (caar args) op)) (append (flatten (cdar args) op) (flatten (cdr args) op))) (else (cons (car args) (flatten (cdr args) op))))) (let ((args (if (or (eq? name '+) (eq? name '*)) ; associative ops (flatten exprs name) exprs))) (or (and (every? const-expr? args) (reduce-global name (map const-value args))) (let ((pattern (arg-pattern args))) (let ((non-const (remove-constant args pattern)) (const (map const-value (extract-constant args pattern)))) (cond ((eq? name '+) ; + is commutative (let ((x (reduce-global '+ const))) (if x (let ((y (const-value x))) (cons '+ (if (= y 0) non-const (cons x non-const)))) (cons name args)))) ((eq? name '*) ; * is commutative (let ((x (reduce-global '* const))) (if x (let ((y (const-value x))) (cons '* (if (= y 1) non-const (cons x non-const)))) (cons name args)))) ((eq? name 'cons) (cond ((and (const-expr? (cadr args)) (null? (const-value (cadr args)))) (list 'list (car args))) ((and (pair? (cadr args)) (eq? (car (cadr args)) 'list)) (cons 'list (cons (car args) (cdr (cadr args))))) (else (cons name args)))) (else (cons name args)))))))) ;------------------------------------------------------------------------------ ; ; Examples: (define (try-peval proc args) (partial-evaluate proc args)) ; . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . (define example1 '(lambda (a b c) (if (null? a) b (+ (car a) c)))) ( try - peval example1 ( list ' ( 10 11 ) not - constant ' 1 ) ) ; . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . (define example2 '(lambda (x y) (let ((q (lambda (a b) (if (< a 0) b (- 10 b))))) (if (< x 0) (q (- y) (- x)) (q y x))))) ;(try-peval example2 (list not-constant '1)) ; . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . (define example3 '(lambda (l n) (letrec ((add-list (lambda (l n) (if (null? l) '() (cons (+ (car l) n) (add-list (cdr l) n)))))) (add-list l n)))) ( try - peval example3 ( list not - constant ' 1 ) ) ;(try-peval example3 (list '(1 2 3) not-constant)) ; . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . (define example4 '(lambda (exp env) (letrec ((eval (lambda (exp env) (letrec ((eval-list (lambda (l env) (if (null? l) '() (cons (eval (car l) env) (eval-list (cdr l) env)))))) (if (symbol? exp) (lookup exp env) (if (not (pair? exp)) exp (if (eq? (car exp) 'quote) (car (cdr exp)) (apply (eval (car exp) env) (eval-list (cdr exp) env))))))))) (eval exp env)))) ;(try-peval example4 (list 'x not-constant)) ;(try-peval example4 (list '(f 1 2 3) not-constant)) ; . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . (define example5 '(lambda (a b) (letrec ((funct (lambda (x) (+ x b (if (< x 1) 0 (funct (- x 1))))))) (funct a)))) ( try - peval example5 ( list ' 5 not - constant ) ) ; . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . (define example6 '(lambda () (letrec ((fib (lambda (x) (if (< x 2) x (+ (fib (- x 1)) (fib (- x 2))))))) (fib 10)))) ;(try-peval example6 '()) ; . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . (define example7 '(lambda (input) (letrec ((copy (lambda (in) (if (pair? in) (cons (copy (car in)) (copy (cdr in))) in)))) (copy input)))) ;(try-peval example7 (list '(a b c d e f g h i j k l m n o p q r s t u v w x y z))) ; . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . (define example8 '(lambda (input) (letrec ((reverse (lambda (in result) (if (pair? in) (reverse (cdr in) (cons (car in) result)) result)))) (reverse input '())))) ( try - peval example8 ( list ' ( a b c d e f g h i j k l m n o p q r s t u v w x y z ) ) ) ; . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . (define (test) (set! *current-num* 0) (list (try-peval example1 (list '(10 11) not-constant '1)) (try-peval example2 (list not-constant '1)) (try-peval example3 (list not-constant '1)) (try-peval example3 (list '(1 2 3) not-constant)) (try-peval example4 (list 'x not-constant)) (try-peval example4 (list '(f 1 2 3) not-constant)) (try-peval example5 (list '5 not-constant)) (try-peval example6 '()) (try-peval example7 (list '(a b c d e f g h i j k l m n o p q r s t u v w x y z))) (try-peval example8 (list '(a b c d e f g h i j k l m n o p q r s t u v w x y z))))) (define (main . args) (run-benchmark "peval" peval-iters (lambda (result) (and (list? result) (= (length result) 10) (equal? (list-ref result 9) '(lambda () (list 'z 'y 'x 'w 'v 'u 't 's 'r 'q 'p 'o 'n 'm 'l 'k 'j 'i 'h 'g 'f 'e 'd 'c 'b 'a))))) (lambda () (lambda () (test)))))
null
https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/bench/gambit-benchmarks/peval.scm
scheme
------------------------------------------------------------------------------ ------------------------------------------------------------------------------ The partial evaluator. return a copy of 'exp' where each bound var has been renamed (to prevent aliasing problems) is 'expr' a constant expression? return the value of a constant expression then it must be a quoted constant make a quoted constant whose value is 'val' ------------------------------------------------------------------------------ (peval proc args) will transform a procedure that is known to be called with constants as some of its arguments into a specialized procedure that is 'equivalent' but accepts only the non-constant parameters. 'proc' is the list representation of a lambda-expression and 'args' is a list of values, one for each parameter of the lambda-expression. A special value (i.e. 'not-constant') is used to indicate an argument that is not a constant. The returned procedure is one that has as parameters the parameters of the original procedure which are NOT passed constants. Constants will have been substituted for the constant parameters that are referenced in the body of the procedure. For example: (peval '(lambda (x y z) (f z x y)) ; the procedure the knowledge about x , y and z will return: (lambda (y) (f '#t '1 y)) get the parameter list get the body of the procedure remove the constant parameters in the body, replace variable refs to the constant parameters by the corresponding constant special value indicating non-constant parms. remove from list 'l' all elements whose corresponding element in 'a' is a constant extract from list 'l' all elements whose corresponding element in 'a' is a constant return a modified 'exp' where each var named in 'env' is replaced by the corresponding expr (it is assumed that the code has been alphatized) ------------------------------------------------------------------------------ The expression simplifier. simplify the expression 'exp' destructively (it is assumed that the code has been alphatized) leave constants the way they are leave variable references the way they are dead code removal for conditionals simplify the predicate is the predicate a constant? false? simplify consequent and alt. remove all useless expressions not last expression? is the operator position a var ref? is it a bound variable? is it a bound variable? compute how many references to variable 'var' are contained in 'exp' *kludge* equal? is not exactly what we want... call proc! on each CONS CELL in the list 'l' return the argument pattern (i.e. the list of constants in 'exps' but with the not-constant value wherever the corresponding expression in 'exps' is not a constant) ------------------------------------------------------------------------------ Knowledge about primitive procedures. associative ops + is commutative * is commutative ------------------------------------------------------------------------------ Examples: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . (try-peval example2 (list not-constant '1)) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . (try-peval example3 (list '(1 2 3) not-constant)) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . (try-peval example4 (list 'x not-constant)) (try-peval example4 (list '(f 1 2 3) not-constant)) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . (try-peval example6 '()) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . (try-peval example7 (list '(a b c d e f g h i j k l m n o p q r s t u v w x y z))) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PEVAL -- A simple partial evaluator for Scheme , written by . Utilities (define (every? pred? l) (let loop ((l l)) (or (null? l) (and (pred? (car l)) (loop (cdr l)))))) (define (some? pred? l) (let loop ((l l)) (if (null? l) #f (or (pred? (car l)) (loop (cdr l)))))) (define (map2 f l1 l2) (let loop ((l1 l1) (l2 l2)) (if (pair? l1) (cons (f (car l1) (car l2)) (loop (cdr l1) (cdr l2))) '()))) (define (get-last-pair l) (let loop ((l l)) (let ((x (cdr l))) (if (pair? x) (loop x) l)))) (define (partial-evaluate proc args) (peval (alphatize proc '()) args)) (cond ((const-expr? exp) (quot (const-value exp))) ((symbol? exp) (let ((x (assq exp env))) (if x (cdr x) exp))) ((or (eq? (car exp) 'if) (eq? (car exp) 'begin)) (cons (car exp) (map alpha (cdr exp)))) ((or (eq? (car exp) 'let) (eq? (car exp) 'letrec)) (let ((new-env (new-variables (map car (cadr exp)) env))) (list (car exp) (map (lambda (x) (list (cdr (assq (car x) new-env)) (if (eq? (car exp) 'let) (alpha (cadr x)) (alphatize (cadr x) new-env)))) (cadr exp)) (alphatize (caddr exp) new-env)))) ((eq? (car exp) 'lambda) (let ((new-env (new-variables (cadr exp) env))) (list 'lambda (map (lambda (x) (cdr (assq x new-env))) (cadr exp)) (alphatize (caddr exp) new-env)))) (else (map alpha exp)))) (alpha exp)) (and (not (symbol? expr)) (or (not (pair? expr)) (eq? (car expr) 'quote)))) (cadr expr) expr)) (list 'quote val)) (define (new-variables parms env) (append (map (lambda (x) (cons x (new-variable x))) parms) env)) (define *current-num* 0) (define (new-variable name) (set! *current-num* (+ *current-num* 1)) (string->symbol (string-append (symbol->string name) "_" (number->string *current-num*)))) (define (peval proc args) (simplify! (list 'lambda (map2 (lambda (x y) (if (not-constant? y) '(()) (cons x (quot y)))) parms args)))))) (define (not-constant? x) (eq? x not-constant)) '()) ((not-constant? (car a)) (cons (car l) (remove-constant (cdr l) (cdr a)))) (else (remove-constant (cdr l) (cdr a))))) '()) ((not-constant? (car a)) (extract-constant (cdr l) (cdr a))) (else (cons (car l) (extract-constant (cdr l) (cdr a)))))) (quot (const-value exp))) ((symbol? exp) (let ((x (assq exp env))) (if x (cdr x) exp))) ((or (eq? (car exp) 'if) (eq? (car exp) 'begin)) (cons (car exp) (map bs (cdr exp)))) ((or (eq? (car exp) 'let) (eq? (car exp) 'letrec)) (list (car exp) (map (lambda (x) (list (car x) (bs (cadr x)))) (cadr exp)) (bs (caddr exp)))) ((eq? (car exp) 'lambda) (list 'lambda (cadr exp) (bs (caddr exp)))) (else (map bs exp)))) (bs exp)) (define (simp! where env) (define (s! where) (let ((exp (car where))) (begin (set-car! where (if (= (length exp) 3) ''() (cadddr exp)) (caddr exp))) (s! where)) ((eq? (car exp) 'begin) (for-each! s! (cdr exp)) (let ((x (cadr exps))) (loop (if (or (const-expr? x) (symbol? x) (and (pair? x) (eq? (car x) 'lambda))) (begin (set-cdr! exps (cddr exps)) exps) (cdr exps)))))) only one expression in the begin ? (set-car! where (cadr exp)))) ((or (eq? (car exp) 'let) (eq? (car exp) 'letrec)) (let ((new-env (cons exp env))) (define (keep i) (if (>= i (length (cadar where))) '() (let* ((var (car (list-ref (cadar where) i))) (val (cadr (assq var (cadar where)))) (refs (ref-count (car where) var)) (self-refs (ref-count val var)) (total-refs (- (car refs) (car self-refs))) (oper-refs (- (cadr refs) (cadr self-refs)))) (cond ((= total-refs 0) (keep (+ i 1))) ((or (const-expr? val) (symbol? val) (and (pair? val) (eq? (car val) 'lambda) (= total-refs 1) (= oper-refs 1) (= (car self-refs) 0)) (and (caddr refs) (= total-refs 1))) (set-car! where (beta-subst (car where) (list (cons var val)))) (keep (+ i 1))) (else (cons var (keep (+ i 1)))))))) (simp! (cddr exp) new-env) (for-each! (lambda (x) (simp! (cdar x) new-env)) (cadr exp)) (let ((to-keep (keep 0))) (if (< (length to-keep) (length (cadar where))) (begin (if (null? to-keep) (set-car! where (caddar where)) (set-car! (cdar where) (map (lambda (v) (assq v (cadar where))) to-keep))) (s! where)) (if (null? to-keep) (set-car! where (caddar where))))))) ((eq? (car exp) 'lambda) (simp! (cddr exp) (cons exp env))) (else (for-each! s! exp) (let ((frame (binding-frame (car exp) env))) (let ((proc (bound-expr (car exp) frame))) (if (and (pair? proc) (eq? (car proc) 'lambda) (some? const-expr? (cdr exp))) (let* ((args (arg-pattern (cdr exp))) (new-proc (peval proc args)) (new-args (remove-constant (cdr exp) args))) (set-car! where (cons (add-binding new-proc frame (car exp)) new-args))))) (set-car! where (constant-fold-global (car exp) (cdr exp)))))) ((not (pair? (car exp)))) ((eq? (caar exp) 'lambda) (set-car! where (list 'let (map2 list (cadar exp) (cdr exp)) (caddar exp))) (s! where))))))) (s! where)) (define (remove-empty-calls! where env) (define (rec! where) (let ((exp (car where))) (cond ((const-expr? exp)) ((symbol? exp)) ((eq? (car exp) 'if) (rec! (cdr exp)) (rec! (cddr exp)) (rec! (cdddr exp))) ((eq? (car exp) 'begin) (for-each! rec! (cdr exp))) ((or (eq? (car exp) 'let) (eq? (car exp) 'letrec)) (let ((new-env (cons exp env))) (remove-empty-calls! (cddr exp) new-env) (for-each! (lambda (x) (remove-empty-calls! (cdar x) new-env)) (cadr exp)))) ((eq? (car exp) 'lambda) (rec! (cddr exp))) (else (for-each! rec! (cdr exp)) (if (and (null? (cdr exp)) (symbol? (car exp))) (let ((frame (binding-frame (car exp) env))) (let ((proc (bound-expr (car exp) frame))) (if (and (pair? proc) (eq? (car proc) 'lambda)) (begin (set! changed? #t) (set-car! where (caddr proc)))))))))))) (rec! where)) (define changed? #f) (let ((x (list exp))) (let loop () (set! changed? #f) (simp! x '()) (remove-empty-calls! x '()) (if changed? (loop) (car x))))) (oper 0) (always-evaled #t)) (define (rc exp ae) (cond ((const-expr? exp)) ((symbol? exp) (if (eq? exp var) (begin (set! total (+ total 1)) (set! always-evaled (and ae always-evaled))))) ((eq? (car exp) 'if) (rc (cadr exp) ae) (for-each (lambda (x) (rc x #f)) (cddr exp))) ((eq? (car exp) 'begin) (for-each (lambda (x) (rc x ae)) (cdr exp))) ((or (eq? (car exp) 'let) (eq? (car exp) 'letrec)) (for-each (lambda (x) (rc (cadr x) ae)) (cadr exp)) (rc (caddr exp) ae)) ((eq? (car exp) 'lambda) (rc (caddr exp) #f)) (else (for-each (lambda (x) (rc x ae)) exp) (if (symbol? (car exp)) (if (eq? (car exp) var) (set! oper (+ oper 1))))))) (rc exp #t) (list total oper always-evaled))) (define (binding-frame var env) (cond ((null? env) #f) ((or (eq? (caar env) 'let) (eq? (caar env) 'letrec)) (if (assq var (cadar env)) (car env) (binding-frame var (cdr env)))) ((eq? (caar env) 'lambda) (if (memq var (cadar env)) (car env) (binding-frame var (cdr env)))) (else (fatal-error "ill-formed environment")))) (define (bound-expr var frame) (cond ((or (eq? (car frame) 'let) (eq? (car frame) 'letrec)) (cadr (assq var (cadr frame)))) ((eq? (car frame) 'lambda) not-constant) (else (fatal-error "ill-formed frame")))) (define (add-binding val frame name) (define (find-val val bindings) (cond ((null? bindings) #f) (else (find-val val (cdr bindings))))) (or (find-val val (cadr frame)) (let ((var (new-variable name))) (set-cdr! (get-last-pair (cadr frame)) (list (list var val))) var))) (if (not (null? l)) (begin (proc! l) (for-each! proc! (cdr l))))) (const-value (car exps)) not-constant) (arg-pattern (cdr exps))))) (define *primitives* (list (cons 'car (lambda (args) (and (= (length args) 1) (pair? (car args)) (quot (car (car args)))))) (cons 'cdr (lambda (args) (and (= (length args) 1) (pair? (car args)) (quot (cdr (car args)))))) (cons '+ (lambda (args) (and (every? number? args) (quot (sum args 0))))) (cons '* (lambda (args) (and (every? number? args) (quot (product args 1))))) (cons '- (lambda (args) (and (> (length args) 0) (every? number? args) (quot (if (null? (cdr args)) (- (car args)) (- (car args) (sum (cdr args) 0))))))) (cons '/ (lambda (args) (and (> (length args) 1) (every? number? args) (quot (if (null? (cdr args)) (/ (car args)) (/ (car args) (product (cdr args) 1))))))) (cons '< (lambda (args) (and (= (length args) 2) (every? number? args) (quot (< (car args) (cadr args)))))) (cons '= (lambda (args) (and (= (length args) 2) (every? number? args) (quot (= (car args) (cadr args)))))) (cons '> (lambda (args) (and (= (length args) 2) (every? number? args) (quot (> (car args) (cadr args)))))) (cons 'eq? (lambda (args) (and (= (length args) 2) (quot (eq? (car args) (cadr args)))))) (cons 'not (lambda (args) (and (= (length args) 1) (quot (not (car args)))))) (cons 'null? (lambda (args) (and (= (length args) 1) (quot (null? (car args)))))) (cons 'pair? (lambda (args) (and (= (length args) 1) (quot (pair? (car args)))))) (cons 'symbol? (lambda (args) (and (= (length args) 1) (quot (symbol? (car args)))))) ) ) (define (sum lst n) (if (null? lst) n (sum (cdr lst) (+ n (car lst))))) (define (product lst n) (if (null? lst) n (product (cdr lst) (* n (car lst))))) (define (reduce-global name args) (let ((x (assq name *primitives*))) (and x ((cdr x) args)))) (define (constant-fold-global name exprs) (define (flatten args op) (cond ((null? args) '()) ((and (pair? (car args)) (eq? (caar args) op)) (append (flatten (cdar args) op) (flatten (cdr args) op))) (else (cons (car args) (flatten (cdr args) op))))) (flatten exprs name) exprs))) (or (and (every? const-expr? args) (reduce-global name (map const-value args))) (let ((pattern (arg-pattern args))) (let ((non-const (remove-constant args pattern)) (const (map const-value (extract-constant args pattern)))) (let ((x (reduce-global '+ const))) (if x (let ((y (const-value x))) (cons '+ (if (= y 0) non-const (cons x non-const)))) (cons name args)))) (let ((x (reduce-global '* const))) (if x (let ((y (const-value x))) (cons '* (if (= y 1) non-const (cons x non-const)))) (cons name args)))) ((eq? name 'cons) (cond ((and (const-expr? (cadr args)) (null? (const-value (cadr args)))) (list 'list (car args))) ((and (pair? (cadr args)) (eq? (car (cadr args)) 'list)) (cons 'list (cons (car args) (cdr (cadr args))))) (else (cons name args)))) (else (cons name args)))))))) (define (try-peval proc args) (partial-evaluate proc args)) (define example1 '(lambda (a b c) (if (null? a) b (+ (car a) c)))) ( try - peval example1 ( list ' ( 10 11 ) not - constant ' 1 ) ) (define example2 '(lambda (x y) (let ((q (lambda (a b) (if (< a 0) b (- 10 b))))) (if (< x 0) (q (- y) (- x)) (q y x))))) (define example3 '(lambda (l n) (letrec ((add-list (lambda (l n) (if (null? l) '() (cons (+ (car l) n) (add-list (cdr l) n)))))) (add-list l n)))) ( try - peval example3 ( list not - constant ' 1 ) ) (define example4 '(lambda (exp env) (letrec ((eval (lambda (exp env) (letrec ((eval-list (lambda (l env) (if (null? l) '() (cons (eval (car l) env) (eval-list (cdr l) env)))))) (if (symbol? exp) (lookup exp env) (if (not (pair? exp)) exp (if (eq? (car exp) 'quote) (car (cdr exp)) (apply (eval (car exp) env) (eval-list (cdr exp) env))))))))) (eval exp env)))) (define example5 '(lambda (a b) (letrec ((funct (lambda (x) (+ x b (if (< x 1) 0 (funct (- x 1))))))) (funct a)))) ( try - peval example5 ( list ' 5 not - constant ) ) (define example6 '(lambda () (letrec ((fib (lambda (x) (if (< x 2) x (+ (fib (- x 1)) (fib (- x 2))))))) (fib 10)))) (define example7 '(lambda (input) (letrec ((copy (lambda (in) (if (pair? in) (cons (copy (car in)) (copy (cdr in))) in)))) (copy input)))) (define example8 '(lambda (input) (letrec ((reverse (lambda (in result) (if (pair? in) (reverse (cdr in) (cons (car in) result)) result)))) (reverse input '())))) ( try - peval example8 ( list ' ( a b c d e f g h i j k l m n o p q r s t u v w x y z ) ) ) (define (test) (set! *current-num* 0) (list (try-peval example1 (list '(10 11) not-constant '1)) (try-peval example2 (list not-constant '1)) (try-peval example3 (list not-constant '1)) (try-peval example3 (list '(1 2 3) not-constant)) (try-peval example4 (list 'x not-constant)) (try-peval example4 (list '(f 1 2 3) not-constant)) (try-peval example5 (list '5 not-constant)) (try-peval example6 '()) (try-peval example7 (list '(a b c d e f g h i j k l m n o p q r s t u v w x y z))) (try-peval example8 (list '(a b c d e f g h i j k l m n o p q r s t u v w x y z))))) (define (main . args) (run-benchmark "peval" peval-iters (lambda (result) (and (list? result) (= (length result) 10) (equal? (list-ref result 9) '(lambda () (list 'z 'y 'x 'w 'v 'u 't 's 'r 'q 'p 'o 'n 'm 'l 'k 'j 'i 'h 'g 'f 'e 'd 'c 'b 'a))))) (lambda () (lambda () (test)))))
d41007e2a76abfeb2e3dbcc59ecf3fd8af37bc9d72cabb4d3eee2179330c4824
PacktWorkshops/The-Clojure-Workshop
examples.clj
;;; In REPL: minimal macros (defmacro minimal-macro [] '(println "I'm trapped inside a macro!")) (defn minimal-function [] (println "I'm trapped inside a function!")) (macroexpand '(minimal-function)) ;;; returns: (minimal-function) (macroexpand '(minimal-macro)) ;;; returns: (println "I'm trapped inside a macro!") (defmacro mistaken-macro [] (println "I'm trapped... somewhere!")) (mistaken-macro) ;;; returns: nil ;;; prints: I'm trapped... somewhere! (macroexpand '(mistaken-macro)) ;;; returns: nil ;;; prints: I'm trapped... somewhere! ;;; In REPL: minimal, but multiple times (defmacro multi-minimal [n-times] (cons 'do (repeat n-times '(println "Macro")))) (multi-minimal 3) ;;; returns: nil ;;; prints: Macro Macro Macro (macroexpand '(multi-minimal 3)) ;;; returns: ;;; (do ( println " Macro " ) ( println " Macro " ) ( println " Macro " ) ) ;;; In REPL: a function to help the macro (defn multi-min [n-times] (cons 'do (repeat n-times '(println "Macro")))) (defmacro multi-minimal-two [n-times] (multi-min n-times)) (multi-minimal-two 3) ;;; returns: nil ;;; prints: Macro Macro Macro ;;; In REPL: run time parameters ;;; Warning: compiles but causes exception when used (defmacro parameterized-multi-minimal [n-times s] (cons 'do (repeat n-times '(println s)))) ;;; This version works (defmacro parameterized-multi-minimal [n-times s] (concat (list 'let ['string-to-print s]) (repeat n-times '(println string-to-print)))) (parameterized-multi-minimal 3 "My own text.") ;;; returns: nil ;;; prints: ;;; My own text. ;;; My own text. ;;; My own text. ;;; In REPL: syntax quoting (defmacro parameterized-with-syntax [n-times s] `(do ~@(repeat n-times `(println ~s)))) (macroexpand '(parameterized-with-syntax 3 "Syntax quoting!")) ;;; returns: ;;; (do ( clojure.core/println " Syntax quoting ! " ) ( clojure.core/println " Syntax quoting ! " ) ( clojure.core/println " Syntax quoting ! " ) ) ;;; In REPL: macro hygiene (defmacro let-number [[binding n] body] `(let [~(symbol (str binding "-as-string")) (str ~n) ~(symbol (str binding "-as-int")) (int ~n) ~(symbol (str binding "-as-double")) (double ~n)] ~body)) (let-number [my-int 5] (type my-int-as-string)) (let [my-int-as-int 1000] (let-number [my-int (/ my-int-as-int 2)] (str "The result is: " my-int-as-double))) In REPL : auto (defmacro let-number [[binding n] body] `(let [result# ~n ~(symbol (str binding "-as-string")) (str result#) ~(symbol (str binding "-as-int")) (int result#) ~(symbol (str binding "-as-double")) (double result#)] ~body)) (let [my-int-as-int 1000.0] (let-number [my-int (/ my-int-as-int 2)] (str "The result is: " my-int-as-double))) In REPL : manual (comment ;; Doesn't work because of multiple syntax-quoting environments (defmacro fn-context [v & symbol-fn-pairs] `(let [v# ~v] ~@(map (fn [[sym f]] `(defn ~sym [x#] (f v# x#))) (partition 2 symbol-fn-pairs))))) (defmacro fn-context [v & symbol-fn-pairs] (let [common-val-gensym (gensym "common-val-")] `(let [~common-val-gensym ~v] ~@(map (fn [[sym f]] `(defn ~sym [x#] (~f ~common-val-gensym x#))) (partition 2 symbol-fn-pairs))))) (let [x 100] (def adder (partial + x)) (def subtractor (partial - x)) (def multiplier (partial * x)))
null
https://raw.githubusercontent.com/PacktWorkshops/The-Clojure-Workshop/3d309bb0e46a41ce2c93737870433b47ce0ba6a2/Chapter11/Examples/examples.clj
clojure
In REPL: minimal macros returns: (minimal-function) returns: (println "I'm trapped inside a macro!") returns: nil prints: I'm trapped... somewhere! returns: nil prints: I'm trapped... somewhere! In REPL: minimal, but multiple times returns: nil prints: returns: (do In REPL: a function to help the macro returns: nil prints: In REPL: run time parameters Warning: compiles but causes exception when used This version works returns: nil prints: My own text. My own text. My own text. In REPL: syntax quoting returns: (do In REPL: macro hygiene Doesn't work because of multiple syntax-quoting environments
(defmacro minimal-macro [] '(println "I'm trapped inside a macro!")) (defn minimal-function [] (println "I'm trapped inside a function!")) (macroexpand '(minimal-function)) (macroexpand '(minimal-macro)) (defmacro mistaken-macro [] (println "I'm trapped... somewhere!")) (mistaken-macro) (macroexpand '(mistaken-macro)) (defmacro multi-minimal [n-times] (cons 'do (repeat n-times '(println "Macro")))) (multi-minimal 3) Macro Macro Macro (macroexpand '(multi-minimal 3)) ( println " Macro " ) ( println " Macro " ) ( println " Macro " ) ) (defn multi-min [n-times] (cons 'do (repeat n-times '(println "Macro")))) (defmacro multi-minimal-two [n-times] (multi-min n-times)) (multi-minimal-two 3) Macro Macro Macro (defmacro parameterized-multi-minimal [n-times s] (cons 'do (repeat n-times '(println s)))) (defmacro parameterized-multi-minimal [n-times s] (concat (list 'let ['string-to-print s]) (repeat n-times '(println string-to-print)))) (parameterized-multi-minimal 3 "My own text.") (defmacro parameterized-with-syntax [n-times s] `(do ~@(repeat n-times `(println ~s)))) (macroexpand '(parameterized-with-syntax 3 "Syntax quoting!")) ( clojure.core/println " Syntax quoting ! " ) ( clojure.core/println " Syntax quoting ! " ) ( clojure.core/println " Syntax quoting ! " ) ) (defmacro let-number [[binding n] body] `(let [~(symbol (str binding "-as-string")) (str ~n) ~(symbol (str binding "-as-int")) (int ~n) ~(symbol (str binding "-as-double")) (double ~n)] ~body)) (let-number [my-int 5] (type my-int-as-string)) (let [my-int-as-int 1000] (let-number [my-int (/ my-int-as-int 2)] (str "The result is: " my-int-as-double))) In REPL : auto (defmacro let-number [[binding n] body] `(let [result# ~n ~(symbol (str binding "-as-string")) (str result#) ~(symbol (str binding "-as-int")) (int result#) ~(symbol (str binding "-as-double")) (double result#)] ~body)) (let [my-int-as-int 1000.0] (let-number [my-int (/ my-int-as-int 2)] (str "The result is: " my-int-as-double))) In REPL : manual (comment (defmacro fn-context [v & symbol-fn-pairs] `(let [v# ~v] ~@(map (fn [[sym f]] `(defn ~sym [x#] (f v# x#))) (partition 2 symbol-fn-pairs))))) (defmacro fn-context [v & symbol-fn-pairs] (let [common-val-gensym (gensym "common-val-")] `(let [~common-val-gensym ~v] ~@(map (fn [[sym f]] `(defn ~sym [x#] (~f ~common-val-gensym x#))) (partition 2 symbol-fn-pairs))))) (let [x 100] (def adder (partial + x)) (def subtractor (partial - x)) (def multiplier (partial * x)))
45ff9fa295d23fc0a2d6915803c02e28726db1ff7886cb2f74a1ff0a8820f351
kelvin-mai/clj-auth
core_test.clj
(ns auth.core-test (:require [auth.core :refer [app]] [clojure.test :refer [deftest testing is]])) (def headers {"accept" "application/edn"}) (def read-body (comp read-string slurp :body)) (deftest test-ping-route (testing "application works" (is (= (-> {:headers headers :request-method :get :uri "/api/ping"} app read-body) {:hello "world" :ping "pong"})))) (deftest test-unauthorized (testing "users route should return unauthorized" (is (= (-> {:headers headers :request-method :get :uri "/api/users"} app read-body) {:error "Unauthorized"}))))
null
https://raw.githubusercontent.com/kelvin-mai/clj-auth/254a82d01c731bf18a5974408d3c5cf5ab159aaf/test/auth/core_test.clj
clojure
(ns auth.core-test (:require [auth.core :refer [app]] [clojure.test :refer [deftest testing is]])) (def headers {"accept" "application/edn"}) (def read-body (comp read-string slurp :body)) (deftest test-ping-route (testing "application works" (is (= (-> {:headers headers :request-method :get :uri "/api/ping"} app read-body) {:hello "world" :ping "pong"})))) (deftest test-unauthorized (testing "users route should return unauthorized" (is (= (-> {:headers headers :request-method :get :uri "/api/users"} app read-body) {:error "Unauthorized"}))))
73dcf766a40b596c9b39cba03171539b3788541a6f9bc08e6345df68a9405326
NorfairKing/smos
OptParse.hs
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # module Smos.Query.OptParse ( module Smos.Query.OptParse, module Smos.Query.OptParse.Types, ) where import Data.Foldable import qualified Data.Map as M import Data.Maybe import qualified Data.Text as T import Data.Version import qualified Env import Options.Applicative as OptParse import Options.Applicative.Help.Pretty as Doc import Paths_smos_query import Smos.Data import Smos.Query.OptParse.Types import Smos.Report.Archive import Smos.Report.Config import qualified Smos.Report.OptParse as Report import Smos.Report.Period import Smos.Report.Time import Smos.Report.TimeBlock import qualified System.Environment as System import Text.Colour import Text.Colour.Layout getInstructions :: IO Instructions getInstructions = do Arguments c flags <- getArguments env <- getEnvironment config <- getConfiguration flags env combineToInstructions c (Report.flagWithRestFlags flags) (Report.envWithRestEnv env) config combineToInstructions :: Command -> Flags -> Environment -> Maybe Configuration -> IO Instructions combineToInstructions c Flags {..} Environment {..} mc = do let hideArchiveWithDefault def mflag = fromMaybe def $ mflag <|> envHideArchive <|> (mc >>= confHideArchive) src <- Report.combineToConfig defaultReportConfig flagReportFlags envReportEnvironment (confReportConf <$> mc) let colourSettings = getColourSettings $ mc >>= confColourConfiguration let settings = Settings { settingColourSettings = colourSettings, settingDirectoryConfig = smosReportConfigDirectoryConfig src } dispatch <- case c of CommandEntry EntryFlags {..} -> pure $ DispatchEntry EntrySettings { entrySetFilter = entryFlagFilter, entrySetProjection = fromMaybe defaultProjection entryFlagProjection, entrySetSorter = entryFlagSorter, entrySetHideArchive = hideArchiveWithDefault HideArchive entryFlagHideArchive, entrySetOutputFormat = fromMaybe OutputPretty entryFlagOutputFormat } CommandReport ReportFlags {..} -> do let mprc :: (PreparedReportConfiguration -> Maybe a) -> Maybe a mprc func = mc >>= confPreparedReportConfiguration >>= func pure $ DispatchReport ReportSettings { reportSetReportName = reportFlagReportName, reportSetAvailableReports = fromMaybe M.empty $ mprc preparedReportConfAvailableReports, reportSetOutputFormat = fromMaybe OutputPretty reportFlagOutputFormat } CommandWaiting WaitingFlags {..} -> do let mwc :: (WaitingReportConfig -> a) -> a mwc func = func $ smosReportConfigWaitingConfig src pure $ DispatchWaiting WaitingSettings { waitingSetFilter = waitingFlagFilter, waitingSetHideArchive = hideArchiveWithDefault HideArchive waitingFlagHideArchive, waitingSetThreshold = fromMaybe (mwc waitingReportConfigThreshold) waitingFlagThreshold } CommandNext NextFlags {..} -> pure $ DispatchNext NextSettings { nextSetFilter = nextFlagFilter, nextSetHideArchive = hideArchiveWithDefault HideArchive nextFlagHideArchive } CommandClock ClockFlags {..} -> pure $ DispatchClock ClockSettings { clockSetFilter = clockFlagFilter, clockSetPeriod = fromMaybe AllTime clockFlagPeriodFlags, clockSetBlock = fromMaybe DayBlock clockFlagBlockFlags, clockSetOutputFormat = fromMaybe OutputPretty clockFlagOutputFormat, clockSetClockFormat = case clockFlagClockFormat of Nothing -> ClockFormatTemporal TemporalMinutesResolution Just cffs -> case cffs of ClockFormatTemporalFlag res -> ClockFormatTemporal $ fromMaybe TemporalMinutesResolution res ClockFormatDecimalFlag res -> ClockFormatDecimal $ fromMaybe (DecimalResolution 2) res, clockSetReportStyle = fromMaybe ClockForest clockFlagReportStyle, clockSetHideArchive = hideArchiveWithDefault Don'tHideArchive clockFlagHideArchive } CommandAgenda AgendaFlags {..} -> do let period = -- Note [Agenda command defaults] -- The default here is 'AllTime' for good reason. -- -- You may think that 'Today' is a better default because smos-calendar-import fills up -- your agenda too much for it to be useful. -- -- However, as a beginner you want to be able to run smos-query agenda to see your -- SCHEDULED and DEADLINE timestamps in the near future. -- By the time users figure out how to use smos-calendar-import, they will probably either already use " smos - query work " or have an alias for ' smos - query agenda --today ' -- if they need it. fromMaybe AllTime agendaFlagPeriod let block = -- See Note [Agenda command defaults] let defaultBlock = case period of AllTime -> OneBlock LastYear -> MonthBlock ThisYear -> MonthBlock NextYear -> MonthBlock LastMonth -> WeekBlock ThisMonth -> WeekBlock NextMonth -> WeekBlock LastWeek -> DayBlock ThisWeek -> DayBlock NextWeek -> DayBlock _ -> OneBlock in fromMaybe defaultBlock agendaFlagBlock pure $ DispatchAgenda AgendaSettings { agendaSetFilter = agendaFlagFilter, agendaSetHistoricity = fromMaybe HistoricalAgenda agendaFlagHistoricity, agendaSetBlock = block, agendaSetHideArchive = hideArchiveWithDefault HideArchive agendaFlagHideArchive, agendaSetPeriod = period } CommandProjects ProjectsFlags {..} -> pure $ DispatchProjects ProjectsSettings {projectsSetFilter = projectsFlagFilter} CommandStuck StuckFlags {..} -> do let msc :: (StuckReportConfig -> a) -> a msc func = func $ smosReportConfigStuckConfig src pure $ DispatchStuck StuckSettings { stuckSetFilter = stuckFlagFilter, stuckSetThreshold = fromMaybe (msc stuckReportConfigThreshold) stuckFlagThreshold } CommandWork WorkFlags {..} -> do let mwac :: (WaitingReportConfig -> a) -> a mwac func = func $ smosReportConfigWaitingConfig src let msc :: (StuckReportConfig -> a) -> a msc func = func $ smosReportConfigStuckConfig src let mwc :: (WorkReportConfig -> a) -> a mwc func = func $ smosReportConfigWorkConfig src pure $ DispatchWork WorkSettings { workSetContext = workFlagContext, workSetTime = workFlagTime, workSetFilter = workFlagFilter, workSetHideArchive = hideArchiveWithDefault HideArchive workFlagHideArchive, workSetProjection = fromMaybe (mwc workReportConfigProjection) workFlagProjection, workSetSorter = mwc workReportConfigSorter <|> workFlagSorter, workSetWaitingThreshold = fromMaybe (mwac waitingReportConfigThreshold) workFlagWaitingThreshold, workSetStuckThreshold = fromMaybe (msc stuckReportConfigThreshold) workFlagStuckThreshold, workSetBaseFilter = mwc workReportConfigBaseFilter, workSetContexts = mwc workReportConfigContexts, workSetChecks = mwc workReportConfigChecks, workSetTimeProperty = mwc workReportConfigTimeProperty } CommandLog LogFlags {..} -> pure $ DispatchLog LogSettings { logSetFilter = logFlagFilter, logSetPeriod = fromMaybe Today logFlagPeriodFlags, logSetBlock = fromMaybe DayBlock logFlagBlockFlags, logSetHideArchive = hideArchiveWithDefault Don'tHideArchive logFlagHideArchive } CommandTags TagsFlags {..} -> pure $ DispatchTags TagsSettings {tagsSetFilter = tagsFlagFilter} CommandStats StatsFlags {..} -> pure $ DispatchStats StatsSettings {statsSetPeriod = fromMaybe AllTime statsFlagPeriodFlags} pure $ Instructions dispatch settings getColourSettings :: Maybe ColourConfiguration -> ColourSettings getColourSettings mcc = ColourSettings { colourSettingBackground = fromMaybe (colourSettingBackground defaultColourSettings) (mcc >>= colourConfigurationBackground) } defaultColourSettings :: ColourSettings defaultColourSettings = ColourSettings { colourSettingBackground = UseTableBackground (Bicolour (Just (Colour8Bit 234)) (Just (Colour8Bit 235))) } getEnvironment :: IO (Report.EnvWithConfigFile Environment) getEnvironment = Env.parse (Env.header "Environment") prefixedEnvironmentParser prefixedEnvironmentParser :: Env.Parser Env.Error (Report.EnvWithConfigFile Environment) prefixedEnvironmentParser = Env.prefixed "SMOS_" environmentParser environmentParser :: Env.Parser Env.Error (Report.EnvWithConfigFile Environment) environmentParser = Report.envWithConfigFileParser $ Environment <$> Report.environmentParser <*> optional (Env.var ignoreArchiveReader "IGNORE_ARCHIVE" (Env.help "whether to ignore the archive")) where ignoreArchiveReader = \case "True" -> Right HideArchive "False" -> Right Don'tHideArchive _ -> Left $ Env.UnreadError "Must be 'True' or 'False' if set" getConfiguration :: Report.FlagsWithConfigFile Flags -> Report.EnvWithConfigFile Environment -> IO (Maybe Configuration) getConfiguration = Report.getConfiguration getArguments :: IO Arguments getArguments = do args <- System.getArgs let result = runArgumentsParser args handleParseResult result runArgumentsParser :: [String] -> ParserResult Arguments runArgumentsParser = execParserPure prefs_ argParser where prefs_ = defaultPrefs { prefShowHelpOnError = True, prefShowHelpOnEmpty = True } argParser :: ParserInfo Arguments argParser = info (helper <*> parseArgs) help_ where help_ = fullDesc <> progDescDoc (Just description) description :: Doc description = Doc.vsep $ map Doc.text $ [ "", "Smos Query Tool version: " <> showVersion version, "" ] ++ readDataVersionsHelpMessage parseArgs :: Parser Arguments parseArgs = Arguments <$> parseCommand <*> Report.parseFlagsWithConfigFile parseFlags parseCommand :: Parser Command parseCommand = hsubparser $ mconcat [ command "entry" parseCommandEntry, command "report" parseCommandReport, command "work" parseCommandWork, command "waiting" parseCommandWaiting, command "next" parseCommandNext, command "clock" parseCommandClock, command "agenda" parseCommandAgenda, command "projects" parseCommandProjects, command "stuck" parseCommandStuck, command "log" parseCommandLog, command "stats" parseCommandStats, command "tags" parseCommandTags ] parseCommandEntry :: ParserInfo Command parseCommandEntry = info parser modifier where modifier = fullDesc <> progDesc "Select entries based on a given filter" parser = CommandEntry <$> ( EntryFlags <$> Report.parseFilterArgsRel <*> Report.parseProjectionArgs <*> Report.parseSorterArgs <*> Report.parseHideArchiveFlag <*> parseOutputFormat ) parseCommandReport :: ParserInfo Command parseCommandReport = info parser modifier where modifier = fullDesc <> progDesc "Run preconfigured reports" parser = CommandReport <$> ( ReportFlags <$> optional ( strArgument ( mconcat [ metavar "REPORT", help "The preconfigured report to run" ] ) ) <*> parseOutputFormat ) parseCommandWork :: ParserInfo Command parseCommandWork = info parser modifier where modifier = fullDesc <> progDesc "Show the work overview" parser = CommandWork <$> ( WorkFlags <$> Report.parseContextNameArg <*> Report.parseTimeFilterArg <*> Report.parseFilterOptionsRel <*> Report.parseProjectionArgs <*> Report.parseSorterArgs <*> Report.parseHideArchiveFlag <*> parseWorkWaitingThresholdFlag <*> parseWorkStuckThresholdFlag ) parseWorkWaitingThresholdFlag :: Parser (Maybe Time) parseWorkWaitingThresholdFlag = optional $ option (eitherReader $ parseTime . T.pack) ( mconcat [ long "waiting-threshold", metavar "TIME", help "The threshold at which to color waiting entries red" ] ) parseWorkStuckThresholdFlag :: Parser (Maybe Time) parseWorkStuckThresholdFlag = optional $ option (eitherReader $ parseTime . T.pack) ( mconcat [ long "stuck-threshold", metavar "TIME", help "The threshold at which to color stuck projects red" ] ) parseCommandWaiting :: ParserInfo Command parseCommandWaiting = info parser modifier where modifier = fullDesc <> progDesc "Print the \"WAITING\" tasks" parser = CommandWaiting <$> ( WaitingFlags <$> Report.parseFilterArgsRel <*> Report.parseHideArchiveFlag <*> parseWaitingThresholdFlag ) parseWaitingThresholdFlag :: Parser (Maybe Time) parseWaitingThresholdFlag = optional $ option (eitherReader $ parseTime . T.pack) ( mconcat [ long "threshold", metavar "TIME", help "The threshold at which to color waiting entries red" ] ) parseCommandNext :: ParserInfo Command parseCommandNext = info parser modifier where modifier = fullDesc <> progDesc "Print the next actions" parser = CommandNext <$> ( NextFlags <$> Report.parseFilterArgsRel <*> Report.parseHideArchiveFlag ) parseCommandClock :: ParserInfo Command parseCommandClock = info parser modifier where modifier = fullDesc <> progDesc "Print the clock table" parser = CommandClock <$> ( ClockFlags <$> Report.parseFilterArgsRel <*> Report.parsePeriod <*> Report.parseTimeBlock <*> parseOutputFormat <*> parseClockFormatFlags <*> parseClockReportStyle <*> Report.parseHideArchiveFlag ) parseClockFormatFlags :: Parser (Maybe ClockFormatFlags) parseClockFormatFlags = optional ( flag' ClockFormatTemporalFlag (long "temporal-resolution") <*> parseTemporalClockResolution <|> flag' ClockFormatDecimalFlag (long "decimal-resolution") <*> parseDecimalClockResolution ) parseTemporalClockResolution :: Parser (Maybe TemporalClockResolution) parseTemporalClockResolution = optional ( flag' TemporalSecondsResolution (long "seconds-resolution") <|> flag' TemporalMinutesResolution (long "minutes-resolution") <|> flag' TemporalHoursResolution (long "hours-resolution") ) parseDecimalClockResolution :: Parser (Maybe DecimalClockResolution) parseDecimalClockResolution = optional ( flag' DecimalQuarterResolution (long "quarters-resolution") <|> (flag' DecimalResolution (long "resolution") <*> argument auto (help "significant digits")) <|> flag' DecimalHoursResolution (long "hours-resolution") ) parseClockReportStyle :: Parser (Maybe ClockReportStyle) parseClockReportStyle = optional (flag' ClockForest (long "forest") <|> flag' ClockFlat (long "flat")) parseCommandAgenda :: ParserInfo Command parseCommandAgenda = info parser modifier where modifier = fullDesc <> progDesc "Print the agenda" parser = CommandAgenda <$> ( AgendaFlags <$> Report.parseFilterArgsRel <*> Report.parseHistoricityFlag <*> Report.parseTimeBlock <*> Report.parseHideArchiveFlag <*> Report.parsePeriod ) parseCommandProjects :: ParserInfo Command parseCommandProjects = info parser modifier where modifier = fullDesc <> progDesc "Print the projects overview" parser = CommandProjects <$> ( ProjectsFlags <$> Report.parseProjectFilterArgs ) parseCommandStuck :: ParserInfo Command parseCommandStuck = info parser modifier where modifier = fullDesc <> progDesc "Print the stuck projects overview" parser = CommandStuck <$> ( StuckFlags <$> Report.parseProjectFilterArgs <*> parseStuckThresholdFlag ) parseStuckThresholdFlag :: Parser (Maybe Time) parseStuckThresholdFlag = optional $ option (eitherReader $ parseTime . T.pack) ( mconcat [ long "threshold", help "The threshold at which to color stuck projects red" ] ) parseCommandLog :: ParserInfo Command parseCommandLog = info parser modifier where modifier = fullDesc <> progDesc "Print a log of what has happened." parser = CommandLog <$> ( LogFlags <$> Report.parseFilterArgsRel <*> Report.parsePeriod <*> Report.parseTimeBlock <*> Report.parseHideArchiveFlag ) parseCommandStats :: ParserInfo Command parseCommandStats = info parser modifier where modifier = fullDesc <> progDesc "Print the stats actions and warn if a file does not have one." parser = CommandStats <$> ( StatsFlags <$> Report.parsePeriod ) parseCommandTags :: ParserInfo Command parseCommandTags = info parser modifier where modifier = fullDesc <> progDesc "Print all the tags that are in use" parser = CommandTags <$> ( TagsFlags <$> Report.parseFilterArgsRel ) parseFlags :: Parser Flags parseFlags = Flags <$> Report.parseFlags parseOutputFormat :: Parser (Maybe OutputFormat) parseOutputFormat = optional ( asum [ flag' OutputPretty $ mconcat [long "pretty", help "pretty text"], flag' OutputYaml $ mconcat [long "yaml", help "Yaml"], flag' OutputJSON $ mconcat [long "json", help "single-line JSON"], flag' OutputJSONPretty $ mconcat [long "pretty-json", help "pretty JSON"] ] )
null
https://raw.githubusercontent.com/NorfairKing/smos/cf1669f353dce8c5d5fc2f378a89a9bc945f3f0b/smos-query/src/Smos/Query/OptParse.hs
haskell
# LANGUAGE OverloadedStrings # Note [Agenda command defaults] The default here is 'AllTime' for good reason. You may think that 'Today' is a better default because smos-calendar-import fills up your agenda too much for it to be useful. However, as a beginner you want to be able to run smos-query agenda to see your SCHEDULED and DEADLINE timestamps in the near future. By the time users figure out how to use smos-calendar-import, they will probably today ' if they need it. See Note [Agenda command defaults]
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE LambdaCase # # LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # module Smos.Query.OptParse ( module Smos.Query.OptParse, module Smos.Query.OptParse.Types, ) where import Data.Foldable import qualified Data.Map as M import Data.Maybe import qualified Data.Text as T import Data.Version import qualified Env import Options.Applicative as OptParse import Options.Applicative.Help.Pretty as Doc import Paths_smos_query import Smos.Data import Smos.Query.OptParse.Types import Smos.Report.Archive import Smos.Report.Config import qualified Smos.Report.OptParse as Report import Smos.Report.Period import Smos.Report.Time import Smos.Report.TimeBlock import qualified System.Environment as System import Text.Colour import Text.Colour.Layout getInstructions :: IO Instructions getInstructions = do Arguments c flags <- getArguments env <- getEnvironment config <- getConfiguration flags env combineToInstructions c (Report.flagWithRestFlags flags) (Report.envWithRestEnv env) config combineToInstructions :: Command -> Flags -> Environment -> Maybe Configuration -> IO Instructions combineToInstructions c Flags {..} Environment {..} mc = do let hideArchiveWithDefault def mflag = fromMaybe def $ mflag <|> envHideArchive <|> (mc >>= confHideArchive) src <- Report.combineToConfig defaultReportConfig flagReportFlags envReportEnvironment (confReportConf <$> mc) let colourSettings = getColourSettings $ mc >>= confColourConfiguration let settings = Settings { settingColourSettings = colourSettings, settingDirectoryConfig = smosReportConfigDirectoryConfig src } dispatch <- case c of CommandEntry EntryFlags {..} -> pure $ DispatchEntry EntrySettings { entrySetFilter = entryFlagFilter, entrySetProjection = fromMaybe defaultProjection entryFlagProjection, entrySetSorter = entryFlagSorter, entrySetHideArchive = hideArchiveWithDefault HideArchive entryFlagHideArchive, entrySetOutputFormat = fromMaybe OutputPretty entryFlagOutputFormat } CommandReport ReportFlags {..} -> do let mprc :: (PreparedReportConfiguration -> Maybe a) -> Maybe a mprc func = mc >>= confPreparedReportConfiguration >>= func pure $ DispatchReport ReportSettings { reportSetReportName = reportFlagReportName, reportSetAvailableReports = fromMaybe M.empty $ mprc preparedReportConfAvailableReports, reportSetOutputFormat = fromMaybe OutputPretty reportFlagOutputFormat } CommandWaiting WaitingFlags {..} -> do let mwc :: (WaitingReportConfig -> a) -> a mwc func = func $ smosReportConfigWaitingConfig src pure $ DispatchWaiting WaitingSettings { waitingSetFilter = waitingFlagFilter, waitingSetHideArchive = hideArchiveWithDefault HideArchive waitingFlagHideArchive, waitingSetThreshold = fromMaybe (mwc waitingReportConfigThreshold) waitingFlagThreshold } CommandNext NextFlags {..} -> pure $ DispatchNext NextSettings { nextSetFilter = nextFlagFilter, nextSetHideArchive = hideArchiveWithDefault HideArchive nextFlagHideArchive } CommandClock ClockFlags {..} -> pure $ DispatchClock ClockSettings { clockSetFilter = clockFlagFilter, clockSetPeriod = fromMaybe AllTime clockFlagPeriodFlags, clockSetBlock = fromMaybe DayBlock clockFlagBlockFlags, clockSetOutputFormat = fromMaybe OutputPretty clockFlagOutputFormat, clockSetClockFormat = case clockFlagClockFormat of Nothing -> ClockFormatTemporal TemporalMinutesResolution Just cffs -> case cffs of ClockFormatTemporalFlag res -> ClockFormatTemporal $ fromMaybe TemporalMinutesResolution res ClockFormatDecimalFlag res -> ClockFormatDecimal $ fromMaybe (DecimalResolution 2) res, clockSetReportStyle = fromMaybe ClockForest clockFlagReportStyle, clockSetHideArchive = hideArchiveWithDefault Don'tHideArchive clockFlagHideArchive } CommandAgenda AgendaFlags {..} -> do let period = fromMaybe AllTime agendaFlagPeriod let block = let defaultBlock = case period of AllTime -> OneBlock LastYear -> MonthBlock ThisYear -> MonthBlock NextYear -> MonthBlock LastMonth -> WeekBlock ThisMonth -> WeekBlock NextMonth -> WeekBlock LastWeek -> DayBlock ThisWeek -> DayBlock NextWeek -> DayBlock _ -> OneBlock in fromMaybe defaultBlock agendaFlagBlock pure $ DispatchAgenda AgendaSettings { agendaSetFilter = agendaFlagFilter, agendaSetHistoricity = fromMaybe HistoricalAgenda agendaFlagHistoricity, agendaSetBlock = block, agendaSetHideArchive = hideArchiveWithDefault HideArchive agendaFlagHideArchive, agendaSetPeriod = period } CommandProjects ProjectsFlags {..} -> pure $ DispatchProjects ProjectsSettings {projectsSetFilter = projectsFlagFilter} CommandStuck StuckFlags {..} -> do let msc :: (StuckReportConfig -> a) -> a msc func = func $ smosReportConfigStuckConfig src pure $ DispatchStuck StuckSettings { stuckSetFilter = stuckFlagFilter, stuckSetThreshold = fromMaybe (msc stuckReportConfigThreshold) stuckFlagThreshold } CommandWork WorkFlags {..} -> do let mwac :: (WaitingReportConfig -> a) -> a mwac func = func $ smosReportConfigWaitingConfig src let msc :: (StuckReportConfig -> a) -> a msc func = func $ smosReportConfigStuckConfig src let mwc :: (WorkReportConfig -> a) -> a mwc func = func $ smosReportConfigWorkConfig src pure $ DispatchWork WorkSettings { workSetContext = workFlagContext, workSetTime = workFlagTime, workSetFilter = workFlagFilter, workSetHideArchive = hideArchiveWithDefault HideArchive workFlagHideArchive, workSetProjection = fromMaybe (mwc workReportConfigProjection) workFlagProjection, workSetSorter = mwc workReportConfigSorter <|> workFlagSorter, workSetWaitingThreshold = fromMaybe (mwac waitingReportConfigThreshold) workFlagWaitingThreshold, workSetStuckThreshold = fromMaybe (msc stuckReportConfigThreshold) workFlagStuckThreshold, workSetBaseFilter = mwc workReportConfigBaseFilter, workSetContexts = mwc workReportConfigContexts, workSetChecks = mwc workReportConfigChecks, workSetTimeProperty = mwc workReportConfigTimeProperty } CommandLog LogFlags {..} -> pure $ DispatchLog LogSettings { logSetFilter = logFlagFilter, logSetPeriod = fromMaybe Today logFlagPeriodFlags, logSetBlock = fromMaybe DayBlock logFlagBlockFlags, logSetHideArchive = hideArchiveWithDefault Don'tHideArchive logFlagHideArchive } CommandTags TagsFlags {..} -> pure $ DispatchTags TagsSettings {tagsSetFilter = tagsFlagFilter} CommandStats StatsFlags {..} -> pure $ DispatchStats StatsSettings {statsSetPeriod = fromMaybe AllTime statsFlagPeriodFlags} pure $ Instructions dispatch settings getColourSettings :: Maybe ColourConfiguration -> ColourSettings getColourSettings mcc = ColourSettings { colourSettingBackground = fromMaybe (colourSettingBackground defaultColourSettings) (mcc >>= colourConfigurationBackground) } defaultColourSettings :: ColourSettings defaultColourSettings = ColourSettings { colourSettingBackground = UseTableBackground (Bicolour (Just (Colour8Bit 234)) (Just (Colour8Bit 235))) } getEnvironment :: IO (Report.EnvWithConfigFile Environment) getEnvironment = Env.parse (Env.header "Environment") prefixedEnvironmentParser prefixedEnvironmentParser :: Env.Parser Env.Error (Report.EnvWithConfigFile Environment) prefixedEnvironmentParser = Env.prefixed "SMOS_" environmentParser environmentParser :: Env.Parser Env.Error (Report.EnvWithConfigFile Environment) environmentParser = Report.envWithConfigFileParser $ Environment <$> Report.environmentParser <*> optional (Env.var ignoreArchiveReader "IGNORE_ARCHIVE" (Env.help "whether to ignore the archive")) where ignoreArchiveReader = \case "True" -> Right HideArchive "False" -> Right Don'tHideArchive _ -> Left $ Env.UnreadError "Must be 'True' or 'False' if set" getConfiguration :: Report.FlagsWithConfigFile Flags -> Report.EnvWithConfigFile Environment -> IO (Maybe Configuration) getConfiguration = Report.getConfiguration getArguments :: IO Arguments getArguments = do args <- System.getArgs let result = runArgumentsParser args handleParseResult result runArgumentsParser :: [String] -> ParserResult Arguments runArgumentsParser = execParserPure prefs_ argParser where prefs_ = defaultPrefs { prefShowHelpOnError = True, prefShowHelpOnEmpty = True } argParser :: ParserInfo Arguments argParser = info (helper <*> parseArgs) help_ where help_ = fullDesc <> progDescDoc (Just description) description :: Doc description = Doc.vsep $ map Doc.text $ [ "", "Smos Query Tool version: " <> showVersion version, "" ] ++ readDataVersionsHelpMessage parseArgs :: Parser Arguments parseArgs = Arguments <$> parseCommand <*> Report.parseFlagsWithConfigFile parseFlags parseCommand :: Parser Command parseCommand = hsubparser $ mconcat [ command "entry" parseCommandEntry, command "report" parseCommandReport, command "work" parseCommandWork, command "waiting" parseCommandWaiting, command "next" parseCommandNext, command "clock" parseCommandClock, command "agenda" parseCommandAgenda, command "projects" parseCommandProjects, command "stuck" parseCommandStuck, command "log" parseCommandLog, command "stats" parseCommandStats, command "tags" parseCommandTags ] parseCommandEntry :: ParserInfo Command parseCommandEntry = info parser modifier where modifier = fullDesc <> progDesc "Select entries based on a given filter" parser = CommandEntry <$> ( EntryFlags <$> Report.parseFilterArgsRel <*> Report.parseProjectionArgs <*> Report.parseSorterArgs <*> Report.parseHideArchiveFlag <*> parseOutputFormat ) parseCommandReport :: ParserInfo Command parseCommandReport = info parser modifier where modifier = fullDesc <> progDesc "Run preconfigured reports" parser = CommandReport <$> ( ReportFlags <$> optional ( strArgument ( mconcat [ metavar "REPORT", help "The preconfigured report to run" ] ) ) <*> parseOutputFormat ) parseCommandWork :: ParserInfo Command parseCommandWork = info parser modifier where modifier = fullDesc <> progDesc "Show the work overview" parser = CommandWork <$> ( WorkFlags <$> Report.parseContextNameArg <*> Report.parseTimeFilterArg <*> Report.parseFilterOptionsRel <*> Report.parseProjectionArgs <*> Report.parseSorterArgs <*> Report.parseHideArchiveFlag <*> parseWorkWaitingThresholdFlag <*> parseWorkStuckThresholdFlag ) parseWorkWaitingThresholdFlag :: Parser (Maybe Time) parseWorkWaitingThresholdFlag = optional $ option (eitherReader $ parseTime . T.pack) ( mconcat [ long "waiting-threshold", metavar "TIME", help "The threshold at which to color waiting entries red" ] ) parseWorkStuckThresholdFlag :: Parser (Maybe Time) parseWorkStuckThresholdFlag = optional $ option (eitherReader $ parseTime . T.pack) ( mconcat [ long "stuck-threshold", metavar "TIME", help "The threshold at which to color stuck projects red" ] ) parseCommandWaiting :: ParserInfo Command parseCommandWaiting = info parser modifier where modifier = fullDesc <> progDesc "Print the \"WAITING\" tasks" parser = CommandWaiting <$> ( WaitingFlags <$> Report.parseFilterArgsRel <*> Report.parseHideArchiveFlag <*> parseWaitingThresholdFlag ) parseWaitingThresholdFlag :: Parser (Maybe Time) parseWaitingThresholdFlag = optional $ option (eitherReader $ parseTime . T.pack) ( mconcat [ long "threshold", metavar "TIME", help "The threshold at which to color waiting entries red" ] ) parseCommandNext :: ParserInfo Command parseCommandNext = info parser modifier where modifier = fullDesc <> progDesc "Print the next actions" parser = CommandNext <$> ( NextFlags <$> Report.parseFilterArgsRel <*> Report.parseHideArchiveFlag ) parseCommandClock :: ParserInfo Command parseCommandClock = info parser modifier where modifier = fullDesc <> progDesc "Print the clock table" parser = CommandClock <$> ( ClockFlags <$> Report.parseFilterArgsRel <*> Report.parsePeriod <*> Report.parseTimeBlock <*> parseOutputFormat <*> parseClockFormatFlags <*> parseClockReportStyle <*> Report.parseHideArchiveFlag ) parseClockFormatFlags :: Parser (Maybe ClockFormatFlags) parseClockFormatFlags = optional ( flag' ClockFormatTemporalFlag (long "temporal-resolution") <*> parseTemporalClockResolution <|> flag' ClockFormatDecimalFlag (long "decimal-resolution") <*> parseDecimalClockResolution ) parseTemporalClockResolution :: Parser (Maybe TemporalClockResolution) parseTemporalClockResolution = optional ( flag' TemporalSecondsResolution (long "seconds-resolution") <|> flag' TemporalMinutesResolution (long "minutes-resolution") <|> flag' TemporalHoursResolution (long "hours-resolution") ) parseDecimalClockResolution :: Parser (Maybe DecimalClockResolution) parseDecimalClockResolution = optional ( flag' DecimalQuarterResolution (long "quarters-resolution") <|> (flag' DecimalResolution (long "resolution") <*> argument auto (help "significant digits")) <|> flag' DecimalHoursResolution (long "hours-resolution") ) parseClockReportStyle :: Parser (Maybe ClockReportStyle) parseClockReportStyle = optional (flag' ClockForest (long "forest") <|> flag' ClockFlat (long "flat")) parseCommandAgenda :: ParserInfo Command parseCommandAgenda = info parser modifier where modifier = fullDesc <> progDesc "Print the agenda" parser = CommandAgenda <$> ( AgendaFlags <$> Report.parseFilterArgsRel <*> Report.parseHistoricityFlag <*> Report.parseTimeBlock <*> Report.parseHideArchiveFlag <*> Report.parsePeriod ) parseCommandProjects :: ParserInfo Command parseCommandProjects = info parser modifier where modifier = fullDesc <> progDesc "Print the projects overview" parser = CommandProjects <$> ( ProjectsFlags <$> Report.parseProjectFilterArgs ) parseCommandStuck :: ParserInfo Command parseCommandStuck = info parser modifier where modifier = fullDesc <> progDesc "Print the stuck projects overview" parser = CommandStuck <$> ( StuckFlags <$> Report.parseProjectFilterArgs <*> parseStuckThresholdFlag ) parseStuckThresholdFlag :: Parser (Maybe Time) parseStuckThresholdFlag = optional $ option (eitherReader $ parseTime . T.pack) ( mconcat [ long "threshold", help "The threshold at which to color stuck projects red" ] ) parseCommandLog :: ParserInfo Command parseCommandLog = info parser modifier where modifier = fullDesc <> progDesc "Print a log of what has happened." parser = CommandLog <$> ( LogFlags <$> Report.parseFilterArgsRel <*> Report.parsePeriod <*> Report.parseTimeBlock <*> Report.parseHideArchiveFlag ) parseCommandStats :: ParserInfo Command parseCommandStats = info parser modifier where modifier = fullDesc <> progDesc "Print the stats actions and warn if a file does not have one." parser = CommandStats <$> ( StatsFlags <$> Report.parsePeriod ) parseCommandTags :: ParserInfo Command parseCommandTags = info parser modifier where modifier = fullDesc <> progDesc "Print all the tags that are in use" parser = CommandTags <$> ( TagsFlags <$> Report.parseFilterArgsRel ) parseFlags :: Parser Flags parseFlags = Flags <$> Report.parseFlags parseOutputFormat :: Parser (Maybe OutputFormat) parseOutputFormat = optional ( asum [ flag' OutputPretty $ mconcat [long "pretty", help "pretty text"], flag' OutputYaml $ mconcat [long "yaml", help "Yaml"], flag' OutputJSON $ mconcat [long "json", help "single-line JSON"], flag' OutputJSONPretty $ mconcat [long "pretty-json", help "pretty JSON"] ] )
3ab3590d524c22f7438271c5dea080ea7c85eca657a2a446549d56812cee0391
jrh13/hol-light
completeness.ml
(* ========================================================================= *) Proof of the modal completeness of the provability logic GL . (* *) ( c ) Copyright , , 2020 - 2022 . (* ========================================================================= *) (* ------------------------------------------------------------------------- *) (* Iterated conjunction of formulae. *) (* ------------------------------------------------------------------------- *) let CONJLIST = new_recursive_definition list_RECURSION `CONJLIST [] = True /\ (!p X. CONJLIST (CONS p X) = if X = [] then p else p && CONJLIST X)`;; let CONJLIST_IMP_MEM = prove (`!p X. MEM p X ==> |-- (CONJLIST X --> p)`, GEN_TAC THEN LIST_INDUCT_TAC THEN REWRITE_TAC[MEM; CONJLIST] THEN STRIP_TAC THENL [POP_ASSUM (SUBST_ALL_TAC o GSYM) THEN COND_CASES_TAC THEN REWRITE_TAC[GL_imp_refl_th; GL_and_left_th]; COND_CASES_TAC THENL [ASM_MESON_TAC[MEM]; ALL_TAC] THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `CONJLIST t` THEN CONJ_TAC THENL [MATCH_ACCEPT_TAC GL_and_right_th; ASM_SIMP_TAC[]]]);; let CONJLIST_MONO = prove (`!X Y. (!p. MEM p Y ==> MEM p X) ==> |-- (CONJLIST X --> CONJLIST Y)`, GEN_TAC THEN LIST_INDUCT_TAC THEN REWRITE_TAC[MEM; CONJLIST] THENL [MESON_TAC[GL_add_assum; GL_truth_th]; ALL_TAC] THEN COND_CASES_TAC THENL [POP_ASSUM SUBST_VAR_TAC THEN REWRITE_TAC[MEM] THEN MESON_TAC[CONJLIST_IMP_MEM]; ALL_TAC] THEN DISCH_TAC THEN MATCH_MP_TAC GL_and_intro THEN CONJ_TAC THENL [ASM_MESON_TAC[CONJLIST_IMP_MEM]; FIRST_X_ASSUM MATCH_MP_TAC THEN ASM_MESON_TAC[]]);; let CONJLIST_CONS = prove (`!p X. |-- (CONJLIST (CONS p X) <-> p && CONJLIST X)`, REPEAT GEN_TAC THEN REWRITE_TAC[CONJLIST] THEN COND_CASES_TAC THEN REWRITE_TAC[GL_iff_refl_th] THEN POP_ASSUM SUBST1_TAC THEN REWRITE_TAC[CONJLIST] THEN ONCE_REWRITE_TAC[GL_iff_sym] THEN MATCH_ACCEPT_TAC GL_and_rigth_true_th);; let CONJLIST_IMP_HEAD = prove (`!p X. |-- (CONJLIST (CONS p X) --> p)`, REPEAT GEN_TAC THEN REWRITE_TAC[CONJLIST] THEN COND_CASES_TAC THENL [ASM_REWRITE_TAC[GL_imp_refl_th]; REWRITE_TAC[GL_and_left_th]]);; let CONJLIST_IMP_TAIL = prove (`!p X. |-- (CONJLIST (CONS p X) --> CONJLIST X)`, REPEAT GEN_TAC THEN REWRITE_TAC[CONJLIST] THEN COND_CASES_TAC THENL [ASM_REWRITE_TAC[CONJLIST; GL_imp_clauses]; REWRITE_TAC[GL_and_right_th]]);; let HEAD_TAIL_IMP_CONJLIST = prove (`!p h t. |-- (p --> h) /\ |-- (p --> CONJLIST t) ==> |-- (p --> CONJLIST (CONS h t))`, INTRO_TAC "!p h t; ph pt" THEN REWRITE_TAC[CONJLIST] THEN COND_CASES_TAC THENL [ASM_REWRITE_TAC[]; ASM_SIMP_TAC[GL_and_intro]]);; let IMP_CONJLIST = prove (`!p X. |-- (p --> CONJLIST X) <=> (!q. MEM q X ==> |-- (p --> q))`, GEN_TAC THEN SUBGOAL_THEN `(!X q. |-- (p --> CONJLIST X) /\ MEM q X ==> |-- (p --> q)) /\ (!X. (!q. MEM q X ==> |-- (p --> q)) ==> |-- (p --> CONJLIST X))` (fun th -> MESON_TAC[th]) THEN CONJ_TAC THENL [REPEAT STRIP_TAC THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `CONJLIST X` THEN ASM_SIMP_TAC[CONJLIST_IMP_MEM]; ALL_TAC] THEN LIST_INDUCT_TAC THEN REWRITE_TAC[MEM] THENL [REWRITE_TAC[CONJLIST; GL_imp_clauses]; ALL_TAC] THEN DISCH_TAC THEN MATCH_MP_TAC HEAD_TAIL_IMP_CONJLIST THEN ASM_SIMP_TAC[]);; let CONJLIST_IMP_SUBLIST = prove (`!X Y. Y SUBLIST X ==> |-- (CONJLIST X --> CONJLIST Y)`, REWRITE_TAC[SUBLIST; IMP_CONJLIST] THEN MESON_TAC[CONJLIST_IMP_MEM]);; let CONJLIST_IMP = prove (`!l m. (!p. MEM p m ==> ?q. MEM q l /\ |-- (q --> p)) ==> |-- (CONJLIST l --> CONJLIST m)`, GEN_TAC THEN LIST_INDUCT_TAC THENL [REWRITE_TAC[CONJLIST; GL_imp_clauses]; ALL_TAC] THEN INTRO_TAC "hp" THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `h && CONJLIST t` THEN CONJ_TAC THENL [MATCH_MP_TAC GL_and_intro THEN CONJ_TAC THENL [HYP_TAC "hp: +" (SPEC `h:form`) THEN REWRITE_TAC[MEM] THEN MESON_TAC[CONJLIST_IMP_MEM; GL_imp_trans]; FIRST_X_ASSUM MATCH_MP_TAC THEN INTRO_TAC "!p; p" THEN FIRST_X_ASSUM (MP_TAC o SPEC `p:form`) THEN ASM_REWRITE_TAC[MEM]]; ALL_TAC] THEN MESON_TAC[CONJLIST_CONS; GL_iff_imp2]);; let CONJLIST_APPEND = prove (`!l m. |-- (CONJLIST (APPEND l m) <-> CONJLIST l && CONJLIST m)`, FIX_TAC "m" THEN LIST_INDUCT_TAC THEN REWRITE_TAC[APPEND] THENL [REWRITE_TAC[CONJLIST] THEN ONCE_REWRITE_TAC[GL_iff_sym] THEN MATCH_ACCEPT_TAC GL_and_left_true_th; ALL_TAC] THEN MATCH_MP_TAC GL_iff_trans THEN EXISTS_TAC `h && CONJLIST (APPEND t m)` THEN REWRITE_TAC[CONJLIST_CONS] THEN MATCH_MP_TAC GL_iff_trans THEN EXISTS_TAC `h && (CONJLIST t && CONJLIST m)` THEN CONJ_TAC THENL [MATCH_MP_TAC GL_and_subst_th THEN ASM_REWRITE_TAC[GL_iff_refl_th]; ALL_TAC] THEN MATCH_MP_TAC GL_iff_trans THEN EXISTS_TAC `(h && CONJLIST t) && CONJLIST m` THEN CONJ_TAC THENL [MESON_TAC[GL_and_assoc_th; GL_iff_sym]; ALL_TAC] THEN MATCH_MP_TAC GL_and_subst_th THEN REWRITE_TAC[GL_iff_refl_th] THEN ONCE_REWRITE_TAC[GL_iff_sym] THEN MATCH_ACCEPT_TAC CONJLIST_CONS);; let FALSE_NOT_CONJLIST = prove (`!X. MEM False X ==> |-- (Not (CONJLIST X))`, INTRO_TAC "!X; X" THEN REWRITE_TAC[GL_not_def] THEN MATCH_MP_TAC CONJLIST_IMP_MEM THEN POP_ASSUM MATCH_ACCEPT_TAC);; let CONJLIST_MAP_BOX = prove (`!l. |-- (CONJLIST (MAP (Box) l) <-> Box (CONJLIST l))`, LIST_INDUCT_TAC THENL [REWRITE_TAC[CONJLIST; MAP; GL_iff_refl_th] THEN MATCH_MP_TAC GL_imp_antisym THEN SIMP_TAC[GL_add_assum; GL_truth_th; GL_necessitation]; ALL_TAC] THEN REWRITE_TAC[MAP] THEN MATCH_MP_TAC GL_iff_trans THEN EXISTS_TAC `Box h && CONJLIST (MAP (Box) t)` THEN CONJ_TAC THENL [MATCH_ACCEPT_TAC CONJLIST_CONS; ALL_TAC] THEN MATCH_MP_TAC GL_iff_trans THEN EXISTS_TAC `Box h && Box (CONJLIST t)` THEN CONJ_TAC THENL [MATCH_MP_TAC GL_imp_antisym THEN CONJ_TAC THEN MATCH_MP_TAC GL_and_intro THEN ASM_MESON_TAC[GL_and_left_th; GL_and_right_th; GL_iff_imp1; GL_iff_imp2; GL_imp_trans]; ALL_TAC] THEN MATCH_MP_TAC GL_iff_trans THEN EXISTS_TAC `Box (h && CONJLIST t)` THEN CONJ_TAC THENL [MESON_TAC[GL_box_and_th; GL_box_and_inv_th; GL_imp_antisym]; ALL_TAC] THEN MATCH_MP_TAC GL_box_iff THEN MATCH_MP_TAC GL_necessitation THEN ONCE_REWRITE_TAC[GL_iff_sym] THEN MATCH_ACCEPT_TAC CONJLIST_CONS);; (* ------------------------------------------------------------------------- *) (* Consistent list of formulas. *) (* ------------------------------------------------------------------------- *) let CONSISTENT = new_definition `CONSISTENT (l:form list) <=> ~ (|-- (Not (CONJLIST l)))`;; let CONSISTENT_SING = prove (`!p. CONSISTENT [p] <=> ~ |-- (Not p)`, REWRITE_TAC[CONSISTENT; CONJLIST]);; let CONSISTENT_LEMMA = prove (`!X p. MEM p X /\ MEM (Not p) X ==> |-- (Not (CONJLIST X))`, REPEAT STRIP_TAC THEN REWRITE_TAC[GL_not_def] THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `p && Not p` THEN CONJ_TAC THENL [MATCH_MP_TAC GL_and_intro THEN ASM_MESON_TAC[CONJLIST_IMP_MEM; GL_imp_trans; GL_and_pair_th]; MESON_TAC[GL_nc_th]]);; let CONSISTENT_SUBLIST = prove (`!X Y. CONSISTENT X /\ Y SUBLIST X ==> CONSISTENT Y`, REPEAT GEN_TAC THEN REWRITE_TAC[CONSISTENT] THEN SUBGOAL_THEN `|-- (CONJLIST Y --> False) /\ Y SUBLIST X ==> |-- (CONJLIST X --> False)` (fun th -> ASM_MESON_TAC[th; GL_not_def]) THEN INTRO_TAC "inc sub" THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `CONJLIST Y` THEN ASM_REWRITE_TAC[] THEN ASM_SIMP_TAC[CONJLIST_IMP_SUBLIST]);; let CONSISTENT_CONS = prove (`!h t. CONSISTENT (CONS h t) <=> ~ |-- (Not h || Not (CONJLIST t))`, GEN_TAC THEN GEN_TAC THEN REWRITE_TAC[CONSISTENT] THEN AP_TERM_TAC THEN MATCH_MP_TAC GL_iff THEN MATCH_MP_TAC GL_iff_trans THEN EXISTS_TAC `Not (h && CONJLIST t)` THEN CONJ_TAC THENL [MATCH_MP_TAC GL_not_subst THEN MATCH_ACCEPT_TAC CONJLIST_CONS; MATCH_ACCEPT_TAC GL_de_morgan_and_th]);; let CONSISTENT_NC = prove (`!X p. MEM p X /\ MEM (Not p) X ==> ~CONSISTENT X`, INTRO_TAC "!X p; p np" THEN REWRITE_TAC[CONSISTENT; GL_not_def] THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `p && Not p` THEN REWRITE_TAC[GL_nc_th] THEN MATCH_MP_TAC GL_and_intro THEN ASM_SIMP_TAC[CONJLIST_IMP_MEM]);; let CONSISTENT_EM = prove (`!h t. CONSISTENT t ==> CONSISTENT (CONS h t) \/ CONSISTENT (CONS (Not h) t)`, REPEAT GEN_TAC THEN REWRITE_TAC[CONSISTENT_CONS] THEN REWRITE_TAC[CONSISTENT] THEN SUBGOAL_THEN `|-- ((Not h || Not CONJLIST t) --> (Not Not h || Not CONJLIST t) --> (Not CONJLIST t))` (fun th -> MESON_TAC[th; GL_modusponens]) THEN REWRITE_TAC[GL_disj_imp] THEN CONJ_TAC THENL [MATCH_MP_TAC GL_imp_swap THEN REWRITE_TAC[GL_disj_imp] THEN CONJ_TAC THENL [MATCH_MP_TAC GL_imp_swap THEN MATCH_MP_TAC GL_shunt THEN MATCH_MP_TAC GL_frege THEN EXISTS_TAC `False` THEN REWRITE_TAC[GL_nc_th] THEN MATCH_MP_TAC GL_add_assum THEN MATCH_ACCEPT_TAC GL_ex_falso_th; MATCH_ACCEPT_TAC GL_axiom_addimp]; MATCH_MP_TAC GL_imp_swap THEN REWRITE_TAC[GL_disj_imp] THEN CONJ_TAC THENL [MATCH_MP_TAC GL_add_assum THEN MATCH_ACCEPT_TAC GL_imp_refl_th; MATCH_ACCEPT_TAC GL_axiom_addimp]]);; let FALSE_IMP_NOT_CONSISTENT = prove (`!X. MEM False X ==> ~ CONSISTENT X`, SIMP_TAC[CONSISTENT; FALSE_NOT_CONJLIST]);; (* ------------------------------------------------------------------------- *) (* Maximal Consistent Sets. *) See p.79 ( pdf p.118 ) . D in the text is p here . (* ------------------------------------------------------------------------- *) let MAXIMAL_CONSISTENT = new_definition `MAXIMAL_CONSISTENT p X <=> CONSISTENT X /\ NOREPETITION X /\ (!q. q SUBFORMULA p ==> MEM q X \/ MEM (Not q) X)`;; let MAXIMAL_CONSISTENT_LEMMA = prove (`!p X A b. MAXIMAL_CONSISTENT p X /\ (!q. MEM q A ==> MEM q X) /\ b SUBFORMULA p /\ |-- (CONJLIST A --> b) ==> MEM b X`, INTRO_TAC "!p X A b; mconst subl b Ab" THEN REFUTE_THEN ASSUME_TAC THEN CLAIM_TAC "rmk" `MEM (Not b) X` THENL [ASM_MESON_TAC[MAXIMAL_CONSISTENT]; ALL_TAC] THEN CLAIM_TAC "rmk2" `|-- (CONJLIST X --> b && Not b)` THENL [MATCH_MP_TAC GL_and_intro THEN CONJ_TAC THENL [ASM_MESON_TAC[CONJLIST_MONO; GL_imp_trans]; ASM_MESON_TAC[CONJLIST_IMP_MEM]]; ALL_TAC] THEN CLAIM_TAC "rmk3" `|-- (CONJLIST X --> False)` THENL [ASM_MESON_TAC[GL_imp_trans; GL_nc_th]; ALL_TAC] THEN SUBGOAL_THEN `~ CONSISTENT X` (fun th -> ASM_MESON_TAC[th; MAXIMAL_CONSISTENT]) THEN ASM_REWRITE_TAC[CONSISTENT; GL_not_def]);; let MAXIMAL_CONSISTENT_MEM_NOT = prove (`!X p q. MAXIMAL_CONSISTENT p X /\ q SUBFORMULA p ==> (MEM (Not q) X <=> ~ MEM q X)`, REWRITE_TAC[MAXIMAL_CONSISTENT] THEN MESON_TAC[CONSISTENT_NC]);; let MAXIMAL_CONSISTENT_MEM_CASES = prove (`!X p q. MAXIMAL_CONSISTENT p X /\ q SUBFORMULA p ==> (MEM q X \/ MEM (Not q) X)`, REWRITE_TAC[MAXIMAL_CONSISTENT] THEN MESON_TAC[CONSISTENT_NC]);; let MAXIMAL_CONSISTENT_SUBFORMULA_MEM_EQ_DERIVABLE = prove (`!p w q. MAXIMAL_CONSISTENT p w /\ q SUBFORMULA p ==> (MEM q w <=> |-- (CONJLIST w --> q))`, REPEAT GEN_TAC THEN REWRITE_TAC[MAXIMAL_CONSISTENT; CONSISTENT] THEN INTRO_TAC "(w em) sub" THEN LABEL_ASM_CASES_TAC "q" `MEM (q:form) w` THEN ASM_SIMP_TAC[CONJLIST_IMP_MEM] THEN CLAIM_TAC "nq" `MEM (Not q) w` THENL [ASM_MESON_TAC[]; INTRO_TAC "deriv"] THEN SUBGOAL_THEN `|-- (Not (CONJLIST w))` (fun th -> ASM_MESON_TAC[th]) THEN REWRITE_TAC[GL_not_def] THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `q && Not q` THEN REWRITE_TAC[GL_nc_th] THEN ASM_SIMP_TAC[GL_and_intro; CONJLIST_IMP_MEM]);; let MAXIMAL_CONSISTENT_SUBFORMULA_MEM_NEG_EQ_DERIVABLE = prove (`!p w q. MAXIMAL_CONSISTENT p w /\ q SUBFORMULA p ==> (MEM (Not q) w <=> |-- (CONJLIST w --> Not q))`, REPEAT GEN_TAC THEN REWRITE_TAC[MAXIMAL_CONSISTENT; CONSISTENT] THEN INTRO_TAC "(w em) sub" THEN LABEL_ASM_CASES_TAC "q" `MEM (Not q) w` THEN ASM_SIMP_TAC[CONJLIST_IMP_MEM] THEN CLAIM_TAC "nq" `MEM (q:form) w` THENL [ASM_MESON_TAC[]; INTRO_TAC "deriv"] THEN SUBGOAL_THEN `|-- (Not (CONJLIST w))` (fun th -> ASM_MESON_TAC[th]) THEN REWRITE_TAC[GL_not_def] THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `q && Not q` THEN REWRITE_TAC[GL_nc_th] THEN ASM_SIMP_TAC[GL_and_intro; CONJLIST_IMP_MEM]);; (* ------------------------------------------------------------------------- *) (* Subsentences. *) (* ------------------------------------------------------------------------- *) parse_as_infix("SUBSENTENCE",get_infix_status "SUBFORMULA");; let SUBSENTENCE_RULES,SUBSENTENCE_INDUCT,SUBSENTENCE_CASES = new_inductive_definition `(!p q. p SUBFORMULA q ==> p SUBSENTENCE q) /\ (!p q. p SUBFORMULA q ==> Not p SUBSENTENCE q)`;; let GL_STANDARD_FRAME = new_definition `GL_STANDARD_FRAME p (W,R) <=> W = {w | MAXIMAL_CONSISTENT p w /\ (!q. MEM q w ==> q SUBSENTENCE p)} /\ ITF (W,R) /\ (!q w. Box q SUBFORMULA p /\ w IN W ==> (MEM (Box q) w <=> !x. R w x ==> MEM q x))`;; let SUBFORMULA_IMP_SUBSENTENCE = prove (`!p q. p SUBFORMULA q ==> p SUBSENTENCE q`, REWRITE_TAC[SUBSENTENCE_RULES]);; let SUBFORMULA_IMP_NEG_SUBSENTENCE = prove (`!p q. p SUBFORMULA q ==> Not p SUBSENTENCE q`, REWRITE_TAC[SUBSENTENCE_RULES]);; (* ------------------------------------------------------------------------- *) (* Standard model. *) (* ------------------------------------------------------------------------- *) let GL_STANDARD_MODEL = new_definition `GL_STANDARD_MODEL p (W,R) V <=> GL_STANDARD_FRAME p (W,R) /\ (!a w. w IN W ==> (V a w <=> MEM (Atom a) w /\ Atom a SUBFORMULA p))`;; (* ------------------------------------------------------------------------- *) (* Truth Lemma. *) (* ------------------------------------------------------------------------- *) let GL_truth_lemma = prove (`!W R p V q. ~ |-- p /\ GL_STANDARD_MODEL p (W,R) V /\ q SUBFORMULA p ==> !w. w IN W ==> (MEM q w <=> holds (W,R) V q w)`, REPEAT GEN_TAC THEN REWRITE_TAC[GL_STANDARD_MODEL; GL_STANDARD_FRAME; SUBSENTENCE_CASES] THEN INTRO_TAC "np ((W itf 1) val) q" THEN REMOVE_THEN "W" SUBST_VAR_TAC THEN REWRITE_TAC[FORALL_IN_GSPEC] THEN REMOVE_THEN "q" MP_TAC THEN HYP_TAC "1" (REWRITE_RULE[IN_ELIM_THM]) THEN HYP_TAC "val" (REWRITE_RULE[FORALL_IN_GSPEC]) THEN SPEC_TAC (`q:form`,`q:form`) THEN MATCH_MP_TAC form_INDUCT THEN REWRITE_TAC[holds] THEN CONJ_TAC THENL [INTRO_TAC "sub; !w; w" THEN HYP_TAC "w -> cons memq" (REWRITE_RULE[MAXIMAL_CONSISTENT]) THEN ASM_MESON_TAC[FALSE_IMP_NOT_CONSISTENT]; ALL_TAC] THEN CONJ_TAC THENL [REWRITE_TAC[MAXIMAL_CONSISTENT] THEN INTRO_TAC "p; !w; (cons (norep mem)) subf" THEN HYP_TAC "mem: t | nt" (C MATCH_MP (ASSUME `True SUBFORMULA p`)) THEN ASM_REWRITE_TAC[] THEN REFUTE_THEN (K ALL_TAC) THEN REMOVE_THEN "cons" MP_TAC THEN REWRITE_TAC[CONSISTENT] THEN REWRITE_TAC[GL_not_def] THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `Not True` THEN ASM_SIMP_TAC[CONJLIST_IMP_MEM] THEN MATCH_MP_TAC GL_iff_imp1 THEN MATCH_ACCEPT_TAC GL_not_true_th; ALL_TAC] THEN CONJ_TAC THENL [ASM_SIMP_TAC[]; ALL_TAC] THEN CONJ_TAC THENL [INTRO_TAC "![q/a]; q; sub; !w; w" THEN REMOVE_THEN "q" MP_TAC THEN MATCH_MP_TAC (MESON[] `P /\ (P /\ Q ==> R) ==> ((P ==> Q) ==> R)`) THEN CONJ_TAC THENL [ASM_MESON_TAC[SUBFORMULA_TRANS; SUBFORMULA_INVERSION; SUBFORMULA_REFL]; INTRO_TAC "sub1 q"] THEN EQ_TAC THENL [HYP MESON_TAC "w sub1 q" [MAXIMAL_CONSISTENT_MEM_NOT]; REMOVE_THEN "q" (MP_TAC o SPEC `w: form list`) THEN ANTS_TAC THEN ASM_REWRITE_TAC[] THEN ASM_MESON_TAC[MAXIMAL_CONSISTENT_MEM_NOT]]; ALL_TAC] THEN REPEAT CONJ_TAC THEN TRY (INTRO_TAC "![q1] [q2]; q1 q2; sub; !w; w" THEN REMOVE_THEN "q1" MP_TAC THEN MATCH_MP_TAC (MESON[] `P /\ (P /\ Q ==> R) ==> ((P ==> Q) ==> R)`) THEN CONJ_TAC THENL [ASM_MESON_TAC[SUBFORMULA_TRANS; SUBFORMULA_INVERSION; SUBFORMULA_REFL]; INTRO_TAC "sub1 +" THEN DISCH_THEN (MP_TAC o SPEC `w:form list`)] THEN REMOVE_THEN "q2" MP_TAC THEN MATCH_MP_TAC (MESON[] `P /\ (P /\ Q ==> R) ==> ((P ==> Q) ==> R)`) THEN CONJ_TAC THENL [ASM_MESON_TAC[SUBFORMULA_TRANS; SUBFORMULA_INVERSION; SUBFORMULA_REFL]; INTRO_TAC "sub2 +" THEN DISCH_THEN (MP_TAC o SPEC `w:form list`)] THEN HYP REWRITE_TAC "w" [] THEN DISCH_THEN (SUBST1_TAC o GSYM) THEN DISCH_THEN (SUBST1_TAC o GSYM) THEN CLAIM_TAC "rmk" `!q. q SUBFORMULA p ==> (MEM q w <=> |-- (CONJLIST w --> q))` THENL [ASM_MESON_TAC[MAXIMAL_CONSISTENT_SUBFORMULA_MEM_EQ_DERIVABLE]; ALL_TAC]) THENL [ (* Case && *) ASM_SIMP_TAC[] THEN ASM_MESON_TAC[MAXIMAL_CONSISTENT_SUBFORMULA_MEM_EQ_DERIVABLE; GL_and_intro; GL_and_left_th; GL_and_right_th; GL_imp_trans] ; (* Case || *) EQ_TAC THENL [INTRO_TAC "q1q2"; ASM_MESON_TAC[GL_or_left_th; GL_or_right_th; GL_imp_trans]] THEN CLAIM_TAC "wq1q2" `|-- (CONJLIST w --> q1 || q2)` THENL [ASM_SIMP_TAC[CONJLIST_IMP_MEM]; ALL_TAC] THEN CLAIM_TAC "hq1 | hq1" `MEM q1 w \/ MEM (Not q1) w` THENL [ASM_MESON_TAC[MAXIMAL_CONSISTENT_MEM_CASES]; ASM_REWRITE_TAC[]; ALL_TAC] THEN CLAIM_TAC "hq2 | hq2" `MEM q2 w \/ MEM (Not q2) w` THENL [ASM_MESON_TAC[MAXIMAL_CONSISTENT_MEM_CASES]; ASM_REWRITE_TAC[]; REFUTE_THEN (K ALL_TAC)] THEN SUBGOAL_THEN `~ (|-- (CONJLIST w --> False))` MP_TAC THENL [REWRITE_TAC[GSYM GL_not_def] THEN ASM_MESON_TAC[MAXIMAL_CONSISTENT; CONSISTENT]; REWRITE_TAC[]] THEN MATCH_MP_TAC GL_frege THEN EXISTS_TAC `q1 || q2` THEN ASM_SIMP_TAC[CONJLIST_IMP_MEM] THEN MATCH_MP_TAC GL_imp_swap THEN REWRITE_TAC[GL_disj_imp] THEN CONJ_TAC THEN MATCH_MP_TAC GL_imp_swap THEN ASM_MESON_TAC[CONJLIST_IMP_MEM; GL_axiom_not; GL_iff_imp1; GL_imp_trans] ; (* Case --> *) ASM_SIMP_TAC[] THEN EQ_TAC THENL [ASM_MESON_TAC[GL_frege; CONJLIST_IMP_MEM]; INTRO_TAC "imp"] THEN CLAIM_TAC "hq1 | hq1" `MEM q1 w \/ MEM (Not q1) w` THENL [ASM_MESON_TAC[MAXIMAL_CONSISTENT_MEM_CASES]; ASM_MESON_TAC[CONJLIST_IMP_MEM; GL_imp_swap; GL_add_assum]; ALL_TAC] THEN MATCH_MP_TAC GL_shunt THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `q1 && Not q1` THEN CONJ_TAC THENL [ALL_TAC; MESON_TAC[GL_nc_th; GL_imp_trans; GL_ex_falso_th]] THEN MATCH_MP_TAC GL_and_intro THEN REWRITE_TAC[GL_and_right_th] THEN ASM_MESON_TAC[CONJLIST_IMP_MEM; GL_imp_trans; GL_and_left_th] ; (* Case <-> *) ASM_SIMP_TAC[] THEN REMOVE_THEN "sub" (K ALL_TAC) THEN EQ_TAC THENL [MESON_TAC[GL_frege; GL_add_assum; GL_modusponens_th; GL_axiom_iffimp1; GL_axiom_iffimp2]; ALL_TAC] THEN INTRO_TAC "iff" THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `(q1 --> q2) && (q2 --> q1)` THEN CONJ_TAC THENL [MATCH_MP_TAC GL_and_intro; MESON_TAC[GL_iff_def_th; GL_iff_imp2]] THEN CLAIM_TAC "rmk'" `!q. q SUBFORMULA p ==> (MEM (Not q) w <=> |-- (CONJLIST w --> Not q))` THENL [ASM_MESON_TAC[MAXIMAL_CONSISTENT_SUBFORMULA_MEM_NEG_EQ_DERIVABLE]; ALL_TAC] THEN CLAIM_TAC "hq1 | hq1" `|-- (CONJLIST w --> q1) \/ |-- (CONJLIST w --> Not q1)` THENL [ASM_MESON_TAC[MAXIMAL_CONSISTENT_MEM_CASES]; ASM_MESON_TAC[GL_imp_swap; GL_add_assum]; ALL_TAC] THEN CLAIM_TAC "hq2 | hq2" `|-- (CONJLIST w --> q2) \/ |-- (CONJLIST w --> Not q2)` THENL [ASM_MESON_TAC[MAXIMAL_CONSISTENT_MEM_CASES]; ASM_MESON_TAC[GL_imp_swap; GL_add_assum]; ALL_TAC] THEN ASM_MESON_TAC[GL_nc_th; GL_imp_trans; GL_and_intro; GL_ex_falso_th; GL_imp_swap; GL_shunt] ; (* Case Box *) INTRO_TAC "!a; a; sub; !w; w" THEN REWRITE_TAC[holds; IN_ELIM_THM] THEN CLAIM_TAC "suba" `a SUBFORMULA p` THENL [MATCH_MP_TAC SUBFORMULA_TRANS THEN EXISTS_TAC `Box a` THEN ASM_REWRITE_TAC[SUBFORMULA_INVERSION; SUBFORMULA_REFL]; ALL_TAC] THEN HYP_TAC "itf" (REWRITE_RULE[ITF; IN_ELIM_THM]) THEN EQ_TAC THENL [INTRO_TAC "boxa; !w'; (maxw' subw') r" THEN HYP_TAC "a" (C MATCH_MP (ASSUME `a SUBFORMULA p`)) THEN HYP_TAC "a: +" (SPEC `w':form list`) THEN ANTS_TAC THENL [ASM_REWRITE_TAC[]; ALL_TAC] THEN DISCH_THEN (SUBST1_TAC o GSYM) THEN REMOVE_THEN "1" (MP_TAC o SPECL [`a: form`;`w: form list`]) THEN ANTS_TAC THENL [ASM_REWRITE_TAC[]; ALL_TAC] THEN ASM_REWRITE_TAC[] THEN DISCH_THEN MATCH_MP_TAC THEN ASM_REWRITE_TAC[] THEN ASM_MESON_TAC[]; ALL_TAC] THEN INTRO_TAC "3" THEN REMOVE_THEN "1" (MP_TAC o SPECL [`a:form`; `w:form list`]) THEN ANTS_TAC THENL [ASM_REWRITE_TAC[]; ALL_TAC] THEN DISCH_THEN SUBST1_TAC THEN INTRO_TAC "![w']; w'" THEN REMOVE_THEN "3" (MP_TAC o SPEC `w':form list`) THEN ANTS_TAC THENL [ASM_MESON_TAC[]; ALL_TAC] THEN HYP_TAC "a" (C MATCH_MP (ASSUME `a SUBFORMULA p`)) THEN HYP_TAC "a: +" (SPEC `w':form list`) THEN ANTS_TAC THENL [ASM_MESON_TAC[]; ALL_TAC] THEN DISCH_THEN (SUBST1_TAC o GSYM) THEN REWRITE_TAC[] ]);; (* ------------------------------------------------------------------------- *) (* Extension Lemma. *) (* Every consistent list of formulae can be extended to a maximal consistent *) list by a construction similar to Lindenbaum 's extension . (* ------------------------------------------------------------------------- *) let EXTEND_MAXIMAL_CONSISTENT = prove (`!p X. CONSISTENT X /\ (!q. MEM q X ==> q SUBSENTENCE p) ==> ?M. MAXIMAL_CONSISTENT p M /\ (!q. MEM q M ==> q SUBSENTENCE p) /\ X SUBLIST M`, GEN_TAC THEN SUBGOAL_THEN `!L X. CONSISTENT X /\ NOREPETITION X /\ (!q. MEM q X ==> q SUBSENTENCE p) /\ (!q. MEM q L ==> q SUBFORMULA p) /\ (!q. q SUBFORMULA p ==> MEM q L \/ MEM q X \/ MEM (Not q) X) ==> ?M. MAXIMAL_CONSISTENT p M /\ (!q. MEM q M ==> q SUBSENTENCE p) /\ X SUBLIST M` (LABEL_TAC "P") THENL [ALL_TAC; INTRO_TAC "![X']; cons' subf'" THEN DESTRUCT_TAC "@X. uniq sub1 sub2" (ISPEC `X':form list` EXISTS_NOREPETITION) THEN DESTRUCT_TAC "@L'. uniq L'" (SPEC `p:form` SUBFORMULA_LIST) THEN HYP_TAC "P: +" (SPECL[`L':form list`; `X:form list`]) THEN ANTS_TAC THENL [CONJ_TAC THENL [ASM_MESON_TAC[CONSISTENT_SUBLIST]; ALL_TAC] THEN CONJ_TAC THENL [ASM_REWRITE_TAC[]; ALL_TAC] THEN CONJ_TAC THENL [ASM_REWRITE_TAC[]; ALL_TAC] THEN ASM_MESON_TAC[SUBLIST]; ALL_TAC] THEN INTRO_TAC "@M. max sub" THEN EXISTS_TAC `M:form list` THEN ASM_REWRITE_TAC[] THEN ASM_MESON_TAC[SUBLIST_TRANS]] THEN LIST_INDUCT_TAC THENL [REWRITE_TAC[MEM] THEN INTRO_TAC "!X; X uniq max subf" THEN EXISTS_TAC `X:form list` THEN ASM_REWRITE_TAC[SUBLIST_REFL; MAXIMAL_CONSISTENT]; ALL_TAC] THEN POP_ASSUM (LABEL_TAC "hpind") THEN REWRITE_TAC[MEM] THEN INTRO_TAC "!X; cons uniq qmem qmem' subf" THEN LABEL_ASM_CASES_TAC "hmemX" `MEM (h:form) X` THENL [REMOVE_THEN "hpind" (MP_TAC o SPEC `X:form list`) THEN ASM_MESON_TAC[]; ALL_TAC] THEN LABEL_ASM_CASES_TAC "nhmemX" `MEM (Not h) X` THENL [REMOVE_THEN "hpind" (MP_TAC o SPEC `X:form list`) THEN ASM_MESON_TAC[]; ALL_TAC] THEN LABEL_ASM_CASES_TAC "consh" `CONSISTENT (CONS (h:form) X)` THENL [REMOVE_THEN "hpind" (MP_TAC o SPEC `CONS (h:form) X`) THEN ANTS_TAC THENL [ASM_REWRITE_TAC[NOREPETITION_CLAUSES; MEM] THEN CONJ_TAC THENL [ALL_TAC; ASM_MESON_TAC[]] THEN ASM_MESON_TAC[SUBLIST; SUBFORMULA_IMP_SUBSENTENCE]; ALL_TAC] THEN INTRO_TAC "@M. max sub" THEN EXISTS_TAC `M:form list` THEN ASM_REWRITE_TAC[] THEN REMOVE_THEN "sub" MP_TAC THEN REWRITE_TAC[SUBLIST; MEM] THEN MESON_TAC[]; ALL_TAC] THEN REMOVE_THEN "hpind" (MP_TAC o SPEC `CONS (Not h) X`) THEN ANTS_TAC THENL [ASM_REWRITE_TAC[NOREPETITION_CLAUSES] THEN CONJ_TAC THENL [ASM_MESON_TAC[CONSISTENT_EM]; ALL_TAC] THEN REWRITE_TAC[MEM] THEN ASM_MESON_TAC[SUBLIST; SUBSENTENCE_RULES]; ALL_TAC] THEN INTRO_TAC "@M. max sub" THEN EXISTS_TAC `M:form list` THEN ASM_REWRITE_TAC[] THEN REMOVE_THEN "sub" MP_TAC THEN REWRITE_TAC[SUBLIST; MEM] THEN MESON_TAC[]);; let NONEMPTY_MAXIMAL_CONSISTENT = prove (`!p. ~ |-- p ==> ?M. MAXIMAL_CONSISTENT p M /\ MEM (Not p) M /\ (!q. MEM q M ==> q SUBSENTENCE p)`, INTRO_TAC "!p; p" THEN MP_TAC (SPECL [`p:form`; `[Not p]`] EXTEND_MAXIMAL_CONSISTENT) THEN ANTS_TAC THENL [CONJ_TAC THENL [REWRITE_TAC[CONSISTENT_SING] THEN ASM_MESON_TAC[GL_DOUBLENEG_CL]; ALL_TAC] THEN GEN_TAC THEN REWRITE_TAC[MEM] THEN REPEAT STRIP_TAC THEN FIRST_X_ASSUM SUBST_VAR_TAC THEN MESON_TAC[SUBFORMULA_IMP_NEG_SUBSENTENCE; SUBFORMULA_REFL]; ALL_TAC] THEN STRIP_TAC THEN EXISTS_TAC `M:form list` THEN ASM_REWRITE_TAC[] THEN ASM_MESON_TAC[SUBLIST; MEM]);; (* ------------------------------------------------------------------------- *) (* Accessibility lemma. *) (* ------------------------------------------------------------------------- *) let GL_STANDARD_REL = new_definition `GL_STANDARD_REL p w x <=> MAXIMAL_CONSISTENT p w /\ (!q. MEM q w ==> q SUBSENTENCE p) /\ MAXIMAL_CONSISTENT p x /\ (!q. MEM q x ==> q SUBSENTENCE p) /\ (!B. MEM (Box B) w ==> MEM (Box B) x /\ MEM B x) /\ (?E. MEM (Box E) x /\ MEM (Not (Box E)) w)`;; let ITF_MAXIMAL_CONSISTENT = prove (`!p. ~ |-- p ==> ITF ({M | MAXIMAL_CONSISTENT p M /\ (!q. MEM q M ==> q SUBSENTENCE p)}, GL_STANDARD_REL p)`, INTRO_TAC "!p; p" THEN REWRITE_TAC[ITF] THEN Nonempty CONJ_TAC THENL [REWRITE_TAC[GSYM MEMBER_NOT_EMPTY; IN_ELIM_THM] THEN ASM_MESON_TAC[NONEMPTY_MAXIMAL_CONSISTENT]; ALL_TAC] THEN (* Well-defined *) CONJ_TAC THENL [REWRITE_TAC[GL_STANDARD_REL; IN_ELIM_THM] THEN MESON_TAC[]; ALL_TAC] THEN (* Finite *) CONJ_TAC THENL [MATCH_MP_TAC FINITE_SUBSET THEN EXISTS_TAC `{l | NOREPETITION l /\ !q. MEM q l ==> q IN {q | q SUBSENTENCE p}}` THEN CONJ_TAC THENL [MATCH_MP_TAC FINITE_NOREPETITION THEN POP_ASSUM_LIST (K ALL_TAC) THEN SUBGOAL_THEN `{q | q SUBSENTENCE p} = {q | q SUBFORMULA p} UNION IMAGE (Not) {q | q SUBFORMULA p}` SUBST1_TAC THENL [REWRITE_TAC[GSYM SUBSET_ANTISYM_EQ; SUBSET; FORALL_IN_UNION; FORALL_IN_GSPEC; FORALL_IN_IMAGE] THEN REWRITE_TAC[IN_UNION; IN_ELIM_THM; SUBSENTENCE_RULES] THEN GEN_TAC THEN GEN_REWRITE_TAC LAND_CONV [SUBSENTENCE_CASES] THEN DISCH_THEN STRUCT_CASES_TAC THEN ASM_REWRITE_TAC[] THEN DISJ2_TAC THEN MATCH_MP_TAC FUN_IN_IMAGE THEN ASM SET_TAC []; ALL_TAC] THEN REWRITE_TAC[FINITE_UNION; FINITE_SUBFORMULA] THEN MATCH_MP_TAC FINITE_IMAGE THEN REWRITE_TAC[FINITE_SUBFORMULA]; ALL_TAC] THEN REWRITE_TAC[SUBSET; IN_ELIM_THM; MAXIMAL_CONSISTENT] THEN GEN_TAC THEN STRIP_TAC THEN ASM_REWRITE_TAC[]; ALL_TAC] THEN Irreflexive CONJ_TAC THENL [REWRITE_TAC[FORALL_IN_GSPEC; GL_STANDARD_REL] THEN INTRO_TAC "!M; M sub" THEN ASM_REWRITE_TAC[] THEN INTRO_TAC "_ (@E. E1 E2)" THEN SUBGOAL_THEN `~ CONSISTENT M` (fun th -> ASM_MESON_TAC[th; MAXIMAL_CONSISTENT]) THEN MATCH_MP_TAC CONSISTENT_NC THEN ASM_MESON_TAC[]; ALL_TAC] THEN (* Transitive *) REWRITE_TAC[IN_ELIM_THM; GL_STANDARD_REL] THEN INTRO_TAC "!x y z; (x1 x2) (y1 y2) (z1 z2) +" THEN ASM_REWRITE_TAC[] THEN ASM_MESON_TAC[]);; let ACCESSIBILITY_LEMMA = let MEM_FLATMAP_LEMMA = prove (`!p l. MEM p (FLATMAP (\x. match x with Box c -> [Box c] | _ -> []) l) <=> (?q. p = Box q /\ MEM p l)`, GEN_TAC THEN LIST_INDUCT_TAC THEN REWRITE_TAC[MEM; FLATMAP] THEN REWRITE_TAC[MEM_APPEND] THEN ASM_CASES_TAC `?c. h = Box c` THENL [POP_ASSUM (CHOOSE_THEN SUBST_VAR_TAC) THEN ASM_REWRITE_TAC[MEM] THEN MESON_TAC[]; ALL_TAC] THEN SUBGOAL_THEN `~ MEM p (match h with Box c -> [Box c] | _ -> [])` (fun th -> ASM_REWRITE_TAC[th]) THENL [POP_ASSUM MP_TAC THEN STRUCT_CASES_TAC (SPEC `h:form` (cases "form")) THEN REWRITE_TAC[MEM; distinctness "form"; injectivity "form"] THEN MESON_TAC[]; ALL_TAC] THEN POP_ASSUM (fun th -> MESON_TAC[th])) and CONJLIST_FLATMAP_DOT_BOX_LEMMA = prove (`!w. |-- (CONJLIST (FLATMAP (\x. match x with Box c -> [Box c] | _ -> []) w) --> CONJLIST (MAP (Box) (FLATMAP (\x. match x with Box c -> [c; Box c] | _ -> []) w)))`, LIST_INDUCT_TAC THENL [REWRITE_TAC[FLATMAP; MAP; GL_imp_refl_th]; ALL_TAC] THEN REWRITE_TAC[FLATMAP; MAP_APPEND] THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `CONJLIST (match h with Box c -> [Box c] | _ -> []) && CONJLIST (FLATMAP (\x. match x with Box c -> [Box c] | _ -> []) t)` THEN CONJ_TAC THENL [MATCH_MP_TAC GL_iff_imp1 THEN MATCH_ACCEPT_TAC CONJLIST_APPEND; ALL_TAC] THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `CONJLIST (MAP (Box) (match h with Box c -> [c; Box c] | _ -> [])) && CONJLIST (MAP (Box) (FLATMAP (\x. match x with Box c -> [c; Box c] | _ -> []) t))` THEN CONJ_TAC THENL [ALL_TAC; MATCH_MP_TAC GL_iff_imp2 THEN MATCH_ACCEPT_TAC CONJLIST_APPEND] THEN MATCH_MP_TAC GL_and_intro THEN CONJ_TAC THENL [ALL_TAC; ASM_MESON_TAC[GL_imp_trans; GL_and_right_th]] THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `CONJLIST (match h with Box c -> [Box c] | _ -> [])` THEN CONJ_TAC THENL [MATCH_ACCEPT_TAC GL_and_left_th; ALL_TAC] THEN POP_ASSUM (K ALL_TAC) THEN STRUCT_CASES_TAC (SPEC `h:form` (cases "form")) THEN REWRITE_TAC[distinctness "form"; MAP; GL_imp_refl_th] THEN REWRITE_TAC[CONJLIST; NOT_CONS_NIL] THEN MATCH_ACCEPT_TAC GL_dot_box) in prove (`!p M w q. ~ |-- p /\ MAXIMAL_CONSISTENT p M /\ (!q. MEM q M ==> q SUBSENTENCE p) /\ MAXIMAL_CONSISTENT p w /\ (!q. MEM q w ==> q SUBSENTENCE p) /\ MEM (Not p) M /\ Box q SUBFORMULA p /\ (!x. GL_STANDARD_REL p w x ==> MEM q x) ==> MEM (Box q) w`, REPEAT GEN_TAC THEN INTRO_TAC "p maxM subM maxw subw notp boxq rrr" THEN REFUTE_THEN (LABEL_TAC "contra") THEN REMOVE_THEN "rrr" MP_TAC THEN REWRITE_TAC[NOT_FORALL_THM] THEN CLAIM_TAC "consistent_X" `CONSISTENT (CONS (Not q) (CONS (Box q) (FLATMAP (\x. match x with Box c -> [c; Box c] | _ -> []) w)))` THENL [REMOVE_THEN "contra" MP_TAC THEN REWRITE_TAC[CONSISTENT; CONTRAPOS_THM] THEN INTRO_TAC "incons" THEN MATCH_MP_TAC MAXIMAL_CONSISTENT_LEMMA THEN MAP_EVERY EXISTS_TAC [`p:form`; `FLATMAP (\x. match x with Box c -> [Box c] | _ -> []) w`] THEN ASM_REWRITE_TAC[] THEN CONJ_TAC THENL [GEN_TAC THEN REWRITE_TAC[MEM_FLATMAP_LEMMA] THEN MESON_TAC[]; ALL_TAC] THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `Box(Box q --> q)` THEN REWRITE_TAC[GL_axiom_lob] THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `CONJLIST (MAP (Box) (FLATMAP (\x. match x with Box c -> [c; Box c] | _ -> []) w))` THEN CONJ_TAC THENL [REWRITE_TAC[CONJLIST_FLATMAP_DOT_BOX_LEMMA]; ALL_TAC] THEN CLAIM_TAC "XIMP" `!x y l. |-- (Not (Not y && CONJLIST (CONS x l))) ==> |-- ((CONJLIST (MAP (Box) l)) --> Box(x --> y))` THENL [REPEAT STRIP_TAC THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `Box (CONJLIST l)` THEN CONJ_TAC THENL [MESON_TAC[CONJLIST_MAP_BOX;GL_iff_imp1]; ALL_TAC] THEN MATCH_MP_TAC GL_imp_box THEN MATCH_MP_TAC GL_shunt THEN ONCE_REWRITE_TAC[GSYM GL_contrapos_eq] THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `CONJLIST (CONS x l) --> False` THEN CONJ_TAC THENL [ASM_MESON_TAC[GL_shunt; GL_not_def]; MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `Not (CONJLIST(CONS x l))` THEN CONJ_TAC THENL [MESON_TAC[GL_axiom_not;GL_iff_imp2]; MESON_TAC[GL_contrapos_eq;CONJLIST_CONS; GL_and_comm_th; GL_iff_imp2; GL_iff_imp1; GL_imp_trans]]]; ALL_TAC] THEN POP_ASSUM MATCH_MP_TAC THEN HYP_TAC "incons" (REWRITE_RULE[CONSISTENT]) THEN HYP_TAC "incons" (ONCE_REWRITE_RULE[CONJLIST]) THEN HYP_TAC "incons" (REWRITE_RULE[NOT_CONS_NIL]) THEN POP_ASSUM MATCH_ACCEPT_TAC; ALL_TAC] THEN MP_TAC (SPECL [`p:form`; `CONS (Not q) (CONS (Box q) (FLATMAP (\x. match x with Box c -> [c; Box c] | _ -> []) w))`] EXTEND_MAXIMAL_CONSISTENT) THEN ANTS_TAC THENL [ASM_REWRITE_TAC[MEM] THEN GEN_TAC THEN STRIP_TAC THEN REPEAT (FIRST_X_ASSUM SUBST_VAR_TAC) THENL [MATCH_MP_TAC SUBFORMULA_IMP_NEG_SUBSENTENCE THEN REWRITE_TAC[UNWIND_THM1] THEN HYP MESON_TAC "boxq" [SUBFORMULA_TRANS; SUBFORMULA_INVERSION; SUBFORMULA_REFL]; MATCH_MP_TAC SUBFORMULA_IMP_SUBSENTENCE THEN ASM_REWRITE_TAC[]; ALL_TAC] THEN POP_ASSUM (DESTRUCT_TAC "@y. +" o REWRITE_RULE[MEM_FLATMAP]) THEN STRUCT_CASES_TAC (SPEC `y:form` (cases "form")) THEN REWRITE_TAC[MEM] THEN STRIP_TAC THEN FIRST_X_ASSUM SUBST_VAR_TAC THENL [MATCH_MP_TAC SUBFORMULA_IMP_SUBSENTENCE THEN CLAIM_TAC "rmk" `Box a SUBSENTENCE p` THENL [POP_ASSUM MP_TAC THEN HYP MESON_TAC "subw" []; ALL_TAC] THEN HYP_TAC "rmk" (REWRITE_RULE[SUBSENTENCE_CASES; distinctness "form"]) THEN TRANS_TAC SUBFORMULA_TRANS `Box a` THEN ASM_REWRITE_TAC[] THEN MESON_TAC[SUBFORMULA_INVERSION; SUBFORMULA_REFL]; POP_ASSUM MP_TAC THEN HYP MESON_TAC "subw" []]; ALL_TAC] THEN INTRO_TAC "@X. maxX subX subl" THEN EXISTS_TAC `X:form list` THEN ASM_REWRITE_TAC[GL_STANDARD_REL; NOT_IMP] THEN CONJ_TAC THENL [CONJ_TAC THENL [INTRO_TAC "!B; B" THEN HYP_TAC "subl" (REWRITE_RULE[SUBLIST]) THEN CONJ_TAC THEN REMOVE_THEN "subl" MATCH_MP_TAC THEN REWRITE_TAC[MEM; distinctness "form"; injectivity "form"] THENL [DISJ2_TAC THEN REWRITE_TAC[MEM_FLATMAP] THEN EXISTS_TAC `Box B` THEN ASM_REWRITE_TAC[MEM]; DISJ2_TAC THEN DISJ2_TAC THEN REWRITE_TAC[MEM_FLATMAP] THEN EXISTS_TAC `Box B` THEN ASM_REWRITE_TAC[MEM]]; ALL_TAC] THEN EXISTS_TAC `q:form` THEN HYP_TAC "subl" (REWRITE_RULE[SUBLIST]) THEN CONJ_TAC THENL [REMOVE_THEN "subl" MATCH_MP_TAC THEN REWRITE_TAC[MEM]; ALL_TAC] THEN ASM_MESON_TAC[MAXIMAL_CONSISTENT_MEM_NOT]; ALL_TAC] THEN HYP_TAC "subl: +" (SPEC `Not q` o REWRITE_RULE[SUBLIST]) THEN REWRITE_TAC[MEM] THEN IMP_REWRITE_TAC[GSYM MAXIMAL_CONSISTENT_MEM_NOT] THEN SIMP_TAC[] THEN INTRO_TAC "_" THEN MATCH_MP_TAC SUBFORMULA_TRANS THEN EXISTS_TAC `Box q` THEN ASM_REWRITE_TAC[] THEN ASM_MESON_TAC[SUBFORMULA_TRANS; SUBFORMULA_INVERSION; SUBFORMULA_REFL]);; (* ------------------------------------------------------------------------- *) Modal completeness theorem for GL . (* ------------------------------------------------------------------------- *) let GL_COUNTERMODEL = prove (`!M p. ~(|-- p) /\ MAXIMAL_CONSISTENT p M /\ MEM (Not p) M /\ (!q. MEM q M ==> q SUBSENTENCE p) ==> ~holds ({M | MAXIMAL_CONSISTENT p M /\ (!q. MEM q M ==> q SUBSENTENCE p)}, GL_STANDARD_REL p) (\a w. Atom a SUBFORMULA p /\ MEM (Atom a) w) p M`, REPEAT GEN_TAC THEN STRIP_TAC THEN MP_TAC (ISPECL [`{M | MAXIMAL_CONSISTENT p M /\ (!q. MEM q M ==> q SUBSENTENCE p)}`; `GL_STANDARD_REL p`; `p:form`; `\a w. Atom a SUBFORMULA p /\ MEM (Atom a) w`; `p:form`] GL_truth_lemma) THEN ANTS_TAC THENL [ASM_REWRITE_TAC[SUBFORMULA_REFL; GL_STANDARD_MODEL; GL_STANDARD_FRAME] THEN ASM_SIMP_TAC[ITF_MAXIMAL_CONSISTENT] THEN REWRITE_TAC[IN_ELIM_THM] THEN CONJ_TAC THENL [ALL_TAC; MESON_TAC[]] THEN INTRO_TAC "!q w; boxq w subf" THEN EQ_TAC THENL [ASM_REWRITE_TAC[GL_STANDARD_REL] THEN SIMP_TAC[]; ALL_TAC] THEN INTRO_TAC "hp" THEN MATCH_MP_TAC ACCESSIBILITY_LEMMA THEN MAP_EVERY EXISTS_TAC [`p:form`; `M:form list`] THEN ASM_REWRITE_TAC[]; ALL_TAC] THEN DISCH_THEN (MP_TAC o SPEC `M:form list`) THEN ANTS_TAC THENL [ASM_REWRITE_TAC[IN_ELIM_THM]; ALL_TAC] THEN DISCH_THEN (SUBST1_TAC o GSYM) THEN ASM_MESON_TAC[MAXIMAL_CONSISTENT; CONSISTENT_NC]);; let GL_COUNTERMODEL_ALT = prove (`!p. ~(|-- p) ==> ~holds_in ({M | MAXIMAL_CONSISTENT p M /\ (!q. MEM q M ==> q SUBSENTENCE p)}, GL_STANDARD_REL p) p`, INTRO_TAC "!p; p" THEN REWRITE_TAC[holds_in; NOT_FORALL_THM; NOT_IMP; IN_ELIM_THM] THEN EXISTS_TAC `\a w. Atom a SUBFORMULA p /\ MEM (Atom a) w` THEN DESTRUCT_TAC "@M. max mem subf" (MATCH_MP NONEMPTY_MAXIMAL_CONSISTENT (ASSUME `~ |-- p`)) THEN EXISTS_TAC `M:form list` THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC GL_COUNTERMODEL THEN ASM_REWRITE_TAC[]);; let COMPLETENESS_THEOREM = prove (`!p. ITF:(form list->bool)#(form list->form list->bool)->bool |= p ==> |-- p`, GEN_TAC THEN GEN_REWRITE_TAC I [GSYM CONTRAPOS_THM] THEN INTRO_TAC "p" THEN REWRITE_TAC[valid; NOT_FORALL_THM] THEN EXISTS_TAC `({M | MAXIMAL_CONSISTENT p M /\ (!q. MEM q M ==> q SUBSENTENCE p)}, GL_STANDARD_REL p)` THEN REWRITE_TAC[NOT_IMP] THEN CONJ_TAC THENL [MATCH_MP_TAC ITF_MAXIMAL_CONSISTENT THEN ASM_REWRITE_TAC[]; ALL_TAC] THEN MATCH_MP_TAC GL_COUNTERMODEL_ALT THEN ASM_REWRITE_TAC[]);; (* ------------------------------------------------------------------------- *) Modal completeness for GL for models on a generic ( infinite ) domain . (* ------------------------------------------------------------------------- *) let COMPLETENESS_THEOREM_GEN = prove (`!p. INFINITE (:A) /\ ITF:(A->bool)#(A->A->bool)->bool |= p ==> |-- p`, SUBGOAL_THEN `INFINITE (:A) ==> !p. ITF:(A->bool)#(A->A->bool)->bool |= p ==> ITF:(form list->bool)#(form list->form list->bool)->bool |= p` (fun th -> MESON_TAC[th; COMPLETENESS_THEOREM]) THEN INTRO_TAC "A" THEN MATCH_MP_TAC BISIMILAR_VALID THEN REPEAT GEN_TAC THEN INTRO_TAC "itf1 w1" THEN CLAIM_TAC "@f. inj" `?f:form list->A. (!x y. f x = f y ==> x = y)` THENL [SUBGOAL_THEN `(:form list) <=_c (:A)` MP_TAC THENL [TRANS_TAC CARD_LE_TRANS `(:num)` THEN ASM_REWRITE_TAC[GSYM INFINITE_CARD_LE; GSYM COUNTABLE_ALT] THEN ASM_SIMP_TAC[COUNTABLE_LIST; COUNTABLE_FORM]; REWRITE_TAC[le_c; IN_UNIV]]; ALL_TAC] THEN MAP_EVERY EXISTS_TAC [`IMAGE (f:form list->A) W1`; `\x y:A. ?a b:form list. a IN W1 /\ b IN W1 /\ x = f a /\ y = f b /\ R1 a b`; `\a:string w:A. ?x:form list. w = f x /\ V1 a x`; `f (w1:form list):A`] THEN CONJ_TAC THENL [REWRITE_TAC[ITF] THEN CONJ_TAC THENL [HYP SET_TAC "w1" []; ALL_TAC] THEN CONJ_TAC THENL [SET_TAC[]; ALL_TAC] THEN CONJ_TAC THENL [ASM_MESON_TAC[ITF; FINITE_IMAGE]; ALL_TAC] THEN CONJ_TAC THENL [REWRITE_TAC[FORALL_IN_IMAGE] THEN HYP_TAC "itf1: _ _ _ irrefl _" (REWRITE_RULE[ITF]) THEN HYP MESON_TAC " irrefl inj" []; ALL_TAC] THEN REWRITE_TAC[IMP_CONJ; RIGHT_FORALL_IMP_THM; FORALL_IN_IMAGE] THEN HYP_TAC "itf1: _ _ _ _ trans" (REWRITE_RULE[ITF]) THEN HYP MESON_TAC " trans inj" []; ALL_TAC] THEN REWRITE_TAC[BISIMILAR] THEN EXISTS_TAC `\w1:form list w2:A. w1 IN W1 /\ w2 = f w1` THEN ASM_REWRITE_TAC[BISIMIMULATION] THEN REMOVE_THEN "w1" (K ALL_TAC) THEN REPEAT GEN_TAC THEN STRIP_TAC THEN FIRST_X_ASSUM SUBST_VAR_TAC THEN ASM_SIMP_TAC[FUN_IN_IMAGE] THEN CONJ_TAC THENL [HYP MESON_TAC "inj" []; ALL_TAC] THEN CONJ_TAC THENL [REPEAT STRIP_TAC THEN REWRITE_TAC[EXISTS_IN_IMAGE] THEN ASM_MESON_TAC[ITF]; ALL_TAC] THEN ASM_MESON_TAC[]);; (* ------------------------------------------------------------------------- *) Simple decision procedure for GL . (* ------------------------------------------------------------------------- *) let GL_TAC : tactic = MATCH_MP_TAC COMPLETENESS_THEOREM THEN REWRITE_TAC[valid; FORALL_PAIR_THM; holds_in; holds; ITF; GSYM MEMBER_NOT_EMPTY] THEN MESON_TAC[];; let GL_RULE tm = prove(tm, REPEAT GEN_TAC THEN GL_TAC);; GL_RULE `!p q r. |-- (p && q && r --> p && r)`;; GL_RULE `!p. |-- (Box p --> Box (Box p))`;; GL_RULE `!p q. |-- (Box (p --> q) && Box p --> Box q)`;; GL_RULE ` ! ( Box p -- > p ) -- > Box p ) ` ; ; GL_RULE ` |-- ( Box ( Box False -- > False ) -- > Box False ) ` ; ; GL_RULE `!p q. |-- (Box (p <-> q) --> (Box p <-> Box q))`;; (* ------------------------------------------------------------------------- *) (* Invariance by permutation. *) (* ------------------------------------------------------------------------- *) let SET_OF_LIST_EQ_IMP_MEM = prove (`!l m x:A. set_of_list l = set_of_list m /\ MEM x l ==> MEM x m`, REPEAT GEN_TAC THEN REWRITE_TAC[GSYM IN_SET_OF_LIST] THEN MESON_TAC[]);; let SET_OF_LIST_EQ_CONJLIST = prove (`!X Y. set_of_list X = set_of_list Y ==> |-- (CONJLIST X --> CONJLIST Y)`, REPEAT STRIP_TAC THEN MATCH_MP_TAC CONJLIST_IMP THEN INTRO_TAC "!p; p" THEN EXISTS_TAC `p:form` THEN REWRITE_TAC[GL_imp_refl_th] THEN ASM_MESON_TAC[SET_OF_LIST_EQ_IMP_MEM]);; let SET_OF_LIST_EQ_CONJLIST_EQ = prove (`!X Y. set_of_list X = set_of_list Y ==> |-- (CONJLIST X <-> CONJLIST Y)`, REWRITE_TAC[GL_iff_def] THEN MESON_TAC[SET_OF_LIST_EQ_CONJLIST]);; let SET_OF_LIST_EQ_CONSISTENT = prove (`!X Y. set_of_list X = set_of_list Y /\ CONSISTENT X ==> CONSISTENT Y`, REWRITE_TAC[CONSISTENT] THEN INTRO_TAC "!X Y; eq hp; p" THEN REMOVE_THEN "hp" MP_TAC THEN REWRITE_TAC[] THEN MATCH_MP_TAC GL_modusponens THEN EXISTS_TAC `Not (CONJLIST Y)` THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC GL_contrapos THEN MATCH_MP_TAC SET_OF_LIST_EQ_CONJLIST THEN ASM_REWRITE_TAC[]);; let SET_OF_LIST_EQ_MAXIMAL_CONSISTENT = prove (`!p X Y. set_of_list X = set_of_list Y /\ NOREPETITION Y /\ MAXIMAL_CONSISTENT p X ==> MAXIMAL_CONSISTENT p Y`, REWRITE_TAC[MAXIMAL_CONSISTENT] THEN REPEAT STRIP_TAC THENL [ASM_MESON_TAC[SET_OF_LIST_EQ_CONSISTENT]; ASM_REWRITE_TAC[]; ASM_MESON_TAC[SET_OF_LIST_EQ_IMP_MEM]]);; let SET_OF_LIST_EQ_GL_STANDARD_REL = prove (`!p u1 u2 w1 w2. set_of_list u1 = set_of_list w1 /\ NOREPETITION w1 /\ set_of_list u2 = set_of_list w2 /\ NOREPETITION w2 /\ GL_STANDARD_REL p u1 u2 ==> GL_STANDARD_REL p w1 w2`, REPEAT GEN_TAC THEN REWRITE_TAC[GL_STANDARD_REL] THEN STRIP_TAC THEN CONJ_TAC THENL [MATCH_MP_TAC SET_OF_LIST_EQ_MAXIMAL_CONSISTENT THEN ASM_MESON_TAC[]; ALL_TAC] THEN CONJ_TAC THENL [ASM_MESON_TAC[SET_OF_LIST_EQ_IMP_MEM]; ALL_TAC] THEN CONJ_TAC THENL [MATCH_MP_TAC SET_OF_LIST_EQ_MAXIMAL_CONSISTENT THEN ASM_MESON_TAC[]; ALL_TAC] THEN ASM_MESON_TAC[SET_OF_LIST_EQ_IMP_MEM]);; (* ------------------------------------------------------------------------- *) Countermodel using set of formulae ( instead of lists of formulae ) . (* ------------------------------------------------------------------------- *) let GL_STDWORLDS_RULES,GL_STDWORLDS_INDUCT,GL_STDWORLDS_CASES = new_inductive_set `!M. MAXIMAL_CONSISTENT p M /\ (!q. MEM q M ==> q SUBSENTENCE p) ==> set_of_list M IN GL_STDWORLDS p`;; let GL_STDREL_RULES,GL_STDREL_INDUCT,GL_STDREL_CASES = new_inductive_definition `!w1 w2. GL_STANDARD_REL p w1 w2 ==> GL_STDREL p (set_of_list w1) (set_of_list w2)`;; let GL_STDREL_IMP_GL_STDWORLDS = prove (`!p w1 w2. GL_STDREL p w1 w2 ==> w1 IN GL_STDWORLDS p /\ w2 IN GL_STDWORLDS p`, GEN_TAC THEN MATCH_MP_TAC GL_STDREL_INDUCT THEN REWRITE_TAC[GL_STANDARD_REL] THEN REPEAT STRIP_TAC THEN MATCH_MP_TAC GL_STDWORLDS_RULES THEN ASM_REWRITE_TAC[]);; let BISIMIMULATION_SET_OF_LIST = prove (`!p. BISIMIMULATION ( {M | MAXIMAL_CONSISTENT p M /\ (!q. MEM q M ==> q SUBSENTENCE p)}, GL_STANDARD_REL p, (\a w. Atom a SUBFORMULA p /\ MEM (Atom a) w) ) (GL_STDWORLDS p, GL_STDREL p, (\a w. Atom a SUBFORMULA p /\ Atom a IN w)) (\w1 w2. MAXIMAL_CONSISTENT p w1 /\ (!q. MEM q w1 ==> q SUBSENTENCE p) /\ w2 IN GL_STDWORLDS p /\ set_of_list w1 = w2)`, GEN_TAC THEN REWRITE_TAC[BISIMIMULATION] THEN REPEAT GEN_TAC THEN STRIP_TAC THEN ASM_REWRITE_TAC[IN_ELIM_THM] THEN CONJ_TAC THENL [GEN_TAC THEN FIRST_X_ASSUM SUBST_VAR_TAC THEN REWRITE_TAC[IN_SET_OF_LIST]; ALL_TAC] THEN CONJ_TAC THENL [INTRO_TAC "![u1]; w1u1" THEN EXISTS_TAC `set_of_list u1:form->bool` THEN HYP_TAC "w1u1 -> hp" (REWRITE_RULE[GL_STANDARD_REL]) THEN ASM_REWRITE_TAC[] THEN CONJ_TAC THENL [MATCH_MP_TAC GL_STDWORLDS_RULES THEN ASM_REWRITE_TAC[]; ALL_TAC] THEN CONJ_TAC THENL [MATCH_MP_TAC GL_STDWORLDS_RULES THEN ASM_REWRITE_TAC[]; ALL_TAC] THEN FIRST_X_ASSUM SUBST_VAR_TAC THEN MATCH_MP_TAC GL_STDREL_RULES THEN ASM_REWRITE_TAC[]; ALL_TAC] THEN INTRO_TAC "![u2]; w2u2" THEN EXISTS_TAC `list_of_set u2:form list` THEN REWRITE_TAC[CONJ_ACI] THEN HYP_TAC "w2u2 -> @x2 y2. x2 y2 x2y2" (REWRITE_RULE[GL_STDREL_CASES]) THEN REPEAT (FIRST_X_ASSUM SUBST_VAR_TAC) THEN SIMP_TAC[SET_OF_LIST_OF_SET; FINITE_SET_OF_LIST] THEN SIMP_TAC[MEM_LIST_OF_SET; FINITE_SET_OF_LIST; IN_SET_OF_LIST] THEN CONJ_TAC THENL [HYP_TAC "x2y2 -> hp" (REWRITE_RULE[GL_STANDARD_REL]) THEN ASM_REWRITE_TAC[]; ALL_TAC] THEN CONJ_TAC THENL [MATCH_MP_TAC SET_OF_LIST_EQ_GL_STANDARD_REL THEN EXISTS_TAC `x2:form list` THEN EXISTS_TAC `y2:form list` THEN ASM_REWRITE_TAC[] THEN SIMP_TAC[NOREPETITION_LIST_OF_SET; FINITE_SET_OF_LIST] THEN SIMP_TAC[EXTENSION; IN_SET_OF_LIST; MEM_LIST_OF_SET; FINITE_SET_OF_LIST] THEN ASM_MESON_TAC[MAXIMAL_CONSISTENT]; ALL_TAC] THEN CONJ_TAC THENL [ASM_MESON_TAC[GL_STDREL_IMP_GL_STDWORLDS]; ALL_TAC] THEN MATCH_MP_TAC SET_OF_LIST_EQ_MAXIMAL_CONSISTENT THEN EXISTS_TAC `y2:form list` THEN SIMP_TAC[NOREPETITION_LIST_OF_SET; FINITE_SET_OF_LIST] THEN SIMP_TAC[EXTENSION; IN_SET_OF_LIST; MEM_LIST_OF_SET; FINITE_SET_OF_LIST] THEN ASM_MESON_TAC[GL_STANDARD_REL]);; let GL_COUNTERMODEL_FINITE_SETS = prove (`!p. ~(|-- p) ==> ~holds_in (GL_STDWORLDS p, GL_STDREL p) p`, INTRO_TAC "!p; p" THEN DESTRUCT_TAC "@M. max mem subf" (MATCH_MP NONEMPTY_MAXIMAL_CONSISTENT (ASSUME `~ |-- p`)) THEN REWRITE_TAC[holds_in; NOT_FORALL_THM; NOT_IMP] THEN ASSUM_LIST (LABEL_TAC "hp" o MATCH_MP GL_COUNTERMODEL o end_itlist CONJ o rev) THEN EXISTS_TAC `\a w. Atom a SUBFORMULA p /\ Atom a IN w` THEN EXISTS_TAC `set_of_list M:form->bool` THEN CONJ_TAC THENL [MATCH_MP_TAC GL_STDWORLDS_RULES THEN ASM_REWRITE_TAC[]; ALL_TAC] THEN REMOVE_THEN "hp" MP_TAC THEN MATCH_MP_TAC (MESON[] `(p <=> q) ==> (~p ==> ~q)`) THEN MATCH_MP_TAC BISIMIMULATION_HOLDS THEN EXISTS_TAC `(\w1 w2. MAXIMAL_CONSISTENT p w1 /\ (!q. MEM q w1 ==> q SUBSENTENCE p) /\ w2 IN GL_STDWORLDS p /\ set_of_list w1 = w2)` THEN ASM_REWRITE_TAC[BISIMIMULATION_SET_OF_LIST] THEN MATCH_MP_TAC GL_STDWORLDS_RULES THEN ASM_REWRITE_TAC[]);;
null
https://raw.githubusercontent.com/jrh13/hol-light/ab57c07ff0105fef75a9fcdd179eda0d26854ba3/GL/completeness.ml
ocaml
========================================================================= ========================================================================= ------------------------------------------------------------------------- Iterated conjunction of formulae. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Consistent list of formulas. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Maximal Consistent Sets. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Subsentences. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Standard model. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Truth Lemma. ------------------------------------------------------------------------- Case && Case || Case --> Case <-> Case Box ------------------------------------------------------------------------- Extension Lemma. Every consistent list of formulae can be extended to a maximal consistent ------------------------------------------------------------------------- ------------------------------------------------------------------------- Accessibility lemma. ------------------------------------------------------------------------- Well-defined Finite Transitive ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- Invariance by permutation. ------------------------------------------------------------------------- ------------------------------------------------------------------------- -------------------------------------------------------------------------
Proof of the modal completeness of the provability logic GL . ( c ) Copyright , , 2020 - 2022 . let CONJLIST = new_recursive_definition list_RECURSION `CONJLIST [] = True /\ (!p X. CONJLIST (CONS p X) = if X = [] then p else p && CONJLIST X)`;; let CONJLIST_IMP_MEM = prove (`!p X. MEM p X ==> |-- (CONJLIST X --> p)`, GEN_TAC THEN LIST_INDUCT_TAC THEN REWRITE_TAC[MEM; CONJLIST] THEN STRIP_TAC THENL [POP_ASSUM (SUBST_ALL_TAC o GSYM) THEN COND_CASES_TAC THEN REWRITE_TAC[GL_imp_refl_th; GL_and_left_th]; COND_CASES_TAC THENL [ASM_MESON_TAC[MEM]; ALL_TAC] THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `CONJLIST t` THEN CONJ_TAC THENL [MATCH_ACCEPT_TAC GL_and_right_th; ASM_SIMP_TAC[]]]);; let CONJLIST_MONO = prove (`!X Y. (!p. MEM p Y ==> MEM p X) ==> |-- (CONJLIST X --> CONJLIST Y)`, GEN_TAC THEN LIST_INDUCT_TAC THEN REWRITE_TAC[MEM; CONJLIST] THENL [MESON_TAC[GL_add_assum; GL_truth_th]; ALL_TAC] THEN COND_CASES_TAC THENL [POP_ASSUM SUBST_VAR_TAC THEN REWRITE_TAC[MEM] THEN MESON_TAC[CONJLIST_IMP_MEM]; ALL_TAC] THEN DISCH_TAC THEN MATCH_MP_TAC GL_and_intro THEN CONJ_TAC THENL [ASM_MESON_TAC[CONJLIST_IMP_MEM]; FIRST_X_ASSUM MATCH_MP_TAC THEN ASM_MESON_TAC[]]);; let CONJLIST_CONS = prove (`!p X. |-- (CONJLIST (CONS p X) <-> p && CONJLIST X)`, REPEAT GEN_TAC THEN REWRITE_TAC[CONJLIST] THEN COND_CASES_TAC THEN REWRITE_TAC[GL_iff_refl_th] THEN POP_ASSUM SUBST1_TAC THEN REWRITE_TAC[CONJLIST] THEN ONCE_REWRITE_TAC[GL_iff_sym] THEN MATCH_ACCEPT_TAC GL_and_rigth_true_th);; let CONJLIST_IMP_HEAD = prove (`!p X. |-- (CONJLIST (CONS p X) --> p)`, REPEAT GEN_TAC THEN REWRITE_TAC[CONJLIST] THEN COND_CASES_TAC THENL [ASM_REWRITE_TAC[GL_imp_refl_th]; REWRITE_TAC[GL_and_left_th]]);; let CONJLIST_IMP_TAIL = prove (`!p X. |-- (CONJLIST (CONS p X) --> CONJLIST X)`, REPEAT GEN_TAC THEN REWRITE_TAC[CONJLIST] THEN COND_CASES_TAC THENL [ASM_REWRITE_TAC[CONJLIST; GL_imp_clauses]; REWRITE_TAC[GL_and_right_th]]);; let HEAD_TAIL_IMP_CONJLIST = prove (`!p h t. |-- (p --> h) /\ |-- (p --> CONJLIST t) ==> |-- (p --> CONJLIST (CONS h t))`, INTRO_TAC "!p h t; ph pt" THEN REWRITE_TAC[CONJLIST] THEN COND_CASES_TAC THENL [ASM_REWRITE_TAC[]; ASM_SIMP_TAC[GL_and_intro]]);; let IMP_CONJLIST = prove (`!p X. |-- (p --> CONJLIST X) <=> (!q. MEM q X ==> |-- (p --> q))`, GEN_TAC THEN SUBGOAL_THEN `(!X q. |-- (p --> CONJLIST X) /\ MEM q X ==> |-- (p --> q)) /\ (!X. (!q. MEM q X ==> |-- (p --> q)) ==> |-- (p --> CONJLIST X))` (fun th -> MESON_TAC[th]) THEN CONJ_TAC THENL [REPEAT STRIP_TAC THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `CONJLIST X` THEN ASM_SIMP_TAC[CONJLIST_IMP_MEM]; ALL_TAC] THEN LIST_INDUCT_TAC THEN REWRITE_TAC[MEM] THENL [REWRITE_TAC[CONJLIST; GL_imp_clauses]; ALL_TAC] THEN DISCH_TAC THEN MATCH_MP_TAC HEAD_TAIL_IMP_CONJLIST THEN ASM_SIMP_TAC[]);; let CONJLIST_IMP_SUBLIST = prove (`!X Y. Y SUBLIST X ==> |-- (CONJLIST X --> CONJLIST Y)`, REWRITE_TAC[SUBLIST; IMP_CONJLIST] THEN MESON_TAC[CONJLIST_IMP_MEM]);; let CONJLIST_IMP = prove (`!l m. (!p. MEM p m ==> ?q. MEM q l /\ |-- (q --> p)) ==> |-- (CONJLIST l --> CONJLIST m)`, GEN_TAC THEN LIST_INDUCT_TAC THENL [REWRITE_TAC[CONJLIST; GL_imp_clauses]; ALL_TAC] THEN INTRO_TAC "hp" THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `h && CONJLIST t` THEN CONJ_TAC THENL [MATCH_MP_TAC GL_and_intro THEN CONJ_TAC THENL [HYP_TAC "hp: +" (SPEC `h:form`) THEN REWRITE_TAC[MEM] THEN MESON_TAC[CONJLIST_IMP_MEM; GL_imp_trans]; FIRST_X_ASSUM MATCH_MP_TAC THEN INTRO_TAC "!p; p" THEN FIRST_X_ASSUM (MP_TAC o SPEC `p:form`) THEN ASM_REWRITE_TAC[MEM]]; ALL_TAC] THEN MESON_TAC[CONJLIST_CONS; GL_iff_imp2]);; let CONJLIST_APPEND = prove (`!l m. |-- (CONJLIST (APPEND l m) <-> CONJLIST l && CONJLIST m)`, FIX_TAC "m" THEN LIST_INDUCT_TAC THEN REWRITE_TAC[APPEND] THENL [REWRITE_TAC[CONJLIST] THEN ONCE_REWRITE_TAC[GL_iff_sym] THEN MATCH_ACCEPT_TAC GL_and_left_true_th; ALL_TAC] THEN MATCH_MP_TAC GL_iff_trans THEN EXISTS_TAC `h && CONJLIST (APPEND t m)` THEN REWRITE_TAC[CONJLIST_CONS] THEN MATCH_MP_TAC GL_iff_trans THEN EXISTS_TAC `h && (CONJLIST t && CONJLIST m)` THEN CONJ_TAC THENL [MATCH_MP_TAC GL_and_subst_th THEN ASM_REWRITE_TAC[GL_iff_refl_th]; ALL_TAC] THEN MATCH_MP_TAC GL_iff_trans THEN EXISTS_TAC `(h && CONJLIST t) && CONJLIST m` THEN CONJ_TAC THENL [MESON_TAC[GL_and_assoc_th; GL_iff_sym]; ALL_TAC] THEN MATCH_MP_TAC GL_and_subst_th THEN REWRITE_TAC[GL_iff_refl_th] THEN ONCE_REWRITE_TAC[GL_iff_sym] THEN MATCH_ACCEPT_TAC CONJLIST_CONS);; let FALSE_NOT_CONJLIST = prove (`!X. MEM False X ==> |-- (Not (CONJLIST X))`, INTRO_TAC "!X; X" THEN REWRITE_TAC[GL_not_def] THEN MATCH_MP_TAC CONJLIST_IMP_MEM THEN POP_ASSUM MATCH_ACCEPT_TAC);; let CONJLIST_MAP_BOX = prove (`!l. |-- (CONJLIST (MAP (Box) l) <-> Box (CONJLIST l))`, LIST_INDUCT_TAC THENL [REWRITE_TAC[CONJLIST; MAP; GL_iff_refl_th] THEN MATCH_MP_TAC GL_imp_antisym THEN SIMP_TAC[GL_add_assum; GL_truth_th; GL_necessitation]; ALL_TAC] THEN REWRITE_TAC[MAP] THEN MATCH_MP_TAC GL_iff_trans THEN EXISTS_TAC `Box h && CONJLIST (MAP (Box) t)` THEN CONJ_TAC THENL [MATCH_ACCEPT_TAC CONJLIST_CONS; ALL_TAC] THEN MATCH_MP_TAC GL_iff_trans THEN EXISTS_TAC `Box h && Box (CONJLIST t)` THEN CONJ_TAC THENL [MATCH_MP_TAC GL_imp_antisym THEN CONJ_TAC THEN MATCH_MP_TAC GL_and_intro THEN ASM_MESON_TAC[GL_and_left_th; GL_and_right_th; GL_iff_imp1; GL_iff_imp2; GL_imp_trans]; ALL_TAC] THEN MATCH_MP_TAC GL_iff_trans THEN EXISTS_TAC `Box (h && CONJLIST t)` THEN CONJ_TAC THENL [MESON_TAC[GL_box_and_th; GL_box_and_inv_th; GL_imp_antisym]; ALL_TAC] THEN MATCH_MP_TAC GL_box_iff THEN MATCH_MP_TAC GL_necessitation THEN ONCE_REWRITE_TAC[GL_iff_sym] THEN MATCH_ACCEPT_TAC CONJLIST_CONS);; let CONSISTENT = new_definition `CONSISTENT (l:form list) <=> ~ (|-- (Not (CONJLIST l)))`;; let CONSISTENT_SING = prove (`!p. CONSISTENT [p] <=> ~ |-- (Not p)`, REWRITE_TAC[CONSISTENT; CONJLIST]);; let CONSISTENT_LEMMA = prove (`!X p. MEM p X /\ MEM (Not p) X ==> |-- (Not (CONJLIST X))`, REPEAT STRIP_TAC THEN REWRITE_TAC[GL_not_def] THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `p && Not p` THEN CONJ_TAC THENL [MATCH_MP_TAC GL_and_intro THEN ASM_MESON_TAC[CONJLIST_IMP_MEM; GL_imp_trans; GL_and_pair_th]; MESON_TAC[GL_nc_th]]);; let CONSISTENT_SUBLIST = prove (`!X Y. CONSISTENT X /\ Y SUBLIST X ==> CONSISTENT Y`, REPEAT GEN_TAC THEN REWRITE_TAC[CONSISTENT] THEN SUBGOAL_THEN `|-- (CONJLIST Y --> False) /\ Y SUBLIST X ==> |-- (CONJLIST X --> False)` (fun th -> ASM_MESON_TAC[th; GL_not_def]) THEN INTRO_TAC "inc sub" THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `CONJLIST Y` THEN ASM_REWRITE_TAC[] THEN ASM_SIMP_TAC[CONJLIST_IMP_SUBLIST]);; let CONSISTENT_CONS = prove (`!h t. CONSISTENT (CONS h t) <=> ~ |-- (Not h || Not (CONJLIST t))`, GEN_TAC THEN GEN_TAC THEN REWRITE_TAC[CONSISTENT] THEN AP_TERM_TAC THEN MATCH_MP_TAC GL_iff THEN MATCH_MP_TAC GL_iff_trans THEN EXISTS_TAC `Not (h && CONJLIST t)` THEN CONJ_TAC THENL [MATCH_MP_TAC GL_not_subst THEN MATCH_ACCEPT_TAC CONJLIST_CONS; MATCH_ACCEPT_TAC GL_de_morgan_and_th]);; let CONSISTENT_NC = prove (`!X p. MEM p X /\ MEM (Not p) X ==> ~CONSISTENT X`, INTRO_TAC "!X p; p np" THEN REWRITE_TAC[CONSISTENT; GL_not_def] THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `p && Not p` THEN REWRITE_TAC[GL_nc_th] THEN MATCH_MP_TAC GL_and_intro THEN ASM_SIMP_TAC[CONJLIST_IMP_MEM]);; let CONSISTENT_EM = prove (`!h t. CONSISTENT t ==> CONSISTENT (CONS h t) \/ CONSISTENT (CONS (Not h) t)`, REPEAT GEN_TAC THEN REWRITE_TAC[CONSISTENT_CONS] THEN REWRITE_TAC[CONSISTENT] THEN SUBGOAL_THEN `|-- ((Not h || Not CONJLIST t) --> (Not Not h || Not CONJLIST t) --> (Not CONJLIST t))` (fun th -> MESON_TAC[th; GL_modusponens]) THEN REWRITE_TAC[GL_disj_imp] THEN CONJ_TAC THENL [MATCH_MP_TAC GL_imp_swap THEN REWRITE_TAC[GL_disj_imp] THEN CONJ_TAC THENL [MATCH_MP_TAC GL_imp_swap THEN MATCH_MP_TAC GL_shunt THEN MATCH_MP_TAC GL_frege THEN EXISTS_TAC `False` THEN REWRITE_TAC[GL_nc_th] THEN MATCH_MP_TAC GL_add_assum THEN MATCH_ACCEPT_TAC GL_ex_falso_th; MATCH_ACCEPT_TAC GL_axiom_addimp]; MATCH_MP_TAC GL_imp_swap THEN REWRITE_TAC[GL_disj_imp] THEN CONJ_TAC THENL [MATCH_MP_TAC GL_add_assum THEN MATCH_ACCEPT_TAC GL_imp_refl_th; MATCH_ACCEPT_TAC GL_axiom_addimp]]);; let FALSE_IMP_NOT_CONSISTENT = prove (`!X. MEM False X ==> ~ CONSISTENT X`, SIMP_TAC[CONSISTENT; FALSE_NOT_CONJLIST]);; See p.79 ( pdf p.118 ) . D in the text is p here . let MAXIMAL_CONSISTENT = new_definition `MAXIMAL_CONSISTENT p X <=> CONSISTENT X /\ NOREPETITION X /\ (!q. q SUBFORMULA p ==> MEM q X \/ MEM (Not q) X)`;; let MAXIMAL_CONSISTENT_LEMMA = prove (`!p X A b. MAXIMAL_CONSISTENT p X /\ (!q. MEM q A ==> MEM q X) /\ b SUBFORMULA p /\ |-- (CONJLIST A --> b) ==> MEM b X`, INTRO_TAC "!p X A b; mconst subl b Ab" THEN REFUTE_THEN ASSUME_TAC THEN CLAIM_TAC "rmk" `MEM (Not b) X` THENL [ASM_MESON_TAC[MAXIMAL_CONSISTENT]; ALL_TAC] THEN CLAIM_TAC "rmk2" `|-- (CONJLIST X --> b && Not b)` THENL [MATCH_MP_TAC GL_and_intro THEN CONJ_TAC THENL [ASM_MESON_TAC[CONJLIST_MONO; GL_imp_trans]; ASM_MESON_TAC[CONJLIST_IMP_MEM]]; ALL_TAC] THEN CLAIM_TAC "rmk3" `|-- (CONJLIST X --> False)` THENL [ASM_MESON_TAC[GL_imp_trans; GL_nc_th]; ALL_TAC] THEN SUBGOAL_THEN `~ CONSISTENT X` (fun th -> ASM_MESON_TAC[th; MAXIMAL_CONSISTENT]) THEN ASM_REWRITE_TAC[CONSISTENT; GL_not_def]);; let MAXIMAL_CONSISTENT_MEM_NOT = prove (`!X p q. MAXIMAL_CONSISTENT p X /\ q SUBFORMULA p ==> (MEM (Not q) X <=> ~ MEM q X)`, REWRITE_TAC[MAXIMAL_CONSISTENT] THEN MESON_TAC[CONSISTENT_NC]);; let MAXIMAL_CONSISTENT_MEM_CASES = prove (`!X p q. MAXIMAL_CONSISTENT p X /\ q SUBFORMULA p ==> (MEM q X \/ MEM (Not q) X)`, REWRITE_TAC[MAXIMAL_CONSISTENT] THEN MESON_TAC[CONSISTENT_NC]);; let MAXIMAL_CONSISTENT_SUBFORMULA_MEM_EQ_DERIVABLE = prove (`!p w q. MAXIMAL_CONSISTENT p w /\ q SUBFORMULA p ==> (MEM q w <=> |-- (CONJLIST w --> q))`, REPEAT GEN_TAC THEN REWRITE_TAC[MAXIMAL_CONSISTENT; CONSISTENT] THEN INTRO_TAC "(w em) sub" THEN LABEL_ASM_CASES_TAC "q" `MEM (q:form) w` THEN ASM_SIMP_TAC[CONJLIST_IMP_MEM] THEN CLAIM_TAC "nq" `MEM (Not q) w` THENL [ASM_MESON_TAC[]; INTRO_TAC "deriv"] THEN SUBGOAL_THEN `|-- (Not (CONJLIST w))` (fun th -> ASM_MESON_TAC[th]) THEN REWRITE_TAC[GL_not_def] THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `q && Not q` THEN REWRITE_TAC[GL_nc_th] THEN ASM_SIMP_TAC[GL_and_intro; CONJLIST_IMP_MEM]);; let MAXIMAL_CONSISTENT_SUBFORMULA_MEM_NEG_EQ_DERIVABLE = prove (`!p w q. MAXIMAL_CONSISTENT p w /\ q SUBFORMULA p ==> (MEM (Not q) w <=> |-- (CONJLIST w --> Not q))`, REPEAT GEN_TAC THEN REWRITE_TAC[MAXIMAL_CONSISTENT; CONSISTENT] THEN INTRO_TAC "(w em) sub" THEN LABEL_ASM_CASES_TAC "q" `MEM (Not q) w` THEN ASM_SIMP_TAC[CONJLIST_IMP_MEM] THEN CLAIM_TAC "nq" `MEM (q:form) w` THENL [ASM_MESON_TAC[]; INTRO_TAC "deriv"] THEN SUBGOAL_THEN `|-- (Not (CONJLIST w))` (fun th -> ASM_MESON_TAC[th]) THEN REWRITE_TAC[GL_not_def] THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `q && Not q` THEN REWRITE_TAC[GL_nc_th] THEN ASM_SIMP_TAC[GL_and_intro; CONJLIST_IMP_MEM]);; parse_as_infix("SUBSENTENCE",get_infix_status "SUBFORMULA");; let SUBSENTENCE_RULES,SUBSENTENCE_INDUCT,SUBSENTENCE_CASES = new_inductive_definition `(!p q. p SUBFORMULA q ==> p SUBSENTENCE q) /\ (!p q. p SUBFORMULA q ==> Not p SUBSENTENCE q)`;; let GL_STANDARD_FRAME = new_definition `GL_STANDARD_FRAME p (W,R) <=> W = {w | MAXIMAL_CONSISTENT p w /\ (!q. MEM q w ==> q SUBSENTENCE p)} /\ ITF (W,R) /\ (!q w. Box q SUBFORMULA p /\ w IN W ==> (MEM (Box q) w <=> !x. R w x ==> MEM q x))`;; let SUBFORMULA_IMP_SUBSENTENCE = prove (`!p q. p SUBFORMULA q ==> p SUBSENTENCE q`, REWRITE_TAC[SUBSENTENCE_RULES]);; let SUBFORMULA_IMP_NEG_SUBSENTENCE = prove (`!p q. p SUBFORMULA q ==> Not p SUBSENTENCE q`, REWRITE_TAC[SUBSENTENCE_RULES]);; let GL_STANDARD_MODEL = new_definition `GL_STANDARD_MODEL p (W,R) V <=> GL_STANDARD_FRAME p (W,R) /\ (!a w. w IN W ==> (V a w <=> MEM (Atom a) w /\ Atom a SUBFORMULA p))`;; let GL_truth_lemma = prove (`!W R p V q. ~ |-- p /\ GL_STANDARD_MODEL p (W,R) V /\ q SUBFORMULA p ==> !w. w IN W ==> (MEM q w <=> holds (W,R) V q w)`, REPEAT GEN_TAC THEN REWRITE_TAC[GL_STANDARD_MODEL; GL_STANDARD_FRAME; SUBSENTENCE_CASES] THEN INTRO_TAC "np ((W itf 1) val) q" THEN REMOVE_THEN "W" SUBST_VAR_TAC THEN REWRITE_TAC[FORALL_IN_GSPEC] THEN REMOVE_THEN "q" MP_TAC THEN HYP_TAC "1" (REWRITE_RULE[IN_ELIM_THM]) THEN HYP_TAC "val" (REWRITE_RULE[FORALL_IN_GSPEC]) THEN SPEC_TAC (`q:form`,`q:form`) THEN MATCH_MP_TAC form_INDUCT THEN REWRITE_TAC[holds] THEN CONJ_TAC THENL [INTRO_TAC "sub; !w; w" THEN HYP_TAC "w -> cons memq" (REWRITE_RULE[MAXIMAL_CONSISTENT]) THEN ASM_MESON_TAC[FALSE_IMP_NOT_CONSISTENT]; ALL_TAC] THEN CONJ_TAC THENL [REWRITE_TAC[MAXIMAL_CONSISTENT] THEN INTRO_TAC "p; !w; (cons (norep mem)) subf" THEN HYP_TAC "mem: t | nt" (C MATCH_MP (ASSUME `True SUBFORMULA p`)) THEN ASM_REWRITE_TAC[] THEN REFUTE_THEN (K ALL_TAC) THEN REMOVE_THEN "cons" MP_TAC THEN REWRITE_TAC[CONSISTENT] THEN REWRITE_TAC[GL_not_def] THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `Not True` THEN ASM_SIMP_TAC[CONJLIST_IMP_MEM] THEN MATCH_MP_TAC GL_iff_imp1 THEN MATCH_ACCEPT_TAC GL_not_true_th; ALL_TAC] THEN CONJ_TAC THENL [ASM_SIMP_TAC[]; ALL_TAC] THEN CONJ_TAC THENL [INTRO_TAC "![q/a]; q; sub; !w; w" THEN REMOVE_THEN "q" MP_TAC THEN MATCH_MP_TAC (MESON[] `P /\ (P /\ Q ==> R) ==> ((P ==> Q) ==> R)`) THEN CONJ_TAC THENL [ASM_MESON_TAC[SUBFORMULA_TRANS; SUBFORMULA_INVERSION; SUBFORMULA_REFL]; INTRO_TAC "sub1 q"] THEN EQ_TAC THENL [HYP MESON_TAC "w sub1 q" [MAXIMAL_CONSISTENT_MEM_NOT]; REMOVE_THEN "q" (MP_TAC o SPEC `w: form list`) THEN ANTS_TAC THEN ASM_REWRITE_TAC[] THEN ASM_MESON_TAC[MAXIMAL_CONSISTENT_MEM_NOT]]; ALL_TAC] THEN REPEAT CONJ_TAC THEN TRY (INTRO_TAC "![q1] [q2]; q1 q2; sub; !w; w" THEN REMOVE_THEN "q1" MP_TAC THEN MATCH_MP_TAC (MESON[] `P /\ (P /\ Q ==> R) ==> ((P ==> Q) ==> R)`) THEN CONJ_TAC THENL [ASM_MESON_TAC[SUBFORMULA_TRANS; SUBFORMULA_INVERSION; SUBFORMULA_REFL]; INTRO_TAC "sub1 +" THEN DISCH_THEN (MP_TAC o SPEC `w:form list`)] THEN REMOVE_THEN "q2" MP_TAC THEN MATCH_MP_TAC (MESON[] `P /\ (P /\ Q ==> R) ==> ((P ==> Q) ==> R)`) THEN CONJ_TAC THENL [ASM_MESON_TAC[SUBFORMULA_TRANS; SUBFORMULA_INVERSION; SUBFORMULA_REFL]; INTRO_TAC "sub2 +" THEN DISCH_THEN (MP_TAC o SPEC `w:form list`)] THEN HYP REWRITE_TAC "w" [] THEN DISCH_THEN (SUBST1_TAC o GSYM) THEN DISCH_THEN (SUBST1_TAC o GSYM) THEN CLAIM_TAC "rmk" `!q. q SUBFORMULA p ==> (MEM q w <=> |-- (CONJLIST w --> q))` THENL [ASM_MESON_TAC[MAXIMAL_CONSISTENT_SUBFORMULA_MEM_EQ_DERIVABLE]; ALL_TAC]) THENL [ ASM_SIMP_TAC[] THEN ASM_MESON_TAC[MAXIMAL_CONSISTENT_SUBFORMULA_MEM_EQ_DERIVABLE; GL_and_intro; GL_and_left_th; GL_and_right_th; GL_imp_trans] ; EQ_TAC THENL [INTRO_TAC "q1q2"; ASM_MESON_TAC[GL_or_left_th; GL_or_right_th; GL_imp_trans]] THEN CLAIM_TAC "wq1q2" `|-- (CONJLIST w --> q1 || q2)` THENL [ASM_SIMP_TAC[CONJLIST_IMP_MEM]; ALL_TAC] THEN CLAIM_TAC "hq1 | hq1" `MEM q1 w \/ MEM (Not q1) w` THENL [ASM_MESON_TAC[MAXIMAL_CONSISTENT_MEM_CASES]; ASM_REWRITE_TAC[]; ALL_TAC] THEN CLAIM_TAC "hq2 | hq2" `MEM q2 w \/ MEM (Not q2) w` THENL [ASM_MESON_TAC[MAXIMAL_CONSISTENT_MEM_CASES]; ASM_REWRITE_TAC[]; REFUTE_THEN (K ALL_TAC)] THEN SUBGOAL_THEN `~ (|-- (CONJLIST w --> False))` MP_TAC THENL [REWRITE_TAC[GSYM GL_not_def] THEN ASM_MESON_TAC[MAXIMAL_CONSISTENT; CONSISTENT]; REWRITE_TAC[]] THEN MATCH_MP_TAC GL_frege THEN EXISTS_TAC `q1 || q2` THEN ASM_SIMP_TAC[CONJLIST_IMP_MEM] THEN MATCH_MP_TAC GL_imp_swap THEN REWRITE_TAC[GL_disj_imp] THEN CONJ_TAC THEN MATCH_MP_TAC GL_imp_swap THEN ASM_MESON_TAC[CONJLIST_IMP_MEM; GL_axiom_not; GL_iff_imp1; GL_imp_trans] ; ASM_SIMP_TAC[] THEN EQ_TAC THENL [ASM_MESON_TAC[GL_frege; CONJLIST_IMP_MEM]; INTRO_TAC "imp"] THEN CLAIM_TAC "hq1 | hq1" `MEM q1 w \/ MEM (Not q1) w` THENL [ASM_MESON_TAC[MAXIMAL_CONSISTENT_MEM_CASES]; ASM_MESON_TAC[CONJLIST_IMP_MEM; GL_imp_swap; GL_add_assum]; ALL_TAC] THEN MATCH_MP_TAC GL_shunt THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `q1 && Not q1` THEN CONJ_TAC THENL [ALL_TAC; MESON_TAC[GL_nc_th; GL_imp_trans; GL_ex_falso_th]] THEN MATCH_MP_TAC GL_and_intro THEN REWRITE_TAC[GL_and_right_th] THEN ASM_MESON_TAC[CONJLIST_IMP_MEM; GL_imp_trans; GL_and_left_th] ; ASM_SIMP_TAC[] THEN REMOVE_THEN "sub" (K ALL_TAC) THEN EQ_TAC THENL [MESON_TAC[GL_frege; GL_add_assum; GL_modusponens_th; GL_axiom_iffimp1; GL_axiom_iffimp2]; ALL_TAC] THEN INTRO_TAC "iff" THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `(q1 --> q2) && (q2 --> q1)` THEN CONJ_TAC THENL [MATCH_MP_TAC GL_and_intro; MESON_TAC[GL_iff_def_th; GL_iff_imp2]] THEN CLAIM_TAC "rmk'" `!q. q SUBFORMULA p ==> (MEM (Not q) w <=> |-- (CONJLIST w --> Not q))` THENL [ASM_MESON_TAC[MAXIMAL_CONSISTENT_SUBFORMULA_MEM_NEG_EQ_DERIVABLE]; ALL_TAC] THEN CLAIM_TAC "hq1 | hq1" `|-- (CONJLIST w --> q1) \/ |-- (CONJLIST w --> Not q1)` THENL [ASM_MESON_TAC[MAXIMAL_CONSISTENT_MEM_CASES]; ASM_MESON_TAC[GL_imp_swap; GL_add_assum]; ALL_TAC] THEN CLAIM_TAC "hq2 | hq2" `|-- (CONJLIST w --> q2) \/ |-- (CONJLIST w --> Not q2)` THENL [ASM_MESON_TAC[MAXIMAL_CONSISTENT_MEM_CASES]; ASM_MESON_TAC[GL_imp_swap; GL_add_assum]; ALL_TAC] THEN ASM_MESON_TAC[GL_nc_th; GL_imp_trans; GL_and_intro; GL_ex_falso_th; GL_imp_swap; GL_shunt] ; INTRO_TAC "!a; a; sub; !w; w" THEN REWRITE_TAC[holds; IN_ELIM_THM] THEN CLAIM_TAC "suba" `a SUBFORMULA p` THENL [MATCH_MP_TAC SUBFORMULA_TRANS THEN EXISTS_TAC `Box a` THEN ASM_REWRITE_TAC[SUBFORMULA_INVERSION; SUBFORMULA_REFL]; ALL_TAC] THEN HYP_TAC "itf" (REWRITE_RULE[ITF; IN_ELIM_THM]) THEN EQ_TAC THENL [INTRO_TAC "boxa; !w'; (maxw' subw') r" THEN HYP_TAC "a" (C MATCH_MP (ASSUME `a SUBFORMULA p`)) THEN HYP_TAC "a: +" (SPEC `w':form list`) THEN ANTS_TAC THENL [ASM_REWRITE_TAC[]; ALL_TAC] THEN DISCH_THEN (SUBST1_TAC o GSYM) THEN REMOVE_THEN "1" (MP_TAC o SPECL [`a: form`;`w: form list`]) THEN ANTS_TAC THENL [ASM_REWRITE_TAC[]; ALL_TAC] THEN ASM_REWRITE_TAC[] THEN DISCH_THEN MATCH_MP_TAC THEN ASM_REWRITE_TAC[] THEN ASM_MESON_TAC[]; ALL_TAC] THEN INTRO_TAC "3" THEN REMOVE_THEN "1" (MP_TAC o SPECL [`a:form`; `w:form list`]) THEN ANTS_TAC THENL [ASM_REWRITE_TAC[]; ALL_TAC] THEN DISCH_THEN SUBST1_TAC THEN INTRO_TAC "![w']; w'" THEN REMOVE_THEN "3" (MP_TAC o SPEC `w':form list`) THEN ANTS_TAC THENL [ASM_MESON_TAC[]; ALL_TAC] THEN HYP_TAC "a" (C MATCH_MP (ASSUME `a SUBFORMULA p`)) THEN HYP_TAC "a: +" (SPEC `w':form list`) THEN ANTS_TAC THENL [ASM_MESON_TAC[]; ALL_TAC] THEN DISCH_THEN (SUBST1_TAC o GSYM) THEN REWRITE_TAC[] ]);; list by a construction similar to Lindenbaum 's extension . let EXTEND_MAXIMAL_CONSISTENT = prove (`!p X. CONSISTENT X /\ (!q. MEM q X ==> q SUBSENTENCE p) ==> ?M. MAXIMAL_CONSISTENT p M /\ (!q. MEM q M ==> q SUBSENTENCE p) /\ X SUBLIST M`, GEN_TAC THEN SUBGOAL_THEN `!L X. CONSISTENT X /\ NOREPETITION X /\ (!q. MEM q X ==> q SUBSENTENCE p) /\ (!q. MEM q L ==> q SUBFORMULA p) /\ (!q. q SUBFORMULA p ==> MEM q L \/ MEM q X \/ MEM (Not q) X) ==> ?M. MAXIMAL_CONSISTENT p M /\ (!q. MEM q M ==> q SUBSENTENCE p) /\ X SUBLIST M` (LABEL_TAC "P") THENL [ALL_TAC; INTRO_TAC "![X']; cons' subf'" THEN DESTRUCT_TAC "@X. uniq sub1 sub2" (ISPEC `X':form list` EXISTS_NOREPETITION) THEN DESTRUCT_TAC "@L'. uniq L'" (SPEC `p:form` SUBFORMULA_LIST) THEN HYP_TAC "P: +" (SPECL[`L':form list`; `X:form list`]) THEN ANTS_TAC THENL [CONJ_TAC THENL [ASM_MESON_TAC[CONSISTENT_SUBLIST]; ALL_TAC] THEN CONJ_TAC THENL [ASM_REWRITE_TAC[]; ALL_TAC] THEN CONJ_TAC THENL [ASM_REWRITE_TAC[]; ALL_TAC] THEN ASM_MESON_TAC[SUBLIST]; ALL_TAC] THEN INTRO_TAC "@M. max sub" THEN EXISTS_TAC `M:form list` THEN ASM_REWRITE_TAC[] THEN ASM_MESON_TAC[SUBLIST_TRANS]] THEN LIST_INDUCT_TAC THENL [REWRITE_TAC[MEM] THEN INTRO_TAC "!X; X uniq max subf" THEN EXISTS_TAC `X:form list` THEN ASM_REWRITE_TAC[SUBLIST_REFL; MAXIMAL_CONSISTENT]; ALL_TAC] THEN POP_ASSUM (LABEL_TAC "hpind") THEN REWRITE_TAC[MEM] THEN INTRO_TAC "!X; cons uniq qmem qmem' subf" THEN LABEL_ASM_CASES_TAC "hmemX" `MEM (h:form) X` THENL [REMOVE_THEN "hpind" (MP_TAC o SPEC `X:form list`) THEN ASM_MESON_TAC[]; ALL_TAC] THEN LABEL_ASM_CASES_TAC "nhmemX" `MEM (Not h) X` THENL [REMOVE_THEN "hpind" (MP_TAC o SPEC `X:form list`) THEN ASM_MESON_TAC[]; ALL_TAC] THEN LABEL_ASM_CASES_TAC "consh" `CONSISTENT (CONS (h:form) X)` THENL [REMOVE_THEN "hpind" (MP_TAC o SPEC `CONS (h:form) X`) THEN ANTS_TAC THENL [ASM_REWRITE_TAC[NOREPETITION_CLAUSES; MEM] THEN CONJ_TAC THENL [ALL_TAC; ASM_MESON_TAC[]] THEN ASM_MESON_TAC[SUBLIST; SUBFORMULA_IMP_SUBSENTENCE]; ALL_TAC] THEN INTRO_TAC "@M. max sub" THEN EXISTS_TAC `M:form list` THEN ASM_REWRITE_TAC[] THEN REMOVE_THEN "sub" MP_TAC THEN REWRITE_TAC[SUBLIST; MEM] THEN MESON_TAC[]; ALL_TAC] THEN REMOVE_THEN "hpind" (MP_TAC o SPEC `CONS (Not h) X`) THEN ANTS_TAC THENL [ASM_REWRITE_TAC[NOREPETITION_CLAUSES] THEN CONJ_TAC THENL [ASM_MESON_TAC[CONSISTENT_EM]; ALL_TAC] THEN REWRITE_TAC[MEM] THEN ASM_MESON_TAC[SUBLIST; SUBSENTENCE_RULES]; ALL_TAC] THEN INTRO_TAC "@M. max sub" THEN EXISTS_TAC `M:form list` THEN ASM_REWRITE_TAC[] THEN REMOVE_THEN "sub" MP_TAC THEN REWRITE_TAC[SUBLIST; MEM] THEN MESON_TAC[]);; let NONEMPTY_MAXIMAL_CONSISTENT = prove (`!p. ~ |-- p ==> ?M. MAXIMAL_CONSISTENT p M /\ MEM (Not p) M /\ (!q. MEM q M ==> q SUBSENTENCE p)`, INTRO_TAC "!p; p" THEN MP_TAC (SPECL [`p:form`; `[Not p]`] EXTEND_MAXIMAL_CONSISTENT) THEN ANTS_TAC THENL [CONJ_TAC THENL [REWRITE_TAC[CONSISTENT_SING] THEN ASM_MESON_TAC[GL_DOUBLENEG_CL]; ALL_TAC] THEN GEN_TAC THEN REWRITE_TAC[MEM] THEN REPEAT STRIP_TAC THEN FIRST_X_ASSUM SUBST_VAR_TAC THEN MESON_TAC[SUBFORMULA_IMP_NEG_SUBSENTENCE; SUBFORMULA_REFL]; ALL_TAC] THEN STRIP_TAC THEN EXISTS_TAC `M:form list` THEN ASM_REWRITE_TAC[] THEN ASM_MESON_TAC[SUBLIST; MEM]);; let GL_STANDARD_REL = new_definition `GL_STANDARD_REL p w x <=> MAXIMAL_CONSISTENT p w /\ (!q. MEM q w ==> q SUBSENTENCE p) /\ MAXIMAL_CONSISTENT p x /\ (!q. MEM q x ==> q SUBSENTENCE p) /\ (!B. MEM (Box B) w ==> MEM (Box B) x /\ MEM B x) /\ (?E. MEM (Box E) x /\ MEM (Not (Box E)) w)`;; let ITF_MAXIMAL_CONSISTENT = prove (`!p. ~ |-- p ==> ITF ({M | MAXIMAL_CONSISTENT p M /\ (!q. MEM q M ==> q SUBSENTENCE p)}, GL_STANDARD_REL p)`, INTRO_TAC "!p; p" THEN REWRITE_TAC[ITF] THEN Nonempty CONJ_TAC THENL [REWRITE_TAC[GSYM MEMBER_NOT_EMPTY; IN_ELIM_THM] THEN ASM_MESON_TAC[NONEMPTY_MAXIMAL_CONSISTENT]; ALL_TAC] THEN CONJ_TAC THENL [REWRITE_TAC[GL_STANDARD_REL; IN_ELIM_THM] THEN MESON_TAC[]; ALL_TAC] THEN CONJ_TAC THENL [MATCH_MP_TAC FINITE_SUBSET THEN EXISTS_TAC `{l | NOREPETITION l /\ !q. MEM q l ==> q IN {q | q SUBSENTENCE p}}` THEN CONJ_TAC THENL [MATCH_MP_TAC FINITE_NOREPETITION THEN POP_ASSUM_LIST (K ALL_TAC) THEN SUBGOAL_THEN `{q | q SUBSENTENCE p} = {q | q SUBFORMULA p} UNION IMAGE (Not) {q | q SUBFORMULA p}` SUBST1_TAC THENL [REWRITE_TAC[GSYM SUBSET_ANTISYM_EQ; SUBSET; FORALL_IN_UNION; FORALL_IN_GSPEC; FORALL_IN_IMAGE] THEN REWRITE_TAC[IN_UNION; IN_ELIM_THM; SUBSENTENCE_RULES] THEN GEN_TAC THEN GEN_REWRITE_TAC LAND_CONV [SUBSENTENCE_CASES] THEN DISCH_THEN STRUCT_CASES_TAC THEN ASM_REWRITE_TAC[] THEN DISJ2_TAC THEN MATCH_MP_TAC FUN_IN_IMAGE THEN ASM SET_TAC []; ALL_TAC] THEN REWRITE_TAC[FINITE_UNION; FINITE_SUBFORMULA] THEN MATCH_MP_TAC FINITE_IMAGE THEN REWRITE_TAC[FINITE_SUBFORMULA]; ALL_TAC] THEN REWRITE_TAC[SUBSET; IN_ELIM_THM; MAXIMAL_CONSISTENT] THEN GEN_TAC THEN STRIP_TAC THEN ASM_REWRITE_TAC[]; ALL_TAC] THEN Irreflexive CONJ_TAC THENL [REWRITE_TAC[FORALL_IN_GSPEC; GL_STANDARD_REL] THEN INTRO_TAC "!M; M sub" THEN ASM_REWRITE_TAC[] THEN INTRO_TAC "_ (@E. E1 E2)" THEN SUBGOAL_THEN `~ CONSISTENT M` (fun th -> ASM_MESON_TAC[th; MAXIMAL_CONSISTENT]) THEN MATCH_MP_TAC CONSISTENT_NC THEN ASM_MESON_TAC[]; ALL_TAC] THEN REWRITE_TAC[IN_ELIM_THM; GL_STANDARD_REL] THEN INTRO_TAC "!x y z; (x1 x2) (y1 y2) (z1 z2) +" THEN ASM_REWRITE_TAC[] THEN ASM_MESON_TAC[]);; let ACCESSIBILITY_LEMMA = let MEM_FLATMAP_LEMMA = prove (`!p l. MEM p (FLATMAP (\x. match x with Box c -> [Box c] | _ -> []) l) <=> (?q. p = Box q /\ MEM p l)`, GEN_TAC THEN LIST_INDUCT_TAC THEN REWRITE_TAC[MEM; FLATMAP] THEN REWRITE_TAC[MEM_APPEND] THEN ASM_CASES_TAC `?c. h = Box c` THENL [POP_ASSUM (CHOOSE_THEN SUBST_VAR_TAC) THEN ASM_REWRITE_TAC[MEM] THEN MESON_TAC[]; ALL_TAC] THEN SUBGOAL_THEN `~ MEM p (match h with Box c -> [Box c] | _ -> [])` (fun th -> ASM_REWRITE_TAC[th]) THENL [POP_ASSUM MP_TAC THEN STRUCT_CASES_TAC (SPEC `h:form` (cases "form")) THEN REWRITE_TAC[MEM; distinctness "form"; injectivity "form"] THEN MESON_TAC[]; ALL_TAC] THEN POP_ASSUM (fun th -> MESON_TAC[th])) and CONJLIST_FLATMAP_DOT_BOX_LEMMA = prove (`!w. |-- (CONJLIST (FLATMAP (\x. match x with Box c -> [Box c] | _ -> []) w) --> CONJLIST (MAP (Box) (FLATMAP (\x. match x with Box c -> [c; Box c] | _ -> []) w)))`, LIST_INDUCT_TAC THENL [REWRITE_TAC[FLATMAP; MAP; GL_imp_refl_th]; ALL_TAC] THEN REWRITE_TAC[FLATMAP; MAP_APPEND] THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `CONJLIST (match h with Box c -> [Box c] | _ -> []) && CONJLIST (FLATMAP (\x. match x with Box c -> [Box c] | _ -> []) t)` THEN CONJ_TAC THENL [MATCH_MP_TAC GL_iff_imp1 THEN MATCH_ACCEPT_TAC CONJLIST_APPEND; ALL_TAC] THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `CONJLIST (MAP (Box) (match h with Box c -> [c; Box c] | _ -> [])) && CONJLIST (MAP (Box) (FLATMAP (\x. match x with Box c -> [c; Box c] | _ -> []) t))` THEN CONJ_TAC THENL [ALL_TAC; MATCH_MP_TAC GL_iff_imp2 THEN MATCH_ACCEPT_TAC CONJLIST_APPEND] THEN MATCH_MP_TAC GL_and_intro THEN CONJ_TAC THENL [ALL_TAC; ASM_MESON_TAC[GL_imp_trans; GL_and_right_th]] THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `CONJLIST (match h with Box c -> [Box c] | _ -> [])` THEN CONJ_TAC THENL [MATCH_ACCEPT_TAC GL_and_left_th; ALL_TAC] THEN POP_ASSUM (K ALL_TAC) THEN STRUCT_CASES_TAC (SPEC `h:form` (cases "form")) THEN REWRITE_TAC[distinctness "form"; MAP; GL_imp_refl_th] THEN REWRITE_TAC[CONJLIST; NOT_CONS_NIL] THEN MATCH_ACCEPT_TAC GL_dot_box) in prove (`!p M w q. ~ |-- p /\ MAXIMAL_CONSISTENT p M /\ (!q. MEM q M ==> q SUBSENTENCE p) /\ MAXIMAL_CONSISTENT p w /\ (!q. MEM q w ==> q SUBSENTENCE p) /\ MEM (Not p) M /\ Box q SUBFORMULA p /\ (!x. GL_STANDARD_REL p w x ==> MEM q x) ==> MEM (Box q) w`, REPEAT GEN_TAC THEN INTRO_TAC "p maxM subM maxw subw notp boxq rrr" THEN REFUTE_THEN (LABEL_TAC "contra") THEN REMOVE_THEN "rrr" MP_TAC THEN REWRITE_TAC[NOT_FORALL_THM] THEN CLAIM_TAC "consistent_X" `CONSISTENT (CONS (Not q) (CONS (Box q) (FLATMAP (\x. match x with Box c -> [c; Box c] | _ -> []) w)))` THENL [REMOVE_THEN "contra" MP_TAC THEN REWRITE_TAC[CONSISTENT; CONTRAPOS_THM] THEN INTRO_TAC "incons" THEN MATCH_MP_TAC MAXIMAL_CONSISTENT_LEMMA THEN MAP_EVERY EXISTS_TAC [`p:form`; `FLATMAP (\x. match x with Box c -> [Box c] | _ -> []) w`] THEN ASM_REWRITE_TAC[] THEN CONJ_TAC THENL [GEN_TAC THEN REWRITE_TAC[MEM_FLATMAP_LEMMA] THEN MESON_TAC[]; ALL_TAC] THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `Box(Box q --> q)` THEN REWRITE_TAC[GL_axiom_lob] THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `CONJLIST (MAP (Box) (FLATMAP (\x. match x with Box c -> [c; Box c] | _ -> []) w))` THEN CONJ_TAC THENL [REWRITE_TAC[CONJLIST_FLATMAP_DOT_BOX_LEMMA]; ALL_TAC] THEN CLAIM_TAC "XIMP" `!x y l. |-- (Not (Not y && CONJLIST (CONS x l))) ==> |-- ((CONJLIST (MAP (Box) l)) --> Box(x --> y))` THENL [REPEAT STRIP_TAC THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `Box (CONJLIST l)` THEN CONJ_TAC THENL [MESON_TAC[CONJLIST_MAP_BOX;GL_iff_imp1]; ALL_TAC] THEN MATCH_MP_TAC GL_imp_box THEN MATCH_MP_TAC GL_shunt THEN ONCE_REWRITE_TAC[GSYM GL_contrapos_eq] THEN MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `CONJLIST (CONS x l) --> False` THEN CONJ_TAC THENL [ASM_MESON_TAC[GL_shunt; GL_not_def]; MATCH_MP_TAC GL_imp_trans THEN EXISTS_TAC `Not (CONJLIST(CONS x l))` THEN CONJ_TAC THENL [MESON_TAC[GL_axiom_not;GL_iff_imp2]; MESON_TAC[GL_contrapos_eq;CONJLIST_CONS; GL_and_comm_th; GL_iff_imp2; GL_iff_imp1; GL_imp_trans]]]; ALL_TAC] THEN POP_ASSUM MATCH_MP_TAC THEN HYP_TAC "incons" (REWRITE_RULE[CONSISTENT]) THEN HYP_TAC "incons" (ONCE_REWRITE_RULE[CONJLIST]) THEN HYP_TAC "incons" (REWRITE_RULE[NOT_CONS_NIL]) THEN POP_ASSUM MATCH_ACCEPT_TAC; ALL_TAC] THEN MP_TAC (SPECL [`p:form`; `CONS (Not q) (CONS (Box q) (FLATMAP (\x. match x with Box c -> [c; Box c] | _ -> []) w))`] EXTEND_MAXIMAL_CONSISTENT) THEN ANTS_TAC THENL [ASM_REWRITE_TAC[MEM] THEN GEN_TAC THEN STRIP_TAC THEN REPEAT (FIRST_X_ASSUM SUBST_VAR_TAC) THENL [MATCH_MP_TAC SUBFORMULA_IMP_NEG_SUBSENTENCE THEN REWRITE_TAC[UNWIND_THM1] THEN HYP MESON_TAC "boxq" [SUBFORMULA_TRANS; SUBFORMULA_INVERSION; SUBFORMULA_REFL]; MATCH_MP_TAC SUBFORMULA_IMP_SUBSENTENCE THEN ASM_REWRITE_TAC[]; ALL_TAC] THEN POP_ASSUM (DESTRUCT_TAC "@y. +" o REWRITE_RULE[MEM_FLATMAP]) THEN STRUCT_CASES_TAC (SPEC `y:form` (cases "form")) THEN REWRITE_TAC[MEM] THEN STRIP_TAC THEN FIRST_X_ASSUM SUBST_VAR_TAC THENL [MATCH_MP_TAC SUBFORMULA_IMP_SUBSENTENCE THEN CLAIM_TAC "rmk" `Box a SUBSENTENCE p` THENL [POP_ASSUM MP_TAC THEN HYP MESON_TAC "subw" []; ALL_TAC] THEN HYP_TAC "rmk" (REWRITE_RULE[SUBSENTENCE_CASES; distinctness "form"]) THEN TRANS_TAC SUBFORMULA_TRANS `Box a` THEN ASM_REWRITE_TAC[] THEN MESON_TAC[SUBFORMULA_INVERSION; SUBFORMULA_REFL]; POP_ASSUM MP_TAC THEN HYP MESON_TAC "subw" []]; ALL_TAC] THEN INTRO_TAC "@X. maxX subX subl" THEN EXISTS_TAC `X:form list` THEN ASM_REWRITE_TAC[GL_STANDARD_REL; NOT_IMP] THEN CONJ_TAC THENL [CONJ_TAC THENL [INTRO_TAC "!B; B" THEN HYP_TAC "subl" (REWRITE_RULE[SUBLIST]) THEN CONJ_TAC THEN REMOVE_THEN "subl" MATCH_MP_TAC THEN REWRITE_TAC[MEM; distinctness "form"; injectivity "form"] THENL [DISJ2_TAC THEN REWRITE_TAC[MEM_FLATMAP] THEN EXISTS_TAC `Box B` THEN ASM_REWRITE_TAC[MEM]; DISJ2_TAC THEN DISJ2_TAC THEN REWRITE_TAC[MEM_FLATMAP] THEN EXISTS_TAC `Box B` THEN ASM_REWRITE_TAC[MEM]]; ALL_TAC] THEN EXISTS_TAC `q:form` THEN HYP_TAC "subl" (REWRITE_RULE[SUBLIST]) THEN CONJ_TAC THENL [REMOVE_THEN "subl" MATCH_MP_TAC THEN REWRITE_TAC[MEM]; ALL_TAC] THEN ASM_MESON_TAC[MAXIMAL_CONSISTENT_MEM_NOT]; ALL_TAC] THEN HYP_TAC "subl: +" (SPEC `Not q` o REWRITE_RULE[SUBLIST]) THEN REWRITE_TAC[MEM] THEN IMP_REWRITE_TAC[GSYM MAXIMAL_CONSISTENT_MEM_NOT] THEN SIMP_TAC[] THEN INTRO_TAC "_" THEN MATCH_MP_TAC SUBFORMULA_TRANS THEN EXISTS_TAC `Box q` THEN ASM_REWRITE_TAC[] THEN ASM_MESON_TAC[SUBFORMULA_TRANS; SUBFORMULA_INVERSION; SUBFORMULA_REFL]);; Modal completeness theorem for GL . let GL_COUNTERMODEL = prove (`!M p. ~(|-- p) /\ MAXIMAL_CONSISTENT p M /\ MEM (Not p) M /\ (!q. MEM q M ==> q SUBSENTENCE p) ==> ~holds ({M | MAXIMAL_CONSISTENT p M /\ (!q. MEM q M ==> q SUBSENTENCE p)}, GL_STANDARD_REL p) (\a w. Atom a SUBFORMULA p /\ MEM (Atom a) w) p M`, REPEAT GEN_TAC THEN STRIP_TAC THEN MP_TAC (ISPECL [`{M | MAXIMAL_CONSISTENT p M /\ (!q. MEM q M ==> q SUBSENTENCE p)}`; `GL_STANDARD_REL p`; `p:form`; `\a w. Atom a SUBFORMULA p /\ MEM (Atom a) w`; `p:form`] GL_truth_lemma) THEN ANTS_TAC THENL [ASM_REWRITE_TAC[SUBFORMULA_REFL; GL_STANDARD_MODEL; GL_STANDARD_FRAME] THEN ASM_SIMP_TAC[ITF_MAXIMAL_CONSISTENT] THEN REWRITE_TAC[IN_ELIM_THM] THEN CONJ_TAC THENL [ALL_TAC; MESON_TAC[]] THEN INTRO_TAC "!q w; boxq w subf" THEN EQ_TAC THENL [ASM_REWRITE_TAC[GL_STANDARD_REL] THEN SIMP_TAC[]; ALL_TAC] THEN INTRO_TAC "hp" THEN MATCH_MP_TAC ACCESSIBILITY_LEMMA THEN MAP_EVERY EXISTS_TAC [`p:form`; `M:form list`] THEN ASM_REWRITE_TAC[]; ALL_TAC] THEN DISCH_THEN (MP_TAC o SPEC `M:form list`) THEN ANTS_TAC THENL [ASM_REWRITE_TAC[IN_ELIM_THM]; ALL_TAC] THEN DISCH_THEN (SUBST1_TAC o GSYM) THEN ASM_MESON_TAC[MAXIMAL_CONSISTENT; CONSISTENT_NC]);; let GL_COUNTERMODEL_ALT = prove (`!p. ~(|-- p) ==> ~holds_in ({M | MAXIMAL_CONSISTENT p M /\ (!q. MEM q M ==> q SUBSENTENCE p)}, GL_STANDARD_REL p) p`, INTRO_TAC "!p; p" THEN REWRITE_TAC[holds_in; NOT_FORALL_THM; NOT_IMP; IN_ELIM_THM] THEN EXISTS_TAC `\a w. Atom a SUBFORMULA p /\ MEM (Atom a) w` THEN DESTRUCT_TAC "@M. max mem subf" (MATCH_MP NONEMPTY_MAXIMAL_CONSISTENT (ASSUME `~ |-- p`)) THEN EXISTS_TAC `M:form list` THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC GL_COUNTERMODEL THEN ASM_REWRITE_TAC[]);; let COMPLETENESS_THEOREM = prove (`!p. ITF:(form list->bool)#(form list->form list->bool)->bool |= p ==> |-- p`, GEN_TAC THEN GEN_REWRITE_TAC I [GSYM CONTRAPOS_THM] THEN INTRO_TAC "p" THEN REWRITE_TAC[valid; NOT_FORALL_THM] THEN EXISTS_TAC `({M | MAXIMAL_CONSISTENT p M /\ (!q. MEM q M ==> q SUBSENTENCE p)}, GL_STANDARD_REL p)` THEN REWRITE_TAC[NOT_IMP] THEN CONJ_TAC THENL [MATCH_MP_TAC ITF_MAXIMAL_CONSISTENT THEN ASM_REWRITE_TAC[]; ALL_TAC] THEN MATCH_MP_TAC GL_COUNTERMODEL_ALT THEN ASM_REWRITE_TAC[]);; Modal completeness for GL for models on a generic ( infinite ) domain . let COMPLETENESS_THEOREM_GEN = prove (`!p. INFINITE (:A) /\ ITF:(A->bool)#(A->A->bool)->bool |= p ==> |-- p`, SUBGOAL_THEN `INFINITE (:A) ==> !p. ITF:(A->bool)#(A->A->bool)->bool |= p ==> ITF:(form list->bool)#(form list->form list->bool)->bool |= p` (fun th -> MESON_TAC[th; COMPLETENESS_THEOREM]) THEN INTRO_TAC "A" THEN MATCH_MP_TAC BISIMILAR_VALID THEN REPEAT GEN_TAC THEN INTRO_TAC "itf1 w1" THEN CLAIM_TAC "@f. inj" `?f:form list->A. (!x y. f x = f y ==> x = y)` THENL [SUBGOAL_THEN `(:form list) <=_c (:A)` MP_TAC THENL [TRANS_TAC CARD_LE_TRANS `(:num)` THEN ASM_REWRITE_TAC[GSYM INFINITE_CARD_LE; GSYM COUNTABLE_ALT] THEN ASM_SIMP_TAC[COUNTABLE_LIST; COUNTABLE_FORM]; REWRITE_TAC[le_c; IN_UNIV]]; ALL_TAC] THEN MAP_EVERY EXISTS_TAC [`IMAGE (f:form list->A) W1`; `\x y:A. ?a b:form list. a IN W1 /\ b IN W1 /\ x = f a /\ y = f b /\ R1 a b`; `\a:string w:A. ?x:form list. w = f x /\ V1 a x`; `f (w1:form list):A`] THEN CONJ_TAC THENL [REWRITE_TAC[ITF] THEN CONJ_TAC THENL [HYP SET_TAC "w1" []; ALL_TAC] THEN CONJ_TAC THENL [SET_TAC[]; ALL_TAC] THEN CONJ_TAC THENL [ASM_MESON_TAC[ITF; FINITE_IMAGE]; ALL_TAC] THEN CONJ_TAC THENL [REWRITE_TAC[FORALL_IN_IMAGE] THEN HYP_TAC "itf1: _ _ _ irrefl _" (REWRITE_RULE[ITF]) THEN HYP MESON_TAC " irrefl inj" []; ALL_TAC] THEN REWRITE_TAC[IMP_CONJ; RIGHT_FORALL_IMP_THM; FORALL_IN_IMAGE] THEN HYP_TAC "itf1: _ _ _ _ trans" (REWRITE_RULE[ITF]) THEN HYP MESON_TAC " trans inj" []; ALL_TAC] THEN REWRITE_TAC[BISIMILAR] THEN EXISTS_TAC `\w1:form list w2:A. w1 IN W1 /\ w2 = f w1` THEN ASM_REWRITE_TAC[BISIMIMULATION] THEN REMOVE_THEN "w1" (K ALL_TAC) THEN REPEAT GEN_TAC THEN STRIP_TAC THEN FIRST_X_ASSUM SUBST_VAR_TAC THEN ASM_SIMP_TAC[FUN_IN_IMAGE] THEN CONJ_TAC THENL [HYP MESON_TAC "inj" []; ALL_TAC] THEN CONJ_TAC THENL [REPEAT STRIP_TAC THEN REWRITE_TAC[EXISTS_IN_IMAGE] THEN ASM_MESON_TAC[ITF]; ALL_TAC] THEN ASM_MESON_TAC[]);; Simple decision procedure for GL . let GL_TAC : tactic = MATCH_MP_TAC COMPLETENESS_THEOREM THEN REWRITE_TAC[valid; FORALL_PAIR_THM; holds_in; holds; ITF; GSYM MEMBER_NOT_EMPTY] THEN MESON_TAC[];; let GL_RULE tm = prove(tm, REPEAT GEN_TAC THEN GL_TAC);; GL_RULE `!p q r. |-- (p && q && r --> p && r)`;; GL_RULE `!p. |-- (Box p --> Box (Box p))`;; GL_RULE `!p q. |-- (Box (p --> q) && Box p --> Box q)`;; GL_RULE ` ! ( Box p -- > p ) -- > Box p ) ` ; ; GL_RULE ` |-- ( Box ( Box False -- > False ) -- > Box False ) ` ; ; GL_RULE `!p q. |-- (Box (p <-> q) --> (Box p <-> Box q))`;; let SET_OF_LIST_EQ_IMP_MEM = prove (`!l m x:A. set_of_list l = set_of_list m /\ MEM x l ==> MEM x m`, REPEAT GEN_TAC THEN REWRITE_TAC[GSYM IN_SET_OF_LIST] THEN MESON_TAC[]);; let SET_OF_LIST_EQ_CONJLIST = prove (`!X Y. set_of_list X = set_of_list Y ==> |-- (CONJLIST X --> CONJLIST Y)`, REPEAT STRIP_TAC THEN MATCH_MP_TAC CONJLIST_IMP THEN INTRO_TAC "!p; p" THEN EXISTS_TAC `p:form` THEN REWRITE_TAC[GL_imp_refl_th] THEN ASM_MESON_TAC[SET_OF_LIST_EQ_IMP_MEM]);; let SET_OF_LIST_EQ_CONJLIST_EQ = prove (`!X Y. set_of_list X = set_of_list Y ==> |-- (CONJLIST X <-> CONJLIST Y)`, REWRITE_TAC[GL_iff_def] THEN MESON_TAC[SET_OF_LIST_EQ_CONJLIST]);; let SET_OF_LIST_EQ_CONSISTENT = prove (`!X Y. set_of_list X = set_of_list Y /\ CONSISTENT X ==> CONSISTENT Y`, REWRITE_TAC[CONSISTENT] THEN INTRO_TAC "!X Y; eq hp; p" THEN REMOVE_THEN "hp" MP_TAC THEN REWRITE_TAC[] THEN MATCH_MP_TAC GL_modusponens THEN EXISTS_TAC `Not (CONJLIST Y)` THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC GL_contrapos THEN MATCH_MP_TAC SET_OF_LIST_EQ_CONJLIST THEN ASM_REWRITE_TAC[]);; let SET_OF_LIST_EQ_MAXIMAL_CONSISTENT = prove (`!p X Y. set_of_list X = set_of_list Y /\ NOREPETITION Y /\ MAXIMAL_CONSISTENT p X ==> MAXIMAL_CONSISTENT p Y`, REWRITE_TAC[MAXIMAL_CONSISTENT] THEN REPEAT STRIP_TAC THENL [ASM_MESON_TAC[SET_OF_LIST_EQ_CONSISTENT]; ASM_REWRITE_TAC[]; ASM_MESON_TAC[SET_OF_LIST_EQ_IMP_MEM]]);; let SET_OF_LIST_EQ_GL_STANDARD_REL = prove (`!p u1 u2 w1 w2. set_of_list u1 = set_of_list w1 /\ NOREPETITION w1 /\ set_of_list u2 = set_of_list w2 /\ NOREPETITION w2 /\ GL_STANDARD_REL p u1 u2 ==> GL_STANDARD_REL p w1 w2`, REPEAT GEN_TAC THEN REWRITE_TAC[GL_STANDARD_REL] THEN STRIP_TAC THEN CONJ_TAC THENL [MATCH_MP_TAC SET_OF_LIST_EQ_MAXIMAL_CONSISTENT THEN ASM_MESON_TAC[]; ALL_TAC] THEN CONJ_TAC THENL [ASM_MESON_TAC[SET_OF_LIST_EQ_IMP_MEM]; ALL_TAC] THEN CONJ_TAC THENL [MATCH_MP_TAC SET_OF_LIST_EQ_MAXIMAL_CONSISTENT THEN ASM_MESON_TAC[]; ALL_TAC] THEN ASM_MESON_TAC[SET_OF_LIST_EQ_IMP_MEM]);; Countermodel using set of formulae ( instead of lists of formulae ) . let GL_STDWORLDS_RULES,GL_STDWORLDS_INDUCT,GL_STDWORLDS_CASES = new_inductive_set `!M. MAXIMAL_CONSISTENT p M /\ (!q. MEM q M ==> q SUBSENTENCE p) ==> set_of_list M IN GL_STDWORLDS p`;; let GL_STDREL_RULES,GL_STDREL_INDUCT,GL_STDREL_CASES = new_inductive_definition `!w1 w2. GL_STANDARD_REL p w1 w2 ==> GL_STDREL p (set_of_list w1) (set_of_list w2)`;; let GL_STDREL_IMP_GL_STDWORLDS = prove (`!p w1 w2. GL_STDREL p w1 w2 ==> w1 IN GL_STDWORLDS p /\ w2 IN GL_STDWORLDS p`, GEN_TAC THEN MATCH_MP_TAC GL_STDREL_INDUCT THEN REWRITE_TAC[GL_STANDARD_REL] THEN REPEAT STRIP_TAC THEN MATCH_MP_TAC GL_STDWORLDS_RULES THEN ASM_REWRITE_TAC[]);; let BISIMIMULATION_SET_OF_LIST = prove (`!p. BISIMIMULATION ( {M | MAXIMAL_CONSISTENT p M /\ (!q. MEM q M ==> q SUBSENTENCE p)}, GL_STANDARD_REL p, (\a w. Atom a SUBFORMULA p /\ MEM (Atom a) w) ) (GL_STDWORLDS p, GL_STDREL p, (\a w. Atom a SUBFORMULA p /\ Atom a IN w)) (\w1 w2. MAXIMAL_CONSISTENT p w1 /\ (!q. MEM q w1 ==> q SUBSENTENCE p) /\ w2 IN GL_STDWORLDS p /\ set_of_list w1 = w2)`, GEN_TAC THEN REWRITE_TAC[BISIMIMULATION] THEN REPEAT GEN_TAC THEN STRIP_TAC THEN ASM_REWRITE_TAC[IN_ELIM_THM] THEN CONJ_TAC THENL [GEN_TAC THEN FIRST_X_ASSUM SUBST_VAR_TAC THEN REWRITE_TAC[IN_SET_OF_LIST]; ALL_TAC] THEN CONJ_TAC THENL [INTRO_TAC "![u1]; w1u1" THEN EXISTS_TAC `set_of_list u1:form->bool` THEN HYP_TAC "w1u1 -> hp" (REWRITE_RULE[GL_STANDARD_REL]) THEN ASM_REWRITE_TAC[] THEN CONJ_TAC THENL [MATCH_MP_TAC GL_STDWORLDS_RULES THEN ASM_REWRITE_TAC[]; ALL_TAC] THEN CONJ_TAC THENL [MATCH_MP_TAC GL_STDWORLDS_RULES THEN ASM_REWRITE_TAC[]; ALL_TAC] THEN FIRST_X_ASSUM SUBST_VAR_TAC THEN MATCH_MP_TAC GL_STDREL_RULES THEN ASM_REWRITE_TAC[]; ALL_TAC] THEN INTRO_TAC "![u2]; w2u2" THEN EXISTS_TAC `list_of_set u2:form list` THEN REWRITE_TAC[CONJ_ACI] THEN HYP_TAC "w2u2 -> @x2 y2. x2 y2 x2y2" (REWRITE_RULE[GL_STDREL_CASES]) THEN REPEAT (FIRST_X_ASSUM SUBST_VAR_TAC) THEN SIMP_TAC[SET_OF_LIST_OF_SET; FINITE_SET_OF_LIST] THEN SIMP_TAC[MEM_LIST_OF_SET; FINITE_SET_OF_LIST; IN_SET_OF_LIST] THEN CONJ_TAC THENL [HYP_TAC "x2y2 -> hp" (REWRITE_RULE[GL_STANDARD_REL]) THEN ASM_REWRITE_TAC[]; ALL_TAC] THEN CONJ_TAC THENL [MATCH_MP_TAC SET_OF_LIST_EQ_GL_STANDARD_REL THEN EXISTS_TAC `x2:form list` THEN EXISTS_TAC `y2:form list` THEN ASM_REWRITE_TAC[] THEN SIMP_TAC[NOREPETITION_LIST_OF_SET; FINITE_SET_OF_LIST] THEN SIMP_TAC[EXTENSION; IN_SET_OF_LIST; MEM_LIST_OF_SET; FINITE_SET_OF_LIST] THEN ASM_MESON_TAC[MAXIMAL_CONSISTENT]; ALL_TAC] THEN CONJ_TAC THENL [ASM_MESON_TAC[GL_STDREL_IMP_GL_STDWORLDS]; ALL_TAC] THEN MATCH_MP_TAC SET_OF_LIST_EQ_MAXIMAL_CONSISTENT THEN EXISTS_TAC `y2:form list` THEN SIMP_TAC[NOREPETITION_LIST_OF_SET; FINITE_SET_OF_LIST] THEN SIMP_TAC[EXTENSION; IN_SET_OF_LIST; MEM_LIST_OF_SET; FINITE_SET_OF_LIST] THEN ASM_MESON_TAC[GL_STANDARD_REL]);; let GL_COUNTERMODEL_FINITE_SETS = prove (`!p. ~(|-- p) ==> ~holds_in (GL_STDWORLDS p, GL_STDREL p) p`, INTRO_TAC "!p; p" THEN DESTRUCT_TAC "@M. max mem subf" (MATCH_MP NONEMPTY_MAXIMAL_CONSISTENT (ASSUME `~ |-- p`)) THEN REWRITE_TAC[holds_in; NOT_FORALL_THM; NOT_IMP] THEN ASSUM_LIST (LABEL_TAC "hp" o MATCH_MP GL_COUNTERMODEL o end_itlist CONJ o rev) THEN EXISTS_TAC `\a w. Atom a SUBFORMULA p /\ Atom a IN w` THEN EXISTS_TAC `set_of_list M:form->bool` THEN CONJ_TAC THENL [MATCH_MP_TAC GL_STDWORLDS_RULES THEN ASM_REWRITE_TAC[]; ALL_TAC] THEN REMOVE_THEN "hp" MP_TAC THEN MATCH_MP_TAC (MESON[] `(p <=> q) ==> (~p ==> ~q)`) THEN MATCH_MP_TAC BISIMIMULATION_HOLDS THEN EXISTS_TAC `(\w1 w2. MAXIMAL_CONSISTENT p w1 /\ (!q. MEM q w1 ==> q SUBSENTENCE p) /\ w2 IN GL_STDWORLDS p /\ set_of_list w1 = w2)` THEN ASM_REWRITE_TAC[BISIMIMULATION_SET_OF_LIST] THEN MATCH_MP_TAC GL_STDWORLDS_RULES THEN ASM_REWRITE_TAC[]);;
368cda031c1a529001f8ea40d93b0b36aeb8870e1c8b27ffd33e06ea22785ea2
clojure-interop/google-cloud-clients
TextToSpeechSettings$Builder.clj
(ns com.google.cloud.texttospeech.v1beta1.TextToSpeechSettings$Builder "Builder for TextToSpeechSettings." (:refer-clojure :only [require comment defn ->]) (:import [com.google.cloud.texttospeech.v1beta1 TextToSpeechSettings$Builder])) (defn get-stub-settings-builder "returns: `com.google.cloud.texttospeech.v1beta1.stub.TextToSpeechStubSettings$Builder`" (^com.google.cloud.texttospeech.v1beta1.stub.TextToSpeechStubSettings$Builder [^TextToSpeechSettings$Builder this] (-> this (.getStubSettingsBuilder)))) (defn apply-to-all-unary-methods "Applies the given settings updater function to all of the unary API methods in this service. Note: This method does not support applying settings to streaming methods. settings-updater - `com.google.api.core.ApiFunction` returns: `com.google.cloud.texttospeech.v1beta1.TextToSpeechSettings$Builder` throws: java.lang.Exception" (^com.google.cloud.texttospeech.v1beta1.TextToSpeechSettings$Builder [^TextToSpeechSettings$Builder this ^com.google.api.core.ApiFunction settings-updater] (-> this (.applyToAllUnaryMethods settings-updater)))) (defn list-voices-settings "Returns the builder for the settings used for calls to listVoices. returns: `com.google.api.gax.rpc.UnaryCallSettings.Builder<com.google.cloud.texttospeech.v1beta1.ListVoicesRequest,com.google.cloud.texttospeech.v1beta1.ListVoicesResponse>`" (^com.google.api.gax.rpc.UnaryCallSettings.Builder [^TextToSpeechSettings$Builder this] (-> this (.listVoicesSettings)))) (defn synthesize-speech-settings "Returns the builder for the settings used for calls to synthesizeSpeech. returns: `com.google.api.gax.rpc.UnaryCallSettings.Builder<com.google.cloud.texttospeech.v1beta1.SynthesizeSpeechRequest,com.google.cloud.texttospeech.v1beta1.SynthesizeSpeechResponse>`" (^com.google.api.gax.rpc.UnaryCallSettings.Builder [^TextToSpeechSettings$Builder this] (-> this (.synthesizeSpeechSettings)))) (defn build "returns: `com.google.cloud.texttospeech.v1beta1.TextToSpeechSettings` throws: java.io.IOException" (^com.google.cloud.texttospeech.v1beta1.TextToSpeechSettings [^TextToSpeechSettings$Builder this] (-> this (.build))))
null
https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.texttospeech/src/com/google/cloud/texttospeech/v1beta1/TextToSpeechSettings%24Builder.clj
clojure
(ns com.google.cloud.texttospeech.v1beta1.TextToSpeechSettings$Builder "Builder for TextToSpeechSettings." (:refer-clojure :only [require comment defn ->]) (:import [com.google.cloud.texttospeech.v1beta1 TextToSpeechSettings$Builder])) (defn get-stub-settings-builder "returns: `com.google.cloud.texttospeech.v1beta1.stub.TextToSpeechStubSettings$Builder`" (^com.google.cloud.texttospeech.v1beta1.stub.TextToSpeechStubSettings$Builder [^TextToSpeechSettings$Builder this] (-> this (.getStubSettingsBuilder)))) (defn apply-to-all-unary-methods "Applies the given settings updater function to all of the unary API methods in this service. Note: This method does not support applying settings to streaming methods. settings-updater - `com.google.api.core.ApiFunction` returns: `com.google.cloud.texttospeech.v1beta1.TextToSpeechSettings$Builder` throws: java.lang.Exception" (^com.google.cloud.texttospeech.v1beta1.TextToSpeechSettings$Builder [^TextToSpeechSettings$Builder this ^com.google.api.core.ApiFunction settings-updater] (-> this (.applyToAllUnaryMethods settings-updater)))) (defn list-voices-settings "Returns the builder for the settings used for calls to listVoices. returns: `com.google.api.gax.rpc.UnaryCallSettings.Builder<com.google.cloud.texttospeech.v1beta1.ListVoicesRequest,com.google.cloud.texttospeech.v1beta1.ListVoicesResponse>`" (^com.google.api.gax.rpc.UnaryCallSettings.Builder [^TextToSpeechSettings$Builder this] (-> this (.listVoicesSettings)))) (defn synthesize-speech-settings "Returns the builder for the settings used for calls to synthesizeSpeech. returns: `com.google.api.gax.rpc.UnaryCallSettings.Builder<com.google.cloud.texttospeech.v1beta1.SynthesizeSpeechRequest,com.google.cloud.texttospeech.v1beta1.SynthesizeSpeechResponse>`" (^com.google.api.gax.rpc.UnaryCallSettings.Builder [^TextToSpeechSettings$Builder this] (-> this (.synthesizeSpeechSettings)))) (defn build "returns: `com.google.cloud.texttospeech.v1beta1.TextToSpeechSettings` throws: java.io.IOException" (^com.google.cloud.texttospeech.v1beta1.TextToSpeechSettings [^TextToSpeechSettings$Builder this] (-> this (.build))))
2e16cc44277b7559a7ab01b7184b58389b645e5f354c96e9c4f225117b253dfb
wireless-net/erlang-nommu
wxClipboardTextEvent.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2008 - 2013 . 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% %% This file is generated DO NOT EDIT %% @doc See external documentation: <a href="">wxClipboardTextEvent</a>. %% <dl><dt>Use {@link wxEvtHandler:connect/3.} with EventType:</dt> %% <dd><em>command_text_copy</em>, <em>command_text_cut</em>, <em>command_text_paste</em></dd></dl> %% See also the message variant {@link wxEvtHandler:wxClipboardText(). #wxClipboardText{}} event record type. %% %% <p>This class is derived (and can use functions) from: %% <br />{@link wxCommandEvent} %% <br />{@link wxEvent} %% </p> %% @type wxClipboardTextEvent(). An object reference, The representation is internal %% and can be changed without notice. It can't be used for comparsion %% stored on disc or distributed for use on other nodes. -module(wxClipboardTextEvent). -include("wxe.hrl"). -export([]). %% inherited exports -export([getClientData/1,getExtraLong/1,getId/1,getInt/1,getSelection/1,getSkipped/1, getString/1,getTimestamp/1,isChecked/1,isCommandEvent/1,isSelection/1, parent_class/1,resumePropagation/2,setInt/2,setString/2,shouldPropagate/1, skip/1,skip/2,stopPropagation/1]). -export_type([wxClipboardTextEvent/0]). %% @hidden parent_class(wxCommandEvent) -> true; parent_class(wxEvent) -> true; parent_class(_Class) -> erlang:error({badtype, ?MODULE}). -type wxClipboardTextEvent() :: wx:wx_object(). %% From wxCommandEvent %% @hidden setString(This,S) -> wxCommandEvent:setString(This,S). %% @hidden setInt(This,I) -> wxCommandEvent:setInt(This,I). %% @hidden isSelection(This) -> wxCommandEvent:isSelection(This). %% @hidden isChecked(This) -> wxCommandEvent:isChecked(This). %% @hidden getString(This) -> wxCommandEvent:getString(This). %% @hidden getSelection(This) -> wxCommandEvent:getSelection(This). %% @hidden getInt(This) -> wxCommandEvent:getInt(This). %% @hidden getExtraLong(This) -> wxCommandEvent:getExtraLong(This). %% @hidden getClientData(This) -> wxCommandEvent:getClientData(This). %% From wxEvent %% @hidden stopPropagation(This) -> wxEvent:stopPropagation(This). %% @hidden skip(This, Options) -> wxEvent:skip(This, Options). %% @hidden skip(This) -> wxEvent:skip(This). %% @hidden shouldPropagate(This) -> wxEvent:shouldPropagate(This). %% @hidden resumePropagation(This,PropagationLevel) -> wxEvent:resumePropagation(This,PropagationLevel). %% @hidden isCommandEvent(This) -> wxEvent:isCommandEvent(This). %% @hidden getTimestamp(This) -> wxEvent:getTimestamp(This). %% @hidden getSkipped(This) -> wxEvent:getSkipped(This). %% @hidden getId(This) -> wxEvent:getId(This).
null
https://raw.githubusercontent.com/wireless-net/erlang-nommu/79f32f81418e022d8ad8e0e447deaea407289926/lib/wx/src/gen/wxClipboardTextEvent.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% This file is generated DO NOT EDIT @doc See external documentation: <a href="">wxClipboardTextEvent</a>. <dl><dt>Use {@link wxEvtHandler:connect/3.} with EventType:</dt> <dd><em>command_text_copy</em>, <em>command_text_cut</em>, <em>command_text_paste</em></dd></dl> See also the message variant {@link wxEvtHandler:wxClipboardText(). #wxClipboardText{}} event record type. <p>This class is derived (and can use functions) from: <br />{@link wxCommandEvent} <br />{@link wxEvent} </p> @type wxClipboardTextEvent(). An object reference, The representation is internal and can be changed without notice. It can't be used for comparsion stored on disc or distributed for use on other nodes. inherited exports @hidden From wxCommandEvent @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden From wxEvent @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden
Copyright Ericsson AB 2008 - 2013 . 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(wxClipboardTextEvent). -include("wxe.hrl"). -export([]). -export([getClientData/1,getExtraLong/1,getId/1,getInt/1,getSelection/1,getSkipped/1, getString/1,getTimestamp/1,isChecked/1,isCommandEvent/1,isSelection/1, parent_class/1,resumePropagation/2,setInt/2,setString/2,shouldPropagate/1, skip/1,skip/2,stopPropagation/1]). -export_type([wxClipboardTextEvent/0]). parent_class(wxCommandEvent) -> true; parent_class(wxEvent) -> true; parent_class(_Class) -> erlang:error({badtype, ?MODULE}). -type wxClipboardTextEvent() :: wx:wx_object(). setString(This,S) -> wxCommandEvent:setString(This,S). setInt(This,I) -> wxCommandEvent:setInt(This,I). isSelection(This) -> wxCommandEvent:isSelection(This). isChecked(This) -> wxCommandEvent:isChecked(This). getString(This) -> wxCommandEvent:getString(This). getSelection(This) -> wxCommandEvent:getSelection(This). getInt(This) -> wxCommandEvent:getInt(This). getExtraLong(This) -> wxCommandEvent:getExtraLong(This). getClientData(This) -> wxCommandEvent:getClientData(This). stopPropagation(This) -> wxEvent:stopPropagation(This). skip(This, Options) -> wxEvent:skip(This, Options). skip(This) -> wxEvent:skip(This). shouldPropagate(This) -> wxEvent:shouldPropagate(This). resumePropagation(This,PropagationLevel) -> wxEvent:resumePropagation(This,PropagationLevel). isCommandEvent(This) -> wxEvent:isCommandEvent(This). getTimestamp(This) -> wxEvent:getTimestamp(This). getSkipped(This) -> wxEvent:getSkipped(This). getId(This) -> wxEvent:getId(This).
33df9c0b4c51e43addb607cfa749935344d4fd96c9fb5061fac7cdd0813857c2
sharplispers/montezuma
segment-merger.lisp
(in-package #:montezuma) (defclass segment-merger () ((directory :initarg :directory) (segment :initarg :name) (term-index-interval :initarg :term-index-interval) (readers :initform (make-array 0 :adjustable T :fill-pointer T)) (field-infos :initform '()) (freq-output :initform nil) (prox-output :initform nil) (term-infos-writer :initform nil) (queue :initform nil) (term-info :initform (make-instance 'term-info)) (skip-buffer :initform (make-instance 'ram-index-output :file (make-instance 'ram-file :name ""))) (skip-interval) (last-skip-doc) (last-skip-freq-pointer) (last-skip-prox-pointer)) (:default-initargs :term-index-interval *index-writer-default-term-index-interval*)) (defgeneric add-reader (segment-merger reader)) (defmethod add-reader ((self segment-merger) reader) (with-slots (readers) self (vector-push-extend reader readers))) (defgeneric segment-reader (segment-merger i)) (defmethod segment-reader ((self segment-merger) i) (with-slots (readers) self (aref readers i))) (defgeneric merge (segment-merger)) (defmethod merge ((self segment-merger)) (with-slots (field-infos) self (let ((value (merge-fields self))) (merge-terms self) (merge-norms self) (when (has-vectors-p field-infos) (merge-vectors self)) value))) (defgeneric close-readers (segment-merger)) (defmethod close-readers ((self segment-merger)) (dosequence (reader (slot-value self 'readers)) (close reader))) (defgeneric create-compound-file (segment-merger filename)) (defmethod create-compound-file ((self segment-merger) filename) (with-slots (directory segment field-infos) self (let ((cfs-writer (make-instance 'compound-file-writer :directory directory :file-name filename)) (files '())) (dolist (extension *index-compound-extensions*) (push (add-file-extension segment extension) files)) (dotimes (i (size field-infos)) (let ((fi (get-field field-infos i))) (when (and (field-indexed-p fi) (not (field-omit-norms-p fi))) (push (add-file-extension segment (format nil "f~D" i)) files)))) (when (has-vectors-p field-infos) (dolist (extension *index-vector-extensions*) (push (add-file-extension segment extension) files))) (dolist (file files) (add-file cfs-writer file)) (close cfs-writer) (reverse files)))) (defgeneric add-indexed (segment-merger reader field-infos field-names store-term-vectors store-position-with-term-vector store-offset-with-term-vector)) (defmethod add-indexed ((self segment-merger) reader field-infos field-names store-term-vectors store-position-with-term-vector store-offset-with-term-vector) (dosequence (field field-names) (add-field-info field-infos field :indexed-p T :store-term-vector store-term-vectors :store-position store-position-with-term-vector :store-offset store-offset-with-term-vector :omit-norms (not (has-norms-p reader field))))) (defgeneric merge-fields (segment-merger)) (defmethod merge-fields ((self segment-merger)) (with-slots (field-infos readers segment directory) self (setf field-infos (make-instance 'field-infos)) (let ((doc-count 0)) (dosequence (reader readers) (add-indexed self reader field-infos (get-field-names reader :term-vector-with-position-offset) T T T) (add-indexed self reader field-infos (get-field-names reader :term-vector-with-position) T T NIL) (add-indexed self reader field-infos (get-field-names reader :term-vector-with-offset) T NIL T) (add-indexed self reader field-infos (get-field-names reader :term-vector) T NIL NIL) (add-indexed self reader field-infos (get-field-names reader :indexed) NIL NIL NIL) (add-fields field-infos (get-field-names reader :unindexed) :indexed-p NIL)) (write-to-dir field-infos directory (add-file-extension segment "fnm")) (let ((fields-writer (make-instance 'fields-writer :directory directory :segment segment :field-infos field-infos))) (unwind-protect (dosequence (reader readers) (let ((max-doc (max-doc reader))) (dotimes (j max-doc) (unless (deleted-p reader j) (add-document fields-writer (get-document reader j)) (incf doc-count))))) (close fields-writer)) doc-count)))) (defgeneric merge-vectors (segment-merger)) (defmethod merge-vectors ((self segment-merger)) (with-slots (directory segment readers field-infos) self (let ((term-vectors-writer (make-instance 'term-vectors-writer :directory directory :segment segment :field-infos field-infos))) (unwind-protect (dosequence (reader readers) (let ((max-doc (max-doc reader))) (dotimes (doc-num max-doc) (unless (deleted-p reader doc-num) (add-all-doc-vectors term-vectors-writer (get-term-vectors reader doc-num)))))) (close term-vectors-writer))))) (defgeneric merge-terms (segment-merger)) (defmethod merge-terms ((self segment-merger)) (with-slots (directory segment readers freq-output prox-output term-infos-writer skip-interval queue field-infos term-index-interval) self (unwind-protect (progn (setf freq-output (create-output directory (add-file-extension segment "frq")) prox-output (create-output directory (add-file-extension segment "prx")) term-infos-writer (make-instance 'term-infos-writer :directory directory :segment segment :field-infos field-infos :interval term-index-interval)) (setf skip-interval (skip-interval term-infos-writer) queue (make-instance 'segment-merge-queue :max-size (length readers))) (merge-term-infos self)) (when freq-output (close freq-output)) (when prox-output (close prox-output)) (when term-infos-writer (close term-infos-writer)) (when queue (close queue))))) (defgeneric merge-term-infos (segment-merger)) (defmethod merge-term-infos ((self segment-merger)) (with-slots (readers queue) self (let ((base 0)) (dosequence (reader readers) (let* ((term-enum (terms reader)) (smi (make-instance 'segment-merge-info :base base :term-enum term-enum :reader reader))) (incf base (num-docs reader)) (if (next? smi) (queue-push queue smi) (close smi)))) (let ((match (make-array (length readers)))) (while (> (size queue) 0) (let ((match-size 0)) (setf (aref match match-size) (queue-pop queue)) (incf match-size) (let ((term-buffer (term-buffer (aref match 0))) (top (queue-top queue))) (while (and (not (null top)) (term-buffer= (term-buffer top) term-buffer)) (setf (aref match match-size) (queue-pop queue)) (incf match-size) (setf top (queue-top queue))) (merge-term-info self match match-size) (while (> match-size 0) (decf match-size) (let ((smi (aref match match-size))) (if (next? smi) (queue-push queue smi) (close smi))))))))))) (defgeneric merge-term-info (segment-merger smis n)) (defmethod merge-term-info ((self segment-merger) smis n) (with-slots (freq-output prox-output term-info term-infos-writer) self (let ((freq-pointer (pos freq-output)) (prox-pointer (pos prox-output)) (df (append-postings self smis n)) (skip-pointer (write-skip self))) (when (> df 0) (set-values term-info df freq-pointer prox-pointer (- skip-pointer freq-pointer)) (add-term term-infos-writer (term (term-buffer (aref smis 0))) term-info))))) (defgeneric append-postings (segment-merger smis n)) (defmethod append-postings ((self segment-merger) smis n) (with-slots (freq-output prox-output skip-interval) self (let ((last-doc 0) (df 0)) (reset-skip self) (dotimes (i n) (let* ((smi (aref smis i)) (postings (positions smi)) (base (base smi)) (doc-map (doc-map smi))) (seek postings (term-enum smi)) (while (next? postings) (let ((doc (doc postings))) (when (not (null doc-map)) (setf doc (aref doc-map doc))) (incf doc base) (when (< doc last-doc) (error "Docs out of order; current doc is ~S and previous doc is ~S" doc last-doc)) (incf df) (when (= (mod df skip-interval) 0) (buffer-skip self last-doc)) (let ((doc-code (ash (- doc last-doc) 1))) (setf last-doc doc) (let ((freq (freq postings))) (if (= freq 1) (write-vint freq-output (logior doc-code 1)) (progn (write-vint freq-output doc-code) (write-vint freq-output freq))) (let ((last-position 0)) (dotimes (j freq) (let ((position (next-position postings))) (write-vint prox-output (- position last-position)) (setf last-position position)))))))))) df))) (defgeneric reset-skip (segment-merger)) (defmethod reset-skip ((self segment-merger)) (with-slots (skip-buffer last-skip-doc last-skip-freq-pointer last-skip-prox-pointer freq-output prox-output) self (reset skip-buffer) (setf last-skip-doc 0) (setf last-skip-freq-pointer (pos freq-output)) (setf last-skip-prox-pointer (pos prox-output)))) (defgeneric buffer-skip (segment-merger doc)) (defmethod buffer-skip ((self segment-merger) doc) (with-slots (skip-buffer freq-output prox-output last-skip-prox-pointer last-skip-freq-pointer last-skip-doc) self (let ((freq-pointer (pos freq-output)) (prox-pointer (pos prox-output))) (write-vint skip-buffer (- doc last-skip-doc)) (write-vint skip-buffer (- freq-pointer last-skip-freq-pointer)) (write-vint skip-buffer (- prox-pointer last-skip-prox-pointer)) (setf last-skip-doc doc last-skip-freq-pointer freq-pointer last-skip-prox-pointer prox-pointer)))) (defgeneric write-skip (segment-merger)) (defmethod write-skip ((self segment-merger)) (with-slots (freq-output skip-buffer) self (let ((skip-pointer (pos freq-output))) (write-to skip-buffer freq-output) skip-pointer))) (defgeneric merge-norms (segment-merger)) (defmethod merge-norms ((self segment-merger)) (with-slots (field-infos readers segment directory) self (dotimes (i (size field-infos)) (let ((fi (get-field field-infos i))) (when (and (field-indexed-p fi) (not (field-omit-norms-p fi))) (let ((output (open-segment-file directory segment (format nil "f~S" i) :output))) (unwind-protect (dosequence (reader readers) (let* ((max-doc (max-doc reader)) (input (make-array max-doc))) (get-norms-into reader (field-name fi) input 0) (dotimes (k max-doc) (unless (deleted-p reader k) (write-byte output (aref input k)))))) (close output))))))))
null
https://raw.githubusercontent.com/sharplispers/montezuma/ee2129eece7065760de4ebbaeffaadcb27644738/src/index/segment-merger.lisp
lisp
(in-package #:montezuma) (defclass segment-merger () ((directory :initarg :directory) (segment :initarg :name) (term-index-interval :initarg :term-index-interval) (readers :initform (make-array 0 :adjustable T :fill-pointer T)) (field-infos :initform '()) (freq-output :initform nil) (prox-output :initform nil) (term-infos-writer :initform nil) (queue :initform nil) (term-info :initform (make-instance 'term-info)) (skip-buffer :initform (make-instance 'ram-index-output :file (make-instance 'ram-file :name ""))) (skip-interval) (last-skip-doc) (last-skip-freq-pointer) (last-skip-prox-pointer)) (:default-initargs :term-index-interval *index-writer-default-term-index-interval*)) (defgeneric add-reader (segment-merger reader)) (defmethod add-reader ((self segment-merger) reader) (with-slots (readers) self (vector-push-extend reader readers))) (defgeneric segment-reader (segment-merger i)) (defmethod segment-reader ((self segment-merger) i) (with-slots (readers) self (aref readers i))) (defgeneric merge (segment-merger)) (defmethod merge ((self segment-merger)) (with-slots (field-infos) self (let ((value (merge-fields self))) (merge-terms self) (merge-norms self) (when (has-vectors-p field-infos) (merge-vectors self)) value))) (defgeneric close-readers (segment-merger)) (defmethod close-readers ((self segment-merger)) (dosequence (reader (slot-value self 'readers)) (close reader))) (defgeneric create-compound-file (segment-merger filename)) (defmethod create-compound-file ((self segment-merger) filename) (with-slots (directory segment field-infos) self (let ((cfs-writer (make-instance 'compound-file-writer :directory directory :file-name filename)) (files '())) (dolist (extension *index-compound-extensions*) (push (add-file-extension segment extension) files)) (dotimes (i (size field-infos)) (let ((fi (get-field field-infos i))) (when (and (field-indexed-p fi) (not (field-omit-norms-p fi))) (push (add-file-extension segment (format nil "f~D" i)) files)))) (when (has-vectors-p field-infos) (dolist (extension *index-vector-extensions*) (push (add-file-extension segment extension) files))) (dolist (file files) (add-file cfs-writer file)) (close cfs-writer) (reverse files)))) (defgeneric add-indexed (segment-merger reader field-infos field-names store-term-vectors store-position-with-term-vector store-offset-with-term-vector)) (defmethod add-indexed ((self segment-merger) reader field-infos field-names store-term-vectors store-position-with-term-vector store-offset-with-term-vector) (dosequence (field field-names) (add-field-info field-infos field :indexed-p T :store-term-vector store-term-vectors :store-position store-position-with-term-vector :store-offset store-offset-with-term-vector :omit-norms (not (has-norms-p reader field))))) (defgeneric merge-fields (segment-merger)) (defmethod merge-fields ((self segment-merger)) (with-slots (field-infos readers segment directory) self (setf field-infos (make-instance 'field-infos)) (let ((doc-count 0)) (dosequence (reader readers) (add-indexed self reader field-infos (get-field-names reader :term-vector-with-position-offset) T T T) (add-indexed self reader field-infos (get-field-names reader :term-vector-with-position) T T NIL) (add-indexed self reader field-infos (get-field-names reader :term-vector-with-offset) T NIL T) (add-indexed self reader field-infos (get-field-names reader :term-vector) T NIL NIL) (add-indexed self reader field-infos (get-field-names reader :indexed) NIL NIL NIL) (add-fields field-infos (get-field-names reader :unindexed) :indexed-p NIL)) (write-to-dir field-infos directory (add-file-extension segment "fnm")) (let ((fields-writer (make-instance 'fields-writer :directory directory :segment segment :field-infos field-infos))) (unwind-protect (dosequence (reader readers) (let ((max-doc (max-doc reader))) (dotimes (j max-doc) (unless (deleted-p reader j) (add-document fields-writer (get-document reader j)) (incf doc-count))))) (close fields-writer)) doc-count)))) (defgeneric merge-vectors (segment-merger)) (defmethod merge-vectors ((self segment-merger)) (with-slots (directory segment readers field-infos) self (let ((term-vectors-writer (make-instance 'term-vectors-writer :directory directory :segment segment :field-infos field-infos))) (unwind-protect (dosequence (reader readers) (let ((max-doc (max-doc reader))) (dotimes (doc-num max-doc) (unless (deleted-p reader doc-num) (add-all-doc-vectors term-vectors-writer (get-term-vectors reader doc-num)))))) (close term-vectors-writer))))) (defgeneric merge-terms (segment-merger)) (defmethod merge-terms ((self segment-merger)) (with-slots (directory segment readers freq-output prox-output term-infos-writer skip-interval queue field-infos term-index-interval) self (unwind-protect (progn (setf freq-output (create-output directory (add-file-extension segment "frq")) prox-output (create-output directory (add-file-extension segment "prx")) term-infos-writer (make-instance 'term-infos-writer :directory directory :segment segment :field-infos field-infos :interval term-index-interval)) (setf skip-interval (skip-interval term-infos-writer) queue (make-instance 'segment-merge-queue :max-size (length readers))) (merge-term-infos self)) (when freq-output (close freq-output)) (when prox-output (close prox-output)) (when term-infos-writer (close term-infos-writer)) (when queue (close queue))))) (defgeneric merge-term-infos (segment-merger)) (defmethod merge-term-infos ((self segment-merger)) (with-slots (readers queue) self (let ((base 0)) (dosequence (reader readers) (let* ((term-enum (terms reader)) (smi (make-instance 'segment-merge-info :base base :term-enum term-enum :reader reader))) (incf base (num-docs reader)) (if (next? smi) (queue-push queue smi) (close smi)))) (let ((match (make-array (length readers)))) (while (> (size queue) 0) (let ((match-size 0)) (setf (aref match match-size) (queue-pop queue)) (incf match-size) (let ((term-buffer (term-buffer (aref match 0))) (top (queue-top queue))) (while (and (not (null top)) (term-buffer= (term-buffer top) term-buffer)) (setf (aref match match-size) (queue-pop queue)) (incf match-size) (setf top (queue-top queue))) (merge-term-info self match match-size) (while (> match-size 0) (decf match-size) (let ((smi (aref match match-size))) (if (next? smi) (queue-push queue smi) (close smi))))))))))) (defgeneric merge-term-info (segment-merger smis n)) (defmethod merge-term-info ((self segment-merger) smis n) (with-slots (freq-output prox-output term-info term-infos-writer) self (let ((freq-pointer (pos freq-output)) (prox-pointer (pos prox-output)) (df (append-postings self smis n)) (skip-pointer (write-skip self))) (when (> df 0) (set-values term-info df freq-pointer prox-pointer (- skip-pointer freq-pointer)) (add-term term-infos-writer (term (term-buffer (aref smis 0))) term-info))))) (defgeneric append-postings (segment-merger smis n)) (defmethod append-postings ((self segment-merger) smis n) (with-slots (freq-output prox-output skip-interval) self (let ((last-doc 0) (df 0)) (reset-skip self) (dotimes (i n) (let* ((smi (aref smis i)) (postings (positions smi)) (base (base smi)) (doc-map (doc-map smi))) (seek postings (term-enum smi)) (while (next? postings) (let ((doc (doc postings))) (when (not (null doc-map)) (setf doc (aref doc-map doc))) (incf doc base) (when (< doc last-doc) (error "Docs out of order; current doc is ~S and previous doc is ~S" doc last-doc)) (incf df) (when (= (mod df skip-interval) 0) (buffer-skip self last-doc)) (let ((doc-code (ash (- doc last-doc) 1))) (setf last-doc doc) (let ((freq (freq postings))) (if (= freq 1) (write-vint freq-output (logior doc-code 1)) (progn (write-vint freq-output doc-code) (write-vint freq-output freq))) (let ((last-position 0)) (dotimes (j freq) (let ((position (next-position postings))) (write-vint prox-output (- position last-position)) (setf last-position position)))))))))) df))) (defgeneric reset-skip (segment-merger)) (defmethod reset-skip ((self segment-merger)) (with-slots (skip-buffer last-skip-doc last-skip-freq-pointer last-skip-prox-pointer freq-output prox-output) self (reset skip-buffer) (setf last-skip-doc 0) (setf last-skip-freq-pointer (pos freq-output)) (setf last-skip-prox-pointer (pos prox-output)))) (defgeneric buffer-skip (segment-merger doc)) (defmethod buffer-skip ((self segment-merger) doc) (with-slots (skip-buffer freq-output prox-output last-skip-prox-pointer last-skip-freq-pointer last-skip-doc) self (let ((freq-pointer (pos freq-output)) (prox-pointer (pos prox-output))) (write-vint skip-buffer (- doc last-skip-doc)) (write-vint skip-buffer (- freq-pointer last-skip-freq-pointer)) (write-vint skip-buffer (- prox-pointer last-skip-prox-pointer)) (setf last-skip-doc doc last-skip-freq-pointer freq-pointer last-skip-prox-pointer prox-pointer)))) (defgeneric write-skip (segment-merger)) (defmethod write-skip ((self segment-merger)) (with-slots (freq-output skip-buffer) self (let ((skip-pointer (pos freq-output))) (write-to skip-buffer freq-output) skip-pointer))) (defgeneric merge-norms (segment-merger)) (defmethod merge-norms ((self segment-merger)) (with-slots (field-infos readers segment directory) self (dotimes (i (size field-infos)) (let ((fi (get-field field-infos i))) (when (and (field-indexed-p fi) (not (field-omit-norms-p fi))) (let ((output (open-segment-file directory segment (format nil "f~S" i) :output))) (unwind-protect (dosequence (reader readers) (let* ((max-doc (max-doc reader)) (input (make-array max-doc))) (get-norms-into reader (field-name fi) input 0) (dotimes (k max-doc) (unless (deleted-p reader k) (write-byte output (aref input k)))))) (close output))))))))
7a245856778c24866102755fdc7176d3c78d5c286536d5267f31c18283c4b7b3
vmchale/apple
Main.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE TupleSections # module Main (main) where import A import Control.Monad.IO.Class (liftIO) import Control.Monad.State (StateT, evalStateT, gets, modify) import Control.Monad.Trans.Class (lift) import qualified Data.ByteString.Lazy as BSL import Data.Int (Int64) import Data.List import Data.Semigroup ((<>)) import qualified Data.Text as T import qualified Data.Text.IO as TIO import qualified Data.Text.Lazy as TL import Data.Text.Lazy.Encoding (encodeUtf8) import Data.Tuple.Extra (fst3) import Dbg import Foreign.LibFFI (callFFI, retCDouble, retInt64, retPtr, retWord8) import Foreign.Marshal.Alloc (free) import Foreign.Ptr (Ptr, castPtr) import Foreign.Storable (peek) import Hs.A import Hs.FFI import L import Name import Parser import Prettyprinter (hardline, pretty, (<+>)) import Prettyprinter.Render.Text (putDoc) import Sys.DL import System.Console.Haskeline (Completion, CompletionFunc, InputT, completeFilename, defaultSettings, fallbackCompletion, getInputLine, historyFile, runInputT, setComplete, simpleCompletion) import System.Directory (getHomeDirectory) import System.FilePath ((</>)) import Ty main :: IO () main = runRepl loop namesStr :: StateT Env IO [String] namesStr = gets (fmap (T.unpack.name.fst) . ee) data Env = Env { _lex :: AlexUserState, ee :: [(Name AlexPosn, E AlexPosn)], mf :: (Int, Int) } aEe :: Name AlexPosn -> E AlexPosn -> Env -> Env aEe n e (Env l ees mm) = Env l ((n,e):ees) mm setL :: AlexUserState -> Env -> Env setL lSt (Env _ ees mm) = Env lSt ees mm type Repl a = InputT (StateT Env IO) cyclicSimple :: [String] -> [Completion] cyclicSimple = fmap simpleCompletion runRepl :: Repl a x -> IO x runRepl x = do histDir <- (</> ".apple_history") <$> getHomeDirectory mfϵ <- mem' let initSt = Env alexInitUserState [] mfϵ let myCompleter = appleCompletions `fallbackCompletion` completeFilename let settings = setComplete myCompleter $ defaultSettings { historyFile = Just histDir } flip evalStateT initSt $ runInputT settings x appleCompletions :: CompletionFunc (StateT Env IO) appleCompletions (":","") = pure (":", cyclicSimple ["help", "h", "ty", "quit", "q", "list", "ann", "y", "yank"]) appleCompletions ("i:", "") = pure ("i:", cyclicSimple ["r", "nspect", ""]) appleCompletions ("ri:", "") = pure ("ri:", cyclicSimple [""]) appleCompletions ("ni:", "") = pure ("ni:", [simpleCompletion "spect"]) appleCompletions ("sni:", "") = pure ("sni:", [simpleCompletion "pect"]) appleCompletions ("psni:", "") = pure ("psni:", [simpleCompletion "ect"]) appleCompletions ("epsni:", "") = pure ("epsni:", [simpleCompletion "ct"]) appleCompletions ("cepsni:", "") = pure ("cepsni:", [simpleCompletion "t"]) appleCompletions ("tcepsni:", "") = pure ("tcepsni:", [simpleCompletion ""]) appleCompletions ("t:", "") = pure ("t:", cyclicSimple ["y"]) appleCompletions ("yt:", "") = pure ("yt:", cyclicSimple [""]) appleCompletions ("y:", "") = pure ("y:", cyclicSimple ["ank", ""]) appleCompletions ("ay:", "") = pure ("ay:", cyclicSimple ["nk"]) appleCompletions ("nay:", "") = pure ("nay:", cyclicSimple ["k"]) appleCompletions ("knay:", "") = pure ("knay:", cyclicSimple [""]) appleCompletions ("d:", "") = pure ("d:", [simpleCompletion "isasm"]) appleCompletions ("id:", "") = pure ("id:", [simpleCompletion "sasm"]) appleCompletions ("sid:", "") = pure ("sid:", [simpleCompletion "asm"]) appleCompletions ("asid:", "") = pure ("asid:", [simpleCompletion "sm"]) appleCompletions ("sasid:", "") = pure ("sasid:", [simpleCompletion "m"]) appleCompletions ("msasid:", "") = pure ("msasid:", [simpleCompletion ""]) appleCompletions ("a:", "") = pure ("a:", [simpleCompletion "sm", simpleCompletion "nn"]) appleCompletions ("sa:", "") = pure ("sa:", [simpleCompletion "m"]) appleCompletions ("msa:", "") = pure ("msa:", [simpleCompletion ""]) appleCompletions ("na:", "") = pure ("na:", [simpleCompletion "n"]) appleCompletions ("nna:", "") = pure ("nna:", [simpleCompletion ""]) appleCompletions ("q:", "") = pure ("q:", cyclicSimple ["uit", ""]) appleCompletions ("uq:", "") = pure ("uq:", [simpleCompletion "it"]) appleCompletions ("iuq:", "") = pure ("iuq:", [simpleCompletion "t"]) appleCompletions ("tiuq:", "") = pure ("tiuq:", [simpleCompletion ""]) appleCompletions ("h:", "") = pure ("h:", cyclicSimple ["elp", ""]) appleCompletions ("eh:", "") = pure ("eh:", [simpleCompletion "lp"]) appleCompletions ("leh:", "") = pure ("leh:", [simpleCompletion "p"]) appleCompletions ("pleh:", "") = pure ("pleh:", [simpleCompletion ""]) appleCompletions (" yt:", "") = do { ns <- namesStr ; pure (" yt:", cyclicSimple ns) } appleCompletions (" t:", "") = do { ns <- namesStr ; pure (" t:", cyclicSimple ns) } appleCompletions ("", "") = ("",) . cyclicSimple <$> namesStr appleCompletions (rp, "") = do { ns <- namesStr ; pure (unwords ("" : tail (words rp)), cyclicSimple (namePrefix ns rp)) } appleCompletions _ = pure (undefined, []) namePrefix :: [String] -> String -> [String] namePrefix names prevRev = filter (last (words (reverse prevRev)) `isPrefixOf`) names loop :: Repl AlexPosn () loop = do inp <- getInputLine " > " case words <$> inp of Just [] -> loop Just (":h":_) -> showHelp *> loop Just (":help":_) -> showHelp *> loop Just ("\\l":_) -> langHelp *> loop Just (":ty":e) -> tyExprR (unwords e) *> loop Just [":q"] -> pure () Just [":quit"] -> pure () Just (":asm":e) -> dumpAsmG (unwords e) *> loop Just (":ann":e) -> annR (unwords e) *> loop Just (":ir":e) -> irR (unwords e) *> loop Just (":disasm":e) -> disasm (unwords e) *> loop Just (":inspect":e) -> inspect (unwords e) *> loop Just (":yank":f:[fp]) -> iCtx f fp *> loop Just (":y":f:[fp]) -> iCtx f fp *> loop Just e -> printExpr (unwords e) *> loop Nothing -> pure () showHelp :: Repl AlexPosn () showHelp = liftIO $ putStr $ concat [ helpOption ":help, :h" "" "Show this help" , helpOption ":ty" "<expression>" "Display the type of an expression" , helpOption ":ann" "<expression>" "Annotate with types" , helpOption ":list" "" "List all names that are in scope" , helpOption ":quit, :q" "" "Quit REPL" , helpOption ":yank, :y" "<fn> <file>" "Read file" , helpOption "\\l" "" "Show reference" -- TODO: dump debug state ] langHelp :: Repl AlexPosn () langHelp = liftIO $ putStr $ concat [ lOption "Λ" "scan" "√" "sqrt" , lOption "⋉" "max" "⋊" "min" , lOption "⍳" "integer range" "⌊" "floor" , lOption "ℯ" "exp" "⨳ {m,n}" "convolve" , lOption "\\~" "successive application" "\\`n" "dyadic infix" , lOption "_." "log" "'n" "map" , lOption "`" "zip" "`{i,j∘[k,l]}" "rank" , lOption "𝒻" "range (real)" "𝜋" "pi" , lOption "_" "negate" ":" "size" , lOption "𝓉" "dimension" "}.?" "last" , lOption "->n" "select" "**" "power" , lOption "gen." "generate" "𝓕" "fibonacci" , lOption "re:" "repeat" "}." "typesafe last" , lOption "⊲" "cons" "⊳" "snoc" , lOption "^:" "iterate" "%." "matmul" , lOption "⊗" "outer product" "|:" "transpose" , lOption "{.?" "head" "{." "typesafe head" , lOption "}.?" "last" "}:" "typesafe init" , lOption "⟨z,w⟩" "array literal" "?p,.e1,.e2" "conditional" , lOption "/*" "fold all" "ℝ" "i->f conversion" , lOption "⧺" "cat" "{:" "typesafe tail" , lOption "⊖" "rotate" "sin." "sine" , lOption "𝔯" "rand" "⍳" "range (int)" , lOption "/ₒ" "fold with seed" "Λₒ" "scan with seed" , lOption "{x←y;z}" "let...in" "" "" ] lOption op0 desc0 op1 desc1 = rightPad 14 op0 ++ rightPad 25 desc0 ++ rightPad 14 op1 ++ desc1 ++ "\n" rightPad :: Int -> String -> String rightPad n str = take n $ str ++ repeat ' ' helpOption :: String -> String -> String -> String helpOption cmd args desc = rightPad 15 cmd ++ rightPad 14 args ++ desc ++ "\n" ubs :: String -> BSL.ByteString ubs = encodeUtf8 . TL.pack disasm :: String -> Repl AlexPosn () disasm s = do st <- lift $ gets _lex liftIO $ do res <- dtxt st (ubs s) case res of Left err -> putDoc (pretty err <> hardline) Right b -> TIO.putStr b irR :: String -> Repl AlexPosn () irR s = do st <- lift $ gets _lex case dumpIR st (ubs s) of Left err -> liftIO $ putDoc (pretty err <> hardline) Right d -> liftIO $ putDoc (d <> hardline) dumpAsmG :: String -> Repl AlexPosn () dumpAsmG s = do st <- lift $ gets _lex case dumpX86G st (ubs s) of Left err -> liftIO $ putDoc (pretty err <> hardline) Right d -> liftIO $ putDoc (d <> hardline) tyExprR :: String -> Repl AlexPosn () tyExprR s = do st <- lift $ gets _lex liftIO $ case tyExprCtx st (ubs s) of Left err -> putDoc (pretty err <> hardline) Right d -> putDoc (d <> hardline) annR :: String -> Repl AlexPosn () annR s = do st <- lift $ gets _lex liftIO $ case tyParseCtx st $ ubs s of Left err -> putDoc(pretty err<>hardline) Right (e,_) -> putDoc(prettyTyped e<>hardline) inspect :: String -> Repl AlexPosn () inspect s = do st <- lift $ gets _lex case tyParseCtx st bs of Left err -> liftIO $ putDoc (pretty err <> hardline) Right (e, _) -> do let dbgPrint = case eAnn e of (Arr _ (P [F,F])) -> \p -> (dbgAB :: Ptr (Apple (Pp Double Double)) -> IO T.Text) (castPtr p) (Arr _ F) -> \p -> (dbgAB :: Ptr (Apple Double) -> IO T.Text) (castPtr p) (Arr _ I) -> \p -> (dbgAB :: Ptr (Apple Int64) -> IO T.Text) (castPtr p) m <- lift $ gets mf liftIO $ do let i = fst3 st (sz, fp) <- eFunP i m e p <- callFFI fp (retPtr undefined) [] TIO.putStrLn =<< dbgPrint p free p *> freeFunPtr sz fp where bs = ubs s iCtx :: String -> String -> Repl AlexPosn () iCtx f fp = do st <- lift $ gets _lex bs <- liftIO $ BSL.readFile fp case tyParseCtx st bs of Left err -> liftIO $ putDoc (pretty err <> hardline) Right (_,i) -> do let (st', n) = newIdent (AlexPn 0 0 0) (T.pack f) (setM i st) x' = parseE st' bs lift $ do {modify (aEe n x'); modify (setL st')} where setM i' (_, mm, im) = (i', mm, im) printExpr :: String -> Repl AlexPosn () printExpr s = do st <- lift $ gets _lex case rwP st bs of Left err -> liftIO $ putDoc (pretty err <> hardline) Right (eP, i) -> do eC <- eRepl eP case tyClosed i eC of Left err -> liftIO $ putDoc (pretty err <> hardline) Right (e, _, _) -> do m <- lift $ gets mf case eAnn e of I -> liftIO $ do (sz, fp) <- eFunP i m eC print =<< callFFI fp retInt64 [] freeFunPtr sz fp F -> liftIO $ do (sz, fp) <- eFunP i m eC print =<< callFFI fp retCDouble [] freeFunPtr sz fp (Arr _ F) -> liftIO $ do (sz, fp) <- eFunP i m eC p <- callFFI fp (retPtr undefined) [] putDoc.(<>hardline).pretty =<< (peek :: Ptr AF -> IO AF) p free p *> freeFunPtr sz fp (Arr _ I) -> liftIO $ do (sz, fp) <- eFunP i m eC p <- callFFI fp (retPtr undefined) [] putDoc.(<>hardline).pretty =<< (peek :: Ptr AI -> IO AI) p free p *> freeFunPtr sz fp B -> liftIO $ do (sz, fp) <- eFunP i m eC cb <- callFFI fp retWord8 [] putStrLn (sB cb) freeFunPtr sz fp where sB 1 = "#t"; sB 0 = "#f" (Arr _ (P [F,F])) -> liftIO $ do (sz, fp) <- eFunP i m eC p <- callFFI fp (retPtr undefined) [] putDoc.(<>hardline).pretty =<< (peek :: Ptr (Apple (Pp Double Double)) -> IO (Apple (Pp Double Double))) p free p *> freeFunPtr sz fp (Arr _ (P [I,I])) -> liftIO $ do (sz, fp) <- eFunP i m eC p <- callFFI fp (retPtr undefined) [] putDoc.(<>hardline).pretty =<< (peek :: Ptr (Apple (Pp Int64 Int64)) -> IO (Apple (Pp Int64 Int64))) p free p *> freeFunPtr sz fp t -> liftIO $ putDoc (pretty e <+> ":" <+> pretty t <> hardline) where bs = ubs s parseE st bs = fst . either (error "Internal error?") id $ rwP st bs eRepl :: E AlexPosn -> Repl AlexPosn (E AlexPosn) eRepl e = do { ees <- lift $ gets ee; pure $ foldLet ees e } where foldLet = thread . fmap (\b@(_,eϵ) -> Let (eAnn eϵ) b) where thread = foldr (.) id
null
https://raw.githubusercontent.com/vmchale/apple/ed41443012d6dd2a73edcff10915c0defda0e34b/run/Main.hs
haskell
# LANGUAGE OverloadedStrings # TODO: dump debug state
# LANGUAGE TupleSections # module Main (main) where import A import Control.Monad.IO.Class (liftIO) import Control.Monad.State (StateT, evalStateT, gets, modify) import Control.Monad.Trans.Class (lift) import qualified Data.ByteString.Lazy as BSL import Data.Int (Int64) import Data.List import Data.Semigroup ((<>)) import qualified Data.Text as T import qualified Data.Text.IO as TIO import qualified Data.Text.Lazy as TL import Data.Text.Lazy.Encoding (encodeUtf8) import Data.Tuple.Extra (fst3) import Dbg import Foreign.LibFFI (callFFI, retCDouble, retInt64, retPtr, retWord8) import Foreign.Marshal.Alloc (free) import Foreign.Ptr (Ptr, castPtr) import Foreign.Storable (peek) import Hs.A import Hs.FFI import L import Name import Parser import Prettyprinter (hardline, pretty, (<+>)) import Prettyprinter.Render.Text (putDoc) import Sys.DL import System.Console.Haskeline (Completion, CompletionFunc, InputT, completeFilename, defaultSettings, fallbackCompletion, getInputLine, historyFile, runInputT, setComplete, simpleCompletion) import System.Directory (getHomeDirectory) import System.FilePath ((</>)) import Ty main :: IO () main = runRepl loop namesStr :: StateT Env IO [String] namesStr = gets (fmap (T.unpack.name.fst) . ee) data Env = Env { _lex :: AlexUserState, ee :: [(Name AlexPosn, E AlexPosn)], mf :: (Int, Int) } aEe :: Name AlexPosn -> E AlexPosn -> Env -> Env aEe n e (Env l ees mm) = Env l ((n,e):ees) mm setL :: AlexUserState -> Env -> Env setL lSt (Env _ ees mm) = Env lSt ees mm type Repl a = InputT (StateT Env IO) cyclicSimple :: [String] -> [Completion] cyclicSimple = fmap simpleCompletion runRepl :: Repl a x -> IO x runRepl x = do histDir <- (</> ".apple_history") <$> getHomeDirectory mfϵ <- mem' let initSt = Env alexInitUserState [] mfϵ let myCompleter = appleCompletions `fallbackCompletion` completeFilename let settings = setComplete myCompleter $ defaultSettings { historyFile = Just histDir } flip evalStateT initSt $ runInputT settings x appleCompletions :: CompletionFunc (StateT Env IO) appleCompletions (":","") = pure (":", cyclicSimple ["help", "h", "ty", "quit", "q", "list", "ann", "y", "yank"]) appleCompletions ("i:", "") = pure ("i:", cyclicSimple ["r", "nspect", ""]) appleCompletions ("ri:", "") = pure ("ri:", cyclicSimple [""]) appleCompletions ("ni:", "") = pure ("ni:", [simpleCompletion "spect"]) appleCompletions ("sni:", "") = pure ("sni:", [simpleCompletion "pect"]) appleCompletions ("psni:", "") = pure ("psni:", [simpleCompletion "ect"]) appleCompletions ("epsni:", "") = pure ("epsni:", [simpleCompletion "ct"]) appleCompletions ("cepsni:", "") = pure ("cepsni:", [simpleCompletion "t"]) appleCompletions ("tcepsni:", "") = pure ("tcepsni:", [simpleCompletion ""]) appleCompletions ("t:", "") = pure ("t:", cyclicSimple ["y"]) appleCompletions ("yt:", "") = pure ("yt:", cyclicSimple [""]) appleCompletions ("y:", "") = pure ("y:", cyclicSimple ["ank", ""]) appleCompletions ("ay:", "") = pure ("ay:", cyclicSimple ["nk"]) appleCompletions ("nay:", "") = pure ("nay:", cyclicSimple ["k"]) appleCompletions ("knay:", "") = pure ("knay:", cyclicSimple [""]) appleCompletions ("d:", "") = pure ("d:", [simpleCompletion "isasm"]) appleCompletions ("id:", "") = pure ("id:", [simpleCompletion "sasm"]) appleCompletions ("sid:", "") = pure ("sid:", [simpleCompletion "asm"]) appleCompletions ("asid:", "") = pure ("asid:", [simpleCompletion "sm"]) appleCompletions ("sasid:", "") = pure ("sasid:", [simpleCompletion "m"]) appleCompletions ("msasid:", "") = pure ("msasid:", [simpleCompletion ""]) appleCompletions ("a:", "") = pure ("a:", [simpleCompletion "sm", simpleCompletion "nn"]) appleCompletions ("sa:", "") = pure ("sa:", [simpleCompletion "m"]) appleCompletions ("msa:", "") = pure ("msa:", [simpleCompletion ""]) appleCompletions ("na:", "") = pure ("na:", [simpleCompletion "n"]) appleCompletions ("nna:", "") = pure ("nna:", [simpleCompletion ""]) appleCompletions ("q:", "") = pure ("q:", cyclicSimple ["uit", ""]) appleCompletions ("uq:", "") = pure ("uq:", [simpleCompletion "it"]) appleCompletions ("iuq:", "") = pure ("iuq:", [simpleCompletion "t"]) appleCompletions ("tiuq:", "") = pure ("tiuq:", [simpleCompletion ""]) appleCompletions ("h:", "") = pure ("h:", cyclicSimple ["elp", ""]) appleCompletions ("eh:", "") = pure ("eh:", [simpleCompletion "lp"]) appleCompletions ("leh:", "") = pure ("leh:", [simpleCompletion "p"]) appleCompletions ("pleh:", "") = pure ("pleh:", [simpleCompletion ""]) appleCompletions (" yt:", "") = do { ns <- namesStr ; pure (" yt:", cyclicSimple ns) } appleCompletions (" t:", "") = do { ns <- namesStr ; pure (" t:", cyclicSimple ns) } appleCompletions ("", "") = ("",) . cyclicSimple <$> namesStr appleCompletions (rp, "") = do { ns <- namesStr ; pure (unwords ("" : tail (words rp)), cyclicSimple (namePrefix ns rp)) } appleCompletions _ = pure (undefined, []) namePrefix :: [String] -> String -> [String] namePrefix names prevRev = filter (last (words (reverse prevRev)) `isPrefixOf`) names loop :: Repl AlexPosn () loop = do inp <- getInputLine " > " case words <$> inp of Just [] -> loop Just (":h":_) -> showHelp *> loop Just (":help":_) -> showHelp *> loop Just ("\\l":_) -> langHelp *> loop Just (":ty":e) -> tyExprR (unwords e) *> loop Just [":q"] -> pure () Just [":quit"] -> pure () Just (":asm":e) -> dumpAsmG (unwords e) *> loop Just (":ann":e) -> annR (unwords e) *> loop Just (":ir":e) -> irR (unwords e) *> loop Just (":disasm":e) -> disasm (unwords e) *> loop Just (":inspect":e) -> inspect (unwords e) *> loop Just (":yank":f:[fp]) -> iCtx f fp *> loop Just (":y":f:[fp]) -> iCtx f fp *> loop Just e -> printExpr (unwords e) *> loop Nothing -> pure () showHelp :: Repl AlexPosn () showHelp = liftIO $ putStr $ concat [ helpOption ":help, :h" "" "Show this help" , helpOption ":ty" "<expression>" "Display the type of an expression" , helpOption ":ann" "<expression>" "Annotate with types" , helpOption ":list" "" "List all names that are in scope" , helpOption ":quit, :q" "" "Quit REPL" , helpOption ":yank, :y" "<fn> <file>" "Read file" , helpOption "\\l" "" "Show reference" ] langHelp :: Repl AlexPosn () langHelp = liftIO $ putStr $ concat [ lOption "Λ" "scan" "√" "sqrt" , lOption "⋉" "max" "⋊" "min" , lOption "⍳" "integer range" "⌊" "floor" , lOption "ℯ" "exp" "⨳ {m,n}" "convolve" , lOption "\\~" "successive application" "\\`n" "dyadic infix" , lOption "_." "log" "'n" "map" , lOption "`" "zip" "`{i,j∘[k,l]}" "rank" , lOption "𝒻" "range (real)" "𝜋" "pi" , lOption "_" "negate" ":" "size" , lOption "𝓉" "dimension" "}.?" "last" , lOption "->n" "select" "**" "power" , lOption "gen." "generate" "𝓕" "fibonacci" , lOption "re:" "repeat" "}." "typesafe last" , lOption "⊲" "cons" "⊳" "snoc" , lOption "^:" "iterate" "%." "matmul" , lOption "⊗" "outer product" "|:" "transpose" , lOption "{.?" "head" "{." "typesafe head" , lOption "}.?" "last" "}:" "typesafe init" , lOption "⟨z,w⟩" "array literal" "?p,.e1,.e2" "conditional" , lOption "/*" "fold all" "ℝ" "i->f conversion" , lOption "⧺" "cat" "{:" "typesafe tail" , lOption "⊖" "rotate" "sin." "sine" , lOption "𝔯" "rand" "⍳" "range (int)" , lOption "/ₒ" "fold with seed" "Λₒ" "scan with seed" , lOption "{x←y;z}" "let...in" "" "" ] lOption op0 desc0 op1 desc1 = rightPad 14 op0 ++ rightPad 25 desc0 ++ rightPad 14 op1 ++ desc1 ++ "\n" rightPad :: Int -> String -> String rightPad n str = take n $ str ++ repeat ' ' helpOption :: String -> String -> String -> String helpOption cmd args desc = rightPad 15 cmd ++ rightPad 14 args ++ desc ++ "\n" ubs :: String -> BSL.ByteString ubs = encodeUtf8 . TL.pack disasm :: String -> Repl AlexPosn () disasm s = do st <- lift $ gets _lex liftIO $ do res <- dtxt st (ubs s) case res of Left err -> putDoc (pretty err <> hardline) Right b -> TIO.putStr b irR :: String -> Repl AlexPosn () irR s = do st <- lift $ gets _lex case dumpIR st (ubs s) of Left err -> liftIO $ putDoc (pretty err <> hardline) Right d -> liftIO $ putDoc (d <> hardline) dumpAsmG :: String -> Repl AlexPosn () dumpAsmG s = do st <- lift $ gets _lex case dumpX86G st (ubs s) of Left err -> liftIO $ putDoc (pretty err <> hardline) Right d -> liftIO $ putDoc (d <> hardline) tyExprR :: String -> Repl AlexPosn () tyExprR s = do st <- lift $ gets _lex liftIO $ case tyExprCtx st (ubs s) of Left err -> putDoc (pretty err <> hardline) Right d -> putDoc (d <> hardline) annR :: String -> Repl AlexPosn () annR s = do st <- lift $ gets _lex liftIO $ case tyParseCtx st $ ubs s of Left err -> putDoc(pretty err<>hardline) Right (e,_) -> putDoc(prettyTyped e<>hardline) inspect :: String -> Repl AlexPosn () inspect s = do st <- lift $ gets _lex case tyParseCtx st bs of Left err -> liftIO $ putDoc (pretty err <> hardline) Right (e, _) -> do let dbgPrint = case eAnn e of (Arr _ (P [F,F])) -> \p -> (dbgAB :: Ptr (Apple (Pp Double Double)) -> IO T.Text) (castPtr p) (Arr _ F) -> \p -> (dbgAB :: Ptr (Apple Double) -> IO T.Text) (castPtr p) (Arr _ I) -> \p -> (dbgAB :: Ptr (Apple Int64) -> IO T.Text) (castPtr p) m <- lift $ gets mf liftIO $ do let i = fst3 st (sz, fp) <- eFunP i m e p <- callFFI fp (retPtr undefined) [] TIO.putStrLn =<< dbgPrint p free p *> freeFunPtr sz fp where bs = ubs s iCtx :: String -> String -> Repl AlexPosn () iCtx f fp = do st <- lift $ gets _lex bs <- liftIO $ BSL.readFile fp case tyParseCtx st bs of Left err -> liftIO $ putDoc (pretty err <> hardline) Right (_,i) -> do let (st', n) = newIdent (AlexPn 0 0 0) (T.pack f) (setM i st) x' = parseE st' bs lift $ do {modify (aEe n x'); modify (setL st')} where setM i' (_, mm, im) = (i', mm, im) printExpr :: String -> Repl AlexPosn () printExpr s = do st <- lift $ gets _lex case rwP st bs of Left err -> liftIO $ putDoc (pretty err <> hardline) Right (eP, i) -> do eC <- eRepl eP case tyClosed i eC of Left err -> liftIO $ putDoc (pretty err <> hardline) Right (e, _, _) -> do m <- lift $ gets mf case eAnn e of I -> liftIO $ do (sz, fp) <- eFunP i m eC print =<< callFFI fp retInt64 [] freeFunPtr sz fp F -> liftIO $ do (sz, fp) <- eFunP i m eC print =<< callFFI fp retCDouble [] freeFunPtr sz fp (Arr _ F) -> liftIO $ do (sz, fp) <- eFunP i m eC p <- callFFI fp (retPtr undefined) [] putDoc.(<>hardline).pretty =<< (peek :: Ptr AF -> IO AF) p free p *> freeFunPtr sz fp (Arr _ I) -> liftIO $ do (sz, fp) <- eFunP i m eC p <- callFFI fp (retPtr undefined) [] putDoc.(<>hardline).pretty =<< (peek :: Ptr AI -> IO AI) p free p *> freeFunPtr sz fp B -> liftIO $ do (sz, fp) <- eFunP i m eC cb <- callFFI fp retWord8 [] putStrLn (sB cb) freeFunPtr sz fp where sB 1 = "#t"; sB 0 = "#f" (Arr _ (P [F,F])) -> liftIO $ do (sz, fp) <- eFunP i m eC p <- callFFI fp (retPtr undefined) [] putDoc.(<>hardline).pretty =<< (peek :: Ptr (Apple (Pp Double Double)) -> IO (Apple (Pp Double Double))) p free p *> freeFunPtr sz fp (Arr _ (P [I,I])) -> liftIO $ do (sz, fp) <- eFunP i m eC p <- callFFI fp (retPtr undefined) [] putDoc.(<>hardline).pretty =<< (peek :: Ptr (Apple (Pp Int64 Int64)) -> IO (Apple (Pp Int64 Int64))) p free p *> freeFunPtr sz fp t -> liftIO $ putDoc (pretty e <+> ":" <+> pretty t <> hardline) where bs = ubs s parseE st bs = fst . either (error "Internal error?") id $ rwP st bs eRepl :: E AlexPosn -> Repl AlexPosn (E AlexPosn) eRepl e = do { ees <- lift $ gets ee; pure $ foldLet ees e } where foldLet = thread . fmap (\b@(_,eϵ) -> Let (eAnn eϵ) b) where thread = foldr (.) id
d8dc6ba39bc8686cdc9f9c97b32b7561869a2f80f3e9722648ffb594c9899de2
charlieg/Sparser
view1.lisp
;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:(SPARSER LISP) -*- copyright ( c ) 1992 - 1996 -- all rights reserved ;;; ;;; File: "view" ;;; Module: "interface;workbench:edge-view:" version : 1.0 November 1995 initiated 2/10/92 v2.2 0.1 ( 1/10/94 ) redesigned from scratch for MCL2.0 as part of the Workbench 0.2 During Feb , & March , continually tweeking to get state transitions right 0.3 ( 3/25 ) added coordination with generic subviews 0.4 ( 6/10 ) added true incremental updates . ( 7/22 ) fixed glitch in " ... " cases ;; Got "" around labels of literal edges. 0.5 ( 7/25 ) changed the indentation on toplevel words to 0 . 0.6 ( 8/1 ) changed populating routine to appreciate edges wrapping ( 8/19 ) tweeked that . And again 8/23 0.7 ( 1/2/95 ) alternative path into edge - selection led to tweaking cons - cases ;; of index calculation in Select-corresponding-item-in-edges-view ( 1/6 ) added Scroll - edges - view / cons . 1/10 gave it another way to get the index 0.8 ( 1/20 ) put a hook into Act - on - edge - in - view for * additional - edge - selection - action * 0.9 ( 1/25 ) identified a funny case in creating the edges list where the nominal ;; start-edge is leftwards of already recycled edges. Fixed it with a ;; 'jump-ahead' routine. ( 2/23 ) put in a stub to catch a ' up ' glitch , fixed some other glitches by ;; rerouting their thread. Wrote Select-edge-in-view/no-side-effects [ broke file into pieces 2/28 ] 0.10 ( 4/21 ) moved widgets in , added ' inspect ' , changed double click action ;; to 'open'. ( 8/9 ) added a debugging block to the warning in Scroll - edges - view / cons 1.0 ( 8/30 ) tweeked Print - edge - in - view to handle elipsis edges . ( 11/13 ) tweeked ;; printing of words based on symbols like para.starts (in-package :sparser) ;;;--------- ;;; widgets ;;;--------- (defparameter *edges/open-button* (MAKE-DIALOG-ITEM 'BUTTON-DIALOG-ITEM 188 pixels over from the left , 336 down from the top ;; This puts it just under the edges view #@(41 17) "down" 'edges/open-edge-to-show-daughters :DEFAULT-BUTTON NIL )) (defparameter *edges/close-button* (MAKE-DIALOG-ITEM 'BUTTON-DIALOG-ITEM #@(138 336) ;; ///ditto #@(28 17) "up" 'edges/close-daughters :DEFAULT-BUTTON NIL )) (defparameter *edges/inspect-button* (MAKE-DIALOG-ITEM 'BUTTON-DIALOG-ITEM #@(25 336) #@(82 16) "inspect" 'edges/inspect-edge :DEFAULT-BUTTON NIL)) ;;;---------------- ;;; the view/table ;;;---------------- (defclass Edges-view (sequence-dialog-item) ()) (defun setup-edges-view () called the first time that the edges view is requested , e.g. after the first run when the ' show edges ' button is on . (size-workbench-for-edges-view) (setq *edges-table* (make-instance 'edges-view :view-container *workshop-window* :view-position #@(14 148) ;; The upper left corner of the box around the view is 14 in from the left margin of the workbence and 148 down from its top . :view-size #@(235 185) 224 points wide horizontally , 185 long vertically :view-font '("Geneva" 9 :plain) :visible-dimensions #@(1 15) :table-sequence *edges-in-view-of-current-article* :dialog-item-action 'act-on-edge-in-view :sequence-wrap-length 8000 :selection-type :single :table-print-function 'print-edge-in-view :table-vscrollp t :table-hscrollp nil : cell - size # @(184 12 ) ;; this will override the :view-size spec -- this value ;; will shrink it horizontally ))) (defparameter *no-lines/edges-table* 15) ;;;---------------------- ;;; populating the table ;;;---------------------- (defun update-edges-display () ;; called from update-workbench (when *show-document-edges?* (if *edges-table* ;; only true if the edges view has been initialized ;; and shown once (update-edge-list-for-current-article) (initialize-edges-display)))) (defun initialize-edges-display () (generate-treetop-list-for-current-article) (setup-edges-view)) (defun update-edge-list-for-current-article ( &optional top-edge ) (generate-treetop-list-for-current-article) (set-table-sequence *edges-table* *edges-in-view-of-current-article*) (when top-edge (etypecase top-edge (edge (scroll-edges-view/top-edge top-edge)) (cons (scroll-edges-view/cons top-edge))))) (defun swap-in-the-edges-table () ;; one of the other subviews is occupying the space under the ;; text view. We hide it and replace it in the space with the ;; edges table and its buttons. ) ;;;----------------------- ;;; edge printing routine ;;;----------------------- (defun print-edge-in-view (e stream) (when e (etypecase e (edge (if (eq (edge-category e) *elipsis-dots*) (print-elipsis-edge e stream) (let ((category (edge-category e)) (depth (gethash e *wb/edge->depth*))) (unless depth (break "no depth for ~A" e)) (if (edge-starts-at e) (let ((start (pos-token-index (pos-edge-starts-at e))) (end (pos-token-index (pos-edge-ends-at e)))) (let ((label-string (etypecase category ((or referential-category category mixin-category) (string-downcase (symbol-name (cat-symbol category)))) (word (concatenate 'string "\"" (word-pname category) "\"")) (polyword (pw-pname category))))) (format stream "e~A " (edge-position-in-resource-array e)) (write-string (string-of-n-spaces (* 2 depth)) stream) (format stream "~A ~A ~A" start label-string end))) ;; otherwise it's an inactive edge (format stream "inactive edge no. ~A" (edge-position-in-resource-array e)))))) (cons ;; it's an encoding of positions and a word (let ((pname (word-pname (second e))) (depth (fourth e)) symbol ) (cond ((null pname) (setq pname (string-downcase (symbol-name (word-symbol (second e)))))) ((equal pname "") (setq pname (string-downcase (symbol-name (word-symbol (second e)))) symbol t))) ( write - string ( string - of - n - spaces ( * 2 depth ) ) stream ) ;; with a variable width font that carefully calculated ;; indentation doesn't work, so decided to exagerate it (when (> depth 0) (write-string " " stream)) (if symbol (format stream "~A \"~A\" ~A" (pos-token-index (first e)) pname (pos-token-index (third e))) (format stream "~A \"~A\" ~A" (pos-token-index (first e)) pname (pos-token-index (third e))))))))) ;;;----------- ;;; scrolling ;;;----------- (defparameter *test-edge-view-coordination* nil) (defun scroll-edges-view/top-edge (edge) make this edge the top one in the view (let ((cell (find-item-in-edges-view edge))) (unless cell (if (edge-used-in edge) (let ((parent (edge-used-in edge))) (loop (setq cell (find-item-in-edges-view parent)) (when cell (return)) (if (edge-used-in parent) (setq parent (edge-used-in parent)) (when *test-edge-view-coordination* (break "Threading bug? Expected the treetop edge ~A~ ~%to be present in the workbench edges table but ~ it isn't." parent))))) (when *test-edge-view-coordination* (when *test-edge-view-coordination* (break "Threading bug? Expected the treetop edge ~A~ ~%to be present in the workbench edges table but ~ it isn't." edge))))) (when cell (let ((index (ccl:cell-to-index *edges-table* cell))) (ccl:scroll-to-cell *edges-table* 0 index))))) (defun scroll-edges-view/cons (wf) (let ((index (or (find-index-of-word-form/edges-table wf) (find-index-of-relevant-edges-gap (first wf)) (find-cell-of-edge-starting-at (first wf))))) (if index (ccl:scroll-to-cell *edges-table* 0 index) (when *break-on-unexpected-cases* (break "~&~%----- Scroll-edges-view/cons couldn't find ~ edges table index to scroll to~%~A~%-----~%" wf))))) (defun scroll-as-needed-to-make-edge-visible (edge) ;; We assume that the edge is in the table -- some earlier routine ;; opened up its parents if that was necessary. (let ((cell (find-cell-of-edge/edges-table edge))) (unless cell (break "Threading bug: edge is not in the table. Should an ~ earlier~%routine have opened its parents?~% ~A" edge)) (let* ((index (ccl:cell-to-index *edges-table* cell)) (top (ccl:point-v (ccl:scroll-position *edges-table*))) (diff (- index top)) ;; positive if edge is lower new-top ) (cond ((minusp diff) ;; it's offscreen and above (setq new-top (- (+ top diff) ;; adding a neg. is subtraction two lines below top ((> diff *no-lines/edges-table*) ;; offscreen and below (setq new-top (+ top (- diff (- *no-lines/edges-table* 7))))) (t ;; onscreen (setq new-top nil))) (when new-top (ccl:scroll-to-cell *edges-table* 0 new-top))))) ;;;------------- ;;; action item ;;;------------- (defvar *selected-edge/edges-view* nil "Points to the actual object in the table, either an edge or a word-form" ) (defvar *selected-cell/index/edges-view* nil "Points to an integer that is the location of the selected item in the table" ) (defvar *edge* nil "holds the last edge or word-form selected in the edges view") (defparameter *additional-edge-selection-action* nil "a hook for other parts of the workbench to use to have their own effects generated by the selection of an edge in the edges view.") (defun act-on-edge-in-view (table) ;; dialog item action for edges-view. It's what happens when ;; you click on an edge (if (selected-cells table) ;; This will have a value if there's a filled cell at the ;; point in the view where the user clicks. (let* ((*click-originated-in-edges-view* t) (cell (car (ccl:selected-cells table))) (index (ccl:cell-to-index table cell)) (edge (elt (table-sequence table) index))) ;(format t "~%cell ~A index ~A" cell index) (setq *selected-edge/edges-view* edge *edge* edge *selected-cell/index/edges-view* index) (ccl:dialog-item-enable *edges/inspect-button*) (select-text-for-edge edge) (establish-edge-button-viability edge) (when (double-click-p) (double-click-action-for-edges-view edge)) (coordinate-subview-to-selected-edge edge) (when *additional-edge-selection-action* (funcall *additional-edge-selection-action* edge))) ;; If there are visible unfilled cells and the user clicks ;; there then we get this case. (else (ccl:dialog-item-disable *edges/inspect-button*)))) (defun double-click-action-for-edges-view (edge) (etypecase edge (edge (unless (daughters-already-visible edge) (edges/Open-edge-to-show-daughters))) (cons ))) ;;;----------------------------------- ;;; action for *edges/inspect-button* ;;;----------------------------------- (defun edges/inspect-edge (edges/inspect-button) (when *edge* (etypecase *edge* (edge (inspect *edge*)) (cons ;; an instance of a word (inspect (second *edge*)))) (ccl:dialog-item-disable edges/inspect-button)))
null
https://raw.githubusercontent.com/charlieg/Sparser/b9bb7d01d2e40f783f3214fc104062db3d15e608/Sparser/code/s/interface/workbench/edge-view/view1.lisp
lisp
-*- Mode:LISP; Syntax:Common-Lisp; Package:(SPARSER LISP) -*- File: "view" Module: "interface;workbench:edge-view:" Got "" around labels of literal edges. of index calculation in Select-corresponding-item-in-edges-view start-edge is leftwards of already recycled edges. Fixed it with a 'jump-ahead' routine. rerouting their thread. Wrote Select-edge-in-view/no-side-effects to 'open'. printing of words based on symbols like para.starts --------- widgets --------- This puts it just under the edges view ///ditto ---------------- the view/table ---------------- The upper left corner of the box around the view is this will override the :view-size spec -- this value will shrink it horizontally ---------------------- populating the table ---------------------- called from update-workbench only true if the edges view has been initialized and shown once one of the other subviews is occupying the space under the text view. We hide it and replace it in the space with the edges table and its buttons. ----------------------- edge printing routine ----------------------- otherwise it's an inactive edge it's an encoding of positions and a word with a variable width font that carefully calculated indentation doesn't work, so decided to exagerate it ----------- scrolling ----------- We assume that the edge is in the table -- some earlier routine opened up its parents if that was necessary. positive if edge is lower it's offscreen and above adding a neg. is subtraction offscreen and below onscreen ------------- action item ------------- dialog item action for edges-view. It's what happens when you click on an edge This will have a value if there's a filled cell at the point in the view where the user clicks. (format t "~%cell ~A index ~A" cell index) If there are visible unfilled cells and the user clicks there then we get this case. ----------------------------------- action for *edges/inspect-button* ----------------------------------- an instance of a word
copyright ( c ) 1992 - 1996 -- all rights reserved version : 1.0 November 1995 initiated 2/10/92 v2.2 0.1 ( 1/10/94 ) redesigned from scratch for MCL2.0 as part of the Workbench 0.2 During Feb , & March , continually tweeking to get state transitions right 0.3 ( 3/25 ) added coordination with generic subviews 0.4 ( 6/10 ) added true incremental updates . ( 7/22 ) fixed glitch in " ... " cases 0.5 ( 7/25 ) changed the indentation on toplevel words to 0 . 0.6 ( 8/1 ) changed populating routine to appreciate edges wrapping ( 8/19 ) tweeked that . And again 8/23 0.7 ( 1/2/95 ) alternative path into edge - selection led to tweaking cons - cases ( 1/6 ) added Scroll - edges - view / cons . 1/10 gave it another way to get the index 0.8 ( 1/20 ) put a hook into Act - on - edge - in - view for * additional - edge - selection - action * 0.9 ( 1/25 ) identified a funny case in creating the edges list where the nominal ( 2/23 ) put in a stub to catch a ' up ' glitch , fixed some other glitches by [ broke file into pieces 2/28 ] 0.10 ( 4/21 ) moved widgets in , added ' inspect ' , changed double click action ( 8/9 ) added a debugging block to the warning in Scroll - edges - view / cons 1.0 ( 8/30 ) tweeked Print - edge - in - view to handle elipsis edges . ( 11/13 ) tweeked (in-package :sparser) (defparameter *edges/open-button* (MAKE-DIALOG-ITEM 'BUTTON-DIALOG-ITEM 188 pixels over from the left , 336 down from the top #@(41 17) "down" 'edges/open-edge-to-show-daughters :DEFAULT-BUTTON NIL )) (defparameter *edges/close-button* (MAKE-DIALOG-ITEM 'BUTTON-DIALOG-ITEM #@(28 17) "up" 'edges/close-daughters :DEFAULT-BUTTON NIL )) (defparameter *edges/inspect-button* (MAKE-DIALOG-ITEM 'BUTTON-DIALOG-ITEM #@(25 336) #@(82 16) "inspect" 'edges/inspect-edge :DEFAULT-BUTTON NIL)) (defclass Edges-view (sequence-dialog-item) ()) (defun setup-edges-view () called the first time that the edges view is requested , e.g. after the first run when the ' show edges ' button is on . (size-workbench-for-edges-view) (setq *edges-table* (make-instance 'edges-view :view-container *workshop-window* :view-position #@(14 148) 14 in from the left margin of the workbence and 148 down from its top . :view-size #@(235 185) 224 points wide horizontally , 185 long vertically :view-font '("Geneva" 9 :plain) :visible-dimensions #@(1 15) :table-sequence *edges-in-view-of-current-article* :dialog-item-action 'act-on-edge-in-view :sequence-wrap-length 8000 :selection-type :single :table-print-function 'print-edge-in-view :table-vscrollp t :table-hscrollp nil : cell - size # @(184 12 ) ))) (defparameter *no-lines/edges-table* 15) (defun update-edges-display () (when *show-document-edges?* (if *edges-table* (update-edge-list-for-current-article) (initialize-edges-display)))) (defun initialize-edges-display () (generate-treetop-list-for-current-article) (setup-edges-view)) (defun update-edge-list-for-current-article ( &optional top-edge ) (generate-treetop-list-for-current-article) (set-table-sequence *edges-table* *edges-in-view-of-current-article*) (when top-edge (etypecase top-edge (edge (scroll-edges-view/top-edge top-edge)) (cons (scroll-edges-view/cons top-edge))))) (defun swap-in-the-edges-table () ) (defun print-edge-in-view (e stream) (when e (etypecase e (edge (if (eq (edge-category e) *elipsis-dots*) (print-elipsis-edge e stream) (let ((category (edge-category e)) (depth (gethash e *wb/edge->depth*))) (unless depth (break "no depth for ~A" e)) (if (edge-starts-at e) (let ((start (pos-token-index (pos-edge-starts-at e))) (end (pos-token-index (pos-edge-ends-at e)))) (let ((label-string (etypecase category ((or referential-category category mixin-category) (string-downcase (symbol-name (cat-symbol category)))) (word (concatenate 'string "\"" (word-pname category) "\"")) (polyword (pw-pname category))))) (format stream "e~A " (edge-position-in-resource-array e)) (write-string (string-of-n-spaces (* 2 depth)) stream) (format stream "~A ~A ~A" start label-string end))) (format stream "inactive edge no. ~A" (edge-position-in-resource-array e)))))) (cons (let ((pname (word-pname (second e))) (depth (fourth e)) symbol ) (cond ((null pname) (setq pname (string-downcase (symbol-name (word-symbol (second e)))))) ((equal pname "") (setq pname (string-downcase (symbol-name (word-symbol (second e)))) symbol t))) ( write - string ( string - of - n - spaces ( * 2 depth ) ) stream ) (when (> depth 0) (write-string " " stream)) (if symbol (format stream "~A \"~A\" ~A" (pos-token-index (first e)) pname (pos-token-index (third e))) (format stream "~A \"~A\" ~A" (pos-token-index (first e)) pname (pos-token-index (third e))))))))) (defparameter *test-edge-view-coordination* nil) (defun scroll-edges-view/top-edge (edge) make this edge the top one in the view (let ((cell (find-item-in-edges-view edge))) (unless cell (if (edge-used-in edge) (let ((parent (edge-used-in edge))) (loop (setq cell (find-item-in-edges-view parent)) (when cell (return)) (if (edge-used-in parent) (setq parent (edge-used-in parent)) (when *test-edge-view-coordination* (break "Threading bug? Expected the treetop edge ~A~ ~%to be present in the workbench edges table but ~ it isn't." parent))))) (when *test-edge-view-coordination* (when *test-edge-view-coordination* (break "Threading bug? Expected the treetop edge ~A~ ~%to be present in the workbench edges table but ~ it isn't." edge))))) (when cell (let ((index (ccl:cell-to-index *edges-table* cell))) (ccl:scroll-to-cell *edges-table* 0 index))))) (defun scroll-edges-view/cons (wf) (let ((index (or (find-index-of-word-form/edges-table wf) (find-index-of-relevant-edges-gap (first wf)) (find-cell-of-edge-starting-at (first wf))))) (if index (ccl:scroll-to-cell *edges-table* 0 index) (when *break-on-unexpected-cases* (break "~&~%----- Scroll-edges-view/cons couldn't find ~ edges table index to scroll to~%~A~%-----~%" wf))))) (defun scroll-as-needed-to-make-edge-visible (edge) (let ((cell (find-cell-of-edge/edges-table edge))) (unless cell (break "Threading bug: edge is not in the table. Should an ~ earlier~%routine have opened its parents?~% ~A" edge)) (let* ((index (ccl:cell-to-index *edges-table* cell)) (top (ccl:point-v (ccl:scroll-position *edges-table*))) new-top ) two lines below top (setq new-top (+ top (- diff (- *no-lines/edges-table* 7))))) (setq new-top nil))) (when new-top (ccl:scroll-to-cell *edges-table* 0 new-top))))) (defvar *selected-edge/edges-view* nil "Points to the actual object in the table, either an edge or a word-form" ) (defvar *selected-cell/index/edges-view* nil "Points to an integer that is the location of the selected item in the table" ) (defvar *edge* nil "holds the last edge or word-form selected in the edges view") (defparameter *additional-edge-selection-action* nil "a hook for other parts of the workbench to use to have their own effects generated by the selection of an edge in the edges view.") (defun act-on-edge-in-view (table) (if (selected-cells table) (let* ((*click-originated-in-edges-view* t) (cell (car (ccl:selected-cells table))) (index (ccl:cell-to-index table cell)) (edge (elt (table-sequence table) index))) (setq *selected-edge/edges-view* edge *edge* edge *selected-cell/index/edges-view* index) (ccl:dialog-item-enable *edges/inspect-button*) (select-text-for-edge edge) (establish-edge-button-viability edge) (when (double-click-p) (double-click-action-for-edges-view edge)) (coordinate-subview-to-selected-edge edge) (when *additional-edge-selection-action* (funcall *additional-edge-selection-action* edge))) (else (ccl:dialog-item-disable *edges/inspect-button*)))) (defun double-click-action-for-edges-view (edge) (etypecase edge (edge (unless (daughters-already-visible edge) (edges/Open-edge-to-show-daughters))) (cons ))) (defun edges/inspect-edge (edges/inspect-button) (when *edge* (etypecase *edge* (edge (inspect *edge*)) (inspect (second *edge*)))) (ccl:dialog-item-disable edges/inspect-button)))
d7cdb2630d048604706f95b8decbf79c5d9e2d1bc49da320cefa5b281c0a0b0e
Kleidukos/Intrigue
Num.hs
module Intrigue.Environment.Num where import Data.Foldable import Data.Text (unpack) import Data.Text.Display import Data.Vector (Vector) import qualified Data.Vector as V import Intrigue.Types add :: Vector AST -> EvalM AST add operands = pure $ foldl' (\acc number -> applyBinOp (+) number acc ) (Number 0) operands sub :: Vector AST -> EvalM AST sub operands = pure $ foldl' (\acc number -> applyBinOp (-) number acc ) (Number 0) operands isNumber :: Vector AST -> EvalM AST isNumber args = pure $ Bool $ checkNumber $ V.head args equal :: Vector AST -> EvalM AST equal args = pure $ Bool $ all (== hd) tl where hd = V.head args tl = V.tail args lessThan :: Vector AST -> EvalM AST lessThan args = pure $ Bool $ transitive (<) args moreThan :: Vector AST -> EvalM AST moreThan args = pure $ Bool $ transitive (>) args lessOrEqual :: Vector AST -> EvalM AST lessOrEqual args = pure $ Bool $ transitive (<=) args moreOrEqual :: Vector AST -> EvalM AST moreOrEqual args = pure $ Bool $ transitive (>=) args isZero :: Vector AST -> EvalM AST isZero args = case V.head args of Number n -> pure $ Bool $ n == 0 x -> error $ "Argument mismatch, expected a Number, got " <> show x isPositive :: Vector AST -> EvalM AST isPositive args = case V.head args of Number n -> pure $ Bool $ n > 0 x -> error $ "Argument mismatch, expected a Number, got " <> show x isNegative :: Vector AST -> EvalM AST isNegative args = case V.head args of Number n -> pure $ Bool $ n < 0 x -> error $ "Argument mismatch, expected a Number, got " <> show x maxNum :: Vector AST -> EvalM AST maxNum args = pure $ Number $ V.maximum $ fmap getNumberContent args minNum :: Vector AST -> EvalM AST minNum args = pure $ Number $ V.minimum $ fmap getNumberContent args numOp :: (Vector AST -> EvalM AST) -> Vector AST -> EvalM AST numOp fun args = if all checkNumber args then fun args else error $ "Argument mismatch, expected a list of numbers, got " <> show args transitive :: (AST -> AST -> Bool) -> Vector AST -> Bool transitive fun args = and $ V.zipWith fun args (V.tail args) checkNumber :: AST -> Bool checkNumber (Number _) = True checkNumber _ = False getNumberContent :: AST -> Integer getNumberContent (Number n) = n getNumberContent x = error $ "Argument mismatch, expected Number, got " <> (unpack $ display x) applyNumber :: (Integer -> Integer) -> AST -> AST applyNumber f (Number n) = Number $ f n applyNumber _ x = error $ "Argument mismatch, expected Number, got " <> (unpack $ display x) applyBinOp :: (Integer -> Integer -> Integer) -> AST -> AST -> AST applyBinOp f (Number n) (Number m) = Number $ f n m applyBinOp _ x y = error $ unpack $ "Argument mismatch, expected Number, got " <> display x <> " and " <> display y
null
https://raw.githubusercontent.com/Kleidukos/Intrigue/d6cb7a0ee13c04b7ef0c8ca15ac5600da25100ff/src/Intrigue/Environment/Num.hs
haskell
module Intrigue.Environment.Num where import Data.Foldable import Data.Text (unpack) import Data.Text.Display import Data.Vector (Vector) import qualified Data.Vector as V import Intrigue.Types add :: Vector AST -> EvalM AST add operands = pure $ foldl' (\acc number -> applyBinOp (+) number acc ) (Number 0) operands sub :: Vector AST -> EvalM AST sub operands = pure $ foldl' (\acc number -> applyBinOp (-) number acc ) (Number 0) operands isNumber :: Vector AST -> EvalM AST isNumber args = pure $ Bool $ checkNumber $ V.head args equal :: Vector AST -> EvalM AST equal args = pure $ Bool $ all (== hd) tl where hd = V.head args tl = V.tail args lessThan :: Vector AST -> EvalM AST lessThan args = pure $ Bool $ transitive (<) args moreThan :: Vector AST -> EvalM AST moreThan args = pure $ Bool $ transitive (>) args lessOrEqual :: Vector AST -> EvalM AST lessOrEqual args = pure $ Bool $ transitive (<=) args moreOrEqual :: Vector AST -> EvalM AST moreOrEqual args = pure $ Bool $ transitive (>=) args isZero :: Vector AST -> EvalM AST isZero args = case V.head args of Number n -> pure $ Bool $ n == 0 x -> error $ "Argument mismatch, expected a Number, got " <> show x isPositive :: Vector AST -> EvalM AST isPositive args = case V.head args of Number n -> pure $ Bool $ n > 0 x -> error $ "Argument mismatch, expected a Number, got " <> show x isNegative :: Vector AST -> EvalM AST isNegative args = case V.head args of Number n -> pure $ Bool $ n < 0 x -> error $ "Argument mismatch, expected a Number, got " <> show x maxNum :: Vector AST -> EvalM AST maxNum args = pure $ Number $ V.maximum $ fmap getNumberContent args minNum :: Vector AST -> EvalM AST minNum args = pure $ Number $ V.minimum $ fmap getNumberContent args numOp :: (Vector AST -> EvalM AST) -> Vector AST -> EvalM AST numOp fun args = if all checkNumber args then fun args else error $ "Argument mismatch, expected a list of numbers, got " <> show args transitive :: (AST -> AST -> Bool) -> Vector AST -> Bool transitive fun args = and $ V.zipWith fun args (V.tail args) checkNumber :: AST -> Bool checkNumber (Number _) = True checkNumber _ = False getNumberContent :: AST -> Integer getNumberContent (Number n) = n getNumberContent x = error $ "Argument mismatch, expected Number, got " <> (unpack $ display x) applyNumber :: (Integer -> Integer) -> AST -> AST applyNumber f (Number n) = Number $ f n applyNumber _ x = error $ "Argument mismatch, expected Number, got " <> (unpack $ display x) applyBinOp :: (Integer -> Integer -> Integer) -> AST -> AST -> AST applyBinOp f (Number n) (Number m) = Number $ f n m applyBinOp _ x y = error $ unpack $ "Argument mismatch, expected Number, got " <> display x <> " and " <> display y
61f503052e7b5c88c39519717c9494b9e48934a74a5d68be80d08124ac4a0068
ghcjs/ghcjs
dsrun002.hs
{- Tests let-expressions in do-statments -} module Main( main ) where foo = do putStr "a" let x = "b" in putStr x putStr "c" main = do putStr "a" foo let x = "b" in putStrLn x
null
https://raw.githubusercontent.com/ghcjs/ghcjs/e4cd4232a31f6371c761acd93853702f4c7ca74c/test/ghc/deSugar/dsrun002.hs
haskell
Tests let-expressions in do-statments
module Main( main ) where foo = do putStr "a" let x = "b" in putStr x putStr "c" main = do putStr "a" foo let x = "b" in putStrLn x
d95fe4ceb9cbbfbbc43730ec0d97546b074463abba2b4607cc50fed7aaa6db51
dorchard/effect-monad
Problem1.hs
{-# LANGUAGE NoMonomorphismRestriction, FlexibleContexts #-} import Control.Monad.State.Lazy appendBuffer x = do buff <- get put (buff ++ x) hello :: Monad m => StateT String (StateT String m) () hello = do name <- get lift $ appendBuffer $ "hello " ++ name incSC :: (Monad m) => StateT Int m () incSC = do x <- get put (x + 1) writeS :: (Monad m) => [a] -> StateT [a] m () writeS y = do x <- get put (x ++ y) write :: (Monad m) => [a] -> StateT [a] (StateT Int m) () write x = do writeS x lift $ incSC hellow = do write "hello" write " " write "world" runHellow = runStateT (runStateT hellow "") 0 -- prog2 :: (Monad m) => StateT Int (StateT String (StateT Int (StateT String m))) () hellowCount = do hellow lift $ lift $ incSC runHellowCount = runStateT (runStateT (runStateT hellowCount "") 0) 1
null
https://raw.githubusercontent.com/dorchard/effect-monad/5750ef8438f750e528002a0a4e255514cbf3150a/examples/Problem1.hs
haskell
# LANGUAGE NoMonomorphismRestriction, FlexibleContexts # prog2 :: (Monad m) => StateT Int (StateT String (StateT Int (StateT String m))) ()
import Control.Monad.State.Lazy appendBuffer x = do buff <- get put (buff ++ x) hello :: Monad m => StateT String (StateT String m) () hello = do name <- get lift $ appendBuffer $ "hello " ++ name incSC :: (Monad m) => StateT Int m () incSC = do x <- get put (x + 1) writeS :: (Monad m) => [a] -> StateT [a] m () writeS y = do x <- get put (x ++ y) write :: (Monad m) => [a] -> StateT [a] (StateT Int m) () write x = do writeS x lift $ incSC hellow = do write "hello" write " " write "world" runHellow = runStateT (runStateT hellow "") 0 hellowCount = do hellow lift $ lift $ incSC runHellowCount = runStateT (runStateT (runStateT hellowCount "") 0) 1
9876222465c8da9433aca2931fc5ac9c43d5849be450910c26385b5328ad669c
anuyts/menkar
Syntax.hs
module Menkar.Basic.Syntax where import Control.DeepSeq.Redone import GHC.Generics import Data.Hashable data Opness = NonOp | Op deriving (Show, Eq, Generic, Hashable, NFData) data Name = Name {opnessName :: Opness, stringName :: String} deriving (Eq, Generic, Hashable, NFData) --deriving Show data Qualified a = Qualified [String] a deriving (Functor, Foldable, Traversable, Eq, Generic1, NFData1) --deriving instance Show a => Show (Qualified a) type QName = Qualified Name data ArgSpec = ArgSpecNext | ArgSpecExplicit | ArgSpecNamed Name deriving (Generic, NFData) data ProjSpec = ProjSpecNamed Name | ProjSpecNumbered Int | ProjSpecTail Int deriving (Generic, NFData)
null
https://raw.githubusercontent.com/anuyts/menkar/1f00e9febd1e9ed70c138ae8232b1c72a17d31da/menkar/src/Menkar/Basic/Syntax.hs
haskell
deriving Show deriving instance Show a => Show (Qualified a)
module Menkar.Basic.Syntax where import Control.DeepSeq.Redone import GHC.Generics import Data.Hashable data Opness = NonOp | Op deriving (Show, Eq, Generic, Hashable, NFData) data Qualified a = Qualified [String] a deriving (Functor, Foldable, Traversable, Eq, Generic1, NFData1) type QName = Qualified Name data ArgSpec = ArgSpecNext | ArgSpecExplicit | ArgSpecNamed Name deriving (Generic, NFData) data ProjSpec = ProjSpecNamed Name | ProjSpecNumbered Int | ProjSpecTail Int deriving (Generic, NFData)
171304fbe749b689125def8849a4ef9dba2414f50e332a4dc90a1a49dbfb69ad
y2q-actionman/with-c-syntax
case-aware-find-symbol.lisp
(in-package #:with-c-syntax.core) (defmacro define-case-aware-find-symbol (finder-function-name package-name &key (upcased-package-name (format nil "~A.~A" (string package-name) '#:UPCASED)) (docstring (format nil "Find a symbol in `~A' package having a same NAME. If not found, returns `nil'." package-name))) `(eval-when (:compile-toplevel :load-toplevel :execute) (defpackage ,upcased-package-name (:use) (:intern ,@(loop for sym being the external-symbol of package-name collect (string-upcase (symbol-name sym))))) ,@(loop for sym being the external-symbol of package-name for upcased = (string-upcase (symbol-name sym)) collect `(setf (symbol-value (find-symbol ,upcased ',upcased-package-name)) ',sym)) (defun ,finder-function-name (string &optional (readtable-case (readtable-case *readtable*))) ,@(if docstring `(,docstring)) (ecase readtable-case ((:upcase :invert) (if-let ((up-sym (find-symbol string ',upcased-package-name))) (symbol-value up-sym))) ((:downcase :preserve) (find-symbol string ',package-name)))))) (define-case-aware-find-symbol find-c-terminal #:with-c-syntax.syntax) (define-case-aware-find-symbol find-preprocessor-directive #:with-c-syntax.preprocessor-directive) (define-case-aware-find-symbol find-pp-operator-name #:with-c-syntax.preprocess-operator) (define-case-aware-find-symbol find-pragma-name #:with-c-syntax.pragma-name) (defmacro define-case-aware-token-p-function (function-name find-symbol-function symbol) `(defun ,function-name (token &optional (readtable-case (readtable-case *readtable*))) (and (symbolp token) (eq (,find-symbol-function (string token) readtable-case) ',symbol)))) (define-case-aware-token-p-function pp-pragma-directive-p find-preprocessor-directive with-c-syntax.preprocessor-directive:|pragma|) (define-case-aware-token-p-function pp-defined-operator-p find-pp-operator-name with-c-syntax.preprocess-operator:|defined|) (define-case-aware-token-p-function pp-pragma-operator-p find-pp-operator-name with-c-syntax.preprocess-operator:|_Pragma|) (define-case-aware-token-p-function pp-stdc-pragma-p find-pragma-name with-c-syntax.pragma-name:|STDC|) (define-case-aware-token-p-function pp-with-c-syntax-pragma-p find-pragma-name with-c-syntax.pragma-name:|WITH_C_SYNTAX|) (define-case-aware-token-p-function pp-once-pragma-p find-pragma-name with-c-syntax.pragma-name:|once|)
null
https://raw.githubusercontent.com/y2q-actionman/with-c-syntax/fa212ff8e570272aea6c6de247d8f03751e60843/src/case-aware-find-symbol.lisp
lisp
(in-package #:with-c-syntax.core) (defmacro define-case-aware-find-symbol (finder-function-name package-name &key (upcased-package-name (format nil "~A.~A" (string package-name) '#:UPCASED)) (docstring (format nil "Find a symbol in `~A' package having a same NAME. If not found, returns `nil'." package-name))) `(eval-when (:compile-toplevel :load-toplevel :execute) (defpackage ,upcased-package-name (:use) (:intern ,@(loop for sym being the external-symbol of package-name collect (string-upcase (symbol-name sym))))) ,@(loop for sym being the external-symbol of package-name for upcased = (string-upcase (symbol-name sym)) collect `(setf (symbol-value (find-symbol ,upcased ',upcased-package-name)) ',sym)) (defun ,finder-function-name (string &optional (readtable-case (readtable-case *readtable*))) ,@(if docstring `(,docstring)) (ecase readtable-case ((:upcase :invert) (if-let ((up-sym (find-symbol string ',upcased-package-name))) (symbol-value up-sym))) ((:downcase :preserve) (find-symbol string ',package-name)))))) (define-case-aware-find-symbol find-c-terminal #:with-c-syntax.syntax) (define-case-aware-find-symbol find-preprocessor-directive #:with-c-syntax.preprocessor-directive) (define-case-aware-find-symbol find-pp-operator-name #:with-c-syntax.preprocess-operator) (define-case-aware-find-symbol find-pragma-name #:with-c-syntax.pragma-name) (defmacro define-case-aware-token-p-function (function-name find-symbol-function symbol) `(defun ,function-name (token &optional (readtable-case (readtable-case *readtable*))) (and (symbolp token) (eq (,find-symbol-function (string token) readtable-case) ',symbol)))) (define-case-aware-token-p-function pp-pragma-directive-p find-preprocessor-directive with-c-syntax.preprocessor-directive:|pragma|) (define-case-aware-token-p-function pp-defined-operator-p find-pp-operator-name with-c-syntax.preprocess-operator:|defined|) (define-case-aware-token-p-function pp-pragma-operator-p find-pp-operator-name with-c-syntax.preprocess-operator:|_Pragma|) (define-case-aware-token-p-function pp-stdc-pragma-p find-pragma-name with-c-syntax.pragma-name:|STDC|) (define-case-aware-token-p-function pp-with-c-syntax-pragma-p find-pragma-name with-c-syntax.pragma-name:|WITH_C_SYNTAX|) (define-case-aware-token-p-function pp-once-pragma-p find-pragma-name with-c-syntax.pragma-name:|once|)
a25ae2e0d9b61399a560c203d48febf341046f851af7227c1c1cc4be313db24b
mooreryan/ocaml_python_bindgen
mkdir.ml
open! Base type file_perm = int [@@deriving of_sexp] module Mkdir : sig val mkdir : ?perm:file_perm -> string -> unit val mkdir_p : ?perm:file_perm -> string -> unit end = struct let atom x = Sexp.Atom x let list x = Sexp.List x let record l = list (List.map l ~f:(fun (name, value) -> list [ atom name; value ])) This wrapper improves the content of the Unix_error exception raised by the standard library ( by including a sexp of the function arguments ) , and it optionally restarts syscalls on . standard library (by including a sexp of the function arguments), and it optionally restarts syscalls on EINTR. *) let improve f make_arg_sexps = try f () with Unix.Unix_error (e, s, _) -> let buf = Buffer.create 100 in let fmt = Caml.Format.formatter_of_buffer buf in Caml.Format.pp_set_margin fmt 10000; Sexp.pp_hum fmt (record (make_arg_sexps ())); Caml.Format.pp_print_flush fmt (); let arg_str = Buffer.contents buf in raise (Unix.Unix_error (e, s, arg_str)) let dirname_r filename = ("dirname", atom filename) let file_perm_r perm = ("perm", atom (Printf.sprintf "0o%o" perm)) let[@inline always] improve_mkdir mkdir dirname perm = improve (fun () -> mkdir dirname perm) (fun () -> [ dirname_r dirname; file_perm_r perm ]) let mkdir = improve_mkdir Unix.mkdir let mkdir_idempotent dirname perm = match Unix.mkdir dirname perm with | () -> () [ mkdir ] on returns [ EISDIR ] instead of [ EEXIST ] if the directory already exists . already exists. *) | exception Unix.Unix_error ((EEXIST | EISDIR), _, _) -> () let mkdir_idempotent = improve_mkdir mkdir_idempotent let rec mkdir_p dir perm = match mkdir_idempotent dir perm with | () -> () | exception (Unix.Unix_error (ENOENT, _, _) as exn) -> let parent = Caml.Filename.dirname dir in if String.( = ) parent dir then raise exn else ( mkdir_p parent perm; mkdir_idempotent dir perm) let mkdir ?(perm = 0o750) dir = mkdir dir perm let mkdir_p ?(perm = 0o750) dir = mkdir_p dir perm end include Mkdir Apapted from JaneStreet Core_unix . Original license follows . The MIT License Copyright ( c ) 2008 - -2022 Jane Street Group , 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 . Copyright (c) 2008--2022 Jane Street Group, 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. *)
null
https://raw.githubusercontent.com/mooreryan/ocaml_python_bindgen/2d8439c9c7ad3ec00264644cdb62687529a2f2a2/lib/mkdir.ml
ocaml
open! Base type file_perm = int [@@deriving of_sexp] module Mkdir : sig val mkdir : ?perm:file_perm -> string -> unit val mkdir_p : ?perm:file_perm -> string -> unit end = struct let atom x = Sexp.Atom x let list x = Sexp.List x let record l = list (List.map l ~f:(fun (name, value) -> list [ atom name; value ])) This wrapper improves the content of the Unix_error exception raised by the standard library ( by including a sexp of the function arguments ) , and it optionally restarts syscalls on . standard library (by including a sexp of the function arguments), and it optionally restarts syscalls on EINTR. *) let improve f make_arg_sexps = try f () with Unix.Unix_error (e, s, _) -> let buf = Buffer.create 100 in let fmt = Caml.Format.formatter_of_buffer buf in Caml.Format.pp_set_margin fmt 10000; Sexp.pp_hum fmt (record (make_arg_sexps ())); Caml.Format.pp_print_flush fmt (); let arg_str = Buffer.contents buf in raise (Unix.Unix_error (e, s, arg_str)) let dirname_r filename = ("dirname", atom filename) let file_perm_r perm = ("perm", atom (Printf.sprintf "0o%o" perm)) let[@inline always] improve_mkdir mkdir dirname perm = improve (fun () -> mkdir dirname perm) (fun () -> [ dirname_r dirname; file_perm_r perm ]) let mkdir = improve_mkdir Unix.mkdir let mkdir_idempotent dirname perm = match Unix.mkdir dirname perm with | () -> () [ mkdir ] on returns [ EISDIR ] instead of [ EEXIST ] if the directory already exists . already exists. *) | exception Unix.Unix_error ((EEXIST | EISDIR), _, _) -> () let mkdir_idempotent = improve_mkdir mkdir_idempotent let rec mkdir_p dir perm = match mkdir_idempotent dir perm with | () -> () | exception (Unix.Unix_error (ENOENT, _, _) as exn) -> let parent = Caml.Filename.dirname dir in if String.( = ) parent dir then raise exn else ( mkdir_p parent perm; mkdir_idempotent dir perm) let mkdir ?(perm = 0o750) dir = mkdir dir perm let mkdir_p ?(perm = 0o750) dir = mkdir_p dir perm end include Mkdir Apapted from JaneStreet Core_unix . Original license follows . The MIT License Copyright ( c ) 2008 - -2022 Jane Street Group , 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 . Copyright (c) 2008--2022 Jane Street Group, 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. *)
b3f1e92ad21595d8a16fedaf999cb0d86f68b25f5dc0af0d54916aae87387440
hpyhacking/openpoker
client.erl
-module(client). -export([loop/2, send/1, send/2]). -include("openpoker.hrl"). -record(pdata, { timer = ?UNDEF, server = global:whereis_name(server), player = ?UNDEF }). loop(connected, ?UNDEF) -> #pdata{timer = erlang:start_timer(?CONNECT_TIMEOUT, self(), ?MODULE)}; loop({connected, _Timeout}, ?UNDEF) -> #pdata{timer = erlang:start_timer(?CONNECT_TIMEOUT, self(), ?MODULE)}; loop(disconnected, _Data = #pdata{}) -> ok; loop({loopdata, player}, Data = #pdata{}) -> Data#pdata.player; loop({recv, Bin}, Data = #pdata{}) when is_binary(Bin) -> case catch protocol:read(Bin) of {'EXIT', {Reason, Stack}} -> ?LOG([{recv, Bin}, {error, {Reason, Stack}}]), err(?ERR_DATA); R -> loop({protocol, R}, Data) end; cancel connection timer when remote client first send protocol must # login loop({protocol, R = #cmd_login{}}, Data = #pdata{timer = T}) when T /= ?UNDEF -> catch erlang:cancel_timer(T), loop({protocol, R}, Data#pdata{timer = ?UNDEF}); loop({protocol, #cmd_login{identity = Identity, password = Password}}, Data) -> case player:auth(binary_to_list(Identity), binary_to_list(Password)) of {ok, unauth} -> err(?ERR_UNAUTH); {ok, player_disable} -> err(?ERR_PLAYER_DISABLE); {ok, pass, Info} -> % create player process by client process, receive { ' EXIT ' } when player process error case player:start(Info) of {ok, Player} when is_pid(Player) -> player:client(Player), player:info(Player), player:balance(Player), Data#pdata{player = Player} end end; loop({protocol, #cmd_logout{}}, #pdata{player = Player}) when is_pid(Player) -> {ok, logout} = player:logout(Player), close_connection(); loop({protocol, #cmd_logout{}}, _Data) -> err(?ERR_PROTOCOL); loop({protocol, #cmd_query_game{}}, Data = #pdata{player = Player}) when is_pid(Player) -> Infos = game:list(), lists:map(fun(Info) -> send(Info) end, Infos), Data; loop({protocol, R}, Data = #pdata{player = Player}) when is_pid(Player) -> player:cast(Player, R), Data; loop({msg, {timeout, _, ?MODULE}}, _Data) -> err(?ERR_CONNECTION_TIMEOUT). %%% %%% client %%% send(R) -> op_game_handler:send(R). send(PID, R) when is_pid(PID), is_tuple(R) -> op_game_handler:send(PID, R). %%% %%% private %%% err(Code) when is_integer(Code) -> send(#notify_error{error = Code}), close_connection(). close_connection() -> self() ! close.
null
https://raw.githubusercontent.com/hpyhacking/openpoker/643193c94f34096cdcfcd610bdb1f18e7bf1e45e/src/client.erl
erlang
create player process by client process, client private
-module(client). -export([loop/2, send/1, send/2]). -include("openpoker.hrl"). -record(pdata, { timer = ?UNDEF, server = global:whereis_name(server), player = ?UNDEF }). loop(connected, ?UNDEF) -> #pdata{timer = erlang:start_timer(?CONNECT_TIMEOUT, self(), ?MODULE)}; loop({connected, _Timeout}, ?UNDEF) -> #pdata{timer = erlang:start_timer(?CONNECT_TIMEOUT, self(), ?MODULE)}; loop(disconnected, _Data = #pdata{}) -> ok; loop({loopdata, player}, Data = #pdata{}) -> Data#pdata.player; loop({recv, Bin}, Data = #pdata{}) when is_binary(Bin) -> case catch protocol:read(Bin) of {'EXIT', {Reason, Stack}} -> ?LOG([{recv, Bin}, {error, {Reason, Stack}}]), err(?ERR_DATA); R -> loop({protocol, R}, Data) end; cancel connection timer when remote client first send protocol must # login loop({protocol, R = #cmd_login{}}, Data = #pdata{timer = T}) when T /= ?UNDEF -> catch erlang:cancel_timer(T), loop({protocol, R}, Data#pdata{timer = ?UNDEF}); loop({protocol, #cmd_login{identity = Identity, password = Password}}, Data) -> case player:auth(binary_to_list(Identity), binary_to_list(Password)) of {ok, unauth} -> err(?ERR_UNAUTH); {ok, player_disable} -> err(?ERR_PLAYER_DISABLE); {ok, pass, Info} -> receive { ' EXIT ' } when player process error case player:start(Info) of {ok, Player} when is_pid(Player) -> player:client(Player), player:info(Player), player:balance(Player), Data#pdata{player = Player} end end; loop({protocol, #cmd_logout{}}, #pdata{player = Player}) when is_pid(Player) -> {ok, logout} = player:logout(Player), close_connection(); loop({protocol, #cmd_logout{}}, _Data) -> err(?ERR_PROTOCOL); loop({protocol, #cmd_query_game{}}, Data = #pdata{player = Player}) when is_pid(Player) -> Infos = game:list(), lists:map(fun(Info) -> send(Info) end, Infos), Data; loop({protocol, R}, Data = #pdata{player = Player}) when is_pid(Player) -> player:cast(Player, R), Data; loop({msg, {timeout, _, ?MODULE}}, _Data) -> err(?ERR_CONNECTION_TIMEOUT). send(R) -> op_game_handler:send(R). send(PID, R) when is_pid(PID), is_tuple(R) -> op_game_handler:send(PID, R). err(Code) when is_integer(Code) -> send(#notify_error{error = Code}), close_connection(). close_connection() -> self() ! close.
3b6c73da10aa8e991a890640986db8a50fd4bca8f387ff379819fd47d7147c03
stevebleazard/ocaml-jsonxt
extended.mli
* [ Extended ] supports parsing and writing JSON data that conforms to the { ! type : Json . Extended.json } json type . This supports non - standard JSON types including integer as well as tuples and variants introduced by [ Yojson ] . The maximim / minimum size of an integer is architecture specific , typically 30 or 62 bits depending on the platform . In cases where the integer overflows the value is converted to a ` Float . For integers in the range ( + /-)2 ^ 53 there is no loss of precision {!type:Json.Extended.json} json type. This supports non-standard JSON types including integer as well as tuples and variants introduced by [Yojson]. The maximim/minimum size of an integer is architecture specific, typically 30 or 62 bits depending on the platform. In cases where the integer overflows the value is converted to a `Float. For integers in the range (+/-)2^53 there is no loss of precision *) type json = Json.Extended.json type t = json * { 1 Reader functions } include (Reader_string_file.Reader_string_file with type json := json) * { 1 Writer functions } include (Writer_intf.Intf with type json := Json.Extended.json) (** {1 Processing functions} *) module Process : sig include (module type of Process.Extended) end * { 1 Internal modules } module Compliance : Compliance.S with type json = Json.Extended.json and type json_stream = Json_stream.Extended.json
null
https://raw.githubusercontent.com/stevebleazard/ocaml-jsonxt/fe982b6087dd76ca003d8fbc19ae9a519f54b828/lib/extended.mli
ocaml
* {1 Processing functions}
* [ Extended ] supports parsing and writing JSON data that conforms to the { ! type : Json . Extended.json } json type . This supports non - standard JSON types including integer as well as tuples and variants introduced by [ Yojson ] . The maximim / minimum size of an integer is architecture specific , typically 30 or 62 bits depending on the platform . In cases where the integer overflows the value is converted to a ` Float . For integers in the range ( + /-)2 ^ 53 there is no loss of precision {!type:Json.Extended.json} json type. This supports non-standard JSON types including integer as well as tuples and variants introduced by [Yojson]. The maximim/minimum size of an integer is architecture specific, typically 30 or 62 bits depending on the platform. In cases where the integer overflows the value is converted to a `Float. For integers in the range (+/-)2^53 there is no loss of precision *) type json = Json.Extended.json type t = json * { 1 Reader functions } include (Reader_string_file.Reader_string_file with type json := json) * { 1 Writer functions } include (Writer_intf.Intf with type json := Json.Extended.json) module Process : sig include (module type of Process.Extended) end * { 1 Internal modules } module Compliance : Compliance.S with type json = Json.Extended.json and type json_stream = Json_stream.Extended.json
218abe56233a484c866b6262e737663dc0fa8c72afe1b7944493b7aec1aed797
dmitryvk/sbcl-win32-threads
arith.lisp
;;;; the VM definition arithmetic VOPs for HPPA This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the ;;;; public domain. The software is in the public domain and is ;;;; provided with absolutely no warranty. See the COPYING and CREDITS ;;;; files for more information. (in-package "SB!VM") Unary operations . (define-vop (fast-safe-arith-op) (:policy :fast-safe) (:effects) (:affected)) (define-vop (fixnum-unop fast-safe-arith-op) (:args (x :scs (any-reg))) (:results (res :scs (any-reg))) (:note "inline fixnum arithmetic") (:arg-types tagged-num) (:result-types tagged-num)) (define-vop (signed-unop fast-safe-arith-op) (:args (x :scs (signed-reg))) (:results (res :scs (signed-reg))) (:note "inline (signed-byte 32) arithmetic") (:arg-types signed-num) (:result-types signed-num)) (define-vop (fast-negate/fixnum fixnum-unop) (:translate %negate) (:generator 1 (inst sub zero-tn x res))) (define-vop (fast-negate/signed signed-unop) (:translate %negate) (:generator 2 (inst sub zero-tn x res))) (define-vop (fast-lognot/fixnum fixnum-unop) (:translate lognot) (:temporary (:scs (any-reg) :type fixnum :to (:result 0)) temp) (:generator 1 (inst li (fixnumize -1) temp) (inst xor x temp res))) (define-vop (fast-lognot/signed signed-unop) (:translate lognot) (:generator 2 (inst uaddcm zero-tn x res))) ;;;; Binary fixnum operations. Assume that any constant operand is the second arg ... (define-vop (fast-fixnum-binop fast-safe-arith-op) (:args (x :target r :scs (any-reg zero)) (y :target r :scs (any-reg zero))) (:arg-types tagged-num tagged-num) (:results (r :scs (any-reg))) (:result-types tagged-num) (:note "inline fixnum arithmetic")) (define-vop (fast-unsigned-binop fast-safe-arith-op) (:args (x :target r :scs (unsigned-reg zero)) (y :target r :scs (unsigned-reg zero))) (:arg-types unsigned-num unsigned-num) (:results (r :scs (unsigned-reg))) (:result-types unsigned-num) (:note "inline (unsigned-byte 32) arithmetic")) (define-vop (fast-signed-binop fast-safe-arith-op) (:args (x :target r :scs (signed-reg zero)) (y :target r :scs (signed-reg zero))) (:arg-types signed-num signed-num) (:results (r :scs (signed-reg))) (:result-types signed-num) (:note "inline (signed-byte 32) arithmetic")) (define-vop (fast-fixnum-c-binop fast-fixnum-binop) (:args (x :target r :scs (any-reg))) (:info y) (:arg-types tagged-num (:constant integer))) (define-vop (fast-signed-c-binop fast-signed-binop) (:args (x :target r :scs (signed-reg))) (:info y) (:arg-types tagged-num (:constant integer))) (define-vop (fast-unsigned-c-binop fast-unsigned-binop) (:args (x :target r :scs (unsigned-reg))) (:info y) (:arg-types tagged-num (:constant integer))) (macrolet ((define-binop (translate cost untagged-cost op arg-swap) `(progn (define-vop (,(symbolicate "FAST-" translate "/FIXNUM=>FIXNUM") fast-fixnum-binop) (:args (x :target r :scs (any-reg)) (y :target r :scs (any-reg))) (:translate ,translate) (:generator ,(1+ cost) ,(if arg-swap `(inst ,op y x r) `(inst ,op x y r)))) (define-vop (,(symbolicate "FAST-" translate "/SIGNED=>SIGNED") fast-signed-binop) (:args (x :target r :scs (signed-reg)) (y :target r :scs (signed-reg))) (:translate ,translate) (:generator ,(1+ untagged-cost) ,(if arg-swap `(inst ,op y x r) `(inst ,op x y r)))) (define-vop (,(symbolicate "FAST-" translate "/UNSIGNED=>UNSIGNED") fast-unsigned-binop) (:args (x :target r :scs (unsigned-reg)) (y :target r :scs (unsigned-reg))) (:translate ,translate) (:generator ,(1+ untagged-cost) ,(if arg-swap `(inst ,op y x r) `(inst ,op x y r))))))) (define-binop + 1 5 add nil) (define-binop - 1 5 sub nil) (define-binop logior 1 2 or nil) (define-binop logand 1 2 and nil) (define-binop logandc1 1 2 andcm t) (define-binop logandc2 1 2 andcm nil) (define-binop logxor 1 2 xor nil)) (macrolet ((define-c-binop (translate cost untagged-cost tagged-type untagged-type inst) `(progn (define-vop (,(symbolicate "FAST-" translate "-C/FIXNUM=>FIXNUM") fast-fixnum-c-binop) (:arg-types tagged-num (:constant ,tagged-type)) (:translate ,translate) (:generator ,cost (let ((y (fixnumize y))) ,inst))) (define-vop (,(symbolicate "FAST-" translate "-C/SIGNED=>SIGNED") fast-signed-c-binop) (:arg-types signed-num (:constant ,untagged-type)) (:translate ,translate) (:generator ,untagged-cost ,inst)) (define-vop (,(symbolicate "FAST-" translate "-C/UNSIGNED=>UNSIGNED") fast-unsigned-c-binop) (:arg-types unsigned-num (:constant ,untagged-type)) (:translate ,translate) (:generator ,untagged-cost ,inst))))) (define-c-binop + 1 3 (signed-byte 9) (signed-byte 11) (inst addi y x r)) (define-c-binop - 1 3 (integer #.(- 1 (ash 1 8)) #.(ash 1 8)) (integer #.(- 1 (ash 1 10)) #.(ash 1 10)) (inst addi (- y) x r))) (define-vop (fast-lognor/fixnum=>fixnum fast-fixnum-binop) (:translate lognor) (:args (x :target r :scs (any-reg)) (y :target r :scs (any-reg))) (:temporary (:sc non-descriptor-reg) temp) (:generator 4 (inst or x y temp) (inst uaddcm zero-tn temp temp) (inst addi (- fixnum-tag-mask) temp r))) (define-vop (fast-lognor/signed=>signed fast-signed-binop) (:translate lognor) (:args (x :target r :scs (signed-reg)) (y :target r :scs (signed-reg))) (:generator 4 (inst or x y r) (inst uaddcm zero-tn r r))) (define-vop (fast-lognor/unsigned=>unsigned fast-unsigned-binop) (:translate lognor) (:args (x :target r :scs (unsigned-reg)) (y :target r :scs (unsigned-reg))) (:generator 4 (inst or x y r) (inst uaddcm zero-tn r r))) ;;; Shifting (macrolet ((fast-ash (name reg num tag save) `(define-vop (,name) (:translate ash) (:note "inline ASH") (:policy :fast-safe) (:args (number :scs (,reg) :to :save) (count :scs (signed-reg) ,@(if save '(:to :save)))) (:arg-types ,num ,tag) (:results (result :scs (,reg))) (:result-types ,num) (:temporary (:scs (unsigned-reg) :to (:result 0)) temp) (:generator 8 (inst comb :>= count zero-tn positive :nullify t) (inst sub zero-tn count temp) (inst comiclr 31 temp zero-tn :>=) (inst li 31 temp) (inst mtctl temp :sar) (inst extrs number 0 1 temp) (inst b done) (inst shd temp number :variable result) POSITIVE (inst subi 31 count temp) (inst mtctl temp :sar) (inst zdep number :variable 32 result) DONE)))) (fast-ash fast-ash/unsigned=>unsigned unsigned-reg unsigned-num tagged-num t) (fast-ash fast-ash/signed=>signed signed-reg signed-num signed-num nil)) (define-vop (fast-ash-c/unsigned=>unsigned) (:translate ash) (:note "inline ASH") (:policy :fast-safe) (:args (number :scs (unsigned-reg))) (:info count) (:arg-types unsigned-num (:constant integer)) (:results (result :scs (unsigned-reg))) (:result-types unsigned-num) (:generator 1 (cond ((< count -31) (move zero-tn result)) ((< count 0) (inst srl number (min (- count) 31) result)) ((> count 0) (inst sll number (min count 31) result)) (t (bug "identity ASH not transformed away"))))) (define-vop (fast-ash-c/signed=>signed) (:translate ash) (:note "inline ASH") (:policy :fast-safe) (:args (number :scs (signed-reg))) (:info count) (:arg-types signed-num (:constant integer)) (:results (result :scs (signed-reg))) (:result-types signed-num) (:generator 1 (cond ((< count 0) (inst sra number (min (- count) 31) result)) ((> count 0) (inst sll number (min count 31) result)) (t (bug "identity ASH not transformed away"))))) (macrolet ((def (name sc-type type result-type cost) `(define-vop (,name) (:translate ash) (:note "inline ASH") (:policy :fast-safe) (:args (number :scs (,sc-type)) (amount :scs (signed-reg unsigned-reg immediate))) (:arg-types ,type positive-fixnum) (:results (result :scs (,result-type))) (:result-types ,type) (:temporary (:scs (,sc-type) :to (:result 0)) temp) (:generator ,cost (sc-case amount ((signed-reg unsigned-reg) (inst subi 31 amount temp) (inst mtctl temp :sar) (inst zdep number :variable 32 result)) (immediate (let ((amount (tn-value amount))) (aver (> amount 0)) (inst sll number amount result)))))))) (def fast-ash-left/fixnum=>fixnum any-reg tagged-num any-reg 2) (def fast-ash-left/signed=>signed signed-reg signed-num signed-reg 3) (def fast-ash-left/unsigned=>unsigned unsigned-reg unsigned-num unsigned-reg 3)) (define-vop (signed-byte-32-len) (:translate integer-length) (:note "inline (signed-byte 32) integer-length") (:policy :fast-safe) (:args (arg :scs (signed-reg) :target shift)) (:arg-types signed-num) (:results (res :scs (any-reg))) (:result-types positive-fixnum) (:temporary (:scs (non-descriptor-reg) :from (:argument 0)) shift) (:generator 30 (inst move arg shift :>=) (inst uaddcm zero-tn shift shift) (inst comb := shift zero-tn done) (inst li 0 res) LOOP (inst srl shift 1 shift) (inst comb :<> shift zero-tn loop) (inst addi (fixnumize 1) res res) DONE)) (define-vop (unsigned-byte-32-count) (:translate logcount) (:note "inline (unsigned-byte 32) logcount") (:policy :fast-safe) (:args (arg :scs (unsigned-reg) :target num)) (:arg-types unsigned-num) (:results (res :scs (unsigned-reg))) (:result-types positive-fixnum) (:temporary (:scs (non-descriptor-reg) :from (:argument 0) :to (:result 0) :target res) num) (:temporary (:scs (non-descriptor-reg)) mask temp) (:generator 30 (inst li #x55555555 mask) (inst srl arg 1 temp) (inst and arg mask num) (inst and temp mask temp) (inst add num temp num) (inst li #x33333333 mask) (inst srl num 2 temp) (inst and num mask num) (inst and temp mask temp) (inst add num temp num) (inst li #x0f0f0f0f mask) (inst srl num 4 temp) (inst and num mask num) (inst and temp mask temp) (inst add num temp num) (inst li #x00ff00ff mask) (inst srl num 8 temp) (inst and num mask num) (inst and temp mask temp) (inst add num temp num) (inst li #x0000ffff mask) (inst srl num 16 temp) (inst and num mask num) (inst and temp mask temp) (inst add num temp res))) ;;; Multiply and Divide. (define-vop (fast-*/fixnum=>fixnum fast-fixnum-binop) (:translate *) (:args (x :scs (any-reg zero) :target x-pass) (y :scs (any-reg zero) :target y-pass)) (:temporary (:sc signed-reg :offset nl0-offset :from (:argument 0) :to (:result 0)) x-pass) (:temporary (:sc signed-reg :offset nl1-offset :from (:argument 1) :to (:result 0)) y-pass) (:temporary (:sc signed-reg :offset nl2-offset :target r :from (:argument 1) :to (:result 0)) res-pass) (:temporary (:sc signed-reg :offset nl3-offset :to (:result 0)) tmp) (:temporary (:sc signed-reg :offset nl4-offset :from (:argument 1) :to (:result 0)) sign) (:temporary (:sc interior-reg :offset lip-offset) lip) (:ignore lip sign) ; fix-lav: why dont we ignore tmp ? (:generator 30 ;; looking at the register setup above, not sure if both can clash ;; maybe it is ok that x and x-pass share register ? like it was (unless (location= y y-pass) (inst sra x 2 x-pass)) (let ((fixup (make-fixup 'multiply :assembly-routine))) (inst ldil fixup tmp) (inst ble fixup lisp-heap-space tmp)) (if (location= y y-pass) (inst sra x 2 x-pass) (inst move y y-pass)) (move res-pass r))) (define-vop (fast-*/signed=>signed fast-signed-binop) (:translate *) (:args (x :scs (signed-reg) :target x-pass) (y :scs (signed-reg) :target y-pass)) (:temporary (:sc signed-reg :offset nl0-offset :from (:argument 0) :to (:result 0)) x-pass) (:temporary (:sc signed-reg :offset nl1-offset :from (:argument 1) :to (:result 0)) y-pass) (:temporary (:sc signed-reg :offset nl2-offset :target r :from (:argument 1) :to (:result 0)) res-pass) (:temporary (:sc signed-reg :offset nl3-offset :to (:result 0)) tmp) (:temporary (:sc signed-reg :offset nl4-offset :from (:argument 1) :to (:result 0)) sign) (:temporary (:sc interior-reg :offset lip-offset) lip) (:ignore lip sign) (:generator 31 (let ((fixup (make-fixup 'multiply :assembly-routine))) (move x x-pass) (move y y-pass) (inst ldil fixup tmp) (inst ble fixup lisp-heap-space tmp) (inst nop) (move res-pass r)))) (define-vop (fast-*/unsigned=>unsigned fast-unsigned-binop) (:translate *) (:args (x :scs (unsigned-reg) :target x-pass) (y :scs (unsigned-reg) :target y-pass)) (:temporary (:sc unsigned-reg :offset nl0-offset :from (:argument 0) :to (:result 0)) x-pass) (:temporary (:sc unsigned-reg :offset nl1-offset :from (:argument 1) :to (:result 0)) y-pass) (:temporary (:sc unsigned-reg :offset nl2-offset :target r :from (:argument 1) :to (:result 0)) res-pass) (:temporary (:sc unsigned-reg :offset nl3-offset :to (:result 0)) tmp) (:temporary (:sc unsigned-reg :offset nl4-offset :from (:argument 1) :to (:result 0)) sign) (:temporary (:sc interior-reg :offset lip-offset) lip) (:ignore lip sign) (:generator 31 (let ((fixup (make-fixup 'multiply :assembly-routine))) (move x x-pass) (move y y-pass) (inst ldil fixup tmp) (inst ble fixup lisp-heap-space tmp) (inst nop) (move res-pass r)))) (define-vop (fast-truncate/fixnum fast-fixnum-binop) (:translate truncate) (:args (x :scs (any-reg) :target x-pass) (y :scs (any-reg) :target y-pass)) (:temporary (:sc signed-reg :offset nl0-offset :from (:argument 0) :to (:result 0)) x-pass) (:temporary (:sc signed-reg :offset nl1-offset :from (:argument 1) :to (:result 0)) y-pass) (:temporary (:sc signed-reg :offset nl2-offset :target q :from (:argument 1) :to (:result 0)) q-pass) (:temporary (:sc signed-reg :offset nl3-offset :target r :from (:argument 1) :to (:result 1)) r-pass) (:results (q :scs (any-reg)) (r :scs (any-reg))) (:result-types tagged-num tagged-num) (:vop-var vop) (:save-p :compute-only) (:generator 30 (let ((zero (generate-error-code vop division-by-zero-error x y))) (inst bc := nil y zero-tn zero)) (move x x-pass) (move y y-pass) (let ((fixup (make-fixup 'truncate :assembly-routine))) (inst ldil fixup q-pass) (inst ble fixup lisp-heap-space q-pass :nullify t)) (inst nop) (inst sll q-pass n-fixnum-tag-bits q) ;(move q-pass q) (move r-pass r))) (define-vop (fast-truncate/unsigned fast-unsigned-binop) (:translate truncate) (:args (x :scs (unsigned-reg) :target x-pass) (y :scs (unsigned-reg) :target y-pass)) (:temporary (:sc unsigned-reg :offset nl0-offset :from (:argument 0) :to (:result 0)) x-pass) (:temporary (:sc unsigned-reg :offset nl1-offset :from (:argument 1) :to (:result 0)) y-pass) (:temporary (:sc unsigned-reg :offset nl2-offset :target q :from (:argument 1) :to (:result 0)) q-pass) (:temporary (:sc unsigned-reg :offset nl3-offset :target r :from (:argument 1) :to (:result 1)) r-pass) (:results (q :scs (unsigned-reg)) (r :scs (unsigned-reg))) (:result-types unsigned-num unsigned-num) (:vop-var vop) (:save-p :compute-only) (:generator 35 (let ((zero (generate-error-code vop division-by-zero-error x y))) (inst bc := nil y zero-tn zero)) (move x x-pass) (move y y-pass) really dirty trick to avoid the bug truncate / unsigned vop ;; followed by move-from/word->fixnum where the result from the truncate is 0xe39516a7 and move - from - word will treat ;; the unsigned high number as an negative number. ;; instead we clear the high bit in the input to truncate. (inst li #x1fffffff q) (inst comb :<> q y skip :nullify t) (inst addi -1 zero-tn q) this should result in # 7fffffff (inst and x-pass q x-pass) (inst and y-pass q y-pass) SKIP fix bug#2 ( truncate # xe39516a7 # x3 ) = > # 0xf687078d,#x0 (inst li #x7fffffff q) (inst and x-pass q x-pass) (let ((fixup (make-fixup 'truncate :assembly-routine))) (inst ldil fixup q-pass) (inst ble fixup lisp-heap-space q-pass :nullify t)) (inst nop) (move q-pass q) (move r-pass r))) (define-vop (fast-truncate/signed fast-signed-binop) (:translate truncate) (:args (x :scs (signed-reg) :target x-pass) (y :scs (signed-reg) :target y-pass)) (:temporary (:sc signed-reg :offset nl0-offset :from (:argument 0) :to (:result 0)) x-pass) (:temporary (:sc signed-reg :offset nl1-offset :from (:argument 1) :to (:result 0)) y-pass) (:temporary (:sc signed-reg :offset nl2-offset :target q :from (:argument 1) :to (:result 0)) q-pass) (:temporary (:sc signed-reg :offset nl3-offset :target r :from (:argument 1) :to (:result 1)) r-pass) (:results (q :scs (signed-reg)) (r :scs (signed-reg))) (:result-types signed-num signed-num) (:vop-var vop) (:save-p :compute-only) (:generator 35 (let ((zero (generate-error-code vop division-by-zero-error x y))) (inst bc := nil y zero-tn zero)) (move x x-pass) (move y y-pass) (let ((fixup (make-fixup 'truncate :assembly-routine))) (inst ldil fixup q-pass) (inst ble fixup lisp-heap-space q-pass :nullify t)) (inst nop) (move q-pass q) (move r-pass r))) ;;;; Binary conditional VOPs: (define-vop (fast-conditional) (:conditional) (:info target not-p) (:effects) (:affected) (:policy :fast-safe)) (define-vop (fast-conditional/fixnum fast-conditional) (:args (x :scs (any-reg)) (y :scs (any-reg))) (:arg-types tagged-num tagged-num) (:note "inline fixnum comparison")) (define-vop (fast-conditional-c/fixnum fast-conditional/fixnum) (:args (x :scs (any-reg))) (:arg-types tagged-num (:constant (signed-byte 9))) (:info target not-p y)) (define-vop (fast-conditional/signed fast-conditional) (:args (x :scs (signed-reg)) (y :scs (signed-reg))) (:arg-types signed-num signed-num) (:note "inline (signed-byte 32) comparison")) (define-vop (fast-conditional-c/signed fast-conditional/signed) (:args (x :scs (signed-reg))) (:arg-types signed-num (:constant (signed-byte 11))) (:info target not-p y)) (define-vop (fast-conditional/unsigned fast-conditional) (:args (x :scs (unsigned-reg)) (y :scs (unsigned-reg))) (:arg-types unsigned-num unsigned-num) (:note "inline (unsigned-byte 32) comparison")) (define-vop (fast-conditional-c/unsigned fast-conditional/unsigned) (:args (x :scs (unsigned-reg))) (:arg-types unsigned-num (:constant (signed-byte 11))) (:info target not-p y)) (defmacro define-conditional-vop (translate signed-cond unsigned-cond) `(progn ,@(mapcar #'(lambda (suffix cost signed imm) (unless (and (member suffix '(/fixnum -c/fixnum)) (eq translate 'eql)) `(define-vop (,(intern (format nil "~:@(FAST-IF-~A~A~)" translate suffix)) ,(intern (format nil "~:@(FAST-CONDITIONAL~A~)" suffix))) (:translate ,translate) (:generator ,cost (inst ,(if imm 'bci 'bc) ,(if signed signed-cond unsigned-cond) not-p ,(if (eq suffix '-c/fixnum) '(fixnumize y) 'y) x target))))) '(/fixnum -c/fixnum /signed -c/signed /unsigned -c/unsigned) '(3 2 5 4 5 4) '(t t t t nil nil) '(nil t nil t nil t)))) We switch < and > because the immediate has to come first . (define-conditional-vop < :> :>>) (define-conditional-vop > :< :<<) EQL / FIXNUM is funny because the first arg can be of any type , not just a ;;; known fixnum. ;;; (define-conditional-vop eql := :=) These versions specify a fixnum restriction on their first arg . We have ;;; also generic-eql/fixnum VOPs which are the same, but have no restriction on the first arg and a higher cost . The reason for doing this is to prevent ;;; fixnum specific operations from being used on word integers, spuriously ;;; consing the argument. ;;; (define-vop (fast-eql/fixnum fast-conditional) (:args (x :scs (any-reg)) (y :scs (any-reg))) (:arg-types tagged-num tagged-num) (:note "inline fixnum comparison") (:translate eql) (:generator 3 (inst bc := not-p x y target))) ;;; (define-vop (generic-eql/fixnum fast-eql/fixnum) (:args (x :scs (any-reg descriptor-reg)) (y :scs (any-reg))) (:arg-types * tagged-num) (:variant-cost 7)) (define-vop (fast-eql-c/fixnum fast-conditional/fixnum) (:args (x :scs (any-reg))) (:arg-types tagged-num (:constant (signed-byte 9))) (:info target not-p y) (:translate eql) (:generator 2 (inst bci := not-p (fixnumize y) x target))) ;;; (define-vop (generic-eql-c/fixnum fast-eql-c/fixnum) (:args (x :scs (any-reg descriptor-reg))) (:arg-types * (:constant (signed-byte 9))) (:variant-cost 6)) ;;;; modular functions (define-modular-fun +-mod32 (x y) + :untagged nil 32) (define-vop (fast-+-mod32/unsigned=>unsigned fast-+/unsigned=>unsigned) (:translate +-mod32)) (define-vop (fast-+-mod32-c/unsigned=>unsigned fast-+-c/unsigned=>unsigned) (:translate +-mod32)) (define-modular-fun --mod32 (x y) - :untagged nil 32) (define-vop (fast---mod32/unsigned=>unsigned fast--/unsigned=>unsigned) (:translate --mod32)) (define-vop (fast---mod32-c/unsigned=>unsigned fast---c/unsigned=>unsigned) (:translate --mod32)) (define-vop (fast-ash-left-mod32-c/unsigned=>unsigned fast-ash-c/unsigned=>unsigned) (:translate ash-left-mod32)) (define-vop (fast-ash-left-mod32/unsigned=>unsigned fast-ash-left/unsigned=>unsigned)) (deftransform ash-left-mod32 ((integer count) ((unsigned-byte 32) (unsigned-byte 5))) (when (sb!c::constant-lvar-p count) (sb!c::give-up-ir1-transform)) '(%primitive fast-ash-left-mod32/unsigned=>unsigned integer count)) ;;; logical operations (define-modular-fun lognot-mod32 (x) lognot :untagged nil 32) (define-vop (lognot-mod32/unsigned=>unsigned) (:translate lognot-mod32) (:args (x :scs (unsigned-reg))) (:arg-types unsigned-num) (:results (res :scs (unsigned-reg))) (:result-types unsigned-num) (:policy :fast-safe) (:generator 1 (inst uaddcm zero-tn x res))) (define-modular-fun lognor-mod32 (x y) lognor :untagged nil 32) (define-vop (fast-lognor-mod32/unsigned=>unsigned fast-lognor/unsigned=>unsigned) (:translate lognor-mod32)) (define-source-transform logeqv (&rest args) (if (oddp (length args)) `(logxor ,@args) `(lognot (logxor ,@args)))) (define-source-transform logorc1 (x y) `(logior (lognot ,x) ,y)) (define-source-transform logorc2 (x y) `(logior ,x (lognot ,y))) (define-source-transform lognand (x y) `(lognot (logand ,x ,y))) (define-source-transform lognor (x y) `(lognot (logior ,x ,y))) (define-vop (shift-towards-someplace) (:policy :fast-safe) (:args (num :scs (unsigned-reg)) (amount :scs (signed-reg))) (:arg-types unsigned-num tagged-num) (:results (r :scs (unsigned-reg))) (:result-types unsigned-num)) (define-vop (shift-towards-start shift-towards-someplace) (:translate shift-towards-start) (:temporary (:scs (unsigned-reg) :to (:result 0)) temp) (:note "SHIFT-TOWARDS-START") (:generator 1 (inst subi 31 amount temp) (inst mtctl temp :sar) (inst zdep num :variable 32 r))) (define-vop (shift-towards-end shift-towards-someplace) (:translate shift-towards-end) (:note "SHIFT-TOWARDS-END") (:generator 1 (inst mtctl amount :sar) (inst shd zero-tn num :variable r))) stuff . (define-vop (bignum-length get-header-data) (:translate sb!bignum:%bignum-length) (:policy :fast-safe)) (define-vop (bignum-set-length set-header-data) (:translate sb!bignum:%bignum-set-length) (:policy :fast-safe)) (define-full-reffer bignum-ref * bignum-digits-offset other-pointer-lowtag (unsigned-reg) unsigned-num sb!bignum:%bignum-ref) (define-full-setter bignum-set * bignum-digits-offset other-pointer-lowtag (unsigned-reg) unsigned-num sb!bignum:%bignum-set) (define-vop (digit-0-or-plus) (:translate sb!bignum:%digit-0-or-plusp) (:policy :fast-safe) (:args (digit :scs (unsigned-reg))) (:arg-types unsigned-num) (:conditional) (:info target not-p) (:generator 2 (inst bc :>= not-p digit zero-tn target))) (define-vop (add-w/carry) (:translate sb!bignum:%add-with-carry) (:policy :fast-safe) (:args (a :scs (unsigned-reg)) (b :scs (unsigned-reg)) (c :scs (any-reg))) (:arg-types unsigned-num unsigned-num positive-fixnum) (:results (result :scs (unsigned-reg)) (carry :scs (unsigned-reg))) (:result-types unsigned-num positive-fixnum) (:generator 3 (inst addi -1 c zero-tn) (inst addc a b result) (inst addc zero-tn zero-tn carry))) (define-vop (sub-w/borrow) (:translate sb!bignum:%subtract-with-borrow) (:policy :fast-safe) (:args (a :scs (unsigned-reg)) (b :scs (unsigned-reg)) (c :scs (unsigned-reg))) (:arg-types unsigned-num unsigned-num positive-fixnum) (:results (result :scs (unsigned-reg)) (borrow :scs (unsigned-reg))) (:result-types unsigned-num positive-fixnum) (:generator 4 (inst addi -1 c zero-tn) (inst subb a b result) (inst addc zero-tn zero-tn borrow))) (define-vop (bignum-mult) (:translate sb!bignum:%multiply) (:policy :fast-safe) (:args (x-arg :scs (unsigned-reg) :target x) (y-arg :scs (unsigned-reg) :target y)) (:arg-types unsigned-num unsigned-num) (:temporary (:scs (signed-reg) :from (:argument 0)) x) (:temporary (:scs (signed-reg) :from (:argument 1)) y) (:temporary (:scs (signed-reg)) tmp) (:results (hi :scs (unsigned-reg)) (lo :scs (unsigned-reg))) (:result-types unsigned-num unsigned-num) (:generator 3 ;; Make sure X is less then Y. (inst comclr x-arg y-arg tmp :<<) (inst xor x-arg y-arg tmp) (inst xor x-arg tmp x) (inst xor y-arg tmp y) Blow out of here if the result is zero . (inst li 0 hi) (inst comb := x zero-tn done) (inst li 0 lo) (inst li 0 tmp) LOOP (inst comb :ev x zero-tn next-bit) (inst srl x 1 x) (inst add lo y lo) (inst addc hi tmp hi) NEXT-BIT (inst add y y y) (inst comb :<> x zero-tn loop) (inst addc tmp tmp tmp) DONE)) (define-source-transform sb!bignum:%multiply-and-add (x y carry &optional (extra 0)) #+nil ;; This would be greate if it worked, but it doesn't. (if (eql extra 0) `(multiple-value-call #'sb!bignum:%dual-word-add (sb!bignum:%multiply ,x ,y) (values ,carry)) `(multiple-value-call #'sb!bignum:%dual-word-add (multiple-value-call #'sb!bignum:%dual-word-add (sb!bignum:%multiply ,x ,y) (values ,carry)) (values ,extra))) (with-unique-names (hi lo) (if (eql extra 0) `(multiple-value-bind (,hi ,lo) (sb!bignum:%multiply ,x ,y) (sb!bignum::%dual-word-add ,hi ,lo ,carry)) `(multiple-value-bind (,hi ,lo) (sb!bignum:%multiply ,x ,y) (multiple-value-bind (,hi ,lo) (sb!bignum::%dual-word-add ,hi ,lo ,carry) (sb!bignum::%dual-word-add ,hi ,lo ,extra)))))) (defknown sb!bignum::%dual-word-add (sb!bignum:bignum-element-type sb!bignum:bignum-element-type sb!bignum:bignum-element-type) (values sb!bignum:bignum-element-type sb!bignum:bignum-element-type) (flushable movable)) (define-vop (dual-word-add) (:policy :fast-safe) (:translate sb!bignum::%dual-word-add) (:args (hi :scs (unsigned-reg) :to (:result 1)) (lo :scs (unsigned-reg)) (extra :scs (unsigned-reg))) (:arg-types unsigned-num unsigned-num unsigned-num) (:results (hi-res :scs (unsigned-reg) :from (:result 1)) (lo-res :scs (unsigned-reg) :from (:result 0))) (:result-types unsigned-num unsigned-num) (:affected) (:effects) (:generator 3 (inst add lo extra lo-res) (inst addc hi zero-tn hi-res))) (define-vop (bignum-lognot lognot-mod32/unsigned=>unsigned) (:translate sb!bignum:%lognot)) (define-vop (fixnum-to-digit) (:translate sb!bignum:%fixnum-to-digit) (:policy :fast-safe) (:args (fixnum :scs (any-reg))) (:arg-types tagged-num) (:results (digit :scs (unsigned-reg))) (:result-types unsigned-num) (:generator 1 (inst sra fixnum n-fixnum-tag-bits digit))) (define-vop (bignum-floor) (:translate sb!bignum:%floor) (:policy :fast-safe) (:args (hi :scs (unsigned-reg) :to (:argument 1)) (lo :scs (unsigned-reg) :to (:argument 0)) (divisor :scs (unsigned-reg))) (:arg-types unsigned-num unsigned-num unsigned-num) (:temporary (:scs (unsigned-reg) :to (:argument 1)) temp) (:results (quo :scs (unsigned-reg) :from (:argument 0)) (rem :scs (unsigned-reg) :from (:argument 1))) (:result-types unsigned-num unsigned-num) (:generator 65 (inst sub zero-tn divisor temp) (inst ds zero-tn temp zero-tn) (inst add lo lo quo) (inst ds hi divisor rem) (inst addc quo quo quo) (dotimes (i 31) (inst ds rem divisor rem) (inst addc quo quo quo)) (inst comclr rem zero-tn zero-tn :>=) (inst add divisor rem rem))) (define-vop (signify-digit) (:translate sb!bignum:%fixnum-digit-with-correct-sign) (:policy :fast-safe) (:args (digit :scs (unsigned-reg) :target res)) (:arg-types unsigned-num) (:results (res :scs (any-reg signed-reg))) (:result-types signed-num) (:generator 1 (sc-case res (any-reg (inst sll digit n-fixnum-tag-bits res)) (signed-reg (move digit res))))) (define-vop (digit-lshr) (:translate sb!bignum:%digit-logical-shift-right) (:policy :fast-safe) (:args (digit :scs (unsigned-reg)) (count :scs (unsigned-reg))) (:arg-types unsigned-num positive-fixnum) (:results (result :scs (unsigned-reg))) (:result-types unsigned-num) (:generator 2 (inst mtctl count :sar) (inst shd zero-tn digit :variable result))) (define-vop (digit-ashr digit-lshr) (:translate sb!bignum:%ashr) (:temporary (:scs (unsigned-reg) :to (:result 0)) temp) (:generator 1 (inst extrs digit 0 1 temp) (inst mtctl count :sar) (inst shd temp digit :variable result))) (define-vop (digit-ashl digit-ashr) (:translate sb!bignum:%ashl) (:generator 1 (inst subi 31 count temp) (inst mtctl temp :sar) (inst zdep digit :variable 32 result))) ;;;; Static functions. (define-static-fun two-arg-gcd (x y) :translate gcd) (define-static-fun two-arg-lcm (x y) :translate lcm) (define-static-fun two-arg-+ (x y) :translate +) (define-static-fun two-arg-- (x y) :translate -) (define-static-fun two-arg-* (x y) :translate *) (define-static-fun two-arg-/ (x y) :translate /) (define-static-fun two-arg-< (x y) :translate <) (define-static-fun two-arg-<= (x y) :translate <=) (define-static-fun two-arg-> (x y) :translate >) (define-static-fun two-arg->= (x y) :translate >=) (define-static-fun two-arg-= (x y) :translate =) (define-static-fun two-arg-/= (x y) :translate /=) (define-static-fun %negate (x) :translate %negate) (define-static-fun two-arg-and (x y) :translate logand) (define-static-fun two-arg-ior (x y) :translate logior) (define-static-fun two-arg-xor (x y) :translate logxor)
null
https://raw.githubusercontent.com/dmitryvk/sbcl-win32-threads/5abfd64b00a0937ba2df2919f177697d1d91bde4/src/compiler/hppa/arith.lisp
lisp
the VM definition arithmetic VOPs for HPPA more information. public domain. The software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information. Binary fixnum operations. Shifting Multiply and Divide. fix-lav: why dont we ignore tmp ? looking at the register setup above, not sure if both can clash maybe it is ok that x and x-pass share register ? like it was (move q-pass q) followed by move-from/word->fixnum where the result from the unsigned high number as an negative number. instead we clear the high bit in the input to truncate. Binary conditional VOPs: known fixnum. also generic-eql/fixnum VOPs which are the same, but have no restriction on fixnum specific operations from being used on word integers, spuriously consing the argument. modular functions logical operations Make sure X is less then Y. This would be greate if it worked, but it doesn't. Static functions.
This software is part of the SBCL system . See the README file for This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the (in-package "SB!VM") Unary operations . (define-vop (fast-safe-arith-op) (:policy :fast-safe) (:effects) (:affected)) (define-vop (fixnum-unop fast-safe-arith-op) (:args (x :scs (any-reg))) (:results (res :scs (any-reg))) (:note "inline fixnum arithmetic") (:arg-types tagged-num) (:result-types tagged-num)) (define-vop (signed-unop fast-safe-arith-op) (:args (x :scs (signed-reg))) (:results (res :scs (signed-reg))) (:note "inline (signed-byte 32) arithmetic") (:arg-types signed-num) (:result-types signed-num)) (define-vop (fast-negate/fixnum fixnum-unop) (:translate %negate) (:generator 1 (inst sub zero-tn x res))) (define-vop (fast-negate/signed signed-unop) (:translate %negate) (:generator 2 (inst sub zero-tn x res))) (define-vop (fast-lognot/fixnum fixnum-unop) (:translate lognot) (:temporary (:scs (any-reg) :type fixnum :to (:result 0)) temp) (:generator 1 (inst li (fixnumize -1) temp) (inst xor x temp res))) (define-vop (fast-lognot/signed signed-unop) (:translate lognot) (:generator 2 (inst uaddcm zero-tn x res))) Assume that any constant operand is the second arg ... (define-vop (fast-fixnum-binop fast-safe-arith-op) (:args (x :target r :scs (any-reg zero)) (y :target r :scs (any-reg zero))) (:arg-types tagged-num tagged-num) (:results (r :scs (any-reg))) (:result-types tagged-num) (:note "inline fixnum arithmetic")) (define-vop (fast-unsigned-binop fast-safe-arith-op) (:args (x :target r :scs (unsigned-reg zero)) (y :target r :scs (unsigned-reg zero))) (:arg-types unsigned-num unsigned-num) (:results (r :scs (unsigned-reg))) (:result-types unsigned-num) (:note "inline (unsigned-byte 32) arithmetic")) (define-vop (fast-signed-binop fast-safe-arith-op) (:args (x :target r :scs (signed-reg zero)) (y :target r :scs (signed-reg zero))) (:arg-types signed-num signed-num) (:results (r :scs (signed-reg))) (:result-types signed-num) (:note "inline (signed-byte 32) arithmetic")) (define-vop (fast-fixnum-c-binop fast-fixnum-binop) (:args (x :target r :scs (any-reg))) (:info y) (:arg-types tagged-num (:constant integer))) (define-vop (fast-signed-c-binop fast-signed-binop) (:args (x :target r :scs (signed-reg))) (:info y) (:arg-types tagged-num (:constant integer))) (define-vop (fast-unsigned-c-binop fast-unsigned-binop) (:args (x :target r :scs (unsigned-reg))) (:info y) (:arg-types tagged-num (:constant integer))) (macrolet ((define-binop (translate cost untagged-cost op arg-swap) `(progn (define-vop (,(symbolicate "FAST-" translate "/FIXNUM=>FIXNUM") fast-fixnum-binop) (:args (x :target r :scs (any-reg)) (y :target r :scs (any-reg))) (:translate ,translate) (:generator ,(1+ cost) ,(if arg-swap `(inst ,op y x r) `(inst ,op x y r)))) (define-vop (,(symbolicate "FAST-" translate "/SIGNED=>SIGNED") fast-signed-binop) (:args (x :target r :scs (signed-reg)) (y :target r :scs (signed-reg))) (:translate ,translate) (:generator ,(1+ untagged-cost) ,(if arg-swap `(inst ,op y x r) `(inst ,op x y r)))) (define-vop (,(symbolicate "FAST-" translate "/UNSIGNED=>UNSIGNED") fast-unsigned-binop) (:args (x :target r :scs (unsigned-reg)) (y :target r :scs (unsigned-reg))) (:translate ,translate) (:generator ,(1+ untagged-cost) ,(if arg-swap `(inst ,op y x r) `(inst ,op x y r))))))) (define-binop + 1 5 add nil) (define-binop - 1 5 sub nil) (define-binop logior 1 2 or nil) (define-binop logand 1 2 and nil) (define-binop logandc1 1 2 andcm t) (define-binop logandc2 1 2 andcm nil) (define-binop logxor 1 2 xor nil)) (macrolet ((define-c-binop (translate cost untagged-cost tagged-type untagged-type inst) `(progn (define-vop (,(symbolicate "FAST-" translate "-C/FIXNUM=>FIXNUM") fast-fixnum-c-binop) (:arg-types tagged-num (:constant ,tagged-type)) (:translate ,translate) (:generator ,cost (let ((y (fixnumize y))) ,inst))) (define-vop (,(symbolicate "FAST-" translate "-C/SIGNED=>SIGNED") fast-signed-c-binop) (:arg-types signed-num (:constant ,untagged-type)) (:translate ,translate) (:generator ,untagged-cost ,inst)) (define-vop (,(symbolicate "FAST-" translate "-C/UNSIGNED=>UNSIGNED") fast-unsigned-c-binop) (:arg-types unsigned-num (:constant ,untagged-type)) (:translate ,translate) (:generator ,untagged-cost ,inst))))) (define-c-binop + 1 3 (signed-byte 9) (signed-byte 11) (inst addi y x r)) (define-c-binop - 1 3 (integer #.(- 1 (ash 1 8)) #.(ash 1 8)) (integer #.(- 1 (ash 1 10)) #.(ash 1 10)) (inst addi (- y) x r))) (define-vop (fast-lognor/fixnum=>fixnum fast-fixnum-binop) (:translate lognor) (:args (x :target r :scs (any-reg)) (y :target r :scs (any-reg))) (:temporary (:sc non-descriptor-reg) temp) (:generator 4 (inst or x y temp) (inst uaddcm zero-tn temp temp) (inst addi (- fixnum-tag-mask) temp r))) (define-vop (fast-lognor/signed=>signed fast-signed-binop) (:translate lognor) (:args (x :target r :scs (signed-reg)) (y :target r :scs (signed-reg))) (:generator 4 (inst or x y r) (inst uaddcm zero-tn r r))) (define-vop (fast-lognor/unsigned=>unsigned fast-unsigned-binop) (:translate lognor) (:args (x :target r :scs (unsigned-reg)) (y :target r :scs (unsigned-reg))) (:generator 4 (inst or x y r) (inst uaddcm zero-tn r r))) (macrolet ((fast-ash (name reg num tag save) `(define-vop (,name) (:translate ash) (:note "inline ASH") (:policy :fast-safe) (:args (number :scs (,reg) :to :save) (count :scs (signed-reg) ,@(if save '(:to :save)))) (:arg-types ,num ,tag) (:results (result :scs (,reg))) (:result-types ,num) (:temporary (:scs (unsigned-reg) :to (:result 0)) temp) (:generator 8 (inst comb :>= count zero-tn positive :nullify t) (inst sub zero-tn count temp) (inst comiclr 31 temp zero-tn :>=) (inst li 31 temp) (inst mtctl temp :sar) (inst extrs number 0 1 temp) (inst b done) (inst shd temp number :variable result) POSITIVE (inst subi 31 count temp) (inst mtctl temp :sar) (inst zdep number :variable 32 result) DONE)))) (fast-ash fast-ash/unsigned=>unsigned unsigned-reg unsigned-num tagged-num t) (fast-ash fast-ash/signed=>signed signed-reg signed-num signed-num nil)) (define-vop (fast-ash-c/unsigned=>unsigned) (:translate ash) (:note "inline ASH") (:policy :fast-safe) (:args (number :scs (unsigned-reg))) (:info count) (:arg-types unsigned-num (:constant integer)) (:results (result :scs (unsigned-reg))) (:result-types unsigned-num) (:generator 1 (cond ((< count -31) (move zero-tn result)) ((< count 0) (inst srl number (min (- count) 31) result)) ((> count 0) (inst sll number (min count 31) result)) (t (bug "identity ASH not transformed away"))))) (define-vop (fast-ash-c/signed=>signed) (:translate ash) (:note "inline ASH") (:policy :fast-safe) (:args (number :scs (signed-reg))) (:info count) (:arg-types signed-num (:constant integer)) (:results (result :scs (signed-reg))) (:result-types signed-num) (:generator 1 (cond ((< count 0) (inst sra number (min (- count) 31) result)) ((> count 0) (inst sll number (min count 31) result)) (t (bug "identity ASH not transformed away"))))) (macrolet ((def (name sc-type type result-type cost) `(define-vop (,name) (:translate ash) (:note "inline ASH") (:policy :fast-safe) (:args (number :scs (,sc-type)) (amount :scs (signed-reg unsigned-reg immediate))) (:arg-types ,type positive-fixnum) (:results (result :scs (,result-type))) (:result-types ,type) (:temporary (:scs (,sc-type) :to (:result 0)) temp) (:generator ,cost (sc-case amount ((signed-reg unsigned-reg) (inst subi 31 amount temp) (inst mtctl temp :sar) (inst zdep number :variable 32 result)) (immediate (let ((amount (tn-value amount))) (aver (> amount 0)) (inst sll number amount result)))))))) (def fast-ash-left/fixnum=>fixnum any-reg tagged-num any-reg 2) (def fast-ash-left/signed=>signed signed-reg signed-num signed-reg 3) (def fast-ash-left/unsigned=>unsigned unsigned-reg unsigned-num unsigned-reg 3)) (define-vop (signed-byte-32-len) (:translate integer-length) (:note "inline (signed-byte 32) integer-length") (:policy :fast-safe) (:args (arg :scs (signed-reg) :target shift)) (:arg-types signed-num) (:results (res :scs (any-reg))) (:result-types positive-fixnum) (:temporary (:scs (non-descriptor-reg) :from (:argument 0)) shift) (:generator 30 (inst move arg shift :>=) (inst uaddcm zero-tn shift shift) (inst comb := shift zero-tn done) (inst li 0 res) LOOP (inst srl shift 1 shift) (inst comb :<> shift zero-tn loop) (inst addi (fixnumize 1) res res) DONE)) (define-vop (unsigned-byte-32-count) (:translate logcount) (:note "inline (unsigned-byte 32) logcount") (:policy :fast-safe) (:args (arg :scs (unsigned-reg) :target num)) (:arg-types unsigned-num) (:results (res :scs (unsigned-reg))) (:result-types positive-fixnum) (:temporary (:scs (non-descriptor-reg) :from (:argument 0) :to (:result 0) :target res) num) (:temporary (:scs (non-descriptor-reg)) mask temp) (:generator 30 (inst li #x55555555 mask) (inst srl arg 1 temp) (inst and arg mask num) (inst and temp mask temp) (inst add num temp num) (inst li #x33333333 mask) (inst srl num 2 temp) (inst and num mask num) (inst and temp mask temp) (inst add num temp num) (inst li #x0f0f0f0f mask) (inst srl num 4 temp) (inst and num mask num) (inst and temp mask temp) (inst add num temp num) (inst li #x00ff00ff mask) (inst srl num 8 temp) (inst and num mask num) (inst and temp mask temp) (inst add num temp num) (inst li #x0000ffff mask) (inst srl num 16 temp) (inst and num mask num) (inst and temp mask temp) (inst add num temp res))) (define-vop (fast-*/fixnum=>fixnum fast-fixnum-binop) (:translate *) (:args (x :scs (any-reg zero) :target x-pass) (y :scs (any-reg zero) :target y-pass)) (:temporary (:sc signed-reg :offset nl0-offset :from (:argument 0) :to (:result 0)) x-pass) (:temporary (:sc signed-reg :offset nl1-offset :from (:argument 1) :to (:result 0)) y-pass) (:temporary (:sc signed-reg :offset nl2-offset :target r :from (:argument 1) :to (:result 0)) res-pass) (:temporary (:sc signed-reg :offset nl3-offset :to (:result 0)) tmp) (:temporary (:sc signed-reg :offset nl4-offset :from (:argument 1) :to (:result 0)) sign) (:temporary (:sc interior-reg :offset lip-offset) lip) (:generator 30 (unless (location= y y-pass) (inst sra x 2 x-pass)) (let ((fixup (make-fixup 'multiply :assembly-routine))) (inst ldil fixup tmp) (inst ble fixup lisp-heap-space tmp)) (if (location= y y-pass) (inst sra x 2 x-pass) (inst move y y-pass)) (move res-pass r))) (define-vop (fast-*/signed=>signed fast-signed-binop) (:translate *) (:args (x :scs (signed-reg) :target x-pass) (y :scs (signed-reg) :target y-pass)) (:temporary (:sc signed-reg :offset nl0-offset :from (:argument 0) :to (:result 0)) x-pass) (:temporary (:sc signed-reg :offset nl1-offset :from (:argument 1) :to (:result 0)) y-pass) (:temporary (:sc signed-reg :offset nl2-offset :target r :from (:argument 1) :to (:result 0)) res-pass) (:temporary (:sc signed-reg :offset nl3-offset :to (:result 0)) tmp) (:temporary (:sc signed-reg :offset nl4-offset :from (:argument 1) :to (:result 0)) sign) (:temporary (:sc interior-reg :offset lip-offset) lip) (:ignore lip sign) (:generator 31 (let ((fixup (make-fixup 'multiply :assembly-routine))) (move x x-pass) (move y y-pass) (inst ldil fixup tmp) (inst ble fixup lisp-heap-space tmp) (inst nop) (move res-pass r)))) (define-vop (fast-*/unsigned=>unsigned fast-unsigned-binop) (:translate *) (:args (x :scs (unsigned-reg) :target x-pass) (y :scs (unsigned-reg) :target y-pass)) (:temporary (:sc unsigned-reg :offset nl0-offset :from (:argument 0) :to (:result 0)) x-pass) (:temporary (:sc unsigned-reg :offset nl1-offset :from (:argument 1) :to (:result 0)) y-pass) (:temporary (:sc unsigned-reg :offset nl2-offset :target r :from (:argument 1) :to (:result 0)) res-pass) (:temporary (:sc unsigned-reg :offset nl3-offset :to (:result 0)) tmp) (:temporary (:sc unsigned-reg :offset nl4-offset :from (:argument 1) :to (:result 0)) sign) (:temporary (:sc interior-reg :offset lip-offset) lip) (:ignore lip sign) (:generator 31 (let ((fixup (make-fixup 'multiply :assembly-routine))) (move x x-pass) (move y y-pass) (inst ldil fixup tmp) (inst ble fixup lisp-heap-space tmp) (inst nop) (move res-pass r)))) (define-vop (fast-truncate/fixnum fast-fixnum-binop) (:translate truncate) (:args (x :scs (any-reg) :target x-pass) (y :scs (any-reg) :target y-pass)) (:temporary (:sc signed-reg :offset nl0-offset :from (:argument 0) :to (:result 0)) x-pass) (:temporary (:sc signed-reg :offset nl1-offset :from (:argument 1) :to (:result 0)) y-pass) (:temporary (:sc signed-reg :offset nl2-offset :target q :from (:argument 1) :to (:result 0)) q-pass) (:temporary (:sc signed-reg :offset nl3-offset :target r :from (:argument 1) :to (:result 1)) r-pass) (:results (q :scs (any-reg)) (r :scs (any-reg))) (:result-types tagged-num tagged-num) (:vop-var vop) (:save-p :compute-only) (:generator 30 (let ((zero (generate-error-code vop division-by-zero-error x y))) (inst bc := nil y zero-tn zero)) (move x x-pass) (move y y-pass) (let ((fixup (make-fixup 'truncate :assembly-routine))) (inst ldil fixup q-pass) (inst ble fixup lisp-heap-space q-pass :nullify t)) (inst nop) (inst sll q-pass n-fixnum-tag-bits q) (move r-pass r))) (define-vop (fast-truncate/unsigned fast-unsigned-binop) (:translate truncate) (:args (x :scs (unsigned-reg) :target x-pass) (y :scs (unsigned-reg) :target y-pass)) (:temporary (:sc unsigned-reg :offset nl0-offset :from (:argument 0) :to (:result 0)) x-pass) (:temporary (:sc unsigned-reg :offset nl1-offset :from (:argument 1) :to (:result 0)) y-pass) (:temporary (:sc unsigned-reg :offset nl2-offset :target q :from (:argument 1) :to (:result 0)) q-pass) (:temporary (:sc unsigned-reg :offset nl3-offset :target r :from (:argument 1) :to (:result 1)) r-pass) (:results (q :scs (unsigned-reg)) (r :scs (unsigned-reg))) (:result-types unsigned-num unsigned-num) (:vop-var vop) (:save-p :compute-only) (:generator 35 (let ((zero (generate-error-code vop division-by-zero-error x y))) (inst bc := nil y zero-tn zero)) (move x x-pass) (move y y-pass) really dirty trick to avoid the bug truncate / unsigned vop the truncate is 0xe39516a7 and move - from - word will treat (inst li #x1fffffff q) (inst comb :<> q y skip :nullify t) (inst addi -1 zero-tn q) this should result in # 7fffffff (inst and x-pass q x-pass) (inst and y-pass q y-pass) SKIP fix bug#2 ( truncate # xe39516a7 # x3 ) = > # 0xf687078d,#x0 (inst li #x7fffffff q) (inst and x-pass q x-pass) (let ((fixup (make-fixup 'truncate :assembly-routine))) (inst ldil fixup q-pass) (inst ble fixup lisp-heap-space q-pass :nullify t)) (inst nop) (move q-pass q) (move r-pass r))) (define-vop (fast-truncate/signed fast-signed-binop) (:translate truncate) (:args (x :scs (signed-reg) :target x-pass) (y :scs (signed-reg) :target y-pass)) (:temporary (:sc signed-reg :offset nl0-offset :from (:argument 0) :to (:result 0)) x-pass) (:temporary (:sc signed-reg :offset nl1-offset :from (:argument 1) :to (:result 0)) y-pass) (:temporary (:sc signed-reg :offset nl2-offset :target q :from (:argument 1) :to (:result 0)) q-pass) (:temporary (:sc signed-reg :offset nl3-offset :target r :from (:argument 1) :to (:result 1)) r-pass) (:results (q :scs (signed-reg)) (r :scs (signed-reg))) (:result-types signed-num signed-num) (:vop-var vop) (:save-p :compute-only) (:generator 35 (let ((zero (generate-error-code vop division-by-zero-error x y))) (inst bc := nil y zero-tn zero)) (move x x-pass) (move y y-pass) (let ((fixup (make-fixup 'truncate :assembly-routine))) (inst ldil fixup q-pass) (inst ble fixup lisp-heap-space q-pass :nullify t)) (inst nop) (move q-pass q) (move r-pass r))) (define-vop (fast-conditional) (:conditional) (:info target not-p) (:effects) (:affected) (:policy :fast-safe)) (define-vop (fast-conditional/fixnum fast-conditional) (:args (x :scs (any-reg)) (y :scs (any-reg))) (:arg-types tagged-num tagged-num) (:note "inline fixnum comparison")) (define-vop (fast-conditional-c/fixnum fast-conditional/fixnum) (:args (x :scs (any-reg))) (:arg-types tagged-num (:constant (signed-byte 9))) (:info target not-p y)) (define-vop (fast-conditional/signed fast-conditional) (:args (x :scs (signed-reg)) (y :scs (signed-reg))) (:arg-types signed-num signed-num) (:note "inline (signed-byte 32) comparison")) (define-vop (fast-conditional-c/signed fast-conditional/signed) (:args (x :scs (signed-reg))) (:arg-types signed-num (:constant (signed-byte 11))) (:info target not-p y)) (define-vop (fast-conditional/unsigned fast-conditional) (:args (x :scs (unsigned-reg)) (y :scs (unsigned-reg))) (:arg-types unsigned-num unsigned-num) (:note "inline (unsigned-byte 32) comparison")) (define-vop (fast-conditional-c/unsigned fast-conditional/unsigned) (:args (x :scs (unsigned-reg))) (:arg-types unsigned-num (:constant (signed-byte 11))) (:info target not-p y)) (defmacro define-conditional-vop (translate signed-cond unsigned-cond) `(progn ,@(mapcar #'(lambda (suffix cost signed imm) (unless (and (member suffix '(/fixnum -c/fixnum)) (eq translate 'eql)) `(define-vop (,(intern (format nil "~:@(FAST-IF-~A~A~)" translate suffix)) ,(intern (format nil "~:@(FAST-CONDITIONAL~A~)" suffix))) (:translate ,translate) (:generator ,cost (inst ,(if imm 'bci 'bc) ,(if signed signed-cond unsigned-cond) not-p ,(if (eq suffix '-c/fixnum) '(fixnumize y) 'y) x target))))) '(/fixnum -c/fixnum /signed -c/signed /unsigned -c/unsigned) '(3 2 5 4 5 4) '(t t t t nil nil) '(nil t nil t nil t)))) We switch < and > because the immediate has to come first . (define-conditional-vop < :> :>>) (define-conditional-vop > :< :<<) EQL / FIXNUM is funny because the first arg can be of any type , not just a (define-conditional-vop eql := :=) These versions specify a fixnum restriction on their first arg . We have the first arg and a higher cost . The reason for doing this is to prevent (define-vop (fast-eql/fixnum fast-conditional) (:args (x :scs (any-reg)) (y :scs (any-reg))) (:arg-types tagged-num tagged-num) (:note "inline fixnum comparison") (:translate eql) (:generator 3 (inst bc := not-p x y target))) (define-vop (generic-eql/fixnum fast-eql/fixnum) (:args (x :scs (any-reg descriptor-reg)) (y :scs (any-reg))) (:arg-types * tagged-num) (:variant-cost 7)) (define-vop (fast-eql-c/fixnum fast-conditional/fixnum) (:args (x :scs (any-reg))) (:arg-types tagged-num (:constant (signed-byte 9))) (:info target not-p y) (:translate eql) (:generator 2 (inst bci := not-p (fixnumize y) x target))) (define-vop (generic-eql-c/fixnum fast-eql-c/fixnum) (:args (x :scs (any-reg descriptor-reg))) (:arg-types * (:constant (signed-byte 9))) (:variant-cost 6)) (define-modular-fun +-mod32 (x y) + :untagged nil 32) (define-vop (fast-+-mod32/unsigned=>unsigned fast-+/unsigned=>unsigned) (:translate +-mod32)) (define-vop (fast-+-mod32-c/unsigned=>unsigned fast-+-c/unsigned=>unsigned) (:translate +-mod32)) (define-modular-fun --mod32 (x y) - :untagged nil 32) (define-vop (fast---mod32/unsigned=>unsigned fast--/unsigned=>unsigned) (:translate --mod32)) (define-vop (fast---mod32-c/unsigned=>unsigned fast---c/unsigned=>unsigned) (:translate --mod32)) (define-vop (fast-ash-left-mod32-c/unsigned=>unsigned fast-ash-c/unsigned=>unsigned) (:translate ash-left-mod32)) (define-vop (fast-ash-left-mod32/unsigned=>unsigned fast-ash-left/unsigned=>unsigned)) (deftransform ash-left-mod32 ((integer count) ((unsigned-byte 32) (unsigned-byte 5))) (when (sb!c::constant-lvar-p count) (sb!c::give-up-ir1-transform)) '(%primitive fast-ash-left-mod32/unsigned=>unsigned integer count)) (define-modular-fun lognot-mod32 (x) lognot :untagged nil 32) (define-vop (lognot-mod32/unsigned=>unsigned) (:translate lognot-mod32) (:args (x :scs (unsigned-reg))) (:arg-types unsigned-num) (:results (res :scs (unsigned-reg))) (:result-types unsigned-num) (:policy :fast-safe) (:generator 1 (inst uaddcm zero-tn x res))) (define-modular-fun lognor-mod32 (x y) lognor :untagged nil 32) (define-vop (fast-lognor-mod32/unsigned=>unsigned fast-lognor/unsigned=>unsigned) (:translate lognor-mod32)) (define-source-transform logeqv (&rest args) (if (oddp (length args)) `(logxor ,@args) `(lognot (logxor ,@args)))) (define-source-transform logorc1 (x y) `(logior (lognot ,x) ,y)) (define-source-transform logorc2 (x y) `(logior ,x (lognot ,y))) (define-source-transform lognand (x y) `(lognot (logand ,x ,y))) (define-source-transform lognor (x y) `(lognot (logior ,x ,y))) (define-vop (shift-towards-someplace) (:policy :fast-safe) (:args (num :scs (unsigned-reg)) (amount :scs (signed-reg))) (:arg-types unsigned-num tagged-num) (:results (r :scs (unsigned-reg))) (:result-types unsigned-num)) (define-vop (shift-towards-start shift-towards-someplace) (:translate shift-towards-start) (:temporary (:scs (unsigned-reg) :to (:result 0)) temp) (:note "SHIFT-TOWARDS-START") (:generator 1 (inst subi 31 amount temp) (inst mtctl temp :sar) (inst zdep num :variable 32 r))) (define-vop (shift-towards-end shift-towards-someplace) (:translate shift-towards-end) (:note "SHIFT-TOWARDS-END") (:generator 1 (inst mtctl amount :sar) (inst shd zero-tn num :variable r))) stuff . (define-vop (bignum-length get-header-data) (:translate sb!bignum:%bignum-length) (:policy :fast-safe)) (define-vop (bignum-set-length set-header-data) (:translate sb!bignum:%bignum-set-length) (:policy :fast-safe)) (define-full-reffer bignum-ref * bignum-digits-offset other-pointer-lowtag (unsigned-reg) unsigned-num sb!bignum:%bignum-ref) (define-full-setter bignum-set * bignum-digits-offset other-pointer-lowtag (unsigned-reg) unsigned-num sb!bignum:%bignum-set) (define-vop (digit-0-or-plus) (:translate sb!bignum:%digit-0-or-plusp) (:policy :fast-safe) (:args (digit :scs (unsigned-reg))) (:arg-types unsigned-num) (:conditional) (:info target not-p) (:generator 2 (inst bc :>= not-p digit zero-tn target))) (define-vop (add-w/carry) (:translate sb!bignum:%add-with-carry) (:policy :fast-safe) (:args (a :scs (unsigned-reg)) (b :scs (unsigned-reg)) (c :scs (any-reg))) (:arg-types unsigned-num unsigned-num positive-fixnum) (:results (result :scs (unsigned-reg)) (carry :scs (unsigned-reg))) (:result-types unsigned-num positive-fixnum) (:generator 3 (inst addi -1 c zero-tn) (inst addc a b result) (inst addc zero-tn zero-tn carry))) (define-vop (sub-w/borrow) (:translate sb!bignum:%subtract-with-borrow) (:policy :fast-safe) (:args (a :scs (unsigned-reg)) (b :scs (unsigned-reg)) (c :scs (unsigned-reg))) (:arg-types unsigned-num unsigned-num positive-fixnum) (:results (result :scs (unsigned-reg)) (borrow :scs (unsigned-reg))) (:result-types unsigned-num positive-fixnum) (:generator 4 (inst addi -1 c zero-tn) (inst subb a b result) (inst addc zero-tn zero-tn borrow))) (define-vop (bignum-mult) (:translate sb!bignum:%multiply) (:policy :fast-safe) (:args (x-arg :scs (unsigned-reg) :target x) (y-arg :scs (unsigned-reg) :target y)) (:arg-types unsigned-num unsigned-num) (:temporary (:scs (signed-reg) :from (:argument 0)) x) (:temporary (:scs (signed-reg) :from (:argument 1)) y) (:temporary (:scs (signed-reg)) tmp) (:results (hi :scs (unsigned-reg)) (lo :scs (unsigned-reg))) (:result-types unsigned-num unsigned-num) (:generator 3 (inst comclr x-arg y-arg tmp :<<) (inst xor x-arg y-arg tmp) (inst xor x-arg tmp x) (inst xor y-arg tmp y) Blow out of here if the result is zero . (inst li 0 hi) (inst comb := x zero-tn done) (inst li 0 lo) (inst li 0 tmp) LOOP (inst comb :ev x zero-tn next-bit) (inst srl x 1 x) (inst add lo y lo) (inst addc hi tmp hi) NEXT-BIT (inst add y y y) (inst comb :<> x zero-tn loop) (inst addc tmp tmp tmp) DONE)) (define-source-transform sb!bignum:%multiply-and-add (x y carry &optional (extra 0)) (if (eql extra 0) `(multiple-value-call #'sb!bignum:%dual-word-add (sb!bignum:%multiply ,x ,y) (values ,carry)) `(multiple-value-call #'sb!bignum:%dual-word-add (multiple-value-call #'sb!bignum:%dual-word-add (sb!bignum:%multiply ,x ,y) (values ,carry)) (values ,extra))) (with-unique-names (hi lo) (if (eql extra 0) `(multiple-value-bind (,hi ,lo) (sb!bignum:%multiply ,x ,y) (sb!bignum::%dual-word-add ,hi ,lo ,carry)) `(multiple-value-bind (,hi ,lo) (sb!bignum:%multiply ,x ,y) (multiple-value-bind (,hi ,lo) (sb!bignum::%dual-word-add ,hi ,lo ,carry) (sb!bignum::%dual-word-add ,hi ,lo ,extra)))))) (defknown sb!bignum::%dual-word-add (sb!bignum:bignum-element-type sb!bignum:bignum-element-type sb!bignum:bignum-element-type) (values sb!bignum:bignum-element-type sb!bignum:bignum-element-type) (flushable movable)) (define-vop (dual-word-add) (:policy :fast-safe) (:translate sb!bignum::%dual-word-add) (:args (hi :scs (unsigned-reg) :to (:result 1)) (lo :scs (unsigned-reg)) (extra :scs (unsigned-reg))) (:arg-types unsigned-num unsigned-num unsigned-num) (:results (hi-res :scs (unsigned-reg) :from (:result 1)) (lo-res :scs (unsigned-reg) :from (:result 0))) (:result-types unsigned-num unsigned-num) (:affected) (:effects) (:generator 3 (inst add lo extra lo-res) (inst addc hi zero-tn hi-res))) (define-vop (bignum-lognot lognot-mod32/unsigned=>unsigned) (:translate sb!bignum:%lognot)) (define-vop (fixnum-to-digit) (:translate sb!bignum:%fixnum-to-digit) (:policy :fast-safe) (:args (fixnum :scs (any-reg))) (:arg-types tagged-num) (:results (digit :scs (unsigned-reg))) (:result-types unsigned-num) (:generator 1 (inst sra fixnum n-fixnum-tag-bits digit))) (define-vop (bignum-floor) (:translate sb!bignum:%floor) (:policy :fast-safe) (:args (hi :scs (unsigned-reg) :to (:argument 1)) (lo :scs (unsigned-reg) :to (:argument 0)) (divisor :scs (unsigned-reg))) (:arg-types unsigned-num unsigned-num unsigned-num) (:temporary (:scs (unsigned-reg) :to (:argument 1)) temp) (:results (quo :scs (unsigned-reg) :from (:argument 0)) (rem :scs (unsigned-reg) :from (:argument 1))) (:result-types unsigned-num unsigned-num) (:generator 65 (inst sub zero-tn divisor temp) (inst ds zero-tn temp zero-tn) (inst add lo lo quo) (inst ds hi divisor rem) (inst addc quo quo quo) (dotimes (i 31) (inst ds rem divisor rem) (inst addc quo quo quo)) (inst comclr rem zero-tn zero-tn :>=) (inst add divisor rem rem))) (define-vop (signify-digit) (:translate sb!bignum:%fixnum-digit-with-correct-sign) (:policy :fast-safe) (:args (digit :scs (unsigned-reg) :target res)) (:arg-types unsigned-num) (:results (res :scs (any-reg signed-reg))) (:result-types signed-num) (:generator 1 (sc-case res (any-reg (inst sll digit n-fixnum-tag-bits res)) (signed-reg (move digit res))))) (define-vop (digit-lshr) (:translate sb!bignum:%digit-logical-shift-right) (:policy :fast-safe) (:args (digit :scs (unsigned-reg)) (count :scs (unsigned-reg))) (:arg-types unsigned-num positive-fixnum) (:results (result :scs (unsigned-reg))) (:result-types unsigned-num) (:generator 2 (inst mtctl count :sar) (inst shd zero-tn digit :variable result))) (define-vop (digit-ashr digit-lshr) (:translate sb!bignum:%ashr) (:temporary (:scs (unsigned-reg) :to (:result 0)) temp) (:generator 1 (inst extrs digit 0 1 temp) (inst mtctl count :sar) (inst shd temp digit :variable result))) (define-vop (digit-ashl digit-ashr) (:translate sb!bignum:%ashl) (:generator 1 (inst subi 31 count temp) (inst mtctl temp :sar) (inst zdep digit :variable 32 result))) (define-static-fun two-arg-gcd (x y) :translate gcd) (define-static-fun two-arg-lcm (x y) :translate lcm) (define-static-fun two-arg-+ (x y) :translate +) (define-static-fun two-arg-- (x y) :translate -) (define-static-fun two-arg-* (x y) :translate *) (define-static-fun two-arg-/ (x y) :translate /) (define-static-fun two-arg-< (x y) :translate <) (define-static-fun two-arg-<= (x y) :translate <=) (define-static-fun two-arg-> (x y) :translate >) (define-static-fun two-arg->= (x y) :translate >=) (define-static-fun two-arg-= (x y) :translate =) (define-static-fun two-arg-/= (x y) :translate /=) (define-static-fun %negate (x) :translate %negate) (define-static-fun two-arg-and (x y) :translate logand) (define-static-fun two-arg-ior (x y) :translate logior) (define-static-fun two-arg-xor (x y) :translate logxor)
db65b4cd8740785a5d522b727bedf7804d291e15525dc5d8ff47f08405372252
MaskRay/OJHaskell
97.hs
powMod a 0 m = 1 powMod a n m | n `mod` 2 == 0 = ret * ret `mod` m where ret = powMod a (n `div` 2) m powMod a n m = powMod a (n-1) m * a `mod` m main = print $ (`mod` (10^10)) $ 28433 * powMod 2 7830457 (10^10) + 1
null
https://raw.githubusercontent.com/MaskRay/OJHaskell/ba24050b2480619f10daa7d37fca558182ba006c/Project%20Euler/97.hs
haskell
powMod a 0 m = 1 powMod a n m | n `mod` 2 == 0 = ret * ret `mod` m where ret = powMod a (n `div` 2) m powMod a n m = powMod a (n-1) m * a `mod` m main = print $ (`mod` (10^10)) $ 28433 * powMod 2 7830457 (10^10) + 1
476c430fa9649816eef77f63dcd28046fc61ca270af3a29ca79e193b444279ab
aitorres/firelink
OffsetSpec.hs
module OffsetSpec where import qualified FireLink.FrontEnd.SymTable as ST import Test.Hspec import qualified TestUtils as U testOffset :: String -> [(String, Int)] -> IO () testOffset = testProgram . baseProgram where baseProgram :: String -> String baseProgram s = "hello ashen one\n\ \ traveling somewhere \ \ with \ \" ++ s ++ "\ \ in your inventory \ \ with orange soapstone say @hello world@ \ \ you died \ \ farewell ashen one" testProgram :: String -> [(String, Int)] -> IO () testProgram program testItems = do dictionary <- getDictionary program mapM_ (test dictionary) testItems test :: ST.Dictionary -> (String, Int) -> IO () test dictionary (varName, expectedOffset) = do let chain = filter (\d -> ST.name d == varName) $ ST.findChain varName dictionary let dictEntry = head chain let ST.Offset actualOffset = U.extractOffsetFromExtra $ ST.extra dictEntry (varName, actualOffset) `shouldBe` (varName, expectedOffset) getDictionary :: String -> IO ST.Dictionary getDictionary program = do ST.SymTable {ST.stDict = dict} <- U.extractDictionary program return dict spec :: Spec spec = describe "Offset calculation" $ do it "calculates offset for the first variable in the list" $ testOffset "var x of type humanity" [("x", 0)] it "calculates offset for second variable in the list when first variable's type width is multiple of `wordsize`" $ testOffset "var x of type humanity, var y of type humanity" [("x", 0), ("y", 4)] it "calculates offset for second variable in the list when first variable's type width is not a multiple of `wordSize`" $ testOffset "var x of type sign, var y of type humanity" [("x", 0), ("y", 4)] it "calculates offset for variables with mixed data types" $ testOffset "\ \var x1 of type bezel {\ \ x2 of type humanity,\ \ x3 of type sign\ \},\ \var x4 of type sign" [("x1", 0), ("x2", 0), ("x3", 4), ("x4", 5)] it "calculates offset for links" $ testOffset "\ \var x1 of type link {\ \ x2 of type humanity,\ \ x3 of type sign\ \}" [("x1", 0), ("x2", 4), ("x3", 4)] it "takes advantage of scopes to achieve a better use of offsets" $ testProgram "hello ashen one\n\ \ traveling somewhere \ \ with \ \ var x of type humanity\ \ in your inventory \ \ while the lit covenant is active:\ \ traveling somewhere\ \ with\ \ var y of type humanity\ \ in your inventory\ \ while the lit covenant is active:\ \ traveling somewhere\ \ with\ \ var w of type humanity\ \ in your inventory\ \ go back\ \ you died \ \ covenant left\ \ you died \ \ covenant left \\ \ \ while the lit covenant is active:\ \ traveling somewhere\ \ with\ \ var z of type humanity\ \ in your inventory\ \ go back\ \ you died \ \ covenant left\ \ you died \ \ farewell ashen one" [("x", 0), ("y", 4), ("z", 4), ("w", 8)] it "calculates offset for function/procedure arguments, starting on 0" $ testProgram "hello ashen one\n\ \ invocation fun1\ \ requesting\ \ val x1 of type bezel { x of type sign, y of type bonfire },\ \ ref x2 of type bezel { x of type humanity, y of type humanity },\ \ val x3 of type humanity\ \ with skill of type humanity\ \ traveling somewhere \ \ with\ \ var y1 of type humanity \ \ in your inventory \ \ go back with 1\ \ you died\ \ after this return to your world\ \ spell fun2\ \ requesting\ \ val x4 of type bezel { x of type sign, y of type bonfire },\ \ ref x5 of type bezel { x of type humanity, y of type bonfire },\ \ val x6 of type humanity\ \ to the estus flask\ \ traveling somewhere \ \ with\ \ var y2 of type humanity \ \ in your inventory \ \ go back\ \ you died\ \ ashen estus flask consumed\ \ traveling somewhere \ \ with \ \ var x7 of type humanity,\ \ var x8 of type sign\ \ in your inventory \ \ go back \ \ you died \ \ farewell ashen one" [ ("x1", 0), ("x2", 4), ("x3", 8), ("y1", 12) , ("x4", 0), ("x5", 4), ("x6", 8), ("y2", 12) , ("x7", 0), ("x8", 4)]
null
https://raw.githubusercontent.com/aitorres/firelink/075d7aad1c053a54e39a27d8db7c3c719d243225/test/Semantic/OffsetSpec.hs
haskell
module OffsetSpec where import qualified FireLink.FrontEnd.SymTable as ST import Test.Hspec import qualified TestUtils as U testOffset :: String -> [(String, Int)] -> IO () testOffset = testProgram . baseProgram where baseProgram :: String -> String baseProgram s = "hello ashen one\n\ \ traveling somewhere \ \ with \ \" ++ s ++ "\ \ in your inventory \ \ with orange soapstone say @hello world@ \ \ you died \ \ farewell ashen one" testProgram :: String -> [(String, Int)] -> IO () testProgram program testItems = do dictionary <- getDictionary program mapM_ (test dictionary) testItems test :: ST.Dictionary -> (String, Int) -> IO () test dictionary (varName, expectedOffset) = do let chain = filter (\d -> ST.name d == varName) $ ST.findChain varName dictionary let dictEntry = head chain let ST.Offset actualOffset = U.extractOffsetFromExtra $ ST.extra dictEntry (varName, actualOffset) `shouldBe` (varName, expectedOffset) getDictionary :: String -> IO ST.Dictionary getDictionary program = do ST.SymTable {ST.stDict = dict} <- U.extractDictionary program return dict spec :: Spec spec = describe "Offset calculation" $ do it "calculates offset for the first variable in the list" $ testOffset "var x of type humanity" [("x", 0)] it "calculates offset for second variable in the list when first variable's type width is multiple of `wordsize`" $ testOffset "var x of type humanity, var y of type humanity" [("x", 0), ("y", 4)] it "calculates offset for second variable in the list when first variable's type width is not a multiple of `wordSize`" $ testOffset "var x of type sign, var y of type humanity" [("x", 0), ("y", 4)] it "calculates offset for variables with mixed data types" $ testOffset "\ \var x1 of type bezel {\ \ x2 of type humanity,\ \ x3 of type sign\ \},\ \var x4 of type sign" [("x1", 0), ("x2", 0), ("x3", 4), ("x4", 5)] it "calculates offset for links" $ testOffset "\ \var x1 of type link {\ \ x2 of type humanity,\ \ x3 of type sign\ \}" [("x1", 0), ("x2", 4), ("x3", 4)] it "takes advantage of scopes to achieve a better use of offsets" $ testProgram "hello ashen one\n\ \ traveling somewhere \ \ with \ \ var x of type humanity\ \ in your inventory \ \ while the lit covenant is active:\ \ traveling somewhere\ \ with\ \ var y of type humanity\ \ in your inventory\ \ while the lit covenant is active:\ \ traveling somewhere\ \ with\ \ var w of type humanity\ \ in your inventory\ \ go back\ \ you died \ \ covenant left\ \ you died \ \ covenant left \\ \ \ while the lit covenant is active:\ \ traveling somewhere\ \ with\ \ var z of type humanity\ \ in your inventory\ \ go back\ \ you died \ \ covenant left\ \ you died \ \ farewell ashen one" [("x", 0), ("y", 4), ("z", 4), ("w", 8)] it "calculates offset for function/procedure arguments, starting on 0" $ testProgram "hello ashen one\n\ \ invocation fun1\ \ requesting\ \ val x1 of type bezel { x of type sign, y of type bonfire },\ \ ref x2 of type bezel { x of type humanity, y of type humanity },\ \ val x3 of type humanity\ \ with skill of type humanity\ \ traveling somewhere \ \ with\ \ var y1 of type humanity \ \ in your inventory \ \ go back with 1\ \ you died\ \ after this return to your world\ \ spell fun2\ \ requesting\ \ val x4 of type bezel { x of type sign, y of type bonfire },\ \ ref x5 of type bezel { x of type humanity, y of type bonfire },\ \ val x6 of type humanity\ \ to the estus flask\ \ traveling somewhere \ \ with\ \ var y2 of type humanity \ \ in your inventory \ \ go back\ \ you died\ \ ashen estus flask consumed\ \ traveling somewhere \ \ with \ \ var x7 of type humanity,\ \ var x8 of type sign\ \ in your inventory \ \ go back \ \ you died \ \ farewell ashen one" [ ("x1", 0), ("x2", 4), ("x3", 8), ("y1", 12) , ("x4", 0), ("x5", 4), ("x6", 8), ("y2", 12) , ("x7", 0), ("x8", 4)]
3803eba015687c578ac9ea43f57e5e1fb3fdcaff0e45cd6d0e921e71c7b3d1c9
wdanilo/haskell-logger
Filter.hs
# LANGUAGE NoMonomorphismRestriction # # LANGUAGE UndecidableInstances # # LANGUAGE OverlappingInstances # # LANGUAGE TypeFamilies # ----------------------------------------------------------------------------- -- | -- Module : System.Log.Filter Copyright : ( C ) 2015 Flowbox -- License : Apache-2.0 Maintainer : < > -- Stability : stable -- Portability : portable ----------------------------------------------------------------------------- module System.Log.Filter where import System.Log.Log (Log) import System.Log.Data (Lvl(Lvl), Msg(Msg), LevelData(LevelData), readData, DataOf, Lookup, LookupDataSet) ---------------------------------------------------------------------- -- Filter ---------------------------------------------------------------------- newtype Filter a = Filter { runFilter :: Log a -> Bool } lvlFilter' :: (LookupDataSet Lvl l, Enum a) => a -> Log l -> Bool lvlFilter' lvl l = (i >= fromEnum lvl) where LevelData i _ = readData Lvl l lvlFilter lvl = Filter (lvlFilter' lvl)
null
https://raw.githubusercontent.com/wdanilo/haskell-logger/bdf3b64f50c0a8e26bd44fdb882e72ffbe19fd3f/src/System/Log/Filter.hs
haskell
--------------------------------------------------------------------------- | Module : System.Log.Filter License : Apache-2.0 Stability : stable Portability : portable --------------------------------------------------------------------------- -------------------------------------------------------------------- Filter --------------------------------------------------------------------
# LANGUAGE NoMonomorphismRestriction # # LANGUAGE UndecidableInstances # # LANGUAGE OverlappingInstances # # LANGUAGE TypeFamilies # Copyright : ( C ) 2015 Flowbox Maintainer : < > module System.Log.Filter where import System.Log.Log (Log) import System.Log.Data (Lvl(Lvl), Msg(Msg), LevelData(LevelData), readData, DataOf, Lookup, LookupDataSet) newtype Filter a = Filter { runFilter :: Log a -> Bool } lvlFilter' :: (LookupDataSet Lvl l, Enum a) => a -> Log l -> Bool lvlFilter' lvl l = (i >= fromEnum lvl) where LevelData i _ = readData Lvl l lvlFilter lvl = Filter (lvlFilter' lvl)
f928afbca94ac36da5b45fc35a767d1397985fc1de9e6a7e73eca790a0e3b6ee
hyperfiddle/electric
photon_blog2.cljc
(ns user (:require [datomic.api :as d] [hyperfiddle.photon-dom :as dom] [hyperfiddle.photon :as photon :refer [defnode]] [missionary.core :as m])) (defnode persons [db needle & [sort-order]] (sort (or sort-order <) (datomic.api/q '[:find [?e ...] :in $ ?needle :where [?e :person/email ?email] [(clojure.string/includes? ?email ?needle)]] db (or needle "")))) (defnode render-persons [db needle] ~@(dom/div (dom/h1 "submissions") (dom/table (photon/for [e ~@(persons db needle)] ~@(let [{:keys [:db/id :person/email :person/gender :person/shirt-size]} (datomic.api/entity db e)] ~@(dom/tr (dom/td (str id)) (dom/td email) (dom/td (pr-str gender)) (dom/td (pr-str shirt-size)))))))) (defnode render-persons [xs props] (dom/div (dom/h1 "submissions") (dom/table (photon/for [{:keys [:db/id :person/email :person/gender :person/shirt-size]} xs] (dom/tr (dom/td (str id)) (dom/td email) (dom/td (pr-str gender)) (dom/td (pr-str shirt-size))))))) (defnode query-persons [db needle sort-order] (let [xs (sort sort-order (datomic.api/q '[:find [?e ...] :in $ ?needle :where [?e :person/email ?email] [(clojure.string/includes? ?email ?needle)]] db (or needle "")))] (photon/for [x xs] (select-keys (datomic.api/entity db x) [:db/id :person/email :person/gender :person/shirt-size])))) (binding )
null
https://raw.githubusercontent.com/hyperfiddle/electric/1c6c3891cbf13123fef8d33e6555d300f0dac134/scratch/dustin/y2021/photon/photon_blog2.cljc
clojure
(ns user (:require [datomic.api :as d] [hyperfiddle.photon-dom :as dom] [hyperfiddle.photon :as photon :refer [defnode]] [missionary.core :as m])) (defnode persons [db needle & [sort-order]] (sort (or sort-order <) (datomic.api/q '[:find [?e ...] :in $ ?needle :where [?e :person/email ?email] [(clojure.string/includes? ?email ?needle)]] db (or needle "")))) (defnode render-persons [db needle] ~@(dom/div (dom/h1 "submissions") (dom/table (photon/for [e ~@(persons db needle)] ~@(let [{:keys [:db/id :person/email :person/gender :person/shirt-size]} (datomic.api/entity db e)] ~@(dom/tr (dom/td (str id)) (dom/td email) (dom/td (pr-str gender)) (dom/td (pr-str shirt-size)))))))) (defnode render-persons [xs props] (dom/div (dom/h1 "submissions") (dom/table (photon/for [{:keys [:db/id :person/email :person/gender :person/shirt-size]} xs] (dom/tr (dom/td (str id)) (dom/td email) (dom/td (pr-str gender)) (dom/td (pr-str shirt-size))))))) (defnode query-persons [db needle sort-order] (let [xs (sort sort-order (datomic.api/q '[:find [?e ...] :in $ ?needle :where [?e :person/email ?email] [(clojure.string/includes? ?email ?needle)]] db (or needle "")))] (photon/for [x xs] (select-keys (datomic.api/entity db x) [:db/id :person/email :person/gender :person/shirt-size])))) (binding )
7bd685d7f8b667a30987cdb5e78af2a9d2befae7b61bc7f5c82312a555af5ecc
city41/mario-review
rectangle_selection.cljs
(ns daisy.client.components.rectangle-selection (:require [om.core :as om :include-macros true] [sablono.core :as html :refer-macros [html]] [cljs.core.async :refer [put!]])) (def mouse-is-down (atom false)) (def upper-corner (atom nil)) (def lower-corner (atom nil)) (defn round [n] (.round js/Math n)) (defn ensure-even [n] (if (zero? (bit-and 1 n)) n (inc n))) (defn get-rect [upper-corner lower-corner] (let [ux (round (min (:x upper-corner) (:x lower-corner))) uy (round (min (:y upper-corner) (:y lower-corner))) lx (round (max (:x upper-corner) (:x lower-corner))) ly (round (max (:y upper-corner) (:y lower-corner))) w (- lx ux) h (- ly uy) w (ensure-even w) h (ensure-even h)] {:x ux :y uy :w w :h h})) (defn has-area [rect] (let [{:keys [w h]} rect] (and (> w 0) (> h 0)))) (defn get-selection [upper-corner lower-corner] (let [rect (get-rect upper-corner lower-corner)] (when (has-area rect) rect))) (defn draw-rect ([canvas upper-corner lower-corner] (draw-rect canvas (get-rect upper-corner lower-corner))) ([canvas rect] (let [ctx (.getContext canvas "2d")] (set! (.-fillStyle ctx) "rgba(255, 255, 255, 0.8)") (set! (.-strokeStyle ctx) "rgba(155, 201, 161, 1)") (.clearRect ctx 0 0 (.-width canvas) (.-height canvas)) (when (has-area rect) (.fillRect ctx 0 0 (.-width canvas) (.-height canvas)) (.clearRect ctx (:x rect) (:y rect) (:w rect) (:h rect)) (.strokeRect ctx (:x rect) (:y rect) (:w rect) (:h rect)))))) (defn get-canvas-xy [e] (let [brect (.getBoundingClientRect (.-target e)) left (.-left brect) top (.-top brect) x (- (.-clientX e) left) y (- (.-clientY e) top)] {:x x :y y})) (defn mouse-down [e] (let [canvas-xy (get-canvas-xy e)] (reset! mouse-is-down true) (reset! upper-corner canvas-xy))) (defn mouse-move [e] (when @mouse-is-down (let [canvas-xy (get-canvas-xy e)] (reset! lower-corner canvas-xy) (draw-rect (.-target e) @upper-corner @lower-corner)))) (defn mouse-up [e app] (reset! mouse-is-down false) (reset! lower-corner (get-canvas-xy e)) (draw-rect (.-target e) @upper-corner @lower-corner) (om/update! app :selection (get-selection @upper-corner @lower-corner))) (defn get-left [frame-width] (str "calc(50% - " (/ frame-width 2) "px)")) (defn cmp [app owner] (reify om/IWillUpdate (will-update [_ {:keys [selection] :as next-props} _] (let [prev-selection (:selection (om/get-props owner))] (when-not (= selection prev-selection) (draw-rect (om/get-node owner "rectangle-selection") selection)))) om/IRender (render [_] (html [:canvas.rectangle-selection { :ref "rectangle-selection" :style #js {:left (get-left (:frame-width app))} :on-mouse-down mouse-down :on-mouse-move mouse-move :on-mouse-up #(mouse-up % app) :width (:frame-width app) :height (:frame-height app)}]))))
null
https://raw.githubusercontent.com/city41/mario-review/1b6ebfff88ad778a52865a062204cabb8deed0f9/cropping-app/src/client/rectangle_selection.cljs
clojure
(ns daisy.client.components.rectangle-selection (:require [om.core :as om :include-macros true] [sablono.core :as html :refer-macros [html]] [cljs.core.async :refer [put!]])) (def mouse-is-down (atom false)) (def upper-corner (atom nil)) (def lower-corner (atom nil)) (defn round [n] (.round js/Math n)) (defn ensure-even [n] (if (zero? (bit-and 1 n)) n (inc n))) (defn get-rect [upper-corner lower-corner] (let [ux (round (min (:x upper-corner) (:x lower-corner))) uy (round (min (:y upper-corner) (:y lower-corner))) lx (round (max (:x upper-corner) (:x lower-corner))) ly (round (max (:y upper-corner) (:y lower-corner))) w (- lx ux) h (- ly uy) w (ensure-even w) h (ensure-even h)] {:x ux :y uy :w w :h h})) (defn has-area [rect] (let [{:keys [w h]} rect] (and (> w 0) (> h 0)))) (defn get-selection [upper-corner lower-corner] (let [rect (get-rect upper-corner lower-corner)] (when (has-area rect) rect))) (defn draw-rect ([canvas upper-corner lower-corner] (draw-rect canvas (get-rect upper-corner lower-corner))) ([canvas rect] (let [ctx (.getContext canvas "2d")] (set! (.-fillStyle ctx) "rgba(255, 255, 255, 0.8)") (set! (.-strokeStyle ctx) "rgba(155, 201, 161, 1)") (.clearRect ctx 0 0 (.-width canvas) (.-height canvas)) (when (has-area rect) (.fillRect ctx 0 0 (.-width canvas) (.-height canvas)) (.clearRect ctx (:x rect) (:y rect) (:w rect) (:h rect)) (.strokeRect ctx (:x rect) (:y rect) (:w rect) (:h rect)))))) (defn get-canvas-xy [e] (let [brect (.getBoundingClientRect (.-target e)) left (.-left brect) top (.-top brect) x (- (.-clientX e) left) y (- (.-clientY e) top)] {:x x :y y})) (defn mouse-down [e] (let [canvas-xy (get-canvas-xy e)] (reset! mouse-is-down true) (reset! upper-corner canvas-xy))) (defn mouse-move [e] (when @mouse-is-down (let [canvas-xy (get-canvas-xy e)] (reset! lower-corner canvas-xy) (draw-rect (.-target e) @upper-corner @lower-corner)))) (defn mouse-up [e app] (reset! mouse-is-down false) (reset! lower-corner (get-canvas-xy e)) (draw-rect (.-target e) @upper-corner @lower-corner) (om/update! app :selection (get-selection @upper-corner @lower-corner))) (defn get-left [frame-width] (str "calc(50% - " (/ frame-width 2) "px)")) (defn cmp [app owner] (reify om/IWillUpdate (will-update [_ {:keys [selection] :as next-props} _] (let [prev-selection (:selection (om/get-props owner))] (when-not (= selection prev-selection) (draw-rect (om/get-node owner "rectangle-selection") selection)))) om/IRender (render [_] (html [:canvas.rectangle-selection { :ref "rectangle-selection" :style #js {:left (get-left (:frame-width app))} :on-mouse-down mouse-down :on-mouse-move mouse-move :on-mouse-up #(mouse-up % app) :width (:frame-width app) :height (:frame-height app)}]))))
8fc9215dcc34559c074e3dcde1aaa7795c341d49c17902d7085abcb419a84d07
iu-parfunc/verified-instances
List.hs
{-@ LIQUID "--higherorder" @-} {-@ LIQUID "--exact-data-cons" @-} {-@ LIQUID "--prune-unsorted" @-} module List where import GHC.Classes . VerifiedEq import Data.VerifiedEq import Language.Haskell.Liquid.ProofCombinators {-@ data List [llen] = Nil | Cons { x :: a , xs :: List a } @-} data List a = Nil | Cons a (List a) {-@ measure llen @-} {-@ llen :: List a -> Nat @-} llen :: List a -> Int llen Nil = 0 llen (Cons _ xs) = 1 + llen xs {-@ axiomatize eqList @-} eqList :: Eq a => List a -> List a -> Bool eqList Nil Nil = True eqList (Cons x xs) (Cons y ys) = if x == y then eqList xs ys else False eqList _ _ = False {-@ eqListRefl :: xs:List a -> {eqList xs xs} @-} eqListRefl :: Eq a => List a -> Proof eqListRefl xs@Nil = eqList xs xs ==. True *** QED eqListRefl (Cons x xs) = eqList (Cons x xs) (Cons x xs) ==. (if x == x then eqList xs xs else False) ==. eqList xs xs ==. True ? eqListRefl xs *** QED {-@ eqListSym :: xs:List a -> ys: List a -> {eqList xs ys ==> eqList ys xs} @-} eqListSym :: Eq a => List a -> List a -> Proof eqListSym Nil Nil = simpleProof eqListSym Nil (Cons y ys) = eqList Nil (Cons y ys) ==. False *** QED eqListSym (Cons x xs) Nil = eqList (Cons x xs) Nil ==. False *** QED eqListSym (Cons x xs) (Cons y ys) = eqList (Cons x xs) (Cons y ys) ==. (if x == y then eqList xs ys else False) ==. (if y == x then eqList xs ys else False) ==. (if y == x then eqList ys xs else False) ? eqListSym xs ys ==. eqList (Cons y ys) (Cons x xs) ==. eqList ys xs *** QED @ eqListTrans : : xs : List a - > ys : List a - > zs : List a - > { eqList xs ys & & eqList ys zs = = > eqList xs zs } @ eqListTrans :: Eq a => List a -> List a -> List a -> Proof eqListTrans Nil Nil Nil = simpleProof eqListTrans Nil Nil (Cons z zs) = eqList Nil (Cons z zs) ==. True *** QED eqListTrans Nil (Cons y ys) _zs = eqList Nil (Cons y ys) ==. False *** QED eqListTrans (Cons x xs) Nil _zs = eqList (Cons x xs) Nil ==. False *** QED eqListTrans (Cons _ _) (Cons y ys) Nil = eqList (Cons y ys) Nil ==. False *** QED eqListTrans (Cons x xs) (Cons y ys) (Cons z zs) = (eqList (Cons x xs) (Cons y ys) && eqList (Cons y ys) (Cons z zs)) ==. ((if x == y then eqList xs ys else False) && (if y == z then eqList ys zs else False)) ==. (if (x == y && y == z) then (eqList xs ys && eqList ys zs) else False) ==. (if x == z then eqList xs zs else False) ? eqListTrans xs ys zs ==. eqList (Cons x xs) (Cons z zs) *** QED instance Eq a => Eq (List a) where (==) = eqList instance VerifiedEq a = > VerifiedEq ( List a ) where -- refl = eqListRefl sym = eqListSym trans = eqListTrans veqList :: Eq a => VerifiedEq (List a) veqList = VerifiedEq eqList eqListRefl eqListSym eqListTrans {-@ axiomatize appendList @-} appendList :: List a -> List a -> List a appendList Nil ys = ys appendList (Cons x xs) ys = Cons x (appendList xs ys) {-@ appendListAssoc :: xs:List a -> ys:List a -> zs:List a -> { appendList (appendList xs ys) zs == appendList xs (appendList ys zs) } @-} appendListAssoc :: List a -> List a -> List a -> Proof appendListAssoc Nil ys zs = appendList (appendList Nil ys) zs ==. appendList ys zs ==. appendList Nil (appendList ys zs) *** QED appendListAssoc (Cons x xs) ys zs = appendList (appendList (Cons x xs) ys) zs ==. appendList (Cons x (appendList xs ys)) zs ==. Cons x (appendList (appendList xs ys) zs) ==. Cons x (appendList xs (appendList ys zs)) ? appendListAssoc xs ys zs ==. appendList (Cons x xs) (appendList ys zs) *** QED
null
https://raw.githubusercontent.com/iu-parfunc/verified-instances/cebfdf1e3357a693360be74c90211be18ce3c045/examples/List.hs
haskell
@ LIQUID "--higherorder" @ @ LIQUID "--exact-data-cons" @ @ LIQUID "--prune-unsorted" @ @ data List [llen] = Nil | Cons { x :: a , xs :: List a } @ @ measure llen @ @ llen :: List a -> Nat @ @ axiomatize eqList @ @ eqListRefl :: xs:List a -> {eqList xs xs} @ @ eqListSym :: xs:List a -> ys: List a -> {eqList xs ys ==> eqList ys xs} @ refl = eqListRefl @ axiomatize appendList @ @ appendListAssoc :: xs:List a -> ys:List a -> zs:List a -> { appendList (appendList xs ys) zs == appendList xs (appendList ys zs) } @
module List where import GHC.Classes . VerifiedEq import Data.VerifiedEq import Language.Haskell.Liquid.ProofCombinators data List a = Nil | Cons a (List a) llen :: List a -> Int llen Nil = 0 llen (Cons _ xs) = 1 + llen xs eqList :: Eq a => List a -> List a -> Bool eqList Nil Nil = True eqList (Cons x xs) (Cons y ys) = if x == y then eqList xs ys else False eqList _ _ = False eqListRefl :: Eq a => List a -> Proof eqListRefl xs@Nil = eqList xs xs ==. True *** QED eqListRefl (Cons x xs) = eqList (Cons x xs) (Cons x xs) ==. (if x == x then eqList xs xs else False) ==. eqList xs xs ==. True ? eqListRefl xs *** QED eqListSym :: Eq a => List a -> List a -> Proof eqListSym Nil Nil = simpleProof eqListSym Nil (Cons y ys) = eqList Nil (Cons y ys) ==. False *** QED eqListSym (Cons x xs) Nil = eqList (Cons x xs) Nil ==. False *** QED eqListSym (Cons x xs) (Cons y ys) = eqList (Cons x xs) (Cons y ys) ==. (if x == y then eqList xs ys else False) ==. (if y == x then eqList xs ys else False) ==. (if y == x then eqList ys xs else False) ? eqListSym xs ys ==. eqList (Cons y ys) (Cons x xs) ==. eqList ys xs *** QED @ eqListTrans : : xs : List a - > ys : List a - > zs : List a - > { eqList xs ys & & eqList ys zs = = > eqList xs zs } @ eqListTrans :: Eq a => List a -> List a -> List a -> Proof eqListTrans Nil Nil Nil = simpleProof eqListTrans Nil Nil (Cons z zs) = eqList Nil (Cons z zs) ==. True *** QED eqListTrans Nil (Cons y ys) _zs = eqList Nil (Cons y ys) ==. False *** QED eqListTrans (Cons x xs) Nil _zs = eqList (Cons x xs) Nil ==. False *** QED eqListTrans (Cons _ _) (Cons y ys) Nil = eqList (Cons y ys) Nil ==. False *** QED eqListTrans (Cons x xs) (Cons y ys) (Cons z zs) = (eqList (Cons x xs) (Cons y ys) && eqList (Cons y ys) (Cons z zs)) ==. ((if x == y then eqList xs ys else False) && (if y == z then eqList ys zs else False)) ==. (if (x == y && y == z) then (eqList xs ys && eqList ys zs) else False) ==. (if x == z then eqList xs zs else False) ? eqListTrans xs ys zs ==. eqList (Cons x xs) (Cons z zs) *** QED instance Eq a => Eq (List a) where (==) = eqList instance VerifiedEq a = > VerifiedEq ( List a ) where sym = eqListSym trans = eqListTrans veqList :: Eq a => VerifiedEq (List a) veqList = VerifiedEq eqList eqListRefl eqListSym eqListTrans appendList :: List a -> List a -> List a appendList Nil ys = ys appendList (Cons x xs) ys = Cons x (appendList xs ys) appendListAssoc :: List a -> List a -> List a -> Proof appendListAssoc Nil ys zs = appendList (appendList Nil ys) zs ==. appendList ys zs ==. appendList Nil (appendList ys zs) *** QED appendListAssoc (Cons x xs) ys zs = appendList (appendList (Cons x xs) ys) zs ==. appendList (Cons x (appendList xs ys)) zs ==. Cons x (appendList (appendList xs ys) zs) ==. Cons x (appendList xs (appendList ys zs)) ? appendListAssoc xs ys zs ==. appendList (Cons x xs) (appendList ys zs) *** QED
61db4fb51ebcb22f1defdd717938c2fcdecbed699f00fa1f124a6dcbf0ffd004
fulcro-legacy/semantic-ui-wrapper
ui_feed_label.cljs
(ns fulcrologic.semantic-ui.views.feed.ui-feed-label (:require [fulcrologic.semantic-ui.factory-helpers :as h] ["semantic-ui-react/dist/commonjs/views/Feed/FeedLabel" :default FeedLabel])) (def ui-feed-label "An event can contain an image or icon label. Props: - as (custom): An element type to render as (string or function). - children (node): Primary content. - className (string): Additional classes. - content (custom): Shorthand for primary content. - icon (custom): An event can contain icon label. - image (custom): An event can contain image label." (h/factory-apply FeedLabel))
null
https://raw.githubusercontent.com/fulcro-legacy/semantic-ui-wrapper/b0473480ddfff18496df086bf506099ac897f18f/semantic-ui-wrappers-shadow/src/main/fulcrologic/semantic_ui/views/feed/ui_feed_label.cljs
clojure
(ns fulcrologic.semantic-ui.views.feed.ui-feed-label (:require [fulcrologic.semantic-ui.factory-helpers :as h] ["semantic-ui-react/dist/commonjs/views/Feed/FeedLabel" :default FeedLabel])) (def ui-feed-label "An event can contain an image or icon label. Props: - as (custom): An element type to render as (string or function). - children (node): Primary content. - className (string): Additional classes. - content (custom): Shorthand for primary content. - icon (custom): An event can contain icon label. - image (custom): An event can contain image label." (h/factory-apply FeedLabel))
0b21bff632b62257998e0f6b0486c35f429b400a784a9a58363472e691d2e5d5
tek/polysemy-hasql
QueryStore.hs
module Polysemy.Hasql.Interpreter.QueryStore where import Hasql.Encoders (Params) import Polysemy.Db.Data.DbConfig (DbConfig) import Polysemy.Db.Data.DbError (DbError) import Polysemy.Db.Data.InitDbError (InitDbError) import qualified Polysemy.Db.Data.QueryStore as QueryStore import Polysemy.Db.Data.QueryStore (QueryStore) import Polysemy.Time (interpretTimeGhc) import Polysemy.Hasql.Crud (interpretCrud, interpretCrudWith) import Polysemy.Hasql.Data.Crud (Crud (..)) import Polysemy.Hasql.Data.Database (Database) import Polysemy.Hasql.Data.ManagedTable (ManagedTable) import Polysemy.Hasql.Data.Query (Query) import qualified Polysemy.Hasql.Data.QueryTable as QueryTable import Polysemy.Hasql.Data.QueryTable (QueryTable) import qualified Polysemy.Hasql.Data.Where as Data import Polysemy.Hasql.Database (interpretDatabase) import Polysemy.Hasql.DbConnection (interpretDbConnection) import Polysemy.Hasql.ManagedTable (interpretManagedTable, interpretManagedTableGen) import Polysemy.Hasql.Query (interpretQuery) import qualified Polysemy.Hasql.Store.Statement as Statement import Polysemy.Hasql.Table.Schema (Schema) type QueryStoreStack i d q p = [QueryStore i d q !! DbError, Crud i d q !! DbError, ManagedTable d !! DbError] interpretQueryStoreDb :: Members [Crud i d q !! e, ManagedTable d !! e] r => InterpreterFor (QueryStore i d q !! e) r interpretQueryStoreDb = interpretResumable \case QueryStore.Insert record -> Statement.insert record QueryStore.Upsert record -> Statement.upsert record QueryStore.Delete id' -> nonEmpty <$> Statement.delete id' QueryStore.DeleteAll -> nonEmpty <$> Statement.deleteAll QueryStore.Fetch id' -> Statement.fetch id' QueryStore.FetchAll -> nonEmpty <$> Statement.fetchAll QueryStore.Query q -> nonEmpty <$> Statement.fetchQ q type QueryStoreDeps t dt = [Database !! DbError, Time t dt, Log, Embed IO] interpretQueryStoreDbFullWith :: Members (QueryStoreDeps t dt) r => QueryTable q d -> Params i -> Data.Where i d -> InterpretersFor (QueryStoreStack i d q p) r interpretQueryStoreDbFullWith table iParams iWhere = interpretManagedTable (table ^. QueryTable.table) . interpretCrudWith table iParams iWhere . interpretQueryStoreDb {-# inline interpretQueryStoreDbFullWith #-} interpretQueryStoreDbQuery :: ∀ qrep rep i d q p t dt r . Schema qrep rep q d => Members [Tagged "id" (Query i d), Tagged "main" (Query q d), Error InitDbError] r => Members (QueryStoreDeps t dt) r => InterpretersFor (QueryStoreStack i d q p) r interpretQueryStoreDbQuery = interpretManagedTableGen @rep . interpretCrud . interpretQueryStoreDb {-# inline interpretQueryStoreDbQuery #-} interpretQueryStoreDbFullGenAs :: ∀ qrep iqrep rep i d q p t dt r . Schema qrep rep q d => Schema iqrep rep i d => Members (Error InitDbError : QueryStoreDeps t dt) r => InterpretersFor (QueryStoreStack i d q p) r interpretQueryStoreDbFullGenAs = interpretQuery @qrep @rep @q @d . untag @"main" . interpretQuery @iqrep @rep @i @d . untag @"id" . interpretQueryStoreDbQuery @qrep @rep @i @d @q @p . raise3Under . raise3Under interpretQueryStoreDbSingle :: ∀ qrep iqrep rep i d q p r . Schema qrep rep q d => Schema iqrep rep i d => Members [Resource, Log, Error InitDbError, Embed IO, Final IO] r => Text -> DbConfig -> InterpretersFor (QueryStoreStack i d q p) r interpretQueryStoreDbSingle name host = interpretDbConnection name host . interpretTimeGhc . interpretDatabase . interpretQueryStoreDbFullGenAs @qrep @iqrep @rep . raise3Under . raise3Under . raise3Under
null
https://raw.githubusercontent.com/tek/polysemy-hasql/1cf195590fc3c356adf042ae3b0a1f9874591a74/packages/hasql/lib/Polysemy/Hasql/Interpreter/QueryStore.hs
haskell
# inline interpretQueryStoreDbFullWith # # inline interpretQueryStoreDbQuery #
module Polysemy.Hasql.Interpreter.QueryStore where import Hasql.Encoders (Params) import Polysemy.Db.Data.DbConfig (DbConfig) import Polysemy.Db.Data.DbError (DbError) import Polysemy.Db.Data.InitDbError (InitDbError) import qualified Polysemy.Db.Data.QueryStore as QueryStore import Polysemy.Db.Data.QueryStore (QueryStore) import Polysemy.Time (interpretTimeGhc) import Polysemy.Hasql.Crud (interpretCrud, interpretCrudWith) import Polysemy.Hasql.Data.Crud (Crud (..)) import Polysemy.Hasql.Data.Database (Database) import Polysemy.Hasql.Data.ManagedTable (ManagedTable) import Polysemy.Hasql.Data.Query (Query) import qualified Polysemy.Hasql.Data.QueryTable as QueryTable import Polysemy.Hasql.Data.QueryTable (QueryTable) import qualified Polysemy.Hasql.Data.Where as Data import Polysemy.Hasql.Database (interpretDatabase) import Polysemy.Hasql.DbConnection (interpretDbConnection) import Polysemy.Hasql.ManagedTable (interpretManagedTable, interpretManagedTableGen) import Polysemy.Hasql.Query (interpretQuery) import qualified Polysemy.Hasql.Store.Statement as Statement import Polysemy.Hasql.Table.Schema (Schema) type QueryStoreStack i d q p = [QueryStore i d q !! DbError, Crud i d q !! DbError, ManagedTable d !! DbError] interpretQueryStoreDb :: Members [Crud i d q !! e, ManagedTable d !! e] r => InterpreterFor (QueryStore i d q !! e) r interpretQueryStoreDb = interpretResumable \case QueryStore.Insert record -> Statement.insert record QueryStore.Upsert record -> Statement.upsert record QueryStore.Delete id' -> nonEmpty <$> Statement.delete id' QueryStore.DeleteAll -> nonEmpty <$> Statement.deleteAll QueryStore.Fetch id' -> Statement.fetch id' QueryStore.FetchAll -> nonEmpty <$> Statement.fetchAll QueryStore.Query q -> nonEmpty <$> Statement.fetchQ q type QueryStoreDeps t dt = [Database !! DbError, Time t dt, Log, Embed IO] interpretQueryStoreDbFullWith :: Members (QueryStoreDeps t dt) r => QueryTable q d -> Params i -> Data.Where i d -> InterpretersFor (QueryStoreStack i d q p) r interpretQueryStoreDbFullWith table iParams iWhere = interpretManagedTable (table ^. QueryTable.table) . interpretCrudWith table iParams iWhere . interpretQueryStoreDb interpretQueryStoreDbQuery :: ∀ qrep rep i d q p t dt r . Schema qrep rep q d => Members [Tagged "id" (Query i d), Tagged "main" (Query q d), Error InitDbError] r => Members (QueryStoreDeps t dt) r => InterpretersFor (QueryStoreStack i d q p) r interpretQueryStoreDbQuery = interpretManagedTableGen @rep . interpretCrud . interpretQueryStoreDb interpretQueryStoreDbFullGenAs :: ∀ qrep iqrep rep i d q p t dt r . Schema qrep rep q d => Schema iqrep rep i d => Members (Error InitDbError : QueryStoreDeps t dt) r => InterpretersFor (QueryStoreStack i d q p) r interpretQueryStoreDbFullGenAs = interpretQuery @qrep @rep @q @d . untag @"main" . interpretQuery @iqrep @rep @i @d . untag @"id" . interpretQueryStoreDbQuery @qrep @rep @i @d @q @p . raise3Under . raise3Under interpretQueryStoreDbSingle :: ∀ qrep iqrep rep i d q p r . Schema qrep rep q d => Schema iqrep rep i d => Members [Resource, Log, Error InitDbError, Embed IO, Final IO] r => Text -> DbConfig -> InterpretersFor (QueryStoreStack i d q p) r interpretQueryStoreDbSingle name host = interpretDbConnection name host . interpretTimeGhc . interpretDatabase . interpretQueryStoreDbFullGenAs @qrep @iqrep @rep . raise3Under . raise3Under . raise3Under
49ebbad3d78d79fb683d86ee7facaeed97f5b7ddaa51801fdb8bebf126ef4837
kronusaturn/lw2-viewer
config-package.lisp
(uiop:define-package #:lw2-viewer.config (:use #:cl #:lw2.sites #:lw2.backend-modules #:lw2.fonts-modules) (:export #:*lmdb-mapsize* #:*dnsbl-list* #:*html-global-resources*) (:unintern #:*site-uri* #:*graphql-uri* #:*websocket-uri* #:*backend-type* #:*secure-cookies* #:*cache-db*)) (in-package #:lw2-viewer.config) (defvar *dnsbl-list* nil) (defvar *html-global-resources* nil)
null
https://raw.githubusercontent.com/kronusaturn/lw2-viewer/f328105e9640be1314d166203c8706f9470054fa/src/config-package.lisp
lisp
(uiop:define-package #:lw2-viewer.config (:use #:cl #:lw2.sites #:lw2.backend-modules #:lw2.fonts-modules) (:export #:*lmdb-mapsize* #:*dnsbl-list* #:*html-global-resources*) (:unintern #:*site-uri* #:*graphql-uri* #:*websocket-uri* #:*backend-type* #:*secure-cookies* #:*cache-db*)) (in-package #:lw2-viewer.config) (defvar *dnsbl-list* nil) (defvar *html-global-resources* nil)
de555838234c05a3324f1d75862afa5a10e9104637b80ec7343c3eeb78f9cef9
input-output-hk/cardano-sl
Base.hs
# LANGUAGE RecordWildCards # {-# LANGUAGE TypeFamilies #-} -- | Basic functionality from Toss. module Pos.Chain.Ssc.Toss.Base ( -- * Trivial functions getCommitment , hasCommitmentToss , hasOpeningToss , hasSharesToss , hasCertificateToss -- * Basic logic , getParticipants , computeParticipants , computeSharesDistrPure , computeSharesDistr , isDistrInaccuracyAcceptable , sharesDistrInaccuracy , sharesDistrMaxSumDistr -- * Payload processing , checkCommitmentsPayload , checkOpeningsPayload , checkSharesPayload , checkCertificatesPayload , checkPayload -- * Helpers , verifyEntriesGuardM ) where import Universum hiding (id, keys) import Control.Monad.Except (MonadError (throwError)) import Control.Monad.ST (ST, runST) import Crypto.Random (MonadRandom) import Data.Array.MArray (newArray, readArray, writeArray) import Data.Array.ST (STUArray) import Data.Containers (ContainerKey, SetContainer (notMember)) import qualified Data.HashMap.Strict as HM import qualified Data.HashSet as HS import qualified Data.List.NonEmpty as NE import Data.STRef (newSTRef, readSTRef, writeSTRef) import Formatting (sformat, (%)) import Pos.Binary.Class (AsBinary, fromBinary) import Pos.Chain.Genesis as Genesis (Config) import Pos.Chain.Lrc.Types (RichmenSet, RichmenStakes) import Pos.Chain.Ssc.Base (verifyOpening, vssThreshold) import Pos.Chain.Ssc.Commitment (Commitment (..), SignedCommitment, commShares, getCommShares) import Pos.Chain.Ssc.CommitmentsMap (CommitmentsMap (getCommitmentsMap)) import Pos.Chain.Ssc.Error (SscVerifyError (..)) import Pos.Chain.Ssc.Opening (Opening (..)) import Pos.Chain.Ssc.OpeningsMap (OpeningsMap) import Pos.Chain.Ssc.Payload (SscPayload (..), spVss) import Pos.Chain.Ssc.SharesDistribution (SharesDistribution) import Pos.Chain.Ssc.SharesMap (InnerSharesMap, SharesMap) import Pos.Chain.Ssc.Toss.Class (MonadToss (..), MonadTossEnv (..), MonadTossRead (..)) import Pos.Chain.Ssc.VssCertificate (vcSigningKey, vcVssKey) import Pos.Chain.Ssc.VssCertificatesMap (VssCertificatesMap (..), lookupVss, memberVss) import Pos.Chain.Update.BlockVersionData (bvdMpcThd) import Pos.Core (CoinPortion, EpochIndex (..), StakeholderId, addressHash, coinPortionDenominator, getCoinPortion, unsafeGetCoin) import Pos.Crypto (DecShare, verifyDecShare, verifyEncShares) import Pos.Util.Util (getKeys, intords) import Pos.Util.Wlog (logWarning) ---------------------------------------------------------------------------- -- Trivial getters (proper interface of MonadTossRead) ---------------------------------------------------------------------------- | Retrieve ' SignedCommitment ' of given stakeholder if it 's known . getCommitment :: MonadTossRead m => StakeholderId -> m (Maybe SignedCommitment) getCommitment id = HM.lookup id . getCommitmentsMap <$> getCommitments -- | Check whether there is a 'SignedCommitment' from given stakeholder. hasCommitmentToss :: MonadTossRead m => StakeholderId -> m Bool hasCommitmentToss id = HM.member id . getCommitmentsMap <$> getCommitments -- | Check whether there is an 'Opening' from given stakeholder. hasOpeningToss :: MonadTossRead m => StakeholderId -> m Bool hasOpeningToss id = HM.member id <$> getOpenings -- | Check whether there is 'InnerSharesMap' from given stakeholder. hasSharesToss :: MonadTossRead m => StakeholderId -> m Bool hasSharesToss id = HM.member id <$> getShares | Check whether there is ' VssCertificate ' from given stakeholder . hasCertificateToss :: MonadTossRead m => StakeholderId -> m Bool hasCertificateToss id = memberVss id <$> getVssCertificates ---------------------------------------------------------------------------- -- Non-trivial getters ---------------------------------------------------------------------------- | Get ' VssCertificatesMap ' containing ' StakeholderId 's and ' VssPublicKey 's of participating nodes for given epoch . getParticipants :: (MonadError SscVerifyError m, MonadToss m, MonadTossEnv m) => Genesis.Config -> EpochIndex -> m VssCertificatesMap getParticipants genesisConfig epoch = do stableCerts <- getStableCertificates genesisConfig epoch richmen <- note (NoRichmen epoch) =<< getRichmen epoch pure $ computeParticipants (getKeys richmen) stableCerts ---------------------------------------------------------------------------- -- Simple checks in 'MonadTossRead' ---------------------------------------------------------------------------- -- | Check that the secret revealed in the opening matches the secret proof -- in the commitment. matchCommitment :: MonadTossRead m => (StakeholderId, Opening) -> m Bool matchCommitment op = flip matchCommitmentPure op <$> getCommitments checkShares :: (MonadTossRead m, MonadTossEnv m) => Genesis.Config -> EpochIndex -> (StakeholderId, InnerSharesMap) -> m Bool checkShares genesisConfig epoch (id, sh) = do certs <- getStableCertificates genesisConfig epoch let warnFmt = ("checkShares: no richmen for "%intords%" epoch") getRichmen epoch >>= \case Nothing -> False <$ logWarning (sformat warnFmt (getEpochIndex epoch)) Just richmen -> do let parts = computeParticipants (getKeys richmen) certs coms <- getCommitments ops <- getOpenings pure $ checkSharesPure coms ops parts id sh ---------------------------------------------------------------------------- -- Pure functions ---------------------------------------------------------------------------- | Compute ' VssCertificate 's of SSC participants using set of -- richmen and stable certificates. computeParticipants :: RichmenSet -> VssCertificatesMap -> VssCertificatesMap computeParticipants (HS.toMap -> richmen) (UnsafeVssCertificatesMap certs) = -- Using 'UnsafeVssCertificatesMap' is safe here because if the original -- 'certs' map is okay, a subset of the original 'certs' map is okay too. UnsafeVssCertificatesMap (HM.intersection certs richmen) | We accept inaccuracy in computation not greater than 0.05 , so stakeholders must have at least 55 % of stake to reveal secret -- in the worst case sharesDistrInaccuracy :: Fractional a => a sharesDistrInaccuracy = 0.05 | sum of distribution sharesDistrMaxSumDistr :: RealFrac a => a -> Word16 sharesDistrMaxSumDistr thd = truncate $ 3 / thd | Internal type for work with Coin . type CoinUnsafe = Int64 | Types represents one dimensional array used for knapsack algorithm in the @computeDistrInaccuracy@ type Knapsack s = STUArray s Word16 CoinUnsafe -- ATTENTION: IMPERATIVE CODE! PROTECT YOUR EYES! -- | Compute inaccuracy between real distribution and generared . It take O(totalDistr * ) time . inaccuracy is more or less heuristic value -- which means difference between generated and -- real distribution we can get in the worst case. This inaccuracy can lead to two bad situation : 1 . when nodes must n't reveal commitment , but they can 2 . when nodes must reveal commitment , but they ca n't -- We can get these situations when sum of stakes of nodes which sent shares is close to 0.5 . isDistrInaccuracyAcceptable :: [(CoinUnsafe, Word16)] -> Bool isDistrInaccuracyAcceptable coinsNDistr = runST $ do let !totalDistr = sum $ map snd coinsNDistr let !totalCoins = sum $ map fst coinsNDistr let halfDistr = totalDistr `div` 2 + 1 let invalid = totalCoins + 1 -- A sum of generated portions can be computed as -- sum of corresponding shares distribution divided by @totalDistr@. -- A sum of real portions can be computed as -- sum of corresponding coins divided by @totalCoins@. For the bad case of type 2 , -- for each sum of shares distribution which is less than @totalDistr@ / 2 -- we would know the maximum sum of real distribution corresponding to -- nodes which form this sum of shares distribution to evaluate inaccuracy of the bad case type 2 . -- So for every sum of generated shares -- we store this sum of coins and try to maximize it. We do n't compute bad case of type 1 explicitly , because if there is such subset which causes inaccuracy of type 1 we can take complement of this subset and get the same inaccuracy of type 2 . dpMax <- newArray (0, totalDistr) (-invalid) :: ST s (Knapsack s) writeArray dpMax 0 0 -- Relaxation function. let relax dp coins w nw cmp = do dpW <- readArray dp w dpNw <- readArray dp nw when ((dpW + coins) `cmp` dpNw) $ writeArray dp nw (dpW + coins) pure (dpW + coins) let weights = [halfDistr - 1, halfDistr - 2..0] let halfCoins = totalCoins `div` 2 + 1 let totalDistrD, totalCoinsD :: Double totalDistrD = fromIntegral totalDistr totalCoinsD = fromIntegral totalCoins let computeLimit i = let p = fromIntegral i / totalDistrD in max halfCoins (ceiling (totalCoinsD * (sharesDistrInaccuracy + p))) let weightsNLimits = zip weights (map computeLimit weights) isAcceptable <- newSTRef True -- Iterate over distribution forM_ coinsNDistr $ \(coins, distr) -> whenM (readSTRef isAcceptable) $ do -- Try to relax coins for whole weights forM_ weightsNLimits $ \(w, limit) -> when (w >= distr) $ do sCoinsMx <- relax dpMax coins (w - distr) w (>) when (sCoinsMx >= limit) $ writeSTRef isAcceptable False readSTRef isAcceptable computeSharesDistrPure :: MonadError SscVerifyError m => RichmenStakes ^ MPC threshold , e.g. ' genesisMpcThd ' -> m SharesDistribution computeSharesDistrPure richmen threshold | null richmen = pure mempty | otherwise = do when (totalCoins == 0) $ throwError $ TossInternalError "Richmen total stake equals zero" let mpcThreshold = toRational (getCoinPortion threshold) / toRational coinPortionDenominator unless (all ((>= mpcThreshold) . toRational) portions) $ throwError $ TossInternalError "Richmen stakes less than threshsold" let fromX = ceiling $ 1 / minimum portions let toX = sharesDistrMaxSumDistr mpcThreshold -- If we didn't find an appropriate distribution we use distribution [ 1 , 1 , ... 1 ] as fallback . Also , if there are less than 4 shares in total , we multiply the number of shares by 4 because ' ' ca n't break the secret into less than 4 shares . pure $ HM.fromList $ zip keys $ (\xs -> if sum xs < 4 then map (*4) xs else xs) $ fromMaybe (repeat 1) (compute fromX toX 0) where keys :: [StakeholderId] keys = map fst $ HM.toList richmen coins :: [CoinUnsafe] coins = map (fromIntegral . unsafeGetCoin . snd) (HM.toList richmen) portions :: [Double] portions = map ((/ fromIntegral totalCoins) . fromIntegral) coins totalCoins :: CoinUnsafe totalCoins = sum coins We multiply all portions by mult and divide them on their gcd -- we get commitment distribution -- compute sum difference between real portions and current portions -- select optimum using next strategy: -- * if sum error < epsilon - we try minimize sum of commitments -- * otherwise we try minimize sum error compute :: Word16 -> Word16 -> Word16 -> Maybe [Word16] compute !x !toX !prevSum | x > toX = Nothing | otherwise = do let curDistrN = multPortions x let curDistr = normalize curDistrN let !s = sum curDistr if s == prevSum then compute (x + 1) toX prevSum else if isDistrInaccuracyAcceptable (zip coins curDistr) then Just curDistr else compute (x + 1) toX s multPortions :: Word16 -> [Word16] multPortions mult = map (truncate . (fromIntegral mult *)) portions normalize :: [Word16] -> [Word16] normalize x = let g = listGCD x in map (`div` g) x listGCD (x:xs) = foldl' gcd x xs listGCD [] = 1 -- CHECK: @matchCommitmentPure -- | Check that the secret revealed in the opening matches the secret proof -- in the commitment. matchCommitmentPure :: CommitmentsMap -> (StakeholderId, Opening) -> Bool matchCommitmentPure (getCommitmentsMap -> globalCommitments) (id, op) = case HM.lookup id globalCommitments of Nothing -> False Just (_, comm, _) -> verifyOpening comm op -- CHECK: @checkShare -- | Check that the decrypted share matches the encrypted share in the -- commitment -- -- #verifyDecShare checkSharePure :: (SetContainer set, ContainerKey set ~ StakeholderId) => CommitmentsMap -> set --set of opening's identifiers -> VssCertificatesMap -> (StakeholderId, StakeholderId, NonEmpty (AsBinary DecShare)) -> Bool checkSharePure globalCommitments globalOpeningsPK globalCertificates (idTo, idFrom, multiShare) = fromMaybe False checks where -- idFrom sent its encrypted share to idTo on commitment phase idTo must decrypt share from on shares phase , checks = do CHECK : Check that really sent its commitment (_, Commitment{..}, _) <- HM.lookup idFrom $ getCommitmentsMap globalCommitments Get idTo 's vss certificate vssKey <- vcVssKey <$> lookupVss idTo globalCertificates idToCommShares <- HM.lookup vssKey commShares -- CHECK: Check that commitment's shares and multishare have same length guard $ length multiShare == length idToCommShares CHECK : Check that really did n't send its opening guard $ notMember idFrom globalOpeningsPK Get encrypted share , which was sent from idFrom to idTo in -- commitment phase pure $ all (checkShare vssKey) $ NE.zip idToCommShares multiShare checkShare vssKey (encShare, decShare) = fromMaybe False . rightToMaybe $ verifyDecShare <$> fromBinary vssKey <*> fromBinary encShare <*> fromBinary decShare CHECK : @checkSharesPure -- Apply checkShare to all shares in map. -- -- #checkSharePure checkSharesPure :: (SetContainer set, ContainerKey set ~ StakeholderId) => CommitmentsMap set of opening 's PK . TODO Should we add phantom type for more typesafety ? -> VssCertificatesMap -> StakeholderId -> InnerSharesMap -> Bool checkSharesPure globalCommitments globalOpeningsPK globalCertificates addrTo shares = let listShares :: [(StakeholderId, StakeholderId, NonEmpty (AsBinary DecShare))] listShares = map convert $ HM.toList shares convert (addrFrom, share) = (addrTo, addrFrom, share) in all (checkSharePure globalCommitments globalOpeningsPK globalCertificates) listShares -- | Check that commitment is generated for proper set of participants. checkCommitmentShareDistr :: SharesDistribution -> VssCertificatesMap -> SignedCommitment -> Bool checkCommitmentShareDistr distr participants (_, Commitment{..}, _) = let vssPublicKeys = map vcVssKey $ toList participants idVss = map (second vcVssKey) $ HM.toList (getVssCertificatesMap participants) in (HS.fromList vssPublicKeys == getKeys commShares) && (all checkPK idVss) where checkPK (id, pk) = case HM.lookup pk commShares of Nothing -> False Just ne -> length ne == fromIntegral (HM.lookupDefault 0 id distr) -- | Check that commitment shares are cryptographically valid checkCommitmentShares :: MonadRandom m => SignedCommitment -> m Bool checkCommitmentShares (_, comm, _) = fromMaybe (pure False) $ do shares <- getCommShares comm let flatShares = [(k, s) | (k, ss) <- shares, s <- toList ss] let threshold = vssThreshold (length flatShares) pure $ verifyEncShares (commProof comm) threshold flatShares ---------------------------------------------------------------------------- -- Impure versions ---------------------------------------------------------------------------- | Like ' computeSharesDistrPure ' , but uses MPC threshold from the database . computeSharesDistr :: (MonadToss m, MonadTossEnv m, MonadError SscVerifyError m) => RichmenStakes -> m SharesDistribution computeSharesDistr richmen = computeSharesDistrPure richmen =<< (bvdMpcThd <$> getAdoptedBVData) ---------------------------------------------------------------------------- -- Payload processing ---------------------------------------------------------------------------- -- For commitments we check that * committing node is participant , she is rich and -- her VSS certificate is one of stable certificates -- * the nodes haven't already sent their commitments before -- in some different block -- * commitment is generated exactly for all participants with correct -- proportions (according to 'computeSharesDistr') -- * shares in the commitment are valid checkCommitmentsPayload :: (MonadToss m, MonadTossEnv m, MonadError SscVerifyError m, MonadRandom m) => Genesis.Config -> EpochIndex -> CommitmentsMap -> m () checkCommitmentsPayload genesisConfig epoch (getCommitmentsMap -> comms) = -- We don't verify an empty commitments map, because an empty commitments -- map is always valid. Moreover, the commitments check requires us to compute ' SharesDistribution ' , which might be expensive . unless (null comms) $ do richmen <- note (NoRichmen epoch) =<< getRichmen epoch participants <- getParticipants genesisConfig epoch distr <- computeSharesDistr richmen exceptGuard CommittingNoParticipants (`memberVss` participants) (HM.keys comms) exceptGuardM CommitmentAlreadySent (notM hasCommitmentToss) (HM.keys comms) exceptGuardSnd CommSharesOnWrongParticipants (checkCommitmentShareDistr distr participants) (HM.toList comms) exceptGuardSndM CommInvalidShares checkCommitmentShares (HM.toList comms) -- For openings, we check that -- * the opening isn't present in previous blocks -- * corresponding commitment is present -- * the opening matches the commitment (this check implies that previous one passes ) checkOpeningsPayload :: (MonadToss m, MonadError SscVerifyError m) => OpeningsMap -> m () checkOpeningsPayload opens = do exceptGuardM OpeningAlreadySent (notM hasOpeningToss) (HM.keys opens) exceptGuardM OpeningWithoutCommitment hasCommitmentToss (HM.keys opens) exceptGuardEntryM OpeningNotMatchCommitment matchCommitment (HM.toList opens) -- For shares, we check that -- * 'InnerSharesMap's are sent only by participants -- * these 'InnerSharesMap's weren't sent before -- * shares have corresponding commitments which don't have openings -- * if encrypted shares (in commitments) are decrypted, they match -- decrypted shares checkSharesPayload :: (MonadToss m, MonadTossEnv m, MonadError SscVerifyError m) => Genesis.Config -> EpochIndex -> SharesMap -> m () checkSharesPayload genesisConfig epoch shares = do -- We intentionally don't check that nodes which decrypted shares sent -- its commitments. If a node decrypted shares correctly, such node is -- useful for us, despite that it didn't send its commitment. part <- getParticipants genesisConfig epoch exceptGuard SharesNotRichmen (`memberVss` part) (HM.keys shares) exceptGuardM InternalShareWithoutCommitment hasCommitmentToss (concatMap HM.keys $ toList shares) exceptGuardM SharesAlreadySent (notM hasSharesToss) (HM.keys shares) exceptGuardEntryM DecrSharesNotMatchCommitment (checkShares genesisConfig epoch) (HM.toList shares) -- For certificates we check that -- * certificate hasn't been sent already -- * certificate is generated by richman -- * there is no existing certificate with the same VSS key in MonadToss 's state -- Note that we don't need to check whether there are certificates with -- duplicate VSS keys in payload itself, because this is detected at -- deserialization stage. checkCertificatesPayload :: (MonadToss m, MonadTossEnv m, MonadError SscVerifyError m) => EpochIndex -> VssCertificatesMap -> m () checkCertificatesPayload epoch certs = do richmenSet <- getKeys <$> (note (NoRichmen epoch) =<< getRichmen epoch) exceptGuardM CertificateAlreadySent (notM hasCertificateToss) (HM.keys (getVssCertificatesMap certs)) exceptGuardSnd CertificateNotRichmen ((`HS.member` richmenSet) . addressHash . vcSigningKey) (HM.toList (getVssCertificatesMap certs)) existingVssKeys <- HS.fromList . map vcVssKey . toList <$> getVssCertificates exceptGuardSnd CertificateDuplicateVssKey (not . (`HS.member` existingVssKeys) . vcVssKey) (HM.toList (getVssCertificatesMap certs)) checkPayload :: (MonadToss m, MonadTossEnv m, MonadError SscVerifyError m, MonadRandom m) => Genesis.Config -> EpochIndex -> SscPayload -> m () checkPayload genesisConfig epoch payload = do let payloadCerts = spVss payload case payload of CommitmentsPayload comms _ -> checkCommitmentsPayload genesisConfig epoch comms OpeningsPayload opens _ -> checkOpeningsPayload opens SharesPayload shares _ -> checkSharesPayload genesisConfig epoch shares CertificatesPayload _ -> pass checkCertificatesPayload epoch payloadCerts ---------------------------------------------------------------------------- -- Verification helpers ---------------------------------------------------------------------------- -- It takes list of entries ([(StakeholderId, v)] or [StakeholderId]), function condition and error tag ( fKey and fValue - see below ) -- If condition is true for every entry - function does nothing. -- Otherwise it gets all entries which don't pass condition -- and throwError with [StakeholderId] corresponding to these entries. fKey is needed for getting from entry . -- fValue is needed for getting value which must be tested by condition function. verifyEntriesGuardM :: MonadError SscVerifyError m => (entry -> key) -> (entry -> verificationVal) -> (NonEmpty key -> SscVerifyError) -> (verificationVal -> m Bool) -> [entry] -> m () verifyEntriesGuardM fKey fVal exception cond lst = maybeThrowError exception =<< (nonEmpty . map fKey) <$> filterM f lst where f x = not <$> cond (fVal x) maybeThrowError _ Nothing = pass maybeThrowError er (Just ne) = throwError $ er ne exceptGuard :: MonadError SscVerifyError m => (NonEmpty key -> SscVerifyError) -> (key -> Bool) -> [key] -> m () exceptGuard onFail f = verifyEntriesGuardM identity identity onFail (pure . f) exceptGuardM :: MonadError SscVerifyError m => (NonEmpty key -> SscVerifyError) -> (key -> m Bool) -> [key] -> m () exceptGuardM = verifyEntriesGuardM identity identity exceptGuardSnd :: MonadError SscVerifyError m => (NonEmpty key -> SscVerifyError) -> (val -> Bool) -> [(key, val)] -> m () exceptGuardSnd onFail f = verifyEntriesGuardM fst snd onFail (pure . f) exceptGuardSndM :: MonadError SscVerifyError m => (NonEmpty key -> SscVerifyError) -> (val -> m Bool) -> [(key, val)] -> m () exceptGuardSndM = verifyEntriesGuardM fst snd exceptGuardEntryM :: MonadError SscVerifyError m => (NonEmpty key -> SscVerifyError) -> ((key, val) -> m Bool) -> [(key, val)] -> m () exceptGuardEntryM = verifyEntriesGuardM fst identity notM :: Monad m => (a -> m Bool) -> (a -> m Bool) notM f = (pure . not) <=< f
null
https://raw.githubusercontent.com/input-output-hk/cardano-sl/1499214d93767b703b9599369a431e67d83f10a2/chain/src/Pos/Chain/Ssc/Toss/Base.hs
haskell
# LANGUAGE TypeFamilies # | Basic functionality from Toss. * Trivial functions * Basic logic * Payload processing * Helpers -------------------------------------------------------------------------- Trivial getters (proper interface of MonadTossRead) -------------------------------------------------------------------------- | Check whether there is a 'SignedCommitment' from given stakeholder. | Check whether there is an 'Opening' from given stakeholder. | Check whether there is 'InnerSharesMap' from given stakeholder. -------------------------------------------------------------------------- Non-trivial getters -------------------------------------------------------------------------- -------------------------------------------------------------------------- Simple checks in 'MonadTossRead' -------------------------------------------------------------------------- | Check that the secret revealed in the opening matches the secret proof in the commitment. -------------------------------------------------------------------------- Pure functions -------------------------------------------------------------------------- richmen and stable certificates. Using 'UnsafeVssCertificatesMap' is safe here because if the original 'certs' map is okay, a subset of the original 'certs' map is okay too. in the worst case ATTENTION: IMPERATIVE CODE! PROTECT YOUR EYES! -- which means difference between generated and real distribution we can get in the worst case. We can get these situations when sum of stakes of nodes A sum of generated portions can be computed as sum of corresponding shares distribution divided by @totalDistr@. A sum of real portions can be computed as sum of corresponding coins divided by @totalCoins@. for each sum of shares distribution which is less than @totalDistr@ / 2 we would know the maximum sum of real distribution corresponding to nodes which form this sum of shares distribution So for every sum of generated shares we store this sum of coins and try to maximize it. Relaxation function. Iterate over distribution Try to relax coins for whole weights If we didn't find an appropriate distribution we use distribution we get commitment distribution compute sum difference between real portions and current portions select optimum using next strategy: * if sum error < epsilon - we try minimize sum of commitments * otherwise we try minimize sum error CHECK: @matchCommitmentPure | Check that the secret revealed in the opening matches the secret proof in the commitment. CHECK: @checkShare | Check that the decrypted share matches the encrypted share in the commitment #verifyDecShare set of opening's identifiers idFrom sent its encrypted share to idTo on commitment phase CHECK: Check that commitment's shares and multishare have same length commitment phase Apply checkShare to all shares in map. #checkSharePure | Check that commitment is generated for proper set of participants. | Check that commitment shares are cryptographically valid -------------------------------------------------------------------------- Impure versions -------------------------------------------------------------------------- -------------------------------------------------------------------------- Payload processing -------------------------------------------------------------------------- For commitments we check that her VSS certificate is one of stable certificates * the nodes haven't already sent their commitments before in some different block * commitment is generated exactly for all participants with correct proportions (according to 'computeSharesDistr') * shares in the commitment are valid We don't verify an empty commitments map, because an empty commitments map is always valid. Moreover, the commitments check requires us to For openings, we check that * the opening isn't present in previous blocks * corresponding commitment is present * the opening matches the commitment (this check implies that previous For shares, we check that * 'InnerSharesMap's are sent only by participants * these 'InnerSharesMap's weren't sent before * shares have corresponding commitments which don't have openings * if encrypted shares (in commitments) are decrypted, they match decrypted shares We intentionally don't check that nodes which decrypted shares sent its commitments. If a node decrypted shares correctly, such node is useful for us, despite that it didn't send its commitment. For certificates we check that * certificate hasn't been sent already * certificate is generated by richman * there is no existing certificate with the same VSS key in Note that we don't need to check whether there are certificates with duplicate VSS keys in payload itself, because this is detected at deserialization stage. -------------------------------------------------------------------------- Verification helpers -------------------------------------------------------------------------- It takes list of entries ([(StakeholderId, v)] or [StakeholderId]), If condition is true for every entry - function does nothing. Otherwise it gets all entries which don't pass condition and throwError with [StakeholderId] corresponding to these entries. fValue is needed for getting value which must be tested by condition function.
# LANGUAGE RecordWildCards # module Pos.Chain.Ssc.Toss.Base ( getCommitment , hasCommitmentToss , hasOpeningToss , hasSharesToss , hasCertificateToss , getParticipants , computeParticipants , computeSharesDistrPure , computeSharesDistr , isDistrInaccuracyAcceptable , sharesDistrInaccuracy , sharesDistrMaxSumDistr , checkCommitmentsPayload , checkOpeningsPayload , checkSharesPayload , checkCertificatesPayload , checkPayload , verifyEntriesGuardM ) where import Universum hiding (id, keys) import Control.Monad.Except (MonadError (throwError)) import Control.Monad.ST (ST, runST) import Crypto.Random (MonadRandom) import Data.Array.MArray (newArray, readArray, writeArray) import Data.Array.ST (STUArray) import Data.Containers (ContainerKey, SetContainer (notMember)) import qualified Data.HashMap.Strict as HM import qualified Data.HashSet as HS import qualified Data.List.NonEmpty as NE import Data.STRef (newSTRef, readSTRef, writeSTRef) import Formatting (sformat, (%)) import Pos.Binary.Class (AsBinary, fromBinary) import Pos.Chain.Genesis as Genesis (Config) import Pos.Chain.Lrc.Types (RichmenSet, RichmenStakes) import Pos.Chain.Ssc.Base (verifyOpening, vssThreshold) import Pos.Chain.Ssc.Commitment (Commitment (..), SignedCommitment, commShares, getCommShares) import Pos.Chain.Ssc.CommitmentsMap (CommitmentsMap (getCommitmentsMap)) import Pos.Chain.Ssc.Error (SscVerifyError (..)) import Pos.Chain.Ssc.Opening (Opening (..)) import Pos.Chain.Ssc.OpeningsMap (OpeningsMap) import Pos.Chain.Ssc.Payload (SscPayload (..), spVss) import Pos.Chain.Ssc.SharesDistribution (SharesDistribution) import Pos.Chain.Ssc.SharesMap (InnerSharesMap, SharesMap) import Pos.Chain.Ssc.Toss.Class (MonadToss (..), MonadTossEnv (..), MonadTossRead (..)) import Pos.Chain.Ssc.VssCertificate (vcSigningKey, vcVssKey) import Pos.Chain.Ssc.VssCertificatesMap (VssCertificatesMap (..), lookupVss, memberVss) import Pos.Chain.Update.BlockVersionData (bvdMpcThd) import Pos.Core (CoinPortion, EpochIndex (..), StakeholderId, addressHash, coinPortionDenominator, getCoinPortion, unsafeGetCoin) import Pos.Crypto (DecShare, verifyDecShare, verifyEncShares) import Pos.Util.Util (getKeys, intords) import Pos.Util.Wlog (logWarning) | Retrieve ' SignedCommitment ' of given stakeholder if it 's known . getCommitment :: MonadTossRead m => StakeholderId -> m (Maybe SignedCommitment) getCommitment id = HM.lookup id . getCommitmentsMap <$> getCommitments hasCommitmentToss :: MonadTossRead m => StakeholderId -> m Bool hasCommitmentToss id = HM.member id . getCommitmentsMap <$> getCommitments hasOpeningToss :: MonadTossRead m => StakeholderId -> m Bool hasOpeningToss id = HM.member id <$> getOpenings hasSharesToss :: MonadTossRead m => StakeholderId -> m Bool hasSharesToss id = HM.member id <$> getShares | Check whether there is ' VssCertificate ' from given stakeholder . hasCertificateToss :: MonadTossRead m => StakeholderId -> m Bool hasCertificateToss id = memberVss id <$> getVssCertificates | Get ' VssCertificatesMap ' containing ' StakeholderId 's and ' VssPublicKey 's of participating nodes for given epoch . getParticipants :: (MonadError SscVerifyError m, MonadToss m, MonadTossEnv m) => Genesis.Config -> EpochIndex -> m VssCertificatesMap getParticipants genesisConfig epoch = do stableCerts <- getStableCertificates genesisConfig epoch richmen <- note (NoRichmen epoch) =<< getRichmen epoch pure $ computeParticipants (getKeys richmen) stableCerts matchCommitment :: MonadTossRead m => (StakeholderId, Opening) -> m Bool matchCommitment op = flip matchCommitmentPure op <$> getCommitments checkShares :: (MonadTossRead m, MonadTossEnv m) => Genesis.Config -> EpochIndex -> (StakeholderId, InnerSharesMap) -> m Bool checkShares genesisConfig epoch (id, sh) = do certs <- getStableCertificates genesisConfig epoch let warnFmt = ("checkShares: no richmen for "%intords%" epoch") getRichmen epoch >>= \case Nothing -> False <$ logWarning (sformat warnFmt (getEpochIndex epoch)) Just richmen -> do let parts = computeParticipants (getKeys richmen) certs coms <- getCommitments ops <- getOpenings pure $ checkSharesPure coms ops parts id sh | Compute ' VssCertificate 's of SSC participants using set of computeParticipants :: RichmenSet -> VssCertificatesMap -> VssCertificatesMap computeParticipants (HS.toMap -> richmen) (UnsafeVssCertificatesMap certs) = UnsafeVssCertificatesMap (HM.intersection certs richmen) | We accept inaccuracy in computation not greater than 0.05 , so stakeholders must have at least 55 % of stake to reveal secret sharesDistrInaccuracy :: Fractional a => a sharesDistrInaccuracy = 0.05 | sum of distribution sharesDistrMaxSumDistr :: RealFrac a => a -> Word16 sharesDistrMaxSumDistr thd = truncate $ 3 / thd | Internal type for work with Coin . type CoinUnsafe = Int64 | Types represents one dimensional array used for knapsack algorithm in the @computeDistrInaccuracy@ type Knapsack s = STUArray s Word16 CoinUnsafe | Compute inaccuracy between real distribution and generared . It take O(totalDistr * ) time . inaccuracy is more or less heuristic value This inaccuracy can lead to two bad situation : 1 . when nodes must n't reveal commitment , but they can 2 . when nodes must reveal commitment , but they ca n't which sent shares is close to 0.5 . isDistrInaccuracyAcceptable :: [(CoinUnsafe, Word16)] -> Bool isDistrInaccuracyAcceptable coinsNDistr = runST $ do let !totalDistr = sum $ map snd coinsNDistr let !totalCoins = sum $ map fst coinsNDistr let halfDistr = totalDistr `div` 2 + 1 let invalid = totalCoins + 1 For the bad case of type 2 , to evaluate inaccuracy of the bad case type 2 . We do n't compute bad case of type 1 explicitly , because if there is such subset which causes inaccuracy of type 1 we can take complement of this subset and get the same inaccuracy of type 2 . dpMax <- newArray (0, totalDistr) (-invalid) :: ST s (Knapsack s) writeArray dpMax 0 0 let relax dp coins w nw cmp = do dpW <- readArray dp w dpNw <- readArray dp nw when ((dpW + coins) `cmp` dpNw) $ writeArray dp nw (dpW + coins) pure (dpW + coins) let weights = [halfDistr - 1, halfDistr - 2..0] let halfCoins = totalCoins `div` 2 + 1 let totalDistrD, totalCoinsD :: Double totalDistrD = fromIntegral totalDistr totalCoinsD = fromIntegral totalCoins let computeLimit i = let p = fromIntegral i / totalDistrD in max halfCoins (ceiling (totalCoinsD * (sharesDistrInaccuracy + p))) let weightsNLimits = zip weights (map computeLimit weights) isAcceptable <- newSTRef True forM_ coinsNDistr $ \(coins, distr) -> whenM (readSTRef isAcceptable) $ do forM_ weightsNLimits $ \(w, limit) -> when (w >= distr) $ do sCoinsMx <- relax dpMax coins (w - distr) w (>) when (sCoinsMx >= limit) $ writeSTRef isAcceptable False readSTRef isAcceptable computeSharesDistrPure :: MonadError SscVerifyError m => RichmenStakes ^ MPC threshold , e.g. ' genesisMpcThd ' -> m SharesDistribution computeSharesDistrPure richmen threshold | null richmen = pure mempty | otherwise = do when (totalCoins == 0) $ throwError $ TossInternalError "Richmen total stake equals zero" let mpcThreshold = toRational (getCoinPortion threshold) / toRational coinPortionDenominator unless (all ((>= mpcThreshold) . toRational) portions) $ throwError $ TossInternalError "Richmen stakes less than threshsold" let fromX = ceiling $ 1 / minimum portions let toX = sharesDistrMaxSumDistr mpcThreshold [ 1 , 1 , ... 1 ] as fallback . Also , if there are less than 4 shares in total , we multiply the number of shares by 4 because ' ' ca n't break the secret into less than 4 shares . pure $ HM.fromList $ zip keys $ (\xs -> if sum xs < 4 then map (*4) xs else xs) $ fromMaybe (repeat 1) (compute fromX toX 0) where keys :: [StakeholderId] keys = map fst $ HM.toList richmen coins :: [CoinUnsafe] coins = map (fromIntegral . unsafeGetCoin . snd) (HM.toList richmen) portions :: [Double] portions = map ((/ fromIntegral totalCoins) . fromIntegral) coins totalCoins :: CoinUnsafe totalCoins = sum coins We multiply all portions by mult and divide them on their gcd compute :: Word16 -> Word16 -> Word16 -> Maybe [Word16] compute !x !toX !prevSum | x > toX = Nothing | otherwise = do let curDistrN = multPortions x let curDistr = normalize curDistrN let !s = sum curDistr if s == prevSum then compute (x + 1) toX prevSum else if isDistrInaccuracyAcceptable (zip coins curDistr) then Just curDistr else compute (x + 1) toX s multPortions :: Word16 -> [Word16] multPortions mult = map (truncate . (fromIntegral mult *)) portions normalize :: [Word16] -> [Word16] normalize x = let g = listGCD x in map (`div` g) x listGCD (x:xs) = foldl' gcd x xs listGCD [] = 1 matchCommitmentPure :: CommitmentsMap -> (StakeholderId, Opening) -> Bool matchCommitmentPure (getCommitmentsMap -> globalCommitments) (id, op) = case HM.lookup id globalCommitments of Nothing -> False Just (_, comm, _) -> verifyOpening comm op checkSharePure :: (SetContainer set, ContainerKey set ~ StakeholderId) => CommitmentsMap -> VssCertificatesMap -> (StakeholderId, StakeholderId, NonEmpty (AsBinary DecShare)) -> Bool checkSharePure globalCommitments globalOpeningsPK globalCertificates (idTo, idFrom, multiShare) = fromMaybe False checks where idTo must decrypt share from on shares phase , checks = do CHECK : Check that really sent its commitment (_, Commitment{..}, _) <- HM.lookup idFrom $ getCommitmentsMap globalCommitments Get idTo 's vss certificate vssKey <- vcVssKey <$> lookupVss idTo globalCertificates idToCommShares <- HM.lookup vssKey commShares guard $ length multiShare == length idToCommShares CHECK : Check that really did n't send its opening guard $ notMember idFrom globalOpeningsPK Get encrypted share , which was sent from idFrom to idTo in pure $ all (checkShare vssKey) $ NE.zip idToCommShares multiShare checkShare vssKey (encShare, decShare) = fromMaybe False . rightToMaybe $ verifyDecShare <$> fromBinary vssKey <*> fromBinary encShare <*> fromBinary decShare CHECK : @checkSharesPure checkSharesPure :: (SetContainer set, ContainerKey set ~ StakeholderId) => CommitmentsMap set of opening 's PK . TODO Should we add phantom type for more typesafety ? -> VssCertificatesMap -> StakeholderId -> InnerSharesMap -> Bool checkSharesPure globalCommitments globalOpeningsPK globalCertificates addrTo shares = let listShares :: [(StakeholderId, StakeholderId, NonEmpty (AsBinary DecShare))] listShares = map convert $ HM.toList shares convert (addrFrom, share) = (addrTo, addrFrom, share) in all (checkSharePure globalCommitments globalOpeningsPK globalCertificates) listShares checkCommitmentShareDistr :: SharesDistribution -> VssCertificatesMap -> SignedCommitment -> Bool checkCommitmentShareDistr distr participants (_, Commitment{..}, _) = let vssPublicKeys = map vcVssKey $ toList participants idVss = map (second vcVssKey) $ HM.toList (getVssCertificatesMap participants) in (HS.fromList vssPublicKeys == getKeys commShares) && (all checkPK idVss) where checkPK (id, pk) = case HM.lookup pk commShares of Nothing -> False Just ne -> length ne == fromIntegral (HM.lookupDefault 0 id distr) checkCommitmentShares :: MonadRandom m => SignedCommitment -> m Bool checkCommitmentShares (_, comm, _) = fromMaybe (pure False) $ do shares <- getCommShares comm let flatShares = [(k, s) | (k, ss) <- shares, s <- toList ss] let threshold = vssThreshold (length flatShares) pure $ verifyEncShares (commProof comm) threshold flatShares | Like ' computeSharesDistrPure ' , but uses MPC threshold from the database . computeSharesDistr :: (MonadToss m, MonadTossEnv m, MonadError SscVerifyError m) => RichmenStakes -> m SharesDistribution computeSharesDistr richmen = computeSharesDistrPure richmen =<< (bvdMpcThd <$> getAdoptedBVData) * committing node is participant , she is rich and checkCommitmentsPayload :: (MonadToss m, MonadTossEnv m, MonadError SscVerifyError m, MonadRandom m) => Genesis.Config -> EpochIndex -> CommitmentsMap -> m () checkCommitmentsPayload genesisConfig epoch (getCommitmentsMap -> comms) = compute ' SharesDistribution ' , which might be expensive . unless (null comms) $ do richmen <- note (NoRichmen epoch) =<< getRichmen epoch participants <- getParticipants genesisConfig epoch distr <- computeSharesDistr richmen exceptGuard CommittingNoParticipants (`memberVss` participants) (HM.keys comms) exceptGuardM CommitmentAlreadySent (notM hasCommitmentToss) (HM.keys comms) exceptGuardSnd CommSharesOnWrongParticipants (checkCommitmentShareDistr distr participants) (HM.toList comms) exceptGuardSndM CommInvalidShares checkCommitmentShares (HM.toList comms) one passes ) checkOpeningsPayload :: (MonadToss m, MonadError SscVerifyError m) => OpeningsMap -> m () checkOpeningsPayload opens = do exceptGuardM OpeningAlreadySent (notM hasOpeningToss) (HM.keys opens) exceptGuardM OpeningWithoutCommitment hasCommitmentToss (HM.keys opens) exceptGuardEntryM OpeningNotMatchCommitment matchCommitment (HM.toList opens) checkSharesPayload :: (MonadToss m, MonadTossEnv m, MonadError SscVerifyError m) => Genesis.Config -> EpochIndex -> SharesMap -> m () checkSharesPayload genesisConfig epoch shares = do part <- getParticipants genesisConfig epoch exceptGuard SharesNotRichmen (`memberVss` part) (HM.keys shares) exceptGuardM InternalShareWithoutCommitment hasCommitmentToss (concatMap HM.keys $ toList shares) exceptGuardM SharesAlreadySent (notM hasSharesToss) (HM.keys shares) exceptGuardEntryM DecrSharesNotMatchCommitment (checkShares genesisConfig epoch) (HM.toList shares) MonadToss 's state checkCertificatesPayload :: (MonadToss m, MonadTossEnv m, MonadError SscVerifyError m) => EpochIndex -> VssCertificatesMap -> m () checkCertificatesPayload epoch certs = do richmenSet <- getKeys <$> (note (NoRichmen epoch) =<< getRichmen epoch) exceptGuardM CertificateAlreadySent (notM hasCertificateToss) (HM.keys (getVssCertificatesMap certs)) exceptGuardSnd CertificateNotRichmen ((`HS.member` richmenSet) . addressHash . vcSigningKey) (HM.toList (getVssCertificatesMap certs)) existingVssKeys <- HS.fromList . map vcVssKey . toList <$> getVssCertificates exceptGuardSnd CertificateDuplicateVssKey (not . (`HS.member` existingVssKeys) . vcVssKey) (HM.toList (getVssCertificatesMap certs)) checkPayload :: (MonadToss m, MonadTossEnv m, MonadError SscVerifyError m, MonadRandom m) => Genesis.Config -> EpochIndex -> SscPayload -> m () checkPayload genesisConfig epoch payload = do let payloadCerts = spVss payload case payload of CommitmentsPayload comms _ -> checkCommitmentsPayload genesisConfig epoch comms OpeningsPayload opens _ -> checkOpeningsPayload opens SharesPayload shares _ -> checkSharesPayload genesisConfig epoch shares CertificatesPayload _ -> pass checkCertificatesPayload epoch payloadCerts function condition and error tag ( fKey and fValue - see below ) fKey is needed for getting from entry . verifyEntriesGuardM :: MonadError SscVerifyError m => (entry -> key) -> (entry -> verificationVal) -> (NonEmpty key -> SscVerifyError) -> (verificationVal -> m Bool) -> [entry] -> m () verifyEntriesGuardM fKey fVal exception cond lst = maybeThrowError exception =<< (nonEmpty . map fKey) <$> filterM f lst where f x = not <$> cond (fVal x) maybeThrowError _ Nothing = pass maybeThrowError er (Just ne) = throwError $ er ne exceptGuard :: MonadError SscVerifyError m => (NonEmpty key -> SscVerifyError) -> (key -> Bool) -> [key] -> m () exceptGuard onFail f = verifyEntriesGuardM identity identity onFail (pure . f) exceptGuardM :: MonadError SscVerifyError m => (NonEmpty key -> SscVerifyError) -> (key -> m Bool) -> [key] -> m () exceptGuardM = verifyEntriesGuardM identity identity exceptGuardSnd :: MonadError SscVerifyError m => (NonEmpty key -> SscVerifyError) -> (val -> Bool) -> [(key, val)] -> m () exceptGuardSnd onFail f = verifyEntriesGuardM fst snd onFail (pure . f) exceptGuardSndM :: MonadError SscVerifyError m => (NonEmpty key -> SscVerifyError) -> (val -> m Bool) -> [(key, val)] -> m () exceptGuardSndM = verifyEntriesGuardM fst snd exceptGuardEntryM :: MonadError SscVerifyError m => (NonEmpty key -> SscVerifyError) -> ((key, val) -> m Bool) -> [(key, val)] -> m () exceptGuardEntryM = verifyEntriesGuardM fst identity notM :: Monad m => (a -> m Bool) -> (a -> m Bool) notM f = (pure . not) <=< f
2dec07c5c4145871276db7cde25e984a068aea72510cd02dd2d60d8a5348d4ce
kadena-io/pact
Regression.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # module Pact.PersistPactDb.Regression (DbEnv(..), initDbEnv, runRegression, regressPure) where import Control.Concurrent.MVar import Control.Exception import Control.Monad import Control.Lens hiding ((.=)) import Control.DeepSeq import Data.Text(pack) import Data.Foldable(for_) import qualified Data.Map.Strict as M import qualified Data.HashMap.Strict as HM import Pact.PersistPactDb import Pact.Persist import Pact.Types.Runtime import Pact.Persist.Pure (initPureDb,persister,PureDb) import Data.Aeson import Pact.Types.Logger import Pact.Types.PactValue import Pact.Repl import Pact.Repl.Types import Pact.Native (nativeDefs) import Pact.Types.RowData loadModule :: IO (ModuleName, ModuleData Ref, PersistModuleData) loadModule = do let fn = "tests/pact/simple.repl" (r,s) <- execScript' (Script False fn) fn let mn = ModuleName "simple" Nothing case r of Left a -> throwFail $ "module load failed: " ++ show a Right _ -> case preview (rEvalState . evalRefs . rsLoadedModules . ix mn) s of Just (md,_) -> case traverse (traverse toPersistDirect) md of Right md' -> return (mn,md,md') Left e -> throwFail $ "toPersistDirect failed: " ++ show e Nothing -> throwFail $ "Failed to find module 'simple': " ++ show (view (rEvalState . evalRefs . rsLoadedModules) s) nativeLookup :: NativeDefName -> Maybe (Term Name) nativeLookup (NativeDefName n) = case HM.lookup n nativeDefs of Just (Direct t) -> Just t _ -> Nothing runRegression :: DbEnv p -> IO (MVar (DbEnv p)) runRegression p = do v <- newMVar p createSchema v (Just t1) <- begin v let user1 = "user1" usert = UserTables user1 toPV :: ToTerm a => a -> PactValue toPV = toPactValueLenient . toTerm' createUserTable' v user1 "free.some-Module" assertEquals' "output of commit 2" [TxLog "SYS_usertables" "user1" $ object [ ("utModule" .= object [ ("name" .= String "some-Module"), ("namespace" .= String "free")]) ] ] (commit v) void $ begin v assertEquals' "user table info correct" "free.some-Module" $ _getUserTableInfo pactdb user1 v let row = RowData RDV0 $ ObjectMap $ M.fromList [("gah",pactValueToRowData $ PLiteral (LDecimal 123.454345))] _writeRow pactdb Insert usert "key1" row v assertEquals' "user insert" (Just row) (_readRow pactdb usert "key1" v) let row' = RowData RDV1 $ ObjectMap $ fmap pactValueToRowData $ M.fromList [("gah",toPV False),("fh",toPV (1 :: Int))] _writeRow pactdb Update usert "key1" row' v assertEquals' "user update" (Just row') (_readRow pactdb usert "key1" v) let ks = mkKeySet [PublicKeyText "skdjhfskj"] "predfun" _writeRow pactdb Write KeySets "ks1" ks v assertEquals' "keyset write" (Just ks) $ _readRow pactdb KeySets "ks1" v (modName,modRef,mod') <- loadModule _writeRow pactdb Write Modules modName mod' v assertEquals' "module write" (Just mod') $ _readRow pactdb Modules modName v assertEquals "module native repopulation" (Right modRef) $ traverse (traverse (fromPersistDirect nativeLookup)) mod' assertEquals' "result of commit 3" [ TxLog { _txDomain = "SYS_keysets" , _txKey = "ks1" , _txValue = toJSON ks } , TxLog { _txDomain = "SYS_modules" , _txKey = asString modName , _txValue = toJSON mod' } , TxLog { _txDomain = "USER_user1" , _txKey = "key1" , _txValue = toJSON row } , TxLog { _txDomain = "USER_user1" , _txKey = "key1" , _txValue = toJSON row' } ] (commit v) void $ begin v tids <- _txids pactdb user1 t1 v assertEquals "user txids" [1] tids assertEquals' "user txlogs" [TxLog "USER_user1" "key1" row, TxLog "USER_user1" "key1" row'] $ _getTxLog pactdb usert (head tids) v _writeRow pactdb Insert usert "key2" row v assertEquals' "user insert key2 pre-rollback" (Just row) (_readRow pactdb usert "key2" v) assertEquals' "keys pre-rollback" ["key1","key2"] $ _keys pactdb (UserTables user1) v _rollbackTx pactdb v assertEquals' "rollback erases key2" Nothing $ _readRow pactdb usert "key2" v assertEquals' "keys" ["key1"] $ _keys pactdb (UserTables user1) v -- Reversed just to ensure inserts are not in order. for_ (reverse [2::Int .. 9]) $ \k -> _writeRow pactdb Insert usert (RowKey $ "key" <> (pack $ show k)) row' v assertEquals' "keys" [RowKey ("key" <> (pack $ show k)) | k <- [1 :: Int .. 9]] $ _keys pactdb (UserTables user1) v return v toTerm' :: ToTerm a => a -> Term Name toTerm' = toTerm begin :: MVar (DbEnv p) -> IO (Maybe TxId) begin v = _beginTx pactdb Transactional v commit :: MVar (DbEnv p) -> IO [TxLog Value] commit v = _commitTx pactdb v throwFail :: String -> IO a throwFail = throwIO . userError assertEquals :: (Eq a,Show a,NFData a) => String -> a -> a -> IO () assertEquals msg a b | [a,b] `deepseq` a == b = return () | otherwise = throwFail $ "FAILURE: " ++ msg ++ ": expected \n " ++ show a ++ "\n got \n " ++ show b assertEquals' :: (Eq a, Show a, NFData a) => String -> a -> IO a -> IO () assertEquals' msg a b = assertEquals msg a =<< b regressPure :: Loggers -> IO (MVar (DbEnv PureDb)) regressPure l = do let e = initDbEnv l persister initPureDb runRegression e _regress :: IO () _regress = void $ regressPure alwaysLog
null
https://raw.githubusercontent.com/kadena-io/pact/0f22b41543a9397391477fb26d1d62798aa23803/src-ghc/Pact/PersistPactDb/Regression.hs
haskell
# LANGUAGE OverloadedStrings # Reversed just to ensure inserts are not in order.
# LANGUAGE ScopedTypeVariables # module Pact.PersistPactDb.Regression (DbEnv(..), initDbEnv, runRegression, regressPure) where import Control.Concurrent.MVar import Control.Exception import Control.Monad import Control.Lens hiding ((.=)) import Control.DeepSeq import Data.Text(pack) import Data.Foldable(for_) import qualified Data.Map.Strict as M import qualified Data.HashMap.Strict as HM import Pact.PersistPactDb import Pact.Persist import Pact.Types.Runtime import Pact.Persist.Pure (initPureDb,persister,PureDb) import Data.Aeson import Pact.Types.Logger import Pact.Types.PactValue import Pact.Repl import Pact.Repl.Types import Pact.Native (nativeDefs) import Pact.Types.RowData loadModule :: IO (ModuleName, ModuleData Ref, PersistModuleData) loadModule = do let fn = "tests/pact/simple.repl" (r,s) <- execScript' (Script False fn) fn let mn = ModuleName "simple" Nothing case r of Left a -> throwFail $ "module load failed: " ++ show a Right _ -> case preview (rEvalState . evalRefs . rsLoadedModules . ix mn) s of Just (md,_) -> case traverse (traverse toPersistDirect) md of Right md' -> return (mn,md,md') Left e -> throwFail $ "toPersistDirect failed: " ++ show e Nothing -> throwFail $ "Failed to find module 'simple': " ++ show (view (rEvalState . evalRefs . rsLoadedModules) s) nativeLookup :: NativeDefName -> Maybe (Term Name) nativeLookup (NativeDefName n) = case HM.lookup n nativeDefs of Just (Direct t) -> Just t _ -> Nothing runRegression :: DbEnv p -> IO (MVar (DbEnv p)) runRegression p = do v <- newMVar p createSchema v (Just t1) <- begin v let user1 = "user1" usert = UserTables user1 toPV :: ToTerm a => a -> PactValue toPV = toPactValueLenient . toTerm' createUserTable' v user1 "free.some-Module" assertEquals' "output of commit 2" [TxLog "SYS_usertables" "user1" $ object [ ("utModule" .= object [ ("name" .= String "some-Module"), ("namespace" .= String "free")]) ] ] (commit v) void $ begin v assertEquals' "user table info correct" "free.some-Module" $ _getUserTableInfo pactdb user1 v let row = RowData RDV0 $ ObjectMap $ M.fromList [("gah",pactValueToRowData $ PLiteral (LDecimal 123.454345))] _writeRow pactdb Insert usert "key1" row v assertEquals' "user insert" (Just row) (_readRow pactdb usert "key1" v) let row' = RowData RDV1 $ ObjectMap $ fmap pactValueToRowData $ M.fromList [("gah",toPV False),("fh",toPV (1 :: Int))] _writeRow pactdb Update usert "key1" row' v assertEquals' "user update" (Just row') (_readRow pactdb usert "key1" v) let ks = mkKeySet [PublicKeyText "skdjhfskj"] "predfun" _writeRow pactdb Write KeySets "ks1" ks v assertEquals' "keyset write" (Just ks) $ _readRow pactdb KeySets "ks1" v (modName,modRef,mod') <- loadModule _writeRow pactdb Write Modules modName mod' v assertEquals' "module write" (Just mod') $ _readRow pactdb Modules modName v assertEquals "module native repopulation" (Right modRef) $ traverse (traverse (fromPersistDirect nativeLookup)) mod' assertEquals' "result of commit 3" [ TxLog { _txDomain = "SYS_keysets" , _txKey = "ks1" , _txValue = toJSON ks } , TxLog { _txDomain = "SYS_modules" , _txKey = asString modName , _txValue = toJSON mod' } , TxLog { _txDomain = "USER_user1" , _txKey = "key1" , _txValue = toJSON row } , TxLog { _txDomain = "USER_user1" , _txKey = "key1" , _txValue = toJSON row' } ] (commit v) void $ begin v tids <- _txids pactdb user1 t1 v assertEquals "user txids" [1] tids assertEquals' "user txlogs" [TxLog "USER_user1" "key1" row, TxLog "USER_user1" "key1" row'] $ _getTxLog pactdb usert (head tids) v _writeRow pactdb Insert usert "key2" row v assertEquals' "user insert key2 pre-rollback" (Just row) (_readRow pactdb usert "key2" v) assertEquals' "keys pre-rollback" ["key1","key2"] $ _keys pactdb (UserTables user1) v _rollbackTx pactdb v assertEquals' "rollback erases key2" Nothing $ _readRow pactdb usert "key2" v assertEquals' "keys" ["key1"] $ _keys pactdb (UserTables user1) v for_ (reverse [2::Int .. 9]) $ \k -> _writeRow pactdb Insert usert (RowKey $ "key" <> (pack $ show k)) row' v assertEquals' "keys" [RowKey ("key" <> (pack $ show k)) | k <- [1 :: Int .. 9]] $ _keys pactdb (UserTables user1) v return v toTerm' :: ToTerm a => a -> Term Name toTerm' = toTerm begin :: MVar (DbEnv p) -> IO (Maybe TxId) begin v = _beginTx pactdb Transactional v commit :: MVar (DbEnv p) -> IO [TxLog Value] commit v = _commitTx pactdb v throwFail :: String -> IO a throwFail = throwIO . userError assertEquals :: (Eq a,Show a,NFData a) => String -> a -> a -> IO () assertEquals msg a b | [a,b] `deepseq` a == b = return () | otherwise = throwFail $ "FAILURE: " ++ msg ++ ": expected \n " ++ show a ++ "\n got \n " ++ show b assertEquals' :: (Eq a, Show a, NFData a) => String -> a -> IO a -> IO () assertEquals' msg a b = assertEquals msg a =<< b regressPure :: Loggers -> IO (MVar (DbEnv PureDb)) regressPure l = do let e = initDbEnv l persister initPureDb runRegression e _regress :: IO () _regress = void $ regressPure alwaysLog
3ecab26608e4e6f713213d56017d1855d4dfbe4bba745c15132fa0789d1ebcaf
8c6794b6/haskell-sc-scratch
PushNegI.hs
------------------------------------------------------------------------------ -- | -- Module : $Header$ CopyRight : ( c ) 8c6794b6 -- License : BSD3 Maintainer : -- Stability : unstable -- Portability : non-portable -- -- Lecture: <-final/course/PushNegI.hs> -- -- What we want to do is, change the grammer from: -- -- > e ::= lit | neg e | add e e -- -- to: -- -- > e ::= factor | add e e -- > factor ::= lit | neg lit -- -- Only integer literals can be negated, and only once. -- module PushNegI where import Intro1 push_neg :: Exp -> Exp push_neg e = case e of Lit _ -> e Neg (Lit _) -> e Neg (Neg e') -> e' Neg (Add e1 e2) -> Add (push_neg (Neg e1)) (push_neg (Neg e2)) Add e1 e2 -> Add (push_neg e1) (push_neg e2) ti1_norm_view = view $ push_neg ti1
null
https://raw.githubusercontent.com/8c6794b6/haskell-sc-scratch/22de2199359fa56f256b544609cd6513b5e40f43/Scratch/Oleg/TTF/PushNegI.hs
haskell
---------------------------------------------------------------------------- | Module : $Header$ License : BSD3 Stability : unstable Portability : non-portable Lecture: <-final/course/PushNegI.hs> What we want to do is, change the grammer from: > e ::= lit | neg e | add e e to: > e ::= factor | add e e > factor ::= lit | neg lit Only integer literals can be negated, and only once.
CopyRight : ( c ) 8c6794b6 Maintainer : module PushNegI where import Intro1 push_neg :: Exp -> Exp push_neg e = case e of Lit _ -> e Neg (Lit _) -> e Neg (Neg e') -> e' Neg (Add e1 e2) -> Add (push_neg (Neg e1)) (push_neg (Neg e2)) Add e1 e2 -> Add (push_neg e1) (push_neg e2) ti1_norm_view = view $ push_neg ti1
acf1222cb5c69e9ad2114a4fe4ee6628fc2ebaf7f44a125a0e8074872292eea8
pablomarx/Thomas
comp-class.scm
* Copyright 1992 Digital Equipment Corporation ;* All Rights Reserved ;* ;* Permission to use, copy, and modify this software and its documentation is ;* hereby granted only under the following terms and conditions. Both the ;* above copyright notice and this permission notice must appear in all copies ;* of the software, derivative works or modified versions, and any portions ;* thereof, and both notices must appear in supporting documentation. ;* ;* Users of this software agree to the terms and conditions set forth herein, * and hereby grant back to Digital a non - exclusive , unrestricted , royalty - free ;* right and license under any changes, enhancements or extensions made to the ;* core functions of the software, including but not limited to those affording ;* compatibility with other hardware or software environments, but excluding ;* applications which incorporate this software. Users further agree to use * their best efforts to return to Digital any such changes , enhancements or * extensions that they make and inform Digital of noteworthy uses of this * software . Correspondence should be provided to Digital at : ;* * Director , Cambridge Research Lab * Digital Equipment Corp * One Kendall Square , Bldg 700 ;* Cambridge MA 02139 ;* ;* This software may be distributed (but not offered for sale or transferred * for compensation ) to third parties , provided such third parties agree to ;* abide by the terms and conditions of this notice. ;* * THE SOFTWARE IS PROVIDED " AS IS " AND DIGITAL EQUIPMENT CORP . DISCLAIMS ALL ;* WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF ;* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT ;* CORPORATION 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 ;* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS ;* SOFTWARE. $ I d : comp - class.scm , v 1.9 1992/09/05 16:04:19 jmiller Exp $ ;;;; More of the compiler: class and binding related operations ;;;; BIND , DEFINE - GENERIC - FUNCTION , DEFINE - CLASS , DEFINE - SLOT Parsing and compiling BIND special forms Access functions for BINDings (define (binding->names binding) (let loop ((names '()) (rest binding)) (if (not (list? binding)) (dylan::error "bind -- bad binding" binding)) (if (or (null? rest) (null? (cdr rest)) (eq? '!rest (car rest))) (reverse names) (let ((this-binding (car rest))) (cond ((variable-name? this-binding) (loop (cons this-binding names) (cdr rest))) ((and (list-of-length? this-binding 2) (variable-name? (car this-binding))) (loop (cons (car this-binding) names) (cdr rest))) (else (dylan::error "bind -- bad binding list" binding))))))) (define (binding->restrictions binding) (let loop ((restrictions '()) (rest binding)) (if (or (null? rest) (null? (cdr rest)) (eq? '!rest (car rest))) (reverse restrictions) (let ((this-binding (car rest))) (loop (cons (if (variable-name? this-binding) #F (cadr this-binding)) restrictions) (cdr rest)))))) (define (binding->rest binding) (let ((found (memq '!rest binding))) (if found (begin (must-be-list-of-length found 3 "bind -- error in bindings") (cadr found)) #F))) (define (binding->init binding) (last binding)) (define (build-BIND-form bound-names rest-name compiled-restrictions compiled-init compiled-body) (let ((all ;; Build a list with entries (offset name restriction) ;; where 'offset' is offset in values vector, (let process ((offset 0) (names bound-names) (restrictions compiled-restrictions)) (if (null? names) '() `((,offset ,(car names) ,(car restrictions)) ,@(process (+ offset 1) (cdr names) (cdr restrictions)))))) (->offset car) (->name cadr) (->restriction caddr)) (define restricted (let loop ((rest all)) (if (null? rest) '() `(,@(if (->restriction (car rest)) (list (car rest)) `()) ,@(loop (cdr rest)))))) `(LET ((!BIND-BODY (LAMBDA (,@bound-names ,@(if rest-name (list rest-name) `())) ,compiled-body)) (!BIND-INIT-FORM (LAMBDA (!MULTI-VALUE) ,compiled-init)) ,@(map (lambda (restriction) `(,(->name restriction) ,(->restriction restriction))) restricted)) (LET* ((!MULTI-VALUE (DYLAN::VECTOR ,@(map (lambda (name) name #F) bound-names) `())) (!FIRST-VALUE (!BIND-INIT-FORM !MULTI-VALUE))) (IF (DYLAN::EQ? !FIRST-VALUE !MULTI-VALUE) ;; We went through values ... ,(let ((call `(!BIND-BODY ,@(map (lambda (offset) `(DYLAN::VECTOR-REF !MULTI-VALUE ,offset)) (map ->offset all)) ,@(if rest-name `((DYLAN::VECTOR-REF !MULTI-VALUE ,(length bound-names))) `())))) (if (null? restricted) call `(BEGIN ,@(map (lambda (offset name) `(DYLAN::TYPE-CHECK (DYLAN::VECTOR-REF !MULTI-VALUE ,offset) ,name)) (map ->offset restricted) (map ->name restricted)) ,call))) ;; Didn't go through values ... ,(if (null? bound-names) `(!BIND-BODY (DYLAN::LIST !FIRST-VALUE)) (let* ((first (car all)) (restriction (->restriction first))) (define call `(!BIND-BODY !FIRST-VALUE ,@(map (lambda (name) name #F) (cdr bound-names)) ,@(if rest-name `('()) `()))) (if restriction `(BEGIN (DYLAN::TYPE-CHECK !FIRST-VALUE ,(->name first)) ,call) call)))))))) Compiling the BIND form (define (compile-BIND-form e module-vars bound-vars really-compile multiple-values? continue) (must-be-list-of-at-least-length e 1 "BIND form invalid") (let ((bindings (car e)) (forms (cdr e))) (if (null? bindings) (if (null? forms) (continue compiled-sharp-f bound-vars) (really-compile `(BEGIN ,@forms) module-vars bound-vars multiple-values? continue)) (begin (if (not (list? bindings)) (dylan::error "bind -- bad bindings" bindings)) (let* ((binding (car bindings)) (bound-names (binding->names binding)) (rest-name (binding->rest binding)) (init-form (binding->init binding))) (if (and (null? bound-names) (not rest-name)) (dylan::error "bind -- no variables bound" e)) (validate-names (if rest-name (cons rest-name bound-names) bound-names)) (compile-forms (binding->restrictions binding) module-vars bound-vars really-compile #F (lambda (compiled-restrictions mod-vars) (really-compile init-form mod-vars bound-vars (if (or rest-name (and (not (null? bound-names)) (not (null? (cdr bound-names))))) '!MULTI-VALUE #F) (lambda (compiled-init new-mods) (let ((bound-names (map variable->name bound-names)) (rest-name (and rest-name (variable->name rest-name)))) (really-compile `(BIND ,(cdr bindings) ,@forms) new-mods (append (if rest-name (list rest-name) '()) bound-names bound-vars) multiple-values? (lambda (compiled-body new-mods) (continue (build-BIND-form bound-names rest-name compiled-restrictions compiled-init compiled-body) new-mods))))))))))))) ;;; Parsing and compiling the DEFINE-GENERIC-FUNCTION special form (define (gen-fn-param-error params where) (dylan::error "define-generic-function -- parameter syntax error" params where)) (define (parse-gen-fn-params orig-params allowed-fn continue) (let loop ((names '()) (params orig-params)) (cond ((null? params) (continue (reverse names) params)) ((not (pair? params)) (gen-fn-param-error orig-params (list 'PARSING params))) ((allowed-fn (car params)) => (lambda (value) (loop (cons value names) (cdr params)))) (else (continue (reverse names) params))))) (define (parse-DEFINE-GENERIC-FUNCTION name params keywords compiler) keywords ; Not used (if (not (variable-name? name)) (dylan::error "define-generic-function -- illegal name" name)) (parse-gen-fn-params params (lambda (x) (and (variable-name? x) x)) (lambda (reqs rest) (define (symbol-or-keyword x) (cond ((memq x '(!KEY !REST)) x) ((dylan-special-name? x) (gen-fn-param-error params (list 'RESERVED-NAME rest))) ((keyword? x) x) ((symbol? x) (name->keyword x)) (else #F))) (define (compile-keys rest) (lambda (keys after-keys) (if (not (null? after-keys)) (gen-fn-param-error params (list 'COMPILE-KEYS after-keys))) (compiler name reqs rest keys))) (cond ((null? rest) (compiler name reqs #F #F)) ((not (pair? rest)) (gen-fn-param-error params (list 'STRANGE-REST rest))) (else (case (car rest) ((!REST) (let ((after-rest (cdr rest))) (if (or (not (pair? after-rest)) (not (variable-name? (car after-rest)))) (gen-fn-param-error params (list 'POST-!REST after-rest))) (let ((rest (car after-rest))) (cond ((null? (cdr after-rest)) (compiler name reqs rest #F)) ((not (pair? (cdr after-rest))) (gen-fn-param-error params (list 'AFTER-!REST (cdr after-rest)))) ((eq? `!KEY (cadr after-rest)) (parse-gen-fn-params (cddr after-rest) symbol-or-keyword (compile-keys rest))) (else (gen-fn-param-error params (list 'BEFORE-!KEY (cddr after-rest)))))))) ((!KEY) (if (null? (cdr rest)) (compiler name reqs #F #T) (parse-gen-fn-params (cdr rest) symbol-or-keyword (compile-keys #F)))) (else (gen-fn-param-error params (list 'UNKNOWN-STOPPER rest))))))))) (define (compile-DEFINE-GENERIC-FUNCTION-form e mod-vars bound-vars compiler multiple-values? continue) compiler ; No sub-compilations multiple-values? ; No reductions (must-be-list-of-length e 2 "DEFINE-GENERIC-FUNCTION: invalid syntax") (parse-DEFINE-GENERIC-FUNCTION (car e) (cadr e) (cddr e) (lambda (name reqs rest keys) (module-refs name bound-vars mod-vars continue (lambda (ref set) `(IF (DYLAN::NOT (OR (DYLAN::EQ? ,ref ',the-unassigned-value) (DYLAN::GENERIC-FUNCTION? ,ref))) (DYLAN-CALL DYLAN:ERROR "define-generic-function -- already has a value" ',name ,ref ',reqs ',rest ',keys) (BEGIN ,(set `(DYLAN::CREATE-GENERIC-FUNCTION ',name ,(length reqs) ',keys ,(if rest #T #F))) ',name))))))) ;;; Parsing and compiling the DEFINE-CLASS form (define (expand-slot slot) (define (build-slot pairs default-getter) (validate-keywords pairs '(getter: setter: type: init-value: init-function: init-keyword: required-init-keyword: allocation:) dylan::error) (let ((getter (dylan::find-keyword pairs 'getter: (lambda () (or default-getter (dylan::error "slot expander -- no getter name" pairs))))) (setter (dylan::find-keyword pairs 'setter: (lambda () (if default-getter `(SETTER ,default-getter) #F)))) (type (dylan::find-keyword pairs 'type: (lambda () '<object>))) (has-initial-value? #T)) (let ((init-value (dylan::find-keyword pairs 'init-value: (lambda () (set! has-initial-value? #F) #F))) (init-function (dylan::find-keyword pairs 'init-function: (lambda () #F))) (init-keyword (dylan::find-keyword pairs 'init-keyword: (lambda () #F))) (required-init-keyword (dylan::find-keyword pairs 'required-init-keyword: (lambda () #F))) (allocation (dylan::find-keyword pairs 'allocation: (lambda () 'instance)))) (if (and (variable-name? getter) (or (not setter) (variable-name? setter)) (or (not has-initial-value?) (not init-function)) (or (not required-init-keyword) (and (not init-keyword) (not has-initial-value?) (not init-function))) (memq allocation '(instance class each-subclass constant virtual))) (make-slot getter ; debug-name getter setter type init-value has-initial-value? init-function init-keyword required-init-keyword allocation #F #F) (dylan::error "slot expander -- bad slot" getter setter has-initial-value? init-value init-function init-keyword required-init-keyword allocation))))) (cond ((symbol? slot) (make-slot slot slot `(SETTER ,slot) '<object> #F #F #F #F #F 'instance #F #F)) ((and (pair? slot) (keyword? (car slot))) (build-slot slot #F)) ((and (pair? slot) (symbol? (car slot)) (variable-name? (car slot))) (build-slot (cdr slot) (car slot))) (else (dylan::error "slot expander -- bad slot specification" slot)))) (define (expand-slots slots) (map expand-slot slots)) (define (make-add-slot-call slot owner bound-vars mod-vars compiler continue) (define (get-mod-var name mod-vars setter? continue) (if name (module-refs name bound-vars mod-vars continue (lambda (ref set) `(BEGIN (COND ((DYLAN::EQ? ,ref ',the-unassigned-value) ,(set `(DYLAN::CREATE-GENERIC-FUNCTION ',(variable->name name) ,(if setter? 2 1) ; # of arguments #F ; No required keywords #F))) ; No rest argument ((DYLAN::NOT (DYLAN::GENERIC-FUNCTION? ,ref)) (DYLAN-CALL DYLAN:ERROR "Slot function -- already has a value" ',(slot.debug-name slot) ,owner))) ,ref))) (continue #F mod-vars))) (get-mod-var (slot.getter slot) mod-vars #F (lambda (getter mv) (get-mod-var (slot.setter slot) mv #T (lambda (setter mv) (compile-forms (list (slot.type slot) (slot.init-value slot) (slot.init-function slot)) mv bound-vars compiler #F (lambda (compiled-forms mv) (continue `(DYLAN::ADD-SLOT ,owner ,(car compiled-forms) ; Type ',(slot.allocation slot) ,setter ,getter ',(slot.debug-name slot) Init - Value ,(slot.has-initial-value? slot) Init - Function ',(slot.init-keyword slot) ',(slot.required-init-keyword slot)) mv)))))))) (define (generate-DEFINE-CLASS name superclasses getter-code slots bound-vars mod-vars compiler continue) (let loop ((slots slots) (mod-vars mod-vars) (add-slot-calls '())) (if (null? slots) (module-refs name bound-vars mod-vars continue (lambda (ref set) set ; Ignored `(BEGIN (IF (DYLAN::NOT (OR (DYLAN::EQ? ,ref ',the-unassigned-value) (DYLAN::CLASS? ,ref))) (DYLAN-CALL DYLAN:ERROR "define-class -- already has a value" ',name ,ref ',(map slot.getter slots)) (LET ((!CLASS (DYLAN::MAKE-A-CLASS ',name (DYLAN::LIST ,@superclasses) (DYLAN::LIST ,@getter-code)))) ,@add-slot-calls ,(set '!CLASS) ',name))))) (make-add-slot-call (car slots) '!CLASS bound-vars mod-vars compiler (lambda (code mod-vars) (loop (cdr slots) mod-vars (cons code add-slot-calls))))))) (define (compile-DEFINE-CLASS-form e mod-vars bound-vars compiler multiple-values? continue) multiple-values? ; No reductions (must-be-list-of-at-least-length e 2 "DEFINE-CLASS: invalid syntax") (let ((superclasses (cadr e)) (slots (expand-slots (cddr e)))) (compile-forms superclasses mod-vars bound-vars compiler #F (lambda (supers mod-vars) (let loop ((getter-code '()) (slots-left slots) (mod-vars mod-vars)) (if (null? slots-left) (generate-DEFINE-CLASS (car e) supers getter-code slots bound-vars mod-vars compiler continue) (module-refs (slot.getter (car slots)) bound-vars mod-vars (lambda (code mod-vars) (loop (cons code getter-code) (cdr slots-left) mod-vars)) (lambda (ref set) set ; Ignored ref)))))))) DEFINE - SLOT (define (compile-DEFINE-SLOT-form e mod-vars bound-vars compiler multiple-values? continue) multiple-values? ; Ignored (must-be-list-of-at-least-length e 2 "DEFINE-SLOT: invalid syntax") (let ((owner (car e)) (slot (cdr e))) (make-add-slot-call (expand-slot (if (keyword? (car slot)) slot `(GETTER: ,@slot))) owner bound-vars mod-vars compiler continue)))
null
https://raw.githubusercontent.com/pablomarx/Thomas/c8ab3f6fa92a9a39667fe37dfe060b651affb18e/kits/scc/src/comp-class.scm
scheme
* All Rights Reserved * * Permission to use, copy, and modify this software and its documentation is * hereby granted only under the following terms and conditions. Both the * above copyright notice and this permission notice must appear in all copies * of the software, derivative works or modified versions, and any portions * thereof, and both notices must appear in supporting documentation. * * Users of this software agree to the terms and conditions set forth herein, * right and license under any changes, enhancements or extensions made to the * core functions of the software, including but not limited to those affording * compatibility with other hardware or software environments, but excluding * applications which incorporate this software. Users further agree to use * * Cambridge MA 02139 * * This software may be distributed (but not offered for sale or transferred * abide by the terms and conditions of this notice. * * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. More of the compiler: class and binding related operations Build a list with entries (offset name restriction) where 'offset' is offset in values vector, We went through values ... Didn't go through values ... Parsing and compiling the DEFINE-GENERIC-FUNCTION special form Not used No sub-compilations No reductions Parsing and compiling the DEFINE-CLASS form debug-name # of arguments No required keywords No rest argument Type Ignored No reductions Ignored Ignored
* Copyright 1992 Digital Equipment Corporation * and hereby grant back to Digital a non - exclusive , unrestricted , royalty - free * their best efforts to return to Digital any such changes , enhancements or * extensions that they make and inform Digital of noteworthy uses of this * software . Correspondence should be provided to Digital at : * Director , Cambridge Research Lab * Digital Equipment Corp * One Kendall Square , Bldg 700 * for compensation ) to third parties , provided such third parties agree to * THE SOFTWARE IS PROVIDED " AS IS " AND DIGITAL EQUIPMENT CORP . DISCLAIMS ALL * PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER $ I d : comp - class.scm , v 1.9 1992/09/05 16:04:19 jmiller Exp $ BIND , DEFINE - GENERIC - FUNCTION , DEFINE - CLASS , DEFINE - SLOT Parsing and compiling BIND special forms Access functions for BINDings (define (binding->names binding) (let loop ((names '()) (rest binding)) (if (not (list? binding)) (dylan::error "bind -- bad binding" binding)) (if (or (null? rest) (null? (cdr rest)) (eq? '!rest (car rest))) (reverse names) (let ((this-binding (car rest))) (cond ((variable-name? this-binding) (loop (cons this-binding names) (cdr rest))) ((and (list-of-length? this-binding 2) (variable-name? (car this-binding))) (loop (cons (car this-binding) names) (cdr rest))) (else (dylan::error "bind -- bad binding list" binding))))))) (define (binding->restrictions binding) (let loop ((restrictions '()) (rest binding)) (if (or (null? rest) (null? (cdr rest)) (eq? '!rest (car rest))) (reverse restrictions) (let ((this-binding (car rest))) (loop (cons (if (variable-name? this-binding) #F (cadr this-binding)) restrictions) (cdr rest)))))) (define (binding->rest binding) (let ((found (memq '!rest binding))) (if found (begin (must-be-list-of-length found 3 "bind -- error in bindings") (cadr found)) #F))) (define (binding->init binding) (last binding)) (define (build-BIND-form bound-names rest-name compiled-restrictions compiled-init compiled-body) (let ((all (let process ((offset 0) (names bound-names) (restrictions compiled-restrictions)) (if (null? names) '() `((,offset ,(car names) ,(car restrictions)) ,@(process (+ offset 1) (cdr names) (cdr restrictions)))))) (->offset car) (->name cadr) (->restriction caddr)) (define restricted (let loop ((rest all)) (if (null? rest) '() `(,@(if (->restriction (car rest)) (list (car rest)) `()) ,@(loop (cdr rest)))))) `(LET ((!BIND-BODY (LAMBDA (,@bound-names ,@(if rest-name (list rest-name) `())) ,compiled-body)) (!BIND-INIT-FORM (LAMBDA (!MULTI-VALUE) ,compiled-init)) ,@(map (lambda (restriction) `(,(->name restriction) ,(->restriction restriction))) restricted)) (LET* ((!MULTI-VALUE (DYLAN::VECTOR ,@(map (lambda (name) name #F) bound-names) `())) (!FIRST-VALUE (!BIND-INIT-FORM !MULTI-VALUE))) (IF (DYLAN::EQ? !FIRST-VALUE !MULTI-VALUE) ,(let ((call `(!BIND-BODY ,@(map (lambda (offset) `(DYLAN::VECTOR-REF !MULTI-VALUE ,offset)) (map ->offset all)) ,@(if rest-name `((DYLAN::VECTOR-REF !MULTI-VALUE ,(length bound-names))) `())))) (if (null? restricted) call `(BEGIN ,@(map (lambda (offset name) `(DYLAN::TYPE-CHECK (DYLAN::VECTOR-REF !MULTI-VALUE ,offset) ,name)) (map ->offset restricted) (map ->name restricted)) ,call))) ,(if (null? bound-names) `(!BIND-BODY (DYLAN::LIST !FIRST-VALUE)) (let* ((first (car all)) (restriction (->restriction first))) (define call `(!BIND-BODY !FIRST-VALUE ,@(map (lambda (name) name #F) (cdr bound-names)) ,@(if rest-name `('()) `()))) (if restriction `(BEGIN (DYLAN::TYPE-CHECK !FIRST-VALUE ,(->name first)) ,call) call)))))))) Compiling the BIND form (define (compile-BIND-form e module-vars bound-vars really-compile multiple-values? continue) (must-be-list-of-at-least-length e 1 "BIND form invalid") (let ((bindings (car e)) (forms (cdr e))) (if (null? bindings) (if (null? forms) (continue compiled-sharp-f bound-vars) (really-compile `(BEGIN ,@forms) module-vars bound-vars multiple-values? continue)) (begin (if (not (list? bindings)) (dylan::error "bind -- bad bindings" bindings)) (let* ((binding (car bindings)) (bound-names (binding->names binding)) (rest-name (binding->rest binding)) (init-form (binding->init binding))) (if (and (null? bound-names) (not rest-name)) (dylan::error "bind -- no variables bound" e)) (validate-names (if rest-name (cons rest-name bound-names) bound-names)) (compile-forms (binding->restrictions binding) module-vars bound-vars really-compile #F (lambda (compiled-restrictions mod-vars) (really-compile init-form mod-vars bound-vars (if (or rest-name (and (not (null? bound-names)) (not (null? (cdr bound-names))))) '!MULTI-VALUE #F) (lambda (compiled-init new-mods) (let ((bound-names (map variable->name bound-names)) (rest-name (and rest-name (variable->name rest-name)))) (really-compile `(BIND ,(cdr bindings) ,@forms) new-mods (append (if rest-name (list rest-name) '()) bound-names bound-vars) multiple-values? (lambda (compiled-body new-mods) (continue (build-BIND-form bound-names rest-name compiled-restrictions compiled-init compiled-body) new-mods))))))))))))) (define (gen-fn-param-error params where) (dylan::error "define-generic-function -- parameter syntax error" params where)) (define (parse-gen-fn-params orig-params allowed-fn continue) (let loop ((names '()) (params orig-params)) (cond ((null? params) (continue (reverse names) params)) ((not (pair? params)) (gen-fn-param-error orig-params (list 'PARSING params))) ((allowed-fn (car params)) => (lambda (value) (loop (cons value names) (cdr params)))) (else (continue (reverse names) params))))) (define (parse-DEFINE-GENERIC-FUNCTION name params keywords compiler) (if (not (variable-name? name)) (dylan::error "define-generic-function -- illegal name" name)) (parse-gen-fn-params params (lambda (x) (and (variable-name? x) x)) (lambda (reqs rest) (define (symbol-or-keyword x) (cond ((memq x '(!KEY !REST)) x) ((dylan-special-name? x) (gen-fn-param-error params (list 'RESERVED-NAME rest))) ((keyword? x) x) ((symbol? x) (name->keyword x)) (else #F))) (define (compile-keys rest) (lambda (keys after-keys) (if (not (null? after-keys)) (gen-fn-param-error params (list 'COMPILE-KEYS after-keys))) (compiler name reqs rest keys))) (cond ((null? rest) (compiler name reqs #F #F)) ((not (pair? rest)) (gen-fn-param-error params (list 'STRANGE-REST rest))) (else (case (car rest) ((!REST) (let ((after-rest (cdr rest))) (if (or (not (pair? after-rest)) (not (variable-name? (car after-rest)))) (gen-fn-param-error params (list 'POST-!REST after-rest))) (let ((rest (car after-rest))) (cond ((null? (cdr after-rest)) (compiler name reqs rest #F)) ((not (pair? (cdr after-rest))) (gen-fn-param-error params (list 'AFTER-!REST (cdr after-rest)))) ((eq? `!KEY (cadr after-rest)) (parse-gen-fn-params (cddr after-rest) symbol-or-keyword (compile-keys rest))) (else (gen-fn-param-error params (list 'BEFORE-!KEY (cddr after-rest)))))))) ((!KEY) (if (null? (cdr rest)) (compiler name reqs #F #T) (parse-gen-fn-params (cdr rest) symbol-or-keyword (compile-keys #F)))) (else (gen-fn-param-error params (list 'UNKNOWN-STOPPER rest))))))))) (define (compile-DEFINE-GENERIC-FUNCTION-form e mod-vars bound-vars compiler multiple-values? continue) (must-be-list-of-length e 2 "DEFINE-GENERIC-FUNCTION: invalid syntax") (parse-DEFINE-GENERIC-FUNCTION (car e) (cadr e) (cddr e) (lambda (name reqs rest keys) (module-refs name bound-vars mod-vars continue (lambda (ref set) `(IF (DYLAN::NOT (OR (DYLAN::EQ? ,ref ',the-unassigned-value) (DYLAN::GENERIC-FUNCTION? ,ref))) (DYLAN-CALL DYLAN:ERROR "define-generic-function -- already has a value" ',name ,ref ',reqs ',rest ',keys) (BEGIN ,(set `(DYLAN::CREATE-GENERIC-FUNCTION ',name ,(length reqs) ',keys ,(if rest #T #F))) ',name))))))) (define (expand-slot slot) (define (build-slot pairs default-getter) (validate-keywords pairs '(getter: setter: type: init-value: init-function: init-keyword: required-init-keyword: allocation:) dylan::error) (let ((getter (dylan::find-keyword pairs 'getter: (lambda () (or default-getter (dylan::error "slot expander -- no getter name" pairs))))) (setter (dylan::find-keyword pairs 'setter: (lambda () (if default-getter `(SETTER ,default-getter) #F)))) (type (dylan::find-keyword pairs 'type: (lambda () '<object>))) (has-initial-value? #T)) (let ((init-value (dylan::find-keyword pairs 'init-value: (lambda () (set! has-initial-value? #F) #F))) (init-function (dylan::find-keyword pairs 'init-function: (lambda () #F))) (init-keyword (dylan::find-keyword pairs 'init-keyword: (lambda () #F))) (required-init-keyword (dylan::find-keyword pairs 'required-init-keyword: (lambda () #F))) (allocation (dylan::find-keyword pairs 'allocation: (lambda () 'instance)))) (if (and (variable-name? getter) (or (not setter) (variable-name? setter)) (or (not has-initial-value?) (not init-function)) (or (not required-init-keyword) (and (not init-keyword) (not has-initial-value?) (not init-function))) (memq allocation '(instance class each-subclass constant virtual))) getter setter type init-value has-initial-value? init-function init-keyword required-init-keyword allocation #F #F) (dylan::error "slot expander -- bad slot" getter setter has-initial-value? init-value init-function init-keyword required-init-keyword allocation))))) (cond ((symbol? slot) (make-slot slot slot `(SETTER ,slot) '<object> #F #F #F #F #F 'instance #F #F)) ((and (pair? slot) (keyword? (car slot))) (build-slot slot #F)) ((and (pair? slot) (symbol? (car slot)) (variable-name? (car slot))) (build-slot (cdr slot) (car slot))) (else (dylan::error "slot expander -- bad slot specification" slot)))) (define (expand-slots slots) (map expand-slot slots)) (define (make-add-slot-call slot owner bound-vars mod-vars compiler continue) (define (get-mod-var name mod-vars setter? continue) (if name (module-refs name bound-vars mod-vars continue (lambda (ref set) `(BEGIN (COND ((DYLAN::EQ? ,ref ',the-unassigned-value) ,(set `(DYLAN::CREATE-GENERIC-FUNCTION ',(variable->name name) ((DYLAN::NOT (DYLAN::GENERIC-FUNCTION? ,ref)) (DYLAN-CALL DYLAN:ERROR "Slot function -- already has a value" ',(slot.debug-name slot) ,owner))) ,ref))) (continue #F mod-vars))) (get-mod-var (slot.getter slot) mod-vars #F (lambda (getter mv) (get-mod-var (slot.setter slot) mv #T (lambda (setter mv) (compile-forms (list (slot.type slot) (slot.init-value slot) (slot.init-function slot)) mv bound-vars compiler #F (lambda (compiled-forms mv) (continue `(DYLAN::ADD-SLOT ,owner ',(slot.allocation slot) ,setter ,getter ',(slot.debug-name slot) Init - Value ,(slot.has-initial-value? slot) Init - Function ',(slot.init-keyword slot) ',(slot.required-init-keyword slot)) mv)))))))) (define (generate-DEFINE-CLASS name superclasses getter-code slots bound-vars mod-vars compiler continue) (let loop ((slots slots) (mod-vars mod-vars) (add-slot-calls '())) (if (null? slots) (module-refs name bound-vars mod-vars continue (lambda (ref set) `(BEGIN (IF (DYLAN::NOT (OR (DYLAN::EQ? ,ref ',the-unassigned-value) (DYLAN::CLASS? ,ref))) (DYLAN-CALL DYLAN:ERROR "define-class -- already has a value" ',name ,ref ',(map slot.getter slots)) (LET ((!CLASS (DYLAN::MAKE-A-CLASS ',name (DYLAN::LIST ,@superclasses) (DYLAN::LIST ,@getter-code)))) ,@add-slot-calls ,(set '!CLASS) ',name))))) (make-add-slot-call (car slots) '!CLASS bound-vars mod-vars compiler (lambda (code mod-vars) (loop (cdr slots) mod-vars (cons code add-slot-calls))))))) (define (compile-DEFINE-CLASS-form e mod-vars bound-vars compiler multiple-values? continue) (must-be-list-of-at-least-length e 2 "DEFINE-CLASS: invalid syntax") (let ((superclasses (cadr e)) (slots (expand-slots (cddr e)))) (compile-forms superclasses mod-vars bound-vars compiler #F (lambda (supers mod-vars) (let loop ((getter-code '()) (slots-left slots) (mod-vars mod-vars)) (if (null? slots-left) (generate-DEFINE-CLASS (car e) supers getter-code slots bound-vars mod-vars compiler continue) (module-refs (slot.getter (car slots)) bound-vars mod-vars (lambda (code mod-vars) (loop (cons code getter-code) (cdr slots-left) mod-vars)) (lambda (ref set) ref)))))))) DEFINE - SLOT (define (compile-DEFINE-SLOT-form e mod-vars bound-vars compiler multiple-values? continue) (must-be-list-of-at-least-length e 2 "DEFINE-SLOT: invalid syntax") (let ((owner (car e)) (slot (cdr e))) (make-add-slot-call (expand-slot (if (keyword? (car slot)) slot `(GETTER: ,@slot))) owner bound-vars mod-vars compiler continue)))
9333c92808732ee84abef734adc2542babeaf56d1cec95d89605b92e932a5661
jhund/re-frame-and-reagent-and-slatejs
core.clj
(ns rrs.core)
null
https://raw.githubusercontent.com/jhund/re-frame-and-reagent-and-slatejs/75593b626d9a31b8069daf16eef2a23e9aa19ec7/src/clj/rrs/core.clj
clojure
(ns rrs.core)
cce2f29cb6c475f31981f3dcde0b7ae68ddfbd3a0735162b3c3aa37c64a39272
tnelson/Forge
abstractSigs.rkt
#lang forge/core (set-option! 'verbose 0) (sig Abstract #:abstract) (sig Extension1 #:extends Abstract) (sig Extension2 #:extends Abstract) (test abstractEnforced #:preds [(= Abstract (+ Extension1 Extension2))] #:expect theorem) (test extensionsAllowed #:preds [(some Extension1)] #:expect sat) (test emptyExtensionsEmptyAbstract #:preds [(=> (no (+ Extension1 Extension2)) (no Abstract))] #:expect theorem)
null
https://raw.githubusercontent.com/tnelson/Forge/1687cba0ebdb598c29c51845d43c98a459d0588f/forge/tests/forge-core/sigs/abstractSigs.rkt
racket
#lang forge/core (set-option! 'verbose 0) (sig Abstract #:abstract) (sig Extension1 #:extends Abstract) (sig Extension2 #:extends Abstract) (test abstractEnforced #:preds [(= Abstract (+ Extension1 Extension2))] #:expect theorem) (test extensionsAllowed #:preds [(some Extension1)] #:expect sat) (test emptyExtensionsEmptyAbstract #:preds [(=> (no (+ Extension1 Extension2)) (no Abstract))] #:expect theorem)
6472008e502b77826bc3b6885943871e4b60d7d7490e76ce155bd367154b73e0
tel/saltine
Password.hs
# LANGUAGE DeriveDataTypeable , , DeriveGeneric , ForeignFunctionInterface # -- | -- Module : Crypto.Saltine.Internal.Password Copyright : ( c ) 2018 2021 License : MIT -- Maintainer : -- Stability : experimental -- Portability : non-portable module Crypto.Saltine.Internal.Password ( c_pwhash , c_pwhash_str , c_pwhash_str_verify , c_pwhash_str_needs_rehash , pwhash_alg_argon2i13 , pwhash_alg_argon2id13 , pwhash_alg_default , algorithm -- Default algorithm constants , pwhash_bytes_max , pwhash_bytes_min , pwhash_memlimit_interactive , pwhash_memlimit_moderate , pwhash_memlimit_sensitive , pwhash_memlimit_min , pwhash_memlimit_max , pwhash_opslimit_interactive , pwhash_opslimit_moderate , pwhash_opslimit_sensitive , pwhash_opslimit_min , pwhash_opslimit_max , pwhash_passwd_min , pwhash_passwd_max , pwhash_saltbytes , pwhash_strbytes , pwhash_strprefix Argon2i algorithm constants , pwhash_argon2i_bytes_max , pwhash_argon2i_bytes_min , pwhash_argon2i_memlimit_interactive , pwhash_argon2i_memlimit_moderate , pwhash_argon2i_memlimit_sensitive , pwhash_argon2i_memlimit_min , pwhash_argon2i_memlimit_max , pwhash_argon2i_opslimit_interactive , pwhash_argon2i_opslimit_moderate , pwhash_argon2i_opslimit_sensitive , pwhash_argon2i_opslimit_min , pwhash_argon2i_opslimit_max , pwhash_argon2i_passwd_min , pwhash_argon2i_passwd_max , pwhash_argon2i_saltbytes , pwhash_argon2i_strbytes , pwhash_argon2i_strprefix -- Argon2id algorithm constants , pwhash_argon2id_bytes_max , pwhash_argon2id_bytes_min , pwhash_argon2id_memlimit_interactive , pwhash_argon2id_memlimit_moderate , pwhash_argon2id_memlimit_sensitive , pwhash_argon2id_memlimit_min , pwhash_argon2id_memlimit_max , pwhash_argon2id_opslimit_interactive , pwhash_argon2id_opslimit_moderate , pwhash_argon2id_opslimit_sensitive , pwhash_argon2id_opslimit_min , pwhash_argon2id_opslimit_max , pwhash_argon2id_passwd_min , pwhash_argon2id_passwd_max , pwhash_argon2id_saltbytes , pwhash_argon2id_strbytes , pwhash_argon2id_strprefix , Salt(..) , PasswordHash(..) , Opslimit(..) , Memlimit(..) , Policy(..) , Algorithm(..) ) where import Control.DeepSeq import Crypto.Saltine.Class import Crypto.Saltine.Internal.Util as U import Data.ByteString (ByteString) import Data.Data (Data, Typeable) import Data.Hashable (Hashable) import Data.Monoid import Data.Text (Text) import GHC.Generics (Generic) import Foreign.C import Foreign.Ptr import qualified Data.ByteString as S import qualified Data.Text.Encoding as DTE -- | Salt for deriving keys from passwords newtype Salt = Salt { unSalt :: ByteString } deriving (Ord, Data, Hashable, Typeable, Generic, NFData) instance Eq Salt where Salt a == Salt b = U.compare a b instance Show Salt where show k = "Password.Salt " <> bin2hex (encode k) instance IsEncoding Salt where decode v = if S.length v == pwhash_saltbytes then Just (Salt v) else Nothing # INLINE decode # encode (Salt v) = v # INLINE encode # -- | Verification string for stored passwords -- This hash contains only printable characters, hence we can just derive Show. newtype PasswordHash = PasswordHash { unPasswordHash :: Text } deriving (Ord, Data, Hashable, Typeable, Generic, Show, NFData) Constant time instance , just in case . instance Eq PasswordHash where PasswordHash a == PasswordHash b = U.compare (DTE.encodeUtf8 a) (DTE.encodeUtf8 b) -- | Wrapper type for the operations used by password hashing newtype Opslimit = Opslimit { getOpslimit :: Int } deriving (Eq, Ord, Data, Hashable, Typeable, Generic, Show, NFData) -- | Wrapper type for the memory used by password hashing newtype Memlimit = Memlimit { getMemlimit :: Int } deriving (Eq, Ord, Data, Hashable, Typeable, Generic, Show, NFData) -- | Wrapper for opslimit, memlimit and algorithm data Policy = Policy { opsPolicy :: Opslimit , memPolicy :: Memlimit , algPolicy :: Algorithm } deriving (Eq, Ord, Data, Typeable, Generic, Show) instance Hashable Policy | Algorithms known to Libsodium , as an enum datatype data Algorithm = DefaultAlgorithm | Argon2i13 | Argon2id13 deriving (Eq, Enum, Ord, Show, Generic, Data, Typeable, Bounded) instance Hashable Algorithm algorithm :: Algorithm -> CInt algorithm DefaultAlgorithm = fromIntegral pwhash_alg_default algorithm Argon2i13 = fromIntegral pwhash_alg_argon2i13 algorithm Argon2id13 = fromIntegral pwhash_alg_argon2id13 -- | Lets libsodium pick a hashing algorithm pwhash_alg_default :: Int pwhash_alg_default = fromIntegral c_crypto_pwhash_alg_default | version 1.3 of the Argon2i algorithm pwhash_alg_argon2i13 :: Int pwhash_alg_argon2i13 = fromIntegral c_crypto_pwhash_alg_argon2i13 | version 1.3 of the Argon2id algorithm pwhash_alg_argon2id13 :: Int pwhash_alg_argon2id13 = fromIntegral c_crypto_pwhash_alg_argon2id13 -- | Constants for the default algorithm | Minimum output length for key derivation ( 16 ( 128 bits ) ) . pwhash_bytes_min :: Int pwhash_bytes_min = fromIntegral c_crypto_pwhash_bytes_min -- | Maximum output length for key derivation. pwhash_bytes_max :: Int pwhash_bytes_max = fromIntegral c_crypto_pwhash_bytes_max -- | Minimum allowed memory limit for password hashing pwhash_memlimit_min :: Int pwhash_memlimit_min = fromIntegral c_crypto_pwhash_memlimit_min -- | Maximum allowed memory limit for password hashing pwhash_memlimit_max :: Int pwhash_memlimit_max = fromIntegral c_crypto_pwhash_memlimit_max | Constant for currently 64 MB memory pwhash_memlimit_interactive :: Int pwhash_memlimit_interactive = fromIntegral c_crypto_pwhash_memlimit_interactive | Constant for currently 256 MB memory pwhash_memlimit_moderate :: Int pwhash_memlimit_moderate = fromIntegral c_crypto_pwhash_memlimit_moderate | Constant for currently 1024 MB memory pwhash_memlimit_sensitive :: Int pwhash_memlimit_sensitive = fromIntegral c_crypto_pwhash_memlimit_sensitive -- | Minimum allowed number of computations for password hashing pwhash_opslimit_min :: Int pwhash_opslimit_min = fromIntegral c_crypto_pwhash_opslimit_min -- | Maximum allowed number of computations for password hashing pwhash_opslimit_max :: Int pwhash_opslimit_max = fromIntegral c_crypto_pwhash_opslimit_max -- | Constant for relatively fast hashing pwhash_opslimit_interactive :: Int pwhash_opslimit_interactive = fromIntegral c_crypto_pwhash_opslimit_interactive -- | Constant for moderately fast hashing pwhash_opslimit_moderate :: Int pwhash_opslimit_moderate = fromIntegral c_crypto_pwhash_opslimit_moderate -- | Constant for relatively slow hashing pwhash_opslimit_sensitive :: Int pwhash_opslimit_sensitive = fromIntegral c_crypto_pwhash_opslimit_sensitive -- | Minimum number of characters in password for key derivation pwhash_passwd_min :: Int pwhash_passwd_min = fromIntegral c_crypto_pwhash_passwd_min -- | Maximum number of characters in password for key derivation pwhash_passwd_max :: Int pwhash_passwd_max = fromIntegral c_crypto_pwhash_passwd_max -- | Size of salt pwhash_saltbytes :: Int pwhash_saltbytes = fromIntegral c_crypto_pwhash_saltbytes -- | (Maximum) size of password hashing output pwhash_strbytes :: Int pwhash_strbytes = fromIntegral c_crypto_pwhash_strbytes -- string that hashes with this algorithm are prefixed with pwhash_strprefix :: Int pwhash_strprefix = fromIntegral c_crypto_pwhash_strprefix -- | Constants for Argon2ID | Minimum output length for key derivation (= 16 ( 128 bits ) ) . pwhash_argon2id_bytes_min :: Int pwhash_argon2id_bytes_min = fromIntegral c_crypto_pwhash_argon2id_bytes_min -- | Maximum output length for key derivation. pwhash_argon2id_bytes_max :: Int pwhash_argon2id_bytes_max = fromIntegral c_crypto_pwhash_argon2id_bytes_max -- | Minimum allowed memory limit for password hashing pwhash_argon2id_memlimit_min :: Int pwhash_argon2id_memlimit_min = fromIntegral c_crypto_pwhash_argon2id_memlimit_min -- | Maximum allowed memory limit for password hashing pwhash_argon2id_memlimit_max :: Int pwhash_argon2id_memlimit_max = fromIntegral c_crypto_pwhash_argon2id_memlimit_max | Constant for currently 64 MB memory pwhash_argon2id_memlimit_interactive :: Int pwhash_argon2id_memlimit_interactive = fromIntegral c_crypto_pwhash_argon2id_memlimit_interactive | Constant for currently 256 MB memory pwhash_argon2id_memlimit_moderate :: Int pwhash_argon2id_memlimit_moderate = fromIntegral c_crypto_pwhash_argon2id_memlimit_moderate | Constant for currently 1024 MB memory pwhash_argon2id_memlimit_sensitive :: Int pwhash_argon2id_memlimit_sensitive = fromIntegral c_crypto_pwhash_argon2id_memlimit_sensitive -- | Minimum allowed number of computations for password hashing pwhash_argon2id_opslimit_min :: Int pwhash_argon2id_opslimit_min = fromIntegral c_crypto_pwhash_argon2id_opslimit_min -- | Maximum allowed number of computations for password hashing pwhash_argon2id_opslimit_max :: Int pwhash_argon2id_opslimit_max = fromIntegral c_crypto_pwhash_argon2id_opslimit_max -- | Constant for relatively fast hashing pwhash_argon2id_opslimit_interactive :: Int pwhash_argon2id_opslimit_interactive = fromIntegral c_crypto_pwhash_argon2id_opslimit_interactive -- | Constant for moderately fast hashing pwhash_argon2id_opslimit_moderate :: Int pwhash_argon2id_opslimit_moderate = fromIntegral c_crypto_pwhash_argon2id_opslimit_moderate -- | Constant for relatively slow hashing pwhash_argon2id_opslimit_sensitive :: Int pwhash_argon2id_opslimit_sensitive = fromIntegral c_crypto_pwhash_argon2id_opslimit_sensitive -- | Minimum number of characters in password for key derivation pwhash_argon2id_passwd_min :: Int pwhash_argon2id_passwd_min = fromIntegral c_crypto_pwhash_argon2id_passwd_min -- | Maximum number of characters in password for key derivation pwhash_argon2id_passwd_max :: Int pwhash_argon2id_passwd_max = fromIntegral c_crypto_pwhash_argon2id_passwd_max -- | Size of salt pwhash_argon2id_saltbytes :: Int pwhash_argon2id_saltbytes = fromIntegral c_crypto_pwhash_argon2id_saltbytes -- | (Maximum) size of password hashing output pwhash_argon2id_strbytes :: Int pwhash_argon2id_strbytes = fromIntegral c_crypto_pwhash_argon2id_strbytes -- string that hashes with this algorithm are prefixed with pwhash_argon2id_strprefix :: Int pwhash_argon2id_strprefix = fromIntegral c_crypto_pwhash_argon2id_strprefix | Constants for ARGON2I | Minimum output length for key derivation (= 16 ( 128 bits ) ) . pwhash_argon2i_bytes_min :: Int pwhash_argon2i_bytes_min = fromIntegral c_crypto_pwhash_argon2i_bytes_min -- | Maximum output length for key derivation. pwhash_argon2i_bytes_max :: Int pwhash_argon2i_bytes_max = fromIntegral c_crypto_pwhash_argon2i_bytes_max -- | Minimum allowed memory limit for password hashing pwhash_argon2i_memlimit_min :: Int pwhash_argon2i_memlimit_min = fromIntegral c_crypto_pwhash_argon2i_memlimit_min -- | Maximum allowed memory limit for password hashing pwhash_argon2i_memlimit_max :: Int pwhash_argon2i_memlimit_max = fromIntegral c_crypto_pwhash_argon2i_memlimit_max | Constant for currently 64 MB memory pwhash_argon2i_memlimit_interactive :: Int pwhash_argon2i_memlimit_interactive = fromIntegral c_crypto_pwhash_argon2i_memlimit_interactive | Constant for currently 256 MB memory pwhash_argon2i_memlimit_moderate :: Int pwhash_argon2i_memlimit_moderate = fromIntegral c_crypto_pwhash_argon2i_memlimit_moderate | Constant for currently 1024 MB memory pwhash_argon2i_memlimit_sensitive :: Int pwhash_argon2i_memlimit_sensitive = fromIntegral c_crypto_pwhash_argon2i_memlimit_sensitive -- | Minimum allowed number of computations for password hashing pwhash_argon2i_opslimit_min :: Int pwhash_argon2i_opslimit_min = fromIntegral c_crypto_pwhash_argon2i_opslimit_min -- | Maximum allowed number of computations for password hashing pwhash_argon2i_opslimit_max :: Int pwhash_argon2i_opslimit_max = fromIntegral c_crypto_pwhash_argon2i_opslimit_max -- | Constant for relatively fast hashing pwhash_argon2i_opslimit_interactive :: Int pwhash_argon2i_opslimit_interactive = fromIntegral c_crypto_pwhash_argon2i_opslimit_interactive -- | Constant for moderately fast hashing pwhash_argon2i_opslimit_moderate :: Int pwhash_argon2i_opslimit_moderate = fromIntegral c_crypto_pwhash_argon2i_opslimit_moderate -- | Constant for relatively slow hashing pwhash_argon2i_opslimit_sensitive :: Int pwhash_argon2i_opslimit_sensitive = fromIntegral c_crypto_pwhash_argon2i_opslimit_sensitive -- | Minimum number of characters in password for key derivation pwhash_argon2i_passwd_min :: Int pwhash_argon2i_passwd_min = fromIntegral c_crypto_pwhash_argon2i_passwd_min -- | Maximum number of characters in password for key derivation pwhash_argon2i_passwd_max :: Int pwhash_argon2i_passwd_max = fromIntegral c_crypto_pwhash_argon2i_passwd_max -- | Size of salt pwhash_argon2i_saltbytes :: Int pwhash_argon2i_saltbytes = fromIntegral c_crypto_pwhash_argon2i_saltbytes -- | (Maximum) size of password hashing output pwhash_argon2i_strbytes :: Int pwhash_argon2i_strbytes = fromIntegral c_crypto_pwhash_argon2i_strbytes -- string that hashes with this algorithm are prefixed with pwhash_argon2i_strprefix :: Int pwhash_argon2i_strprefix = fromIntegral c_crypto_pwhash_argon2i_strprefix foreign import ccall "crypto_pwhash" c_pwhash :: Ptr CChar -- ^ Derived key output buffer -> CULLong -- ^ Derived key length -> Ptr CChar -- ^ Password input buffer -> CULLong -- ^ Password length -> Ptr CChar -- ^ Salt input buffer -> CULLong -- ^ Operation limit -> CSize -- ^ Memory usage limit -> CInt -- ^ Algorithm -> IO CInt foreign import ccall "crypto_pwhash_str" c_pwhash_str :: Ptr CChar -- ^ Hashed password output buffer -> Ptr CChar -- ^ Password input buffer -> CULLong -- ^ Password length -> CULLong -- ^ Operation limit -> CSize -- ^ Memory usage limit -> IO CInt foreign import ccall "crypto_pwhash_str_verify" c_pwhash_str_verify :: Ptr CChar -- ^ Hashed password input buffer -> Ptr CChar -- ^ Password input buffer -> CULLong -- ^ Password length -> IO CInt foreign import ccall "crypto_pwhash_str_needs_rehash" c_pwhash_str_needs_rehash :: Ptr CChar -- ^ Hashed password input buffer -> CULLong -- ^ Operation limit -> CSize -- ^ Memory usage limit -> IO CInt foreign import ccall "crypto_pwhash_alg_argon2id13" c_crypto_pwhash_alg_argon2id13 :: CSize foreign import ccall "crypto_pwhash_alg_argon2i13" c_crypto_pwhash_alg_argon2i13 :: CSize foreign import ccall "crypto_pwhash_alg_default" c_crypto_pwhash_alg_default :: CSize -- Constants for the default algorithm foreign import ccall "crypto_pwhash_bytes_min" c_crypto_pwhash_bytes_min :: CSize foreign import ccall "crypto_pwhash_bytes_max" c_crypto_pwhash_bytes_max :: CSize foreign import ccall "crypto_pwhash_memlimit_min" c_crypto_pwhash_memlimit_min :: CSize foreign import ccall "crypto_pwhash_memlimit_max" c_crypto_pwhash_memlimit_max :: CSize foreign import ccall "crypto_pwhash_memlimit_interactive" c_crypto_pwhash_memlimit_interactive :: CSize foreign import ccall "crypto_pwhash_memlimit_moderate" c_crypto_pwhash_memlimit_moderate :: CSize foreign import ccall "crypto_pwhash_memlimit_sensitive" c_crypto_pwhash_memlimit_sensitive :: CSize foreign import ccall "crypto_pwhash_opslimit_min" c_crypto_pwhash_opslimit_min :: CSize foreign import ccall "crypto_pwhash_opslimit_max" c_crypto_pwhash_opslimit_max :: CSize foreign import ccall "crypto_pwhash_opslimit_interactive" c_crypto_pwhash_opslimit_interactive :: CSize foreign import ccall "crypto_pwhash_opslimit_moderate" c_crypto_pwhash_opslimit_moderate :: CSize foreign import ccall "crypto_pwhash_opslimit_sensitive" c_crypto_pwhash_opslimit_sensitive :: CSize foreign import ccall "crypto_pwhash_passwd_min" c_crypto_pwhash_passwd_min :: CSize foreign import ccall "crypto_pwhash_passwd_max" c_crypto_pwhash_passwd_max :: CSize foreign import ccall "crypto_pwhash_saltbytes" c_crypto_pwhash_saltbytes :: CSize foreign import ccall "crypto_pwhash_strbytes" c_crypto_pwhash_strbytes :: CSize foreign import ccall "crypto_pwhash_strprefix" c_crypto_pwhash_strprefix :: CSize -- Constants for ARGON2ID (currently default) foreign import ccall "crypto_pwhash_argon2id_bytes_min" c_crypto_pwhash_argon2id_bytes_min :: CSize foreign import ccall "crypto_pwhash_argon2id_bytes_max" c_crypto_pwhash_argon2id_bytes_max :: CSize foreign import ccall "crypto_pwhash_argon2id_memlimit_min" c_crypto_pwhash_argon2id_memlimit_min :: CSize foreign import ccall "crypto_pwhash_argon2id_memlimit_max" c_crypto_pwhash_argon2id_memlimit_max :: CSize foreign import ccall "crypto_pwhash_argon2id_memlimit_interactive" c_crypto_pwhash_argon2id_memlimit_interactive :: CSize foreign import ccall "crypto_pwhash_argon2id_memlimit_moderate" c_crypto_pwhash_argon2id_memlimit_moderate :: CSize foreign import ccall "crypto_pwhash_argon2id_memlimit_sensitive" c_crypto_pwhash_argon2id_memlimit_sensitive :: CSize foreign import ccall "crypto_pwhash_argon2id_opslimit_min" c_crypto_pwhash_argon2id_opslimit_min :: CSize foreign import ccall "crypto_pwhash_argon2id_opslimit_max" c_crypto_pwhash_argon2id_opslimit_max :: CSize foreign import ccall "crypto_pwhash_argon2id_opslimit_interactive" c_crypto_pwhash_argon2id_opslimit_interactive :: CSize foreign import ccall "crypto_pwhash_argon2id_opslimit_moderate" c_crypto_pwhash_argon2id_opslimit_moderate :: CSize foreign import ccall "crypto_pwhash_argon2id_opslimit_sensitive" c_crypto_pwhash_argon2id_opslimit_sensitive :: CSize foreign import ccall "crypto_pwhash_argon2id_passwd_min" c_crypto_pwhash_argon2id_passwd_min :: CSize foreign import ccall "crypto_pwhash_argon2id_passwd_max" c_crypto_pwhash_argon2id_passwd_max :: CSize foreign import ccall "crypto_pwhash_argon2id_saltbytes" c_crypto_pwhash_argon2id_saltbytes :: CSize foreign import ccall "crypto_pwhash_argon2id_strbytes" c_crypto_pwhash_argon2id_strbytes :: CSize foreign import ccall "crypto_pwhash_argon2id_strprefix" c_crypto_pwhash_argon2id_strprefix :: CSize Constants for ARGON2I foreign import ccall "crypto_pwhash_argon2i_bytes_min" c_crypto_pwhash_argon2i_bytes_min :: CSize foreign import ccall "crypto_pwhash_argon2i_bytes_max" c_crypto_pwhash_argon2i_bytes_max :: CSize foreign import ccall "crypto_pwhash_argon2i_memlimit_min" c_crypto_pwhash_argon2i_memlimit_min :: CSize foreign import ccall "crypto_pwhash_argon2i_memlimit_max" c_crypto_pwhash_argon2i_memlimit_max :: CSize foreign import ccall "crypto_pwhash_argon2i_memlimit_interactive" c_crypto_pwhash_argon2i_memlimit_interactive :: CSize foreign import ccall "crypto_pwhash_argon2i_memlimit_moderate" c_crypto_pwhash_argon2i_memlimit_moderate :: CSize foreign import ccall "crypto_pwhash_argon2i_memlimit_sensitive" c_crypto_pwhash_argon2i_memlimit_sensitive :: CSize foreign import ccall "crypto_pwhash_argon2i_opslimit_min" c_crypto_pwhash_argon2i_opslimit_min :: CSize foreign import ccall "crypto_pwhash_argon2i_opslimit_max" c_crypto_pwhash_argon2i_opslimit_max :: CSize foreign import ccall "crypto_pwhash_argon2i_opslimit_interactive" c_crypto_pwhash_argon2i_opslimit_interactive :: CSize foreign import ccall "crypto_pwhash_argon2i_opslimit_moderate" c_crypto_pwhash_argon2i_opslimit_moderate :: CSize foreign import ccall "crypto_pwhash_argon2i_opslimit_sensitive" c_crypto_pwhash_argon2i_opslimit_sensitive :: CSize foreign import ccall "crypto_pwhash_argon2i_passwd_min" c_crypto_pwhash_argon2i_passwd_min :: CSize foreign import ccall "crypto_pwhash_argon2i_passwd_max" c_crypto_pwhash_argon2i_passwd_max :: CSize foreign import ccall "crypto_pwhash_argon2i_saltbytes" c_crypto_pwhash_argon2i_saltbytes :: CSize foreign import ccall "crypto_pwhash_argon2i_strbytes" c_crypto_pwhash_argon2i_strbytes :: CSize foreign import ccall "crypto_pwhash_argon2i_strprefix" c_crypto_pwhash_argon2i_strprefix :: CSize
null
https://raw.githubusercontent.com/tel/saltine/b00e00fa8ce8bf4ee176a9d3deead57c590fc686/src/Crypto/Saltine/Internal/Password.hs
haskell
| Module : Crypto.Saltine.Internal.Password Maintainer : Stability : experimental Portability : non-portable Default algorithm constants Argon2id algorithm constants | Salt for deriving keys from passwords | Verification string for stored passwords This hash contains only printable characters, hence we can just derive Show. | Wrapper type for the operations used by password hashing | Wrapper type for the memory used by password hashing | Wrapper for opslimit, memlimit and algorithm | Lets libsodium pick a hashing algorithm | Constants for the default algorithm | Maximum output length for key derivation. | Minimum allowed memory limit for password hashing | Maximum allowed memory limit for password hashing | Minimum allowed number of computations for password hashing | Maximum allowed number of computations for password hashing | Constant for relatively fast hashing | Constant for moderately fast hashing | Constant for relatively slow hashing | Minimum number of characters in password for key derivation | Maximum number of characters in password for key derivation | Size of salt | (Maximum) size of password hashing output string that hashes with this algorithm are prefixed with | Constants for Argon2ID | Maximum output length for key derivation. | Minimum allowed memory limit for password hashing | Maximum allowed memory limit for password hashing | Minimum allowed number of computations for password hashing | Maximum allowed number of computations for password hashing | Constant for relatively fast hashing | Constant for moderately fast hashing | Constant for relatively slow hashing | Minimum number of characters in password for key derivation | Maximum number of characters in password for key derivation | Size of salt | (Maximum) size of password hashing output string that hashes with this algorithm are prefixed with | Maximum output length for key derivation. | Minimum allowed memory limit for password hashing | Maximum allowed memory limit for password hashing | Minimum allowed number of computations for password hashing | Maximum allowed number of computations for password hashing | Constant for relatively fast hashing | Constant for moderately fast hashing | Constant for relatively slow hashing | Minimum number of characters in password for key derivation | Maximum number of characters in password for key derivation | Size of salt | (Maximum) size of password hashing output string that hashes with this algorithm are prefixed with ^ Derived key output buffer ^ Derived key length ^ Password input buffer ^ Password length ^ Salt input buffer ^ Operation limit ^ Memory usage limit ^ Algorithm ^ Hashed password output buffer ^ Password input buffer ^ Password length ^ Operation limit ^ Memory usage limit ^ Hashed password input buffer ^ Password input buffer ^ Password length ^ Hashed password input buffer ^ Operation limit ^ Memory usage limit Constants for the default algorithm Constants for ARGON2ID (currently default)
# LANGUAGE DeriveDataTypeable , , DeriveGeneric , ForeignFunctionInterface # Copyright : ( c ) 2018 2021 License : MIT module Crypto.Saltine.Internal.Password ( c_pwhash , c_pwhash_str , c_pwhash_str_verify , c_pwhash_str_needs_rehash , pwhash_alg_argon2i13 , pwhash_alg_argon2id13 , pwhash_alg_default , algorithm , pwhash_bytes_max , pwhash_bytes_min , pwhash_memlimit_interactive , pwhash_memlimit_moderate , pwhash_memlimit_sensitive , pwhash_memlimit_min , pwhash_memlimit_max , pwhash_opslimit_interactive , pwhash_opslimit_moderate , pwhash_opslimit_sensitive , pwhash_opslimit_min , pwhash_opslimit_max , pwhash_passwd_min , pwhash_passwd_max , pwhash_saltbytes , pwhash_strbytes , pwhash_strprefix Argon2i algorithm constants , pwhash_argon2i_bytes_max , pwhash_argon2i_bytes_min , pwhash_argon2i_memlimit_interactive , pwhash_argon2i_memlimit_moderate , pwhash_argon2i_memlimit_sensitive , pwhash_argon2i_memlimit_min , pwhash_argon2i_memlimit_max , pwhash_argon2i_opslimit_interactive , pwhash_argon2i_opslimit_moderate , pwhash_argon2i_opslimit_sensitive , pwhash_argon2i_opslimit_min , pwhash_argon2i_opslimit_max , pwhash_argon2i_passwd_min , pwhash_argon2i_passwd_max , pwhash_argon2i_saltbytes , pwhash_argon2i_strbytes , pwhash_argon2i_strprefix , pwhash_argon2id_bytes_max , pwhash_argon2id_bytes_min , pwhash_argon2id_memlimit_interactive , pwhash_argon2id_memlimit_moderate , pwhash_argon2id_memlimit_sensitive , pwhash_argon2id_memlimit_min , pwhash_argon2id_memlimit_max , pwhash_argon2id_opslimit_interactive , pwhash_argon2id_opslimit_moderate , pwhash_argon2id_opslimit_sensitive , pwhash_argon2id_opslimit_min , pwhash_argon2id_opslimit_max , pwhash_argon2id_passwd_min , pwhash_argon2id_passwd_max , pwhash_argon2id_saltbytes , pwhash_argon2id_strbytes , pwhash_argon2id_strprefix , Salt(..) , PasswordHash(..) , Opslimit(..) , Memlimit(..) , Policy(..) , Algorithm(..) ) where import Control.DeepSeq import Crypto.Saltine.Class import Crypto.Saltine.Internal.Util as U import Data.ByteString (ByteString) import Data.Data (Data, Typeable) import Data.Hashable (Hashable) import Data.Monoid import Data.Text (Text) import GHC.Generics (Generic) import Foreign.C import Foreign.Ptr import qualified Data.ByteString as S import qualified Data.Text.Encoding as DTE newtype Salt = Salt { unSalt :: ByteString } deriving (Ord, Data, Hashable, Typeable, Generic, NFData) instance Eq Salt where Salt a == Salt b = U.compare a b instance Show Salt where show k = "Password.Salt " <> bin2hex (encode k) instance IsEncoding Salt where decode v = if S.length v == pwhash_saltbytes then Just (Salt v) else Nothing # INLINE decode # encode (Salt v) = v # INLINE encode # newtype PasswordHash = PasswordHash { unPasswordHash :: Text } deriving (Ord, Data, Hashable, Typeable, Generic, Show, NFData) Constant time instance , just in case . instance Eq PasswordHash where PasswordHash a == PasswordHash b = U.compare (DTE.encodeUtf8 a) (DTE.encodeUtf8 b) newtype Opslimit = Opslimit { getOpslimit :: Int } deriving (Eq, Ord, Data, Hashable, Typeable, Generic, Show, NFData) newtype Memlimit = Memlimit { getMemlimit :: Int } deriving (Eq, Ord, Data, Hashable, Typeable, Generic, Show, NFData) data Policy = Policy { opsPolicy :: Opslimit , memPolicy :: Memlimit , algPolicy :: Algorithm } deriving (Eq, Ord, Data, Typeable, Generic, Show) instance Hashable Policy | Algorithms known to Libsodium , as an enum datatype data Algorithm = DefaultAlgorithm | Argon2i13 | Argon2id13 deriving (Eq, Enum, Ord, Show, Generic, Data, Typeable, Bounded) instance Hashable Algorithm algorithm :: Algorithm -> CInt algorithm DefaultAlgorithm = fromIntegral pwhash_alg_default algorithm Argon2i13 = fromIntegral pwhash_alg_argon2i13 algorithm Argon2id13 = fromIntegral pwhash_alg_argon2id13 pwhash_alg_default :: Int pwhash_alg_default = fromIntegral c_crypto_pwhash_alg_default | version 1.3 of the Argon2i algorithm pwhash_alg_argon2i13 :: Int pwhash_alg_argon2i13 = fromIntegral c_crypto_pwhash_alg_argon2i13 | version 1.3 of the Argon2id algorithm pwhash_alg_argon2id13 :: Int pwhash_alg_argon2id13 = fromIntegral c_crypto_pwhash_alg_argon2id13 | Minimum output length for key derivation ( 16 ( 128 bits ) ) . pwhash_bytes_min :: Int pwhash_bytes_min = fromIntegral c_crypto_pwhash_bytes_min pwhash_bytes_max :: Int pwhash_bytes_max = fromIntegral c_crypto_pwhash_bytes_max pwhash_memlimit_min :: Int pwhash_memlimit_min = fromIntegral c_crypto_pwhash_memlimit_min pwhash_memlimit_max :: Int pwhash_memlimit_max = fromIntegral c_crypto_pwhash_memlimit_max | Constant for currently 64 MB memory pwhash_memlimit_interactive :: Int pwhash_memlimit_interactive = fromIntegral c_crypto_pwhash_memlimit_interactive | Constant for currently 256 MB memory pwhash_memlimit_moderate :: Int pwhash_memlimit_moderate = fromIntegral c_crypto_pwhash_memlimit_moderate | Constant for currently 1024 MB memory pwhash_memlimit_sensitive :: Int pwhash_memlimit_sensitive = fromIntegral c_crypto_pwhash_memlimit_sensitive pwhash_opslimit_min :: Int pwhash_opslimit_min = fromIntegral c_crypto_pwhash_opslimit_min pwhash_opslimit_max :: Int pwhash_opslimit_max = fromIntegral c_crypto_pwhash_opslimit_max pwhash_opslimit_interactive :: Int pwhash_opslimit_interactive = fromIntegral c_crypto_pwhash_opslimit_interactive pwhash_opslimit_moderate :: Int pwhash_opslimit_moderate = fromIntegral c_crypto_pwhash_opslimit_moderate pwhash_opslimit_sensitive :: Int pwhash_opslimit_sensitive = fromIntegral c_crypto_pwhash_opslimit_sensitive pwhash_passwd_min :: Int pwhash_passwd_min = fromIntegral c_crypto_pwhash_passwd_min pwhash_passwd_max :: Int pwhash_passwd_max = fromIntegral c_crypto_pwhash_passwd_max pwhash_saltbytes :: Int pwhash_saltbytes = fromIntegral c_crypto_pwhash_saltbytes pwhash_strbytes :: Int pwhash_strbytes = fromIntegral c_crypto_pwhash_strbytes pwhash_strprefix :: Int pwhash_strprefix = fromIntegral c_crypto_pwhash_strprefix | Minimum output length for key derivation (= 16 ( 128 bits ) ) . pwhash_argon2id_bytes_min :: Int pwhash_argon2id_bytes_min = fromIntegral c_crypto_pwhash_argon2id_bytes_min pwhash_argon2id_bytes_max :: Int pwhash_argon2id_bytes_max = fromIntegral c_crypto_pwhash_argon2id_bytes_max pwhash_argon2id_memlimit_min :: Int pwhash_argon2id_memlimit_min = fromIntegral c_crypto_pwhash_argon2id_memlimit_min pwhash_argon2id_memlimit_max :: Int pwhash_argon2id_memlimit_max = fromIntegral c_crypto_pwhash_argon2id_memlimit_max | Constant for currently 64 MB memory pwhash_argon2id_memlimit_interactive :: Int pwhash_argon2id_memlimit_interactive = fromIntegral c_crypto_pwhash_argon2id_memlimit_interactive | Constant for currently 256 MB memory pwhash_argon2id_memlimit_moderate :: Int pwhash_argon2id_memlimit_moderate = fromIntegral c_crypto_pwhash_argon2id_memlimit_moderate | Constant for currently 1024 MB memory pwhash_argon2id_memlimit_sensitive :: Int pwhash_argon2id_memlimit_sensitive = fromIntegral c_crypto_pwhash_argon2id_memlimit_sensitive pwhash_argon2id_opslimit_min :: Int pwhash_argon2id_opslimit_min = fromIntegral c_crypto_pwhash_argon2id_opslimit_min pwhash_argon2id_opslimit_max :: Int pwhash_argon2id_opslimit_max = fromIntegral c_crypto_pwhash_argon2id_opslimit_max pwhash_argon2id_opslimit_interactive :: Int pwhash_argon2id_opslimit_interactive = fromIntegral c_crypto_pwhash_argon2id_opslimit_interactive pwhash_argon2id_opslimit_moderate :: Int pwhash_argon2id_opslimit_moderate = fromIntegral c_crypto_pwhash_argon2id_opslimit_moderate pwhash_argon2id_opslimit_sensitive :: Int pwhash_argon2id_opslimit_sensitive = fromIntegral c_crypto_pwhash_argon2id_opslimit_sensitive pwhash_argon2id_passwd_min :: Int pwhash_argon2id_passwd_min = fromIntegral c_crypto_pwhash_argon2id_passwd_min pwhash_argon2id_passwd_max :: Int pwhash_argon2id_passwd_max = fromIntegral c_crypto_pwhash_argon2id_passwd_max pwhash_argon2id_saltbytes :: Int pwhash_argon2id_saltbytes = fromIntegral c_crypto_pwhash_argon2id_saltbytes pwhash_argon2id_strbytes :: Int pwhash_argon2id_strbytes = fromIntegral c_crypto_pwhash_argon2id_strbytes pwhash_argon2id_strprefix :: Int pwhash_argon2id_strprefix = fromIntegral c_crypto_pwhash_argon2id_strprefix | Constants for ARGON2I | Minimum output length for key derivation (= 16 ( 128 bits ) ) . pwhash_argon2i_bytes_min :: Int pwhash_argon2i_bytes_min = fromIntegral c_crypto_pwhash_argon2i_bytes_min pwhash_argon2i_bytes_max :: Int pwhash_argon2i_bytes_max = fromIntegral c_crypto_pwhash_argon2i_bytes_max pwhash_argon2i_memlimit_min :: Int pwhash_argon2i_memlimit_min = fromIntegral c_crypto_pwhash_argon2i_memlimit_min pwhash_argon2i_memlimit_max :: Int pwhash_argon2i_memlimit_max = fromIntegral c_crypto_pwhash_argon2i_memlimit_max | Constant for currently 64 MB memory pwhash_argon2i_memlimit_interactive :: Int pwhash_argon2i_memlimit_interactive = fromIntegral c_crypto_pwhash_argon2i_memlimit_interactive | Constant for currently 256 MB memory pwhash_argon2i_memlimit_moderate :: Int pwhash_argon2i_memlimit_moderate = fromIntegral c_crypto_pwhash_argon2i_memlimit_moderate | Constant for currently 1024 MB memory pwhash_argon2i_memlimit_sensitive :: Int pwhash_argon2i_memlimit_sensitive = fromIntegral c_crypto_pwhash_argon2i_memlimit_sensitive pwhash_argon2i_opslimit_min :: Int pwhash_argon2i_opslimit_min = fromIntegral c_crypto_pwhash_argon2i_opslimit_min pwhash_argon2i_opslimit_max :: Int pwhash_argon2i_opslimit_max = fromIntegral c_crypto_pwhash_argon2i_opslimit_max pwhash_argon2i_opslimit_interactive :: Int pwhash_argon2i_opslimit_interactive = fromIntegral c_crypto_pwhash_argon2i_opslimit_interactive pwhash_argon2i_opslimit_moderate :: Int pwhash_argon2i_opslimit_moderate = fromIntegral c_crypto_pwhash_argon2i_opslimit_moderate pwhash_argon2i_opslimit_sensitive :: Int pwhash_argon2i_opslimit_sensitive = fromIntegral c_crypto_pwhash_argon2i_opslimit_sensitive pwhash_argon2i_passwd_min :: Int pwhash_argon2i_passwd_min = fromIntegral c_crypto_pwhash_argon2i_passwd_min pwhash_argon2i_passwd_max :: Int pwhash_argon2i_passwd_max = fromIntegral c_crypto_pwhash_argon2i_passwd_max pwhash_argon2i_saltbytes :: Int pwhash_argon2i_saltbytes = fromIntegral c_crypto_pwhash_argon2i_saltbytes pwhash_argon2i_strbytes :: Int pwhash_argon2i_strbytes = fromIntegral c_crypto_pwhash_argon2i_strbytes pwhash_argon2i_strprefix :: Int pwhash_argon2i_strprefix = fromIntegral c_crypto_pwhash_argon2i_strprefix foreign import ccall "crypto_pwhash" c_pwhash :: Ptr CChar -> CULLong -> Ptr CChar -> CULLong -> Ptr CChar -> CULLong -> CSize -> CInt -> IO CInt foreign import ccall "crypto_pwhash_str" c_pwhash_str :: Ptr CChar -> Ptr CChar -> CULLong -> CULLong -> CSize -> IO CInt foreign import ccall "crypto_pwhash_str_verify" c_pwhash_str_verify :: Ptr CChar -> Ptr CChar -> CULLong -> IO CInt foreign import ccall "crypto_pwhash_str_needs_rehash" c_pwhash_str_needs_rehash :: Ptr CChar -> CULLong -> CSize -> IO CInt foreign import ccall "crypto_pwhash_alg_argon2id13" c_crypto_pwhash_alg_argon2id13 :: CSize foreign import ccall "crypto_pwhash_alg_argon2i13" c_crypto_pwhash_alg_argon2i13 :: CSize foreign import ccall "crypto_pwhash_alg_default" c_crypto_pwhash_alg_default :: CSize foreign import ccall "crypto_pwhash_bytes_min" c_crypto_pwhash_bytes_min :: CSize foreign import ccall "crypto_pwhash_bytes_max" c_crypto_pwhash_bytes_max :: CSize foreign import ccall "crypto_pwhash_memlimit_min" c_crypto_pwhash_memlimit_min :: CSize foreign import ccall "crypto_pwhash_memlimit_max" c_crypto_pwhash_memlimit_max :: CSize foreign import ccall "crypto_pwhash_memlimit_interactive" c_crypto_pwhash_memlimit_interactive :: CSize foreign import ccall "crypto_pwhash_memlimit_moderate" c_crypto_pwhash_memlimit_moderate :: CSize foreign import ccall "crypto_pwhash_memlimit_sensitive" c_crypto_pwhash_memlimit_sensitive :: CSize foreign import ccall "crypto_pwhash_opslimit_min" c_crypto_pwhash_opslimit_min :: CSize foreign import ccall "crypto_pwhash_opslimit_max" c_crypto_pwhash_opslimit_max :: CSize foreign import ccall "crypto_pwhash_opslimit_interactive" c_crypto_pwhash_opslimit_interactive :: CSize foreign import ccall "crypto_pwhash_opslimit_moderate" c_crypto_pwhash_opslimit_moderate :: CSize foreign import ccall "crypto_pwhash_opslimit_sensitive" c_crypto_pwhash_opslimit_sensitive :: CSize foreign import ccall "crypto_pwhash_passwd_min" c_crypto_pwhash_passwd_min :: CSize foreign import ccall "crypto_pwhash_passwd_max" c_crypto_pwhash_passwd_max :: CSize foreign import ccall "crypto_pwhash_saltbytes" c_crypto_pwhash_saltbytes :: CSize foreign import ccall "crypto_pwhash_strbytes" c_crypto_pwhash_strbytes :: CSize foreign import ccall "crypto_pwhash_strprefix" c_crypto_pwhash_strprefix :: CSize foreign import ccall "crypto_pwhash_argon2id_bytes_min" c_crypto_pwhash_argon2id_bytes_min :: CSize foreign import ccall "crypto_pwhash_argon2id_bytes_max" c_crypto_pwhash_argon2id_bytes_max :: CSize foreign import ccall "crypto_pwhash_argon2id_memlimit_min" c_crypto_pwhash_argon2id_memlimit_min :: CSize foreign import ccall "crypto_pwhash_argon2id_memlimit_max" c_crypto_pwhash_argon2id_memlimit_max :: CSize foreign import ccall "crypto_pwhash_argon2id_memlimit_interactive" c_crypto_pwhash_argon2id_memlimit_interactive :: CSize foreign import ccall "crypto_pwhash_argon2id_memlimit_moderate" c_crypto_pwhash_argon2id_memlimit_moderate :: CSize foreign import ccall "crypto_pwhash_argon2id_memlimit_sensitive" c_crypto_pwhash_argon2id_memlimit_sensitive :: CSize foreign import ccall "crypto_pwhash_argon2id_opslimit_min" c_crypto_pwhash_argon2id_opslimit_min :: CSize foreign import ccall "crypto_pwhash_argon2id_opslimit_max" c_crypto_pwhash_argon2id_opslimit_max :: CSize foreign import ccall "crypto_pwhash_argon2id_opslimit_interactive" c_crypto_pwhash_argon2id_opslimit_interactive :: CSize foreign import ccall "crypto_pwhash_argon2id_opslimit_moderate" c_crypto_pwhash_argon2id_opslimit_moderate :: CSize foreign import ccall "crypto_pwhash_argon2id_opslimit_sensitive" c_crypto_pwhash_argon2id_opslimit_sensitive :: CSize foreign import ccall "crypto_pwhash_argon2id_passwd_min" c_crypto_pwhash_argon2id_passwd_min :: CSize foreign import ccall "crypto_pwhash_argon2id_passwd_max" c_crypto_pwhash_argon2id_passwd_max :: CSize foreign import ccall "crypto_pwhash_argon2id_saltbytes" c_crypto_pwhash_argon2id_saltbytes :: CSize foreign import ccall "crypto_pwhash_argon2id_strbytes" c_crypto_pwhash_argon2id_strbytes :: CSize foreign import ccall "crypto_pwhash_argon2id_strprefix" c_crypto_pwhash_argon2id_strprefix :: CSize Constants for ARGON2I foreign import ccall "crypto_pwhash_argon2i_bytes_min" c_crypto_pwhash_argon2i_bytes_min :: CSize foreign import ccall "crypto_pwhash_argon2i_bytes_max" c_crypto_pwhash_argon2i_bytes_max :: CSize foreign import ccall "crypto_pwhash_argon2i_memlimit_min" c_crypto_pwhash_argon2i_memlimit_min :: CSize foreign import ccall "crypto_pwhash_argon2i_memlimit_max" c_crypto_pwhash_argon2i_memlimit_max :: CSize foreign import ccall "crypto_pwhash_argon2i_memlimit_interactive" c_crypto_pwhash_argon2i_memlimit_interactive :: CSize foreign import ccall "crypto_pwhash_argon2i_memlimit_moderate" c_crypto_pwhash_argon2i_memlimit_moderate :: CSize foreign import ccall "crypto_pwhash_argon2i_memlimit_sensitive" c_crypto_pwhash_argon2i_memlimit_sensitive :: CSize foreign import ccall "crypto_pwhash_argon2i_opslimit_min" c_crypto_pwhash_argon2i_opslimit_min :: CSize foreign import ccall "crypto_pwhash_argon2i_opslimit_max" c_crypto_pwhash_argon2i_opslimit_max :: CSize foreign import ccall "crypto_pwhash_argon2i_opslimit_interactive" c_crypto_pwhash_argon2i_opslimit_interactive :: CSize foreign import ccall "crypto_pwhash_argon2i_opslimit_moderate" c_crypto_pwhash_argon2i_opslimit_moderate :: CSize foreign import ccall "crypto_pwhash_argon2i_opslimit_sensitive" c_crypto_pwhash_argon2i_opslimit_sensitive :: CSize foreign import ccall "crypto_pwhash_argon2i_passwd_min" c_crypto_pwhash_argon2i_passwd_min :: CSize foreign import ccall "crypto_pwhash_argon2i_passwd_max" c_crypto_pwhash_argon2i_passwd_max :: CSize foreign import ccall "crypto_pwhash_argon2i_saltbytes" c_crypto_pwhash_argon2i_saltbytes :: CSize foreign import ccall "crypto_pwhash_argon2i_strbytes" c_crypto_pwhash_argon2i_strbytes :: CSize foreign import ccall "crypto_pwhash_argon2i_strprefix" c_crypto_pwhash_argon2i_strprefix :: CSize
4e5be8ee20b237325b583b508790aed2fbe34106b78e804b68149802e7f2c5af
zeromq/chumak
chumak_command.erl
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. @doc Module responsible to decode and encode ZeroMQ commands -module(chumak_command). -include("chumak.hrl"). -export_type([command/0]). -export([decode/2, command_name/1, encode_ready/4, ready_socket_type/1, ready_identity/1, ready_resource/1, ready_metadata/1, initiate_metadata/1, initiate_client_key/1, encode_error/1, error_reason/1, encode_subscribe/1, subscribe_subscription/1, encode_cancel/1, cancel_subscription/1, encode_ready_properties/1 ]). -record(ready, { socket_type=nil :: nil | string(), identity="" :: string(), resource="" :: string(), metadata=#{} :: map() }). -record(ping, {}). -record(error, {reason :: string()}). -record(subscribe, {subscription :: binary()}). -record(cancel, {subscription :: binary()}). -record(hello, {}). -record(welcome, {}). -record(initiate, {metadata = #{} :: map(), client_public_key :: binary()}). -record(message, {}). -type ready() :: ready(). %% ready command -type ping() :: ping(). %% ping command -type error() :: error(). %% error command -type subscribe():: subscribe(). %% subscribe command -type cancel() :: cancel(). %% cancel command %% commands used in the curveZMQ handshake: -type hello() :: #hello{}. -type welcome() :: #welcome{}. -type initiate() :: #initiate{}. %% CurveZMQ payload (messages) is also encoded as commands -type message() :: #message{}. %% commands available -type command() :: ready() | ping() | error() | subscribe() | cancel() | hello() | welcome() | initiate() | ready() | message(). -type ready_decode_error() :: wrong_ready_message. -type decode_error() :: ready_decode_error(). %% %% Public API %% %% @doc decode reads incoming command and generate an command 'object' -spec decode(Frame::chumak_protocol:frame(), CurveData::chumak_curve:curve_data()) -> {ok, Command::command(), NewCurveData::chumak_curve:curve_data()} | {error, decode_error()}. decode(Frame, CurveData) -> <<CommandNameByteSize, Frame2/binary>> = Frame, CommandNameBitSize = 8 * CommandNameByteSize, <<CommandName:CommandNameBitSize/bitstring, CommandBody/binary>> = Frame2, decode_message(binary_to_atom(CommandName, utf8), CommandBody, CurveData). %% @doc returns the name of a command -spec command_name(Command::command()) -> Name::atom(). command_name(Command) -> element(1, Command). %% %% Ready command handler functions %% %% @doc return the socket type of a ready command -spec ready_socket_type(Command::ready()) -> SocketType::atom(). ready_socket_type(#ready{socket_type=SocketType}) -> SocketType. %% @doc return the identity of a ready command -spec ready_identity(Command::ready()) -> Identity::string(). ready_identity(#ready{identity=Identity}) -> Identity. %% @doc return the resource of a ready command -spec ready_resource(Command::ready()) -> Resource::string(). ready_resource(#ready{resource=Resource}) -> Resource. %% @doc return the metadata of a ready command -spec ready_metadata(Command::ready()) -> Metadata::map(). ready_metadata(#ready{metadata=Metadata}) -> Metadata. %% @doc return the metadata of an initiate command -spec initiate_metadata(Command::initiate()) -> Metadata::map(). initiate_metadata(#initiate{metadata=Metadata}) -> Metadata. %% @doc return the public key of the client. This is an element of the %% INITIATE command. It can be used to identify the client. -spec initiate_client_key(Command::initiate()) -> Key::binary(). initiate_client_key(#initiate{client_public_key=Value}) -> Value. %% @doc encode a ready command -spec encode_ready(SocketType::atom(), Identity::string(), Resource::string(), Metadata::map()) -> Data::binary(). encode_ready(SocketType, Identity, Resource, Metadata) when is_atom(SocketType) -> SocketTypeBin = string:to_upper(atom_to_list(SocketType)), Properties = lists:flatten([ {"Socket-Type", SocketTypeBin}, {"Identity", Identity}, {"Resource", Resource}, maps:to_list(Metadata) ]), PropertiesFrame = encode_ready_properties(Properties), <<5, "READY", PropertiesFrame/binary>>. %% %% Error command functions %% %% @doc returns the reason of error -spec error_reason(Command::error()) -> Reason::string(). error_reason(#error{reason=Reason}) -> Reason. %% @doc returns an encoded error command -spec encode_error(Reason::string()) -> Data::binary(). encode_error(Reason) when is_list(Reason) -> ReasonBin = list_to_binary(Reason), ReasonSize = byte_size(ReasonBin), <<5, "ERROR", ReasonSize, ReasonBin/binary>>. %% %% SUBSCRIBE functions %% %% @doc encode a subscribe command -spec encode_subscribe(Subscription::binary()) -> Command::binary(). encode_subscribe(Subscription) when is_binary(Subscription) -> <<9, "SUBSCRIBE", Subscription/binary>>. %% @doc return subscription of subscribe command -spec subscribe_subscription(Command::subscribe()) -> Subscription::binary(). subscribe_subscription(#subscribe{subscription=Subscription}) -> Subscription. %% @doc encode a cancel command -spec encode_cancel(Subscription::binary()) -> Command::binary(). encode_cancel(Subscription) when is_binary(Subscription) -> <<6, "CANCEL", Subscription/binary>>. %% @doc return subscription of cancel command -spec cancel_subscription(Command::cancel()) -> Subscription::binary(). cancel_subscription(#cancel{subscription=Subscription}) -> Subscription. %% Private API %% Both the 'curve' and the 'null' mechanism use a READY message. decode_message('READY', Body, #{mechanism := curve} = CurveData) -> try decode_curve_ready_message(Body, CurveData) of Result -> Result catch error:{badmatch,_Error} -> {error, wrong_ready_message} end; decode_message('READY', Body, SecurityData) -> try decode_ready_message(#ready{}, Body) of Message -> {ok, Message, SecurityData} catch error:{badmatch,_} -> {error, wrong_ready_message} end; decode_message('PING', _Body, SecurityData) -> {ok, #ping{}, SecurityData}; decode_message('ERROR', Body, SecurityData) -> try decode_error_message(Body) of Message -> {ok, Message, SecurityData} catch error:{badmatch,_} -> {error, wrong_error_message} end; decode_message('SUBSCRIBE', Body, SecurityData) -> {ok, #subscribe{subscription=Body}, SecurityData}; decode_message('CANCEL', Body, SecurityData) -> {ok, #cancel{subscription=Body}, SecurityData}; decode_message('HELLO', Body, CurveData) -> try decode_hello_message(Body, CurveData) of Result -> Result catch %% TODO: ensure that client is disconnected in case the command %% malformed. error:{badmatch,_} -> {error, wrong_hello_message} end; decode_message('WELCOME', Body, CurveData) -> try decode_welcome_message(Body, CurveData) of Result -> Result catch %% TODO: ensure that client is disconnected in case the command %% malformed. error:{badmatch,_} -> {error, wrong_welcome_message} end; decode_message('INITIATE', Body, CurveData) -> try decode_initiate_message(Body, CurveData) of Result -> Result catch %% TODO: ensure that client is disconnected in case the command %% malformed. error:{badmatch,_} -> {error, wrong_initiate_message} end; decode_message('MESSAGE', Body, CurveData) -> try decode_curve_message(Body, CurveData) of Result -> Result catch error:{badmatch,_} -> {error, wrong_message} end. %% Decode Ready message utils decode_ready_message(Command, Message) -> Properties = decode_ready_properties(Message), maps:fold(fun append_ready_property/3, Command, Properties). append_ready_property("socket-type", SocketType, ReadyCommand) -> ReadyCommand#ready{ socket_type=string:to_lower(SocketType) }; append_ready_property("identity", Identity, ReadyCommand) -> ReadyCommand#ready{identity=Identity}; append_ready_property("resource", Resource, ReadyCommand) -> ReadyCommand#ready{resource=Resource}; append_ready_property(Name, Value, #ready{metadata=MetaData}=ReadyCommand) -> ReadyCommand#ready{metadata=MetaData#{Name=>Value}}. decode_ready_properties(MetaData) -> decode_ready_properties(MetaData, #{}). decode_ready_properties(<<>>, Map) -> Map; decode_ready_properties(<<PropertyNameLen, Rest/binary>>, Map) -> <<PropertyName:PropertyNameLen/binary, PropertyValueLen:32, Rest2/binary>> = Rest, <<PropertyValue:PropertyValueLen/binary, Rest3/binary>> = Rest2, Name = string:to_lower(binary_to_list(PropertyName)), Value = binary_to_list(PropertyValue), decode_ready_properties(Rest3, Map#{Name => Value}). encode_ready_properties([]) -> <<"">>; %%encode_ready_properties([{_Name, ""}|Properties]) -> %%encode_ready_properties(Properties); encode_ready_properties([{Name, Value}|Properties]) -> NameBin = list_to_binary(Name), ValueBin = list_to_binary(Value), NameLen = byte_size(NameBin), ValueLen = byte_size(ValueBin), Tail = encode_ready_properties(Properties), <<NameLen, NameBin/binary, ValueLen:32, ValueBin/binary, Tail/binary>>. decode_error_message(Body) -> <<Size, RemaingBody/binary>> = Body, <<Reason:Size/binary>> = RemaingBody, #error{reason=binary_to_list(Reason)}. %% hello = %d5 "HELLO" version padding hello-client hello-nonce hello-box hello - version = % x1 % ; CurveZMQ major - minor version %% hello-padding = 72%x00 ; Anti-amplification padding %% hello-client = 32OCTET ; Client public transient key C' hello - nonce = 8OCTET ; Short nonce , prefixed by " " hello - box = 80OCTET ; Signature , Box [ 64 * % x0](C'->S ) decode_hello_message(<<1, 0, 0:72/integer-unit:8, ClientPublicTransientKey:32/binary, NonceBinary:8/binary, HelloBox:80/binary>>, #{curve_secretkey := ServerSecretPermanentKey} = CurveData) -> <<Nonce:8/integer-unit:8>> = NonceBinary, HelloNonceBinary = <<"CurveZMQHELLO---", NonceBinary/binary>>, %% TODO: Do something specific when decryption fails? {ok, <<0:64/integer-unit:8>>} = chumak_curve_if:box_open(HelloBox, HelloNonceBinary, ClientPublicTransientKey, ServerSecretPermanentKey), NewCurveData = CurveData#{client_nonce => Nonce, client_public_transient_key => ClientPublicTransientKey}, {ok, #hello{}, NewCurveData}. ; WELCOME command , 168 octets %% welcome = %d7 "WELCOME" welcome-nonce welcome-box welcome - nonce = 16OCTET ; Long nonce , prefixed by " WELCOME- " %% welcome-box = 144OCTET ; Box [S' + cookie](S->C') %% ; This is the text sent encrypted in the box %% cookie = cookie-nonce cookie-box cookie - nonce = 16OCTET ; Long nonce , prefixed by " " %% cookie-box = 80OCTET ; Box [C' + s'](K) decode_welcome_message(<<NonceBinary:16/binary, WelcomeBox:144/binary>>, #{client_secret_transient_key := ClientSecretTransientKey, curve_serverkey := ServerPublicPermanentKey } = CurveData) -> WelcomeNonceBinary = <<"WELCOME-", NonceBinary/binary>>, %% TODO: Do something specific when decryption fails? {ok, <<ServerPublicTransientKey:32/binary, Cookie:96/binary>>} = chumak_curve_if:box_open(WelcomeBox, WelcomeNonceBinary, ServerPublicPermanentKey, ClientSecretTransientKey), NewCurveData = CurveData#{server_public_transient_key => ServerPublicTransientKey, cookie => Cookie}, {ok, #welcome{}, NewCurveData}. ; INITIATE command , 257 + octets %% initiate = %d8 "INITIATE" cookie initiate-nonce initiate-box %% initiate-cookie = cookie ; Server-provided cookie %% initiate-nonce = 8OCTET ; Short nonce, prefixed by "CurveZMQINITIATE" %% initiate-box = 144*OCTET ; Box [C + vouch + metadata](C'->S') %% ; This is the text sent encrypted in the box %% vouch = vouch-nonce vouch-box %% vouch-nonce = 16OCTET ; Long nonce, prefixed by "VOUCH---" %% vouch-box = 80OCTET ; Box [C',S](C->S') %% metadata = *property %% property = name value %% name = OCTET *name-char %% name-char = ALPHA | DIGIT | "-" | "_" | "." | "+" %% value = value-size value-data value - size = 4OCTET ; Size in network order value - data = * OCTET ; 0 or more octets decode_initiate_message(<<CookieNonceBinary:16/binary, CookieBox:80/binary, NonceBinary:8/binary, InitiateBox/binary>>, #{ cookie_public_key := CookiePublicKey, cookie_secret_key := CookieSecretKey, client_nonce := OldClientNonce } = CurveData) -> <<Nonce:8/integer-unit:8>> = NonceBinary, true = (Nonce > OldClientNonce), %% The cookie contains the server's secret transient key and %% the client public transient key. CookieNonce = <<"COOKIE--", CookieNonceBinary/binary>>, {ok, <<ClientPublicTransientKey:32/binary, ServerSecretTransientKey:32/binary>>} = chumak_curve_if:box_open(CookieBox, CookieNonce, CookiePublicKey, CookieSecretKey), InitiateNonceBinary = <<"CurveZMQINITIATE", NonceBinary/binary>>, {ok, <<ClientPublicPermanentKey:32/binary, VouchNonceBinary:16/binary, VouchBox:80/binary, MetaData/binary>>} = chumak_curve_if:box_open(InitiateBox, InitiateNonceBinary, ClientPublicTransientKey, ServerSecretTransientKey), %% The vouch must be decoded using the client permanent key, %% so that we know that the client also has the secret key, and %% therefore is who he claims to be. The vouch box ( 80 octets ) encrypts the client 's transient key C ' ( 32 octets ) and the server permanent key S ( 32 octets ) from the %% client permanent key C to the server transient key S'. VouchNonce = <<"VOUCH---", VouchNonceBinary/binary>>, {ok, <<ClientPublicTransientKey:32/binary, _ServerPublicPermanentKey:32/binary>>} = chumak_curve_if:box_open(VouchBox, VouchNonce, ClientPublicPermanentKey, ServerSecretTransientKey), NewCurveData = CurveData#{client_nonce => Nonce, server_secret_transient_key => ServerSecretTransientKey, client_public_permanent_key => ClientPublicPermanentKey, client_public_transient_key => ClientPublicTransientKey, cookie_secret_key => <<>>, cookie_public_key => <<>>}, {ok, #initiate{metadata = decode_ready_properties(MetaData), client_public_key = ClientPublicPermanentKey}, NewCurveData}. ; READY command , 30 + octets %% ready = %d5 "READY" ready-nonce ready-box %% ready-nonce = 8OCTET ; Short nonce, prefixed by "CurveZMQREADY---" %% ready-box = 16*OCTET ; Box [metadata](S'->C') decode_curve_ready_message( <<NonceBinary:8/binary, ReadyBox/binary>>, #{server_public_transient_key := ServerPublicTransientKey, client_secret_transient_key := ClientSecretTransientKey } = CurveData) -> <<Nonce:8/integer-unit:8>> = NonceBinary, ReadyNonceBinary = <<"CurveZMQREADY---", NonceBinary/binary>>, {ok, MetaData} = chumak_curve_if:box_open(ReadyBox, ReadyNonceBinary, ServerPublicTransientKey, ClientSecretTransientKey), NewCurveData = CurveData#{server_nonce => Nonce}, {ok, #ready{metadata = decode_ready_properties(MetaData)}, NewCurveData}. ; MESSAGE command , 33 + octets %% message = %d7 "MESSAGE" message_nonce message-box %% message-nonce = 8OCTET ; Short nonce, prefixed by "CurveZMQMESSAGE-" message - box = 17*OCTET ; Box [ payload](S'->C ' ) or ( C'->S ' ) %% ; This is the text sent encrypted in the box %% payload = payload-flags payload-data %% payload-flags = OCTET ; Explained below payload - data = * octet ; 0 or more octets decode_curve_message( <<NonceBinary:8/binary, MessageBox/binary>>, #{role := server, client_public_transient_key := PublicKey, server_secret_transient_key := SecretKey, client_nonce := OldNonceValue } = CurveData) -> <<Nonce:8/integer-unit:8>> = NonceBinary, true = (Nonce > OldNonceValue), MessageNonce = <<"CurveZMQMESSAGEC", NonceBinary/binary>>, {ok, <<_, MessageData/binary>>} = chumak_curve_if:box_open(MessageBox, MessageNonce, PublicKey, SecretKey), NewCurveData = CurveData#{client_nonce => Nonce}, {ok, MessageData, NewCurveData}; decode_curve_message( <<NonceBinary:8/binary, MessageBox/binary>>, #{role := client, server_public_transient_key := PublicKey, client_secret_transient_key := SecretKey, server_nonce := OldNonceValue } = CurveData) -> <<Nonce:8/integer-unit:8>> = NonceBinary, true = (Nonce > OldNonceValue), MessageNonce = <<"CurveZMQMESSAGES", NonceBinary/binary>>, {ok, <<_, MessageData/binary>>} = chumak_curve_if:box_open(MessageBox, MessageNonce, PublicKey, SecretKey), NewCurveData = CurveData#{server_nonce => Nonce}, {ok, MessageData, NewCurveData}.
null
https://raw.githubusercontent.com/zeromq/chumak/e705fa6db05dc3f4801f5cc71eb18b0e60f7ba35/src/chumak_command.erl
erlang
ready command ping command error command subscribe command cancel command commands used in the curveZMQ handshake: CurveZMQ payload (messages) is also encoded as commands commands available Public API @doc decode reads incoming command and generate an command 'object' @doc returns the name of a command Ready command handler functions @doc return the socket type of a ready command @doc return the identity of a ready command @doc return the resource of a ready command @doc return the metadata of a ready command @doc return the metadata of an initiate command @doc return the public key of the client. This is an element of the INITIATE command. It can be used to identify the client. @doc encode a ready command Error command functions @doc returns the reason of error @doc returns an encoded error command SUBSCRIBE functions @doc encode a subscribe command @doc return subscription of subscribe command @doc encode a cancel command @doc return subscription of cancel command Private API Both the 'curve' and the 'null' mechanism use a READY message. TODO: ensure that client is disconnected in case the command malformed. TODO: ensure that client is disconnected in case the command malformed. TODO: ensure that client is disconnected in case the command malformed. Decode Ready message utils encode_ready_properties([{_Name, ""}|Properties]) -> encode_ready_properties(Properties); hello = %d5 "HELLO" version padding hello-client hello-nonce hello-box x1 % ; CurveZMQ major - minor version hello-padding = 72%x00 ; Anti-amplification padding hello-client = 32OCTET ; Client public transient key C' x0](C'->S ) TODO: Do something specific when decryption fails? welcome = %d7 "WELCOME" welcome-nonce welcome-box welcome-box = 144OCTET ; Box [S' + cookie](S->C') ; This is the text sent encrypted in the box cookie = cookie-nonce cookie-box cookie-box = 80OCTET ; Box [C' + s'](K) TODO: Do something specific when decryption fails? initiate = %d8 "INITIATE" cookie initiate-nonce initiate-box initiate-cookie = cookie ; Server-provided cookie initiate-nonce = 8OCTET ; Short nonce, prefixed by "CurveZMQINITIATE" initiate-box = 144*OCTET ; Box [C + vouch + metadata](C'->S') ; This is the text sent encrypted in the box vouch = vouch-nonce vouch-box vouch-nonce = 16OCTET ; Long nonce, prefixed by "VOUCH---" vouch-box = 80OCTET ; Box [C',S](C->S') metadata = *property property = name value name = OCTET *name-char name-char = ALPHA | DIGIT | "-" | "_" | "." | "+" value = value-size value-data The cookie contains the server's secret transient key and the client public transient key. The vouch must be decoded using the client permanent key, so that we know that the client also has the secret key, and therefore is who he claims to be. client permanent key C to the server transient key S'. ready = %d5 "READY" ready-nonce ready-box ready-nonce = 8OCTET ; Short nonce, prefixed by "CurveZMQREADY---" ready-box = 16*OCTET ; Box [metadata](S'->C') message = %d7 "MESSAGE" message_nonce message-box message-nonce = 8OCTET ; Short nonce, prefixed by "CurveZMQMESSAGE-" ; This is the text sent encrypted in the box payload = payload-flags payload-data payload-flags = OCTET ; Explained below
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. @doc Module responsible to decode and encode ZeroMQ commands -module(chumak_command). -include("chumak.hrl"). -export_type([command/0]). -export([decode/2, command_name/1, encode_ready/4, ready_socket_type/1, ready_identity/1, ready_resource/1, ready_metadata/1, initiate_metadata/1, initiate_client_key/1, encode_error/1, error_reason/1, encode_subscribe/1, subscribe_subscription/1, encode_cancel/1, cancel_subscription/1, encode_ready_properties/1 ]). -record(ready, { socket_type=nil :: nil | string(), identity="" :: string(), resource="" :: string(), metadata=#{} :: map() }). -record(ping, {}). -record(error, {reason :: string()}). -record(subscribe, {subscription :: binary()}). -record(cancel, {subscription :: binary()}). -record(hello, {}). -record(welcome, {}). -record(initiate, {metadata = #{} :: map(), client_public_key :: binary()}). -record(message, {}). -type hello() :: #hello{}. -type welcome() :: #welcome{}. -type initiate() :: #initiate{}. -type message() :: #message{}. -type command() :: ready() | ping() | error() | subscribe() | cancel() | hello() | welcome() | initiate() | ready() | message(). -type ready_decode_error() :: wrong_ready_message. -type decode_error() :: ready_decode_error(). -spec decode(Frame::chumak_protocol:frame(), CurveData::chumak_curve:curve_data()) -> {ok, Command::command(), NewCurveData::chumak_curve:curve_data()} | {error, decode_error()}. decode(Frame, CurveData) -> <<CommandNameByteSize, Frame2/binary>> = Frame, CommandNameBitSize = 8 * CommandNameByteSize, <<CommandName:CommandNameBitSize/bitstring, CommandBody/binary>> = Frame2, decode_message(binary_to_atom(CommandName, utf8), CommandBody, CurveData). -spec command_name(Command::command()) -> Name::atom(). command_name(Command) -> element(1, Command). -spec ready_socket_type(Command::ready()) -> SocketType::atom(). ready_socket_type(#ready{socket_type=SocketType}) -> SocketType. -spec ready_identity(Command::ready()) -> Identity::string(). ready_identity(#ready{identity=Identity}) -> Identity. -spec ready_resource(Command::ready()) -> Resource::string(). ready_resource(#ready{resource=Resource}) -> Resource. -spec ready_metadata(Command::ready()) -> Metadata::map(). ready_metadata(#ready{metadata=Metadata}) -> Metadata. -spec initiate_metadata(Command::initiate()) -> Metadata::map(). initiate_metadata(#initiate{metadata=Metadata}) -> Metadata. -spec initiate_client_key(Command::initiate()) -> Key::binary(). initiate_client_key(#initiate{client_public_key=Value}) -> Value. -spec encode_ready(SocketType::atom(), Identity::string(), Resource::string(), Metadata::map()) -> Data::binary(). encode_ready(SocketType, Identity, Resource, Metadata) when is_atom(SocketType) -> SocketTypeBin = string:to_upper(atom_to_list(SocketType)), Properties = lists:flatten([ {"Socket-Type", SocketTypeBin}, {"Identity", Identity}, {"Resource", Resource}, maps:to_list(Metadata) ]), PropertiesFrame = encode_ready_properties(Properties), <<5, "READY", PropertiesFrame/binary>>. -spec error_reason(Command::error()) -> Reason::string(). error_reason(#error{reason=Reason}) -> Reason. -spec encode_error(Reason::string()) -> Data::binary(). encode_error(Reason) when is_list(Reason) -> ReasonBin = list_to_binary(Reason), ReasonSize = byte_size(ReasonBin), <<5, "ERROR", ReasonSize, ReasonBin/binary>>. -spec encode_subscribe(Subscription::binary()) -> Command::binary(). encode_subscribe(Subscription) when is_binary(Subscription) -> <<9, "SUBSCRIBE", Subscription/binary>>. -spec subscribe_subscription(Command::subscribe()) -> Subscription::binary(). subscribe_subscription(#subscribe{subscription=Subscription}) -> Subscription. -spec encode_cancel(Subscription::binary()) -> Command::binary(). encode_cancel(Subscription) when is_binary(Subscription) -> <<6, "CANCEL", Subscription/binary>>. -spec cancel_subscription(Command::cancel()) -> Subscription::binary(). cancel_subscription(#cancel{subscription=Subscription}) -> Subscription. decode_message('READY', Body, #{mechanism := curve} = CurveData) -> try decode_curve_ready_message(Body, CurveData) of Result -> Result catch error:{badmatch,_Error} -> {error, wrong_ready_message} end; decode_message('READY', Body, SecurityData) -> try decode_ready_message(#ready{}, Body) of Message -> {ok, Message, SecurityData} catch error:{badmatch,_} -> {error, wrong_ready_message} end; decode_message('PING', _Body, SecurityData) -> {ok, #ping{}, SecurityData}; decode_message('ERROR', Body, SecurityData) -> try decode_error_message(Body) of Message -> {ok, Message, SecurityData} catch error:{badmatch,_} -> {error, wrong_error_message} end; decode_message('SUBSCRIBE', Body, SecurityData) -> {ok, #subscribe{subscription=Body}, SecurityData}; decode_message('CANCEL', Body, SecurityData) -> {ok, #cancel{subscription=Body}, SecurityData}; decode_message('HELLO', Body, CurveData) -> try decode_hello_message(Body, CurveData) of Result -> Result catch error:{badmatch,_} -> {error, wrong_hello_message} end; decode_message('WELCOME', Body, CurveData) -> try decode_welcome_message(Body, CurveData) of Result -> Result catch error:{badmatch,_} -> {error, wrong_welcome_message} end; decode_message('INITIATE', Body, CurveData) -> try decode_initiate_message(Body, CurveData) of Result -> Result catch error:{badmatch,_} -> {error, wrong_initiate_message} end; decode_message('MESSAGE', Body, CurveData) -> try decode_curve_message(Body, CurveData) of Result -> Result catch error:{badmatch,_} -> {error, wrong_message} end. decode_ready_message(Command, Message) -> Properties = decode_ready_properties(Message), maps:fold(fun append_ready_property/3, Command, Properties). append_ready_property("socket-type", SocketType, ReadyCommand) -> ReadyCommand#ready{ socket_type=string:to_lower(SocketType) }; append_ready_property("identity", Identity, ReadyCommand) -> ReadyCommand#ready{identity=Identity}; append_ready_property("resource", Resource, ReadyCommand) -> ReadyCommand#ready{resource=Resource}; append_ready_property(Name, Value, #ready{metadata=MetaData}=ReadyCommand) -> ReadyCommand#ready{metadata=MetaData#{Name=>Value}}. decode_ready_properties(MetaData) -> decode_ready_properties(MetaData, #{}). decode_ready_properties(<<>>, Map) -> Map; decode_ready_properties(<<PropertyNameLen, Rest/binary>>, Map) -> <<PropertyName:PropertyNameLen/binary, PropertyValueLen:32, Rest2/binary>> = Rest, <<PropertyValue:PropertyValueLen/binary, Rest3/binary>> = Rest2, Name = string:to_lower(binary_to_list(PropertyName)), Value = binary_to_list(PropertyValue), decode_ready_properties(Rest3, Map#{Name => Value}). encode_ready_properties([]) -> <<"">>; encode_ready_properties([{Name, Value}|Properties]) -> NameBin = list_to_binary(Name), ValueBin = list_to_binary(Value), NameLen = byte_size(NameBin), ValueLen = byte_size(ValueBin), Tail = encode_ready_properties(Properties), <<NameLen, NameBin/binary, ValueLen:32, ValueBin/binary, Tail/binary>>. decode_error_message(Body) -> <<Size, RemaingBody/binary>> = Body, <<Reason:Size/binary>> = RemaingBody, #error{reason=binary_to_list(Reason)}. hello - nonce = 8OCTET ; Short nonce , prefixed by " " decode_hello_message(<<1, 0, 0:72/integer-unit:8, ClientPublicTransientKey:32/binary, NonceBinary:8/binary, HelloBox:80/binary>>, #{curve_secretkey := ServerSecretPermanentKey} = CurveData) -> <<Nonce:8/integer-unit:8>> = NonceBinary, HelloNonceBinary = <<"CurveZMQHELLO---", NonceBinary/binary>>, {ok, <<0:64/integer-unit:8>>} = chumak_curve_if:box_open(HelloBox, HelloNonceBinary, ClientPublicTransientKey, ServerSecretPermanentKey), NewCurveData = CurveData#{client_nonce => Nonce, client_public_transient_key => ClientPublicTransientKey}, {ok, #hello{}, NewCurveData}. ; WELCOME command , 168 octets welcome - nonce = 16OCTET ; Long nonce , prefixed by " WELCOME- " cookie - nonce = 16OCTET ; Long nonce , prefixed by " " decode_welcome_message(<<NonceBinary:16/binary, WelcomeBox:144/binary>>, #{client_secret_transient_key := ClientSecretTransientKey, curve_serverkey := ServerPublicPermanentKey } = CurveData) -> WelcomeNonceBinary = <<"WELCOME-", NonceBinary/binary>>, {ok, <<ServerPublicTransientKey:32/binary, Cookie:96/binary>>} = chumak_curve_if:box_open(WelcomeBox, WelcomeNonceBinary, ServerPublicPermanentKey, ClientSecretTransientKey), NewCurveData = CurveData#{server_public_transient_key => ServerPublicTransientKey, cookie => Cookie}, {ok, #welcome{}, NewCurveData}. ; INITIATE command , 257 + octets value - size = 4OCTET ; Size in network order value - data = * OCTET ; 0 or more octets decode_initiate_message(<<CookieNonceBinary:16/binary, CookieBox:80/binary, NonceBinary:8/binary, InitiateBox/binary>>, #{ cookie_public_key := CookiePublicKey, cookie_secret_key := CookieSecretKey, client_nonce := OldClientNonce } = CurveData) -> <<Nonce:8/integer-unit:8>> = NonceBinary, true = (Nonce > OldClientNonce), CookieNonce = <<"COOKIE--", CookieNonceBinary/binary>>, {ok, <<ClientPublicTransientKey:32/binary, ServerSecretTransientKey:32/binary>>} = chumak_curve_if:box_open(CookieBox, CookieNonce, CookiePublicKey, CookieSecretKey), InitiateNonceBinary = <<"CurveZMQINITIATE", NonceBinary/binary>>, {ok, <<ClientPublicPermanentKey:32/binary, VouchNonceBinary:16/binary, VouchBox:80/binary, MetaData/binary>>} = chumak_curve_if:box_open(InitiateBox, InitiateNonceBinary, ClientPublicTransientKey, ServerSecretTransientKey), The vouch box ( 80 octets ) encrypts the client 's transient key C ' ( 32 octets ) and the server permanent key S ( 32 octets ) from the VouchNonce = <<"VOUCH---", VouchNonceBinary/binary>>, {ok, <<ClientPublicTransientKey:32/binary, _ServerPublicPermanentKey:32/binary>>} = chumak_curve_if:box_open(VouchBox, VouchNonce, ClientPublicPermanentKey, ServerSecretTransientKey), NewCurveData = CurveData#{client_nonce => Nonce, server_secret_transient_key => ServerSecretTransientKey, client_public_permanent_key => ClientPublicPermanentKey, client_public_transient_key => ClientPublicTransientKey, cookie_secret_key => <<>>, cookie_public_key => <<>>}, {ok, #initiate{metadata = decode_ready_properties(MetaData), client_public_key = ClientPublicPermanentKey}, NewCurveData}. ; READY command , 30 + octets decode_curve_ready_message( <<NonceBinary:8/binary, ReadyBox/binary>>, #{server_public_transient_key := ServerPublicTransientKey, client_secret_transient_key := ClientSecretTransientKey } = CurveData) -> <<Nonce:8/integer-unit:8>> = NonceBinary, ReadyNonceBinary = <<"CurveZMQREADY---", NonceBinary/binary>>, {ok, MetaData} = chumak_curve_if:box_open(ReadyBox, ReadyNonceBinary, ServerPublicTransientKey, ClientSecretTransientKey), NewCurveData = CurveData#{server_nonce => Nonce}, {ok, #ready{metadata = decode_ready_properties(MetaData)}, NewCurveData}. ; MESSAGE command , 33 + octets message - box = 17*OCTET ; Box [ payload](S'->C ' ) or ( C'->S ' ) payload - data = * octet ; 0 or more octets decode_curve_message( <<NonceBinary:8/binary, MessageBox/binary>>, #{role := server, client_public_transient_key := PublicKey, server_secret_transient_key := SecretKey, client_nonce := OldNonceValue } = CurveData) -> <<Nonce:8/integer-unit:8>> = NonceBinary, true = (Nonce > OldNonceValue), MessageNonce = <<"CurveZMQMESSAGEC", NonceBinary/binary>>, {ok, <<_, MessageData/binary>>} = chumak_curve_if:box_open(MessageBox, MessageNonce, PublicKey, SecretKey), NewCurveData = CurveData#{client_nonce => Nonce}, {ok, MessageData, NewCurveData}; decode_curve_message( <<NonceBinary:8/binary, MessageBox/binary>>, #{role := client, server_public_transient_key := PublicKey, client_secret_transient_key := SecretKey, server_nonce := OldNonceValue } = CurveData) -> <<Nonce:8/integer-unit:8>> = NonceBinary, true = (Nonce > OldNonceValue), MessageNonce = <<"CurveZMQMESSAGES", NonceBinary/binary>>, {ok, <<_, MessageData/binary>>} = chumak_curve_if:box_open(MessageBox, MessageNonce, PublicKey, SecretKey), NewCurveData = CurveData#{server_nonce => Nonce}, {ok, MessageData, NewCurveData}.
297b8312c3e323f9d43771687e4e967b641ed5c91df1bd5b1b750f2be0e125de
aryx/xix
spinlock_.ml
open Types (* we can not put this type in concurrency/ because of mutual deps * between locks and a proc *) type t = { hold: bool ref; (* debugging and defensive programming fields *) less : opti : direct reference to Proc.t instead of pid really ' pid option ' but for init kernel code we use the pid 0 , the * one in Globals.fakeproc assigned initially to Globals.up . * one in Globals.fakeproc assigned initially to Globals.up. *) mutable p: pid; less : debugging fields * pc : ; * pc: kern_addr; *) }
null
https://raw.githubusercontent.com/aryx/xix/60ce1bd9a3f923e0e8bb2192f8938a9aa49c739c/kernel/core/spinlock_.ml
ocaml
we can not put this type in concurrency/ because of mutual deps * between locks and a proc debugging and defensive programming fields
open Types type t = { hold: bool ref; less : opti : direct reference to Proc.t instead of pid really ' pid option ' but for init kernel code we use the pid 0 , the * one in Globals.fakeproc assigned initially to Globals.up . * one in Globals.fakeproc assigned initially to Globals.up. *) mutable p: pid; less : debugging fields * pc : ; * pc: kern_addr; *) }
7f42fb49d0e5771dcfb53f84a81373b1c2adb53c7dc43dc08f9627f3148a0e66
static-analysis-engineering/codehawk
bCHPowerAssemblyInstructions.mli
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Binary Analyzer Author : ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2022 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 Binary Analyzer Author: Henny Sipma ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2022 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. ============================================================================= *) (* bchlib *) open BCHLibTypes (* bchlibpower32 *) open BCHPowerTypes val power_assembly_instructions: power_assembly_instructions_int ref val initialize_power_instructions: int -> unit val initialize_power_assembly_instructions: int (* length in bytes of the combined executable sections *) -> doubleword_int (* address of code base *) -> unit
null
https://raw.githubusercontent.com/static-analysis-engineering/codehawk/d2e83cef7430defdc4cf30fc1495fe4ff64d9f9d/CodeHawk/CHB/bchlibpower32/bCHPowerAssemblyInstructions.mli
ocaml
bchlib bchlibpower32 length in bytes of the combined executable sections address of code base
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Binary Analyzer Author : ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2022 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 Binary Analyzer Author: Henny Sipma ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2022 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. ============================================================================= *) open BCHLibTypes open BCHPowerTypes val power_assembly_instructions: power_assembly_instructions_int ref val initialize_power_instructions: int -> unit val initialize_power_assembly_instructions: -> unit
89684d1d97bd3ef49733068dbeb09cd676386359e609be0db751167b8f009d6f
dfinity-side-projects/winter
Kind.hs
# LANGUAGE KindSignatures # module Wasm.Syntax.Ops.Kind where import Data.Kind (Type) data Unary :: Type data Binary :: Type data Test :: Type data Compare :: Type data Convert :: Type
null
https://raw.githubusercontent.com/dfinity-side-projects/winter/cca827ab9299146c0b3b51920e5ad63c4c6014c3/src/Wasm/Syntax/Ops/Kind.hs
haskell
# LANGUAGE KindSignatures # module Wasm.Syntax.Ops.Kind where import Data.Kind (Type) data Unary :: Type data Binary :: Type data Test :: Type data Compare :: Type data Convert :: Type
b72117fc03b9c22e27b222972cd52c1e4a6e3a00a5cef3b85037710bfc1e6aec
yetanalytics/datasim
repl.clj
(ns com.yetanalytics.datasim.onyx.repl "Cluster repl" (:require clojure.main rebel-readline.core rebel-readline.clojure.line-reader rebel-readline.clojure.service.local rebel-readline.clojure.main)) (defn repl! [] (rebel-readline.core/with-line-reader (rebel-readline.clojure.line-reader/create (rebel-readline.clojure.service.local/create)) (clojure.main/repl :prompt (fn []) ;; prompt is handled by line-reader :read (rebel-readline.clojure.main/create-repl-read))))
null
https://raw.githubusercontent.com/yetanalytics/datasim/0047cb3123e32b72380ea31ec98a26ef85543b63/src/onyx/com/yetanalytics/datasim/onyx/repl.clj
clojure
prompt is handled by line-reader
(ns com.yetanalytics.datasim.onyx.repl "Cluster repl" (:require clojure.main rebel-readline.core rebel-readline.clojure.line-reader rebel-readline.clojure.service.local rebel-readline.clojure.main)) (defn repl! [] (rebel-readline.core/with-line-reader (rebel-readline.clojure.line-reader/create (rebel-readline.clojure.service.local/create)) (clojure.main/repl :read (rebel-readline.clojure.main/create-repl-read))))
45a0eb66b2c6fd0d7a4629ccdb8de981ffe09258500670bb763e7f6e04e9032c
vindarel/ABStock
api.lisp
(in-package :abstock) ;; ;; Routes for the API. ;; (easy-routes:defroute api-selection-route ("/api/v1/selection.json" :method :get) () (setf (hunchentoot:content-type*) "application/json") (jojo:to-json *selection*)) (easy-routes:defroute api-newly-created-route ("/api/v1/lastcreated.json" :method :get) () (setf (hunchentoot:content-type*) "application/json") (jojo:to-json (last-created-cards))) (defcached (search-cards-with-cache :timeout (* 60 5)) (query) "Search cards in stock with keywords. Results are cached for 5min." (search-cards query)) (easy-routes:defroute api-search-route ("/api/v1/search.json" :method :get) (query all) "Search with keywords. If `all' is non-blank, return all cards in stock." (setf (hunchentoot:content-type*) "application/json") (cond ((str:non-blank-string-p all) (jojo:to-json (search-cards-with-cache ""))) (t (jojo:to-json (if (str:non-blank-string-p query) (search-cards-with-cache query) (values))))))
null
https://raw.githubusercontent.com/vindarel/ABStock/25edc5ebac5eac40378936a597300116d2a37337/src/api.lisp
lisp
Routes for the API.
(in-package :abstock) (easy-routes:defroute api-selection-route ("/api/v1/selection.json" :method :get) () (setf (hunchentoot:content-type*) "application/json") (jojo:to-json *selection*)) (easy-routes:defroute api-newly-created-route ("/api/v1/lastcreated.json" :method :get) () (setf (hunchentoot:content-type*) "application/json") (jojo:to-json (last-created-cards))) (defcached (search-cards-with-cache :timeout (* 60 5)) (query) "Search cards in stock with keywords. Results are cached for 5min." (search-cards query)) (easy-routes:defroute api-search-route ("/api/v1/search.json" :method :get) (query all) "Search with keywords. If `all' is non-blank, return all cards in stock." (setf (hunchentoot:content-type*) "application/json") (cond ((str:non-blank-string-p all) (jojo:to-json (search-cards-with-cache ""))) (t (jojo:to-json (if (str:non-blank-string-p query) (search-cards-with-cache query) (values))))))
3ef67e184a1375f0a744bf57ecc33a9b1f06424f8ed4267cf8349f5f5bb0eed7
okeuday/erlbench
mochinum.erl
2007 Mochi Media , Inc. @author < > %% @doc Useful numeric algorithms for floats that cover some deficiencies %% in the math module. More interesting is digits/1, which implements %% the algorithm from: %% /~burger/fp/index.html See also " Printing Floating - Point Numbers Quickly and Accurately " in Proceedings of the SIGPLAN ' 96 Conference on Programming Language %% Design and Implementation. -module(mochinum). -author("Bob Ippolito <>"). -export([digits/1, frexp/1, int_pow/2, int_ceil/1]). IEEE 754 Float exponent bias -define(FLOAT_BIAS, 1022). -define(MIN_EXP, -1074). -define(BIG_POW, 4503599627370496). %% External API ( ) ) - > string ( ) %% @doc Returns a string that accurately represents the given integer or float %% using a conservative amount of digits. Great for generating %% human-readable output, or compact ASCII serializations for floats. digits(N) when is_integer(N) -> integer_to_list(N); digits(0.0) -> "0.0"; digits(Float) -> {Frac, Exp} = frexp(Float), Exp1 = Exp - 53, Frac1 = trunc(abs(Frac) * (1 bsl 53)), [Place | Digits] = digits1(Float, Exp1, Frac1), R = insert_decimal(Place, [$0 + D || D <- Digits]), case Float < 0 of true -> [$- | R]; _ -> R end. @spec frexp(F::float ( ) ) - > { Frac::float ( ) , ( ) } %% @doc Return the fractional and exponent part of an IEEE 754 double, %% equivalent to the libc function of the same name. %% F = Frac * pow(2, Exp). frexp(F) -> frexp1(unpack(F)). ( ) , N::integer ( ) ) - > Y::integer ( ) %% @doc Moderately efficient way to exponentiate integers. int_pow(10 , 2 ) = 100 . int_pow(_X, 0) -> 1; int_pow(X, N) when N > 0 -> int_pow(X, N, 1). @spec int_ceil(F::float ( ) ) - > integer ( ) %% @doc Return the ceiling of F as an integer. The ceiling is defined as %% F when F == trunc(F); trunc(F ) when F & lt ; 0 ; trunc(F ) + 1 when F & gt ; 0 . int_ceil(X) -> T = trunc(X), case (X - T) of Neg when Neg < 0 -> T; Pos when Pos > 0 -> T + 1; _ -> T end. %% Internal API int_pow(X, N, R) when N < 2 -> R * X; int_pow(X, N, R) -> int_pow(X * X, N bsr 1, case N band 1 of 1 -> R * X; 0 -> R end). insert_decimal(0, S) -> "0." ++ S; insert_decimal(Place, S) when Place > 0 -> L = length(S), case Place - L of 0 -> S ++ ".0"; N when N < 0 -> {S0, S1} = lists:split(L + N, S), S0 ++ "." ++ S1; N when N < 6 -> %% More places than digits S ++ lists:duplicate(N, $0) ++ ".0"; _ -> insert_decimal_exp(Place, S) end; insert_decimal(Place, S) when Place > -6 -> "0." ++ lists:duplicate(abs(Place), $0) ++ S; insert_decimal(Place, S) -> insert_decimal_exp(Place, S). insert_decimal_exp(Place, S) -> [C | S0] = S, S1 = case S0 of [] -> "0"; _ -> S0 end, Exp = case Place < 0 of true -> "e-"; false -> "e+" end, [C] ++ "." ++ S1 ++ Exp ++ integer_to_list(abs(Place - 1)). digits1(Float, Exp, Frac) -> Round = ((Frac band 1) =:= 0), case Exp >= 0 of true -> BExp = 1 bsl Exp, case (Frac =/= ?BIG_POW) of true -> scale((Frac * BExp * 2), 2, BExp, BExp, Round, Round, Float); false -> scale((Frac * BExp * 4), 4, (BExp * 2), BExp, Round, Round, Float) end; false -> case (Exp =:= ?MIN_EXP) orelse (Frac =/= ?BIG_POW) of true -> scale((Frac * 2), 1 bsl (1 - Exp), 1, 1, Round, Round, Float); false -> scale((Frac * 4), 1 bsl (2 - Exp), 2, 1, Round, Round, Float) end end. scale(R, S, MPlus, MMinus, LowOk, HighOk, Float) -> Est = int_ceil(math:log10(abs(Float)) - 1.0e-10), Note that the scheme implementation uses a 326 element look - up table %% for int_pow(10, N) where we do not. case Est >= 0 of true -> fixup(R, S * int_pow(10, Est), MPlus, MMinus, Est, LowOk, HighOk); false -> Scale = int_pow(10, -Est), fixup(R * Scale, S, MPlus * Scale, MMinus * Scale, Est, LowOk, HighOk) end. fixup(R, S, MPlus, MMinus, K, LowOk, HighOk) -> TooLow = case HighOk of true -> (R + MPlus) >= S; false -> (R + MPlus) > S end, case TooLow of true -> [(K + 1) | generate(R, S, MPlus, MMinus, LowOk, HighOk)]; false -> [K | generate(R * 10, S, MPlus * 10, MMinus * 10, LowOk, HighOk)] end. generate(R0, S, MPlus, MMinus, LowOk, HighOk) -> D = R0 div S, R = R0 rem S, TC1 = case LowOk of true -> R =< MMinus; false -> R < MMinus end, TC2 = case HighOk of true -> (R + MPlus) >= S; false -> (R + MPlus) > S end, case TC1 of false -> case TC2 of false -> [D | generate(R * 10, S, MPlus * 10, MMinus * 10, LowOk, HighOk)]; true -> [D + 1] end; true -> case TC2 of false -> [D]; true -> case R * 2 < S of true -> [D]; false -> [D + 1] end end end. unpack(Float) -> <<Sign:1, Exp:11, Frac:52>> = <<Float:64/float>>, {Sign, Exp, Frac}. frexp1({_Sign, 0, 0}) -> {0.0, 0}; frexp1({Sign, 0, Frac}) -> Exp = log2floor(Frac), <<Frac1:64/float>> = <<Sign:1, ?FLOAT_BIAS:11, (Frac-1):52>>, {Frac1, -(?FLOAT_BIAS) - 52 + Exp}; frexp1({Sign, Exp, Frac}) -> <<Frac1:64/float>> = <<Sign:1, ?FLOAT_BIAS:11, Frac:52>>, {Frac1, Exp - ?FLOAT_BIAS}. log2floor(Int) -> log2floor(Int, 0). log2floor(0, N) -> N; log2floor(Int, N) -> log2floor(Int bsr 1, 1 + N). %% %% Tests %% -include_lib("eunit/include/eunit.hrl"). -ifdef(TEST). int_ceil_test() -> 1 = int_ceil(0.0001), 0 = int_ceil(0.0), 1 = int_ceil(0.99), 1 = int_ceil(1.0), -1 = int_ceil(-1.5), -2 = int_ceil(-2.0), ok. int_pow_test() -> 1 = int_pow(1, 1), 1 = int_pow(1, 0), 1 = int_pow(10, 0), 10 = int_pow(10, 1), 100 = int_pow(10, 2), 1000 = int_pow(10, 3), ok. digits_test() -> ?assertEqual("0", digits(0)), ?assertEqual("0.0", digits(0.0)), ?assertEqual("1.0", digits(1.0)), ?assertEqual("-1.0", digits(-1.0)), ?assertEqual("0.1", digits(0.1)), ?assertEqual("0.01", digits(0.01)), ?assertEqual("0.001", digits(0.001)), ?assertEqual("1.0e+6", digits(1000000.0)), ?assertEqual("0.5", digits(0.5)), ?assertEqual("4503599627370496.0", digits(4503599627370496.0)), small denormalized number 4.94065645841246544177e-324 <<SmallDenorm/float>> = <<0,0,0,0,0,0,0,1>>, ?assertEqual("4.9406564584124654e-324", digits(SmallDenorm)), ?assertEqual(SmallDenorm, list_to_float(digits(SmallDenorm))), large denormalized number 2.22507385850720088902e-308 <<BigDenorm/float>> = <<0,15,255,255,255,255,255,255>>, ?assertEqual("2.225073858507201e-308", digits(BigDenorm)), ?assertEqual(BigDenorm, list_to_float(digits(BigDenorm))), %% small normalized number 2.22507385850720138309e-308 <<SmallNorm/float>> = <<0,16,0,0,0,0,0,0>>, ?assertEqual("2.2250738585072014e-308", digits(SmallNorm)), ?assertEqual(SmallNorm, list_to_float(digits(SmallNorm))), %% large normalized number 1.79769313486231570815e+308 <<LargeNorm/float>> = <<127,239,255,255,255,255,255,255>>, ?assertEqual("1.7976931348623157e+308", digits(LargeNorm)), ?assertEqual(LargeNorm, list_to_float(digits(LargeNorm))), ok. frexp_test() -> zero {0.0, 0} = frexp(0.0), one {0.5, 1} = frexp(1.0), %% negative one {-0.5, 1} = frexp(-1.0), small denormalized number 4.94065645841246544177e-324 <<SmallDenorm/float>> = <<0,0,0,0,0,0,0,1>>, {0.5, -1073} = frexp(SmallDenorm), large denormalized number 2.22507385850720088902e-308 <<BigDenorm/float>> = <<0,15,255,255,255,255,255,255>>, {0.99999999999999978, -1022} = frexp(BigDenorm), %% small normalized number 2.22507385850720138309e-308 <<SmallNorm/float>> = <<0,16,0,0,0,0,0,0>>, {0.5, -1021} = frexp(SmallNorm), %% large normalized number 1.79769313486231570815e+308 <<LargeNorm/float>> = <<127,239,255,255,255,255,255,255>>, {0.99999999999999989, 1024} = frexp(LargeNorm), ok. -endif.
null
https://raw.githubusercontent.com/okeuday/erlbench/9fc02a2e748b287b85f6e9641db6b2ca68791fa4/src/mochinum.erl
erlang
@doc Useful numeric algorithms for floats that cover some deficiencies in the math module. More interesting is digits/1, which implements the algorithm from: /~burger/fp/index.html Design and Implementation. External API @doc Returns a string that accurately represents the given integer or float using a conservative amount of digits. Great for generating human-readable output, or compact ASCII serializations for floats. @doc Return the fractional and exponent part of an IEEE 754 double, equivalent to the libc function of the same name. F = Frac * pow(2, Exp). @doc Moderately efficient way to exponentiate integers. @doc Return the ceiling of F as an integer. The ceiling is defined as F when F == trunc(F); Internal API More places than digits for int_pow(10, N) where we do not. Tests small normalized number large normalized number negative one small normalized number large normalized number
2007 Mochi Media , Inc. @author < > See also " Printing Floating - Point Numbers Quickly and Accurately " in Proceedings of the SIGPLAN ' 96 Conference on Programming Language -module(mochinum). -author("Bob Ippolito <>"). -export([digits/1, frexp/1, int_pow/2, int_ceil/1]). IEEE 754 Float exponent bias -define(FLOAT_BIAS, 1022). -define(MIN_EXP, -1074). -define(BIG_POW, 4503599627370496). ( ) ) - > string ( ) digits(N) when is_integer(N) -> integer_to_list(N); digits(0.0) -> "0.0"; digits(Float) -> {Frac, Exp} = frexp(Float), Exp1 = Exp - 53, Frac1 = trunc(abs(Frac) * (1 bsl 53)), [Place | Digits] = digits1(Float, Exp1, Frac1), R = insert_decimal(Place, [$0 + D || D <- Digits]), case Float < 0 of true -> [$- | R]; _ -> R end. @spec frexp(F::float ( ) ) - > { Frac::float ( ) , ( ) } frexp(F) -> frexp1(unpack(F)). ( ) , N::integer ( ) ) - > Y::integer ( ) int_pow(10 , 2 ) = 100 . int_pow(_X, 0) -> 1; int_pow(X, N) when N > 0 -> int_pow(X, N, 1). @spec int_ceil(F::float ( ) ) - > integer ( ) trunc(F ) when F & lt ; 0 ; trunc(F ) + 1 when F & gt ; 0 . int_ceil(X) -> T = trunc(X), case (X - T) of Neg when Neg < 0 -> T; Pos when Pos > 0 -> T + 1; _ -> T end. int_pow(X, N, R) when N < 2 -> R * X; int_pow(X, N, R) -> int_pow(X * X, N bsr 1, case N band 1 of 1 -> R * X; 0 -> R end). insert_decimal(0, S) -> "0." ++ S; insert_decimal(Place, S) when Place > 0 -> L = length(S), case Place - L of 0 -> S ++ ".0"; N when N < 0 -> {S0, S1} = lists:split(L + N, S), S0 ++ "." ++ S1; N when N < 6 -> S ++ lists:duplicate(N, $0) ++ ".0"; _ -> insert_decimal_exp(Place, S) end; insert_decimal(Place, S) when Place > -6 -> "0." ++ lists:duplicate(abs(Place), $0) ++ S; insert_decimal(Place, S) -> insert_decimal_exp(Place, S). insert_decimal_exp(Place, S) -> [C | S0] = S, S1 = case S0 of [] -> "0"; _ -> S0 end, Exp = case Place < 0 of true -> "e-"; false -> "e+" end, [C] ++ "." ++ S1 ++ Exp ++ integer_to_list(abs(Place - 1)). digits1(Float, Exp, Frac) -> Round = ((Frac band 1) =:= 0), case Exp >= 0 of true -> BExp = 1 bsl Exp, case (Frac =/= ?BIG_POW) of true -> scale((Frac * BExp * 2), 2, BExp, BExp, Round, Round, Float); false -> scale((Frac * BExp * 4), 4, (BExp * 2), BExp, Round, Round, Float) end; false -> case (Exp =:= ?MIN_EXP) orelse (Frac =/= ?BIG_POW) of true -> scale((Frac * 2), 1 bsl (1 - Exp), 1, 1, Round, Round, Float); false -> scale((Frac * 4), 1 bsl (2 - Exp), 2, 1, Round, Round, Float) end end. scale(R, S, MPlus, MMinus, LowOk, HighOk, Float) -> Est = int_ceil(math:log10(abs(Float)) - 1.0e-10), Note that the scheme implementation uses a 326 element look - up table case Est >= 0 of true -> fixup(R, S * int_pow(10, Est), MPlus, MMinus, Est, LowOk, HighOk); false -> Scale = int_pow(10, -Est), fixup(R * Scale, S, MPlus * Scale, MMinus * Scale, Est, LowOk, HighOk) end. fixup(R, S, MPlus, MMinus, K, LowOk, HighOk) -> TooLow = case HighOk of true -> (R + MPlus) >= S; false -> (R + MPlus) > S end, case TooLow of true -> [(K + 1) | generate(R, S, MPlus, MMinus, LowOk, HighOk)]; false -> [K | generate(R * 10, S, MPlus * 10, MMinus * 10, LowOk, HighOk)] end. generate(R0, S, MPlus, MMinus, LowOk, HighOk) -> D = R0 div S, R = R0 rem S, TC1 = case LowOk of true -> R =< MMinus; false -> R < MMinus end, TC2 = case HighOk of true -> (R + MPlus) >= S; false -> (R + MPlus) > S end, case TC1 of false -> case TC2 of false -> [D | generate(R * 10, S, MPlus * 10, MMinus * 10, LowOk, HighOk)]; true -> [D + 1] end; true -> case TC2 of false -> [D]; true -> case R * 2 < S of true -> [D]; false -> [D + 1] end end end. unpack(Float) -> <<Sign:1, Exp:11, Frac:52>> = <<Float:64/float>>, {Sign, Exp, Frac}. frexp1({_Sign, 0, 0}) -> {0.0, 0}; frexp1({Sign, 0, Frac}) -> Exp = log2floor(Frac), <<Frac1:64/float>> = <<Sign:1, ?FLOAT_BIAS:11, (Frac-1):52>>, {Frac1, -(?FLOAT_BIAS) - 52 + Exp}; frexp1({Sign, Exp, Frac}) -> <<Frac1:64/float>> = <<Sign:1, ?FLOAT_BIAS:11, Frac:52>>, {Frac1, Exp - ?FLOAT_BIAS}. log2floor(Int) -> log2floor(Int, 0). log2floor(0, N) -> N; log2floor(Int, N) -> log2floor(Int bsr 1, 1 + N). -include_lib("eunit/include/eunit.hrl"). -ifdef(TEST). int_ceil_test() -> 1 = int_ceil(0.0001), 0 = int_ceil(0.0), 1 = int_ceil(0.99), 1 = int_ceil(1.0), -1 = int_ceil(-1.5), -2 = int_ceil(-2.0), ok. int_pow_test() -> 1 = int_pow(1, 1), 1 = int_pow(1, 0), 1 = int_pow(10, 0), 10 = int_pow(10, 1), 100 = int_pow(10, 2), 1000 = int_pow(10, 3), ok. digits_test() -> ?assertEqual("0", digits(0)), ?assertEqual("0.0", digits(0.0)), ?assertEqual("1.0", digits(1.0)), ?assertEqual("-1.0", digits(-1.0)), ?assertEqual("0.1", digits(0.1)), ?assertEqual("0.01", digits(0.01)), ?assertEqual("0.001", digits(0.001)), ?assertEqual("1.0e+6", digits(1000000.0)), ?assertEqual("0.5", digits(0.5)), ?assertEqual("4503599627370496.0", digits(4503599627370496.0)), small denormalized number 4.94065645841246544177e-324 <<SmallDenorm/float>> = <<0,0,0,0,0,0,0,1>>, ?assertEqual("4.9406564584124654e-324", digits(SmallDenorm)), ?assertEqual(SmallDenorm, list_to_float(digits(SmallDenorm))), large denormalized number 2.22507385850720088902e-308 <<BigDenorm/float>> = <<0,15,255,255,255,255,255,255>>, ?assertEqual("2.225073858507201e-308", digits(BigDenorm)), ?assertEqual(BigDenorm, list_to_float(digits(BigDenorm))), 2.22507385850720138309e-308 <<SmallNorm/float>> = <<0,16,0,0,0,0,0,0>>, ?assertEqual("2.2250738585072014e-308", digits(SmallNorm)), ?assertEqual(SmallNorm, list_to_float(digits(SmallNorm))), 1.79769313486231570815e+308 <<LargeNorm/float>> = <<127,239,255,255,255,255,255,255>>, ?assertEqual("1.7976931348623157e+308", digits(LargeNorm)), ?assertEqual(LargeNorm, list_to_float(digits(LargeNorm))), ok. frexp_test() -> zero {0.0, 0} = frexp(0.0), one {0.5, 1} = frexp(1.0), {-0.5, 1} = frexp(-1.0), small denormalized number 4.94065645841246544177e-324 <<SmallDenorm/float>> = <<0,0,0,0,0,0,0,1>>, {0.5, -1073} = frexp(SmallDenorm), large denormalized number 2.22507385850720088902e-308 <<BigDenorm/float>> = <<0,15,255,255,255,255,255,255>>, {0.99999999999999978, -1022} = frexp(BigDenorm), 2.22507385850720138309e-308 <<SmallNorm/float>> = <<0,16,0,0,0,0,0,0>>, {0.5, -1021} = frexp(SmallNorm), 1.79769313486231570815e+308 <<LargeNorm/float>> = <<127,239,255,255,255,255,255,255>>, {0.99999999999999989, 1024} = frexp(LargeNorm), ok. -endif.
3584b74329be505ec36148f0d82c523dedd137ef6258781e0c6e89e10498e25a
richcarl/eunit
eunit_test.erl
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. %% %% Alternatively, you may use this file under the terms of the GNU Lesser General Public License ( the " LGPL " ) as published by the Free Software Foundation ; either version 2.1 , or ( at your option ) any later version . %% If you wish to allow use of your version of this file only under the %% terms of the LGPL, you should delete the provisions above and replace %% them with the notice and other provisions required by the LGPL; see %% </>. If you do not delete the provisions %% above, a recipient may use your version of this file under the terms of either the Apache License or the LGPL . %% @author < > 2006 @private %% @see eunit %% @doc Test running functionality -module(eunit_test). -export([run_testfun/1, mf_wrapper/2, enter_context/4, multi_setup/1]). -include("eunit.hrl"). -include("eunit_internal.hrl"). %% --------------------------------------------------------------------- %% Getting a cleaned up stack trace. (We don't want it to include %% eunit's own internal functions. This complicates self-testing %% somewhat, but you can't have everything.) Note that we assume that %% this particular module is the boundary between eunit and user code. get_stacktrace() -> get_stacktrace([]). get_stacktrace(Ts) -> eunit_lib:uniq(prune_trace(erlang:get_stacktrace(), Ts)). prune_trace([{eunit_data, _, _} | Rest], Tail) -> prune_trace(Rest, Tail); prune_trace([{eunit_data, _, _, _} | Rest], Tail) -> prune_trace(Rest, Tail); prune_trace([{?MODULE, _, _} | _Rest], Tail) -> Tail; prune_trace([{?MODULE, _, _, _} | _Rest], Tail) -> Tail; prune_trace([T | Ts], Tail) -> [T | prune_trace(Ts, Tail)]; prune_trace([], Tail) -> Tail. %% --------------------------------------------------------------------- %% Test runner ( ( any ( ) ) - > any ( ) ) - > { ok , Value } | { error , eunit_lib : exception ( ) } %% @throws wrapperError() run_testfun(F) -> try F() of Value -> {ok, Value} catch {eunit_internal, Term} -> %% Internally generated: re-throw Term (lose the trace) throw(Term); Class:Reason -> {error, {Class, Reason, get_stacktrace()}} end. -ifdef(TEST). macro_test_() -> {"macro definitions", [{?LINE, fun () -> {?LINE, F} = ?_test(undefined), {ok, undefined} = run_testfun(F) end}, ?_test(begin {?LINE, F} = ?_assert(true), {ok, ok} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assert(false), {error,{error,{assertion_failed, [{module,_}, {line,_}, {expression,_}, {expected,true}, {value,false}]}, _}} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assert([]), {error,{error,{assertion_failed, [{module,_}, {line,_}, {expression,_}, {expected,true}, {value,{not_a_boolean,[]}}]}, _}} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertNot(false), {ok, ok} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertNot(true), {error,{error,{assertion_failed, [{module,_}, {line,_}, {expression,_}, {expected,true}, {value,false}]}, _}} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertMatch(ok, ok), {ok, ok} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertMatch([_], []), {error,{error,{assertMatch_failed, [{module,_}, {line,_}, {expression,_}, {pattern,"[ _ ]"}, {value,[]}]}, _}} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertNotMatch(ok, error), {ok, ok} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertNotMatch([_], [42]), {error,{error,{assertNotMatch_failed, [{module,_}, {line,_}, {expression,_}, {pattern,"[ _ ]"}, {value,[42]}]}, _}} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertEqual(ok, ok), {ok, ok} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertEqual(3, 1+1), {error,{error,{assertEqual_failed, [{module,_}, {line,_}, {expression,_}, {expected,3}, {value,2}]}, _}} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertNotEqual(1, 0), {ok, ok} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertNotEqual(2, 1+1), {error,{error,{assertNotEqual_failed, [{module,_}, {line,_}, {expression,_}, {value,2}]}, _}} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertException(error, badarith, erlang:error(badarith)), {ok, ok} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertException(error, badarith, ok), {error,{error,{assertException_failed, [{module,_}, {line,_}, {expression,_}, {pattern,_}, {unexpected_success,ok}]}, _}} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertException(error, badarg, erlang:error(badarith)), {error,{error,{assertException_failed, [{module,_}, {line,_}, {expression,_}, {pattern,_}, {unexpected_exception, {error,badarith,_}}]}, _}} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertError(badarith, erlang:error(badarith)), {ok, ok} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertExit(normal, exit(normal)), {ok, ok} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertThrow(foo, throw(foo)), {ok, ok} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertNotException(error, badarith, 42), {ok, ok} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertNotException(error, badarith, erlang:error(badarg)), {ok, ok} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertNotException(error, badarith, erlang:error(badarith)), {error,{error,{assertNotException_failed, [{module,_}, {line,_}, {expression,_}, {pattern,_}, {unexpected_exception, {error,badarith,_}}]}, _}} = run_testfun(F) end) ]}. -endif. %% --------------------------------------------------------------------- %% Wrapper for simple "named function" tests ({M,F}), which provides %% better error reporting when the function is missing at test time. %% %% Note that the wrapper fun is usually called by run_testfun/1, and the %% special exceptions thrown here are expected to be handled there. %% @throws { eunit_internal , wrapperError ( ) } %% @type wrapperError ( ) = { no_such_function , ( ) } %% | {module_not_found, moduleName()} mf_wrapper(M, F) -> fun () -> try M:F() catch error:undef -> %% Check if it was M:F/0 that was undefined case erlang:module_loaded(M) of false -> fail({module_not_found, M}); true -> case erlang:function_exported(M, F, 0) of false -> fail({no_such_function, {M,F,0}}); true -> rethrow(error, undef, [{M,F,0}]) end end end end. rethrow(Class, Reason, Trace) -> erlang:raise(Class, Reason, get_stacktrace(Trace)). fail(Term) -> throw({eunit_internal, Term}). -ifdef(TEST). wrapper_test_() -> {"error handling in function wrapper", [?_assertException(throw, {module_not_found, eunit_nonexisting}, run_testfun(mf_wrapper(eunit_nonexisting,test))), ?_assertException(throw, {no_such_function, {?MODULE,nonexisting_test,0}}, run_testfun(mf_wrapper(?MODULE,nonexisting_test))), ?_test({error, {error, undef, _T}} = run_testfun(mf_wrapper(?MODULE,wrapper_test_exported_))) ]}. %% this must be exported (done automatically by the autoexport transform) wrapper_test_exported_() -> {ok, ?MODULE:nonexisting_function()}. -endif. %% --------------------------------------------------------------------- %% Entering a setup-context, with guaranteed cleanup. %% @spec (Setup, Cleanup, Instantiate, Callback) -> any() %% Setup = () -> any() %% Cleanup = (any()) -> any() %% Instantiate = (any()) -> tests() %% Callback = (tests()) -> any() %% @throws {context_error, Error, eunit_lib:exception()} %% Error = setup_failed | instantiation_failed | cleanup_failed enter_context(Setup, Cleanup, Instantiate, Callback) -> try Setup() of R -> try Instantiate(R) of T -> case eunit_lib:is_not_test(T) of true -> catch throw(error), % generate a stack trace {module,M} = erlang:fun_info(Instantiate, module), {name,N} = erlang:fun_info(Instantiate, name), {arity,A} = erlang:fun_info(Instantiate, arity), context_error({bad_instantiator, {{M,N,A},T}}, error, badarg); false -> ok end, try Callback(T) %% call back to client code after %% Always run cleanup; client may be an idiot try Cleanup(R) catch Class:Term -> context_error(cleanup_failed, Class, Term) end end catch Class:Term -> context_error(instantiation_failed, Class, Term) end catch Class:Term -> context_error(setup_failed, Class, Term) end. context_error(Type, Class, Term) -> throw({context_error, Type, {Class, Term, get_stacktrace()}}). %% This generates single setup/cleanup functions from a list of tuples %% on the form {Tag, Setup, Cleanup}, where the setup function always %% backs out correctly from partial completion. multi_setup(List) -> {SetupAll, CleanupAll} = multi_setup(List, fun ok/1), %% must reverse back and forth here in order to present the list in %% "natural" order to the test instantiation function {fun () -> lists:reverse(SetupAll([])) end, fun (Rs) -> CleanupAll(lists:reverse(Rs)) end}. multi_setup([{Tag, S, C} | Es], CleanupPrev) -> Cleanup = fun ([R | Rs]) -> try C(R) of _ -> CleanupPrev(Rs) catch Class:Term -> throw({Tag, {Class, Term, get_stacktrace()}}) end end, {SetupRest, CleanupAll} = multi_setup(Es, Cleanup), {fun (Rs) -> try S() of R -> SetupRest([R|Rs]) catch Class:Term -> CleanupPrev(Rs), throw({Tag, {Class, Term, get_stacktrace()}}) end end, CleanupAll}; multi_setup([{Tag, S} | Es], CleanupPrev) -> multi_setup([{Tag, S, fun ok/1} | Es], CleanupPrev); multi_setup([], CleanupAll) -> {fun (Rs) -> Rs end, CleanupAll}. ok(_) -> ok.
null
https://raw.githubusercontent.com/richcarl/eunit/cb7eb2bc2cec01e405c717b6f6b551be7d256f06/src/eunit_test.erl
erlang
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. Alternatively, you may use this file under the terms of the GNU Lesser If you wish to allow use of your version of this file only under the terms of the LGPL, you should delete the provisions above and replace them with the notice and other provisions required by the LGPL; see </>. If you do not delete the provisions above, a recipient may use your version of this file under the terms of @see eunit @doc Test running functionality --------------------------------------------------------------------- Getting a cleaned up stack trace. (We don't want it to include eunit's own internal functions. This complicates self-testing somewhat, but you can't have everything.) Note that we assume that this particular module is the boundary between eunit and user code. --------------------------------------------------------------------- Test runner @throws wrapperError() Internally generated: re-throw Term (lose the trace) --------------------------------------------------------------------- Wrapper for simple "named function" tests ({M,F}), which provides better error reporting when the function is missing at test time. Note that the wrapper fun is usually called by run_testfun/1, and the special exceptions thrown here are expected to be handled there. | {module_not_found, moduleName()} Check if it was M:F/0 that was undefined this must be exported (done automatically by the autoexport transform) --------------------------------------------------------------------- Entering a setup-context, with guaranteed cleanup. @spec (Setup, Cleanup, Instantiate, Callback) -> any() Setup = () -> any() Cleanup = (any()) -> any() Instantiate = (any()) -> tests() Callback = (tests()) -> any() @throws {context_error, Error, eunit_lib:exception()} Error = setup_failed | instantiation_failed | cleanup_failed generate a stack trace call back to client code Always run cleanup; client may be an idiot This generates single setup/cleanup functions from a list of tuples on the form {Tag, Setup, Cleanup}, where the setup function always backs out correctly from partial completion. must reverse back and forth here in order to present the list in "natural" order to the test instantiation function
Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may distributed under the License is distributed on an " AS IS " BASIS , General Public License ( the " LGPL " ) as published by the Free Software Foundation ; either version 2.1 , or ( at your option ) any later version . either the Apache License or the LGPL . @author < > 2006 @private -module(eunit_test). -export([run_testfun/1, mf_wrapper/2, enter_context/4, multi_setup/1]). -include("eunit.hrl"). -include("eunit_internal.hrl"). get_stacktrace() -> get_stacktrace([]). get_stacktrace(Ts) -> eunit_lib:uniq(prune_trace(erlang:get_stacktrace(), Ts)). prune_trace([{eunit_data, _, _} | Rest], Tail) -> prune_trace(Rest, Tail); prune_trace([{eunit_data, _, _, _} | Rest], Tail) -> prune_trace(Rest, Tail); prune_trace([{?MODULE, _, _} | _Rest], Tail) -> Tail; prune_trace([{?MODULE, _, _, _} | _Rest], Tail) -> Tail; prune_trace([T | Ts], Tail) -> [T | prune_trace(Ts, Tail)]; prune_trace([], Tail) -> Tail. ( ( any ( ) ) - > any ( ) ) - > { ok , Value } | { error , eunit_lib : exception ( ) } run_testfun(F) -> try F() of Value -> {ok, Value} catch {eunit_internal, Term} -> throw(Term); Class:Reason -> {error, {Class, Reason, get_stacktrace()}} end. -ifdef(TEST). macro_test_() -> {"macro definitions", [{?LINE, fun () -> {?LINE, F} = ?_test(undefined), {ok, undefined} = run_testfun(F) end}, ?_test(begin {?LINE, F} = ?_assert(true), {ok, ok} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assert(false), {error,{error,{assertion_failed, [{module,_}, {line,_}, {expression,_}, {expected,true}, {value,false}]}, _}} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assert([]), {error,{error,{assertion_failed, [{module,_}, {line,_}, {expression,_}, {expected,true}, {value,{not_a_boolean,[]}}]}, _}} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertNot(false), {ok, ok} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertNot(true), {error,{error,{assertion_failed, [{module,_}, {line,_}, {expression,_}, {expected,true}, {value,false}]}, _}} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertMatch(ok, ok), {ok, ok} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertMatch([_], []), {error,{error,{assertMatch_failed, [{module,_}, {line,_}, {expression,_}, {pattern,"[ _ ]"}, {value,[]}]}, _}} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertNotMatch(ok, error), {ok, ok} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertNotMatch([_], [42]), {error,{error,{assertNotMatch_failed, [{module,_}, {line,_}, {expression,_}, {pattern,"[ _ ]"}, {value,[42]}]}, _}} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertEqual(ok, ok), {ok, ok} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertEqual(3, 1+1), {error,{error,{assertEqual_failed, [{module,_}, {line,_}, {expression,_}, {expected,3}, {value,2}]}, _}} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertNotEqual(1, 0), {ok, ok} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertNotEqual(2, 1+1), {error,{error,{assertNotEqual_failed, [{module,_}, {line,_}, {expression,_}, {value,2}]}, _}} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertException(error, badarith, erlang:error(badarith)), {ok, ok} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertException(error, badarith, ok), {error,{error,{assertException_failed, [{module,_}, {line,_}, {expression,_}, {pattern,_}, {unexpected_success,ok}]}, _}} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertException(error, badarg, erlang:error(badarith)), {error,{error,{assertException_failed, [{module,_}, {line,_}, {expression,_}, {pattern,_}, {unexpected_exception, {error,badarith,_}}]}, _}} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertError(badarith, erlang:error(badarith)), {ok, ok} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertExit(normal, exit(normal)), {ok, ok} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertThrow(foo, throw(foo)), {ok, ok} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertNotException(error, badarith, 42), {ok, ok} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertNotException(error, badarith, erlang:error(badarg)), {ok, ok} = run_testfun(F) end), ?_test(begin {?LINE, F} = ?_assertNotException(error, badarith, erlang:error(badarith)), {error,{error,{assertNotException_failed, [{module,_}, {line,_}, {expression,_}, {pattern,_}, {unexpected_exception, {error,badarith,_}}]}, _}} = run_testfun(F) end) ]}. -endif. @throws { eunit_internal , wrapperError ( ) } @type wrapperError ( ) = { no_such_function , ( ) } mf_wrapper(M, F) -> fun () -> try M:F() catch error:undef -> case erlang:module_loaded(M) of false -> fail({module_not_found, M}); true -> case erlang:function_exported(M, F, 0) of false -> fail({no_such_function, {M,F,0}}); true -> rethrow(error, undef, [{M,F,0}]) end end end end. rethrow(Class, Reason, Trace) -> erlang:raise(Class, Reason, get_stacktrace(Trace)). fail(Term) -> throw({eunit_internal, Term}). -ifdef(TEST). wrapper_test_() -> {"error handling in function wrapper", [?_assertException(throw, {module_not_found, eunit_nonexisting}, run_testfun(mf_wrapper(eunit_nonexisting,test))), ?_assertException(throw, {no_such_function, {?MODULE,nonexisting_test,0}}, run_testfun(mf_wrapper(?MODULE,nonexisting_test))), ?_test({error, {error, undef, _T}} = run_testfun(mf_wrapper(?MODULE,wrapper_test_exported_))) ]}. wrapper_test_exported_() -> {ok, ?MODULE:nonexisting_function()}. -endif. enter_context(Setup, Cleanup, Instantiate, Callback) -> try Setup() of R -> try Instantiate(R) of T -> case eunit_lib:is_not_test(T) of true -> {module,M} = erlang:fun_info(Instantiate, module), {name,N} = erlang:fun_info(Instantiate, name), {arity,A} = erlang:fun_info(Instantiate, arity), context_error({bad_instantiator, {{M,N,A},T}}, error, badarg); false -> ok end, after try Cleanup(R) catch Class:Term -> context_error(cleanup_failed, Class, Term) end end catch Class:Term -> context_error(instantiation_failed, Class, Term) end catch Class:Term -> context_error(setup_failed, Class, Term) end. context_error(Type, Class, Term) -> throw({context_error, Type, {Class, Term, get_stacktrace()}}). multi_setup(List) -> {SetupAll, CleanupAll} = multi_setup(List, fun ok/1), {fun () -> lists:reverse(SetupAll([])) end, fun (Rs) -> CleanupAll(lists:reverse(Rs)) end}. multi_setup([{Tag, S, C} | Es], CleanupPrev) -> Cleanup = fun ([R | Rs]) -> try C(R) of _ -> CleanupPrev(Rs) catch Class:Term -> throw({Tag, {Class, Term, get_stacktrace()}}) end end, {SetupRest, CleanupAll} = multi_setup(Es, Cleanup), {fun (Rs) -> try S() of R -> SetupRest([R|Rs]) catch Class:Term -> CleanupPrev(Rs), throw({Tag, {Class, Term, get_stacktrace()}}) end end, CleanupAll}; multi_setup([{Tag, S} | Es], CleanupPrev) -> multi_setup([{Tag, S, fun ok/1} | Es], CleanupPrev); multi_setup([], CleanupAll) -> {fun (Rs) -> Rs end, CleanupAll}. ok(_) -> ok.
7cf6e873685d7bb04a1ea6e872801f6022a71c38f5a492e45a5513f2c1cf4151
rowangithub/DOrder
boolFormula.ml
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author : * Copyright reserved * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: Bow-Yaw Wang * Copyright reserved *****************************************************************************) type var_t = int type lit_t = int type t = Lit of lit_t | Not of t | And of t array | Or of t array let is_positive l = let _ = assert (l <> 0) in l > 0 let of_var l = let _ = assert (l <> 0) in abs l let rec from_boolformula_t f = match Cdnfp.get_type f with | Cdnfp.Lit -> let cdnf_lit = Cdnfp.get_literal f in let cdnf_var = Cdnfp.var_of_literal cdnf_lit in Lit (if Cdnfp.positive_literal cdnf_lit then cdnf_var else - cdnf_var) | Cdnfp.And | Cdnfp.Or -> let n_args = Cdnfp.get_length f in let args = let helper i = from_boolformula_t (Cdnfp.get_boolformula f i) in Array.init n_args helper in if Cdnfp.get_type f = Cdnfp.And then And args else Or args let rec from_clauses res in_chan nvars nclauses = let rec helper res l = let _ = assert (abs l <= nvars) in if l = 0 then res else Scanf.fscanf in_chan " %d" (helper (l::res)) in if nclauses = 0 then (nvars, And (Array.of_list res)) else let ls = Scanf.fscanf in_chan " %d" (helper []) in let clause = Or (Array.of_list (List.rev_map (fun l -> Lit l) ls)) in from_clauses (clause::res) in_chan nvars (pred nclauses) let from_dimacs in_chan = let rec helper () = let line = try input_line in_chan with End_of_file -> "" in if String.length line = 0 then (0, And [| |]) else match line.[0] with | 'c' -> helper () | 'p' -> let _ = assert (String.sub line 0 5 = "p cnf") in Scanf.sscanf line "p cnf %d %d" (from_clauses [] in_chan) | _ -> assert false in helper () let rec print boolf = match boolf with | Lit l -> print_int l | Not arg -> (print_string "(!"; print arg; print_string ")") | And args | Or args -> let length = Array.length args in if length = 0 then print_string (match boolf with | And _ -> "T" | Or _ -> "F" | _ -> assert false) else let helper op i arg = (print arg; if i < length - 1 then print_string op else ()) in let op = match boolf with | And _ -> " & " | Or _ -> " | " | _ -> assert false in print_string "("; Array.iteri (helper op) args; print_string ")"
null
https://raw.githubusercontent.com/rowangithub/DOrder/e0d5efeb8853d2a51cc4796d7db0f8be3185d7df/learning/cdnf/boolFormula.ml
ocaml
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author : * Copyright reserved * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: Bow-Yaw Wang * Copyright reserved *****************************************************************************) type var_t = int type lit_t = int type t = Lit of lit_t | Not of t | And of t array | Or of t array let is_positive l = let _ = assert (l <> 0) in l > 0 let of_var l = let _ = assert (l <> 0) in abs l let rec from_boolformula_t f = match Cdnfp.get_type f with | Cdnfp.Lit -> let cdnf_lit = Cdnfp.get_literal f in let cdnf_var = Cdnfp.var_of_literal cdnf_lit in Lit (if Cdnfp.positive_literal cdnf_lit then cdnf_var else - cdnf_var) | Cdnfp.And | Cdnfp.Or -> let n_args = Cdnfp.get_length f in let args = let helper i = from_boolformula_t (Cdnfp.get_boolformula f i) in Array.init n_args helper in if Cdnfp.get_type f = Cdnfp.And then And args else Or args let rec from_clauses res in_chan nvars nclauses = let rec helper res l = let _ = assert (abs l <= nvars) in if l = 0 then res else Scanf.fscanf in_chan " %d" (helper (l::res)) in if nclauses = 0 then (nvars, And (Array.of_list res)) else let ls = Scanf.fscanf in_chan " %d" (helper []) in let clause = Or (Array.of_list (List.rev_map (fun l -> Lit l) ls)) in from_clauses (clause::res) in_chan nvars (pred nclauses) let from_dimacs in_chan = let rec helper () = let line = try input_line in_chan with End_of_file -> "" in if String.length line = 0 then (0, And [| |]) else match line.[0] with | 'c' -> helper () | 'p' -> let _ = assert (String.sub line 0 5 = "p cnf") in Scanf.sscanf line "p cnf %d %d" (from_clauses [] in_chan) | _ -> assert false in helper () let rec print boolf = match boolf with | Lit l -> print_int l | Not arg -> (print_string "(!"; print arg; print_string ")") | And args | Or args -> let length = Array.length args in if length = 0 then print_string (match boolf with | And _ -> "T" | Or _ -> "F" | _ -> assert false) else let helper op i arg = (print arg; if i < length - 1 then print_string op else ()) in let op = match boolf with | And _ -> " & " | Or _ -> " | " | _ -> assert false in print_string "("; Array.iteri (helper op) args; print_string ")"
0430a00e52a3f5d7b7b3b3098465ac29f514c255a3e07aec645b1b28300e6342
plexus/cljs-test-example
main.cljs
(ns basic-shadow.main) (js/console.log "*hacker voice* I'm in")
null
https://raw.githubusercontent.com/plexus/cljs-test-example/0ad2ba200f52edd65f822b48c8be276a484ca1f8/shadow-browser/src/basic_shadow/main.cljs
clojure
(ns basic-shadow.main) (js/console.log "*hacker voice* I'm in")
a9769aa1d016cad0c5bc514450e18884724d6f560a532cd6a898938078fcacaf
technoblogy/ulisp-builder
prettyprint.lisp
;;;-*- Mode: Lisp; Package: cl-user -*- (in-package :cl-user) and tree editor (defparameter *prettyprint* '( #" // Prettyprint"# #-(or badge gfx) #" const int PPINDENT = 2; const int PPWIDTH = 80;"# #+badge #" const int PPINDENT = 2; const int PPWIDTH = 42;"# #+gfx #" const int PPINDENT = 2; const int PPWIDTH = 80; // 320 pixel wide screen int ppwidth = PPWIDTH;"# #" void pcount (char c) { if (c == '\n') PrintCount++; PrintCount++; } /* atomwidth - calculates the character width of an atom */ uint8_t atomwidth (object *obj) { PrintCount = 0; printobject(obj, pcount); return PrintCount; } uint8_t basewidth (object *obj, uint8_t base) { PrintCount = 0; pintbase(obj->integer, base, pcount); return PrintCount; } bool quoted (object *obj) { return (consp(obj) && car(obj) != NULL && car(obj)->name == sym(QUOTE) && consp(cdr(obj)) && cddr(obj) == NULL); } int subwidth (object *obj, int w) { if (atom(obj)) return w - atomwidth(obj); if (quoted(obj)) obj = car(cdr(obj)); return subwidthlist(obj, w - 1); } int subwidthlist (object *form, int w) { while (form != NULL && w >= 0) { if (atom(form)) return w - (2 + atomwidth(form)); w = subwidth(car(form), w - 1); form = cdr(form); } return w; }"# #-gfx #" /* superprint - the main pretty-print subroutine */ void superprint (object *form, int lm, pfun_t pfun) { if (atom(form)) { if (symbolp(form) && form->name == sym(NOTHING)) printsymbol(form, pfun); else printobject(form, pfun); } else if (quoted(form)) { pfun('\''); superprint(car(cdr(form)), lm + 1, pfun); } else if (subwidth(form, PPWIDTH - lm) >= 0) supersub(form, lm + PPINDENT, 0, pfun); else supersub(form, lm + PPINDENT, 1, pfun); }"# #+gfx #" /* superprint - the main pretty-print subroutine */ void superprint (object *form, int lm, pfun_t pfun) { if (atom(form)) { if (symbolp(form) && form->name == sym(NOTHING)) printsymbol(form, pfun); else printobject(form, pfun); } else if (quoted(form)) { pfun('\''); superprint(car(cdr(form)), lm + 1, pfun); } else if (subwidth(form, ppwidth - lm) >= 0) supersub(form, lm + PPINDENT, 0, pfun); else supersub(form, lm + PPINDENT, 1, pfun); }"# #+(and avr (not badge)) #" const int ppspecials = 16; const char ppspecial[ppspecials] PROGMEM = { DOTIMES, DOLIST, IF, SETQ, TEE, LET, LETSTAR, LAMBDA, WHEN, UNLESS, WITHI2C, WITHSERIAL, WITHSPI, WITHSDCARD, FORMILLIS, DEFVAR }; /* supersub - subroutine used by pprint */ void supersub (object *form, int lm, int super, pfun_t pfun) { int special = 0, separate = 1; object *arg = car(form); if (symbolp(arg)) { symbol_t sname = arg->name; #if defined(CODESIZE) if (sname == sym(DEFUN) || sname == sym(DEFCODE)) special = 2; #else if (sname == sym(DEFUN)) special = 2; #endif else for (int i=0; i<ppspecials; i++) { #if defined(CPU_ATmega4809) if (sname == sym(ppspecial[i])) { special = 1; break; } #else if (sname == sym((builtin_t)pgm_read_byte(&ppspecial[i]))) { special = 1; break; } #endif } } while (form != NULL) { printobject(form , pfun ) ; pfun ( ' ) ' ) ; return ; } separate = 0 ; } else if (special) { pfun(' '); special--; } else if (!super) pfun(' '); indent(lm , ' ' , pfun ) ; } superprint(car(form), lm, pfun); form = cdr(form); } pfun(')'); return; }"# #+arm #" const int ppspecials = 20; const char ppspecial[ppspecials] PROGMEM = { DOTIMES, DOLIST, IF, SETQ, TEE, LET, LETSTAR, LAMBDA, WHEN, UNLESS, WITHI2C, WITHSERIAL, WITHSPI, WITHSDCARD, FORMILLIS, WITHOUTPUTTOSTRING, DEFVAR, CASE, WITHGFX, WITHCLIENT }; /* supersub - subroutine used by pprint */ void supersub (object *form, int lm, int super, pfun_t pfun) { int special = 0, separate = 1; object *arg = car(form); if (symbolp(arg)) { symbol_t sname = arg->name; if (sname == sym(DEFUN) || sname == sym(DEFCODE)) special = 2; else for (int i=0; i<ppspecials; i++) { if (sname == sym((builtin_t)ppspecial[i])) { special = 1; break; } } } while (form != NULL) { printobject(form , pfun ) ; pfun ( ' ) ' ) ; return ; } separate = 0 ; } else if (special) { pfun(' '); special--; } else if (!super) pfun(' '); indent(lm , ' ' , pfun ) ; } superprint(car(form), lm, pfun); form = cdr(form); } pfun(')'); return; }"# #+riscv #" const int ppspecials = 19; const char ppspecial[ppspecials] PROGMEM = { DOTIMES, DOLIST, IF, SETQ, TEE, LET, LETSTAR, LAMBDA, WHEN, UNLESS, WITHI2C, WITHSERIAL, WITHSPI, WITHSDCARD, FORMILLIS, WITHOUTPUTTOSTRING, DEFVAR, CASE, WITHGFX }; /* supersub - subroutine used by pprint */ void supersub (object *form, int lm, int super, pfun_t pfun) { int special = 0, separate = 1; object *arg = car(form); if (symbolp(arg)) { symbol_t sname = arg->name; if (sname == sym(DEFUN) || sname == sym(DEFCODE)) special = 2; else for (int i=0; i<ppspecials; i++) { if (sname == sym((builtin_t)ppspecial[i])) { special = 1; break; } } } while (form != NULL) { printobject(form , pfun ) ; pfun ( ' ) ' ) ; return ; } separate = 0 ; } else if (special) { pfun(' '); special--; } else if (!super) pfun(' '); indent(lm , ' ' , pfun ) ; } superprint(car(form), lm, pfun); form = cdr(form); } pfun(')'); return; }"# #+msp430 #" const int ppspecials = 16; const char ppspecial[ppspecials] PROGMEM = { DOTIMES, DOLIST, IF, SETQ, TEE, LET, LETSTAR, LAMBDA, WHEN, UNLESS, WITHI2C, WITHSERIAL, WITHSPI, WITHSDCARD, FORMILLIS, WITHLCD }; /* supersub - subroutine used by pprint */ void supersub (object *form, int lm, int super, pfun_t pfun) { int special = 0, separate = 1; object *arg = car(form); if (symbolp(arg)) { int name = arg->name; if (name == DEFUN) special = 2; else for (int i=0; i<ppspecials; i++) { if (name == pgm_read_byte(&ppspecial[i])) { special = 1; break; } } } while (form != NULL) { printobject(form , pfun ) ; pfun ( ' ) ' ) ; return ; } separate = 0 ; } else if (special) { pfun(' '); special--; } else if (!super) pfun(' '); indent(lm , ' ' , pfun ) ; } superprint(car(form), lm, pfun); form = cdr(form); } pfun(')'); return; }"# #+badge #" const int ppspecials = 15; const uint8_t ppspecial[ppspecials] PROGMEM = { DOTIMES, DOLIST, IF, SETQ, TEE, LET, LETSTAR, LAMBDA, WHEN, UNLESS, WITHI2C, WITHSERIAL, WITHSPI, WITHSDCARD, FORMILLIS }; /* supersub - subroutine used by pprint */ void supersub (object *form, int lm, int super, pfun_t pfun) { int special = 0, separate = 1; object *arg = car(form); if (symbolp(arg)) { int name = arg->name; #if defined(CODESIZE) if (name == DEFUN || name == DEFCODE) special = 2; #else if (name == DEFUN) special = 2; #endif else for (int i=0; i<ppspecials; i++) { if (name == pgm_read_byte(&ppspecial[i])) { special = 1; break; } } } while (form != NULL) { printobject(form , pfun ) ; pfun ( ' ) ' ) ; return ; } separate = 0 ; } else if (special) { pfun(' '); special--; } else if (!super) pfun(' '); indent(lm , ' ' , pfun ) ; } superprint(car(form), lm, pfun); form = cdr(form); } pfun(')'); return; }"# #+esp #" const int ppspecials = 20; const char ppspecial[ppspecials] PROGMEM = { DOTIMES, DOLIST, IF, SETQ, TEE, LET, LETSTAR, LAMBDA, WHEN, UNLESS, WITHI2C, WITHSERIAL, WITHSPI, WITHSDCARD, FORMILLIS, WITHOUTPUTTOSTRING, DEFVAR, CASE, WITHGFX, WITHCLIENT }; /* supersub - subroutine used by pprint */ void supersub (object *form, int lm, int super, pfun_t pfun) { int special = 0, separate = 1; object *arg = car(form); if (symbolp(arg)) { symbol_t sname = arg->name; if (sname == sym(DEFUN)) special = 2; else for (int i=0; i<ppspecials; i++) { if (sname == sym((builtin_t)pgm_read_byte(&ppspecial[i]))) { special = 1; break; } } } while (form != NULL) { printobject(form , pfun ) ; pfun ( ' ) ' ) ; return ; } separate = 0 ; } else if (special) { pfun(' '); special--; } else if (!super) pfun(' '); indent(lm , ' ' , pfun ) ; } superprint(car(form), lm, pfun); form = cdr(form); } pfun(')'); return; }"# #+stm32 #" const int ppspecials = 18; const char ppspecial[ppspecials] PROGMEM = { DOTIMES, DOLIST, IF, SETQ, TEE, LET, LETSTAR, LAMBDA, WHEN, UNLESS, WITHI2C, WITHSERIAL, WITHSPI, WITHSDCARD, WITHGFX, WITHOUTPUTTOSTRING, FORMILLIS }; /* supersub - subroutine used by pprint */ void supersub (object *form, int lm, int super, pfun_t pfun) { int special = 0, separate = 1; object *arg = car(form); if (symbolp(arg)) { int name = arg->name; if (name == DEFUN || name == DEFCODE) special = 2; else for (int i=0; i<ppspecials; i++) { if (name == ppspecial[i]) { special = 1; break; } } } while (form != NULL) { printobject(form , pfun ) ; pfun ( ' ) ' ) ; return ; } separate = 0 ; } else if (special) { pfun(' '); special--; } else if (!super) pfun(' '); indent(lm , ' ' , pfun ) ; } superprint(car(form), lm, pfun); form = cdr(form); } pfun(')'); return; }"# #" /* edit - the Lisp tree editor Steps through a function definition, editing it a bit at a time, using single-key editing commands. */ object *edit (object *fun) { while (1) { if (tstflag(EXITEDITOR)) return fun; char c = gserial(); if (c == 'q') setflag(EXITEDITOR); else if (c == 'b') return fun; else if (c == 'r') fun = read(gserial); else if (c == '\n') { pfl(pserial); superprint(fun, 0, pserial); pln(pserial); } else if (c == 'c') fun = cons(read(gserial), fun); else if (atom(fun)) pserial('!'); else if (c == 'd') fun = cons(car(fun), edit(cdr(fun))); else if (c == 'a') fun = cons(edit(car(fun)), cdr(fun)); else if (c == 'x') fun = cdr(fun); else pserial('?'); } }"#))
null
https://raw.githubusercontent.com/technoblogy/ulisp-builder/fbab6e2331f2d43bfb75b1a6d01fc893144b35b1/prettyprint.lisp
lisp
-*- Mode: Lisp; Package: cl-user -*- "# "# "# superprint(car(cdr(form)), lm + 1, pfun); } superprint(car(cdr(form)), lm + 1, pfun); } i<ppspecials; i++) { break; } break; } pfun ( ' ) ' ) ; return ; } } special--; } } return; i<ppspecials; i++) { break; } pfun ( ' ) ' ) ; return ; } } special--; } } return; i<ppspecials; i++) { break; } pfun ( ' ) ' ) ; return ; } } special--; } } return; i<ppspecials; i++) { break; } pfun ( ' ) ' ) ; return ; } } special--; } } return; i<ppspecials; i++) { break; } pfun ( ' ) ' ) ; return ; } } special--; } } return; i<ppspecials; i++) { break; } pfun ( ' ) ' ) ; return ; } } special--; } } return; i<ppspecials; i++) { break; } pfun ( ' ) ' ) ; return ; } } special--; } } return; superprint(fun, 0, pserial); pln(pserial); }
(in-package :cl-user) and tree editor (defparameter *prettyprint* '( #" // Prettyprint"# #-(or badge gfx) #" #+badge #" #+gfx #" // 320 pixel wide screen #" void pcount (char c) { } /* atomwidth - calculates the character width of an atom */ uint8_t atomwidth (object *obj) { } uint8_t basewidth (object *obj, uint8_t base) { } bool quoted (object *obj) { } int subwidth (object *obj, int w) { } int subwidthlist (object *form, int w) { while (form != NULL && w >= 0) { } }"# #-gfx #" /* superprint - the main pretty-print subroutine */ void superprint (object *form, int lm, pfun_t pfun) { if (atom(form)) { } }"# #+gfx #" /* superprint - the main pretty-print subroutine */ void superprint (object *form, int lm, pfun_t pfun) { if (atom(form)) { } }"# #+(and avr (not badge)) #" const char ppspecial[ppspecials] PROGMEM = /* supersub - subroutine used by pprint */ void supersub (object *form, int lm, int super, pfun_t pfun) { if (symbolp(arg)) { #if defined(CODESIZE) #else #endif #if defined(CPU_ATmega4809) #else #endif } } while (form != NULL) { } }"# #+arm #" const char ppspecial[ppspecials] PROGMEM = { DOTIMES, DOLIST, IF, SETQ, TEE, LET, LETSTAR, LAMBDA, WHEN, UNLESS, WITHI2C, WITHSERIAL, WITHSPI, WITHSDCARD, FORMILLIS, /* supersub - subroutine used by pprint */ void supersub (object *form, int lm, int super, pfun_t pfun) { if (symbolp(arg)) { } } while (form != NULL) { } }"# #+riscv #" const char ppspecial[ppspecials] PROGMEM = { DOTIMES, DOLIST, IF, SETQ, TEE, LET, LETSTAR, LAMBDA, WHEN, UNLESS, WITHI2C, WITHSERIAL, WITHSPI, WITHSDCARD, FORMILLIS, /* supersub - subroutine used by pprint */ void supersub (object *form, int lm, int super, pfun_t pfun) { if (symbolp(arg)) { } } while (form != NULL) { } }"# #+msp430 #" const char ppspecial[ppspecials] PROGMEM = /* supersub - subroutine used by pprint */ void supersub (object *form, int lm, int super, pfun_t pfun) { if (symbolp(arg)) { } } while (form != NULL) { } }"# #+badge #" const uint8_t ppspecial[ppspecials] PROGMEM = /* supersub - subroutine used by pprint */ void supersub (object *form, int lm, int super, pfun_t pfun) { if (symbolp(arg)) { #if defined(CODESIZE) #else #endif } } while (form != NULL) { } }"# #+esp #" const char ppspecial[ppspecials] PROGMEM = { DOTIMES, DOLIST, IF, SETQ, TEE, LET, LETSTAR, LAMBDA, WHEN, UNLESS, WITHI2C, WITHSERIAL, WITHSPI, WITHSDCARD, FORMILLIS, /* supersub - subroutine used by pprint */ void supersub (object *form, int lm, int super, pfun_t pfun) { if (symbolp(arg)) { } } while (form != NULL) { } }"# #+stm32 #" const char ppspecial[ppspecials] PROGMEM = /* supersub - subroutine used by pprint */ void supersub (object *form, int lm, int super, pfun_t pfun) { if (symbolp(arg)) { } } while (form != NULL) { } }"# #" /* edit - the Lisp tree editor Steps through a function definition, editing it a bit at a time, using single-key editing commands. */ object *edit (object *fun) { while (1) { } }"#))
4b4ab6730d6f3eb59a73f5c60aedb5a66957689849504de374ed0d13252e6034
dradtke/Lisp-Text-Editor
misc.lisp
(in-package :gtk-cffi) (defclass misc (widget) ()) (defcfun "gtk_misc_set_alignment" :void (misc pobject) (x :float) (y :float)) (defmethod (setf alignment) (coords (misc misc)) (gtk-misc-set-alignment misc (float (first coords)) (float (second coords)))) (defcfun "gtk_misc_get_alignment" :void (misc pobject) (x :pointer) (y :pointer)) (defmethod alignment ((misc misc)) (with-foreign-objects ((x :float) (y :float)) (gtk-misc-get-alignment misc x y) (list (mem-ref x :float) (mem-ref y :float))))
null
https://raw.githubusercontent.com/dradtke/Lisp-Text-Editor/b0947828eda82d7edd0df8ec2595e7491a633580/quicklisp/dists/quicklisp/software/gtk-cffi-20120208-cvs/gtk/misc.lisp
lisp
(in-package :gtk-cffi) (defclass misc (widget) ()) (defcfun "gtk_misc_set_alignment" :void (misc pobject) (x :float) (y :float)) (defmethod (setf alignment) (coords (misc misc)) (gtk-misc-set-alignment misc (float (first coords)) (float (second coords)))) (defcfun "gtk_misc_get_alignment" :void (misc pobject) (x :pointer) (y :pointer)) (defmethod alignment ((misc misc)) (with-foreign-objects ((x :float) (y :float)) (gtk-misc-get-alignment misc x y) (list (mem-ref x :float) (mem-ref y :float))))
4572817b68988d4a48915de96a42df1fd4021312393fef67b21505bce18bd3cb
Functional-AutoDiff/STALINGRAD
probabilistic-lambda-calculus-R-mitscheme.scm
(define (make-constant-expression value) (list 0 value)) (define (constant-expression? expression) (d= (first expression) 0)) (define (constant-expression-value expression) (second expression)) (define (make-variable-access-expression variable) (list 1 variable)) (define (variable-access-expression? expression) (d= (first expression) 1)) (define (variable-access-expression-variable expression) (second expression)) (define (make-lambda-expression variable body) (list 2 variable body)) (define (lambda-expression? expression) (d= (first expression) 2)) (define (lambda-expression-variable expression) (second expression)) (define (lambda-expression-body expression) (third expression)) (define (make-application callee argument) (list 3 callee argument)) (define (application-callee expression) (second expression)) (define (application-argument expression) (third expression)) (define (make-ignore) 0) (define (make-if-procedure) 1) (define (make-x0) 2) (define (make-x1) 3) (define (make-binding variable value) (list variable value)) (define (binding-variable binding) (first binding)) (define (binding-value binding) (second binding)) (define (make-triple p environment value) (list p environment value)) (define (triple-p triple) (first triple)) (define (triple-environment triple) (second triple)) (define (triple-value triple) (third triple)) (define (binds? environment variable) (and (not (null? environment)) (or (equal? variable (binding-variable (first environment))) (binds? (rest environment) variable)))) (define (lookup-value variable environment) (if (equal? variable (binding-variable (first environment))) (binding-value (first environment)) (lookup-value variable (rest environment)))) (define (merge-environments environment1 environment2) (if (null? environment1) environment2 (let ((environment (merge-environments (rest environment1) environment2))) (if (boolean? environment) #f (if (binds? environment (binding-variable (first environment1))) (if (equal? (lookup-value (binding-variable (first environment1)) environment) (binding-value (first environment1))) environment #f) (cons (first environment1) environment)))))) (define (singleton-tagged-distribution value) (list (make-triple 1.0 '() value))) (define (boolean-distribution p variable) (list (make-triple (d- 1.0 p) (list (make-binding variable #f)) #f) (make-triple p (list (make-binding variable #t)) #t))) (define (normalize-tagged-distribution tagged-distribution) (let ((n (let loop ((tagged-distribution tagged-distribution)) (if (null? tagged-distribution) 0.0 (d+ (triple-p (first tagged-distribution)) (loop (rest tagged-distribution))))))) (map (lambda (triple) (make-triple (d/ (triple-p triple) n) (triple-environment triple) (triple-value triple))) tagged-distribution))) (define (map-tagged-distribution f tagged-distribution) (normalize-tagged-distribution (let loop ((tagged-distribution tagged-distribution)) (if (null? tagged-distribution) '() (append (remove-if (lambda (triple) (boolean? (triple-environment triple))) (map (lambda (triple) (make-triple (d* (triple-p (first tagged-distribution)) (triple-p triple)) (merge-environments (triple-environment (first tagged-distribution)) (triple-environment triple)) (triple-value triple))) (f (triple-value (first tagged-distribution))))) (loop (rest tagged-distribution))))))) (define (evaluate expression environment) (cond ((constant-expression? expression) (singleton-tagged-distribution (constant-expression-value expression))) ((variable-access-expression? expression) (lookup-value (variable-access-expression-variable expression) environment)) ((lambda-expression? expression) (singleton-tagged-distribution (lambda (tagged-distribution) (evaluate (lambda-expression-body expression) (cons (make-binding (lambda-expression-variable expression) tagged-distribution) environment))))) (else (let ((tagged-distribution (evaluate (application-argument expression) environment))) (map-tagged-distribution (lambda (value) (value tagged-distribution)) (evaluate (application-callee expression) environment)))))) (define (likelihood value tagged-distribution) (if (null? tagged-distribution) 0.0 (d+ (if (equal? value (triple-value (first tagged-distribution))) (triple-p (first tagged-distribution)) 0.0) (likelihood value (rest tagged-distribution))))) (define (make-if antecedent consequent alternate) (make-application (make-application (make-application (make-variable-access-expression (make-if-procedure)) antecedent) (make-lambda-expression (make-ignore) consequent)) (make-lambda-expression (make-ignore) alternate))) (define (example) (gradient-ascent-R (lambda (p) (let ((tagged-distribution (evaluate (make-if (make-variable-access-expression (make-x0)) (make-constant-expression 0) (make-if (make-variable-access-expression (make-x1)) (make-constant-expression 1) (make-constant-expression 2))) (list (make-binding (make-x0) (boolean-distribution (list-ref p 0) (make-x0))) (make-binding (make-x1) (boolean-distribution (list-ref p 1) (make-x1))) (make-binding (make-if-procedure) (singleton-tagged-distribution (lambda (x) (singleton-tagged-distribution (lambda (y) (singleton-tagged-distribution (lambda (z) (map-tagged-distribution (lambda (xe) (map-tagged-distribution (lambda (ye) (map-tagged-distribution (lambda (ze) (if xe (ye #f) (ze #f))) z)) y)) x)))))))))))) (map-reduce d* 1.0 (lambda (observation) (likelihood observation tagged-distribution)) '(0 1 2 2)))) '(0.5 0.5) 1000.0 0.1)) (define (run) (let loop ((i 10.0) (result (list 0.0 0.0))) (if (dzero? i) result (let ((p (first (example)))) (loop (d- i 1) (list (write-real (list-ref p 0)) (write-real (list-ref p 1))))))))
null
https://raw.githubusercontent.com/Functional-AutoDiff/STALINGRAD/8a782171872d5caf414ef9f8b9b0efebaace3b51/examples/examples2009/probabilistic-lambda-calculus-R-mitscheme.scm
scheme
(define (make-constant-expression value) (list 0 value)) (define (constant-expression? expression) (d= (first expression) 0)) (define (constant-expression-value expression) (second expression)) (define (make-variable-access-expression variable) (list 1 variable)) (define (variable-access-expression? expression) (d= (first expression) 1)) (define (variable-access-expression-variable expression) (second expression)) (define (make-lambda-expression variable body) (list 2 variable body)) (define (lambda-expression? expression) (d= (first expression) 2)) (define (lambda-expression-variable expression) (second expression)) (define (lambda-expression-body expression) (third expression)) (define (make-application callee argument) (list 3 callee argument)) (define (application-callee expression) (second expression)) (define (application-argument expression) (third expression)) (define (make-ignore) 0) (define (make-if-procedure) 1) (define (make-x0) 2) (define (make-x1) 3) (define (make-binding variable value) (list variable value)) (define (binding-variable binding) (first binding)) (define (binding-value binding) (second binding)) (define (make-triple p environment value) (list p environment value)) (define (triple-p triple) (first triple)) (define (triple-environment triple) (second triple)) (define (triple-value triple) (third triple)) (define (binds? environment variable) (and (not (null? environment)) (or (equal? variable (binding-variable (first environment))) (binds? (rest environment) variable)))) (define (lookup-value variable environment) (if (equal? variable (binding-variable (first environment))) (binding-value (first environment)) (lookup-value variable (rest environment)))) (define (merge-environments environment1 environment2) (if (null? environment1) environment2 (let ((environment (merge-environments (rest environment1) environment2))) (if (boolean? environment) #f (if (binds? environment (binding-variable (first environment1))) (if (equal? (lookup-value (binding-variable (first environment1)) environment) (binding-value (first environment1))) environment #f) (cons (first environment1) environment)))))) (define (singleton-tagged-distribution value) (list (make-triple 1.0 '() value))) (define (boolean-distribution p variable) (list (make-triple (d- 1.0 p) (list (make-binding variable #f)) #f) (make-triple p (list (make-binding variable #t)) #t))) (define (normalize-tagged-distribution tagged-distribution) (let ((n (let loop ((tagged-distribution tagged-distribution)) (if (null? tagged-distribution) 0.0 (d+ (triple-p (first tagged-distribution)) (loop (rest tagged-distribution))))))) (map (lambda (triple) (make-triple (d/ (triple-p triple) n) (triple-environment triple) (triple-value triple))) tagged-distribution))) (define (map-tagged-distribution f tagged-distribution) (normalize-tagged-distribution (let loop ((tagged-distribution tagged-distribution)) (if (null? tagged-distribution) '() (append (remove-if (lambda (triple) (boolean? (triple-environment triple))) (map (lambda (triple) (make-triple (d* (triple-p (first tagged-distribution)) (triple-p triple)) (merge-environments (triple-environment (first tagged-distribution)) (triple-environment triple)) (triple-value triple))) (f (triple-value (first tagged-distribution))))) (loop (rest tagged-distribution))))))) (define (evaluate expression environment) (cond ((constant-expression? expression) (singleton-tagged-distribution (constant-expression-value expression))) ((variable-access-expression? expression) (lookup-value (variable-access-expression-variable expression) environment)) ((lambda-expression? expression) (singleton-tagged-distribution (lambda (tagged-distribution) (evaluate (lambda-expression-body expression) (cons (make-binding (lambda-expression-variable expression) tagged-distribution) environment))))) (else (let ((tagged-distribution (evaluate (application-argument expression) environment))) (map-tagged-distribution (lambda (value) (value tagged-distribution)) (evaluate (application-callee expression) environment)))))) (define (likelihood value tagged-distribution) (if (null? tagged-distribution) 0.0 (d+ (if (equal? value (triple-value (first tagged-distribution))) (triple-p (first tagged-distribution)) 0.0) (likelihood value (rest tagged-distribution))))) (define (make-if antecedent consequent alternate) (make-application (make-application (make-application (make-variable-access-expression (make-if-procedure)) antecedent) (make-lambda-expression (make-ignore) consequent)) (make-lambda-expression (make-ignore) alternate))) (define (example) (gradient-ascent-R (lambda (p) (let ((tagged-distribution (evaluate (make-if (make-variable-access-expression (make-x0)) (make-constant-expression 0) (make-if (make-variable-access-expression (make-x1)) (make-constant-expression 1) (make-constant-expression 2))) (list (make-binding (make-x0) (boolean-distribution (list-ref p 0) (make-x0))) (make-binding (make-x1) (boolean-distribution (list-ref p 1) (make-x1))) (make-binding (make-if-procedure) (singleton-tagged-distribution (lambda (x) (singleton-tagged-distribution (lambda (y) (singleton-tagged-distribution (lambda (z) (map-tagged-distribution (lambda (xe) (map-tagged-distribution (lambda (ye) (map-tagged-distribution (lambda (ze) (if xe (ye #f) (ze #f))) z)) y)) x)))))))))))) (map-reduce d* 1.0 (lambda (observation) (likelihood observation tagged-distribution)) '(0 1 2 2)))) '(0.5 0.5) 1000.0 0.1)) (define (run) (let loop ((i 10.0) (result (list 0.0 0.0))) (if (dzero? i) result (let ((p (first (example)))) (loop (d- i 1) (list (write-real (list-ref p 0)) (write-real (list-ref p 1))))))))
775286e3dd7292c5311b3e59e08e3e62f5fb31eea7eab7256070137d4739c99d
larcenists/larceny
case-lambda.sps
(import (tests scheme case-lambda) (tests scheme test) (scheme write)) (display "Running tests for (scheme case-lambda)\n") (run-case-lambda-tests) (report-test-results)
null
https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/test/R7RS/Lib/tests/scheme/run/case-lambda.sps
scheme
(import (tests scheme case-lambda) (tests scheme test) (scheme write)) (display "Running tests for (scheme case-lambda)\n") (run-case-lambda-tests) (report-test-results)
f9b7812e904deaf0215b851cd9f6bf74147ce246e4de42dcc2169e8f7f23adbd
gravicappa/gambit-sdl
sdl-draw.scm
(define (sdl-draw screen sprite time) (let* ((xc (* 0.5 (sdl#surface-w screen))) (yc (* 0.5 (sdl#surface-h screen))) (x (inexact->exact (+ xc (round (* 20 (+ 1 (sin (* time 1.0)))))))) (y (inexact->exact (+ yc (round (* 50 (+ 1 (cos (* time 1.5)))))))) (xs (inexact->exact (+ yc (round (* 20 (+ 1 (sin (* time 4.0))))))))) (sdl#fill-rect/xywh! screen x y 30 20 #xff00ff) (if sprite (sdl#blit-surface! sprite #f screen (sdl#make-rect xs x (sdl#surface-w sprite) (sdl#surface-h sprite)))))) (let ((sprite #f)) (add-hook (init-hook) (lambda (s) (set! sprite (sdl#load-image "img.png")))) (add-hook (draw-hook) (lambda (s t) (sdl-draw s sprite t))))
null
https://raw.githubusercontent.com/gravicappa/gambit-sdl/bde15600d7911e8c629e32f715bfa030000a3b09/example/sdl-draw.scm
scheme
(define (sdl-draw screen sprite time) (let* ((xc (* 0.5 (sdl#surface-w screen))) (yc (* 0.5 (sdl#surface-h screen))) (x (inexact->exact (+ xc (round (* 20 (+ 1 (sin (* time 1.0)))))))) (y (inexact->exact (+ yc (round (* 50 (+ 1 (cos (* time 1.5)))))))) (xs (inexact->exact (+ yc (round (* 20 (+ 1 (sin (* time 4.0))))))))) (sdl#fill-rect/xywh! screen x y 30 20 #xff00ff) (if sprite (sdl#blit-surface! sprite #f screen (sdl#make-rect xs x (sdl#surface-w sprite) (sdl#surface-h sprite)))))) (let ((sprite #f)) (add-hook (init-hook) (lambda (s) (set! sprite (sdl#load-image "img.png")))) (add-hook (draw-hook) (lambda (s t) (sdl-draw s sprite t))))
f5c634c031071d94658a66529569507ea678995870ffd2a7ff1efe1ff646da3f
xapi-project/xen-api-libs-transitional
test_server.ml
open Xapi_stdext_threads.Threadext open Xapi_stdext_unix let finished = ref false let finished_m = Mutex.create () let finished_c = Condition.create () let _ = let port = ref 8080 in let use_fastpath = ref false in Arg.parse [ ("-p", Arg.Set_int port, "port to listen on") ; ("-fast", Arg.Set use_fastpath, "use HTTP fastpath") ] (fun x -> Printf.fprintf stderr "Ignoring unexpected argument: %s\n" x) "A simple test HTTP server" ; let open Http_svr in let server = Server.empty () in if !use_fastpath then Server.enable_fastpath server ; Server.add_handler server Http.Get "/stop" (FdIO (fun _ s _ -> let r = Http.Response.to_wire_string (Http.Response.make "200" "OK") in Unixext.really_write_string s r ; Mutex.execute finished_m (fun () -> finished := true ; Condition.signal finished_c ) ) ) ; Server.add_handler server Http.Post "/echo" (FdIO (fun request s _ -> match request.Http.Request.content_length with | None -> Unixext.really_write_string s (Http.Response.to_wire_string (Http.Response.make "404" "content length missing") ) | Some l -> let txt = Unixext.really_read_string s (Int64.to_int l) in let r = Http.Response.to_wire_string (Http.Response.make ~body:txt "200" "OK") in Unixext.really_write_string s r ) ) ; Server.add_handler server Http.Get "/stats" (FdIO (fun _ s _ -> let lines = List.map (fun (m, uri, s) -> Printf.sprintf "%s,%s,%d,%d\n" (Http.string_of_method_t m) uri s.Http_svr.Stats.n_requests s.Http_svr.Stats.n_connections ) (Server.all_stats server) in let txt = String.concat "" lines in let r = Http.Response.to_wire_string (Http.Response.make ~body:txt "200" "OK") in Unixext.really_write_string s r ) ) ; let ip = "0.0.0.0" in let inet_addr = Unix.inet_addr_of_string ip in let addr = Unix.ADDR_INET (inet_addr, !port) in let socket = Http_svr.bind ~listen_backlog:5 addr "server" in start server socket ; Printf.printf "Server started on %s:%d\n" ip !port ; Mutex.execute finished_m (fun () -> while not !finished do Condition.wait finished_c finished_m done ) ; Printf.printf "Exiting\n" ; stop socket
null
https://raw.githubusercontent.com/xapi-project/xen-api-libs-transitional/656e5e750d77a98e6656ac1c37d9309be795b0b6/http-svr/test_server.ml
ocaml
open Xapi_stdext_threads.Threadext open Xapi_stdext_unix let finished = ref false let finished_m = Mutex.create () let finished_c = Condition.create () let _ = let port = ref 8080 in let use_fastpath = ref false in Arg.parse [ ("-p", Arg.Set_int port, "port to listen on") ; ("-fast", Arg.Set use_fastpath, "use HTTP fastpath") ] (fun x -> Printf.fprintf stderr "Ignoring unexpected argument: %s\n" x) "A simple test HTTP server" ; let open Http_svr in let server = Server.empty () in if !use_fastpath then Server.enable_fastpath server ; Server.add_handler server Http.Get "/stop" (FdIO (fun _ s _ -> let r = Http.Response.to_wire_string (Http.Response.make "200" "OK") in Unixext.really_write_string s r ; Mutex.execute finished_m (fun () -> finished := true ; Condition.signal finished_c ) ) ) ; Server.add_handler server Http.Post "/echo" (FdIO (fun request s _ -> match request.Http.Request.content_length with | None -> Unixext.really_write_string s (Http.Response.to_wire_string (Http.Response.make "404" "content length missing") ) | Some l -> let txt = Unixext.really_read_string s (Int64.to_int l) in let r = Http.Response.to_wire_string (Http.Response.make ~body:txt "200" "OK") in Unixext.really_write_string s r ) ) ; Server.add_handler server Http.Get "/stats" (FdIO (fun _ s _ -> let lines = List.map (fun (m, uri, s) -> Printf.sprintf "%s,%s,%d,%d\n" (Http.string_of_method_t m) uri s.Http_svr.Stats.n_requests s.Http_svr.Stats.n_connections ) (Server.all_stats server) in let txt = String.concat "" lines in let r = Http.Response.to_wire_string (Http.Response.make ~body:txt "200" "OK") in Unixext.really_write_string s r ) ) ; let ip = "0.0.0.0" in let inet_addr = Unix.inet_addr_of_string ip in let addr = Unix.ADDR_INET (inet_addr, !port) in let socket = Http_svr.bind ~listen_backlog:5 addr "server" in start server socket ; Printf.printf "Server started on %s:%d\n" ip !port ; Mutex.execute finished_m (fun () -> while not !finished do Condition.wait finished_c finished_m done ) ; Printf.printf "Exiting\n" ; stop socket
eb6e428710de0994445765bd3d51813c89abd9d7353f582936f9271b174298c0
Flamefork/fleet
fleet_api_test.clj
(ns fleet-api-test (:use clojure.test fleet)) (def test-posts [{:body "First post."} {:body "Second post."}]) (def test-data {:title "Posts"}) (def filters [ "js" :str "html" :xml :fleet :bypass]) (fleet-ns tpl "test/resources/ns" filters) (deftest fleet-ns-test (let [initial-ns *ns*] (fleet-ns 'tpl "test/resources/ns" filters) (is (= *ns* initial-ns)) (is (= (tpl.posts/posts-html test-posts test-data) (slurp "test/resources/ns/posts/posts.html"))))) (deftest error-reporting-test (let [e (is (thrown? ClassCastException (tpl.posts/exceptional))) ste (first (.getStackTrace e))] (is (= (.getFileName ste) "exceptional.fleet")) (is (= (.getLineNumber ste) 4)))) (deftest cross-lang-test (is (= (tpl.posts/update (first test-posts)) (slurp "test/resources/ns/posts/update.js")))) (deftest layout-test (is (= (tpl/layout (tpl.posts/posts-html test-posts test-data)) (slurp "test/resources/ns/posts/posts_with_layout.html"))))
null
https://raw.githubusercontent.com/Flamefork/fleet/dc4adcd84b2f92d40797789c98e71746181f1a04/test/fleet_api_test.clj
clojure
(ns fleet-api-test (:use clojure.test fleet)) (def test-posts [{:body "First post."} {:body "Second post."}]) (def test-data {:title "Posts"}) (def filters [ "js" :str "html" :xml :fleet :bypass]) (fleet-ns tpl "test/resources/ns" filters) (deftest fleet-ns-test (let [initial-ns *ns*] (fleet-ns 'tpl "test/resources/ns" filters) (is (= *ns* initial-ns)) (is (= (tpl.posts/posts-html test-posts test-data) (slurp "test/resources/ns/posts/posts.html"))))) (deftest error-reporting-test (let [e (is (thrown? ClassCastException (tpl.posts/exceptional))) ste (first (.getStackTrace e))] (is (= (.getFileName ste) "exceptional.fleet")) (is (= (.getLineNumber ste) 4)))) (deftest cross-lang-test (is (= (tpl.posts/update (first test-posts)) (slurp "test/resources/ns/posts/update.js")))) (deftest layout-test (is (= (tpl/layout (tpl.posts/posts-html test-posts test-data)) (slurp "test/resources/ns/posts/posts_with_layout.html"))))
71fbf5abd999c9d9ba5043da79e98f529cea16d22bd0c01d862a66bd680d6154
MaskRay/OJHaskell
102.hs
check [x1,y1,x2,y2,x3,y3] = oab*abc >= 0 && obc*abc >= 0 && oca*abc >= 0 where o = (0,0) a = (x1,y1) b = (x2,y2) c = (x3,y3) abc = area a b c oab = area o a b obc = area o b c oca = area o c a area (x0,y0) (x1,y1) (x2,y2) = (x1-x0)*(y2-y0)-(x2-x0)*(y1-y0) p102 = length . filter check . map (\l -> read $ "["++l++"]") . lines main = readFile "triangles.txt" >>= print . p102
null
https://raw.githubusercontent.com/MaskRay/OJHaskell/ba24050b2480619f10daa7d37fca558182ba006c/Project%20Euler/102.hs
haskell
check [x1,y1,x2,y2,x3,y3] = oab*abc >= 0 && obc*abc >= 0 && oca*abc >= 0 where o = (0,0) a = (x1,y1) b = (x2,y2) c = (x3,y3) abc = area a b c oab = area o a b obc = area o b c oca = area o c a area (x0,y0) (x1,y1) (x2,y2) = (x1-x0)*(y2-y0)-(x2-x0)*(y1-y0) p102 = length . filter check . map (\l -> read $ "["++l++"]") . lines main = readFile "triangles.txt" >>= print . p102
cda8c1c882c7ae74670f78256356535bb6f967a2b386b75d7827991264dad13d
inconvergent/cl-veq
checks.lisp
(in-package :veq) (fvdef* f2segdst ((varg 2 va vb v)) "find distance between line, (va vb), and v. returns (values distance s) where is is the interpolation value that will yield the closest point on line." (declare #.*opt* (ff va vb v)) (let ((l2 (f2dst2 va vb))) (declare (ff l2)) (if (< l2 *eps*) (values (f2dst va v) 0d0) ; line is a point, else: (let ((s (max 0f0 (min 1f0 (/ (+ (* (- (vref v 0) (vref va 0)) (- (vref vb 0) (vref va 0))) (* (- (vref v 1) (vref va 1)) (- (vref vb 1) (vref va 1)))) l2))))) (values (f2dst v (f2lerp va vb s)) s))))) (fvdef* f2segx ((varg 2 a1 a2 b1 b2)) (declare #.*opt* (ff a1 a2 b1 b2)) "find intersection between lines (a1 a2), (b1 b2). returns isect? p q where p and q is the distance along each line to the intersection point" (f2let ((sa (f2- a2 a1)) (sb (f2- b2 b1))) (let ((u (f2cross sa sb)) (1eps (- 1f0 *eps*))) (declare (ff u 1eps)) (if (<= (abs u) *eps*) ; return nil if the lines are parallel or very short. ; this is just a div0 guard. it's not a good way to test. (values nil 0f0 0f0) ; otherwise check if they intersect (f2let ((ab (f2- a1 b1))) ; t if intersection, nil otherwise (let ((p (/ (f2cross sa ab) u)) (q (/ (f2cross sb ab) u))) (declare (ff p q)) (values (and (> 1eps p *eps*) (> 1eps q *eps*)) q p))))))) (deftype array-fvec () `(simple-array fvec)) (declaim (inline -sweep-line)) (defun -sweep-line (lines line-points) (declare #.*opt* (array-fvec lines) (list line-points)) "perform sweep line search for intersections along x" add first line index to sweep line state , ; and set sweep line position ; TODO: special cases: equal x pos, vertical line (let ((res (make-array (length lines) :element-type 'list :initial-element nil :adjustable nil)) (state (list (cdar line-points)))) (declare (type (simple-array list) res) (list state)) (labels ((-append (i c p) (declare #.*opt* (pos-int i c) (ff p)) (if (aref res i) (push `(,c . ,p) (aref res i)) (setf (aref res i) `((,c . ,p))))) (-isects (i cands) (declare #.*opt* (pos-int i) (list cands)) "intersection test" (loop with line of-type fvec = (aref lines i) for c of-type pos-int in cands do (fvprogn (mvb (x p q) (f2segx (f2$ line 0 1) (f2$ (aref lines c) 0 1)) (declare (boolean x) (ff p q)) (when x (-append i c p) (-append c i q)))))) (-remove (i) (declare #.*opt* (pos-int i)) (setf state (remove-if #'(lambda (e) (declare (optimize speed) (pos-int e)) (eql e i)) state)))) (loop for (_ . i) of-type (ff . pos-int) in (cdr line-points) ; if i in state, kick i out of state, if (member i state) do (-remove i) ; else check i against all state, add i to state else do (-isects i state) (setf state (cons i state)))) res)) (declaim (inline -sorted-point-pairs)) (defun -sorted-point-pairs (lines &aux (res (list))) (declare #.*opt* (list res) (array-fvec lines)) (loop for line of-type fvec across lines for i of-type pos-int from 0 do (push `(,(aref line 0) . ,i) res) (push `(,(aref line 2) . ,i) res)) (sort res #'< :key #'car)) (fvdef* f2lsegx (lines*) (declare #.*opt* (sequence lines*)) "lines = #( #(ax ay bx by) ... ) not entirely slow line-line intersection for all lines. this is faster than comparing all lines when lines are short relative to the area that the lines cover. it can be improved further by using binary search tree to store current state." (let ((lines (typecase lines* (list (make-array (length lines*) :initial-contents lines* :adjustable nil :element-type 'fvec)) (vector lines*) (t (error "f2lsegx error: incorrect type: ~a~%" lines*))))) (declare (array-fvec lines)) (-sweep-line lines (-sorted-point-pairs lines)))) ;;;;;;;;;; CONCAVE SHAPE RAY CAST TEST (fvdef* f2in-bbox ((varg 2 top-left bottom-right pt)) (declare (ff top-left bottom-right pt)) (and (< (vref top-left 0) (vref pt 0) (vref bottom-right 0)) (< (vref top-left 1) (vref pt 1) (vref bottom-right 1)))) (fvdef* f2in-concave (shape (varg 2 pt)) (declare (fvec shape) (ff pt)) (let ((n (2$num shape))) (mvb (minx maxx miny maxy) (f2$mima shape :n n) (declare (ff minx maxx miny maxy)) pt outside bbox - > outside shape (return-from %f2in-concave nil)) (let* ((c 0) (width (- maxx minx)) (shift (- (vref pt 0) (* 2f0 width)))) (declare (pos-int c) (ff width shift)) (f2$with-rows (n shape) (lambda (i (varg 2 a)) (declare (optimize speed) (ff a)) (when (f2segx pt shift (vref pt 1) a (f2$ shape (mod (1+ i) n))) (incf c)))) ; odd number of isects means pt is inside shape (oddp c))))) (fvdef* f3planex ((varg 3 n p a b)) (declare #.*opt* (ff n p a b)) "intersection of plane (n:normal, p:point) and line (a b)" (f3let ((ln (f3- b a))) (let ((ldotn (f3. ln n))) (declare (ff ldotn)) (when (< (abs ldotn) *eps*) ; avoid div0. (return-from %f3planex (values nil 0f0 0f0 0f0 0f0))) ; else: (let ((d (/ (f3. (f3- p a) n) ldotn))) (declare (ff d)) (~ t d (f3from a ln d)))))) ; TODO: ; (defun f2inside-convex-poly (convex v) ( declare # .*opt - settings * ( list convex ) ( v ) ) ; (loop with convex* = (math:close-path* convex) ; for a of-type vec in convex* ; and b of-type vec in (cdr convex*) always ( > = ( cross ( sub b a ) ( sub v b ) ) 0d0 ) ) ) (fvdef* f2in-triangle ((varg 2 a b c p)) (declare #.*opt* (ff a b c p)) (labels ((f2norm-safe ((varg 2 a)) (declare (ff a)) (let ((l (f2len a))) (declare (ff l)) (if (< *eps* l) (f2iscale a l) (f2rep 0f0)))) (check ((varg 2 p1 p2 p3)) (declare (ff p1 p2 p3)) (f2cross (mvc #'f2norm-safe (f2- p3 p1)) (mvc #'f2norm-safe (f2- p3 p2))))) (let ((d1 (check a b p)) (d2 (check b c p)) (d3 (check c a p)) (ep (- *eps*)) (-ep (+ *eps*))) (not (and (or (< d1 ep) (< d2 ep) (< d3 ep)) (or (> d1 -ep) (> d2 -ep) (> d3 -ep)))))))
null
https://raw.githubusercontent.com/inconvergent/cl-veq/04386c4019e1f7a6824fc97640458232f426c32d/src/checks.lisp
lisp
line is a point, else: return nil if the lines are parallel or very short. this is just a div0 guard. it's not a good way to test. otherwise check if they intersect t if intersection, nil otherwise and set sweep line position TODO: special cases: equal x pos, vertical line if i in state, kick i out of state, else check i against all state, add i to state CONCAVE SHAPE RAY CAST TEST odd number of isects means pt is inside shape avoid div0. else: TODO: (defun f2inside-convex-poly (convex v) (loop with convex* = (math:close-path* convex) for a of-type vec in convex* and b of-type vec in (cdr convex*)
(in-package :veq) (fvdef* f2segdst ((varg 2 va vb v)) "find distance between line, (va vb), and v. returns (values distance s) where is is the interpolation value that will yield the closest point on line." (declare #.*opt* (ff va vb v)) (let ((l2 (f2dst2 va vb))) (declare (ff l2)) (if (< l2 *eps*) (let ((s (max 0f0 (min 1f0 (/ (+ (* (- (vref v 0) (vref va 0)) (- (vref vb 0) (vref va 0))) (* (- (vref v 1) (vref va 1)) (- (vref vb 1) (vref va 1)))) l2))))) (values (f2dst v (f2lerp va vb s)) s))))) (fvdef* f2segx ((varg 2 a1 a2 b1 b2)) (declare #.*opt* (ff a1 a2 b1 b2)) "find intersection between lines (a1 a2), (b1 b2). returns isect? p q where p and q is the distance along each line to the intersection point" (f2let ((sa (f2- a2 a1)) (sb (f2- b2 b1))) (let ((u (f2cross sa sb)) (1eps (- 1f0 *eps*))) (declare (ff u 1eps)) (if (<= (abs u) *eps*) (values nil 0f0 0f0) (f2let ((ab (f2- a1 b1))) (let ((p (/ (f2cross sa ab) u)) (q (/ (f2cross sb ab) u))) (declare (ff p q)) (values (and (> 1eps p *eps*) (> 1eps q *eps*)) q p))))))) (deftype array-fvec () `(simple-array fvec)) (declaim (inline -sweep-line)) (defun -sweep-line (lines line-points) (declare #.*opt* (array-fvec lines) (list line-points)) "perform sweep line search for intersections along x" add first line index to sweep line state , (let ((res (make-array (length lines) :element-type 'list :initial-element nil :adjustable nil)) (state (list (cdar line-points)))) (declare (type (simple-array list) res) (list state)) (labels ((-append (i c p) (declare #.*opt* (pos-int i c) (ff p)) (if (aref res i) (push `(,c . ,p) (aref res i)) (setf (aref res i) `((,c . ,p))))) (-isects (i cands) (declare #.*opt* (pos-int i) (list cands)) "intersection test" (loop with line of-type fvec = (aref lines i) for c of-type pos-int in cands do (fvprogn (mvb (x p q) (f2segx (f2$ line 0 1) (f2$ (aref lines c) 0 1)) (declare (boolean x) (ff p q)) (when x (-append i c p) (-append c i q)))))) (-remove (i) (declare #.*opt* (pos-int i)) (setf state (remove-if #'(lambda (e) (declare (optimize speed) (pos-int e)) (eql e i)) state)))) (loop for (_ . i) of-type (ff . pos-int) in (cdr line-points) if (member i state) do (-remove i) else do (-isects i state) (setf state (cons i state)))) res)) (declaim (inline -sorted-point-pairs)) (defun -sorted-point-pairs (lines &aux (res (list))) (declare #.*opt* (list res) (array-fvec lines)) (loop for line of-type fvec across lines for i of-type pos-int from 0 do (push `(,(aref line 0) . ,i) res) (push `(,(aref line 2) . ,i) res)) (sort res #'< :key #'car)) (fvdef* f2lsegx (lines*) (declare #.*opt* (sequence lines*)) "lines = #( #(ax ay bx by) ... ) not entirely slow line-line intersection for all lines. this is faster than comparing all lines when lines are short relative to the area that the lines cover. it can be improved further by using binary search tree to store current state." (let ((lines (typecase lines* (list (make-array (length lines*) :initial-contents lines* :adjustable nil :element-type 'fvec)) (vector lines*) (t (error "f2lsegx error: incorrect type: ~a~%" lines*))))) (declare (array-fvec lines)) (-sweep-line lines (-sorted-point-pairs lines)))) (fvdef* f2in-bbox ((varg 2 top-left bottom-right pt)) (declare (ff top-left bottom-right pt)) (and (< (vref top-left 0) (vref pt 0) (vref bottom-right 0)) (< (vref top-left 1) (vref pt 1) (vref bottom-right 1)))) (fvdef* f2in-concave (shape (varg 2 pt)) (declare (fvec shape) (ff pt)) (let ((n (2$num shape))) (mvb (minx maxx miny maxy) (f2$mima shape :n n) (declare (ff minx maxx miny maxy)) pt outside bbox - > outside shape (return-from %f2in-concave nil)) (let* ((c 0) (width (- maxx minx)) (shift (- (vref pt 0) (* 2f0 width)))) (declare (pos-int c) (ff width shift)) (f2$with-rows (n shape) (lambda (i (varg 2 a)) (declare (optimize speed) (ff a)) (when (f2segx pt shift (vref pt 1) a (f2$ shape (mod (1+ i) n))) (incf c)))) (oddp c))))) (fvdef* f3planex ((varg 3 n p a b)) (declare #.*opt* (ff n p a b)) "intersection of plane (n:normal, p:point) and line (a b)" (f3let ((ln (f3- b a))) (let ((ldotn (f3. ln n))) (declare (ff ldotn)) (let ((d (/ (f3. (f3- p a) n) ldotn))) (declare (ff d)) (~ t d (f3from a ln d)))))) ( declare # .*opt - settings * ( list convex ) ( v ) ) always ( > = ( cross ( sub b a ) ( sub v b ) ) 0d0 ) ) ) (fvdef* f2in-triangle ((varg 2 a b c p)) (declare #.*opt* (ff a b c p)) (labels ((f2norm-safe ((varg 2 a)) (declare (ff a)) (let ((l (f2len a))) (declare (ff l)) (if (< *eps* l) (f2iscale a l) (f2rep 0f0)))) (check ((varg 2 p1 p2 p3)) (declare (ff p1 p2 p3)) (f2cross (mvc #'f2norm-safe (f2- p3 p1)) (mvc #'f2norm-safe (f2- p3 p2))))) (let ((d1 (check a b p)) (d2 (check b c p)) (d3 (check c a p)) (ep (- *eps*)) (-ep (+ *eps*))) (not (and (or (< d1 ep) (< d2 ep) (< d3 ep)) (or (> d1 -ep) (> d2 -ep) (> d3 -ep)))))))
58318d3b12d42353dae44e6b620acf610e06841956d48412613e714151c3f56e
thicksteadTHpp/Obvius
gl-ffi-fmclient-functions.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; fmclient-functions.lisp ;;; ;;; Font Manager Functions ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package 'gl) ;;; int fmcachelimit(); (def-exported-c-function ("fmcachelimit" (:return-type int))) void fmconcatpagematrix(double [ 3][2 ] ) ; (def-exported-c-function "fmconcatpagematrix" ((:array double (3 2) :row-major))) ;;; void fmenumerate(); (def-exported-c-function "fmenumerate") ;;; fmfonthandle fmfindfont(const char *); (def-exported-c-function ("fmfindfont" (:return-type fmfonthandle)) (String)) ;;; void fmfreefont(fmfonthandle); (def-exported-c-function "fmfreefont" (fmfonthandle)) ;;; char *fmfontpath(); /* pass back the path */ (def-exported-c-function ("fmfontpath" (:return-type String))) ;;; void fmsetpath(const char *);/* pass in the path */ (def-exported-c-function "fmsetpath" (String)) ;;; int fmgetcacheused(); (def-exported-c-function ("fmgetcacheused" (:return-type int))) ;;; long fmgetchrwidth(fmfonthandle, const unsigned char); (def-exported-c-function ("fmgetchrwidth" (:return-type long)) (fmfonthandle u-char)) ;;; int fmgetcomment(fmfonthandle, int, char *); (def-exported-c-function ("fmgetcomment" (:return-type int)) (fmfonthandle int String)) ;;; int fmgetfontinfo(fmfonthandle, fmfontinfo *); (def-exported-c-function ("fmgetfontinfo" (:return-type int)) (fmfonthandle (:pointer fmfontinfo))) ;;; int fmgetfontname(fmfonthandle, int len, char *); (def-exported-c-function ("fmgetfontname" (:return-type int)) (fmfonthandle int String)) void fmgetpagematrix(double [ 3][2 ] ) ; (def-exported-c-function "fmgetpagematrix" ((:array double (3 2) :row-major))) ;;; long fmgetstrwidth(fmfonthandle, const char *); (def-exported-c-function ("fmgetstrwidth" (:return-type long)) (fmfonthandle String)) long fmgetwholemetrics(fmfonthandle , * ) ; (def-exported-c-function ("fmgetwholemetrics" (:return-type long)) (fmfonthandle (:pointer fmglyphinfo))) void ( ) ; (def-exported-c-function "fminitpagematrix") ;;; fmfonthandle fmmakefont(fmfonthandle, double[3][2]); (def-exported-c-function ("fmmakefont" (:return-type fmfonthandle)) (fmfonthandle (:array double (3 2) :row-major))) ;;; void fmcacheenable(); (def-exported-c-function "fmcacheenable") ;;; void fmcachedisable(); (def-exported-c-function "fmcachedisable") ;;; long fmoutchar(fmfonthandle, const unsigned int); (def-exported-c-function ("fmoutchar" (:return-type long)) (fmfonthandle u-int)) ;;; void fmprintermatch(int); (def-exported-c-function "fmprintermatch" (int)) ;;; int fmprstr(const char *); (def-exported-c-function ("fmprstr" (:return-type int)) (String)) ;;; void fmrotatepagematrix(double); (def-exported-c-function "fmrotatepagematrix" (double)) ;;; fmfonthandle fmscalefont(fmfonthandle, double); (def-exported-c-function ("fmscalefont" (:return-type fmfonthandle)) (fmfonthandle double)) ;;; void fmsetcachelimit(int); (def-exported-c-function "fmsetcachelimit" (int)) ;;; void fmsetfont(fmfonthandle); (def-exported-c-function "fmsetfont" (fmfonthandle)) void fmsetpagematrix(double [ 3][2 ] ) ; (def-exported-c-function "fmsetpagematrix" ((:array double (3 2) :row-major))) ;;; void fmscalepagematrix(double); (def-exported-c-function "fmscalepagematrix" (double))
null
https://raw.githubusercontent.com/thicksteadTHpp/Obvius/9a91673609def033539c9ebaf098e8f11eb0df6e/gl_ffi/gl-ffi-fmclient-functions.lisp
lisp
fmclient-functions.lisp Font Manager Functions int fmcachelimit(); void fmenumerate(); fmfonthandle fmfindfont(const char *); void fmfreefont(fmfonthandle); char *fmfontpath(); /* pass back the path */ void fmsetpath(const char *);/* pass in the path */ int fmgetcacheused(); long fmgetchrwidth(fmfonthandle, const unsigned char); int fmgetcomment(fmfonthandle, int, char *); int fmgetfontinfo(fmfonthandle, fmfontinfo *); int fmgetfontname(fmfonthandle, int len, char *); long fmgetstrwidth(fmfonthandle, const char *); fmfonthandle fmmakefont(fmfonthandle, double[3][2]); void fmcacheenable(); void fmcachedisable(); long fmoutchar(fmfonthandle, const unsigned int); void fmprintermatch(int); int fmprstr(const char *); void fmrotatepagematrix(double); fmfonthandle fmscalefont(fmfonthandle, double); void fmsetcachelimit(int); void fmsetfont(fmfonthandle); void fmscalepagematrix(double);
(in-package 'gl) (def-exported-c-function ("fmcachelimit" (:return-type int))) (def-exported-c-function "fmconcatpagematrix" ((:array double (3 2) :row-major))) (def-exported-c-function "fmenumerate") (def-exported-c-function ("fmfindfont" (:return-type fmfonthandle)) (String)) (def-exported-c-function "fmfreefont" (fmfonthandle)) (def-exported-c-function ("fmfontpath" (:return-type String))) (def-exported-c-function "fmsetpath" (String)) (def-exported-c-function ("fmgetcacheused" (:return-type int))) (def-exported-c-function ("fmgetchrwidth" (:return-type long)) (fmfonthandle u-char)) (def-exported-c-function ("fmgetcomment" (:return-type int)) (fmfonthandle int String)) (def-exported-c-function ("fmgetfontinfo" (:return-type int)) (fmfonthandle (:pointer fmfontinfo))) (def-exported-c-function ("fmgetfontname" (:return-type int)) (fmfonthandle int String)) (def-exported-c-function "fmgetpagematrix" ((:array double (3 2) :row-major))) (def-exported-c-function ("fmgetstrwidth" (:return-type long)) (fmfonthandle String)) (def-exported-c-function ("fmgetwholemetrics" (:return-type long)) (fmfonthandle (:pointer fmglyphinfo))) (def-exported-c-function "fminitpagematrix") (def-exported-c-function ("fmmakefont" (:return-type fmfonthandle)) (fmfonthandle (:array double (3 2) :row-major))) (def-exported-c-function "fmcacheenable") (def-exported-c-function "fmcachedisable") (def-exported-c-function ("fmoutchar" (:return-type long)) (fmfonthandle u-int)) (def-exported-c-function "fmprintermatch" (int)) (def-exported-c-function ("fmprstr" (:return-type int)) (String)) (def-exported-c-function "fmrotatepagematrix" (double)) (def-exported-c-function ("fmscalefont" (:return-type fmfonthandle)) (fmfonthandle double)) (def-exported-c-function "fmsetcachelimit" (int)) (def-exported-c-function "fmsetfont" (fmfonthandle)) (def-exported-c-function "fmsetpagematrix" ((:array double (3 2) :row-major))) (def-exported-c-function "fmscalepagematrix" (double))
51a40717891c1bba990deadaa15a40765910b9933916fef862ed64dd485213d5
stackbuilders/scalendar
Internal.hs
module SCalendarTest.Internal where import Data.List (elem) import Data.Maybe (isJust, fromMaybe) import Data.Time (UTCTime(..), toGregorian, diffUTCTime ) import SCalendarTest.Helpers (getUTCdayNum) import Time.SCalendar.Types ( Calendar(..) , Reservation(..) , TimePeriod , getFrom , getTo , isIncluded , powerOfTwo , oneDay , makeTimePeriod ) import Time.SCalendar.Zippers (goUp) import SCalendarTest.Arbitrary (RandomZippers(..), CalendarReservations(..)) import Time.SCalendar.Internal ( goToNode , leftMostTopNode , rightMostTopNode , topMostNodes , getZipInterval , commonParent ) alwaysGreateOrEqualThanN :: Int -> Bool alwaysGreateOrEqualThanN n = 2^ powerOfTwo n >= n eqIntervalsIfIncludeEachOther :: TimePeriod -> TimePeriod -> Bool eqIntervalsIfIncludeEachOther i j | isIncluded i j && isIncluded j i = i1 == j1 && i2 == j2 | isIncluded i j = not $ isIncluded j i | isIncluded j i = not $ isIncluded i j | not (isIncluded i j) && not (isIncluded j i) && wellFormed = i1 < j2 || j1 < i2 | otherwise = not wellFormed where (i1, i2) = (getFrom i, getTo i) (j1, j2) = (getFrom j, getTo j) wellFormed = i1 <= i2 && j1 <= j2 returnsTargetZipper :: Calendar -> TimePeriod -> Bool returnsTargetZipper calendar interval = let maybeCalendar = fst <$> goToNode interval calendar in maybe (ifNothing calendar) checkTarget maybeCalendar where checkTarget (Unit unit _ _) = unit == interval checkTarget (Node interval' _ _ _ _) = interval' == interval -- ^ -- ifNothing (Node interval' _ _ _ _) = not $ isIncluded interval interval' && ((getUTCdayNum . getFrom) interval) `mod` 2 == 0 ifNothing _ = False isLeftMostTopNode :: CalendarReservations -> Bool isLeftMostTopNode (CalReservs _ []) = False isLeftMostTopNode (CalReservs calendar (reserv:_)) = fromMaybe False $ do i2 <- getZipInterval <$> leftMostTopNode i1 calendar return $ getFrom i2 == getFrom i1 && if getTo i2 == getTo i1 then (getFrom i1, getTo i1) == (getFrom i2, getTo i2) else getTo i2 < getTo i1 where i1 = reservPeriod reserv isRightMostTopNode :: CalendarReservations -> Bool isRightMostTopNode (CalReservs _ []) = False isRightMostTopNode (CalReservs calendar (reserv:_)) = fromMaybe False $ do i2 <- getZipInterval <$> rightMostTopNode i1 calendar return $ getTo i2 == getTo i1 && if getFrom i2 == getFrom i1 then (getFrom i1, getTo i1) == (getFrom i2, getTo i2) else getFrom i2 > getFrom i1 where i1 = reservPeriod reserv returnsCommonParent :: RandomZippers -> Bool returnsCommonParent (RandomZippers zip1 zip2) = fromMaybe False $ do parent <- commonParent zip1 zip2 let c1 = getZipInterval zip1 c2 = getZipInterval zip2 p= getZipInterval parent return $ getFrom p <= getFrom c1 && getFrom p <= getFrom c2 && getTo p >= getTo c1 && getTo p >= getTo c2 leftMostAndRightMostInTopMost :: CalendarReservations -> Bool leftMostAndRightMostInTopMost (CalReservs _ []) = False leftMostAndRightMostInTopMost (CalReservs calendar (reserv:_)) = fromMaybe False $ do ltmInterval <- getZipInterval <$> leftMostTopNode interval calendar rtmInterval <- getZipInterval <$> rightMostTopNode interval calendar topMostIntervals <- (fmap . fmap) getZipInterval (topMostNodes interval calendar) return $ (ltmInterval `elem` topMostIntervals) && (rtmInterval `elem` topMostIntervals) where interval = reservPeriod reserv outerMostNodesIncludeIntermediate :: CalendarReservations -> Bool outerMostNodesIncludeIntermediate (CalReservs _ []) = False outerMostNodesIncludeIntermediate (CalReservs calendar (reserv:_)) = fromMaybe False $ do from' <- (getFrom . getZipInterval) <$> leftMostTopNode interval calendar to' <- (getTo . getZipInterval) <$> rightMostTopNode interval calendar topMostIntervals <- (fmap . fmap) getZipInterval (topMostNodes interval calendar) -- ^ Each intermediate interval must be included in the leftmost and rightmost ones let numDays = round $ diffUTCTime to' from' / oneDay (UTCTime gregDay _) = from' (year, month, day) = toGregorian gregDay timePeriod <- makeTimePeriod year month day numDays return $ all (`isIncluded` timePeriod) topMostIntervals || timePeriod `elem` topMostIntervals where interval = reservPeriod reserv ifOnlyOneTopNodeItEqualsInterval :: CalendarReservations -> Bool ifOnlyOneTopNodeItEqualsInterval (CalReservs _ []) = False ifOnlyOneTopNodeItEqualsInterval (CalReservs calendar (reserv:_)) = fromMaybe False $ do topMostIntervals <- (fmap . fmap) getZipInterval (topMostNodes interval calendar) if length topMostIntervals == 1 then return $ head topMostIntervals == interval else return True where interval = reservPeriod reserv parentOfTopNodesNotIncluded :: CalendarReservations -> Bool parentOfTopNodesNotIncluded (CalReservs _ []) = False parentOfTopNodesNotIncluded (CalReservs calendar (reserv:_)) = fromMaybe False $ do from' <- (getFrom . getZipInterval) <$> leftMostTopNode interval calendar to' <- (getTo . getZipInterval) <$> rightMostTopNode interval calendar tmNodes <- topMostNodes interval calendar parentIntervals <- (fmap . fmap) getZipInterval (sequence $ filter isJust (goUp <$> tmNodes)) let numDays = round $ diffUTCTime to' from' / oneDay (UTCTime gregDay _) = from' (year, month, day) = toGregorian gregDay timePeriod <- makeTimePeriod year month day numDays return $ all (`notIncluded` timePeriod) parentIntervals where notIncluded i1 i2 = not $ isIncluded i1 i2 -- ^ -- interval = reservPeriod reserv
null
https://raw.githubusercontent.com/stackbuilders/scalendar/3778aef23f736878669613fb01dad6f4e153384d/test/SCalendarTest/Internal.hs
haskell
^ -- ^ Each intermediate interval must be included in the leftmost and rightmost ones ^ --
module SCalendarTest.Internal where import Data.List (elem) import Data.Maybe (isJust, fromMaybe) import Data.Time (UTCTime(..), toGregorian, diffUTCTime ) import SCalendarTest.Helpers (getUTCdayNum) import Time.SCalendar.Types ( Calendar(..) , Reservation(..) , TimePeriod , getFrom , getTo , isIncluded , powerOfTwo , oneDay , makeTimePeriod ) import Time.SCalendar.Zippers (goUp) import SCalendarTest.Arbitrary (RandomZippers(..), CalendarReservations(..)) import Time.SCalendar.Internal ( goToNode , leftMostTopNode , rightMostTopNode , topMostNodes , getZipInterval , commonParent ) alwaysGreateOrEqualThanN :: Int -> Bool alwaysGreateOrEqualThanN n = 2^ powerOfTwo n >= n eqIntervalsIfIncludeEachOther :: TimePeriod -> TimePeriod -> Bool eqIntervalsIfIncludeEachOther i j | isIncluded i j && isIncluded j i = i1 == j1 && i2 == j2 | isIncluded i j = not $ isIncluded j i | isIncluded j i = not $ isIncluded i j | not (isIncluded i j) && not (isIncluded j i) && wellFormed = i1 < j2 || j1 < i2 | otherwise = not wellFormed where (i1, i2) = (getFrom i, getTo i) (j1, j2) = (getFrom j, getTo j) wellFormed = i1 <= i2 && j1 <= j2 returnsTargetZipper :: Calendar -> TimePeriod -> Bool returnsTargetZipper calendar interval = let maybeCalendar = fst <$> goToNode interval calendar in maybe (ifNothing calendar) checkTarget maybeCalendar where checkTarget (Unit unit _ _) = unit == interval checkTarget (Node interval' _ _ _ _) = interval' == interval ifNothing (Node interval' _ _ _ _) = not $ isIncluded interval interval' && ((getUTCdayNum . getFrom) interval) `mod` 2 == 0 ifNothing _ = False isLeftMostTopNode :: CalendarReservations -> Bool isLeftMostTopNode (CalReservs _ []) = False isLeftMostTopNode (CalReservs calendar (reserv:_)) = fromMaybe False $ do i2 <- getZipInterval <$> leftMostTopNode i1 calendar return $ getFrom i2 == getFrom i1 && if getTo i2 == getTo i1 then (getFrom i1, getTo i1) == (getFrom i2, getTo i2) else getTo i2 < getTo i1 where i1 = reservPeriod reserv isRightMostTopNode :: CalendarReservations -> Bool isRightMostTopNode (CalReservs _ []) = False isRightMostTopNode (CalReservs calendar (reserv:_)) = fromMaybe False $ do i2 <- getZipInterval <$> rightMostTopNode i1 calendar return $ getTo i2 == getTo i1 && if getFrom i2 == getFrom i1 then (getFrom i1, getTo i1) == (getFrom i2, getTo i2) else getFrom i2 > getFrom i1 where i1 = reservPeriod reserv returnsCommonParent :: RandomZippers -> Bool returnsCommonParent (RandomZippers zip1 zip2) = fromMaybe False $ do parent <- commonParent zip1 zip2 let c1 = getZipInterval zip1 c2 = getZipInterval zip2 p= getZipInterval parent return $ getFrom p <= getFrom c1 && getFrom p <= getFrom c2 && getTo p >= getTo c1 && getTo p >= getTo c2 leftMostAndRightMostInTopMost :: CalendarReservations -> Bool leftMostAndRightMostInTopMost (CalReservs _ []) = False leftMostAndRightMostInTopMost (CalReservs calendar (reserv:_)) = fromMaybe False $ do ltmInterval <- getZipInterval <$> leftMostTopNode interval calendar rtmInterval <- getZipInterval <$> rightMostTopNode interval calendar topMostIntervals <- (fmap . fmap) getZipInterval (topMostNodes interval calendar) return $ (ltmInterval `elem` topMostIntervals) && (rtmInterval `elem` topMostIntervals) where interval = reservPeriod reserv outerMostNodesIncludeIntermediate :: CalendarReservations -> Bool outerMostNodesIncludeIntermediate (CalReservs _ []) = False outerMostNodesIncludeIntermediate (CalReservs calendar (reserv:_)) = fromMaybe False $ do from' <- (getFrom . getZipInterval) <$> leftMostTopNode interval calendar to' <- (getTo . getZipInterval) <$> rightMostTopNode interval calendar topMostIntervals <- (fmap . fmap) getZipInterval (topMostNodes interval calendar) let numDays = round $ diffUTCTime to' from' / oneDay (UTCTime gregDay _) = from' (year, month, day) = toGregorian gregDay timePeriod <- makeTimePeriod year month day numDays return $ all (`isIncluded` timePeriod) topMostIntervals || timePeriod `elem` topMostIntervals where interval = reservPeriod reserv ifOnlyOneTopNodeItEqualsInterval :: CalendarReservations -> Bool ifOnlyOneTopNodeItEqualsInterval (CalReservs _ []) = False ifOnlyOneTopNodeItEqualsInterval (CalReservs calendar (reserv:_)) = fromMaybe False $ do topMostIntervals <- (fmap . fmap) getZipInterval (topMostNodes interval calendar) if length topMostIntervals == 1 then return $ head topMostIntervals == interval else return True where interval = reservPeriod reserv parentOfTopNodesNotIncluded :: CalendarReservations -> Bool parentOfTopNodesNotIncluded (CalReservs _ []) = False parentOfTopNodesNotIncluded (CalReservs calendar (reserv:_)) = fromMaybe False $ do from' <- (getFrom . getZipInterval) <$> leftMostTopNode interval calendar to' <- (getTo . getZipInterval) <$> rightMostTopNode interval calendar tmNodes <- topMostNodes interval calendar parentIntervals <- (fmap . fmap) getZipInterval (sequence $ filter isJust (goUp <$> tmNodes)) let numDays = round $ diffUTCTime to' from' / oneDay (UTCTime gregDay _) = from' (year, month, day) = toGregorian gregDay timePeriod <- makeTimePeriod year month day numDays return $ all (`notIncluded` timePeriod) parentIntervals where notIncluded i1 i2 = not $ isIncluded i1 i2 interval = reservPeriod reserv
13a544cc3a00f13adb1c7e7fd141a60dc7b4ec7ff163da4685bfef483133ece5
amnh/poy5
addVec.ml
POY 5.1.1 . A phylogenetic analysis program using Dynamic Homologies . Copyright ( C ) 2014 , , , Ward Wheeler , and the American Museum of Natural History . (* *) (* This program is free software; you can redistribute it and/or modify *) it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or (* (at your option) any later version. *) (* *) (* This program is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU General Public License for more details. *) (* *) You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA type ct external register : unit -> unit = "add_CAML_register" external register_globals : unit -> unit = "add_CAML_register_mem" let () = register (); register_globals () external create : int array -> int array -> ct = "add_CAML_create" external median : ct -> ct -> ct = "add_CAML_median" external distance : ct -> ct -> float = "add_CAML_distance" external distance_2 : ct -> ct -> ct -> float = "add_CAML_distance_2" external distance_median : ct -> ct -> float * ct = "add_CAML_distance_and_median" external median_cost : ct -> float = "add_CAML_total" external compare_data : ct -> ct -> int = "add_CAML_compare_data" external copy : ct -> ct -> unit = "add_CAML_copy" external clone : ct -> ct = "add_CAML_dup" external pos_set_state : ct -> int -> int -> int -> unit = "add_CAML_set_state" external pos_get_max : ct -> int -> int = "add_CAML_get_max" external pos_get_min : ct -> int -> int = "add_CAML_get_min" external pos_get_cost : ct -> int -> float = "add_CAML_get_cost" external median_3 : ct -> ct -> ct -> ct -> ct = "add_CAML_median_3" external full_unioni : ct -> ct -> ct -> unit = "add_CAML_full_union" let full_union a b = let r = clone a in full_unioni a b r; r external mediani : ct -> ct -> ct -> unit = "add_CAML_median_imp" external to_string : ct -> string = "add_CAML_to_string" external cardinal : ct -> int = "add_CAML_cardinal" let print ct = Printf.printf "%s" (to_string ct)
null
https://raw.githubusercontent.com/amnh/poy5/da563a2339d3fa9c0110ae86cc35fad576f728ab/src/addVec.ml
ocaml
This program is free software; you can redistribute it and/or modify (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.
POY 5.1.1 . A phylogenetic analysis program using Dynamic Homologies . Copyright ( C ) 2014 , , , Ward Wheeler , and the American Museum of Natural History . it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA type ct external register : unit -> unit = "add_CAML_register" external register_globals : unit -> unit = "add_CAML_register_mem" let () = register (); register_globals () external create : int array -> int array -> ct = "add_CAML_create" external median : ct -> ct -> ct = "add_CAML_median" external distance : ct -> ct -> float = "add_CAML_distance" external distance_2 : ct -> ct -> ct -> float = "add_CAML_distance_2" external distance_median : ct -> ct -> float * ct = "add_CAML_distance_and_median" external median_cost : ct -> float = "add_CAML_total" external compare_data : ct -> ct -> int = "add_CAML_compare_data" external copy : ct -> ct -> unit = "add_CAML_copy" external clone : ct -> ct = "add_CAML_dup" external pos_set_state : ct -> int -> int -> int -> unit = "add_CAML_set_state" external pos_get_max : ct -> int -> int = "add_CAML_get_max" external pos_get_min : ct -> int -> int = "add_CAML_get_min" external pos_get_cost : ct -> int -> float = "add_CAML_get_cost" external median_3 : ct -> ct -> ct -> ct -> ct = "add_CAML_median_3" external full_unioni : ct -> ct -> ct -> unit = "add_CAML_full_union" let full_union a b = let r = clone a in full_unioni a b r; r external mediani : ct -> ct -> ct -> unit = "add_CAML_median_imp" external to_string : ct -> string = "add_CAML_to_string" external cardinal : ct -> int = "add_CAML_cardinal" let print ct = Printf.printf "%s" (to_string ct)
7ce206ab5fbaf07646abbcc9ce7d21258b20c3565f0a15e82402c1a80efc4faf
Risto-Stevcev/bs-declaredom
Test_Html_Node.ml
open BsTape open Test open! Html ;; let _ = Jsdom.init () let (tagName, outerHTML, ofNode) = Webapi.Dom.Element.(tagName, outerHTML, ofNode) let to_element x = x |> Html_Node.to_node |> ofNode |> Js.Option.getExn;; let tag_name x = x |. Html_Node.to_node |. ofNode |. Js.Option.getExn |. Webapi.Dom.Element.tagName;; test ~name:"node - a" @@ fun t -> begin let element = a ~aria:(Html.Aria.link ~aria_label:"foo" ()) ~href:"" ~target:`blank ~download:() ~rel:`nofollow ~rev:`bookmark ~hreflang:"en-US" ~_type:"html" ~referrerpolicy:`no_referrer [||] in t |> T.equal (tag_name element) "A"; t |> T.equal (Html_Node.show element) @@ "<a href=\"\" target=\"_blank\" download=\"\" "^ "rel=\"nofollow\" rev=\"bookmark\" hreflang=\"en-US\" type=\"html\" "^ "referrerpolicy=\"no-referrer\" aria-label=\"foo\"></a>"; t |> T.end_ end; test ~name:"node - area" @@ fun t -> begin let element = area ~aria:(Aria.link ~aria_label:"foo" ()) ~alt:"foobar" ~coords:[123;456] ~download:() ~href:"" ~hreflang:"en-US" ~rel:`nofollow ~shape:`circle ~target:`blank ~_type:"html" ~referrerpolicy:`no_referrer () in t |> T.equal (tag_name element) "AREA"; t |> T.equal (Html_Node.show element) @@ "<area alt=\"foobar\" coords=\"123,456\" download=\"\" "^ "href=\"\" hreflang=\"en-US\" rel=\"nofollow\" "^ "shape=\"circle\" target=\"_blank\" type=\"html\" "^ "referrerpolicy=\"no-referrer\" aria-label=\"foo\">"; t |> T.end_ end; test ~name:"node - audio" @@ fun t -> begin let element = audio ~aria:(Aria.application ~aria_label:"foo" ()) ~src:"foo.wav" ~crossorigin:`anonymous ~preload:`metadata ~autoplay:() ~loop:() ~muted:() ~controls:() [||] in t |> T.equal (tag_name element) "AUDIO"; t |> T.equal (Html_Node.show element) @@ "<audio src=\"foo.wav\" crossorigin=\"anonymous\" preload=\"metadata\" "^ "autoplay=\"\" loop=\"\" muted=\"\" controls=\"\" role=\"application\" "^ "aria-label=\"foo\"></audio>"; t |> T.end_ end; test ~name:"node - blockquote" @@ fun t -> begin let element = blockquote ~cite:"foo" [||] in t |> T.equal (tag_name element) "BLOCKQUOTE"; t |> T.equal (Html_Node.show element) @@ "<blockquote cite=\"foo\"></blockquote>"; t |> T.end_ end; test ~name:"node - button" @@ fun t -> begin let element = button ~autofocus:() ~disabled:() ~form:"foo" ~formaction:"foo.com" ~formenctype:`x_www_form_urlencoded ~formmethod:`post ~formnovalidate:() ~formtarget:`blank ~formelements:"bar" ~name:"baz" ~_type:`submit ~value:"qux" [||] in t |> T.equal (tag_name element) "BUTTON"; t |> T.equal (Html_Node.show element) @@ "<button autofocus=\"\" disabled=\"\" form=\"foo\" formaction=\"foo.com\" "^ "formenctype=\"x_www_form_urlencoded\" formmethod=\"post\" "^ "formnovalidate=\"\" formtarget=\"_blank\" formelements=\"bar\" "^ "name=\"baz\" type=\"submit\" value=\"qux\"></button>"; t |> T.end_ end; test ~name:"node - canvas" @@ fun t -> begin let element = canvas ~width:800 ~height:600 [||] in t |> T.equal (tag_name element) "CANVAS"; t |> T.equal (Html_Node.show element) @@ "<canvas width=\"800\" height=\"600\"></canvas>"; t |> T.end_ end; test ~name:"node - colgroup" @@ fun t -> begin let element = colgroup ~span:3 [||] in t |> T.equal (tag_name element) "COLGROUP"; t |> T.equal (Html_Node.show element) @@ "<colgroup span=\"3\"></colgroup>"; t |> T.end_ end; test ~name:"node - data" @@ fun t -> begin let element = data ~value:"foo" [||] in t |> T.equal (tag_name element) "DATA"; t |> T.equal (Html_Node.show element) @@ "<data value=\"foo\"></data>"; t |> T.end_ end; test ~name:"node - del" @@ fun t -> begin let date = Js.Date.make () in let element = del ~cite:"foo" ~datetime:date [||] in t |> T.equal (tag_name element) "DEL"; t |> T.equal (Html_Node.show element) @@ "<del cite=\"foo\" datetime=\""^ Js.Date.toISOString date ^"\"></del>"; t |> T.end_ end; test ~name:"node - details" @@ fun t -> begin let element = details ~_open:() [||] in t |> T.equal (tag_name element) "DETAILS"; t |> T.equal (Html_Node.show element) @@ "<details open=\"\"></details>"; t |> T.end_ end; test ~name:"node - dialog" @@ fun t -> begin let element = dialog ~_open:() [||] in t |> T.equal (tag_name element) "DIALOG"; t |> T.equal (Html_Node.show element) @@ "<dialog open=\"\"></dialog>"; t |> T.end_ end; test ~name:"node - fieldset" @@ fun t -> begin let element = fieldset ~form:"foo" ~name:"bar" ~disabled:() [||] in t |> T.equal (tag_name element) "FIELDSET"; t |> T.equal (Html_Node.show element) @@ "<fieldset disabled=\"\" form=\"foo\" name=\"bar\"></fieldset>"; t |> T.end_ end; test ~name:"node - form" @@ fun t -> begin let element = form ~accept_charset:"utf-8" ~action:"foo/" ~autocomplete:`off ~enctype:`x_www_form_urlencoded ~_method:`post ~name:"foo" ~novalidate:() ~target:`blank [||] in t |> T.equal (tag_name element) "FORM"; t |> T.equal (Html_Node.show element) @@ "<form accept-charset=\"utf-8\" action=\"foo/\" autocomplete=\"off\" "^ "enctype=\"x_www_form_urlencoded\" method=\"post\" name=\"foo\" "^ "novalidate=\"\" target=\"_blank\"></form>"; t |> T.end_ end; test ~name:"node - html" @@ fun t -> begin let element = html ~manifest:"foo" [||] in t |> T.equal (tag_name element) "HTML"; t |> T.equal (Html_Node.show element) @@ "<html manifest=\"foo\"></html>"; t |> T.end_ end; test ~name:"node - iframe" @@ fun t -> begin let element = iframe ~src:"foo" ~srcdoc:"bar" ~name:"baz" ~sandbox:`allow_forms ~allow:"qux" ~allowfullscreen:() ~allowpaymentrequest:() ~width:800 ~height:600 ~referrerpolicy:`no_referrer () in t |> T.equal (tag_name element) "IFRAME"; t |> T.equal (Html_Node.show element) @@ "<iframe src=\"foo\" srcdoc=\"bar\" name=\"baz\" sandbox=\"allow-forms\" "^ "allow=\"qux\" allowfullscreen=\"\" allowpaymentrequest=\"\" width=\"800\" "^ "height=\"600\" referrerpolicy=\"no-referrer\"></iframe>"; t |> T.end_ end; test ~name:"node - img" @@ fun t -> begin let element = img ~alt:"foo" ~src:"bar" ~srcset:"baz" ~sizes:"norf" ~crossorigin:`anonymous ~usemap:"qux" ~ismap:() ~width:800 ~height:600 ~referrerpolicy:`no_referrer ~decoding:`sync () in t |> T.equal (tag_name element) "IMG"; t |> T.equal (Html_Node.show element) @@ "<img alt=\"foo\" src=\"bar\" srcset=\"baz\" sizes=\"norf\" "^ "crossorigin=\"anonymous\" usemap=\"qux\" ismap=\"\" width=\"800\" "^ "height=\"600\" referrerpolicy=\"no-referrer\" decoding=\"sync\">"; t |> T.end_ end; test ~name:"node - input" @@ fun t -> begin let element = input ~_type:`text ~alt:"foo" ~autocomplete:`email ~autofocus:() ~checked:() ~dirname:`ltr ~disabled:() ~form:"foo" ~formaction:"bar" ~formenctype:`x_www_form_urlencoded ~formmethod:`post ~formnovalidate:() ~formtarget:`blank ~height:600 ~list:"baz" ~max:"100" ~maxlength:100 ~min:"0" ~minlength:0 ~multiple:() ~name:"qux" ~pattern:([%re "/[0-9]*/"]) ~readonly:() ~required:() ~size:200 ~src:"worble" ~step:`any ~width:800 () in t |> T.equal (tag_name element) "INPUT"; t |> T.equal (Html_Node.show element) @@ "<input alt=\"foo\" autocomplete=\"email\" autofocus=\"\" checked=\"\" "^ "dirname=\"ltr\" disabled=\"\" form=\"foo\" formaction=\"bar\" "^ "formenctype=\"x_www_form_urlencoded\" formmethod=\"post\" "^ "formnovalidate=\"\" formtarget=\"_blank\" height=\"600\" list=\"baz\" "^ "max=\"100\" maxlength=\"100\" min=\"0\" minlength=\"0\" multiple=\"\" "^ "name=\"qux\" pattern=\"[0-9]*\" readonly=\"\" required=\"\" size=\"200\" "^ "src=\"worble\" step=\"any\" type=\"text\" width=\"800\">"; t |> T.end_ end; test ~name:"node - ins" @@ fun t -> begin let date = Js.Date.make () in let element = ins ~cite:"foo" ~datetime:date [||] in t |> T.equal (tag_name element) "INS"; t |> T.equal (Html_Node.show element) @@ "<ins cite=\"foo\" datetime=\""^ Js.Date.toISOString date ^"\"></ins>"; t |> T.end_ end; test ~name:"node - label" @@ fun t -> begin let element = label ~_for:"foo" [||] in t |> T.equal (tag_name element) "LABEL"; t |> T.equal (Html_Node.show element) @@ "<label for=\"foo\"></label>"; t |> T.end_ end; test ~name:"node - link" @@ fun t -> begin let element = link ~rel:`nofollow ~href:"foobar.com" () and element2 = link ~rel:`stylesheet ~href:"foobar.com" () in t |> T.equal (tag_name element) "LINK"; t |> T.equal (Html_Node.show element) @@ "<link href=\"foobar.com\" rel=\"nofollow\">"; t |> T.equal (Html_Node.show element2) @@ "<link href=\"foobar.com\" rel=\"stylesheet\">"; t |> T.end_; end; test ~name:"node - meta" @@ fun t -> begin let element = meta ~name:"foo" ~http_equiv:`set_cookie ~content:"bar" ~charset:"baz" () in t |> T.equal (tag_name element) "META"; t |> T.equal (Html_Node.show element) @@ "<meta name=\"foo\" http-equiv=\"set-cookie\" content=\"bar\" "^ "charset=\"baz\">"; t |> T.end_ end; test ~name:"node - meter" @@ fun t -> begin let element = meter ~value:10. ~min:0. ~max:100. ~low:5. ~high:80. [||] in t |> T.equal (tag_name element) "METER"; t |> T.equal (Html_Node.show element) @@ "<meter value=\"10\" min=\"0\" max=\"100\" low=\"5\" high=\"80\"></meter>"; t |> T.end_ end; test ~name:"node - object" @@ fun t -> begin let element = object_ ~data:"foo" ~_type:"bar" ~typemustmatch:() ~name:"baz" ~usemap:"qux" ~form:"norf" ~width:800 ~height:600 [||] in t |> T.equal (tag_name element) "OBJECT"; t |> T.equal (Html_Node.show element) @@ "<object data=\"foo\" type=\"bar\" typemustmatch=\"\" name=\"baz\" "^ "usemap=\"qux\" form=\"norf\" width=\"800\" height=\"600\"></object>"; t |> T.end_ end; test ~name:"node - ol" @@ fun t -> begin let element = ol ~reversed:() ~start:3 ~_type:`upper_roman [||] in t |> T.equal (tag_name element) "OL"; t |> T.equal (Html_Node.show element) @@ "<ol reversed=\"\" start=\"3\" type=\"upper-roman\"></ol>"; t |> T.end_ end; test ~name:"node - optgroup" @@ fun t -> begin let element = optgroup ~disabled:() ~label:"foo" [||] in t |> T.equal (tag_name element) "OPTGROUP"; t |> T.equal (Html_Node.show element) @@ "<optgroup disabled=\"\" label=\"foo\"></optgroup>"; t |> T.end_ end; test ~name:"node - option" @@ fun t -> begin let element = option ~disabled:() ~label:"foo" ~selected:() ~value:"foo" [||] in t |> T.equal (tag_name element) "OPTION"; t |> T.equal (Html_Node.show element) @@ "<option disabled=\"\" label=\"foo\" selected=\"\" value=\"foo\"></option>"; t |> T.end_ end; test ~name:"node - output" @@ fun t -> begin let element = output ~_for:"foo" ~form:"bar" ~name:"baz" [||] in t |> T.equal (tag_name element) "OUTPUT"; t |> T.equal (Html_Node.show element) @@ "<output for=\"foo\" form=\"bar\" name=\"baz\"></output>"; t |> T.end_ end; test ~name:"node - param" @@ fun t -> begin let element = param ~name:"foo" ~value:"bar" () in t |> T.equal (tag_name element) "PARAM"; t |> T.equal (Html_Node.show element) @@ "<param name=\"foo\" value=\"bar\">"; t |> T.end_ end; test ~name:"node - progress" @@ fun t -> begin let element = progress ~value:10. ~max:100. [||] in t |> T.equal (tag_name element) "PROGRESS"; t |> T.equal (Html_Node.show element) @@ "<progress value=\"10\" max=\"100\"></progress>"; t |> T.end_ end; test ~name:"node - q" @@ fun t -> begin let element = q ~cite:"foo" [||] in t |> T.equal (tag_name element) "Q"; t |> T.equal (Html_Node.show element) @@ "<q cite=\"foo\"></q>"; t |> T.end_ end; test ~name:"node - script" @@ fun t -> begin let element = script ~src:"foo" ~_type:"bar" ~nomodule:() ~async:() ~defer:() ~crossorigin:`anonymous ~integrity:"baz" ~referrerpolicy:`no_referrer () and element' = inline_script "var foo = 123" in t |> T.equal (tag_name element) "SCRIPT"; t |> T.equal (Html_Node.show element) @@ "<script src=\"foo\" type=\"bar\" nomodule=\"\" async=\"\" defer=\"\" "^ "crossorigin=\"anonymous\" integrity=\"baz\" "^ "referrerpolicy=\"no-referrer\"></script>"; t |> T.equal (Html_Node.show element') "<script>var foo = 123</script>"; t |> T.end_ end; test ~name:"node - select" @@ fun t -> begin let element = select ~autocomplete:`email ~autofocus:() ~disabled:() ~form:"foo" ~multiple:() ~name:"bar" ~required:() ~size:10 [||] in t |> T.equal (tag_name element) "SELECT"; t |> T.equal (Html_Node.show element) @@ "<select autocomplete=\"email\" autofocus=\"\" disabled=\"\" form=\"foo\" "^ "multiple=\"\" name=\"bar\" required=\"\" size=\"10\"></select>"; t |> T.end_ end; test ~name:"node - slot" @@ fun t -> begin let element = slot ~name:"foo" [||] in t |> T.equal (tag_name element) "SLOT"; t |> T.equal (Html_Node.show element) @@ "<slot name=\"foo\"></slot>"; t |> T.end_ end; test ~name:"node - style" @@ fun t -> begin let element = style ~media:[Css_Media.Fn.max_width (`px 200.) |> Css_Media.Fn.to_query] ".foo { color: red; }" in t |> T.equal (tag_name element) "STYLE"; t |> T.equal (Html_Node.show element) @@ "<style media=\"@media (max-width: 200px)\">.foo { color: red; }</style>"; t |> T.end_ end; test ~name:"node - td" @@ fun t -> begin let element = td ~colspan:3 ~rowspan:2 ~headers:"foo" [||] in t |> T.equal (tag_name element) "TD"; t |> T.equal (Html_Node.show element) @@ "<td colspan=\"3\" rowspan=\"2\" headers=\"foo\"></td>"; t |> T.end_ end; test ~name:"node - textarea" @@ fun t -> begin let element = textarea ~autocomplete:`email ~autofocus:() ~dirname:`rtl ~disabled:() ~form:"foo" ~maxlength:100 ~minlength:0 ~name:"bar" ~placeholder:"baz" ~readonly:() ~required:() ~rows:4 ~wrap:`soft [||] in t |> T.equal (tag_name element) "TEXTAREA"; t |> T.equal (Html_Node.show element) @@ "<textarea autocomplete=\"email\" autofocus=\"\" dirname=\"rtl\" "^ "disabled=\"\" form=\"foo\" maxlength=\"100\" minlength=\"0\" name=\"bar\" "^ "placeholder=\"baz\" readonly=\"\" required=\"\" rows=\"4\" wrap=\"soft\">"^ "</textarea>"; t |> T.end_ end; test ~name:"node - th" @@ fun t -> begin let element = th ~colspan:3 ~rowspan:2 ~headers:"foo" ~scope:`row ~abbr:"baz" [||] in t |> T.equal (tag_name element) "TH"; t |> T.equal (Html_Node.show element) @@ "<th colspan=\"3\" rowspan=\"2\" headers=\"foo\" scope=\"row\" "^ "abbr=\"baz\"></th>"; t |> T.end_ end; test ~name:"node - time" @@ fun t -> begin let date = Js.Date.make () in let element = time ~datetime:date [||] in t |> T.equal (tag_name element) "TIME"; t |> T.equal (Html_Node.show element) @@ "<time datetime=\""^ Js.Date.toISOString date ^"\"></time>"; t |> T.end_ end; test ~name:"node - track" @@ fun t -> begin let element = track ~kind:`subtitles ~src:"foo" ~srclang:"bar" ~label:"baz" ~default:() () in t |> T.equal (tag_name element) "TRACK"; t |> T.equal (Html_Node.show element) @@ "<track kind=\"subtitles\" src=\"foo\" srclang=\"bar\" label=\"baz\" "^ "default=\"\">"; t |> T.end_ end; test ~name:"node - video" @@ fun t -> begin let element = video ~src:"foo" ~crossorigin:`anonymous ~poster:"bar" ~preload:`metadata ~autoplay:() ~playsinline:() ~loop:() ~muted:() ~controls:() ~width:800 ~height:600 [||] in t |> T.equal (tag_name element) "VIDEO"; t |> T.equal (Html_Node.show element) @@ "<video src=\"foo\" crossorigin=\"anonymous\" poster=\"bar\" "^ "preload=\"metadata\" autoplay=\"\" playsinline=\"\" loop=\"\" muted=\"\" "^ "controls=\"\" width=\"800\" height=\"600\"></video>"; t |> T.end_ end; test ~name:"node - global attributes" @@ fun t -> begin let element = span ~accesskey:"foo" ~autocapitalize:`on ~class_name:"bar" ~class_set:(Js.Dict.fromList [("baz", true); ("qux", false)]) ~contenteditable:() ~dataset:(Js.Dict.fromList [("a", "norf"); ("b", "worble")]) ~dir:`ltr ~draggable:() ~enterkeyhint:`search ~hidden:() ~id:"fizz" ~inputmode:`text ~is:"fuzz" ~itemid:"wizzle" ~itemprop:"wuzzle" ~itemref:"wazzle" ~itemscope:() ~itemtype:"foos" ~lang:"bars" ~nonce:"bazs" ~slot:"quxs" ~spellcheck:"norfs" ~tabindex:(-1) ~title:"hello" ~translate:`yes [||] in t |> T.equal (Html_Node.show element) @@ "<span accesskey=\"foo\" autocapitalize=\"on\" class=\"bar baz\" "^ "contenteditable=\"\" data-a=\"norf\" data-b=\"worble\" dir=\"ltr\" "^ "draggable=\"\" enterkeyhint=\"search\" hidden=\"\" id=\"fizz\" "^ "inputmode=\"text\" is=\"fuzz\" itemid=\"wizzle\" itemprop=\"wuzzle\" "^ "itemref=\"wazzle\" itemscope=\"\" itemtype=\"foos\" lang=\"bars\" "^ "nonce=\"bazs\" slot=\"quxs\" spellcheck=\"norfs\" tabindex=\"-1\" "^ "title=\"hello\" translate=\"yes\"></span>"; t |> T.end_ end; test ~name:"node - global aria attributes" @@ fun t -> begin let element = span ~aria:( Html.Aria.roletype ~aria_atomic:"a" ~aria_busy:() ~aria_controls:"c" ~aria_current:`date ~aria_describedby:"d" ~aria_details:"e" ~aria_disabled:() ~aria_dropeffect:[`copy;`move] ~aria_errormessage:"f" ~aria_flowto:"g" ~aria_grabbed:() ~aria_haspopup:`menu ~aria_hidden:() ~aria_invalid:`grammar ~aria_keyshortcuts:"h" ~aria_label:"i" ~aria_labelledby:"j" ~aria_live:`polite ~aria_owns:"k" ~aria_relevant:[`all;`text] ~aria_roledescription:"l" () ) [||] in t |> T.equal (Html_Node.show element) @@ "<span aria-atomic=\"a\" aria-busy=\"\" aria-controls=\"c\" "^ "aria-current=\"date\" aria-describedby=\"d\" aria-details=\"e\" "^ "aria-disabled=\"\" aria-dropeffect=\"copy move\" aria-errormessage=\"f\" "^ "aria-flowto=\"g\" aria-grabbed=\"\" aria-haspopup=\"menu\" "^ "aria-hidden=\"\" aria-invalid=\"grammar\" aria-keyshortcuts=\"h\" "^ "aria-label=\"i\" aria-labelledby=\"j\" aria-live=\"polite\" "^ "aria-owns=\"k\" aria-relevant=\"all text\" "^ "aria-roledescription=\"l\"></span>"; t |> T.end_ end; test ~name:"node - style" @@ fun t -> begin let element = span ~style:(Css_Style.inline ~color:`red ~font_size:(`px 12.) ()) [||] in t |> T.equal (Html_Node.show element) "<span style=\"color: red; font-size: 12px;\"></span>"; t |> T.end_ end; test ~name:"node - css module" @@ fun t -> begin let title = Css_Module.make @@ Css_Style.inline ~vertical_align:`initial ~color:`black () in let element = span ~css_module:title [||] in t |> T.equal (Html_Node.show element) "<span class=\"m72adb46b0467f9510ed02cc8fe77c7dd\"></span>"; t |> T.end_ end; test ~name:"node - text node" @@ fun t -> begin t |> T.equal (Html_Node.show_text @@ text "foo") "foo"; t |> T.end_ end; test ~name:"node - fragment node" @@ fun t -> begin let node = fragment [| span [|text "foo"|]; strong [|text "bar"|] |] in t |> T.equal (Html_Node.show_fragment node) "<span>foo</span>\n<strong>bar</strong>"; t |> T.end_ end; test ~name:"node - show_doc" @@ fun t -> begin let doc = html [| body [|text "hello world"|] |] in t |> T.equal (Html_Node.show_doc doc) "<!DOCTYPE html>\n<html><body>hello world</body></html>"; t |> T.end_ end;
null
https://raw.githubusercontent.com/Risto-Stevcev/bs-declaredom/6e2eb1f0daa32a7253caadbdd6392f3371807c88/test/html/Test_Html_Node.ml
ocaml
open BsTape open Test open! Html ;; let _ = Jsdom.init () let (tagName, outerHTML, ofNode) = Webapi.Dom.Element.(tagName, outerHTML, ofNode) let to_element x = x |> Html_Node.to_node |> ofNode |> Js.Option.getExn;; let tag_name x = x |. Html_Node.to_node |. ofNode |. Js.Option.getExn |. Webapi.Dom.Element.tagName;; test ~name:"node - a" @@ fun t -> begin let element = a ~aria:(Html.Aria.link ~aria_label:"foo" ()) ~href:"" ~target:`blank ~download:() ~rel:`nofollow ~rev:`bookmark ~hreflang:"en-US" ~_type:"html" ~referrerpolicy:`no_referrer [||] in t |> T.equal (tag_name element) "A"; t |> T.equal (Html_Node.show element) @@ "<a href=\"\" target=\"_blank\" download=\"\" "^ "rel=\"nofollow\" rev=\"bookmark\" hreflang=\"en-US\" type=\"html\" "^ "referrerpolicy=\"no-referrer\" aria-label=\"foo\"></a>"; t |> T.end_ end; test ~name:"node - area" @@ fun t -> begin let element = area ~aria:(Aria.link ~aria_label:"foo" ()) ~alt:"foobar" ~coords:[123;456] ~download:() ~href:"" ~hreflang:"en-US" ~rel:`nofollow ~shape:`circle ~target:`blank ~_type:"html" ~referrerpolicy:`no_referrer () in t |> T.equal (tag_name element) "AREA"; t |> T.equal (Html_Node.show element) @@ "<area alt=\"foobar\" coords=\"123,456\" download=\"\" "^ "href=\"\" hreflang=\"en-US\" rel=\"nofollow\" "^ "shape=\"circle\" target=\"_blank\" type=\"html\" "^ "referrerpolicy=\"no-referrer\" aria-label=\"foo\">"; t |> T.end_ end; test ~name:"node - audio" @@ fun t -> begin let element = audio ~aria:(Aria.application ~aria_label:"foo" ()) ~src:"foo.wav" ~crossorigin:`anonymous ~preload:`metadata ~autoplay:() ~loop:() ~muted:() ~controls:() [||] in t |> T.equal (tag_name element) "AUDIO"; t |> T.equal (Html_Node.show element) @@ "<audio src=\"foo.wav\" crossorigin=\"anonymous\" preload=\"metadata\" "^ "autoplay=\"\" loop=\"\" muted=\"\" controls=\"\" role=\"application\" "^ "aria-label=\"foo\"></audio>"; t |> T.end_ end; test ~name:"node - blockquote" @@ fun t -> begin let element = blockquote ~cite:"foo" [||] in t |> T.equal (tag_name element) "BLOCKQUOTE"; t |> T.equal (Html_Node.show element) @@ "<blockquote cite=\"foo\"></blockquote>"; t |> T.end_ end; test ~name:"node - button" @@ fun t -> begin let element = button ~autofocus:() ~disabled:() ~form:"foo" ~formaction:"foo.com" ~formenctype:`x_www_form_urlencoded ~formmethod:`post ~formnovalidate:() ~formtarget:`blank ~formelements:"bar" ~name:"baz" ~_type:`submit ~value:"qux" [||] in t |> T.equal (tag_name element) "BUTTON"; t |> T.equal (Html_Node.show element) @@ "<button autofocus=\"\" disabled=\"\" form=\"foo\" formaction=\"foo.com\" "^ "formenctype=\"x_www_form_urlencoded\" formmethod=\"post\" "^ "formnovalidate=\"\" formtarget=\"_blank\" formelements=\"bar\" "^ "name=\"baz\" type=\"submit\" value=\"qux\"></button>"; t |> T.end_ end; test ~name:"node - canvas" @@ fun t -> begin let element = canvas ~width:800 ~height:600 [||] in t |> T.equal (tag_name element) "CANVAS"; t |> T.equal (Html_Node.show element) @@ "<canvas width=\"800\" height=\"600\"></canvas>"; t |> T.end_ end; test ~name:"node - colgroup" @@ fun t -> begin let element = colgroup ~span:3 [||] in t |> T.equal (tag_name element) "COLGROUP"; t |> T.equal (Html_Node.show element) @@ "<colgroup span=\"3\"></colgroup>"; t |> T.end_ end; test ~name:"node - data" @@ fun t -> begin let element = data ~value:"foo" [||] in t |> T.equal (tag_name element) "DATA"; t |> T.equal (Html_Node.show element) @@ "<data value=\"foo\"></data>"; t |> T.end_ end; test ~name:"node - del" @@ fun t -> begin let date = Js.Date.make () in let element = del ~cite:"foo" ~datetime:date [||] in t |> T.equal (tag_name element) "DEL"; t |> T.equal (Html_Node.show element) @@ "<del cite=\"foo\" datetime=\""^ Js.Date.toISOString date ^"\"></del>"; t |> T.end_ end; test ~name:"node - details" @@ fun t -> begin let element = details ~_open:() [||] in t |> T.equal (tag_name element) "DETAILS"; t |> T.equal (Html_Node.show element) @@ "<details open=\"\"></details>"; t |> T.end_ end; test ~name:"node - dialog" @@ fun t -> begin let element = dialog ~_open:() [||] in t |> T.equal (tag_name element) "DIALOG"; t |> T.equal (Html_Node.show element) @@ "<dialog open=\"\"></dialog>"; t |> T.end_ end; test ~name:"node - fieldset" @@ fun t -> begin let element = fieldset ~form:"foo" ~name:"bar" ~disabled:() [||] in t |> T.equal (tag_name element) "FIELDSET"; t |> T.equal (Html_Node.show element) @@ "<fieldset disabled=\"\" form=\"foo\" name=\"bar\"></fieldset>"; t |> T.end_ end; test ~name:"node - form" @@ fun t -> begin let element = form ~accept_charset:"utf-8" ~action:"foo/" ~autocomplete:`off ~enctype:`x_www_form_urlencoded ~_method:`post ~name:"foo" ~novalidate:() ~target:`blank [||] in t |> T.equal (tag_name element) "FORM"; t |> T.equal (Html_Node.show element) @@ "<form accept-charset=\"utf-8\" action=\"foo/\" autocomplete=\"off\" "^ "enctype=\"x_www_form_urlencoded\" method=\"post\" name=\"foo\" "^ "novalidate=\"\" target=\"_blank\"></form>"; t |> T.end_ end; test ~name:"node - html" @@ fun t -> begin let element = html ~manifest:"foo" [||] in t |> T.equal (tag_name element) "HTML"; t |> T.equal (Html_Node.show element) @@ "<html manifest=\"foo\"></html>"; t |> T.end_ end; test ~name:"node - iframe" @@ fun t -> begin let element = iframe ~src:"foo" ~srcdoc:"bar" ~name:"baz" ~sandbox:`allow_forms ~allow:"qux" ~allowfullscreen:() ~allowpaymentrequest:() ~width:800 ~height:600 ~referrerpolicy:`no_referrer () in t |> T.equal (tag_name element) "IFRAME"; t |> T.equal (Html_Node.show element) @@ "<iframe src=\"foo\" srcdoc=\"bar\" name=\"baz\" sandbox=\"allow-forms\" "^ "allow=\"qux\" allowfullscreen=\"\" allowpaymentrequest=\"\" width=\"800\" "^ "height=\"600\" referrerpolicy=\"no-referrer\"></iframe>"; t |> T.end_ end; test ~name:"node - img" @@ fun t -> begin let element = img ~alt:"foo" ~src:"bar" ~srcset:"baz" ~sizes:"norf" ~crossorigin:`anonymous ~usemap:"qux" ~ismap:() ~width:800 ~height:600 ~referrerpolicy:`no_referrer ~decoding:`sync () in t |> T.equal (tag_name element) "IMG"; t |> T.equal (Html_Node.show element) @@ "<img alt=\"foo\" src=\"bar\" srcset=\"baz\" sizes=\"norf\" "^ "crossorigin=\"anonymous\" usemap=\"qux\" ismap=\"\" width=\"800\" "^ "height=\"600\" referrerpolicy=\"no-referrer\" decoding=\"sync\">"; t |> T.end_ end; test ~name:"node - input" @@ fun t -> begin let element = input ~_type:`text ~alt:"foo" ~autocomplete:`email ~autofocus:() ~checked:() ~dirname:`ltr ~disabled:() ~form:"foo" ~formaction:"bar" ~formenctype:`x_www_form_urlencoded ~formmethod:`post ~formnovalidate:() ~formtarget:`blank ~height:600 ~list:"baz" ~max:"100" ~maxlength:100 ~min:"0" ~minlength:0 ~multiple:() ~name:"qux" ~pattern:([%re "/[0-9]*/"]) ~readonly:() ~required:() ~size:200 ~src:"worble" ~step:`any ~width:800 () in t |> T.equal (tag_name element) "INPUT"; t |> T.equal (Html_Node.show element) @@ "<input alt=\"foo\" autocomplete=\"email\" autofocus=\"\" checked=\"\" "^ "dirname=\"ltr\" disabled=\"\" form=\"foo\" formaction=\"bar\" "^ "formenctype=\"x_www_form_urlencoded\" formmethod=\"post\" "^ "formnovalidate=\"\" formtarget=\"_blank\" height=\"600\" list=\"baz\" "^ "max=\"100\" maxlength=\"100\" min=\"0\" minlength=\"0\" multiple=\"\" "^ "name=\"qux\" pattern=\"[0-9]*\" readonly=\"\" required=\"\" size=\"200\" "^ "src=\"worble\" step=\"any\" type=\"text\" width=\"800\">"; t |> T.end_ end; test ~name:"node - ins" @@ fun t -> begin let date = Js.Date.make () in let element = ins ~cite:"foo" ~datetime:date [||] in t |> T.equal (tag_name element) "INS"; t |> T.equal (Html_Node.show element) @@ "<ins cite=\"foo\" datetime=\""^ Js.Date.toISOString date ^"\"></ins>"; t |> T.end_ end; test ~name:"node - label" @@ fun t -> begin let element = label ~_for:"foo" [||] in t |> T.equal (tag_name element) "LABEL"; t |> T.equal (Html_Node.show element) @@ "<label for=\"foo\"></label>"; t |> T.end_ end; test ~name:"node - link" @@ fun t -> begin let element = link ~rel:`nofollow ~href:"foobar.com" () and element2 = link ~rel:`stylesheet ~href:"foobar.com" () in t |> T.equal (tag_name element) "LINK"; t |> T.equal (Html_Node.show element) @@ "<link href=\"foobar.com\" rel=\"nofollow\">"; t |> T.equal (Html_Node.show element2) @@ "<link href=\"foobar.com\" rel=\"stylesheet\">"; t |> T.end_; end; test ~name:"node - meta" @@ fun t -> begin let element = meta ~name:"foo" ~http_equiv:`set_cookie ~content:"bar" ~charset:"baz" () in t |> T.equal (tag_name element) "META"; t |> T.equal (Html_Node.show element) @@ "<meta name=\"foo\" http-equiv=\"set-cookie\" content=\"bar\" "^ "charset=\"baz\">"; t |> T.end_ end; test ~name:"node - meter" @@ fun t -> begin let element = meter ~value:10. ~min:0. ~max:100. ~low:5. ~high:80. [||] in t |> T.equal (tag_name element) "METER"; t |> T.equal (Html_Node.show element) @@ "<meter value=\"10\" min=\"0\" max=\"100\" low=\"5\" high=\"80\"></meter>"; t |> T.end_ end; test ~name:"node - object" @@ fun t -> begin let element = object_ ~data:"foo" ~_type:"bar" ~typemustmatch:() ~name:"baz" ~usemap:"qux" ~form:"norf" ~width:800 ~height:600 [||] in t |> T.equal (tag_name element) "OBJECT"; t |> T.equal (Html_Node.show element) @@ "<object data=\"foo\" type=\"bar\" typemustmatch=\"\" name=\"baz\" "^ "usemap=\"qux\" form=\"norf\" width=\"800\" height=\"600\"></object>"; t |> T.end_ end; test ~name:"node - ol" @@ fun t -> begin let element = ol ~reversed:() ~start:3 ~_type:`upper_roman [||] in t |> T.equal (tag_name element) "OL"; t |> T.equal (Html_Node.show element) @@ "<ol reversed=\"\" start=\"3\" type=\"upper-roman\"></ol>"; t |> T.end_ end; test ~name:"node - optgroup" @@ fun t -> begin let element = optgroup ~disabled:() ~label:"foo" [||] in t |> T.equal (tag_name element) "OPTGROUP"; t |> T.equal (Html_Node.show element) @@ "<optgroup disabled=\"\" label=\"foo\"></optgroup>"; t |> T.end_ end; test ~name:"node - option" @@ fun t -> begin let element = option ~disabled:() ~label:"foo" ~selected:() ~value:"foo" [||] in t |> T.equal (tag_name element) "OPTION"; t |> T.equal (Html_Node.show element) @@ "<option disabled=\"\" label=\"foo\" selected=\"\" value=\"foo\"></option>"; t |> T.end_ end; test ~name:"node - output" @@ fun t -> begin let element = output ~_for:"foo" ~form:"bar" ~name:"baz" [||] in t |> T.equal (tag_name element) "OUTPUT"; t |> T.equal (Html_Node.show element) @@ "<output for=\"foo\" form=\"bar\" name=\"baz\"></output>"; t |> T.end_ end; test ~name:"node - param" @@ fun t -> begin let element = param ~name:"foo" ~value:"bar" () in t |> T.equal (tag_name element) "PARAM"; t |> T.equal (Html_Node.show element) @@ "<param name=\"foo\" value=\"bar\">"; t |> T.end_ end; test ~name:"node - progress" @@ fun t -> begin let element = progress ~value:10. ~max:100. [||] in t |> T.equal (tag_name element) "PROGRESS"; t |> T.equal (Html_Node.show element) @@ "<progress value=\"10\" max=\"100\"></progress>"; t |> T.end_ end; test ~name:"node - q" @@ fun t -> begin let element = q ~cite:"foo" [||] in t |> T.equal (tag_name element) "Q"; t |> T.equal (Html_Node.show element) @@ "<q cite=\"foo\"></q>"; t |> T.end_ end; test ~name:"node - script" @@ fun t -> begin let element = script ~src:"foo" ~_type:"bar" ~nomodule:() ~async:() ~defer:() ~crossorigin:`anonymous ~integrity:"baz" ~referrerpolicy:`no_referrer () and element' = inline_script "var foo = 123" in t |> T.equal (tag_name element) "SCRIPT"; t |> T.equal (Html_Node.show element) @@ "<script src=\"foo\" type=\"bar\" nomodule=\"\" async=\"\" defer=\"\" "^ "crossorigin=\"anonymous\" integrity=\"baz\" "^ "referrerpolicy=\"no-referrer\"></script>"; t |> T.equal (Html_Node.show element') "<script>var foo = 123</script>"; t |> T.end_ end; test ~name:"node - select" @@ fun t -> begin let element = select ~autocomplete:`email ~autofocus:() ~disabled:() ~form:"foo" ~multiple:() ~name:"bar" ~required:() ~size:10 [||] in t |> T.equal (tag_name element) "SELECT"; t |> T.equal (Html_Node.show element) @@ "<select autocomplete=\"email\" autofocus=\"\" disabled=\"\" form=\"foo\" "^ "multiple=\"\" name=\"bar\" required=\"\" size=\"10\"></select>"; t |> T.end_ end; test ~name:"node - slot" @@ fun t -> begin let element = slot ~name:"foo" [||] in t |> T.equal (tag_name element) "SLOT"; t |> T.equal (Html_Node.show element) @@ "<slot name=\"foo\"></slot>"; t |> T.end_ end; test ~name:"node - style" @@ fun t -> begin let element = style ~media:[Css_Media.Fn.max_width (`px 200.) |> Css_Media.Fn.to_query] ".foo { color: red; }" in t |> T.equal (tag_name element) "STYLE"; t |> T.equal (Html_Node.show element) @@ "<style media=\"@media (max-width: 200px)\">.foo { color: red; }</style>"; t |> T.end_ end; test ~name:"node - td" @@ fun t -> begin let element = td ~colspan:3 ~rowspan:2 ~headers:"foo" [||] in t |> T.equal (tag_name element) "TD"; t |> T.equal (Html_Node.show element) @@ "<td colspan=\"3\" rowspan=\"2\" headers=\"foo\"></td>"; t |> T.end_ end; test ~name:"node - textarea" @@ fun t -> begin let element = textarea ~autocomplete:`email ~autofocus:() ~dirname:`rtl ~disabled:() ~form:"foo" ~maxlength:100 ~minlength:0 ~name:"bar" ~placeholder:"baz" ~readonly:() ~required:() ~rows:4 ~wrap:`soft [||] in t |> T.equal (tag_name element) "TEXTAREA"; t |> T.equal (Html_Node.show element) @@ "<textarea autocomplete=\"email\" autofocus=\"\" dirname=\"rtl\" "^ "disabled=\"\" form=\"foo\" maxlength=\"100\" minlength=\"0\" name=\"bar\" "^ "placeholder=\"baz\" readonly=\"\" required=\"\" rows=\"4\" wrap=\"soft\">"^ "</textarea>"; t |> T.end_ end; test ~name:"node - th" @@ fun t -> begin let element = th ~colspan:3 ~rowspan:2 ~headers:"foo" ~scope:`row ~abbr:"baz" [||] in t |> T.equal (tag_name element) "TH"; t |> T.equal (Html_Node.show element) @@ "<th colspan=\"3\" rowspan=\"2\" headers=\"foo\" scope=\"row\" "^ "abbr=\"baz\"></th>"; t |> T.end_ end; test ~name:"node - time" @@ fun t -> begin let date = Js.Date.make () in let element = time ~datetime:date [||] in t |> T.equal (tag_name element) "TIME"; t |> T.equal (Html_Node.show element) @@ "<time datetime=\""^ Js.Date.toISOString date ^"\"></time>"; t |> T.end_ end; test ~name:"node - track" @@ fun t -> begin let element = track ~kind:`subtitles ~src:"foo" ~srclang:"bar" ~label:"baz" ~default:() () in t |> T.equal (tag_name element) "TRACK"; t |> T.equal (Html_Node.show element) @@ "<track kind=\"subtitles\" src=\"foo\" srclang=\"bar\" label=\"baz\" "^ "default=\"\">"; t |> T.end_ end; test ~name:"node - video" @@ fun t -> begin let element = video ~src:"foo" ~crossorigin:`anonymous ~poster:"bar" ~preload:`metadata ~autoplay:() ~playsinline:() ~loop:() ~muted:() ~controls:() ~width:800 ~height:600 [||] in t |> T.equal (tag_name element) "VIDEO"; t |> T.equal (Html_Node.show element) @@ "<video src=\"foo\" crossorigin=\"anonymous\" poster=\"bar\" "^ "preload=\"metadata\" autoplay=\"\" playsinline=\"\" loop=\"\" muted=\"\" "^ "controls=\"\" width=\"800\" height=\"600\"></video>"; t |> T.end_ end; test ~name:"node - global attributes" @@ fun t -> begin let element = span ~accesskey:"foo" ~autocapitalize:`on ~class_name:"bar" ~class_set:(Js.Dict.fromList [("baz", true); ("qux", false)]) ~contenteditable:() ~dataset:(Js.Dict.fromList [("a", "norf"); ("b", "worble")]) ~dir:`ltr ~draggable:() ~enterkeyhint:`search ~hidden:() ~id:"fizz" ~inputmode:`text ~is:"fuzz" ~itemid:"wizzle" ~itemprop:"wuzzle" ~itemref:"wazzle" ~itemscope:() ~itemtype:"foos" ~lang:"bars" ~nonce:"bazs" ~slot:"quxs" ~spellcheck:"norfs" ~tabindex:(-1) ~title:"hello" ~translate:`yes [||] in t |> T.equal (Html_Node.show element) @@ "<span accesskey=\"foo\" autocapitalize=\"on\" class=\"bar baz\" "^ "contenteditable=\"\" data-a=\"norf\" data-b=\"worble\" dir=\"ltr\" "^ "draggable=\"\" enterkeyhint=\"search\" hidden=\"\" id=\"fizz\" "^ "inputmode=\"text\" is=\"fuzz\" itemid=\"wizzle\" itemprop=\"wuzzle\" "^ "itemref=\"wazzle\" itemscope=\"\" itemtype=\"foos\" lang=\"bars\" "^ "nonce=\"bazs\" slot=\"quxs\" spellcheck=\"norfs\" tabindex=\"-1\" "^ "title=\"hello\" translate=\"yes\"></span>"; t |> T.end_ end; test ~name:"node - global aria attributes" @@ fun t -> begin let element = span ~aria:( Html.Aria.roletype ~aria_atomic:"a" ~aria_busy:() ~aria_controls:"c" ~aria_current:`date ~aria_describedby:"d" ~aria_details:"e" ~aria_disabled:() ~aria_dropeffect:[`copy;`move] ~aria_errormessage:"f" ~aria_flowto:"g" ~aria_grabbed:() ~aria_haspopup:`menu ~aria_hidden:() ~aria_invalid:`grammar ~aria_keyshortcuts:"h" ~aria_label:"i" ~aria_labelledby:"j" ~aria_live:`polite ~aria_owns:"k" ~aria_relevant:[`all;`text] ~aria_roledescription:"l" () ) [||] in t |> T.equal (Html_Node.show element) @@ "<span aria-atomic=\"a\" aria-busy=\"\" aria-controls=\"c\" "^ "aria-current=\"date\" aria-describedby=\"d\" aria-details=\"e\" "^ "aria-disabled=\"\" aria-dropeffect=\"copy move\" aria-errormessage=\"f\" "^ "aria-flowto=\"g\" aria-grabbed=\"\" aria-haspopup=\"menu\" "^ "aria-hidden=\"\" aria-invalid=\"grammar\" aria-keyshortcuts=\"h\" "^ "aria-label=\"i\" aria-labelledby=\"j\" aria-live=\"polite\" "^ "aria-owns=\"k\" aria-relevant=\"all text\" "^ "aria-roledescription=\"l\"></span>"; t |> T.end_ end; test ~name:"node - style" @@ fun t -> begin let element = span ~style:(Css_Style.inline ~color:`red ~font_size:(`px 12.) ()) [||] in t |> T.equal (Html_Node.show element) "<span style=\"color: red; font-size: 12px;\"></span>"; t |> T.end_ end; test ~name:"node - css module" @@ fun t -> begin let title = Css_Module.make @@ Css_Style.inline ~vertical_align:`initial ~color:`black () in let element = span ~css_module:title [||] in t |> T.equal (Html_Node.show element) "<span class=\"m72adb46b0467f9510ed02cc8fe77c7dd\"></span>"; t |> T.end_ end; test ~name:"node - text node" @@ fun t -> begin t |> T.equal (Html_Node.show_text @@ text "foo") "foo"; t |> T.end_ end; test ~name:"node - fragment node" @@ fun t -> begin let node = fragment [| span [|text "foo"|]; strong [|text "bar"|] |] in t |> T.equal (Html_Node.show_fragment node) "<span>foo</span>\n<strong>bar</strong>"; t |> T.end_ end; test ~name:"node - show_doc" @@ fun t -> begin let doc = html [| body [|text "hello world"|] |] in t |> T.equal (Html_Node.show_doc doc) "<!DOCTYPE html>\n<html><body>hello world</body></html>"; t |> T.end_ end;
a3cb8646553ccd81ea122cf98d7f1f415695fd81ad34322c91e16ec9f232dc28
terry-xiaoyu/learn-erlang-in-30-mins
chat_test.erl
-module(chat_test). -compile(export_all). -include("chat_protocol.hrl"). test_startup() -> route:ensure_db(). test_client_connected(UserID) -> chat_server:start_link(UserID, fake_socket). test_msg_received_from_client(ServerID, FromUserID, ToUserID, Payload) -> ServerID ! {tcp, #msg{from_userid=FromUserID, to_userid = ToUserID, payload = Payload}}, ok.
null
https://raw.githubusercontent.com/terry-xiaoyu/learn-erlang-in-30-mins/5bf4a7278ec89c264084c335c11d6f52a68ab76f/chat/chat_test.erl
erlang
-module(chat_test). -compile(export_all). -include("chat_protocol.hrl"). test_startup() -> route:ensure_db(). test_client_connected(UserID) -> chat_server:start_link(UserID, fake_socket). test_msg_received_from_client(ServerID, FromUserID, ToUserID, Payload) -> ServerID ! {tcp, #msg{from_userid=FromUserID, to_userid = ToUserID, payload = Payload}}, ok.
f2cca00c67cf8369cc7d6a08c6fa01867bdc59e080e043b5f279742ac115b693
antalsz/choose-your-own-derivative
Constraints.hs
# LANGUAGE KindSignatures , PolyKinds , TypeOperators , DataKinds , TypeFamilies , GADTs , UndecidableInstances , RankNTypes , AllowAmbiguousTypes , ConstraintKinds , ScopedTypeVariables , TypeApplications , InstanceSigs , MultiParamTypeClasses , FlexibleInstances , FunctionalDependencies , TypeInType , EmptyCase , StandaloneDeriving # TypeFamilies, GADTs, UndecidableInstances, RankNTypes, AllowAmbiguousTypes, ConstraintKinds, ScopedTypeVariables, TypeApplications, InstanceSigs, MultiParamTypeClasses, FlexibleInstances, FunctionalDependencies, TypeInType, EmptyCase, StandaloneDeriving #-} # OPTIONS_GHC -Wall -fno - warn - unticked - promoted - constructors # module Constraints where import Data.Constraint import Data.Type.Equality import Unsafe.Coerce import Data.Singletons import Data.Singletons.Prelude.Maybe import Data.Singletons.Prelude.Tuple import Data.Kind (type (*)) import Data.Typeable (Proxy(..)) -- Nats data Nat = Z | S Nat instance Eq Nat where Z == Z = True Z == S _ = False S _ == Z = False S m == S n = (m == n) type instance Z == Z= True type instance Z == S _ = False type instance S _ == Z = False type instance S m == S n = m == n type family Max (m :: Nat) (n :: Nat) :: Nat where Max 'Z n = n Max ('S m) 'Z = 'S m Max ('S m) ('S n) = 'S (Max m n) sMax :: Sing m -> Sing n -> Sing (Max m n) sMax SZ n = n sMax (SS m) SZ = SS m sMax (SS m) (SS n) = SS $ sMax m n type family (m :: Nat) >= (n :: Nat) :: Bool where Z >= Z = True S _ >= Z = True Z >= S _ = False S m >= S n = m >= n type family Or b1 b2 where Or True _ = True Or _ True = True Or False False = False type family (m :: Nat) + (n :: Nat) :: Nat where Z + n = n S m + n = S (m + n) data NEq ( m : : ) ( n : : ) where TODO eqEq :: forall (x :: Nat) y. ((x == y) ~True) => Sing x -> Sing y -> Dict (x ~ y) eqEq SZ SZ = Dict eqEq (SS x) (SS y) = case eqEq x y of Dict -> Dict eqSuccFalse :: forall (n :: Nat). Sing n -> Dict ((S n==n) ~ 'False, (n==S n) ~ 'False) eqSuccFalse SZ = Dict eqSuccFalse (SS n) = eqSuccFalse n eqRefl :: Sing (n :: Nat) -> Dict ((n==n)~'True) eqRefl SZ = Dict eqRefl (SS n) = case eqRefl n of Dict -> Dict geRefl :: Sing (n :: Nat) -> Dict ((n >= n) ~ True) geRefl SZ = Dict geRefl (SS n) = geRefl n succGeTrue :: (x >= S y) ~ True => Sing x -> Sing y -> Dict ((x == y) ~ False, (y == x) ~ False) succGeTrue (SS _) SZ = Dict succGeTrue (SS x) (SS y) = succGeTrue x y maxSymm :: Sing m -> Sing n -> Dict (Max m n ~ Max n m) maxSymm SZ SZ = Dict maxSymm (SS _) SZ = Dict maxSymm SZ (SS _) = Dict maxSymm (SS m) (SS n) = case maxSymm m n of Dict -> Dict maxGeTrans :: (x >= Max m n ~ True) => Sing x -> Sing m -> Sing n -> Dict (x >= m ~ True, x >= n ~ True) maxGeTrans SZ SZ SZ = Dict maxGeTrans (SS _) SZ SZ = Dict maxGeTrans SZ (SS _) m = case m of maxGeTrans (SS _) (SS _) SZ = Dict maxGeTrans (SS _) SZ (SS _) = Dict maxGeTrans (SS x) (SS m) (SS n) = maxGeTrans x m n geEqFalse :: x >= S y ~ True => Sing x -> Sing y -> Dict ((x == y) ~ False) geEqFalse (SS _) SZ = Dict geEqFalse (SS x) (SS y) = geEqFalse x y SNats -------------------------------------------------------- data instance Sing (n :: Nat) where SZ :: Sing 'Z SS :: Sing n -> Sing ('S n) deriving instance Show (Sing (n :: Nat)) instance SingI Z where sing = SZ instance SingI n => SingI (S n) where sing = SS sing compareSNat :: forall (m :: Nat) (n :: Nat). Sing m -> Sing n -> Bool compareSNat SZ SZ = True compareSNat (SS m) (SS n) = compareSNat m n compareSNat _ _ = False withDict :: Dict c -> (c => r) -> r withDict Dict r = r type family IfEqNat (x :: Nat) (y :: Nat) (t :: k) (f :: k) :: k where IfEqNat x x t _ = t IfEqNat _ _ _ f = f ifEqNat :: forall (x :: Nat) (y :: Nat) (r :: *). Sing x -> Sing y -> (((x == y) ~ 'True, x ~ y) => r) -> (((x == y) ~ 'False, (y==x) ~ 'False) => r) -> r ifEqNat x y t f | compareSNat x y = isTrue t | otherwise = isFalse f where isTrue :: (((x == y) ~ 'True, x ~ y) => r) -> r isTrue = withDict ((unsafeCoerce :: Dict ((),()) -> Dict ((x == y) ~ 'True, x ~ y)) Dict) isFalse :: (((x == y) ~ 'False, (y==x) ~ 'False) => r) -> r isFalse = withDict ((unsafeCoerce :: Dict ((),()) -> Dict (((x == y) ~ 'False), (y == x) ~ 'False)) Dict) Type - level maps indexed by ------------------------------ data Ctx a = Empty | N (NCtx a) data NCtx a = End a | Cons (Maybe a) (NCtx a) -- Singleton contexts data instance Sing (g :: Ctx a) where SEmpty :: Sing Empty SN :: Sing g -> Sing (N g) data instance Sing (g :: NCtx a) where SEnd :: Sing a -> Sing (End a) SCons :: Sing u -> Sing g -> Sing (Cons u g) instance SingI Empty where sing = SEmpty instance SingI g => SingI (N g) where sing = SN sing instance SingI a => SingI (End a) where sing = SEnd sing instance (SingI u, SingI g) => SingI (Cons u g) where sing = SCons sing sing class FinMap (map :: * -> *) where type Lookup (ctx :: map a) (i :: Nat) :: Maybe a type Add (ctx :: map a) (x :: Nat) (v :: a) :: map a type SingletonMap (x :: Nat) (v :: a) :: map a add :: Sing (ctx :: map a) -> Sing (x :: Nat) -> Sing (v :: a) -> Sing (Add ctx x v) singletonMap :: Sing (x :: Nat) -> Sing (v :: a) -> Sing (SingletonMap x v :: map a) lookupAddEq :: Sing (env :: map α) -> Sing x -> Proxy (a :: α) -> Dict (Lookup (Add env x a) x ~ Just a) lookupAddNEq :: ((x==y) ~ 'False) => Sing (env :: map α) -> Sing x -> Sing y -> Proxy s -> Dict (Lookup (Add env y s) x ~ Lookup env x) lookupSingletonEq :: Sing x -> Proxy (a :: α) -> Dict (Lookup (SingletonMap x a :: map α) x ~ Just a) lookupSingletonNEq :: forall a x y. ((x==y) ~ 'False) => Sing x -> Sing y -> Proxy a -> Dict (Lookup (SingletonMap y a :: map α) x ~ 'Nothing) instance FinMap Ctx where type Lookup Empty _ = Nothing type Lookup (N ctx) i = Lookup ctx i type Add Empty x v = SingletonMap x v type Add (N ctx) x v = N (Add ctx x v) type SingletonMap x v = N (SingletonMap x v) add SEmpty x v = singletonMap x v add (SN ctx) x v = SN $ add ctx x v singletonMap x v = SN $ singletonMap x v lookupAddEq SEmpty x a = lookupSingletonEq @Ctx x a lookupAddEq (SN ctx) x a = lookupAddEq ctx x a lookupAddNEq SEmpty x y a = lookupSingletonNEq @Ctx x y a lookupAddNEq (SN ctx) x y a = lookupAddNEq ctx x y a lookupSingletonEq x a = lookupSingletonEq @NCtx x a lookupSingletonNEq x y a = lookupSingletonNEq @NCtx x y a instance FinMap NCtx where type Lookup (End t) Z = Just t type Lookup (End t) (S _) = Nothing type Lookup (Cons u _) Z = u type Lookup (Cons _ ctx) (S x) = Lookup ctx x type Add (End _) Z v = End v type Add (End w) (S x) v = Cons (Just w) (SingletonMap x v) type Add (Cons _ ctx) Z v = Cons (Just v) ctx type Add (Cons u ctx) (S x) v = Cons u (Add ctx x v) add (SEnd _) SZ v = SEnd v add (SEnd a) (SS x) v = SCons (SJust a) (singletonMap x v) add (SCons _ ctx) SZ v = SCons (SJust v) ctx add (SCons u ctx) (SS x) v = SCons u (add ctx x v) type SingletonMap Z v = End v type SingletonMap (S x) v = Cons Nothing (SingletonMap x v) singletonMap SZ v = SEnd v singletonMap (SS x) v = SCons SNothing $ singletonMap x v lookupAddEq (SEnd _) SZ _ = Dict lookupAddEq (SEnd _) (SS x) v = lookupSingletonEq @NCtx x v lookupAddEq (SCons _ _) SZ _ = Dict lookupAddEq (SCons _ ctx) (SS x) a = lookupAddEq ctx x a lookupAddNEq (SEnd _) SZ (SS _) _ = Dict lookupAddNEq (SEnd _) (SS _) SZ _ = Dict lookupAddNEq (SEnd _) (SS x) (SS y) a = lookupSingletonNEq @NCtx x y a lookupAddNEq (SCons _ _) SZ (SS _) _ = Dict lookupAddNEq (SCons _ _) (SS _) SZ _ = Dict lookupAddNEq (SCons _ ctx) (SS x) (SS y) a = lookupAddNEq ctx x y a lookupSingletonEq SZ _ = Dict lookupSingletonEq (SS x) a = case lookupSingletonEq @NCtx x a of Dict -> Dict lookupSingletonNEq SZ (SS _) _ = Dict lookupSingletonNEq (SS _) SZ _ = Dict lookupSingletonNEq (SS x) (SS y) a = lookupSingletonNEq @NCtx x y a -- Lists type family Append (ls1 :: [k]) (ls2 :: [k]) :: [k] where Append '[] ls2 = ls2 Append (a ': ls1) ls2= a ': (Append ls1 ls2) --------------------------------------- -- Merge -- Merge ----------------------------------------- class Mergeable (a :: *) where type family Merge a (x :: a) (y :: a) :: a (⋓) :: Sing dom1 -> Sing dom2 -> Sing (Merge a dom1 dom2) mergeSymm :: Sing x -> Sing y -> Dict (Merge a x y ~ Merge a y x) instance Mergeable a => Mergeable (Maybe a) where type Merge (Maybe a) m Nothing = m type Merge (Maybe a) Nothing m = m type Merge (Maybe a) (Just x) (Just y) = Just (Merge a x y) SNothing ⋓ SNothing = SNothing SJust a ⋓ SNothing = SJust a SNothing ⋓ SJust a = SJust a SJust a ⋓ SJust b = SJust (a ⋓ b) mergeSymm SNothing SNothing = Dict mergeSymm (SJust _) SNothing = Dict mergeSymm SNothing (SJust _) = Dict mergeSymm (SJust a) (SJust b) = case mergeSymm a b of Dict -> Dict instance Mergeable () where type Merge () '() '() = '() STuple0 ⋓ STuple0 = STuple0 mergeSymm STuple0 STuple0 = Dict instance Mergeable a => Mergeable (NCtx a) where type Merge (NCtx a) (End x) (End y) = End (Merge a x y) type Merge (NCtx a) (End x) (Cons m g) = Cons (Merge (Maybe a) (Just x) m) g type Merge (NCtx a) (Cons m g) (End x) = Cons (Merge (Maybe a) m (Just x)) g type Merge (NCtx a) (Cons m1 g1) (Cons m2 g2) = Cons (Merge (Maybe a) m1 m2) (Merge (NCtx a) g1 g2) (SEnd a) ⋓ (SEnd b) = SEnd (a ⋓ b) (SEnd a1) ⋓ (SCons m2 g2) = SCons (SJust a1 ⋓ m2) g2 (SCons m1 g1) ⋓ (SEnd a2) = SCons (m1 ⋓ SJust a2) g1 SCons m1 g1 ⋓ SCons m2 g2 = SCons (m1 ⋓ m2) (g1 ⋓ g2) mergeSymm (SEnd a) (SEnd b) = case mergeSymm a b of Dict -> Dict mergeSymm (SEnd a) (SCons m _) = case mergeSymm (SJust a) m of Dict -> Dict mergeSymm (SCons m _) (SEnd b) = case mergeSymm m (SJust b) of Dict -> Dict mergeSymm (SCons m1 g1) (SCons m2 g2) = case mergeSymm m1 m2 of {Dict -> case mergeSymm g1 g2 of {Dict -> Dict }} instance Mergeable a => Mergeable (Ctx a) where type Merge (Ctx a) Empty Empty = Empty type Merge (Ctx a) Empty (N g) = N g type Merge (Ctx a) (N g) Empty = N g type Merge (Ctx a) (N g1) (N g2) = N (Merge (NCtx a) g1 g2) SEmpty ⋓ SEmpty = SEmpty SEmpty ⋓ SN g = SN g SN g ⋓ SEmpty = SN g SN g1 ⋓ SN g2 = SN (g1 ⋓ g2) mergeSymm SEmpty SEmpty = Dict mergeSymm SEmpty (SN _) = Dict mergeSymm (SN _) SEmpty = Dict mergeSymm (SN g1) (SN g2) = case mergeSymm g1 g2 of Dict -> Dict lookupMerge :: forall a (dom1 :: Ctx a) (dom2 :: Ctx a) (x :: Nat). Sing dom1 -> Sing dom2 -> Sing x -> Dict ( Lookup (Merge (Ctx a) dom1 dom2) x ~ Merge (Maybe a) (Lookup dom1 x) (Lookup dom2 x) ) lookupMerge SEmpty SEmpty _ = Dict lookupMerge SEmpty (SN _) _ = Dict lookupMerge (SN _) SEmpty _ = Dict lookupMerge (SN dom1) (SN dom2) x = lookupMergeN dom1 dom2 x lookupMergeN :: forall a (dom1 :: NCtx a) (dom2 :: NCtx a) (x :: Nat). Sing dom1 -> Sing dom2 -> Sing x -> Dict ( Lookup (Merge (NCtx a) dom1 dom2) x ~ Merge (Maybe a) (Lookup dom1 x) (Lookup dom2 x) ) lookupMergeN (SEnd _) (SEnd _) SZ = Dict lookupMergeN (SEnd _) (SEnd _) (SS _) = Dict lookupMergeN (SEnd _) (SCons _ _) SZ = Dict lookupMergeN (SEnd _) (SCons _ _) (SS _) = Dict lookupMergeN (SCons _ _) (SEnd _) SZ = Dict lookupMergeN (SCons _ _) (SEnd _) (SS _) = Dict lookupMergeN (SCons _ _) (SCons _ _) SZ = Dict lookupMergeN (SCons _ ctx1) (SCons _ ctx2) (SS n) = lookupMergeN ctx1 ctx2 n -- Remove Type Family type family Remove (x :: Nat) (g :: Ctx a) :: Ctx a where Remove _ Empty = Empty Remove x (N g) = RemoveN x g type family RemoveN (x :: Nat) (g :: NCtx a) :: Ctx a where RemoveN Z (End s) = Empty RemoveN (S _) (End s) = N (End s) RemoveN Z (Cons _ g) = N (Cons Nothing g) RemoveN (S x) (Cons u g) = Cons' u (RemoveN x g) remove :: Sing x -> Sing g -> Sing (Remove x g) remove _ SEmpty = SEmpty remove x (SN g) = removeN x g removeN :: Sing x -> Sing g -> Sing (RemoveN x g) removeN SZ (SEnd _) = SEmpty removeN (SS _) (SEnd s) = SN $ SEnd s removeN SZ (SCons _ g) = SN $ SCons SNothing g removeN (SS x) (SCons u g) = sCons u $ removeN x g type family Cons' (u :: Maybe a) (g :: Ctx a) :: Ctx a where Cons' Nothing Empty = Empty Cons' (Just x) Empty = N (End x) Cons' u (N g) = N (Cons u g) sCons :: Sing u -> Sing g -> Sing (Cons' u g) sCons SNothing SEmpty = SEmpty sCons (SJust x) SEmpty = SN $ SEnd x sCons u (SN g) = SN $ SCons u g lookupRemove :: Sing x -> Sing g -> Dict (Lookup (Remove x g) x ~ Nothing) lookupRemove _ SEmpty = Dict lookupRemove x (SN g) = lookupRemoveN x g lookupRemoveN :: Sing x -> Sing g -> Dict (Lookup (RemoveN x g) x ~ Nothing) lookupRemoveN SZ (SEnd _) = Dict lookupRemoveN (SS _) (SEnd _) = Dict lookupRemoveN SZ (SCons _ _) = Dict lookupRemoveN (SS x) (SCons u g) = case lookupRemoveN x g of {Dict -> case lookupCons' x u (removeN x g) of {Dict -> Dict}} lookupRemoveNEq :: (x == y) ~ False => Sing x -> Sing y -> Sing g -> Dict (Lookup (Remove y g) x ~ Lookup g x) lookupRemoveNEq _ _ SEmpty = Dict lookupRemoveNEq x y (SN γ) = lookupRemoveNNEq x y γ lookupRemoveNNEq :: (x == y) ~ False => Sing x -> Sing y -> Sing g -> Dict (Lookup (RemoveN y g) x ~ Lookup g x) lookupRemoveNNEq (SS _) SZ (SEnd _) = Dict lookupRemoveNNEq _ (SS _) (SEnd _) = Dict lookupRemoveNNEq (SS _) SZ (SCons _ _) = Dict lookupRemoveNNEq SZ (SS y) (SCons u g) = lookupCons'Z u (removeN y g) lookupRemoveNNEq (SS x) (SS y) (SCons u g) = case lookupCons' x u (removeN y g) of Dict -> lookupRemoveNNEq x y g lookupCons'Z :: Sing u -> Sing g -> Dict (Lookup (Cons' u g) Z ~ u) lookupCons'Z SNothing SEmpty = Dict lookupCons'Z (SJust _) SEmpty = Dict lookupCons'Z _ (SN _) = Dict lookupCons' :: Sing x -> Sing u -> Sing g -> Dict (Lookup (Cons' u g) (S x) ~ Lookup g x) lookupCons' _ SNothing SEmpty = Dict lookupCons' _ (SJust _) SEmpty = Dict lookupCons' _ _ (SN _) = Dict Proofs about the intersection of Add and Merge ( and Singleton ) addMergeSingleton :: Sing γ -> Sing x -> Dict (Add γ x '() ~ Merge (NCtx ()) (SingletonMap x '()) γ) addMergeSingleton (SEnd STuple0) SZ = Dict addMergeSingleton (SEnd STuple0) (SS _) = Dict addMergeSingleton (SCons SNothing _) SZ = Dict addMergeSingleton (SCons (SJust STuple0) _) SZ = Dict addMergeSingleton (SCons _ γ) (SS x) = case addMergeSingleton γ x of Dict -> Dict addDistrL :: Sing g1 -> Sing g2 -> Sing x -> Dict (Add (Merge (Ctx ()) g1 g2) x '() ~ Merge (Ctx ()) (Add g1 x '()) g2) addDistrL SEmpty SEmpty _ = Dict -- Add ([] ⋓ N γ) x = Add (N γ) x -- vs ( Add [ ] x ) ⋓ N γ = ( ) ⋓ N γ addDistrL SEmpty (SN γ) x = case addMergeSingleton γ x of Dict -> Dict addDistrL (SN _) SEmpty _ = Dict addDistrL (SN γ1) (SN γ2) x = case addNDistrL γ1 γ2 x of Dict -> Dict addNDistrL :: Sing g1 -> Sing g2 -> Sing x -> Dict (Add (Merge (NCtx ()) g1 g2) x '() ~ Merge (NCtx ()) (Add g1 x '()) g2) addNDistrL (SEnd STuple0) (SEnd STuple0) SZ = Dict addNDistrL (SEnd STuple0) (SEnd STuple0) (SS _) = Dict addNDistrL (SEnd STuple0) (SCons SNothing _) SZ = Dict addNDistrL (SEnd STuple0) (SCons (SJust STuple0) _) SZ = Dict -- End () ⋓ u :: γ = (Just () ⋓ u) :: γ Add ^ ( SS x ) = ( Just ( ) ⋓ u ) : : Add γ x -- vs -- (Add (End ()) (S x)) ⋓ (u :: γ) = ( Just ( ) : : x ( ) ) ⋓ ( u : : γ ) = ( Just ( ) ⋓ u ) : : ( ( ) ⋓ γ ) addNDistrL (SEnd STuple0) (SCons _ γ) (SS x) = case addMergeSingleton γ x of Dict -> Dict addNDistrL (SCons _ _) (SEnd STuple0) SZ = Dict addNDistrL (SCons _ _) (SEnd STuple0) (SS _) = Dict Add ( ( u1 : : γ1 ) ⋓ ( u2 : : γ2 ) ) 0 = Add ( ( u1 ⋓ u2 ) : : ( γ1 ⋓ γ2 ) ) 0 -- = (Just ()) :: γ1 ⋓ γ2 -- vs -- (Add (u1 :: γ1) 0) ⋓ (u2 :: γ2) -- = (Just () :: γ1) ⋓ (u2 :: γ2) -- = (Just () ⋓ u2) :: γ1 ⋓ γ2 addNDistrL (SCons _ _) (SCons u2 _) SZ = case u2 of SJust STuple0 -> Dict SNothing -> Dict -- Add ((u1 :: γ1) ⋓ (u2 :: γ2)) (S x) -- = Add ((u1 ⋓ u2) :: (γ1 ⋓ γ2)) (S x) -- = (u1 ⋓ u2) :: (Add (γ1 ⋓ γ2) x) -- vs -- (Add (u1 :: γ1) (S x)) ⋓ (u2 :: γ2) -- = (u1 :: Add γ1 x) ⋓ (u2 :: γ2) -- = (u1 ⋓ u2) :: (Add γ1 x ⋓ γ2) addNDistrL (SCons _ γ1) (SCons _ γ2) (SS x) = case addNDistrL γ1 γ2 x of Dict -> Dict
null
https://raw.githubusercontent.com/antalsz/choose-your-own-derivative/29897118314da416023977b317971ba4f840a5eb/src/Constraints.hs
haskell
Nats ------------------------------------------------------ ---------------------------- Singleton contexts Lists ------------------------------------- Merge Merge ----------------------------------------- Remove Type Family Add ([] ⋓ N γ) x = Add (N γ) x vs End () ⋓ u :: γ = (Just () ⋓ u) :: γ vs (Add (End ()) (S x)) ⋓ (u :: γ) = (Just ()) :: γ1 ⋓ γ2 vs (Add (u1 :: γ1) 0) ⋓ (u2 :: γ2) = (Just () :: γ1) ⋓ (u2 :: γ2) = (Just () ⋓ u2) :: γ1 ⋓ γ2 Add ((u1 :: γ1) ⋓ (u2 :: γ2)) (S x) = Add ((u1 ⋓ u2) :: (γ1 ⋓ γ2)) (S x) = (u1 ⋓ u2) :: (Add (γ1 ⋓ γ2) x) vs (Add (u1 :: γ1) (S x)) ⋓ (u2 :: γ2) = (u1 :: Add γ1 x) ⋓ (u2 :: γ2) = (u1 ⋓ u2) :: (Add γ1 x ⋓ γ2)
# LANGUAGE KindSignatures , PolyKinds , TypeOperators , DataKinds , TypeFamilies , GADTs , UndecidableInstances , RankNTypes , AllowAmbiguousTypes , ConstraintKinds , ScopedTypeVariables , TypeApplications , InstanceSigs , MultiParamTypeClasses , FlexibleInstances , FunctionalDependencies , TypeInType , EmptyCase , StandaloneDeriving # TypeFamilies, GADTs, UndecidableInstances, RankNTypes, AllowAmbiguousTypes, ConstraintKinds, ScopedTypeVariables, TypeApplications, InstanceSigs, MultiParamTypeClasses, FlexibleInstances, FunctionalDependencies, TypeInType, EmptyCase, StandaloneDeriving #-} # OPTIONS_GHC -Wall -fno - warn - unticked - promoted - constructors # module Constraints where import Data.Constraint import Data.Type.Equality import Unsafe.Coerce import Data.Singletons import Data.Singletons.Prelude.Maybe import Data.Singletons.Prelude.Tuple import Data.Kind (type (*)) import Data.Typeable (Proxy(..)) data Nat = Z | S Nat instance Eq Nat where Z == Z = True Z == S _ = False S _ == Z = False S m == S n = (m == n) type instance Z == Z= True type instance Z == S _ = False type instance S _ == Z = False type instance S m == S n = m == n type family Max (m :: Nat) (n :: Nat) :: Nat where Max 'Z n = n Max ('S m) 'Z = 'S m Max ('S m) ('S n) = 'S (Max m n) sMax :: Sing m -> Sing n -> Sing (Max m n) sMax SZ n = n sMax (SS m) SZ = SS m sMax (SS m) (SS n) = SS $ sMax m n type family (m :: Nat) >= (n :: Nat) :: Bool where Z >= Z = True S _ >= Z = True Z >= S _ = False S m >= S n = m >= n type family Or b1 b2 where Or True _ = True Or _ True = True Or False False = False type family (m :: Nat) + (n :: Nat) :: Nat where Z + n = n S m + n = S (m + n) data NEq ( m : : ) ( n : : ) where TODO eqEq :: forall (x :: Nat) y. ((x == y) ~True) => Sing x -> Sing y -> Dict (x ~ y) eqEq SZ SZ = Dict eqEq (SS x) (SS y) = case eqEq x y of Dict -> Dict eqSuccFalse :: forall (n :: Nat). Sing n -> Dict ((S n==n) ~ 'False, (n==S n) ~ 'False) eqSuccFalse SZ = Dict eqSuccFalse (SS n) = eqSuccFalse n eqRefl :: Sing (n :: Nat) -> Dict ((n==n)~'True) eqRefl SZ = Dict eqRefl (SS n) = case eqRefl n of Dict -> Dict geRefl :: Sing (n :: Nat) -> Dict ((n >= n) ~ True) geRefl SZ = Dict geRefl (SS n) = geRefl n succGeTrue :: (x >= S y) ~ True => Sing x -> Sing y -> Dict ((x == y) ~ False, (y == x) ~ False) succGeTrue (SS _) SZ = Dict succGeTrue (SS x) (SS y) = succGeTrue x y maxSymm :: Sing m -> Sing n -> Dict (Max m n ~ Max n m) maxSymm SZ SZ = Dict maxSymm (SS _) SZ = Dict maxSymm SZ (SS _) = Dict maxSymm (SS m) (SS n) = case maxSymm m n of Dict -> Dict maxGeTrans :: (x >= Max m n ~ True) => Sing x -> Sing m -> Sing n -> Dict (x >= m ~ True, x >= n ~ True) maxGeTrans SZ SZ SZ = Dict maxGeTrans (SS _) SZ SZ = Dict maxGeTrans SZ (SS _) m = case m of maxGeTrans (SS _) (SS _) SZ = Dict maxGeTrans (SS _) SZ (SS _) = Dict maxGeTrans (SS x) (SS m) (SS n) = maxGeTrans x m n geEqFalse :: x >= S y ~ True => Sing x -> Sing y -> Dict ((x == y) ~ False) geEqFalse (SS _) SZ = Dict geEqFalse (SS x) (SS y) = geEqFalse x y data instance Sing (n :: Nat) where SZ :: Sing 'Z SS :: Sing n -> Sing ('S n) deriving instance Show (Sing (n :: Nat)) instance SingI Z where sing = SZ instance SingI n => SingI (S n) where sing = SS sing compareSNat :: forall (m :: Nat) (n :: Nat). Sing m -> Sing n -> Bool compareSNat SZ SZ = True compareSNat (SS m) (SS n) = compareSNat m n compareSNat _ _ = False withDict :: Dict c -> (c => r) -> r withDict Dict r = r type family IfEqNat (x :: Nat) (y :: Nat) (t :: k) (f :: k) :: k where IfEqNat x x t _ = t IfEqNat _ _ _ f = f ifEqNat :: forall (x :: Nat) (y :: Nat) (r :: *). Sing x -> Sing y -> (((x == y) ~ 'True, x ~ y) => r) -> (((x == y) ~ 'False, (y==x) ~ 'False) => r) -> r ifEqNat x y t f | compareSNat x y = isTrue t | otherwise = isFalse f where isTrue :: (((x == y) ~ 'True, x ~ y) => r) -> r isTrue = withDict ((unsafeCoerce :: Dict ((),()) -> Dict ((x == y) ~ 'True, x ~ y)) Dict) isFalse :: (((x == y) ~ 'False, (y==x) ~ 'False) => r) -> r isFalse = withDict ((unsafeCoerce :: Dict ((),()) -> Dict (((x == y) ~ 'False), (y == x) ~ 'False)) Dict) data Ctx a = Empty | N (NCtx a) data NCtx a = End a | Cons (Maybe a) (NCtx a) data instance Sing (g :: Ctx a) where SEmpty :: Sing Empty SN :: Sing g -> Sing (N g) data instance Sing (g :: NCtx a) where SEnd :: Sing a -> Sing (End a) SCons :: Sing u -> Sing g -> Sing (Cons u g) instance SingI Empty where sing = SEmpty instance SingI g => SingI (N g) where sing = SN sing instance SingI a => SingI (End a) where sing = SEnd sing instance (SingI u, SingI g) => SingI (Cons u g) where sing = SCons sing sing class FinMap (map :: * -> *) where type Lookup (ctx :: map a) (i :: Nat) :: Maybe a type Add (ctx :: map a) (x :: Nat) (v :: a) :: map a type SingletonMap (x :: Nat) (v :: a) :: map a add :: Sing (ctx :: map a) -> Sing (x :: Nat) -> Sing (v :: a) -> Sing (Add ctx x v) singletonMap :: Sing (x :: Nat) -> Sing (v :: a) -> Sing (SingletonMap x v :: map a) lookupAddEq :: Sing (env :: map α) -> Sing x -> Proxy (a :: α) -> Dict (Lookup (Add env x a) x ~ Just a) lookupAddNEq :: ((x==y) ~ 'False) => Sing (env :: map α) -> Sing x -> Sing y -> Proxy s -> Dict (Lookup (Add env y s) x ~ Lookup env x) lookupSingletonEq :: Sing x -> Proxy (a :: α) -> Dict (Lookup (SingletonMap x a :: map α) x ~ Just a) lookupSingletonNEq :: forall a x y. ((x==y) ~ 'False) => Sing x -> Sing y -> Proxy a -> Dict (Lookup (SingletonMap y a :: map α) x ~ 'Nothing) instance FinMap Ctx where type Lookup Empty _ = Nothing type Lookup (N ctx) i = Lookup ctx i type Add Empty x v = SingletonMap x v type Add (N ctx) x v = N (Add ctx x v) type SingletonMap x v = N (SingletonMap x v) add SEmpty x v = singletonMap x v add (SN ctx) x v = SN $ add ctx x v singletonMap x v = SN $ singletonMap x v lookupAddEq SEmpty x a = lookupSingletonEq @Ctx x a lookupAddEq (SN ctx) x a = lookupAddEq ctx x a lookupAddNEq SEmpty x y a = lookupSingletonNEq @Ctx x y a lookupAddNEq (SN ctx) x y a = lookupAddNEq ctx x y a lookupSingletonEq x a = lookupSingletonEq @NCtx x a lookupSingletonNEq x y a = lookupSingletonNEq @NCtx x y a instance FinMap NCtx where type Lookup (End t) Z = Just t type Lookup (End t) (S _) = Nothing type Lookup (Cons u _) Z = u type Lookup (Cons _ ctx) (S x) = Lookup ctx x type Add (End _) Z v = End v type Add (End w) (S x) v = Cons (Just w) (SingletonMap x v) type Add (Cons _ ctx) Z v = Cons (Just v) ctx type Add (Cons u ctx) (S x) v = Cons u (Add ctx x v) add (SEnd _) SZ v = SEnd v add (SEnd a) (SS x) v = SCons (SJust a) (singletonMap x v) add (SCons _ ctx) SZ v = SCons (SJust v) ctx add (SCons u ctx) (SS x) v = SCons u (add ctx x v) type SingletonMap Z v = End v type SingletonMap (S x) v = Cons Nothing (SingletonMap x v) singletonMap SZ v = SEnd v singletonMap (SS x) v = SCons SNothing $ singletonMap x v lookupAddEq (SEnd _) SZ _ = Dict lookupAddEq (SEnd _) (SS x) v = lookupSingletonEq @NCtx x v lookupAddEq (SCons _ _) SZ _ = Dict lookupAddEq (SCons _ ctx) (SS x) a = lookupAddEq ctx x a lookupAddNEq (SEnd _) SZ (SS _) _ = Dict lookupAddNEq (SEnd _) (SS _) SZ _ = Dict lookupAddNEq (SEnd _) (SS x) (SS y) a = lookupSingletonNEq @NCtx x y a lookupAddNEq (SCons _ _) SZ (SS _) _ = Dict lookupAddNEq (SCons _ _) (SS _) SZ _ = Dict lookupAddNEq (SCons _ ctx) (SS x) (SS y) a = lookupAddNEq ctx x y a lookupSingletonEq SZ _ = Dict lookupSingletonEq (SS x) a = case lookupSingletonEq @NCtx x a of Dict -> Dict lookupSingletonNEq SZ (SS _) _ = Dict lookupSingletonNEq (SS _) SZ _ = Dict lookupSingletonNEq (SS x) (SS y) a = lookupSingletonNEq @NCtx x y a type family Append (ls1 :: [k]) (ls2 :: [k]) :: [k] where Append '[] ls2 = ls2 Append (a ': ls1) ls2= a ': (Append ls1 ls2) class Mergeable (a :: *) where type family Merge a (x :: a) (y :: a) :: a (⋓) :: Sing dom1 -> Sing dom2 -> Sing (Merge a dom1 dom2) mergeSymm :: Sing x -> Sing y -> Dict (Merge a x y ~ Merge a y x) instance Mergeable a => Mergeable (Maybe a) where type Merge (Maybe a) m Nothing = m type Merge (Maybe a) Nothing m = m type Merge (Maybe a) (Just x) (Just y) = Just (Merge a x y) SNothing ⋓ SNothing = SNothing SJust a ⋓ SNothing = SJust a SNothing ⋓ SJust a = SJust a SJust a ⋓ SJust b = SJust (a ⋓ b) mergeSymm SNothing SNothing = Dict mergeSymm (SJust _) SNothing = Dict mergeSymm SNothing (SJust _) = Dict mergeSymm (SJust a) (SJust b) = case mergeSymm a b of Dict -> Dict instance Mergeable () where type Merge () '() '() = '() STuple0 ⋓ STuple0 = STuple0 mergeSymm STuple0 STuple0 = Dict instance Mergeable a => Mergeable (NCtx a) where type Merge (NCtx a) (End x) (End y) = End (Merge a x y) type Merge (NCtx a) (End x) (Cons m g) = Cons (Merge (Maybe a) (Just x) m) g type Merge (NCtx a) (Cons m g) (End x) = Cons (Merge (Maybe a) m (Just x)) g type Merge (NCtx a) (Cons m1 g1) (Cons m2 g2) = Cons (Merge (Maybe a) m1 m2) (Merge (NCtx a) g1 g2) (SEnd a) ⋓ (SEnd b) = SEnd (a ⋓ b) (SEnd a1) ⋓ (SCons m2 g2) = SCons (SJust a1 ⋓ m2) g2 (SCons m1 g1) ⋓ (SEnd a2) = SCons (m1 ⋓ SJust a2) g1 SCons m1 g1 ⋓ SCons m2 g2 = SCons (m1 ⋓ m2) (g1 ⋓ g2) mergeSymm (SEnd a) (SEnd b) = case mergeSymm a b of Dict -> Dict mergeSymm (SEnd a) (SCons m _) = case mergeSymm (SJust a) m of Dict -> Dict mergeSymm (SCons m _) (SEnd b) = case mergeSymm m (SJust b) of Dict -> Dict mergeSymm (SCons m1 g1) (SCons m2 g2) = case mergeSymm m1 m2 of {Dict -> case mergeSymm g1 g2 of {Dict -> Dict }} instance Mergeable a => Mergeable (Ctx a) where type Merge (Ctx a) Empty Empty = Empty type Merge (Ctx a) Empty (N g) = N g type Merge (Ctx a) (N g) Empty = N g type Merge (Ctx a) (N g1) (N g2) = N (Merge (NCtx a) g1 g2) SEmpty ⋓ SEmpty = SEmpty SEmpty ⋓ SN g = SN g SN g ⋓ SEmpty = SN g SN g1 ⋓ SN g2 = SN (g1 ⋓ g2) mergeSymm SEmpty SEmpty = Dict mergeSymm SEmpty (SN _) = Dict mergeSymm (SN _) SEmpty = Dict mergeSymm (SN g1) (SN g2) = case mergeSymm g1 g2 of Dict -> Dict lookupMerge :: forall a (dom1 :: Ctx a) (dom2 :: Ctx a) (x :: Nat). Sing dom1 -> Sing dom2 -> Sing x -> Dict ( Lookup (Merge (Ctx a) dom1 dom2) x ~ Merge (Maybe a) (Lookup dom1 x) (Lookup dom2 x) ) lookupMerge SEmpty SEmpty _ = Dict lookupMerge SEmpty (SN _) _ = Dict lookupMerge (SN _) SEmpty _ = Dict lookupMerge (SN dom1) (SN dom2) x = lookupMergeN dom1 dom2 x lookupMergeN :: forall a (dom1 :: NCtx a) (dom2 :: NCtx a) (x :: Nat). Sing dom1 -> Sing dom2 -> Sing x -> Dict ( Lookup (Merge (NCtx a) dom1 dom2) x ~ Merge (Maybe a) (Lookup dom1 x) (Lookup dom2 x) ) lookupMergeN (SEnd _) (SEnd _) SZ = Dict lookupMergeN (SEnd _) (SEnd _) (SS _) = Dict lookupMergeN (SEnd _) (SCons _ _) SZ = Dict lookupMergeN (SEnd _) (SCons _ _) (SS _) = Dict lookupMergeN (SCons _ _) (SEnd _) SZ = Dict lookupMergeN (SCons _ _) (SEnd _) (SS _) = Dict lookupMergeN (SCons _ _) (SCons _ _) SZ = Dict lookupMergeN (SCons _ ctx1) (SCons _ ctx2) (SS n) = lookupMergeN ctx1 ctx2 n type family Remove (x :: Nat) (g :: Ctx a) :: Ctx a where Remove _ Empty = Empty Remove x (N g) = RemoveN x g type family RemoveN (x :: Nat) (g :: NCtx a) :: Ctx a where RemoveN Z (End s) = Empty RemoveN (S _) (End s) = N (End s) RemoveN Z (Cons _ g) = N (Cons Nothing g) RemoveN (S x) (Cons u g) = Cons' u (RemoveN x g) remove :: Sing x -> Sing g -> Sing (Remove x g) remove _ SEmpty = SEmpty remove x (SN g) = removeN x g removeN :: Sing x -> Sing g -> Sing (RemoveN x g) removeN SZ (SEnd _) = SEmpty removeN (SS _) (SEnd s) = SN $ SEnd s removeN SZ (SCons _ g) = SN $ SCons SNothing g removeN (SS x) (SCons u g) = sCons u $ removeN x g type family Cons' (u :: Maybe a) (g :: Ctx a) :: Ctx a where Cons' Nothing Empty = Empty Cons' (Just x) Empty = N (End x) Cons' u (N g) = N (Cons u g) sCons :: Sing u -> Sing g -> Sing (Cons' u g) sCons SNothing SEmpty = SEmpty sCons (SJust x) SEmpty = SN $ SEnd x sCons u (SN g) = SN $ SCons u g lookupRemove :: Sing x -> Sing g -> Dict (Lookup (Remove x g) x ~ Nothing) lookupRemove _ SEmpty = Dict lookupRemove x (SN g) = lookupRemoveN x g lookupRemoveN :: Sing x -> Sing g -> Dict (Lookup (RemoveN x g) x ~ Nothing) lookupRemoveN SZ (SEnd _) = Dict lookupRemoveN (SS _) (SEnd _) = Dict lookupRemoveN SZ (SCons _ _) = Dict lookupRemoveN (SS x) (SCons u g) = case lookupRemoveN x g of {Dict -> case lookupCons' x u (removeN x g) of {Dict -> Dict}} lookupRemoveNEq :: (x == y) ~ False => Sing x -> Sing y -> Sing g -> Dict (Lookup (Remove y g) x ~ Lookup g x) lookupRemoveNEq _ _ SEmpty = Dict lookupRemoveNEq x y (SN γ) = lookupRemoveNNEq x y γ lookupRemoveNNEq :: (x == y) ~ False => Sing x -> Sing y -> Sing g -> Dict (Lookup (RemoveN y g) x ~ Lookup g x) lookupRemoveNNEq (SS _) SZ (SEnd _) = Dict lookupRemoveNNEq _ (SS _) (SEnd _) = Dict lookupRemoveNNEq (SS _) SZ (SCons _ _) = Dict lookupRemoveNNEq SZ (SS y) (SCons u g) = lookupCons'Z u (removeN y g) lookupRemoveNNEq (SS x) (SS y) (SCons u g) = case lookupCons' x u (removeN y g) of Dict -> lookupRemoveNNEq x y g lookupCons'Z :: Sing u -> Sing g -> Dict (Lookup (Cons' u g) Z ~ u) lookupCons'Z SNothing SEmpty = Dict lookupCons'Z (SJust _) SEmpty = Dict lookupCons'Z _ (SN _) = Dict lookupCons' :: Sing x -> Sing u -> Sing g -> Dict (Lookup (Cons' u g) (S x) ~ Lookup g x) lookupCons' _ SNothing SEmpty = Dict lookupCons' _ (SJust _) SEmpty = Dict lookupCons' _ _ (SN _) = Dict Proofs about the intersection of Add and Merge ( and Singleton ) addMergeSingleton :: Sing γ -> Sing x -> Dict (Add γ x '() ~ Merge (NCtx ()) (SingletonMap x '()) γ) addMergeSingleton (SEnd STuple0) SZ = Dict addMergeSingleton (SEnd STuple0) (SS _) = Dict addMergeSingleton (SCons SNothing _) SZ = Dict addMergeSingleton (SCons (SJust STuple0) _) SZ = Dict addMergeSingleton (SCons _ γ) (SS x) = case addMergeSingleton γ x of Dict -> Dict addDistrL :: Sing g1 -> Sing g2 -> Sing x -> Dict (Add (Merge (Ctx ()) g1 g2) x '() ~ Merge (Ctx ()) (Add g1 x '()) g2) addDistrL SEmpty SEmpty _ = Dict ( Add [ ] x ) ⋓ N γ = ( ) ⋓ N γ addDistrL SEmpty (SN γ) x = case addMergeSingleton γ x of Dict -> Dict addDistrL (SN _) SEmpty _ = Dict addDistrL (SN γ1) (SN γ2) x = case addNDistrL γ1 γ2 x of Dict -> Dict addNDistrL :: Sing g1 -> Sing g2 -> Sing x -> Dict (Add (Merge (NCtx ()) g1 g2) x '() ~ Merge (NCtx ()) (Add g1 x '()) g2) addNDistrL (SEnd STuple0) (SEnd STuple0) SZ = Dict addNDistrL (SEnd STuple0) (SEnd STuple0) (SS _) = Dict addNDistrL (SEnd STuple0) (SCons SNothing _) SZ = Dict addNDistrL (SEnd STuple0) (SCons (SJust STuple0) _) SZ = Dict Add ^ ( SS x ) = ( Just ( ) ⋓ u ) : : Add γ x = ( Just ( ) : : x ( ) ) ⋓ ( u : : γ ) = ( Just ( ) ⋓ u ) : : ( ( ) ⋓ γ ) addNDistrL (SEnd STuple0) (SCons _ γ) (SS x) = case addMergeSingleton γ x of Dict -> Dict addNDistrL (SCons _ _) (SEnd STuple0) SZ = Dict addNDistrL (SCons _ _) (SEnd STuple0) (SS _) = Dict Add ( ( u1 : : γ1 ) ⋓ ( u2 : : γ2 ) ) 0 = Add ( ( u1 ⋓ u2 ) : : ( γ1 ⋓ γ2 ) ) 0 addNDistrL (SCons _ _) (SCons u2 _) SZ = case u2 of SJust STuple0 -> Dict SNothing -> Dict addNDistrL (SCons _ γ1) (SCons _ γ2) (SS x) = case addNDistrL γ1 γ2 x of Dict -> Dict
5d20ac4d7d0aefd39a296cdd86e81ed3d213ad64786d8bdb367f647613a713b5
OCADml/ppx_deriving_cad
dim.ml
open! Ppxlib open! Ast_builder.Default type t = | D2 | D3 | Poly of string * string * string * string type error = | MixedDimensions | PolyCollapse | PolyMismatch | UnknownDimension let unwrap_result ~loc res = let r = Location.raise_errorf ~loc in match res with | Ok (Some dim) -> dim | Error MixedDimensions -> r "Transformable cannot contain both 2d and 3d entities." | Error PolyCollapse -> r "Transformable cannot contain polymorphic and concrete dimensional entities." | Error PolyMismatch -> r "All polymorphic dimensional entities must share the same type variables." | Ok None | Error UnknownDimension -> r "Dimension could not be determined. Provide @cad.d2 or @cad.d3." let dim_attr (type a) ~loc (module A : Attr.S with type t = a) (a : a) = match Attribute.get A.d2 a, Attribute.get A.d3 a with | Some (), None -> Some D2 | None, Some () -> Some D3 | None, None -> None | Some (), Some () -> Location.raise_errorf ~loc "Cannot tag with multiple dimensions." let rec check ~loc dim = function | [%type: [%t? typ] option] | [%type: [%t? typ] Option.t] | [%type: [%t? typ] list] | [%type: [%t? typ] List.t] | [%type: ([%t? typ], [%t? _]) result] | [%type: ([%t? typ], [%t? _]) Result.t] -> check ~loc dim typ | [%type: v2] | [%type: OCADml.v2] | [%type: V2.t] | [%type: OCADml.V2.t] | [%type: Path2.t] | [%type: OCADml.Path2.t] | [%type: Poly2.t] | [%type: OCADml.Poly2.t] | [%type: Bezier2.t] | [%type: OCADml.Bezier2.t] | [%type: ([ `D2 ], V2.t, float, Affine2.t) Scad.t] | [%type: ([ `D2 ], v2, float, Affine2.t) Scad.t] | [%type: ([ `D2 ], OCADml.V2.t, float, OCADml.Affine2.t) OCADml.Scad.t] | [%type: ([ `D2 ], OCADml.v2, float, OCADml.Affine2.t) OCADml.Scad.t] | [%type: Scad.d2] | [%type: OSCADml.Scad.d2] -> ( match dim with | Some D3 -> Error MixedDimensions | Some (Poly _) -> Error PolyCollapse | _ -> Ok (Some D2) ) | [%type: v3] | [%type: OCADml.v3] | [%type: V3.t] | [%type: OCADml.V3.t] | [%type: Path3.t] | [%type: OCADml.Path3.t] | [%type: Poly3.t] | [%type: OCADml.Poly3.t] | [%type: Bezier3.t] | [%type: OCADml.Bezier3.t] | [%type: Mesh.t] | [%type: OCADml.Mesh.t] | [%type: ([ `D3 ], V3.t, V3.t, Affine3.t) Scad.t] | [%type: ([ `D3 ], v3, v3, Affine3.t) Scad.t] | [%type: ([ `D3 ], OCADml.V3.t, OCADml.V3.t, OCADml.Affine3.t) OSCADml.Scad.t] | [%type: ([ `D3 ], OCADml.v3, OCADml.v3, OCADml.Affine3.t) OSCADml.Scad.t] | [%type: Scad.d3] | [%type: OSCADml.Scad.d3] | [%type: Manifold.t] | [%type: OManifold.Manifold.t] -> ( match dim with | Some D2 -> Error MixedDimensions | Some (Poly _) -> Error PolyCollapse | _ -> Ok (Some D3) ) | [%type: ( [%t? { ptyp_desc = Ptyp_var d; _ }] , [%t? { ptyp_desc = Ptyp_var s; _ }] , [%t? { ptyp_desc = Ptyp_var r; _ }] , [%t? { ptyp_desc = Ptyp_var a; _ }] ) Scad.t] | [%type: ( [%t? { ptyp_desc = Ptyp_var d; _ }] , [%t? { ptyp_desc = Ptyp_var s; _ }] , [%t? { ptyp_desc = Ptyp_var r; _ }] , [%t? { ptyp_desc = Ptyp_var a; _ }] ) OSCADml.Scad.t] -> ( match dim with | Some (D2 | D3) -> Error PolyCollapse | Some (Poly (d', s', r', a')) as dim when String.equal d d' && String.equal s s' && String.equal r r' && String.equal a a' -> Ok dim | None -> Ok (Some (Poly (d, s, r, a))) | _ -> Error PolyMismatch ) | { ptyp_desc = Ptyp_tuple (hd :: cts); _ } -> let f dim' ct = if Option.is_some @@ Attr.get_ignore (`Type ct) then Ok dim' else check ~loc dim' ct in Result.bind (f dim hd) (fun init -> Util.list_fold_result f init cts) | { ptyp_desc = Ptyp_constr (_, []); _ } -> Ok dim | { ptyp_desc = Ptyp_constr (_, (arg :: _ as args)); _ } -> if List.for_all (Fun.negate Util.is_constr) args then Ok dim else check ~loc dim arg | { ptyp_desc = Ptyp_arrow (_, _, ct); _ } -> check ~loc dim ct TODO : consider allowing type variables if they can be pegged to a Scad.t 's ' space parameter ( v2 or v3 ) . to a Scad.t's 'space parameter (v2 or v3). *) | ct -> Location.raise_errorf ~loc "Unhandled type: %s" (string_of_core_type ct) let decide_type ~loc ct = let f = function | None -> dim_attr ~loc (module Attr.Type) ct | d -> d in unwrap_result ~loc @@ Result.map f (check ~loc None ct) let decide_record ~loc = function | [] -> Location.raise_errorf ~loc "Cannot transform empty record." | (hd : label_declaration) :: tl -> let checker dim ld = if Option.is_some @@ Attr.get_ignore (`Field ld) then Ok dim else check ~loc dim ld.pld_type |> Result.map (function | None -> dim_attr ~loc (module Attr.Field) ld | d -> d ) in Result.bind (checker None hd) (fun init -> Util.list_fold_result checker init tl) |> unwrap_result ~loc
null
https://raw.githubusercontent.com/OCADml/ppx_deriving_cad/c24aab53d2fba3395bee29f3d9954ec888de4c80/src/dim.ml
ocaml
open! Ppxlib open! Ast_builder.Default type t = | D2 | D3 | Poly of string * string * string * string type error = | MixedDimensions | PolyCollapse | PolyMismatch | UnknownDimension let unwrap_result ~loc res = let r = Location.raise_errorf ~loc in match res with | Ok (Some dim) -> dim | Error MixedDimensions -> r "Transformable cannot contain both 2d and 3d entities." | Error PolyCollapse -> r "Transformable cannot contain polymorphic and concrete dimensional entities." | Error PolyMismatch -> r "All polymorphic dimensional entities must share the same type variables." | Ok None | Error UnknownDimension -> r "Dimension could not be determined. Provide @cad.d2 or @cad.d3." let dim_attr (type a) ~loc (module A : Attr.S with type t = a) (a : a) = match Attribute.get A.d2 a, Attribute.get A.d3 a with | Some (), None -> Some D2 | None, Some () -> Some D3 | None, None -> None | Some (), Some () -> Location.raise_errorf ~loc "Cannot tag with multiple dimensions." let rec check ~loc dim = function | [%type: [%t? typ] option] | [%type: [%t? typ] Option.t] | [%type: [%t? typ] list] | [%type: [%t? typ] List.t] | [%type: ([%t? typ], [%t? _]) result] | [%type: ([%t? typ], [%t? _]) Result.t] -> check ~loc dim typ | [%type: v2] | [%type: OCADml.v2] | [%type: V2.t] | [%type: OCADml.V2.t] | [%type: Path2.t] | [%type: OCADml.Path2.t] | [%type: Poly2.t] | [%type: OCADml.Poly2.t] | [%type: Bezier2.t] | [%type: OCADml.Bezier2.t] | [%type: ([ `D2 ], V2.t, float, Affine2.t) Scad.t] | [%type: ([ `D2 ], v2, float, Affine2.t) Scad.t] | [%type: ([ `D2 ], OCADml.V2.t, float, OCADml.Affine2.t) OCADml.Scad.t] | [%type: ([ `D2 ], OCADml.v2, float, OCADml.Affine2.t) OCADml.Scad.t] | [%type: Scad.d2] | [%type: OSCADml.Scad.d2] -> ( match dim with | Some D3 -> Error MixedDimensions | Some (Poly _) -> Error PolyCollapse | _ -> Ok (Some D2) ) | [%type: v3] | [%type: OCADml.v3] | [%type: V3.t] | [%type: OCADml.V3.t] | [%type: Path3.t] | [%type: OCADml.Path3.t] | [%type: Poly3.t] | [%type: OCADml.Poly3.t] | [%type: Bezier3.t] | [%type: OCADml.Bezier3.t] | [%type: Mesh.t] | [%type: OCADml.Mesh.t] | [%type: ([ `D3 ], V3.t, V3.t, Affine3.t) Scad.t] | [%type: ([ `D3 ], v3, v3, Affine3.t) Scad.t] | [%type: ([ `D3 ], OCADml.V3.t, OCADml.V3.t, OCADml.Affine3.t) OSCADml.Scad.t] | [%type: ([ `D3 ], OCADml.v3, OCADml.v3, OCADml.Affine3.t) OSCADml.Scad.t] | [%type: Scad.d3] | [%type: OSCADml.Scad.d3] | [%type: Manifold.t] | [%type: OManifold.Manifold.t] -> ( match dim with | Some D2 -> Error MixedDimensions | Some (Poly _) -> Error PolyCollapse | _ -> Ok (Some D3) ) | [%type: ( [%t? { ptyp_desc = Ptyp_var d; _ }] , [%t? { ptyp_desc = Ptyp_var s; _ }] , [%t? { ptyp_desc = Ptyp_var r; _ }] , [%t? { ptyp_desc = Ptyp_var a; _ }] ) Scad.t] | [%type: ( [%t? { ptyp_desc = Ptyp_var d; _ }] , [%t? { ptyp_desc = Ptyp_var s; _ }] , [%t? { ptyp_desc = Ptyp_var r; _ }] , [%t? { ptyp_desc = Ptyp_var a; _ }] ) OSCADml.Scad.t] -> ( match dim with | Some (D2 | D3) -> Error PolyCollapse | Some (Poly (d', s', r', a')) as dim when String.equal d d' && String.equal s s' && String.equal r r' && String.equal a a' -> Ok dim | None -> Ok (Some (Poly (d, s, r, a))) | _ -> Error PolyMismatch ) | { ptyp_desc = Ptyp_tuple (hd :: cts); _ } -> let f dim' ct = if Option.is_some @@ Attr.get_ignore (`Type ct) then Ok dim' else check ~loc dim' ct in Result.bind (f dim hd) (fun init -> Util.list_fold_result f init cts) | { ptyp_desc = Ptyp_constr (_, []); _ } -> Ok dim | { ptyp_desc = Ptyp_constr (_, (arg :: _ as args)); _ } -> if List.for_all (Fun.negate Util.is_constr) args then Ok dim else check ~loc dim arg | { ptyp_desc = Ptyp_arrow (_, _, ct); _ } -> check ~loc dim ct TODO : consider allowing type variables if they can be pegged to a Scad.t 's ' space parameter ( v2 or v3 ) . to a Scad.t's 'space parameter (v2 or v3). *) | ct -> Location.raise_errorf ~loc "Unhandled type: %s" (string_of_core_type ct) let decide_type ~loc ct = let f = function | None -> dim_attr ~loc (module Attr.Type) ct | d -> d in unwrap_result ~loc @@ Result.map f (check ~loc None ct) let decide_record ~loc = function | [] -> Location.raise_errorf ~loc "Cannot transform empty record." | (hd : label_declaration) :: tl -> let checker dim ld = if Option.is_some @@ Attr.get_ignore (`Field ld) then Ok dim else check ~loc dim ld.pld_type |> Result.map (function | None -> dim_attr ~loc (module Attr.Field) ld | d -> d ) in Result.bind (checker None hd) (fun init -> Util.list_fold_result checker init tl) |> unwrap_result ~loc
1788a2a2aa0b2525f0456482b632dec65c571eacb53cd81a46c2ef5d07a8322e
tjammer/raylib-ocaml
generate_ml_gui.ml
let () = Cstubs.write_ml Format.std_formatter ~prefix:Sys.argv.(1) (module Raygui_functions.Description)
null
https://raw.githubusercontent.com/tjammer/raylib-ocaml/0bf114c7102edea6d7d97fcc166204f289b60c61/src/c/stubgen/generate_ml_gui.ml
ocaml
let () = Cstubs.write_ml Format.std_formatter ~prefix:Sys.argv.(1) (module Raygui_functions.Description)
a9ce7f78ed872db89362414f274b07c2279769a656a2ab466941b044ab8eaeb4
Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library
LegalEntityCompanyVerification.hs
{-# LANGUAGE MultiWayIf #-} CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator . {-# LANGUAGE OverloadedStrings #-} | Contains the types generated from the schema LegalEntityCompanyVerification module StripeAPI.Types.LegalEntityCompanyVerification where import qualified Control.Monad.Fail import qualified Data.Aeson import qualified Data.Aeson as Data.Aeson.Encoding.Internal import qualified Data.Aeson as Data.Aeson.Types import qualified Data.Aeson as Data.Aeson.Types.FromJSON import qualified Data.Aeson as Data.Aeson.Types.Internal import qualified Data.Aeson as Data.Aeson.Types.ToJSON import qualified Data.ByteString.Char8 import qualified Data.ByteString.Char8 as Data.ByteString.Internal import qualified Data.Foldable import qualified Data.Functor import qualified Data.Maybe import qualified Data.Scientific import qualified Data.Text import qualified Data.Text.Internal import qualified Data.Time.Calendar as Data.Time.Calendar.Days import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime import qualified GHC.Base import qualified GHC.Classes import qualified GHC.Int import qualified GHC.Show import qualified GHC.Types import qualified StripeAPI.Common import StripeAPI.TypeAlias import {-# SOURCE #-} StripeAPI.Types.LegalEntityCompanyVerificationDocument import qualified Prelude as GHC.Integer.Type import qualified Prelude as GHC.Maybe -- | Defines the object schema located at @components.schemas.legal_entity_company_verification@ in the specification. data LegalEntityCompanyVerification = LegalEntityCompanyVerification { -- | document: legalEntityCompanyVerificationDocument :: LegalEntityCompanyVerificationDocument } deriving ( GHC.Show.Show, GHC.Classes.Eq ) instance Data.Aeson.Types.ToJSON.ToJSON LegalEntityCompanyVerification where toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (["document" Data.Aeson.Types.ToJSON..= legalEntityCompanyVerificationDocument obj] : GHC.Base.mempty)) toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (["document" Data.Aeson.Types.ToJSON..= legalEntityCompanyVerificationDocument obj] : GHC.Base.mempty))) instance Data.Aeson.Types.FromJSON.FromJSON LegalEntityCompanyVerification where parseJSON = Data.Aeson.Types.FromJSON.withObject "LegalEntityCompanyVerification" (\obj -> GHC.Base.pure LegalEntityCompanyVerification GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "document")) -- | Create a new 'LegalEntityCompanyVerification' with all required fields. mkLegalEntityCompanyVerification :: -- | 'legalEntityCompanyVerificationDocument' LegalEntityCompanyVerificationDocument -> LegalEntityCompanyVerification mkLegalEntityCompanyVerification legalEntityCompanyVerificationDocument = LegalEntityCompanyVerification {legalEntityCompanyVerificationDocument = legalEntityCompanyVerificationDocument}
null
https://raw.githubusercontent.com/Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library/ba4401f083ff054f8da68c741f762407919de42f/src/StripeAPI/Types/LegalEntityCompanyVerification.hs
haskell
# LANGUAGE MultiWayIf # # LANGUAGE OverloadedStrings # # SOURCE # | Defines the object schema located at @components.schemas.legal_entity_company_verification@ in the specification. | document: | Create a new 'LegalEntityCompanyVerification' with all required fields. | 'legalEntityCompanyVerificationDocument'
CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator . | Contains the types generated from the schema LegalEntityCompanyVerification module StripeAPI.Types.LegalEntityCompanyVerification where import qualified Control.Monad.Fail import qualified Data.Aeson import qualified Data.Aeson as Data.Aeson.Encoding.Internal import qualified Data.Aeson as Data.Aeson.Types import qualified Data.Aeson as Data.Aeson.Types.FromJSON import qualified Data.Aeson as Data.Aeson.Types.Internal import qualified Data.Aeson as Data.Aeson.Types.ToJSON import qualified Data.ByteString.Char8 import qualified Data.ByteString.Char8 as Data.ByteString.Internal import qualified Data.Foldable import qualified Data.Functor import qualified Data.Maybe import qualified Data.Scientific import qualified Data.Text import qualified Data.Text.Internal import qualified Data.Time.Calendar as Data.Time.Calendar.Days import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime import qualified GHC.Base import qualified GHC.Classes import qualified GHC.Int import qualified GHC.Show import qualified GHC.Types import qualified StripeAPI.Common import StripeAPI.TypeAlias import qualified Prelude as GHC.Integer.Type import qualified Prelude as GHC.Maybe data LegalEntityCompanyVerification = LegalEntityCompanyVerification legalEntityCompanyVerificationDocument :: LegalEntityCompanyVerificationDocument } deriving ( GHC.Show.Show, GHC.Classes.Eq ) instance Data.Aeson.Types.ToJSON.ToJSON LegalEntityCompanyVerification where toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (["document" Data.Aeson.Types.ToJSON..= legalEntityCompanyVerificationDocument obj] : GHC.Base.mempty)) toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (["document" Data.Aeson.Types.ToJSON..= legalEntityCompanyVerificationDocument obj] : GHC.Base.mempty))) instance Data.Aeson.Types.FromJSON.FromJSON LegalEntityCompanyVerification where parseJSON = Data.Aeson.Types.FromJSON.withObject "LegalEntityCompanyVerification" (\obj -> GHC.Base.pure LegalEntityCompanyVerification GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "document")) mkLegalEntityCompanyVerification :: LegalEntityCompanyVerificationDocument -> LegalEntityCompanyVerification mkLegalEntityCompanyVerification legalEntityCompanyVerificationDocument = LegalEntityCompanyVerification {legalEntityCompanyVerificationDocument = legalEntityCompanyVerificationDocument}
9f8a9856da55b6d31346d4a9879ebcba248227e24db8fa204a4d1b746a6bcd5a
fumieval/free-game
FreeGame.hs
# LANGUAGE GeneralisedNewtypeDeriving # ----------------------------------------------------------------------------- -- | -- Module : FreeGame Copyright : ( C ) 2013 -- License : BSD-style (see the file LICENSE) -- Maintainer : < > -- Stability : provisional -- Portability : non-portable ---------------------------------------------------------------------------- module FreeGame ( -- * Game Game(..), runGame, runGameDefault, WindowMode(..), BoundingBox2, Box(..), isInside, delay, tick, foreverFrame, untick, untickInfinite, -- * Frame Frame, FreeGame(..), liftFrame, -- * Transformations Vec2, Affine(..), Local(), globalize, localize, -- * Pictures Picture2D(..), BlendMode(..), Bitmap, bitmapSize, readBitmap, cropBitmap, clipBitmap, loadBitmaps, loadBitmapsWith, writeBitmap, -- * Text Font, loadFont, text, -- * Keyboard Keyboard(..), Key(..), charToKey, keyPress, keyUp, keyDown, -- * Mouse Mouse(), mouseScroll, mouseInWindow, mousePositionMay, mousePosition, mouseButtonL, mouseButtonR, mouseButtonM, mouseDownL, mouseDownR, mouseDownM, mouseUpL, mouseUpR, mouseUpM, -- * IO liftIO, randomness, -- * Utility functions unitV2, angleV2, degrees, radians, * module Control.Monad, module Control.Applicative, module Control.Bool, module Data.Color, module Data.Color.Names, module Linear, -- * Deprecated keyChar, keySpecial ) where import Control.Applicative import Control.Bool import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans import Data.BoundingBox import Data.Color import Data.Color.Names import FreeGame.Backend.GLFW import FreeGame.Class import FreeGame.Data.Bitmap import FreeGame.Data.Font import FreeGame.Instances () import FreeGame.Text import FreeGame.Types import FreeGame.UI import FreeGame.Util import Linear liftFrame :: Frame a -> Game a liftFrame = Game . lift runGameDefault :: Game a -> IO (Maybe a) runGameDefault = runGame Windowed (Box (V2 0 0) (V2 640 480))
null
https://raw.githubusercontent.com/fumieval/free-game/6896d2b681416bead55530d4d40e6412559d65c6/FreeGame.hs
haskell
--------------------------------------------------------------------------- | Module : FreeGame License : BSD-style (see the file LICENSE) Stability : provisional Portability : non-portable -------------------------------------------------------------------------- * Game * Frame * Transformations * Pictures * Text * Keyboard * Mouse * IO * Utility functions * Deprecated
# LANGUAGE GeneralisedNewtypeDeriving # Copyright : ( C ) 2013 Maintainer : < > module FreeGame Game(..), runGame, runGameDefault, WindowMode(..), BoundingBox2, Box(..), isInside, delay, tick, foreverFrame, untick, untickInfinite, Frame, FreeGame(..), liftFrame, Vec2, Affine(..), Local(), globalize, localize, Picture2D(..), BlendMode(..), Bitmap, bitmapSize, readBitmap, cropBitmap, clipBitmap, loadBitmaps, loadBitmapsWith, writeBitmap, Font, loadFont, text, Keyboard(..), Key(..), charToKey, keyPress, keyUp, keyDown, Mouse(), mouseScroll, mouseInWindow, mousePositionMay, mousePosition, mouseButtonL, mouseButtonR, mouseButtonM, mouseDownL, mouseDownR, mouseDownM, mouseUpL, mouseUpR, mouseUpM, liftIO, randomness, unitV2, angleV2, degrees, radians, * module Control.Monad, module Control.Applicative, module Control.Bool, module Data.Color, module Data.Color.Names, module Linear, keyChar, keySpecial ) where import Control.Applicative import Control.Bool import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans import Data.BoundingBox import Data.Color import Data.Color.Names import FreeGame.Backend.GLFW import FreeGame.Class import FreeGame.Data.Bitmap import FreeGame.Data.Font import FreeGame.Instances () import FreeGame.Text import FreeGame.Types import FreeGame.UI import FreeGame.Util import Linear liftFrame :: Frame a -> Game a liftFrame = Game . lift runGameDefault :: Game a -> IO (Maybe a) runGameDefault = runGame Windowed (Box (V2 0 0) (V2 640 480))
7b35a9678d625eedb12d4bfa5c5d84dd077cebd96c98995b07f99c4d95602fac
nuvla/api-server
credential_template_infrastructure_service_minio.clj
(ns sixsq.nuvla.server.resources.credential-template-infrastructure-service-minio " Allows credentials for Minio S3 services to be stored. " (:require [sixsq.nuvla.auth.utils.acl :as acl-utils] [sixsq.nuvla.server.resources.common.utils :as u] [sixsq.nuvla.server.resources.credential-template :as p] [sixsq.nuvla.server.resources.resource-metadata :as md] [sixsq.nuvla.server.resources.spec.credential-template-infrastructure-service-minio :as cred-tpl-minio] [sixsq.nuvla.server.util.metadata :as gen-md])) (def ^:const credential-subtype "infrastructure-service-minio") (def ^:const resource-url credential-subtype) (def ^:const resource-name "Minio S3 Credentials") (def ^:const method "infrastructure-service-minio") (def resource-acl (acl-utils/normalize-acl {:owners ["group/nuvla-admin"] :view-acl ["group/nuvla-user"]})) ;; ;; resource ;; (def ^:const resource {:subtype credential-subtype :method method :name resource-name :description "Minio S3 credentials" :acl resource-acl :resource-metadata "resource-metadata/credential-template-minio"}) ;; ;; multimethods for validation ;; (def validate-fn (u/create-spec-validation-fn ::cred-tpl-minio/schema)) (defmethod p/validate-subtype method [resource] (validate-fn resource)) ;; ;; initialization: register this credential-template ;; (def resource-metadata (gen-md/generate-metadata ::ns ::p/ns ::cred-tpl-minio/schema)) (def resource-metadata-create (gen-md/generate-metadata ::ns ::p/ns ::cred-tpl-minio/schema-create "create")) (defn initialize [] (p/register resource) (md/register resource-metadata) (md/register resource-metadata-create))
null
https://raw.githubusercontent.com/nuvla/api-server/a64a61b227733f1a0a945003edf5abaf5150a15c/code/src/sixsq/nuvla/server/resources/credential_template_infrastructure_service_minio.clj
clojure
resource multimethods for validation initialization: register this credential-template
(ns sixsq.nuvla.server.resources.credential-template-infrastructure-service-minio " Allows credentials for Minio S3 services to be stored. " (:require [sixsq.nuvla.auth.utils.acl :as acl-utils] [sixsq.nuvla.server.resources.common.utils :as u] [sixsq.nuvla.server.resources.credential-template :as p] [sixsq.nuvla.server.resources.resource-metadata :as md] [sixsq.nuvla.server.resources.spec.credential-template-infrastructure-service-minio :as cred-tpl-minio] [sixsq.nuvla.server.util.metadata :as gen-md])) (def ^:const credential-subtype "infrastructure-service-minio") (def ^:const resource-url credential-subtype) (def ^:const resource-name "Minio S3 Credentials") (def ^:const method "infrastructure-service-minio") (def resource-acl (acl-utils/normalize-acl {:owners ["group/nuvla-admin"] :view-acl ["group/nuvla-user"]})) (def ^:const resource {:subtype credential-subtype :method method :name resource-name :description "Minio S3 credentials" :acl resource-acl :resource-metadata "resource-metadata/credential-template-minio"}) (def validate-fn (u/create-spec-validation-fn ::cred-tpl-minio/schema)) (defmethod p/validate-subtype method [resource] (validate-fn resource)) (def resource-metadata (gen-md/generate-metadata ::ns ::p/ns ::cred-tpl-minio/schema)) (def resource-metadata-create (gen-md/generate-metadata ::ns ::p/ns ::cred-tpl-minio/schema-create "create")) (defn initialize [] (p/register resource) (md/register resource-metadata) (md/register resource-metadata-create))
70ba0405ecc05d1ea41577483fdb2198d6a73c8e2e5bf2d5d6744622af2a98ee
ekmett/machines
Benchmarks.hs
module Main (main) where import Control.Applicative import Data.Function ((&)) import Control.Monad (void) import Control.Monad.Identity import Criterion.Main import Data.Void import qualified Data.Conduit as C import qualified Data.Conduit.Combinators as CC import qualified Data.Conduit.List as C import qualified Data.Machine as M import qualified Pipes as P import qualified Pipes.Prelude as P import qualified Streaming.Prelude as S import Prelude value :: Int value = 1000000 drainM :: M.ProcessT Identity Int o -> () drainM m = runIdentity $ M.runT_ (sourceM M.~> m) drainMIO :: M.ProcessT IO Int o -> IO () drainMIO m = M.runT_ (sourceM M.~> m) drainP :: P.Proxy () Int () a Identity () -> () drainP p = runIdentity $ P.runEffect $ P.for (sourceP P.>-> p) P.discard drainPIO :: P.Proxy () Int () a IO () -> IO () drainPIO p = P.runEffect $ sourceP P.>-> p P.>-> P.mapM_ (\_ -> return ()) drainC :: C.ConduitT Int a Identity () -> () drainC c = runIdentity $ C.runConduit $ (sourceC C..| c) C..| C.sinkNull drainCIO :: C.ConduitT Int a IO () -> IO () drainCIO c = C.runConduit $ (sourceC C..| c) C..| C.mapM_ (\_ -> return ()) drainSC :: C.ConduitT Int Void Identity b -> () drainSC c = runIdentity $ void $! C.runConduit $ sourceC C..| c drainS :: (S.Stream (S.Of Int) Identity () -> S.Stream (S.Of Int) Identity ()) -> () drainS s = runIdentity $ S.effects $ sourceS & s drainSIO :: (S.Stream (S.Of Int) IO () -> S.Stream (S.Of Int) IO ()) -> IO () drainSIO s = sourceS & s & S.mapM_ (\_ -> return ()) sourceM :: M.Source Int sourceM = M.enumerateFromTo 1 value sourceC :: Monad m => C.ConduitT i Int m () sourceC = C.enumFromTo 1 value sourceP :: Monad m => P.Producer' Int m () sourceP = P.each [1..value] sourceS :: Monad m => S.Stream (S.Of Int) m () sourceS = S.each [1..value] main :: IO () main = defaultMain [ bgroup "map" [ bench "machines" $ whnf drainM (M.mapping (+1)) , bench "streaming" $ whnf drainS (S.map (+1)) , bench "pipes" $ whnf drainP (P.map (+1)) , bench "conduit" $ whnf drainC (C.map (+1)) ] , bgroup "drop" [ bench "machines" $ whnf drainM (M.dropping value) , bench "streaming" $ whnf drainS (S.drop value) , bench "pipes" $ whnf drainP (P.drop value) , bench "conduit" $ whnf drainC (C.drop value) ] , bgroup "dropWhile" [ bench "machines" $ whnf drainM (M.droppingWhile (<= value)) , bench "streaming" $ whnf drainS (S.dropWhile (<= value)) , bench "pipes" $ whnf drainP (P.dropWhile (<= value)) , bench "conduit" $ whnf drainC (CC.dropWhile (<= value)) ] , bgroup "scan" [ bench "machines" $ whnf drainM (M.scan (+) 0) , bench "streaming" $ whnf drainS (S.scan (+) 0 id) , bench "pipes" $ whnf drainP (P.scan (+) 0 id) , bench "conduit" $ whnf drainC (CC.scanl (+) 0) ] , bgroup "take" [ bench "machines" $ whnf drainM (M.taking value) , bench "streaming" $ whnf drainS (S.take value) , bench "pipes" $ whnf drainP (P.take value) , bench "conduit" $ whnf drainC (C.isolate value) ] , bgroup "takeWhile" [ bench "machines" $ whnf drainM (M.takingWhile (<= value)) , bench "streaming" $ whnf drainS (S.takeWhile (<= value)) , bench "pipes" $ whnf drainP (P.takeWhile (<= value)) , bench "conduit" $ whnf drainC (CC.takeWhile (<= value)) ] , bgroup "fold" [ bench "machines" $ whnf drainM (M.fold (+) 0) , bench "streaming" $ whnf runIdentity $ (S.fold (+) 0 id) sourceS , bench "pipes" $ whnf runIdentity $ (P.fold (+) 0 id) sourceP , bench "conduit" $ whnf drainSC (C.fold (+) 0) ] , bgroup "filter" [ bench "machines" $ whnf drainM (M.filtered even) , bench "streaming" $ whnf drainS (S.filter even) , bench "pipes" $ whnf drainP (P.filter even) , bench "conduit" $ whnf drainC (C.filter even) ] , bgroup "mapM" [ bench "machines" $ whnf drainM (M.autoM Identity) , bench "streaming" $ whnf drainS (S.mapM Identity) , bench "pipes" $ whnf drainP (P.mapM Identity) , bench "conduit" $ whnf drainC (C.mapM Identity) ] , bgroup "zip" [ bench "machines" $ whnf (\x -> runIdentity $ M.runT_ x) (M.capT sourceM sourceM M.zipping) , bench "streaming" $ whnf (\x -> runIdentity $ S.effects $ x) (S.zip sourceS sourceS) , bench "pipes" $ whnf (\x -> runIdentity $ P.runEffect $ P.for x P.discard) (P.zip sourceP sourceP) , bench "conduit" $ whnf (\x -> runIdentity $ C.runConduit $ x C..| C.sinkNull) (C.getZipSource $ (,) <$> C.ZipSource sourceC <*> C.ZipSource sourceC) ] , bgroup "concat" [ bench "machines" $ whnf drainM (M.mapping (replicate 10) M.~> M.asParts) , bench "streaming" $ whnf drainS (S.concat . S.map (replicate 10)) , bench "pipes" $ whnf drainP (P.map (replicate 10) P.>-> P.concat) , bench "conduit" $ whnf drainC (C.map (replicate 10) C..| C.concat) ] , bgroup "last" [ bench "machines" $ whnf drainM (M.final) , bench "streaming" $ whnf runIdentity $ S.last sourceS , bench "pipes" $ whnf runIdentity $ P.last sourceP ] , bgroup "buffered" [ bench "machines" $ whnf drainM (M.buffered 1000) ] , bgroup "toList" [ bench "machines" $ whnf (length . runIdentity) $ M.runT sourceM , bench "streaming" $ whnf (length . runIdentity) $ S.toList sourceS >>= (\(xs S.:> _) -> return xs) , bench "pipes" $ whnf (length . runIdentity) $ P.toListM sourceP , bench "conduit" $ whnf (length . runIdentity) $ C.runConduit $ sourceC C..| CC.sinkList ] , bgroup "toListIO" [ bench "machines" $ whnfIO $ M.runT sourceM , bench "streaming" $ whnfIO $ S.toList sourceS , bench "pipes" $ whnfIO $ P.toListM sourceP , bench "conduit" $ whnfIO $ C.runConduit $ sourceC C..| CC.sinkList ] , bgroup "compose" [ -- Compose multiple ops, all stages letting everything through let m = M.filtered (<= value) s = S.filter (<= value) p = P.filter (<= value) c = C.filter (<= value) in bgroup "summary" [ bench "machines" $ whnf drainM $ m M.~> m M.~> m M.~> m , bench "streaming" $ whnf drainS $ \x -> s x & s & s & s , bench "pipes" $ whnf drainP $ p P.>-> p P.>-> p P.>-> p , bench "conduit" $ whnf drainC $ c C..| c C..| c C..| c ] IO monad makes a big difference especially for machines , let m = M.filtered (<= value) s = S.filter (<= value) p = P.filter (<= value) c = C.filter (<= value) in bgroup "summary-io" [ bench "machines" $ whnfIO $ drainMIO $ m M.~> m M.~> m M.~> m , bench "streaming" $ whnfIO $ drainSIO $ \x -> s x & s & s & s , bench "pipes" $ whnfIO $ drainPIO $ p P.>-> p P.>-> p P.>-> p , bench "conduit" $ whnfIO $ drainCIO $ c C..| c C..| c C..| c ] -- Scaling with same operation in sequence , let f = M.filtered (<= value) in bgroup "machines" [ bench "1-filter" $ whnf drainM f , bench "2-filters" $ whnf drainM $ f M.~> f , bench "3-filters" $ whnf drainM $ f M.~> f M.~> f , bench "4-filters" $ whnf drainM $ f M.~> f M.~> f M.~> f ] , let f = S.filter (<= value) in bgroup "streaming" [ bench "1-filter" $ whnf drainS (\x -> f x) , bench "2-filters" $ whnf drainS $ \x -> f x & f , bench "3-filters" $ whnf drainS $ \x -> f x & f & f , bench "4-filters" $ whnf drainS $ \x -> f x & f & f & f ] , let f = P.filter (<= value) in bgroup "pipes" [ bench "1-filter" $ whnf drainP f , bench "2-filters" $ whnf drainP $ f P.>-> f , bench "3-filters" $ whnf drainP $ f P.>-> f P.>-> f , bench "4-filters" $ whnf drainP $ f P.>-> f P.>-> f P.>-> f ] , let f = C.filter (<= value) in bgroup "conduit" [ bench "1-filter" $ whnf drainC f , bench "2-filters" $ whnf drainC $ f C..| f , bench "3-filters" $ whnf drainC $ f C..| f C..| f , bench "4-filters" $ whnf drainC $ f C..| f C..| f C..| f ] , let m = M.mapping (subtract 1) M.~> M.filtered (<= value) s = S.filter (<= value) . S.map (subtract 1) p = P.map (subtract 1) P.>-> P.filter (<= value) c = C.map (subtract 1) C..| C.filter (<= value) in bgroup "summary-alternate" [ bench "machines" $ whnf drainM $ m M.~> m M.~> m M.~> m , bench "streaming" $ whnf drainS $ \x -> s x & s & s & s , bench "pipes" $ whnf drainP $ p P.>-> p P.>-> p P.>-> p , bench "conduit" $ whnf drainC $ c C..| c C..| c C..| c ] , let f = M.mapping (subtract 1) M.~> M.filtered (<= value) in bgroup "machines-alternate" [ bench "1-map-filter" $ whnf drainM f , bench "2-map-filters" $ whnf drainM $ f M.~> f , bench "3-map-filters" $ whnf drainM $ f M.~> f M.~> f , bench "4-map-filters" $ whnf drainM $ f M.~> f M.~> f M.~> f ] , let f = S.filter (<= value) . S.map (subtract 1) in bgroup "streaming-alternate" [ bench "1-map-filter" $ whnf drainS (\x -> f x) , bench "2-map-filters" $ whnf drainS $ \x -> f x & f , bench "3-map-filters" $ whnf drainS $ \x -> f x & f & f , bench "4-map-filters" $ whnf drainS $ \x -> f x & f & f & f ] , let f = P.map (subtract 1) P.>-> P.filter (<= value) in bgroup "pipes-alternate" [ bench "1-map-filter" $ whnf drainP f , bench "2-map-filters" $ whnf drainP $ f P.>-> f , bench "3-map-filters" $ whnf drainP $ f P.>-> f P.>-> f , bench "4-map-filters" $ whnf drainP $ f P.>-> f P.>-> f P.>-> f ] , let f = C.map (subtract 1) C..| C.filter (<= value) in bgroup "conduit-alternate" [ bench "1-map-filter" $ whnf drainC f , bench "2-map-filters" $ whnf drainC $ f C..| f , bench "3-map-filters" $ whnf drainC $ f C..| f C..| f , bench "4-map-filters" $ whnf drainC $ f C..| f C..| f C..| f ] -- how filtering affects the subsequent composition , let m = M.filtered (> value) s = S.filter (> value) p = P.filter (> value) c = C.filter (> value) in bgroup "summary-filter-effect" [ bench "machines" $ whnf drainM $ m M.~> m M.~> m M.~> m , bench "streaming" $ whnf drainS $ \x -> s x & s & s & s , bench "pipes" $ whnf drainP $ p P.>-> p P.>-> p P.>-> p , bench "conduit" $ whnf drainC $ c C..| c C..| c C..| c ] , let m = M.filtered (> value) s = S.filter (> value) p = P.filter (> value) c = C.filter (> value) in bgroup "summary-filter-effect-io" [ bench "machines" $ whnfIO $ drainMIO $ m M.~> m M.~> m M.~> m , bench "streaming" $ whnfIO $ drainSIO $ \x -> s x & s & s & s , bench "pipes" $ whnfIO $ drainPIO $ p P.>-> p P.>-> p P.>-> p , bench "conduit" $ whnfIO $ drainCIO $ c C..| c C..| c C..| c ] , let f = M.filtered (> value) in bgroup "machines-filter-effect" [ bench "filter1" $ whnf drainM f , bench "filter2" $ whnf drainM $ f M.~> f , bench "filter3" $ whnf drainM $ f M.~> f M.~> f , bench "filter4" $ whnf drainM $ f M.~> f M.~> f M.~> f ] , let f = S.filter (> value) in bgroup "streaming-filter-effect" [ bench "filter1" $ whnf drainS (\x -> f x) , bench "filter2" $ whnf drainS $ \x -> f x & f , bench "filter3" $ whnf drainS $ \x -> f x & f & f , bench "filter4" $ whnf drainS $ \x -> f x & f & f & f ] , let f = P.filter (> value) in bgroup "pipes-filter-effect" [ bench "filter1" $ whnf drainP f , bench "filter2" $ whnf drainP $ f P.>-> f , bench "filter3" $ whnf drainP $ f P.>-> f P.>-> f , bench "filter4" $ whnf drainP $ f P.>-> f P.>-> f P.>-> f ] , let f = C.filter (> value) in bgroup "conduit-filter-effect" [ bench "filter1" $ whnf drainC f , bench "filter2" $ whnf drainC $ f C..| f , bench "filter3" $ whnf drainC $ f C..| f C..| f , bench "filter4" $ whnf drainC $ f C..| f C..| f C..| f ] ] ]
null
https://raw.githubusercontent.com/ekmett/machines/d76bb4cf5798b495f1648c5f5075209e81e11eac/benchmarks/Benchmarks.hs
haskell
Compose multiple ops, all stages letting everything through Scaling with same operation in sequence how filtering affects the subsequent composition
module Main (main) where import Control.Applicative import Data.Function ((&)) import Control.Monad (void) import Control.Monad.Identity import Criterion.Main import Data.Void import qualified Data.Conduit as C import qualified Data.Conduit.Combinators as CC import qualified Data.Conduit.List as C import qualified Data.Machine as M import qualified Pipes as P import qualified Pipes.Prelude as P import qualified Streaming.Prelude as S import Prelude value :: Int value = 1000000 drainM :: M.ProcessT Identity Int o -> () drainM m = runIdentity $ M.runT_ (sourceM M.~> m) drainMIO :: M.ProcessT IO Int o -> IO () drainMIO m = M.runT_ (sourceM M.~> m) drainP :: P.Proxy () Int () a Identity () -> () drainP p = runIdentity $ P.runEffect $ P.for (sourceP P.>-> p) P.discard drainPIO :: P.Proxy () Int () a IO () -> IO () drainPIO p = P.runEffect $ sourceP P.>-> p P.>-> P.mapM_ (\_ -> return ()) drainC :: C.ConduitT Int a Identity () -> () drainC c = runIdentity $ C.runConduit $ (sourceC C..| c) C..| C.sinkNull drainCIO :: C.ConduitT Int a IO () -> IO () drainCIO c = C.runConduit $ (sourceC C..| c) C..| C.mapM_ (\_ -> return ()) drainSC :: C.ConduitT Int Void Identity b -> () drainSC c = runIdentity $ void $! C.runConduit $ sourceC C..| c drainS :: (S.Stream (S.Of Int) Identity () -> S.Stream (S.Of Int) Identity ()) -> () drainS s = runIdentity $ S.effects $ sourceS & s drainSIO :: (S.Stream (S.Of Int) IO () -> S.Stream (S.Of Int) IO ()) -> IO () drainSIO s = sourceS & s & S.mapM_ (\_ -> return ()) sourceM :: M.Source Int sourceM = M.enumerateFromTo 1 value sourceC :: Monad m => C.ConduitT i Int m () sourceC = C.enumFromTo 1 value sourceP :: Monad m => P.Producer' Int m () sourceP = P.each [1..value] sourceS :: Monad m => S.Stream (S.Of Int) m () sourceS = S.each [1..value] main :: IO () main = defaultMain [ bgroup "map" [ bench "machines" $ whnf drainM (M.mapping (+1)) , bench "streaming" $ whnf drainS (S.map (+1)) , bench "pipes" $ whnf drainP (P.map (+1)) , bench "conduit" $ whnf drainC (C.map (+1)) ] , bgroup "drop" [ bench "machines" $ whnf drainM (M.dropping value) , bench "streaming" $ whnf drainS (S.drop value) , bench "pipes" $ whnf drainP (P.drop value) , bench "conduit" $ whnf drainC (C.drop value) ] , bgroup "dropWhile" [ bench "machines" $ whnf drainM (M.droppingWhile (<= value)) , bench "streaming" $ whnf drainS (S.dropWhile (<= value)) , bench "pipes" $ whnf drainP (P.dropWhile (<= value)) , bench "conduit" $ whnf drainC (CC.dropWhile (<= value)) ] , bgroup "scan" [ bench "machines" $ whnf drainM (M.scan (+) 0) , bench "streaming" $ whnf drainS (S.scan (+) 0 id) , bench "pipes" $ whnf drainP (P.scan (+) 0 id) , bench "conduit" $ whnf drainC (CC.scanl (+) 0) ] , bgroup "take" [ bench "machines" $ whnf drainM (M.taking value) , bench "streaming" $ whnf drainS (S.take value) , bench "pipes" $ whnf drainP (P.take value) , bench "conduit" $ whnf drainC (C.isolate value) ] , bgroup "takeWhile" [ bench "machines" $ whnf drainM (M.takingWhile (<= value)) , bench "streaming" $ whnf drainS (S.takeWhile (<= value)) , bench "pipes" $ whnf drainP (P.takeWhile (<= value)) , bench "conduit" $ whnf drainC (CC.takeWhile (<= value)) ] , bgroup "fold" [ bench "machines" $ whnf drainM (M.fold (+) 0) , bench "streaming" $ whnf runIdentity $ (S.fold (+) 0 id) sourceS , bench "pipes" $ whnf runIdentity $ (P.fold (+) 0 id) sourceP , bench "conduit" $ whnf drainSC (C.fold (+) 0) ] , bgroup "filter" [ bench "machines" $ whnf drainM (M.filtered even) , bench "streaming" $ whnf drainS (S.filter even) , bench "pipes" $ whnf drainP (P.filter even) , bench "conduit" $ whnf drainC (C.filter even) ] , bgroup "mapM" [ bench "machines" $ whnf drainM (M.autoM Identity) , bench "streaming" $ whnf drainS (S.mapM Identity) , bench "pipes" $ whnf drainP (P.mapM Identity) , bench "conduit" $ whnf drainC (C.mapM Identity) ] , bgroup "zip" [ bench "machines" $ whnf (\x -> runIdentity $ M.runT_ x) (M.capT sourceM sourceM M.zipping) , bench "streaming" $ whnf (\x -> runIdentity $ S.effects $ x) (S.zip sourceS sourceS) , bench "pipes" $ whnf (\x -> runIdentity $ P.runEffect $ P.for x P.discard) (P.zip sourceP sourceP) , bench "conduit" $ whnf (\x -> runIdentity $ C.runConduit $ x C..| C.sinkNull) (C.getZipSource $ (,) <$> C.ZipSource sourceC <*> C.ZipSource sourceC) ] , bgroup "concat" [ bench "machines" $ whnf drainM (M.mapping (replicate 10) M.~> M.asParts) , bench "streaming" $ whnf drainS (S.concat . S.map (replicate 10)) , bench "pipes" $ whnf drainP (P.map (replicate 10) P.>-> P.concat) , bench "conduit" $ whnf drainC (C.map (replicate 10) C..| C.concat) ] , bgroup "last" [ bench "machines" $ whnf drainM (M.final) , bench "streaming" $ whnf runIdentity $ S.last sourceS , bench "pipes" $ whnf runIdentity $ P.last sourceP ] , bgroup "buffered" [ bench "machines" $ whnf drainM (M.buffered 1000) ] , bgroup "toList" [ bench "machines" $ whnf (length . runIdentity) $ M.runT sourceM , bench "streaming" $ whnf (length . runIdentity) $ S.toList sourceS >>= (\(xs S.:> _) -> return xs) , bench "pipes" $ whnf (length . runIdentity) $ P.toListM sourceP , bench "conduit" $ whnf (length . runIdentity) $ C.runConduit $ sourceC C..| CC.sinkList ] , bgroup "toListIO" [ bench "machines" $ whnfIO $ M.runT sourceM , bench "streaming" $ whnfIO $ S.toList sourceS , bench "pipes" $ whnfIO $ P.toListM sourceP , bench "conduit" $ whnfIO $ C.runConduit $ sourceC C..| CC.sinkList ] , bgroup "compose" [ let m = M.filtered (<= value) s = S.filter (<= value) p = P.filter (<= value) c = C.filter (<= value) in bgroup "summary" [ bench "machines" $ whnf drainM $ m M.~> m M.~> m M.~> m , bench "streaming" $ whnf drainS $ \x -> s x & s & s & s , bench "pipes" $ whnf drainP $ p P.>-> p P.>-> p P.>-> p , bench "conduit" $ whnf drainC $ c C..| c C..| c C..| c ] IO monad makes a big difference especially for machines , let m = M.filtered (<= value) s = S.filter (<= value) p = P.filter (<= value) c = C.filter (<= value) in bgroup "summary-io" [ bench "machines" $ whnfIO $ drainMIO $ m M.~> m M.~> m M.~> m , bench "streaming" $ whnfIO $ drainSIO $ \x -> s x & s & s & s , bench "pipes" $ whnfIO $ drainPIO $ p P.>-> p P.>-> p P.>-> p , bench "conduit" $ whnfIO $ drainCIO $ c C..| c C..| c C..| c ] , let f = M.filtered (<= value) in bgroup "machines" [ bench "1-filter" $ whnf drainM f , bench "2-filters" $ whnf drainM $ f M.~> f , bench "3-filters" $ whnf drainM $ f M.~> f M.~> f , bench "4-filters" $ whnf drainM $ f M.~> f M.~> f M.~> f ] , let f = S.filter (<= value) in bgroup "streaming" [ bench "1-filter" $ whnf drainS (\x -> f x) , bench "2-filters" $ whnf drainS $ \x -> f x & f , bench "3-filters" $ whnf drainS $ \x -> f x & f & f , bench "4-filters" $ whnf drainS $ \x -> f x & f & f & f ] , let f = P.filter (<= value) in bgroup "pipes" [ bench "1-filter" $ whnf drainP f , bench "2-filters" $ whnf drainP $ f P.>-> f , bench "3-filters" $ whnf drainP $ f P.>-> f P.>-> f , bench "4-filters" $ whnf drainP $ f P.>-> f P.>-> f P.>-> f ] , let f = C.filter (<= value) in bgroup "conduit" [ bench "1-filter" $ whnf drainC f , bench "2-filters" $ whnf drainC $ f C..| f , bench "3-filters" $ whnf drainC $ f C..| f C..| f , bench "4-filters" $ whnf drainC $ f C..| f C..| f C..| f ] , let m = M.mapping (subtract 1) M.~> M.filtered (<= value) s = S.filter (<= value) . S.map (subtract 1) p = P.map (subtract 1) P.>-> P.filter (<= value) c = C.map (subtract 1) C..| C.filter (<= value) in bgroup "summary-alternate" [ bench "machines" $ whnf drainM $ m M.~> m M.~> m M.~> m , bench "streaming" $ whnf drainS $ \x -> s x & s & s & s , bench "pipes" $ whnf drainP $ p P.>-> p P.>-> p P.>-> p , bench "conduit" $ whnf drainC $ c C..| c C..| c C..| c ] , let f = M.mapping (subtract 1) M.~> M.filtered (<= value) in bgroup "machines-alternate" [ bench "1-map-filter" $ whnf drainM f , bench "2-map-filters" $ whnf drainM $ f M.~> f , bench "3-map-filters" $ whnf drainM $ f M.~> f M.~> f , bench "4-map-filters" $ whnf drainM $ f M.~> f M.~> f M.~> f ] , let f = S.filter (<= value) . S.map (subtract 1) in bgroup "streaming-alternate" [ bench "1-map-filter" $ whnf drainS (\x -> f x) , bench "2-map-filters" $ whnf drainS $ \x -> f x & f , bench "3-map-filters" $ whnf drainS $ \x -> f x & f & f , bench "4-map-filters" $ whnf drainS $ \x -> f x & f & f & f ] , let f = P.map (subtract 1) P.>-> P.filter (<= value) in bgroup "pipes-alternate" [ bench "1-map-filter" $ whnf drainP f , bench "2-map-filters" $ whnf drainP $ f P.>-> f , bench "3-map-filters" $ whnf drainP $ f P.>-> f P.>-> f , bench "4-map-filters" $ whnf drainP $ f P.>-> f P.>-> f P.>-> f ] , let f = C.map (subtract 1) C..| C.filter (<= value) in bgroup "conduit-alternate" [ bench "1-map-filter" $ whnf drainC f , bench "2-map-filters" $ whnf drainC $ f C..| f , bench "3-map-filters" $ whnf drainC $ f C..| f C..| f , bench "4-map-filters" $ whnf drainC $ f C..| f C..| f C..| f ] , let m = M.filtered (> value) s = S.filter (> value) p = P.filter (> value) c = C.filter (> value) in bgroup "summary-filter-effect" [ bench "machines" $ whnf drainM $ m M.~> m M.~> m M.~> m , bench "streaming" $ whnf drainS $ \x -> s x & s & s & s , bench "pipes" $ whnf drainP $ p P.>-> p P.>-> p P.>-> p , bench "conduit" $ whnf drainC $ c C..| c C..| c C..| c ] , let m = M.filtered (> value) s = S.filter (> value) p = P.filter (> value) c = C.filter (> value) in bgroup "summary-filter-effect-io" [ bench "machines" $ whnfIO $ drainMIO $ m M.~> m M.~> m M.~> m , bench "streaming" $ whnfIO $ drainSIO $ \x -> s x & s & s & s , bench "pipes" $ whnfIO $ drainPIO $ p P.>-> p P.>-> p P.>-> p , bench "conduit" $ whnfIO $ drainCIO $ c C..| c C..| c C..| c ] , let f = M.filtered (> value) in bgroup "machines-filter-effect" [ bench "filter1" $ whnf drainM f , bench "filter2" $ whnf drainM $ f M.~> f , bench "filter3" $ whnf drainM $ f M.~> f M.~> f , bench "filter4" $ whnf drainM $ f M.~> f M.~> f M.~> f ] , let f = S.filter (> value) in bgroup "streaming-filter-effect" [ bench "filter1" $ whnf drainS (\x -> f x) , bench "filter2" $ whnf drainS $ \x -> f x & f , bench "filter3" $ whnf drainS $ \x -> f x & f & f , bench "filter4" $ whnf drainS $ \x -> f x & f & f & f ] , let f = P.filter (> value) in bgroup "pipes-filter-effect" [ bench "filter1" $ whnf drainP f , bench "filter2" $ whnf drainP $ f P.>-> f , bench "filter3" $ whnf drainP $ f P.>-> f P.>-> f , bench "filter4" $ whnf drainP $ f P.>-> f P.>-> f P.>-> f ] , let f = C.filter (> value) in bgroup "conduit-filter-effect" [ bench "filter1" $ whnf drainC f , bench "filter2" $ whnf drainC $ f C..| f , bench "filter3" $ whnf drainC $ f C..| f C..| f , bench "filter4" $ whnf drainC $ f C..| f C..| f C..| f ] ] ]
f4a4008d007aa4868a60acdb9556511dcd9314790777e795d5db9523a4699994
uber/NEAL
skip.ml
Copyright ( c ) 2017 Uber Technologies , Inc. (* *) (* Permission is hereby granted, free of charge, to any person obtaining a copy *) (* of this software and associated documentation files (the "Software"), to deal *) in the Software without restriction , including without limitation the rights (* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell *) copies of the Software , and to permit persons to whom the Software is (* furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included in *) all copies or substantial portions of the Software . (* *) THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *) (* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *) LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , (* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN *) (* THE SOFTWARE. *) open Lexing open Neal.Ctx open Skip_absyn let neal_marker = Str.regexp "NEAL:[^\n]+" let print_position line index outx lexbuf = let pos = lexbuf.lex_curr_p in Printf.fprintf outx "%s:%d:%d" pos.pos_fname line (pos.pos_cnum - pos.pos_bol + 1 + index) let parse line index lexbuf = try Some (Skip_parser.parse Skip_lexer.read lexbuf) with _ -> Printf.fprintf stderr "%a: syntax error on NEAL comment\n" (print_position line index) lexbuf; None let parse directives file line index matched = let lexbuf = Lexing.from_string matched in lexbuf.lex_curr_p <- { lexbuf.lex_curr_p with pos_fname = file }; match parse line index lexbuf with | Some directive -> (line, directive) :: directives | None -> directives let compute_directives { file; source } = let lines = String.split_on_char '\n' source in let rec aux line matches = function | [] -> matches | l::ls -> let matches' = try let index = Str.search_forward neal_marker l 0 in let matched = (Str.matched_string l) in parse matches file line index matched with Not_found -> matches in aux (line + 1) matches' ls in aux 1 [] lines
null
https://raw.githubusercontent.com/uber/NEAL/6a382a3f957c3bb4abe3f9aba9761ffef13fa5fe/src/core/directives/skip.ml
ocaml
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal to use, copy, modify, merge, publish, distribute, sublicense, and/or sell furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Copyright ( c ) 2017 Uber Technologies , Inc. in the Software without restriction , including without limitation the rights copies of the Software , and to permit persons to whom the Software is all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , open Lexing open Neal.Ctx open Skip_absyn let neal_marker = Str.regexp "NEAL:[^\n]+" let print_position line index outx lexbuf = let pos = lexbuf.lex_curr_p in Printf.fprintf outx "%s:%d:%d" pos.pos_fname line (pos.pos_cnum - pos.pos_bol + 1 + index) let parse line index lexbuf = try Some (Skip_parser.parse Skip_lexer.read lexbuf) with _ -> Printf.fprintf stderr "%a: syntax error on NEAL comment\n" (print_position line index) lexbuf; None let parse directives file line index matched = let lexbuf = Lexing.from_string matched in lexbuf.lex_curr_p <- { lexbuf.lex_curr_p with pos_fname = file }; match parse line index lexbuf with | Some directive -> (line, directive) :: directives | None -> directives let compute_directives { file; source } = let lines = String.split_on_char '\n' source in let rec aux line matches = function | [] -> matches | l::ls -> let matches' = try let index = Str.search_forward neal_marker l 0 in let matched = (Str.matched_string l) in parse matches file line index matched with Not_found -> matches in aux (line + 1) matches' ls in aux 1 [] lines
716992241beb20d7033c9268756b0a620400e368aaf6bba96449207fb510f508
tamarin-prover/tamarin-prover
Lemma.hs
-- | Copyright : ( c ) 2010 - 2012 , contributing in 2019 : , , -- License : GPL v3 (see LICENSE) -- Maintainer : < > -- Portability : portable -- -- Parsing Lemmas module Theory.Text.Parser.Lemma( lemma , lemmaAttribute , plainLemma , diffLemma ) where import Prelude hiding (id, (.)) import Data.Foldable (asum) -- import Data.Monoid hiding (Last) import Control.Applicative hiding (empty, many, optional) import Text.Parsec hiding ((<|>)) import Theory import Theory.Text.Parser.Token import Debug.Trace import Theory.Text.Parser.Formula import Theory.Text.Parser.Rule import Theory.Text.Parser.Proof import Theory.Text.Parser.Signature import Data.Functor (($>)) -- | Parse an arbitrary type consisting of simple constructors constructorp :: (Show a, Enum a, Bounded a) => Parser a constructorp = asum $ map (\x -> symbol_ (show x) $> x) constructorList where constructorList = enumFrom minBound | Parse a ' LemmaAttribute ' . lemmaAttribute :: Bool -> Maybe FilePath -> Parser LemmaAttribute lemmaAttribute diff workDir = asum [ symbol "typing" *> trace ("Deprecation Warning: using 'typing' is retired notation, replace all uses of 'typing' by 'sources'.\n") pure SourceLemma -- legacy support, emits deprecation warning -- , symbol "typing" *> fail "Using 'typing' is retired notation, replace all uses of 'typing' by 'sources'." , symbol "sources" *> pure SourceLemma , symbol "reuse" *> pure ReuseLemma , symbol "diff_reuse" *> pure ReuseDiffLemma , symbol "use_induction" *> pure InvariantLemma , symbol "hide_lemma" *> opEqual *> (HideLemma <$> identifier) , symbol "heuristic" *> opEqual *> (LemmaHeuristic <$> goalRanking diff workDir) , symbol "output" *> opEqual *> (LemmaModule <$> list constructorp) , symbol "left" *> pure LHSLemma , symbol "right" *> pure RHSLemma , symbol " both " * > pure BothLemma ] | Parse a ' TraceQuantifier ' . traceQuantifier :: Parser TraceQuantifier traceQuantifier = asum [ symbol "all-traces" *> pure AllTraces , symbol "exists-trace" *> pure ExistsTrace ] protoLemma :: Parser f -> Maybe FilePath -> Parser (ProtoLemma f ProofSkeleton) protoLemma parseFormula workDir = skeletonLemma <$> (symbol "lemma" *> optional moduloE *> identifier) <*> (option [] $ list (lemmaAttribute False workDir)) <*> (colon *> option AllTraces traceQuantifier) <*> doubleQuoted parseFormula <*> (startProofSkeleton <|> pure (unproven ())) -- | Parse a lemma. lemma :: Maybe FilePath -> Parser (SyntacticLemma ProofSkeleton) lemma = protoLemma $ standardFormula msgvar nodevar -- | Parse a lemma w/o syntactic sugar plainLemma :: Maybe FilePath -> Parser (Lemma ProofSkeleton) plainLemma = protoLemma plainFormula -- | Parse a diff lemma. diffLemma :: Maybe FilePath -> Parser (DiffLemma DiffProofSkeleton) diffLemma workDir = skeletonDiffLemma <$> (symbol "diffLemma" *> identifier) <*> (option [] $ list (lemmaAttribute True workDir)) <*> (colon *> (diffProofSkeleton <|> pure (diffUnproven ())))
null
https://raw.githubusercontent.com/tamarin-prover/tamarin-prover/958f8b1767650c06dffe4eba63a38508c9b17a7f/lib/theory/src/Theory/Text/Parser/Lemma.hs
haskell
| License : GPL v3 (see LICENSE) Portability : portable Parsing Lemmas import Data.Monoid hiding (Last) | Parse an arbitrary type consisting of simple constructors legacy support, emits deprecation warning , symbol "typing" *> fail "Using 'typing' is retired notation, replace all uses of 'typing' by 'sources'." | Parse a lemma. | Parse a lemma w/o syntactic sugar | Parse a diff lemma.
Copyright : ( c ) 2010 - 2012 , contributing in 2019 : , , Maintainer : < > module Theory.Text.Parser.Lemma( lemma , lemmaAttribute , plainLemma , diffLemma ) where import Prelude hiding (id, (.)) import Data.Foldable (asum) import Control.Applicative hiding (empty, many, optional) import Text.Parsec hiding ((<|>)) import Theory import Theory.Text.Parser.Token import Debug.Trace import Theory.Text.Parser.Formula import Theory.Text.Parser.Rule import Theory.Text.Parser.Proof import Theory.Text.Parser.Signature import Data.Functor (($>)) constructorp :: (Show a, Enum a, Bounded a) => Parser a constructorp = asum $ map (\x -> symbol_ (show x) $> x) constructorList where constructorList = enumFrom minBound | Parse a ' LemmaAttribute ' . lemmaAttribute :: Bool -> Maybe FilePath -> Parser LemmaAttribute lemmaAttribute diff workDir = asum , symbol "sources" *> pure SourceLemma , symbol "reuse" *> pure ReuseLemma , symbol "diff_reuse" *> pure ReuseDiffLemma , symbol "use_induction" *> pure InvariantLemma , symbol "hide_lemma" *> opEqual *> (HideLemma <$> identifier) , symbol "heuristic" *> opEqual *> (LemmaHeuristic <$> goalRanking diff workDir) , symbol "output" *> opEqual *> (LemmaModule <$> list constructorp) , symbol "left" *> pure LHSLemma , symbol "right" *> pure RHSLemma , symbol " both " * > pure BothLemma ] | Parse a ' TraceQuantifier ' . traceQuantifier :: Parser TraceQuantifier traceQuantifier = asum [ symbol "all-traces" *> pure AllTraces , symbol "exists-trace" *> pure ExistsTrace ] protoLemma :: Parser f -> Maybe FilePath -> Parser (ProtoLemma f ProofSkeleton) protoLemma parseFormula workDir = skeletonLemma <$> (symbol "lemma" *> optional moduloE *> identifier) <*> (option [] $ list (lemmaAttribute False workDir)) <*> (colon *> option AllTraces traceQuantifier) <*> doubleQuoted parseFormula <*> (startProofSkeleton <|> pure (unproven ())) lemma :: Maybe FilePath -> Parser (SyntacticLemma ProofSkeleton) lemma = protoLemma $ standardFormula msgvar nodevar plainLemma :: Maybe FilePath -> Parser (Lemma ProofSkeleton) plainLemma = protoLemma plainFormula diffLemma :: Maybe FilePath -> Parser (DiffLemma DiffProofSkeleton) diffLemma workDir = skeletonDiffLemma <$> (symbol "diffLemma" *> identifier) <*> (option [] $ list (lemmaAttribute True workDir)) <*> (colon *> (diffProofSkeleton <|> pure (diffUnproven ())))
ff815983e236752d48a42c5541f1ff122b4bd63974e20363255ba02dc734e344
input-output-hk/plutus
Eq.hs
-- editorconfig-checker-disable-file | ' ' instances for core data types . # OPTIONS_GHC -fno - warn - orphans # # LANGUAGE FlexibleInstances # {-# LANGUAGE RankNTypes #-} # LANGUAGE TypeApplications # {-# LANGUAGE TypeFamilies #-} # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # module PlutusCore.Core.Instance.Eq () where import PlutusPrelude import PlutusCore.Core.Type import PlutusCore.DeBruijn import PlutusCore.Eq import PlutusCore.Name import PlutusCore.Rename.Monad import Universe instance (GEq uni, Eq ann) => Eq (Type TyName uni ann) where ty1 == ty2 = runEqRename @TypeRenaming $ eqTypeM ty1 ty2 instance ( GEq uni, Closed uni, uni `Everywhere` Eq, Eq fun, Eq ann ) => Eq (Term TyName Name uni fun ann) where term1 == term2 = runEqRename $ eqTermM term1 term2 Simple Structural Equality of a ` Term NamedDeBruijn ` . This implies three things : b ) We do not do equality " modulo starting index " . E.g. ` 0 ( Var 0 ) /= LamAbs 1 ( Var 1 ) ` . -- c) We do not do equality ""modulo annotations". -- Note that we ignore the name part in case of the nameddebruijn -- If a user wants to ignore annotations he must prior do `void <$> term`, to throw away any annotations. deriving stock instance (GEq uni, Closed uni, uni `Everywhere` Eq, Eq fun, Eq ann) => Eq (Term NamedTyDeBruijn NamedDeBruijn uni fun ann) deriving stock instance (GEq uni, Closed uni, uni `Everywhere` Eq, Eq fun, Eq ann) => Eq (Term TyDeBruijn DeBruijn uni fun ann) deriving stock instance (GEq uni, Closed uni, uni `Everywhere` Eq, Eq ann) => Eq (Type NamedTyDeBruijn uni ann) deriving stock instance (GEq uni, Closed uni, uni `Everywhere` Eq, Eq ann) => Eq (Type TyDeBruijn uni ann) deriving stock instance (GEq uni, Closed uni, uni `Everywhere` Eq, Eq fun, Eq ann, Eq (Term tyname name uni fun ann) ) => Eq (Program tyname name uni fun ann) type EqRenameOf ren a = HasUniques a => a -> a -> EqRename ren -- See Note [Modulo alpha]. -- See Note [Scope tracking] -- See Note [Side tracking] -- See Note [No catch-all]. | Check equality of two ' Type 's . eqTypeM :: (HasRenaming ren TypeUnique, GEq uni, Eq ann) => EqRenameOf ren (Type tyname uni ann) eqTypeM (TyVar ann1 name1) (TyVar ann2 name2) = do eqM ann1 ann2 eqNameM name1 name2 eqTypeM (TyLam ann1 name1 kind1 ty1) (TyLam ann2 name2 kind2 ty2) = do eqM ann1 ann2 eqM kind1 kind2 withTwinBindings name1 name2 $ eqTypeM ty1 ty2 eqTypeM (TyForall ann1 name1 kind1 ty1) (TyForall ann2 name2 kind2 ty2) = do eqM ann1 ann2 eqM kind1 kind2 withTwinBindings name1 name2 $ eqTypeM ty1 ty2 eqTypeM (TyIFix ann1 pat1 arg1) (TyIFix ann2 pat2 arg2) = do eqM ann1 ann2 eqTypeM pat1 pat2 eqTypeM arg1 arg2 eqTypeM (TyApp ann1 fun1 arg1) (TyApp ann2 fun2 arg2) = do eqM ann1 ann2 eqTypeM fun1 fun2 eqTypeM arg1 arg2 eqTypeM (TyFun ann1 dom1 cod1) (TyFun ann2 dom2 cod2) = do eqM ann1 ann2 eqTypeM dom1 dom2 eqTypeM cod1 cod2 eqTypeM (TyBuiltin ann1 bi1) (TyBuiltin ann2 bi2) = do eqM ann1 ann2 eqM bi1 bi2 eqTypeM TyVar{} _ = empty eqTypeM TyLam{} _ = empty eqTypeM TyForall{} _ = empty eqTypeM TyIFix{} _ = empty eqTypeM TyApp{} _ = empty eqTypeM TyFun{} _ = empty eqTypeM TyBuiltin{} _ = empty -- See Note [Modulo alpha]. -- See Note [Scope tracking] -- See Note [Side tracking] -- See Note [No catch-all]. | Check equality of two ' Term 's . eqTermM :: (GEq uni, Closed uni, uni `Everywhere` Eq, Eq fun, Eq ann) => EqRenameOf ScopedRenaming (Term tyname name uni fun ann) eqTermM (LamAbs ann1 name1 ty1 body1) (LamAbs ann2 name2 ty2 body2) = do eqM ann1 ann2 eqTypeM ty1 ty2 withTwinBindings name1 name2 $ eqTermM body1 body2 eqTermM (TyAbs ann1 name1 kind1 body1) (TyAbs ann2 name2 kind2 body2) = do eqM ann1 ann2 eqM kind1 kind2 withTwinBindings name1 name2 $ eqTermM body1 body2 eqTermM (IWrap ann1 pat1 arg1 term1) (IWrap ann2 pat2 arg2 term2) = do eqM ann1 ann2 eqTypeM pat1 pat2 eqTypeM arg1 arg2 eqTermM term1 term2 eqTermM (Apply ann1 fun1 arg1) (Apply ann2 fun2 arg2) = do eqM ann1 ann2 eqTermM fun1 fun2 eqTermM arg1 arg2 eqTermM (Unwrap ann1 term1) (Unwrap ann2 term2) = do eqM ann1 ann2 eqTermM term1 term2 eqTermM (Error ann1 ty1) (Error ann2 ty2) = do eqM ann1 ann2 eqTypeM ty1 ty2 eqTermM (TyInst ann1 term1 ty1) (TyInst ann2 term2 ty2) = do eqM ann1 ann2 eqTermM term1 term2 eqTypeM ty1 ty2 eqTermM (Var ann1 name1) (Var ann2 name2) = do eqM ann1 ann2 eqNameM name1 name2 eqTermM (Constant ann1 con1) (Constant ann2 con2) = do eqM ann1 ann2 eqM con1 con2 eqTermM (Builtin ann1 bi1) (Builtin ann2 bi2) = do eqM ann1 ann2 eqM bi1 bi2 eqTermM LamAbs{} _ = empty eqTermM TyAbs{} _ = empty eqTermM IWrap{} _ = empty eqTermM Apply{} _ = empty eqTermM Unwrap{} _ = empty eqTermM Error{} _ = empty eqTermM TyInst{} _ = empty eqTermM Var{} _ = empty eqTermM Constant{} _ = empty eqTermM Builtin{} _ = empty
null
https://raw.githubusercontent.com/input-output-hk/plutus/c8d4364d0e639fef4d5b93f7d6c0912d992b54f9/plutus-core/plutus-core/src/PlutusCore/Core/Instance/Eq.hs
haskell
editorconfig-checker-disable-file # LANGUAGE RankNTypes # # LANGUAGE TypeFamilies # c) We do not do equality ""modulo annotations". Note that we ignore the name part in case of the nameddebruijn If a user wants to ignore annotations he must prior do `void <$> term`, to throw away any annotations. See Note [Modulo alpha]. See Note [Scope tracking] See Note [Side tracking] See Note [No catch-all]. See Note [Modulo alpha]. See Note [Scope tracking] See Note [Side tracking] See Note [No catch-all].
| ' ' instances for core data types . # OPTIONS_GHC -fno - warn - orphans # # LANGUAGE FlexibleInstances # # LANGUAGE TypeApplications # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # module PlutusCore.Core.Instance.Eq () where import PlutusPrelude import PlutusCore.Core.Type import PlutusCore.DeBruijn import PlutusCore.Eq import PlutusCore.Name import PlutusCore.Rename.Monad import Universe instance (GEq uni, Eq ann) => Eq (Type TyName uni ann) where ty1 == ty2 = runEqRename @TypeRenaming $ eqTypeM ty1 ty2 instance ( GEq uni, Closed uni, uni `Everywhere` Eq, Eq fun, Eq ann ) => Eq (Term TyName Name uni fun ann) where term1 == term2 = runEqRename $ eqTermM term1 term2 Simple Structural Equality of a ` Term NamedDeBruijn ` . This implies three things : b ) We do not do equality " modulo starting index " . E.g. ` 0 ( Var 0 ) /= LamAbs 1 ( Var 1 ) ` . deriving stock instance (GEq uni, Closed uni, uni `Everywhere` Eq, Eq fun, Eq ann) => Eq (Term NamedTyDeBruijn NamedDeBruijn uni fun ann) deriving stock instance (GEq uni, Closed uni, uni `Everywhere` Eq, Eq fun, Eq ann) => Eq (Term TyDeBruijn DeBruijn uni fun ann) deriving stock instance (GEq uni, Closed uni, uni `Everywhere` Eq, Eq ann) => Eq (Type NamedTyDeBruijn uni ann) deriving stock instance (GEq uni, Closed uni, uni `Everywhere` Eq, Eq ann) => Eq (Type TyDeBruijn uni ann) deriving stock instance (GEq uni, Closed uni, uni `Everywhere` Eq, Eq fun, Eq ann, Eq (Term tyname name uni fun ann) ) => Eq (Program tyname name uni fun ann) type EqRenameOf ren a = HasUniques a => a -> a -> EqRename ren | Check equality of two ' Type 's . eqTypeM :: (HasRenaming ren TypeUnique, GEq uni, Eq ann) => EqRenameOf ren (Type tyname uni ann) eqTypeM (TyVar ann1 name1) (TyVar ann2 name2) = do eqM ann1 ann2 eqNameM name1 name2 eqTypeM (TyLam ann1 name1 kind1 ty1) (TyLam ann2 name2 kind2 ty2) = do eqM ann1 ann2 eqM kind1 kind2 withTwinBindings name1 name2 $ eqTypeM ty1 ty2 eqTypeM (TyForall ann1 name1 kind1 ty1) (TyForall ann2 name2 kind2 ty2) = do eqM ann1 ann2 eqM kind1 kind2 withTwinBindings name1 name2 $ eqTypeM ty1 ty2 eqTypeM (TyIFix ann1 pat1 arg1) (TyIFix ann2 pat2 arg2) = do eqM ann1 ann2 eqTypeM pat1 pat2 eqTypeM arg1 arg2 eqTypeM (TyApp ann1 fun1 arg1) (TyApp ann2 fun2 arg2) = do eqM ann1 ann2 eqTypeM fun1 fun2 eqTypeM arg1 arg2 eqTypeM (TyFun ann1 dom1 cod1) (TyFun ann2 dom2 cod2) = do eqM ann1 ann2 eqTypeM dom1 dom2 eqTypeM cod1 cod2 eqTypeM (TyBuiltin ann1 bi1) (TyBuiltin ann2 bi2) = do eqM ann1 ann2 eqM bi1 bi2 eqTypeM TyVar{} _ = empty eqTypeM TyLam{} _ = empty eqTypeM TyForall{} _ = empty eqTypeM TyIFix{} _ = empty eqTypeM TyApp{} _ = empty eqTypeM TyFun{} _ = empty eqTypeM TyBuiltin{} _ = empty | Check equality of two ' Term 's . eqTermM :: (GEq uni, Closed uni, uni `Everywhere` Eq, Eq fun, Eq ann) => EqRenameOf ScopedRenaming (Term tyname name uni fun ann) eqTermM (LamAbs ann1 name1 ty1 body1) (LamAbs ann2 name2 ty2 body2) = do eqM ann1 ann2 eqTypeM ty1 ty2 withTwinBindings name1 name2 $ eqTermM body1 body2 eqTermM (TyAbs ann1 name1 kind1 body1) (TyAbs ann2 name2 kind2 body2) = do eqM ann1 ann2 eqM kind1 kind2 withTwinBindings name1 name2 $ eqTermM body1 body2 eqTermM (IWrap ann1 pat1 arg1 term1) (IWrap ann2 pat2 arg2 term2) = do eqM ann1 ann2 eqTypeM pat1 pat2 eqTypeM arg1 arg2 eqTermM term1 term2 eqTermM (Apply ann1 fun1 arg1) (Apply ann2 fun2 arg2) = do eqM ann1 ann2 eqTermM fun1 fun2 eqTermM arg1 arg2 eqTermM (Unwrap ann1 term1) (Unwrap ann2 term2) = do eqM ann1 ann2 eqTermM term1 term2 eqTermM (Error ann1 ty1) (Error ann2 ty2) = do eqM ann1 ann2 eqTypeM ty1 ty2 eqTermM (TyInst ann1 term1 ty1) (TyInst ann2 term2 ty2) = do eqM ann1 ann2 eqTermM term1 term2 eqTypeM ty1 ty2 eqTermM (Var ann1 name1) (Var ann2 name2) = do eqM ann1 ann2 eqNameM name1 name2 eqTermM (Constant ann1 con1) (Constant ann2 con2) = do eqM ann1 ann2 eqM con1 con2 eqTermM (Builtin ann1 bi1) (Builtin ann2 bi2) = do eqM ann1 ann2 eqM bi1 bi2 eqTermM LamAbs{} _ = empty eqTermM TyAbs{} _ = empty eqTermM IWrap{} _ = empty eqTermM Apply{} _ = empty eqTermM Unwrap{} _ = empty eqTermM Error{} _ = empty eqTermM TyInst{} _ = empty eqTermM Var{} _ = empty eqTermM Constant{} _ = empty eqTermM Builtin{} _ = empty
5468b4955818f23fa4539a4e34d1f06f9609973858d5a3cd51d0a66fa1c9d523
joodie/flutter
input_fields.clj
(ns flutter.html4.input-fields (:use flutter.selected)) ;;;; ;;;; minimal input fields that provide a given name => value pair ;;;; (defn wrap-basic-input-fields "accept type :input and translate straight to a hiccup [:input] element, adding name and value in attributes (which probably should include a :type). ignores opts." [f] (fn [type attrs name opts value] (if (= type :input) [:input (assoc attrs :name name :value value)] (f type attrs name opts value)))) (defn wrap-html4-input-fields "provides the standard HTML 4 input types: translates types :text :password :checkbox :radio :submit :reset :file :hidden :image and :button to type :input. If you want the full set of HTML 4 form fields, use `wrap-html4-fields' instead." [f] (fn [type attrs name opts value] (if (#{:text :password :checkbox :radio :submit :reset :file :hidden :image :button} type) (f :input (assoc attrs :type type) name nil value) (f type attrs name opts value)))) ;;;; elements that can be used to select one or more values for a name . ;;;; (defn wrap-radio-and-checkbox "provides semantics for radio and check boxes: opts is the value given for this particular input, sets the :checked attribute if that value is (in) the current value(s)" [f] (fn [type attrs name opts values] (if (#{:radio :checkbox} type) (f type (if (selected? opts values) (assoc attrs :checked :checked) attrs) name nil opts) (f type attrs name opts values))))
null
https://raw.githubusercontent.com/joodie/flutter/336e40386ff4e79ce9243ec8690e2a62c41f80a3/src/flutter/html4/input_fields.clj
clojure
minimal input fields that provide a given name => value pair
(ns flutter.html4.input-fields (:use flutter.selected)) (defn wrap-basic-input-fields "accept type :input and translate straight to a hiccup [:input] element, adding name and value in attributes (which probably should include a :type). ignores opts." [f] (fn [type attrs name opts value] (if (= type :input) [:input (assoc attrs :name name :value value)] (f type attrs name opts value)))) (defn wrap-html4-input-fields "provides the standard HTML 4 input types: translates types :text :password :checkbox :radio :submit :reset :file :hidden :image and :button to type :input. If you want the full set of HTML 4 form fields, use `wrap-html4-fields' instead." [f] (fn [type attrs name opts value] (if (#{:text :password :checkbox :radio :submit :reset :file :hidden :image :button} type) (f :input (assoc attrs :type type) name nil value) (f type attrs name opts value)))) elements that can be used to select one or more values for a name . (defn wrap-radio-and-checkbox "provides semantics for radio and check boxes: opts is the value given for this particular input, sets the :checked attribute if that value is (in) the current value(s)" [f] (fn [type attrs name opts values] (if (#{:radio :checkbox} type) (f type (if (selected? opts values) (assoc attrs :checked :checked) attrs) name nil opts) (f type attrs name opts values))))
7e7575a0a312355fd9c1af242a39bbaa89f165f3478fe8c1ce4370ca96a1e68f
janestreet/merlin-jst
mreader_parser.mli
{ { { COPYING * ( This file is part of Merlin , an helper for ocaml editors Copyright ( C ) 2013 - 2015 < frederic.bour(_)lakaban.net > refis.thomas(_)gmail.com > < simon.castellan(_)iuwt.fr > Permission is hereby granted , free of charge , to any person obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without restriction , including without limitation the rights to use , copy , modify , merge , publish , distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . The Software is provided " as is " , without warranty of any kind , express or implied , including but not limited to the warranties of merchantability , fitness for a particular purpose and noninfringement . In no event shall the authors or copyright holders be liable for any claim , damages or other liability , whether in an action of contract , tort or otherwise , arising from , out of or in connection with the software or the use or other dealings in the Software . ) * } } } This file is part of Merlin, an helper for ocaml editors Copyright (C) 2013 - 2015 Frédéric Bour <frederic.bour(_)lakaban.net> Thomas Refis <refis.thomas(_)gmail.com> Simon Castellan <simon.castellan(_)iuwt.fr> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the Software. )* }}} *) type kind = | ML | MLI (*| MLL | MLY*) type t val make : Warnings.state -> Mreader_lexer.t -> kind -> t type tree = [ | `Interface of Parsetree.signature | `Implementation of Parsetree.structure ] val result : t -> tree val errors : t -> exn list
null
https://raw.githubusercontent.com/janestreet/merlin-jst/0152b4e8ef1b7cd0ddee2873aa1860a971585391/src/kernel/mreader_parser.mli
ocaml
| MLL | MLY
{ { { COPYING * ( This file is part of Merlin , an helper for ocaml editors Copyright ( C ) 2013 - 2015 < frederic.bour(_)lakaban.net > refis.thomas(_)gmail.com > < simon.castellan(_)iuwt.fr > Permission is hereby granted , free of charge , to any person obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without restriction , including without limitation the rights to use , copy , modify , merge , publish , distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . The Software is provided " as is " , without warranty of any kind , express or implied , including but not limited to the warranties of merchantability , fitness for a particular purpose and noninfringement . In no event shall the authors or copyright holders be liable for any claim , damages or other liability , whether in an action of contract , tort or otherwise , arising from , out of or in connection with the software or the use or other dealings in the Software . ) * } } } This file is part of Merlin, an helper for ocaml editors Copyright (C) 2013 - 2015 Frédéric Bour <frederic.bour(_)lakaban.net> Thomas Refis <refis.thomas(_)gmail.com> Simon Castellan <simon.castellan(_)iuwt.fr> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the Software. )* }}} *) type kind = | ML | MLI type t val make : Warnings.state -> Mreader_lexer.t -> kind -> t type tree = [ | `Interface of Parsetree.signature | `Implementation of Parsetree.structure ] val result : t -> tree val errors : t -> exn list