_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
|
---|---|---|---|---|---|---|---|---|
11e1292c369f47fca809a5ad3874b1c4117941c98c6ab53ca861f7a4c9c4f09f | mathiasbourgoin/SPOC | Kirc.mli | type float64 = float
type float32 = float
type extension = ExFloat32 | ExFloat64
type ('a, 'b, 'c) kirc_kernel = {
ml_kern : 'a;
body : Kirc_Ast.k_ext;
ret_val : Kirc_Ast.k_ext * ('b, 'c) Spoc.Vector.kind;
extensions : extension array;
}
type ('a,'b,'c, 'd) kirc_function =
{
fun_name:string;
ml_fun : 'a;
funbody : Kirc_Ast.k_ext;
fun_ret : Kirc_Ast.k_ext* ('b,'c) Spoc.Vector.kind;
fastflow_acc : 'd;
fun_extensions : extension array
}
type ('a, 'b, 'c, 'd, 'e) sarek_kernel =
('a, 'b) Spoc.Kernel.spoc_kernel * ('c, 'd, 'e) kirc_kernel
val constructors : string list ref
val eint32 : Kirc_Ast.elttype
val eint64 : Kirc_Ast.elttype
val efloat32 : Kirc_Ast.elttype
val efloat64 : Kirc_Ast.elttype
val global : Kirc_Ast.memspace
val local : Kirc_Ast.memspace
val shared : Kirc_Ast.memspace
val print_ast : Kirc_Ast.k_ext -> unit
val opencl_head : string
val opencl_float64 : string
val cuda_float64 : string
val cuda_head : string
val new_var : int -> Kirc_Ast.k_ext
val global_fun : ('a,'b,'c, 'd) kirc_function -> Kirc_Ast.k_ext
val new_array : string -> Kirc_Ast.k_ext -> Kirc_Ast.elttype -> Kirc_Ast.memspace -> Kirc_Ast.k_ext
val var : int -> string -> Kirc_Ast.k_ext
val spoc_gen_kernel : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_fun_kernel : 'a -> 'b -> unit
val seq : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val app : Kirc_Ast.k_ext -> Kirc_Ast.k_ext array -> Kirc_Ast.k_ext
val spoc_unit : unit -> Kirc_Ast.k_ext
val spoc_int : int -> Kirc_Ast.k_ext
val global_int_var : (unit -> int32) -> Kirc_Ast.k_ext
val global_float_var : (unit -> float) -> Kirc_Ast.k_ext
val global_float64_var : (unit -> float) -> Kirc_Ast.k_ext
val spoc_int32 : int32 -> Kirc_Ast.k_ext
val spoc_float : float -> Kirc_Ast.k_ext
val spoc_double : float -> Kirc_Ast.k_ext
val spoc_int_id : int -> Kirc_Ast.k_ext
val spoc_float_id : float -> Kirc_Ast.k_ext
val spoc_plus : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_plus_float : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_min : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_min_float : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_mul : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_mul_float : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_div : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_div_float : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_mod : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_ife :
Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_if : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_match : string -> Kirc_Ast.k_ext -> Kirc_Ast.case array -> Kirc_Ast.k_ext
val spoc_case : int -> (string*string*int*string) option -> Kirc_Ast.k_ext -> Kirc_Ast.case
val spoc_do :
Kirc_Ast.k_ext ->
Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_while : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val params : Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_id : 'a -> Kirc_Ast.k_ext
val spoc_constr : string -> string -> Kirc_Ast.k_ext list -> Kirc_Ast.k_ext
val spoc_record : string -> Kirc_Ast.k_ext list -> Kirc_Ast.k_ext
val spoc_rec_get : Kirc_Ast.k_ext -> string -> Kirc_Ast.k_ext
val spoc_rec_set : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_return : Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val concat : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val empty_arg : unit -> Kirc_Ast.k_ext
val new_int_var : int -> string -> Kirc_Ast.k_ext
val new_float_var : int -> string -> Kirc_Ast.k_ext
val new_float64_var : int -> string -> Kirc_Ast.k_ext
val new_double_var : int -> string -> Kirc_Ast.k_ext
val new_unit_var : int -> string -> Kirc_Ast.k_ext
val new_custom_var : string -> int -> string -> Kirc_Ast.k_ext
val new_int_vec_var : int -> string -> Kirc_Ast.k_ext
val new_float_vec_var : int -> string -> Kirc_Ast.k_ext
val new_double_vec_var : int -> string -> Kirc_Ast.k_ext
val new_custom_vec_var : string -> int -> string -> Kirc_Ast.k_ext
val int_vect : int -> Kirc_Ast.kvect
val set_vect_var : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val set_arr_var : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val intrinsics : string -> string -> Kirc_Ast.k_ext
val spoc_local_env : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_set : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_declare : Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_local_var : 'a -> 'a
val spoc_acc : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val int_var : 'a -> 'a
val int32_var : 'a -> 'a
val float_var : 'a -> 'a
val double_var : int -> Kirc_Ast.k_ext
val equals : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val equals_custom : string -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val equals32 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val equals64 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val equalsF : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val equalsF64 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val b_or : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val b_and : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val b_not : Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val lt : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val lt32 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val lt64 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val ltF : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val ltF64 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val gt : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val gt32 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val gt64 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val gtF : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val gtF64 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val lte : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val lte32 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val lte64 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val lteF : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val lteF64 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val gte : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val gte32 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val gte64 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val gteF : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val gteF64 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val get_vec : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val get_arr : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val return_unit : unit -> Kirc_Ast.k_ext
val return_int : int -> string -> Kirc_Ast.k_ext
val return_float : int -> string -> Kirc_Ast.k_ext
val return_double : int -> string -> Kirc_Ast.k_ext
val return_bool : int -> string -> Kirc_Ast.k_ext
val return_custom : string -> string -> string -> Kirc_Ast.k_ext
val rewrite : Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_native : (Spoc.Devices.device -> string) -> Kirc_Ast.k_ext
val pragma : string list -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val return_v : (string * string) ref
val save : string -> string -> unit
val load_file : string -> bytes
val map : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val gen_profile :
('a, 'b, 'c, 'd, 'e) sarek_kernel -> Spoc.Devices.device -> unit
val gen :
?keep_temp:bool -> ?profile:bool -> ?return:bool ->
?only:Spoc.Devices.specificLibrary ->
?nvrtc_options:string array ->
('a, 'b, 'c, 'd, 'e) sarek_kernel ->
Spoc.Devices.device ->
('a, 'b, 'c, 'd, 'e) sarek_kernel
val run :
?recompile:bool ->
('a, ('b, 'f) Spoc.Kernel.kernelArgs array, 'c, 'd, 'e) sarek_kernel ->
'a ->
Spoc.Kernel.block * Spoc.Kernel.grid -> int -> Spoc.Devices.device -> unit
val profile_run :
?recompile:bool ->
('a, ('b, 'f) Spoc.Kernel.kernelArgs array, 'c, 'd, 'e) sarek_kernel ->
'a ->
Spoc.Kernel.block * Spoc.Kernel.grid -> int -> Spoc.Devices.device -> unit
val compile_kernel_to_files :
string -> ('a, 'b, 'c, 'd, 'e) sarek_kernel -> Spoc.Devices.device ->unit
module Std :
sig
val thread_idx_x : Int32.t
val thread_idx_y : Int32.t
val thread_idx_z : Int32.t
val block_idx_x : Int32.t
val block_idx_y : Int32.t
val block_idx_z : Int32.t
val block_dim_x : Int32.t
val block_dim_y : Int32.t
val block_dim_z : Int32.t
val grid_dim_x : Int32.t
val grid_dim_y : Int32.t
val grid_dim_z : Int32.t
val global_thread_id : Int32.t
val return : unit -> unit
val float64 : Int32.t -> float
val int_of_float64 : float -> Int32.t
val float : Int32.t -> float
val int_of_float : float -> Int32.t
val block_barrier : unit -> unit
val make_shared : Int32.t -> Int32.t array
val make_local : Int32.t -> Int32.t array
val map :
('a -> 'b) -> (*, 'c, 'd, 'e) kirc_function -> *)
('a, 'f) Spoc.Vector.vector -> ('b, 'g) Spoc.Vector.vector -> unit
val reduce :
('a -> 'a -> 'a) -> (*, 'c, 'd, 'e) kirc_function -> *)
('a, 'f) Spoc.Vector.vector -> ('a, 'g) Spoc.Vector.vector -> unit
end
module Sarek_vector :
sig
val length : ('a,'b) Spoc.Vector.vector -> int32
end
module Math :
sig
val pow : Int32.t -> Int32.t -> Int32.t
val logical_and : Int32.t -> Int32.t -> Int32.t
val xor : Int32.t -> Int32.t -> Int32.t
module Float32 :
sig
val add : float -> float -> float
val minus : float -> float -> float
val mul : float -> float -> float
val div : float -> float -> float
val pow : float -> float -> float
val sqrt : float -> float
val rsqrt : float -> float
val exp : float -> float
val log : float -> float
val log10 : float -> float
val expm1 : float -> float
val log1p : float -> float
val acos : float -> float
val cos : float -> float
val cosh : float -> float
val asin : float -> float
val sin : float -> float
val sinh : float -> float
val tan : float -> float
val tanh : float -> float
val atan : float -> float
val atan2 : float -> float -> float
val hypot : float -> float -> float
val ceil : float -> float
val floor : float -> float
val abs_float : float -> float
val copysign : float -> float -> float
val modf : float -> float * float
val zero : float
val one : float
val make_shared : Int32.t -> float array
val make_local : Int32.t -> float array
end
module Float64 :
sig
val add : float -> float -> float
val minus : float -> float -> float
val mul : float -> float -> float
val div : float -> float -> float
val pow : float -> float -> float
val sqrt : float -> float
val rsqrt : float -> float
val exp : float -> float
val log : float -> float
val log10 : float -> float
val expm1 : float -> float
val log1p : float -> float
val acos : float -> float
val cos : float -> float
val cosh : float -> float
val asin : float -> float
val sin : float -> float
val sinh : float -> float
val tan : float -> float
val tanh : float -> float
val atan : float -> float
val atan2 : float -> float -> float
val hypot : float -> float -> float
val ceil : float -> float
val floor : float -> float
val abs_float : float -> float
val copysign : float -> float -> float
val modf : float -> float * float
val zero : float
val one : float
val of_float32 : float -> float
val of_float : float -> float
val to_float32 : float -> float
val make_shared : Int32.t -> float array
val make_local : Int32.t -> float array
end
end
val a_to_vect : Kirc_Ast.k_ext - > Kirc_Ast.k_ext
val a_to_return_vect :
Kirc_Ast.k_ext - > Kirc_Ast.k_ext - > Kirc_Ast.k_ext - > Kirc_Ast.k_ext
val param_list : int list ref
val add_to_param_list : int - > unit
val check_and_transform_to_map : Kirc_Ast.k_ext - > Kirc_Ast.k_ext
:
( ' a , ' b ) Spoc.Vector.vector - > ( ' a , ' b ) . Kernel.kernelArgs
val propagate :
( Kirc_Ast.k_ext - > Kirc_Ast.k_ext ) - > Kirc_Ast.k_ext - > Kirc_Ast.k_ext
val map :
( ' a , ' b , ' c - > ' i , ' i , ' j ) sarek_kernel - >
? dev : Spoc . Devices.device - >
( ' g , ' h ) Spoc.Vector.vector - > ( ' i , ' j ) Spoc.Vector.vector
val map2 :
( ' a , ' b , ' c - > 'd - > ' l , ' l , ' m ) sarek_kernel - >
? dev : Spoc . Devices.device - >
( ' h , ' i ) Spoc.Vector.vector - >
( ' j , ' k ) Spoc.Vector.vector - > ( ' l , ' m ) Spoc.Vector.vector
val a_to_return_vect :
Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val param_list : int list ref
val add_to_param_list : int -> unit
val check_and_transform_to_map : Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val arg_of_vec :
('a, 'b) Spoc.Vector.vector -> ('a, 'b) Spoc.Kernel.kernelArgs
val propagate :
(Kirc_Ast.k_ext -> Kirc_Ast.k_ext) -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val map :
('a, 'b, 'c -> 'i, 'i, 'j) sarek_kernel ->
?dev:Spoc.Devices.device ->
('g, 'h) Spoc.Vector.vector -> ('i, 'j) Spoc.Vector.vector
val map2 :
('a, 'b, 'c -> 'd -> 'l, 'l, 'm) sarek_kernel ->
?dev:Spoc.Devices.device ->
('h, 'i) Spoc.Vector.vector ->
('j, 'k) Spoc.Vector.vector -> ('l, 'm) Spoc.Vector.vector
*)
| null | https://raw.githubusercontent.com/mathiasbourgoin/SPOC/ddfde5bdb089f519457c7bb0a2cb1469d71d00fb/SpocLibs/Sarek/Kirc.mli | ocaml | , 'c, 'd, 'e) kirc_function ->
, 'c, 'd, 'e) kirc_function -> | type float64 = float
type float32 = float
type extension = ExFloat32 | ExFloat64
type ('a, 'b, 'c) kirc_kernel = {
ml_kern : 'a;
body : Kirc_Ast.k_ext;
ret_val : Kirc_Ast.k_ext * ('b, 'c) Spoc.Vector.kind;
extensions : extension array;
}
type ('a,'b,'c, 'd) kirc_function =
{
fun_name:string;
ml_fun : 'a;
funbody : Kirc_Ast.k_ext;
fun_ret : Kirc_Ast.k_ext* ('b,'c) Spoc.Vector.kind;
fastflow_acc : 'd;
fun_extensions : extension array
}
type ('a, 'b, 'c, 'd, 'e) sarek_kernel =
('a, 'b) Spoc.Kernel.spoc_kernel * ('c, 'd, 'e) kirc_kernel
val constructors : string list ref
val eint32 : Kirc_Ast.elttype
val eint64 : Kirc_Ast.elttype
val efloat32 : Kirc_Ast.elttype
val efloat64 : Kirc_Ast.elttype
val global : Kirc_Ast.memspace
val local : Kirc_Ast.memspace
val shared : Kirc_Ast.memspace
val print_ast : Kirc_Ast.k_ext -> unit
val opencl_head : string
val opencl_float64 : string
val cuda_float64 : string
val cuda_head : string
val new_var : int -> Kirc_Ast.k_ext
val global_fun : ('a,'b,'c, 'd) kirc_function -> Kirc_Ast.k_ext
val new_array : string -> Kirc_Ast.k_ext -> Kirc_Ast.elttype -> Kirc_Ast.memspace -> Kirc_Ast.k_ext
val var : int -> string -> Kirc_Ast.k_ext
val spoc_gen_kernel : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_fun_kernel : 'a -> 'b -> unit
val seq : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val app : Kirc_Ast.k_ext -> Kirc_Ast.k_ext array -> Kirc_Ast.k_ext
val spoc_unit : unit -> Kirc_Ast.k_ext
val spoc_int : int -> Kirc_Ast.k_ext
val global_int_var : (unit -> int32) -> Kirc_Ast.k_ext
val global_float_var : (unit -> float) -> Kirc_Ast.k_ext
val global_float64_var : (unit -> float) -> Kirc_Ast.k_ext
val spoc_int32 : int32 -> Kirc_Ast.k_ext
val spoc_float : float -> Kirc_Ast.k_ext
val spoc_double : float -> Kirc_Ast.k_ext
val spoc_int_id : int -> Kirc_Ast.k_ext
val spoc_float_id : float -> Kirc_Ast.k_ext
val spoc_plus : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_plus_float : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_min : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_min_float : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_mul : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_mul_float : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_div : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_div_float : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_mod : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_ife :
Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_if : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_match : string -> Kirc_Ast.k_ext -> Kirc_Ast.case array -> Kirc_Ast.k_ext
val spoc_case : int -> (string*string*int*string) option -> Kirc_Ast.k_ext -> Kirc_Ast.case
val spoc_do :
Kirc_Ast.k_ext ->
Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_while : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val params : Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_id : 'a -> Kirc_Ast.k_ext
val spoc_constr : string -> string -> Kirc_Ast.k_ext list -> Kirc_Ast.k_ext
val spoc_record : string -> Kirc_Ast.k_ext list -> Kirc_Ast.k_ext
val spoc_rec_get : Kirc_Ast.k_ext -> string -> Kirc_Ast.k_ext
val spoc_rec_set : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_return : Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val concat : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val empty_arg : unit -> Kirc_Ast.k_ext
val new_int_var : int -> string -> Kirc_Ast.k_ext
val new_float_var : int -> string -> Kirc_Ast.k_ext
val new_float64_var : int -> string -> Kirc_Ast.k_ext
val new_double_var : int -> string -> Kirc_Ast.k_ext
val new_unit_var : int -> string -> Kirc_Ast.k_ext
val new_custom_var : string -> int -> string -> Kirc_Ast.k_ext
val new_int_vec_var : int -> string -> Kirc_Ast.k_ext
val new_float_vec_var : int -> string -> Kirc_Ast.k_ext
val new_double_vec_var : int -> string -> Kirc_Ast.k_ext
val new_custom_vec_var : string -> int -> string -> Kirc_Ast.k_ext
val int_vect : int -> Kirc_Ast.kvect
val set_vect_var : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val set_arr_var : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val intrinsics : string -> string -> Kirc_Ast.k_ext
val spoc_local_env : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_set : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_declare : Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_local_var : 'a -> 'a
val spoc_acc : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val int_var : 'a -> 'a
val int32_var : 'a -> 'a
val float_var : 'a -> 'a
val double_var : int -> Kirc_Ast.k_ext
val equals : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val equals_custom : string -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val equals32 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val equals64 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val equalsF : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val equalsF64 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val b_or : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val b_and : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val b_not : Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val lt : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val lt32 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val lt64 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val ltF : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val ltF64 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val gt : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val gt32 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val gt64 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val gtF : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val gtF64 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val lte : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val lte32 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val lte64 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val lteF : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val lteF64 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val gte : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val gte32 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val gte64 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val gteF : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val gteF64 : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val get_vec : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val get_arr : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val return_unit : unit -> Kirc_Ast.k_ext
val return_int : int -> string -> Kirc_Ast.k_ext
val return_float : int -> string -> Kirc_Ast.k_ext
val return_double : int -> string -> Kirc_Ast.k_ext
val return_bool : int -> string -> Kirc_Ast.k_ext
val return_custom : string -> string -> string -> Kirc_Ast.k_ext
val rewrite : Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val spoc_native : (Spoc.Devices.device -> string) -> Kirc_Ast.k_ext
val pragma : string list -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val return_v : (string * string) ref
val save : string -> string -> unit
val load_file : string -> bytes
val map : Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val gen_profile :
('a, 'b, 'c, 'd, 'e) sarek_kernel -> Spoc.Devices.device -> unit
val gen :
?keep_temp:bool -> ?profile:bool -> ?return:bool ->
?only:Spoc.Devices.specificLibrary ->
?nvrtc_options:string array ->
('a, 'b, 'c, 'd, 'e) sarek_kernel ->
Spoc.Devices.device ->
('a, 'b, 'c, 'd, 'e) sarek_kernel
val run :
?recompile:bool ->
('a, ('b, 'f) Spoc.Kernel.kernelArgs array, 'c, 'd, 'e) sarek_kernel ->
'a ->
Spoc.Kernel.block * Spoc.Kernel.grid -> int -> Spoc.Devices.device -> unit
val profile_run :
?recompile:bool ->
('a, ('b, 'f) Spoc.Kernel.kernelArgs array, 'c, 'd, 'e) sarek_kernel ->
'a ->
Spoc.Kernel.block * Spoc.Kernel.grid -> int -> Spoc.Devices.device -> unit
val compile_kernel_to_files :
string -> ('a, 'b, 'c, 'd, 'e) sarek_kernel -> Spoc.Devices.device ->unit
module Std :
sig
val thread_idx_x : Int32.t
val thread_idx_y : Int32.t
val thread_idx_z : Int32.t
val block_idx_x : Int32.t
val block_idx_y : Int32.t
val block_idx_z : Int32.t
val block_dim_x : Int32.t
val block_dim_y : Int32.t
val block_dim_z : Int32.t
val grid_dim_x : Int32.t
val grid_dim_y : Int32.t
val grid_dim_z : Int32.t
val global_thread_id : Int32.t
val return : unit -> unit
val float64 : Int32.t -> float
val int_of_float64 : float -> Int32.t
val float : Int32.t -> float
val int_of_float : float -> Int32.t
val block_barrier : unit -> unit
val make_shared : Int32.t -> Int32.t array
val make_local : Int32.t -> Int32.t array
val map :
('a, 'f) Spoc.Vector.vector -> ('b, 'g) Spoc.Vector.vector -> unit
val reduce :
('a, 'f) Spoc.Vector.vector -> ('a, 'g) Spoc.Vector.vector -> unit
end
module Sarek_vector :
sig
val length : ('a,'b) Spoc.Vector.vector -> int32
end
module Math :
sig
val pow : Int32.t -> Int32.t -> Int32.t
val logical_and : Int32.t -> Int32.t -> Int32.t
val xor : Int32.t -> Int32.t -> Int32.t
module Float32 :
sig
val add : float -> float -> float
val minus : float -> float -> float
val mul : float -> float -> float
val div : float -> float -> float
val pow : float -> float -> float
val sqrt : float -> float
val rsqrt : float -> float
val exp : float -> float
val log : float -> float
val log10 : float -> float
val expm1 : float -> float
val log1p : float -> float
val acos : float -> float
val cos : float -> float
val cosh : float -> float
val asin : float -> float
val sin : float -> float
val sinh : float -> float
val tan : float -> float
val tanh : float -> float
val atan : float -> float
val atan2 : float -> float -> float
val hypot : float -> float -> float
val ceil : float -> float
val floor : float -> float
val abs_float : float -> float
val copysign : float -> float -> float
val modf : float -> float * float
val zero : float
val one : float
val make_shared : Int32.t -> float array
val make_local : Int32.t -> float array
end
module Float64 :
sig
val add : float -> float -> float
val minus : float -> float -> float
val mul : float -> float -> float
val div : float -> float -> float
val pow : float -> float -> float
val sqrt : float -> float
val rsqrt : float -> float
val exp : float -> float
val log : float -> float
val log10 : float -> float
val expm1 : float -> float
val log1p : float -> float
val acos : float -> float
val cos : float -> float
val cosh : float -> float
val asin : float -> float
val sin : float -> float
val sinh : float -> float
val tan : float -> float
val tanh : float -> float
val atan : float -> float
val atan2 : float -> float -> float
val hypot : float -> float -> float
val ceil : float -> float
val floor : float -> float
val abs_float : float -> float
val copysign : float -> float -> float
val modf : float -> float * float
val zero : float
val one : float
val of_float32 : float -> float
val of_float : float -> float
val to_float32 : float -> float
val make_shared : Int32.t -> float array
val make_local : Int32.t -> float array
end
end
val a_to_vect : Kirc_Ast.k_ext - > Kirc_Ast.k_ext
val a_to_return_vect :
Kirc_Ast.k_ext - > Kirc_Ast.k_ext - > Kirc_Ast.k_ext - > Kirc_Ast.k_ext
val param_list : int list ref
val add_to_param_list : int - > unit
val check_and_transform_to_map : Kirc_Ast.k_ext - > Kirc_Ast.k_ext
:
( ' a , ' b ) Spoc.Vector.vector - > ( ' a , ' b ) . Kernel.kernelArgs
val propagate :
( Kirc_Ast.k_ext - > Kirc_Ast.k_ext ) - > Kirc_Ast.k_ext - > Kirc_Ast.k_ext
val map :
( ' a , ' b , ' c - > ' i , ' i , ' j ) sarek_kernel - >
? dev : Spoc . Devices.device - >
( ' g , ' h ) Spoc.Vector.vector - > ( ' i , ' j ) Spoc.Vector.vector
val map2 :
( ' a , ' b , ' c - > 'd - > ' l , ' l , ' m ) sarek_kernel - >
? dev : Spoc . Devices.device - >
( ' h , ' i ) Spoc.Vector.vector - >
( ' j , ' k ) Spoc.Vector.vector - > ( ' l , ' m ) Spoc.Vector.vector
val a_to_return_vect :
Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val param_list : int list ref
val add_to_param_list : int -> unit
val check_and_transform_to_map : Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val arg_of_vec :
('a, 'b) Spoc.Vector.vector -> ('a, 'b) Spoc.Kernel.kernelArgs
val propagate :
(Kirc_Ast.k_ext -> Kirc_Ast.k_ext) -> Kirc_Ast.k_ext -> Kirc_Ast.k_ext
val map :
('a, 'b, 'c -> 'i, 'i, 'j) sarek_kernel ->
?dev:Spoc.Devices.device ->
('g, 'h) Spoc.Vector.vector -> ('i, 'j) Spoc.Vector.vector
val map2 :
('a, 'b, 'c -> 'd -> 'l, 'l, 'm) sarek_kernel ->
?dev:Spoc.Devices.device ->
('h, 'i) Spoc.Vector.vector ->
('j, 'k) Spoc.Vector.vector -> ('l, 'm) Spoc.Vector.vector
*)
|
e723d7fa82402e3525d1ebd008ee1409d75d408045e489328bf19099a853d54f | boxp/spellcard | example-entity.clj | (ns {{name}}.domain.entity.example)
(defrecord Example [message])
| null | https://raw.githubusercontent.com/boxp/spellcard/0ad124a276e3e7003967eb3ae9ffdf1b572e4a2a/resources/leiningen/new/spellcard/example-entity.clj | clojure | (ns {{name}}.domain.entity.example)
(defrecord Example [message])
|
|
2d3ba028c33835b8b8eceead43fffe15c881effb56953b8dc7d7de2d73d0f5ce | cardmagic/lucash | tty-consts.scm | ;;; Constant definitions for tty control code (POSIX termios).
Copyright ( c ) 1995 by . See file COPYING .
Largely rehacked by Olin .
These constants are for 2.x ,
;;; and are taken from /usr/include/sys/termio.h
;;; and /usr/include/sys/termios.h.
Non - standard ( POSIX , , 4.3+BSD ) things :
;;; - Some of the baud rates.
;;; Special Control Characters
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Indices into the c_cc[] character array.
;;; Name Subscript Enabled by
;;; ---- --------- ----------
;;; POSIX
^d icanon
icanon
^ ? icanon
(define ttychar/delete-line 3) ; ^u icanon
(define ttychar/interrupt 0) ; ^c isig
^\ isig
(define ttychar/suspend 10) ; ^z isig
^q ixon , ixoff
^s ixon , ixoff
(define ttychar/min 4) ; !icanon ; Not exported
(define ttychar/time 5) ; !icanon ; Not exported
SVR4 & 4.3+BSD
(define ttychar/reprint 12) ; ^r icanon
(define ttychar/literal-next 15) ; ^v iexten
(define ttychar/discard 13) ; ^o iexten
(define ttychar/delayed-suspend 11) ; ^y isig
icanon
4.3+BSD
(define ttychar/status #f) ; ^t icanon
;;; Length of control-char string -- *Not Exported*
(define num-ttychars 19)
Magic " disable feature " tty character
(define disable-tty-char (ascii->char #x00)) ; _POSIX_VDISABLE
;;; Flags controllling input processing
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; POSIX
(define ttyin/ignore-break #o00001) ; ignbrk
(define ttyin/interrupt-on-break #o00002) ; brkint
(define ttyin/ignore-bad-parity-chars #o00004) ; ignpar
(define ttyin/mark-parity-errors #o00010) ; parmrk
(define ttyin/check-parity #o00020) ; inpck
(define ttyin/7bits #o00040) ; istrip
(define ttyin/nl->cr #o00100) ; inlcr
(define ttyin/ignore-cr #o00200) ; igncr
(define ttyin/cr->nl #o00400) ; icrnl
ixon
(define ttyin/input-flow-ctl #o10000) ; ixoff
SVR4 & 4.3+BSD
(define ttyin/xon-any #o4000) ; ixany: Any char restarts after stop
(define ttyin/beep-on-overflow #o20000) ; imaxbel: queue full => ring bell
;;; SVR4
(define ttyin/lowercase #o1000) ; iuclc: Map upper-case to lower case
;;; Flags controlling output processing
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; POSIX
(define ttyout/enable #o000001) ; opost: enable output processing
SVR4 & 4.3+BSD
onlcr : map nl to cr - nl
4.3+BSD
(define ttyout/discard-eot #f) ; onoeot
(define ttyout/expand-tabs #f) ; oxtabs (NOT xtabs)
;;; SVR4
(define ttyout/cr->nl #o000010) ; ocrnl
(define ttyout/fill-w/del #o000200) ; ofdel
(define ttyout/delay-w/fill-char #o000100) ; ofill
(define ttyout/uppercase #o000002) ; olcuc
(define ttyout/nl-does-cr #o000040) ; onlret
(define ttyout/no-col0-cr #o000020) ; onocr
;;; Newline delay
(define ttyout/nl-delay #o000400) ; mask (nldly)
(define ttyout/nl-delay0 #o000000)
tty 37
;;; Horizontal-tab delay
(define ttyout/tab-delay #o014000) ; mask (tabdly)
(define ttyout/tab-delay0 #o000000)
tty 37
(define ttyout/tab-delay2 #o010000)
(define ttyout/tab-delayx #o014000) ; Expand tabs (xtabs, tab3)
;;; Carriage-return delay
(define ttyout/cr-delay #o003000) ; mask (crdly)
(define ttyout/cr-delay0 #o000000)
tn 300
tty 37
concept 100
;;; Vertical tab delay
mask ( vtdly )
(define ttyout/vtab-delay0 #o000000)
tty 37
;;; Backspace delay
mask ( bsdly )
(define ttyout/bs-delay0 #o000000)
(define ttyout/bs-delay1 #o020000)
;;; Form-feed delay
(define ttyout/ff-delay #o100000) ; mask (ffdly)
(define ttyout/ff-delay0 #o000000)
(define ttyout/ff-delay1 #o100000)
(define ttyout/all-delay
(bitwise-ior (bitwise-ior (bitwise-ior ttyout/nl-delay ttyout/tab-delay)
(bitwise-ior ttyout/cr-delay ttyout/vtab-delay))
(bitwise-ior ttyout/bs-delay ttyout/ff-delay)))
;;; Control flags - hacking the serial-line.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; POSIX
(define ttyc/char-size #o00060) ; csize: character size mask
5 bits ( cs5 )
6 bits ( )
7 bits ( cs7 )
8 bits ( cs8 )
cstopb : Send 2 stop bits .
(define ttyc/enable-read #o00200) ; cread: Enable receiver.
parenb
parodd
(define ttyc/hup-on-close #o02000) ; hupcl: Hang up on last close.
(define ttyc/no-modem-sync #o04000) ; clocal: Ignore modem lines.
4.3+BSD
(define ttyc/ignore-flags #f) ; cignore: ignore control flags
(define ttyc/CTS-output-flow-ctl #f) ; ccts_oflow: CTS flow control of output
(define ttyc/RTS-input-flow-ctl #f) ; crts_iflow: RTS flow control of input
(define ttyc/carrier-flow-ctl #f) ; mdmbuf
;;; Local flags -- hacking the tty driver / user interface.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; POSIX
(define ttyl/visual-delete #o020) ; echoe: Visually erase chars
echok : Echo nl after line kill
(define ttyl/echo #o010) ; echo: Enable echoing
echonl : Echo nl even if echo is off
icanon : input
(define ttyl/enable-signals #o001) ; isig: Enable ^c, ^z signalling
(define ttyl/extended #o100000) ; iexten: Enable extensions
tostop : SIGTTOU on background output
(define ttyl/no-flush-on-interrupt #o200) ; noflsh
SVR4 & 4.3+BSD
(define ttyl/visual-delete-line #o04000); echoke: visually erase a line-kill
(define ttyl/hardcopy-delete #o02000); echoprt: visual erase for hardcopy
(define ttyl/echo-ctl #o01000); echoctl: echo control chars as "^X"
(define ttyl/flush-output #o20000); flusho: output is being flushed
(define ttyl/reprint-unread-chars #o40000); pendin: retype pending input
4.3+BSD
(define ttyl/alt-delete-word #f) ; altwerase
(define ttyl/no-kernel-status #f) ; nokerninfo: no kernel status on ^T
;;; SVR4
(define ttyl/case-map #o4) ; xcase: canonical upper/lower presentation
;;; Vector of (speed . code) pairs.
(define baud-rates '#((0 . 0) (1 . 50) (2 . 75)
(3 . 110) (4 . 134) (5 . 150)
(6 . 200) (7 . 300) (8 . 600)
(9 . 1200) (10 . 1800) (11 . 2400)
(12 . 4800) (13 . 9600) (14 . 19200)
(15 . 38400)))
;;; tcflush() constants
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define %flush-tty/input 0) ; TCIFLUSH
TCOFLUSH
(define %flush-tty/both 2) ; TCIOFLUSH
;;; tcflow() constants
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define %tcflow/start-out 1) ; TCOON
(define %tcflow/stop-out 0) ; TCOOFF
(define %tcflow/start-in 3) ; TCION
(define %tcflow/stop-in 2) ; TCIOFF
;;; tcsetattr() constants
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
TCSANOW Make change immediately .
(define %set-tty-info/drain 21519) ; TCSADRAIN Drain output, then change.
(define %set-tty-info/flush 21520) ; TCSAFLUSH Drain output, flush input.
| null | https://raw.githubusercontent.com/cardmagic/lucash/0452d410430d12140c14948f7f583624f819cdad/reference/scsh-0.6.6/scsh/solaris/tty-consts.scm | scheme | Constant definitions for tty control code (POSIX termios).
and are taken from /usr/include/sys/termio.h
and /usr/include/sys/termios.h.
- Some of the baud rates.
Special Control Characters
Indices into the c_cc[] character array.
Name Subscript Enabled by
---- --------- ----------
POSIX
^u icanon
^c isig
^z isig
!icanon ; Not exported
!icanon ; Not exported
^r icanon
^v iexten
^o iexten
^y isig
^t icanon
Length of control-char string -- *Not Exported*
_POSIX_VDISABLE
Flags controllling input processing
POSIX
ignbrk
brkint
ignpar
parmrk
inpck
istrip
inlcr
igncr
icrnl
ixoff
ixany: Any char restarts after stop
imaxbel: queue full => ring bell
SVR4
iuclc: Map upper-case to lower case
Flags controlling output processing
POSIX
opost: enable output processing
onoeot
oxtabs (NOT xtabs)
SVR4
ocrnl
ofdel
ofill
olcuc
onlret
onocr
Newline delay
mask (nldly)
Horizontal-tab delay
mask (tabdly)
Expand tabs (xtabs, tab3)
Carriage-return delay
mask (crdly)
Vertical tab delay
Backspace delay
Form-feed delay
mask (ffdly)
Control flags - hacking the serial-line.
POSIX
csize: character size mask
cread: Enable receiver.
hupcl: Hang up on last close.
clocal: Ignore modem lines.
cignore: ignore control flags
ccts_oflow: CTS flow control of output
crts_iflow: RTS flow control of input
mdmbuf
Local flags -- hacking the tty driver / user interface.
POSIX
echoe: Visually erase chars
echo: Enable echoing
isig: Enable ^c, ^z signalling
iexten: Enable extensions
noflsh
echoke: visually erase a line-kill
echoprt: visual erase for hardcopy
echoctl: echo control chars as "^X"
flusho: output is being flushed
pendin: retype pending input
altwerase
nokerninfo: no kernel status on ^T
SVR4
xcase: canonical upper/lower presentation
Vector of (speed . code) pairs.
tcflush() constants
TCIFLUSH
TCIOFLUSH
tcflow() constants
TCOON
TCOOFF
TCION
TCIOFF
tcsetattr() constants
TCSADRAIN Drain output, then change.
TCSAFLUSH Drain output, flush input. | Copyright ( c ) 1995 by . See file COPYING .
Largely rehacked by Olin .
These constants are for 2.x ,
Non - standard ( POSIX , , 4.3+BSD ) things :
^d icanon
icanon
^ ? icanon
^\ isig
^q ixon , ixoff
^s ixon , ixoff
SVR4 & 4.3+BSD
icanon
4.3+BSD
(define num-ttychars 19)
Magic " disable feature " tty character
ixon
SVR4 & 4.3+BSD
SVR4 & 4.3+BSD
onlcr : map nl to cr - nl
4.3+BSD
(define ttyout/nl-delay0 #o000000)
tty 37
(define ttyout/tab-delay0 #o000000)
tty 37
(define ttyout/tab-delay2 #o010000)
(define ttyout/cr-delay0 #o000000)
tn 300
tty 37
concept 100
mask ( vtdly )
(define ttyout/vtab-delay0 #o000000)
tty 37
mask ( bsdly )
(define ttyout/bs-delay0 #o000000)
(define ttyout/bs-delay1 #o020000)
(define ttyout/ff-delay0 #o000000)
(define ttyout/ff-delay1 #o100000)
(define ttyout/all-delay
(bitwise-ior (bitwise-ior (bitwise-ior ttyout/nl-delay ttyout/tab-delay)
(bitwise-ior ttyout/cr-delay ttyout/vtab-delay))
(bitwise-ior ttyout/bs-delay ttyout/ff-delay)))
5 bits ( cs5 )
6 bits ( )
7 bits ( cs7 )
8 bits ( cs8 )
cstopb : Send 2 stop bits .
parenb
parodd
4.3+BSD
echok : Echo nl after line kill
echonl : Echo nl even if echo is off
icanon : input
tostop : SIGTTOU on background output
SVR4 & 4.3+BSD
4.3+BSD
(define baud-rates '#((0 . 0) (1 . 50) (2 . 75)
(3 . 110) (4 . 134) (5 . 150)
(6 . 200) (7 . 300) (8 . 600)
(9 . 1200) (10 . 1800) (11 . 2400)
(12 . 4800) (13 . 9600) (14 . 19200)
(15 . 38400)))
TCOFLUSH
TCSANOW Make change immediately .
|
b38ca69f27d5e709ddf6dbcb83bd4a85ab92aade985e6a2a7e34845ba09cb5c9 | tonsky/compact-uuids | core.cljs | (ns compact-uuids.core
"Compact 26-char URL-safe representation of UUIDs"
(:refer-clojure :exclude [str read])
(:require-macros
[compact-uuids.core :as uuid]))
(defn char-of-alphabet [i]
;;
(.charAt "0123456789abcdefghjkmnpqrstvwxyz" i))
(defn char-of-hex [i]
(.charAt "0123456789abcdef" i))
(defn parse-char* [c]
(uuid/parse-char c))
(defn- parse-hex [c]
(cond
0 .. 9
(<= 97 c 102) (- c 87) ;; a-f
(<= 65 c 70) (- c 55))) ;; A-F
(defn- convert [s bits-from bits-to mask from->code code->to]
moving right - to - left , one char at a time
acc 0
acc-len 0
res ""]
(cond
;; accumulated enough bits to generate char from lowest `bits-to` bits
(>= acc-len bits-to)
(recur
pos
(unsigned-bit-shift-right acc bits-to) ;; drop lowest `bits-to` bits
(- acc-len bits-to)
(clojure.core/str (code->to (bit-and acc mask)) res)) ;; prepend char corresponding to lowest `bits-to` bits
;; end of string
(neg? pos)
(clojure.core/str (code->to (bit-and acc mask)) res) ;; prepend rest of bits
;; read next `bits-from` bits from the string
:else
(recur
(dec pos)
put next ` bits - from ` bits in front of ` acc `
(-> (from->code (.charCodeAt s pos))
(bit-shift-left acc-len)
(bit-or acc))
(+ acc-len bits-from)
res))))
(defn- base32->hex [s]
base32 is 65 bits from which we only use 64
when converted to hex , we pad it to 68 bits ( 17 chars )
drop first one as known to always be 0000
(-> (convert s 5 4 0x0F parse-char* char-of-hex)
(.substring 1)))
(defn read [s]
(let [h (base32->hex (subs s 0 13))
l (base32->hex (subs s 13 26))]
(uuid (clojure.core/str (subs h 0 8) "-" (subs h 8 12) "-" (subs h 12 16) "-" (subs l 0 4) "-" (subs l 4 16)))))
(defn read-both [s]
(case (count s)
26 (read s)
36 (uuid s)))
(defn- hex->base32 [s]
(convert s 4 5 0x1F parse-hex char-of-alphabet))
(defn str [uuid]
(let [s (clojure.core/str uuid)]
(clojure.core/str
(hex->base32 (clojure.core/str (subs s 0 8) (subs s 9 13) (subs s 14 18)))
(hex->base32 (clojure.core/str (subs s 19 23) (subs s 24 36)))))) | null | https://raw.githubusercontent.com/tonsky/compact-uuids/de6f44c393a008dfcefc30bc42d8519312a66175/src/compact_uuids/core.cljs | clojure |
a-f
A-F
accumulated enough bits to generate char from lowest `bits-to` bits
drop lowest `bits-to` bits
prepend char corresponding to lowest `bits-to` bits
end of string
prepend rest of bits
read next `bits-from` bits from the string | (ns compact-uuids.core
"Compact 26-char URL-safe representation of UUIDs"
(:refer-clojure :exclude [str read])
(:require-macros
[compact-uuids.core :as uuid]))
(defn char-of-alphabet [i]
(.charAt "0123456789abcdefghjkmnpqrstvwxyz" i))
(defn char-of-hex [i]
(.charAt "0123456789abcdef" i))
(defn parse-char* [c]
(uuid/parse-char c))
(defn- parse-hex [c]
(cond
0 .. 9
(defn- convert [s bits-from bits-to mask from->code code->to]
moving right - to - left , one char at a time
acc 0
acc-len 0
res ""]
(cond
(>= acc-len bits-to)
(recur
pos
(- acc-len bits-to)
(neg? pos)
:else
(recur
(dec pos)
put next ` bits - from ` bits in front of ` acc `
(-> (from->code (.charCodeAt s pos))
(bit-shift-left acc-len)
(bit-or acc))
(+ acc-len bits-from)
res))))
(defn- base32->hex [s]
base32 is 65 bits from which we only use 64
when converted to hex , we pad it to 68 bits ( 17 chars )
drop first one as known to always be 0000
(-> (convert s 5 4 0x0F parse-char* char-of-hex)
(.substring 1)))
(defn read [s]
(let [h (base32->hex (subs s 0 13))
l (base32->hex (subs s 13 26))]
(uuid (clojure.core/str (subs h 0 8) "-" (subs h 8 12) "-" (subs h 12 16) "-" (subs l 0 4) "-" (subs l 4 16)))))
(defn read-both [s]
(case (count s)
26 (read s)
36 (uuid s)))
(defn- hex->base32 [s]
(convert s 4 5 0x1F parse-hex char-of-alphabet))
(defn str [uuid]
(let [s (clojure.core/str uuid)]
(clojure.core/str
(hex->base32 (clojure.core/str (subs s 0 8) (subs s 9 13) (subs s 14 18)))
(hex->base32 (clojure.core/str (subs s 19 23) (subs s 24 36)))))) |
62134d7a1db36d62a274be8a4e4fbd9cbb4131583b6a1d92f0df11ad7e9310e3 | kishanov/re-frame-datatable-example | core.clj | (ns re-frame-datatable-example.core)
| null | https://raw.githubusercontent.com/kishanov/re-frame-datatable-example/4468158b0fd33343c51a5e9d7c0edeb8278e1a26/src/clj/re_frame_datatable_example/core.clj | clojure | (ns re-frame-datatable-example.core)
|
|
c8eb92c5c4d1488d9f527e517a87570cdfcbb5fa04e4c3d3364297fb8c6417e0 | camllight/camllight | determ.mli | type état =
{ mutable dtransitions : transition vect;
dterminal : bool }
and transition =
Vers of état
| Rejet;;
value déterminise : auto__état -> determ__état
and reconnaît : determ__état -> string -> bool;;
| null | https://raw.githubusercontent.com/camllight/camllight/0cc537de0846393322058dbb26449427bfc76786/windows/examples/grep/determ.mli | ocaml | type état =
{ mutable dtransitions : transition vect;
dterminal : bool }
and transition =
Vers of état
| Rejet;;
value déterminise : auto__état -> determ__état
and reconnaît : determ__état -> string -> bool;;
|
|
9b820d51a2b6c83550cdffea6f7d206f81695a54715e614303b12d9936026b72 | binaryage/chromex | printer_provider.clj | (ns chromex.app.printer-provider
"The chrome.printerProvider API exposes events used by print
manager to query printers controlled by extensions, to query their
capabilities and to submit print jobs to these printers.
* available since Chrome 44
* "
(:refer-clojure :only [defmacro defn apply declare meta let partial])
(:require [chromex.wrapgen :refer [gen-wrap-helper]]
[chromex.callgen :refer [gen-call-helper gen-tap-all-events-call]]))
(declare api-table)
(declare gen-call)
; -- events -----------------------------------------------------------------------------------------------------------------
;
; docs: /#tapping-events
(defmacro tap-on-get-printers-requested-events
"Event fired when print manager requests printers provided by extensions.
Events will be put on the |channel| with signature [::on-get-printers-requested [result-callback]].
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onGetPrintersRequested."
([channel & args] (apply gen-call :event ::on-get-printers-requested &form channel args)))
(defmacro tap-on-get-usb-printer-info-requested-events
"Event fired when print manager requests information about a USB device that may be a printer. Note: An application should
not rely on this event being fired more than once per device. If a connected device is supported it should be returned in
the 'onGetPrintersRequested' event.
Events will be put on the |channel| with signature [::on-get-usb-printer-info-requested [device result-callback]] where:
|device| - The USB device.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onGetUsbPrinterInfoRequested."
([channel & args] (apply gen-call :event ::on-get-usb-printer-info-requested &form channel args)))
(defmacro tap-on-get-capability-requested-events
"Event fired when print manager requests printer capabilities.
Events will be put on the |channel| with signature [::on-get-capability-requested [printer-id result-callback]] where:
|printer-id| - Unique ID of the printer whose capabilities are requested.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onGetCapabilityRequested."
([channel & args] (apply gen-call :event ::on-get-capability-requested &form channel args)))
(defmacro tap-on-print-requested-events
"Event fired when print manager requests printing.
Events will be put on the |channel| with signature [::on-print-requested [print-job result-callback]] where:
|print-job| - The printing request parameters.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onPrintRequested."
([channel & args] (apply gen-call :event ::on-print-requested &form channel args)))
; -- convenience ------------------------------------------------------------------------------------------------------------
(defmacro tap-all-events
"Taps all valid non-deprecated events in chromex.app.printer-provider namespace."
[chan]
(gen-tap-all-events-call api-table (meta &form) chan))
; ---------------------------------------------------------------------------------------------------------------------------
; -- API TABLE --------------------------------------------------------------------------------------------------------------
; ---------------------------------------------------------------------------------------------------------------------------
(def api-table
{:namespace "chrome.printerProvider",
:since "44",
:events
[{:id ::on-get-printers-requested,
:name "onGetPrintersRequested",
:params [{:name "result-callback", :type :callback}]}
{:id ::on-get-usb-printer-info-requested,
:name "onGetUsbPrinterInfoRequested",
:since "45",
:params [{:name "device", :type "usb.Device"} {:name "result-callback", :type :callback}]}
{:id ::on-get-capability-requested,
:name "onGetCapabilityRequested",
:params [{:name "printer-id", :type "string"} {:name "result-callback", :type :callback}]}
{:id ::on-print-requested,
:name "onPrintRequested",
:params [{:name "print-job", :type "printerProvider.PrintJob"} {:name "result-callback", :type :callback}]}]})
; -- helpers ----------------------------------------------------------------------------------------------------------------
; code generation for native API wrapper
(defmacro gen-wrap [kind item-id config & args]
(apply gen-wrap-helper api-table kind item-id config args))
; code generation for API call-site
(def gen-call (partial gen-call-helper api-table)) | null | https://raw.githubusercontent.com/binaryage/chromex/33834ba5dd4f4238a3c51f99caa0416f30c308c5/src/apps/chromex/app/printer_provider.clj | clojure | -- events -----------------------------------------------------------------------------------------------------------------
docs: /#tapping-events
-- convenience ------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
-- API TABLE --------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
-- helpers ----------------------------------------------------------------------------------------------------------------
code generation for native API wrapper
code generation for API call-site | (ns chromex.app.printer-provider
"The chrome.printerProvider API exposes events used by print
manager to query printers controlled by extensions, to query their
capabilities and to submit print jobs to these printers.
* available since Chrome 44
* "
(:refer-clojure :only [defmacro defn apply declare meta let partial])
(:require [chromex.wrapgen :refer [gen-wrap-helper]]
[chromex.callgen :refer [gen-call-helper gen-tap-all-events-call]]))
(declare api-table)
(declare gen-call)
(defmacro tap-on-get-printers-requested-events
"Event fired when print manager requests printers provided by extensions.
Events will be put on the |channel| with signature [::on-get-printers-requested [result-callback]].
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onGetPrintersRequested."
([channel & args] (apply gen-call :event ::on-get-printers-requested &form channel args)))
(defmacro tap-on-get-usb-printer-info-requested-events
"Event fired when print manager requests information about a USB device that may be a printer. Note: An application should
not rely on this event being fired more than once per device. If a connected device is supported it should be returned in
the 'onGetPrintersRequested' event.
Events will be put on the |channel| with signature [::on-get-usb-printer-info-requested [device result-callback]] where:
|device| - The USB device.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onGetUsbPrinterInfoRequested."
([channel & args] (apply gen-call :event ::on-get-usb-printer-info-requested &form channel args)))
(defmacro tap-on-get-capability-requested-events
"Event fired when print manager requests printer capabilities.
Events will be put on the |channel| with signature [::on-get-capability-requested [printer-id result-callback]] where:
|printer-id| - Unique ID of the printer whose capabilities are requested.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onGetCapabilityRequested."
([channel & args] (apply gen-call :event ::on-get-capability-requested &form channel args)))
(defmacro tap-on-print-requested-events
"Event fired when print manager requests printing.
Events will be put on the |channel| with signature [::on-print-requested [print-job result-callback]] where:
|print-job| - The printing request parameters.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onPrintRequested."
([channel & args] (apply gen-call :event ::on-print-requested &form channel args)))
(defmacro tap-all-events
"Taps all valid non-deprecated events in chromex.app.printer-provider namespace."
[chan]
(gen-tap-all-events-call api-table (meta &form) chan))
(def api-table
{:namespace "chrome.printerProvider",
:since "44",
:events
[{:id ::on-get-printers-requested,
:name "onGetPrintersRequested",
:params [{:name "result-callback", :type :callback}]}
{:id ::on-get-usb-printer-info-requested,
:name "onGetUsbPrinterInfoRequested",
:since "45",
:params [{:name "device", :type "usb.Device"} {:name "result-callback", :type :callback}]}
{:id ::on-get-capability-requested,
:name "onGetCapabilityRequested",
:params [{:name "printer-id", :type "string"} {:name "result-callback", :type :callback}]}
{:id ::on-print-requested,
:name "onPrintRequested",
:params [{:name "print-job", :type "printerProvider.PrintJob"} {:name "result-callback", :type :callback}]}]})
(defmacro gen-wrap [kind item-id config & args]
(apply gen-wrap-helper api-table kind item-id config args))
(def gen-call (partial gen-call-helper api-table)) |
e9df054c3affa7256c6e45ec6a48a31a778df38979ac9f3eb510c790fe43f8fc | gstew5/cs4100-public | interp.mli | open Errors
open Exp
val tycheck_and_print_result : exp -> unit
val print_result : exp -> unit
| null | https://raw.githubusercontent.com/gstew5/cs4100-public/53c99e3e87331aa5dfa9161ca350a8e23acee739/tyckeck-example/interp.mli | ocaml | open Errors
open Exp
val tycheck_and_print_result : exp -> unit
val print_result : exp -> unit
|
|
a49a76668a63cf8a19876a8d4aee65feaa3fed9d508f3fe93f593e543c7c84e7 | ivanjovanovic/sicp | e-5.33-factorial-compiled.scm | (assign val (op make-compiled-procedure) (label entry18) (reg env))
(goto (label after-lambda19))
entry18
(assign env (op compiled-procedure-env) (reg proc))
(assign env (op extend-environment) (const (n)) (reg argl) (reg env))
(save continue)
(save env)
(assign proc (op lookup-variable-value) (const =) (reg env))
(assign val (const 1))
(assign argl (op list) (reg val))
(assign val (op lookup-variable-value) (const n) (reg env))
(assign argl (op cons) (reg val) (reg argl))
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-branch23))
compiled-branch24
(assign continue (label after-call25))
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
primitive-branch23
(assign val (op apply-primitive-procedure) (reg proc) (reg argl))
after-call25
(restore env)
(restore continue)
(test (op false?) (reg val))
(branch (label false-branch21))
true-branch20
(assign val (const 1))
(goto (reg continue))
false-branch21
(assign proc (op lookup-variable-value) (const *) (reg env))
(save continue)
(save proc)
(save env)
(assign proc (op lookup-variable-value) (const factorial-alt) (reg env))
(save proc)
(assign proc (op lookup-variable-value) (const -) (reg env))
(assign val (const 1))
(assign argl (op list) (reg val))
(assign val (op lookup-variable-value) (const n) (reg env))
(assign argl (op cons) (reg val) (reg argl))
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-branch26))
compiled-branch27
(assign continue (label after-call28))
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
primitive-branch26
(assign val (op apply-primitive-procedure) (reg proc) (reg argl))
after-call28
(assign argl (op list) (reg val))
(restore proc)
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-branch29))
compiled-branch30
(assign continue (label after-call31))
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
primitive-branch29
(assign val (op apply-primitive-procedure) (reg proc) (reg argl))
after-call31
(assign argl (op list) (reg val))
(restore env)
(assign val (op lookup-variable-value) (const n) (reg env))
(assign argl (op cons) (reg val) (reg argl))
(restore proc)
(restore continue)
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-branch32))
compiled-branch33
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
primitive-branch32
(assign val (op apply-primitive-procedure) (reg proc) (reg argl))
(goto (reg continue))
after-call34
after-if22
after-lambda19
(perform (op define-variable!) (const factorial-alt) (reg val) (reg env))
(assign val (const ok))
| null | https://raw.githubusercontent.com/ivanjovanovic/sicp/a3bfbae0a0bda414b042e16bbb39bf39cd3c38f8/5.5/e-5.33-factorial-compiled.scm | scheme | (assign val (op make-compiled-procedure) (label entry18) (reg env))
(goto (label after-lambda19))
entry18
(assign env (op compiled-procedure-env) (reg proc))
(assign env (op extend-environment) (const (n)) (reg argl) (reg env))
(save continue)
(save env)
(assign proc (op lookup-variable-value) (const =) (reg env))
(assign val (const 1))
(assign argl (op list) (reg val))
(assign val (op lookup-variable-value) (const n) (reg env))
(assign argl (op cons) (reg val) (reg argl))
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-branch23))
compiled-branch24
(assign continue (label after-call25))
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
primitive-branch23
(assign val (op apply-primitive-procedure) (reg proc) (reg argl))
after-call25
(restore env)
(restore continue)
(test (op false?) (reg val))
(branch (label false-branch21))
true-branch20
(assign val (const 1))
(goto (reg continue))
false-branch21
(assign proc (op lookup-variable-value) (const *) (reg env))
(save continue)
(save proc)
(save env)
(assign proc (op lookup-variable-value) (const factorial-alt) (reg env))
(save proc)
(assign proc (op lookup-variable-value) (const -) (reg env))
(assign val (const 1))
(assign argl (op list) (reg val))
(assign val (op lookup-variable-value) (const n) (reg env))
(assign argl (op cons) (reg val) (reg argl))
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-branch26))
compiled-branch27
(assign continue (label after-call28))
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
primitive-branch26
(assign val (op apply-primitive-procedure) (reg proc) (reg argl))
after-call28
(assign argl (op list) (reg val))
(restore proc)
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-branch29))
compiled-branch30
(assign continue (label after-call31))
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
primitive-branch29
(assign val (op apply-primitive-procedure) (reg proc) (reg argl))
after-call31
(assign argl (op list) (reg val))
(restore env)
(assign val (op lookup-variable-value) (const n) (reg env))
(assign argl (op cons) (reg val) (reg argl))
(restore proc)
(restore continue)
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-branch32))
compiled-branch33
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
primitive-branch32
(assign val (op apply-primitive-procedure) (reg proc) (reg argl))
(goto (reg continue))
after-call34
after-if22
after-lambda19
(perform (op define-variable!) (const factorial-alt) (reg val) (reg env))
(assign val (const ok))
|
|
45ee5afbe83c3809b0d2a7ec610963f008a89594273f8d305b439ee33ee8f142 | CryptoKami/cryptokami-core | Impl.hs | -- | This module re-exports slotting implementations.
# OPTIONS_GHC -F -pgmF autoexporter #
| null | https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/infra/Pos/Slotting/Impl.hs | haskell | | This module re-exports slotting implementations. |
# OPTIONS_GHC -F -pgmF autoexporter #
|
f767f6dc98f6132de7483bb8585f901f8223c02656c8806a062bfda41b324c85 | tweag/ormolu | associated-data2-out.hs | # LANGUAGE TypeFamilies #
module Main where
-- | Something more.
class Baz a where
-- | Baz bar
data
BazBar
a
b
c
| baz
data
BazBaz
b
a
c
| null | https://raw.githubusercontent.com/tweag/ormolu/34bdf62429768f24b70d0f8ba7730fc4d8ae73ba/data/examples/declaration/class/associated-data2-out.hs | haskell | | Something more.
| Baz bar | # LANGUAGE TypeFamilies #
module Main where
class Baz a where
data
BazBar
a
b
c
| baz
data
BazBaz
b
a
c
|
1519842b28340749066e97e5adc16ac2d56467501b801193dc141b2306874dbd | alphaHeavy/llvm-general-typed | ValueWrap.hs | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE InstanceSigs #
# LANGUAGE LambdaCase #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
module LLVM.General.Typed.ValueWrap
( operandWrap
, functionWrap
) where
import Control.Monad
import qualified Data.Foldable as Foldable
import Data.Typeable
import GHC.TypeLits
import qualified LLVM.General.AST as AST
import qualified LLVM.General.AST.Constant as Constant
import qualified LLVM.General.AST.Float as Float
import qualified LLVM.General.AST.Global as AST
import qualified LLVM.General.AST.Type as Type
import LLVM.General.Typed.ArgumentList
import LLVM.General.Typed.CallingConv
import LLVM.General.Typed.Function
import LLVM.General.Typed.FunctionType
import LLVM.General.Typed.Value
import LLVM.General.Typed.ValueOf
-- |
-- Attempt to lift an operand into a typed 'Value'
class OperandWrap op where
type OperandConstness op :: Constness
operandWrap :: ValueOf a => op -> Maybe (Value (OperandConstness op) a)
instance OperandWrap AST.Operand where
type OperandConstness AST.Operand = 'Operand
operandWrap :: forall a. ValueOf a => AST.Operand -> Maybe (Value 'Operand a)
operandWrap op@(AST.LocalReference ty _)
| valueType (Proxy :: Proxy a) == ty = Just (ValuePure op)
operandWrap (AST.ConstantOperand op) = ValueWeakened <$> operandWrap op
operandWrap _ = Nothing
-- |
-- Test if a 'Constant' matches a given 'Type'
constantMatch :: AST.Type -> Constant.Constant -> Bool
constantMatch rep = go where
go = \ case
Constant.Int n _ | AST.IntegerType n' <- rep, n == n' -> True
Constant.Float (Float.Single _) | AST.FloatingPointType 4 Type.IEEE <- rep -> True
Constant.Float (Float.Double _) | AST.FloatingPointType 8 Type.IEEE <- rep -> True
Constant.Null typ -> typ == rep
Constant.Array typ _ -> typ == rep
Constant.Vector typs -> Foldable.all go typs
Constant.Undef typ -> typ == rep
Constant.GlobalReference typ _ -> typ == rep
Constant.Add _ _ lhs rhs -> go lhs && go rhs
Constant.FAdd lhs rhs -> go lhs && go rhs
Constant.Sub _ _ lhs rhs -> go lhs && go rhs
Constant.FSub lhs rhs -> go lhs && go rhs
Constant.Mul _ _ lhs rhs -> go lhs && go rhs
Constant.FMul lhs rhs -> go lhs && go rhs
Constant.UDiv _ lhs rhs -> go lhs && go rhs
Constant.SDiv _ lhs rhs -> go lhs && go rhs
Constant.FDiv lhs rhs -> go lhs && go rhs
Constant.URem lhs rhs -> go lhs && go rhs
Constant.SRem lhs rhs -> go lhs && go rhs
Constant.FRem lhs rhs -> go lhs && go rhs
Constant.Shl _ _ lhs rhs -> go lhs && go rhs
Constant.LShr _ lhs rhs -> go lhs && go rhs
Constant.AShr _ lhs rhs -> go lhs && go rhs
Constant.And lhs rhs -> go lhs && go rhs
Constant.Or lhs rhs -> go lhs && go rhs
Constant.Xor lhs rhs -> go lhs && go rhs
Constant.Select _ lhs rhs -> go lhs && go rhs
Constant.Trunc _ typ -> typ == rep
Constant.ZExt _ typ -> typ == rep
Constant.SExt _ typ -> typ == rep
Constant.FPToUI _ typ -> typ == rep
Constant.FPToSI _ typ -> typ == rep
Constant.UIToFP _ typ -> typ == rep
Constant.SIToFP _ typ -> typ == rep
Constant.FPTrunc _ typ -> typ == rep
Constant.FPExt _ typ -> typ == rep
Constant.PtrToInt _ typ -> typ == rep
Constant.IntToPtr _ typ -> typ == rep
Constant.BitCast _ typ -> typ == rep
Constant.ICmp{} -> valueType (Proxy :: Proxy Bool) == rep
Constant.FCmp{} -> valueType (Proxy :: Proxy Bool) == rep
_ -> False
instance OperandWrap Constant.Constant where
type OperandConstness Constant.Constant = 'Constant
operandWrap :: forall a. ValueOf a => Constant.Constant -> Maybe (Value 'Constant a)
operandWrap op = do
let rep = valueType (Proxy :: Proxy a)
guard $ constantMatch rep op
return $ ValueConstant op
-- |
-- Attempt to convert a 'AST.Global' function pointer to a strongly typed 'Function'
functionWrap
:: forall a cc . (KnownNat cc, FunctionType (ArgumentList a))
=> AST.Global
-> Maybe (Function ('CallingConv cc) a)
functionWrap AST.Function{..} = do
-- check that the requested calling convention matches the declaration
let callingConvention' = reifyCallingConv (Proxy :: Proxy ('CallingConv cc))
guard (callingConvention == callingConvention')
-- split the type signature into argument types and return type
(ty', rty) <- splitFunctionTypes $ functionType (Proxy :: Proxy (ArgumentList a))
-- and test that these types match the declaration
guard $ returnType == rty
let pty = [ty | AST.Parameter ty _ _ <- fst parameters]
fty = Type.FunctionType returnType pty (snd parameters)
guard $ pty == ty'
-- global Functions are always constant
return $ Function (ValueConstant (Constant.GlobalReference fty name)) callingConvention'
functionWrap _ = Nothing
| null | https://raw.githubusercontent.com/alphaHeavy/llvm-general-typed/75c39111f7fc685aacb3eaf1b2948451e7222e0b/llvm-general-typed-pure/src/LLVM/General/Typed/ValueWrap.hs | haskell | # LANGUAGE RankNTypes #
|
Attempt to lift an operand into a typed 'Value'
|
Test if a 'Constant' matches a given 'Type'
|
Attempt to convert a 'AST.Global' function pointer to a strongly typed 'Function'
check that the requested calling convention matches the declaration
split the type signature into argument types and return type
and test that these types match the declaration
global Functions are always constant | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE InstanceSigs #
# LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
module LLVM.General.Typed.ValueWrap
( operandWrap
, functionWrap
) where
import Control.Monad
import qualified Data.Foldable as Foldable
import Data.Typeable
import GHC.TypeLits
import qualified LLVM.General.AST as AST
import qualified LLVM.General.AST.Constant as Constant
import qualified LLVM.General.AST.Float as Float
import qualified LLVM.General.AST.Global as AST
import qualified LLVM.General.AST.Type as Type
import LLVM.General.Typed.ArgumentList
import LLVM.General.Typed.CallingConv
import LLVM.General.Typed.Function
import LLVM.General.Typed.FunctionType
import LLVM.General.Typed.Value
import LLVM.General.Typed.ValueOf
class OperandWrap op where
type OperandConstness op :: Constness
operandWrap :: ValueOf a => op -> Maybe (Value (OperandConstness op) a)
instance OperandWrap AST.Operand where
type OperandConstness AST.Operand = 'Operand
operandWrap :: forall a. ValueOf a => AST.Operand -> Maybe (Value 'Operand a)
operandWrap op@(AST.LocalReference ty _)
| valueType (Proxy :: Proxy a) == ty = Just (ValuePure op)
operandWrap (AST.ConstantOperand op) = ValueWeakened <$> operandWrap op
operandWrap _ = Nothing
constantMatch :: AST.Type -> Constant.Constant -> Bool
constantMatch rep = go where
go = \ case
Constant.Int n _ | AST.IntegerType n' <- rep, n == n' -> True
Constant.Float (Float.Single _) | AST.FloatingPointType 4 Type.IEEE <- rep -> True
Constant.Float (Float.Double _) | AST.FloatingPointType 8 Type.IEEE <- rep -> True
Constant.Null typ -> typ == rep
Constant.Array typ _ -> typ == rep
Constant.Vector typs -> Foldable.all go typs
Constant.Undef typ -> typ == rep
Constant.GlobalReference typ _ -> typ == rep
Constant.Add _ _ lhs rhs -> go lhs && go rhs
Constant.FAdd lhs rhs -> go lhs && go rhs
Constant.Sub _ _ lhs rhs -> go lhs && go rhs
Constant.FSub lhs rhs -> go lhs && go rhs
Constant.Mul _ _ lhs rhs -> go lhs && go rhs
Constant.FMul lhs rhs -> go lhs && go rhs
Constant.UDiv _ lhs rhs -> go lhs && go rhs
Constant.SDiv _ lhs rhs -> go lhs && go rhs
Constant.FDiv lhs rhs -> go lhs && go rhs
Constant.URem lhs rhs -> go lhs && go rhs
Constant.SRem lhs rhs -> go lhs && go rhs
Constant.FRem lhs rhs -> go lhs && go rhs
Constant.Shl _ _ lhs rhs -> go lhs && go rhs
Constant.LShr _ lhs rhs -> go lhs && go rhs
Constant.AShr _ lhs rhs -> go lhs && go rhs
Constant.And lhs rhs -> go lhs && go rhs
Constant.Or lhs rhs -> go lhs && go rhs
Constant.Xor lhs rhs -> go lhs && go rhs
Constant.Select _ lhs rhs -> go lhs && go rhs
Constant.Trunc _ typ -> typ == rep
Constant.ZExt _ typ -> typ == rep
Constant.SExt _ typ -> typ == rep
Constant.FPToUI _ typ -> typ == rep
Constant.FPToSI _ typ -> typ == rep
Constant.UIToFP _ typ -> typ == rep
Constant.SIToFP _ typ -> typ == rep
Constant.FPTrunc _ typ -> typ == rep
Constant.FPExt _ typ -> typ == rep
Constant.PtrToInt _ typ -> typ == rep
Constant.IntToPtr _ typ -> typ == rep
Constant.BitCast _ typ -> typ == rep
Constant.ICmp{} -> valueType (Proxy :: Proxy Bool) == rep
Constant.FCmp{} -> valueType (Proxy :: Proxy Bool) == rep
_ -> False
instance OperandWrap Constant.Constant where
type OperandConstness Constant.Constant = 'Constant
operandWrap :: forall a. ValueOf a => Constant.Constant -> Maybe (Value 'Constant a)
operandWrap op = do
let rep = valueType (Proxy :: Proxy a)
guard $ constantMatch rep op
return $ ValueConstant op
functionWrap
:: forall a cc . (KnownNat cc, FunctionType (ArgumentList a))
=> AST.Global
-> Maybe (Function ('CallingConv cc) a)
functionWrap AST.Function{..} = do
let callingConvention' = reifyCallingConv (Proxy :: Proxy ('CallingConv cc))
guard (callingConvention == callingConvention')
(ty', rty) <- splitFunctionTypes $ functionType (Proxy :: Proxy (ArgumentList a))
guard $ returnType == rty
let pty = [ty | AST.Parameter ty _ _ <- fst parameters]
fty = Type.FunctionType returnType pty (snd parameters)
guard $ pty == ty'
return $ Function (ValueConstant (Constant.GlobalReference fty name)) callingConvention'
functionWrap _ = Nothing
|
5c5201761de5bce646d7b6cf5d58fae1ddfde87774f35f84370ddfe35cc599d1 | GillianPlatform/Gillian | GInterpreter.ml | open Literal
open BranchCase
module L = Logging
module DL = Debugger_log
open Syntaxes.Result
type branch_case = BranchCase.t [@@deriving yojson]
module type S = sig
module CallStack : CallStack.S
type vt
type st
type store_t
type state_t
type state_err_t [@@deriving show]
type state_vt [@@deriving yojson, show]
type heap_t
type init_data
type annot
module Val : Val.S with type t = vt
module Store : Store.S with type t = store_t and type vt = vt
type invariant_frames = (string * state_t) list
type err_t = (vt, state_err_t) ExecErr.t [@@deriving show, yojson]
type branch_path = branch_case list [@@deriving yojson]
type cconf_t =
| ConfErr of {
callstack : CallStack.t;
proc_idx : int;
error_state : state_t;
errors : err_t list;
branch_path : branch_path;
}
| ConfCont of {
state : state_t;
callstack : CallStack.t;
invariant_frames : invariant_frames;
prev_idx : int;
next_idx : int;
loop_ids : string list;
branch_count : int;
prev_cmd_report_id : L.Report_id.t option;
branch_case : branch_case option;
branch_path : branch_path;
new_branches : (state_t * int * branch_case) list;
}
| ConfFinish of {
flag : Flag.t;
ret_val : state_vt;
final_state : state_t;
branch_path : branch_path;
} (** Equal to Conf cont + the id of the required spec *)
| ConfSusp of {
spec_id : string;
state : state_t;
callstack : CallStack.t;
invariant_frames : invariant_frames;
prev_idx : int;
next_idx : int;
loop_ids : string list;
branch_count : int;
branch_path : branch_path;
}
type conf_t = BConfErr of err_t list | BConfCont of state_t
type result_t = (state_t, state_vt, err_t) ExecRes.t
type 'a cont_func_f = ?path:branch_path -> unit -> 'a cont_func
and 'a cont_func =
| Finished of 'a list
| Continue of
(Logging.Report_id.t option
* branch_path
* branch_case list option
* 'a cont_func_f)
| EndOfBranch of 'a * 'a cont_func_f
module Logging : sig
module ConfigReport : sig
type t = {
proc_line : int;
time : float;
cmd : int Cmd.t;
callstack : CallStack.t;
annot : annot;
branching : int;
state : state_t;
branch_case : branch_case option;
}
[@@deriving yojson]
end
module CmdResult : sig
type t = {
callstack : CallStack.t;
proc_body_index : int;
state : state_t option;
errors : err_t list;
branch_case : branch_case option;
}
[@@deriving yojson]
end
val pp_err : Format.formatter -> (vt, state_err_t) ExecErr.t -> unit
val pp_result : Format.formatter -> result_t list -> unit
end
val call_graph : CallGraph.t
val reset : unit -> unit
val evaluate_lcmds :
annot UP.prog ->
LCmd.t list ->
state_t ->
(state_t list, state_err_t list) result
val init_evaluate_proc :
(result_t -> 'a) ->
annot UP.prog ->
string ->
string list ->
state_t ->
'a cont_func
val evaluate_proc :
(result_t -> 'a) ->
annot UP.prog ->
string ->
string list ->
state_t ->
'a list
end
(** General GIL Interpreter *)
module Make
(Val : Val.S)
(ESubst : ESubst.S with type vt = Val.t and type t = Val.et)
(Store : Store.S with type vt = Val.t)
(State : State.S
with type vt = Val.t
and type st = ESubst.t
and type store_t = Store.t)
(PC : ParserAndCompiler.S)
(External : External.T(PC.Annot).S) =
struct
(* *************** *
* Auxiliary Types *
* *************** *)
module CallStack = CallStack.Make (Val) (Store)
module External = External (Val) (ESubst) (Store) (State) (CallStack)
module Val = Val
module State = State
module Store = Store
module Annot = PC.Annot
type vt = Val.t
type st = ESubst.t
type store_t = Store.t
type state_t = State.t [@@deriving yojson]
type state_err_t = State.err_t [@@deriving yojson]
type init_data = State.init_data
type annot = Annot.t [@@deriving yojson]
let pp_state_err_t = State.pp_err
let show_state_err_t = Fmt.to_to_string pp_state_err_t
type state_vt = State.vt [@@deriving yojson, show]
type heap_t = State.heap_t
type invariant_frames = (string * State.t) list [@@deriving yojson]
type err_t = (Val.t, state_err_t) ExecErr.t [@@deriving show, yojson]
type branch_path = branch_case list [@@deriving yojson]
(** Type of configurations: state, call stack, previous index, previous loop ids, current index, branching *)
type cconf_t =
| ConfErr of {
callstack : CallStack.t;
proc_idx : int;
error_state : state_t;
errors : err_t list;
branch_path : branch_path;
}
| ConfCont of {
state : State.t;
callstack : CallStack.t;
invariant_frames : invariant_frames;
prev_idx : int;
next_idx : int;
loop_ids : string list;
branch_count : int;
prev_cmd_report_id : L.Report_id.t option;
branch_case : branch_case option;
branch_path : branch_path;
new_branches : (state_t * int * branch_case) list;
}
| ConfFinish of {
flag : Flag.t;
ret_val : State.vt;
final_state : State.t;
branch_path : branch_path;
} (** Equal to Conf cont + the id of the required spec *)
| ConfSusp of {
spec_id : string;
state : state_t;
callstack : CallStack.t;
invariant_frames : invariant_frames;
prev_idx : int;
next_idx : int;
loop_ids : string list;
branch_count : int;
branch_path : branch_path;
}
[@@deriving yojson]
let make_confcont
~state
~callstack
~invariant_frames
~prev_idx
~next_idx
~loop_ids
~branch_count
~branch_path
?prev_cmd_report_id
?branch_case
?(new_branches = [])
() =
(* We only want to track branches for the base function. *)
let branch_case, new_branches =
if List.length callstack > 1 then (None, [])
else (branch_case, new_branches)
in
ConfCont
{
state;
callstack;
invariant_frames;
prev_idx;
next_idx;
loop_ids;
branch_count;
branch_path;
prev_cmd_report_id;
branch_case;
new_branches;
}
let cconf_path = function
| ConfErr { branch_path; _ } -> branch_path
| ConfFinish { branch_path; _ } -> branch_path
| ConfSusp { branch_path; _ } -> branch_path
| ConfCont { branch_path; branch_case; _ } ->
List_utils.cons_opt branch_case branch_path
type conf_t = BConfErr of err_t list | BConfCont of State.t
type result_t = (State.t, State.vt, err_t) ExecRes.t [@@deriving yojson]
type 'a cont_func_f = ?path:branch_path -> unit -> 'a cont_func
and 'a cont_func =
| Finished of 'a list
| Continue of
(Logging.Report_id.t option
* branch_path
* branch_case list option
* 'a cont_func_f)
| EndOfBranch of 'a * 'a cont_func_f
module Logging = struct
let pp_str_list = Fmt.(brackets (list ~sep:comma string))
module ConfigReport = struct
type t = {
proc_line : int;
time : float;
cmd : int Cmd.t;
callstack : CallStack.t;
annot : annot;
branching : int;
state : state_t;
branch_case : branch_case option;
}
[@@deriving yojson, make]
let pp
state_printer
fmt
{
proc_line = i;
time;
cmd;
callstack = cs;
annot;
branching;
state;
_;
} =
Fmt.pf fmt
"@[------------------------------------------------------@\n\
--%s: %i--@\n\
TIME: %f@\n\
CMD: %a@\n\
PROCS: %a@\n\
LOOPS: %a ++ %a@\n\
BRANCHING: %d@\n\
@\n\
%a@\n\
------------------------------------------------------@]\n"
(CallStack.get_cur_proc_id cs)
i time Cmd.pp_indexed cmd pp_str_list
(CallStack.get_cur_procs cs)
pp_str_list
(Annot.get_loop_info annot)
pp_str_list
(CallStack.get_loop_ids cs)
branching state_printer state
let to_loggable state_printer =
L.Loggable.make (pp state_printer) of_yojson to_yojson
let log state_printer report =
L.Specific.normal
(to_loggable state_printer report)
L.Logging_constants.Content_type.cmd
end
module CmdResult = struct
type t = {
callstack : CallStack.t;
proc_body_index : int;
state : state_t option;
errors : err_t list;
branch_case : branch_case option;
}
[@@deriving yojson]
let pp fmt cmd_step =
(* TODO: Cmd step should contain all things in a configuration
print the same contents as log_configuration *)
CallStack.pp fmt cmd_step.callstack
let to_loggable = L.Loggable.make pp of_yojson to_yojson
let log type_ report = L.Specific.normal (to_loggable report) type_
open L.Logging_constants.Content_type
let log_result = log cmd_result
let log_init = log proc_init
end
module AnnotatedAction = struct
type t = { annot : Annot.t; action_name : string } [@@deriving yojson]
let pp fmt annotated_action =
let origin_loc = Annot.get_origin_loc annotated_action.annot in
Fmt.pf fmt "Executing action '%s' at %a" annotated_action.action_name
(Fmt.option ~none:(Fmt.any "none") Location.pp)
origin_loc
let to_loggable = L.Loggable.make pp of_yojson to_yojson
let log report =
L.Specific.normal (to_loggable report)
L.Logging_constants.Content_type.annotated_action
end
let log_configuration
(cmd : Annot.t * int Cmd.t)
(state : State.t)
(cs : CallStack.t)
(i : int)
(b_counter : int)
(branch_case : branch_case option) : L.Report_id.t option =
let annot, cmd = cmd in
let state_printer =
match !Config.pbn with
| false -> State.pp
| true ->
let pvars, lvars, locs =
(Cmd.pvars cmd, Cmd.lvars cmd, Cmd.locs cmd)
in
State.pp_by_need pvars lvars locs
in
ConfigReport.log state_printer
(ConfigReport.make ~proc_line:i ~time:(Sys.time ()) ~cmd ~callstack:cs
~annot ~branching:b_counter ~state ?branch_case ())
let print_lconfiguration (lcmd : LCmd.t) (state : State.t) : unit =
L.normal (fun m ->
m
"@[------------------------------------------------------@\n\
TIME: %f@\n\
LCMD: %a@\n\
@\n\
%a@\n\
------------------------------------------------------@]@\n"
(Sys.time ()) LCmd.pp lcmd State.pp state)
let pp_err = ExecErr.pp Val.pp State.pp_err
let pp_single_result ft res = ExecRes.pp State.pp Val.pp pp_err ft res
(** Configuration pretty-printer *)
let pp_result (ft : Format.formatter) (reslt : result_t list) : unit =
let open Fmt in
let pp_one ft (i, res) =
pf ft "RESULT: %d.@\n%a" i pp_single_result res
in
(iter_bindings List.iteri pp_one) ft reslt
end
open Logging
let max_branching = 100
exception Interpreter_error of err_t list * State.t
(** Internal error, carrying a string description *)
exception Internal_error of string
(** Syntax error, carrying a string description *)
exception Syntax_error of string
let call_graph = CallGraph.make ~init_capacity:128 ()
let reset () = CallGraph.reset call_graph
(* Often-used values *)
let vtrue = Val.from_literal (Bool true)
let vfalse = Val.from_literal (Bool false)
let symb_exec_next = ref false
type loop_action =
| Nothing
| FrameOff of string
| FrameOn of string list
| Malformed
let understand_loop_action current previous : loop_action =
match current = previous with
(* No change in loop structure *)
| true -> Nothing
(* Change in loop structure *)
| false -> (
let len_cur = List.length current in
let len_prev = List.length previous in
match len_cur - len_prev with
(* We have entered a new loop *)
| 1 ->
if List.tl current <> previous then Malformed
else FrameOff (List.hd current)
We have entered more than one loop - this is not allowed
| n when n > 0 -> Malformed
We have exited at least one loop
| n ->
let ids = Option.get (List_utils.list_sub previous 0 (-n)) in
let rest =
Option.get (List_utils.list_sub previous (-n) (len_prev + n))
in
if rest <> current then Malformed else FrameOn ids)
(* ******************* *
* Auxiliary Functions *
* ******************* *)
let get_cmd (prog : annot UP.prog) (cs : CallStack.t) (i : int) :
string * (Annot.t * int Cmd.t) =
let pid = CallStack.get_cur_proc_id cs in
let proc = Prog.get_proc prog.prog pid in
let proc =
match proc with
| Some proc -> proc
| None -> raise (Failure ("Procedure " ^ pid ^ " does not exist."))
in
let annot, _, cmd = proc.proc_body.(i) in
(pid, (annot, cmd))
let get_predecessor
(prog : annot UP.prog)
(cs : CallStack.t)
(prev : int)
(i : int) : int =
let pid = CallStack.get_cur_proc_id cs in
try Hashtbl.find prog.prog.predecessors (pid, prev, i)
with _ ->
raise
(Failure (Printf.sprintf "Undefined predecessor: %s %d %d" pid prev i))
let update_store (state : State.t) (x : string) (v : Val.t) : State.t =
let store = State.get_store state in
let () = Store.put store x v in
let state' = State.set_store state store in
state'
let eval_subst_list
(state : State.t)
(subst_lst : (string * (string * Expr.t) list) option) :
(string * (string * Val.t) list) option =
match subst_lst with
| None -> None
| Some (lab, subst_lst) ->
let subst_lst' : (string * Val.t) list =
List.map (fun (x, e) -> (x, State.eval_expr state e)) subst_lst
in
Some (lab, subst_lst')
let make_eval_expr (state : State.t) : Expr.t -> Val.t =
fun e ->
try State.eval_expr state e
with State.Internal_State_Error (errs, s) ->
raise (Interpreter_error (List.map (fun x -> ExecErr.ESt x) errs, s))
let check_loop_ids actual expected =
match actual = expected with
| false ->
Fmt.failwith
"Malformed loop structure: current loops: %a; expected loops: %a"
pp_str_list actual pp_str_list expected
| true -> ()
let rec loop_ids_to_frame_on_at_the_end end_ids start_ids =
if end_ids = start_ids then []
else
match end_ids with
| [] ->
Fmt.failwith
"Malformed loop structure (at return): current loops: %a; expected \
loops: %a"
pp_str_list end_ids pp_str_list start_ids
| x :: r -> x :: loop_ids_to_frame_on_at_the_end r start_ids
(* ************** *
* Main Functions *
* ************** *)
*
Evaluation of logic commands
@param prog GIL program
@param lcmd Logic command to be evaluated
@param state Current state
@param Current predicate set
@return List of states / predicate sets resulting from the evaluation
Evaluation of logic commands
@param prog GIL program
@param lcmd Logic command to be evaluated
@param state Current state
@param preds Current predicate set
@return List of states/predicate sets resulting from the evaluation
*)
let rec evaluate_lcmd (prog : annot UP.prog) (lcmd : LCmd.t) (state : State.t)
: (State.t list, state_err_t list) result =
print_lconfiguration lcmd state;
let eval_expr = make_eval_expr state in
match lcmd with
| AssumeType (e, t) -> (
let v_x = eval_expr e in
match State.assume_t state v_x t with
| Some state' -> Ok [ state' ]
| _ ->
Fmt.failwith
"ERROR: AssumeType: Cannot assume type %s for expression %a."
(Type.str t) Expr.pp e)
| Assume f ->
let store_subst = Store.to_ssubst (State.get_store state) in
let f' = SVal.SESubst.substitute_formula store_subst ~partial:true f in
Printf.printf " Assuming % s\n " ( Formula.str f ' ) ;
let fos =
if Exec_mode.biabduction_exec !Config.current_exec_mode then
let fos = Formula.get_disjuncts f' in
match fos with
| [] -> []
| [ f' ] -> [ (f', state) ]
| f' :: other_fos ->
let new_fos_states =
List.map (fun f'' -> (f'', State.copy state)) other_fos
in
(f', state) :: new_fos_states
else [ (f', state) ]
in
(* Printf.printf "Considering the following disjuncts: %s\n" *)
(* I commented the following, because it builds a string and discards it ? *)
( String.concat " ; " ( List.map ( fun ( f , _ ) - > Formula.str f ) fos ) ) ;
Ok
(List.concat
(List.map
(fun (f'', state) ->
match State.assume_a state [ f'' ] with
| Some state' -> [ state' ]
| _ -> [])
fos))
| FreshSVar x ->
let new_svar = Generators.fresh_svar () in
let state' = State.add_spec_vars state (SS.singleton new_svar) in
let v = Val.from_expr (LVar new_svar) |> Option.get in
Ok [ update_store state' x v ]
| Assert f -> (
let store_subst = Store.to_ssubst (State.get_store state) in
let f' = SVal.SESubst.substitute_formula store_subst ~partial:true f in
match State.assert_a state [ f' ] with
| true -> Ok [ state ]
| false ->
let err = StateErr.EPure f' in
let failing_model = State.sat_check_f state [ Not f' ] in
let msg =
Fmt.str
"Assert failed with argument @[<h>%a@].@\n\
@[<v 2>Failing Model:@\n\
%a@]@\n"
Formula.pp f'
Fmt.(option ~none:(any "CANNOT CREATE MODEL") ESubst.pp)
failing_model
in
if not (Exec_mode.biabduction_exec !Config.current_exec_mode) then
Printf.printf "%s" msg;
L.normal (fun m -> m "%s" msg);
raise (Interpreter_error ([ ESt err ], state)))
| Macro (name, args) -> (
let macro = Macro.get prog.prog.macros name in
match macro with
| None ->
L.verbose (fun m ->
m "@[<v 2>Current MACRO TABLE:\n%a\n@]" Macro.pp_tbl
prog.prog.macros);
raise
(Failure
(Fmt.str "NO MACRO found when executing: @[<h>%a@]" LCmd.pp
lcmd))
| Some macro ->
let expand_macro (macro : Macro.t) (args : Expr.t list) :
LCmd.t list =
let params = macro.macro_params in
let params_card = List.length params in
let args_card = List.length args in
if params_card <> args_card then
raise
(Failure
(Printf.sprintf
"Macro %s called with incorrect number of parameters: \
%d instead of %d."
macro.macro_name args_card params_card));
let subst = SVal.SSubst.init (List.combine params args) in
let lcmds = macro.macro_definition in
List.map (SVal.SSubst.substitute_lcmd subst ~partial:true) lcmds
in
let lcmds = expand_macro macro args in
evaluate_lcmds prog lcmds state)
(* We have to understand what is the intended semantics of the logic if *)
| If (e, lcmds_t, lcmds_e) -> (
let ve = eval_expr e in
let e = Val.to_expr ve in
match Formula.lift_logic_expr e with
| Some (True, False) -> evaluate_lcmds prog lcmds_t state
| Some (False, True) -> evaluate_lcmds prog lcmds_e state
| Some (foe, nfoe) ->
let state' = State.copy state in
let* then_states =
State.assume_a state [ foe ]
|> Option.fold
~some:(fun state -> evaluate_lcmds prog lcmds_t state)
~none:(Ok [])
in
let+ else_states =
State.assume_a state' [ nfoe ]
|> Option.fold
~some:(fun state -> evaluate_lcmds prog lcmds_e state)
~none:(Ok [])
in
then_states @ else_states
| None ->
raise
(Failure
"Non-boolean expression in the condition of the logical if"))
| Branch fof ->
let state' = State.copy state in
let state =
Option.fold
~some:(fun x -> [ x ])
~none:[]
(State.assume_a state [ fof ])
in
let state' =
Option.fold
~some:(fun x -> [ x ])
~none:[]
(State.assume_a state' [ Not fof ])
in
Ok (state @ state')
| SL sl_cmd -> State.evaluate_slcmd prog sl_cmd state
and evaluate_lcmds
(prog : annot UP.prog)
(lcmds : LCmd.t list)
(state : State.t) : (State.t list, state_err_t list) result =
match lcmds with
| [] -> Ok [ state ]
| lcmd :: rest_lcmds ->
let* rets = evaluate_lcmd prog lcmd state in
let+ next_rets =
rets
|> List_utils.map_results (fun state ->
evaluate_lcmds prog rest_lcmds state)
in
List.concat next_rets
*
Evaluation of commands
@param prog GIL program
@param state Current state
@param Current predicate set
@param cs Current call stack
@param prev Previous index
@param i Current index
@return List of configurations resulting from the evaluation
Evaluation of commands
@param prog GIL program
@param state Current state
@param preds Current predicate set
@param cs Current call stack
@param prev Previous index
@param i Current index
@return List of configurations resulting from the evaluation
*)
let rec evaluate_cmd
(prog : annot UP.prog)
(state : State.t)
(cs : CallStack.t)
(iframes : invariant_frames)
(prev : int)
(prev_loop_ids : string list)
(i : int)
(b_counter : int)
(report_id_ref : L.Report_id.t option ref)
(branch_path : branch_path)
(branch_case : branch_case option) : cconf_t list =
let _, (annot, _) = get_cmd prog cs i in
(* The full list of loop ids is the concatenation
of the loop ids of the current procedure plus
the loop ids that have come from the call stack *)
let loop_ids = Annot.get_loop_info annot @ CallStack.get_loop_ids cs in
let loop_action : loop_action =
if Exec_mode.verification_exec !Config.current_exec_mode then
understand_loop_action loop_ids prev_loop_ids
else Nothing
in
let eval_in_state state =
evaluate_cmd_after_frame_handling prog state cs iframes prev prev_loop_ids
i b_counter report_id_ref branch_path branch_case
in
match loop_action with
| Nothing -> eval_in_state state
| FrameOff id ->
L.verbose (fun fmt -> fmt "INFO: Expecting to frame off %s" id);
eval_in_state state
| Malformed -> L.fail "Malformed loop identifiers"
| FrameOn ids ->
L.verbose (fun fmt -> fmt "INFO: Going to frame on %a" pp_str_list ids);
let states = State.frame_on state iframes ids in
let n = List.length states in
if n == 0 then
L.normal (fun fmt -> fmt "WARNING: FRAMING ON RESULTED IN 0 STATES !")
else if n > 1 then
L.verbose (fun fmt ->
fmt
"WARNING: FRAMING ON AFTER EXITING LOOP BRANCHED INTO %i STATES"
n);
List.concat_map eval_in_state states
and evaluate_cmd_after_frame_handling
(prog : annot UP.prog)
(state : State.t)
(cs : CallStack.t)
(iframes : invariant_frames)
(prev : int)
(prev_loop_ids : string list)
(i : int)
(b_counter : int)
(report_id_ref : L.Report_id.t option ref)
(branch_path : branch_path)
(branch_case : branch_case option) : cconf_t list =
let store = State.get_store state in
let eval_expr = make_eval_expr state in
let proc_name, annot_cmd = get_cmd prog cs i in
let annot, cmd = annot_cmd in
let loop_ids = Annot.get_loop_info annot @ CallStack.get_loop_ids cs in
let loop_action : loop_action =
if Exec_mode.verification_exec !Config.current_exec_mode then
understand_loop_action loop_ids prev_loop_ids
else Nothing
in
if ! then Statistics.exec_cmds : = ! Statistics.exec_cmds + 1 ;
UP.update_coverage prog proc_name i;
log_configuration annot_cmd state cs i b_counter branch_case
|> Option.iter (fun report_id ->
report_id_ref := Some report_id;
L.Parent.set report_id);
let branch_path = List_utils.cons_opt branch_case branch_path in
let make_confcont =
make_confcont ?prev_cmd_report_id:!report_id_ref ~branch_path
in
DL.log (fun m ->
m
~json:[ ("path", branch_path_to_yojson branch_path) ]
"GInterpreter: stepping with path");
let evaluate_procedure_call x pid v_args j subst =
let pid =
match Val.to_literal pid with
| Some (String pid) -> pid
| Some _ ->
let err = [ ExecErr.EProc pid ] in
raise (Interpreter_error (err, state))
| None ->
raise
(Internal_error
"Procedure Call Error - unlifting procedure ID failed")
in
let proc = Prog.get_proc prog.prog pid in
let spec = Hashtbl.find_opt prog.specs pid in
let params =
match (proc, spec) with
| Some proc, _ -> Proc.get_params proc
| None, Some spec -> Spec.get_params spec.spec
| _ ->
raise
(Interpreter_error
([ EProc (Val.from_literal (String pid)) ], state))
in
let caller = CallStack.get_cur_proc_id cs in
let () = CallGraph.add_proc_call call_graph caller pid in
let prmlen = List.length params in
let args = Array.make prmlen (Val.from_literal Undefined) in
let () =
List.iteri (fun i v_arg -> if i < prmlen then args.(i) <- v_arg) v_args
in
let args = Array.to_list args in
let process_ret is_first ret_state fl b_counter others : cconf_t =
let new_cs =
match is_first with
| true -> CallStack.copy cs
| false -> cs
in
let new_j =
match (fl, j) with
| Flag.Normal, _ -> i + 1
| Flag.Error, Some j -> j
| Flag.Error, None ->
let msg =
Printf.sprintf
"SYNTAX ERROR: No error label provided when calling \
procedure %s"
pid
in
L.normal (fun fmt -> fmt "%s" msg);
raise (Syntax_error msg)
in
let branch_case = SpecExec fl in
let branch_case, new_branches =
match (is_first, others) with
| _, Some (_ :: _ as others) ->
let new_branches =
Some
(List_utils.get_list_somes
@@ List.map
(fun conf ->
match conf with
| ConfCont { state; next_idx; _ } ->
Some (state, next_idx, branch_case)
| _ -> None)
others)
in
(Some branch_case, new_branches)
| false, _ -> (Some branch_case, None)
| _ -> (None, None)
in
make_confcont ~state:ret_state ~callstack:new_cs
~invariant_frames:iframes ~prev_idx:i ~loop_ids ~next_idx:new_j
~branch_count:b_counter ?branch_case ?new_branches ()
in
let is_internal_proc proc_name =
(Prog.get_proc_exn prog.prog proc_name).proc_internal
in
let symb_exec_proc () =
let new_store = Store.init (List.combine params args) in
let old_store = State.get_store state in
let state' = State.set_store state new_store in
let cs' =
(* Note the new loop identifiers *)
CallStack.push cs ~pid ~arguments:v_args ~store:old_store ~loop_ids
~ret_var:x ~call_index:i ~continue_index:(i + 1) ?error_index:j ()
in
[
make_confcont ~state:state' ~callstack:cs' ~invariant_frames:iframes
~prev_idx:(-1) ~loop_ids ~next_idx:0 ~branch_count:b_counter ();
]
in
let spec_exec_proc () =
match spec with
| Some spec -> (
match !symb_exec_next with
| true ->
symb_exec_next := false;
symb_exec_proc ()
| false -> (
let subst = eval_subst_list state subst in
L.verbose (fun fmt -> fmt "ABOUT TO USE THE SPEC OF %s" pid);
(* print_to_all ("\tStarting run spec: " ^ pid); *)
let rets : ((State.t * Flag.t) list, state_err_t list) result =
State.run_spec spec state x args subst
in
match rets with
| Ok rets -> (
(* print_to_all ("\tFinished run spec: " ^ pid); *)
L.verbose (fun fmt ->
fmt "Run_spec returned %d Results" (List.length rets));
let b_counter =
if List.length rets > 1 then b_counter + 1 else b_counter
in
match rets with
| (ret_state, fl) :: rest_rets ->
let others =
List.map
(fun (ret_state, fl) ->
process_ret false ret_state fl b_counter None)
rest_rets
in
process_ret true ret_state fl b_counter (Some others)
:: others
(* Run spec returned no results *)
| _ -> (
match spec.spec.spec_incomplete with
| true ->
L.normal (fun fmt ->
fmt "Proceeding with symbolic execution.");
symb_exec_proc ()
| false ->
L.fail
(Format.asprintf
"ERROR: Unable to use specification of \
function %s"
spec.spec.spec_name)))
| Error errors ->
let errors = errors |> List.map (fun e -> ExecErr.ESt e) in
[
ConfErr
{
callstack = cs;
proc_idx = i;
error_state = state;
errors;
branch_path;
};
]))
| None ->
if Hashtbl.mem prog.prog.bi_specs pid then
[
ConfSusp
{
spec_id = pid;
state;
callstack = cs;
invariant_frames = iframes;
prev_idx = prev;
loop_ids = prev_loop_ids;
next_idx = i;
branch_path;
branch_count = b_counter;
};
]
else symb_exec_proc ()
in
match Exec_mode.biabduction_exec !Config.current_exec_mode with
| true -> (
match
( pid = caller,
is_internal_proc pid,
CallStack.recursive_depth cs pid >= !Config.bi_unroll_depth )
with
(* In bi-abduction, reached max depth of recursive calls *)
| _, _, true -> []
(* In bi-abduction, recursive call *)
| true, false, _ -> symb_exec_proc ()
TODO : When JS internals work
| true , false , false
when
( List.filter is_internal_proc ( CallStack.get_cur_procs cs ) )
< ! Config.bi_no_spec_depth - > symb_exec_proc ( )
| true, false, false
when List.length
(List.filter is_internal_proc (CallStack.get_cur_procs cs))
< !Config.bi_no_spec_depth -> symb_exec_proc () *)
| _ -> spec_exec_proc ())
| false -> spec_exec_proc ()
in
match cmd with
(* Skip *)
| Skip ->
[
make_confcont ~state ~callstack:cs ~invariant_frames:iframes
~prev_idx:i ~loop_ids ~next_idx:(i + 1) ~branch_count:b_counter ();
]
(* Assignment *)
| Assignment (x, e) ->
DL.log (fun m ->
m
~json:[ ("target", `String x); ("expr", Expr.to_yojson e) ]
"Assignment");
let v = eval_expr e in
let state' = update_store state x v in
[
make_confcont ~state:state' ~callstack:cs ~invariant_frames:iframes
~prev_idx:i ~loop_ids ~next_idx:(i + 1) ~branch_count:b_counter ();
]
(* Action *)
| LAction (x, a, es) -> (
DL.log (fun m ->
m
~json:
[
("x", `String x);
("a", `String a);
("es", `List (List.map Expr.to_yojson es));
]
"LAction");
AnnotatedAction.log { annot; action_name = a } |> ignore;
let v_es = List.map eval_expr es in
match State.execute_action a state v_es with
| Ok [] -> failwith "HORROR: Successful action resulted in no states"
| Ok ((state', vs) :: rest_rets) -> (
DL.log (fun m ->
m
~json:
[
("state'", state_t_to_yojson state');
("vs", `List (List.map state_vt_to_yojson vs));
]
"Ok");
let e' = Expr.EList (List.map Val.to_expr vs) in
let v' = eval_expr e' in
let state'' = update_store state' x v' in
let rest_confs, new_branches =
List.split
@@ List.map
(fun (r_state, r_vs) ->
let r_e = Expr.EList (List.map Val.to_expr r_vs) in
let r_v = eval_expr r_e in
let r_state' = update_store r_state x r_v in
let branch_case =
LAction (r_vs |> List.map state_vt_to_yojson)
in
( make_confcont ~state:r_state'
~callstack:(CallStack.copy cs)
~invariant_frames:iframes ~prev_idx:i ~loop_ids
~next_idx:(i + 1) ~branch_count:b_counter ~branch_case
(),
(r_state', i + 1, branch_case) ))
rest_rets
in
let ret_len = 1 + List.length rest_rets in
let b_counter = b_counter + if ret_len > 1 then 1 else 0 in
let branch_case = LAction (vs |> List.map state_vt_to_yojson) in
match
(ret_len >= 3 && !Config.parallel, ret_len = 2 && !Config.parallel)
(* XXX: && !Config.act_threads < !Config.max_threads ) *)
with
| true, _ -> (
print_endline ( Printf.sprintf " Action returned > =3 : % d " ( ! Config.act_threads + 2 ) ) ;
let pid = Unix.fork () in
match pid with
| 0 -> (
let pid = Unix.fork () in
match pid with
| 0 -> List.tl rest_confs
| _ -> [ List.hd rest_confs ])
| _ ->
[
make_confcont ~state:state'' ~callstack:cs
~invariant_frames:iframes ~prev_idx:i ~loop_ids
~next_idx:(i + 1) ~branch_count:b_counter ~branch_case
~new_branches ();
])
| false, true -> (
Can split into two threads
let b_counter = b_counter + 1 in
print_endline ( Printf.sprintf " Action returned 2 : % d " ( ! Config.act_threads + 1 ) ) ;
let pid = Unix.fork () in
match pid with
| 0 ->
[
make_confcont ~state:state'' ~callstack:cs
~invariant_frames:iframes ~prev_idx:i ~loop_ids
~next_idx:(i + 1) ~branch_count:b_counter ~branch_case
~new_branches ();
]
| _ -> rest_confs)
| _ ->
make_confcont ~state:state'' ~callstack:cs
~invariant_frames:iframes ~prev_idx:i ~loop_ids
~next_idx:(i + 1) ~branch_count:b_counter ()
:: rest_confs)
| Error errs ->
DL.log (fun m ->
m
~json:
[ ("errs", `List (List.map state_err_t_to_yojson errs)) ]
"Error");
if not (Exec_mode.concrete_exec !Config.current_exec_mode) then (
let expr_params = List.map Val.to_expr v_es in
let recovery_params =
List.concat_map Expr.base_elements expr_params
in
let recovery_params =
List.map Option.get (List.map Val.from_expr recovery_params)
in
let recovery_vals =
State.get_recovery_vals state errs @ recovery_params
in
let recovery_states : (State.t list, string) result =
State.automatic_unfold state recovery_vals
in
match recovery_states with
| Ok recovery_states ->
let b_counter =
b_counter + if List.length recovery_states = 1 then 0 else 1
in
List.mapi
(fun ix state ->
let branch_case =
if List.length recovery_states > 1 then
Some (LActionFail ix)
else None
in
let new_branches =
match (ix, recovery_states) with
| 0, _ :: rest ->
Some
(List.mapi
(fun ix state ->
(state, i, LActionFail (ix + 1)))
rest)
| _ -> None
in
make_confcont ~state ~callstack:cs
~invariant_frames:iframes ~prev_idx:prev
~loop_ids:prev_loop_ids ~next_idx:i
~branch_count:b_counter ?branch_case ?new_branches ())
recovery_states
| _ ->
let pp_err ft (a, errs) =
Fmt.pf ft "FAILURE: Action %s failed with: %a" a
(Fmt.Dump.list State.pp_err)
errs
in
Fmt.pr "%a\n@?" (Fmt.styled `Red pp_err) (a, errs);
L.normal ~title:"failure" ~severity:Error (fun m ->
m "Action call failed with:@.%a"
(Fmt.Dump.list State.pp_err)
errs);
raise (State.Internal_State_Error (errs, state)))
else
let pp_err ft (a, errs) =
Fmt.pf ft "FAILURE: Action %s failed with: %a" a
(Fmt.Dump.list State.pp_err)
errs
in
Fmt.failwith "%a\n@?" (Fmt.styled `Red pp_err) (a, errs))
Logic command
| Logic lcmd -> (
DL.log (fun m -> m "LCmd");
match lcmd with
| SL SymbExec ->
symb_exec_next := true;
[
make_confcont ~state ~callstack:cs ~invariant_frames:iframes
~prev_idx:i ~loop_ids ~next_idx:(i + 1) ~branch_count:b_counter
();
]
(* Invariant being revisited *)
| SL (Invariant (a, binders)) when prev_loop_ids = loop_ids ->
let ( ) = Fmt.pr " - establishing invariant ... @ ? " in
let _ = State.unify_invariant prog true state a binders in
let () = L.verbose (fun fmt -> fmt "Invariant re-established.") in
let ( ) = Fmt.pr " \nInvariant re - established . @ ? " in
[]
| SL (Invariant (a, binders)) ->
assert (loop_action = FrameOff (List.hd loop_ids));
let ( ) = Fmt.pr " \nEstablishing invariant ... @ ? " in
let frames_and_states : (State.t * State.t) list =
State.unify_invariant prog false state a binders
in
let ( ) = Fmt.pr " established invariant . @ ? " in
List.map
(fun (frame, state) ->
let iframes = (List.hd loop_ids, frame) :: iframes in
make_confcont ~state ~callstack:cs ~invariant_frames:iframes
~prev_idx:i ~loop_ids ~next_idx:(i + 1)
~branch_count:b_counter ())
frames_and_states
| _ -> (
match evaluate_lcmd prog lcmd state with
| Ok resulting_states ->
let b_counter =
if List.length resulting_states > 1 then b_counter + 1
else b_counter
in
resulting_states
|> List.mapi (fun ix state ->
let branch_case =
if List.length resulting_states > 1 then Some (LCmd ix)
else None
in
let new_branches =
match (ix, resulting_states) with
| 0, _ :: rest ->
Some
(List.mapi
(fun ix state -> (state, i, LCmd (ix + 1)))
rest)
| _ -> None
in
make_confcont ~state ~callstack:cs
~invariant_frames:iframes ~prev_idx:i ~loop_ids
~next_idx:(i + 1) ~branch_count:b_counter ?branch_case
?new_branches ())
| Error errors ->
let errors = errors |> List.map (fun e -> ExecErr.ESt e) in
[
ConfErr
{
callstack = cs;
proc_idx = i;
error_state = state;
errors;
branch_path;
};
]))
(* Unconditional goto *)
| Goto j ->
[
make_confcont ~state ~callstack:cs ~invariant_frames:iframes
~prev_idx:i ~loop_ids ~next_idx:j ~branch_count:b_counter ();
]
(* Conditional goto *)
| GuardedGoto (e, j, k) -> (
let vt = eval_expr e in
let lvt = Val.to_literal vt in
let vf =
match lvt with
| Some (Bool true) -> vfalse
| Some (Bool false) -> vtrue
| _ -> eval_expr (UnOp (UNot, e))
in
L.verbose (fun fmt ->
fmt "Evaluated expressions: %a, %a" Val.pp vt Val.pp vf);
let can_put_t, can_put_f =
match lvt with
| Some (Bool true) -> (true, false)
| Some (Bool false) -> (false, true)
| _ ->
let vtx = State.sat_check state vt in
let vfx =
match vtx with
| false -> true
| true -> State.sat_check state vf
in
(vtx, vfx)
in
let sp_t, sp_f =
match (can_put_t, can_put_f) with
| false, false -> ([], [])
| true, false ->
(List.map (fun x -> (x, j)) (State.assume state vt), [])
| false, true ->
([], List.map (fun x -> (x, k)) (State.assume state vf))
| true, true ->
let state_t = State.copy state in
let unfolded_trues = State.assume ~unfold:true state_t vt in
let state_f = State.copy state in
let unfolded_falses = State.assume ~unfold:true state_f vf in
let utlen, uflen =
(List.length unfolded_trues, List.length unfolded_falses)
in
if utlen = 0 || uflen = 0 || utlen + uflen = 2 then
( List.map (fun x -> (x, j)) unfolded_trues,
List.map (fun x -> (x, k)) unfolded_falses )
else
let state' = State.copy state in
( List.map (fun x -> (x, j)) (State.assume state vt),
List.map (fun x -> (x, k)) (State.assume state' vf) )
in
let sp_t = List.map (fun t -> (t, true)) sp_t in
let sp_f = List.map (fun f -> (f, false)) sp_f in
let sp = sp_t @ sp_f in
let b_counter =
if can_put_t && can_put_f && List.length sp > 1 then b_counter + 1
else b_counter
in
let result =
sp
|> List.mapi (fun j ((state, next), case) ->
make_confcont ~state
~callstack:(if j = 0 then cs else CallStack.copy cs)
~invariant_frames:iframes ~prev_idx:i ~loop_ids
~next_idx:next ~branch_count:b_counter
~branch_case:(GuardedGoto case)
~new_branches:
(if j = 0 then
List.map
(fun ((state, next), case) ->
(state, next, GuardedGoto case))
(List.tl sp)
else [])
())
in
match
List.length result = 2 && !Config.parallel
(* XXX: && !Config.act_threads < !Config.max_threads *)
with
| true -> (
(* print_endline (Printf.sprintf "Conditional goto: %d" (!Config.act_threads + 1)); *)
let pid = Unix.fork () in
match pid with
| 0 -> [ List.hd result ]
| _ -> List.tl result)
| false -> result)
| PhiAssignment lxarr ->
DL.log (fun m -> m "PhiAssignment");
let j = get_predecessor prog cs prev i in
let state' =
List.fold_left
(fun state (x, x_arr) ->
let e = List.nth x_arr j in
let v = eval_expr e in
update_store state x v)
state lxarr
in
[
make_confcont ~state:state' ~callstack:cs ~invariant_frames:iframes
~prev_idx:i ~loop_ids ~next_idx:(i + 1) ~branch_count:b_counter ();
]
(* Function call *)
| Call (x, e, args, j, subst) ->
DL.log (fun m -> m "Call");
let pid = eval_expr e in
let v_args = List.map eval_expr args in
let result = evaluate_procedure_call x pid v_args j subst in
result
(* External function call *)
| ECall (x, pid, args, j) ->
DL.log (fun m -> m "ECall");
let pid =
match pid with
| PVar pid -> pid
| Lit (String pid) -> pid
| _ ->
raise
(Exceptions.Impossible
"Procedure identifier not a program variable")
in
let v_args = List.map eval_expr args in
List.map
(fun (state, cs, i, j) ->
make_confcont ~state ~callstack:cs ~invariant_frames:iframes
~prev_idx:i ~loop_ids ~next_idx:j ~branch_count:b_counter ())
(External.execute prog.prog state cs i x pid v_args j)
(* Function application *)
| Apply (x, pid_args, j) -> (
DL.log (fun m -> m "Apply");
let v_pid_args = eval_expr pid_args in
let v_pid_args_list = Val.to_list v_pid_args in
match v_pid_args_list with
| Some v_pid_args_list ->
let pid = List.hd v_pid_args_list in
let v_args = List.tl v_pid_args_list in
evaluate_procedure_call x pid v_args j None
| None ->
raise
(Failure
(Fmt.str "Apply not called with a list: @[<h>%a@]" Val.pp
v_pid_args)))
(* Arguments *)
| Arguments x ->
DL.log (fun m -> m "Arguments");
let args = CallStack.get_cur_args cs in
let args = Val.from_list args in
let state' = update_store state x args in
[
make_confcont ~state:state' ~callstack:cs ~invariant_frames:iframes
~prev_idx:i ~loop_ids ~next_idx:(i + 1) ~branch_count:b_counter ();
]
(* Normal-mode return *)
| ReturnNormal ->
let v_ret = Store.get store Names.return_variable in
let result =
match (v_ret, cs) with
| None, _ -> raise (Failure "nm_ret_var not in store (normal return)")
| Some v_ret, { store = None; loop_ids = start_loop_ids; _ } :: _ ->
check_loop_ids loop_ids start_loop_ids;
TODO : Redirect stdout to a file in debugging mode , as
the debug adapter communicates with VSCode via stdout . This
particular print statement currently causes issues , but
should be re - added once stdout has been redirected .
the debug adapter communicates with VSCode via stdout. This
particular print statement currently causes issues, but
should be re-added once stdout has been redirected. *)
Fmt.pr " n @ ? " ;
[
ConfFinish
{
flag = Normal;
ret_val = v_ret;
final_state = state;
branch_path;
};
]
| ( Some v_ret,
{
store = Some old_store;
loop_ids = start_loop_ids;
ret_var = x;
call_index = prev';
continue_index = j;
_;
}
:: cs' ) ->
let to_frame_on =
loop_ids_to_frame_on_at_the_end loop_ids start_loop_ids
in
let ( let+ ) x f = List.map f x in
let+ state =
if Exec_mode.verification_exec !Config.current_exec_mode then
State.frame_on state iframes to_frame_on
else [ state ]
in
let state' = State.set_store state old_store in
let state'' = update_store state' x v_ret in
make_confcont ~state:state'' ~callstack:cs'
~invariant_frames:iframes ~prev_idx:prev'
~loop_ids:start_loop_ids ~next_idx:j ~branch_count:b_counter ()
| _ -> raise (Failure "Malformed callstack")
in
L.verbose (fun m -> m "Returning.");
result
(* Error-mode return *)
| ReturnError -> (
let v_ret = Store.get store Names.return_variable in
match (v_ret, cs) with
| None, _ ->
raise (Failure "Return variable not in store (error return) ")
| Some v_ret, { store = None; loop_ids = start_loop_ids; _ } :: _ ->
check_loop_ids loop_ids start_loop_ids;
Fmt.pr "e @?";
[
ConfFinish
{
flag = Error;
ret_val = v_ret;
final_state = state;
branch_path : branch_path;
};
]
| ( Some v_ret,
{
store = Some old_store;
loop_ids = start_loop_ids;
ret_var = x;
call_index = prev';
error_index = Some j;
_;
}
:: cs' ) ->
let to_frame_on =
loop_ids_to_frame_on_at_the_end loop_ids start_loop_ids
in
let ( let+ ) x f = List.map f x in
let+ state =
if Exec_mode.verification_exec !Config.current_exec_mode then
State.frame_on state iframes to_frame_on
else [ state ]
in
let state' = State.set_store state old_store in
let state'' = update_store state' x v_ret in
make_confcont ~state:state'' ~callstack:cs'
~invariant_frames:iframes ~prev_idx:prev' ~loop_ids:start_loop_ids
~next_idx:j ~branch_count:b_counter ()
| _ -> raise (Failure "Malformed callstack"))
(* Explicit failure *)
| Fail (fail_code, fail_params) ->
let fail_params = List.map (State.eval_expr state) fail_params in
let err = ExecErr.EFailReached { fail_code; fail_params } in
raise (Interpreter_error ([ err ], state))
let simplify state =
snd (State.simplify ~save:true ~kill_new_lvars:true state)
let protected_evaluate_cmd
(prog : annot UP.prog)
(state : State.t)
(cs : CallStack.t)
(iframes : invariant_frames)
(prev : int)
(prev_loop_ids : string list)
(i : int)
(b_counter : int)
(report_id_ref : L.Report_id.t option ref)
(branch_path : branch_path)
(branch_case : branch_case option) : cconf_t list =
let states =
match get_cmd prog cs i with
| _, (_, LAction _) -> simplify state
| _ -> [ state ]
in
List.concat_map
(fun state ->
try
evaluate_cmd prog state cs iframes prev prev_loop_ids i b_counter
report_id_ref branch_path branch_case
with
| Interpreter_error (errors, error_state) ->
[
ConfErr
{
callstack = cs;
proc_idx = i;
error_state;
errors;
branch_path = List_utils.cons_opt branch_case branch_path;
};
]
| State.Internal_State_Error (errs, error_state) ->
(* Return: current procedure name, current command index, the state, and the associated errors *)
[
ConfErr
{
callstack = cs;
proc_idx = i;
error_state;
errors = List.map (fun x -> ExecErr.ESt x) errs;
branch_path = List_utils.cons_opt branch_case branch_path;
};
])
states
*
Evaluates one step of a program
@param ret_fun Function to transform the results
@param prog GIL program
@param name Identifier of the procedure to be evaluated
@param params Parameters of the procedure to be evaluated
@state state Current state
@preds Current predicate set
@return Continuation function specifying the next step of evaluation
Evaluates one step of a program
@param ret_fun Function to transform the results
@param prog GIL program
@param name Identifier of the procedure to be evaluated
@param params Parameters of the procedure to be evaluated
@state state Current state
@preds preds Current predicate set
@return Continuation function specifying the next step of evaluation
*)
let rec evaluate_cmd_step
(ret_fun : result_t -> 'a)
(retry : bool)
(prog : annot UP.prog)
(hold_results : 'a list)
(on_hold : (cconf_t * string) list)
(confs : cconf_t list)
(branch_path : branch_path option)
(results : (branch_path * result_t) list) : 'a cont_func =
let f = evaluate_cmd_step ret_fun retry prog hold_results on_hold in
let parent_id_ref = ref None in
let log_confcont is_first = function
| ConfCont
{
state;
callstack;
next_idx = proc_body_index;
branch_case;
prev_cmd_report_id;
_;
} ->
let cmd_step : CmdResult.t =
{
callstack;
proc_body_index;
state = Some state;
errors = [];
branch_case;
}
in
if is_first then (
prev_cmd_report_id
|> Option.iter (fun prev_report_id ->
L.Parent.release !parent_id_ref;
L.Parent.set prev_report_id;
parent_id_ref := Some prev_report_id);
DL.log (fun m ->
m
~json:[ ("conf", CmdResult.to_yojson cmd_step) ]
"Debugger.evaluate_cmd_step: New ConfCont"));
CmdResult.log_result cmd_step |> ignore;
Some cmd_step
| _ -> None
in
let continue_or_pause rest_confs cont_func =
match rest_confs with
| ConfCont { branch_case; new_branches; branch_path; _ } :: _ ->
rest_confs
|> List.iteri (fun i conf -> log_confcont (i = 0) conf |> ignore);
let new_branch_cases =
branch_case
|> Option.map (fun branch_case ->
branch_case
:: (new_branches |> List.map (fun (_, _, case) -> case)))
in
Continue (!parent_id_ref, branch_path, new_branch_cases, cont_func)
| ConfErr
{
callstack;
proc_idx = proc_body_index;
error_state = state;
errors;
branch_path;
}
:: _ ->
CmdResult.log_result
{
callstack;
proc_body_index;
state = Some state;
errors;
branch_case = None;
}
|> ignore;
Continue (!parent_id_ref, branch_path, None, cont_func)
| _ ->
if !Config.debug then
let branch_path = Option.value branch_path ~default:[] in
Continue (!parent_id_ref, branch_path, None, cont_func)
else cont_func ()
in
Fun.protect
~finally:(fun () -> L.Parent.release !parent_id_ref)
(fun () ->
let conf, rest_confs =
match branch_path with
| None ->
DL.log (fun m ->
m "HORROR: branch_path shouldn't be None when debugging!");
List_utils.hd_tl confs
| Some branch_path ->
confs
|> List_utils.pop_where (fun conf ->
cconf_path conf = branch_path)
in
DL.log (fun m ->
let conf_json =
match conf with
| None -> `Null
| Some conf -> cconf_t_to_yojson conf
in
m
~json:
[
("conf", conf_json);
("rest_confs", `List (List.map cconf_t_to_yojson rest_confs));
]
"GInterpreter.evaluate_cmd_step: Evaluating conf");
let end_of_branch ?branch_case results =
match branch_path with
| None ->
failwith "HORROR: branch_path shouldn't be None when debugging!"
| Some branch_path -> (
match results |> List.assoc_opt branch_path with
| None ->
DL.failwith
(fun () ->
let result_jsons =
results
|> List.map (fun (path, result) ->
`Assoc
[
("path", branch_path_to_yojson path);
("result", result_t_to_yojson result);
])
in
let conf_json =
match conf with
| None -> `Null
| Some conf -> cconf_t_to_yojson conf
in
[
("branch_path", branch_path_to_yojson branch_path);
( "branch_case",
opt_to_yojson branch_case_to_yojson branch_case );
("results", `List result_jsons);
("conf", conf_json);
( "rest_confs",
`List (List.map cconf_t_to_yojson rest_confs) );
])
"No result for branch path!"
| Some result ->
EndOfBranch
(ret_fun result, fun ?path () -> f rest_confs path results))
in
match (conf, rest_confs) with
| None, _ :: _ -> end_of_branch results
| None, [] when !Config.debug -> end_of_branch results
| None, [] ->
let results =
List.map (fun (_, result) -> ret_fun result) results
in
let results = hold_results @ results in
if not retry then Finished results
else (
L.(verbose (fun m -> m "Relaunching suspended confs"));
let hold_confs =
List.filter_map
(fun (conf, pid) ->
if Hashtbl.mem prog.specs pid then Some conf else None)
on_hold
in
continue_or_pause hold_confs (fun ?path () ->
evaluate_cmd_step ret_fun false prog results [] hold_confs
path []))
| ( Some
(ConfCont
{
state;
callstack = cs;
invariant_frames = iframes;
prev_idx = prev;
loop_ids = prev_loop_ids;
next_idx = i;
branch_count = b_counter;
prev_cmd_report_id;
branch_path;
branch_case;
_;
}),
_ )
when b_counter < max_branching ->
L.set_previous prev_cmd_report_id;
let next_confs =
protected_evaluate_cmd prog state cs iframes prev prev_loop_ids i
b_counter parent_id_ref branch_path branch_case
in
continue_or_pause next_confs (fun ?path () ->
f (next_confs @ rest_confs) path results)
| ( Some
(ConfCont
{
state;
callstack = cs;
next_idx = i;
branch_count = b_counter;
prev_cmd_report_id;
branch_case;
_;
}),
_ ) ->
let _, annot_cmd = get_cmd prog cs i in
Printf.printf "WARNING: MAX BRANCHING STOP: %d.\n" b_counter;
L.set_previous prev_cmd_report_id;
L.(
verbose (fun m ->
m
"Stopping Symbolic Execution due to MAX BRANCHING with %d. \
STOPPING CONF:\n"
b_counter));
log_configuration annot_cmd state cs i b_counter branch_case
|> Option.iter (fun report_id ->
parent_id_ref := Some report_id;
L.Parent.set report_id);
continue_or_pause [] (fun ?path () -> f rest_confs path results)
| ( Some
(ConfErr
{ callstack; proc_idx; error_state; errors; branch_path }),
_ ) ->
let proc = CallStack.get_cur_proc_id callstack in
let result =
ExecRes.RFail { proc; proc_idx; error_state; errors }
in
let results = (branch_path, result) :: results in
if !Config.debug then end_of_branch results
else
continue_or_pause rest_confs (fun ?path () ->
f rest_confs path results)
| Some (ConfFinish { flag; ret_val; final_state; branch_path }), _ ->
let result =
ExecRes.RSucc
{ flag; ret_val; final_state; last_report = L.Parent.get () }
in
let results = (branch_path, result) :: results in
if !Config.debug then end_of_branch results
else
continue_or_pause rest_confs (fun ?path () ->
f rest_confs path results)
| ( Some
(ConfSusp
{
spec_id = fid;
state;
callstack;
invariant_frames;
prev_idx;
loop_ids;
next_idx;
branch_count;
branch_path;
}),
_ )
when retry ->
let conf =
make_confcont ~state ~callstack ~invariant_frames ~prev_idx
~loop_ids ~next_idx ~branch_count ~branch_path ()
in
L.(
verbose (fun m ->
m "Suspending a computation that was trying to call %s" fid));
continue_or_pause [] (fun ?path () ->
evaluate_cmd_step ret_fun retry prog hold_results
((conf, fid) :: on_hold) rest_confs path results)
| Some _, _ ->
continue_or_pause rest_confs (fun ?path () ->
f rest_confs path results))
*
Evaluates commands iteratively
@param init_func The initial continuation function which evaluates the first
step of the program
Evaluates commands iteratively
@param init_func The initial continuation function which evaluates the first
step of the program
*)
let rec evaluate_cmd_iter (init_func : 'a cont_func) : 'a list =
match init_func with
| Finished results -> results
| Continue (_, _, _, cont_func) -> evaluate_cmd_iter (cont_func ())
| EndOfBranch _ ->
failwith "HORROR: EndOfBranch encountered in continuous eval!"
*
Sets the initial values for evaluating a program , and returns a continuation
function which evaluates the first step of the program
@param ret_fun Function to transform the results
@param prog GIL program
@param name Identifier of the procedure to be evaluated
@param params Parameters of the procedure to be evaluated
@state state Current state
@preds Current predicate set
@return Continuation function which evaluates the first step of the program
Sets the initial values for evaluating a program, and returns a continuation
function which evaluates the first step of the program
@param ret_fun Function to transform the results
@param prog GIL program
@param name Identifier of the procedure to be evaluated
@param params Parameters of the procedure to be evaluated
@state state Current state
@preds preds Current predicate set
@return Continuation function which evaluates the first step of the program
*)
let init_evaluate_proc
(ret_fun : result_t -> 'a)
(prog : annot UP.prog)
(name : string)
(params : string list)
(state : State.t) : 'a cont_func =
let () = CallGraph.add_proc call_graph name in
L.normal (fun m ->
m
("*******************************************@\n"
^^ "*** Executing procedure: %s@\n"
^^ "*******************************************@\n")
name);
let store = State.get_store state in
let arguments =
List.map
(fun x ->
match Store.get store x with
| Some v_x -> v_x
| None ->
raise (Failure "Symbolic State does NOT contain formal parameter"))
params
in
let cs : CallStack.t =
CallStack.push CallStack.empty ~pid:name ~arguments ~loop_ids:[]
~ret_var:"out" ~call_index:(-1) ~continue_index:(-1) ~error_index:(-1)
()
in
let proc_body_index = 0 in
let conf : cconf_t =
make_confcont ~state ~callstack:cs ~invariant_frames:[] ~prev_idx:(-1)
~loop_ids:[] ~next_idx:proc_body_index ~branch_count:0 ~branch_path:[]
()
in
let report_id =
CmdResult.log_init
{
callstack = cs;
proc_body_index;
state = Some state;
errors = [];
branch_case = None;
}
in
Continue
( report_id,
[],
None,
fun ?path () ->
evaluate_cmd_step ret_fun true prog [] [] [ conf ] path [] )
*
Evaluation of procedures
@param prog GIL program
@param name Identifier of the procedure to be evaluated
@param params Parameters of the procedure to be evaluated
@state state Current state
@preds Current predicate set
@return List of final configurations
Evaluation of procedures
@param prog GIL program
@param name Identifier of the procedure to be evaluated
@param params Parameters of the procedure to be evaluated
@state state Current state
@preds preds Current predicate set
@return List of final configurations
*)
let evaluate_proc
(ret_fun : result_t -> 'a)
(prog : annot UP.prog)
(name : string)
(params : string list)
(state : State.t) : 'a list =
let init_func = init_evaluate_proc ret_fun prog name params state in
evaluate_cmd_iter init_func
*
Evaluation of programs
@param prog Target GIL program
@return Final configurations
Evaluation of programs
@param prog Target GIL program
@return Final configurations
*)
end
| null | https://raw.githubusercontent.com/GillianPlatform/Gillian/06739278bc266d218c1516d4c8e670b4edff9041/GillianCore/engine/GeneralSemantics/General/GInterpreter.ml | ocaml | * Equal to Conf cont + the id of the required spec
* General GIL Interpreter
*************** *
* Auxiliary Types *
* ***************
* Type of configurations: state, call stack, previous index, previous loop ids, current index, branching
* Equal to Conf cont + the id of the required spec
We only want to track branches for the base function.
TODO: Cmd step should contain all things in a configuration
print the same contents as log_configuration
* Configuration pretty-printer
* Internal error, carrying a string description
* Syntax error, carrying a string description
Often-used values
No change in loop structure
Change in loop structure
We have entered a new loop
******************* *
* Auxiliary Functions *
* *******************
************** *
* Main Functions *
* **************
Printf.printf "Considering the following disjuncts: %s\n"
I commented the following, because it builds a string and discards it ?
We have to understand what is the intended semantics of the logic if
The full list of loop ids is the concatenation
of the loop ids of the current procedure plus
the loop ids that have come from the call stack
Note the new loop identifiers
print_to_all ("\tStarting run spec: " ^ pid);
print_to_all ("\tFinished run spec: " ^ pid);
Run spec returned no results
In bi-abduction, reached max depth of recursive calls
In bi-abduction, recursive call
Skip
Assignment
Action
XXX: && !Config.act_threads < !Config.max_threads )
Invariant being revisited
Unconditional goto
Conditional goto
XXX: && !Config.act_threads < !Config.max_threads
print_endline (Printf.sprintf "Conditional goto: %d" (!Config.act_threads + 1));
Function call
External function call
Function application
Arguments
Normal-mode return
Error-mode return
Explicit failure
Return: current procedure name, current command index, the state, and the associated errors | open Literal
open BranchCase
module L = Logging
module DL = Debugger_log
open Syntaxes.Result
type branch_case = BranchCase.t [@@deriving yojson]
module type S = sig
module CallStack : CallStack.S
type vt
type st
type store_t
type state_t
type state_err_t [@@deriving show]
type state_vt [@@deriving yojson, show]
type heap_t
type init_data
type annot
module Val : Val.S with type t = vt
module Store : Store.S with type t = store_t and type vt = vt
type invariant_frames = (string * state_t) list
type err_t = (vt, state_err_t) ExecErr.t [@@deriving show, yojson]
type branch_path = branch_case list [@@deriving yojson]
type cconf_t =
| ConfErr of {
callstack : CallStack.t;
proc_idx : int;
error_state : state_t;
errors : err_t list;
branch_path : branch_path;
}
| ConfCont of {
state : state_t;
callstack : CallStack.t;
invariant_frames : invariant_frames;
prev_idx : int;
next_idx : int;
loop_ids : string list;
branch_count : int;
prev_cmd_report_id : L.Report_id.t option;
branch_case : branch_case option;
branch_path : branch_path;
new_branches : (state_t * int * branch_case) list;
}
| ConfFinish of {
flag : Flag.t;
ret_val : state_vt;
final_state : state_t;
branch_path : branch_path;
| ConfSusp of {
spec_id : string;
state : state_t;
callstack : CallStack.t;
invariant_frames : invariant_frames;
prev_idx : int;
next_idx : int;
loop_ids : string list;
branch_count : int;
branch_path : branch_path;
}
type conf_t = BConfErr of err_t list | BConfCont of state_t
type result_t = (state_t, state_vt, err_t) ExecRes.t
type 'a cont_func_f = ?path:branch_path -> unit -> 'a cont_func
and 'a cont_func =
| Finished of 'a list
| Continue of
(Logging.Report_id.t option
* branch_path
* branch_case list option
* 'a cont_func_f)
| EndOfBranch of 'a * 'a cont_func_f
module Logging : sig
module ConfigReport : sig
type t = {
proc_line : int;
time : float;
cmd : int Cmd.t;
callstack : CallStack.t;
annot : annot;
branching : int;
state : state_t;
branch_case : branch_case option;
}
[@@deriving yojson]
end
module CmdResult : sig
type t = {
callstack : CallStack.t;
proc_body_index : int;
state : state_t option;
errors : err_t list;
branch_case : branch_case option;
}
[@@deriving yojson]
end
val pp_err : Format.formatter -> (vt, state_err_t) ExecErr.t -> unit
val pp_result : Format.formatter -> result_t list -> unit
end
val call_graph : CallGraph.t
val reset : unit -> unit
val evaluate_lcmds :
annot UP.prog ->
LCmd.t list ->
state_t ->
(state_t list, state_err_t list) result
val init_evaluate_proc :
(result_t -> 'a) ->
annot UP.prog ->
string ->
string list ->
state_t ->
'a cont_func
val evaluate_proc :
(result_t -> 'a) ->
annot UP.prog ->
string ->
string list ->
state_t ->
'a list
end
module Make
(Val : Val.S)
(ESubst : ESubst.S with type vt = Val.t and type t = Val.et)
(Store : Store.S with type vt = Val.t)
(State : State.S
with type vt = Val.t
and type st = ESubst.t
and type store_t = Store.t)
(PC : ParserAndCompiler.S)
(External : External.T(PC.Annot).S) =
struct
module CallStack = CallStack.Make (Val) (Store)
module External = External (Val) (ESubst) (Store) (State) (CallStack)
module Val = Val
module State = State
module Store = Store
module Annot = PC.Annot
type vt = Val.t
type st = ESubst.t
type store_t = Store.t
type state_t = State.t [@@deriving yojson]
type state_err_t = State.err_t [@@deriving yojson]
type init_data = State.init_data
type annot = Annot.t [@@deriving yojson]
let pp_state_err_t = State.pp_err
let show_state_err_t = Fmt.to_to_string pp_state_err_t
type state_vt = State.vt [@@deriving yojson, show]
type heap_t = State.heap_t
type invariant_frames = (string * State.t) list [@@deriving yojson]
type err_t = (Val.t, state_err_t) ExecErr.t [@@deriving show, yojson]
type branch_path = branch_case list [@@deriving yojson]
type cconf_t =
| ConfErr of {
callstack : CallStack.t;
proc_idx : int;
error_state : state_t;
errors : err_t list;
branch_path : branch_path;
}
| ConfCont of {
state : State.t;
callstack : CallStack.t;
invariant_frames : invariant_frames;
prev_idx : int;
next_idx : int;
loop_ids : string list;
branch_count : int;
prev_cmd_report_id : L.Report_id.t option;
branch_case : branch_case option;
branch_path : branch_path;
new_branches : (state_t * int * branch_case) list;
}
| ConfFinish of {
flag : Flag.t;
ret_val : State.vt;
final_state : State.t;
branch_path : branch_path;
| ConfSusp of {
spec_id : string;
state : state_t;
callstack : CallStack.t;
invariant_frames : invariant_frames;
prev_idx : int;
next_idx : int;
loop_ids : string list;
branch_count : int;
branch_path : branch_path;
}
[@@deriving yojson]
let make_confcont
~state
~callstack
~invariant_frames
~prev_idx
~next_idx
~loop_ids
~branch_count
~branch_path
?prev_cmd_report_id
?branch_case
?(new_branches = [])
() =
let branch_case, new_branches =
if List.length callstack > 1 then (None, [])
else (branch_case, new_branches)
in
ConfCont
{
state;
callstack;
invariant_frames;
prev_idx;
next_idx;
loop_ids;
branch_count;
branch_path;
prev_cmd_report_id;
branch_case;
new_branches;
}
let cconf_path = function
| ConfErr { branch_path; _ } -> branch_path
| ConfFinish { branch_path; _ } -> branch_path
| ConfSusp { branch_path; _ } -> branch_path
| ConfCont { branch_path; branch_case; _ } ->
List_utils.cons_opt branch_case branch_path
type conf_t = BConfErr of err_t list | BConfCont of State.t
type result_t = (State.t, State.vt, err_t) ExecRes.t [@@deriving yojson]
type 'a cont_func_f = ?path:branch_path -> unit -> 'a cont_func
and 'a cont_func =
| Finished of 'a list
| Continue of
(Logging.Report_id.t option
* branch_path
* branch_case list option
* 'a cont_func_f)
| EndOfBranch of 'a * 'a cont_func_f
module Logging = struct
let pp_str_list = Fmt.(brackets (list ~sep:comma string))
module ConfigReport = struct
type t = {
proc_line : int;
time : float;
cmd : int Cmd.t;
callstack : CallStack.t;
annot : annot;
branching : int;
state : state_t;
branch_case : branch_case option;
}
[@@deriving yojson, make]
let pp
state_printer
fmt
{
proc_line = i;
time;
cmd;
callstack = cs;
annot;
branching;
state;
_;
} =
Fmt.pf fmt
"@[------------------------------------------------------@\n\
--%s: %i--@\n\
TIME: %f@\n\
CMD: %a@\n\
PROCS: %a@\n\
LOOPS: %a ++ %a@\n\
BRANCHING: %d@\n\
@\n\
%a@\n\
------------------------------------------------------@]\n"
(CallStack.get_cur_proc_id cs)
i time Cmd.pp_indexed cmd pp_str_list
(CallStack.get_cur_procs cs)
pp_str_list
(Annot.get_loop_info annot)
pp_str_list
(CallStack.get_loop_ids cs)
branching state_printer state
let to_loggable state_printer =
L.Loggable.make (pp state_printer) of_yojson to_yojson
let log state_printer report =
L.Specific.normal
(to_loggable state_printer report)
L.Logging_constants.Content_type.cmd
end
module CmdResult = struct
type t = {
callstack : CallStack.t;
proc_body_index : int;
state : state_t option;
errors : err_t list;
branch_case : branch_case option;
}
[@@deriving yojson]
let pp fmt cmd_step =
CallStack.pp fmt cmd_step.callstack
let to_loggable = L.Loggable.make pp of_yojson to_yojson
let log type_ report = L.Specific.normal (to_loggable report) type_
open L.Logging_constants.Content_type
let log_result = log cmd_result
let log_init = log proc_init
end
module AnnotatedAction = struct
type t = { annot : Annot.t; action_name : string } [@@deriving yojson]
let pp fmt annotated_action =
let origin_loc = Annot.get_origin_loc annotated_action.annot in
Fmt.pf fmt "Executing action '%s' at %a" annotated_action.action_name
(Fmt.option ~none:(Fmt.any "none") Location.pp)
origin_loc
let to_loggable = L.Loggable.make pp of_yojson to_yojson
let log report =
L.Specific.normal (to_loggable report)
L.Logging_constants.Content_type.annotated_action
end
let log_configuration
(cmd : Annot.t * int Cmd.t)
(state : State.t)
(cs : CallStack.t)
(i : int)
(b_counter : int)
(branch_case : branch_case option) : L.Report_id.t option =
let annot, cmd = cmd in
let state_printer =
match !Config.pbn with
| false -> State.pp
| true ->
let pvars, lvars, locs =
(Cmd.pvars cmd, Cmd.lvars cmd, Cmd.locs cmd)
in
State.pp_by_need pvars lvars locs
in
ConfigReport.log state_printer
(ConfigReport.make ~proc_line:i ~time:(Sys.time ()) ~cmd ~callstack:cs
~annot ~branching:b_counter ~state ?branch_case ())
let print_lconfiguration (lcmd : LCmd.t) (state : State.t) : unit =
L.normal (fun m ->
m
"@[------------------------------------------------------@\n\
TIME: %f@\n\
LCMD: %a@\n\
@\n\
%a@\n\
------------------------------------------------------@]@\n"
(Sys.time ()) LCmd.pp lcmd State.pp state)
let pp_err = ExecErr.pp Val.pp State.pp_err
let pp_single_result ft res = ExecRes.pp State.pp Val.pp pp_err ft res
let pp_result (ft : Format.formatter) (reslt : result_t list) : unit =
let open Fmt in
let pp_one ft (i, res) =
pf ft "RESULT: %d.@\n%a" i pp_single_result res
in
(iter_bindings List.iteri pp_one) ft reslt
end
open Logging
let max_branching = 100
exception Interpreter_error of err_t list * State.t
exception Internal_error of string
exception Syntax_error of string
let call_graph = CallGraph.make ~init_capacity:128 ()
let reset () = CallGraph.reset call_graph
let vtrue = Val.from_literal (Bool true)
let vfalse = Val.from_literal (Bool false)
let symb_exec_next = ref false
type loop_action =
| Nothing
| FrameOff of string
| FrameOn of string list
| Malformed
let understand_loop_action current previous : loop_action =
match current = previous with
| true -> Nothing
| false -> (
let len_cur = List.length current in
let len_prev = List.length previous in
match len_cur - len_prev with
| 1 ->
if List.tl current <> previous then Malformed
else FrameOff (List.hd current)
We have entered more than one loop - this is not allowed
| n when n > 0 -> Malformed
We have exited at least one loop
| n ->
let ids = Option.get (List_utils.list_sub previous 0 (-n)) in
let rest =
Option.get (List_utils.list_sub previous (-n) (len_prev + n))
in
if rest <> current then Malformed else FrameOn ids)
let get_cmd (prog : annot UP.prog) (cs : CallStack.t) (i : int) :
string * (Annot.t * int Cmd.t) =
let pid = CallStack.get_cur_proc_id cs in
let proc = Prog.get_proc prog.prog pid in
let proc =
match proc with
| Some proc -> proc
| None -> raise (Failure ("Procedure " ^ pid ^ " does not exist."))
in
let annot, _, cmd = proc.proc_body.(i) in
(pid, (annot, cmd))
let get_predecessor
(prog : annot UP.prog)
(cs : CallStack.t)
(prev : int)
(i : int) : int =
let pid = CallStack.get_cur_proc_id cs in
try Hashtbl.find prog.prog.predecessors (pid, prev, i)
with _ ->
raise
(Failure (Printf.sprintf "Undefined predecessor: %s %d %d" pid prev i))
let update_store (state : State.t) (x : string) (v : Val.t) : State.t =
let store = State.get_store state in
let () = Store.put store x v in
let state' = State.set_store state store in
state'
let eval_subst_list
(state : State.t)
(subst_lst : (string * (string * Expr.t) list) option) :
(string * (string * Val.t) list) option =
match subst_lst with
| None -> None
| Some (lab, subst_lst) ->
let subst_lst' : (string * Val.t) list =
List.map (fun (x, e) -> (x, State.eval_expr state e)) subst_lst
in
Some (lab, subst_lst')
let make_eval_expr (state : State.t) : Expr.t -> Val.t =
fun e ->
try State.eval_expr state e
with State.Internal_State_Error (errs, s) ->
raise (Interpreter_error (List.map (fun x -> ExecErr.ESt x) errs, s))
let check_loop_ids actual expected =
match actual = expected with
| false ->
Fmt.failwith
"Malformed loop structure: current loops: %a; expected loops: %a"
pp_str_list actual pp_str_list expected
| true -> ()
let rec loop_ids_to_frame_on_at_the_end end_ids start_ids =
if end_ids = start_ids then []
else
match end_ids with
| [] ->
Fmt.failwith
"Malformed loop structure (at return): current loops: %a; expected \
loops: %a"
pp_str_list end_ids pp_str_list start_ids
| x :: r -> x :: loop_ids_to_frame_on_at_the_end r start_ids
*
Evaluation of logic commands
@param prog GIL program
@param lcmd Logic command to be evaluated
@param state Current state
@param Current predicate set
@return List of states / predicate sets resulting from the evaluation
Evaluation of logic commands
@param prog GIL program
@param lcmd Logic command to be evaluated
@param state Current state
@param preds Current predicate set
@return List of states/predicate sets resulting from the evaluation
*)
let rec evaluate_lcmd (prog : annot UP.prog) (lcmd : LCmd.t) (state : State.t)
: (State.t list, state_err_t list) result =
print_lconfiguration lcmd state;
let eval_expr = make_eval_expr state in
match lcmd with
| AssumeType (e, t) -> (
let v_x = eval_expr e in
match State.assume_t state v_x t with
| Some state' -> Ok [ state' ]
| _ ->
Fmt.failwith
"ERROR: AssumeType: Cannot assume type %s for expression %a."
(Type.str t) Expr.pp e)
| Assume f ->
let store_subst = Store.to_ssubst (State.get_store state) in
let f' = SVal.SESubst.substitute_formula store_subst ~partial:true f in
Printf.printf " Assuming % s\n " ( Formula.str f ' ) ;
let fos =
if Exec_mode.biabduction_exec !Config.current_exec_mode then
let fos = Formula.get_disjuncts f' in
match fos with
| [] -> []
| [ f' ] -> [ (f', state) ]
| f' :: other_fos ->
let new_fos_states =
List.map (fun f'' -> (f'', State.copy state)) other_fos
in
(f', state) :: new_fos_states
else [ (f', state) ]
in
( String.concat " ; " ( List.map ( fun ( f , _ ) - > Formula.str f ) fos ) ) ;
Ok
(List.concat
(List.map
(fun (f'', state) ->
match State.assume_a state [ f'' ] with
| Some state' -> [ state' ]
| _ -> [])
fos))
| FreshSVar x ->
let new_svar = Generators.fresh_svar () in
let state' = State.add_spec_vars state (SS.singleton new_svar) in
let v = Val.from_expr (LVar new_svar) |> Option.get in
Ok [ update_store state' x v ]
| Assert f -> (
let store_subst = Store.to_ssubst (State.get_store state) in
let f' = SVal.SESubst.substitute_formula store_subst ~partial:true f in
match State.assert_a state [ f' ] with
| true -> Ok [ state ]
| false ->
let err = StateErr.EPure f' in
let failing_model = State.sat_check_f state [ Not f' ] in
let msg =
Fmt.str
"Assert failed with argument @[<h>%a@].@\n\
@[<v 2>Failing Model:@\n\
%a@]@\n"
Formula.pp f'
Fmt.(option ~none:(any "CANNOT CREATE MODEL") ESubst.pp)
failing_model
in
if not (Exec_mode.biabduction_exec !Config.current_exec_mode) then
Printf.printf "%s" msg;
L.normal (fun m -> m "%s" msg);
raise (Interpreter_error ([ ESt err ], state)))
| Macro (name, args) -> (
let macro = Macro.get prog.prog.macros name in
match macro with
| None ->
L.verbose (fun m ->
m "@[<v 2>Current MACRO TABLE:\n%a\n@]" Macro.pp_tbl
prog.prog.macros);
raise
(Failure
(Fmt.str "NO MACRO found when executing: @[<h>%a@]" LCmd.pp
lcmd))
| Some macro ->
let expand_macro (macro : Macro.t) (args : Expr.t list) :
LCmd.t list =
let params = macro.macro_params in
let params_card = List.length params in
let args_card = List.length args in
if params_card <> args_card then
raise
(Failure
(Printf.sprintf
"Macro %s called with incorrect number of parameters: \
%d instead of %d."
macro.macro_name args_card params_card));
let subst = SVal.SSubst.init (List.combine params args) in
let lcmds = macro.macro_definition in
List.map (SVal.SSubst.substitute_lcmd subst ~partial:true) lcmds
in
let lcmds = expand_macro macro args in
evaluate_lcmds prog lcmds state)
| If (e, lcmds_t, lcmds_e) -> (
let ve = eval_expr e in
let e = Val.to_expr ve in
match Formula.lift_logic_expr e with
| Some (True, False) -> evaluate_lcmds prog lcmds_t state
| Some (False, True) -> evaluate_lcmds prog lcmds_e state
| Some (foe, nfoe) ->
let state' = State.copy state in
let* then_states =
State.assume_a state [ foe ]
|> Option.fold
~some:(fun state -> evaluate_lcmds prog lcmds_t state)
~none:(Ok [])
in
let+ else_states =
State.assume_a state' [ nfoe ]
|> Option.fold
~some:(fun state -> evaluate_lcmds prog lcmds_e state)
~none:(Ok [])
in
then_states @ else_states
| None ->
raise
(Failure
"Non-boolean expression in the condition of the logical if"))
| Branch fof ->
let state' = State.copy state in
let state =
Option.fold
~some:(fun x -> [ x ])
~none:[]
(State.assume_a state [ fof ])
in
let state' =
Option.fold
~some:(fun x -> [ x ])
~none:[]
(State.assume_a state' [ Not fof ])
in
Ok (state @ state')
| SL sl_cmd -> State.evaluate_slcmd prog sl_cmd state
and evaluate_lcmds
(prog : annot UP.prog)
(lcmds : LCmd.t list)
(state : State.t) : (State.t list, state_err_t list) result =
match lcmds with
| [] -> Ok [ state ]
| lcmd :: rest_lcmds ->
let* rets = evaluate_lcmd prog lcmd state in
let+ next_rets =
rets
|> List_utils.map_results (fun state ->
evaluate_lcmds prog rest_lcmds state)
in
List.concat next_rets
*
Evaluation of commands
@param prog GIL program
@param state Current state
@param Current predicate set
@param cs Current call stack
@param prev Previous index
@param i Current index
@return List of configurations resulting from the evaluation
Evaluation of commands
@param prog GIL program
@param state Current state
@param preds Current predicate set
@param cs Current call stack
@param prev Previous index
@param i Current index
@return List of configurations resulting from the evaluation
*)
let rec evaluate_cmd
(prog : annot UP.prog)
(state : State.t)
(cs : CallStack.t)
(iframes : invariant_frames)
(prev : int)
(prev_loop_ids : string list)
(i : int)
(b_counter : int)
(report_id_ref : L.Report_id.t option ref)
(branch_path : branch_path)
(branch_case : branch_case option) : cconf_t list =
let _, (annot, _) = get_cmd prog cs i in
let loop_ids = Annot.get_loop_info annot @ CallStack.get_loop_ids cs in
let loop_action : loop_action =
if Exec_mode.verification_exec !Config.current_exec_mode then
understand_loop_action loop_ids prev_loop_ids
else Nothing
in
let eval_in_state state =
evaluate_cmd_after_frame_handling prog state cs iframes prev prev_loop_ids
i b_counter report_id_ref branch_path branch_case
in
match loop_action with
| Nothing -> eval_in_state state
| FrameOff id ->
L.verbose (fun fmt -> fmt "INFO: Expecting to frame off %s" id);
eval_in_state state
| Malformed -> L.fail "Malformed loop identifiers"
| FrameOn ids ->
L.verbose (fun fmt -> fmt "INFO: Going to frame on %a" pp_str_list ids);
let states = State.frame_on state iframes ids in
let n = List.length states in
if n == 0 then
L.normal (fun fmt -> fmt "WARNING: FRAMING ON RESULTED IN 0 STATES !")
else if n > 1 then
L.verbose (fun fmt ->
fmt
"WARNING: FRAMING ON AFTER EXITING LOOP BRANCHED INTO %i STATES"
n);
List.concat_map eval_in_state states
and evaluate_cmd_after_frame_handling
(prog : annot UP.prog)
(state : State.t)
(cs : CallStack.t)
(iframes : invariant_frames)
(prev : int)
(prev_loop_ids : string list)
(i : int)
(b_counter : int)
(report_id_ref : L.Report_id.t option ref)
(branch_path : branch_path)
(branch_case : branch_case option) : cconf_t list =
let store = State.get_store state in
let eval_expr = make_eval_expr state in
let proc_name, annot_cmd = get_cmd prog cs i in
let annot, cmd = annot_cmd in
let loop_ids = Annot.get_loop_info annot @ CallStack.get_loop_ids cs in
let loop_action : loop_action =
if Exec_mode.verification_exec !Config.current_exec_mode then
understand_loop_action loop_ids prev_loop_ids
else Nothing
in
if ! then Statistics.exec_cmds : = ! Statistics.exec_cmds + 1 ;
UP.update_coverage prog proc_name i;
log_configuration annot_cmd state cs i b_counter branch_case
|> Option.iter (fun report_id ->
report_id_ref := Some report_id;
L.Parent.set report_id);
let branch_path = List_utils.cons_opt branch_case branch_path in
let make_confcont =
make_confcont ?prev_cmd_report_id:!report_id_ref ~branch_path
in
DL.log (fun m ->
m
~json:[ ("path", branch_path_to_yojson branch_path) ]
"GInterpreter: stepping with path");
let evaluate_procedure_call x pid v_args j subst =
let pid =
match Val.to_literal pid with
| Some (String pid) -> pid
| Some _ ->
let err = [ ExecErr.EProc pid ] in
raise (Interpreter_error (err, state))
| None ->
raise
(Internal_error
"Procedure Call Error - unlifting procedure ID failed")
in
let proc = Prog.get_proc prog.prog pid in
let spec = Hashtbl.find_opt prog.specs pid in
let params =
match (proc, spec) with
| Some proc, _ -> Proc.get_params proc
| None, Some spec -> Spec.get_params spec.spec
| _ ->
raise
(Interpreter_error
([ EProc (Val.from_literal (String pid)) ], state))
in
let caller = CallStack.get_cur_proc_id cs in
let () = CallGraph.add_proc_call call_graph caller pid in
let prmlen = List.length params in
let args = Array.make prmlen (Val.from_literal Undefined) in
let () =
List.iteri (fun i v_arg -> if i < prmlen then args.(i) <- v_arg) v_args
in
let args = Array.to_list args in
let process_ret is_first ret_state fl b_counter others : cconf_t =
let new_cs =
match is_first with
| true -> CallStack.copy cs
| false -> cs
in
let new_j =
match (fl, j) with
| Flag.Normal, _ -> i + 1
| Flag.Error, Some j -> j
| Flag.Error, None ->
let msg =
Printf.sprintf
"SYNTAX ERROR: No error label provided when calling \
procedure %s"
pid
in
L.normal (fun fmt -> fmt "%s" msg);
raise (Syntax_error msg)
in
let branch_case = SpecExec fl in
let branch_case, new_branches =
match (is_first, others) with
| _, Some (_ :: _ as others) ->
let new_branches =
Some
(List_utils.get_list_somes
@@ List.map
(fun conf ->
match conf with
| ConfCont { state; next_idx; _ } ->
Some (state, next_idx, branch_case)
| _ -> None)
others)
in
(Some branch_case, new_branches)
| false, _ -> (Some branch_case, None)
| _ -> (None, None)
in
make_confcont ~state:ret_state ~callstack:new_cs
~invariant_frames:iframes ~prev_idx:i ~loop_ids ~next_idx:new_j
~branch_count:b_counter ?branch_case ?new_branches ()
in
let is_internal_proc proc_name =
(Prog.get_proc_exn prog.prog proc_name).proc_internal
in
let symb_exec_proc () =
let new_store = Store.init (List.combine params args) in
let old_store = State.get_store state in
let state' = State.set_store state new_store in
let cs' =
CallStack.push cs ~pid ~arguments:v_args ~store:old_store ~loop_ids
~ret_var:x ~call_index:i ~continue_index:(i + 1) ?error_index:j ()
in
[
make_confcont ~state:state' ~callstack:cs' ~invariant_frames:iframes
~prev_idx:(-1) ~loop_ids ~next_idx:0 ~branch_count:b_counter ();
]
in
let spec_exec_proc () =
match spec with
| Some spec -> (
match !symb_exec_next with
| true ->
symb_exec_next := false;
symb_exec_proc ()
| false -> (
let subst = eval_subst_list state subst in
L.verbose (fun fmt -> fmt "ABOUT TO USE THE SPEC OF %s" pid);
let rets : ((State.t * Flag.t) list, state_err_t list) result =
State.run_spec spec state x args subst
in
match rets with
| Ok rets -> (
L.verbose (fun fmt ->
fmt "Run_spec returned %d Results" (List.length rets));
let b_counter =
if List.length rets > 1 then b_counter + 1 else b_counter
in
match rets with
| (ret_state, fl) :: rest_rets ->
let others =
List.map
(fun (ret_state, fl) ->
process_ret false ret_state fl b_counter None)
rest_rets
in
process_ret true ret_state fl b_counter (Some others)
:: others
| _ -> (
match spec.spec.spec_incomplete with
| true ->
L.normal (fun fmt ->
fmt "Proceeding with symbolic execution.");
symb_exec_proc ()
| false ->
L.fail
(Format.asprintf
"ERROR: Unable to use specification of \
function %s"
spec.spec.spec_name)))
| Error errors ->
let errors = errors |> List.map (fun e -> ExecErr.ESt e) in
[
ConfErr
{
callstack = cs;
proc_idx = i;
error_state = state;
errors;
branch_path;
};
]))
| None ->
if Hashtbl.mem prog.prog.bi_specs pid then
[
ConfSusp
{
spec_id = pid;
state;
callstack = cs;
invariant_frames = iframes;
prev_idx = prev;
loop_ids = prev_loop_ids;
next_idx = i;
branch_path;
branch_count = b_counter;
};
]
else symb_exec_proc ()
in
match Exec_mode.biabduction_exec !Config.current_exec_mode with
| true -> (
match
( pid = caller,
is_internal_proc pid,
CallStack.recursive_depth cs pid >= !Config.bi_unroll_depth )
with
| _, _, true -> []
| true, false, _ -> symb_exec_proc ()
TODO : When JS internals work
| true , false , false
when
( List.filter is_internal_proc ( CallStack.get_cur_procs cs ) )
< ! Config.bi_no_spec_depth - > symb_exec_proc ( )
| true, false, false
when List.length
(List.filter is_internal_proc (CallStack.get_cur_procs cs))
< !Config.bi_no_spec_depth -> symb_exec_proc () *)
| _ -> spec_exec_proc ())
| false -> spec_exec_proc ()
in
match cmd with
| Skip ->
[
make_confcont ~state ~callstack:cs ~invariant_frames:iframes
~prev_idx:i ~loop_ids ~next_idx:(i + 1) ~branch_count:b_counter ();
]
| Assignment (x, e) ->
DL.log (fun m ->
m
~json:[ ("target", `String x); ("expr", Expr.to_yojson e) ]
"Assignment");
let v = eval_expr e in
let state' = update_store state x v in
[
make_confcont ~state:state' ~callstack:cs ~invariant_frames:iframes
~prev_idx:i ~loop_ids ~next_idx:(i + 1) ~branch_count:b_counter ();
]
| LAction (x, a, es) -> (
DL.log (fun m ->
m
~json:
[
("x", `String x);
("a", `String a);
("es", `List (List.map Expr.to_yojson es));
]
"LAction");
AnnotatedAction.log { annot; action_name = a } |> ignore;
let v_es = List.map eval_expr es in
match State.execute_action a state v_es with
| Ok [] -> failwith "HORROR: Successful action resulted in no states"
| Ok ((state', vs) :: rest_rets) -> (
DL.log (fun m ->
m
~json:
[
("state'", state_t_to_yojson state');
("vs", `List (List.map state_vt_to_yojson vs));
]
"Ok");
let e' = Expr.EList (List.map Val.to_expr vs) in
let v' = eval_expr e' in
let state'' = update_store state' x v' in
let rest_confs, new_branches =
List.split
@@ List.map
(fun (r_state, r_vs) ->
let r_e = Expr.EList (List.map Val.to_expr r_vs) in
let r_v = eval_expr r_e in
let r_state' = update_store r_state x r_v in
let branch_case =
LAction (r_vs |> List.map state_vt_to_yojson)
in
( make_confcont ~state:r_state'
~callstack:(CallStack.copy cs)
~invariant_frames:iframes ~prev_idx:i ~loop_ids
~next_idx:(i + 1) ~branch_count:b_counter ~branch_case
(),
(r_state', i + 1, branch_case) ))
rest_rets
in
let ret_len = 1 + List.length rest_rets in
let b_counter = b_counter + if ret_len > 1 then 1 else 0 in
let branch_case = LAction (vs |> List.map state_vt_to_yojson) in
match
(ret_len >= 3 && !Config.parallel, ret_len = 2 && !Config.parallel)
with
| true, _ -> (
print_endline ( Printf.sprintf " Action returned > =3 : % d " ( ! Config.act_threads + 2 ) ) ;
let pid = Unix.fork () in
match pid with
| 0 -> (
let pid = Unix.fork () in
match pid with
| 0 -> List.tl rest_confs
| _ -> [ List.hd rest_confs ])
| _ ->
[
make_confcont ~state:state'' ~callstack:cs
~invariant_frames:iframes ~prev_idx:i ~loop_ids
~next_idx:(i + 1) ~branch_count:b_counter ~branch_case
~new_branches ();
])
| false, true -> (
Can split into two threads
let b_counter = b_counter + 1 in
print_endline ( Printf.sprintf " Action returned 2 : % d " ( ! Config.act_threads + 1 ) ) ;
let pid = Unix.fork () in
match pid with
| 0 ->
[
make_confcont ~state:state'' ~callstack:cs
~invariant_frames:iframes ~prev_idx:i ~loop_ids
~next_idx:(i + 1) ~branch_count:b_counter ~branch_case
~new_branches ();
]
| _ -> rest_confs)
| _ ->
make_confcont ~state:state'' ~callstack:cs
~invariant_frames:iframes ~prev_idx:i ~loop_ids
~next_idx:(i + 1) ~branch_count:b_counter ()
:: rest_confs)
| Error errs ->
DL.log (fun m ->
m
~json:
[ ("errs", `List (List.map state_err_t_to_yojson errs)) ]
"Error");
if not (Exec_mode.concrete_exec !Config.current_exec_mode) then (
let expr_params = List.map Val.to_expr v_es in
let recovery_params =
List.concat_map Expr.base_elements expr_params
in
let recovery_params =
List.map Option.get (List.map Val.from_expr recovery_params)
in
let recovery_vals =
State.get_recovery_vals state errs @ recovery_params
in
let recovery_states : (State.t list, string) result =
State.automatic_unfold state recovery_vals
in
match recovery_states with
| Ok recovery_states ->
let b_counter =
b_counter + if List.length recovery_states = 1 then 0 else 1
in
List.mapi
(fun ix state ->
let branch_case =
if List.length recovery_states > 1 then
Some (LActionFail ix)
else None
in
let new_branches =
match (ix, recovery_states) with
| 0, _ :: rest ->
Some
(List.mapi
(fun ix state ->
(state, i, LActionFail (ix + 1)))
rest)
| _ -> None
in
make_confcont ~state ~callstack:cs
~invariant_frames:iframes ~prev_idx:prev
~loop_ids:prev_loop_ids ~next_idx:i
~branch_count:b_counter ?branch_case ?new_branches ())
recovery_states
| _ ->
let pp_err ft (a, errs) =
Fmt.pf ft "FAILURE: Action %s failed with: %a" a
(Fmt.Dump.list State.pp_err)
errs
in
Fmt.pr "%a\n@?" (Fmt.styled `Red pp_err) (a, errs);
L.normal ~title:"failure" ~severity:Error (fun m ->
m "Action call failed with:@.%a"
(Fmt.Dump.list State.pp_err)
errs);
raise (State.Internal_State_Error (errs, state)))
else
let pp_err ft (a, errs) =
Fmt.pf ft "FAILURE: Action %s failed with: %a" a
(Fmt.Dump.list State.pp_err)
errs
in
Fmt.failwith "%a\n@?" (Fmt.styled `Red pp_err) (a, errs))
Logic command
| Logic lcmd -> (
DL.log (fun m -> m "LCmd");
match lcmd with
| SL SymbExec ->
symb_exec_next := true;
[
make_confcont ~state ~callstack:cs ~invariant_frames:iframes
~prev_idx:i ~loop_ids ~next_idx:(i + 1) ~branch_count:b_counter
();
]
| SL (Invariant (a, binders)) when prev_loop_ids = loop_ids ->
let ( ) = Fmt.pr " - establishing invariant ... @ ? " in
let _ = State.unify_invariant prog true state a binders in
let () = L.verbose (fun fmt -> fmt "Invariant re-established.") in
let ( ) = Fmt.pr " \nInvariant re - established . @ ? " in
[]
| SL (Invariant (a, binders)) ->
assert (loop_action = FrameOff (List.hd loop_ids));
let ( ) = Fmt.pr " \nEstablishing invariant ... @ ? " in
let frames_and_states : (State.t * State.t) list =
State.unify_invariant prog false state a binders
in
let ( ) = Fmt.pr " established invariant . @ ? " in
List.map
(fun (frame, state) ->
let iframes = (List.hd loop_ids, frame) :: iframes in
make_confcont ~state ~callstack:cs ~invariant_frames:iframes
~prev_idx:i ~loop_ids ~next_idx:(i + 1)
~branch_count:b_counter ())
frames_and_states
| _ -> (
match evaluate_lcmd prog lcmd state with
| Ok resulting_states ->
let b_counter =
if List.length resulting_states > 1 then b_counter + 1
else b_counter
in
resulting_states
|> List.mapi (fun ix state ->
let branch_case =
if List.length resulting_states > 1 then Some (LCmd ix)
else None
in
let new_branches =
match (ix, resulting_states) with
| 0, _ :: rest ->
Some
(List.mapi
(fun ix state -> (state, i, LCmd (ix + 1)))
rest)
| _ -> None
in
make_confcont ~state ~callstack:cs
~invariant_frames:iframes ~prev_idx:i ~loop_ids
~next_idx:(i + 1) ~branch_count:b_counter ?branch_case
?new_branches ())
| Error errors ->
let errors = errors |> List.map (fun e -> ExecErr.ESt e) in
[
ConfErr
{
callstack = cs;
proc_idx = i;
error_state = state;
errors;
branch_path;
};
]))
| Goto j ->
[
make_confcont ~state ~callstack:cs ~invariant_frames:iframes
~prev_idx:i ~loop_ids ~next_idx:j ~branch_count:b_counter ();
]
| GuardedGoto (e, j, k) -> (
let vt = eval_expr e in
let lvt = Val.to_literal vt in
let vf =
match lvt with
| Some (Bool true) -> vfalse
| Some (Bool false) -> vtrue
| _ -> eval_expr (UnOp (UNot, e))
in
L.verbose (fun fmt ->
fmt "Evaluated expressions: %a, %a" Val.pp vt Val.pp vf);
let can_put_t, can_put_f =
match lvt with
| Some (Bool true) -> (true, false)
| Some (Bool false) -> (false, true)
| _ ->
let vtx = State.sat_check state vt in
let vfx =
match vtx with
| false -> true
| true -> State.sat_check state vf
in
(vtx, vfx)
in
let sp_t, sp_f =
match (can_put_t, can_put_f) with
| false, false -> ([], [])
| true, false ->
(List.map (fun x -> (x, j)) (State.assume state vt), [])
| false, true ->
([], List.map (fun x -> (x, k)) (State.assume state vf))
| true, true ->
let state_t = State.copy state in
let unfolded_trues = State.assume ~unfold:true state_t vt in
let state_f = State.copy state in
let unfolded_falses = State.assume ~unfold:true state_f vf in
let utlen, uflen =
(List.length unfolded_trues, List.length unfolded_falses)
in
if utlen = 0 || uflen = 0 || utlen + uflen = 2 then
( List.map (fun x -> (x, j)) unfolded_trues,
List.map (fun x -> (x, k)) unfolded_falses )
else
let state' = State.copy state in
( List.map (fun x -> (x, j)) (State.assume state vt),
List.map (fun x -> (x, k)) (State.assume state' vf) )
in
let sp_t = List.map (fun t -> (t, true)) sp_t in
let sp_f = List.map (fun f -> (f, false)) sp_f in
let sp = sp_t @ sp_f in
let b_counter =
if can_put_t && can_put_f && List.length sp > 1 then b_counter + 1
else b_counter
in
let result =
sp
|> List.mapi (fun j ((state, next), case) ->
make_confcont ~state
~callstack:(if j = 0 then cs else CallStack.copy cs)
~invariant_frames:iframes ~prev_idx:i ~loop_ids
~next_idx:next ~branch_count:b_counter
~branch_case:(GuardedGoto case)
~new_branches:
(if j = 0 then
List.map
(fun ((state, next), case) ->
(state, next, GuardedGoto case))
(List.tl sp)
else [])
())
in
match
List.length result = 2 && !Config.parallel
with
| true -> (
let pid = Unix.fork () in
match pid with
| 0 -> [ List.hd result ]
| _ -> List.tl result)
| false -> result)
| PhiAssignment lxarr ->
DL.log (fun m -> m "PhiAssignment");
let j = get_predecessor prog cs prev i in
let state' =
List.fold_left
(fun state (x, x_arr) ->
let e = List.nth x_arr j in
let v = eval_expr e in
update_store state x v)
state lxarr
in
[
make_confcont ~state:state' ~callstack:cs ~invariant_frames:iframes
~prev_idx:i ~loop_ids ~next_idx:(i + 1) ~branch_count:b_counter ();
]
| Call (x, e, args, j, subst) ->
DL.log (fun m -> m "Call");
let pid = eval_expr e in
let v_args = List.map eval_expr args in
let result = evaluate_procedure_call x pid v_args j subst in
result
| ECall (x, pid, args, j) ->
DL.log (fun m -> m "ECall");
let pid =
match pid with
| PVar pid -> pid
| Lit (String pid) -> pid
| _ ->
raise
(Exceptions.Impossible
"Procedure identifier not a program variable")
in
let v_args = List.map eval_expr args in
List.map
(fun (state, cs, i, j) ->
make_confcont ~state ~callstack:cs ~invariant_frames:iframes
~prev_idx:i ~loop_ids ~next_idx:j ~branch_count:b_counter ())
(External.execute prog.prog state cs i x pid v_args j)
| Apply (x, pid_args, j) -> (
DL.log (fun m -> m "Apply");
let v_pid_args = eval_expr pid_args in
let v_pid_args_list = Val.to_list v_pid_args in
match v_pid_args_list with
| Some v_pid_args_list ->
let pid = List.hd v_pid_args_list in
let v_args = List.tl v_pid_args_list in
evaluate_procedure_call x pid v_args j None
| None ->
raise
(Failure
(Fmt.str "Apply not called with a list: @[<h>%a@]" Val.pp
v_pid_args)))
| Arguments x ->
DL.log (fun m -> m "Arguments");
let args = CallStack.get_cur_args cs in
let args = Val.from_list args in
let state' = update_store state x args in
[
make_confcont ~state:state' ~callstack:cs ~invariant_frames:iframes
~prev_idx:i ~loop_ids ~next_idx:(i + 1) ~branch_count:b_counter ();
]
| ReturnNormal ->
let v_ret = Store.get store Names.return_variable in
let result =
match (v_ret, cs) with
| None, _ -> raise (Failure "nm_ret_var not in store (normal return)")
| Some v_ret, { store = None; loop_ids = start_loop_ids; _ } :: _ ->
check_loop_ids loop_ids start_loop_ids;
TODO : Redirect stdout to a file in debugging mode , as
the debug adapter communicates with VSCode via stdout . This
particular print statement currently causes issues , but
should be re - added once stdout has been redirected .
the debug adapter communicates with VSCode via stdout. This
particular print statement currently causes issues, but
should be re-added once stdout has been redirected. *)
Fmt.pr " n @ ? " ;
[
ConfFinish
{
flag = Normal;
ret_val = v_ret;
final_state = state;
branch_path;
};
]
| ( Some v_ret,
{
store = Some old_store;
loop_ids = start_loop_ids;
ret_var = x;
call_index = prev';
continue_index = j;
_;
}
:: cs' ) ->
let to_frame_on =
loop_ids_to_frame_on_at_the_end loop_ids start_loop_ids
in
let ( let+ ) x f = List.map f x in
let+ state =
if Exec_mode.verification_exec !Config.current_exec_mode then
State.frame_on state iframes to_frame_on
else [ state ]
in
let state' = State.set_store state old_store in
let state'' = update_store state' x v_ret in
make_confcont ~state:state'' ~callstack:cs'
~invariant_frames:iframes ~prev_idx:prev'
~loop_ids:start_loop_ids ~next_idx:j ~branch_count:b_counter ()
| _ -> raise (Failure "Malformed callstack")
in
L.verbose (fun m -> m "Returning.");
result
| ReturnError -> (
let v_ret = Store.get store Names.return_variable in
match (v_ret, cs) with
| None, _ ->
raise (Failure "Return variable not in store (error return) ")
| Some v_ret, { store = None; loop_ids = start_loop_ids; _ } :: _ ->
check_loop_ids loop_ids start_loop_ids;
Fmt.pr "e @?";
[
ConfFinish
{
flag = Error;
ret_val = v_ret;
final_state = state;
branch_path : branch_path;
};
]
| ( Some v_ret,
{
store = Some old_store;
loop_ids = start_loop_ids;
ret_var = x;
call_index = prev';
error_index = Some j;
_;
}
:: cs' ) ->
let to_frame_on =
loop_ids_to_frame_on_at_the_end loop_ids start_loop_ids
in
let ( let+ ) x f = List.map f x in
let+ state =
if Exec_mode.verification_exec !Config.current_exec_mode then
State.frame_on state iframes to_frame_on
else [ state ]
in
let state' = State.set_store state old_store in
let state'' = update_store state' x v_ret in
make_confcont ~state:state'' ~callstack:cs'
~invariant_frames:iframes ~prev_idx:prev' ~loop_ids:start_loop_ids
~next_idx:j ~branch_count:b_counter ()
| _ -> raise (Failure "Malformed callstack"))
| Fail (fail_code, fail_params) ->
let fail_params = List.map (State.eval_expr state) fail_params in
let err = ExecErr.EFailReached { fail_code; fail_params } in
raise (Interpreter_error ([ err ], state))
let simplify state =
snd (State.simplify ~save:true ~kill_new_lvars:true state)
let protected_evaluate_cmd
(prog : annot UP.prog)
(state : State.t)
(cs : CallStack.t)
(iframes : invariant_frames)
(prev : int)
(prev_loop_ids : string list)
(i : int)
(b_counter : int)
(report_id_ref : L.Report_id.t option ref)
(branch_path : branch_path)
(branch_case : branch_case option) : cconf_t list =
let states =
match get_cmd prog cs i with
| _, (_, LAction _) -> simplify state
| _ -> [ state ]
in
List.concat_map
(fun state ->
try
evaluate_cmd prog state cs iframes prev prev_loop_ids i b_counter
report_id_ref branch_path branch_case
with
| Interpreter_error (errors, error_state) ->
[
ConfErr
{
callstack = cs;
proc_idx = i;
error_state;
errors;
branch_path = List_utils.cons_opt branch_case branch_path;
};
]
| State.Internal_State_Error (errs, error_state) ->
[
ConfErr
{
callstack = cs;
proc_idx = i;
error_state;
errors = List.map (fun x -> ExecErr.ESt x) errs;
branch_path = List_utils.cons_opt branch_case branch_path;
};
])
states
*
Evaluates one step of a program
@param ret_fun Function to transform the results
@param prog GIL program
@param name Identifier of the procedure to be evaluated
@param params Parameters of the procedure to be evaluated
@state state Current state
@preds Current predicate set
@return Continuation function specifying the next step of evaluation
Evaluates one step of a program
@param ret_fun Function to transform the results
@param prog GIL program
@param name Identifier of the procedure to be evaluated
@param params Parameters of the procedure to be evaluated
@state state Current state
@preds preds Current predicate set
@return Continuation function specifying the next step of evaluation
*)
let rec evaluate_cmd_step
(ret_fun : result_t -> 'a)
(retry : bool)
(prog : annot UP.prog)
(hold_results : 'a list)
(on_hold : (cconf_t * string) list)
(confs : cconf_t list)
(branch_path : branch_path option)
(results : (branch_path * result_t) list) : 'a cont_func =
let f = evaluate_cmd_step ret_fun retry prog hold_results on_hold in
let parent_id_ref = ref None in
let log_confcont is_first = function
| ConfCont
{
state;
callstack;
next_idx = proc_body_index;
branch_case;
prev_cmd_report_id;
_;
} ->
let cmd_step : CmdResult.t =
{
callstack;
proc_body_index;
state = Some state;
errors = [];
branch_case;
}
in
if is_first then (
prev_cmd_report_id
|> Option.iter (fun prev_report_id ->
L.Parent.release !parent_id_ref;
L.Parent.set prev_report_id;
parent_id_ref := Some prev_report_id);
DL.log (fun m ->
m
~json:[ ("conf", CmdResult.to_yojson cmd_step) ]
"Debugger.evaluate_cmd_step: New ConfCont"));
CmdResult.log_result cmd_step |> ignore;
Some cmd_step
| _ -> None
in
let continue_or_pause rest_confs cont_func =
match rest_confs with
| ConfCont { branch_case; new_branches; branch_path; _ } :: _ ->
rest_confs
|> List.iteri (fun i conf -> log_confcont (i = 0) conf |> ignore);
let new_branch_cases =
branch_case
|> Option.map (fun branch_case ->
branch_case
:: (new_branches |> List.map (fun (_, _, case) -> case)))
in
Continue (!parent_id_ref, branch_path, new_branch_cases, cont_func)
| ConfErr
{
callstack;
proc_idx = proc_body_index;
error_state = state;
errors;
branch_path;
}
:: _ ->
CmdResult.log_result
{
callstack;
proc_body_index;
state = Some state;
errors;
branch_case = None;
}
|> ignore;
Continue (!parent_id_ref, branch_path, None, cont_func)
| _ ->
if !Config.debug then
let branch_path = Option.value branch_path ~default:[] in
Continue (!parent_id_ref, branch_path, None, cont_func)
else cont_func ()
in
Fun.protect
~finally:(fun () -> L.Parent.release !parent_id_ref)
(fun () ->
let conf, rest_confs =
match branch_path with
| None ->
DL.log (fun m ->
m "HORROR: branch_path shouldn't be None when debugging!");
List_utils.hd_tl confs
| Some branch_path ->
confs
|> List_utils.pop_where (fun conf ->
cconf_path conf = branch_path)
in
DL.log (fun m ->
let conf_json =
match conf with
| None -> `Null
| Some conf -> cconf_t_to_yojson conf
in
m
~json:
[
("conf", conf_json);
("rest_confs", `List (List.map cconf_t_to_yojson rest_confs));
]
"GInterpreter.evaluate_cmd_step: Evaluating conf");
let end_of_branch ?branch_case results =
match branch_path with
| None ->
failwith "HORROR: branch_path shouldn't be None when debugging!"
| Some branch_path -> (
match results |> List.assoc_opt branch_path with
| None ->
DL.failwith
(fun () ->
let result_jsons =
results
|> List.map (fun (path, result) ->
`Assoc
[
("path", branch_path_to_yojson path);
("result", result_t_to_yojson result);
])
in
let conf_json =
match conf with
| None -> `Null
| Some conf -> cconf_t_to_yojson conf
in
[
("branch_path", branch_path_to_yojson branch_path);
( "branch_case",
opt_to_yojson branch_case_to_yojson branch_case );
("results", `List result_jsons);
("conf", conf_json);
( "rest_confs",
`List (List.map cconf_t_to_yojson rest_confs) );
])
"No result for branch path!"
| Some result ->
EndOfBranch
(ret_fun result, fun ?path () -> f rest_confs path results))
in
match (conf, rest_confs) with
| None, _ :: _ -> end_of_branch results
| None, [] when !Config.debug -> end_of_branch results
| None, [] ->
let results =
List.map (fun (_, result) -> ret_fun result) results
in
let results = hold_results @ results in
if not retry then Finished results
else (
L.(verbose (fun m -> m "Relaunching suspended confs"));
let hold_confs =
List.filter_map
(fun (conf, pid) ->
if Hashtbl.mem prog.specs pid then Some conf else None)
on_hold
in
continue_or_pause hold_confs (fun ?path () ->
evaluate_cmd_step ret_fun false prog results [] hold_confs
path []))
| ( Some
(ConfCont
{
state;
callstack = cs;
invariant_frames = iframes;
prev_idx = prev;
loop_ids = prev_loop_ids;
next_idx = i;
branch_count = b_counter;
prev_cmd_report_id;
branch_path;
branch_case;
_;
}),
_ )
when b_counter < max_branching ->
L.set_previous prev_cmd_report_id;
let next_confs =
protected_evaluate_cmd prog state cs iframes prev prev_loop_ids i
b_counter parent_id_ref branch_path branch_case
in
continue_or_pause next_confs (fun ?path () ->
f (next_confs @ rest_confs) path results)
| ( Some
(ConfCont
{
state;
callstack = cs;
next_idx = i;
branch_count = b_counter;
prev_cmd_report_id;
branch_case;
_;
}),
_ ) ->
let _, annot_cmd = get_cmd prog cs i in
Printf.printf "WARNING: MAX BRANCHING STOP: %d.\n" b_counter;
L.set_previous prev_cmd_report_id;
L.(
verbose (fun m ->
m
"Stopping Symbolic Execution due to MAX BRANCHING with %d. \
STOPPING CONF:\n"
b_counter));
log_configuration annot_cmd state cs i b_counter branch_case
|> Option.iter (fun report_id ->
parent_id_ref := Some report_id;
L.Parent.set report_id);
continue_or_pause [] (fun ?path () -> f rest_confs path results)
| ( Some
(ConfErr
{ callstack; proc_idx; error_state; errors; branch_path }),
_ ) ->
let proc = CallStack.get_cur_proc_id callstack in
let result =
ExecRes.RFail { proc; proc_idx; error_state; errors }
in
let results = (branch_path, result) :: results in
if !Config.debug then end_of_branch results
else
continue_or_pause rest_confs (fun ?path () ->
f rest_confs path results)
| Some (ConfFinish { flag; ret_val; final_state; branch_path }), _ ->
let result =
ExecRes.RSucc
{ flag; ret_val; final_state; last_report = L.Parent.get () }
in
let results = (branch_path, result) :: results in
if !Config.debug then end_of_branch results
else
continue_or_pause rest_confs (fun ?path () ->
f rest_confs path results)
| ( Some
(ConfSusp
{
spec_id = fid;
state;
callstack;
invariant_frames;
prev_idx;
loop_ids;
next_idx;
branch_count;
branch_path;
}),
_ )
when retry ->
let conf =
make_confcont ~state ~callstack ~invariant_frames ~prev_idx
~loop_ids ~next_idx ~branch_count ~branch_path ()
in
L.(
verbose (fun m ->
m "Suspending a computation that was trying to call %s" fid));
continue_or_pause [] (fun ?path () ->
evaluate_cmd_step ret_fun retry prog hold_results
((conf, fid) :: on_hold) rest_confs path results)
| Some _, _ ->
continue_or_pause rest_confs (fun ?path () ->
f rest_confs path results))
*
Evaluates commands iteratively
@param init_func The initial continuation function which evaluates the first
step of the program
Evaluates commands iteratively
@param init_func The initial continuation function which evaluates the first
step of the program
*)
let rec evaluate_cmd_iter (init_func : 'a cont_func) : 'a list =
match init_func with
| Finished results -> results
| Continue (_, _, _, cont_func) -> evaluate_cmd_iter (cont_func ())
| EndOfBranch _ ->
failwith "HORROR: EndOfBranch encountered in continuous eval!"
*
Sets the initial values for evaluating a program , and returns a continuation
function which evaluates the first step of the program
@param ret_fun Function to transform the results
@param prog GIL program
@param name Identifier of the procedure to be evaluated
@param params Parameters of the procedure to be evaluated
@state state Current state
@preds Current predicate set
@return Continuation function which evaluates the first step of the program
Sets the initial values for evaluating a program, and returns a continuation
function which evaluates the first step of the program
@param ret_fun Function to transform the results
@param prog GIL program
@param name Identifier of the procedure to be evaluated
@param params Parameters of the procedure to be evaluated
@state state Current state
@preds preds Current predicate set
@return Continuation function which evaluates the first step of the program
*)
let init_evaluate_proc
(ret_fun : result_t -> 'a)
(prog : annot UP.prog)
(name : string)
(params : string list)
(state : State.t) : 'a cont_func =
let () = CallGraph.add_proc call_graph name in
L.normal (fun m ->
m
("*******************************************@\n"
^^ "*** Executing procedure: %s@\n"
^^ "*******************************************@\n")
name);
let store = State.get_store state in
let arguments =
List.map
(fun x ->
match Store.get store x with
| Some v_x -> v_x
| None ->
raise (Failure "Symbolic State does NOT contain formal parameter"))
params
in
let cs : CallStack.t =
CallStack.push CallStack.empty ~pid:name ~arguments ~loop_ids:[]
~ret_var:"out" ~call_index:(-1) ~continue_index:(-1) ~error_index:(-1)
()
in
let proc_body_index = 0 in
let conf : cconf_t =
make_confcont ~state ~callstack:cs ~invariant_frames:[] ~prev_idx:(-1)
~loop_ids:[] ~next_idx:proc_body_index ~branch_count:0 ~branch_path:[]
()
in
let report_id =
CmdResult.log_init
{
callstack = cs;
proc_body_index;
state = Some state;
errors = [];
branch_case = None;
}
in
Continue
( report_id,
[],
None,
fun ?path () ->
evaluate_cmd_step ret_fun true prog [] [] [ conf ] path [] )
*
Evaluation of procedures
@param prog GIL program
@param name Identifier of the procedure to be evaluated
@param params Parameters of the procedure to be evaluated
@state state Current state
@preds Current predicate set
@return List of final configurations
Evaluation of procedures
@param prog GIL program
@param name Identifier of the procedure to be evaluated
@param params Parameters of the procedure to be evaluated
@state state Current state
@preds preds Current predicate set
@return List of final configurations
*)
let evaluate_proc
(ret_fun : result_t -> 'a)
(prog : annot UP.prog)
(name : string)
(params : string list)
(state : State.t) : 'a list =
let init_func = init_evaluate_proc ret_fun prog name params state in
evaluate_cmd_iter init_func
*
Evaluation of programs
@param prog Target GIL program
@return Final configurations
Evaluation of programs
@param prog Target GIL program
@return Final configurations
*)
end
|
52853b596b74d36b460ecd140d535ecaecaf6a072e9aee1e33198534a02e39da | 0install/0install | feed_provider_impl.ml | Copyright ( C ) 2013 , the README file for details , or visit .
* See the README file for details, or visit .
*)
(** Caching feeds in memory *)
module U = Support.Utils
module Basedir = Support.Basedir
module FeedMap = Feed_url.FeedMap
(** Provides feeds to the [Impl_provider.impl_provider] during a solve. Afterwards, it can be used to
find out which feeds were used (and therefore may need updating). *)
class feed_provider config distro =
object (self : #Feed_provider.feed_provider)
val mutable cache = FeedMap.empty
val mutable distro_cache : Feed_provider.distro_impls FeedMap.t = FeedMap.empty
method get_feed url : (Feed.t * Feed_metadata.t) option =
try FeedMap.find url cache
with Not_found ->
let result =
match Feed_cache.get_cached_feed config url with
| Some feed ->
let overrides = Feed_metadata.load config url in
Some (feed, overrides)
| None -> None in
cache <- FeedMap.add url result cache;
result
method get_distro_impls feed =
let master_feed_url = Feed.url feed in
let url = `Distribution_feed master_feed_url in
try FeedMap.find master_feed_url distro_cache
with Not_found ->
let problems = ref [] in
let problem msg = problems := msg :: !problems in
let result =
let impls = Distro.get_impls_for_feed distro ~problem feed in
let overrides = Feed_metadata.load config url in
{Feed_provider.impls; overrides; problems = !problems} in
distro_cache <- FeedMap.add master_feed_url result distro_cache;
result
method get_iface_config uri =
Feed_cache.load_iface_config config uri
(* Note: excludes distro feeds *)
method get_feeds_used =
FeedMap.fold (fun uri _value lst -> uri :: lst) cache []
method was_used feed = FeedMap.mem feed cache
method have_stale_feeds =
let check url info =
match url, info with
| `Local_feed _, _ -> false
| `Remote_feed _ as url, None -> Feed_cache.internal_is_stale config url None
| `Remote_feed _ as url, Some (_feed, overrides) -> Feed_cache.internal_is_stale config url (Some overrides) in
FeedMap.exists check cache
method replace_feed url new_feed =
let overrides = Feed_metadata.load config url in
cache <- FeedMap.add url (Some (new_feed, overrides)) cache
method forget_distro url = distro_cache <- FeedMap.remove url distro_cache
(* Used after compiling a new version. *)
method forget_user_feeds iface =
let iface_config = self#get_iface_config iface in
iface_config.Feed_cache.extra_feeds |> List.iter (fun {Feed_import.src; _} ->
cache <- FeedMap.remove src cache
)
end
| null | https://raw.githubusercontent.com/0install/0install/22eebdbe51a9f46cda29eed3e9e02e37e36b2d18/src/zeroinstall/feed_provider_impl.ml | ocaml | * Caching feeds in memory
* Provides feeds to the [Impl_provider.impl_provider] during a solve. Afterwards, it can be used to
find out which feeds were used (and therefore may need updating).
Note: excludes distro feeds
Used after compiling a new version. | Copyright ( C ) 2013 , the README file for details , or visit .
* See the README file for details, or visit .
*)
module U = Support.Utils
module Basedir = Support.Basedir
module FeedMap = Feed_url.FeedMap
class feed_provider config distro =
object (self : #Feed_provider.feed_provider)
val mutable cache = FeedMap.empty
val mutable distro_cache : Feed_provider.distro_impls FeedMap.t = FeedMap.empty
method get_feed url : (Feed.t * Feed_metadata.t) option =
try FeedMap.find url cache
with Not_found ->
let result =
match Feed_cache.get_cached_feed config url with
| Some feed ->
let overrides = Feed_metadata.load config url in
Some (feed, overrides)
| None -> None in
cache <- FeedMap.add url result cache;
result
method get_distro_impls feed =
let master_feed_url = Feed.url feed in
let url = `Distribution_feed master_feed_url in
try FeedMap.find master_feed_url distro_cache
with Not_found ->
let problems = ref [] in
let problem msg = problems := msg :: !problems in
let result =
let impls = Distro.get_impls_for_feed distro ~problem feed in
let overrides = Feed_metadata.load config url in
{Feed_provider.impls; overrides; problems = !problems} in
distro_cache <- FeedMap.add master_feed_url result distro_cache;
result
method get_iface_config uri =
Feed_cache.load_iface_config config uri
method get_feeds_used =
FeedMap.fold (fun uri _value lst -> uri :: lst) cache []
method was_used feed = FeedMap.mem feed cache
method have_stale_feeds =
let check url info =
match url, info with
| `Local_feed _, _ -> false
| `Remote_feed _ as url, None -> Feed_cache.internal_is_stale config url None
| `Remote_feed _ as url, Some (_feed, overrides) -> Feed_cache.internal_is_stale config url (Some overrides) in
FeedMap.exists check cache
method replace_feed url new_feed =
let overrides = Feed_metadata.load config url in
cache <- FeedMap.add url (Some (new_feed, overrides)) cache
method forget_distro url = distro_cache <- FeedMap.remove url distro_cache
method forget_user_feeds iface =
let iface_config = self#get_iface_config iface in
iface_config.Feed_cache.extra_feeds |> List.iter (fun {Feed_import.src; _} ->
cache <- FeedMap.remove src cache
)
end
|
3b77baeac062fbab092b71188e2df6fda5d04a71de6e06d23350eabbe948658c | MaartenFaddegon/Hoed | Example4.hs | import Debug.Hoed
main = runO $ print (observe "main" $ 42 :: Int)
| null | https://raw.githubusercontent.com/MaartenFaddegon/Hoed/8769d69e309928aab439b22bc3f3dbf5452acc77/examples/Example4.hs | haskell | import Debug.Hoed
main = runO $ print (observe "main" $ 42 :: Int)
|
|
662a769feb5f07d1a8fd6872044aa94ee303b9acb321c3dec7921d121c03fab3 | tonyg/racket-font | font-render.rkt | #lang racket/base
Copyright ( c ) 2011 < >
;;
;; 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.
(require racket/match)
(require racket/class)
(require racket/draw)
(require "font.rkt")
(require "cache.rkt")
(provide glyph->path
draw-glyph
string->glyphs
glyphs->path
draw-glyphs
make-horizontal-glyph-advancer
age-font-caches!)
(define GENERATIONS 5)
(define GLYPH-CACHE (make-cache hasheq GENERATIONS))
(define (glyph->path glyph)
(cache-lookup/insert! GLYPH-CACHE glyph
(lambda ()
(define path (new dc-path%))
(for-each (lambda (instruction)
(match instruction
[(list 'move-to x y)
(send path move-to x (- y))]
[(list 'line-to x y)
(send path line-to x (- y))]
[(list 'curve-to x1 y1 x2 y2 x3 y3)
(send path curve-to x1 (- y1) x2 (- y2) x3 (- y3))]
[(list 'close-path)
(send path close)]))
(glyph-path glyph))
path)))
(define (draw-glyph glyph dc)
(send dc draw-path (glyph->path glyph)))
(define (string->glyphs face str [low 0] [high (string-length str)])
(do ((i (- high 1) (- i 1))
(glyphs '() (cons (character->glyph face (string-ref str i)) glyphs)))
((< i low) glyphs)))
(define (glyphs->path* face glyphs)
(define advancer (make-horizontal-glyph-advancer face))
(define path (new dc-path%))
(for-each (lambda (g)
(match-define (cons kx ky) (advancer g))
(send path translate (- kx) ky)
(send path append (glyph->path g))
(send path close)
(send path translate kx (- ky)))
glyphs)
path)
(define FACE-CACHE (make-cache hasheq GENERATIONS))
(define (glyphs->path face glyphs)
(define glyphs-cache (cache-lookup/insert! FACE-CACHE face
(lambda () (make-cache hasheq GENERATIONS))))
(cache-lookup/insert! glyphs-cache glyphs (lambda () (glyphs->path* face glyphs))))
;; (define cache (make-hash))
;; (define cache-accesses 0)
;; (define cache-misses 0)
;; (define bitmap-supersample 1)
;; (struct cache-entry (bitmap left top width height) #:transparent)
;; (define (draw-glyphs face glyphs size dc)
;; (define pen (send dc get-pen))
;; (define brush (send dc get-brush))
;; (define key (list (font-face-family face)
;; (font-face-style face)
;; (map glyph-number glyphs)
;; pen
;; brush))
( set ! cache - accesses ( + cache - accesses 1 ) )
;; (match-define (cache-entry bitmap left top width height)
;; (hash-ref cache key
;; (lambda ()
;; (define path (glyphs->path face glyphs))
;; (define-values (left top width height)
;; (send path get-bounding-box))
;; (define bitmap
;; (make-object bitmap%
( max 1 ( inexact->exact ( ceiling ( * width size bitmap - supersample ) ) ) )
( max 1 ( inexact->exact ( ceiling ( * height size bitmap - supersample ) ) ) )
# f # t ) )
( define bdc ( new bitmap - dc% [ bitmap bitmap ] ) )
( send bdc set - smoothing ' smoothed )
( send bdc set - pen pen )
( send bdc set - brush brush )
( send bdc set - scale ( * bitmap - supersample size ) ( * bitmap - supersample size ) )
( send bdc draw - path path ( - left ) ( - top ) )
( send bdc flush )
;; (define entry (cache-entry bitmap
;; (* bitmap-supersample size left)
;; (* bitmap-supersample size top)
;; (* bitmap-supersample size width)
;; (* bitmap-supersample size height)))
;; (hash-set! cache key entry)
( set ! cache - misses ( + cache - misses 1 ) )
;; (write `(cache count ,(hash-count cache)
;; accesses ,cache-accesses
;; hits ,(- cache-accesses cache-misses)
;; misses ,cache-misses
;; )) (newline)
;; entry)))
;; ;;(send dc set-scale (/ bitmap-supersample) (/ bitmap-supersample))
;; (send dc draw-bitmap bitmap left top)
; ; ( send dc set - scale 1 1 )
;; )
;; (define cache (make-hash))
;; (define cache-accesses 0)
;; (define cache-misses 0)
;; (define (draw-glyphs face glyphs size dc)
;; (define key (list (font-face-family face)
;; (font-face-style face)
;; (map glyph-number glyphs)))
( set ! cache - accesses ( + cache - accesses 1 ) )
;; (define path (hash-ref cache key (lambda ()
;; (define path (glyphs->path face glyphs))
;; (hash-set! cache key path)
( set ! cache - misses ( + cache - misses 1 ) )
;; (write `(cache count ,(hash-count cache)
;; accesses ,cache-accesses
;; hits ,(- cache-accesses cache-misses)
;; misses ,cache-misses
;; )) (newline)
;; path)))
;; (define-values (sx sy) (send dc get-scale))
;; (send dc set-scale size size)
;; (send dc draw-path path)
;; (send dc set-scale sx sy))
;; SIDE EFFECT: alters the scale of the dc!
(define (draw-glyphs face glyphs size dc)
(define-values (sx sy) (send dc get-scale))
(when (not (= sx sy size))
(send dc set-scale size size))
(send dc draw-path (glyphs->path face glyphs)))
;; (define (draw-glyphs face glyphs size dc)
;; (void))
(define (make-horizontal-glyph-advancer face)
(define offset 0)
(define previous-glyph #f)
(lambda (g)
(define p previous-glyph)
(set! previous-glyph g)
(match-define (cons kx ky) (if p (kerning face p g) (cons 0 0)))
(set! offset (+ offset kx))
(define rx offset)
(set! offset (+ offset (glyph-horizontal-advance g)))
(cons rx ky)))
(define (age-font-caches!)
(cache-age! GLYPH-CACHE)
(log-info "GLYPH-CACHE occupancy: ~v" (cache-stats GLYPH-CACHE))
(cache-age! FACE-CACHE)
(log-info "FACE-CACHE occupancy: ~v" (cache-stats FACE-CACHE))
(for ([(face glyphs-cache) (in-cache FACE-CACHE)])
(cache-age! glyphs-cache)
(log-info " occupancy for ~v/~v: ~v"
(font-face-family face)
(font-face-style face)
(cache-stats glyphs-cache))))
| null | https://raw.githubusercontent.com/tonyg/racket-font/ad38475a64ba09d4f483bc387812fd6e79a2e9a4/font-render.rkt | racket |
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
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.
(define cache (make-hash))
(define cache-accesses 0)
(define cache-misses 0)
(define bitmap-supersample 1)
(struct cache-entry (bitmap left top width height) #:transparent)
(define (draw-glyphs face glyphs size dc)
(define pen (send dc get-pen))
(define brush (send dc get-brush))
(define key (list (font-face-family face)
(font-face-style face)
(map glyph-number glyphs)
pen
brush))
(match-define (cache-entry bitmap left top width height)
(hash-ref cache key
(lambda ()
(define path (glyphs->path face glyphs))
(define-values (left top width height)
(send path get-bounding-box))
(define bitmap
(make-object bitmap%
(define entry (cache-entry bitmap
(* bitmap-supersample size left)
(* bitmap-supersample size top)
(* bitmap-supersample size width)
(* bitmap-supersample size height)))
(hash-set! cache key entry)
(write `(cache count ,(hash-count cache)
accesses ,cache-accesses
hits ,(- cache-accesses cache-misses)
misses ,cache-misses
)) (newline)
entry)))
;;(send dc set-scale (/ bitmap-supersample) (/ bitmap-supersample))
(send dc draw-bitmap bitmap left top)
; ( send dc set - scale 1 1 )
)
(define cache (make-hash))
(define cache-accesses 0)
(define cache-misses 0)
(define (draw-glyphs face glyphs size dc)
(define key (list (font-face-family face)
(font-face-style face)
(map glyph-number glyphs)))
(define path (hash-ref cache key (lambda ()
(define path (glyphs->path face glyphs))
(hash-set! cache key path)
(write `(cache count ,(hash-count cache)
accesses ,cache-accesses
hits ,(- cache-accesses cache-misses)
misses ,cache-misses
)) (newline)
path)))
(define-values (sx sy) (send dc get-scale))
(send dc set-scale size size)
(send dc draw-path path)
(send dc set-scale sx sy))
SIDE EFFECT: alters the scale of the dc!
(define (draw-glyphs face glyphs size dc)
(void)) | #lang racket/base
Copyright ( c ) 2011 < >
files ( the " Software " ) , to deal in the Software without
of the Software , and to permit persons to whom the Software is
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
(require racket/match)
(require racket/class)
(require racket/draw)
(require "font.rkt")
(require "cache.rkt")
(provide glyph->path
draw-glyph
string->glyphs
glyphs->path
draw-glyphs
make-horizontal-glyph-advancer
age-font-caches!)
(define GENERATIONS 5)
(define GLYPH-CACHE (make-cache hasheq GENERATIONS))
(define (glyph->path glyph)
(cache-lookup/insert! GLYPH-CACHE glyph
(lambda ()
(define path (new dc-path%))
(for-each (lambda (instruction)
(match instruction
[(list 'move-to x y)
(send path move-to x (- y))]
[(list 'line-to x y)
(send path line-to x (- y))]
[(list 'curve-to x1 y1 x2 y2 x3 y3)
(send path curve-to x1 (- y1) x2 (- y2) x3 (- y3))]
[(list 'close-path)
(send path close)]))
(glyph-path glyph))
path)))
(define (draw-glyph glyph dc)
(send dc draw-path (glyph->path glyph)))
(define (string->glyphs face str [low 0] [high (string-length str)])
(do ((i (- high 1) (- i 1))
(glyphs '() (cons (character->glyph face (string-ref str i)) glyphs)))
((< i low) glyphs)))
(define (glyphs->path* face glyphs)
(define advancer (make-horizontal-glyph-advancer face))
(define path (new dc-path%))
(for-each (lambda (g)
(match-define (cons kx ky) (advancer g))
(send path translate (- kx) ky)
(send path append (glyph->path g))
(send path close)
(send path translate kx (- ky)))
glyphs)
path)
(define FACE-CACHE (make-cache hasheq GENERATIONS))
(define (glyphs->path face glyphs)
(define glyphs-cache (cache-lookup/insert! FACE-CACHE face
(lambda () (make-cache hasheq GENERATIONS))))
(cache-lookup/insert! glyphs-cache glyphs (lambda () (glyphs->path* face glyphs))))
( set ! cache - accesses ( + cache - accesses 1 ) )
( max 1 ( inexact->exact ( ceiling ( * width size bitmap - supersample ) ) ) )
( max 1 ( inexact->exact ( ceiling ( * height size bitmap - supersample ) ) ) )
# f # t ) )
( define bdc ( new bitmap - dc% [ bitmap bitmap ] ) )
( send bdc set - smoothing ' smoothed )
( send bdc set - pen pen )
( send bdc set - brush brush )
( send bdc set - scale ( * bitmap - supersample size ) ( * bitmap - supersample size ) )
( send bdc draw - path path ( - left ) ( - top ) )
( send bdc flush )
( set ! cache - misses ( + cache - misses 1 ) )
( set ! cache - accesses ( + cache - accesses 1 ) )
( set ! cache - misses ( + cache - misses 1 ) )
(define (draw-glyphs face glyphs size dc)
(define-values (sx sy) (send dc get-scale))
(when (not (= sx sy size))
(send dc set-scale size size))
(send dc draw-path (glyphs->path face glyphs)))
(define (make-horizontal-glyph-advancer face)
(define offset 0)
(define previous-glyph #f)
(lambda (g)
(define p previous-glyph)
(set! previous-glyph g)
(match-define (cons kx ky) (if p (kerning face p g) (cons 0 0)))
(set! offset (+ offset kx))
(define rx offset)
(set! offset (+ offset (glyph-horizontal-advance g)))
(cons rx ky)))
(define (age-font-caches!)
(cache-age! GLYPH-CACHE)
(log-info "GLYPH-CACHE occupancy: ~v" (cache-stats GLYPH-CACHE))
(cache-age! FACE-CACHE)
(log-info "FACE-CACHE occupancy: ~v" (cache-stats FACE-CACHE))
(for ([(face glyphs-cache) (in-cache FACE-CACHE)])
(cache-age! glyphs-cache)
(log-info " occupancy for ~v/~v: ~v"
(font-face-family face)
(font-face-style face)
(cache-stats glyphs-cache))))
|
cb2f4b33ba64505a589bae86aa2ab7374c72a38041415878f07491bd3cc90833 | diku-dk/futhark | MapNest.hs | # LANGUAGE TypeFamilies #
module Futhark.Analysis.HORep.MapNest
( Nesting (..),
MapNest (..),
typeOf,
params,
inputs,
setInputs,
fromSOAC,
toSOAC,
)
where
import Data.List (find)
import Data.Map.Strict qualified as M
import Data.Maybe
import Futhark.Analysis.HORep.SOAC (SOAC)
import Futhark.Analysis.HORep.SOAC qualified as SOAC
import Futhark.Construct
import Futhark.IR hiding (typeOf)
import Futhark.IR.SOACS.SOAC qualified as Futhark
import Futhark.Transform.Substitute
data Nesting rep = Nesting
{ nestingParamNames :: [VName],
nestingResult :: [VName],
nestingReturnType :: [Type],
nestingWidth :: SubExp
}
deriving (Eq, Ord, Show)
data MapNest rep = MapNest SubExp (Lambda rep) [Nesting rep] [SOAC.Input]
deriving (Show)
typeOf :: MapNest rep -> [Type]
typeOf (MapNest w lam [] _) =
map (`arrayOfRow` w) $ lambdaReturnType lam
typeOf (MapNest w _ (nest : _) _) =
map (`arrayOfRow` w) $ nestingReturnType nest
params :: MapNest rep -> [VName]
params (MapNest _ lam [] _) =
map paramName $ lambdaParams lam
params (MapNest _ _ (nest : _) _) =
nestingParamNames nest
inputs :: MapNest rep -> [SOAC.Input]
inputs (MapNest _ _ _ inps) = inps
setInputs :: [SOAC.Input] -> MapNest rep -> MapNest rep
setInputs [] (MapNest w body ns _) = MapNest w body ns []
setInputs (inp : inps) (MapNest _ body ns _) = MapNest w body ns' (inp : inps)
where
w = arraySize 0 $ SOAC.inputType inp
ws = drop 1 $ arrayDims $ SOAC.inputType inp
ns' = zipWith setDepth ns ws
setDepth n nw = n {nestingWidth = nw}
fromSOAC ::
( Buildable rep,
MonadFreshNames m,
LocalScope rep m,
Op rep ~ Futhark.SOAC rep
) =>
SOAC rep ->
m (Maybe (MapNest rep))
fromSOAC = fromSOAC' mempty
fromSOAC' ::
( Buildable rep,
MonadFreshNames m,
LocalScope rep m,
Op rep ~ Futhark.SOAC rep
) =>
[Ident] ->
SOAC rep ->
m (Maybe (MapNest rep))
fromSOAC' bound (SOAC.Screma w (SOAC.ScremaForm [] [] lam) inps) = do
maybenest <- case ( stmsToList $ bodyStms $ lambdaBody lam,
bodyResult $ lambdaBody lam
) of
([Let pat _ e], res)
| map resSubExp res == map Var (patNames pat) ->
localScope (scopeOfLParams $ lambdaParams lam) $
SOAC.fromExp e
>>= either (pure . Left) (fmap (Right . fmap (pat,)) . fromSOAC' bound')
_ ->
pure $ Right Nothing
case maybenest of
-- Do we have a nested MapNest?
Right (Just (pat, mn@(MapNest inner_w body' ns' inps'))) -> do
(ps, inps'') <-
unzip
<$> fixInputs
w
(zip (map paramName $ lambdaParams lam) inps)
(zip (params mn) inps')
let n' =
Nesting
{ nestingParamNames = ps,
nestingResult = patNames pat,
nestingReturnType = typeOf mn,
nestingWidth = inner_w
}
pure $ Just $ MapNest w body' (n' : ns') inps''
-- No nested MapNest it seems.
_ -> do
let isBound name
| Just param <- find ((name ==) . identName) bound =
Just param
| otherwise =
Nothing
boundUsedInBody =
mapMaybe isBound $ namesToList $ freeIn lam
newParams <- mapM (newIdent' (++ "_wasfree")) boundUsedInBody
let subst =
M.fromList $
zip (map identName boundUsedInBody) (map identName newParams)
inps' =
inps
++ map
(SOAC.addTransform (SOAC.Replicate mempty $ Shape [w]) . SOAC.identInput)
boundUsedInBody
lam' =
lam
{ lambdaBody =
substituteNames subst $ lambdaBody lam,
lambdaParams =
lambdaParams lam
++ [Param mempty name t | Ident name t <- newParams]
}
pure $ Just $ MapNest w lam' [] inps'
where
bound' = bound <> map paramIdent (lambdaParams lam)
fromSOAC' _ _ = pure Nothing
toSOAC ::
( MonadFreshNames m,
HasScope rep m,
Buildable rep,
BuilderOps rep,
Op rep ~ Futhark.SOAC rep
) =>
MapNest rep ->
m (SOAC rep)
toSOAC (MapNest w lam [] inps) =
pure $ SOAC.Screma w (Futhark.mapSOAC lam) inps
toSOAC (MapNest w lam (Nesting npnames nres nrettype nw : ns) inps) = do
let nparams = zipWith (Param mempty) npnames $ map SOAC.inputRowType inps
body <- runBodyBuilder $
localScope (scopeOfLParams nparams) $ do
letBindNames nres
=<< SOAC.toExp
=<< toSOAC (MapNest nw lam ns $ map (SOAC.identInput . paramIdent) nparams)
pure $ resultBody $ map Var nres
let outerlam =
Lambda
{ lambdaParams = nparams,
lambdaBody = body,
lambdaReturnType = nrettype
}
pure $ SOAC.Screma w (Futhark.mapSOAC outerlam) inps
fixInputs ::
MonadFreshNames m =>
SubExp ->
[(VName, SOAC.Input)] ->
[(VName, SOAC.Input)] ->
m [(VName, SOAC.Input)]
fixInputs w ourInps = mapM inspect
where
isParam x (y, _) = x == y
inspect (_, SOAC.Input ts v _)
| Just (p, pInp) <- find (isParam v) ourInps = do
let pInp' = SOAC.transformRows ts pInp
p' <- newNameFromString $ baseString p
pure (p', pInp')
inspect (param, SOAC.Input ts a t) = do
param' <- newNameFromString (baseString param ++ "_rep")
pure (param', SOAC.Input (ts SOAC.|> SOAC.Replicate mempty (Shape [w])) a t)
| null | https://raw.githubusercontent.com/diku-dk/futhark/98e4a75e4de7042afe030837084764bbf3c6c66e/src/Futhark/Analysis/HORep/MapNest.hs | haskell | Do we have a nested MapNest?
No nested MapNest it seems. | # LANGUAGE TypeFamilies #
module Futhark.Analysis.HORep.MapNest
( Nesting (..),
MapNest (..),
typeOf,
params,
inputs,
setInputs,
fromSOAC,
toSOAC,
)
where
import Data.List (find)
import Data.Map.Strict qualified as M
import Data.Maybe
import Futhark.Analysis.HORep.SOAC (SOAC)
import Futhark.Analysis.HORep.SOAC qualified as SOAC
import Futhark.Construct
import Futhark.IR hiding (typeOf)
import Futhark.IR.SOACS.SOAC qualified as Futhark
import Futhark.Transform.Substitute
data Nesting rep = Nesting
{ nestingParamNames :: [VName],
nestingResult :: [VName],
nestingReturnType :: [Type],
nestingWidth :: SubExp
}
deriving (Eq, Ord, Show)
data MapNest rep = MapNest SubExp (Lambda rep) [Nesting rep] [SOAC.Input]
deriving (Show)
typeOf :: MapNest rep -> [Type]
typeOf (MapNest w lam [] _) =
map (`arrayOfRow` w) $ lambdaReturnType lam
typeOf (MapNest w _ (nest : _) _) =
map (`arrayOfRow` w) $ nestingReturnType nest
params :: MapNest rep -> [VName]
params (MapNest _ lam [] _) =
map paramName $ lambdaParams lam
params (MapNest _ _ (nest : _) _) =
nestingParamNames nest
inputs :: MapNest rep -> [SOAC.Input]
inputs (MapNest _ _ _ inps) = inps
setInputs :: [SOAC.Input] -> MapNest rep -> MapNest rep
setInputs [] (MapNest w body ns _) = MapNest w body ns []
setInputs (inp : inps) (MapNest _ body ns _) = MapNest w body ns' (inp : inps)
where
w = arraySize 0 $ SOAC.inputType inp
ws = drop 1 $ arrayDims $ SOAC.inputType inp
ns' = zipWith setDepth ns ws
setDepth n nw = n {nestingWidth = nw}
fromSOAC ::
( Buildable rep,
MonadFreshNames m,
LocalScope rep m,
Op rep ~ Futhark.SOAC rep
) =>
SOAC rep ->
m (Maybe (MapNest rep))
fromSOAC = fromSOAC' mempty
fromSOAC' ::
( Buildable rep,
MonadFreshNames m,
LocalScope rep m,
Op rep ~ Futhark.SOAC rep
) =>
[Ident] ->
SOAC rep ->
m (Maybe (MapNest rep))
fromSOAC' bound (SOAC.Screma w (SOAC.ScremaForm [] [] lam) inps) = do
maybenest <- case ( stmsToList $ bodyStms $ lambdaBody lam,
bodyResult $ lambdaBody lam
) of
([Let pat _ e], res)
| map resSubExp res == map Var (patNames pat) ->
localScope (scopeOfLParams $ lambdaParams lam) $
SOAC.fromExp e
>>= either (pure . Left) (fmap (Right . fmap (pat,)) . fromSOAC' bound')
_ ->
pure $ Right Nothing
case maybenest of
Right (Just (pat, mn@(MapNest inner_w body' ns' inps'))) -> do
(ps, inps'') <-
unzip
<$> fixInputs
w
(zip (map paramName $ lambdaParams lam) inps)
(zip (params mn) inps')
let n' =
Nesting
{ nestingParamNames = ps,
nestingResult = patNames pat,
nestingReturnType = typeOf mn,
nestingWidth = inner_w
}
pure $ Just $ MapNest w body' (n' : ns') inps''
_ -> do
let isBound name
| Just param <- find ((name ==) . identName) bound =
Just param
| otherwise =
Nothing
boundUsedInBody =
mapMaybe isBound $ namesToList $ freeIn lam
newParams <- mapM (newIdent' (++ "_wasfree")) boundUsedInBody
let subst =
M.fromList $
zip (map identName boundUsedInBody) (map identName newParams)
inps' =
inps
++ map
(SOAC.addTransform (SOAC.Replicate mempty $ Shape [w]) . SOAC.identInput)
boundUsedInBody
lam' =
lam
{ lambdaBody =
substituteNames subst $ lambdaBody lam,
lambdaParams =
lambdaParams lam
++ [Param mempty name t | Ident name t <- newParams]
}
pure $ Just $ MapNest w lam' [] inps'
where
bound' = bound <> map paramIdent (lambdaParams lam)
fromSOAC' _ _ = pure Nothing
toSOAC ::
( MonadFreshNames m,
HasScope rep m,
Buildable rep,
BuilderOps rep,
Op rep ~ Futhark.SOAC rep
) =>
MapNest rep ->
m (SOAC rep)
toSOAC (MapNest w lam [] inps) =
pure $ SOAC.Screma w (Futhark.mapSOAC lam) inps
toSOAC (MapNest w lam (Nesting npnames nres nrettype nw : ns) inps) = do
let nparams = zipWith (Param mempty) npnames $ map SOAC.inputRowType inps
body <- runBodyBuilder $
localScope (scopeOfLParams nparams) $ do
letBindNames nres
=<< SOAC.toExp
=<< toSOAC (MapNest nw lam ns $ map (SOAC.identInput . paramIdent) nparams)
pure $ resultBody $ map Var nres
let outerlam =
Lambda
{ lambdaParams = nparams,
lambdaBody = body,
lambdaReturnType = nrettype
}
pure $ SOAC.Screma w (Futhark.mapSOAC outerlam) inps
fixInputs ::
MonadFreshNames m =>
SubExp ->
[(VName, SOAC.Input)] ->
[(VName, SOAC.Input)] ->
m [(VName, SOAC.Input)]
fixInputs w ourInps = mapM inspect
where
isParam x (y, _) = x == y
inspect (_, SOAC.Input ts v _)
| Just (p, pInp) <- find (isParam v) ourInps = do
let pInp' = SOAC.transformRows ts pInp
p' <- newNameFromString $ baseString p
pure (p', pInp')
inspect (param, SOAC.Input ts a t) = do
param' <- newNameFromString (baseString param ++ "_rep")
pure (param', SOAC.Input (ts SOAC.|> SOAC.Replicate mempty (Shape [w])) a t)
|
db5fb6011f76bce701badd8ecfebfa7f463c6415103b486320d5ad66de0206ae | RedPRL/asai | DiagnosticEmitter.ml | module type S = DiagnosticEmitterSigs.S
module Make (Code : Code.S) : S with module Code := Code =
struct
type _ Effect.t += Emit : Code.t Diagnostic.t -> unit Effect.t
exception Fatal of Code.t Diagnostic.t
let emit d = Effect.perform @@ Emit d
let fatal d = raise @@ Fatal d
let handler ~(emit : _ -> unit) ~fatal : _ Effect.Deep.handler =
{ retc = Fun.id;
exnc = (function Fatal d -> fatal d | exn -> raise exn);
effc = fun (type a) (eff : a Effect.t) ->
match eff with
| Emit d -> Option.some @@ fun (k : (a, _) Effect.Deep.continuation) ->
Algaeff.Fun.Deep.finally k @@ fun () -> emit d
| _ -> None }
let run ~emit ~fatal f =
Effect.Deep.match_with f () @@ handler ~emit ~fatal
let try_with ?(emit=emit) ?(fatal=fatal) f =
Effect.Deep.match_with f () @@ handler ~emit ~fatal
end
| null | https://raw.githubusercontent.com/RedPRL/asai/75aa6d45af721575b7507b1bf06e0e405d6d9be0/src/core/logger/DiagnosticEmitter.ml | ocaml | module type S = DiagnosticEmitterSigs.S
module Make (Code : Code.S) : S with module Code := Code =
struct
type _ Effect.t += Emit : Code.t Diagnostic.t -> unit Effect.t
exception Fatal of Code.t Diagnostic.t
let emit d = Effect.perform @@ Emit d
let fatal d = raise @@ Fatal d
let handler ~(emit : _ -> unit) ~fatal : _ Effect.Deep.handler =
{ retc = Fun.id;
exnc = (function Fatal d -> fatal d | exn -> raise exn);
effc = fun (type a) (eff : a Effect.t) ->
match eff with
| Emit d -> Option.some @@ fun (k : (a, _) Effect.Deep.continuation) ->
Algaeff.Fun.Deep.finally k @@ fun () -> emit d
| _ -> None }
let run ~emit ~fatal f =
Effect.Deep.match_with f () @@ handler ~emit ~fatal
let try_with ?(emit=emit) ?(fatal=fatal) f =
Effect.Deep.match_with f () @@ handler ~emit ~fatal
end
|
|
349d3b1a4b604e602384f8be1684aab5c7c34c805f9128d775a1b47639bb0111 | Frechmatz/cl-synthesizer | agent.lisp | (in-package :cl-synthesizer-monitor-buffer-agent)
(defun make-symbol-impl (name num package)
(if num
(intern (format nil "~a-~a" (string-upcase name) num) package)
(intern (string-upcase name) package)))
(defun make-keyword (name num)
(make-symbol-impl name num "KEYWORD"))
(defun make-keyword-list (name count)
"Returns list of keywords ordered by number of keyword: (:<name>-1, :<name>-2, ..., <name>-<count>.
The numbering starts by one."
(let ((l nil))
(dotimes (i count)
(push (make-keyword name (+ i 1)) l))
(nreverse l)))
(defun make-buffer-module (name environment &key buffer)
(declare (ignore environment))
(let ((count (length buffer)))
(if (<= count 0)
(error
'cl-synthesizer:assembly-error
:format-control "'~a': Length of buffer must be greater than 0: '~a'"
:format-arguments (list name count)))
(let ((input-sockets (make-keyword-list
"input" count)))
(let ((inputs nil) (index 0))
(dolist (input-socket input-sockets)
(let ((cur-index index))
(push (lambda(value) (setf (aref buffer cur-index) value)) inputs)
(push input-socket inputs)
(setf index (+ 1 index))))
(list
:inputs (lambda () inputs)
:outputs (lambda () nil)
:update (lambda ()))))))
;;
;;
;;
(defun make-backend (name environment inputs &rest rest &key buffer &allow-other-keys)
"Creates a monitor backend which writes its inputs into a buffer.
<p>The function has the following parameters:
<ul>
<li>name A name.</li>
<li>environment The synthesizer environment.</li>
<li>inputs The input settings as provided by the Monitor component.</li>
<li>:buffer An array with dimension (length inputs).</li>
</ul></p>
<p>The function returns a values object consisting of
<ul>
<li>A property list that implements a module (this is the Monitor-Backend).</li>
<li>An ordered list of input sockets of the module.</li>
</ul></p>"
(declare (ignore rest))
(let ((handler (make-buffer-module name environment :buffer buffer)))
(values
handler
(make-keyword-list "input" (length inputs)))))
| null | https://raw.githubusercontent.com/Frechmatz/cl-synthesizer/7490d12f0f1e744fa1f71e014627551ebc4388c7/src/monitor/buffer/agent.lisp | lisp | (in-package :cl-synthesizer-monitor-buffer-agent)
(defun make-symbol-impl (name num package)
(if num
(intern (format nil "~a-~a" (string-upcase name) num) package)
(intern (string-upcase name) package)))
(defun make-keyword (name num)
(make-symbol-impl name num "KEYWORD"))
(defun make-keyword-list (name count)
"Returns list of keywords ordered by number of keyword: (:<name>-1, :<name>-2, ..., <name>-<count>.
The numbering starts by one."
(let ((l nil))
(dotimes (i count)
(push (make-keyword name (+ i 1)) l))
(nreverse l)))
(defun make-buffer-module (name environment &key buffer)
(declare (ignore environment))
(let ((count (length buffer)))
(if (<= count 0)
(error
'cl-synthesizer:assembly-error
:format-control "'~a': Length of buffer must be greater than 0: '~a'"
:format-arguments (list name count)))
(let ((input-sockets (make-keyword-list
"input" count)))
(let ((inputs nil) (index 0))
(dolist (input-socket input-sockets)
(let ((cur-index index))
(push (lambda(value) (setf (aref buffer cur-index) value)) inputs)
(push input-socket inputs)
(setf index (+ 1 index))))
(list
:inputs (lambda () inputs)
:outputs (lambda () nil)
:update (lambda ()))))))
(defun make-backend (name environment inputs &rest rest &key buffer &allow-other-keys)
"Creates a monitor backend which writes its inputs into a buffer.
<p>The function has the following parameters:
<ul>
<li>name A name.</li>
<li>environment The synthesizer environment.</li>
<li>inputs The input settings as provided by the Monitor component.</li>
<li>:buffer An array with dimension (length inputs).</li>
</ul></p>
<p>The function returns a values object consisting of
<ul>
<li>A property list that implements a module (this is the Monitor-Backend).</li>
<li>An ordered list of input sockets of the module.</li>
</ul></p>"
(declare (ignore rest))
(let ((handler (make-buffer-module name environment :buffer buffer)))
(values
handler
(make-keyword-list "input" (length inputs)))))
|
|
ffb18c2b70309320f715eb130ad5f7864a9fbc7b37d94b0c5e5b176284aa1f8b | stchang/macrotypes | typed-rackunit-typechecking.rkt | #lang racket/base
;; this file is a copy of rackunit/turnstile,
;; except it uses typed/rackunit instead of rackunit
;; TODO: can this be avoided?
(provide check-type typecheck-fail)
(require (for-syntax rackunit syntax/srcloc racket/pretty racket/string)
typed/rackunit macrotypes/typecheck-core
(only-in macrotypes/typecheck infer+erase))
(define-syntax (check-type stx)
(syntax-parse stx
[(_ e tag:id τ-expected)
#:with τ-expected+ ((current-type-eval) #'τ-expected)
#:with (e+ τ) (infer+erase #'(add-expected e τ-expected+) #:tag (stx->datum #'tag))
#:fail-unless (typecheck? #'τ #'τ-expected+)
(format
"Expression ~a [loc ~a:~a] has type ~a, expected ~a"
(syntax->datum #'e) (syntax-line #'e) (syntax-column #'e)
(type->str #'τ) (type->str #'τ-expected))
;; count this test case in the test count
(syntax/loc stx (check-true #t))]))
(define-syntax (typecheck-fail stx)
(syntax-parse stx #:datum-literals (:)
[(_ e (~or
(~optional (~seq #:with-msg msg-pat) #:defaults ([msg-pat #'""]))
(~optional (~seq #:verb-msg vmsg) #:defaults ([vmsg #'""]))))
#:with msg:str
(if (attribute msg-pat)
(eval-syntax (datum->stx #'h (stx->datum #'msg-pat)))
(eval-syntax (datum->stx #'h `(add-escs ,(stx->datum #'vmsg)))))
#:when (with-check-info*
(list (make-check-expected (syntax-e #'msg))
(make-check-expression (syntax->datum stx))
(make-check-location (build-source-location-list stx))
(make-check-name 'typecheck-fail)
(make-check-params (list (syntax->datum #'e) (syntax-e #'msg))))
(λ ()
(check-exn
(λ (ex)
(and (or (exn:fail? ex) (exn:test:check? ex))
; check err msg matches
(regexp-match? (syntax-e #'msg) (exn-message ex))))
(λ ()
(expand/df #'e)))))
;; count this test case in the test count
(syntax/loc stx (check-true #t))]))
| null | https://raw.githubusercontent.com/stchang/macrotypes/05ec31f2e1fe0ddd653211e041e06c6c8071ffa6/turnstile-test/tests/turnstile/typed-rackunit-typechecking.rkt | racket | this file is a copy of rackunit/turnstile,
except it uses typed/rackunit instead of rackunit
TODO: can this be avoided?
count this test case in the test count
check err msg matches
count this test case in the test count | #lang racket/base
(provide check-type typecheck-fail)
(require (for-syntax rackunit syntax/srcloc racket/pretty racket/string)
typed/rackunit macrotypes/typecheck-core
(only-in macrotypes/typecheck infer+erase))
(define-syntax (check-type stx)
(syntax-parse stx
[(_ e tag:id τ-expected)
#:with τ-expected+ ((current-type-eval) #'τ-expected)
#:with (e+ τ) (infer+erase #'(add-expected e τ-expected+) #:tag (stx->datum #'tag))
#:fail-unless (typecheck? #'τ #'τ-expected+)
(format
"Expression ~a [loc ~a:~a] has type ~a, expected ~a"
(syntax->datum #'e) (syntax-line #'e) (syntax-column #'e)
(type->str #'τ) (type->str #'τ-expected))
(syntax/loc stx (check-true #t))]))
(define-syntax (typecheck-fail stx)
(syntax-parse stx #:datum-literals (:)
[(_ e (~or
(~optional (~seq #:with-msg msg-pat) #:defaults ([msg-pat #'""]))
(~optional (~seq #:verb-msg vmsg) #:defaults ([vmsg #'""]))))
#:with msg:str
(if (attribute msg-pat)
(eval-syntax (datum->stx #'h (stx->datum #'msg-pat)))
(eval-syntax (datum->stx #'h `(add-escs ,(stx->datum #'vmsg)))))
#:when (with-check-info*
(list (make-check-expected (syntax-e #'msg))
(make-check-expression (syntax->datum stx))
(make-check-location (build-source-location-list stx))
(make-check-name 'typecheck-fail)
(make-check-params (list (syntax->datum #'e) (syntax-e #'msg))))
(λ ()
(check-exn
(λ (ex)
(and (or (exn:fail? ex) (exn:test:check? ex))
(regexp-match? (syntax-e #'msg) (exn-message ex))))
(λ ()
(expand/df #'e)))))
(syntax/loc stx (check-true #t))]))
|
14065bf1bbf5618dd00485a4e214f6f12eff81aa6e3b60f5cbc4d64bea8f032b | robdockins/edison | EnumSet.hs | -----------------------------------------------------------------------------
-- |
Module : Data . Edison . . EnumSet
Copyright : ( c ) 2006
License : BSD
--
Maintainer : robdockins AT fastmail DOT fm
-- Stability : stable
Portability : GHC , Hugs ( MPTC and FD )
--
-- An efficient implementation of sets over small enumerations.
The implementation of ' EnumSet ' is based on bit - wise operations .
--
-- For this implementation to work as expected at type @A@, there are a number
of preconditions on the @Eq@ , @Enum@ and @Ord@ instances .
--
The @Enum A@ instance must create a bijection between the elements of type and
-- a finite subset of the naturals [0,1,2,3....]. As a corollary we must have:
--
-- > forall x y::A, fromEnum x == fromEnum y <==> x is indistinguishable from y
--
Also , the number of distinct elements of must be less than or equal
to the number of bits in @Word@.
--
-- The @Enum A@ instance must be consistent with the @Eq A@ instance.
-- That is, we must have:
--
-- > forall x y::A, x == y <==> toEnum x == toEnum y
--
-- Additionally, for operations that require an @Ord A@ context, we require that
-- toEnum be monotonic with respect to comparison. That is, we must have:
--
-- > forall x y::A, x < y <==> toEnum x < toEnum y
--
Derived @Eq@ , @Ord@ and @Enum@ instances will fulfill these conditions , if
-- the enumerated type has sufficently few constructors.
Copyright ( c ) 2006 , 2008 ,
All rights reserved .
Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are
met :
* Redistributions of source code must retain the above copyright
notice , this list of conditions and the following disclaimer .
* Redistributions in binary form must reproduce the above copyright
notice , this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution .
* Neither the name of nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission .
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
Copyright (c) 2006, 2008, David F. Place
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of David F. Place nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Data.Edison.Coll.EnumSet (
-- * Set type
Set
* CollX operations
, empty
, singleton
, fromSeq
, insert
, insertSeq
, union
, unionSeq
, delete
, deleteAll
, deleteSeq
, null
, size
, member
, count
, strict
-- * OrdCollX operations
, deleteMin
, deleteMax
, unsafeInsertMin
, unsafeInsertMax
, unsafeFromOrdSeq
, unsafeAppend
, filterLT
, filterLE
, filterGT
, filterGE
, partitionLT_GE
, partitionLE_GT
, partitionLT_GT
-- * SetX operations
, intersection
, difference
, symmetricDifference
, properSubset
, subset
-- * Coll operations
, toSeq
, lookup
, lookupM
, lookupAll
, lookupWithDefault
, fold, fold', fold1, fold1'
, filter
, partition
, strictWith
* OrdColl operations
, minView
, minElem
, maxView
, maxElem
, foldr, foldr', foldl, foldl'
, foldr1, foldr1', foldl1, foldl1'
, toOrdSeq
, unsafeMapMonotonic
-- * Set operations
, fromSeqWith
, fromOrdSeq
, insertWith
, insertSeqWith
, unionl
, unionr
, unionWith
, unionSeqWith
, intersectionWith
-- * Bonus operations
, map
, setCoerce
, complement
, toBits
, fromBits
-- * Documenation
, moduleName
) where
import qualified Prelude
import Prelude hiding (filter,foldl,foldr,null,map,lookup,foldl1,foldr1)
import qualified Control.Monad.Fail as Fail
import qualified Data.Bits as Bits
import Data.Bits hiding (complement)
import Data.Word
import Data.Monoid (Monoid(..))
import Data.Semigroup as SG
import qualified Data.Edison.Seq as S
import qualified Data.Edison.Coll as C
import Data.Edison.Coll.Defaults
import Test.QuickCheck (Arbitrary(..), CoArbitrary(..))
moduleName :: String
moduleName = "Data.Edison.Coll.EnumSet"
-------------------------------------------------------------------
Sets are bit strings of width wordLength .
-------------------------------------------------------------------
Sets are bit strings of width wordLength.
--------------------------------------------------------------------}
-- | A set of values @a@ implemented as bitwise operations. Useful
for members of class with no more elements than there are bits
in @Word@.
newtype Set a = Set Word deriving (Eq)
wordLength :: Int
wordLength =
#if MIN_VERSION_base(4,7,0)
finiteBitSize
#else
bitSize
#endif
(0::Word)
check :: String -> Int -> Int
check msg x
| x < wordLength = x
| otherwise = error $ "EnumSet."++msg++": element beyond word size."
-- no interesting structural invariants
structuralInvariant :: Set a -> Bool
structuralInvariant = const True
----------------------------------------------------
-- bit twiddly magic
countBits :: Word -> Int
countBits w = w `seq` bitcount 0 w
bitcount :: Int -> Word -> Int
bitcount a 0 = a
bitcount a x = a `seq` bitcount (a+1) (x .&. (x-1))
-- stolen from /
lsb :: Word -> Int
lsb x = countBits ((x-1) .&. (Bits.complement x))
msb :: Word -> Int
msb x0 = let
x1 = x0 .|. (x0 `shiftR` 1)
x2 = x1 .|. (x1 `shiftR` 2)
x3 = x2 .|. (x2 `shiftR` 4)
x4 = x3 .|. (x3 `shiftR` 8)
x5 = x4 .|. (x4 `shiftR` 16)
in countBits x5 - 1
lowMask :: Int -> Word
lowMask x = bit x - 1
highMask :: Int -> Word
highMask x = Bits.complement (lowMask x)
{--------------------------------------------------------------------
Query
--------------------------------------------------------------------}
-- | /O(1)/. Is this the empty set?
null :: Set a -> Bool
null (Set 0) = True
null _ = False
-- | /O(1)/. The number of elements in the set.
size :: Set a -> Int
size (Set w) = countBits w
-- | /O(1)/. Is the element in the set?
member :: (Eq a, Enum a) => a -> Set a -> Bool
member x (Set w) = testBit w $ fromEnum x
count :: (Eq a, Enum a) => a -> Set a -> Int
count = countUsingMember
lookup :: (Eq a, Enum a) => a -> Set a -> a
lookup = lookupUsingLookupAll
lookupM :: (Eq a, Enum a, Fail.MonadFail m) => a -> Set a -> m a
lookupM x s
| member x s = return x
| otherwise = fail (moduleName++".lookupM: lookup failed")
lookupAll :: (Eq a, Enum a, S.Sequence s) => a -> Set a -> s a
lookupAll = lookupAllUsingLookupM
lookupWithDefault :: (Eq a, Enum a) => a -> a -> Set a -> a
lookupWithDefault = lookupWithDefaultUsingLookupM
{--------------------------------------------------------------------
Construction
--------------------------------------------------------------------}
-- | /O(1)/. The empty set.
empty :: Set a
empty = Set 0
-- | /O(1)/. Create a singleton set.
singleton :: (Eq a, Enum a) => a -> Set a
singleton x =
Set $ setBit 0 $ check "singleton" $ fromEnum x
{--------------------------------------------------------------------
Insertion, Deletion
--------------------------------------------------------------------}
-- | /O(1)/. Insert an element in a set.
-- If the set already contains an element equal to the given value,
-- it is replaced with the new value.
insert :: (Eq a, Enum a) => a -> Set a -> Set a
insert x (Set w) =
Set $ setBit w $ check "insert" $ fromEnum x
-- given the preconditions, we can just ignore the combining function
insertWith :: (Eq a, Enum a) => (a -> a -> a) -> a -> Set a -> Set a
insertWith _ x (Set w) =
Set $ setBit w $ check "insertWith" $ fromEnum x
-- | /O(1)/. Delete an element from a set.
delete :: (Eq a, Enum a) => a -> Set a -> Set a
delete x (Set w) =
Set $ clearBit w $ fromEnum x
deleteAll :: (Eq a, Enum a) => a -> Set a -> Set a
deleteAll = delete
deleteSeq :: (Eq a, Enum a, S.Sequence s) => s a -> Set a -> Set a
deleteSeq = deleteSeqUsingDelete
{--------------------------------------------------------------------
Subset
--------------------------------------------------------------------}
-- | /O(1)/. Is this a proper subset? (ie. a subset but not equal).
properSubset :: Set a -> Set a -> Bool
properSubset x y = (x /= y) && (subset x y)
-- | /O(1)/. Is this a subset?
@(s1 ` subset ` tells whether @s1@ is a subset of @s2@.
subset :: Set a -> Set a -> Bool
subset x y = (x `union` y) == y
-------------------------------------------------------------------
Minimal , Maximal
-------------------------------------------------------------------
Minimal, Maximal
--------------------------------------------------------------------}
-- | /O(1)/. The minimal element of a set.
minElem :: (Enum a) => Set a -> a
minElem (Set w)
| w == 0 = error $ moduleName++".minElem: empty set"
| otherwise = toEnum $ lsb w
-- | /O(1)/. The maximal element of a set.
maxElem :: (Enum a) => Set a -> a
maxElem (Set w)
| w == 0 = error $ moduleName++".maxElem: empty set"
| otherwise = toEnum $ msb w
-- | /O(1)/. Delete the minimal element.
deleteMin :: (Enum a) => Set a -> Set a
deleteMin (Set w)
| w == 0 = empty
| otherwise = Set $ clearBit w $ lsb w
-- | /O(1)/. Delete the maximal element.
deleteMax :: (Enum a) => Set a -> Set a
deleteMax (Set w)
| w == 0 = empty
| otherwise = Set $ clearBit w $ msb w
minView :: (Enum a, Fail.MonadFail m) => Set a -> m (a, Set a)
minView (Set w)
| w == 0 = fail (moduleName++".minView: empty set")
| otherwise = let i = lsb w in return (toEnum i,Set $ clearBit w i)
maxView :: (Enum a, Fail.MonadFail m) => Set a -> m (a, Set a)
maxView (Set w)
| w == 0 = fail (moduleName++".maxView: empty set")
| otherwise = let i = msb w in return (toEnum i, Set $ clearBit w i)
unsafeInsertMin :: (Ord a, Enum a) => a -> Set a -> Set a
unsafeInsertMin = insert
unsafeInsertMax :: (Ord a, Enum a) => a -> Set a -> Set a
unsafeInsertMax = insert
unsafeAppend :: (Ord a, Enum a) => Set a -> Set a -> Set a
unsafeAppend = union
unsafeFromOrdSeq :: (Ord a, Enum a, S.Sequence s) => s a -> Set a
unsafeFromOrdSeq = fromSeq
filterLT :: (Ord a, Enum a) => a -> Set a -> Set a
filterLT x (Set w) = Set (w .&. lowMask (fromEnum x))
filterLE :: (Ord a, Enum a) => a -> Set a -> Set a
filterLE x (Set w) = Set (w .&. lowMask (fromEnum x + 1))
filterGT :: (Ord a, Enum a) => a -> Set a -> Set a
filterGT x (Set w) = Set (w .&. highMask (fromEnum x + 1))
filterGE :: (Ord a, Enum a) => a -> Set a -> Set a
filterGE x (Set w) = Set (w .&. highMask (fromEnum x))
partitionLT_GE :: (Ord a, Enum a) => a -> Set a -> (Set a, Set a)
partitionLT_GE x s = (filterLT x s,filterGE x s)
partitionLE_GT :: (Ord a, Enum a) => a -> Set a -> (Set a, Set a)
partitionLE_GT x s = (filterLE x s,filterGT x s)
partitionLT_GT :: (Ord a, Enum a) => a -> Set a -> (Set a, Set a)
partitionLT_GT x s = (filterLT x s,filterGT x s)
{--------------------------------------------------------------------
Union.
--------------------------------------------------------------------}
-- | The union of a list of sets: (@'unions' == 'foldl' 'union' 'empty'@).
unionSeq :: (Eq a, Enum a, S.Sequence s) => s (Set a) -> Set a
unionSeq = unionSeqUsingFoldl'
| /O(1)/. The union of two sets .
union :: Set a -> Set a -> Set a
union (Set x) (Set y) = Set $ x .|. y
unionl :: Set a -> Set a -> Set a
unionl = union
unionr :: Set a -> Set a -> Set a
unionr = union
-- given the preconditions, we can just ignore the combining function
unionWith :: (a -> a -> a) -> Set a -> Set a -> Set a
unionWith _ = union
unionSeqWith :: (Eq a, Enum a, S.Sequence s) => (a -> a -> a) -> s (Set a) -> Set a
unionSeqWith _ = unionSeq
{--------------------------------------------------------------------
Difference
--------------------------------------------------------------------}
| /O(1)/. Difference of two sets .
difference :: Set a -> Set a -> Set a
difference (Set x) (Set y) = Set $ (x .|. y) `xor` y
symmetricDifference :: Set a -> Set a -> Set a
symmetricDifference (Set x) (Set y) = Set $ x `xor` y
{--------------------------------------------------------------------
Intersection
--------------------------------------------------------------------}
| /O(1)/. The intersection of two sets .
intersection :: Set a -> Set a -> Set a
intersection (Set x) (Set y) = Set $ x .&. y
intersectionWith :: (a -> a -> a) -> Set a -> Set a -> Set a
intersectionWith _ = intersection
{--------------------------------------------------------------------
Complement
--------------------------------------------------------------------}
-- | /O(1)/. The complement of a set with its universe set. @complement@ can be used
-- with bounded types for which the universe set
-- will be automatically created.
complement :: (Eq a, Bounded a, Enum a) => Set a -> Set a
complement x = symmetricDifference u x
where u = (fromSeq [minBound .. maxBound]) `asTypeOf` x
{--------------------------------------------------------------------
Filter and partition
--------------------------------------------------------------------}
-- | /O(n)/. Filter all elements that satisfy the predicate.
filter :: (Eq a, Enum a) => (a -> Bool) -> Set a -> Set a
filter p (Set w) = Set $ foldlBits' f 0 w
where
f z i
| p $ toEnum i = setBit z i
| otherwise = z
| /O(n)/. Partition the set into two sets , one with all elements that satisfy
-- the predicate and one with all elements that don't satisfy the predicate.
-- See also 'split'.
partition :: (Eq a, Enum a) => (a -> Bool) -> Set a -> (Set a,Set a)
partition p (Set w) = (Set yay,Set nay)
where
(yay,nay) = foldlBits' f (0,0) w
f (x,y) i
| p $ toEnum i = (setBit x i,y)
| otherwise = (x,setBit y i)
{----------------------------------------------------------------------
Map
----------------------------------------------------------------------}
-- | /O(n)/.
@'map ' f s@ is the set obtained by applying @f@ to each element of @s@.
--
-- It's worth noting that the size of the result may be smaller if,
for some @(x , y)@ , @x \/= y & & f x = = f y@
map :: (Enum a,Enum b) => (a -> b) -> Set a -> Set b
map f0 (Set w) = Set $ foldlBits' f 0 w
where
f z i = setBit z $ check "map" $ fromEnum $ f0 (toEnum i)
unsafeMapMonotonic :: (Enum a) => (a -> a) -> Set a -> Set a
unsafeMapMonotonic = map
-- | /O(1)/ Changes the type of the elements in the set without changing
-- the representation. Equivalant to @map (toEnum . fromEnum)@, and
to @(fromBits . toBits)@. This method is operationally a no - op .
setCoerce :: (Enum a, Enum b) => Set a -> Set b
setCoerce (Set w) = Set w
-- | /O(1)/ Get the underlying bit-encoded representation.
-- This method is operationally a no-op.
toBits :: Set a -> Word
toBits (Set w) = w
| /O(1)/ Create an EnumSet from a bit - encoded representation .
-- This method is operationally a no-op.
fromBits :: Word -> Set a
fromBits w = Set w
-------------------------------------------------------------------
Fold
-------------------------------------------------------------------
Fold
--------------------------------------------------------------------}
fold :: (Eq a, Enum a) => (a -> c -> c) -> c -> Set a -> c
fold f z (Set w) = foldrBits folder z w
where folder i = f (toEnum i)
fold' :: (Eq a, Enum a) => (a -> c -> c) -> c -> Set a -> c
fold' f z (Set w) = foldrBits' folder z w
where folder i = f (toEnum i)
fold1 :: (Eq a, Enum a) => (a -> a -> a) -> Set a -> a
fold1 _ (Set 0) = error (moduleName++".fold1: empty set")
fold1 f (Set w) = foldrBits folder (toEnum maxi) (clearBit w maxi)
where
maxi = msb w
folder i z = f (toEnum i) z
fold1' :: (Eq a, Enum a) => (a -> a -> a) -> Set a -> a
fold1' _ (Set 0) = error (moduleName++".fold1': empty set")
fold1' f (Set w) = foldrBits folder (toEnum maxi) (clearBit w maxi)
where
maxi = msb w
folder i z = f (toEnum i) z
foldr :: (Ord a, Enum a) => (a -> b -> b) -> b -> Set a -> b
foldr f z (Set w) = foldrBits folder z w
where folder i = f (toEnum i)
foldr' :: (Ord a, Enum a) => (a -> b -> b) -> b -> Set a -> b
foldr' f z (Set w) = foldrBits' folder z w
where folder i j = f (toEnum i) j
foldr1 :: (Ord a, Enum a) => (a -> a -> a) -> Set a -> a
foldr1 _ (Set 0) = error (moduleName ++ ".foldr1: empty set")
foldr1 f (Set w) = foldrBits folder (toEnum maxi) (clearBit w maxi)
where
maxi = msb w
folder i z = f (toEnum i) z
foldr1' :: (Ord a, Enum a) => (a -> a -> a) -> Set a -> a
foldr1' _ (Set 0) = error (moduleName++".foldr1': empty set")
foldr1' f (Set w) = foldrBits folder (toEnum maxi) (clearBit w maxi)
where
maxi = msb w
folder i z = f (toEnum i) z
foldl :: (Ord a, Enum a) => (c -> a -> c) -> c -> Set a -> c
foldl f z (Set w) = foldlBits folder z w
where folder h i = f h (toEnum i)
foldl' :: (Ord a, Enum a) => (c -> a -> c) -> c -> Set a -> c
foldl' f z (Set w) = foldlBits' folder z w
where folder h i = f h (toEnum i)
foldl1 :: (Ord a, Enum a) => (a -> a -> a) -> Set a -> a
foldl1 _ (Set 0) = error (moduleName++".foldl1: empty set")
foldl1 f (Set w) = foldlBits folder (toEnum mininum) (clearBit w mininum)
where
mininum = lsb w
folder z i = f z (toEnum i)
foldl1' :: (Ord a, Enum a) => (a -> a -> a) -> Set a -> a
foldl1' _ (Set 0) = error (moduleName++".foldl1': empty set")
foldl1' f (Set w) = foldlBits' folder (toEnum mininum) (clearBit w mininum)
where
mininum = lsb w
folder z i = f z (toEnum i)
{--------------------------------------------------------------------
Lists
--------------------------------------------------------------------}
fromSeq :: (Eq a, Enum a, S.Sequence s) => s a -> Set a
fromSeq xs = Set $ S.fold' f 0 xs
where f x z = setBit z $ check "fromSeq" $ fromEnum x
fromOrdSeq :: (Ord a, Enum a, S.Sequence s) => s a -> Set a
fromOrdSeq = fromSeq
insertSeq :: (Eq a, Enum a, S.Sequence s) => s a -> Set a -> Set a
insertSeq = insertSeqUsingUnion
-- given the preconditions, we can just ignore the combining function
insertSeqWith :: (Eq a, Enum a, S.Sequence s) => (a -> a -> a) -> s a -> Set a -> Set a
insertSeqWith _ = insertSeq
toSeq :: (Eq a, Enum a, S.Sequence s) => Set a -> s a
toSeq (Set w) = foldrBits f S.empty w
where f i z = S.lcons (toEnum i) z
toOrdSeq :: (Ord a, Enum a, S.Sequence s) => Set a -> s a
toOrdSeq = toSeq
fromSeqWith :: (Eq a, Enum a, S.Sequence s) => (a -> a -> a) -> s a -> Set a
fromSeqWith = fromSeqWithUsingInsertWith
{--------------------------------------------------------------------
Split
--------------------------------------------------------------------}
splitMember : : ( a , a ) = > a - > Set a - > ( Set a , , Set a )
( Set w ) = ( Set lesser , isMember , Set greater )
where
( lesser , isMember , greater ) = foldrBits f ( 0,False,0 ) w
f i ( lesser , isMember , greater ) =
case compare ( toEnum i ) x of
GT - > ( lesser , isMember , setBit greater i )
LT - > ( setBit lesser i , , greater )
EQ - > ( lesser , True , greater )
splitMember :: (Ord a, Enum a) => a -> Set a -> (Set a,Bool,Set a)
splitMember x (Set w) = (Set lesser,isMember,Set greater)
where
(lesser,isMember,greater) = foldrBits f (0,False,0) w
f i (lesser,isMember,greater) =
case compare (toEnum i) x of
GT -> (lesser,isMember,setBit greater i)
LT -> (setBit lesser i,isMember,greater)
EQ -> (lesser,True,greater)
-}
---------------------------------------------------------------
Strictness enhancement
---------------------------------------------------------------
Strictness enhancement
----------------------------------------------------------------}
strict :: Set a -> Set a
strict s@(Set w) = w `seq` s
strictWith :: (a -> b) -> Set a -> Set a
strictWith _ s@(Set w) = w `seq` s
{--------------------------------------------------------------------
Utility functions.
--------------------------------------------------------------------}
foldrBits :: (Int -> a -> a) -> a -> Word -> a
foldrBits f z w = foldrBits_aux f z 0 w
foldrBits_aux :: (Int -> a -> a) -> a -> Int -> Word -> a
foldrBits_aux _ z _ 0 = z
foldrBits_aux f z i w
| i `seq` w `seq` False = undefined
| otherwise =
case w .&. 0x0F of
0x00 -> a
0x01 -> f i $ a
0x02 -> f (i+1) $ a
0x03 -> f i $ f (i+1) $ a
0x04 -> f (i+2) $ a
0x05 -> f i $ f (i+2) $ a
0x06 -> f (i+1) $ f (i+2) $ a
0x07 -> f i $ f (i+1) $ f (i+2) $ a
0x08 -> f (i+3) $ a
0x09 -> f i $ f (i+3) $ a
0x0A -> f (i+1) $ f (i+3) $ a
0x0B -> f i $ f (i+1) $ f (i+3) $ a
0x0C -> f (i+2) $ f (i+3) $ a
0x0D -> f i $ f (i+2) $ f (i+3) $ a
0x0E -> f (i+1) $ f (i+2) $ f (i+3) $ a
0x0F -> f i $ f (i+1) $ f (i+2) $ f (i+3) $ a
_ -> error "bug in foldrBits_aux"
where a = foldrBits_aux f z (i+4) (Bits.shiftR w 4)
foldrBits' :: (Int -> a -> a) -> a -> Word -> a
foldrBits' f z w = foldrBits_aux' f z 0 w
foldrBits_aux' :: (Int -> a -> a) -> a -> Int -> Word -> a
foldrBits_aux' _ z _ 0 = z
foldrBits_aux' f z i w
| i `seq` w `seq` False = undefined
| otherwise =
case w .&. 0x0F of
0x00 -> a
0x01 -> f i $! a
0x02 -> f (i+1) $! a
0x03 -> f i $! f (i+1) $! a
0x04 -> f (i+2) $! a
0x05 -> f i $! f (i+2) $! a
0x06 -> f (i+1) $! f (i+2) $! a
0x07 -> f i $! f (i+1) $! f (i+2) $! a
0x08 -> f (i+3) $! a
0x09 -> f i $! f (i+3) $! a
0x0A -> f (i+1) $! f (i+3) $! a
0x0B -> f i $! f (i+1) $! f (i+3) $! a
0x0C -> f (i+2) $! f (i+3) $! a
0x0D -> f i $! f (i+2) $! f (i+3) $! a
0x0E -> f (i+1) $! f (i+2) $! f (i+3) $! a
0x0F -> f i $! f (i+1) $! f (i+2) $! f (i+3) $! a
_ -> error "bug in foldrBits_aux'"
where a = foldrBits_aux' f z (i+4) (Bits.shiftR w 4)
foldlBits :: (a -> Int -> a) -> a -> Word -> a
foldlBits f z w = foldlBits_aux f z 0 w
foldlBits_aux :: (a -> Int -> a) -> a -> Int -> Word -> a
foldlBits_aux _ z _ 0 = z
foldlBits_aux f z i w
| i `seq` w `seq` False = undefined
| otherwise =
case w .&. 0x0F of
0x00 -> a $ z
0x01 -> a $ f z i
0x02 -> a $ f z (i+1)
0x03 -> a $ f (f z i) (i+1)
0x04 -> a $ f z (i+2)
0x05 -> a $ f (f z i) (i+2)
0x06 -> a $ f (f z (i+1)) (i+2)
0x07 -> a $ f (f (f z i) (i+1)) (i+2)
0x08 -> a $ f z (i+3)
0x09 -> a $ f (f z i) (i+3)
0x0A -> a $ f (f z (i+1)) (i+3)
0x0B -> a $ f (f (f z i) (i+1)) (i+3)
0x0C -> a $ f (f z (i+2)) (i+3)
0x0D -> a $ f (f (f z i) (i+2)) (i+3)
0x0E -> a $ f (f (f z (i+1)) (i+2)) (i+3)
0x0F -> a $ f (f (f (f z i) (i+1)) (i+2)) (i+3)
_ -> error "bug in foldlBits_aux"
where a b = foldlBits_aux f b (i + 4) (Bits.shiftR w 4)
foldlBits' :: (a -> Int -> a) -> a -> Word -> a
foldlBits' f z w = foldlBits_aux' (\x i -> x `seq` f x i) z 0 w
foldlBits_aux' :: (a -> Int -> a) -> a -> Int -> Word -> a
foldlBits_aux' _ z _ 0 = z
foldlBits_aux' f z i w
| i `seq` w `seq` False = undefined
| otherwise =
case w .&. 0x0F of
0x00 -> a $! z
0x01 -> a $! f z i
0x02 -> a $! f z (i+1)
0x03 -> a $! f (f z i) (i+1)
0x04 -> a $! f z (i+2)
0x05 -> a $! f (f z i) (i+2)
0x06 -> a $! f (f z (i+1)) (i+2)
0x07 -> a $! f (f (f z i) (i+1)) (i+2)
0x08 -> a $! f z (i+3)
0x09 -> a $! f (f z i) (i+3)
0x0A -> a $! f (f z (i+1)) (i+3)
0x0B -> a $! f (f (f z i) (i+1)) (i+3)
0x0C -> a $! f (f z (i+2)) (i+3)
0x0D -> a $! f (f (f z i) (i+2)) (i+3)
0x0E -> a $! f (f (f z (i+1)) (i+2)) (i+3)
0x0F -> a $! f (f (f (f z i) (i+1)) (i+2)) (i+3)
_ -> error "bug in foldlBits_aux"
where a b = foldlBits_aux' f b (i + 4) (Bits.shiftR w 4)
instance (Eq a, Enum a) => C.CollX (Set a) a where
{singleton = singleton; fromSeq = fromSeq; insert = insert;
insertSeq = insertSeq; unionSeq = unionSeq;
delete = delete; deleteAll = deleteAll; deleteSeq = deleteSeq;
null = null; size = size; member = member; count = count;
strict = strict;
structuralInvariant = structuralInvariant; instanceName _ = moduleName}
instance (Ord a, Enum a) => C.OrdCollX (Set a) a where
{deleteMin = deleteMin; deleteMax = deleteMax;
unsafeInsertMin = unsafeInsertMin; unsafeInsertMax = unsafeInsertMax;
unsafeFromOrdSeq = unsafeFromOrdSeq; unsafeAppend = unsafeAppend;
filterLT = filterLT; filterLE = filterLE; filterGT = filterGT;
filterGE = filterGE; partitionLT_GE = partitionLT_GE;
partitionLE_GT = partitionLE_GT; partitionLT_GT = partitionLT_GT}
instance (Eq a, Enum a) => C.SetX (Set a) a where
{intersection = intersection; difference = difference;
symmetricDifference = symmetricDifference;
properSubset = properSubset; subset = subset}
instance (Eq a, Enum a) => C.Coll (Set a) a where
{toSeq = toSeq; lookup = lookup; lookupM = lookupM;
lookupAll = lookupAll; lookupWithDefault = lookupWithDefault;
fold = fold; fold' = fold'; fold1 = fold1; fold1' = fold1';
filter = filter; partition = partition; strictWith = strictWith}
instance (Ord a, Enum a) => C.OrdColl (Set a) a where
{minView = minView; minElem = minElem; maxView = maxView;
maxElem = maxElem; foldr = foldr; foldr' = foldr';
foldl = foldl; foldl' = foldl'; foldr1 = foldr1; foldr1' = foldr1';
foldl1 = foldl1; foldl1' = foldl1'; toOrdSeq = toOrdSeq;
unsafeMapMonotonic = unsafeMapMonotonic}
instance (Eq a, Enum a) => C.Set (Set a) a where
{fromSeqWith = fromSeqWith; insertWith = insertWith;
insertSeqWith = insertSeqWith; unionl = unionl; unionr = unionr;
unionWith = unionWith; unionSeqWith = unionSeqWith;
intersectionWith = intersectionWith}
instance (Ord a, Enum a) => C.OrdSetX (Set a) a
instance (Ord a, Enum a) => C.OrdSet (Set a) a
instance (Eq a, Enum a, Show a) => Show (Set a) where
showsPrec = showsPrecUsingToList
instance (Eq a, Enum a, Read a) => Read (Set a) where
readsPrec = readsPrecUsingFromList
instance (Eq a, Enum a, Arbitrary a) => Arbitrary (Set a) where
arbitrary = do (w::Int) <- arbitrary
return (Set (fromIntegral w))
instance (Eq a, Enum a, CoArbitrary a) => CoArbitrary (Set a) where
coarbitrary (Set w) = coarbitrary (fromIntegral w :: Int)
instance (Eq a, Enum a) => Semigroup (Set a) where
(<>) = union
instance (Eq a, Enum a) => Monoid (Set a) where
mempty = empty
mappend = (SG.<>)
mconcat = unionSeq
instance (Ord a, Enum a) => Ord (Set a) where
compare = compareUsingToOrdList
| null | https://raw.githubusercontent.com/robdockins/edison/543a9085384ac2f4effbfc3266cca5f2d3b08e1b/edison-core/src/Data/Edison/Coll/EnumSet.hs | haskell | ---------------------------------------------------------------------------
|
Stability : stable
An efficient implementation of sets over small enumerations.
For this implementation to work as expected at type @A@, there are a number
a finite subset of the naturals [0,1,2,3....]. As a corollary we must have:
> forall x y::A, fromEnum x == fromEnum y <==> x is indistinguishable from y
The @Enum A@ instance must be consistent with the @Eq A@ instance.
That is, we must have:
> forall x y::A, x == y <==> toEnum x == toEnum y
Additionally, for operations that require an @Ord A@ context, we require that
toEnum be monotonic with respect to comparison. That is, we must have:
> forall x y::A, x < y <==> toEnum x < toEnum y
the enumerated type has sufficently few constructors.
* Set type
* OrdCollX operations
* SetX operations
* Coll operations
* Set operations
* Bonus operations
* Documenation
-----------------------------------------------------------------
-----------------------------------------------------------------
------------------------------------------------------------------}
| A set of values @a@ implemented as bitwise operations. Useful
no interesting structural invariants
--------------------------------------------------
bit twiddly magic
stolen from /
-------------------------------------------------------------------
Query
-------------------------------------------------------------------
| /O(1)/. Is this the empty set?
| /O(1)/. The number of elements in the set.
| /O(1)/. Is the element in the set?
-------------------------------------------------------------------
Construction
-------------------------------------------------------------------
| /O(1)/. The empty set.
| /O(1)/. Create a singleton set.
-------------------------------------------------------------------
Insertion, Deletion
-------------------------------------------------------------------
| /O(1)/. Insert an element in a set.
If the set already contains an element equal to the given value,
it is replaced with the new value.
given the preconditions, we can just ignore the combining function
| /O(1)/. Delete an element from a set.
-------------------------------------------------------------------
Subset
-------------------------------------------------------------------
| /O(1)/. Is this a proper subset? (ie. a subset but not equal).
| /O(1)/. Is this a subset?
-----------------------------------------------------------------
-----------------------------------------------------------------
------------------------------------------------------------------}
| /O(1)/. The minimal element of a set.
| /O(1)/. The maximal element of a set.
| /O(1)/. Delete the minimal element.
| /O(1)/. Delete the maximal element.
-------------------------------------------------------------------
Union.
-------------------------------------------------------------------
| The union of a list of sets: (@'unions' == 'foldl' 'union' 'empty'@).
given the preconditions, we can just ignore the combining function
-------------------------------------------------------------------
Difference
-------------------------------------------------------------------
-------------------------------------------------------------------
Intersection
-------------------------------------------------------------------
-------------------------------------------------------------------
Complement
-------------------------------------------------------------------
| /O(1)/. The complement of a set with its universe set. @complement@ can be used
with bounded types for which the universe set
will be automatically created.
-------------------------------------------------------------------
Filter and partition
-------------------------------------------------------------------
| /O(n)/. Filter all elements that satisfy the predicate.
the predicate and one with all elements that don't satisfy the predicate.
See also 'split'.
---------------------------------------------------------------------
Map
---------------------------------------------------------------------
| /O(n)/.
It's worth noting that the size of the result may be smaller if,
| /O(1)/ Changes the type of the elements in the set without changing
the representation. Equivalant to @map (toEnum . fromEnum)@, and
| /O(1)/ Get the underlying bit-encoded representation.
This method is operationally a no-op.
This method is operationally a no-op.
-----------------------------------------------------------------
-----------------------------------------------------------------
------------------------------------------------------------------}
-------------------------------------------------------------------
Lists
-------------------------------------------------------------------
given the preconditions, we can just ignore the combining function
-------------------------------------------------------------------
Split
-------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
--------------------------------------------------------------}
-------------------------------------------------------------------
Utility functions.
------------------------------------------------------------------- | Module : Data . Edison . . EnumSet
Copyright : ( c ) 2006
License : BSD
Maintainer : robdockins AT fastmail DOT fm
Portability : GHC , Hugs ( MPTC and FD )
The implementation of ' EnumSet ' is based on bit - wise operations .
of preconditions on the @Eq@ , @Enum@ and @Ord@ instances .
The @Enum A@ instance must create a bijection between the elements of type and
Also , the number of distinct elements of must be less than or equal
to the number of bits in @Word@.
Derived @Eq@ , @Ord@ and @Enum@ instances will fulfill these conditions , if
Copyright ( c ) 2006 , 2008 ,
All rights reserved .
Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are
met :
* Redistributions of source code must retain the above copyright
notice , this list of conditions and the following disclaimer .
* Redistributions in binary form must reproduce the above copyright
notice , this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution .
* Neither the name of nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission .
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
Copyright (c) 2006, 2008, David F. Place
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of David F. Place nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Data.Edison.Coll.EnumSet (
Set
* CollX operations
, empty
, singleton
, fromSeq
, insert
, insertSeq
, union
, unionSeq
, delete
, deleteAll
, deleteSeq
, null
, size
, member
, count
, strict
, deleteMin
, deleteMax
, unsafeInsertMin
, unsafeInsertMax
, unsafeFromOrdSeq
, unsafeAppend
, filterLT
, filterLE
, filterGT
, filterGE
, partitionLT_GE
, partitionLE_GT
, partitionLT_GT
, intersection
, difference
, symmetricDifference
, properSubset
, subset
, toSeq
, lookup
, lookupM
, lookupAll
, lookupWithDefault
, fold, fold', fold1, fold1'
, filter
, partition
, strictWith
* OrdColl operations
, minView
, minElem
, maxView
, maxElem
, foldr, foldr', foldl, foldl'
, foldr1, foldr1', foldl1, foldl1'
, toOrdSeq
, unsafeMapMonotonic
, fromSeqWith
, fromOrdSeq
, insertWith
, insertSeqWith
, unionl
, unionr
, unionWith
, unionSeqWith
, intersectionWith
, map
, setCoerce
, complement
, toBits
, fromBits
, moduleName
) where
import qualified Prelude
import Prelude hiding (filter,foldl,foldr,null,map,lookup,foldl1,foldr1)
import qualified Control.Monad.Fail as Fail
import qualified Data.Bits as Bits
import Data.Bits hiding (complement)
import Data.Word
import Data.Monoid (Monoid(..))
import Data.Semigroup as SG
import qualified Data.Edison.Seq as S
import qualified Data.Edison.Coll as C
import Data.Edison.Coll.Defaults
import Test.QuickCheck (Arbitrary(..), CoArbitrary(..))
moduleName :: String
moduleName = "Data.Edison.Coll.EnumSet"
Sets are bit strings of width wordLength .
Sets are bit strings of width wordLength.
for members of class with no more elements than there are bits
in @Word@.
newtype Set a = Set Word deriving (Eq)
wordLength :: Int
wordLength =
#if MIN_VERSION_base(4,7,0)
finiteBitSize
#else
bitSize
#endif
(0::Word)
check :: String -> Int -> Int
check msg x
| x < wordLength = x
| otherwise = error $ "EnumSet."++msg++": element beyond word size."
structuralInvariant :: Set a -> Bool
structuralInvariant = const True
countBits :: Word -> Int
countBits w = w `seq` bitcount 0 w
bitcount :: Int -> Word -> Int
bitcount a 0 = a
bitcount a x = a `seq` bitcount (a+1) (x .&. (x-1))
lsb :: Word -> Int
lsb x = countBits ((x-1) .&. (Bits.complement x))
msb :: Word -> Int
msb x0 = let
x1 = x0 .|. (x0 `shiftR` 1)
x2 = x1 .|. (x1 `shiftR` 2)
x3 = x2 .|. (x2 `shiftR` 4)
x4 = x3 .|. (x3 `shiftR` 8)
x5 = x4 .|. (x4 `shiftR` 16)
in countBits x5 - 1
lowMask :: Int -> Word
lowMask x = bit x - 1
highMask :: Int -> Word
highMask x = Bits.complement (lowMask x)
null :: Set a -> Bool
null (Set 0) = True
null _ = False
size :: Set a -> Int
size (Set w) = countBits w
member :: (Eq a, Enum a) => a -> Set a -> Bool
member x (Set w) = testBit w $ fromEnum x
count :: (Eq a, Enum a) => a -> Set a -> Int
count = countUsingMember
lookup :: (Eq a, Enum a) => a -> Set a -> a
lookup = lookupUsingLookupAll
lookupM :: (Eq a, Enum a, Fail.MonadFail m) => a -> Set a -> m a
lookupM x s
| member x s = return x
| otherwise = fail (moduleName++".lookupM: lookup failed")
lookupAll :: (Eq a, Enum a, S.Sequence s) => a -> Set a -> s a
lookupAll = lookupAllUsingLookupM
lookupWithDefault :: (Eq a, Enum a) => a -> a -> Set a -> a
lookupWithDefault = lookupWithDefaultUsingLookupM
empty :: Set a
empty = Set 0
singleton :: (Eq a, Enum a) => a -> Set a
singleton x =
Set $ setBit 0 $ check "singleton" $ fromEnum x
insert :: (Eq a, Enum a) => a -> Set a -> Set a
insert x (Set w) =
Set $ setBit w $ check "insert" $ fromEnum x
insertWith :: (Eq a, Enum a) => (a -> a -> a) -> a -> Set a -> Set a
insertWith _ x (Set w) =
Set $ setBit w $ check "insertWith" $ fromEnum x
delete :: (Eq a, Enum a) => a -> Set a -> Set a
delete x (Set w) =
Set $ clearBit w $ fromEnum x
deleteAll :: (Eq a, Enum a) => a -> Set a -> Set a
deleteAll = delete
deleteSeq :: (Eq a, Enum a, S.Sequence s) => s a -> Set a -> Set a
deleteSeq = deleteSeqUsingDelete
properSubset :: Set a -> Set a -> Bool
properSubset x y = (x /= y) && (subset x y)
@(s1 ` subset ` tells whether @s1@ is a subset of @s2@.
subset :: Set a -> Set a -> Bool
subset x y = (x `union` y) == y
Minimal , Maximal
Minimal, Maximal
minElem :: (Enum a) => Set a -> a
minElem (Set w)
| w == 0 = error $ moduleName++".minElem: empty set"
| otherwise = toEnum $ lsb w
maxElem :: (Enum a) => Set a -> a
maxElem (Set w)
| w == 0 = error $ moduleName++".maxElem: empty set"
| otherwise = toEnum $ msb w
deleteMin :: (Enum a) => Set a -> Set a
deleteMin (Set w)
| w == 0 = empty
| otherwise = Set $ clearBit w $ lsb w
deleteMax :: (Enum a) => Set a -> Set a
deleteMax (Set w)
| w == 0 = empty
| otherwise = Set $ clearBit w $ msb w
minView :: (Enum a, Fail.MonadFail m) => Set a -> m (a, Set a)
minView (Set w)
| w == 0 = fail (moduleName++".minView: empty set")
| otherwise = let i = lsb w in return (toEnum i,Set $ clearBit w i)
maxView :: (Enum a, Fail.MonadFail m) => Set a -> m (a, Set a)
maxView (Set w)
| w == 0 = fail (moduleName++".maxView: empty set")
| otherwise = let i = msb w in return (toEnum i, Set $ clearBit w i)
unsafeInsertMin :: (Ord a, Enum a) => a -> Set a -> Set a
unsafeInsertMin = insert
unsafeInsertMax :: (Ord a, Enum a) => a -> Set a -> Set a
unsafeInsertMax = insert
unsafeAppend :: (Ord a, Enum a) => Set a -> Set a -> Set a
unsafeAppend = union
unsafeFromOrdSeq :: (Ord a, Enum a, S.Sequence s) => s a -> Set a
unsafeFromOrdSeq = fromSeq
filterLT :: (Ord a, Enum a) => a -> Set a -> Set a
filterLT x (Set w) = Set (w .&. lowMask (fromEnum x))
filterLE :: (Ord a, Enum a) => a -> Set a -> Set a
filterLE x (Set w) = Set (w .&. lowMask (fromEnum x + 1))
filterGT :: (Ord a, Enum a) => a -> Set a -> Set a
filterGT x (Set w) = Set (w .&. highMask (fromEnum x + 1))
filterGE :: (Ord a, Enum a) => a -> Set a -> Set a
filterGE x (Set w) = Set (w .&. highMask (fromEnum x))
partitionLT_GE :: (Ord a, Enum a) => a -> Set a -> (Set a, Set a)
partitionLT_GE x s = (filterLT x s,filterGE x s)
partitionLE_GT :: (Ord a, Enum a) => a -> Set a -> (Set a, Set a)
partitionLE_GT x s = (filterLE x s,filterGT x s)
partitionLT_GT :: (Ord a, Enum a) => a -> Set a -> (Set a, Set a)
partitionLT_GT x s = (filterLT x s,filterGT x s)
unionSeq :: (Eq a, Enum a, S.Sequence s) => s (Set a) -> Set a
unionSeq = unionSeqUsingFoldl'
| /O(1)/. The union of two sets .
union :: Set a -> Set a -> Set a
union (Set x) (Set y) = Set $ x .|. y
unionl :: Set a -> Set a -> Set a
unionl = union
unionr :: Set a -> Set a -> Set a
unionr = union
unionWith :: (a -> a -> a) -> Set a -> Set a -> Set a
unionWith _ = union
unionSeqWith :: (Eq a, Enum a, S.Sequence s) => (a -> a -> a) -> s (Set a) -> Set a
unionSeqWith _ = unionSeq
| /O(1)/. Difference of two sets .
difference :: Set a -> Set a -> Set a
difference (Set x) (Set y) = Set $ (x .|. y) `xor` y
symmetricDifference :: Set a -> Set a -> Set a
symmetricDifference (Set x) (Set y) = Set $ x `xor` y
| /O(1)/. The intersection of two sets .
intersection :: Set a -> Set a -> Set a
intersection (Set x) (Set y) = Set $ x .&. y
intersectionWith :: (a -> a -> a) -> Set a -> Set a -> Set a
intersectionWith _ = intersection
complement :: (Eq a, Bounded a, Enum a) => Set a -> Set a
complement x = symmetricDifference u x
where u = (fromSeq [minBound .. maxBound]) `asTypeOf` x
filter :: (Eq a, Enum a) => (a -> Bool) -> Set a -> Set a
filter p (Set w) = Set $ foldlBits' f 0 w
where
f z i
| p $ toEnum i = setBit z i
| otherwise = z
| /O(n)/. Partition the set into two sets , one with all elements that satisfy
partition :: (Eq a, Enum a) => (a -> Bool) -> Set a -> (Set a,Set a)
partition p (Set w) = (Set yay,Set nay)
where
(yay,nay) = foldlBits' f (0,0) w
f (x,y) i
| p $ toEnum i = (setBit x i,y)
| otherwise = (x,setBit y i)
@'map ' f s@ is the set obtained by applying @f@ to each element of @s@.
for some @(x , y)@ , @x \/= y & & f x = = f y@
map :: (Enum a,Enum b) => (a -> b) -> Set a -> Set b
map f0 (Set w) = Set $ foldlBits' f 0 w
where
f z i = setBit z $ check "map" $ fromEnum $ f0 (toEnum i)
unsafeMapMonotonic :: (Enum a) => (a -> a) -> Set a -> Set a
unsafeMapMonotonic = map
to @(fromBits . toBits)@. This method is operationally a no - op .
setCoerce :: (Enum a, Enum b) => Set a -> Set b
setCoerce (Set w) = Set w
toBits :: Set a -> Word
toBits (Set w) = w
| /O(1)/ Create an EnumSet from a bit - encoded representation .
fromBits :: Word -> Set a
fromBits w = Set w
Fold
Fold
fold :: (Eq a, Enum a) => (a -> c -> c) -> c -> Set a -> c
fold f z (Set w) = foldrBits folder z w
where folder i = f (toEnum i)
fold' :: (Eq a, Enum a) => (a -> c -> c) -> c -> Set a -> c
fold' f z (Set w) = foldrBits' folder z w
where folder i = f (toEnum i)
fold1 :: (Eq a, Enum a) => (a -> a -> a) -> Set a -> a
fold1 _ (Set 0) = error (moduleName++".fold1: empty set")
fold1 f (Set w) = foldrBits folder (toEnum maxi) (clearBit w maxi)
where
maxi = msb w
folder i z = f (toEnum i) z
fold1' :: (Eq a, Enum a) => (a -> a -> a) -> Set a -> a
fold1' _ (Set 0) = error (moduleName++".fold1': empty set")
fold1' f (Set w) = foldrBits folder (toEnum maxi) (clearBit w maxi)
where
maxi = msb w
folder i z = f (toEnum i) z
foldr :: (Ord a, Enum a) => (a -> b -> b) -> b -> Set a -> b
foldr f z (Set w) = foldrBits folder z w
where folder i = f (toEnum i)
foldr' :: (Ord a, Enum a) => (a -> b -> b) -> b -> Set a -> b
foldr' f z (Set w) = foldrBits' folder z w
where folder i j = f (toEnum i) j
foldr1 :: (Ord a, Enum a) => (a -> a -> a) -> Set a -> a
foldr1 _ (Set 0) = error (moduleName ++ ".foldr1: empty set")
foldr1 f (Set w) = foldrBits folder (toEnum maxi) (clearBit w maxi)
where
maxi = msb w
folder i z = f (toEnum i) z
foldr1' :: (Ord a, Enum a) => (a -> a -> a) -> Set a -> a
foldr1' _ (Set 0) = error (moduleName++".foldr1': empty set")
foldr1' f (Set w) = foldrBits folder (toEnum maxi) (clearBit w maxi)
where
maxi = msb w
folder i z = f (toEnum i) z
foldl :: (Ord a, Enum a) => (c -> a -> c) -> c -> Set a -> c
foldl f z (Set w) = foldlBits folder z w
where folder h i = f h (toEnum i)
foldl' :: (Ord a, Enum a) => (c -> a -> c) -> c -> Set a -> c
foldl' f z (Set w) = foldlBits' folder z w
where folder h i = f h (toEnum i)
foldl1 :: (Ord a, Enum a) => (a -> a -> a) -> Set a -> a
foldl1 _ (Set 0) = error (moduleName++".foldl1: empty set")
foldl1 f (Set w) = foldlBits folder (toEnum mininum) (clearBit w mininum)
where
mininum = lsb w
folder z i = f z (toEnum i)
foldl1' :: (Ord a, Enum a) => (a -> a -> a) -> Set a -> a
foldl1' _ (Set 0) = error (moduleName++".foldl1': empty set")
foldl1' f (Set w) = foldlBits' folder (toEnum mininum) (clearBit w mininum)
where
mininum = lsb w
folder z i = f z (toEnum i)
fromSeq :: (Eq a, Enum a, S.Sequence s) => s a -> Set a
fromSeq xs = Set $ S.fold' f 0 xs
where f x z = setBit z $ check "fromSeq" $ fromEnum x
fromOrdSeq :: (Ord a, Enum a, S.Sequence s) => s a -> Set a
fromOrdSeq = fromSeq
insertSeq :: (Eq a, Enum a, S.Sequence s) => s a -> Set a -> Set a
insertSeq = insertSeqUsingUnion
insertSeqWith :: (Eq a, Enum a, S.Sequence s) => (a -> a -> a) -> s a -> Set a -> Set a
insertSeqWith _ = insertSeq
toSeq :: (Eq a, Enum a, S.Sequence s) => Set a -> s a
toSeq (Set w) = foldrBits f S.empty w
where f i z = S.lcons (toEnum i) z
toOrdSeq :: (Ord a, Enum a, S.Sequence s) => Set a -> s a
toOrdSeq = toSeq
fromSeqWith :: (Eq a, Enum a, S.Sequence s) => (a -> a -> a) -> s a -> Set a
fromSeqWith = fromSeqWithUsingInsertWith
splitMember : : ( a , a ) = > a - > Set a - > ( Set a , , Set a )
( Set w ) = ( Set lesser , isMember , Set greater )
where
( lesser , isMember , greater ) = foldrBits f ( 0,False,0 ) w
f i ( lesser , isMember , greater ) =
case compare ( toEnum i ) x of
GT - > ( lesser , isMember , setBit greater i )
LT - > ( setBit lesser i , , greater )
EQ - > ( lesser , True , greater )
splitMember :: (Ord a, Enum a) => a -> Set a -> (Set a,Bool,Set a)
splitMember x (Set w) = (Set lesser,isMember,Set greater)
where
(lesser,isMember,greater) = foldrBits f (0,False,0) w
f i (lesser,isMember,greater) =
case compare (toEnum i) x of
GT -> (lesser,isMember,setBit greater i)
LT -> (setBit lesser i,isMember,greater)
EQ -> (lesser,True,greater)
-}
Strictness enhancement
Strictness enhancement
strict :: Set a -> Set a
strict s@(Set w) = w `seq` s
strictWith :: (a -> b) -> Set a -> Set a
strictWith _ s@(Set w) = w `seq` s
foldrBits :: (Int -> a -> a) -> a -> Word -> a
foldrBits f z w = foldrBits_aux f z 0 w
foldrBits_aux :: (Int -> a -> a) -> a -> Int -> Word -> a
foldrBits_aux _ z _ 0 = z
foldrBits_aux f z i w
| i `seq` w `seq` False = undefined
| otherwise =
case w .&. 0x0F of
0x00 -> a
0x01 -> f i $ a
0x02 -> f (i+1) $ a
0x03 -> f i $ f (i+1) $ a
0x04 -> f (i+2) $ a
0x05 -> f i $ f (i+2) $ a
0x06 -> f (i+1) $ f (i+2) $ a
0x07 -> f i $ f (i+1) $ f (i+2) $ a
0x08 -> f (i+3) $ a
0x09 -> f i $ f (i+3) $ a
0x0A -> f (i+1) $ f (i+3) $ a
0x0B -> f i $ f (i+1) $ f (i+3) $ a
0x0C -> f (i+2) $ f (i+3) $ a
0x0D -> f i $ f (i+2) $ f (i+3) $ a
0x0E -> f (i+1) $ f (i+2) $ f (i+3) $ a
0x0F -> f i $ f (i+1) $ f (i+2) $ f (i+3) $ a
_ -> error "bug in foldrBits_aux"
where a = foldrBits_aux f z (i+4) (Bits.shiftR w 4)
foldrBits' :: (Int -> a -> a) -> a -> Word -> a
foldrBits' f z w = foldrBits_aux' f z 0 w
foldrBits_aux' :: (Int -> a -> a) -> a -> Int -> Word -> a
foldrBits_aux' _ z _ 0 = z
foldrBits_aux' f z i w
| i `seq` w `seq` False = undefined
| otherwise =
case w .&. 0x0F of
0x00 -> a
0x01 -> f i $! a
0x02 -> f (i+1) $! a
0x03 -> f i $! f (i+1) $! a
0x04 -> f (i+2) $! a
0x05 -> f i $! f (i+2) $! a
0x06 -> f (i+1) $! f (i+2) $! a
0x07 -> f i $! f (i+1) $! f (i+2) $! a
0x08 -> f (i+3) $! a
0x09 -> f i $! f (i+3) $! a
0x0A -> f (i+1) $! f (i+3) $! a
0x0B -> f i $! f (i+1) $! f (i+3) $! a
0x0C -> f (i+2) $! f (i+3) $! a
0x0D -> f i $! f (i+2) $! f (i+3) $! a
0x0E -> f (i+1) $! f (i+2) $! f (i+3) $! a
0x0F -> f i $! f (i+1) $! f (i+2) $! f (i+3) $! a
_ -> error "bug in foldrBits_aux'"
where a = foldrBits_aux' f z (i+4) (Bits.shiftR w 4)
foldlBits :: (a -> Int -> a) -> a -> Word -> a
foldlBits f z w = foldlBits_aux f z 0 w
foldlBits_aux :: (a -> Int -> a) -> a -> Int -> Word -> a
foldlBits_aux _ z _ 0 = z
foldlBits_aux f z i w
| i `seq` w `seq` False = undefined
| otherwise =
case w .&. 0x0F of
0x00 -> a $ z
0x01 -> a $ f z i
0x02 -> a $ f z (i+1)
0x03 -> a $ f (f z i) (i+1)
0x04 -> a $ f z (i+2)
0x05 -> a $ f (f z i) (i+2)
0x06 -> a $ f (f z (i+1)) (i+2)
0x07 -> a $ f (f (f z i) (i+1)) (i+2)
0x08 -> a $ f z (i+3)
0x09 -> a $ f (f z i) (i+3)
0x0A -> a $ f (f z (i+1)) (i+3)
0x0B -> a $ f (f (f z i) (i+1)) (i+3)
0x0C -> a $ f (f z (i+2)) (i+3)
0x0D -> a $ f (f (f z i) (i+2)) (i+3)
0x0E -> a $ f (f (f z (i+1)) (i+2)) (i+3)
0x0F -> a $ f (f (f (f z i) (i+1)) (i+2)) (i+3)
_ -> error "bug in foldlBits_aux"
where a b = foldlBits_aux f b (i + 4) (Bits.shiftR w 4)
foldlBits' :: (a -> Int -> a) -> a -> Word -> a
foldlBits' f z w = foldlBits_aux' (\x i -> x `seq` f x i) z 0 w
foldlBits_aux' :: (a -> Int -> a) -> a -> Int -> Word -> a
foldlBits_aux' _ z _ 0 = z
foldlBits_aux' f z i w
| i `seq` w `seq` False = undefined
| otherwise =
case w .&. 0x0F of
0x00 -> a $! z
0x01 -> a $! f z i
0x02 -> a $! f z (i+1)
0x03 -> a $! f (f z i) (i+1)
0x04 -> a $! f z (i+2)
0x05 -> a $! f (f z i) (i+2)
0x06 -> a $! f (f z (i+1)) (i+2)
0x07 -> a $! f (f (f z i) (i+1)) (i+2)
0x08 -> a $! f z (i+3)
0x09 -> a $! f (f z i) (i+3)
0x0A -> a $! f (f z (i+1)) (i+3)
0x0B -> a $! f (f (f z i) (i+1)) (i+3)
0x0C -> a $! f (f z (i+2)) (i+3)
0x0D -> a $! f (f (f z i) (i+2)) (i+3)
0x0E -> a $! f (f (f z (i+1)) (i+2)) (i+3)
0x0F -> a $! f (f (f (f z i) (i+1)) (i+2)) (i+3)
_ -> error "bug in foldlBits_aux"
where a b = foldlBits_aux' f b (i + 4) (Bits.shiftR w 4)
instance (Eq a, Enum a) => C.CollX (Set a) a where
{singleton = singleton; fromSeq = fromSeq; insert = insert;
insertSeq = insertSeq; unionSeq = unionSeq;
delete = delete; deleteAll = deleteAll; deleteSeq = deleteSeq;
null = null; size = size; member = member; count = count;
strict = strict;
structuralInvariant = structuralInvariant; instanceName _ = moduleName}
instance (Ord a, Enum a) => C.OrdCollX (Set a) a where
{deleteMin = deleteMin; deleteMax = deleteMax;
unsafeInsertMin = unsafeInsertMin; unsafeInsertMax = unsafeInsertMax;
unsafeFromOrdSeq = unsafeFromOrdSeq; unsafeAppend = unsafeAppend;
filterLT = filterLT; filterLE = filterLE; filterGT = filterGT;
filterGE = filterGE; partitionLT_GE = partitionLT_GE;
partitionLE_GT = partitionLE_GT; partitionLT_GT = partitionLT_GT}
instance (Eq a, Enum a) => C.SetX (Set a) a where
{intersection = intersection; difference = difference;
symmetricDifference = symmetricDifference;
properSubset = properSubset; subset = subset}
instance (Eq a, Enum a) => C.Coll (Set a) a where
{toSeq = toSeq; lookup = lookup; lookupM = lookupM;
lookupAll = lookupAll; lookupWithDefault = lookupWithDefault;
fold = fold; fold' = fold'; fold1 = fold1; fold1' = fold1';
filter = filter; partition = partition; strictWith = strictWith}
instance (Ord a, Enum a) => C.OrdColl (Set a) a where
{minView = minView; minElem = minElem; maxView = maxView;
maxElem = maxElem; foldr = foldr; foldr' = foldr';
foldl = foldl; foldl' = foldl'; foldr1 = foldr1; foldr1' = foldr1';
foldl1 = foldl1; foldl1' = foldl1'; toOrdSeq = toOrdSeq;
unsafeMapMonotonic = unsafeMapMonotonic}
instance (Eq a, Enum a) => C.Set (Set a) a where
{fromSeqWith = fromSeqWith; insertWith = insertWith;
insertSeqWith = insertSeqWith; unionl = unionl; unionr = unionr;
unionWith = unionWith; unionSeqWith = unionSeqWith;
intersectionWith = intersectionWith}
instance (Ord a, Enum a) => C.OrdSetX (Set a) a
instance (Ord a, Enum a) => C.OrdSet (Set a) a
instance (Eq a, Enum a, Show a) => Show (Set a) where
showsPrec = showsPrecUsingToList
instance (Eq a, Enum a, Read a) => Read (Set a) where
readsPrec = readsPrecUsingFromList
instance (Eq a, Enum a, Arbitrary a) => Arbitrary (Set a) where
arbitrary = do (w::Int) <- arbitrary
return (Set (fromIntegral w))
instance (Eq a, Enum a, CoArbitrary a) => CoArbitrary (Set a) where
coarbitrary (Set w) = coarbitrary (fromIntegral w :: Int)
instance (Eq a, Enum a) => Semigroup (Set a) where
(<>) = union
instance (Eq a, Enum a) => Monoid (Set a) where
mempty = empty
mappend = (SG.<>)
mconcat = unionSeq
instance (Ord a, Enum a) => Ord (Set a) where
compare = compareUsingToOrdList
|
7dd513ddb0355b27c7e994f9504f8af1916b0d2ebac82493d0c8006230ea235e | maximedenes/native-coq | typeclasses.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(*i*)
open Names
open Libnames
open Decl_kinds
open Term
open Sign
open Evd
open Environ
open Nametab
open Mod_subst
open Errors
open Util
open Typeclasses_errors
open Libobject
(*i*)
let add_instance_hint_ref = ref (fun id local pri -> assert false)
let register_add_instance_hint =
(:=) add_instance_hint_ref
let add_instance_hint id = !add_instance_hint_ref id
let remove_instance_hint_ref = ref (fun id -> assert false)
let register_remove_instance_hint =
(:=) remove_instance_hint_ref
let remove_instance_hint id = !remove_instance_hint_ref id
let set_typeclass_transparency_ref = ref (fun id local c -> assert false)
let register_set_typeclass_transparency =
(:=) set_typeclass_transparency_ref
let set_typeclass_transparency gr local c = !set_typeclass_transparency_ref gr local c
let classes_transparent_state_ref = ref (fun () -> assert false)
let register_classes_transparent_state = (:=) classes_transparent_state_ref
let classes_transparent_state () = !classes_transparent_state_ref ()
let solve_instanciation_problem = ref (fun _ _ _ -> assert false)
let resolve_one_typeclass env evm t =
!solve_instanciation_problem env evm t
type rels = constr list
type direction = Forward | Backward
(* This module defines type-classes *)
type typeclass = {
(* The class implementation *)
cl_impl : global_reference;
Context in which the definitions are typed . Includes both typeclass parameters and superclasses .
cl_context : (global_reference * bool) option list * rel_context;
Context of definitions and properties on defs , will not be shared
cl_props : rel_context;
(* The method implementaions as projections. *)
cl_projs : (name * (direction * int option) option * constant option) list;
}
module Gmap = Fmap.Make(RefOrdered)
type typeclasses = typeclass Gmap.t
type instance = {
is_class: global_reference;
is_pri: int option;
(* Sections where the instance should be redeclared,
-1 for discard, 0 for none, mutable to avoid redeclarations
when multiple rebuild_object happen. *)
is_global: int;
is_impl: global_reference;
}
type instances = (instance Gmap.t) Gmap.t
let instance_impl is = is.is_impl
let new_instance cl pri glob impl =
let global =
if glob then Lib.sections_depth ()
else -1
in
{ is_class = cl.cl_impl;
is_pri = pri ;
is_global = global ;
is_impl = impl }
(*
* states management
*)
let classes : typeclasses ref = ref Gmap.empty
let instances : instances ref = ref Gmap.empty
let freeze () = !classes, !instances
let unfreeze (cl,is) =
classes:=cl;
instances:=is
let init () =
classes:= Gmap.empty;
instances:= Gmap.empty
let _ =
Summary.declare_summary "classes_and_instances"
{ Summary.freeze_function = freeze;
Summary.unfreeze_function = unfreeze;
Summary.init_function = init }
let class_info c =
try Gmap.find c !classes
with _ -> not_a_class (Global.env()) (constr_of_global c)
let global_class_of_constr env c =
try class_info (global_of_constr c)
with Not_found -> not_a_class env c
let dest_class_app env c =
let cl, args = decompose_app c in
global_class_of_constr env cl, args
let dest_class_arity env c =
let rels, c = Term.decompose_prod_assum c in
rels, dest_class_app env c
let class_of_constr c = try Some (dest_class_arity (Global.env ()) c) with _ -> None
let rec is_class_type evd c =
match kind_of_term c with
| Prod (_, _, t) -> is_class_type evd t
| Evar (e, _) when is_defined evd e -> is_class_type evd (Evarutil.nf_evar evd c)
| _ -> class_of_constr c <> None
let is_class_evar evd evi =
is_class_type evd evi.Evd.evar_concl
(*
* classes persistent object
*)
let load_class (_, cl) =
classes := Gmap.add cl.cl_impl cl !classes
let cache_class = load_class
let subst_class (subst,cl) =
let do_subst_con c = fst (Mod_subst.subst_con subst c)
and do_subst c = Mod_subst.subst_mps subst c
and do_subst_gr gr = fst (subst_global subst gr) in
let do_subst_ctx ctx = list_smartmap
(fun (na, b, t) -> (na, Option.smartmap do_subst b, do_subst t))
ctx in
let do_subst_context (grs,ctx) =
list_smartmap (Option.smartmap (fun (gr,b) -> do_subst_gr gr, b)) grs,
do_subst_ctx ctx in
let do_subst_projs projs = list_smartmap (fun (x, y, z) -> (x, y, Option.smartmap do_subst_con z)) projs in
{ cl_impl = do_subst_gr cl.cl_impl;
cl_context = do_subst_context cl.cl_context;
cl_props = do_subst_ctx cl.cl_props;
cl_projs = do_subst_projs cl.cl_projs; }
let discharge_class (_,cl) =
let repl = Lib.replacement_context () in
let rel_of_variable_context ctx = List.fold_right
( fun (n,_,b,t) (ctx', subst) ->
let decl = (Name n, Option.map (substn_vars 1 subst) b, substn_vars 1 subst t) in
(decl :: ctx', n :: subst)
) ctx ([], []) in
let discharge_rel_context subst n rel =
let rel = map_rel_context (Cooking.expmod_constr repl) rel in
let ctx, _ =
List.fold_right
(fun (id, b, t) (ctx, k) ->
(id, Option.smartmap (substn_vars k subst) b, substn_vars k subst t) :: ctx, succ k)
rel ([], n)
in ctx
in
let abs_context cl =
match cl.cl_impl with
| VarRef _ | ConstructRef _ -> assert false
| ConstRef cst -> Lib.section_segment_of_constant cst
| IndRef (ind,_) -> Lib.section_segment_of_mutual_inductive ind in
let discharge_context ctx' subst (grs, ctx) =
let grs' =
let newgrs = List.map (fun (_, _, t) ->
match class_of_constr t with
| None -> None
| Some (_, (tc, _)) -> Some (tc.cl_impl, true))
ctx'
in
list_smartmap (Option.smartmap (fun (gr, b) -> Lib.discharge_global gr, b)) grs
@ newgrs
in grs', discharge_rel_context subst 1 ctx @ ctx' in
let cl_impl' = Lib.discharge_global cl.cl_impl in
if cl_impl' == cl.cl_impl then cl else
let ctx = abs_context cl in
let ctx, subst = rel_of_variable_context ctx in
let context = discharge_context ctx subst cl.cl_context in
let props = discharge_rel_context subst (succ (List.length (fst cl.cl_context))) cl.cl_props in
{ cl_impl = cl_impl';
cl_context = context;
cl_props = props;
cl_projs = list_smartmap (fun (x, y, z) -> x, y, Option.smartmap Lib.discharge_con z) cl.cl_projs }
let rebuild_class cl =
try
let cst = Tacred.evaluable_of_global_reference (Global.env ()) cl.cl_impl in
set_typeclass_transparency cst false false; cl
with _ -> cl
let class_input : typeclass -> obj =
declare_object
{ (default_object "type classes state") with
cache_function = cache_class;
load_function = (fun _ -> load_class);
open_function = (fun _ -> load_class);
classify_function = (fun x -> Substitute x);
discharge_function = (fun a -> Some (discharge_class a));
rebuild_function = rebuild_class;
subst_function = subst_class }
let add_class cl =
Lib.add_anonymous_leaf (class_input cl)
(** Build the subinstances hints. *)
let check_instance env sigma c =
try
let (evd, c) = resolve_one_typeclass env sigma
(Retyping.get_type_of env sigma c) in
Evd.is_empty (Evd.undefined_evars evd)
with _ -> false
let build_subclasses ~check env sigma glob pri =
let rec aux pri c =
let ty = Evarutil.nf_evar sigma (Retyping.get_type_of env sigma c) in
match class_of_constr ty with
| None -> []
| Some (rels, (tc, args)) ->
let instapp = Reductionops.whd_beta sigma (appvectc c (Termops.extended_rel_vect 0 rels)) in
let projargs = Array.of_list (args @ [instapp]) in
let projs = list_map_filter
(fun (n, b, proj) ->
match b with
| None -> None
| Some (Backward, _) -> None
| Some (Forward, pri') ->
let proj = Option.get proj in
let body = it_mkLambda_or_LetIn (mkApp (mkConst proj, projargs)) rels in
if check && check_instance env sigma body then None
else
let pri =
match pri, pri' with
| Some p, Some p' -> Some (p + p')
| Some p, None -> Some (p + 1)
| _, _ -> None
in
Some (ConstRef proj, pri, body)) tc.cl_projs
in
let declare_proj hints (cref, pri, body) =
let rest = aux pri body in
hints @ (pri, body) :: rest
in List.fold_left declare_proj [] projs
in aux pri (constr_of_global glob)
(*
* instances persistent object
*)
type instance_action =
| AddInstance
| RemoveInstance
let load_instance inst =
let insts =
try Gmap.find inst.is_class !instances
with Not_found -> Gmap.empty in
let insts = Gmap.add inst.is_impl inst insts in
instances := Gmap.add inst.is_class insts !instances
let remove_instance inst =
let insts =
try Gmap.find inst.is_class !instances
with Not_found -> assert false in
let insts = Gmap.remove inst.is_impl insts in
instances := Gmap.add inst.is_class insts !instances
let cache_instance (_, (action, i)) =
match action with
| AddInstance -> load_instance i
| RemoveInstance -> remove_instance i
let subst_instance (subst, (action, inst)) = action,
{ inst with
is_class = fst (subst_global subst inst.is_class);
is_impl = fst (subst_global subst inst.is_impl) }
let discharge_instance (_, (action, inst)) =
if inst.is_global <= 0 then None
else Some (action,
{ inst with
is_global = pred inst.is_global;
is_class = Lib.discharge_global inst.is_class;
is_impl = Lib.discharge_global inst.is_impl })
let is_local i = i.is_global = -1
let add_instance check inst =
add_instance_hint (constr_of_global inst.is_impl) (is_local inst) inst.is_pri;
List.iter (fun (pri, c) -> add_instance_hint c (is_local inst) pri)
(build_subclasses ~check:(check && not (isVarRef inst.is_impl))
(Global.env ()) Evd.empty inst.is_impl inst.is_pri)
let rebuild_instance (action, inst) =
if action = AddInstance then add_instance true inst;
(action, inst)
let classify_instance (action, inst) =
if is_local inst then Dispose
else Substitute (action, inst)
let load_instance (_, (action, inst) as ai) =
cache_instance ai;
if action = AddInstance then
add_instance_hint (constr_of_global inst.is_impl) (is_local inst) inst.is_pri
let instance_input : instance_action * instance -> obj =
declare_object
{ (default_object "type classes instances state") with
cache_function = cache_instance;
load_function = (fun _ x -> cache_instance x);
open_function = (fun _ x -> cache_instance x);
classify_function = classify_instance;
discharge_function = discharge_instance;
rebuild_function = rebuild_instance;
subst_function = subst_instance }
let add_instance i =
Lib.add_anonymous_leaf (instance_input (AddInstance, i));
add_instance true i
let remove_instance i =
Lib.add_anonymous_leaf (instance_input (RemoveInstance, i));
remove_instance_hint i.is_impl
let declare_instance pri local glob =
let c = constr_of_global glob in
let ty = Retyping.get_type_of (Global.env ()) Evd.empty c in
match class_of_constr ty with
| Some (rels, (tc, args) as _cl) ->
add_instance (new_instance tc pri (not local) glob)
(* let path, hints = build_subclasses (not local) (Global.env ()) Evd.empty glob in *)
let entries = List.map ( fun ( path , pri , c ) - > ( pri , local , path , c ) ) hints in
Auto.add_hints local [ typeclasses_db ] ( Auto . HintsResolveEntry entries ) ;
Auto.add_hints local [ ]
( Auto . HintsCutEntry ( PathSeq ( PathStar ( PathAtom ) , path ) ) )
| None -> ()
let add_class cl =
add_class cl;
List.iter (fun (n, inst, body) ->
match inst with
| Some (Backward, pri) ->
declare_instance pri false (ConstRef (Option.get body))
| _ -> ())
cl.cl_projs
open Declarations
let add_constant_class cst =
let ty = Typeops.type_of_constant (Global.env ()) cst in
let ctx, arity = decompose_prod_assum ty in
let tc =
{ cl_impl = ConstRef cst;
cl_context = (List.map (const None) ctx, ctx);
cl_props = [(Anonymous, None, arity)];
cl_projs = []
}
in add_class tc;
set_typeclass_transparency (EvalConstRef cst) false false
let add_inductive_class ind =
let mind, oneind = Global.lookup_inductive ind in
let k =
let ctx = oneind.mind_arity_ctxt in
let ty = Inductive.type_of_inductive_knowing_parameters
(push_rel_context ctx (Global.env ()))
oneind (Termops.extended_rel_vect 0 ctx)
in
{ cl_impl = IndRef ind;
cl_context = List.map (const None) ctx, ctx;
cl_props = [Anonymous, None, ty];
cl_projs = [] }
in add_class k
(*
* interface functions
*)
let instance_constructor cl args =
let lenpars = List.length (List.filter (fun (na, b, t) -> b = None) (snd cl.cl_context)) in
let pars = fst (list_chop lenpars args) in
match cl.cl_impl with
| IndRef ind -> Some (applistc (mkConstruct (ind, 1)) args),
applistc (mkInd ind) pars
| ConstRef cst ->
let term = if args = [] then None else Some (list_last args) in
term, applistc (mkConst cst) pars
| _ -> assert false
let typeclasses () = Gmap.fold (fun _ l c -> l :: c) !classes []
let cmap_elements c = Gmap.fold (fun k v acc -> v :: acc) c []
let instances_of c =
try cmap_elements (Gmap.find c.cl_impl !instances) with Not_found -> []
let all_instances () =
Gmap.fold (fun k v acc ->
Gmap.fold (fun k v acc -> v :: acc) v acc)
!instances []
let instances r =
let cl = class_info r in instances_of cl
let is_class gr =
Gmap.fold (fun k v acc -> acc || v.cl_impl = gr) !classes false
let is_instance = function
| ConstRef c ->
(match Decls.constant_kind c with
| IsDefinition Instance -> true
| _ -> false)
| VarRef v ->
(match Decls.variable_kind v with
| IsDefinition Instance -> true
| _ -> false)
| ConstructRef (ind,_) ->
is_class (IndRef ind)
| _ -> false
let is_implicit_arg k = k <> GoalEvar
(* match k with *)
ImplicitArg ( ref , ( n , i d ) , b ) - > true
(* | InternalHole -> true *)
(* | _ -> false *)
To embed a boolean for resolvability status .
This is essentially a hack to mark which evars correspond to
goals and do not need to be resolved when we have nested [ resolve_all_evars ]
calls ( e.g. when doing apply in an External hint in typeclass_instances ) .
Would be solved by having real evars - as - goals .
: we will only check the resolvability status of undefined evars .
This is essentially a hack to mark which evars correspond to
goals and do not need to be resolved when we have nested [resolve_all_evars]
calls (e.g. when doing apply in an External hint in typeclass_instances).
Would be solved by having real evars-as-goals.
Nota: we will only check the resolvability status of undefined evars.
*)
let resolvable = Store.field ()
open Store.Field
let is_resolvable evi =
assert (evi.evar_body = Evar_empty);
Option.default true (resolvable.get evi.evar_extra)
let mark_resolvability_undef b evi =
let t = resolvable.set b evi.evar_extra in
{ evi with evar_extra = t }
let mark_resolvability b evi =
assert (evi.evar_body = Evar_empty);
mark_resolvability_undef b evi
let mark_unresolvable evi = mark_resolvability false evi
let mark_resolvable evi = mark_resolvability true evi
let mark_resolvability b sigma =
Evd.fold_undefined (fun ev evi evs ->
Evd.add evs ev (mark_resolvability_undef b evi))
sigma (Evd.defined_evars sigma)
let mark_unresolvables sigma = mark_resolvability false sigma
let mark_resolvables sigma = mark_resolvability true sigma
let has_typeclasses evd =
Evd.fold_undefined (fun ev evi has -> has ||
(is_class_evar evd evi && is_resolvable evi))
evd false
let solve_instanciations_problem = ref (fun _ _ _ _ _ -> assert false)
let resolve_typeclasses ?(with_goals=false) ?(split=true) ?(fail=true) env evd =
if not (has_typeclasses evd) then evd
else !solve_instanciations_problem env evd with_goals split fail
| null | https://raw.githubusercontent.com/maximedenes/native-coq/3623a4d9fe95c165f02f7119c0e6564a83a9f4c9/pretyping/typeclasses.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
i
i
This module defines type-classes
The class implementation
The method implementaions as projections.
Sections where the instance should be redeclared,
-1 for discard, 0 for none, mutable to avoid redeclarations
when multiple rebuild_object happen.
* states management
* classes persistent object
* Build the subinstances hints.
* instances persistent object
let path, hints = build_subclasses (not local) (Global.env ()) Evd.empty glob in
* interface functions
match k with
| InternalHole -> true
| _ -> false | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Names
open Libnames
open Decl_kinds
open Term
open Sign
open Evd
open Environ
open Nametab
open Mod_subst
open Errors
open Util
open Typeclasses_errors
open Libobject
let add_instance_hint_ref = ref (fun id local pri -> assert false)
let register_add_instance_hint =
(:=) add_instance_hint_ref
let add_instance_hint id = !add_instance_hint_ref id
let remove_instance_hint_ref = ref (fun id -> assert false)
let register_remove_instance_hint =
(:=) remove_instance_hint_ref
let remove_instance_hint id = !remove_instance_hint_ref id
let set_typeclass_transparency_ref = ref (fun id local c -> assert false)
let register_set_typeclass_transparency =
(:=) set_typeclass_transparency_ref
let set_typeclass_transparency gr local c = !set_typeclass_transparency_ref gr local c
let classes_transparent_state_ref = ref (fun () -> assert false)
let register_classes_transparent_state = (:=) classes_transparent_state_ref
let classes_transparent_state () = !classes_transparent_state_ref ()
let solve_instanciation_problem = ref (fun _ _ _ -> assert false)
let resolve_one_typeclass env evm t =
!solve_instanciation_problem env evm t
type rels = constr list
type direction = Forward | Backward
type typeclass = {
cl_impl : global_reference;
Context in which the definitions are typed . Includes both typeclass parameters and superclasses .
cl_context : (global_reference * bool) option list * rel_context;
Context of definitions and properties on defs , will not be shared
cl_props : rel_context;
cl_projs : (name * (direction * int option) option * constant option) list;
}
module Gmap = Fmap.Make(RefOrdered)
type typeclasses = typeclass Gmap.t
type instance = {
is_class: global_reference;
is_pri: int option;
is_global: int;
is_impl: global_reference;
}
type instances = (instance Gmap.t) Gmap.t
let instance_impl is = is.is_impl
let new_instance cl pri glob impl =
let global =
if glob then Lib.sections_depth ()
else -1
in
{ is_class = cl.cl_impl;
is_pri = pri ;
is_global = global ;
is_impl = impl }
let classes : typeclasses ref = ref Gmap.empty
let instances : instances ref = ref Gmap.empty
let freeze () = !classes, !instances
let unfreeze (cl,is) =
classes:=cl;
instances:=is
let init () =
classes:= Gmap.empty;
instances:= Gmap.empty
let _ =
Summary.declare_summary "classes_and_instances"
{ Summary.freeze_function = freeze;
Summary.unfreeze_function = unfreeze;
Summary.init_function = init }
let class_info c =
try Gmap.find c !classes
with _ -> not_a_class (Global.env()) (constr_of_global c)
let global_class_of_constr env c =
try class_info (global_of_constr c)
with Not_found -> not_a_class env c
let dest_class_app env c =
let cl, args = decompose_app c in
global_class_of_constr env cl, args
let dest_class_arity env c =
let rels, c = Term.decompose_prod_assum c in
rels, dest_class_app env c
let class_of_constr c = try Some (dest_class_arity (Global.env ()) c) with _ -> None
let rec is_class_type evd c =
match kind_of_term c with
| Prod (_, _, t) -> is_class_type evd t
| Evar (e, _) when is_defined evd e -> is_class_type evd (Evarutil.nf_evar evd c)
| _ -> class_of_constr c <> None
let is_class_evar evd evi =
is_class_type evd evi.Evd.evar_concl
let load_class (_, cl) =
classes := Gmap.add cl.cl_impl cl !classes
let cache_class = load_class
let subst_class (subst,cl) =
let do_subst_con c = fst (Mod_subst.subst_con subst c)
and do_subst c = Mod_subst.subst_mps subst c
and do_subst_gr gr = fst (subst_global subst gr) in
let do_subst_ctx ctx = list_smartmap
(fun (na, b, t) -> (na, Option.smartmap do_subst b, do_subst t))
ctx in
let do_subst_context (grs,ctx) =
list_smartmap (Option.smartmap (fun (gr,b) -> do_subst_gr gr, b)) grs,
do_subst_ctx ctx in
let do_subst_projs projs = list_smartmap (fun (x, y, z) -> (x, y, Option.smartmap do_subst_con z)) projs in
{ cl_impl = do_subst_gr cl.cl_impl;
cl_context = do_subst_context cl.cl_context;
cl_props = do_subst_ctx cl.cl_props;
cl_projs = do_subst_projs cl.cl_projs; }
let discharge_class (_,cl) =
let repl = Lib.replacement_context () in
let rel_of_variable_context ctx = List.fold_right
( fun (n,_,b,t) (ctx', subst) ->
let decl = (Name n, Option.map (substn_vars 1 subst) b, substn_vars 1 subst t) in
(decl :: ctx', n :: subst)
) ctx ([], []) in
let discharge_rel_context subst n rel =
let rel = map_rel_context (Cooking.expmod_constr repl) rel in
let ctx, _ =
List.fold_right
(fun (id, b, t) (ctx, k) ->
(id, Option.smartmap (substn_vars k subst) b, substn_vars k subst t) :: ctx, succ k)
rel ([], n)
in ctx
in
let abs_context cl =
match cl.cl_impl with
| VarRef _ | ConstructRef _ -> assert false
| ConstRef cst -> Lib.section_segment_of_constant cst
| IndRef (ind,_) -> Lib.section_segment_of_mutual_inductive ind in
let discharge_context ctx' subst (grs, ctx) =
let grs' =
let newgrs = List.map (fun (_, _, t) ->
match class_of_constr t with
| None -> None
| Some (_, (tc, _)) -> Some (tc.cl_impl, true))
ctx'
in
list_smartmap (Option.smartmap (fun (gr, b) -> Lib.discharge_global gr, b)) grs
@ newgrs
in grs', discharge_rel_context subst 1 ctx @ ctx' in
let cl_impl' = Lib.discharge_global cl.cl_impl in
if cl_impl' == cl.cl_impl then cl else
let ctx = abs_context cl in
let ctx, subst = rel_of_variable_context ctx in
let context = discharge_context ctx subst cl.cl_context in
let props = discharge_rel_context subst (succ (List.length (fst cl.cl_context))) cl.cl_props in
{ cl_impl = cl_impl';
cl_context = context;
cl_props = props;
cl_projs = list_smartmap (fun (x, y, z) -> x, y, Option.smartmap Lib.discharge_con z) cl.cl_projs }
let rebuild_class cl =
try
let cst = Tacred.evaluable_of_global_reference (Global.env ()) cl.cl_impl in
set_typeclass_transparency cst false false; cl
with _ -> cl
let class_input : typeclass -> obj =
declare_object
{ (default_object "type classes state") with
cache_function = cache_class;
load_function = (fun _ -> load_class);
open_function = (fun _ -> load_class);
classify_function = (fun x -> Substitute x);
discharge_function = (fun a -> Some (discharge_class a));
rebuild_function = rebuild_class;
subst_function = subst_class }
let add_class cl =
Lib.add_anonymous_leaf (class_input cl)
let check_instance env sigma c =
try
let (evd, c) = resolve_one_typeclass env sigma
(Retyping.get_type_of env sigma c) in
Evd.is_empty (Evd.undefined_evars evd)
with _ -> false
let build_subclasses ~check env sigma glob pri =
let rec aux pri c =
let ty = Evarutil.nf_evar sigma (Retyping.get_type_of env sigma c) in
match class_of_constr ty with
| None -> []
| Some (rels, (tc, args)) ->
let instapp = Reductionops.whd_beta sigma (appvectc c (Termops.extended_rel_vect 0 rels)) in
let projargs = Array.of_list (args @ [instapp]) in
let projs = list_map_filter
(fun (n, b, proj) ->
match b with
| None -> None
| Some (Backward, _) -> None
| Some (Forward, pri') ->
let proj = Option.get proj in
let body = it_mkLambda_or_LetIn (mkApp (mkConst proj, projargs)) rels in
if check && check_instance env sigma body then None
else
let pri =
match pri, pri' with
| Some p, Some p' -> Some (p + p')
| Some p, None -> Some (p + 1)
| _, _ -> None
in
Some (ConstRef proj, pri, body)) tc.cl_projs
in
let declare_proj hints (cref, pri, body) =
let rest = aux pri body in
hints @ (pri, body) :: rest
in List.fold_left declare_proj [] projs
in aux pri (constr_of_global glob)
type instance_action =
| AddInstance
| RemoveInstance
let load_instance inst =
let insts =
try Gmap.find inst.is_class !instances
with Not_found -> Gmap.empty in
let insts = Gmap.add inst.is_impl inst insts in
instances := Gmap.add inst.is_class insts !instances
let remove_instance inst =
let insts =
try Gmap.find inst.is_class !instances
with Not_found -> assert false in
let insts = Gmap.remove inst.is_impl insts in
instances := Gmap.add inst.is_class insts !instances
let cache_instance (_, (action, i)) =
match action with
| AddInstance -> load_instance i
| RemoveInstance -> remove_instance i
let subst_instance (subst, (action, inst)) = action,
{ inst with
is_class = fst (subst_global subst inst.is_class);
is_impl = fst (subst_global subst inst.is_impl) }
let discharge_instance (_, (action, inst)) =
if inst.is_global <= 0 then None
else Some (action,
{ inst with
is_global = pred inst.is_global;
is_class = Lib.discharge_global inst.is_class;
is_impl = Lib.discharge_global inst.is_impl })
let is_local i = i.is_global = -1
let add_instance check inst =
add_instance_hint (constr_of_global inst.is_impl) (is_local inst) inst.is_pri;
List.iter (fun (pri, c) -> add_instance_hint c (is_local inst) pri)
(build_subclasses ~check:(check && not (isVarRef inst.is_impl))
(Global.env ()) Evd.empty inst.is_impl inst.is_pri)
let rebuild_instance (action, inst) =
if action = AddInstance then add_instance true inst;
(action, inst)
let classify_instance (action, inst) =
if is_local inst then Dispose
else Substitute (action, inst)
let load_instance (_, (action, inst) as ai) =
cache_instance ai;
if action = AddInstance then
add_instance_hint (constr_of_global inst.is_impl) (is_local inst) inst.is_pri
let instance_input : instance_action * instance -> obj =
declare_object
{ (default_object "type classes instances state") with
cache_function = cache_instance;
load_function = (fun _ x -> cache_instance x);
open_function = (fun _ x -> cache_instance x);
classify_function = classify_instance;
discharge_function = discharge_instance;
rebuild_function = rebuild_instance;
subst_function = subst_instance }
let add_instance i =
Lib.add_anonymous_leaf (instance_input (AddInstance, i));
add_instance true i
let remove_instance i =
Lib.add_anonymous_leaf (instance_input (RemoveInstance, i));
remove_instance_hint i.is_impl
let declare_instance pri local glob =
let c = constr_of_global glob in
let ty = Retyping.get_type_of (Global.env ()) Evd.empty c in
match class_of_constr ty with
| Some (rels, (tc, args) as _cl) ->
add_instance (new_instance tc pri (not local) glob)
let entries = List.map ( fun ( path , pri , c ) - > ( pri , local , path , c ) ) hints in
Auto.add_hints local [ typeclasses_db ] ( Auto . HintsResolveEntry entries ) ;
Auto.add_hints local [ ]
( Auto . HintsCutEntry ( PathSeq ( PathStar ( PathAtom ) , path ) ) )
| None -> ()
let add_class cl =
add_class cl;
List.iter (fun (n, inst, body) ->
match inst with
| Some (Backward, pri) ->
declare_instance pri false (ConstRef (Option.get body))
| _ -> ())
cl.cl_projs
open Declarations
let add_constant_class cst =
let ty = Typeops.type_of_constant (Global.env ()) cst in
let ctx, arity = decompose_prod_assum ty in
let tc =
{ cl_impl = ConstRef cst;
cl_context = (List.map (const None) ctx, ctx);
cl_props = [(Anonymous, None, arity)];
cl_projs = []
}
in add_class tc;
set_typeclass_transparency (EvalConstRef cst) false false
let add_inductive_class ind =
let mind, oneind = Global.lookup_inductive ind in
let k =
let ctx = oneind.mind_arity_ctxt in
let ty = Inductive.type_of_inductive_knowing_parameters
(push_rel_context ctx (Global.env ()))
oneind (Termops.extended_rel_vect 0 ctx)
in
{ cl_impl = IndRef ind;
cl_context = List.map (const None) ctx, ctx;
cl_props = [Anonymous, None, ty];
cl_projs = [] }
in add_class k
let instance_constructor cl args =
let lenpars = List.length (List.filter (fun (na, b, t) -> b = None) (snd cl.cl_context)) in
let pars = fst (list_chop lenpars args) in
match cl.cl_impl with
| IndRef ind -> Some (applistc (mkConstruct (ind, 1)) args),
applistc (mkInd ind) pars
| ConstRef cst ->
let term = if args = [] then None else Some (list_last args) in
term, applistc (mkConst cst) pars
| _ -> assert false
let typeclasses () = Gmap.fold (fun _ l c -> l :: c) !classes []
let cmap_elements c = Gmap.fold (fun k v acc -> v :: acc) c []
let instances_of c =
try cmap_elements (Gmap.find c.cl_impl !instances) with Not_found -> []
let all_instances () =
Gmap.fold (fun k v acc ->
Gmap.fold (fun k v acc -> v :: acc) v acc)
!instances []
let instances r =
let cl = class_info r in instances_of cl
let is_class gr =
Gmap.fold (fun k v acc -> acc || v.cl_impl = gr) !classes false
let is_instance = function
| ConstRef c ->
(match Decls.constant_kind c with
| IsDefinition Instance -> true
| _ -> false)
| VarRef v ->
(match Decls.variable_kind v with
| IsDefinition Instance -> true
| _ -> false)
| ConstructRef (ind,_) ->
is_class (IndRef ind)
| _ -> false
let is_implicit_arg k = k <> GoalEvar
ImplicitArg ( ref , ( n , i d ) , b ) - > true
To embed a boolean for resolvability status .
This is essentially a hack to mark which evars correspond to
goals and do not need to be resolved when we have nested [ resolve_all_evars ]
calls ( e.g. when doing apply in an External hint in typeclass_instances ) .
Would be solved by having real evars - as - goals .
: we will only check the resolvability status of undefined evars .
This is essentially a hack to mark which evars correspond to
goals and do not need to be resolved when we have nested [resolve_all_evars]
calls (e.g. when doing apply in an External hint in typeclass_instances).
Would be solved by having real evars-as-goals.
Nota: we will only check the resolvability status of undefined evars.
*)
let resolvable = Store.field ()
open Store.Field
let is_resolvable evi =
assert (evi.evar_body = Evar_empty);
Option.default true (resolvable.get evi.evar_extra)
let mark_resolvability_undef b evi =
let t = resolvable.set b evi.evar_extra in
{ evi with evar_extra = t }
let mark_resolvability b evi =
assert (evi.evar_body = Evar_empty);
mark_resolvability_undef b evi
let mark_unresolvable evi = mark_resolvability false evi
let mark_resolvable evi = mark_resolvability true evi
let mark_resolvability b sigma =
Evd.fold_undefined (fun ev evi evs ->
Evd.add evs ev (mark_resolvability_undef b evi))
sigma (Evd.defined_evars sigma)
let mark_unresolvables sigma = mark_resolvability false sigma
let mark_resolvables sigma = mark_resolvability true sigma
let has_typeclasses evd =
Evd.fold_undefined (fun ev evi has -> has ||
(is_class_evar evd evi && is_resolvable evi))
evd false
let solve_instanciations_problem = ref (fun _ _ _ _ _ -> assert false)
let resolve_typeclasses ?(with_goals=false) ?(split=true) ?(fail=true) env evd =
if not (has_typeclasses evd) then evd
else !solve_instanciations_problem env evd with_goals split fail
|
5a73fe858ad39c9d54a0097c8b0fbf41f4a445377bdb99fb5b934ad8af0fec2a | danieljharvey/mimsa | Module.hs | # LANGUAGE DerivingStrategies #
{-# LANGUAGE OverloadedStrings #-}
module Language.Mimsa.Core.Parser.Module
( parseModule,
moduleParser,
DefPart (..),
)
where
import Data.Char as Char
import Data.Text (Text)
import Language.Mimsa.Core.Parser.Helpers
import Language.Mimsa.Core.Parser.Identifier
import Language.Mimsa.Core.Parser.Identifiers
import Language.Mimsa.Core.Parser.Language
import Language.Mimsa.Core.Parser.Lexeme
import Language.Mimsa.Core.Parser.Literal
import Language.Mimsa.Core.Parser.MonoType
import Language.Mimsa.Core.Types.AST
import Language.Mimsa.Core.Types.Module.Module
import Language.Mimsa.Core.Types.Module.ModuleHash
import Text.Megaparsec hiding (parseTest)
import Text.Megaparsec.Char
parseModule :: Text -> Either ParseErrorType [ModuleItem Annotation]
parseModule = parse (space *> moduleParser <* eof) "repl"
currently fails at the first hurdle
-- since we can parse each thing separately, maybe
we should be making each throw errors for later , but returning ` ` so
-- we can collect all of the separate parse errors at once?
use ` registerParseError ` from -9.2.1/docs/Text-Megaparsec.html
moduleParser :: Parser [ModuleItem Annotation]
moduleParser =
let bigParsers = parseModuleItem <|> parseExport
in mconcat
<$> ( chainl1 ((: []) <$> bigParsers) (pure (<>))
<|> pure mempty
)
-- we've excluded Export here
parseModuleItem :: Parser [ModuleItem Annotation]
parseModuleItem =
parseDef
<|> try typeParser
<|> parseImport
<|> parseInfix
<|> parseTest
-------
-- type definitions
-- type Maybe a = Just a | Nothing
type Tree a = Branch ( Tree a ) a ( Tree a ) | Leaf a
typeParser :: Parser [ModuleItem Annotation]
typeParser = do
td <- typeDeclParser
pure [ModuleDataType td]
-------
-- definitions
def oneHundred = 100
-- def id a = a
-- def exclaim (str: String) = str ++ "!!!"
-- def exclaim2 (str: String): String = str ++ "!!!"
defPartParser :: Parser (DefPart Annotation)
defPartParser =
let parseDefArg = DefArg <$> identifierParser
parseTypeArg =
inBrackets
( do
name <- identifierParser
myString ":"
DefTypedArg name <$> monoTypeParser
)
parseDefType = do
myString ":"
DefType <$> monoTypeParser
in parseDefType <|> parseTypeArg <|> parseDefArg
-- top level definition
parseDef :: Parser [ModuleItem Annotation]
parseDef = do
myString "def"
name <- nameParser
parts <-
chainl1 ((: []) <$> defPartParser) (pure (<>))
<|> pure mempty
myString "="
expr <- expressionParser
pure [ModuleExpression name parts expr]
parseExport :: Parser [ModuleItem Annotation]
parseExport = do
myString "export"
items <- parseModuleItem
pure (ModuleExport <$> items)
parseHash :: Parser ModuleHash
parseHash =
ModuleHash
<$> myLexeme
( takeWhile1P (Just "module hash") Char.isAlphaNum
)
TODO : maybe make these into one parser that handles both to avoid
-- backtracking
parseImport :: Parser [ModuleItem Annotation]
parseImport = try parseImportAll <|> parseImportNamed
` import Prelude from a123123bcbcbcb `
parseImportNamed :: Parser [ModuleItem Annotation]
parseImportNamed = do
myString "import"
modName <- moduleNameParser
myString "from"
hash <- parseHash
pure [ModuleImport (ImportNamedFromHash hash modName)]
-- `import * from a123123bcbcbcb`
parseImportAll :: Parser [ModuleItem Annotation]
parseImportAll = do
myString "import"
myString "*"
myString "from"
hash <- parseHash
pure [ModuleImport (ImportAllFromHash hash)]
-- `infix <|> = altMaybe`
parseInfix :: Parser [ModuleItem Annotation]
parseInfix = do
myString "infix"
infixOp <- infixOpParser
myString "="
boundExpr <- expressionParser
pure [ModuleInfix infixOp boundExpr]
` test " 1 + 1 = = 2 " = 1 + 1 = = 2 `
parseTest :: Parser [ModuleItem Annotation]
parseTest = do
myString "test"
testName <- testNameParser
myString "="
boundExpr <- expressionParser
pure [ModuleTest testName boundExpr]
| null | https://raw.githubusercontent.com/danieljharvey/mimsa/e6b177dd2c38e8a67d6e27063ca600406b3e6b56/core/src/Language/Mimsa/Core/Parser/Module.hs | haskell | # LANGUAGE OverloadedStrings #
since we can parse each thing separately, maybe
we can collect all of the separate parse errors at once?
we've excluded Export here
-----
type definitions
type Maybe a = Just a | Nothing
-----
definitions
def id a = a
def exclaim (str: String) = str ++ "!!!"
def exclaim2 (str: String): String = str ++ "!!!"
top level definition
backtracking
`import * from a123123bcbcbcb`
`infix <|> = altMaybe` | # LANGUAGE DerivingStrategies #
module Language.Mimsa.Core.Parser.Module
( parseModule,
moduleParser,
DefPart (..),
)
where
import Data.Char as Char
import Data.Text (Text)
import Language.Mimsa.Core.Parser.Helpers
import Language.Mimsa.Core.Parser.Identifier
import Language.Mimsa.Core.Parser.Identifiers
import Language.Mimsa.Core.Parser.Language
import Language.Mimsa.Core.Parser.Lexeme
import Language.Mimsa.Core.Parser.Literal
import Language.Mimsa.Core.Parser.MonoType
import Language.Mimsa.Core.Types.AST
import Language.Mimsa.Core.Types.Module.Module
import Language.Mimsa.Core.Types.Module.ModuleHash
import Text.Megaparsec hiding (parseTest)
import Text.Megaparsec.Char
parseModule :: Text -> Either ParseErrorType [ModuleItem Annotation]
parseModule = parse (space *> moduleParser <* eof) "repl"
currently fails at the first hurdle
we should be making each throw errors for later , but returning ` ` so
use ` registerParseError ` from -9.2.1/docs/Text-Megaparsec.html
moduleParser :: Parser [ModuleItem Annotation]
moduleParser =
let bigParsers = parseModuleItem <|> parseExport
in mconcat
<$> ( chainl1 ((: []) <$> bigParsers) (pure (<>))
<|> pure mempty
)
parseModuleItem :: Parser [ModuleItem Annotation]
parseModuleItem =
parseDef
<|> try typeParser
<|> parseImport
<|> parseInfix
<|> parseTest
type Tree a = Branch ( Tree a ) a ( Tree a ) | Leaf a
typeParser :: Parser [ModuleItem Annotation]
typeParser = do
td <- typeDeclParser
pure [ModuleDataType td]
def oneHundred = 100
defPartParser :: Parser (DefPart Annotation)
defPartParser =
let parseDefArg = DefArg <$> identifierParser
parseTypeArg =
inBrackets
( do
name <- identifierParser
myString ":"
DefTypedArg name <$> monoTypeParser
)
parseDefType = do
myString ":"
DefType <$> monoTypeParser
in parseDefType <|> parseTypeArg <|> parseDefArg
parseDef :: Parser [ModuleItem Annotation]
parseDef = do
myString "def"
name <- nameParser
parts <-
chainl1 ((: []) <$> defPartParser) (pure (<>))
<|> pure mempty
myString "="
expr <- expressionParser
pure [ModuleExpression name parts expr]
parseExport :: Parser [ModuleItem Annotation]
parseExport = do
myString "export"
items <- parseModuleItem
pure (ModuleExport <$> items)
parseHash :: Parser ModuleHash
parseHash =
ModuleHash
<$> myLexeme
( takeWhile1P (Just "module hash") Char.isAlphaNum
)
TODO : maybe make these into one parser that handles both to avoid
parseImport :: Parser [ModuleItem Annotation]
parseImport = try parseImportAll <|> parseImportNamed
` import Prelude from a123123bcbcbcb `
parseImportNamed :: Parser [ModuleItem Annotation]
parseImportNamed = do
myString "import"
modName <- moduleNameParser
myString "from"
hash <- parseHash
pure [ModuleImport (ImportNamedFromHash hash modName)]
parseImportAll :: Parser [ModuleItem Annotation]
parseImportAll = do
myString "import"
myString "*"
myString "from"
hash <- parseHash
pure [ModuleImport (ImportAllFromHash hash)]
parseInfix :: Parser [ModuleItem Annotation]
parseInfix = do
myString "infix"
infixOp <- infixOpParser
myString "="
boundExpr <- expressionParser
pure [ModuleInfix infixOp boundExpr]
` test " 1 + 1 = = 2 " = 1 + 1 = = 2 `
parseTest :: Parser [ModuleItem Annotation]
parseTest = do
myString "test"
testName <- testNameParser
myString "="
boundExpr <- expressionParser
pure [ModuleTest testName boundExpr]
|
05b75fe1956937135786e93cfd02a78c26b50e64f18d5070d2aab07015abac52 | fulcrologic/fulcro-rad | resolvers_pathom3_spec.cljc | (ns com.fulcrologic.rad.resolvers-pathom3-spec
(:require
[com.fulcrologic.rad.attributes :as attr]
[com.fulcrologic.rad.attributes-options :as ao]
[com.fulcrologic.rad.authorization :as auth]
[com.fulcrologic.rad.resolvers-pathom3 :as resolvers-pathom3]
;; Pathom3 available on test cp, only
[com.wsscode.pathom3.interface.eql :as p.eql]
[com.wsscode.pathom3.connect.indexes :as pci]
[com.wsscode.pathom3.connect.operation :as pco]
[fulcro-spec.core :refer [assertions specification behavior component =>]]))
(specification "pathom3 resolver generation"
(let [resolve-mock-answer #?(:clj (java.util.Date.)
:cljs (js/Date.))
three-attributes [(attr/new-attribute ::time :inst
{::pco/resolve (fn [_env _input]
{::time resolve-mock-answer})})
(attr/new-attribute ::secret :inst
{::auth/permissions (fn [_] #{})
::pco/resolve (fn [_env _input]
{::secret #inst "2013-12-13"})})
(attr/new-attribute ::ignore-this-attr :string {ao/required? true})]]
(behavior "can do it"
(assertions
(count (resolvers-pathom3/generate-resolvers [])) => 0
(count (resolvers-pathom3/generate-resolvers three-attributes)) => (dec (count three-attributes))))
(behavior "does it correctly"
(let [all-generated-resolvers (resolvers-pathom3/generate-resolvers three-attributes)
base-env (pci/register all-generated-resolvers)
env ((attr/wrap-env three-attributes) base-env)]
(assertions
(every? pco/resolver? all-generated-resolvers) => true
(p.eql/process env [::time]) => {::time resolve-mock-answer}
(p.eql/process env [::secret]) => {::secret ::auth/REDACTED})))))
#_ (clojure.test/run-tests) | null | https://raw.githubusercontent.com/fulcrologic/fulcro-rad/d2a40fdd7ca6ee0ec5fdb3897d5764bb6c5f7800/src/test/com/fulcrologic/rad/resolvers_pathom3_spec.cljc | clojure | Pathom3 available on test cp, only | (ns com.fulcrologic.rad.resolvers-pathom3-spec
(:require
[com.fulcrologic.rad.attributes :as attr]
[com.fulcrologic.rad.attributes-options :as ao]
[com.fulcrologic.rad.authorization :as auth]
[com.fulcrologic.rad.resolvers-pathom3 :as resolvers-pathom3]
[com.wsscode.pathom3.interface.eql :as p.eql]
[com.wsscode.pathom3.connect.indexes :as pci]
[com.wsscode.pathom3.connect.operation :as pco]
[fulcro-spec.core :refer [assertions specification behavior component =>]]))
(specification "pathom3 resolver generation"
(let [resolve-mock-answer #?(:clj (java.util.Date.)
:cljs (js/Date.))
three-attributes [(attr/new-attribute ::time :inst
{::pco/resolve (fn [_env _input]
{::time resolve-mock-answer})})
(attr/new-attribute ::secret :inst
{::auth/permissions (fn [_] #{})
::pco/resolve (fn [_env _input]
{::secret #inst "2013-12-13"})})
(attr/new-attribute ::ignore-this-attr :string {ao/required? true})]]
(behavior "can do it"
(assertions
(count (resolvers-pathom3/generate-resolvers [])) => 0
(count (resolvers-pathom3/generate-resolvers three-attributes)) => (dec (count three-attributes))))
(behavior "does it correctly"
(let [all-generated-resolvers (resolvers-pathom3/generate-resolvers three-attributes)
base-env (pci/register all-generated-resolvers)
env ((attr/wrap-env three-attributes) base-env)]
(assertions
(every? pco/resolver? all-generated-resolvers) => true
(p.eql/process env [::time]) => {::time resolve-mock-answer}
(p.eql/process env [::secret]) => {::secret ::auth/REDACTED})))))
#_ (clojure.test/run-tests) |
df54609a19aeb5cb49953c348d60a6a7fc334f87259a2aff4389f29a64e1d3b3 | anmonteiro/piaf | carl.ml | ----------------------------------------------------------------------------
* Copyright ( c ) 2019 - 2020 ,
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are met :
*
* 1 . Redistributions of source code must retain the above copyright notice ,
* this list of conditions and the following disclaimer .
*
* 2 . Redistributions in binary form must reproduce the above copyright notice ,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution .
*
* 3 . Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission .
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
* AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
* CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS
* INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , IN
* CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE )
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE .
* ---------------------------------------------------------------------------
* Copyright (c) 2019-2020, António Nuno Monteiro
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*---------------------------------------------------------------------------*)
open Eio.Std
open Cmdliner
open Piaf
let setup_log ?style_renderer level =
let pp_header src ppf (l, h) =
if l = Logs.App
then Format.fprintf ppf "%a" Logs_fmt.pp_header (l, h)
else
let x =
match Array.length Sys.argv with
| 0 -> Filename.basename Sys.executable_name
| _n -> Filename.basename Sys.argv.(0)
in
let x =
if Logs.Src.equal src Logs.default then x else Logs.Src.name src
in
Format.fprintf ppf "%s: %a " x Logs_fmt.pp_header (l, h)
in
let format_reporter =
let report src =
let { Logs.report } = Logs_fmt.reporter ~pp_header:(pp_header src) () in
report src
in
{ Logs.report }
in
Fmt_tty.setup_std_outputs ?style_renderer ();
Logs.set_level ~all:true level;
Logs.set_reporter format_reporter
type output =
| Stdout
| Channel of string
type data =
| File of string
| Data of string
type cli =
{ follow_redirects : bool
; max_redirects : int
; meth : Method.t
; log_level : Logs.level option
; urls : string list
; data : data option
; default_proto : string
; head : bool
; headers : (string * string) list
; include_ : bool
; max_http_version : Versions.HTTP.t
; h2c_upgrade : bool
; http2_prior_knowledge : bool
; cacert : Cert.t option
; capath : string option
; clientcert : (Cert.t * Cert.t) option
; min_tls_version : Versions.TLS.t
; max_tls_version : Versions.TLS.t
; insecure : bool
; user_agent : string
; connect_timeout : float
; referer : string option
; compressed : bool
; user : string option
; oauth2_bearer : string option
; output : output
}
let format_header formatter (name, value) =
Format.fprintf formatter "%a: %s" Fmt.(styled `Bold string) name value
let pp_response_headers formatter { Response.headers; status; version; _ } =
let reason_phrase =
match status with
| #Status.standard as st ->
Format.asprintf " %s" (Status.default_reason_phrase st)
| `Code _ -> ""
in
Format.fprintf
formatter
"@[%a %a%s@]@\n@[%a@]"
Versions.HTTP.pp
version
Status.pp_hum
status
reason_phrase
(Format.pp_print_list
~pp_sep:(fun f () -> Format.fprintf f "@\n")
format_header)
(Headers.to_list headers)
let rec uri_of_string ~scheme s =
let maybe_uri = Uri.of_string s in
match Uri.host maybe_uri, Uri.scheme maybe_uri with
| None, _ ->
If Uri.of_string did n't get a host it must mean that the scheme was n't
* even present .
* even present. *)
Logs.debug (fun m ->
m "Protocol not provided for %s. Using the default scheme: %s" s scheme);
uri_of_string ~scheme ("//" ^ s)
| Some _, None ->
(* e.g. `//example.com` *)
Uri.with_scheme maybe_uri (Some scheme)
| Some _, Some _ -> maybe_uri
module Ansi = struct
let clear_line = "\u{1B}[2K"
let line_up = "\u{1B}[A"
let dumb =
try match Sys.getenv "TERM" with "dumb" | "" -> true | _ -> false with
| Not_found -> true
let isatty = try Unix.(isatty stdout) with Unix.Unix_error _ -> false
end
let ok = Ok ()
let print_string ~cli formatter s =
if Ansi.isatty && cli.output = Stdout && String.contains s '\000'
then (
let msg =
"Binary output can mess up your terminal. Use \"--output -\" to tell \
carl to output it to your terminal anyway, or consider \"--output \
<FILE>\" to save to a file."
in
Logs.warn (fun m -> m "%s" msg);
Error (`Msg msg))
else (
Format.fprintf formatter "%s" s;
Format.pp_print_flush formatter ();
ok)
module Size = struct
let gb = int_of_float (1024. ** 3.)
let mb = int_of_float (1024. ** 2.)
let kb = 1024
end
let report_progess ?(first = false) ~cli len total_len =
match cli.output, total_len with
| Channel "-", _ -> ()
| Stdout, _ when Unix.isatty Unix.stdout -> ()
| (Stdout | Channel _), `Fixed total_len ->
let total_bars = 40. in
let pct_complete = Int64.(to_float (div (mul len 100L) total_len)) in
We show 40 bars
let bars = ceil (pct_complete /. (100. /. total_bars)) in
let spaces = total_bars -. bars in
Format.eprintf
"%s[%s%s] %d%%@\n%!"
(if not first then Ansi.clear_line ^ Ansi.line_up else Ansi.clear_line)
(String.concat "" (List.init (int_of_float bars) (fun _ -> "\u{25a0}")))
(String.make (int_of_float spaces) ' ')
(int_of_float pct_complete)
| (Stdout | Channel _), (`Chunked | `Unknown | `Close_delimited) ->
let len = Int64.to_int len in
let len, unit =
match len with
| len when len >= Size.gb -> float_of_int len /. float_of_int Size.gb, "G"
| len when len >= Size.mb -> float_of_int len /. float_of_int Size.mb, "M"
| len when len >= Size.kb -> float_of_int len /. float_of_int Size.kb, "k"
| _ -> float_of_int len, "B"
in
Format.eprintf
"%s Transferred:@;<0 3>@[<v 0>%.2f%s@]@\n%!"
(if not first
then Ansi.clear_line ^ Ansi.line_up ^ Ansi.clear_line ^ Ansi.line_up
else Ansi.clear_line)
len
unit
| _ -> ()
let inflate_chunk zstream result_buffer chunk =
let buf_size = 1024 in
let buf = Bytes.create buf_size in
let rec inner ~off ~len =
let is_end, used_in, used_out =
Zlib.inflate_string zstream chunk off len buf 0 buf_size Zlib.Z_SYNC_FLUSH
in
Buffer.add_subbytes result_buffer buf 0 used_out;
match is_end, used_in < len with
| true, _ ->
assert (used_in <= len);
Zlib.inflate_end zstream
| false, true -> inner ~off:(off + used_in) ~len:(len - used_in)
| false, false -> ()
in
inner ~off:0 ~len:(String.length chunk)
(* TODO: try / catch *)
let inflate response_body =
let open Util.Result.Syntax in
let zstream = Zlib.inflate_init false in
let result_buf = Buffer.create 1024 in
let+ () =
Body.iter_string
~f:(fun chunk -> inflate_chunk zstream result_buf chunk)
response_body
in
Buffer.contents result_buf
let handle_response
~cli
~sw
~(stdout : Eio.Flow.sink)
({ Response.body; _ } as response)
=
let open Util.Result.Syntax in
let { head; compressed; include_; _ } = cli in
let* channel, formatter =
match cli.output with
| Stdout | Channel "-" -> Ok (stdout, Format.std_formatter)
| Channel filename ->
(try
Eio_unix.run_in_systhread (fun () ->
let fd =
Unix.openfile
filename
Unix.[ O_NONBLOCK; O_WRONLY; O_TRUNC; O_CREAT ]
0o600
in
Ok
( (Eio_unix.FD.as_socket ~sw ~close_unix:true fd :> Eio.Flow.sink)
, Format.formatter_of_out_channel (Unix.out_channel_of_descr fd)
))
with
| exn -> Error (`Exn exn))
in
if head || include_
then (
Format.fprintf formatter "%a" pp_response_headers response;
Format.pp_print_flush formatter ());
let result =
if head
then (
Fiber.fork ~sw (fun () ->
let (_ : (unit, _) result) = Body.drain body in
());
ok)
else
match compressed, Headers.get response.headers "content-encoding" with
| true, Some encoding when String.lowercase_ascii encoding = "gzip" ->
(* We requested a compressed response, and we got a compressed response
* back. *)
let* response_body_str = Body.to_string body in
(match Ezgzip.decompress response_body_str with
| Ok body_str -> print_string ~cli formatter body_str
| Error _ -> assert false)
| true, Some encoding when String.lowercase_ascii encoding = "deflate" ->
(* We requested a compressed response, and we got a compressed response
* back. *)
let* s = inflate body in
print_string ~cli formatter s
| _ ->
let stream = Body.to_stream body in
let total_len = Body.length body in
(try
match Stream.take stream with
| Some { Piaf.IOVec.buffer; off; len } ->
let running_total = Int64.of_int len in
report_progess ~first:true ~cli running_total total_len;
let chunk = Bigstringaf.substring buffer ~off ~len in
let* () = print_string ~cli formatter chunk in
let+ (_ret : int64) =
Body.fold
~f:(fun running_total { Piaf.IOVec.buffer; off; len } ->
let new_total = Int64.(add (of_int len) running_total) in
report_progess ~cli new_total total_len;
let body_fragment = Bigstringaf.substring buffer ~off ~len in
let (_ : _ result) =
print_string ~cli formatter body_fragment
in
new_total)
~init:running_total
body
in
()
| None -> assert false
with
| exn -> Error (`Exn exn))
in
(match cli.output with
| Stdout | Channel "-" -> Format.pp_print_newline formatter ()
| Channel _ ->
Eio_unix.run_in_systhread (fun () ->
Unix.close (Option.get (Eio_unix.FD.peek_opt channel))));
result
let build_headers
~cli:{ headers; user_agent; referer; compressed; oauth2_bearer; user; _ }
=
let headers = ("User-Agent", user_agent) :: headers in
let headers =
match referer with
| None -> headers
| Some referer -> ("Referer", referer) :: headers
in
let headers =
if compressed
then ("Accept-Encoding", "deflate, gzip") :: headers
else headers
in
match oauth2_bearer, user with
| Some token, _ ->
Logs.debug (fun m ->
let user = match user with Some user -> user | None -> "''" in
m "Server authorization using Bearer with user %s" user);
Bearer token overrides ` user `
("Authorization", "Bearer " ^ token) :: headers
| None, Some user ->
Logs.debug (fun m -> m "Server authorization using Basic with user %s" user);
("Authorization", "Basic " ^ Base64.encode_exn user) :: headers
| None, None -> headers
let request env ~sw ~cli ~config uri =
let module Client = Client.Oneshot in
let { meth; data; _ } = cli in
let uri_user = Uri.userinfo uri in
let cli =
match cli.user with
| None -> { cli with user = uri_user }
| Some _ ->
` -u ` overrides the URI userinfo
cli
in
let headers = build_headers ~cli in
let body =
match data with
| Some (Data s) -> Some (Body.of_string s)
| Some (File filename) ->
let fd = Unix.openfile filename [ O_RDONLY ] 0 in
let { Unix.st_size = length; _ } =
Eio_unix.run_in_systhread (fun () -> Unix.fstat fd)
in
let remaining = ref length in
let flow = Eio_unix.FD.as_socket ~sw ~close_unix:true fd in
let stream =
Stream.from ~f:(fun () ->
if !remaining = 0
then None
else
let len = min config.Config.body_buffer_size !remaining in
let cs = Cstruct.create len in
Eio.Flow.read_exact flow cs;
remaining := !remaining - len;
Some { Faraday.buffer = cs.buffer; off = cs.off; len = cs.len })
in
Fiber.fork ~sw (fun () ->
Stream.when_closed ~f:(fun () -> Eio.Flow.close flow) stream);
let body_length =
match
List.find_opt
(fun (nm, _) -> String.lowercase_ascii nm = "transfer-encoding")
headers
with
| Some (_, "chunked") -> `Chunked
| _ -> `Fixed (Int64.of_int length)
in
Some (Body.of_stream ~length:body_length stream)
| None -> None
in
let open Util.Result.Syntax in
let* response = Client.request ~sw ~config ~meth ~headers ?body env uri in
handle_response ~cli ~sw ~stdout:(Eio.Stdenv.stdout env) response
let rec request_many ~sw ~cli ~config env urls =
let { default_proto; _ } = cli in
match urls with
| [] ->
(* Never happens, cmdliner guarantees we get a non-empty list. *)
assert false
| [ x ] ->
let uri = uri_of_string ~scheme:default_proto x in
let r = request ~sw ~cli ~config env uri in
(match r with
| Ok () -> `Ok ()
| Error e -> `Error (false, Error.to_string e))
| x :: xs ->
let uri = uri_of_string ~scheme:default_proto x in
let _r = request ~sw ~cli ~config env uri in
request_many ~sw ~cli ~config env xs
let log_level_of_list ~silent = function
| [] -> if silent then None else Some Logs.Warning
| [ _ ] -> Some Info
| _ -> Some Debug
let piaf_config_of_cli
{ follow_redirects
; max_redirects
; max_http_version
; h2c_upgrade
; http2_prior_knowledge
; cacert
; capath
; insecure
; min_tls_version
; max_tls_version
; connect_timeout
; data
; head
; _
}
=
match data, head with
| Some _, true ->
let msg =
"You can only select one HTTP request method! You asked for both POST \
(-d / --data) and HEAD (-I / --head)"
in
Logs.warn (fun m -> m "%s" msg);
Error msg
| _, _ ->
Ok
{ Config.default with
follow_redirects
; max_redirects
; max_http_version
; h2c_upgrade
; http2_prior_knowledge
; cacert
; capath
; allow_insecure = insecure
; min_tls_version
; max_tls_version
; connect_timeout
; body_buffer_size = 0x10000
}
let main ({ log_level; urls; _ } as cli) =
setup_log log_level;
if (not Ansi.dumb) && Ansi.isatty
then Fmt.set_style_renderer (Format.get_std_formatter ()) `Ansi_tty;
match piaf_config_of_cli cli with
| Error msg -> `Error (false, msg)
| Ok config ->
Eio_main.run (fun env ->
Eio.Switch.run (fun sw -> request_many ~sw ~cli ~config env urls))
(* --resolve <host:port:address[,address]...> Resolve the host+port to this address
* --retry <num> Retry request if transient problems occur
* --retry-connrefused Retry on connection refused (use with --retry)
* --retry-delay <seconds> Wait time between retries
* --retry-max-time <seconds> Retry only within this period
*)
module CLI = struct
let request =
let request_conv =
let parse meth = Ok (Method.of_string meth) in
let print = Method.pp_hum in
Arg.conv ~docv:"method" (parse, print)
in
let doc = "Specify request method to use" in
let docv = "method" in
Arg.(
value & opt (some request_conv) None & info [ "X"; "request" ] ~doc ~docv)
let cacert =
let cert_conv =
let parse s = Ok (Cert.Filepath s) in
Arg.conv ~docv:"method" (parse, Cert.pp)
in
let doc = "CA certificate to verify peer against" in
let docv = "file" in
Arg.(value & opt (some cert_conv) None & info [ "cacert" ] ~doc ~docv)
let capath =
let doc = "CA directory to verify peer against" in
let docv = "dir" in
Arg.(value & opt (some string) None & info [ "capath" ] ~doc ~docv)
let cert =
let doc = "Client certificate file path" in
let docv = "file" in
Arg.(value & opt (some string) None & info [ "E"; "cert" ] ~doc ~docv)
let compressed =
let doc = "Request compressed response" in
Arg.(value & flag & info [ "compressed" ] ~doc)
let connect_timeout =
let doc = "Maximum time allowed for connection" in
let docv = "seconds" in
Arg.(value & opt float 30. & info [ "connect-timeout" ] ~doc ~docv)
let data =
let doc = "HTTP POST data" in
let docv = "data" in
Arg.(value & opt (some string) None & info [ "d"; "data" ] ~doc ~docv)
let insecure =
let doc = "Allow insecure server connections when using SSL" in
Arg.(value & flag & info [ "k"; "insecure" ] ~doc)
let key =
let doc = "Client certificate private key" in
let docv = "file" in
Arg.(value & opt (some string) None & info [ "key" ] ~doc ~docv)
let default_proto =
let doc = "Use $(docv) for any URL missing a scheme (without `://`)" in
let docv = "protocol" in
Arg.(value & opt string "http" & info [ "proto-default" ] ~doc ~docv)
let head =
let doc = "Show document info only" in
Arg.(value & flag & info [ "I"; "head" ] ~doc)
let headers =
let header_conv =
let parse header =
match String.split_on_char ':' header with
| [] -> Error (`Msg "Header can't be the empty string")
| [ x ] ->
Error
(`Msg (Format.asprintf "Expecting `name: value` string, got: %s" x))
| name :: values ->
let value = Util.String.trim_left (String.concat ":" values) in
Ok (name, value)
in
let print = format_header in
Arg.conv ~docv:"method" (parse, print)
in
let doc = "Pass custom header(s) to server" in
let docv = "header" in
Arg.(value & opt_all header_conv [] & info [ "H"; "header" ] ~doc ~docv)
let include_ =
let doc = "Include protocol response headers in the output" in
Arg.(value & flag & info [ "i"; "include" ] ~doc)
let follow_redirects =
let doc = "Follow redirects" in
Arg.(value & flag & info [ "L"; "location" ] ~doc)
let max_redirects =
let doc = "Max number of redirects to follow" in
let docv = "int" in
Arg.(
value
& opt int Config.default.max_redirects
& info [ "max-redirs" ] ~doc ~docv)
let use_http_1_0 =
let doc = "Use HTTP 1.0" in
Arg.(value & flag & info [ "0"; "http1.0" ] ~doc)
let use_http_1_1 =
let doc = "Use HTTP 1.1" in
Arg.(value & flag & info [ "http1.1" ] ~doc)
let use_http_2 =
let doc = "Use HTTP 2" in
Arg.(value & flag & info [ "http2" ] ~doc)
let http_2_prior_knowledge =
let doc = "Use HTTP 2 without HTTP/1.1 Upgrade" in
Arg.(value & flag & info [ "http2-prior-knowledge" ] ~doc)
let referer =
let doc = "Referrer URL" in
let docv = "URL" in
Arg.(value & opt (some string) None & info [ "e"; "referer" ] ~doc ~docv)
let silent =
let doc = "Silent mode" in
Arg.(value & flag & info [ "s"; "silent" ] ~doc)
let verbose =
let doc = "Verbosity (use multiple times to increase)" in
Arg.(value & flag_all & info [ "v"; "verbose" ] ~doc)
let sslv3 =
let doc = "Use SSLv3" in
Arg.(value & flag & info [ "3"; "sslv3" ] ~doc)
let tlsv1 =
let doc = "Use TLSv1.0 or greater" in
Arg.(value & flag & info [ "1"; "tlsv1" ] ~doc)
let tlsv1_0 =
let doc = "Use TLSv1.0 or greater" in
Arg.(value & flag & info [ "tlsv1.0" ] ~doc)
let tlsv1_1 =
let doc = "Use TLSv1.1 or greater" in
Arg.(value & flag & info [ "tlsv1.1" ] ~doc)
let tlsv1_2 =
let doc = "Use TLSv1.2 or greater" in
Arg.(value & flag & info [ "tlsv1.2" ] ~doc)
let tlsv1_3 =
let doc = "Use TLSv1.3 or greater" in
Arg.(value & flag & info [ "tlsv1.3" ] ~doc)
let tls_max_version =
let tls_conv =
let parse s =
match Versions.TLS.of_string s with
| Ok v -> Ok v
| Error msg -> Error (`Msg msg)
in
let print = Versions.TLS.pp_hum in
Arg.conv ~docv:"" (parse, print)
in
let doc = "Set maximum allowed TLS version" in
let docv = "version" in
Arg.(
value & opt tls_conv Versions.TLS.TLSv1_3 & info [ "tls-max" ] ~doc ~docv)
let upload_file =
let doc = "Transfer local $(docv) to destination" in
let docv = "file" in
Arg.(
value & opt (some string) None & info [ "T"; "upload-file" ] ~doc ~docv)
let user_agent =
let doc = "Send User-Agent $(docv) to server" in
let docv = "name" in
Arg.(
value
& opt string "carl/0.0.0-experimental"
& info [ "A"; "user-agent" ] ~doc ~docv)
let user =
let doc = "Server user and password" in
let docv = "user:password" in
Arg.(value & opt (some string) None & info [ "u"; "user" ] ~doc ~docv)
let oauth2_bearer =
let doc = "OAuth 2 Bearer Token" in
let docv = "token" in
Arg.(value & opt (some string) None & info [ "oauth2-bearer" ] ~doc ~docv)
let output =
let output_conv =
let parse s =
let output = Channel s in
Ok output
in
let print formatter output =
let s = match output with Stdout -> "stdout" | Channel f -> f in
Format.fprintf formatter "%s" s
in
Arg.conv ~docv:"method" (parse, print)
in
let doc = "Write to file instead of stdout" in
let docv = "file" in
Arg.(value & opt output_conv Stdout & info [ "o"; "output" ] ~doc ~docv)
let urls =
let docv = "URLs" in
Arg.(non_empty & pos_all string [] & info [] ~docv)
let parse
cacert
capath
cert
compressed
connect_timeout
data
default_proto
head
headers
include_
insecure
key
follow_redirects
max_redirects
request
use_http_1_0
use_http_1_1
use_http_2
http2_prior_knowledge
referer
sslv3
tlsv1
tlsv1_0
tlsv1_1
tlsv1_2
tlsv1_3
max_tls_version
upload_file
user_agent
user
oauth2_bearer
silent
verbose
output
urls
=
{ follow_redirects
; max_redirects
; data =
(match data, upload_file with
| None, None -> None
| Some data, _ ->
(* `-d` takes precedence over `-T` *)
Some (Data data)
| None, Some filename -> Some (File filename))
; meth =
(match head, request, data with
| true, None, None -> `HEAD
| _, None, Some _ -> `POST
| _, None, None -> `GET
| _, Some meth, _ -> meth)
; log_level = log_level_of_list ~silent verbose
; urls
; default_proto
; head
; headers
; include_
; max_http_version =
(match use_http_2, use_http_1_1, use_http_1_0 with
| true, _, _ | false, false, false ->
(* Default to the highest supported if no override specified. *)
Versions.HTTP.HTTP_2
| false, true, _ -> HTTP_1_1
| false, false, true -> HTTP_1_0)
; h2c_upgrade = use_http_2
; http2_prior_knowledge
; cacert
; capath
; clientcert =
(match cert, key with
| Some cert, Some key -> Some (Cert.Filepath cert, Cert.Filepath key)
| _ -> None)
; min_tls_version =
(* select the _maximum_ min version *)
Versions.TLS.(
match tlsv1_3, tlsv1_2, tlsv1_1, tlsv1_0, tlsv1, sslv3 with
| true, _, _, _, _, _ -> TLSv1_3
| _, true, _, _, _, _ -> TLSv1_2
| _, _, true, _, _, _ -> TLSv1_1
| _, _, _, true, _, _ -> TLSv1_0
| _, _, _, _, true, _ -> TLSv1_0
| _, _, _, _, _, true -> SSLv3
| _, _, _, _, _, _ -> TLSv1_0)
; max_tls_version
; insecure
; user_agent
; compressed
; connect_timeout
; referer
; user
; oauth2_bearer
; output
}
let default_cmd =
Term.(
const parse
$ cacert
$ capath
$ cert
$ compressed
$ connect_timeout
$ data
$ default_proto
$ head
$ headers
$ include_
$ insecure
$ key
$ follow_redirects
$ max_redirects
$ request
$ use_http_1_0
$ use_http_1_1
$ use_http_2
$ http_2_prior_knowledge
$ referer
$ sslv3
$ tlsv1
$ tlsv1_0
$ tlsv1_1
$ tlsv1_2
$ tlsv1_3
$ tls_max_version
$ upload_file
$ user_agent
$ user
$ oauth2_bearer
$ silent
$ verbose
$ output
$ urls)
let cmd =
let doc = "Like curl, for caml" in
let info = Cmd.info "carl" ~version:"todo" ~doc in
Cmd.v info Term.(ret (const main $ default_cmd))
end
let () = exit (Cmd.eval CLI.cmd)
| null | https://raw.githubusercontent.com/anmonteiro/piaf/3b6a79d720c2767601396dd37a940787a2f095db/bin/carl.ml | ocaml | e.g. `//example.com`
TODO: try / catch
We requested a compressed response, and we got a compressed response
* back.
We requested a compressed response, and we got a compressed response
* back.
Never happens, cmdliner guarantees we get a non-empty list.
--resolve <host:port:address[,address]...> Resolve the host+port to this address
* --retry <num> Retry request if transient problems occur
* --retry-connrefused Retry on connection refused (use with --retry)
* --retry-delay <seconds> Wait time between retries
* --retry-max-time <seconds> Retry only within this period
`-d` takes precedence over `-T`
Default to the highest supported if no override specified.
select the _maximum_ min version | ----------------------------------------------------------------------------
* Copyright ( c ) 2019 - 2020 ,
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are met :
*
* 1 . Redistributions of source code must retain the above copyright notice ,
* this list of conditions and the following disclaimer .
*
* 2 . Redistributions in binary form must reproduce the above copyright notice ,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution .
*
* 3 . Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission .
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
* AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
* CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS
* INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , IN
* CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE )
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE .
* ---------------------------------------------------------------------------
* Copyright (c) 2019-2020, António Nuno Monteiro
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*---------------------------------------------------------------------------*)
open Eio.Std
open Cmdliner
open Piaf
let setup_log ?style_renderer level =
let pp_header src ppf (l, h) =
if l = Logs.App
then Format.fprintf ppf "%a" Logs_fmt.pp_header (l, h)
else
let x =
match Array.length Sys.argv with
| 0 -> Filename.basename Sys.executable_name
| _n -> Filename.basename Sys.argv.(0)
in
let x =
if Logs.Src.equal src Logs.default then x else Logs.Src.name src
in
Format.fprintf ppf "%s: %a " x Logs_fmt.pp_header (l, h)
in
let format_reporter =
let report src =
let { Logs.report } = Logs_fmt.reporter ~pp_header:(pp_header src) () in
report src
in
{ Logs.report }
in
Fmt_tty.setup_std_outputs ?style_renderer ();
Logs.set_level ~all:true level;
Logs.set_reporter format_reporter
type output =
| Stdout
| Channel of string
type data =
| File of string
| Data of string
type cli =
{ follow_redirects : bool
; max_redirects : int
; meth : Method.t
; log_level : Logs.level option
; urls : string list
; data : data option
; default_proto : string
; head : bool
; headers : (string * string) list
; include_ : bool
; max_http_version : Versions.HTTP.t
; h2c_upgrade : bool
; http2_prior_knowledge : bool
; cacert : Cert.t option
; capath : string option
; clientcert : (Cert.t * Cert.t) option
; min_tls_version : Versions.TLS.t
; max_tls_version : Versions.TLS.t
; insecure : bool
; user_agent : string
; connect_timeout : float
; referer : string option
; compressed : bool
; user : string option
; oauth2_bearer : string option
; output : output
}
let format_header formatter (name, value) =
Format.fprintf formatter "%a: %s" Fmt.(styled `Bold string) name value
let pp_response_headers formatter { Response.headers; status; version; _ } =
let reason_phrase =
match status with
| #Status.standard as st ->
Format.asprintf " %s" (Status.default_reason_phrase st)
| `Code _ -> ""
in
Format.fprintf
formatter
"@[%a %a%s@]@\n@[%a@]"
Versions.HTTP.pp
version
Status.pp_hum
status
reason_phrase
(Format.pp_print_list
~pp_sep:(fun f () -> Format.fprintf f "@\n")
format_header)
(Headers.to_list headers)
let rec uri_of_string ~scheme s =
let maybe_uri = Uri.of_string s in
match Uri.host maybe_uri, Uri.scheme maybe_uri with
| None, _ ->
If Uri.of_string did n't get a host it must mean that the scheme was n't
* even present .
* even present. *)
Logs.debug (fun m ->
m "Protocol not provided for %s. Using the default scheme: %s" s scheme);
uri_of_string ~scheme ("//" ^ s)
| Some _, None ->
Uri.with_scheme maybe_uri (Some scheme)
| Some _, Some _ -> maybe_uri
module Ansi = struct
let clear_line = "\u{1B}[2K"
let line_up = "\u{1B}[A"
let dumb =
try match Sys.getenv "TERM" with "dumb" | "" -> true | _ -> false with
| Not_found -> true
let isatty = try Unix.(isatty stdout) with Unix.Unix_error _ -> false
end
let ok = Ok ()
let print_string ~cli formatter s =
if Ansi.isatty && cli.output = Stdout && String.contains s '\000'
then (
let msg =
"Binary output can mess up your terminal. Use \"--output -\" to tell \
carl to output it to your terminal anyway, or consider \"--output \
<FILE>\" to save to a file."
in
Logs.warn (fun m -> m "%s" msg);
Error (`Msg msg))
else (
Format.fprintf formatter "%s" s;
Format.pp_print_flush formatter ();
ok)
module Size = struct
let gb = int_of_float (1024. ** 3.)
let mb = int_of_float (1024. ** 2.)
let kb = 1024
end
let report_progess ?(first = false) ~cli len total_len =
match cli.output, total_len with
| Channel "-", _ -> ()
| Stdout, _ when Unix.isatty Unix.stdout -> ()
| (Stdout | Channel _), `Fixed total_len ->
let total_bars = 40. in
let pct_complete = Int64.(to_float (div (mul len 100L) total_len)) in
We show 40 bars
let bars = ceil (pct_complete /. (100. /. total_bars)) in
let spaces = total_bars -. bars in
Format.eprintf
"%s[%s%s] %d%%@\n%!"
(if not first then Ansi.clear_line ^ Ansi.line_up else Ansi.clear_line)
(String.concat "" (List.init (int_of_float bars) (fun _ -> "\u{25a0}")))
(String.make (int_of_float spaces) ' ')
(int_of_float pct_complete)
| (Stdout | Channel _), (`Chunked | `Unknown | `Close_delimited) ->
let len = Int64.to_int len in
let len, unit =
match len with
| len when len >= Size.gb -> float_of_int len /. float_of_int Size.gb, "G"
| len when len >= Size.mb -> float_of_int len /. float_of_int Size.mb, "M"
| len when len >= Size.kb -> float_of_int len /. float_of_int Size.kb, "k"
| _ -> float_of_int len, "B"
in
Format.eprintf
"%s Transferred:@;<0 3>@[<v 0>%.2f%s@]@\n%!"
(if not first
then Ansi.clear_line ^ Ansi.line_up ^ Ansi.clear_line ^ Ansi.line_up
else Ansi.clear_line)
len
unit
| _ -> ()
let inflate_chunk zstream result_buffer chunk =
let buf_size = 1024 in
let buf = Bytes.create buf_size in
let rec inner ~off ~len =
let is_end, used_in, used_out =
Zlib.inflate_string zstream chunk off len buf 0 buf_size Zlib.Z_SYNC_FLUSH
in
Buffer.add_subbytes result_buffer buf 0 used_out;
match is_end, used_in < len with
| true, _ ->
assert (used_in <= len);
Zlib.inflate_end zstream
| false, true -> inner ~off:(off + used_in) ~len:(len - used_in)
| false, false -> ()
in
inner ~off:0 ~len:(String.length chunk)
let inflate response_body =
let open Util.Result.Syntax in
let zstream = Zlib.inflate_init false in
let result_buf = Buffer.create 1024 in
let+ () =
Body.iter_string
~f:(fun chunk -> inflate_chunk zstream result_buf chunk)
response_body
in
Buffer.contents result_buf
let handle_response
~cli
~sw
~(stdout : Eio.Flow.sink)
({ Response.body; _ } as response)
=
let open Util.Result.Syntax in
let { head; compressed; include_; _ } = cli in
let* channel, formatter =
match cli.output with
| Stdout | Channel "-" -> Ok (stdout, Format.std_formatter)
| Channel filename ->
(try
Eio_unix.run_in_systhread (fun () ->
let fd =
Unix.openfile
filename
Unix.[ O_NONBLOCK; O_WRONLY; O_TRUNC; O_CREAT ]
0o600
in
Ok
( (Eio_unix.FD.as_socket ~sw ~close_unix:true fd :> Eio.Flow.sink)
, Format.formatter_of_out_channel (Unix.out_channel_of_descr fd)
))
with
| exn -> Error (`Exn exn))
in
if head || include_
then (
Format.fprintf formatter "%a" pp_response_headers response;
Format.pp_print_flush formatter ());
let result =
if head
then (
Fiber.fork ~sw (fun () ->
let (_ : (unit, _) result) = Body.drain body in
());
ok)
else
match compressed, Headers.get response.headers "content-encoding" with
| true, Some encoding when String.lowercase_ascii encoding = "gzip" ->
let* response_body_str = Body.to_string body in
(match Ezgzip.decompress response_body_str with
| Ok body_str -> print_string ~cli formatter body_str
| Error _ -> assert false)
| true, Some encoding when String.lowercase_ascii encoding = "deflate" ->
let* s = inflate body in
print_string ~cli formatter s
| _ ->
let stream = Body.to_stream body in
let total_len = Body.length body in
(try
match Stream.take stream with
| Some { Piaf.IOVec.buffer; off; len } ->
let running_total = Int64.of_int len in
report_progess ~first:true ~cli running_total total_len;
let chunk = Bigstringaf.substring buffer ~off ~len in
let* () = print_string ~cli formatter chunk in
let+ (_ret : int64) =
Body.fold
~f:(fun running_total { Piaf.IOVec.buffer; off; len } ->
let new_total = Int64.(add (of_int len) running_total) in
report_progess ~cli new_total total_len;
let body_fragment = Bigstringaf.substring buffer ~off ~len in
let (_ : _ result) =
print_string ~cli formatter body_fragment
in
new_total)
~init:running_total
body
in
()
| None -> assert false
with
| exn -> Error (`Exn exn))
in
(match cli.output with
| Stdout | Channel "-" -> Format.pp_print_newline formatter ()
| Channel _ ->
Eio_unix.run_in_systhread (fun () ->
Unix.close (Option.get (Eio_unix.FD.peek_opt channel))));
result
let build_headers
~cli:{ headers; user_agent; referer; compressed; oauth2_bearer; user; _ }
=
let headers = ("User-Agent", user_agent) :: headers in
let headers =
match referer with
| None -> headers
| Some referer -> ("Referer", referer) :: headers
in
let headers =
if compressed
then ("Accept-Encoding", "deflate, gzip") :: headers
else headers
in
match oauth2_bearer, user with
| Some token, _ ->
Logs.debug (fun m ->
let user = match user with Some user -> user | None -> "''" in
m "Server authorization using Bearer with user %s" user);
Bearer token overrides ` user `
("Authorization", "Bearer " ^ token) :: headers
| None, Some user ->
Logs.debug (fun m -> m "Server authorization using Basic with user %s" user);
("Authorization", "Basic " ^ Base64.encode_exn user) :: headers
| None, None -> headers
let request env ~sw ~cli ~config uri =
let module Client = Client.Oneshot in
let { meth; data; _ } = cli in
let uri_user = Uri.userinfo uri in
let cli =
match cli.user with
| None -> { cli with user = uri_user }
| Some _ ->
` -u ` overrides the URI userinfo
cli
in
let headers = build_headers ~cli in
let body =
match data with
| Some (Data s) -> Some (Body.of_string s)
| Some (File filename) ->
let fd = Unix.openfile filename [ O_RDONLY ] 0 in
let { Unix.st_size = length; _ } =
Eio_unix.run_in_systhread (fun () -> Unix.fstat fd)
in
let remaining = ref length in
let flow = Eio_unix.FD.as_socket ~sw ~close_unix:true fd in
let stream =
Stream.from ~f:(fun () ->
if !remaining = 0
then None
else
let len = min config.Config.body_buffer_size !remaining in
let cs = Cstruct.create len in
Eio.Flow.read_exact flow cs;
remaining := !remaining - len;
Some { Faraday.buffer = cs.buffer; off = cs.off; len = cs.len })
in
Fiber.fork ~sw (fun () ->
Stream.when_closed ~f:(fun () -> Eio.Flow.close flow) stream);
let body_length =
match
List.find_opt
(fun (nm, _) -> String.lowercase_ascii nm = "transfer-encoding")
headers
with
| Some (_, "chunked") -> `Chunked
| _ -> `Fixed (Int64.of_int length)
in
Some (Body.of_stream ~length:body_length stream)
| None -> None
in
let open Util.Result.Syntax in
let* response = Client.request ~sw ~config ~meth ~headers ?body env uri in
handle_response ~cli ~sw ~stdout:(Eio.Stdenv.stdout env) response
let rec request_many ~sw ~cli ~config env urls =
let { default_proto; _ } = cli in
match urls with
| [] ->
assert false
| [ x ] ->
let uri = uri_of_string ~scheme:default_proto x in
let r = request ~sw ~cli ~config env uri in
(match r with
| Ok () -> `Ok ()
| Error e -> `Error (false, Error.to_string e))
| x :: xs ->
let uri = uri_of_string ~scheme:default_proto x in
let _r = request ~sw ~cli ~config env uri in
request_many ~sw ~cli ~config env xs
let log_level_of_list ~silent = function
| [] -> if silent then None else Some Logs.Warning
| [ _ ] -> Some Info
| _ -> Some Debug
let piaf_config_of_cli
{ follow_redirects
; max_redirects
; max_http_version
; h2c_upgrade
; http2_prior_knowledge
; cacert
; capath
; insecure
; min_tls_version
; max_tls_version
; connect_timeout
; data
; head
; _
}
=
match data, head with
| Some _, true ->
let msg =
"You can only select one HTTP request method! You asked for both POST \
(-d / --data) and HEAD (-I / --head)"
in
Logs.warn (fun m -> m "%s" msg);
Error msg
| _, _ ->
Ok
{ Config.default with
follow_redirects
; max_redirects
; max_http_version
; h2c_upgrade
; http2_prior_knowledge
; cacert
; capath
; allow_insecure = insecure
; min_tls_version
; max_tls_version
; connect_timeout
; body_buffer_size = 0x10000
}
let main ({ log_level; urls; _ } as cli) =
setup_log log_level;
if (not Ansi.dumb) && Ansi.isatty
then Fmt.set_style_renderer (Format.get_std_formatter ()) `Ansi_tty;
match piaf_config_of_cli cli with
| Error msg -> `Error (false, msg)
| Ok config ->
Eio_main.run (fun env ->
Eio.Switch.run (fun sw -> request_many ~sw ~cli ~config env urls))
module CLI = struct
let request =
let request_conv =
let parse meth = Ok (Method.of_string meth) in
let print = Method.pp_hum in
Arg.conv ~docv:"method" (parse, print)
in
let doc = "Specify request method to use" in
let docv = "method" in
Arg.(
value & opt (some request_conv) None & info [ "X"; "request" ] ~doc ~docv)
let cacert =
let cert_conv =
let parse s = Ok (Cert.Filepath s) in
Arg.conv ~docv:"method" (parse, Cert.pp)
in
let doc = "CA certificate to verify peer against" in
let docv = "file" in
Arg.(value & opt (some cert_conv) None & info [ "cacert" ] ~doc ~docv)
let capath =
let doc = "CA directory to verify peer against" in
let docv = "dir" in
Arg.(value & opt (some string) None & info [ "capath" ] ~doc ~docv)
let cert =
let doc = "Client certificate file path" in
let docv = "file" in
Arg.(value & opt (some string) None & info [ "E"; "cert" ] ~doc ~docv)
let compressed =
let doc = "Request compressed response" in
Arg.(value & flag & info [ "compressed" ] ~doc)
let connect_timeout =
let doc = "Maximum time allowed for connection" in
let docv = "seconds" in
Arg.(value & opt float 30. & info [ "connect-timeout" ] ~doc ~docv)
let data =
let doc = "HTTP POST data" in
let docv = "data" in
Arg.(value & opt (some string) None & info [ "d"; "data" ] ~doc ~docv)
let insecure =
let doc = "Allow insecure server connections when using SSL" in
Arg.(value & flag & info [ "k"; "insecure" ] ~doc)
let key =
let doc = "Client certificate private key" in
let docv = "file" in
Arg.(value & opt (some string) None & info [ "key" ] ~doc ~docv)
let default_proto =
let doc = "Use $(docv) for any URL missing a scheme (without `://`)" in
let docv = "protocol" in
Arg.(value & opt string "http" & info [ "proto-default" ] ~doc ~docv)
let head =
let doc = "Show document info only" in
Arg.(value & flag & info [ "I"; "head" ] ~doc)
let headers =
let header_conv =
let parse header =
match String.split_on_char ':' header with
| [] -> Error (`Msg "Header can't be the empty string")
| [ x ] ->
Error
(`Msg (Format.asprintf "Expecting `name: value` string, got: %s" x))
| name :: values ->
let value = Util.String.trim_left (String.concat ":" values) in
Ok (name, value)
in
let print = format_header in
Arg.conv ~docv:"method" (parse, print)
in
let doc = "Pass custom header(s) to server" in
let docv = "header" in
Arg.(value & opt_all header_conv [] & info [ "H"; "header" ] ~doc ~docv)
let include_ =
let doc = "Include protocol response headers in the output" in
Arg.(value & flag & info [ "i"; "include" ] ~doc)
let follow_redirects =
let doc = "Follow redirects" in
Arg.(value & flag & info [ "L"; "location" ] ~doc)
let max_redirects =
let doc = "Max number of redirects to follow" in
let docv = "int" in
Arg.(
value
& opt int Config.default.max_redirects
& info [ "max-redirs" ] ~doc ~docv)
let use_http_1_0 =
let doc = "Use HTTP 1.0" in
Arg.(value & flag & info [ "0"; "http1.0" ] ~doc)
let use_http_1_1 =
let doc = "Use HTTP 1.1" in
Arg.(value & flag & info [ "http1.1" ] ~doc)
let use_http_2 =
let doc = "Use HTTP 2" in
Arg.(value & flag & info [ "http2" ] ~doc)
let http_2_prior_knowledge =
let doc = "Use HTTP 2 without HTTP/1.1 Upgrade" in
Arg.(value & flag & info [ "http2-prior-knowledge" ] ~doc)
let referer =
let doc = "Referrer URL" in
let docv = "URL" in
Arg.(value & opt (some string) None & info [ "e"; "referer" ] ~doc ~docv)
let silent =
let doc = "Silent mode" in
Arg.(value & flag & info [ "s"; "silent" ] ~doc)
let verbose =
let doc = "Verbosity (use multiple times to increase)" in
Arg.(value & flag_all & info [ "v"; "verbose" ] ~doc)
let sslv3 =
let doc = "Use SSLv3" in
Arg.(value & flag & info [ "3"; "sslv3" ] ~doc)
let tlsv1 =
let doc = "Use TLSv1.0 or greater" in
Arg.(value & flag & info [ "1"; "tlsv1" ] ~doc)
let tlsv1_0 =
let doc = "Use TLSv1.0 or greater" in
Arg.(value & flag & info [ "tlsv1.0" ] ~doc)
let tlsv1_1 =
let doc = "Use TLSv1.1 or greater" in
Arg.(value & flag & info [ "tlsv1.1" ] ~doc)
let tlsv1_2 =
let doc = "Use TLSv1.2 or greater" in
Arg.(value & flag & info [ "tlsv1.2" ] ~doc)
let tlsv1_3 =
let doc = "Use TLSv1.3 or greater" in
Arg.(value & flag & info [ "tlsv1.3" ] ~doc)
let tls_max_version =
let tls_conv =
let parse s =
match Versions.TLS.of_string s with
| Ok v -> Ok v
| Error msg -> Error (`Msg msg)
in
let print = Versions.TLS.pp_hum in
Arg.conv ~docv:"" (parse, print)
in
let doc = "Set maximum allowed TLS version" in
let docv = "version" in
Arg.(
value & opt tls_conv Versions.TLS.TLSv1_3 & info [ "tls-max" ] ~doc ~docv)
let upload_file =
let doc = "Transfer local $(docv) to destination" in
let docv = "file" in
Arg.(
value & opt (some string) None & info [ "T"; "upload-file" ] ~doc ~docv)
let user_agent =
let doc = "Send User-Agent $(docv) to server" in
let docv = "name" in
Arg.(
value
& opt string "carl/0.0.0-experimental"
& info [ "A"; "user-agent" ] ~doc ~docv)
let user =
let doc = "Server user and password" in
let docv = "user:password" in
Arg.(value & opt (some string) None & info [ "u"; "user" ] ~doc ~docv)
let oauth2_bearer =
let doc = "OAuth 2 Bearer Token" in
let docv = "token" in
Arg.(value & opt (some string) None & info [ "oauth2-bearer" ] ~doc ~docv)
let output =
let output_conv =
let parse s =
let output = Channel s in
Ok output
in
let print formatter output =
let s = match output with Stdout -> "stdout" | Channel f -> f in
Format.fprintf formatter "%s" s
in
Arg.conv ~docv:"method" (parse, print)
in
let doc = "Write to file instead of stdout" in
let docv = "file" in
Arg.(value & opt output_conv Stdout & info [ "o"; "output" ] ~doc ~docv)
let urls =
let docv = "URLs" in
Arg.(non_empty & pos_all string [] & info [] ~docv)
let parse
cacert
capath
cert
compressed
connect_timeout
data
default_proto
head
headers
include_
insecure
key
follow_redirects
max_redirects
request
use_http_1_0
use_http_1_1
use_http_2
http2_prior_knowledge
referer
sslv3
tlsv1
tlsv1_0
tlsv1_1
tlsv1_2
tlsv1_3
max_tls_version
upload_file
user_agent
user
oauth2_bearer
silent
verbose
output
urls
=
{ follow_redirects
; max_redirects
; data =
(match data, upload_file with
| None, None -> None
| Some data, _ ->
Some (Data data)
| None, Some filename -> Some (File filename))
; meth =
(match head, request, data with
| true, None, None -> `HEAD
| _, None, Some _ -> `POST
| _, None, None -> `GET
| _, Some meth, _ -> meth)
; log_level = log_level_of_list ~silent verbose
; urls
; default_proto
; head
; headers
; include_
; max_http_version =
(match use_http_2, use_http_1_1, use_http_1_0 with
| true, _, _ | false, false, false ->
Versions.HTTP.HTTP_2
| false, true, _ -> HTTP_1_1
| false, false, true -> HTTP_1_0)
; h2c_upgrade = use_http_2
; http2_prior_knowledge
; cacert
; capath
; clientcert =
(match cert, key with
| Some cert, Some key -> Some (Cert.Filepath cert, Cert.Filepath key)
| _ -> None)
; min_tls_version =
Versions.TLS.(
match tlsv1_3, tlsv1_2, tlsv1_1, tlsv1_0, tlsv1, sslv3 with
| true, _, _, _, _, _ -> TLSv1_3
| _, true, _, _, _, _ -> TLSv1_2
| _, _, true, _, _, _ -> TLSv1_1
| _, _, _, true, _, _ -> TLSv1_0
| _, _, _, _, true, _ -> TLSv1_0
| _, _, _, _, _, true -> SSLv3
| _, _, _, _, _, _ -> TLSv1_0)
; max_tls_version
; insecure
; user_agent
; compressed
; connect_timeout
; referer
; user
; oauth2_bearer
; output
}
let default_cmd =
Term.(
const parse
$ cacert
$ capath
$ cert
$ compressed
$ connect_timeout
$ data
$ default_proto
$ head
$ headers
$ include_
$ insecure
$ key
$ follow_redirects
$ max_redirects
$ request
$ use_http_1_0
$ use_http_1_1
$ use_http_2
$ http_2_prior_knowledge
$ referer
$ sslv3
$ tlsv1
$ tlsv1_0
$ tlsv1_1
$ tlsv1_2
$ tlsv1_3
$ tls_max_version
$ upload_file
$ user_agent
$ user
$ oauth2_bearer
$ silent
$ verbose
$ output
$ urls)
let cmd =
let doc = "Like curl, for caml" in
let info = Cmd.info "carl" ~version:"todo" ~doc in
Cmd.v info Term.(ret (const main $ default_cmd))
end
let () = exit (Cmd.eval CLI.cmd)
|
952fb3be6e10f28fa20d24aa82347806c3761448d66f98ab4514a0e73bd035da | galdor/tungsten | io-multiplexing-epoll.lisp | (in-package :system)
(defclass epoll-io-base (io-base)
((fd
:type (or (integer 0) null)
:initarg :fd
:reader epoll-io-base-fd)))
(defmethod initialize-instance :after ((base epoll-io-base)
&key &allow-other-keys)
(with-slots (fd) base
(setf fd (epoll-create1 '(:epoll-cloexec)))))
(defmethod close-io-base ((base epoll-io-base))
(with-slots (fd) base
(when fd
(close-fd fd)
(setf fd nil)
t)))
(defmethod add-io-watcher ((base epoll-io-base) (watcher io-watcher))
(with-slots (fd events) watcher
(ffi:with-foreign-value (%event 'epoll-event)
(setf (ffi:struct-member %event 'epoll-event :events)
(epoll-events events))
(let ((%data (ffi:struct-member-pointer %event 'epoll-event :data)))
(setf (ffi:foreign-union-member %data 'epoll-data :fd) fd))
(epoll-ctl (epoll-io-base-fd base) :epoll-ctl-add fd %event))))
(defmethod update-io-watcher ((base epoll-io-base) (watcher io-watcher) events)
(with-slots (fd) watcher
(ffi:with-foreign-value (%event 'epoll-event)
(setf (ffi:struct-member %event 'epoll-event :events)
(epoll-events events))
(let ((%data (ffi:struct-member-pointer %event 'epoll-event :data)))
(setf (ffi:foreign-union-member %data 'epoll-data :fd) fd))
(epoll-ctl (epoll-io-base-fd base) :epoll-ctl-mod fd %event))))
(defmethod remove-io-watcher ((base epoll-io-base) (watcher io-watcher))
(with-slots (fd) watcher
(epoll-ctl (epoll-io-base-fd base) :epoll-ctl-del fd (ffi:null-pointer))))
(defun epoll-events (events)
(declare (type list events))
(let ((epoll-events nil))
(dolist (event events epoll-events)
(push (ecase event
(:read :epollin)
(:write :epollout)
(:hangup :epollhup))
epoll-events))))
(defmethod read-and-dispatch-io-events ((base epoll-io-base) &key timeout)
(declare (type (or (integer 0) null) timeout))
(with-slots ((epoll-fd fd)) base
(with-epoll-wait (%event epoll-fd 32 (or timeout -1))
(let* ((events (ffi:struct-member %event 'epoll-event :events))
(%data (ffi:struct-member-pointer %event 'epoll-event :data))
(fd (ffi:foreign-union-member %data 'epoll-data :fd)))
(dispatch-fd-event base fd events)))))
| null | https://raw.githubusercontent.com/galdor/tungsten/5d6e71fb89af32ab3994c5b2daf8b902a5447447/tungsten-system/src/io-multiplexing-epoll.lisp | lisp | (in-package :system)
(defclass epoll-io-base (io-base)
((fd
:type (or (integer 0) null)
:initarg :fd
:reader epoll-io-base-fd)))
(defmethod initialize-instance :after ((base epoll-io-base)
&key &allow-other-keys)
(with-slots (fd) base
(setf fd (epoll-create1 '(:epoll-cloexec)))))
(defmethod close-io-base ((base epoll-io-base))
(with-slots (fd) base
(when fd
(close-fd fd)
(setf fd nil)
t)))
(defmethod add-io-watcher ((base epoll-io-base) (watcher io-watcher))
(with-slots (fd events) watcher
(ffi:with-foreign-value (%event 'epoll-event)
(setf (ffi:struct-member %event 'epoll-event :events)
(epoll-events events))
(let ((%data (ffi:struct-member-pointer %event 'epoll-event :data)))
(setf (ffi:foreign-union-member %data 'epoll-data :fd) fd))
(epoll-ctl (epoll-io-base-fd base) :epoll-ctl-add fd %event))))
(defmethod update-io-watcher ((base epoll-io-base) (watcher io-watcher) events)
(with-slots (fd) watcher
(ffi:with-foreign-value (%event 'epoll-event)
(setf (ffi:struct-member %event 'epoll-event :events)
(epoll-events events))
(let ((%data (ffi:struct-member-pointer %event 'epoll-event :data)))
(setf (ffi:foreign-union-member %data 'epoll-data :fd) fd))
(epoll-ctl (epoll-io-base-fd base) :epoll-ctl-mod fd %event))))
(defmethod remove-io-watcher ((base epoll-io-base) (watcher io-watcher))
(with-slots (fd) watcher
(epoll-ctl (epoll-io-base-fd base) :epoll-ctl-del fd (ffi:null-pointer))))
(defun epoll-events (events)
(declare (type list events))
(let ((epoll-events nil))
(dolist (event events epoll-events)
(push (ecase event
(:read :epollin)
(:write :epollout)
(:hangup :epollhup))
epoll-events))))
(defmethod read-and-dispatch-io-events ((base epoll-io-base) &key timeout)
(declare (type (or (integer 0) null) timeout))
(with-slots ((epoll-fd fd)) base
(with-epoll-wait (%event epoll-fd 32 (or timeout -1))
(let* ((events (ffi:struct-member %event 'epoll-event :events))
(%data (ffi:struct-member-pointer %event 'epoll-event :data))
(fd (ffi:foreign-union-member %data 'epoll-data :fd)))
(dispatch-fd-event base fd events)))))
|
|
67b7a41fef5534170de0c68844664cf4e5a199b5a1681325aa77a17c3406ab6a | codinuum/cca | LCfragment.ml |
Copyright 2012 - 2020 Codinuum Software Lab < >
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 .
Copyright 2012-2020 Codinuum Software Lab <>
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.
*)
(* LCfragment.ml *)
module M = Fragment.F(LCrange.LineColumn)
class c = M.c
let load = M.load
| null | https://raw.githubusercontent.com/codinuum/cca/88ea07f3fe3671b78518769d804fdebabcd28e90/src/ast/analyzing/common/LCfragment.ml | ocaml | LCfragment.ml |
Copyright 2012 - 2020 Codinuum Software Lab < >
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 .
Copyright 2012-2020 Codinuum Software Lab <>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module M = Fragment.F(LCrange.LineColumn)
class c = M.c
let load = M.load
|
0133e33f4cd2820a59df2fe74c57c7a904d8e354648a0ab4fbf8d9a379e2ff9f | w3ntao/programming-in-haskell | Exercise_12_5_8.hs | # OPTIONS_GHC -Wall #
module Exercise_12_5_8 where
type State = Int
newtype ST a = S (State -> (a, State))
extract :: ST a -> (State -> (a, State))
extract (S x) = x
instance Functor ST where
fmap g st = do S func
where func x = (g a, int)
where (a, int) = (extract st) x
instance Applicative ST where
pure x = S (\s -> (x, s))
sfx <*> stx = do S g
where g x = (h y, st)
where (y, st) = (extract stx) x
(h, _ ) = (extract sfx) x
app :: ST a -> State -> (a, State)
app (S st) x = st x
instance Monad ST where
st >>= f = S g
where g s = app (f x) s'
where (x, s') = app st s | null | https://raw.githubusercontent.com/w3ntao/programming-in-haskell/c2769fa19d8507aad209818c83f67e82c3698f07/Chapter-12/Exercise_12_5_8.hs | haskell | # OPTIONS_GHC -Wall #
module Exercise_12_5_8 where
type State = Int
newtype ST a = S (State -> (a, State))
extract :: ST a -> (State -> (a, State))
extract (S x) = x
instance Functor ST where
fmap g st = do S func
where func x = (g a, int)
where (a, int) = (extract st) x
instance Applicative ST where
pure x = S (\s -> (x, s))
sfx <*> stx = do S g
where g x = (h y, st)
where (y, st) = (extract stx) x
(h, _ ) = (extract sfx) x
app :: ST a -> State -> (a, State)
app (S st) x = st x
instance Monad ST where
st >>= f = S g
where g s = app (f x) s'
where (x, s') = app st s |
|
98d1920d66a27de952e1347412b6555d757b46fcdd4290d84a9bdc8b2edb8ff4 | Kappa-Dev/KappaTools | KaSaWorker.ml | (******************************************************************************)
(* _ __ * The Kappa Language *)
| |/ / * Copyright 2010 - 2020 CNRS - Harvard Medical School - INRIA - IRIF
(* | ' / *********************************************************************)
(* | . \ * This file is distributed under the terms of the *)
(* |_|\_\ * GNU Lesser General Public License Version 3 *)
(******************************************************************************)
let on_message (text_message : string) : unit =
Kasa_mpi.on_message
(fun s -> Worker.post_message s)
text_message
let () = Worker.set_onmessage on_message
| null | https://raw.githubusercontent.com/Kappa-Dev/KappaTools/eef2337e8688018eda47ccc838aea809cae68de7/gui/KaSaWorker.ml | ocaml | ****************************************************************************
_ __ * The Kappa Language
| ' / ********************************************************************
| . \ * This file is distributed under the terms of the
|_|\_\ * GNU Lesser General Public License Version 3
**************************************************************************** | | |/ / * Copyright 2010 - 2020 CNRS - Harvard Medical School - INRIA - IRIF
let on_message (text_message : string) : unit =
Kasa_mpi.on_message
(fun s -> Worker.post_message s)
text_message
let () = Worker.set_onmessage on_message
|
bc0b12d8c84ad2df0d17bd325422cf1312b130cd92399021a523f49e12608fd5 | appleshan/cl-http | cl-http-70-1.lisp | -*- Mode : LISP ; Syntax : Common - Lisp ; Package : USER ; Base : 10 ; Patch - File : T -*-
Patch file for CL - HTTP version 70.1
Reason : Function ( CLOS : METHOD ( CL : SETF WWW - UTILS::GET - VALUE ) ( T CL : PATHNAME T ) ): Missing ( setf get - value ) for pathname .
Written by JCMa ,
while running on Publications Y2 K Testbed from HOST6:/usr / lib / symbolics / eop - world - pub6 -
with Open Genera 2.0 , Genera 8.5 , Logical Pathnames Translation Files NEWEST ,
Lock Simple 437.0 , Version Control 405.0 , Compare Merge 404.0 , CLIM 72.0 ,
Genera CLIM 72.0 , PostScript CLIM 72.0 , CLIM Documentation 72.0 ,
Statice Runtime 466.1 , Statice 466.0 , Statice Browser 466.0 ,
Statice Server 466.2 , Statice Documentation 426.0 , ,
Joshua Documentation 216.0 , Image Substrate 440.4 ,
Essential Image Substrate 433.0 , Mailer 438.0 , Showable Procedures 36.3 ,
Binary Tree 34.0 , Working LispM Mailer 8.0 , Experimental HTTP Server 70.0 ,
Experimental W3 Presentation System 8.0 ,
Experimental CL - HTTP Server Interface 53.0 ,
Experimental Symbolics Common Lisp Compatibility 4.0 ,
Experimental Comlink Packages 6.0 , Experimental Comlink Utilities 10.0 ,
Experimental COMLINK Cryptography 2.0 , Experimental Routing Taxonomy 9.0 ,
Experimental COMLINK Database 11.7 , Experimental Email Servers 12.0 ,
Experimental Comlink Customized LispM Mailer 7.0 ,
Experimental Dynamic Forms 14.0 , Experimental Communications Linker Server 39.2 ,
Experimental Lambda Information Retrieval System 22.0 ,
Experimental Comlink Documentation Utilities 6.0 ,
Experimental White House Publication System 25.2 ,
Experimental WH Automatic Categorization System 15.0 ,
8 - 5 - Genera - Local - Patches 1.0 , 39 - COMLINK - Local - Patches 1.0 , Ivory Revision 5 ,
VLM Debugger 329 , Genera program 8.16 , DEC OSF/1 V4.0 ( Rev. 205 ) ,
1260x932 24 - bit TRUE - COLOR X Screen HOST6:0.0 with 224 Genera fonts ( DECWINDOWS Digital Equipment Corporation Digital UNIX V4.0 R1 ) ,
Machine serial number 1719841853 ,
Local flavor function patch ( from EOP : CONFIG;MAIL - SERVER;PATCHES;LOCAL - FLAVOR - FUNCTION - PATCH - MARK2 ) ,
Get emb file host patch ( from EOP : CONFIG;MAIL - SERVER;PATCHES;GET - EMB - FILE - HOST - PATCH ) ,
Get mailer home location from namespace ( from EOP : CONFIG;MAIL - SERVER;PATCHES;MAILER - ENVIRONMENT - PATCH ) ,
Consider internet - domain - name when matching names to file hosts ( from EOP : CONFIG;MAIL - SERVER;PATCHES;PATHNAME - HOST - NAMEP - PATCH.LISP.2 ) ,
Parse pathname patch ( from EOP : CONFIG;MAIL - SERVER;PATCHES;PARSE - PATHNAME - PATCH ) ,
Get internal event code patch ( from EOP : CONFIG;MAIL - SERVER;PATCHES;GET - INTERNAL - EVENT - CODE - PATCH ) ,
AutoLogin ( from EOP : CONFIG;MAIL - SERVER;PATCHES;AUTO - LOGIN.LISP.3 ) ,
Generate an error any time there domain system tries to create a bogus host object for the local host . ( from EOP : CONFIG;MAIL - SERVER;PATCHES;DETECT - BOGUS - HOST.LISP.6 ) ,
Set Mailer UID variables for current namespace . ( from EOP : - SERVER;PATCHES;MAILER - UID.LISP.1 ) ,
Provide Switch between EOP and MIT sources . ( from EOP : CONFIG;MAIL - SERVER;PATCHES;MIT - SOURCE.LISP.4 ) ,
Make FS : USER - HOMEDIR look in the namespace as one strategy . ( from EOP : CONFIG;MAIL - SERVER;PATCHES;USER - HOMEDIR.LISP.2 ) ,
Local uid patch ( from EOP : CONFIG;MAIL - SERVER;PATCHES;LOCAL - UID - PATCH ) ,
Statice log clear patch ( from EOP : CONFIG;MAIL - SERVER;PATCHES;STATICE - LOG - CLEAR - PATCH ) ,
Make compiled - function - spec - p of CLOS class symbol return NIL instead of erring ( from EOP : CONFIG;MAIL - SERVER;PATCHES;COMPILED - FUNCTION - SPEC - P - PATCH.LISP.1 ) ,
Improve mailer host parsing ( from EOP : CONFIG;MAIL - SERVER;PATCHES;PARSE - MAILER - HOST - PATCH.LISP.1 ) ,
Make native domain name host patch ( from EOP : CONFIG;MAIL - SERVER;PATCHES;MAKE - NATIVE - DOMAIN - NAME - HOST - PATCH.LISP.1 ) ,
Domain query cname loop patch ( from EOP : CONFIG;MAIL - SERVER;PATCHES;DOMAIN - QUERY - CNAME - LOOP - PATCH.LISP.1 ) ,
Increase disk wired wait timeout from 30 to 90 seconds ( from DISTRIBUTION|DIS - EMB - HOST:/db / eop.sct / eop / config / mail - server / patches / disk - wait-90 - patch. ) ,
Checkpoint command patch ( from EOP : CONFIG;MAIL - SERVER;PATCHES;CHECKPOINT - COMMAND - PATCH.LISP.9 ) ,
Domain Fixes ( from CML : MAILER;DOMAIN - FIXES.LISP.33 ) ,
Do n't force in the mail - x host ( from CML : MAILER;MAILBOX - FORMAT.LISP.24 ) ,
Make Mailer More Robust ( from CML : MAILER;MAILER - FIXES.LISP.15 ) ,
;;; Patch TCP hang on close when client drops connection. (from HTTP:LISPM;SERVER;TCP-PATCH-HANG-ON-CLOSE.LISP.10),
Add CLIM presentation and text style format directives . ( from FV : SCLC;FORMAT.LISP.20 ) ,
Fix Statice Lossage ( from CML : LISPM;STATICE - PATCH.LISP.3 ) ,
Make update schema work on set - value attributes with accessor names ( from CML : LISPM;STATICE - SET - VALUED - UPDATE.LISP.1 ) ,
COMLINK Mailer Patches . ( from CML : LISPM;MAILER - PATCH.LISP.107 ) ,
Clim patches ( from CML : DYNAMIC - FORMS;CLIM - PATCHES.LISP.48 ) ,
Increase disk wired wait timeout from 30 to 900 seconds ( from EOP : CONFIG;MAIL - SERVER;PATCHES;DISK - WAIT-900 - PATCH.LISP.1 ) ,
implementation error intsrumentation patch ( from HOST6:/usr / users / comlink / local - patches / tcp - implementation - error - intsrumentation - patch.lisp ) ,
Increase packet buffers patch ( from HOST6:/usr / users / comlink / local - patches / increase - packet - buffers - patch.lisp ) ,
Close tcb patch ( from HOST6:/usr / users / comlink / local - patches / close - tcb - patch. ) ,
Get output segment patch ( from HOST6:/usr / users / comlink / local - patches / get - output - segment - patch.lisp ) ,
Expansion buffer hack patch ( from HOST6:/usr / users / comlink / local - patches / expansion - buffer - hack - patch.lisp ) ,
Nfs directory list fast patch ( from HOST6:/usr / users / comlink / local - patches / nfs - directory - list - fast - patch.lisp ) ,
Gc report patch ( from EOP : MAIL - SERVER;PATCHES;GC - REPORT - PATCH.LISP.1 ) ,
;;; Pathname patch (from EOP:MAIL-SERVER;PATCHES;PATHNAME-PATCH.LISP.2),
;;; Pathname2 patch (from EOP:MAIL-SERVER;PATCHES;PATHNAME2-PATCH.LISP.3),
;;; Fix NFS brain damage. (from EOP:MAIL-SERVER;PATCHES;NFS-PATCH.LISP.8),
;;; Log patch (from EOP:MAIL-SERVER;PATCHES;LOG-PATCH.LISP.2),
Vlm namespace append patch ( from EOP : MAIL - SERVER;PATCHES;VLM - NAMESPACE - APPEND - PATCH.LISP.7 ) ,
Bad rid error patch ( from HOST6:/usr / users / comlink / local - patches / bad - rid - error - patch.lisp ) ,
Copy database patch ( from HOST6:/usr / users / comlink / local - patches / copy - database - patch.lisp ) ,
Cml bulk mail patch ( from HOST6:/usr / users / comlink / local - patches / cml - bulk - mail - patch.lisp ) ,
Encode integer date patch ( from HOST6:/usr / users / comlink / local - patches / encode - integer - date - patch.lisp ) ,
Fix year 199 ,
from silly browsers ( from HOST6:/usr / users / comlink / local - patches / fix - year-199.lisp ) ,
Fix wddi obsolete references ( from HOST6:/usr / users / comlink / local - patches / fix - wddi - obsolete - references.lisp ) ,
Ccc sign document enable services ( from HOST6:/usr / users / comlink / local - patches / ccc - sign - document - enable - services.lisp ) ,
End date for wh pub default ( from HOST6:/usr / users / comlink / local - patches / end - date - for - wh - pub - default.lisp ) ,
Redirect to WWW.PUB.WHITEHOUSE.GOV ( from EOP : PUB;HTTP;REDIRECT - TO - PRIMARY.LISP.12 ) .
(SCT:FILES-PATCHED-IN-THIS-PATCH-FILE
"HTTP:LISPM;SERVER;LISPM.LISP.435")
;========================
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:LISPM;SERVER;LISPM.LISP.435")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Mode: LISP; Package: WWW-UTILS; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:fix :roman :normal);-*-")
(defmethod (setf http:get-value) (value (pathname pathname) indicator &optional default)
(declare (ignore default))
(scl:send pathname :putprop value indicator))
| null | https://raw.githubusercontent.com/appleshan/cl-http/a7ec6bf51e260e9bb69d8e180a103daf49aa0ac2/lispm/server/patch/cl-http-70/cl-http-70-1.lisp | lisp | Syntax : Common - Lisp ; Package : USER ; Base : 10 ; Patch - File : T -*-
MAIL - SERVER;PATCHES;LOCAL - FLAVOR - FUNCTION - PATCH - MARK2 ) ,
MAIL - SERVER;PATCHES;GET - EMB - FILE - HOST - PATCH ) ,
MAIL - SERVER;PATCHES;MAILER - ENVIRONMENT - PATCH ) ,
MAIL - SERVER;PATCHES;PATHNAME - HOST - NAMEP - PATCH.LISP.2 ) ,
MAIL - SERVER;PATCHES;PARSE - PATHNAME - PATCH ) ,
MAIL - SERVER;PATCHES;GET - INTERNAL - EVENT - CODE - PATCH ) ,
MAIL - SERVER;PATCHES;AUTO - LOGIN.LISP.3 ) ,
MAIL - SERVER;PATCHES;DETECT - BOGUS - HOST.LISP.6 ) ,
PATCHES;MAILER - UID.LISP.1 ) ,
MAIL - SERVER;PATCHES;MIT - SOURCE.LISP.4 ) ,
MAIL - SERVER;PATCHES;USER - HOMEDIR.LISP.2 ) ,
MAIL - SERVER;PATCHES;LOCAL - UID - PATCH ) ,
MAIL - SERVER;PATCHES;STATICE - LOG - CLEAR - PATCH ) ,
MAIL - SERVER;PATCHES;COMPILED - FUNCTION - SPEC - P - PATCH.LISP.1 ) ,
MAIL - SERVER;PATCHES;PARSE - MAILER - HOST - PATCH.LISP.1 ) ,
MAIL - SERVER;PATCHES;MAKE - NATIVE - DOMAIN - NAME - HOST - PATCH.LISP.1 ) ,
MAIL - SERVER;PATCHES;DOMAIN - QUERY - CNAME - LOOP - PATCH.LISP.1 ) ,
MAIL - SERVER;PATCHES;CHECKPOINT - COMMAND - PATCH.LISP.9 ) ,
DOMAIN - FIXES.LISP.33 ) ,
MAILBOX - FORMAT.LISP.24 ) ,
MAILER - FIXES.LISP.15 ) ,
Patch TCP hang on close when client drops connection. (from HTTP:LISPM;SERVER;TCP-PATCH-HANG-ON-CLOSE.LISP.10),
FORMAT.LISP.20 ) ,
STATICE - PATCH.LISP.3 ) ,
STATICE - SET - VALUED - UPDATE.LISP.1 ) ,
MAILER - PATCH.LISP.107 ) ,
CLIM - PATCHES.LISP.48 ) ,
MAIL - SERVER;PATCHES;DISK - WAIT-900 - PATCH.LISP.1 ) ,
PATCHES;GC - REPORT - PATCH.LISP.1 ) ,
Pathname patch (from EOP:MAIL-SERVER;PATCHES;PATHNAME-PATCH.LISP.2),
Pathname2 patch (from EOP:MAIL-SERVER;PATCHES;PATHNAME2-PATCH.LISP.3),
Fix NFS brain damage. (from EOP:MAIL-SERVER;PATCHES;NFS-PATCH.LISP.8),
Log patch (from EOP:MAIL-SERVER;PATCHES;LOG-PATCH.LISP.2),
PATCHES;VLM - NAMESPACE - APPEND - PATCH.LISP.7 ) ,
HTTP;REDIRECT - TO - PRIMARY.LISP.12 ) .
======================== | Patch file for CL - HTTP version 70.1
Reason : Function ( CLOS : METHOD ( CL : SETF WWW - UTILS::GET - VALUE ) ( T CL : PATHNAME T ) ): Missing ( setf get - value ) for pathname .
Written by JCMa ,
while running on Publications Y2 K Testbed from HOST6:/usr / lib / symbolics / eop - world - pub6 -
with Open Genera 2.0 , Genera 8.5 , Logical Pathnames Translation Files NEWEST ,
Lock Simple 437.0 , Version Control 405.0 , Compare Merge 404.0 , CLIM 72.0 ,
Genera CLIM 72.0 , PostScript CLIM 72.0 , CLIM Documentation 72.0 ,
Statice Runtime 466.1 , Statice 466.0 , Statice Browser 466.0 ,
Statice Server 466.2 , Statice Documentation 426.0 , ,
Joshua Documentation 216.0 , Image Substrate 440.4 ,
Essential Image Substrate 433.0 , Mailer 438.0 , Showable Procedures 36.3 ,
Binary Tree 34.0 , Working LispM Mailer 8.0 , Experimental HTTP Server 70.0 ,
Experimental W3 Presentation System 8.0 ,
Experimental CL - HTTP Server Interface 53.0 ,
Experimental Symbolics Common Lisp Compatibility 4.0 ,
Experimental Comlink Packages 6.0 , Experimental Comlink Utilities 10.0 ,
Experimental COMLINK Cryptography 2.0 , Experimental Routing Taxonomy 9.0 ,
Experimental COMLINK Database 11.7 , Experimental Email Servers 12.0 ,
Experimental Comlink Customized LispM Mailer 7.0 ,
Experimental Dynamic Forms 14.0 , Experimental Communications Linker Server 39.2 ,
Experimental Lambda Information Retrieval System 22.0 ,
Experimental Comlink Documentation Utilities 6.0 ,
Experimental White House Publication System 25.2 ,
Experimental WH Automatic Categorization System 15.0 ,
8 - 5 - Genera - Local - Patches 1.0 , 39 - COMLINK - Local - Patches 1.0 , Ivory Revision 5 ,
VLM Debugger 329 , Genera program 8.16 , DEC OSF/1 V4.0 ( Rev. 205 ) ,
1260x932 24 - bit TRUE - COLOR X Screen HOST6:0.0 with 224 Genera fonts ( DECWINDOWS Digital Equipment Corporation Digital UNIX V4.0 R1 ) ,
Machine serial number 1719841853 ,
Increase disk wired wait timeout from 30 to 90 seconds ( from DISTRIBUTION|DIS - EMB - HOST:/db / eop.sct / eop / config / mail - server / patches / disk - wait-90 - patch. ) ,
implementation error intsrumentation patch ( from HOST6:/usr / users / comlink / local - patches / tcp - implementation - error - intsrumentation - patch.lisp ) ,
Increase packet buffers patch ( from HOST6:/usr / users / comlink / local - patches / increase - packet - buffers - patch.lisp ) ,
Close tcb patch ( from HOST6:/usr / users / comlink / local - patches / close - tcb - patch. ) ,
Get output segment patch ( from HOST6:/usr / users / comlink / local - patches / get - output - segment - patch.lisp ) ,
Expansion buffer hack patch ( from HOST6:/usr / users / comlink / local - patches / expansion - buffer - hack - patch.lisp ) ,
Nfs directory list fast patch ( from HOST6:/usr / users / comlink / local - patches / nfs - directory - list - fast - patch.lisp ) ,
Bad rid error patch ( from HOST6:/usr / users / comlink / local - patches / bad - rid - error - patch.lisp ) ,
Copy database patch ( from HOST6:/usr / users / comlink / local - patches / copy - database - patch.lisp ) ,
Cml bulk mail patch ( from HOST6:/usr / users / comlink / local - patches / cml - bulk - mail - patch.lisp ) ,
Encode integer date patch ( from HOST6:/usr / users / comlink / local - patches / encode - integer - date - patch.lisp ) ,
Fix year 199 ,
from silly browsers ( from HOST6:/usr / users / comlink / local - patches / fix - year-199.lisp ) ,
Fix wddi obsolete references ( from HOST6:/usr / users / comlink / local - patches / fix - wddi - obsolete - references.lisp ) ,
Ccc sign document enable services ( from HOST6:/usr / users / comlink / local - patches / ccc - sign - document - enable - services.lisp ) ,
End date for wh pub default ( from HOST6:/usr / users / comlink / local - patches / end - date - for - wh - pub - default.lisp ) ,
(SCT:FILES-PATCHED-IN-THIS-PATCH-FILE
"HTTP:LISPM;SERVER;LISPM.LISP.435")
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:LISPM;SERVER;LISPM.LISP.435")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Mode: LISP; Package: WWW-UTILS; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:fix :roman :normal);-*-")
(defmethod (setf http:get-value) (value (pathname pathname) indicator &optional default)
(declare (ignore default))
(scl:send pathname :putprop value indicator))
|
93217d7b68d04d11dfaa1cce66dd21cdaa5ee9ab9c049a556c452d7c443a54ee | kana/sicp | ex-4.68.scm | Exercise 4.68 . Define rules to implement the reverse operation of exercise
2.18 , which returns a list containing the same elements as a given list in
;;; reverse order. (Hint: Use append-to-form.) Can your rules answer both
;;; (reverse (1 2 3) ?x) and (reverse ?x (1 2 3)) ?
(rule (reverse (?x) (?x)))
(rule (reverse (?x . (?y)) (?y . (?x))))
(rule (reverse (?x . ?y) (?a . ?b))
TODO
)
| null | https://raw.githubusercontent.com/kana/sicp/912bda4276995492ffc2ec971618316701e196f6/ex-4.68.scm | scheme | reverse order. (Hint: Use append-to-form.) Can your rules answer both
(reverse (1 2 3) ?x) and (reverse ?x (1 2 3)) ? | Exercise 4.68 . Define rules to implement the reverse operation of exercise
2.18 , which returns a list containing the same elements as a given list in
(rule (reverse (?x) (?x)))
(rule (reverse (?x . (?y)) (?y . (?x))))
(rule (reverse (?x . ?y) (?a . ?b))
TODO
)
|
9c5794ed2b9e8555d65bf155e40e9ae336d737f140733fbff05e9d1198d6db3a | lilydjwg/myhaskells | Function.hs | module Control.Function (
applyMaybe,
applyUntil,
applyUntilM,
mapFst,
mapSnd,
) where
import Data.Maybe (isJust)
-- |Applies a list of functions until a Just value is got
applyMaybe :: [(a -> Maybe b)] -> a -> Maybe b
applyMaybe = applyUntil isJust
-- |applies until p becomes True
applyUntil :: (b -> Bool) -> [(a -> b)] -> a -> b
applyUntil _ (f:[]) a = f a
applyUntil p (f:fs) a = if p r then r else applyUntil p fs a
where r = f a
applyUntilM :: Monad m => (b -> Bool) -> [(a -> m b)] -> a -> m b
applyUntilM _ (f:[]) a = f a
applyUntilM p (f:fs) a = do
r <- f a
if p r then return r else applyUntilM p fs a
isRight :: Either a b -> Bool
isRight (Left _) = False
isRight (Right _) = True
mapFst :: (a -> b) -> (a, c) -> (b, c)
mapFst f (a, b) = (f a, b)
mapSnd :: (a -> b) -> (c, a) -> (c, b)
mapSnd f (a, b) = (a, f b)
| null | https://raw.githubusercontent.com/lilydjwg/myhaskells/9a028c36a46e811e56d47a11ac4f261787fba0cf/lib/Control/Function.hs | haskell | |Applies a list of functions until a Just value is got
|applies until p becomes True | module Control.Function (
applyMaybe,
applyUntil,
applyUntilM,
mapFst,
mapSnd,
) where
import Data.Maybe (isJust)
applyMaybe :: [(a -> Maybe b)] -> a -> Maybe b
applyMaybe = applyUntil isJust
applyUntil :: (b -> Bool) -> [(a -> b)] -> a -> b
applyUntil _ (f:[]) a = f a
applyUntil p (f:fs) a = if p r then r else applyUntil p fs a
where r = f a
applyUntilM :: Monad m => (b -> Bool) -> [(a -> m b)] -> a -> m b
applyUntilM _ (f:[]) a = f a
applyUntilM p (f:fs) a = do
r <- f a
if p r then return r else applyUntilM p fs a
isRight :: Either a b -> Bool
isRight (Left _) = False
isRight (Right _) = True
mapFst :: (a -> b) -> (a, c) -> (b, c)
mapFst f (a, b) = (f a, b)
mapSnd :: (a -> b) -> (c, a) -> (c, b)
mapSnd f (a, b) = (a, f b)
|
9694d255959fa8ad5fcf08c2f07700f0b6622849eab7ab3421a4dab6642e5d98 | haskell-numerics/hmatrix | GSL.hs | |
Module : Numeric . GSL
Copyright : ( c ) 2006 - 14
License : GPL
Maintainer :
Stability : provisional
This module reexports all available GSL functions .
The GSL special functions are in the separate package hmatrix - special .
Module : Numeric.GSL
Copyright : (c) Alberto Ruiz 2006-14
License : GPL
Maintainer : Alberto Ruiz
Stability : provisional
This module reexports all available GSL functions.
The GSL special functions are in the separate package hmatrix-special.
-}
module Numeric.GSL (
module Numeric.GSL.Integration
, module Numeric.GSL.Differentiation
, module Numeric.GSL.Fourier
, module Numeric.GSL.Polynomials
, module Numeric.GSL.Minimization
, module Numeric.GSL.Root
, module Numeric.GSL.ODE
, module Numeric.GSL.Fitting
, module Numeric.GSL.Interpolation
, module Data.Complex
, setErrorHandlerOff
) where
import Numeric.GSL.Integration
import Numeric.GSL.Differentiation
import Numeric.GSL.Fourier
import Numeric.GSL.Polynomials
import Numeric.GSL.Minimization
import Numeric.GSL.Root
import Numeric.GSL.ODE
import Numeric.GSL.Fitting
import Numeric.GSL.Interpolation
import Data.Complex
| This action removes the GSL default error handler ( which aborts the program ) , so that
GSL errors can be handled by ( using Control . Exception ) and ghci does n't abort .
foreign import ccall unsafe "GSL/gsl-aux.h no_abort_on_error" setErrorHandlerOff :: IO ()
| null | https://raw.githubusercontent.com/haskell-numerics/hmatrix/2694f776c7b5034d239acb5d984c489417739225/packages/gsl/src/Numeric/GSL.hs | haskell | |
Module : Numeric . GSL
Copyright : ( c ) 2006 - 14
License : GPL
Maintainer :
Stability : provisional
This module reexports all available GSL functions .
The GSL special functions are in the separate package hmatrix - special .
Module : Numeric.GSL
Copyright : (c) Alberto Ruiz 2006-14
License : GPL
Maintainer : Alberto Ruiz
Stability : provisional
This module reexports all available GSL functions.
The GSL special functions are in the separate package hmatrix-special.
-}
module Numeric.GSL (
module Numeric.GSL.Integration
, module Numeric.GSL.Differentiation
, module Numeric.GSL.Fourier
, module Numeric.GSL.Polynomials
, module Numeric.GSL.Minimization
, module Numeric.GSL.Root
, module Numeric.GSL.ODE
, module Numeric.GSL.Fitting
, module Numeric.GSL.Interpolation
, module Data.Complex
, setErrorHandlerOff
) where
import Numeric.GSL.Integration
import Numeric.GSL.Differentiation
import Numeric.GSL.Fourier
import Numeric.GSL.Polynomials
import Numeric.GSL.Minimization
import Numeric.GSL.Root
import Numeric.GSL.ODE
import Numeric.GSL.Fitting
import Numeric.GSL.Interpolation
import Data.Complex
| This action removes the GSL default error handler ( which aborts the program ) , so that
GSL errors can be handled by ( using Control . Exception ) and ghci does n't abort .
foreign import ccall unsafe "GSL/gsl-aux.h no_abort_on_error" setErrorHandlerOff :: IO ()
|
|
846a31c93dd01d4d32966a335de31cb0d8495ae56ff64b2591bd11d65bc1a712 | DATX02-17-26/DATX02-17-26 | EvaluationMonad.hs | DATX02 - 17 - 26 , automated assessment of imperative programs .
- Copyright , 2017 , see AUTHORS.md .
-
- 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 , MA 02110 - 1301 , USA .
- Copyright, 2017, see AUTHORS.md.
-
- 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, MA 02110-1301, USA.
-}
# LANGUAGE GeneralizedNewtypeDeriving #
module EvaluationMonad (
liftIO,
throw,
catch,
logMessage,
withTemporaryDirectory,
inTemporaryDirectory,
issue,
comment,
EvalM,
runEvalM,
executeEvalM,
resultEvalM,
Env(..),
defaultEnv,
parseEnv
) where
import Control.Monad.Trans.Class
import Control.Monad.Trans.Except as E
import Control.Monad.Writer.Lazy hiding ((<>))
import Control.Monad.Reader
import qualified Control.Exception as Exc
import System.Exit
import System.Directory
import Options.Applicative
import Data.Semigroup hiding (option)
-- | A monad for evaluating student solutions
newtype EvalM a = EvalM { unEvalM :: ExceptT EvalError (ReaderT Env (WriterT Feedback (WriterT Log IO))) a }
deriving (Monad, Applicative, Functor, MonadReader Env)
-- | For now we just log strings
type LogMessage = String
type Log = [LogMessage]
-- | Evaluation errors are also just strings
type EvalError = String
-- | Feedback generated for the student
data Feedback = Feedback { comments :: [String]
, issues :: [String]
}
-- | Feedback is a monoid
instance Monoid Feedback where
mempty = Feedback [] []
f `mappend` g = Feedback { comments = comments f ++ comments g
, issues = issues f ++ issues g
}
-- | Pretty print feedback for the instructor
printFeedback :: Feedback -> String
printFeedback f = init
$ unlines
$ ["Comments:"]
++ (number $ comments f)
++ ["", "Issues:"]
++ (number $ issues f)
where
number xs = [show i ++ ". " ++ x | (x, i) <- zip xs [0..]]
-- | The environment of the program
data Env = Env { verbose :: Bool
, logfile :: FilePath
, numberOfTests :: Int
, ignoreFailingParse :: Bool
}
deriving Show
-- | The default environment
defaultEnv :: Env
defaultEnv = Env { verbose = False
, logfile = "logfile.log"
, numberOfTests = 100
, ignoreFailingParse = False
}
-- | A parser for environments
parseEnv :: Parser Env
parseEnv = Env
<$> switch
( long "verbose"
<> short 'v'
<> help "Prints log messages during execution"
)
<*> strOption
( long "logfile"
<> short 'l'
<> value "logfile.log"
<> metavar "LOGFILE"
<> help "Logfile produced on program crash"
)
<*> option auto
( long "numTests"
<> short 'n'
<> value 100
<> metavar "NUM_TESTS"
<> help "Number of tests during property based testing"
)
<*> switch
( long "ignoreFailingParse"
<> short 'i'
<> help "Ignore the JAA parser failing if javac was OK, proceed with testing only"
)
-- | `printLog log` converts the log to a format suitable
-- for logfiles
printLog :: Log -> String
printLog = unlines
-- | Log a message
logMessage :: LogMessage -> EvalM ()
logMessage l = do
EvalM $ (lift . lift . lift) $ tell [l]
verb <- verbose <$> ask
if verb then
liftIO $ putStrLn l
else
return ()
-- | Generate a comment
comment :: String -> EvalM ()
comment c = EvalM $ (lift . lift) $ tell (Feedback [c] [])
-- | Generate an issue
issue :: String -> EvalM ()
issue i = EvalM $ (lift . lift) $ tell (Feedback [] [i])
-- | Throw an error
throw :: EvalError -> EvalM a
throw = EvalM . throwE
-- | Catch an error
catch :: EvalM a -> (EvalError -> EvalM a) -> EvalM a
catch action handler = EvalM $ catchE (unEvalM action) (unEvalM . handler)
-- | Lift an IO action and throw an exception if the
-- IO action throws an exception
performIO :: IO a -> EvalM a
performIO io = EvalM $ do
result <- liftIO $ Exc.catch (Right <$> io) (\e -> return $ Left $ show (e :: Exc.SomeException))
case result of
Left err -> throwE err
Right a -> return a
-- | A `MonadIO` instance where
-- lifting means catching and rethrowing exceptions
instance MonadIO EvalM where
liftIO = performIO
-- | Run an `EvalM` computation
runEvalM :: Env -> EvalM a -> IO ((Either EvalError a, Feedback), Log)
runEvalM env = runWriterT . runWriterT . flip runReaderT env . runExceptT . unEvalM
-- | Execute an `EvalM logfile` computation, reporting
-- errors to the user and dumping the log to file
-- before exiting
executeEvalM :: Env -> EvalM a -> IO a
executeEvalM env eval = do
((result, feedback), log) <- runEvalM env eval
case result of
Left e -> do
putStrLn $ "Error: " ++ e
putStrLn $ "The log has been written to " ++ (logfile env)
writeFile (logfile env) $ printLog log
exitFailure
Right a -> do
putStrLn $ printFeedback feedback
return a
resultEvalM :: EvalM a -> IO a
resultEvalM eval = do
((result, feedback), log) <- runEvalM defaultEnv eval
case result of
Left e -> do
putStrLn $ "Error: " ++ e
exitFailure
Right a -> return a
-- | Run an `EvalM` computation with a temporary directory
withTemporaryDirectory :: FilePath -> EvalM a -> EvalM a
withTemporaryDirectory dir evalm = do
liftIO $ createDirectoryIfMissing True dir
result <- catch evalm $ \e -> liftIO (removeDirectoryRecursive dir) >> throw e
liftIO $ removeDirectoryRecursive dir
return result
-- | Run an `EvalM` computation _in_ a temporary directory
inTemporaryDirectory :: FilePath -> EvalM a -> EvalM a
inTemporaryDirectory dir evalm = do
was <- liftIO getCurrentDirectory
logMessage $ "Changing directory to " ++ dir
liftIO $ setCurrentDirectory dir
result <- catch evalm $ \e -> liftIO (setCurrentDirectory was) >> throw e
logMessage $ "Changing directory to " ++ was
liftIO $ setCurrentDirectory was
return result
| null | https://raw.githubusercontent.com/DATX02-17-26/DATX02-17-26/f5eeec0b2034d5b1adcc66071f8cb5cd1b089acb/libsrc/EvaluationMonad.hs | haskell | | A monad for evaluating student solutions
| For now we just log strings
| Evaluation errors are also just strings
| Feedback generated for the student
| Feedback is a monoid
| Pretty print feedback for the instructor
| The environment of the program
| The default environment
| A parser for environments
| `printLog log` converts the log to a format suitable
for logfiles
| Log a message
| Generate a comment
| Generate an issue
| Throw an error
| Catch an error
| Lift an IO action and throw an exception if the
IO action throws an exception
| A `MonadIO` instance where
lifting means catching and rethrowing exceptions
| Run an `EvalM` computation
| Execute an `EvalM logfile` computation, reporting
errors to the user and dumping the log to file
before exiting
| Run an `EvalM` computation with a temporary directory
| Run an `EvalM` computation _in_ a temporary directory | DATX02 - 17 - 26 , automated assessment of imperative programs .
- Copyright , 2017 , see AUTHORS.md .
-
- 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 , MA 02110 - 1301 , USA .
- Copyright, 2017, see AUTHORS.md.
-
- 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, MA 02110-1301, USA.
-}
# LANGUAGE GeneralizedNewtypeDeriving #
module EvaluationMonad (
liftIO,
throw,
catch,
logMessage,
withTemporaryDirectory,
inTemporaryDirectory,
issue,
comment,
EvalM,
runEvalM,
executeEvalM,
resultEvalM,
Env(..),
defaultEnv,
parseEnv
) where
import Control.Monad.Trans.Class
import Control.Monad.Trans.Except as E
import Control.Monad.Writer.Lazy hiding ((<>))
import Control.Monad.Reader
import qualified Control.Exception as Exc
import System.Exit
import System.Directory
import Options.Applicative
import Data.Semigroup hiding (option)
newtype EvalM a = EvalM { unEvalM :: ExceptT EvalError (ReaderT Env (WriterT Feedback (WriterT Log IO))) a }
deriving (Monad, Applicative, Functor, MonadReader Env)
type LogMessage = String
type Log = [LogMessage]
type EvalError = String
data Feedback = Feedback { comments :: [String]
, issues :: [String]
}
instance Monoid Feedback where
mempty = Feedback [] []
f `mappend` g = Feedback { comments = comments f ++ comments g
, issues = issues f ++ issues g
}
printFeedback :: Feedback -> String
printFeedback f = init
$ unlines
$ ["Comments:"]
++ (number $ comments f)
++ ["", "Issues:"]
++ (number $ issues f)
where
number xs = [show i ++ ". " ++ x | (x, i) <- zip xs [0..]]
data Env = Env { verbose :: Bool
, logfile :: FilePath
, numberOfTests :: Int
, ignoreFailingParse :: Bool
}
deriving Show
defaultEnv :: Env
defaultEnv = Env { verbose = False
, logfile = "logfile.log"
, numberOfTests = 100
, ignoreFailingParse = False
}
parseEnv :: Parser Env
parseEnv = Env
<$> switch
( long "verbose"
<> short 'v'
<> help "Prints log messages during execution"
)
<*> strOption
( long "logfile"
<> short 'l'
<> value "logfile.log"
<> metavar "LOGFILE"
<> help "Logfile produced on program crash"
)
<*> option auto
( long "numTests"
<> short 'n'
<> value 100
<> metavar "NUM_TESTS"
<> help "Number of tests during property based testing"
)
<*> switch
( long "ignoreFailingParse"
<> short 'i'
<> help "Ignore the JAA parser failing if javac was OK, proceed with testing only"
)
printLog :: Log -> String
printLog = unlines
logMessage :: LogMessage -> EvalM ()
logMessage l = do
EvalM $ (lift . lift . lift) $ tell [l]
verb <- verbose <$> ask
if verb then
liftIO $ putStrLn l
else
return ()
comment :: String -> EvalM ()
comment c = EvalM $ (lift . lift) $ tell (Feedback [c] [])
issue :: String -> EvalM ()
issue i = EvalM $ (lift . lift) $ tell (Feedback [] [i])
throw :: EvalError -> EvalM a
throw = EvalM . throwE
catch :: EvalM a -> (EvalError -> EvalM a) -> EvalM a
catch action handler = EvalM $ catchE (unEvalM action) (unEvalM . handler)
performIO :: IO a -> EvalM a
performIO io = EvalM $ do
result <- liftIO $ Exc.catch (Right <$> io) (\e -> return $ Left $ show (e :: Exc.SomeException))
case result of
Left err -> throwE err
Right a -> return a
instance MonadIO EvalM where
liftIO = performIO
runEvalM :: Env -> EvalM a -> IO ((Either EvalError a, Feedback), Log)
runEvalM env = runWriterT . runWriterT . flip runReaderT env . runExceptT . unEvalM
executeEvalM :: Env -> EvalM a -> IO a
executeEvalM env eval = do
((result, feedback), log) <- runEvalM env eval
case result of
Left e -> do
putStrLn $ "Error: " ++ e
putStrLn $ "The log has been written to " ++ (logfile env)
writeFile (logfile env) $ printLog log
exitFailure
Right a -> do
putStrLn $ printFeedback feedback
return a
resultEvalM :: EvalM a -> IO a
resultEvalM eval = do
((result, feedback), log) <- runEvalM defaultEnv eval
case result of
Left e -> do
putStrLn $ "Error: " ++ e
exitFailure
Right a -> return a
withTemporaryDirectory :: FilePath -> EvalM a -> EvalM a
withTemporaryDirectory dir evalm = do
liftIO $ createDirectoryIfMissing True dir
result <- catch evalm $ \e -> liftIO (removeDirectoryRecursive dir) >> throw e
liftIO $ removeDirectoryRecursive dir
return result
inTemporaryDirectory :: FilePath -> EvalM a -> EvalM a
inTemporaryDirectory dir evalm = do
was <- liftIO getCurrentDirectory
logMessage $ "Changing directory to " ++ dir
liftIO $ setCurrentDirectory dir
result <- catch evalm $ \e -> liftIO (setCurrentDirectory was) >> throw e
logMessage $ "Changing directory to " ++ was
liftIO $ setCurrentDirectory was
return result
|
34b4416660df4178d778497af674b7bd1301a242de67c4b82112098909859f44 | OCamlPro/freeton_wallet | encoding.ml | (**************************************************************************)
(* *)
Copyright ( c ) 2021 OCamlPro SAS
(* *)
(* All rights reserved. *)
(* This file is distributed under the terms of the GNU Lesser General *)
Public License version 2.1 , with the special exception on linking
(* described in the LICENSE.md file in the root directory. *)
(* *)
(* *)
(**************************************************************************)
let keypair = Ton_sdk.TYPES.keypair_enc
let config = Types.config_enc
let key = Types.key_enc
let wallet = Json_encoding.list key
| null | https://raw.githubusercontent.com/OCamlPro/freeton_wallet/4e61b636bb086711bf1fbfa03b70d4cf7223edf7/src/freeton_wallet_lib/encoding.ml | ocaml | ************************************************************************
All rights reserved.
This file is distributed under the terms of the GNU Lesser General
described in the LICENSE.md file in the root directory.
************************************************************************ | Copyright ( c ) 2021 OCamlPro SAS
Public License version 2.1 , with the special exception on linking
let keypair = Ton_sdk.TYPES.keypair_enc
let config = Types.config_enc
let key = Types.key_enc
let wallet = Json_encoding.list key
|
be18b807f6c39d7925a670d5c8cbcbdf71b67dc152c092e637d6fe0683793485 | snorecone/meru | mountain.erl | -module(mountain).
-compile({parse_transform, meru_transform}).
-meru_pool(default).
-meru_bucket(<<"mountains">>).
-meru_record(mountain).
-meru_keyfun(make_key).
-meru_mergefun(merge).
-export([
test/0,
merge/3
]).
-record(mountain, {
name,
range,
planet,
lakes = [],
height =1,
type = "hello",
created_at,
updated_at
}).
test() ->
construct 2 mountain records
Chimbo = #mountain{
name = <<"Chimborazo">>,
range = <<"Cordillera Occidental">>,
planet = <<"Earth">>,
height = 6267,
type = <<"volcano">>
},
Oly = #mountain{
name = <<"Olympus Mons">>,
range = <<"Amazonis">>,
planet = <<"Mars">>,
height = 21171,
type = <<"volcano">>
},
% put our mountains in the store
{ok, ChimboKey, Chimbo} = mountain:put(Chimbo),
{ok, OlyKey, Oly} = mountain:put(Oly),
update chimborazo
ChimboUpdate = #mountain{
lakes = [<<"Rio Chambo Dam">>]
},
{ok, ChimboKey, _MergedChimbo} = mountain:put_merge(ChimboKey, ChimboUpdate, [{lake_merge, union}]),
% get the mountains out by key or tuple
{ok, Chimbo2} = mountain:get(ChimboKey),
{ok, Chimbo2} = mountain:get({<<"Chimborazo">>, <<"Cordillera Occidental">>}),
{ok, Oly} = mountain:get(OlyKey),
{ok, Oly} = mountain:get({<<"Olympus Mons">>, <<"Amazonis">>}),
% deleting a deleted record should return not found
{ok, ChimboKey} = mountain:delete({<<"Chimborazo">>, <<"Cordillera Occidental">>}),
{ok, ChimboKey} = mountain:delete(ChimboKey),
{ok, OlyKey} = mountain:delete(OlyKey).
%%
%% private
%%
make_key(#mountain{ name = Name, range = Range }) ->
make_key({Name, Range});
make_key({Name, Range}) -> term_to_binary({Name, Range});
make_key(Key) when is_binary(Key) -> Key.
merge(notfound, NewMountain, _) ->
NewMountain;
merge(OldMountain, NewMountain, MergeOpts) ->
Lakes = case proplists:get_value(lake_merge, MergeOpts) of
overwrite ->
NewMountain#mountain.lakes;
union ->
lists:usort(OldMountain#mountain.lakes ++ NewMountain#mountain.lakes)
end,
OldMountain#mountain{
lakes = Lakes,
updated_at = calendar:universal_time()
}.
| null | https://raw.githubusercontent.com/snorecone/meru/01e8ebe5da49f41bf5392be06c784c0550afbd3d/examples/mountain.erl | erlang | put our mountains in the store
get the mountains out by key or tuple
deleting a deleted record should return not found
private
| -module(mountain).
-compile({parse_transform, meru_transform}).
-meru_pool(default).
-meru_bucket(<<"mountains">>).
-meru_record(mountain).
-meru_keyfun(make_key).
-meru_mergefun(merge).
-export([
test/0,
merge/3
]).
-record(mountain, {
name,
range,
planet,
lakes = [],
height =1,
type = "hello",
created_at,
updated_at
}).
test() ->
construct 2 mountain records
Chimbo = #mountain{
name = <<"Chimborazo">>,
range = <<"Cordillera Occidental">>,
planet = <<"Earth">>,
height = 6267,
type = <<"volcano">>
},
Oly = #mountain{
name = <<"Olympus Mons">>,
range = <<"Amazonis">>,
planet = <<"Mars">>,
height = 21171,
type = <<"volcano">>
},
{ok, ChimboKey, Chimbo} = mountain:put(Chimbo),
{ok, OlyKey, Oly} = mountain:put(Oly),
update chimborazo
ChimboUpdate = #mountain{
lakes = [<<"Rio Chambo Dam">>]
},
{ok, ChimboKey, _MergedChimbo} = mountain:put_merge(ChimboKey, ChimboUpdate, [{lake_merge, union}]),
{ok, Chimbo2} = mountain:get(ChimboKey),
{ok, Chimbo2} = mountain:get({<<"Chimborazo">>, <<"Cordillera Occidental">>}),
{ok, Oly} = mountain:get(OlyKey),
{ok, Oly} = mountain:get({<<"Olympus Mons">>, <<"Amazonis">>}),
{ok, ChimboKey} = mountain:delete({<<"Chimborazo">>, <<"Cordillera Occidental">>}),
{ok, ChimboKey} = mountain:delete(ChimboKey),
{ok, OlyKey} = mountain:delete(OlyKey).
make_key(#mountain{ name = Name, range = Range }) ->
make_key({Name, Range});
make_key({Name, Range}) -> term_to_binary({Name, Range});
make_key(Key) when is_binary(Key) -> Key.
merge(notfound, NewMountain, _) ->
NewMountain;
merge(OldMountain, NewMountain, MergeOpts) ->
Lakes = case proplists:get_value(lake_merge, MergeOpts) of
overwrite ->
NewMountain#mountain.lakes;
union ->
lists:usort(OldMountain#mountain.lakes ++ NewMountain#mountain.lakes)
end,
OldMountain#mountain{
lakes = Lakes,
updated_at = calendar:universal_time()
}.
|
d2e40a31ecfaa57c0cb5e83d732f236f851862187277ee2ccb22ad8110a95152 | phadej/staged | Fn.hs | -- | Collection of type families
--
-- See individual modules for utilities.
module Data.SOP.Fn (
Append,
Concat,
ConcatMapAppend,
LiftA2Cons,
MapAppend,
MapConcat,
MapCons,
Sequence,
FLATTEN,
) where
import Data.SOP.Fn.Append
import Data.SOP.Fn.Concat
import Data.SOP.Fn.ConcatMapAppend
import Data.SOP.Fn.Flatten
import Data.SOP.Fn.LiftA2Cons
import Data.SOP.Fn.MapAppend
import Data.SOP.Fn.MapConcat
import Data.SOP.Fn.MapCons
import Data.SOP.Fn.Sequence
| null | https://raw.githubusercontent.com/phadej/staged/b51c8c508af71ddb2aca4a75030da9b2c4f9e3dd/staged-streams/src/Data/SOP/Fn.hs | haskell | | Collection of type families
See individual modules for utilities. | module Data.SOP.Fn (
Append,
Concat,
ConcatMapAppend,
LiftA2Cons,
MapAppend,
MapConcat,
MapCons,
Sequence,
FLATTEN,
) where
import Data.SOP.Fn.Append
import Data.SOP.Fn.Concat
import Data.SOP.Fn.ConcatMapAppend
import Data.SOP.Fn.Flatten
import Data.SOP.Fn.LiftA2Cons
import Data.SOP.Fn.MapAppend
import Data.SOP.Fn.MapConcat
import Data.SOP.Fn.MapCons
import Data.SOP.Fn.Sequence
|
853940b6c5dc4029fb4fb6a488da6d4d160178a7f6f149072910471e471f660e | inhabitedtype/ocaml-aws | modifyTransitGateway.ml | open Types
open Aws
type input = ModifyTransitGatewayRequest.t
type output = ModifyTransitGatewayResult.t
type error = Errors_internal.t
let service = "ec2"
let signature_version = Request.V4
let to_http service region req =
let uri =
Uri.add_query_params
(Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region)))
(List.append
[ "Version", [ "2016-11-15" ]; "Action", [ "ModifyTransitGateway" ] ]
(Util.drop_empty
(Uri.query_of_encoded
(Query.render (ModifyTransitGatewayRequest.to_query req)))))
in
`POST, uri, []
let of_http body =
try
let xml = Ezxmlm.from_string body in
let resp = Xml.member "ModifyTransitGatewayResponse" (snd xml) in
try
Util.or_error
(Util.option_bind resp ModifyTransitGatewayResult.parse)
(let open Error in
BadResponse
{ body; message = "Could not find well formed ModifyTransitGatewayResult." })
with Xml.RequiredFieldMissing msg ->
let open Error in
`Error
(BadResponse
{ body
; message =
"Error parsing ModifyTransitGatewayResult - missing field in body or \
children: "
^ msg
})
with Failure msg ->
`Error
(let open Error in
BadResponse { body; message = "Error parsing xml: " ^ msg })
let parse_error code err =
let errors = [] @ Errors_internal.common in
match Errors_internal.of_string err with
| Some var ->
if List.mem var errors
&&
match Errors_internal.to_http_code var with
| Some var -> var = code
| None -> true
then Some var
else None
| None -> None
| null | https://raw.githubusercontent.com/inhabitedtype/ocaml-aws/b6d5554c5d201202b5de8d0b0253871f7b66dab6/libraries/ec2/lib/modifyTransitGateway.ml | ocaml | open Types
open Aws
type input = ModifyTransitGatewayRequest.t
type output = ModifyTransitGatewayResult.t
type error = Errors_internal.t
let service = "ec2"
let signature_version = Request.V4
let to_http service region req =
let uri =
Uri.add_query_params
(Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region)))
(List.append
[ "Version", [ "2016-11-15" ]; "Action", [ "ModifyTransitGateway" ] ]
(Util.drop_empty
(Uri.query_of_encoded
(Query.render (ModifyTransitGatewayRequest.to_query req)))))
in
`POST, uri, []
let of_http body =
try
let xml = Ezxmlm.from_string body in
let resp = Xml.member "ModifyTransitGatewayResponse" (snd xml) in
try
Util.or_error
(Util.option_bind resp ModifyTransitGatewayResult.parse)
(let open Error in
BadResponse
{ body; message = "Could not find well formed ModifyTransitGatewayResult." })
with Xml.RequiredFieldMissing msg ->
let open Error in
`Error
(BadResponse
{ body
; message =
"Error parsing ModifyTransitGatewayResult - missing field in body or \
children: "
^ msg
})
with Failure msg ->
`Error
(let open Error in
BadResponse { body; message = "Error parsing xml: " ^ msg })
let parse_error code err =
let errors = [] @ Errors_internal.common in
match Errors_internal.of_string err with
| Some var ->
if List.mem var errors
&&
match Errors_internal.to_http_code var with
| Some var -> var = code
| None -> true
then Some var
else None
| None -> None
|
|
6839f61d18802739ac1dc37924a3f8e85ac2655f4294ed1d2f2b9bf2e54fbb46 | racket/typed-racket | sequences.rkt | #lang typed/racket/shallow
(ann (for ([z (list 1 2 3)]) (add1 z)) Void)
(ann (for ([z (vector 1 2 3)]) (add1 z)) Void)
(ann (for ([z "foobar"]) (string z)) Void)
(ann (for ([z #"foobar"]) (add1 z)) Void)
(ann (for ([z (open-input-string "foobar")]) (add1 z)) Void)
(ann (for ([z (in-list (list 1 2 3))]) (add1 z)) Void)
(ann (for ([z (in-vector (vector 1 2 3))]) (add1 z)) Void)
| null | https://raw.githubusercontent.com/racket/typed-racket/1dde78d165472d67ae682b68622d2b7ee3e15e1e/typed-racket-test/succeed/shallow/sequences.rkt | racket | #lang typed/racket/shallow
(ann (for ([z (list 1 2 3)]) (add1 z)) Void)
(ann (for ([z (vector 1 2 3)]) (add1 z)) Void)
(ann (for ([z "foobar"]) (string z)) Void)
(ann (for ([z #"foobar"]) (add1 z)) Void)
(ann (for ([z (open-input-string "foobar")]) (add1 z)) Void)
(ann (for ([z (in-list (list 1 2 3))]) (add1 z)) Void)
(ann (for ([z (in-vector (vector 1 2 3))]) (add1 z)) Void)
|
|
360d5a64b95ea30e8198aba2127ef3b7014d16191939e6c5568f20a80a26732a | ThatGuyHughesy/blockchain | endpoints.clj | (ns blockchain.endpoints
(:require [blockchain.blockchain :as blockchain]))
(defn get-chain []
{:chain @blockchain/chain
:length (count @blockchain/chain)})
(defn add-transaction [{:keys [sender recipient amount]}]
{:message (str "Transaction will be added to Block "
(blockchain/new-transaction! sender recipient amount))})
(defn mine-block []
(let [block (blockchain/mine!)]
{:message "New Block forged"
:index (:index block)
:transactions (:transactions block)
:proof (:proof block)
:previous-hash (:previous-hash block)}))
(defn get-nodes []
{:nodes @blockchain/nodes
:length (count @blockchain/nodes)})
(defn add-node [request]
{:message "New node has been added"
:nodes (blockchain/new-node! (:address request))})
(defn resolve-node []
(if (blockchain/resolve-conflicts! @blockchain/nodes 0)
{:message "Chain was replaced"
:chain @blockchain/chain}
{:message "Chain is authoritative"
:chain @blockchain/chain})) | null | https://raw.githubusercontent.com/ThatGuyHughesy/blockchain/e5e89be99d87c7909b570782fb5d847caed648fd/src/blockchain/endpoints.clj | clojure | (ns blockchain.endpoints
(:require [blockchain.blockchain :as blockchain]))
(defn get-chain []
{:chain @blockchain/chain
:length (count @blockchain/chain)})
(defn add-transaction [{:keys [sender recipient amount]}]
{:message (str "Transaction will be added to Block "
(blockchain/new-transaction! sender recipient amount))})
(defn mine-block []
(let [block (blockchain/mine!)]
{:message "New Block forged"
:index (:index block)
:transactions (:transactions block)
:proof (:proof block)
:previous-hash (:previous-hash block)}))
(defn get-nodes []
{:nodes @blockchain/nodes
:length (count @blockchain/nodes)})
(defn add-node [request]
{:message "New node has been added"
:nodes (blockchain/new-node! (:address request))})
(defn resolve-node []
(if (blockchain/resolve-conflicts! @blockchain/nodes 0)
{:message "Chain was replaced"
:chain @blockchain/chain}
{:message "Chain is authoritative"
:chain @blockchain/chain})) |
|
435de3d3bcead8497187cdc40dbebc7c13fb53d3806b55ca3a201147d4e81f90 | dbuenzli/fut | pkg.ml | #!/usr/bin/env ocaml
#use "topfind"
#require "topkg"
open Topkg
let base_unix = Conf.with_pkg "base-unix"
let react = Conf.with_pkg "react"
let jsoo = Conf.with_pkg "js_of_ocaml"
let jsoo_test ~cond test =
Pkg.flatten
[ Pkg.test ~run:false ~cond ~auto:false (test ^ ".js");
Pkg.test ~run:false ~cond ~auto:false (test ^ ".html"); ]
let () =
Pkg.describe "fut" @@ fun c ->
let base_unix = Conf.value c base_unix in
let react = Conf.value c react in
let jsoo = Conf.value c jsoo in
Ok [ Pkg.mllib "src/fut.mllib";
Pkg.mllib "src/fut_backend_base.mllib";
Pkg.mllib ~cond:react "src/futr.mllib";
Pkg.mllib ~cond:base_unix "src/futu.mllib";
Pkg.mllib ~cond:base_unix "src-select/fut_select.mllib"
~dst_dir:"select/";
Pkg.mllib ~cond:jsoo "src-jsoo/fut_jsoo.mllib" ~dst_dir:"jsoo/";
Pkg.test "test/test_select";
jsoo_test ~cond:jsoo "test/test_jsoo";
Pkg.test "test/cancel";
(* Pkg.test "test/sbox"; *)
Pkg.test "test/examples";
(*
Pkg.test "test/client";
Pkg.test "test/echoserver";
Pkg.test "test/uclient";
*)
]
| null | https://raw.githubusercontent.com/dbuenzli/fut/907de63df12815f2df2cb796baa7fa37ac2758d4/pkg/pkg.ml | ocaml | Pkg.test "test/sbox";
Pkg.test "test/client";
Pkg.test "test/echoserver";
Pkg.test "test/uclient";
| #!/usr/bin/env ocaml
#use "topfind"
#require "topkg"
open Topkg
let base_unix = Conf.with_pkg "base-unix"
let react = Conf.with_pkg "react"
let jsoo = Conf.with_pkg "js_of_ocaml"
let jsoo_test ~cond test =
Pkg.flatten
[ Pkg.test ~run:false ~cond ~auto:false (test ^ ".js");
Pkg.test ~run:false ~cond ~auto:false (test ^ ".html"); ]
let () =
Pkg.describe "fut" @@ fun c ->
let base_unix = Conf.value c base_unix in
let react = Conf.value c react in
let jsoo = Conf.value c jsoo in
Ok [ Pkg.mllib "src/fut.mllib";
Pkg.mllib "src/fut_backend_base.mllib";
Pkg.mllib ~cond:react "src/futr.mllib";
Pkg.mllib ~cond:base_unix "src/futu.mllib";
Pkg.mllib ~cond:base_unix "src-select/fut_select.mllib"
~dst_dir:"select/";
Pkg.mllib ~cond:jsoo "src-jsoo/fut_jsoo.mllib" ~dst_dir:"jsoo/";
Pkg.test "test/test_select";
jsoo_test ~cond:jsoo "test/test_jsoo";
Pkg.test "test/cancel";
Pkg.test "test/examples";
]
|
28876943a12301b0d5102e9b08fa7563cdffdfcd5bd08d90df5460c11333ba95 | vonli/Ext2-for-movitz | asm-x86.lisp | ;;;;------------------------------------------------------------------
;;;;
Copyright ( C ) 2007
;;;;
Description : x86 assembler for 16 , 32 , and 64 - bit modes .
Author : < >
;;;; Distribution: See the accompanying file COPYING.
;;;;
$ I d : asm - x86.lisp , v 1.37 2008/03/06 19:14:39 ffjeld Exp $
;;;;
;;;;------------------------------------------------------------------
(defpackage asm-x86
(:use :common-lisp :asm)
(:export #:assemble-instruction
#:disassemble-instruction
#:*cpu-mode*
#:*position-independent-p*))
(in-package asm-x86)
(defvar *cpu-mode* :32-bit)
(defvar *instruction-encoders*
(make-hash-table :test 'eq))
(defvar *use-jcc-16-bit-p* nil
"Whether to use 16-bit JCC instructions in 32-bit mode.")
(defun prefix-lookup (prefix-name)
(cdr (or (assoc prefix-name
'((:operand-size-override . #x66)
(:address-size-override . #x67)
(:16-bit-operand . #x66)
(:16-bit-address . #x67)
(:lock . #xf0)
(:repne . #xf2)
(:repz . #xf3)
(:cs-override . #x2e)
(:ss-override . #x36)
(:ds-override . #x3e)
(:es-override . #x26)
(:fs-override . #x64)
(:gs-override . #x65)))
(error "There is no instruction prefix named ~S." prefix-name))))
(defun rex-encode (rexes &key rm)
(let ((rex (logior (if (null rexes)
0
(+ #x40 (loop for rex in rexes
sum (ecase rex
(:rex.w #b1000)
(:rex.r #b0100)
(:rex.x #b0010)
(:rex.b #b0001)))))
(if (not rm)
0
(ldb (byte 1 3) rm)))))
(unless (zerop rex)
(list rex))))
(deftype octet ()
'(unsigned-byte 8))
(deftype xint (size)
`(or (unsigned-byte ,size)
(signed-byte ,size)))
(deftype uint (size)
`(unsigned-byte ,size))
(deftype sint (size)
`(signed-byte ,size))
(defun integer-to-octets (i n)
"Return list of n octets, encoding i in signed little endian."
(loop for b from 0 below (* 8 n) by 8
collect (ldb (byte 8 b) i)))
(defun encode-values-fun (operator legacy-prefixes prefixes rexes opcode mod reg rm scale index base displacement immediate operand-size address-size)
(assert opcode)
(when (or (and (eq address-size :32-bit)
(eq *cpu-mode* :64-bit))
(and (eq address-size :16-bit)
(eq *cpu-mode* :32-bit))
(and (eq address-size :64-bit)
(eq *cpu-mode* :32-bit))
(and (eq address-size :32-bit)
(eq *cpu-mode* :16-bit)))
(pushnew :address-size-override
prefixes))
(when (or (and (eq operand-size :16-bit)
(eq *cpu-mode* :64-bit))
(and (eq operand-size :16-bit)
(eq *cpu-mode* :32-bit))
(and (eq operand-size :32-bit)
(eq *cpu-mode* :16-bit)))
(pushnew :operand-size-override
prefixes))
(let ((code (append legacy-prefixes
(mapcar #'prefix-lookup (reverse prefixes))
(rex-encode rexes :rm rm)
(when (< 16 (integer-length opcode))
(list (ldb (byte 8 16) opcode)))
(when (< 8(integer-length opcode))
(list (ldb (byte 8 8) opcode)))
(list (ldb (byte 8 0) opcode))
(when (or mod reg rm)
(assert (and mod reg rm) (mod reg rm)
"Either all or none of mod, reg, and rm must be defined. mod=~S, reg=~S, rm=~S." mod reg rm)
(check-type mod (unsigned-byte 2))
(list (logior (ash (ldb (byte 2 0) mod)
6)
(ash (ldb (byte 3 0) reg)
3)
(ash (ldb (byte 3 0) rm)
0))))
(when (or scale index base)
(assert (and scale index base) (scale index base)
"Either all or none of scale, index, and base must be defined. scale=~S, index=~S, base=~S." scale index base)
(check-type scale (unsigned-byte 2))
(check-type index (unsigned-byte 4))
(check-type base (unsigned-byte 4))
(list (logior (ash (ldb (byte 2 0) scale)
6)
(ash (ldb (byte 3 0) index)
3)
(ash (ldb (byte 3 0) base)
0))))
displacement
immediate)))
(append (compute-extra-prefixes operator *pc* (length code))
code)))
(defmacro encode (values-form)
`(multiple-value-call #'encode-values-fun operator legacy-prefixes ,values-form))
(defmacro merge-encodings (form1 form2)
`(multiple-value-bind (prefixes1 rexes1 opcode1 mod1 reg1 rm1 scale1 index1 base1 displacement1 immediate1 operand-size1 address-size1)
,form1
(multiple-value-bind (prefixes2 rexes2 opcode2 mod2 reg2 rm2 scale2 index2 base2 displacement2 immediate2 operand-size2 address-size2)
,form2
(macrolet ((getone (a b name)
`(cond
((and ,a ,b)
(error "~A doubly defined: ~S and ~S." ',name ,a ,b))
(,a)
(,b))))
(encoded-values :prefixes (append prefixes1 prefixes2)
:rex (append (if (listp rexes1)
rexes1
(list rexes1))
(if (listp rexes2)
rexes2
(list rexes2)))
:opcode (getone opcode1 opcode2 opcode)
:mod (getone mod1 mod2 mod)
:reg (getone reg1 reg2 reg)
:rm (getone rm1 rm2 rm)
:scale (getone scale1 scale2 scale)
:index (getone index1 index2 index)
:base (getone base1 base2 base)
:displacement (getone displacement1 displacement2 displacement)
:immediate (getone immediate1 immediate2 immediate)
:operand-size (getone operand-size1 operand-size2 operand-size)
:address-size (getone address-size1 address-size2 address-size))))))
(defun encoded-values (&key prefixes prefix rex opcode mod reg rm scale index base displacement immediate operand-size address-size)
(values (append (when prefix
(list prefix))
prefixes)
(if (keywordp rex)
(list rex)
rex)
opcode
mod reg rm
scale index base
displacement
immediate
operand-size
address-size))
(defun assemble-instruction (instruction)
"Assemble a single instruction to a list of octets of x86 machine code, according to *cpu-mode* etc."
(multiple-value-bind (instruction legacy-prefixes options)
(if (listp (car instruction))
(values (cdr instruction)
(remove-if #'listp (car instruction))
(remove-if #'keywordp (car instruction)))
(values instruction
nil
nil))
(destructuring-bind (operator &rest operands)
instruction
(multiple-value-bind (code failp)
(apply (or (gethash operator *instruction-encoders*)
(error "Unknown instruction operator ~S in ~S." operator instruction))
operator
(mapcar #'prefix-lookup legacy-prefixes)
operands)
(cond
(failp
(error "Unable to encode ~S." instruction))
((null options)
code)
((assoc :size options)
(assert (= (second (assoc :size options))
(length code)))
code))))))
(defmacro define-operator (operator operator-mode lambda-list &body body)
(check-type operator keyword)
(labels ((find-forms (body)
(cond
((atom body)
nil)
((member (car body) '(reg-modrm modrm opcode imm-modrm imm opcode-reg
opcode-reg-imm pc-rel moffset sreg-modrm reg-cr
far-pointer))
(list body))
(t (mapcan #'find-forms body)))))
(let ((defun-name (intern (format nil "~A-~A" 'instruction-encoder operator))))
`(progn
(defun ,defun-name (operator legacy-prefixes ,@lambda-list)
(declare (ignorable operator legacy-prefixes))
(let ((operator-mode ',operator-mode)
(default-rex nil))
(declare (ignorable operator-mode default-rex))
(macrolet ((disassembler (&body body)
(declare (ignore body)))
(assembler (&body body)
`(progn ,@body)))
(block operator
,@body
(values nil 'fail)))))
(setf (gethash ',operator *instruction-encoders*)
',defun-name)
(macrolet ((disassembler (&body body)
`(progn ,@body))
(assembler (&body body)
(declare (ignore body))))
(let ((operator ',operator)
(operator-mode ',operator-mode)
(operand-formals ',lambda-list))
(declare (ignorable operator operand-formals operator-mode))
,@(find-forms body)))
',operator))))
(defmacro define-operator/none (name lambda-list &body body)
`(define-operator ,name nil ,lambda-list ,@body))
(deftype list-of (&rest elements)
"A list with elements of specified type(s)."
(labels ((make-list-of (elements)
(if (null elements)
'null
`(cons ,(car elements)
,(make-list-of (cdr elements))))))
(make-list-of elements)))
(deftype list-of* (&rest elements)
"A list starting with elements of specified type(s)."
(labels ((make-list-of (elements)
(if (null elements)
'list
`(cons ,(car elements)
,(make-list-of (cdr elements))))))
(make-list-of elements)))
(defparameter *opcode-disassemblers-16*
(make-array 256 :initial-element nil))
(defparameter *opcode-disassemblers-32*
(make-array 256 :initial-element nil))
(defparameter *opcode-disassemblers-64*
(make-array 256 :initial-element nil))
(deftype disassembly-decoder ()
'(list-of* boolean keyword (or keyword null) symbol))
(defun (setf opcode-disassembler) (decoder opcode operator-mode)
(check-type decoder disassembly-decoder)
(labels ((set-it (table pos)
(check-type pos (integer 0 *))
(check-type table (simple-vector 256))
(let ((bit-pos (* 8 (1- (ceiling (integer-length pos) 8)))))
(if (not (plusp bit-pos))
(progn
#+(or) (unless (or (eq nil decoder)
(eq nil (svref table pos))
(equal decoder (svref table pos)))
(warn "Redefining disassembler for ~@[~(~A~) ~]opcode #x~X from ~{~S ~}to ~{~S~^ ~}."
operator-mode opcode (svref table pos) decoder))
(setf (svref table pos) decoder))
(set-it (or (svref table (ldb (byte 8 bit-pos) pos))
(setf (svref table (ldb (byte 8 bit-pos) pos))
(make-array 256 :initial-element nil)))
(ldb (byte bit-pos 0) pos))))))
(ecase operator-mode
(:16-bit
(set-it *opcode-disassemblers-16* opcode))
(:32-bit
(set-it *opcode-disassemblers-32* opcode))
(:64-bit
(set-it *opcode-disassemblers-64* opcode))
((:8-bit nil)
(set-it *opcode-disassemblers-16* opcode)
(set-it *opcode-disassemblers-32* opcode)
(set-it *opcode-disassemblers-64* opcode)))))
(defmacro pop-code (code-place &optional context)
`(progn
(unless ,code-place
(error "End of byte-stream in the middle of an instruction."))
(let ((x (pop ,code-place)))
(check-type x (unsigned-byte 8) ,(format nil "an octet (context: ~A)" context))
x)))
(defmacro code-call (form &optional (code-place (case (car form) ((funcall apply) (third form)) (t (second form)))))
"Execute form, then 'magically' update the code binding with the secondary return value from form."
`(let (tmp)
(declare (ignorable tmp))
(setf (values tmp ,code-place) ,form)))
(defmacro define-disassembler ((operator opcode &optional cpu-mode digit backup-p operand-size) lambda-list &body body)
(cond
(digit
`(loop for mod from #b00 to #b11
do (loop for r/m from #b000 to #b111
as ext-opcode = (logior (ash ,opcode 8)
(ash ,digit 3)
(ash mod 6)
r/m)
do (define-disassembler (,operator ext-opcode ,cpu-mode nil t ,operand-size) ,lambda-list ,@body))))
((symbolp lambda-list)
`(setf (opcode-disassembler ,opcode ,cpu-mode) (list ,backup-p ,operator ,(or operand-size cpu-mode) ',lambda-list ,@body)))
(t (let ((defun-name (intern (format nil "~A-~A-~X~@[-~A~]" 'disassembler operator opcode cpu-mode))))
`(progn
(defun ,defun-name ,lambda-list ,@body)
(setf (opcode-disassembler ,opcode ',cpu-mode) (list ,backup-p ,operator ',(or operand-size cpu-mode) ',defun-name))
',defun-name)))))
(defun disassemble-simple-prefix (code operator opcode operand-size address-size rex)
(declare (ignore opcode rex))
(let ((instruction (code-call (disassemble-instruction code operand-size address-size nil))))
(values (if (consp (car instruction))
(list* (list* operator (car instruction))
(cdr instruction))
(list* (list operator)
instruction))
code)))
(define-disassembler (:lock #xf0) disassemble-simple-prefix)
(define-disassembler (:repne #xf2) disassemble-simple-prefix)
(define-disassembler (:repz #xf3) disassemble-simple-prefix)
(define-disassembler (:cs-override #x2e) disassemble-simple-prefix)
(define-disassembler (:ss-override #x36) disassemble-simple-prefix)
(define-disassembler (:ds-override #x3e) disassemble-simple-prefix)
(define-disassembler (:es-override #x26) disassemble-simple-prefix)
(define-disassembler (:fs-override #x64) disassemble-simple-prefix)
(define-disassembler (:gs-override #x65) disassemble-simple-prefix)
(define-disassembler (:operand-size-override #x66 :32-bit) (code operator opcode operand-size address-size rex)
(declare (ignore operator opcode operand-size rex))
(disassemble-instruction code :16-bit address-size nil))
(define-disassembler (:address-size-override #x67 :32-bit) (code operator opcode operand-size address-size rex)
(declare (ignore operator opcode address-size rex))
(disassemble-instruction code operand-size :16-bit nil))
(define-disassembler (:operand-size-override #x66 :16-bit) (code operator opcode operand-size address-size rex)
(declare (ignore operator opcode operand-size rex))
(disassemble-instruction code :32-bit address-size nil))
(define-disassembler (:address-size-override #x67 :16-bit) (code operator opcode operand-size address-size rex)
(declare (ignore operator opcode address-size rex))
(disassemble-instruction code operand-size :32-bit nil))
(defmacro define-operator/8 (operator lambda-list &body body)
`(define-operator ,operator :8-bit ,lambda-list
(let ((default-rex nil))
(declare (ignorable default-rex))
,@body)))
(defmacro define-operator/16 (operator lambda-list &body body)
`(define-operator ,operator :16-bit ,lambda-list
(let ((default-rex nil))
(declare (ignorable default-rex))
,@body)))
(defmacro define-operator/32 (operator lambda-list &body body)
`(define-operator ,operator :32-bit ,lambda-list
(let ((default-rex nil))
(declare (ignorable default-rex))
,@body)))
(defmacro define-operator/64 (operator lambda-list &body body)
`(define-operator ,operator :64-bit ,lambda-list
(let ((default-rex '(:rex.w)))
(declare (ignorable default-rex))
,@body)))
(defmacro define-operator/64* (operator lambda-list &body body)
`(define-operator ,operator :64-bit ,lambda-list
(let ((default-rex (case *cpu-mode*
(:64-bit nil)
(t '(:rex.w)))))
(declare (ignorable default-rex))
,@body)))
(defmacro define-operator* ((&key |16| |32| |64| dispatch) args &body body)
(let ((body16 (subst '(xint 16) :int-16-32-64
(subst :dx :dx-edx-rdx
(subst :ax :ax-eax-rax body))))
(body32 (subst '(xint 32) :int-16-32-64
(subst :edx :dx-edx-rdx
(subst :eax :ax-eax-rax body))))
(body64 (subst '(sint 32) :int-16-32-64
(subst :rdx :dx-edx-rdx
(subst :rax :ax-eax-rax body)))))
`(progn
,(when |16|
`(define-operator/16 ,|16| ,args ,@body16))
,(when |32|
`(define-operator/32 ,|32| ,args ,@body32))
,(when |64|
`(define-operator/64 ,|64| ,args ,@body64))
,(when dispatch
(let ((dispatch-name (intern (format nil "~A-~A" 'instruction-dispatcher dispatch))))
`(progn
(defun ,dispatch-name (&rest args)
(declare (dynamic-extent args))
(loop for encoder in (ecase *cpu-mode*
(:32-bit ',(remove nil (list |32| |16| |64|)))
(:64-bit ',(remove nil (list |64| |32| |16|)))
(:16-bit ',(remove nil (list |16| |32| |64|))))
thereis (apply (gethash encoder *instruction-encoders*) args)
finally (return (values nil 'fail))))
(setf (gethash ',dispatch *instruction-encoders*)
',dispatch-name))))
nil)))
(defun resolve-and-encode (x type &key size)
(encode-integer (cond
((typep x type)
x)
((integerp x)
(error "Immediate value #x~X out of range for ~S." x type))
((assoc x *symtab*)
(let ((value (cdr (assoc x *symtab*))))
(assert (typep value type))
value))
(t (error "Unresolved symbol ~S (size ~S)." x size)))
type))
(defun resolve-pc-relative (operand)
(etypecase operand
(pc-relative-operand
(reduce #'+ (cdr operand)
:key #'resolve-operand))
(symbol-reference
(assert *pc* (*pc*) "Cannot encode a pc-relative operand without a value for ~S." '*pc*)
(- (resolve-operand operand)
*pc*))))
(defun encode-integer (i type)
(assert (typep i type))
(let ((bit-size (cadr type)))
(loop for b upfrom 0 below bit-size by 8
collect (ldb (byte 8 b) i))))
(defun type-octet-size (type)
(assert (member (car type)
'(sint uint xint))
(type))
(values (ceiling (cadr type) 8)))
(defun opcode-octet-size (opcode)
(loop do (setf opcode (ash opcode -8))
count t
while (plusp opcode)))
(defun parse-indirect-operand (operand)
(assert (indirect-operand-p operand))
(let (reg offsets reg2 reg-scale)
(dolist (expr operand)
(etypecase expr
(register-operand
(if reg
(setf reg2 expr)
(setf reg expr)))
((cons register-operand
(cons (member 1 2 4 8) null))
(when reg
(assert (not reg-scale))
(setf reg2 reg))
(setf reg (first expr)
reg-scale (second expr)))
(immediate-operand
(push expr offsets))
((cons (eql :+))
(dolist (term (cdr expr))
(push term offsets)))))
(when (and (eq reg2 :esp)
(or (not reg-scale)
(eql 1 reg-scale)))
(psetf reg reg2
reg2 reg))
(values reg offsets reg2 (if (not reg)
nil
(or reg-scale 1)))))
(defun register-set-by-mode (mode)
(ecase mode
(:8-bit '(:al :cl :dl :bl :ah :ch :dh :bh))
(:16-bit '(:ax :cx :dx :bx :sp :bp :si :di))
(:32-bit '(:eax :ecx :edx :ebx :esp :ebp :esi :edi))
(:64-bit '(:rax :rcx :rdx :rbx :rsp :rbp :rsi :rdi :r8 :r9 :r10 :r11 :r12 :13 :r14 :r15))
(:mm '(:mm0 :mm1 :mm2 :mm3 :mm4 :mm5 :mm6 :mm7))
(:xmm '(:xmm0 :xmm1 :xmm2 :xmm3 :xmm4 :xmm5 :xmm6 :xmm7))
(:segment '(:es :cs :ss :ds :fs :gs))))
(defun encode-reg/mem (operand mode)
(check-type mode (member nil :8-bit :16-bit :32-bit :64-bit :mm :xmm))
(if (and mode (keywordp operand))
(encoded-values :mod #b11
:rm (or (position operand (register-set-by-mode mode))
(error "Unknown ~(~D~) register ~S." mode operand)))
(multiple-value-bind (reg offsets reg2 reg-scale)
(parse-indirect-operand operand)
(check-type reg-scale (member nil 1 2 4 8))
(assert (or (not reg2)
(and reg reg2)))
(assert (or (not reg-scale)
(and reg reg-scale)))
(let ((offset (reduce #'+ offsets
:key #'resolve-operand)))
(cond
((and (not reg)
(eq mode :16-bit)
(typep offset '(xint 16)))
(encoded-values :mod #b00
:rm #b110
:address-size :16-bit
:displacement (encode-integer offset '(xint 16))))
((and (not reg)
(typep offset '(xint 32)))
(encoded-values :mod #b00
:rm #b101
:address-size :32-bit
:displacement (encode-integer offset '(xint 32))))
((and (eq reg :sp)
(not reg2)
(= 1 reg-scale))
(etypecase offset
((eql 0)
(encoded-values :mod #b00
:rm #b100
:scale 0
:index #b100
:base #b100
:address-size :16-bit))
((sint 8)
(encoded-values :mod #b01
:rm #b100
:displacement (encode-integer offset '(sint 8))
:scale 0
:index #b100
:base #b100
:address-size :16-bit))
((xint 32)
(encoded-values :mod #b10
:rm #b100
:displacement (encode-integer offset '(xint 32))
:scale 0
:index #b100
:base #b100
:address-size :16-bit))))
((and (eq reg :esp)
(= 1 reg-scale))
(let ((reg2-index (or (position reg2 '(:eax :ecx :edx :ebx nil :ebp :esi :edi))
(error "Unknown reg2 [F] ~S." reg2))))
(etypecase offset
((eql 0)
(encoded-values :mod #b00
:rm #b100
:scale 0
:index reg2-index
:base #b100
:address-size :32-bit))
((sint 8)
(encoded-values :mod #b01
:rm #b100
:displacement (encode-integer offset '(sint 8))
:scale 0
:index reg2-index
:base #b100
:address-size :32-bit))
((xint 32)
(encoded-values :mod #b10
:rm #b100
:displacement (encode-integer offset '(xint 32))
:scale 0
:index reg2-index
:base #b100
:address-size :32-bit)))))
((and (eq reg :rsp)
(not reg2)
(= 1 reg-scale))
(etypecase offset
((eql 0)
(encoded-values :mod #b00
:rm #b100
:scale 0
:index #b100
:base #b100
:address-size :64-bit))
((sint 8)
(encoded-values :mod #b01
:rm #b100
:displacement (encode-integer offset '(sint 8))
:scale 0
:index #b100
:base #b100
:address-size :64-bit))
((sint 32)
(encoded-values :mod #b10
:rm #b100
:displacement (encode-integer offset '(sint 32))
:scale 0
:index #b100
:base #b100
:address-size :64-bit))))
(t (multiple-value-bind (register-index map address-size)
(let* ((map32 '(:eax :ecx :edx :ebx :esp :ebp :esi :edi))
(index32 (position reg map32))
(map64 '(:rax :rcx :rdx :rbx :rsp :rbp :rsi :rdi :r8 :r9 :r10 :r11 :r12 :r13 :r14 :r15))
(index64 (unless index32
(position reg map64))))
(if index32
(values index32 map32 :32-bit)
(values index64 map64 :64-bit)))
(cond
((and (not reg2)
register-index
(= 1 reg-scale)
(and (zerop offset)
(not (= register-index #b101))))
(encoded-values :mod #b00
:rm register-index
:address-size address-size))
((and (not reg2)
register-index
(= 1 reg-scale)
(typep offset '(sint 8)))
(encoded-values :mod #b01
:rm register-index
:displacement (encode-integer offset '(sint 8))
:address-size address-size))
((and (not reg2)
register-index
(= 1 reg-scale)
(or (typep offset '(sint 32))
(and (eq :32-bit address-size)
(typep offset '(xint 32)))))
(encoded-values :mod #b10
:rm register-index
:displacement (encode-integer offset '(sint 32))
:address-size address-size))
((and (not reg2)
register-index
(if (eq :64-bit *cpu-mode*)
(typep offset '(sint 32))
(typep offset '(xint 32)))
(not (= #b100 register-index)))
(encoded-values :rm #b100
:mod #b00
:index register-index
:base #b101
:scale (or (position reg-scale '(1 2 4 8))
(error "Unknown register scale ~S." reg-scale))
:displacement (encode-integer offset '(xint 32))))
((and reg2
register-index
(zerop offset)
(not (= register-index #b100)))
(encoded-values :mod #b00
:rm #b100
:scale (or (position reg-scale '(1 2 4 8))
(error "Unknown register scale ~S." reg-scale))
:index register-index
:base (or (position reg2 map)
(error "unknown reg2 [A] ~S" reg2))
:address-size address-size))
((and reg2
register-index
(typep offset '(sint 8))
(not (= register-index #b100)))
(encoded-values :mod #b01
:rm #b100
:scale (position reg-scale '(1 2 4 8))
:index register-index
:base (or (position reg2 map)
(error "unknown reg2 [B] ~S" reg2))
:address-size address-size
:displacement (encode-integer offset '(sint 8))))
((and reg2
register-index
(eq :32-bit address-size)
(typep offset '(sint 8))
(not (= register-index #b100)))
(encoded-values :mod #b01
:rm #b100
:scale (position reg-scale '(1 2 4 8))
:index register-index
:base (or (position reg2 map)
(error "unknown reg2 [C] ~S." reg2))
:address-size address-size
:displacement (encode-integer offset '(sint 8))))
((and reg2
register-index
(eq :32-bit address-size)
(typep offset '(xint 32))
(not (= register-index #b100)))
(encoded-values :mod #b10
:rm #b100
:scale (position reg-scale '(1 2 4 8))
:index register-index
:base (or (position reg2 map)
(error "unknown reg2 [D] ~S." reg2))
:address-size address-size
:displacement (encode-integer offset '(xint 32))))
((and reg2
register-index
(eq :64-bit address-size)
(typep offset '(sint 32))
(not (= register-index #b100)))
(encoded-values :mod #b01
:rm #b100
:scale (position reg-scale '(1 2 4 8))
:index register-index
:base (or (position reg2 map)
(error "unknown reg2 [E] ~S" reg2))
:address-size address-size
:displacement (encode-integer offset '(sint 32))))
(t (let ((rm16 (position-if (lambda (x)
(or (and (eq (car x) reg)
(eq (cdr x) reg2))
(and (eq (car x) reg2)
(eq (cdr x) reg))))
'((:bx . :si) (:bx . :di) (:bp . :si) (:bp . :di)
(:si) (:di) (:bp) (:bx)))))
(cond
((and rm16
(zerop offset)
(not (= #b110 rm16)))
(encoded-values :mod #b00
:rm rm16
:address-size :16-bit))
((and rm16
(typep offset '(sint 8)))
(encoded-values :mod #b01
:rm rm16
:address-size :16-bit
:displacement (encode-integer offset '(sint 8))))
((and rm16
(typep offset '(xint 16)))
(encoded-values :mod #b10
:rm rm16
:address-size :16-bit
:displacement (encode-integer offset '(xint 16))))
(t (error "Huh? reg: ~S, reg2: ~S, scale: ~S, offset: ~S" reg reg2 reg-scale offset)))))))))))))
(defun operand-ordering (formals &rest arrangement)
(loop with rarrangement = (reverse arrangement)
for formal in formals
when (getf rarrangement formal)
collect it))
(defun order-operands (ordering &rest operands)
(loop for key in ordering
collect (or (getf operands key)
(error "No operand ~S in ~S." key operands))))
(defun decode-integer (code type)
"Decode an integer of specified type."
(let* ((bit-size (cadr type))
(unsigned-integer (loop for b from 0 below bit-size by 8
sum (ash (pop-code code integer) b))))
(values (if (or (not (member (car type) '(sint signed-byte)))
(not (logbitp (1- bit-size) unsigned-integer)))
unsigned-integer
(- (ldb (byte bit-size 0)
(1+ (lognot unsigned-integer)))))
code)))
(defun disassemble-instruction (code &optional override-operand-size override-address-size rex)
(labels ((lookup-decoder (table opcode)
(let* ((backup-code code)
(datum (pop-code code))
(opcode (logior (ash opcode 8)
datum))
(decoder (svref table datum)))
(typecase decoder
(vector
(lookup-decoder decoder opcode))
(disassembly-decoder
(when (car decoder)
(setf code backup-code))
(values (cdr decoder)
opcode))
(t (error "No disassembler registered for opcode #x~X." opcode))))))
(multiple-value-bind (decoder opcode)
(lookup-decoder (ecase (or override-operand-size *cpu-mode*)
(:16-bit *opcode-disassemblers-16*)
(:32-bit *opcode-disassemblers-32*)
(:64-bit *opcode-disassemblers-64*))
0)
(destructuring-bind (operator operand-size decoder-function &rest extra-args)
decoder
(values (code-call (apply decoder-function
code
operator
opcode
(or operand-size override-operand-size)
(or override-address-size *cpu-mode*)
rex
extra-args))
code)))))
(defun decode-no-operands (code operator opcode operand-size address-size rex &rest fixed-operands)
(declare (ignore opcode operand-size address-size rex))
(values (list* operator
(remove nil fixed-operands))
code))
(defun decode-reg-cr (code operator opcode operand-size address-size rex operand-ordering)
(declare (ignore opcode operand-size address-size))
(let ((modrm (pop-code code)))
(values (list* operator
(order-operands operand-ordering
:reg (nth (ldb (byte 3 0) modrm)
(register-set-by-mode (if rex :64-bit :32-bit)))
:cr (nth (ldb (byte 3 3) modrm)
'(:cr0 :cr1 :cr2 :cr3 :cr4 :cr5 :cr6 :cr7))))
code)))
(defun decode-reg-modrm (code operator opcode operand-size address-size rex operand-ordering &optional (reg-mode operand-size))
(declare (ignore opcode rex))
(values (list* operator
(order-operands operand-ordering
:reg (nth (ldb (byte 3 3) (car code))
(register-set-by-mode reg-mode))
:modrm (ecase address-size
(:32-bit
(code-call (decode-reg-modrm-32 code operand-size)))
(:16-bit
(code-call (decode-reg-modrm-16 code operand-size))))))
code))
(defun decode-modrm (code operator opcode operand-size address-size rex)
(declare (ignore opcode rex))
(values (list operator
(ecase address-size
(:32-bit
(code-call (decode-reg-modrm-32 code operand-size)))
(:16-bit
(code-call (decode-reg-modrm-16 code operand-size)))))
code))
(defun decode-imm-modrm (code operator opcode operand-size address-size rex imm-type operand-ordering &key fixed-modrm)
(declare (ignore opcode rex))
(values (list* operator
(order-operands operand-ordering
:modrm (or fixed-modrm
(when (member :modrm operand-ordering)
(ecase address-size
(:32-bit
(code-call (decode-reg-modrm-32 code operand-size)))
(:16-bit
(code-call (decode-reg-modrm-16 code operand-size))))))
:imm (code-call (decode-integer code imm-type))))
code))
(defun decode-far-pointer (code operator opcode operand-size address-size rex type)
(declare (ignore opcode operand-size address-size rex))
(let ((offset (code-call (decode-integer code type)))
(segment (code-call (decode-integer code '(uint 16)))))
(values (list operator
segment
(list offset))
code)))
(defun decode-pc-rel (code operator opcode operand-size address-size rex type)
(declare (ignore opcode operand-size address-size rex))
(values (list operator
`(:pc+ ,(code-call (decode-integer code type))))
code))
(defun decode-moffset (code operator opcode operand-size address-size rex type operand-ordering fixed-operand)
(declare (ignore opcode operand-size address-size rex))
(values (list* operator
(order-operands operand-ordering
:moffset (list (code-call (decode-integer code type)))
:fixed fixed-operand))
code))
(defun decode-opcode-reg (code operator opcode operand-size address-size rex operand-ordering extra-operand)
(declare (ignore address-size rex))
(values (list* operator
(order-operands operand-ordering
:reg (nth (ldb (byte 3 0) opcode)
(register-set-by-mode operand-size))
:extra extra-operand))
code))
(defun decode-opcode-reg-imm (code operator opcode operand-size address-size rex operand-ordering imm-type)
(declare (ignore address-size rex))
(values (list* operator
(order-operands operand-ordering
:reg (nth (ldb (byte 3 0) opcode)
(register-set-by-mode operand-size))
:imm (code-call (decode-integer code imm-type))))
code))
(defun decode-reg-modrm-16 (code operand-size)
(let* ((modrm (pop-code code mod/rm))
(mod (ldb (byte 2 6) modrm))
(reg (ldb (byte 3 3) modrm))
(r/m (ldb (byte 3 0) modrm)))
(values (if (= mod #b11)
(nth reg (register-set-by-mode operand-size))
(flet ((operands (i)
(nth i '((:bx :si) (:bx :di) (:bp :si) (:bp :di) (:si) (:di) (:bp) (:bx)))))
(ecase mod
(#b00
(case r/m
(#b110 (list (code-call (decode-integer code '(uint 16)))))
(t (operands r/m))))
(#b01
(append (operands r/m)
(list (code-call (decode-integer code '(sint 8))))))
(#b10
(append (operands r/m)
(list (code-call (decode-integer code '(uint 16)))))))))
code)))
(defun decode-reg-modrm-32 (code operand-size)
"Return a list of the REG, and the MOD/RM operands."
(let* ((modrm (pop-code code mod/rm))
(mod (ldb (byte 2 6) modrm))
(r/m (ldb (byte 3 0) modrm)))
(values (if (= mod #b11)
(nth r/m (register-set-by-mode operand-size))
(flet ((decode-sib ()
(let* ((sib (pop-code code sib))
(ss (ldb (byte 2 6) sib))
(index (ldb (byte 3 3) sib))
(base (ldb (byte 3 0) sib)))
(nconc (unless (= index #b100)
(let ((index-reg (nth index (register-set-by-mode :32-bit))))
(if (= ss #b00)
(list index-reg)
(list (list index-reg (ash 2 ss))))))
(if (/= base #b101)
(list (nth base (register-set-by-mode :32-bit)))
(ecase mod
(#b00 nil)
((#b01 #b10) (list :ebp))))))))
(ecase mod
(#b00 (case r/m
(#b100 (decode-sib))
(#b101 (code-call (decode-integer code '(uint 32))))
(t (list (nth r/m (register-set-by-mode :32-bit))))))
(#b01 (case r/m
(#b100 (nconc(decode-sib)
(list (code-call (decode-integer code '(sint 8))))))
(t (list (nth r/m (register-set-by-mode :32-bit))
(code-call (decode-integer code '(sint 8)))))))
(#b10 (case r/m
(#b100 (nconc (decode-sib)
(list (code-call (decode-integer code '(uint 32))))))
(t (list (nth r/m (register-set-by-mode :32-bit))
(code-call (decode-integer code '(uint 32))))))))))
code)))
(defmacro return-when (form)
`(let ((x ,form))
(when x (return-from operator x))))
(defmacro return-values-when (form)
`(let ((x (encode ,form)))
(when x (return-from operator x))))
(defmacro imm (imm-operand opcode imm-type &optional extra-operand &rest extras)
`(progn
(assembler
(when (and ,@(when extra-operand
(list (list* 'eql extra-operand)))
(immediate-p ,imm-operand))
(let ((immediate (resolve-operand ,imm-operand)))
(when (typep immediate ',imm-type)
(return-values-when
(encoded-values :opcode ,opcode
:immediate (encode-integer immediate ',imm-type)
:operand-size operator-mode
:rex default-rex
,@extras))))))
(disassembler
,(if extra-operand
`(define-disassembler (operator ,opcode operator-mode)
decode-imm-modrm
',imm-type
(operand-ordering operand-formals
:imm ',imm-operand
:modrm ',(first extra-operand))
:fixed-modrm ',(second extra-operand))
`(define-disassembler (operator ,opcode operator-mode)
decode-imm-modrm
',imm-type
'(:imm))))))
(defmacro imm-modrm (op-imm op-modrm opcode digit type)
`(progn
(assembler
(when (immediate-p ,op-imm)
(let ((immediate (resolve-operand ,op-imm)))
(when (typep immediate ',type)
(return-values-when
(merge-encodings (encoded-values :opcode ,opcode
:reg ,digit
:operand-size operator-mode
:rex default-rex
:immediate (encode-integer immediate ',type))
(encode-reg/mem ,op-modrm operator-mode)))))))
(disassembler
(define-disassembler (operator ,opcode operator-mode ,digit)
decode-imm-modrm
',type
(operand-ordering operand-formals
:imm ',op-imm
:modrm ',op-modrm)))))
(defun compute-extra-prefixes (operator pc size)
(let ((ff (assoc operator *instruction-compute-extra-prefix-map*)))
(when ff
(funcall (cdr ff) pc size))))
(defun encode-pc-rel (operator legacy-prefixes opcode operand type &rest extras)
(when (typep operand '(or pc-relative-operand symbol-reference))
(let* ((estimated-code-size-no-extras (+ (length legacy-prefixes)
(type-octet-size type)
(opcode-octet-size opcode)))
(estimated-extra-prefixes (compute-extra-prefixes operator *pc* estimated-code-size-no-extras))
(estimated-code-size (+ estimated-code-size-no-extras
(length estimated-extra-prefixes)))
(offset (let ((*pc* (when *pc*
(+ *pc* estimated-code-size))))
(resolve-pc-relative operand))))
(when (typep offset type)
(let ((code (let ((*instruction-compute-extra-prefix-map* nil))
(encode (apply #'encoded-values
:opcode opcode
:displacement (encode-integer offset type)
extras)))))
(if (= (length code)
estimated-code-size-no-extras)
(append estimated-extra-prefixes code)
(let* ((code-size (length code))
(extra-prefixes (compute-extra-prefixes operator *pc* code-size))
(offset (let ((*pc* (when *pc*
(+ *pc* code-size (length extra-prefixes)))))
(resolve-pc-relative operand))))
(when (typep offset type)
(let ((code (let ((*instruction-compute-extra-prefix-map* nil))
(encode (apply #'encoded-values
:opcode opcode
:displacement (encode-integer offset type)
extras)))))
(assert (= code-size (length code)))
(append extra-prefixes code))))))))))
(defmacro pc-rel (opcode operand type &optional (mode 'operator-mode) &rest extras)
`(progn
(assembler
(return-when (encode-pc-rel operator legacy-prefixes ,opcode ,operand ',type ,@extras)))
(disassembler
(define-disassembler (operator ,opcode ,mode)
decode-pc-rel
',type))))
(defmacro modrm (operand opcode digit)
`(progn
(assembler
(when (typep ,operand '(or register-operand indirect-operand))
(return-values-when
(merge-encodings (encoded-values :opcode ,opcode
:reg ,digit
:operand-size operator-mode
:rex default-rex)
(encode-reg/mem ,operand operator-mode)))))
(disassembler
(define-disassembler (operator ,opcode operator-mode ,digit) decode-modrm))))
(defun encode-reg-modrm (operator legacy-prefixes op-reg op-modrm opcode operator-mode default-rex &optional reg/mem-mode &rest extras)
(let* ((reg-map (ecase operator-mode
(:8-bit '(:al :cl :dl :bl :ah :ch :dh :bh))
(:16-bit '(:ax :cx :dx :bx :sp :bp :si :di))
(:32-bit '(:eax :ecx :edx :ebx :esp :ebp :esi :edi))
(:64-bit '(:rax :rcx :rdx :rbx :rsp :rbp :rsi :rdi :r8 :r9 :r10 :r11 :r12 :r13 :r14 :r15))
(:mm '(:mm0 :mm1 :mm2 :mm3 :mm4 :mm5 :mm6 :mm7 :mm8))
(:xmm '(:xmm0 :xmm1 :xmm2 :xmm3 :xmm4 :xmm5 :xmm6 :xmm7))))
(reg-index (position op-reg reg-map)))
(when reg-index
(encode (merge-encodings (apply #'encoded-values
:opcode opcode
:reg reg-index
:operand-size operator-mode
:rex default-rex
extras)
(encode-reg/mem op-modrm (or reg/mem-mode operator-mode)))))))
(defmacro reg-modrm (op-reg op-modrm opcode &optional reg/mem-mode &rest extras)
`(progn
(assembler
(return-when (encode-reg-modrm operator legacy-prefixes ,op-reg ,op-modrm ,opcode
operator-mode default-rex ,reg/mem-mode ,@extras)))
(disassembler
(define-disassembler (operator ,opcode operator-mode)
decode-reg-modrm
(operand-ordering operand-formals
:reg ',op-reg
:modrm ',op-modrm)))))
(defun encode-reg-cr (operator legacy-prefixes op-reg op-cr opcode operator-mode default-rex &rest extras)
(let* ((reg-map (ecase operator-mode
(:32-bit '(:eax :ecx :edx :ebx :esp :ebp :esi :edi))
(:64-bit '(:rax :rcx :rdx :rbx :rsp :rbp :rsi :rdi :r8 :r9 :r10 :r11 :r12 :r13 :r14 :r15))))
(reg-index (position op-reg reg-map))
(cr-index (position op-cr '(:cr0 :cr1 :cr2 :cr3 :cr4 :cr5 :cr6 :cr7))))
(when (and reg-index
cr-index)
(encode (apply #'encoded-values
:opcode opcode
:mod #b11
:rm reg-index
:reg cr-index
:operand-size (if (not (eq *cpu-mode* :64-bit))
nil
operator-mode)
:rex default-rex
extras)))))
(defmacro reg-cr (op-reg op-cr opcode &rest extras)
`(progn
(assembler
(return-when (encode-reg-cr operator legacy-prefixes ,op-reg ,op-cr ,opcode operator-mode default-rex ,@extras)))
(disassembler
(define-disassembler (operator ,opcode nil nil nil :32-bit)
decode-reg-cr
(operand-ordering operand-formals
:reg ',op-reg
:cr ',op-cr)))))
(defmacro sreg-modrm (op-sreg op-modrm opcode &rest extras)
`(progn
(assembler
(let* ((reg-map '(:es :cs :ss :ds :fs :gs))
(reg-index (position ,op-sreg reg-map)))
(when reg-index
(return-values-when
(merge-encodings (encoded-values :opcode ,opcode
:reg reg-index
:rex default-rex
,@extras)
(encode-reg/mem ,op-modrm operator-mode))))))
(disassembler
(define-disassembler (operator ,opcode nil nil nil :16-bit)
decode-reg-modrm
(operand-ordering operand-formals
:reg ',op-sreg
:modrm ',op-modrm)
:segment))))
(defmacro moffset (opcode op-offset type fixed-operand)
`(progn
(assembler
(when (and ,@(when fixed-operand
`((eql ,@fixed-operand)))
(indirect-operand-p ,op-offset))
(multiple-value-bind (reg offsets reg2)
(parse-indirect-operand ,op-offset)
(when (and (not reg)
(not reg2))
(return-values-when
(encoded-values :opcode ,opcode
:displacement (encode-integer (reduce #'+ offsets
:key #'resolve-operand)
',type)))))))
(disassembler
(define-disassembler (operator ,opcode operator-mode)
decode-moffset
',type
(operand-ordering operand-formals
:moffset ',op-offset
:fixed ',(first fixed-operand))
',(second fixed-operand)))))
(defmacro opcode (opcode &optional fixed-operand fixed-operand2 &rest extras)
`(progn
(assembler
(when (and ,@(when fixed-operand
`((eql ,@fixed-operand)))
,@(when fixed-operand2
`((eql ,@fixed-operand2))))
(return-values-when
(encoded-values :opcode ,opcode
,@extras
:operand-size operator-mode))))
(disassembler
(define-disassembler (operator ,opcode)
decode-no-operands
,(second fixed-operand)
,(second fixed-operand2)))))
(defmacro opcode* (opcode &rest extras)
`(return-values-when
(encoded-values :opcode ,opcode
,@extras)))
(defun encode-opcode-reg (operator legacy-prefixes opcode op-reg operator-mode default-rex)
(let* ((reg-map (ecase operator-mode
(:8-bit '(:al :cl :dl :bl :ah :ch :dh :bh))
(:16-bit '(:ax :cx :dx :bx :sp :bp :si :di))
(:32-bit '(:eax :ecx :edx :ebx :esp :ebp :esi :edi))
(:64-bit '(:rax :rcx :rdx :rbx :rsp :rbp :rsi :rdi :r8 :r9 :r10 :r11 :r12 :r13 :r14 :r15))
(:mm '(:mm0 :mm1 :mm2 :mm3 :mm4 :mm5 :mm6 :mm7 :mm8))
(:xmm '(:xmm0 :xmm1 :xmm2 :xmm3 :xmm4 :xmm5 :xmm6 :xmm7))))
(reg-index (position op-reg reg-map)))
(when reg-index
(encode (encoded-values :opcode (+ opcode (ldb (byte 3 0) reg-index))
:operand-size operator-mode
:rex (cond
((>= reg-index 8)
(assert (eq :64-bit operator-mode))
'(:rex.w :rex.r))
(t default-rex)))))))
(defmacro opcode-reg (opcode op-reg &optional extra-operand)
`(progn
(assembler
(when (and ,@(when extra-operand
`((eql ,@extra-operand))))
(return-when
(encode-opcode-reg operator legacy-prefixes ,opcode ,op-reg operator-mode default-rex))))
(disassembler
(loop for reg from #b000 to #b111
do ,(if (not extra-operand)
`(define-disassembler (operator (logior ,opcode reg) operator-mode)
decode-opcode-reg
'(:reg)
nil)
`(define-disassembler (operator (logior ,opcode reg) operator-mode)
decode-opcode-reg
(operand-ordering operand-formals
:reg ',op-reg
:extra ',(first extra-operand))
',(second extra-operand)))))))
(defun encode-opcode-reg-imm (operator legacy-prefixes opcode op-reg op-imm type operator-mode default-rex)
(when (immediate-p op-imm)
(let ((immediate (resolve-operand op-imm)))
(when (typep immediate type)
(let* ((reg-map (ecase operator-mode
(:8-bit '(:al :cl :dl :bl :ah :ch :dh :bh))
(:16-bit '(:ax :cx :dx :bx :sp :bp :si :di))
(:32-bit '(:eax :ecx :edx :ebx :esp :ebp :esi :edi))
(:64-bit '(:rax :rcx :rdx :rbx :rsp :rbp :rsi :rdi :r8 :r9 :r10 :r11 :r12 :r13 :r14 :r15))
(:mm '(:mm0 :mm1 :mm2 :mm3 :mm4 :mm5 :mm6 :mm7 :mm8))
(:xmm '(:xmm0 :xmm1 :xmm2 :xmm3 :xmm4 :xmm5 :xmm6 :xmm7))))
(reg-index (position op-reg reg-map)))
(when reg-index
(encode (encoded-values :opcode (+ opcode (ldb (byte 3 0) reg-index))
:operand-size operator-mode
:immediate (encode-integer immediate type)
:rex (cond
((>= reg-index 8)
(assert (eq :64-bit operator-mode))
'(:rex.w :rex.r))
(t default-rex))))))))))
(defmacro opcode-reg-imm (opcode op-reg op-imm type)
`(progn
(assembler
(return-when
(encode-opcode-reg-imm operator legacy-prefixes ,opcode ,op-reg ,op-imm ',type operator-mode default-rex)))
(disassembler
(loop for reg from #b000 to #b111
do (define-disassembler (operator (logior ,opcode reg) operator-mode)
decode-opcode-reg-imm
(operand-ordering operand-formals
:reg ',op-reg
:imm ',op-imm)
',type)))))
(defmacro far-pointer (opcode segment offset offset-type &optional mode &rest extra)
`(progn
(assembler
(when (and (immediate-p ,segment)
FIXME : should be immediate - p , change in bootblock.lisp .
(let ((segment (resolve-operand ,segment))
(offset (resolve-operand (car ,offset))))
(when (and (typep segment '(uint 16))
(typep offset ',offset-type))
(return-when (encode (encoded-values :opcode ,opcode
:immediate (append (encode-integer offset ',offset-type)
(encode-integer segment '(uint 16)))
,@extra)))))))
(disassembler
(define-disassembler (operator ,opcode ,(or mode 'operator-mode))
decode-far-pointer
',offset-type))))
;;;;;;;;;;; Pseudo-instructions
(define-operator/none :% (op &rest form)
(case op
(:bytes
(return-from operator
(destructuring-bind (byte-size &rest data)
form
(loop for datum in data
append (loop for b from 0 below byte-size by 8
collect (ldb (byte 8 b)
(resolve-operand datum)))))))
(:funcall
(return-from operator
(destructuring-bind (function &rest args)
form
(apply function (mapcar #'resolve-operand args)))))
(:fun
(return-from operator
(destructuring-bind (function &rest args)
(car form)
(loop for cbyte in (apply function (mapcar #'resolve-operand args))
append (loop for octet from 0 below (imagpart cbyte)
collect (ldb (byte 8 (* 8 octet))
(realpart cbyte)))))))
(:format
(return-from operator
(destructuring-bind (byte-size format-control &rest format-args)
form
(ecase byte-size
(8 (let ((data (map 'list #'char-code
(apply #'format nil format-control
(mapcar #'resolve-operand format-args)))))
(cons (length data)
data)))))))
(:align
(return-from operator
(destructuring-bind (alignment)
form
(let* ((offset (mod *pc* alignment)))
(when (plusp offset)
(make-list (- alignment offset)
:initial-element 0))))))))
ADC
(define-operator/8 :adcb (src dst)
(imm src #x14 (xint 8) (dst :al))
(imm-modrm src dst #x80 2 (xint 8))
(reg-modrm dst src #x12)
(reg-modrm src dst #x10))
(define-operator* (:16 :adcw :32 :adcl :64 :adcr) (src dst)
(imm-modrm src dst #x83 2 (sint 8))
(imm src #x15 :int-16-32-64 (dst :ax-eax-rax))
(imm-modrm src dst #x81 2 :int-16-32-64)
(reg-modrm dst src #x13)
(reg-modrm src dst #x11))
;;;;;;;;;;; ADD
(define-operator/8 :addb (src dst)
(imm src #x04 (xint 8) (dst :al))
(imm-modrm src dst #x80 0 (xint 8))
(reg-modrm dst src #x02)
(reg-modrm src dst #x00))
(define-operator* (:16 :addw :32 :addl :64 :addr) (src dst)
(imm-modrm src dst #x83 0 (sint 8))
(imm src #x05 :int-16-32-64 (dst :ax-eax-rax))
(imm-modrm src dst #x81 0 :int-16-32-64)
(reg-modrm dst src #x03)
(reg-modrm src dst #x01))
;;;;;;;;;;; AND
(define-operator/8 :andb (mask dst)
(imm mask #x24 (xint 8) (dst :al))
(imm-modrm mask dst #x80 4 (xint 8))
(reg-modrm dst mask #x22)
(reg-modrm mask dst #x20))
(define-operator* (:16 :andw :32 :andl :64 :andr) (mask dst)
(imm-modrm mask dst #x83 4 (sint 8))
(imm mask #x25 :int-16-32-64 (dst :ax-eax-rax))
(imm-modrm mask dst #x81 4 :int-16-32-64)
(reg-modrm dst mask #x23)
(reg-modrm mask dst #x21))
BOUND , BSF , BSR , BSWAP
(define-operator* (:16 :boundw :32 :bound) (bounds reg)
(reg-modrm reg bounds #x62))
(define-operator* (:16 :bsfw :32 :bsfl :64 :bsfr) (src dst)
(reg-modrm dst src #x0fbc))
(define-operator* (:16 :bsrw :32 :bsrl :64 :bsrr) (src dst)
(reg-modrm dst src #x0fbd))
(define-operator* (:32 :bswap :64 :bswapr) (dst)
(opcode-reg #x0fc8 dst))
BT , BTC , BTR , BTS
(define-operator* (:16 :btw :32 :btl :64 :btr) (bit src)
(imm-modrm bit src #x0fba 4 (uint 8))
(reg-modrm bit src #x0fa3))
(define-operator* (:16 :btcw :32 :btcl :64 :btcr) (bit src)
(imm-modrm bit src #x0fba 7 (uint 8))
(reg-modrm bit src #x0fbb))
(define-operator* (:16 :btrw :32 :btrl :64 :btrr) (bit src)
(imm-modrm bit src #x0fba 6 (uint 8))
(reg-modrm bit src #x0fb3))
(define-operator* (:16 :btsw :32 :btsl :64 :btsr) (bit src)
(imm-modrm bit src #x0fba 5 (uint 8))
(reg-modrm bit src #x0fab))
;;;;;;;;;;; CALL
(define-operator/16 :callw (dest)
(pc-rel #xe8 dest (sint 16))
(modrm dest #xff 2))
(define-operator/32 :call (dest)
(pc-rel #xe8 dest (sint 32))
(modrm dest #xff 2))
(define-operator/none :call-segment (dest)
(modrm dest #xff 3))
CLC , CLD , CLI , CLTS , CMC
(define-operator/none :clc () (opcode #xf8))
(define-operator/none :cld () (opcode #xfc))
(define-operator/none :cli () (opcode #xfa))
(define-operator/none :clts () (opcode #x0f06))
(define-operator/none :cmc () (opcode #xf5))
;;;;;;;;;;; CMOVcc
(define-operator* (:16 :cmovaw :32 :cmova :64 :cmovar) (src dst)
Move if above , and ZF=0 .
(define-operator* (:16 :cmovaew :32 :cmovae :64 :cmovaer) (src dst)
(reg-modrm dst src #x0f43)) ; Move if above or equal, CF=0.
(define-operator* (:16 :cmovbw :32 :cmovb :64 :cmovbr) (src dst)
(reg-modrm dst src #x0f42)) ; Move if below, CF=1.
(define-operator* (:16 :cmovbew :32 :cmovbe :64 :cmovber) (src dst)
Move if below or equal , CF=1 or ZF=1 .
(define-operator* (:16 :cmovcw :32 :cmovc :64 :cmovcr) (src dst)
(reg-modrm dst src #x0f42)) ; Move if carry, CF=1.
(define-operator* (:16 :cmovew :32 :cmove :64 :cmover) (src dst)
Move if equal , ZF=1 .
(define-operator* (:16 :cmovgw :32 :cmovg :64 :cmovgr) (src dst)
Move if greater , ZF=0 and SF = OF .
(define-operator* (:16 :cmovgew :32 :cmovge :64 :cmovger) (src dst)
Move if greater or equal , SF = OF .
(define-operator* (:16 :cmovlw :32 :cmovl :64 :cmovlr) (src dst)
(reg-modrm dst src #x0f4c))
(define-operator* (:16 :cmovlew :32 :cmovle :64 :cmovler) (src dst)
Move if less or equal , ZF=1 or SF/=OF .
(define-operator* (:16 :cmovnaw :32 :cmovna :64 :cmovnar) (src dst)
Move if not above , CF=1 or ZF=1 .
(define-operator* (:16 :cmovnaew :32 :cmovnae :64 :cmovnaer) (src dst)
(reg-modrm dst src #x0f42)) ; Move if not above or equal, CF=1.
(define-operator* (:16 :cmovnbw :32 :cmovnb :64 :cmovnbr) (src dst)
(reg-modrm dst src #x0f43)) ; Move if not below, CF=0.
(define-operator* (:16 :cmovnbew :32 :cmovnbe :64 :cmovnber) (src dst)
Move if not below or equal , and ZF=0 .
(define-operator* (:16 :cmovncw :32 :cmovnc :64 :cmovncr) (src dst)
(reg-modrm dst src #x0f43)) ; Move if not carry, CF=0.
(define-operator* (:16 :cmovnew :32 :cmovne :64 :cmovner) (src dst)
(reg-modrm dst src #x0f45)) ; Move if not equal, ZF=0.
(define-operator* (:16 :cmovngew :32 :cmovnge :64 :cmovnger) (src dst)
Move if not greater or equal , SF/=OF .
(define-operator* (:16 :cmovnlw :32 :cmovnl :64 :cmovnlr) (src dst)
Move if not less SF = OF .
(define-operator* (:16 :cmovnlew :32 :cmovnle :64 :cmovnler) (src dst)
Move if not less or equal , ZF=0 and SF = OF .
(define-operator* (:16 :cmovnow :32 :cmovno :64 :cmovnor) (src dst)
(reg-modrm dst src #x0f41)) ; Move if not overflow, OF=0.
(define-operator* (:16 :cmovnpw :32 :cmovnp :64 :cmovnpr) (src dst)
Move if not parity , .
(define-operator* (:16 :cmovnsw :32 :cmovns :64 :cmovnsr) (src dst)
(reg-modrm dst src #x0f49)) ; Move if not sign, SF=0.
(define-operator* (:16 :cmovnzw :32 :cmovnz :64 :cmovnzr) (src dst)
Move if not zero , ZF=0 .
(define-operator* (:16 :cmovow :32 :cmovo :64 :cmovor) (src dst)
(reg-modrm dst src #x0f40)) ; Move if overflow, OF=1.
(define-operator* (:16 :cmovpw :32 :cmovp :64 :cmovpr) (src dst)
Move if parity , PF=1 .
(define-operator* (:16 :cmovsw :32 :cmovs :64 :cmovsr) (src dst)
(reg-modrm dst src #x0f48)) ; Move if sign, SF=1
(define-operator* (:16 :cmovzw :32 :cmovz :64 :cmovzr) (src dst)
Move if zero , ZF=1
CMP
(define-operator/8 :cmpb (src dst)
(imm src #x3c (xint 8) (dst :al))
(imm-modrm src dst #x80 7 (xint 8))
(reg-modrm dst src #x3a)
(reg-modrm src dst #x38))
(define-operator* (:16 :cmpw :32 :cmpl :64 :cmpr) (src dst)
(imm-modrm src dst #x83 7 (sint 8))
(imm src #x3d :int-16-32-64 (dst :ax-eax-rax))
(imm-modrm src dst #x81 7 :int-16-32-64)
(reg-modrm dst src #x3b)
(reg-modrm src dst #x39))
;;;;;;;;;;; CMPXCHG
(define-operator/8 :cmpxchgb (cmp-reg cmp-modrm al-dst)
(when (eq al-dst :al)
(reg-modrm cmp-reg cmp-modrm #x0fb0)))
(define-operator* (:16 :cmpxchgw :32 :cmpxchgl :64 :cmpxchgr) (cmp-reg cmp-modrm al-dst)
(when (eq al-dst :ax-eax-rax)
(reg-modrm cmp-reg cmp-modrm #x0fb1)))
;;;;;;;;;;; CMPXCHG8B, CMPXCHG16B
(define-operator/32 :cmpxchg8b (address)
(modrm address #x0fc7 1))
(define-operator/64 :cmpxchg16b (address)
(modrm address #x0fc7 1))
(define-operator/none :cpuid ()
(opcode* #x0fa2))
CWD , CDQ
(define-operator/16 :cwd (reg1 reg2)
(when (and (eq reg1 :ax)
(eq reg2 :dx))
(opcode #x99)))
(define-operator/32 :cdq (reg1 reg2)
(when (and (eq reg1 :eax)
(eq reg2 :edx))
(opcode #x99)))
(define-operator/64 :cqo (reg1 reg2)
(when (and (eq reg1 :rax)
(eq reg2 :rdx))
(opcode #x99)))
DEC
(define-operator/8 :decb (dst)
(modrm dst #xfe 1))
(define-operator* (:16 :decw :32 :decl) (dst)
(unless (eq *cpu-mode* :64-bit)
(opcode-reg #x48 dst))
(modrm dst #xff 1))
(define-operator* (:64 :decr) (dst)
(modrm dst #xff 1))
DIV
(define-operator/8 :divb (divisor dividend)
(when (eq dividend :ax)
(modrm divisor #xf6 6)))
(define-operator* (:16 :divw :32 :divl :64 :divr) (divisor dividend1 dividend2)
(when (and (eq dividend1 :ax-eax-rax)
(eq dividend2 :dx-edx-rdx))
(modrm divisor #xf7 6)))
HLT
(define-operator/none :halt ()
(opcode #xf4))
IDIV
(define-operator/8 :idivb (divisor dividend1 dividend2)
(when (and (eq dividend1 :al)
(eq dividend2 :ah))
(modrm divisor #xf6 7)))
(define-operator* (:16 :idivw :32 :idivl :64 :idivr) (divisor dividend1 dividend2)
(when (and (eq dividend1 :ax-eax-rax)
(eq dividend2 :dx-edx-rdx))
(modrm divisor #xf7 7)))
IMUL
(define-operator/32 :imull (factor product1 &optional product2)
(when (not product2)
(reg-modrm product1 factor #x0faf))
(when (and (eq product1 :eax)
(eq product2 :edx))
(modrm factor #xf7 5))
(typecase factor
((sint 8)
(reg-modrm product1 product2 #x6b
nil
:displacement (encode-integer factor '(sint 8))))
((sint 32)
(reg-modrm product1 product2 #x69
nil
:displacement (encode-integer factor '(sint 32))))))
;;;;;;;;;;; IN
(define-operator/8 :inb (port dst)
(opcode #xec (port :dx) (dst :al))
(imm port #xe4 (uint 8) (dst :al)))
(define-operator/16 :inw (port dst)
(opcode #xed (port :dx) (dst :ax))
(imm port #xe5 (uint 8) (dst :ax)))
(define-operator/32 :inl (port dst)
(opcode #xed (port :dx) (dst :eax))
(imm port #xe5 (uint 8) (dst :eax)))
;;;;;;;;;;; INC
(define-operator/8 :incb (dst)
(modrm dst #xfe 0))
(define-operator* (:16 :incw :32 :incl) (dst)
(unless (eq *cpu-mode* :64-bit)
(opcode-reg #x40 dst))
(modrm dst #xff 0))
(define-operator* (:64 :incr) (dst)
(modrm dst #xff 0))
;;;;;;;;;;; INT
(define-operator/none :break ()
(opcode #xcc))
(define-operator/none :int (vector)
(imm vector #xcd (uint 8)))
(define-operator/none :into ()
(opcode #xce))
INVLPG
(define-operator/none :invlpg (address)
(modrm address #x0f01 7))
;;;;;;;;;;; IRET
(define-operator* (:16 :iret :32 :iretd :64 :iretq) ()
(opcode #xcf () ()
:rex default-rex))
(defmacro define-jcc (name opcode1 &optional (opcode2 (+ #x0f10 opcode1)))
`(define-operator/none ,name (dst)
(pc-rel ,opcode1 dst (sint 8))
(when (or (and (eq *cpu-mode* :32-bit)
*use-jcc-16-bit-p*)
(eq *cpu-mode* :16-bit))
(pc-rel ,opcode2 dst (sint 16) nil
:operand-size :16-bit))
(pc-rel ,opcode2 dst (sint 32) nil
:operand-size (case *cpu-mode*
((:16-bit :32-bit)
:32-bit)))))
(define-jcc :ja #x77)
(define-jcc :jae #x73)
(define-jcc :jb #x72)
(define-jcc :jbe #x76)
(define-jcc :jc #x72)
(define-jcc :jecx #xe3)
(define-jcc :je #x74)
(define-jcc :jg #x7f)
(define-jcc :jge #x7d)
(define-jcc :jl #x7c)
(define-jcc :jle #x7e)
(define-jcc :jna #x76)
(define-jcc :jnae #x72)
(define-jcc :jnb #x73)
(define-jcc :jnbe #x77)
(define-jcc :jnc #x73)
(define-jcc :jne #x75)
(define-jcc :jng #x7e)
(define-jcc :jnge #x7c)
(define-jcc :jnl #x7d)
(define-jcc :jnle #x7f)
(define-jcc :jno #x71)
(define-jcc :jnp #x7b)
(define-jcc :jns #x79)
(define-jcc :jnz #x75)
(define-jcc :jo #x70)
(define-jcc :jp #x7a)
(define-jcc :jpe #x7a)
(define-jcc :jpo #x7b)
(define-jcc :js #x78)
(define-jcc :jz #x74)
(define-operator* (:16 :jcxz :32 :jecxz :64 :jrcxz) (dst)
(pc-rel #xe3 dst (sint 8) nil
:operand-size operator-mode
:rex default-rex))
JMP
(define-operator/none :jmp (seg-dst &optional dst)
(cond
(dst
(when (eq *cpu-mode* :16-bit)
(far-pointer #xea seg-dst dst (uint 16) :16-bit))
(when (eq *cpu-mode* :32-bit)
(far-pointer #xea seg-dst dst (xint 32) :32-bit)))
(t (let ((dst seg-dst))
(pc-rel #xeb dst (sint 8))
(when (or (and (eq *cpu-mode* :32-bit)
*use-jcc-16-bit-p*)
(eq *cpu-mode* :16-bit))
(pc-rel #xe9 dst (sint 16) :16-bit))
(pc-rel #xe9 dst (sint 32) :32-bit)
(when (or (not *position-independent-p*)
(indirect-operand-p dst))
(let ((operator-mode :32-bit))
(modrm dst #xff 4)))))))
(define-operator* (:16 :jmpw-segment :32 :jmp-segment :64 :jmpr-segment) (addr)
(modrm addr #xff 5))
LAHF , LAR
(define-operator/none :lahf ()
(case *cpu-mode*
((:16-bit :32-bit)
(opcode #x9f))))
(define-operator* (:16 :larw :32 :larl :64 :larr) (src dst)
(reg-modrm dst src #x0f02))
LEA
(define-operator* (:16 :leaw :32 :leal :64 :lear) (addr dst)
(reg-modrm dst addr #x8d))
;;;;;;;;;;; LEAVE
(define-operator/none :leave ()
(opcode #xc9))
;;;;;;;;;;; LFENCE
(define-operator/none :lfence ()
(opcode #x0faee8))
LGDT ,
(define-operator* (:16 :lgdtw :32 :lgdtl :64 :lgdtr :dispatch :lgdt) (addr)
(when (eq operator-mode *cpu-mode*)
(modrm addr #x0f01 2)))
(define-operator* (:16 :lidtw :32 :lidt :64 :lidtr) (addr)
(modrm addr #x0f01 3))
;;;;;;;;;;; LMSW
(define-operator/16 :lmsw (src)
(modrm src #x0f01 6))
;;;;;;;;;;; LODS
(define-operator/8 :lodsb ()
(opcode #xac))
(define-operator* (:16 :lodsw :32 :lodsl :64 :lodsr) ()
(opcode #xad))
LOOP , LOOPE , LOOPNE
(define-operator/none :loop (dst)
(pc-rel #xe2 dst (sint 8)))
(define-operator/none :loope (dst)
(pc-rel #xe1 dst (sint 8)))
(define-operator/none :loopne (dst)
(pc-rel #xe0 dst (sint 8)))
MOV
(define-operator/8 :movb (src dst)
(moffset #xa2 dst (uint 8) (src :al))
(moffset #xa0 src (uint 8) (dst :al))
(opcode-reg-imm #xb0 dst src (xint 8))
(imm-modrm src dst #xc6 0 (xint 8))
(reg-modrm dst src #x8a)
(reg-modrm src dst #x88))
(define-operator/16 :movw (src dst)
(moffset #xa3 dst (uint 16) (src :ax))
(moffset #xa0 src (uint 16) (dst :ax))
(opcode-reg-imm #xb8 dst src (xint 16))
(imm-modrm src dst #xc7 0 (xint 16))
(sreg-modrm src dst #x8c)
(sreg-modrm dst src #x8e)
(reg-modrm dst src #x8b)
(reg-modrm src dst #x89))
(define-operator/32 :movl (src dst)
(moffset #xa3 dst (uint 32) (src :eax))
(moffset #xa0 src (uint 32) (dst :eax))
(opcode-reg-imm #xb8 dst src (xint 32))
(imm-modrm src dst #xc7 0 (xint 32))
(reg-modrm dst src #x8b)
(reg-modrm src dst #x89))
MOVCR
(define-operator* (:32 :movcrl :dispatch :movcr) (src dst)
(reg-cr src dst #x0f22)
(reg-cr dst src #x0f20))
MOVS
(define-operator/8 :movsb ()
(opcode #xa4))
(define-operator/16 :movsw ()
(opcode #xa5))
(define-operator/32 :movsl ()
(opcode #xa5))
;;;;;;;;;;; MOVSX
(define-operator* (:32 :movsxb) (src dst)
(reg-modrm dst src #x0fbe))
(define-operator* (:32 :movsxw) (src dst)
(reg-modrm dst src #x0fbf))
;;;;;;;;;;; MOVZX
(define-operator* (:16 :movzxbw :32 :movzxbl :dispatch :movzxb) (src dst)
(reg-modrm dst src #x0fb6 :8-bit))
(define-operator* (:32 :movzxw) (src dst)
(reg-modrm dst src #x0fb7))
;;;;;;;;;;; MUL
(define-operator/32 :mull (factor product1 &optional product2)
(when (and (eq product1 :eax)
(eq product2 :edx))
(modrm factor #xf7 4)))
;;;;;;;;;;; NEG
(define-operator/8 :negb (dst)
(modrm dst #xf6 3))
(define-operator* (:16 :negw :32 :negl :64 :negr) (dst)
(modrm dst #xf7 3))
;;;;;;;;;;; NOT
(define-operator/8 :notb (dst)
(modrm dst #xf6 2))
(define-operator* (:16 :notw :32 :notl :64 :notr) (dst)
(modrm dst #xf7 2))
;;;;;;;;;;; OR
(define-operator/8 :orb (src dst)
(imm src #x0c (xint 8) (dst :al))
(imm-modrm src dst #x80 1 (xint 8))
(reg-modrm dst src #x0a)
(reg-modrm src dst #x08))
(define-operator* (:16 :orw :32 :orl :64 :orr) (src dst)
(imm-modrm src dst #x83 1 (sint 8))
(imm src #x0d :int-16-32-64 (dst :ax-eax-rax))
(imm-modrm src dst #x81 1 :int-16-32-64)
(reg-modrm dst src #x0b)
(reg-modrm src dst #x09))
;;;;;;;;;;; OUT
(define-operator/8 :outb (src port)
(opcode #xee (src :al) (port :dx))
(imm port #xe6 (uint 8) (src :al)))
(define-operator/16 :outw (src port)
(opcode #xef (src :ax) (port :dx))
(imm port #xe7 (uint 8) (src :ax)))
(define-operator/32 :outl (src port)
(opcode #xef (src :eax) (port :dx))
(imm port #xe7 (uint 8) (src :eax)))
;;;;;;;;;;; POP
(define-operator* (:16 :popw :32 :popl) (dst)
(opcode #x1f (dst :ds))
(opcode #x07 (dst :es))
(opcode #x17 (dst :ss))
(opcode #x0fa1 (dst :fs))
(opcode #x0fa9 (dst :gs))
(opcode-reg #x58 dst)
(modrm dst #x8f 0))
(define-operator/64* :popr (dst)
(opcode-reg #x58 dst)
(modrm dst #x8f 0))
;;;;;;;;;;; POPF
(define-operator* (:16 :popfw :32 :popfl :64 :popfr) ()
(opcode #x9d))
;;;;;;;;;;; PRFETCH
(define-operator/none :prefetch-nta (m8)
(modrm m8 #x0f18 0))
(define-operator/none :prefetch-t0 (m8)
(modrm m8 #x0f18 1))
(define-operator/none :prefetch-t1 (m8)
(modrm m8 #x0f18 2))
(define-operator/none :prefetch-t2 (m8)
(modrm m8 #x0f18 3))
;;;;;;;;;;; PUSH
(define-operator* (:16 :pushw :32 :pushl) (src)
(opcode #x0e (src :cs))
(opcode #x16 (src :ss))
(opcode #x1e (src :ds))
(opcode #x06 (src :es))
(opcode #x0fa0 (src :fs))
(opcode #x0fa8 (src :gs))
(opcode-reg #x50 src)
(imm src #x6a (sint 8))
(imm src #x68 :int-16-32-64 () :operand-size operator-mode)
(modrm src #xff 6))
(define-operator/64* :pushr (src)
(opcode-reg #x50 src)
(imm src #x6a (sint 8))
(imm src #x68 (sint 16) () :operand-size :16-bit)
(imm src #x68 (sint 32))
(modrm src #xff 6))
;;;;;;;;;;; PUSHF
(define-operator* (:16 :pushfw :32 :pushfl :64 :pushfr) ()
(opcode #x9c))
;;;;;;;;;;; RDTSC
(define-operator/none :rdtsc ()
(opcode #x0f31))
RET
(define-operator/none :ret ()
(opcode #xc3))
SAR
(define-operator/8 :sarb (count dst)
(case count
(1 (modrm dst #xd0 7))
(:cl (modrm dst #xd2 7)))
(imm-modrm count dst #xc0 7 (uint 8)))
(define-operator* (:16 :sarw :32 :sarl :64 :sarr) (count dst)
(case count
(1 (modrm dst #xd1 7))
(:cl (modrm dst #xd3 7)))
(imm-modrm count dst #xc1 7 (uint 8)))
SBB
(define-operator/8 :sbbb (subtrahend dst)
(imm subtrahend #x1c (xint 8) (dst :al))
(imm-modrm subtrahend dst #x80 3 (xint 8))
(reg-modrm dst subtrahend #x1a)
(reg-modrm subtrahend dst #x18))
(define-operator* (:16 :sbbw :32 :sbbl :64 :sbbr) (subtrahend dst)
(imm-modrm subtrahend dst #x83 3 (sint 8))
(imm subtrahend #x1d :int-16-32-64 (dst :ax-eax-rax))
(imm-modrm subtrahend dst #x81 3 :int-16-32-64)
(reg-modrm dst subtrahend #x1b)
(reg-modrm subtrahend dst #x19))
;;;;;;;;;;; SGDT
(define-operator/8 :sgdt (addr)
(modrm addr #x0f01 0))
SHL
(define-operator/8 :shlb (count dst)
(case count
(1 (modrm dst #xd0 4))
(:cl (modrm dst #xd2 4)))
(imm-modrm count dst #xc0 4 (uint 8)))
(define-operator* (:16 :shlw :32 :shll :64 :shlr) (count dst)
(case count
(1 (modrm dst #xd1 4))
(:cl (modrm dst #xd3 4)))
(imm-modrm count dst #xc1 4 (uint 8)))
;;;;;;;;;;; SHLD
(define-operator* (:16 :shldw :32 :shldl :64 :shldr) (count dst1 dst2)
(when (eq :cl count)
(reg-modrm dst1 dst2 #x0fa5))
(when (immediate-p count)
(let ((immediate (resolve-operand count)))
(when (typep immediate '(uint #x8))
(reg-modrm dst1 dst2 #x0fa4
nil
:immediate (encode-integer count '(uint 8)))))))
;;;;;;;;;;; SHR
(define-operator/8 :shrb (count dst)
(case count
(1 (modrm dst #xd0 5))
(:cl (modrm dst #xd2 5)))
(imm-modrm count dst #xc0 5 (uint 8)))
(define-operator* (:16 :shrw :32 :shrl :64 :shrr) (count dst)
(case count
(1 (modrm dst #xd1 5))
(:cl (modrm dst #xd3 5)))
(imm-modrm count dst #xc1 5 (uint 8)))
;;;;;;;;;;; SHRD
(define-operator* (:16 :shrdw :32 :shrdl :64 :shrdr) (count dst1 dst2)
(when (eq :cl count)
(reg-modrm dst1 dst2 #x0fad))
(when (immediate-p count)
(let ((immediate (resolve-operand count)))
(when (typep immediate '(uint #x8))
(reg-modrm dst1 dst2 #x0fac
nil
:immediate (encode-integer count '(uint 8)))))))
STC , STD , STI
(define-operator/none :stc ()
(opcode #xf9))
(define-operator/none :std ()
(opcode #xfd))
(define-operator/none :sti ()
(opcode #xfb))
;;;;;;;;;;; SUB
(define-operator/8 :subb (subtrahend dst)
(imm subtrahend #x2c (xint 8) (dst :al))
(imm-modrm subtrahend dst #x80 5 (xint 8))
(reg-modrm dst subtrahend #x2a)
(reg-modrm subtrahend dst #x28))
(define-operator* (:16 :subw :32 :subl :64 :subr) (subtrahend dst)
(imm-modrm subtrahend dst #x83 5 (sint 8))
(imm subtrahend #x2d :int-16-32-64 (dst :ax-eax-rax))
(imm-modrm subtrahend dst #x81 5 :int-16-32-64)
(reg-modrm dst subtrahend #x2b)
(reg-modrm subtrahend dst #x29))
;;;;;;;;;;; TEST
(define-operator/8 :testb (mask dst)
(imm mask #xa8 (xint 8) (dst :al))
(imm-modrm mask dst #xf6 0 (xint 8))
(reg-modrm mask dst #x84))
(define-operator* (:16 :testw :32 :testl :64 :testr) (mask dst)
(imm mask #xa9 :int-16-32-64 (dst :ax-eax-rax))
(imm-modrm mask dst #xf7 0 :int-16-32-64)
(reg-modrm mask dst #x85))
WBINVD ,
(define-operator/none :wbinvd ()
(opcode #x0f09))
(define-operator/none :wrmsr ()
(opcode #x0f30))
;;;;;;;;;;; XCHG
(define-operator/8 :xchgb (x y)
(reg-modrm y x #x86)
(reg-modrm x y #x86))
(define-operator* (:16 :xchgw :32 :xchgl :64 :xchgr) (x y)
(opcode-reg #x90 x (y :ax-eax-rax))
(opcode-reg #x90 y (x :ax-eax-rax))
(reg-modrm x y #x87)
(reg-modrm y x #x87))
;;;;;;;;;;; XOR
(define-operator/8 :xorb (src dst)
(imm src #x34 (xint 8) (dst :al))
(imm-modrm src dst #x80 6 (xint 8))
(reg-modrm dst src #x32)
(reg-modrm src dst #x30))
(define-operator* (:16 :xorw :32 :xorl :64 :xorr) (src dst)
(imm-modrm src dst #x83 6 (sint 8))
(imm src #x35 :int-16-32-64 (dst :ax-eax-rax))
(imm-modrm src dst #x81 6 :int-16-32-64)
(reg-modrm dst src #x33)
(reg-modrm src dst #x31))
NOP
(define-operator/none :nop ()
(opcode #x90))
| null | https://raw.githubusercontent.com/vonli/Ext2-for-movitz/81b6f8e165de3e1ea9cc7d2035b9259af83a6d26/asm-x86.lisp | lisp | ------------------------------------------------------------------
Distribution: See the accompanying file COPYING.
------------------------------------------------------------------
Pseudo-instructions
ADD
AND
CALL
CMOVcc
Move if above or equal, CF=0.
Move if below, CF=1.
Move if carry, CF=1.
Move if not above or equal, CF=1.
Move if not below, CF=0.
Move if not carry, CF=0.
Move if not equal, ZF=0.
Move if not overflow, OF=0.
Move if not sign, SF=0.
Move if overflow, OF=1.
Move if sign, SF=1
CMPXCHG
CMPXCHG8B, CMPXCHG16B
IN
INC
INT
IRET
LEAVE
LFENCE
LMSW
LODS
MOVSX
MOVZX
MUL
NEG
NOT
OR
OUT
POP
POPF
PRFETCH
PUSH
PUSHF
RDTSC
SGDT
SHLD
SHR
SHRD
SUB
TEST
XCHG
XOR | Copyright ( C ) 2007
Description : x86 assembler for 16 , 32 , and 64 - bit modes .
Author : < >
$ I d : asm - x86.lisp , v 1.37 2008/03/06 19:14:39 ffjeld Exp $
(defpackage asm-x86
(:use :common-lisp :asm)
(:export #:assemble-instruction
#:disassemble-instruction
#:*cpu-mode*
#:*position-independent-p*))
(in-package asm-x86)
(defvar *cpu-mode* :32-bit)
(defvar *instruction-encoders*
(make-hash-table :test 'eq))
(defvar *use-jcc-16-bit-p* nil
"Whether to use 16-bit JCC instructions in 32-bit mode.")
(defun prefix-lookup (prefix-name)
(cdr (or (assoc prefix-name
'((:operand-size-override . #x66)
(:address-size-override . #x67)
(:16-bit-operand . #x66)
(:16-bit-address . #x67)
(:lock . #xf0)
(:repne . #xf2)
(:repz . #xf3)
(:cs-override . #x2e)
(:ss-override . #x36)
(:ds-override . #x3e)
(:es-override . #x26)
(:fs-override . #x64)
(:gs-override . #x65)))
(error "There is no instruction prefix named ~S." prefix-name))))
(defun rex-encode (rexes &key rm)
(let ((rex (logior (if (null rexes)
0
(+ #x40 (loop for rex in rexes
sum (ecase rex
(:rex.w #b1000)
(:rex.r #b0100)
(:rex.x #b0010)
(:rex.b #b0001)))))
(if (not rm)
0
(ldb (byte 1 3) rm)))))
(unless (zerop rex)
(list rex))))
(deftype octet ()
'(unsigned-byte 8))
(deftype xint (size)
`(or (unsigned-byte ,size)
(signed-byte ,size)))
(deftype uint (size)
`(unsigned-byte ,size))
(deftype sint (size)
`(signed-byte ,size))
(defun integer-to-octets (i n)
"Return list of n octets, encoding i in signed little endian."
(loop for b from 0 below (* 8 n) by 8
collect (ldb (byte 8 b) i)))
(defun encode-values-fun (operator legacy-prefixes prefixes rexes opcode mod reg rm scale index base displacement immediate operand-size address-size)
(assert opcode)
(when (or (and (eq address-size :32-bit)
(eq *cpu-mode* :64-bit))
(and (eq address-size :16-bit)
(eq *cpu-mode* :32-bit))
(and (eq address-size :64-bit)
(eq *cpu-mode* :32-bit))
(and (eq address-size :32-bit)
(eq *cpu-mode* :16-bit)))
(pushnew :address-size-override
prefixes))
(when (or (and (eq operand-size :16-bit)
(eq *cpu-mode* :64-bit))
(and (eq operand-size :16-bit)
(eq *cpu-mode* :32-bit))
(and (eq operand-size :32-bit)
(eq *cpu-mode* :16-bit)))
(pushnew :operand-size-override
prefixes))
(let ((code (append legacy-prefixes
(mapcar #'prefix-lookup (reverse prefixes))
(rex-encode rexes :rm rm)
(when (< 16 (integer-length opcode))
(list (ldb (byte 8 16) opcode)))
(when (< 8(integer-length opcode))
(list (ldb (byte 8 8) opcode)))
(list (ldb (byte 8 0) opcode))
(when (or mod reg rm)
(assert (and mod reg rm) (mod reg rm)
"Either all or none of mod, reg, and rm must be defined. mod=~S, reg=~S, rm=~S." mod reg rm)
(check-type mod (unsigned-byte 2))
(list (logior (ash (ldb (byte 2 0) mod)
6)
(ash (ldb (byte 3 0) reg)
3)
(ash (ldb (byte 3 0) rm)
0))))
(when (or scale index base)
(assert (and scale index base) (scale index base)
"Either all or none of scale, index, and base must be defined. scale=~S, index=~S, base=~S." scale index base)
(check-type scale (unsigned-byte 2))
(check-type index (unsigned-byte 4))
(check-type base (unsigned-byte 4))
(list (logior (ash (ldb (byte 2 0) scale)
6)
(ash (ldb (byte 3 0) index)
3)
(ash (ldb (byte 3 0) base)
0))))
displacement
immediate)))
(append (compute-extra-prefixes operator *pc* (length code))
code)))
(defmacro encode (values-form)
`(multiple-value-call #'encode-values-fun operator legacy-prefixes ,values-form))
(defmacro merge-encodings (form1 form2)
`(multiple-value-bind (prefixes1 rexes1 opcode1 mod1 reg1 rm1 scale1 index1 base1 displacement1 immediate1 operand-size1 address-size1)
,form1
(multiple-value-bind (prefixes2 rexes2 opcode2 mod2 reg2 rm2 scale2 index2 base2 displacement2 immediate2 operand-size2 address-size2)
,form2
(macrolet ((getone (a b name)
`(cond
((and ,a ,b)
(error "~A doubly defined: ~S and ~S." ',name ,a ,b))
(,a)
(,b))))
(encoded-values :prefixes (append prefixes1 prefixes2)
:rex (append (if (listp rexes1)
rexes1
(list rexes1))
(if (listp rexes2)
rexes2
(list rexes2)))
:opcode (getone opcode1 opcode2 opcode)
:mod (getone mod1 mod2 mod)
:reg (getone reg1 reg2 reg)
:rm (getone rm1 rm2 rm)
:scale (getone scale1 scale2 scale)
:index (getone index1 index2 index)
:base (getone base1 base2 base)
:displacement (getone displacement1 displacement2 displacement)
:immediate (getone immediate1 immediate2 immediate)
:operand-size (getone operand-size1 operand-size2 operand-size)
:address-size (getone address-size1 address-size2 address-size))))))
(defun encoded-values (&key prefixes prefix rex opcode mod reg rm scale index base displacement immediate operand-size address-size)
(values (append (when prefix
(list prefix))
prefixes)
(if (keywordp rex)
(list rex)
rex)
opcode
mod reg rm
scale index base
displacement
immediate
operand-size
address-size))
(defun assemble-instruction (instruction)
"Assemble a single instruction to a list of octets of x86 machine code, according to *cpu-mode* etc."
(multiple-value-bind (instruction legacy-prefixes options)
(if (listp (car instruction))
(values (cdr instruction)
(remove-if #'listp (car instruction))
(remove-if #'keywordp (car instruction)))
(values instruction
nil
nil))
(destructuring-bind (operator &rest operands)
instruction
(multiple-value-bind (code failp)
(apply (or (gethash operator *instruction-encoders*)
(error "Unknown instruction operator ~S in ~S." operator instruction))
operator
(mapcar #'prefix-lookup legacy-prefixes)
operands)
(cond
(failp
(error "Unable to encode ~S." instruction))
((null options)
code)
((assoc :size options)
(assert (= (second (assoc :size options))
(length code)))
code))))))
(defmacro define-operator (operator operator-mode lambda-list &body body)
(check-type operator keyword)
(labels ((find-forms (body)
(cond
((atom body)
nil)
((member (car body) '(reg-modrm modrm opcode imm-modrm imm opcode-reg
opcode-reg-imm pc-rel moffset sreg-modrm reg-cr
far-pointer))
(list body))
(t (mapcan #'find-forms body)))))
(let ((defun-name (intern (format nil "~A-~A" 'instruction-encoder operator))))
`(progn
(defun ,defun-name (operator legacy-prefixes ,@lambda-list)
(declare (ignorable operator legacy-prefixes))
(let ((operator-mode ',operator-mode)
(default-rex nil))
(declare (ignorable operator-mode default-rex))
(macrolet ((disassembler (&body body)
(declare (ignore body)))
(assembler (&body body)
`(progn ,@body)))
(block operator
,@body
(values nil 'fail)))))
(setf (gethash ',operator *instruction-encoders*)
',defun-name)
(macrolet ((disassembler (&body body)
`(progn ,@body))
(assembler (&body body)
(declare (ignore body))))
(let ((operator ',operator)
(operator-mode ',operator-mode)
(operand-formals ',lambda-list))
(declare (ignorable operator operand-formals operator-mode))
,@(find-forms body)))
',operator))))
(defmacro define-operator/none (name lambda-list &body body)
`(define-operator ,name nil ,lambda-list ,@body))
(deftype list-of (&rest elements)
"A list with elements of specified type(s)."
(labels ((make-list-of (elements)
(if (null elements)
'null
`(cons ,(car elements)
,(make-list-of (cdr elements))))))
(make-list-of elements)))
(deftype list-of* (&rest elements)
"A list starting with elements of specified type(s)."
(labels ((make-list-of (elements)
(if (null elements)
'list
`(cons ,(car elements)
,(make-list-of (cdr elements))))))
(make-list-of elements)))
(defparameter *opcode-disassemblers-16*
(make-array 256 :initial-element nil))
(defparameter *opcode-disassemblers-32*
(make-array 256 :initial-element nil))
(defparameter *opcode-disassemblers-64*
(make-array 256 :initial-element nil))
(deftype disassembly-decoder ()
'(list-of* boolean keyword (or keyword null) symbol))
(defun (setf opcode-disassembler) (decoder opcode operator-mode)
(check-type decoder disassembly-decoder)
(labels ((set-it (table pos)
(check-type pos (integer 0 *))
(check-type table (simple-vector 256))
(let ((bit-pos (* 8 (1- (ceiling (integer-length pos) 8)))))
(if (not (plusp bit-pos))
(progn
#+(or) (unless (or (eq nil decoder)
(eq nil (svref table pos))
(equal decoder (svref table pos)))
(warn "Redefining disassembler for ~@[~(~A~) ~]opcode #x~X from ~{~S ~}to ~{~S~^ ~}."
operator-mode opcode (svref table pos) decoder))
(setf (svref table pos) decoder))
(set-it (or (svref table (ldb (byte 8 bit-pos) pos))
(setf (svref table (ldb (byte 8 bit-pos) pos))
(make-array 256 :initial-element nil)))
(ldb (byte bit-pos 0) pos))))))
(ecase operator-mode
(:16-bit
(set-it *opcode-disassemblers-16* opcode))
(:32-bit
(set-it *opcode-disassemblers-32* opcode))
(:64-bit
(set-it *opcode-disassemblers-64* opcode))
((:8-bit nil)
(set-it *opcode-disassemblers-16* opcode)
(set-it *opcode-disassemblers-32* opcode)
(set-it *opcode-disassemblers-64* opcode)))))
(defmacro pop-code (code-place &optional context)
`(progn
(unless ,code-place
(error "End of byte-stream in the middle of an instruction."))
(let ((x (pop ,code-place)))
(check-type x (unsigned-byte 8) ,(format nil "an octet (context: ~A)" context))
x)))
(defmacro code-call (form &optional (code-place (case (car form) ((funcall apply) (third form)) (t (second form)))))
"Execute form, then 'magically' update the code binding with the secondary return value from form."
`(let (tmp)
(declare (ignorable tmp))
(setf (values tmp ,code-place) ,form)))
(defmacro define-disassembler ((operator opcode &optional cpu-mode digit backup-p operand-size) lambda-list &body body)
(cond
(digit
`(loop for mod from #b00 to #b11
do (loop for r/m from #b000 to #b111
as ext-opcode = (logior (ash ,opcode 8)
(ash ,digit 3)
(ash mod 6)
r/m)
do (define-disassembler (,operator ext-opcode ,cpu-mode nil t ,operand-size) ,lambda-list ,@body))))
((symbolp lambda-list)
`(setf (opcode-disassembler ,opcode ,cpu-mode) (list ,backup-p ,operator ,(or operand-size cpu-mode) ',lambda-list ,@body)))
(t (let ((defun-name (intern (format nil "~A-~A-~X~@[-~A~]" 'disassembler operator opcode cpu-mode))))
`(progn
(defun ,defun-name ,lambda-list ,@body)
(setf (opcode-disassembler ,opcode ',cpu-mode) (list ,backup-p ,operator ',(or operand-size cpu-mode) ',defun-name))
',defun-name)))))
(defun disassemble-simple-prefix (code operator opcode operand-size address-size rex)
(declare (ignore opcode rex))
(let ((instruction (code-call (disassemble-instruction code operand-size address-size nil))))
(values (if (consp (car instruction))
(list* (list* operator (car instruction))
(cdr instruction))
(list* (list operator)
instruction))
code)))
(define-disassembler (:lock #xf0) disassemble-simple-prefix)
(define-disassembler (:repne #xf2) disassemble-simple-prefix)
(define-disassembler (:repz #xf3) disassemble-simple-prefix)
(define-disassembler (:cs-override #x2e) disassemble-simple-prefix)
(define-disassembler (:ss-override #x36) disassemble-simple-prefix)
(define-disassembler (:ds-override #x3e) disassemble-simple-prefix)
(define-disassembler (:es-override #x26) disassemble-simple-prefix)
(define-disassembler (:fs-override #x64) disassemble-simple-prefix)
(define-disassembler (:gs-override #x65) disassemble-simple-prefix)
(define-disassembler (:operand-size-override #x66 :32-bit) (code operator opcode operand-size address-size rex)
(declare (ignore operator opcode operand-size rex))
(disassemble-instruction code :16-bit address-size nil))
(define-disassembler (:address-size-override #x67 :32-bit) (code operator opcode operand-size address-size rex)
(declare (ignore operator opcode address-size rex))
(disassemble-instruction code operand-size :16-bit nil))
(define-disassembler (:operand-size-override #x66 :16-bit) (code operator opcode operand-size address-size rex)
(declare (ignore operator opcode operand-size rex))
(disassemble-instruction code :32-bit address-size nil))
(define-disassembler (:address-size-override #x67 :16-bit) (code operator opcode operand-size address-size rex)
(declare (ignore operator opcode address-size rex))
(disassemble-instruction code operand-size :32-bit nil))
(defmacro define-operator/8 (operator lambda-list &body body)
`(define-operator ,operator :8-bit ,lambda-list
(let ((default-rex nil))
(declare (ignorable default-rex))
,@body)))
(defmacro define-operator/16 (operator lambda-list &body body)
`(define-operator ,operator :16-bit ,lambda-list
(let ((default-rex nil))
(declare (ignorable default-rex))
,@body)))
(defmacro define-operator/32 (operator lambda-list &body body)
`(define-operator ,operator :32-bit ,lambda-list
(let ((default-rex nil))
(declare (ignorable default-rex))
,@body)))
(defmacro define-operator/64 (operator lambda-list &body body)
`(define-operator ,operator :64-bit ,lambda-list
(let ((default-rex '(:rex.w)))
(declare (ignorable default-rex))
,@body)))
(defmacro define-operator/64* (operator lambda-list &body body)
`(define-operator ,operator :64-bit ,lambda-list
(let ((default-rex (case *cpu-mode*
(:64-bit nil)
(t '(:rex.w)))))
(declare (ignorable default-rex))
,@body)))
(defmacro define-operator* ((&key |16| |32| |64| dispatch) args &body body)
(let ((body16 (subst '(xint 16) :int-16-32-64
(subst :dx :dx-edx-rdx
(subst :ax :ax-eax-rax body))))
(body32 (subst '(xint 32) :int-16-32-64
(subst :edx :dx-edx-rdx
(subst :eax :ax-eax-rax body))))
(body64 (subst '(sint 32) :int-16-32-64
(subst :rdx :dx-edx-rdx
(subst :rax :ax-eax-rax body)))))
`(progn
,(when |16|
`(define-operator/16 ,|16| ,args ,@body16))
,(when |32|
`(define-operator/32 ,|32| ,args ,@body32))
,(when |64|
`(define-operator/64 ,|64| ,args ,@body64))
,(when dispatch
(let ((dispatch-name (intern (format nil "~A-~A" 'instruction-dispatcher dispatch))))
`(progn
(defun ,dispatch-name (&rest args)
(declare (dynamic-extent args))
(loop for encoder in (ecase *cpu-mode*
(:32-bit ',(remove nil (list |32| |16| |64|)))
(:64-bit ',(remove nil (list |64| |32| |16|)))
(:16-bit ',(remove nil (list |16| |32| |64|))))
thereis (apply (gethash encoder *instruction-encoders*) args)
finally (return (values nil 'fail))))
(setf (gethash ',dispatch *instruction-encoders*)
',dispatch-name))))
nil)))
(defun resolve-and-encode (x type &key size)
(encode-integer (cond
((typep x type)
x)
((integerp x)
(error "Immediate value #x~X out of range for ~S." x type))
((assoc x *symtab*)
(let ((value (cdr (assoc x *symtab*))))
(assert (typep value type))
value))
(t (error "Unresolved symbol ~S (size ~S)." x size)))
type))
(defun resolve-pc-relative (operand)
(etypecase operand
(pc-relative-operand
(reduce #'+ (cdr operand)
:key #'resolve-operand))
(symbol-reference
(assert *pc* (*pc*) "Cannot encode a pc-relative operand without a value for ~S." '*pc*)
(- (resolve-operand operand)
*pc*))))
(defun encode-integer (i type)
(assert (typep i type))
(let ((bit-size (cadr type)))
(loop for b upfrom 0 below bit-size by 8
collect (ldb (byte 8 b) i))))
(defun type-octet-size (type)
(assert (member (car type)
'(sint uint xint))
(type))
(values (ceiling (cadr type) 8)))
(defun opcode-octet-size (opcode)
(loop do (setf opcode (ash opcode -8))
count t
while (plusp opcode)))
(defun parse-indirect-operand (operand)
(assert (indirect-operand-p operand))
(let (reg offsets reg2 reg-scale)
(dolist (expr operand)
(etypecase expr
(register-operand
(if reg
(setf reg2 expr)
(setf reg expr)))
((cons register-operand
(cons (member 1 2 4 8) null))
(when reg
(assert (not reg-scale))
(setf reg2 reg))
(setf reg (first expr)
reg-scale (second expr)))
(immediate-operand
(push expr offsets))
((cons (eql :+))
(dolist (term (cdr expr))
(push term offsets)))))
(when (and (eq reg2 :esp)
(or (not reg-scale)
(eql 1 reg-scale)))
(psetf reg reg2
reg2 reg))
(values reg offsets reg2 (if (not reg)
nil
(or reg-scale 1)))))
(defun register-set-by-mode (mode)
(ecase mode
(:8-bit '(:al :cl :dl :bl :ah :ch :dh :bh))
(:16-bit '(:ax :cx :dx :bx :sp :bp :si :di))
(:32-bit '(:eax :ecx :edx :ebx :esp :ebp :esi :edi))
(:64-bit '(:rax :rcx :rdx :rbx :rsp :rbp :rsi :rdi :r8 :r9 :r10 :r11 :r12 :13 :r14 :r15))
(:mm '(:mm0 :mm1 :mm2 :mm3 :mm4 :mm5 :mm6 :mm7))
(:xmm '(:xmm0 :xmm1 :xmm2 :xmm3 :xmm4 :xmm5 :xmm6 :xmm7))
(:segment '(:es :cs :ss :ds :fs :gs))))
(defun encode-reg/mem (operand mode)
(check-type mode (member nil :8-bit :16-bit :32-bit :64-bit :mm :xmm))
(if (and mode (keywordp operand))
(encoded-values :mod #b11
:rm (or (position operand (register-set-by-mode mode))
(error "Unknown ~(~D~) register ~S." mode operand)))
(multiple-value-bind (reg offsets reg2 reg-scale)
(parse-indirect-operand operand)
(check-type reg-scale (member nil 1 2 4 8))
(assert (or (not reg2)
(and reg reg2)))
(assert (or (not reg-scale)
(and reg reg-scale)))
(let ((offset (reduce #'+ offsets
:key #'resolve-operand)))
(cond
((and (not reg)
(eq mode :16-bit)
(typep offset '(xint 16)))
(encoded-values :mod #b00
:rm #b110
:address-size :16-bit
:displacement (encode-integer offset '(xint 16))))
((and (not reg)
(typep offset '(xint 32)))
(encoded-values :mod #b00
:rm #b101
:address-size :32-bit
:displacement (encode-integer offset '(xint 32))))
((and (eq reg :sp)
(not reg2)
(= 1 reg-scale))
(etypecase offset
((eql 0)
(encoded-values :mod #b00
:rm #b100
:scale 0
:index #b100
:base #b100
:address-size :16-bit))
((sint 8)
(encoded-values :mod #b01
:rm #b100
:displacement (encode-integer offset '(sint 8))
:scale 0
:index #b100
:base #b100
:address-size :16-bit))
((xint 32)
(encoded-values :mod #b10
:rm #b100
:displacement (encode-integer offset '(xint 32))
:scale 0
:index #b100
:base #b100
:address-size :16-bit))))
((and (eq reg :esp)
(= 1 reg-scale))
(let ((reg2-index (or (position reg2 '(:eax :ecx :edx :ebx nil :ebp :esi :edi))
(error "Unknown reg2 [F] ~S." reg2))))
(etypecase offset
((eql 0)
(encoded-values :mod #b00
:rm #b100
:scale 0
:index reg2-index
:base #b100
:address-size :32-bit))
((sint 8)
(encoded-values :mod #b01
:rm #b100
:displacement (encode-integer offset '(sint 8))
:scale 0
:index reg2-index
:base #b100
:address-size :32-bit))
((xint 32)
(encoded-values :mod #b10
:rm #b100
:displacement (encode-integer offset '(xint 32))
:scale 0
:index reg2-index
:base #b100
:address-size :32-bit)))))
((and (eq reg :rsp)
(not reg2)
(= 1 reg-scale))
(etypecase offset
((eql 0)
(encoded-values :mod #b00
:rm #b100
:scale 0
:index #b100
:base #b100
:address-size :64-bit))
((sint 8)
(encoded-values :mod #b01
:rm #b100
:displacement (encode-integer offset '(sint 8))
:scale 0
:index #b100
:base #b100
:address-size :64-bit))
((sint 32)
(encoded-values :mod #b10
:rm #b100
:displacement (encode-integer offset '(sint 32))
:scale 0
:index #b100
:base #b100
:address-size :64-bit))))
(t (multiple-value-bind (register-index map address-size)
(let* ((map32 '(:eax :ecx :edx :ebx :esp :ebp :esi :edi))
(index32 (position reg map32))
(map64 '(:rax :rcx :rdx :rbx :rsp :rbp :rsi :rdi :r8 :r9 :r10 :r11 :r12 :r13 :r14 :r15))
(index64 (unless index32
(position reg map64))))
(if index32
(values index32 map32 :32-bit)
(values index64 map64 :64-bit)))
(cond
((and (not reg2)
register-index
(= 1 reg-scale)
(and (zerop offset)
(not (= register-index #b101))))
(encoded-values :mod #b00
:rm register-index
:address-size address-size))
((and (not reg2)
register-index
(= 1 reg-scale)
(typep offset '(sint 8)))
(encoded-values :mod #b01
:rm register-index
:displacement (encode-integer offset '(sint 8))
:address-size address-size))
((and (not reg2)
register-index
(= 1 reg-scale)
(or (typep offset '(sint 32))
(and (eq :32-bit address-size)
(typep offset '(xint 32)))))
(encoded-values :mod #b10
:rm register-index
:displacement (encode-integer offset '(sint 32))
:address-size address-size))
((and (not reg2)
register-index
(if (eq :64-bit *cpu-mode*)
(typep offset '(sint 32))
(typep offset '(xint 32)))
(not (= #b100 register-index)))
(encoded-values :rm #b100
:mod #b00
:index register-index
:base #b101
:scale (or (position reg-scale '(1 2 4 8))
(error "Unknown register scale ~S." reg-scale))
:displacement (encode-integer offset '(xint 32))))
((and reg2
register-index
(zerop offset)
(not (= register-index #b100)))
(encoded-values :mod #b00
:rm #b100
:scale (or (position reg-scale '(1 2 4 8))
(error "Unknown register scale ~S." reg-scale))
:index register-index
:base (or (position reg2 map)
(error "unknown reg2 [A] ~S" reg2))
:address-size address-size))
((and reg2
register-index
(typep offset '(sint 8))
(not (= register-index #b100)))
(encoded-values :mod #b01
:rm #b100
:scale (position reg-scale '(1 2 4 8))
:index register-index
:base (or (position reg2 map)
(error "unknown reg2 [B] ~S" reg2))
:address-size address-size
:displacement (encode-integer offset '(sint 8))))
((and reg2
register-index
(eq :32-bit address-size)
(typep offset '(sint 8))
(not (= register-index #b100)))
(encoded-values :mod #b01
:rm #b100
:scale (position reg-scale '(1 2 4 8))
:index register-index
:base (or (position reg2 map)
(error "unknown reg2 [C] ~S." reg2))
:address-size address-size
:displacement (encode-integer offset '(sint 8))))
((and reg2
register-index
(eq :32-bit address-size)
(typep offset '(xint 32))
(not (= register-index #b100)))
(encoded-values :mod #b10
:rm #b100
:scale (position reg-scale '(1 2 4 8))
:index register-index
:base (or (position reg2 map)
(error "unknown reg2 [D] ~S." reg2))
:address-size address-size
:displacement (encode-integer offset '(xint 32))))
((and reg2
register-index
(eq :64-bit address-size)
(typep offset '(sint 32))
(not (= register-index #b100)))
(encoded-values :mod #b01
:rm #b100
:scale (position reg-scale '(1 2 4 8))
:index register-index
:base (or (position reg2 map)
(error "unknown reg2 [E] ~S" reg2))
:address-size address-size
:displacement (encode-integer offset '(sint 32))))
(t (let ((rm16 (position-if (lambda (x)
(or (and (eq (car x) reg)
(eq (cdr x) reg2))
(and (eq (car x) reg2)
(eq (cdr x) reg))))
'((:bx . :si) (:bx . :di) (:bp . :si) (:bp . :di)
(:si) (:di) (:bp) (:bx)))))
(cond
((and rm16
(zerop offset)
(not (= #b110 rm16)))
(encoded-values :mod #b00
:rm rm16
:address-size :16-bit))
((and rm16
(typep offset '(sint 8)))
(encoded-values :mod #b01
:rm rm16
:address-size :16-bit
:displacement (encode-integer offset '(sint 8))))
((and rm16
(typep offset '(xint 16)))
(encoded-values :mod #b10
:rm rm16
:address-size :16-bit
:displacement (encode-integer offset '(xint 16))))
(t (error "Huh? reg: ~S, reg2: ~S, scale: ~S, offset: ~S" reg reg2 reg-scale offset)))))))))))))
(defun operand-ordering (formals &rest arrangement)
(loop with rarrangement = (reverse arrangement)
for formal in formals
when (getf rarrangement formal)
collect it))
(defun order-operands (ordering &rest operands)
(loop for key in ordering
collect (or (getf operands key)
(error "No operand ~S in ~S." key operands))))
(defun decode-integer (code type)
"Decode an integer of specified type."
(let* ((bit-size (cadr type))
(unsigned-integer (loop for b from 0 below bit-size by 8
sum (ash (pop-code code integer) b))))
(values (if (or (not (member (car type) '(sint signed-byte)))
(not (logbitp (1- bit-size) unsigned-integer)))
unsigned-integer
(- (ldb (byte bit-size 0)
(1+ (lognot unsigned-integer)))))
code)))
(defun disassemble-instruction (code &optional override-operand-size override-address-size rex)
(labels ((lookup-decoder (table opcode)
(let* ((backup-code code)
(datum (pop-code code))
(opcode (logior (ash opcode 8)
datum))
(decoder (svref table datum)))
(typecase decoder
(vector
(lookup-decoder decoder opcode))
(disassembly-decoder
(when (car decoder)
(setf code backup-code))
(values (cdr decoder)
opcode))
(t (error "No disassembler registered for opcode #x~X." opcode))))))
(multiple-value-bind (decoder opcode)
(lookup-decoder (ecase (or override-operand-size *cpu-mode*)
(:16-bit *opcode-disassemblers-16*)
(:32-bit *opcode-disassemblers-32*)
(:64-bit *opcode-disassemblers-64*))
0)
(destructuring-bind (operator operand-size decoder-function &rest extra-args)
decoder
(values (code-call (apply decoder-function
code
operator
opcode
(or operand-size override-operand-size)
(or override-address-size *cpu-mode*)
rex
extra-args))
code)))))
(defun decode-no-operands (code operator opcode operand-size address-size rex &rest fixed-operands)
(declare (ignore opcode operand-size address-size rex))
(values (list* operator
(remove nil fixed-operands))
code))
(defun decode-reg-cr (code operator opcode operand-size address-size rex operand-ordering)
(declare (ignore opcode operand-size address-size))
(let ((modrm (pop-code code)))
(values (list* operator
(order-operands operand-ordering
:reg (nth (ldb (byte 3 0) modrm)
(register-set-by-mode (if rex :64-bit :32-bit)))
:cr (nth (ldb (byte 3 3) modrm)
'(:cr0 :cr1 :cr2 :cr3 :cr4 :cr5 :cr6 :cr7))))
code)))
(defun decode-reg-modrm (code operator opcode operand-size address-size rex operand-ordering &optional (reg-mode operand-size))
(declare (ignore opcode rex))
(values (list* operator
(order-operands operand-ordering
:reg (nth (ldb (byte 3 3) (car code))
(register-set-by-mode reg-mode))
:modrm (ecase address-size
(:32-bit
(code-call (decode-reg-modrm-32 code operand-size)))
(:16-bit
(code-call (decode-reg-modrm-16 code operand-size))))))
code))
(defun decode-modrm (code operator opcode operand-size address-size rex)
(declare (ignore opcode rex))
(values (list operator
(ecase address-size
(:32-bit
(code-call (decode-reg-modrm-32 code operand-size)))
(:16-bit
(code-call (decode-reg-modrm-16 code operand-size)))))
code))
(defun decode-imm-modrm (code operator opcode operand-size address-size rex imm-type operand-ordering &key fixed-modrm)
(declare (ignore opcode rex))
(values (list* operator
(order-operands operand-ordering
:modrm (or fixed-modrm
(when (member :modrm operand-ordering)
(ecase address-size
(:32-bit
(code-call (decode-reg-modrm-32 code operand-size)))
(:16-bit
(code-call (decode-reg-modrm-16 code operand-size))))))
:imm (code-call (decode-integer code imm-type))))
code))
(defun decode-far-pointer (code operator opcode operand-size address-size rex type)
(declare (ignore opcode operand-size address-size rex))
(let ((offset (code-call (decode-integer code type)))
(segment (code-call (decode-integer code '(uint 16)))))
(values (list operator
segment
(list offset))
code)))
(defun decode-pc-rel (code operator opcode operand-size address-size rex type)
(declare (ignore opcode operand-size address-size rex))
(values (list operator
`(:pc+ ,(code-call (decode-integer code type))))
code))
(defun decode-moffset (code operator opcode operand-size address-size rex type operand-ordering fixed-operand)
(declare (ignore opcode operand-size address-size rex))
(values (list* operator
(order-operands operand-ordering
:moffset (list (code-call (decode-integer code type)))
:fixed fixed-operand))
code))
(defun decode-opcode-reg (code operator opcode operand-size address-size rex operand-ordering extra-operand)
(declare (ignore address-size rex))
(values (list* operator
(order-operands operand-ordering
:reg (nth (ldb (byte 3 0) opcode)
(register-set-by-mode operand-size))
:extra extra-operand))
code))
(defun decode-opcode-reg-imm (code operator opcode operand-size address-size rex operand-ordering imm-type)
(declare (ignore address-size rex))
(values (list* operator
(order-operands operand-ordering
:reg (nth (ldb (byte 3 0) opcode)
(register-set-by-mode operand-size))
:imm (code-call (decode-integer code imm-type))))
code))
(defun decode-reg-modrm-16 (code operand-size)
(let* ((modrm (pop-code code mod/rm))
(mod (ldb (byte 2 6) modrm))
(reg (ldb (byte 3 3) modrm))
(r/m (ldb (byte 3 0) modrm)))
(values (if (= mod #b11)
(nth reg (register-set-by-mode operand-size))
(flet ((operands (i)
(nth i '((:bx :si) (:bx :di) (:bp :si) (:bp :di) (:si) (:di) (:bp) (:bx)))))
(ecase mod
(#b00
(case r/m
(#b110 (list (code-call (decode-integer code '(uint 16)))))
(t (operands r/m))))
(#b01
(append (operands r/m)
(list (code-call (decode-integer code '(sint 8))))))
(#b10
(append (operands r/m)
(list (code-call (decode-integer code '(uint 16)))))))))
code)))
(defun decode-reg-modrm-32 (code operand-size)
"Return a list of the REG, and the MOD/RM operands."
(let* ((modrm (pop-code code mod/rm))
(mod (ldb (byte 2 6) modrm))
(r/m (ldb (byte 3 0) modrm)))
(values (if (= mod #b11)
(nth r/m (register-set-by-mode operand-size))
(flet ((decode-sib ()
(let* ((sib (pop-code code sib))
(ss (ldb (byte 2 6) sib))
(index (ldb (byte 3 3) sib))
(base (ldb (byte 3 0) sib)))
(nconc (unless (= index #b100)
(let ((index-reg (nth index (register-set-by-mode :32-bit))))
(if (= ss #b00)
(list index-reg)
(list (list index-reg (ash 2 ss))))))
(if (/= base #b101)
(list (nth base (register-set-by-mode :32-bit)))
(ecase mod
(#b00 nil)
((#b01 #b10) (list :ebp))))))))
(ecase mod
(#b00 (case r/m
(#b100 (decode-sib))
(#b101 (code-call (decode-integer code '(uint 32))))
(t (list (nth r/m (register-set-by-mode :32-bit))))))
(#b01 (case r/m
(#b100 (nconc(decode-sib)
(list (code-call (decode-integer code '(sint 8))))))
(t (list (nth r/m (register-set-by-mode :32-bit))
(code-call (decode-integer code '(sint 8)))))))
(#b10 (case r/m
(#b100 (nconc (decode-sib)
(list (code-call (decode-integer code '(uint 32))))))
(t (list (nth r/m (register-set-by-mode :32-bit))
(code-call (decode-integer code '(uint 32))))))))))
code)))
(defmacro return-when (form)
`(let ((x ,form))
(when x (return-from operator x))))
(defmacro return-values-when (form)
`(let ((x (encode ,form)))
(when x (return-from operator x))))
(defmacro imm (imm-operand opcode imm-type &optional extra-operand &rest extras)
`(progn
(assembler
(when (and ,@(when extra-operand
(list (list* 'eql extra-operand)))
(immediate-p ,imm-operand))
(let ((immediate (resolve-operand ,imm-operand)))
(when (typep immediate ',imm-type)
(return-values-when
(encoded-values :opcode ,opcode
:immediate (encode-integer immediate ',imm-type)
:operand-size operator-mode
:rex default-rex
,@extras))))))
(disassembler
,(if extra-operand
`(define-disassembler (operator ,opcode operator-mode)
decode-imm-modrm
',imm-type
(operand-ordering operand-formals
:imm ',imm-operand
:modrm ',(first extra-operand))
:fixed-modrm ',(second extra-operand))
`(define-disassembler (operator ,opcode operator-mode)
decode-imm-modrm
',imm-type
'(:imm))))))
(defmacro imm-modrm (op-imm op-modrm opcode digit type)
`(progn
(assembler
(when (immediate-p ,op-imm)
(let ((immediate (resolve-operand ,op-imm)))
(when (typep immediate ',type)
(return-values-when
(merge-encodings (encoded-values :opcode ,opcode
:reg ,digit
:operand-size operator-mode
:rex default-rex
:immediate (encode-integer immediate ',type))
(encode-reg/mem ,op-modrm operator-mode)))))))
(disassembler
(define-disassembler (operator ,opcode operator-mode ,digit)
decode-imm-modrm
',type
(operand-ordering operand-formals
:imm ',op-imm
:modrm ',op-modrm)))))
(defun compute-extra-prefixes (operator pc size)
(let ((ff (assoc operator *instruction-compute-extra-prefix-map*)))
(when ff
(funcall (cdr ff) pc size))))
(defun encode-pc-rel (operator legacy-prefixes opcode operand type &rest extras)
(when (typep operand '(or pc-relative-operand symbol-reference))
(let* ((estimated-code-size-no-extras (+ (length legacy-prefixes)
(type-octet-size type)
(opcode-octet-size opcode)))
(estimated-extra-prefixes (compute-extra-prefixes operator *pc* estimated-code-size-no-extras))
(estimated-code-size (+ estimated-code-size-no-extras
(length estimated-extra-prefixes)))
(offset (let ((*pc* (when *pc*
(+ *pc* estimated-code-size))))
(resolve-pc-relative operand))))
(when (typep offset type)
(let ((code (let ((*instruction-compute-extra-prefix-map* nil))
(encode (apply #'encoded-values
:opcode opcode
:displacement (encode-integer offset type)
extras)))))
(if (= (length code)
estimated-code-size-no-extras)
(append estimated-extra-prefixes code)
(let* ((code-size (length code))
(extra-prefixes (compute-extra-prefixes operator *pc* code-size))
(offset (let ((*pc* (when *pc*
(+ *pc* code-size (length extra-prefixes)))))
(resolve-pc-relative operand))))
(when (typep offset type)
(let ((code (let ((*instruction-compute-extra-prefix-map* nil))
(encode (apply #'encoded-values
:opcode opcode
:displacement (encode-integer offset type)
extras)))))
(assert (= code-size (length code)))
(append extra-prefixes code))))))))))
(defmacro pc-rel (opcode operand type &optional (mode 'operator-mode) &rest extras)
`(progn
(assembler
(return-when (encode-pc-rel operator legacy-prefixes ,opcode ,operand ',type ,@extras)))
(disassembler
(define-disassembler (operator ,opcode ,mode)
decode-pc-rel
',type))))
(defmacro modrm (operand opcode digit)
`(progn
(assembler
(when (typep ,operand '(or register-operand indirect-operand))
(return-values-when
(merge-encodings (encoded-values :opcode ,opcode
:reg ,digit
:operand-size operator-mode
:rex default-rex)
(encode-reg/mem ,operand operator-mode)))))
(disassembler
(define-disassembler (operator ,opcode operator-mode ,digit) decode-modrm))))
(defun encode-reg-modrm (operator legacy-prefixes op-reg op-modrm opcode operator-mode default-rex &optional reg/mem-mode &rest extras)
(let* ((reg-map (ecase operator-mode
(:8-bit '(:al :cl :dl :bl :ah :ch :dh :bh))
(:16-bit '(:ax :cx :dx :bx :sp :bp :si :di))
(:32-bit '(:eax :ecx :edx :ebx :esp :ebp :esi :edi))
(:64-bit '(:rax :rcx :rdx :rbx :rsp :rbp :rsi :rdi :r8 :r9 :r10 :r11 :r12 :r13 :r14 :r15))
(:mm '(:mm0 :mm1 :mm2 :mm3 :mm4 :mm5 :mm6 :mm7 :mm8))
(:xmm '(:xmm0 :xmm1 :xmm2 :xmm3 :xmm4 :xmm5 :xmm6 :xmm7))))
(reg-index (position op-reg reg-map)))
(when reg-index
(encode (merge-encodings (apply #'encoded-values
:opcode opcode
:reg reg-index
:operand-size operator-mode
:rex default-rex
extras)
(encode-reg/mem op-modrm (or reg/mem-mode operator-mode)))))))
(defmacro reg-modrm (op-reg op-modrm opcode &optional reg/mem-mode &rest extras)
`(progn
(assembler
(return-when (encode-reg-modrm operator legacy-prefixes ,op-reg ,op-modrm ,opcode
operator-mode default-rex ,reg/mem-mode ,@extras)))
(disassembler
(define-disassembler (operator ,opcode operator-mode)
decode-reg-modrm
(operand-ordering operand-formals
:reg ',op-reg
:modrm ',op-modrm)))))
(defun encode-reg-cr (operator legacy-prefixes op-reg op-cr opcode operator-mode default-rex &rest extras)
(let* ((reg-map (ecase operator-mode
(:32-bit '(:eax :ecx :edx :ebx :esp :ebp :esi :edi))
(:64-bit '(:rax :rcx :rdx :rbx :rsp :rbp :rsi :rdi :r8 :r9 :r10 :r11 :r12 :r13 :r14 :r15))))
(reg-index (position op-reg reg-map))
(cr-index (position op-cr '(:cr0 :cr1 :cr2 :cr3 :cr4 :cr5 :cr6 :cr7))))
(when (and reg-index
cr-index)
(encode (apply #'encoded-values
:opcode opcode
:mod #b11
:rm reg-index
:reg cr-index
:operand-size (if (not (eq *cpu-mode* :64-bit))
nil
operator-mode)
:rex default-rex
extras)))))
(defmacro reg-cr (op-reg op-cr opcode &rest extras)
`(progn
(assembler
(return-when (encode-reg-cr operator legacy-prefixes ,op-reg ,op-cr ,opcode operator-mode default-rex ,@extras)))
(disassembler
(define-disassembler (operator ,opcode nil nil nil :32-bit)
decode-reg-cr
(operand-ordering operand-formals
:reg ',op-reg
:cr ',op-cr)))))
(defmacro sreg-modrm (op-sreg op-modrm opcode &rest extras)
`(progn
(assembler
(let* ((reg-map '(:es :cs :ss :ds :fs :gs))
(reg-index (position ,op-sreg reg-map)))
(when reg-index
(return-values-when
(merge-encodings (encoded-values :opcode ,opcode
:reg reg-index
:rex default-rex
,@extras)
(encode-reg/mem ,op-modrm operator-mode))))))
(disassembler
(define-disassembler (operator ,opcode nil nil nil :16-bit)
decode-reg-modrm
(operand-ordering operand-formals
:reg ',op-sreg
:modrm ',op-modrm)
:segment))))
(defmacro moffset (opcode op-offset type fixed-operand)
`(progn
(assembler
(when (and ,@(when fixed-operand
`((eql ,@fixed-operand)))
(indirect-operand-p ,op-offset))
(multiple-value-bind (reg offsets reg2)
(parse-indirect-operand ,op-offset)
(when (and (not reg)
(not reg2))
(return-values-when
(encoded-values :opcode ,opcode
:displacement (encode-integer (reduce #'+ offsets
:key #'resolve-operand)
',type)))))))
(disassembler
(define-disassembler (operator ,opcode operator-mode)
decode-moffset
',type
(operand-ordering operand-formals
:moffset ',op-offset
:fixed ',(first fixed-operand))
',(second fixed-operand)))))
(defmacro opcode (opcode &optional fixed-operand fixed-operand2 &rest extras)
`(progn
(assembler
(when (and ,@(when fixed-operand
`((eql ,@fixed-operand)))
,@(when fixed-operand2
`((eql ,@fixed-operand2))))
(return-values-when
(encoded-values :opcode ,opcode
,@extras
:operand-size operator-mode))))
(disassembler
(define-disassembler (operator ,opcode)
decode-no-operands
,(second fixed-operand)
,(second fixed-operand2)))))
(defmacro opcode* (opcode &rest extras)
`(return-values-when
(encoded-values :opcode ,opcode
,@extras)))
(defun encode-opcode-reg (operator legacy-prefixes opcode op-reg operator-mode default-rex)
(let* ((reg-map (ecase operator-mode
(:8-bit '(:al :cl :dl :bl :ah :ch :dh :bh))
(:16-bit '(:ax :cx :dx :bx :sp :bp :si :di))
(:32-bit '(:eax :ecx :edx :ebx :esp :ebp :esi :edi))
(:64-bit '(:rax :rcx :rdx :rbx :rsp :rbp :rsi :rdi :r8 :r9 :r10 :r11 :r12 :r13 :r14 :r15))
(:mm '(:mm0 :mm1 :mm2 :mm3 :mm4 :mm5 :mm6 :mm7 :mm8))
(:xmm '(:xmm0 :xmm1 :xmm2 :xmm3 :xmm4 :xmm5 :xmm6 :xmm7))))
(reg-index (position op-reg reg-map)))
(when reg-index
(encode (encoded-values :opcode (+ opcode (ldb (byte 3 0) reg-index))
:operand-size operator-mode
:rex (cond
((>= reg-index 8)
(assert (eq :64-bit operator-mode))
'(:rex.w :rex.r))
(t default-rex)))))))
(defmacro opcode-reg (opcode op-reg &optional extra-operand)
`(progn
(assembler
(when (and ,@(when extra-operand
`((eql ,@extra-operand))))
(return-when
(encode-opcode-reg operator legacy-prefixes ,opcode ,op-reg operator-mode default-rex))))
(disassembler
(loop for reg from #b000 to #b111
do ,(if (not extra-operand)
`(define-disassembler (operator (logior ,opcode reg) operator-mode)
decode-opcode-reg
'(:reg)
nil)
`(define-disassembler (operator (logior ,opcode reg) operator-mode)
decode-opcode-reg
(operand-ordering operand-formals
:reg ',op-reg
:extra ',(first extra-operand))
',(second extra-operand)))))))
(defun encode-opcode-reg-imm (operator legacy-prefixes opcode op-reg op-imm type operator-mode default-rex)
(when (immediate-p op-imm)
(let ((immediate (resolve-operand op-imm)))
(when (typep immediate type)
(let* ((reg-map (ecase operator-mode
(:8-bit '(:al :cl :dl :bl :ah :ch :dh :bh))
(:16-bit '(:ax :cx :dx :bx :sp :bp :si :di))
(:32-bit '(:eax :ecx :edx :ebx :esp :ebp :esi :edi))
(:64-bit '(:rax :rcx :rdx :rbx :rsp :rbp :rsi :rdi :r8 :r9 :r10 :r11 :r12 :r13 :r14 :r15))
(:mm '(:mm0 :mm1 :mm2 :mm3 :mm4 :mm5 :mm6 :mm7 :mm8))
(:xmm '(:xmm0 :xmm1 :xmm2 :xmm3 :xmm4 :xmm5 :xmm6 :xmm7))))
(reg-index (position op-reg reg-map)))
(when reg-index
(encode (encoded-values :opcode (+ opcode (ldb (byte 3 0) reg-index))
:operand-size operator-mode
:immediate (encode-integer immediate type)
:rex (cond
((>= reg-index 8)
(assert (eq :64-bit operator-mode))
'(:rex.w :rex.r))
(t default-rex))))))))))
(defmacro opcode-reg-imm (opcode op-reg op-imm type)
`(progn
(assembler
(return-when
(encode-opcode-reg-imm operator legacy-prefixes ,opcode ,op-reg ,op-imm ',type operator-mode default-rex)))
(disassembler
(loop for reg from #b000 to #b111
do (define-disassembler (operator (logior ,opcode reg) operator-mode)
decode-opcode-reg-imm
(operand-ordering operand-formals
:reg ',op-reg
:imm ',op-imm)
',type)))))
(defmacro far-pointer (opcode segment offset offset-type &optional mode &rest extra)
`(progn
(assembler
(when (and (immediate-p ,segment)
FIXME : should be immediate - p , change in bootblock.lisp .
(let ((segment (resolve-operand ,segment))
(offset (resolve-operand (car ,offset))))
(when (and (typep segment '(uint 16))
(typep offset ',offset-type))
(return-when (encode (encoded-values :opcode ,opcode
:immediate (append (encode-integer offset ',offset-type)
(encode-integer segment '(uint 16)))
,@extra)))))))
(disassembler
(define-disassembler (operator ,opcode ,(or mode 'operator-mode))
decode-far-pointer
',offset-type))))
(define-operator/none :% (op &rest form)
(case op
(:bytes
(return-from operator
(destructuring-bind (byte-size &rest data)
form
(loop for datum in data
append (loop for b from 0 below byte-size by 8
collect (ldb (byte 8 b)
(resolve-operand datum)))))))
(:funcall
(return-from operator
(destructuring-bind (function &rest args)
form
(apply function (mapcar #'resolve-operand args)))))
(:fun
(return-from operator
(destructuring-bind (function &rest args)
(car form)
(loop for cbyte in (apply function (mapcar #'resolve-operand args))
append (loop for octet from 0 below (imagpart cbyte)
collect (ldb (byte 8 (* 8 octet))
(realpart cbyte)))))))
(:format
(return-from operator
(destructuring-bind (byte-size format-control &rest format-args)
form
(ecase byte-size
(8 (let ((data (map 'list #'char-code
(apply #'format nil format-control
(mapcar #'resolve-operand format-args)))))
(cons (length data)
data)))))))
(:align
(return-from operator
(destructuring-bind (alignment)
form
(let* ((offset (mod *pc* alignment)))
(when (plusp offset)
(make-list (- alignment offset)
:initial-element 0))))))))
ADC
(define-operator/8 :adcb (src dst)
(imm src #x14 (xint 8) (dst :al))
(imm-modrm src dst #x80 2 (xint 8))
(reg-modrm dst src #x12)
(reg-modrm src dst #x10))
(define-operator* (:16 :adcw :32 :adcl :64 :adcr) (src dst)
(imm-modrm src dst #x83 2 (sint 8))
(imm src #x15 :int-16-32-64 (dst :ax-eax-rax))
(imm-modrm src dst #x81 2 :int-16-32-64)
(reg-modrm dst src #x13)
(reg-modrm src dst #x11))
(define-operator/8 :addb (src dst)
(imm src #x04 (xint 8) (dst :al))
(imm-modrm src dst #x80 0 (xint 8))
(reg-modrm dst src #x02)
(reg-modrm src dst #x00))
(define-operator* (:16 :addw :32 :addl :64 :addr) (src dst)
(imm-modrm src dst #x83 0 (sint 8))
(imm src #x05 :int-16-32-64 (dst :ax-eax-rax))
(imm-modrm src dst #x81 0 :int-16-32-64)
(reg-modrm dst src #x03)
(reg-modrm src dst #x01))
(define-operator/8 :andb (mask dst)
(imm mask #x24 (xint 8) (dst :al))
(imm-modrm mask dst #x80 4 (xint 8))
(reg-modrm dst mask #x22)
(reg-modrm mask dst #x20))
(define-operator* (:16 :andw :32 :andl :64 :andr) (mask dst)
(imm-modrm mask dst #x83 4 (sint 8))
(imm mask #x25 :int-16-32-64 (dst :ax-eax-rax))
(imm-modrm mask dst #x81 4 :int-16-32-64)
(reg-modrm dst mask #x23)
(reg-modrm mask dst #x21))
BOUND , BSF , BSR , BSWAP
(define-operator* (:16 :boundw :32 :bound) (bounds reg)
(reg-modrm reg bounds #x62))
(define-operator* (:16 :bsfw :32 :bsfl :64 :bsfr) (src dst)
(reg-modrm dst src #x0fbc))
(define-operator* (:16 :bsrw :32 :bsrl :64 :bsrr) (src dst)
(reg-modrm dst src #x0fbd))
(define-operator* (:32 :bswap :64 :bswapr) (dst)
(opcode-reg #x0fc8 dst))
BT , BTC , BTR , BTS
(define-operator* (:16 :btw :32 :btl :64 :btr) (bit src)
(imm-modrm bit src #x0fba 4 (uint 8))
(reg-modrm bit src #x0fa3))
(define-operator* (:16 :btcw :32 :btcl :64 :btcr) (bit src)
(imm-modrm bit src #x0fba 7 (uint 8))
(reg-modrm bit src #x0fbb))
(define-operator* (:16 :btrw :32 :btrl :64 :btrr) (bit src)
(imm-modrm bit src #x0fba 6 (uint 8))
(reg-modrm bit src #x0fb3))
(define-operator* (:16 :btsw :32 :btsl :64 :btsr) (bit src)
(imm-modrm bit src #x0fba 5 (uint 8))
(reg-modrm bit src #x0fab))
(define-operator/16 :callw (dest)
(pc-rel #xe8 dest (sint 16))
(modrm dest #xff 2))
(define-operator/32 :call (dest)
(pc-rel #xe8 dest (sint 32))
(modrm dest #xff 2))
(define-operator/none :call-segment (dest)
(modrm dest #xff 3))
CLC , CLD , CLI , CLTS , CMC
(define-operator/none :clc () (opcode #xf8))
(define-operator/none :cld () (opcode #xfc))
(define-operator/none :cli () (opcode #xfa))
(define-operator/none :clts () (opcode #x0f06))
(define-operator/none :cmc () (opcode #xf5))
(define-operator* (:16 :cmovaw :32 :cmova :64 :cmovar) (src dst)
Move if above , and ZF=0 .
(define-operator* (:16 :cmovaew :32 :cmovae :64 :cmovaer) (src dst)
(define-operator* (:16 :cmovbw :32 :cmovb :64 :cmovbr) (src dst)
(define-operator* (:16 :cmovbew :32 :cmovbe :64 :cmovber) (src dst)
Move if below or equal , CF=1 or ZF=1 .
(define-operator* (:16 :cmovcw :32 :cmovc :64 :cmovcr) (src dst)
(define-operator* (:16 :cmovew :32 :cmove :64 :cmover) (src dst)
Move if equal , ZF=1 .
(define-operator* (:16 :cmovgw :32 :cmovg :64 :cmovgr) (src dst)
Move if greater , ZF=0 and SF = OF .
(define-operator* (:16 :cmovgew :32 :cmovge :64 :cmovger) (src dst)
Move if greater or equal , SF = OF .
(define-operator* (:16 :cmovlw :32 :cmovl :64 :cmovlr) (src dst)
(reg-modrm dst src #x0f4c))
(define-operator* (:16 :cmovlew :32 :cmovle :64 :cmovler) (src dst)
Move if less or equal , ZF=1 or SF/=OF .
(define-operator* (:16 :cmovnaw :32 :cmovna :64 :cmovnar) (src dst)
Move if not above , CF=1 or ZF=1 .
(define-operator* (:16 :cmovnaew :32 :cmovnae :64 :cmovnaer) (src dst)
(define-operator* (:16 :cmovnbw :32 :cmovnb :64 :cmovnbr) (src dst)
(define-operator* (:16 :cmovnbew :32 :cmovnbe :64 :cmovnber) (src dst)
Move if not below or equal , and ZF=0 .
(define-operator* (:16 :cmovncw :32 :cmovnc :64 :cmovncr) (src dst)
(define-operator* (:16 :cmovnew :32 :cmovne :64 :cmovner) (src dst)
(define-operator* (:16 :cmovngew :32 :cmovnge :64 :cmovnger) (src dst)
Move if not greater or equal , SF/=OF .
(define-operator* (:16 :cmovnlw :32 :cmovnl :64 :cmovnlr) (src dst)
Move if not less SF = OF .
(define-operator* (:16 :cmovnlew :32 :cmovnle :64 :cmovnler) (src dst)
Move if not less or equal , ZF=0 and SF = OF .
(define-operator* (:16 :cmovnow :32 :cmovno :64 :cmovnor) (src dst)
(define-operator* (:16 :cmovnpw :32 :cmovnp :64 :cmovnpr) (src dst)
Move if not parity , .
(define-operator* (:16 :cmovnsw :32 :cmovns :64 :cmovnsr) (src dst)
(define-operator* (:16 :cmovnzw :32 :cmovnz :64 :cmovnzr) (src dst)
Move if not zero , ZF=0 .
(define-operator* (:16 :cmovow :32 :cmovo :64 :cmovor) (src dst)
(define-operator* (:16 :cmovpw :32 :cmovp :64 :cmovpr) (src dst)
Move if parity , PF=1 .
(define-operator* (:16 :cmovsw :32 :cmovs :64 :cmovsr) (src dst)
(define-operator* (:16 :cmovzw :32 :cmovz :64 :cmovzr) (src dst)
Move if zero , ZF=1
CMP
(define-operator/8 :cmpb (src dst)
(imm src #x3c (xint 8) (dst :al))
(imm-modrm src dst #x80 7 (xint 8))
(reg-modrm dst src #x3a)
(reg-modrm src dst #x38))
(define-operator* (:16 :cmpw :32 :cmpl :64 :cmpr) (src dst)
(imm-modrm src dst #x83 7 (sint 8))
(imm src #x3d :int-16-32-64 (dst :ax-eax-rax))
(imm-modrm src dst #x81 7 :int-16-32-64)
(reg-modrm dst src #x3b)
(reg-modrm src dst #x39))
(define-operator/8 :cmpxchgb (cmp-reg cmp-modrm al-dst)
(when (eq al-dst :al)
(reg-modrm cmp-reg cmp-modrm #x0fb0)))
(define-operator* (:16 :cmpxchgw :32 :cmpxchgl :64 :cmpxchgr) (cmp-reg cmp-modrm al-dst)
(when (eq al-dst :ax-eax-rax)
(reg-modrm cmp-reg cmp-modrm #x0fb1)))
(define-operator/32 :cmpxchg8b (address)
(modrm address #x0fc7 1))
(define-operator/64 :cmpxchg16b (address)
(modrm address #x0fc7 1))
(define-operator/none :cpuid ()
(opcode* #x0fa2))
CWD , CDQ
(define-operator/16 :cwd (reg1 reg2)
(when (and (eq reg1 :ax)
(eq reg2 :dx))
(opcode #x99)))
(define-operator/32 :cdq (reg1 reg2)
(when (and (eq reg1 :eax)
(eq reg2 :edx))
(opcode #x99)))
(define-operator/64 :cqo (reg1 reg2)
(when (and (eq reg1 :rax)
(eq reg2 :rdx))
(opcode #x99)))
DEC
(define-operator/8 :decb (dst)
(modrm dst #xfe 1))
(define-operator* (:16 :decw :32 :decl) (dst)
(unless (eq *cpu-mode* :64-bit)
(opcode-reg #x48 dst))
(modrm dst #xff 1))
(define-operator* (:64 :decr) (dst)
(modrm dst #xff 1))
DIV
(define-operator/8 :divb (divisor dividend)
(when (eq dividend :ax)
(modrm divisor #xf6 6)))
(define-operator* (:16 :divw :32 :divl :64 :divr) (divisor dividend1 dividend2)
(when (and (eq dividend1 :ax-eax-rax)
(eq dividend2 :dx-edx-rdx))
(modrm divisor #xf7 6)))
HLT
(define-operator/none :halt ()
(opcode #xf4))
IDIV
(define-operator/8 :idivb (divisor dividend1 dividend2)
(when (and (eq dividend1 :al)
(eq dividend2 :ah))
(modrm divisor #xf6 7)))
(define-operator* (:16 :idivw :32 :idivl :64 :idivr) (divisor dividend1 dividend2)
(when (and (eq dividend1 :ax-eax-rax)
(eq dividend2 :dx-edx-rdx))
(modrm divisor #xf7 7)))
IMUL
(define-operator/32 :imull (factor product1 &optional product2)
(when (not product2)
(reg-modrm product1 factor #x0faf))
(when (and (eq product1 :eax)
(eq product2 :edx))
(modrm factor #xf7 5))
(typecase factor
((sint 8)
(reg-modrm product1 product2 #x6b
nil
:displacement (encode-integer factor '(sint 8))))
((sint 32)
(reg-modrm product1 product2 #x69
nil
:displacement (encode-integer factor '(sint 32))))))
(define-operator/8 :inb (port dst)
(opcode #xec (port :dx) (dst :al))
(imm port #xe4 (uint 8) (dst :al)))
(define-operator/16 :inw (port dst)
(opcode #xed (port :dx) (dst :ax))
(imm port #xe5 (uint 8) (dst :ax)))
(define-operator/32 :inl (port dst)
(opcode #xed (port :dx) (dst :eax))
(imm port #xe5 (uint 8) (dst :eax)))
(define-operator/8 :incb (dst)
(modrm dst #xfe 0))
(define-operator* (:16 :incw :32 :incl) (dst)
(unless (eq *cpu-mode* :64-bit)
(opcode-reg #x40 dst))
(modrm dst #xff 0))
(define-operator* (:64 :incr) (dst)
(modrm dst #xff 0))
(define-operator/none :break ()
(opcode #xcc))
(define-operator/none :int (vector)
(imm vector #xcd (uint 8)))
(define-operator/none :into ()
(opcode #xce))
INVLPG
(define-operator/none :invlpg (address)
(modrm address #x0f01 7))
(define-operator* (:16 :iret :32 :iretd :64 :iretq) ()
(opcode #xcf () ()
:rex default-rex))
(defmacro define-jcc (name opcode1 &optional (opcode2 (+ #x0f10 opcode1)))
`(define-operator/none ,name (dst)
(pc-rel ,opcode1 dst (sint 8))
(when (or (and (eq *cpu-mode* :32-bit)
*use-jcc-16-bit-p*)
(eq *cpu-mode* :16-bit))
(pc-rel ,opcode2 dst (sint 16) nil
:operand-size :16-bit))
(pc-rel ,opcode2 dst (sint 32) nil
:operand-size (case *cpu-mode*
((:16-bit :32-bit)
:32-bit)))))
(define-jcc :ja #x77)
(define-jcc :jae #x73)
(define-jcc :jb #x72)
(define-jcc :jbe #x76)
(define-jcc :jc #x72)
(define-jcc :jecx #xe3)
(define-jcc :je #x74)
(define-jcc :jg #x7f)
(define-jcc :jge #x7d)
(define-jcc :jl #x7c)
(define-jcc :jle #x7e)
(define-jcc :jna #x76)
(define-jcc :jnae #x72)
(define-jcc :jnb #x73)
(define-jcc :jnbe #x77)
(define-jcc :jnc #x73)
(define-jcc :jne #x75)
(define-jcc :jng #x7e)
(define-jcc :jnge #x7c)
(define-jcc :jnl #x7d)
(define-jcc :jnle #x7f)
(define-jcc :jno #x71)
(define-jcc :jnp #x7b)
(define-jcc :jns #x79)
(define-jcc :jnz #x75)
(define-jcc :jo #x70)
(define-jcc :jp #x7a)
(define-jcc :jpe #x7a)
(define-jcc :jpo #x7b)
(define-jcc :js #x78)
(define-jcc :jz #x74)
(define-operator* (:16 :jcxz :32 :jecxz :64 :jrcxz) (dst)
(pc-rel #xe3 dst (sint 8) nil
:operand-size operator-mode
:rex default-rex))
JMP
(define-operator/none :jmp (seg-dst &optional dst)
(cond
(dst
(when (eq *cpu-mode* :16-bit)
(far-pointer #xea seg-dst dst (uint 16) :16-bit))
(when (eq *cpu-mode* :32-bit)
(far-pointer #xea seg-dst dst (xint 32) :32-bit)))
(t (let ((dst seg-dst))
(pc-rel #xeb dst (sint 8))
(when (or (and (eq *cpu-mode* :32-bit)
*use-jcc-16-bit-p*)
(eq *cpu-mode* :16-bit))
(pc-rel #xe9 dst (sint 16) :16-bit))
(pc-rel #xe9 dst (sint 32) :32-bit)
(when (or (not *position-independent-p*)
(indirect-operand-p dst))
(let ((operator-mode :32-bit))
(modrm dst #xff 4)))))))
(define-operator* (:16 :jmpw-segment :32 :jmp-segment :64 :jmpr-segment) (addr)
(modrm addr #xff 5))
LAHF , LAR
(define-operator/none :lahf ()
(case *cpu-mode*
((:16-bit :32-bit)
(opcode #x9f))))
(define-operator* (:16 :larw :32 :larl :64 :larr) (src dst)
(reg-modrm dst src #x0f02))
LEA
(define-operator* (:16 :leaw :32 :leal :64 :lear) (addr dst)
(reg-modrm dst addr #x8d))
(define-operator/none :leave ()
(opcode #xc9))
(define-operator/none :lfence ()
(opcode #x0faee8))
LGDT ,
(define-operator* (:16 :lgdtw :32 :lgdtl :64 :lgdtr :dispatch :lgdt) (addr)
(when (eq operator-mode *cpu-mode*)
(modrm addr #x0f01 2)))
(define-operator* (:16 :lidtw :32 :lidt :64 :lidtr) (addr)
(modrm addr #x0f01 3))
(define-operator/16 :lmsw (src)
(modrm src #x0f01 6))
(define-operator/8 :lodsb ()
(opcode #xac))
(define-operator* (:16 :lodsw :32 :lodsl :64 :lodsr) ()
(opcode #xad))
LOOP , LOOPE , LOOPNE
(define-operator/none :loop (dst)
(pc-rel #xe2 dst (sint 8)))
(define-operator/none :loope (dst)
(pc-rel #xe1 dst (sint 8)))
(define-operator/none :loopne (dst)
(pc-rel #xe0 dst (sint 8)))
MOV
(define-operator/8 :movb (src dst)
(moffset #xa2 dst (uint 8) (src :al))
(moffset #xa0 src (uint 8) (dst :al))
(opcode-reg-imm #xb0 dst src (xint 8))
(imm-modrm src dst #xc6 0 (xint 8))
(reg-modrm dst src #x8a)
(reg-modrm src dst #x88))
(define-operator/16 :movw (src dst)
(moffset #xa3 dst (uint 16) (src :ax))
(moffset #xa0 src (uint 16) (dst :ax))
(opcode-reg-imm #xb8 dst src (xint 16))
(imm-modrm src dst #xc7 0 (xint 16))
(sreg-modrm src dst #x8c)
(sreg-modrm dst src #x8e)
(reg-modrm dst src #x8b)
(reg-modrm src dst #x89))
(define-operator/32 :movl (src dst)
(moffset #xa3 dst (uint 32) (src :eax))
(moffset #xa0 src (uint 32) (dst :eax))
(opcode-reg-imm #xb8 dst src (xint 32))
(imm-modrm src dst #xc7 0 (xint 32))
(reg-modrm dst src #x8b)
(reg-modrm src dst #x89))
MOVCR
(define-operator* (:32 :movcrl :dispatch :movcr) (src dst)
(reg-cr src dst #x0f22)
(reg-cr dst src #x0f20))
MOVS
(define-operator/8 :movsb ()
(opcode #xa4))
(define-operator/16 :movsw ()
(opcode #xa5))
(define-operator/32 :movsl ()
(opcode #xa5))
(define-operator* (:32 :movsxb) (src dst)
(reg-modrm dst src #x0fbe))
(define-operator* (:32 :movsxw) (src dst)
(reg-modrm dst src #x0fbf))
(define-operator* (:16 :movzxbw :32 :movzxbl :dispatch :movzxb) (src dst)
(reg-modrm dst src #x0fb6 :8-bit))
(define-operator* (:32 :movzxw) (src dst)
(reg-modrm dst src #x0fb7))
(define-operator/32 :mull (factor product1 &optional product2)
(when (and (eq product1 :eax)
(eq product2 :edx))
(modrm factor #xf7 4)))
(define-operator/8 :negb (dst)
(modrm dst #xf6 3))
(define-operator* (:16 :negw :32 :negl :64 :negr) (dst)
(modrm dst #xf7 3))
(define-operator/8 :notb (dst)
(modrm dst #xf6 2))
(define-operator* (:16 :notw :32 :notl :64 :notr) (dst)
(modrm dst #xf7 2))
(define-operator/8 :orb (src dst)
(imm src #x0c (xint 8) (dst :al))
(imm-modrm src dst #x80 1 (xint 8))
(reg-modrm dst src #x0a)
(reg-modrm src dst #x08))
(define-operator* (:16 :orw :32 :orl :64 :orr) (src dst)
(imm-modrm src dst #x83 1 (sint 8))
(imm src #x0d :int-16-32-64 (dst :ax-eax-rax))
(imm-modrm src dst #x81 1 :int-16-32-64)
(reg-modrm dst src #x0b)
(reg-modrm src dst #x09))
(define-operator/8 :outb (src port)
(opcode #xee (src :al) (port :dx))
(imm port #xe6 (uint 8) (src :al)))
(define-operator/16 :outw (src port)
(opcode #xef (src :ax) (port :dx))
(imm port #xe7 (uint 8) (src :ax)))
(define-operator/32 :outl (src port)
(opcode #xef (src :eax) (port :dx))
(imm port #xe7 (uint 8) (src :eax)))
(define-operator* (:16 :popw :32 :popl) (dst)
(opcode #x1f (dst :ds))
(opcode #x07 (dst :es))
(opcode #x17 (dst :ss))
(opcode #x0fa1 (dst :fs))
(opcode #x0fa9 (dst :gs))
(opcode-reg #x58 dst)
(modrm dst #x8f 0))
(define-operator/64* :popr (dst)
(opcode-reg #x58 dst)
(modrm dst #x8f 0))
(define-operator* (:16 :popfw :32 :popfl :64 :popfr) ()
(opcode #x9d))
(define-operator/none :prefetch-nta (m8)
(modrm m8 #x0f18 0))
(define-operator/none :prefetch-t0 (m8)
(modrm m8 #x0f18 1))
(define-operator/none :prefetch-t1 (m8)
(modrm m8 #x0f18 2))
(define-operator/none :prefetch-t2 (m8)
(modrm m8 #x0f18 3))
(define-operator* (:16 :pushw :32 :pushl) (src)
(opcode #x0e (src :cs))
(opcode #x16 (src :ss))
(opcode #x1e (src :ds))
(opcode #x06 (src :es))
(opcode #x0fa0 (src :fs))
(opcode #x0fa8 (src :gs))
(opcode-reg #x50 src)
(imm src #x6a (sint 8))
(imm src #x68 :int-16-32-64 () :operand-size operator-mode)
(modrm src #xff 6))
(define-operator/64* :pushr (src)
(opcode-reg #x50 src)
(imm src #x6a (sint 8))
(imm src #x68 (sint 16) () :operand-size :16-bit)
(imm src #x68 (sint 32))
(modrm src #xff 6))
(define-operator* (:16 :pushfw :32 :pushfl :64 :pushfr) ()
(opcode #x9c))
(define-operator/none :rdtsc ()
(opcode #x0f31))
RET
(define-operator/none :ret ()
(opcode #xc3))
SAR
(define-operator/8 :sarb (count dst)
(case count
(1 (modrm dst #xd0 7))
(:cl (modrm dst #xd2 7)))
(imm-modrm count dst #xc0 7 (uint 8)))
(define-operator* (:16 :sarw :32 :sarl :64 :sarr) (count dst)
(case count
(1 (modrm dst #xd1 7))
(:cl (modrm dst #xd3 7)))
(imm-modrm count dst #xc1 7 (uint 8)))
SBB
(define-operator/8 :sbbb (subtrahend dst)
(imm subtrahend #x1c (xint 8) (dst :al))
(imm-modrm subtrahend dst #x80 3 (xint 8))
(reg-modrm dst subtrahend #x1a)
(reg-modrm subtrahend dst #x18))
(define-operator* (:16 :sbbw :32 :sbbl :64 :sbbr) (subtrahend dst)
(imm-modrm subtrahend dst #x83 3 (sint 8))
(imm subtrahend #x1d :int-16-32-64 (dst :ax-eax-rax))
(imm-modrm subtrahend dst #x81 3 :int-16-32-64)
(reg-modrm dst subtrahend #x1b)
(reg-modrm subtrahend dst #x19))
(define-operator/8 :sgdt (addr)
(modrm addr #x0f01 0))
SHL
(define-operator/8 :shlb (count dst)
(case count
(1 (modrm dst #xd0 4))
(:cl (modrm dst #xd2 4)))
(imm-modrm count dst #xc0 4 (uint 8)))
(define-operator* (:16 :shlw :32 :shll :64 :shlr) (count dst)
(case count
(1 (modrm dst #xd1 4))
(:cl (modrm dst #xd3 4)))
(imm-modrm count dst #xc1 4 (uint 8)))
(define-operator* (:16 :shldw :32 :shldl :64 :shldr) (count dst1 dst2)
(when (eq :cl count)
(reg-modrm dst1 dst2 #x0fa5))
(when (immediate-p count)
(let ((immediate (resolve-operand count)))
(when (typep immediate '(uint #x8))
(reg-modrm dst1 dst2 #x0fa4
nil
:immediate (encode-integer count '(uint 8)))))))
(define-operator/8 :shrb (count dst)
(case count
(1 (modrm dst #xd0 5))
(:cl (modrm dst #xd2 5)))
(imm-modrm count dst #xc0 5 (uint 8)))
(define-operator* (:16 :shrw :32 :shrl :64 :shrr) (count dst)
(case count
(1 (modrm dst #xd1 5))
(:cl (modrm dst #xd3 5)))
(imm-modrm count dst #xc1 5 (uint 8)))
(define-operator* (:16 :shrdw :32 :shrdl :64 :shrdr) (count dst1 dst2)
(when (eq :cl count)
(reg-modrm dst1 dst2 #x0fad))
(when (immediate-p count)
(let ((immediate (resolve-operand count)))
(when (typep immediate '(uint #x8))
(reg-modrm dst1 dst2 #x0fac
nil
:immediate (encode-integer count '(uint 8)))))))
STC , STD , STI
(define-operator/none :stc ()
(opcode #xf9))
(define-operator/none :std ()
(opcode #xfd))
(define-operator/none :sti ()
(opcode #xfb))
(define-operator/8 :subb (subtrahend dst)
(imm subtrahend #x2c (xint 8) (dst :al))
(imm-modrm subtrahend dst #x80 5 (xint 8))
(reg-modrm dst subtrahend #x2a)
(reg-modrm subtrahend dst #x28))
(define-operator* (:16 :subw :32 :subl :64 :subr) (subtrahend dst)
(imm-modrm subtrahend dst #x83 5 (sint 8))
(imm subtrahend #x2d :int-16-32-64 (dst :ax-eax-rax))
(imm-modrm subtrahend dst #x81 5 :int-16-32-64)
(reg-modrm dst subtrahend #x2b)
(reg-modrm subtrahend dst #x29))
(define-operator/8 :testb (mask dst)
(imm mask #xa8 (xint 8) (dst :al))
(imm-modrm mask dst #xf6 0 (xint 8))
(reg-modrm mask dst #x84))
(define-operator* (:16 :testw :32 :testl :64 :testr) (mask dst)
(imm mask #xa9 :int-16-32-64 (dst :ax-eax-rax))
(imm-modrm mask dst #xf7 0 :int-16-32-64)
(reg-modrm mask dst #x85))
WBINVD ,
(define-operator/none :wbinvd ()
(opcode #x0f09))
(define-operator/none :wrmsr ()
(opcode #x0f30))
(define-operator/8 :xchgb (x y)
(reg-modrm y x #x86)
(reg-modrm x y #x86))
(define-operator* (:16 :xchgw :32 :xchgl :64 :xchgr) (x y)
(opcode-reg #x90 x (y :ax-eax-rax))
(opcode-reg #x90 y (x :ax-eax-rax))
(reg-modrm x y #x87)
(reg-modrm y x #x87))
(define-operator/8 :xorb (src dst)
(imm src #x34 (xint 8) (dst :al))
(imm-modrm src dst #x80 6 (xint 8))
(reg-modrm dst src #x32)
(reg-modrm src dst #x30))
(define-operator* (:16 :xorw :32 :xorl :64 :xorr) (src dst)
(imm-modrm src dst #x83 6 (sint 8))
(imm src #x35 :int-16-32-64 (dst :ax-eax-rax))
(imm-modrm src dst #x81 6 :int-16-32-64)
(reg-modrm dst src #x33)
(reg-modrm src dst #x31))
NOP
(define-operator/none :nop ()
(opcode #x90))
|
c9249e644a4c7d1d9592879b0e67a27fa28973cd0806c1f74f0266d53d3f5a66 | spawnfest/eep49ers | m.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1998 - 2016 . All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
-module(m).
-export([factorial/1]).
factorial(0) ->
1;
factorial(N) ->
N * factorial(N-1).
| null | https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/stdlib/test/c_SUITE_data/m.erl | erlang |
%CopyrightBegin%
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
%CopyrightEnd%
| Copyright Ericsson AB 1998 - 2016 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(m).
-export([factorial/1]).
factorial(0) ->
1;
factorial(N) ->
N * factorial(N-1).
|
cdaa2da06a76b238c0e49f64454925921c5221aaa30a0c733aa2d00ed4654b1f | madvas/cljs-react-material-ui-example | core.cljs | (ns cljs-react-material-ui-example.core
(:require
[cljsjs.material-ui]
[cljs-react-material-ui.core :as ui]
[cljs-react-material-ui.icons :as ic]
[goog.dom :as gdom]
[om.next :as om :refer-macros [defui]]
[cljs-react-material-ui-example.parser :as p]
[cljs-react-material-ui-example.util :as u]
[cljs-react-material-ui.chip-input.core :refer [chip-input]]
[om.dom :as dom]
[cljs-time.format :as tf]
[cljs-time.coerce :refer [from-date]]
[cljs-react-material-ui-example.state :refer [init-state]]
;[schema.core :as s :include-macros true]
[print.foo :as pf :include-macros true]))
(enable-console-print!)
(defn get-step-content [step-index]
(case step-index
0 "Select campaign settings..."
1 "What is an ad group anyways?"
2 "This is the bit I really care about!"
"You're a long way from home sonny jim!"))
(defui MyStepper
Object
(componentWillMount [this]
(om/set-state! this {:finished? false :step-index 0}))
(render [this]
(let [{:keys [finished? step-index]} (om/get-state this)]
(dom/div
#js {:className "row center-xs mar-top-20"}
(ui/paper
{:class-name "col-xs-12 col-md-8 col-lg-6 pad-10"}
(ui/stepper
{:active-step step-index}
(ui/step
(ui/step-label "Select campaign settings"))
(ui/step
(ui/step-label "Create an ad group"))
(ui/step
(ui/step-label "Create an ad")))
(if finished?
(dom/div
nil
(ui/floating-action-button
{:secondary true
:on-click #(om/set-state! this {:finished? false :step-index 0})}
(ic/content-clear)))
(dom/div
nil
(dom/p #js {:className "mar-bot-20"} (get-step-content step-index))
(dom/div
nil
(ui/flat-button
{:label "Back"
:disabled (= step-index 0)
:on-click #(om/set-state! this {:step-index (- step-index 1)})})
(ui/raised-button
{:label (if (= step-index 2) "Finish" "Next")
:primary true
:on-click #(om/set-state! this {:step-index (+ step-index 1)
:finished? (>= step-index 2)})})))))))))
(def my-stepper (om/factory MyStepper {}))
(defui Person
static om/Ident
(ident [this {:keys [db/id]}]
[:person/by-id id])
static om/IQuery
(query [this]
[:db/id :person/name :person/date {:person/status [:status/name]} {:person/happiness [:db/id :happiness/name]}])
Object
(render [this]
(let [{:keys [person/name person/date person/status person/happiness]} (om/props this)]
(ui/table-row
(ui/table-row-column name)
(ui/table-row-column (tf/unparse (:date tf/formatters) (from-date date)))
(ui/table-row-column (:status/name status))
(ui/table-row-column (:happiness/name happiness))))))
(def person (om/factory Person {}))
(defn my-table [people]
(ui/table
{:height "250px"}
(ui/table-header
{:display-select-all false
:adjust-for-checkbox false}
(ui/table-row
(ui/table-header-column "Name")
(ui/table-header-column "Date")
(ui/table-header-column "Status")
(ui/table-header-column "Happiness")))
(ui/table-body
(map person people))))
(defn radio-btn-group [c happiness-list val]
(let [[sad normal superb] happiness-list]
(ui/radio-button-group
{:name "happiness"
:value-selected (str val)
:on-change #(om/transact! c `[(person-new/change {:value ~(js/parseInt %2)
:path [:person/happiness 1]})
:person/new])
:class-name "row between-xs mar-ver-15"}
(ui/radio-button
{:value (str (:db/id sad))
:label (:happiness/name sad)
:class-name "col-xs-4"
:checked-icon (ic/social-sentiment-dissatisfied)
:unchecked-icon (ic/social-sentiment-dissatisfied)})
(ui/radio-button
{:value (str (:db/id normal))
:label (:happiness/name normal)
:class-name "col-xs-4"})
(ui/radio-button
{:value (str (:db/id superb))
:label (:happiness/name superb)
:class-name "col-xs-4"
:checked-icon (ic/action-favorite)
:unchecked-icon (ic/action-favorite-border)}))))
#_(s/defschema ValidPerson
{:person/name s/Str
:person/date s/Inst
:person/status [(s/one s/Keyword "status/by-id") s/Int]
:person/happiness [(s/one s/Keyword "happiness/by-id") s/Int]})
(defn handle-chip-delete [this idx]
(om/update-state! this (fn [state]
(update state :chip-data (partial remove #(= (key %) idx))))))
(defui MyChips
Object
(componentWillMount [this]
(om/set-state! this {:chip-data {0 "Clojure"
1 "Clojurescript"
2 "Om.Next"
3 "MaterialUI"}}))
(render [this]
(let [chip-data (:chip-data (om/get-state this))]
(ui/paper
{:class-name "col-xs-12 col-md-8 col-md-offset-2 col-lg-6 col-lg-offset-3 pad-10 mar-top-20 row"}
(for [chip (into [] chip-data)]
(ui/chip {:key (key chip)
:style {:margin-right 5}
:on-request-delete #(handle-chip-delete this (key chip))}
(val chip)))))))
(def my-chips (om/factory MyChips))
(defui AppRoot
static om/IQuery
(query [this]
[{:person/list (om/get-query Person)}
{:status/list [:db/id :status/name]}
{:happiness/list [:db/id :happiness/name]}
{:person/new (om/get-query Person)}])
Object
(render [this]
(let [props (om/props this)
state (om/get-state this)
person-list (:person/list props)
status-list (:status/list props)
happiness-list (:happiness/list props)
person-new (:person/new props)
close-help #(om/update-state! this assoc :open-help? false)
{:keys [drawer-open?]} (om/get-state this)]
(ui/mui-theme-provider
{:mui-theme (ui/get-mui-theme)}
(dom/div
#js {:className "h-100"}
(ui/app-bar
{:title "Material UI Om.Next App"
:icon-element-right
(ui/flat-button
{:label "Github"
:href "-react-material-ui-example"
:secondary true
:target :_blank})
:on-left-icon-button-touch-tap
#(om/set-state! this {:drawer-open? true})})
(ui/drawer
{:docked false
:open drawer-open?
:on-request-change #(om/set-state! this {:drawer-open? %})}
(ui/menu-item {:on-click #(println "Menu Item Clicked")} "Menu Item")
(ui/menu-item "Menu Item 2"))
(dom/div
#js {:className "row around-xs mar-top-20"}
(ui/paper
{:class-name "col-xs-11 col-md-6 col-lg-4"}
(ui/text-field
{:floating-label-text "Name"
:class-name "w-100"
:value (:person/name person-new)
:on-change #(om/transact! this `[(person-new/change {:value ~(u/target-val %)
:path [:person/name]})
:person/new])})
(ui/date-picker
{:hint-text "Select Date"
:mode :landscape
:class-name "w-100"
:value (:person/date person-new)
:on-change #(om/transact! this `[(person-new/change {:value ~%2
:path [:person/date]})
:person/new])})
(ui/auto-complete
{:dataSource (map :status/name status-list)
:hint-text "Type status"
:full-width true
:open-on-focus true
:search-text (or (:status/name
(u/find-by-key :db/id (second (:person/status person-new)) status-list))
"")
:filter (aget js/MaterialUI "AutoComplete" "caseInsensitiveFilter")
:on-new-request (fn [chosen]
(let [status-id (:db/id (u/find-by-key :status/name chosen status-list))]
(om/transact! this `[(person-new/change {:value [:status/by-id ~status-id]
:path [:person/status]})
:person/new])))})
(radio-btn-group this happiness-list (get-in person-new [:person/happiness 1]))
(dom/div
#js {:className "row pad-10 reverse"}
(ui/raised-button
{:label "Add"
:primary true
:label-position :before
:icon (ic/content-add-circle)
: disabled ( boolean ( s / check person - new ) )
:on-click #(om/transact! this `[(person-new/add)
:person/new :person/list])})
(ui/raised-button
{:label "Help"
:class-name "mar-rig-10"
:secondary true
:label-position :before
:icon (ic/action-help)
:on-click #(om/update-state! this assoc :open-help? true)})))
(ui/paper
{:class-name "col-xs-11 col-md-11 col-lg-7"}
(ui/mui-theme-provider
{:mui-theme (ui/get-mui-theme
{:table-header-column
{:text-color (ui/color :deep-orange500)}})}
(my-table person-list))))
(ui/mui-theme-provider
{:mui-theme (ui/get-mui-theme
{:palette {:primary1-color (ui/color :amber600)
:shadow-color (ui/color :deep-orange900)
:text-color (ui/color :indigo900)}
:stepper {:inactive-icon-color (ui/color :deep-orange900)
:connector-line-color (ui/color :light-blue600)
:text-color (ui/color :teal900)
:disabled-text-color (ui/color :teal200)}})}
(my-stepper))
(my-chips)
(ui/paper
{:class-name "col-xs-12 col-md-8 col-md-offset-2 col-lg-6 col-lg-offset-3 pad-10 mar-top-20 row"}
(chip-input
{:full-width true
:default-value ["write" "here"]}))
(ui/dialog
{:title "Help"
:key "dialog"
:modal false
:open (boolean (:open-help? state))
:actions [(ui/raised-button
{:label "Back"
:key "back"
:on-click close-help})
(ui/raised-button
{:label "Thanks"
:key "thanks"
:on-click close-help})]
:on-request-close close-help})
)))))
(def reconciler
(om/reconciler
{:state (atom init-state)
:normalize true
:parser (om/parser {:read p/read :mutate p/mutate})}))
(om/add-root! reconciler AppRoot (gdom/getElement "app"))
| null | https://raw.githubusercontent.com/madvas/cljs-react-material-ui-example/55a1ecda8f0ff2348f9d424a2c758bf24fef531c/src/cljs/cljs_react_material_ui_example/core.cljs | clojure | [schema.core :as s :include-macros true] | (ns cljs-react-material-ui-example.core
(:require
[cljsjs.material-ui]
[cljs-react-material-ui.core :as ui]
[cljs-react-material-ui.icons :as ic]
[goog.dom :as gdom]
[om.next :as om :refer-macros [defui]]
[cljs-react-material-ui-example.parser :as p]
[cljs-react-material-ui-example.util :as u]
[cljs-react-material-ui.chip-input.core :refer [chip-input]]
[om.dom :as dom]
[cljs-time.format :as tf]
[cljs-time.coerce :refer [from-date]]
[cljs-react-material-ui-example.state :refer [init-state]]
[print.foo :as pf :include-macros true]))
(enable-console-print!)
(defn get-step-content [step-index]
(case step-index
0 "Select campaign settings..."
1 "What is an ad group anyways?"
2 "This is the bit I really care about!"
"You're a long way from home sonny jim!"))
(defui MyStepper
Object
(componentWillMount [this]
(om/set-state! this {:finished? false :step-index 0}))
(render [this]
(let [{:keys [finished? step-index]} (om/get-state this)]
(dom/div
#js {:className "row center-xs mar-top-20"}
(ui/paper
{:class-name "col-xs-12 col-md-8 col-lg-6 pad-10"}
(ui/stepper
{:active-step step-index}
(ui/step
(ui/step-label "Select campaign settings"))
(ui/step
(ui/step-label "Create an ad group"))
(ui/step
(ui/step-label "Create an ad")))
(if finished?
(dom/div
nil
(ui/floating-action-button
{:secondary true
:on-click #(om/set-state! this {:finished? false :step-index 0})}
(ic/content-clear)))
(dom/div
nil
(dom/p #js {:className "mar-bot-20"} (get-step-content step-index))
(dom/div
nil
(ui/flat-button
{:label "Back"
:disabled (= step-index 0)
:on-click #(om/set-state! this {:step-index (- step-index 1)})})
(ui/raised-button
{:label (if (= step-index 2) "Finish" "Next")
:primary true
:on-click #(om/set-state! this {:step-index (+ step-index 1)
:finished? (>= step-index 2)})})))))))))
(def my-stepper (om/factory MyStepper {}))
(defui Person
static om/Ident
(ident [this {:keys [db/id]}]
[:person/by-id id])
static om/IQuery
(query [this]
[:db/id :person/name :person/date {:person/status [:status/name]} {:person/happiness [:db/id :happiness/name]}])
Object
(render [this]
(let [{:keys [person/name person/date person/status person/happiness]} (om/props this)]
(ui/table-row
(ui/table-row-column name)
(ui/table-row-column (tf/unparse (:date tf/formatters) (from-date date)))
(ui/table-row-column (:status/name status))
(ui/table-row-column (:happiness/name happiness))))))
(def person (om/factory Person {}))
(defn my-table [people]
(ui/table
{:height "250px"}
(ui/table-header
{:display-select-all false
:adjust-for-checkbox false}
(ui/table-row
(ui/table-header-column "Name")
(ui/table-header-column "Date")
(ui/table-header-column "Status")
(ui/table-header-column "Happiness")))
(ui/table-body
(map person people))))
(defn radio-btn-group [c happiness-list val]
(let [[sad normal superb] happiness-list]
(ui/radio-button-group
{:name "happiness"
:value-selected (str val)
:on-change #(om/transact! c `[(person-new/change {:value ~(js/parseInt %2)
:path [:person/happiness 1]})
:person/new])
:class-name "row between-xs mar-ver-15"}
(ui/radio-button
{:value (str (:db/id sad))
:label (:happiness/name sad)
:class-name "col-xs-4"
:checked-icon (ic/social-sentiment-dissatisfied)
:unchecked-icon (ic/social-sentiment-dissatisfied)})
(ui/radio-button
{:value (str (:db/id normal))
:label (:happiness/name normal)
:class-name "col-xs-4"})
(ui/radio-button
{:value (str (:db/id superb))
:label (:happiness/name superb)
:class-name "col-xs-4"
:checked-icon (ic/action-favorite)
:unchecked-icon (ic/action-favorite-border)}))))
#_(s/defschema ValidPerson
{:person/name s/Str
:person/date s/Inst
:person/status [(s/one s/Keyword "status/by-id") s/Int]
:person/happiness [(s/one s/Keyword "happiness/by-id") s/Int]})
(defn handle-chip-delete [this idx]
(om/update-state! this (fn [state]
(update state :chip-data (partial remove #(= (key %) idx))))))
(defui MyChips
Object
(componentWillMount [this]
(om/set-state! this {:chip-data {0 "Clojure"
1 "Clojurescript"
2 "Om.Next"
3 "MaterialUI"}}))
(render [this]
(let [chip-data (:chip-data (om/get-state this))]
(ui/paper
{:class-name "col-xs-12 col-md-8 col-md-offset-2 col-lg-6 col-lg-offset-3 pad-10 mar-top-20 row"}
(for [chip (into [] chip-data)]
(ui/chip {:key (key chip)
:style {:margin-right 5}
:on-request-delete #(handle-chip-delete this (key chip))}
(val chip)))))))
(def my-chips (om/factory MyChips))
(defui AppRoot
static om/IQuery
(query [this]
[{:person/list (om/get-query Person)}
{:status/list [:db/id :status/name]}
{:happiness/list [:db/id :happiness/name]}
{:person/new (om/get-query Person)}])
Object
(render [this]
(let [props (om/props this)
state (om/get-state this)
person-list (:person/list props)
status-list (:status/list props)
happiness-list (:happiness/list props)
person-new (:person/new props)
close-help #(om/update-state! this assoc :open-help? false)
{:keys [drawer-open?]} (om/get-state this)]
(ui/mui-theme-provider
{:mui-theme (ui/get-mui-theme)}
(dom/div
#js {:className "h-100"}
(ui/app-bar
{:title "Material UI Om.Next App"
:icon-element-right
(ui/flat-button
{:label "Github"
:href "-react-material-ui-example"
:secondary true
:target :_blank})
:on-left-icon-button-touch-tap
#(om/set-state! this {:drawer-open? true})})
(ui/drawer
{:docked false
:open drawer-open?
:on-request-change #(om/set-state! this {:drawer-open? %})}
(ui/menu-item {:on-click #(println "Menu Item Clicked")} "Menu Item")
(ui/menu-item "Menu Item 2"))
(dom/div
#js {:className "row around-xs mar-top-20"}
(ui/paper
{:class-name "col-xs-11 col-md-6 col-lg-4"}
(ui/text-field
{:floating-label-text "Name"
:class-name "w-100"
:value (:person/name person-new)
:on-change #(om/transact! this `[(person-new/change {:value ~(u/target-val %)
:path [:person/name]})
:person/new])})
(ui/date-picker
{:hint-text "Select Date"
:mode :landscape
:class-name "w-100"
:value (:person/date person-new)
:on-change #(om/transact! this `[(person-new/change {:value ~%2
:path [:person/date]})
:person/new])})
(ui/auto-complete
{:dataSource (map :status/name status-list)
:hint-text "Type status"
:full-width true
:open-on-focus true
:search-text (or (:status/name
(u/find-by-key :db/id (second (:person/status person-new)) status-list))
"")
:filter (aget js/MaterialUI "AutoComplete" "caseInsensitiveFilter")
:on-new-request (fn [chosen]
(let [status-id (:db/id (u/find-by-key :status/name chosen status-list))]
(om/transact! this `[(person-new/change {:value [:status/by-id ~status-id]
:path [:person/status]})
:person/new])))})
(radio-btn-group this happiness-list (get-in person-new [:person/happiness 1]))
(dom/div
#js {:className "row pad-10 reverse"}
(ui/raised-button
{:label "Add"
:primary true
:label-position :before
:icon (ic/content-add-circle)
: disabled ( boolean ( s / check person - new ) )
:on-click #(om/transact! this `[(person-new/add)
:person/new :person/list])})
(ui/raised-button
{:label "Help"
:class-name "mar-rig-10"
:secondary true
:label-position :before
:icon (ic/action-help)
:on-click #(om/update-state! this assoc :open-help? true)})))
(ui/paper
{:class-name "col-xs-11 col-md-11 col-lg-7"}
(ui/mui-theme-provider
{:mui-theme (ui/get-mui-theme
{:table-header-column
{:text-color (ui/color :deep-orange500)}})}
(my-table person-list))))
(ui/mui-theme-provider
{:mui-theme (ui/get-mui-theme
{:palette {:primary1-color (ui/color :amber600)
:shadow-color (ui/color :deep-orange900)
:text-color (ui/color :indigo900)}
:stepper {:inactive-icon-color (ui/color :deep-orange900)
:connector-line-color (ui/color :light-blue600)
:text-color (ui/color :teal900)
:disabled-text-color (ui/color :teal200)}})}
(my-stepper))
(my-chips)
(ui/paper
{:class-name "col-xs-12 col-md-8 col-md-offset-2 col-lg-6 col-lg-offset-3 pad-10 mar-top-20 row"}
(chip-input
{:full-width true
:default-value ["write" "here"]}))
(ui/dialog
{:title "Help"
:key "dialog"
:modal false
:open (boolean (:open-help? state))
:actions [(ui/raised-button
{:label "Back"
:key "back"
:on-click close-help})
(ui/raised-button
{:label "Thanks"
:key "thanks"
:on-click close-help})]
:on-request-close close-help})
)))))
(def reconciler
(om/reconciler
{:state (atom init-state)
:normalize true
:parser (om/parser {:read p/read :mutate p/mutate})}))
(om/add-root! reconciler AppRoot (gdom/getElement "app"))
|
121b3f21903da831823869888ab7dee9d0a3ed5150bfb00ebfd6f44177f4c40c | tweag/kernmantle | Trans.hs | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE FunctionalDependencies #
# LANGUAGE FlexibleInstances #
# LANGUAGE UndecidableInstances #
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE RankNTypes #-}
| This module exposes the SieveTrans class and some Sieve transformers based
on usual Reader and Writer
module Data.Profunctor.Trans where
import Control.Arrow
import Control.Monad.IO.Class
import Data.Bifunctor.Tannen
import Data.Profunctor
import Data.Profunctor.Cayley
import qualified Control.Monad.Trans.Reader as R
import qualified Control.Monad.Trans.Writer.Strict as W
| A general version of ' ' that allows mapping and recursively reaching
-- the sieve
class SieveTrans f cat | cat -> f where
liftSieve :: (a -> f b) -> cat a b
mapSieve :: ((a -> f b) -> (a' -> f b')) -> cat a b -> cat a' b'
-- | Just an alias
type HasKleisli = SieveTrans
-- | Just an alias
liftKleisli :: (HasKleisli m eff) => (a -> m b) -> eff a b
liftKleisli = liftSieve
# INLINE liftKleisli #
-- | Just an alias
mapKleisli :: (HasKleisli m eff)
=> ((a -> m b) -> (a' -> m b')) -> eff a b -> eff a' b'
mapKleisli = mapSieve
# INLINE mapKleisli #
instance SieveTrans f (Star f) where
liftSieve = Star
mapSieve f (Star m) = Star $ f m
instance SieveTrans m (Kleisli m) where
liftSieve = Kleisli
mapSieve f (Kleisli m) = Kleisli $ f m
instance (SieveTrans f cat, Applicative f')
=> SieveTrans f (Cayley f' cat) where
liftSieve = Cayley . pure . liftSieve
# INLINE liftSieve #
mapSieve f (Cayley app) = Cayley $ mapSieve f <$> app
# INLINE mapSieve #
instance (SieveTrans f cat, Applicative f)
=> SieveTrans f (Tannen f cat) where
liftSieve = Tannen . pure . liftSieve
# INLINE liftSieve #
mapSieve f (Tannen app) = Tannen $ mapSieve f <$> app
# INLINE mapSieve #
type HasKleisliIO m eff = (HasKleisli m eff, MonadIO m)
| When you want to lift some IO action in a Sieve of any MonadIO
liftKleisliIO :: (HasKleisliIO m eff) => (a -> IO b) -> eff a b
liftKleisliIO f = liftKleisli $ liftIO . f
# INLINE liftKleisliIO #
-- | An alias to make signatures more readable
type (~>) = Cayley
infixr 1 ~> -- To be of a lower precedence than (:->)
type Reader r = R.Reader r
type Writer w = W.Writer w
fmapping :: (Functor f) => f t -> (t -> eff a b) -> (f ~> eff) a b
fmapping a f = Cayley $ fmap f a
# INLINE fmapping #
| mapCayley in profunctors maps the functor . mapCayleyEff maps the effect in
-- it.
mapCayleyEff :: (Functor f)
=> (eff a b -> eff' a' b')
-> (f ~> eff) a b
-> (f ~> eff') a' b'
mapCayleyEff f (Cayley eff) = Cayley $ fmap f eff
# INLINE mapCayleyEff #
reading :: (t -> eff a b) -> (Reader t ~> eff) a b
reading f = Cayley $ R.reader $ f
# INLINE reading #
mapReader :: (t' -> eff a b -> (t, eff' a' b'))
-> (Reader t ~> eff) a b
-> (Reader t' ~> eff') a' b'
mapReader f (Cayley eff) = Cayley (R.reader $ \t' ->
let (t,eff') = f t' $ R.runReader eff t
in eff')
# INLINE mapReader #
mapReader_ :: (t -> eff a b -> eff' a' b')
-> (Reader t ~> eff) a b
-> (Reader t ~> eff') a' b'
mapReader_ f (Cayley eff) = Cayley (R.reader $ \x -> f x $ R.runReader eff x)
{-# INLINE mapReader_ #-}
runReader :: t -> (Reader t ~> eff) a b -> eff a b
runReader t (Cayley f) = R.runReader f t
# INLINE runReader #
writing :: w -> eff :-> (Writer w ~> eff)
writing w eff = Cayley $ W.writer (eff, w)
# INLINE writing #
mapWriter :: (w -> eff a b -> (w',eff' a' b'))
-> (Writer w ~> eff) a b
-> (Writer w' ~> eff') a' b'
mapWriter f (Cayley act) = Cayley $ case W.runWriter act of
(eff,w) -> W.writer $ swap $ f w eff
# INLINE mapWriter #
mapWriter_ :: (w -> eff a b -> eff' a' b')
-> (Writer w ~> eff) a b
-> (Writer w ~> eff') a' b'
mapWriter_ f = mapWriter (\w e -> (w,f w e))
{-# INLINE mapWriter_ #-}
runWriter :: (Writer w ~> eff) a b -> (w, eff a b)
runWriter (Cayley eff) = swap $ W.runWriter eff
# INLINE runWriter #
runWriter_ :: (Writer w ~> eff) a b -> eff a b
runWriter_ (Cayley eff) = fst $ W.runWriter eff
{-# INLINE runWriter_ #-}
swap :: (a,b) -> (b,a)
swap (a,b) = (b,a)
# INLINE swap #
returning :: (Arrow eff) => b -> eff a b
returning = arr . const
{-# INLINE returning #-}
-- | Just a flipped variant of runKleisli
perform :: a -> Kleisli m a b -> m b
perform = flip runKleisli
# INLINE perform #
| null | https://raw.githubusercontent.com/tweag/kernmantle/19e018449f4fba68d383611a9d38a1b9e04e81ee/kernmantle/src/Data/Profunctor/Trans.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE TypeOperators #
# LANGUAGE RankNTypes #
the sieve
| Just an alias
| Just an alias
| Just an alias
| An alias to make signatures more readable
To be of a lower precedence than (:->)
it.
# INLINE mapReader_ #
# INLINE mapWriter_ #
# INLINE runWriter_ #
# INLINE returning #
| Just a flipped variant of runKleisli | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE FunctionalDependencies #
# LANGUAGE FlexibleInstances #
# LANGUAGE UndecidableInstances #
| This module exposes the SieveTrans class and some Sieve transformers based
on usual Reader and Writer
module Data.Profunctor.Trans where
import Control.Arrow
import Control.Monad.IO.Class
import Data.Bifunctor.Tannen
import Data.Profunctor
import Data.Profunctor.Cayley
import qualified Control.Monad.Trans.Reader as R
import qualified Control.Monad.Trans.Writer.Strict as W
| A general version of ' ' that allows mapping and recursively reaching
class SieveTrans f cat | cat -> f where
liftSieve :: (a -> f b) -> cat a b
mapSieve :: ((a -> f b) -> (a' -> f b')) -> cat a b -> cat a' b'
type HasKleisli = SieveTrans
liftKleisli :: (HasKleisli m eff) => (a -> m b) -> eff a b
liftKleisli = liftSieve
# INLINE liftKleisli #
mapKleisli :: (HasKleisli m eff)
=> ((a -> m b) -> (a' -> m b')) -> eff a b -> eff a' b'
mapKleisli = mapSieve
# INLINE mapKleisli #
instance SieveTrans f (Star f) where
liftSieve = Star
mapSieve f (Star m) = Star $ f m
instance SieveTrans m (Kleisli m) where
liftSieve = Kleisli
mapSieve f (Kleisli m) = Kleisli $ f m
instance (SieveTrans f cat, Applicative f')
=> SieveTrans f (Cayley f' cat) where
liftSieve = Cayley . pure . liftSieve
# INLINE liftSieve #
mapSieve f (Cayley app) = Cayley $ mapSieve f <$> app
# INLINE mapSieve #
instance (SieveTrans f cat, Applicative f)
=> SieveTrans f (Tannen f cat) where
liftSieve = Tannen . pure . liftSieve
# INLINE liftSieve #
mapSieve f (Tannen app) = Tannen $ mapSieve f <$> app
# INLINE mapSieve #
type HasKleisliIO m eff = (HasKleisli m eff, MonadIO m)
| When you want to lift some IO action in a Sieve of any MonadIO
liftKleisliIO :: (HasKleisliIO m eff) => (a -> IO b) -> eff a b
liftKleisliIO f = liftKleisli $ liftIO . f
# INLINE liftKleisliIO #
type (~>) = Cayley
type Reader r = R.Reader r
type Writer w = W.Writer w
fmapping :: (Functor f) => f t -> (t -> eff a b) -> (f ~> eff) a b
fmapping a f = Cayley $ fmap f a
# INLINE fmapping #
| mapCayley in profunctors maps the functor . mapCayleyEff maps the effect in
mapCayleyEff :: (Functor f)
=> (eff a b -> eff' a' b')
-> (f ~> eff) a b
-> (f ~> eff') a' b'
mapCayleyEff f (Cayley eff) = Cayley $ fmap f eff
# INLINE mapCayleyEff #
reading :: (t -> eff a b) -> (Reader t ~> eff) a b
reading f = Cayley $ R.reader $ f
# INLINE reading #
mapReader :: (t' -> eff a b -> (t, eff' a' b'))
-> (Reader t ~> eff) a b
-> (Reader t' ~> eff') a' b'
mapReader f (Cayley eff) = Cayley (R.reader $ \t' ->
let (t,eff') = f t' $ R.runReader eff t
in eff')
# INLINE mapReader #
mapReader_ :: (t -> eff a b -> eff' a' b')
-> (Reader t ~> eff) a b
-> (Reader t ~> eff') a' b'
mapReader_ f (Cayley eff) = Cayley (R.reader $ \x -> f x $ R.runReader eff x)
runReader :: t -> (Reader t ~> eff) a b -> eff a b
runReader t (Cayley f) = R.runReader f t
# INLINE runReader #
writing :: w -> eff :-> (Writer w ~> eff)
writing w eff = Cayley $ W.writer (eff, w)
# INLINE writing #
mapWriter :: (w -> eff a b -> (w',eff' a' b'))
-> (Writer w ~> eff) a b
-> (Writer w' ~> eff') a' b'
mapWriter f (Cayley act) = Cayley $ case W.runWriter act of
(eff,w) -> W.writer $ swap $ f w eff
# INLINE mapWriter #
mapWriter_ :: (w -> eff a b -> eff' a' b')
-> (Writer w ~> eff) a b
-> (Writer w ~> eff') a' b'
mapWriter_ f = mapWriter (\w e -> (w,f w e))
runWriter :: (Writer w ~> eff) a b -> (w, eff a b)
runWriter (Cayley eff) = swap $ W.runWriter eff
# INLINE runWriter #
runWriter_ :: (Writer w ~> eff) a b -> eff a b
runWriter_ (Cayley eff) = fst $ W.runWriter eff
swap :: (a,b) -> (b,a)
swap (a,b) = (b,a)
# INLINE swap #
returning :: (Arrow eff) => b -> eff a b
returning = arr . const
perform :: a -> Kleisli m a b -> m b
perform = flip runKleisli
# INLINE perform #
|
ce220a1e5dc3fb8498fca273a2f3378239c6f2801b2960915b77e610bff4ea1b | yi-editor/yi | Completion.hs | {-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Completion
-- License : GPL-2
-- Maintainer :
-- Stability : experimental
-- Portability : portable
--
-- Collection of functions for completion and matching.
module Yi.Completion
( completeInList, completeInList'
, completeInListCustomShow
, commonPrefix
, prefixMatch, infixUptoEndMatch
, subsequenceMatch, subsequenceTextMatch
, containsMatch', containsMatch, containsMatchCaseInsensitive
, isCasePrefixOf
)
where
import Data.Function (on)
import Data.List (find, nub)
import Data.Maybe (catMaybes)
import Data.Monoid ((<>))
import Data.Text (Text)
import qualified Data.Text as T (Text, breakOn, isPrefixOf, length, null, tails, toCaseFold, splitAt)
import Yi.Editor (EditorM, printMsg, printMsgs)
import Yi.String (commonTPrefix', showT)
import Yi.Utils (commonPrefix)
-------------------------------------------
-- General completion
-- | Like usual 'T.isPrefixOf' but user can specify case sensitivity.
See ' T.toCaseFold ' for exotic unicode gotchas .
isCasePrefixOf :: Bool -- ^ Is case-sensitive?
-> T.Text
-> T.Text
-> Bool
isCasePrefixOf True = T.isPrefixOf
isCasePrefixOf False = T.isPrefixOf `on` T.toCaseFold
-- | Prefix matching function, for use with 'completeInList'
prefixMatch :: T.Text -> T.Text -> Maybe T.Text
prefixMatch prefix s = if prefix `T.isPrefixOf` s then Just s else Nothing
-- | Text from the match up to the end, for use with 'completeInList'
infixUptoEndMatch :: T.Text -> T.Text -> Maybe T.Text
infixUptoEndMatch "" haystack = Just haystack
infixUptoEndMatch needle haystack = case T.breakOn needle haystack of
(_, t) -> if T.null t then Nothing else Just t
| A simple fuzzy match algorithm . Example : " abc " matches " a1b2c "
subsequenceMatch :: String -> String -> Bool
subsequenceMatch needle haystack = go needle haystack
where go (n:ns) (h:hs) | n == h = go ns hs
go (n:ns) (h:hs) | n /= h = go (n:ns) hs
go [] _ = True
go _ [] = False
go _ _ = False
| A simple fuzzy match algorithm . Example : " abc " matches " a1b2c "
subsequenceTextMatch :: Text -> Text -> Bool
subsequenceTextMatch needle haystack
| T.null needle = True
| T.null haystack = False
| n == h = subsequenceTextMatch ns hs
| n /= h = subsequenceTextMatch needle hs
| otherwise = False
where
n,ns,h,hs :: Text
(n,ns) = T.splitAt 1 needle
(h,hs) = T.splitAt 1 haystack
-- | TODO: this is a terrible function, isn't this just
-- case-insensitive infix? – Fūzetsu
containsMatch' :: Bool -> T.Text -> T.Text -> Maybe T.Text
containsMatch' caseSensitive pattern str =
const str <$> find (pattern `tstPrefix`) (T.tails str)
where
tstPrefix = isCasePrefixOf caseSensitive
containsMatch :: T.Text -> T.Text -> Maybe T.Text
containsMatch = containsMatch' True
containsMatchCaseInsensitive :: T.Text -> T.Text -> Maybe T.Text
containsMatchCaseInsensitive = containsMatch' False
-- | Complete a string given a user input string, a matching function
-- and a list of possibilites. Matching function should return the
-- part of the string that matches the user string.
completeInList :: T.Text -- ^ Input to match on
-> (T.Text -> Maybe T.Text) -- ^ matcher function
-> [T.Text] -- ^ items to match against
-> EditorM T.Text
completeInList = completeInListCustomShow id
-- | Same as 'completeInList', but maps @showFunction@ on possible
-- matches when printing
completeInListCustomShow :: (T.Text -> T.Text) -- ^ Show function
-> T.Text -- ^ Input to match on
-> (T.Text -> Maybe T.Text) -- ^ matcher function
-> [T.Text] -- ^ items to match against
-> EditorM T.Text
completeInListCustomShow showFunction s match possibilities
| null filtered = printMsg "No match" >> return s
| prefix /= s = return prefix
| isSingleton filtered = printMsg "Sole completion" >> return s
| prefix `elem` filtered =
printMsg ("Complete, but not unique: " <> showT filtered) >> return s
| otherwise = printMsgs (map showFunction filtered)
>> return (bestMatch filtered s)
where
prefix = commonTPrefix' filtered
filtered = filterMatches match possibilities
completeInList' :: T.Text
-> (T.Text -> Maybe T.Text)
-> [T.Text]
-> EditorM T.Text
completeInList' s match l = case filtered of
[] -> printMsg "No match" >> return s
[x] | s == x -> printMsg "Sole completion" >> return s
| otherwise -> return x
_ -> printMsgs filtered >> return (bestMatch filtered s)
where
filtered = filterMatches match l
-- | This function attempts to provide a better tab completion result in
cases where more than one file matches our prefix . Consider directory with
following files : @["Main.hs " , " Main.hi " , " Main.o " , " " , " Foo.hs"]@.
--
After inserting into the minibuffer and attempting to complete , the
-- possible matches will be filtered in 'completeInList'' to
-- @["Main.hs", "Main.hi", "Main.o"]@ however because of multiple matches,
the buffer will not be updated to say @Main.@ but will instead stay at @Mai@.
--
-- This is extremely tedious when trying to complete filenames in directories
-- with many files so here we try to catch common prefixes of filtered files and
-- if the result is longer than what we have, we use it instead.
bestMatch :: [T.Text] -> T.Text -> T.Text
bestMatch fs s = let p = commonTPrefix' fs
in if T.length p > T.length s then p else s
filterMatches :: Eq a => (b -> Maybe a) -> [b] -> [a]
filterMatches match = nub . catMaybes . fmap match
Not really necessary but a bit faster than @(length l ) = = 1@
isSingleton :: [a] -> Bool
isSingleton [_] = True
isSingleton _ = False
| null | https://raw.githubusercontent.com/yi-editor/yi/58c239e3a77cef8f4f77e94677bd6a295f585f5f/yi-core/src/Yi/Completion.hs | haskell | # LANGUAGE OverloadedStrings #
# OPTIONS_HADDOCK show-extensions #
|
Module : Yi.Completion
License : GPL-2
Maintainer :
Stability : experimental
Portability : portable
Collection of functions for completion and matching.
-----------------------------------------
General completion
| Like usual 'T.isPrefixOf' but user can specify case sensitivity.
^ Is case-sensitive?
| Prefix matching function, for use with 'completeInList'
| Text from the match up to the end, for use with 'completeInList'
| TODO: this is a terrible function, isn't this just
case-insensitive infix? – Fūzetsu
| Complete a string given a user input string, a matching function
and a list of possibilites. Matching function should return the
part of the string that matches the user string.
^ Input to match on
^ matcher function
^ items to match against
| Same as 'completeInList', but maps @showFunction@ on possible
matches when printing
^ Show function
^ Input to match on
^ matcher function
^ items to match against
| This function attempts to provide a better tab completion result in
possible matches will be filtered in 'completeInList'' to
@["Main.hs", "Main.hi", "Main.o"]@ however because of multiple matches,
This is extremely tedious when trying to complete filenames in directories
with many files so here we try to catch common prefixes of filtered files and
if the result is longer than what we have, we use it instead. |
module Yi.Completion
( completeInList, completeInList'
, completeInListCustomShow
, commonPrefix
, prefixMatch, infixUptoEndMatch
, subsequenceMatch, subsequenceTextMatch
, containsMatch', containsMatch, containsMatchCaseInsensitive
, isCasePrefixOf
)
where
import Data.Function (on)
import Data.List (find, nub)
import Data.Maybe (catMaybes)
import Data.Monoid ((<>))
import Data.Text (Text)
import qualified Data.Text as T (Text, breakOn, isPrefixOf, length, null, tails, toCaseFold, splitAt)
import Yi.Editor (EditorM, printMsg, printMsgs)
import Yi.String (commonTPrefix', showT)
import Yi.Utils (commonPrefix)
See ' T.toCaseFold ' for exotic unicode gotchas .
-> T.Text
-> T.Text
-> Bool
isCasePrefixOf True = T.isPrefixOf
isCasePrefixOf False = T.isPrefixOf `on` T.toCaseFold
prefixMatch :: T.Text -> T.Text -> Maybe T.Text
prefixMatch prefix s = if prefix `T.isPrefixOf` s then Just s else Nothing
infixUptoEndMatch :: T.Text -> T.Text -> Maybe T.Text
infixUptoEndMatch "" haystack = Just haystack
infixUptoEndMatch needle haystack = case T.breakOn needle haystack of
(_, t) -> if T.null t then Nothing else Just t
| A simple fuzzy match algorithm . Example : " abc " matches " a1b2c "
subsequenceMatch :: String -> String -> Bool
subsequenceMatch needle haystack = go needle haystack
where go (n:ns) (h:hs) | n == h = go ns hs
go (n:ns) (h:hs) | n /= h = go (n:ns) hs
go [] _ = True
go _ [] = False
go _ _ = False
| A simple fuzzy match algorithm . Example : " abc " matches " a1b2c "
subsequenceTextMatch :: Text -> Text -> Bool
subsequenceTextMatch needle haystack
| T.null needle = True
| T.null haystack = False
| n == h = subsequenceTextMatch ns hs
| n /= h = subsequenceTextMatch needle hs
| otherwise = False
where
n,ns,h,hs :: Text
(n,ns) = T.splitAt 1 needle
(h,hs) = T.splitAt 1 haystack
containsMatch' :: Bool -> T.Text -> T.Text -> Maybe T.Text
containsMatch' caseSensitive pattern str =
const str <$> find (pattern `tstPrefix`) (T.tails str)
where
tstPrefix = isCasePrefixOf caseSensitive
containsMatch :: T.Text -> T.Text -> Maybe T.Text
containsMatch = containsMatch' True
containsMatchCaseInsensitive :: T.Text -> T.Text -> Maybe T.Text
containsMatchCaseInsensitive = containsMatch' False
-> EditorM T.Text
completeInList = completeInListCustomShow id
-> EditorM T.Text
completeInListCustomShow showFunction s match possibilities
| null filtered = printMsg "No match" >> return s
| prefix /= s = return prefix
| isSingleton filtered = printMsg "Sole completion" >> return s
| prefix `elem` filtered =
printMsg ("Complete, but not unique: " <> showT filtered) >> return s
| otherwise = printMsgs (map showFunction filtered)
>> return (bestMatch filtered s)
where
prefix = commonTPrefix' filtered
filtered = filterMatches match possibilities
completeInList' :: T.Text
-> (T.Text -> Maybe T.Text)
-> [T.Text]
-> EditorM T.Text
completeInList' s match l = case filtered of
[] -> printMsg "No match" >> return s
[x] | s == x -> printMsg "Sole completion" >> return s
| otherwise -> return x
_ -> printMsgs filtered >> return (bestMatch filtered s)
where
filtered = filterMatches match l
cases where more than one file matches our prefix . Consider directory with
following files : @["Main.hs " , " Main.hi " , " Main.o " , " " , " Foo.hs"]@.
After inserting into the minibuffer and attempting to complete , the
the buffer will not be updated to say @Main.@ but will instead stay at @Mai@.
bestMatch :: [T.Text] -> T.Text -> T.Text
bestMatch fs s = let p = commonTPrefix' fs
in if T.length p > T.length s then p else s
filterMatches :: Eq a => (b -> Maybe a) -> [b] -> [a]
filterMatches match = nub . catMaybes . fmap match
Not really necessary but a bit faster than @(length l ) = = 1@
isSingleton :: [a] -> Bool
isSingleton [_] = True
isSingleton _ = False
|
1c76e60e53c20523c72658a100996f00b159f2f849ed4ce7c8dabfc67f05e91a | tweag/ormolu | backticks-out.hs | foo x y = x `bar` y
| null | https://raw.githubusercontent.com/tweag/ormolu/34bdf62429768f24b70d0f8ba7730fc4d8ae73ba/data/examples/declaration/value/function/backticks-out.hs | haskell | foo x y = x `bar` y
|
|
5d6cd1d8be7cd28fb176fe4cdc1f2e0128da411ec05a8b9c7b94f67fcbf963e9 | leftaroundabout/beamonad | Grid.hs | -- |
-- Module : Presentation.Yeamer.Internal.Grid
Copyright : ( c ) 2017
-- License : GPL v3
--
-- Maintainer : (@) jsag $ hvl.no
-- Stability : experimental
-- Portability : portable
--
# LANGUAGE FlexibleInstances #
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveFoldable #
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE TemplateHaskell #-}
module Presentation.Yeamer.Internal.Grid where
import Data.Semigroup.Numbered
import GHC.Generics
import Data.Aeson (FromJSON, ToJSON)
import Flat (Flat)
import Data.Ratio ((%))
import Data.List (sortBy)
import Data.Ord (comparing)
import Control.Applicative (liftA2)
import Control.Monad.Trans.State
import Control.Arrow (second)
import Lens.Micro
import Lens.Micro.TH
data Gridded a = GridRegion a
| GridDivisions [[Gridded a]]
deriving (Generic, Functor, Eq, Show, Foldable, Traversable)
instance FromJSON a => FromJSON (Gridded a)
instance ToJSON a => ToJSON (Gridded a)
instance Flat a => Flat (Gridded a)
instance Applicative Gridded where
pure = GridRegion
fs <*> GridRegion x = ($ x) <$> fs
GridRegion f <*> xs = f <$> xs
GridDivisions fs <*> GridDivisions xs = GridDivisions $ liftA2 (<*>) <$> fs <*> xs
instance Monad Gridded where
return = GridRegion
GridRegion x >>= f = f x
GridDivisions xs >>= f = GridDivisions $ map (>>=f) <$> xs
instance SemigroupNo 0 (Gridded a) where
sappendN _ (GridDivisions g) (GridDivisions h) | length g == length h
= GridDivisions $ zipWith (++) g h
sappendN _ e (GridDivisions [r]) = GridDivisions [e:r]
sappendN _ (GridDivisions [r]) e = GridDivisions [r++[e]]
sappendN p a b = GridDivisions [[a,b]]
instance SemigroupNo 1 (Gridded a) where
sappendN _ (GridDivisions g@(l:_)) (GridDivisions h@(m:_)) | length l == length m
= GridDivisions $ g++h
sappendN _ e (GridDivisions c@([r]:_)) = GridDivisions $ [e]:c
sappendN _ (GridDivisions c@([r]:_)) e = GridDivisions $ c++[[e]]
sappendN p a b = GridDivisions [[a],[b]]
data GridRange = GridRange {
_xBegin, _xEnd, _yBegin, _yEnd :: Int }
deriving (Eq, Show, Generic)
makeLenses ''GridRange
data GridLayout a = GridLayout {
_gridWidth, _gridHeight :: Int
, _gridContents :: [(GridRange, a)]
} deriving (Functor, Generic, Eq, Show)
makeLenses ''GridLayout
layoutGrid :: Gridded a -> GridLayout a
layoutGrid = fmap snd . fst . layoutGridP
type GridRegionId = Int
layoutGridP :: Gridded a -> ( GridLayout (GridRegionId, a)
, [(GridRegionId, b)] -> (Gridded b, [(GridRegionId, b)]) )
layoutGridP = (`evalState`0) . go
where go (GridRegion a) = do
i <- get
put $ i+1
return ( GridLayout 1 1 [(GridRange 0 1 0 1, (i, a))]
, \((_, b):lgrs) -> (GridRegion b, lgrs) )
go (GridDivisions [])
= return ( GridLayout 0 0 []
, \lgrs -> (GridDivisions [], lgrs) )
go (GridDivisions [row]) = do
layouts <- mapM go row
return ( alignLayoutDirectional gridWidth xBegin xEnd
gridHeight yBegin yEnd
(fst<$>layouts)
, let procLgrs [] acc lgrs = (GridDivisions [acc []], lgrs)
procLgrs (srow:srows) acc lgrs
= let (srowRes, lgrs') = srow lgrs
in procLgrs srows (acc . (srowRes:)) lgrs'
in procLgrs (snd<$>layouts) id )
go (GridDivisions rows) = do
rLayouts <- mapM (go . GridDivisions . pure) rows
return ( alignLayoutDirectional gridHeight yBegin yEnd
gridWidth xBegin xEnd
(fst<$>rLayouts)
, let procLgrs [] acc lgrs = (GridDivisions $ acc [], lgrs)
procLgrs (srow:srows) acc lgrs
= let (GridDivisions [srowRes], lgrs') = srow lgrs
in procLgrs srows (acc . (srowRes:)) lgrs'
in procLgrs (snd<$>rLayouts) id )
alignLayoutDirectional
:: Lens' (GridLayout a) Int -> Lens' GridRange Int -> Lens' GridRange Int
-> Lens' (GridLayout a) Int -> Lens' GridRange Int -> Lens' GridRange Int
-> [GridLayout a] -> GridLayout a
alignLayoutDirectional gridLength sBegin sEnd
gridThickness zBegin zEnd
= align . map (\(ζ, h') -> ((0,h'), (h',(ζ,0))))
. xcat 0
where align state = case sortBy (comparing $ snd . fst) state of
(headSnail@((_,ySnail), _) : others)
| ySnail < 1
-> case break ((>ySnail) . snd . fst) others of
(snails, hares)
-> align $
[ ((ySnail, ySnail+h'), (h', (ζ,i+1)))
| (_, (h', (ζ,i))) <- headSnail : snails ]
++ [ ((ySnail,yHare), (h', shiftup cH))
| ((_,yHare), (h', cH)) <- hares ]
_ -> gather $ fst . snd . snd <$> state
shiftup (ζ, i)
= ( ζ & gridThickness %~ (+1)
& gridContents . mapped
%~ \(range, a) -> (range & zBegin%~shift
& zEnd%~shift , a)
, i+1 )
where shift j | j>i = j+1
| otherwise = j
xcat _ [] = []
xcat ix (ζ : cells)
= ( ζ & gridContents . mapped . _1 %~ (sBegin %~(+ix))
. (sEnd %~(+ix))
, 1%(ζ^.gridThickness) )
: xcat (ix + ζ^.gridLength) cells
gather [ζ] = ζ
gather (ζ₀ : others) = case gather others of
ζo | ζ₀^.gridThickness == ζo^.gridThickness
-> ζo & gridLength %~ (ζ₀^.gridLength +)
& gridContents %~ (ζ₀^.gridContents ++)
| null | https://raw.githubusercontent.com/leftaroundabout/beamonad/4f6273b479ea10c29759acab5edc56623b22c9a8/Presentation/Yeamer/Internal/Grid.hs | haskell | |
Module : Presentation.Yeamer.Internal.Grid
License : GPL v3
Maintainer : (@) jsag $ hvl.no
Stability : experimental
Portability : portable
# LANGUAGE DeriveTraversable #
# LANGUAGE DeriveGeneric #
# LANGUAGE DataKinds #
# LANGUAGE RankNTypes #
# LANGUAGE TemplateHaskell # | Copyright : ( c ) 2017
# LANGUAGE FlexibleInstances #
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveFoldable #
# LANGUAGE MultiParamTypeClasses #
module Presentation.Yeamer.Internal.Grid where
import Data.Semigroup.Numbered
import GHC.Generics
import Data.Aeson (FromJSON, ToJSON)
import Flat (Flat)
import Data.Ratio ((%))
import Data.List (sortBy)
import Data.Ord (comparing)
import Control.Applicative (liftA2)
import Control.Monad.Trans.State
import Control.Arrow (second)
import Lens.Micro
import Lens.Micro.TH
data Gridded a = GridRegion a
| GridDivisions [[Gridded a]]
deriving (Generic, Functor, Eq, Show, Foldable, Traversable)
instance FromJSON a => FromJSON (Gridded a)
instance ToJSON a => ToJSON (Gridded a)
instance Flat a => Flat (Gridded a)
instance Applicative Gridded where
pure = GridRegion
fs <*> GridRegion x = ($ x) <$> fs
GridRegion f <*> xs = f <$> xs
GridDivisions fs <*> GridDivisions xs = GridDivisions $ liftA2 (<*>) <$> fs <*> xs
instance Monad Gridded where
return = GridRegion
GridRegion x >>= f = f x
GridDivisions xs >>= f = GridDivisions $ map (>>=f) <$> xs
instance SemigroupNo 0 (Gridded a) where
sappendN _ (GridDivisions g) (GridDivisions h) | length g == length h
= GridDivisions $ zipWith (++) g h
sappendN _ e (GridDivisions [r]) = GridDivisions [e:r]
sappendN _ (GridDivisions [r]) e = GridDivisions [r++[e]]
sappendN p a b = GridDivisions [[a,b]]
instance SemigroupNo 1 (Gridded a) where
sappendN _ (GridDivisions g@(l:_)) (GridDivisions h@(m:_)) | length l == length m
= GridDivisions $ g++h
sappendN _ e (GridDivisions c@([r]:_)) = GridDivisions $ [e]:c
sappendN _ (GridDivisions c@([r]:_)) e = GridDivisions $ c++[[e]]
sappendN p a b = GridDivisions [[a],[b]]
data GridRange = GridRange {
_xBegin, _xEnd, _yBegin, _yEnd :: Int }
deriving (Eq, Show, Generic)
makeLenses ''GridRange
data GridLayout a = GridLayout {
_gridWidth, _gridHeight :: Int
, _gridContents :: [(GridRange, a)]
} deriving (Functor, Generic, Eq, Show)
makeLenses ''GridLayout
layoutGrid :: Gridded a -> GridLayout a
layoutGrid = fmap snd . fst . layoutGridP
type GridRegionId = Int
layoutGridP :: Gridded a -> ( GridLayout (GridRegionId, a)
, [(GridRegionId, b)] -> (Gridded b, [(GridRegionId, b)]) )
layoutGridP = (`evalState`0) . go
where go (GridRegion a) = do
i <- get
put $ i+1
return ( GridLayout 1 1 [(GridRange 0 1 0 1, (i, a))]
, \((_, b):lgrs) -> (GridRegion b, lgrs) )
go (GridDivisions [])
= return ( GridLayout 0 0 []
, \lgrs -> (GridDivisions [], lgrs) )
go (GridDivisions [row]) = do
layouts <- mapM go row
return ( alignLayoutDirectional gridWidth xBegin xEnd
gridHeight yBegin yEnd
(fst<$>layouts)
, let procLgrs [] acc lgrs = (GridDivisions [acc []], lgrs)
procLgrs (srow:srows) acc lgrs
= let (srowRes, lgrs') = srow lgrs
in procLgrs srows (acc . (srowRes:)) lgrs'
in procLgrs (snd<$>layouts) id )
go (GridDivisions rows) = do
rLayouts <- mapM (go . GridDivisions . pure) rows
return ( alignLayoutDirectional gridHeight yBegin yEnd
gridWidth xBegin xEnd
(fst<$>rLayouts)
, let procLgrs [] acc lgrs = (GridDivisions $ acc [], lgrs)
procLgrs (srow:srows) acc lgrs
= let (GridDivisions [srowRes], lgrs') = srow lgrs
in procLgrs srows (acc . (srowRes:)) lgrs'
in procLgrs (snd<$>rLayouts) id )
alignLayoutDirectional
:: Lens' (GridLayout a) Int -> Lens' GridRange Int -> Lens' GridRange Int
-> Lens' (GridLayout a) Int -> Lens' GridRange Int -> Lens' GridRange Int
-> [GridLayout a] -> GridLayout a
alignLayoutDirectional gridLength sBegin sEnd
gridThickness zBegin zEnd
= align . map (\(ζ, h') -> ((0,h'), (h',(ζ,0))))
. xcat 0
where align state = case sortBy (comparing $ snd . fst) state of
(headSnail@((_,ySnail), _) : others)
| ySnail < 1
-> case break ((>ySnail) . snd . fst) others of
(snails, hares)
-> align $
[ ((ySnail, ySnail+h'), (h', (ζ,i+1)))
| (_, (h', (ζ,i))) <- headSnail : snails ]
++ [ ((ySnail,yHare), (h', shiftup cH))
| ((_,yHare), (h', cH)) <- hares ]
_ -> gather $ fst . snd . snd <$> state
shiftup (ζ, i)
= ( ζ & gridThickness %~ (+1)
& gridContents . mapped
%~ \(range, a) -> (range & zBegin%~shift
& zEnd%~shift , a)
, i+1 )
where shift j | j>i = j+1
| otherwise = j
xcat _ [] = []
xcat ix (ζ : cells)
= ( ζ & gridContents . mapped . _1 %~ (sBegin %~(+ix))
. (sEnd %~(+ix))
, 1%(ζ^.gridThickness) )
: xcat (ix + ζ^.gridLength) cells
gather [ζ] = ζ
gather (ζ₀ : others) = case gather others of
ζo | ζ₀^.gridThickness == ζo^.gridThickness
-> ζo & gridLength %~ (ζ₀^.gridLength +)
& gridContents %~ (ζ₀^.gridContents ++)
|
53f4a1615f3b6f462127cf4500c1e8b51816be504f0ebfb719e2a98f5a06c428 | tweag/lagoon | SqlTrigger.hs | Copyright 2020 Pfizer Inc.
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
-- -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.
{-# LANGUAGE OverloadedStrings #-}
-- | PL/pgSQL: Triggers
module Lagoon.Util.PostgreSQL.Schema.SqlTrigger (
SqlTrigger(..)
, sqlTriggerName
) where
import Data.Monoid
import Database.PostgreSQL.Simple (Query)
import Lagoon.Interface
import Lagoon.Util
import Lagoon.Util.PostgreSQL.Transaction
import Lagoon.Util.PostgreSQL.Quoted
import Lagoon.Util.PostgreSQL.Schema.SqlFun
import Lagoon.Util.PostgreSQL.Schema.SqlEntity
-- | PL/pgSQL trigger
data SqlTrigger = SqlTrigger {
sqlTriggerExec :: SqlFun -- ^ Function to execute
^ " BEFORE UPDATE " , " AFTER INSERT " , etc .
, sqlTriggerTable :: TableName
}
instance SqlEntity SqlTrigger where
createEntity = createSqlTrigger
dropEntity = dropSqlTrigger
createSqlTrigger :: SqlTrigger -> QueryS
createSqlTrigger SqlTrigger{..} schema = intercalateM " " [
"CREATE TRIGGER " <> quoted (sqlTriggerName sqlTriggerExec)
, sqlTriggerEvent <> " ON " <> quoted (schema, sqlTriggerTable)
, " FOR EACH ROW" -- hardcoded for now
, " EXECUTE PROCEDURE " <> quoted (schema, sqlTriggerExec) <> "()"
]
dropSqlTrigger :: Cascade -> SqlTrigger -> QueryS
dropSqlTrigger cascade SqlTrigger{..} schema = intercalateM " " [
"DROP TRIGGER IF EXISTS"
, quoted (sqlTriggerName sqlTriggerExec)
, "ON"
, quoted (schema, sqlTriggerTable)
, cascadeToQuery cascade
]
| Construct ' TriggerNames ' from the ' FunctionName 's they call
sqlTriggerName :: SqlFun -> TriggerName
sqlTriggerName SqlFun{sqlFunName = FunctionName nm} =
TriggerName (nm ++ "_trigger")
| null | https://raw.githubusercontent.com/tweag/lagoon/2ef0440db810f4f45dbed160b369daf41d92bfa4/src/backend/src/Lagoon/Util/PostgreSQL/Schema/SqlTrigger.hs | haskell | you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
# LANGUAGE OverloadedStrings #
| PL/pgSQL: Triggers
| PL/pgSQL trigger
^ Function to execute
hardcoded for now | Copyright 2020 Pfizer Inc.
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
module Lagoon.Util.PostgreSQL.Schema.SqlTrigger (
SqlTrigger(..)
, sqlTriggerName
) where
import Data.Monoid
import Database.PostgreSQL.Simple (Query)
import Lagoon.Interface
import Lagoon.Util
import Lagoon.Util.PostgreSQL.Transaction
import Lagoon.Util.PostgreSQL.Quoted
import Lagoon.Util.PostgreSQL.Schema.SqlFun
import Lagoon.Util.PostgreSQL.Schema.SqlEntity
data SqlTrigger = SqlTrigger {
^ " BEFORE UPDATE " , " AFTER INSERT " , etc .
, sqlTriggerTable :: TableName
}
instance SqlEntity SqlTrigger where
createEntity = createSqlTrigger
dropEntity = dropSqlTrigger
createSqlTrigger :: SqlTrigger -> QueryS
createSqlTrigger SqlTrigger{..} schema = intercalateM " " [
"CREATE TRIGGER " <> quoted (sqlTriggerName sqlTriggerExec)
, sqlTriggerEvent <> " ON " <> quoted (schema, sqlTriggerTable)
, " EXECUTE PROCEDURE " <> quoted (schema, sqlTriggerExec) <> "()"
]
dropSqlTrigger :: Cascade -> SqlTrigger -> QueryS
dropSqlTrigger cascade SqlTrigger{..} schema = intercalateM " " [
"DROP TRIGGER IF EXISTS"
, quoted (sqlTriggerName sqlTriggerExec)
, "ON"
, quoted (schema, sqlTriggerTable)
, cascadeToQuery cascade
]
| Construct ' TriggerNames ' from the ' FunctionName 's they call
sqlTriggerName :: SqlFun -> TriggerName
sqlTriggerName SqlFun{sqlFunName = FunctionName nm} =
TriggerName (nm ++ "_trigger")
|
d3a2a0a33e528c072576a001637bc6ae6aa849eff4d5fb99de2fc5172c93134e | naoiwata/sicp | q2.57.scm | ;; @author naoiwata
SICP Chapter2
question 2.57
(add-load-path "." :relative)
(load "q2.56.scm")
; before
(print (deriv '(* x y (+ x 3)) 'x))
; redfine augend and multiplicand
(define (augend s)
(if (null? (cdddr s))
(caddr s)
(cons '+ (cddr s))))
(define (multiplicand s)
(if (null? (cdddr s))
(caddr s)
(cons '* (cddr s))))
; after
(print (deriv '(* x y (+ x 3)) 'x))
; END | null | https://raw.githubusercontent.com/naoiwata/sicp/7314136c5892de402015acfe4b9148a3558b1211/chapter2/q2.57.scm | scheme | @author naoiwata
before
redfine augend and multiplicand
after
END | SICP Chapter2
question 2.57
(add-load-path "." :relative)
(load "q2.56.scm")
(print (deriv '(* x y (+ x 3)) 'x))
(define (augend s)
(if (null? (cdddr s))
(caddr s)
(cons '+ (cddr s))))
(define (multiplicand s)
(if (null? (cdddr s))
(caddr s)
(cons '* (cddr s))))
(print (deriv '(* x y (+ x 3)) 'x))
|
72bd8237d24736ae3aa408aa1a96e288276b7761c414b2a032ac14867199c059 | techascent/tech.ml.dataset | zip.clj | (ns tech.v3.dataset.zip
"Load zip data. Zip files with a single file entry can be loaded with ->dataset. When
a zip file has multiple entries you have to call zipfile->dataset-seq."
(:require [tech.v3.dataset.io :as ds-io]
[tech.v3.io :as io]
[clojure.tools.logging :as log])
(:import [java.util.zip ZipInputStream ZipOutputStream ZipEntry]
[java.util Set HashSet]
[tech.v3.dataset NoCloseInputStream NoCloseOutputStream]))
(set! *warn-on-reflection* true)
(defmethod ds-io/data->dataset :zip
[data options]
(with-open [is (-> (apply io/input-stream data (apply concat (seq options)))
(ZipInputStream.))]
(let [zentry (.getNextEntry is)
ftype (-> (ds-io/str->file-info (.getName zentry))
(get :file-type))
retval (ds-io/data->dataset (NoCloseInputStream. is)
(assoc options :file-type ftype))]
(when (.getNextEntry is)
(log/warnf "Multiple entries found in zipfile"))
retval)))
(defmethod ds-io/dataset->data! :zip
[data output options]
(let [inner-name (.substring (str output) 0 (- (count output) 4))
ftype (-> (ds-io/str->file-info inner-name)
(get :file-type))]
(with-open [os (-> (apply io/output-stream! output (apply concat (seq options)))
(ZipOutputStream.))]
(.putNextEntry os (ZipEntry. inner-name))
(ds-io/dataset->data! data os (assoc options :file-type ftype)))))
(defn- load-zip-entry
[^ZipInputStream is options]
(try
(if-let [entry (.getNextEntry is)]
(let [ftype (-> (ds-io/str->file-info (.getName entry))
(get :file-type))]
(cons (ds-io/data->dataset (NoCloseInputStream. is)
(assoc options
:file-type ftype
:dataset-name (.getName entry)))
(lazy-seq (load-zip-entry is options))))
(do
(.close is)
nil))
(catch Exception e
(.close is)
(throw e))))
(defn zipfile->dataset-seq
"Load a zipfile attempting to load each zip entry."
([input options]
(let [is (-> (apply io/input-stream input (apply concat (seq options)))
(ZipInputStream.))]
(load-zip-entry is options)))
([input]
(zipfile->dataset-seq input nil)))
(defn- ds-name->string
^String [ds]
(let [nm (:name (meta ds))]
(if (or (symbol? nm) (keyword? nm))
(name nm)
(str nm))))
(defn- unique-name!
^String [ds ^Set used]
(let [nm (ds-name->string ds)
nm (if (.contains used nm )
(loop [idx 0]
(let [idx-nm (str nm "-" idx)]
(if (.contains used idx-nm)
(recur (inc idx))
idx-nm)))
nm)]
(.add used nm)
nm))
(defn dataset-seq->zipfile!
"Write a sequence of datasets to zipfiles. You can control the inner type with the
:file-type option which defaults to .tsv"
([output options ds-seq]
(let [fnames (HashSet.)
ftype (get options :file-type :tsv)
options (assoc options :file-type ftype)]
(with-open [os (-> (apply io/output-stream! output (apply concat (set options)))
(ZipOutputStream.))]
(doseq [ds ds-seq]
(.putNextEntry os (ZipEntry. (str (unique-name! ds fnames) "." (name ftype))))
(ds-io/dataset->data! ds (NoCloseOutputStream. os) options)))))
([output ds-seq]
(dataset-seq->zipfile! output nil ds-seq)))
| null | https://raw.githubusercontent.com/techascent/tech.ml.dataset/6fc44a715b4d1facc7c0bbbc73eb5512b1380ed0/src/tech/v3/dataset/zip.clj | clojure | (ns tech.v3.dataset.zip
"Load zip data. Zip files with a single file entry can be loaded with ->dataset. When
a zip file has multiple entries you have to call zipfile->dataset-seq."
(:require [tech.v3.dataset.io :as ds-io]
[tech.v3.io :as io]
[clojure.tools.logging :as log])
(:import [java.util.zip ZipInputStream ZipOutputStream ZipEntry]
[java.util Set HashSet]
[tech.v3.dataset NoCloseInputStream NoCloseOutputStream]))
(set! *warn-on-reflection* true)
(defmethod ds-io/data->dataset :zip
[data options]
(with-open [is (-> (apply io/input-stream data (apply concat (seq options)))
(ZipInputStream.))]
(let [zentry (.getNextEntry is)
ftype (-> (ds-io/str->file-info (.getName zentry))
(get :file-type))
retval (ds-io/data->dataset (NoCloseInputStream. is)
(assoc options :file-type ftype))]
(when (.getNextEntry is)
(log/warnf "Multiple entries found in zipfile"))
retval)))
(defmethod ds-io/dataset->data! :zip
[data output options]
(let [inner-name (.substring (str output) 0 (- (count output) 4))
ftype (-> (ds-io/str->file-info inner-name)
(get :file-type))]
(with-open [os (-> (apply io/output-stream! output (apply concat (seq options)))
(ZipOutputStream.))]
(.putNextEntry os (ZipEntry. inner-name))
(ds-io/dataset->data! data os (assoc options :file-type ftype)))))
(defn- load-zip-entry
[^ZipInputStream is options]
(try
(if-let [entry (.getNextEntry is)]
(let [ftype (-> (ds-io/str->file-info (.getName entry))
(get :file-type))]
(cons (ds-io/data->dataset (NoCloseInputStream. is)
(assoc options
:file-type ftype
:dataset-name (.getName entry)))
(lazy-seq (load-zip-entry is options))))
(do
(.close is)
nil))
(catch Exception e
(.close is)
(throw e))))
(defn zipfile->dataset-seq
"Load a zipfile attempting to load each zip entry."
([input options]
(let [is (-> (apply io/input-stream input (apply concat (seq options)))
(ZipInputStream.))]
(load-zip-entry is options)))
([input]
(zipfile->dataset-seq input nil)))
(defn- ds-name->string
^String [ds]
(let [nm (:name (meta ds))]
(if (or (symbol? nm) (keyword? nm))
(name nm)
(str nm))))
(defn- unique-name!
^String [ds ^Set used]
(let [nm (ds-name->string ds)
nm (if (.contains used nm )
(loop [idx 0]
(let [idx-nm (str nm "-" idx)]
(if (.contains used idx-nm)
(recur (inc idx))
idx-nm)))
nm)]
(.add used nm)
nm))
(defn dataset-seq->zipfile!
"Write a sequence of datasets to zipfiles. You can control the inner type with the
:file-type option which defaults to .tsv"
([output options ds-seq]
(let [fnames (HashSet.)
ftype (get options :file-type :tsv)
options (assoc options :file-type ftype)]
(with-open [os (-> (apply io/output-stream! output (apply concat (set options)))
(ZipOutputStream.))]
(doseq [ds ds-seq]
(.putNextEntry os (ZipEntry. (str (unique-name! ds fnames) "." (name ftype))))
(ds-io/dataset->data! ds (NoCloseOutputStream. os) options)))))
([output ds-seq]
(dataset-seq->zipfile! output nil ds-seq)))
|
|
2cd06dc0bc22ca1baa2b09ba55c86255f5144f179f8b253f21fc1dd53ab5b8ee | colis-anr/morbig | patternMatchingRecognizer.ml | (**************************************************************************)
(* -*- tuareg -*- *)
(* *)
Copyright ( C ) 2017 - 2021 , ,
.
(* *)
(* This is free software: you can redistribute it and/or modify it *)
under the terms of the GNU General Public License , version 3 .
(* *)
(* Additional terms apply, due to the reproduction of portions of *)
(* the POSIX standard. Please refer to the file COPYING for details. *)
(**************************************************************************)
open REBracketExpressionParser
open REBracketExpressionParser.MenhirInterpreter
open CST
*
This module implements a recognizer for pattern - matching as
specified in section 2.13 of the POSIX standard .
The main difficulty is the implementation of a parser for RE
bracket expressions whose specification is 9.3.5 of the POSIX
standard . The lexer can not be easily expressed by a sole ocamllex
specification because of some position - dependent lexical rules .
For this reason , we wrap the lexer generated by
{ ! } in a function that takes care of
these adhoc position - dependent rules .
Notice that we again use the incremental interface of Menhir but
this is not mandatory : a non incremental parser would work as
well .
This module implements a recognizer for pattern-matching as
specified in section 2.13 of the POSIX standard.
The main difficulty is the implementation of a parser for RE
bracket expressions whose specification is 9.3.5 of the POSIX
standard. The lexer cannot be easily expressed by a sole ocamllex
specification because of some position-dependent lexical rules.
For this reason, we wrap the lexer generated by
{!REBracketExpressionLexer} in a function that takes care of
these adhoc position-dependent rules.
Notice that we again use the incremental interface of Menhir but
this is not mandatory: a non incremental parser would work as
well.
*)
* [ ] is used to interpret some special
characters depending on the parsing context .
characters depending on the parsing context. *)
(** [recognize_re_bracket_expression s start] *)
let recognize_re_bracket_expression s start =
let module Prelexer : sig
val current_position : unit -> int
val lexing_position : unit -> Lexing.position
val next_token : unit -> token * Lexing.position * Lexing.position
val after_starting_hat : unit -> bool
val after_starting_bracket : unit -> bool
val just_before_ending_bracket : unit -> bool
val read_string : unit -> string
end = struct
let current_position = ref start
let next_char () =
if !current_position < String.length s then (
let c = s.[!current_position] in
incr current_position;
Some c
) else None
let eof_reached () =
!current_position >= String.length s
let lexbuf =
Lexing.from_function @@ fun b count ->
let rec aux i =
if i = count then count
else match next_char () with
| None -> i
| Some c -> Bytes.set b i c; aux (i + 1)
in
aux 0
let lookahead_buffer = Queue.create ()
let with_positions token =
(token, lexbuf.Lexing.lex_start_p, lexbuf.Lexing.lex_curr_p)
let lex () =
REBracketExpressionLexer.token lexbuf |> with_positions
let next_token () =
if Queue.is_empty lookahead_buffer then
lex ()
else if eof_reached () then
with_positions REBracketExpressionParser.EOF
else
Queue.pop lookahead_buffer
let read_string () =
String.sub s start (!current_position - start)
let current_position () =
start + lexbuf.Lexing.lex_start_p.pos_cnum
let lexing_position () = lexbuf.Lexing.lex_start_p
let after_starting_bracket () =
(lexing_position ()).pos_cnum = 1
let just_before_ending_bracket () =
(lexing_position ()).pos_cnum = String.length s - 2 - start
let after_starting_hat () =
(lexing_position ()).pos_cnum = 2 && s.[1] = '^'
end
in
specification :
META_CHAR One of the characters :
^
When found first in a bracket expression
-
When found anywhere but first ( after an initial ' ^ ' , if any ) or last in a
bracket expression , or as the ending range point in a range expression
]
When found anywhere but first ( after an initial ' ^ ' , if any ) in a
bracket expression
META_CHAR One of the characters:
^
When found first in a bracket expression
-
When found anywhere but first (after an initial '^', if any) or last in a
bracket expression, or as the ending range point in a range expression
]
When found anywhere but first (after an initial '^', if any) in a
bracket expression
*)
*
The specification phrasing is a bit ackward . We interpret it as a
definition for tokens HAT , MINUS and RBRACKET as well a definition
for META_CHAR which is supposed to be the union of these three tokens .
As a consequence , META_CHAR is better expressed as a non terminal
` meta_char ` . We decided to slightly change the POSIX standard grammar
in that direction because it seems to make more sense .
The specification phrasing is a bit ackward. We interpret it as a
definition for tokens HAT, MINUS and RBRACKET as well a definition
for META_CHAR which is supposed to be the union of these three tokens.
As a consequence, META_CHAR is better expressed as a non terminal
`meta_char`. We decided to slightly change the POSIX standard grammar
in that direction because it seems to make more sense.
*)
let next_token () =
let rewrite_token f =
let (token, p1, p2) = Prelexer.next_token () in
(f token, p1, p2)
in
rewrite_token (function
| HAT ->
if Prelexer.after_starting_bracket () then
HAT
else
by 2.13.1 , < circumflex > is < exclamation - mark > in the context of
shell .
shell. *)
COLL_ELEM_SINGLE '!'
| (COLL_ELEM_SINGLE '^') as token ->
if Prelexer.after_starting_bracket ()
&& Options.error_on_unspecified ()
then
let msg =
"Unquoted <circumflex> at the beginning of a bracket expression \
has an unspecified semantics."
in
raise (Errors.DuringLexing (Prelexer.lexing_position (), msg))
else
token
| (RBRACKET | MINUS) as token ->
let final_minus =
(token = MINUS) && (Prelexer.just_before_ending_bracket ())
in
if Prelexer.(after_starting_bracket ()
|| after_starting_hat ()
|| final_minus)
then
COLL_ELEM_SINGLE (if token = MINUS then '-' else ']')
else
token
| token ->
token)
in
let rec parse checkpoint =
match checkpoint with
| InputNeeded _ ->
parse (offer checkpoint (next_token ()))
| Accepted cst ->
Some (cst, Prelexer.read_string (), Prelexer.current_position ())
| Rejected ->
None
| _ ->
parse (resume checkpoint)
in
parse (Incremental.bracket_expression (Prelexer.lexing_position ()))
(** [process s] recognizes pattern-matching expressions inside [s]
returning the resulting stream of word components, in reverse
order. *)
let process s : (string * word_component) list =
let b = Buffer.create 31 in
let rec analyze output i =
let flush () =
if Buffer.length b > 0 then
let w = Buffer.contents b in
(w, WordLiteral w) :: output
else
output
in
let produce ?(next=i+1) char ast =
let output = flush () in
Buffer.clear b;
analyze ((char, ast) :: output) next
in
let push char =
Buffer.add_char b char;
analyze output (i + 1)
in
if i >= String.length s then
flush ()
else
match s.[i] with
| '?' -> produce "?" WordGlobAny
| '*' -> produce "*" WordGlobAll
| '[' -> begin match recognize_re_bracket_expression s i with
| Some (re_bracket_exp, rs, j) ->
produce rs (WordReBracketExpression re_bracket_exp) ~next:j
| None ->
push '['
end
| c -> push c
in
analyze [] 0 |> List.rev
| null | https://raw.githubusercontent.com/colis-anr/morbig/77c2ca402785979c4af351b412fe7be2d521838f/src/patternMatchingRecognizer.ml | ocaml | ************************************************************************
-*- tuareg -*-
This is free software: you can redistribute it and/or modify it
Additional terms apply, due to the reproduction of portions of
the POSIX standard. Please refer to the file COPYING for details.
************************************************************************
* [recognize_re_bracket_expression s start]
* [process s] recognizes pattern-matching expressions inside [s]
returning the resulting stream of word components, in reverse
order. | Copyright ( C ) 2017 - 2021 , ,
.
under the terms of the GNU General Public License , version 3 .
open REBracketExpressionParser
open REBracketExpressionParser.MenhirInterpreter
open CST
*
This module implements a recognizer for pattern - matching as
specified in section 2.13 of the POSIX standard .
The main difficulty is the implementation of a parser for RE
bracket expressions whose specification is 9.3.5 of the POSIX
standard . The lexer can not be easily expressed by a sole ocamllex
specification because of some position - dependent lexical rules .
For this reason , we wrap the lexer generated by
{ ! } in a function that takes care of
these adhoc position - dependent rules .
Notice that we again use the incremental interface of Menhir but
this is not mandatory : a non incremental parser would work as
well .
This module implements a recognizer for pattern-matching as
specified in section 2.13 of the POSIX standard.
The main difficulty is the implementation of a parser for RE
bracket expressions whose specification is 9.3.5 of the POSIX
standard. The lexer cannot be easily expressed by a sole ocamllex
specification because of some position-dependent lexical rules.
For this reason, we wrap the lexer generated by
{!REBracketExpressionLexer} in a function that takes care of
these adhoc position-dependent rules.
Notice that we again use the incremental interface of Menhir but
this is not mandatory: a non incremental parser would work as
well.
*)
* [ ] is used to interpret some special
characters depending on the parsing context .
characters depending on the parsing context. *)
let recognize_re_bracket_expression s start =
let module Prelexer : sig
val current_position : unit -> int
val lexing_position : unit -> Lexing.position
val next_token : unit -> token * Lexing.position * Lexing.position
val after_starting_hat : unit -> bool
val after_starting_bracket : unit -> bool
val just_before_ending_bracket : unit -> bool
val read_string : unit -> string
end = struct
let current_position = ref start
let next_char () =
if !current_position < String.length s then (
let c = s.[!current_position] in
incr current_position;
Some c
) else None
let eof_reached () =
!current_position >= String.length s
let lexbuf =
Lexing.from_function @@ fun b count ->
let rec aux i =
if i = count then count
else match next_char () with
| None -> i
| Some c -> Bytes.set b i c; aux (i + 1)
in
aux 0
let lookahead_buffer = Queue.create ()
let with_positions token =
(token, lexbuf.Lexing.lex_start_p, lexbuf.Lexing.lex_curr_p)
let lex () =
REBracketExpressionLexer.token lexbuf |> with_positions
let next_token () =
if Queue.is_empty lookahead_buffer then
lex ()
else if eof_reached () then
with_positions REBracketExpressionParser.EOF
else
Queue.pop lookahead_buffer
let read_string () =
String.sub s start (!current_position - start)
let current_position () =
start + lexbuf.Lexing.lex_start_p.pos_cnum
let lexing_position () = lexbuf.Lexing.lex_start_p
let after_starting_bracket () =
(lexing_position ()).pos_cnum = 1
let just_before_ending_bracket () =
(lexing_position ()).pos_cnum = String.length s - 2 - start
let after_starting_hat () =
(lexing_position ()).pos_cnum = 2 && s.[1] = '^'
end
in
specification :
META_CHAR One of the characters :
^
When found first in a bracket expression
-
When found anywhere but first ( after an initial ' ^ ' , if any ) or last in a
bracket expression , or as the ending range point in a range expression
]
When found anywhere but first ( after an initial ' ^ ' , if any ) in a
bracket expression
META_CHAR One of the characters:
^
When found first in a bracket expression
-
When found anywhere but first (after an initial '^', if any) or last in a
bracket expression, or as the ending range point in a range expression
]
When found anywhere but first (after an initial '^', if any) in a
bracket expression
*)
*
The specification phrasing is a bit ackward . We interpret it as a
definition for tokens HAT , MINUS and RBRACKET as well a definition
for META_CHAR which is supposed to be the union of these three tokens .
As a consequence , META_CHAR is better expressed as a non terminal
` meta_char ` . We decided to slightly change the POSIX standard grammar
in that direction because it seems to make more sense .
The specification phrasing is a bit ackward. We interpret it as a
definition for tokens HAT, MINUS and RBRACKET as well a definition
for META_CHAR which is supposed to be the union of these three tokens.
As a consequence, META_CHAR is better expressed as a non terminal
`meta_char`. We decided to slightly change the POSIX standard grammar
in that direction because it seems to make more sense.
*)
let next_token () =
let rewrite_token f =
let (token, p1, p2) = Prelexer.next_token () in
(f token, p1, p2)
in
rewrite_token (function
| HAT ->
if Prelexer.after_starting_bracket () then
HAT
else
by 2.13.1 , < circumflex > is < exclamation - mark > in the context of
shell .
shell. *)
COLL_ELEM_SINGLE '!'
| (COLL_ELEM_SINGLE '^') as token ->
if Prelexer.after_starting_bracket ()
&& Options.error_on_unspecified ()
then
let msg =
"Unquoted <circumflex> at the beginning of a bracket expression \
has an unspecified semantics."
in
raise (Errors.DuringLexing (Prelexer.lexing_position (), msg))
else
token
| (RBRACKET | MINUS) as token ->
let final_minus =
(token = MINUS) && (Prelexer.just_before_ending_bracket ())
in
if Prelexer.(after_starting_bracket ()
|| after_starting_hat ()
|| final_minus)
then
COLL_ELEM_SINGLE (if token = MINUS then '-' else ']')
else
token
| token ->
token)
in
let rec parse checkpoint =
match checkpoint with
| InputNeeded _ ->
parse (offer checkpoint (next_token ()))
| Accepted cst ->
Some (cst, Prelexer.read_string (), Prelexer.current_position ())
| Rejected ->
None
| _ ->
parse (resume checkpoint)
in
parse (Incremental.bracket_expression (Prelexer.lexing_position ()))
let process s : (string * word_component) list =
let b = Buffer.create 31 in
let rec analyze output i =
let flush () =
if Buffer.length b > 0 then
let w = Buffer.contents b in
(w, WordLiteral w) :: output
else
output
in
let produce ?(next=i+1) char ast =
let output = flush () in
Buffer.clear b;
analyze ((char, ast) :: output) next
in
let push char =
Buffer.add_char b char;
analyze output (i + 1)
in
if i >= String.length s then
flush ()
else
match s.[i] with
| '?' -> produce "?" WordGlobAny
| '*' -> produce "*" WordGlobAll
| '[' -> begin match recognize_re_bracket_expression s i with
| Some (re_bracket_exp, rs, j) ->
produce rs (WordReBracketExpression re_bracket_exp) ~next:j
| None ->
push '['
end
| c -> push c
in
analyze [] 0 |> List.rev
|
1abff4acd4486e9a03c7bb189f2e56d7557020f73008273a0b2fc775ad2852ec | namin/clpsmt-miniKanren | sign-domain.scm | (define s/declare-bito
(lambda (b)
(z/ `(declare-const ,b Bool))))
(define s/declareo
(lambda (s)
(z/ `(declare-const ,s (_ BitVec 3)))))
(define s/haso
(lambda (p)
(lambda (s b)
(z/assert `(= ,s (ite ,b (bvor ,s ,p) (bvand ,s (bvnot ,p))))))))
(define s/hasnto
(lambda (p)
(lambda (s b)
(z/assert `(= ,s (ite ,b (bvand ,s (bvnot ,p)) (bvor ,s ,p)))))))
(define s/chaso
(lambda (p)
(lambda (s)
(z/assert `(= ,s (bvor ,s ,p))))))
(define s/chasnto
(lambda (p)
(lambda (s)
(z/assert `(= ,s (bvand ,s (bvnot ,p)))))))
(define vec-neg 'bitvec-001)
(define s/has-nego (s/haso vec-neg))
(define s/hasnt-nego (s/hasnto vec-neg))
(define s/chas-nego (s/chaso vec-neg))
(define s/chasnt-nego (s/chasnto vec-neg))
(define vec-zero 'bitvec-010)
(define s/has-zeroo (s/haso vec-zero))
(define s/hasnt-zeroo (s/hasnto vec-zero))
(define s/chas-zeroo (s/chaso vec-zero))
(define s/chasnt-zeroo (s/chasnto vec-zero))
(define vec-pos 'bitvec-100)
(define s/has-poso (s/haso vec-pos))
(define s/hasnt-poso (s/hasnto vec-pos))
(define s/chas-poso (s/chaso vec-pos))
(define s/chasnt-poso (s/chasnto vec-pos))
(define vecs (list vec-neg vec-zero vec-pos))
(define s/iso
(lambda (p)
(lambda (s)
(z/assert `(= ,s ,p)))))
(define s/is-nego
(s/iso vec-neg))
(define s/is-zeroo
(s/iso vec-zero))
(define s/is-poso
(s/iso vec-pos))
(define s/uniono
(lambda (s1 s2 so)
(z/assert `(= (bvor ,s1 ,s2) ,so))))
(define s/is-bito
(lambda (b)
(conde
((z/assert `(= ,b ,vec-neg)))
((z/assert `(= ,b ,vec-zero)))
((z/assert `(= ,b ,vec-pos))))))
(define s/membero
(lambda (s b)
(fresh ()
(z/assert `(= (bvand ,s ,b) ,b))
(s/is-bito b))))
(define s/alphao
(lambda (n s)
(fresh ()
(conde
((z/assert `(< ,n 0))
(s/is-nego s))
((z/assert `(= ,n 0))
(s/is-zeroo s))
((z/assert `(> ,n 0))
(s/is-poso s))))))
(define s/z3-alphao
(lambda (n s)
(z/assert `(= ,s (ite (> ,n 0) ,vec-pos (ite (= ,n 0) ,vec-zero ,vec-neg))))))
;; For example,
{ −,0}⊕{−}={− } and { −}⊕{+}={−,0,+ } .
;; {−}⊗{+,0}={−,0} and {−,+}⊗{0}={0}
(define s/plus-alphao
(lambda (s1 s2 so)
(conde
((s/is-zeroo s1)
(z/assert `(= ,so ,s2)))
((s/is-zeroo s2)
(z/assert `(= ,so ,s1)))
((s/is-nego s1)
(s/is-nego s2)
(s/is-nego so))
((s/is-poso s1)
(s/is-poso s2)
(s/is-poso so))
((s/is-nego s1)
(s/is-poso s2)
(z/assert `(= ,so bitvec-111)))
((s/is-poso s1)
(s/is-nego s2)
(z/assert `(= ,so bitvec-111))))))
(define s/containso
(lambda (s1 s2)
(z/assert `(= (bvor ,s1 ,s2) ,s1))))
(define s/pluso
(lambda (s1 s2 so)
(fresh ()
(conde ((s/chas-zeroo s1)
(s/containso so s2))
((s/chasnt-zeroo s1)))
(conde ((s/chas-zeroo s2)
(s/containso so s1))
((s/chasnt-zeroo s2)))
(conde ((s/chas-nego s1)
(s/chas-nego s2)
(s/chas-nego so))
((s/chasnt-nego s1))
((s/chasnt-nego s2)))
(conde ((s/chas-poso s1)
(s/chas-poso s2)
(s/chas-poso so))
((s/chasnt-poso s1))
((s/chasnt-poso s2)))
(conde ((s/chas-nego s1)
(s/chas-poso s2)
(z/assert `(= ,so bitvec-111)))
((s/chasnt-nego s1))
((s/chasnt-poso s2)))
(conde ((s/chas-poso s1)
(s/chas-nego s2)
(z/assert `(= ,so bitvec-111)))
((s/chasnt-poso s1))
((s/chasnt-nego s2))))))
(define (plus-alpha s1 s2)
(define (from a b)
(and (eq? a s1) (eq? b s2)))
(define (set . xs)
xs)
(cond
[(from '- '-) (set '-)]
[(from '- 0) (set '-)]
[(from '- '+) (set '- '0 '+)]
[(from '0 s2) (set s2)]
[(from '+ '-) (set '- '0 '+)]
[(from '+ 0) (set '+)]
[(from '+ '+) (set '+)]))
(define (times-alpha s1 s2)
(define (from a b)
(and (eq? a s1) (eq? b s2)))
(define (set . xs)
xs)
(cond
[(from '- '-) (set '+)]
[(from '- '0) (set '0)]
[(from '- '+) (set '-)]
[(from '0 s2) (set '0)]
[(from '+ '-) (set '-)]
[(from '+ 0) (set '0)]
[(from '+ '+) (set '+)]))
(define (sub1-alpha s1)
(define (from a)
(eq? a s1))
(define (set . xs)
xs)
(cond
[(from '-) (set '-)]
[(from '0) (set '0)]
[(from '+) (set '0 '+)]))
(define to-bitvec
(lambda (s)
(string->symbol
(string-append
"bitvec-"
(if (memq '+ s) "1" "0")
(if (memq '0 s) "1" "0")
(if (memq '- s) "1" "0")))))
(define flatten
(lambda (xs)
(cond ((null? xs) xs)
((atom? xs) (list xs))
(else (append (flatten (car xs))
(flatten (cdr xs)))))))
(define op-abstract
(lambda (op)
(lambda (s1 s2)
(to-bitvec
(flatten
(map
(lambda (b1)
(map
(lambda (b2)
(op b1 b2))
s2))
s1))))))
(define plus-abstract (op-abstract plus-alpha))
(define times-abstract (op-abstract times-alpha))
(define op1-abstract
(lambda (op)
(lambda (s1)
(to-bitvec
(flatten
(map (lambda (b1) (op b1)) s1))))))
(define sub1-abstract (op1-abstract sub1-alpha))
(define (comb xs)
(if (null? xs) '(())
(let ((r (comb (cdr xs))))
(append r (map (lambda (s) (cons (car xs) s)) r)))))
(define (op-table op)
(let ((r (comb '(- 0 +))))
(apply
append
(map
(lambda (s1)
(map
(lambda (s2)
(list (to-bitvec s1) (to-bitvec s2)
(op s1 s2)))
r))
r))))
(define (op1-table op)
(let ((r (comb '(- 0 +))))
(map
(lambda (s1)
(list (to-bitvec s1)
(op s1)))
r)))
(define s/op-tableo
(lambda (table)
(lambda (s1 s2 so)
(define itero
(lambda (es)
(if (null? es)
fail
(let ((e (car es)))
(conde
((z/assert `(= ,(car e) ,s1))
(z/assert `(= ,(cadr e) ,s2))
(z/assert `(= ,(caddr e) ,so)))
((z/assert `(or (not (= ,(car e) ,s1))
(not (= ,(cadr e) ,s2))))
(itero (cdr es))))))))
(itero table))))
(define s/plus-tableo (s/op-tableo (op-table plus-abstract)))
(define s/times-tableo (s/op-tableo (op-table times-abstract)))
(define s/z3-op-tableo
(lambda (table)
(lambda (s1 s2 so)
(define iter
(lambda (es)
(let ((e (car es)))
(if (null? (cdr es))
(caddr e)
`(ite (and (= ,(car e) ,s1)
(= ,(cadr e) ,s2))
,(caddr e)
,(iter (cdr es)))))))
(z/assert `(= ,so ,(iter table))))))
(define s/z3-plus-tableo (s/z3-op-tableo (op-table plus-abstract)))
(define s/z3-times-tableo (s/z3-op-tableo (op-table times-abstract)))
(define s/z3-op1-tableo
(lambda (table)
(lambda (s1 so)
(define iter
(lambda (es)
(let ((e (car es)))
(if (null? (cdr es))
(cadr e)
`(ite (= ,(car e) ,s1)
,(cadr e)
,(iter (cdr es)))))))
(z/assert `(= ,so ,(iter table))))))
(define s/z3-sub1-tableo (s/z3-op1-tableo (op1-table sub1-abstract)))
| null | https://raw.githubusercontent.com/namin/clpsmt-miniKanren/4fa74fb973c95b7913f0e0239852f18a23073ccc/sign-domain.scm | scheme | For example,
{−}⊗{+,0}={−,0} and {−,+}⊗{0}={0} | (define s/declare-bito
(lambda (b)
(z/ `(declare-const ,b Bool))))
(define s/declareo
(lambda (s)
(z/ `(declare-const ,s (_ BitVec 3)))))
(define s/haso
(lambda (p)
(lambda (s b)
(z/assert `(= ,s (ite ,b (bvor ,s ,p) (bvand ,s (bvnot ,p))))))))
(define s/hasnto
(lambda (p)
(lambda (s b)
(z/assert `(= ,s (ite ,b (bvand ,s (bvnot ,p)) (bvor ,s ,p)))))))
(define s/chaso
(lambda (p)
(lambda (s)
(z/assert `(= ,s (bvor ,s ,p))))))
(define s/chasnto
(lambda (p)
(lambda (s)
(z/assert `(= ,s (bvand ,s (bvnot ,p)))))))
(define vec-neg 'bitvec-001)
(define s/has-nego (s/haso vec-neg))
(define s/hasnt-nego (s/hasnto vec-neg))
(define s/chas-nego (s/chaso vec-neg))
(define s/chasnt-nego (s/chasnto vec-neg))
(define vec-zero 'bitvec-010)
(define s/has-zeroo (s/haso vec-zero))
(define s/hasnt-zeroo (s/hasnto vec-zero))
(define s/chas-zeroo (s/chaso vec-zero))
(define s/chasnt-zeroo (s/chasnto vec-zero))
(define vec-pos 'bitvec-100)
(define s/has-poso (s/haso vec-pos))
(define s/hasnt-poso (s/hasnto vec-pos))
(define s/chas-poso (s/chaso vec-pos))
(define s/chasnt-poso (s/chasnto vec-pos))
(define vecs (list vec-neg vec-zero vec-pos))
(define s/iso
(lambda (p)
(lambda (s)
(z/assert `(= ,s ,p)))))
(define s/is-nego
(s/iso vec-neg))
(define s/is-zeroo
(s/iso vec-zero))
(define s/is-poso
(s/iso vec-pos))
(define s/uniono
(lambda (s1 s2 so)
(z/assert `(= (bvor ,s1 ,s2) ,so))))
(define s/is-bito
(lambda (b)
(conde
((z/assert `(= ,b ,vec-neg)))
((z/assert `(= ,b ,vec-zero)))
((z/assert `(= ,b ,vec-pos))))))
(define s/membero
(lambda (s b)
(fresh ()
(z/assert `(= (bvand ,s ,b) ,b))
(s/is-bito b))))
(define s/alphao
(lambda (n s)
(fresh ()
(conde
((z/assert `(< ,n 0))
(s/is-nego s))
((z/assert `(= ,n 0))
(s/is-zeroo s))
((z/assert `(> ,n 0))
(s/is-poso s))))))
(define s/z3-alphao
(lambda (n s)
(z/assert `(= ,s (ite (> ,n 0) ,vec-pos (ite (= ,n 0) ,vec-zero ,vec-neg))))))
{ −,0}⊕{−}={− } and { −}⊕{+}={−,0,+ } .
(define s/plus-alphao
(lambda (s1 s2 so)
(conde
((s/is-zeroo s1)
(z/assert `(= ,so ,s2)))
((s/is-zeroo s2)
(z/assert `(= ,so ,s1)))
((s/is-nego s1)
(s/is-nego s2)
(s/is-nego so))
((s/is-poso s1)
(s/is-poso s2)
(s/is-poso so))
((s/is-nego s1)
(s/is-poso s2)
(z/assert `(= ,so bitvec-111)))
((s/is-poso s1)
(s/is-nego s2)
(z/assert `(= ,so bitvec-111))))))
(define s/containso
(lambda (s1 s2)
(z/assert `(= (bvor ,s1 ,s2) ,s1))))
(define s/pluso
(lambda (s1 s2 so)
(fresh ()
(conde ((s/chas-zeroo s1)
(s/containso so s2))
((s/chasnt-zeroo s1)))
(conde ((s/chas-zeroo s2)
(s/containso so s1))
((s/chasnt-zeroo s2)))
(conde ((s/chas-nego s1)
(s/chas-nego s2)
(s/chas-nego so))
((s/chasnt-nego s1))
((s/chasnt-nego s2)))
(conde ((s/chas-poso s1)
(s/chas-poso s2)
(s/chas-poso so))
((s/chasnt-poso s1))
((s/chasnt-poso s2)))
(conde ((s/chas-nego s1)
(s/chas-poso s2)
(z/assert `(= ,so bitvec-111)))
((s/chasnt-nego s1))
((s/chasnt-poso s2)))
(conde ((s/chas-poso s1)
(s/chas-nego s2)
(z/assert `(= ,so bitvec-111)))
((s/chasnt-poso s1))
((s/chasnt-nego s2))))))
(define (plus-alpha s1 s2)
(define (from a b)
(and (eq? a s1) (eq? b s2)))
(define (set . xs)
xs)
(cond
[(from '- '-) (set '-)]
[(from '- 0) (set '-)]
[(from '- '+) (set '- '0 '+)]
[(from '0 s2) (set s2)]
[(from '+ '-) (set '- '0 '+)]
[(from '+ 0) (set '+)]
[(from '+ '+) (set '+)]))
(define (times-alpha s1 s2)
(define (from a b)
(and (eq? a s1) (eq? b s2)))
(define (set . xs)
xs)
(cond
[(from '- '-) (set '+)]
[(from '- '0) (set '0)]
[(from '- '+) (set '-)]
[(from '0 s2) (set '0)]
[(from '+ '-) (set '-)]
[(from '+ 0) (set '0)]
[(from '+ '+) (set '+)]))
(define (sub1-alpha s1)
(define (from a)
(eq? a s1))
(define (set . xs)
xs)
(cond
[(from '-) (set '-)]
[(from '0) (set '0)]
[(from '+) (set '0 '+)]))
(define to-bitvec
(lambda (s)
(string->symbol
(string-append
"bitvec-"
(if (memq '+ s) "1" "0")
(if (memq '0 s) "1" "0")
(if (memq '- s) "1" "0")))))
(define flatten
(lambda (xs)
(cond ((null? xs) xs)
((atom? xs) (list xs))
(else (append (flatten (car xs))
(flatten (cdr xs)))))))
(define op-abstract
(lambda (op)
(lambda (s1 s2)
(to-bitvec
(flatten
(map
(lambda (b1)
(map
(lambda (b2)
(op b1 b2))
s2))
s1))))))
(define plus-abstract (op-abstract plus-alpha))
(define times-abstract (op-abstract times-alpha))
(define op1-abstract
(lambda (op)
(lambda (s1)
(to-bitvec
(flatten
(map (lambda (b1) (op b1)) s1))))))
(define sub1-abstract (op1-abstract sub1-alpha))
(define (comb xs)
(if (null? xs) '(())
(let ((r (comb (cdr xs))))
(append r (map (lambda (s) (cons (car xs) s)) r)))))
(define (op-table op)
(let ((r (comb '(- 0 +))))
(apply
append
(map
(lambda (s1)
(map
(lambda (s2)
(list (to-bitvec s1) (to-bitvec s2)
(op s1 s2)))
r))
r))))
(define (op1-table op)
(let ((r (comb '(- 0 +))))
(map
(lambda (s1)
(list (to-bitvec s1)
(op s1)))
r)))
(define s/op-tableo
(lambda (table)
(lambda (s1 s2 so)
(define itero
(lambda (es)
(if (null? es)
fail
(let ((e (car es)))
(conde
((z/assert `(= ,(car e) ,s1))
(z/assert `(= ,(cadr e) ,s2))
(z/assert `(= ,(caddr e) ,so)))
((z/assert `(or (not (= ,(car e) ,s1))
(not (= ,(cadr e) ,s2))))
(itero (cdr es))))))))
(itero table))))
(define s/plus-tableo (s/op-tableo (op-table plus-abstract)))
(define s/times-tableo (s/op-tableo (op-table times-abstract)))
(define s/z3-op-tableo
(lambda (table)
(lambda (s1 s2 so)
(define iter
(lambda (es)
(let ((e (car es)))
(if (null? (cdr es))
(caddr e)
`(ite (and (= ,(car e) ,s1)
(= ,(cadr e) ,s2))
,(caddr e)
,(iter (cdr es)))))))
(z/assert `(= ,so ,(iter table))))))
(define s/z3-plus-tableo (s/z3-op-tableo (op-table plus-abstract)))
(define s/z3-times-tableo (s/z3-op-tableo (op-table times-abstract)))
(define s/z3-op1-tableo
(lambda (table)
(lambda (s1 so)
(define iter
(lambda (es)
(let ((e (car es)))
(if (null? (cdr es))
(cadr e)
`(ite (= ,(car e) ,s1)
,(cadr e)
,(iter (cdr es)))))))
(z/assert `(= ,so ,(iter table))))))
(define s/z3-sub1-tableo (s/z3-op1-tableo (op1-table sub1-abstract)))
|
e04195dde272fe0d70160be21d4b4e5f9dc40b3a64f037a7975bdc118609483e | RefactoringTools/HaRe | RmDecl4.hs | # LANGUAGE FlexibleContexts #
module RmDecl4 where
Remove first declaration from a where clause , rest should still be indented
ff y = y + zz ++ xx
where
zz = 1
xx = 2
EOF
| null | https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/test/testdata/RmDecl4.hs | haskell | # LANGUAGE FlexibleContexts #
module RmDecl4 where
Remove first declaration from a where clause , rest should still be indented
ff y = y + zz ++ xx
where
zz = 1
xx = 2
EOF
|
|
c2a4d8004a22d74d9a1c55cc0dbd3688b205216a6285216299a020fab5825f57 | nikita-volkov/rerebase | Lex.hs | module Text.Read.Lex
(
module Rebase.Text.Read.Lex
)
where
import Rebase.Text.Read.Lex
| null | https://raw.githubusercontent.com/nikita-volkov/rerebase/25895e6d8b0c515c912c509ad8dd8868780a74b6/library/Text/Read/Lex.hs | haskell | module Text.Read.Lex
(
module Rebase.Text.Read.Lex
)
where
import Rebase.Text.Read.Lex
|
|
eff73c28069b28232bc6c2a2014c195c8ee405621de2c2579f52f6139bc87a5a | djblue/portal | user.clj | (ns user
(:require [clojure.datafy :as d]
[clojure.instant :as i]
[portal.api :as p]
[taoensso.timbre :as log]))
(defn log->portal [{:keys [level ?err msg_ timestamp_ ?ns-str ?file context ?line]}]
(merge
(when ?err
{:error (d/datafy ?err)})
(when-let [ts (force timestamp_)]
{:time (i/read-instant-date ts)})
{:level level
:ns (symbol (or ?ns-str ?file "?"))
:line (or ?line 1)
:column 1
:result (force msg_)
:runtime :clj}
context))
(defonce logs (atom '()))
(defn log
"Accumulate a rolling log of 100 entries."
[log]
(swap! logs
(fn [logs]
(take 100 (conj logs (log->portal log))))))
(defn setup []
(reset! logs '())
(log/merge-config!
{:appenders
{:memory {:enabled? true :fn log}}}))
(defn open []
(p/open {:window-title "Logs Viewer" :value logs}))
(comment
(log/info "my info log")
(log/error (ex-info "my exception" {:hello :world}) "my error log")
(log/with-context+
{:runtime :cljs}
(log/info "my cljs log")))
| null | https://raw.githubusercontent.com/djblue/portal/0afc0624b5dbaebd46d2c11abb10bb4f0d5fbee6/examples/timbre/src/user.clj | clojure | (ns user
(:require [clojure.datafy :as d]
[clojure.instant :as i]
[portal.api :as p]
[taoensso.timbre :as log]))
(defn log->portal [{:keys [level ?err msg_ timestamp_ ?ns-str ?file context ?line]}]
(merge
(when ?err
{:error (d/datafy ?err)})
(when-let [ts (force timestamp_)]
{:time (i/read-instant-date ts)})
{:level level
:ns (symbol (or ?ns-str ?file "?"))
:line (or ?line 1)
:column 1
:result (force msg_)
:runtime :clj}
context))
(defonce logs (atom '()))
(defn log
"Accumulate a rolling log of 100 entries."
[log]
(swap! logs
(fn [logs]
(take 100 (conj logs (log->portal log))))))
(defn setup []
(reset! logs '())
(log/merge-config!
{:appenders
{:memory {:enabled? true :fn log}}}))
(defn open []
(p/open {:window-title "Logs Viewer" :value logs}))
(comment
(log/info "my info log")
(log/error (ex-info "my exception" {:hello :world}) "my error log")
(log/with-context+
{:runtime :cljs}
(log/info "my cljs log")))
|
|
a01dcccd47f8cd4e39958e4f3b4a610466e0a77c680654237f0213a5519380cc | janestreet/zstandard | explicit_dependencies_unignored.ml | (*_ Generated by ${ROOT}/bin/gen-explicit-dependencies.sh *)
module _ = Zstd_c
| null | https://raw.githubusercontent.com/janestreet/zstandard/8233812546164fbe3d67f4fe02b57f8bec5288d7/src/explicit_dependencies_unignored.ml | ocaml | _ Generated by ${ROOT}/bin/gen-explicit-dependencies.sh | module _ = Zstd_c
|
4cfb6236b84b44d652db6bcbdfdf470efa5782cd6e5be7e39a3ad4f1edddf4e0 | agentm/project-m36 | Base.hs | # LANGUAGE CPP #
module TutorialD.Interpreter.Import.Base where
import ProjectM36.Base
import ProjectM36.Error
import Text.URI (URI)
import Data.Text (Text)
#if __GLASGOW_HASKELL__ < 804
import Data.Monoid
#endif
-- | import data into a relation variable
data RelVarDataImportOperator = RelVarDataImportOperator RelVarName FilePath (RelVarName -> TypeConstructorMapping -> Attributes -> FilePath -> IO (Either RelationalError DatabaseContextExpr))
instance Show RelVarDataImportOperator where
show (RelVarDataImportOperator rv path _) = "RelVarDataImportOperator " <> show rv <> " " <> path
type HashVerification = Maybe Text
-- | import data into a database context
data DatabaseContextDataImportOperator = DatabaseContextDataImportOperator URI HashVerification (URI -> HashVerification -> IO (Either RelationalError DatabaseContextExpr))
instance Show DatabaseContextDataImportOperator where
show (DatabaseContextDataImportOperator uri hash _) =
"DatabaseContextDataImportOperator " <> show uri <> " " <> show hash
-- perhaps create a structure to import a whole transaction graph section in the future
evalRelVarDataImportOperator :: RelVarDataImportOperator -> TypeConstructorMapping -> Attributes -> IO (Either RelationalError DatabaseContextExpr)
evalRelVarDataImportOperator (RelVarDataImportOperator relVarName path importFunc) tConsMap attrs = importFunc relVarName tConsMap attrs path
evalDatabaseContextDataImportOperator :: DatabaseContextDataImportOperator -> IO (Either RelationalError DatabaseContextExpr)
evalDatabaseContextDataImportOperator (DatabaseContextDataImportOperator uri hash importFunc) = importFunc uri hash
| null | https://raw.githubusercontent.com/agentm/project-m36/57a75b35e84bebf0945db6dae53350fda83f24b6/src/bin/TutorialD/Interpreter/Import/Base.hs | haskell | | import data into a relation variable
| import data into a database context
perhaps create a structure to import a whole transaction graph section in the future | # LANGUAGE CPP #
module TutorialD.Interpreter.Import.Base where
import ProjectM36.Base
import ProjectM36.Error
import Text.URI (URI)
import Data.Text (Text)
#if __GLASGOW_HASKELL__ < 804
import Data.Monoid
#endif
data RelVarDataImportOperator = RelVarDataImportOperator RelVarName FilePath (RelVarName -> TypeConstructorMapping -> Attributes -> FilePath -> IO (Either RelationalError DatabaseContextExpr))
instance Show RelVarDataImportOperator where
show (RelVarDataImportOperator rv path _) = "RelVarDataImportOperator " <> show rv <> " " <> path
type HashVerification = Maybe Text
data DatabaseContextDataImportOperator = DatabaseContextDataImportOperator URI HashVerification (URI -> HashVerification -> IO (Either RelationalError DatabaseContextExpr))
instance Show DatabaseContextDataImportOperator where
show (DatabaseContextDataImportOperator uri hash _) =
"DatabaseContextDataImportOperator " <> show uri <> " " <> show hash
evalRelVarDataImportOperator :: RelVarDataImportOperator -> TypeConstructorMapping -> Attributes -> IO (Either RelationalError DatabaseContextExpr)
evalRelVarDataImportOperator (RelVarDataImportOperator relVarName path importFunc) tConsMap attrs = importFunc relVarName tConsMap attrs path
evalDatabaseContextDataImportOperator :: DatabaseContextDataImportOperator -> IO (Either RelationalError DatabaseContextExpr)
evalDatabaseContextDataImportOperator (DatabaseContextDataImportOperator uri hash importFunc) = importFunc uri hash
|
7da564d029771e5f9f9af1b41b5dd035aba85cd724eb5573ff7a0de774957852 | donut-party/system | 02.clj | (ns tutorial.02
"Local refs"
(:require
[donut.system :as ds]
[ring.adapter.jetty :as rj]))
_ refs _ allow one component 's signal handlers to receive another component
;; instance as an argument. This is a form of dependency injection, and it's how
;; you let the components in a system use each other.
;;
;; For example, let's say you want your http server component to receive its
;; `handler` as an argument. The example below shows how you would do that.
;;
;; The `:conf` for `[:http :server]` contains `{:handler (ds/ref :handler)}`.
;; (ds/ref :component-name) returns a _local ref_, a value that represents a
;; reference to a component in the same group. `:server` and `:req-handler` are
;; in the same group.
;;
;; When `:server`'s `:start` signal is called, it will receive the _instance_
for ` : req - handler ` in its first argument as part of its conf .
;;
;; donut.system handles starting components in the correct order: if Component A
;; refers to Component B, then Component B is started before Component A. This
;; ordering is reversed for the `:stop` signal.
;;
;; There are many reasons why you might want to decompose your components like
this . In this example , one reason to break out the request handler is so that
;; you can retrieve it in tests.
(def system
{::ds/defs
{:http
{:server {:start (fn [{:keys [port req-handler]} _ _]
(rj/run-jetty req-handler {:port port
:join? false}))
:stop (fn [_ instance _]
(.stop instance))
:conf {:port 9000
:req-handler (ds/ref :req-handler)}}
:req-handler {:start (fn [_ _ _]
(fn handler [_] {:status 200
:body "hello!"}))}}}})
(comment
(def running-system (ds/signal system :start))
(ds/signal running-system :stop)
)
| null | https://raw.githubusercontent.com/donut-party/system/96cc6036e245c248a83bd24c877ab1adc7c50515/tutorial/src/tutorial/02.clj | clojure | instance as an argument. This is a form of dependency injection, and it's how
you let the components in a system use each other.
For example, let's say you want your http server component to receive its
`handler` as an argument. The example below shows how you would do that.
The `:conf` for `[:http :server]` contains `{:handler (ds/ref :handler)}`.
(ds/ref :component-name) returns a _local ref_, a value that represents a
reference to a component in the same group. `:server` and `:req-handler` are
in the same group.
When `:server`'s `:start` signal is called, it will receive the _instance_
donut.system handles starting components in the correct order: if Component A
refers to Component B, then Component B is started before Component A. This
ordering is reversed for the `:stop` signal.
There are many reasons why you might want to decompose your components like
you can retrieve it in tests. | (ns tutorial.02
"Local refs"
(:require
[donut.system :as ds]
[ring.adapter.jetty :as rj]))
_ refs _ allow one component 's signal handlers to receive another component
for ` : req - handler ` in its first argument as part of its conf .
this . In this example , one reason to break out the request handler is so that
(def system
{::ds/defs
{:http
{:server {:start (fn [{:keys [port req-handler]} _ _]
(rj/run-jetty req-handler {:port port
:join? false}))
:stop (fn [_ instance _]
(.stop instance))
:conf {:port 9000
:req-handler (ds/ref :req-handler)}}
:req-handler {:start (fn [_ _ _]
(fn handler [_] {:status 200
:body "hello!"}))}}}})
(comment
(def running-system (ds/signal system :start))
(ds/signal running-system :stop)
)
|
da0d5f57980a8d73fd500753944d0ab2805c70a42667036aaff4531bc96bbe6e | bobzhang/fan | big2.ml |
let f a c =
a.{1,2,3} <- c
let f a b d e f c = begin
a.{1,2,3,4,5}<-c;
a.{1,2,3,4,5};
b.{1,2,3,4}<-c;
b.{1,2,3,4};
d.{1,2,3}<-c;
d.{1,2,3};
e.{1,2}<-c;
e.{1,2};
f.{1}<-c;
f.{1}
end
| null | https://raw.githubusercontent.com/bobzhang/fan/7ed527d96c5a006da43d3813f32ad8a5baa31b7f/src/todoml/test/printer/big2.ml | ocaml |
let f a c =
a.{1,2,3} <- c
let f a b d e f c = begin
a.{1,2,3,4,5}<-c;
a.{1,2,3,4,5};
b.{1,2,3,4}<-c;
b.{1,2,3,4};
d.{1,2,3}<-c;
d.{1,2,3};
e.{1,2}<-c;
e.{1,2};
f.{1}<-c;
f.{1}
end
|
|
4d4143f139b95d047e8dc0985583cbc14e35a5dbb6458f793ba36dfaef1e5876 | jacquev6/General | InFile.ml | module OCSP = OCamlStandard.Pervasives
type t = OCSP.in_channel
let seek x ~pos =
OCSP.LargeFile.seek_in x pos
let pos = OCSP.LargeFile.pos_in
let size = OCSP.LargeFile.in_channel_length
let channel = identity
let with_file s ~f =
let file = OCSP.open_in s in
try
let r = f file in
OCSP.close_in file;
r
with
| ex -> OCSP.close_in file; Exception.raise ex
let with_channel s ~f =
with_file s ~f:(f % channel)
| null | https://raw.githubusercontent.com/jacquev6/General/5237123668e939c0cb83aa3e1c4756473336bc7e/src/Implementation/InFile.ml | ocaml | module OCSP = OCamlStandard.Pervasives
type t = OCSP.in_channel
let seek x ~pos =
OCSP.LargeFile.seek_in x pos
let pos = OCSP.LargeFile.pos_in
let size = OCSP.LargeFile.in_channel_length
let channel = identity
let with_file s ~f =
let file = OCSP.open_in s in
try
let r = f file in
OCSP.close_in file;
r
with
| ex -> OCSP.close_in file; Exception.raise ex
let with_channel s ~f =
with_file s ~f:(f % channel)
|
|
b2f1c242ab3e555d622ecd8f8eb19506e054600a691ce5426c91d757c5f33d50 | codinuum/cca | fact_base.ml |
Copyright 2012 - 2020 Codinuum Software Lab < >
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 .
Copyright 2012-2020 Codinuum Software Lab <>
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.
*)
(* fact_base.ml *)
let mkver vkind ver = Triple.make_version_entity (vkind, ver)
let mklit = Triple.make_literal
let p_is_a = Triple.p_is_a
let p_version = Triple.p_version
let p_file_location = Triple.p_file_location
class virtual fact_buffer_tbl = object (self)
method virtual find : string -> Triple.buffer
method virtual add : string -> Triple.buffer -> unit
method virtual iter : (string -> Triple.buffer -> unit) -> unit
end
class separate_fact_buffer_tbl = object (self)
inherit fact_buffer_tbl
val tbl = Hashtbl.create 0
method find key = Hashtbl.find tbl key
method add key buf = Hashtbl.add tbl key buf
method iter f = Hashtbl.iter f tbl
end
class unified_fact_buffer_tbl = object (self)
inherit fact_buffer_tbl
val mutable _buf = Triple.dummy_buffer
method find key = _buf
method add key buf = _buf <- buf
method iter f = f "" _buf
end
let _apply_to_vkey_v vkind ver =
if not (Entity.vkind_is_unknown vkind) && ver <> "" then
let vkey = Entity.mkvkey vkind ver in
let v = mkver vkind ver in
fun f -> f vkind vkey v
else
fun f -> ()
let create_fact_buf
options
?(acquire_lock=(fun () -> ()))
?(fact_file_path="")
?(cache_name="")
~into_virtuoso
~into_directory
cache_path
=
let fact_file_path =
if fact_file_path = "" then
Filename.concat cache_path Stat.fact_file_name
else
fact_file_path
in
let cache_name =
if cache_name = "" then
Cache.get_cache_name options cache_path
else
cache_name
in
let buf =
if into_virtuoso then begin
DEBUG_MSG "preparing fact buffer for virtuoso...";
assert (not into_directory);
(*
try
*)
acquire_lock();
new Triple.buffer_virtuoso options
(*
with
| Triple.Lock_failed -> Triple.dummy_buffer
*)
end
else if into_directory then begin
DEBUG_MSG "preparing fact buffer for directory...";
(*
try
*)
acquire_lock();
new Triple.buffer_directory options cache_name
(*
with
| Triple.Lock_failed -> Triple.dummy_buffer
*)
end
else begin
DEBUG_MSG "preparing fact buffer...";
try
new Triple.buffer ~overwrite:false options fact_file_path
with
| Triple.File_exists s ->
Xprint.warning "file exists: \"%s\"" s;
Triple.dummy_buffer
end
in
DEBUG_MSG "done.";
buf
class fact_store ?(lock=true) options cache_path =
let fact_file_path =
Filename.concat cache_path Stat.fact_file_name
in
let _ = DEBUG_MSG "cache_path: %s" cache_path in
let _ = DEBUG_MSG "fact_file_path: %s" fact_file_path in
let cache_name = Cache.get_cache_name options cache_path in
let lock_fd = ref None in
let acquire_lock() =
if lock then
let fd = Triple.lock_fact cache_path in
lock_fd := Some fd
in
let into_virtuoso = options#fact_into_virtuoso <> "" in
let into_directory = options#fact_into_directory <> "" in
object (self)
method id = ""
method warning_msg : 'a. ('a, unit, string, unit) format4 -> 'a =
Xprint.warning ~head:(if self#id = "" then "" else "["^self#id^"]") ~out:stderr
method verbose_msg : 'a. ('a, unit, string, unit) format4 -> 'a =
Xprint.verbose options#verbose_flag
val fact_buf =
create_fact_buf
options
~acquire_lock ~fact_file_path ~into_virtuoso ~into_directory
cache_path
val a_fact_buf_tbl =
if into_virtuoso || into_directory then begin
let tbl = new unified_fact_buffer_tbl in
if into_virtuoso then
tbl#add "" (new Triple.buffer_virtuoso options)
else if into_directory then
tbl#add "" (new Triple.buffer_directory options cache_name);
tbl
end
else
new separate_fact_buffer_tbl
method close =
fact_buf#close;
a_fact_buf_tbl#iter (fun _ buf -> buf#close);
match !lock_fd with
| None -> ()
| Some fd -> Triple.unlock_fact fd
method add (tri : Triple.t) =
if not (Triple.is_ghost tri) then
fact_buf#add tri
method add_group (tri_list : Triple.t list) =
if List.for_all (fun t -> not (Triple.is_ghost t)) tri_list then
fact_buf#add_group tri_list
method add_a (key : string) (tri_list : Triple.t list) =
if List.for_all (fun t -> not (Triple.is_ghost t)) tri_list then
try
let buf = a_fact_buf_tbl#find key in
buf#add_group tri_list
with
| Not_found -> begin
let buf =
try
new Triple.buffer ~overwrite:false options (Triple.make_a_name key fact_file_path)
with
Triple.File_exists s ->
self#warning_msg "file exists: \"%s\"" s;
Triple.dummy_buffer
in
buf#add_group tri_list;
a_fact_buf_tbl#add key buf
end
method add_vg key ((s, p, o) as tri : Triple.t) v =
if not (Triple.is_ghost tri) then begin
let gp = Triple.p_guard p in
let bn = Triple.gen_blank_node() in
let tri_l = [tri;(bn, gp, s);(bn, gp, o);(bn, p_version, v)] in
self#add_a key tri_l
end
method _set_version (vkind, ver) ent =
(_apply_to_vkey_v vkind ver)
(fun vkind vkey v -> self#add_a vkey [ent, p_version, v])
method _set_file_location (vkind, ver) ent floc =
let setfloc vkind vkey v =
if floc <> "" then
let floc_lit = mklit floc in
self#add_vg vkey (ent, p_file_location, floc_lit) v
in
(_apply_to_vkey_v vkind ver) setfloc
method _set_ver_class (vkind, ver) =
let set_v_class vkind vkey v =
let get_ver_class = function
| Entity.V_REL -> Triple.c_release
| Entity.V_SVNREV -> Triple.c_svnrev
| Entity.V_GITREV -> Triple.c_gitrev
| Entity.V_VARIANT -> Triple.c_variant
| _ -> raise Not_found
in
try
self#add_a vkey [v, p_is_a, get_ver_class vkind]
with
Not_found -> ()
in
(_apply_to_vkey_v vkind ver) set_v_class;
end (* of class fact_store *)
module F (L : Spec.LABEL_T) = struct
let mkent = Triple.mkent
let mkproj = Triple.mkproj
let mkrel = Triple.mkrel
let mksvnrev = Triple.mksvnrev
let mkgitrev = Triple.mksvnrev
let mkext = Triple.mkext
let mklit = mklit
let lit_ty_string = Triple.lit_ty_string
let lit_ty_int = Triple.lit_ty_int
let lit_ty_nn_int = Triple.lit_ty_nn_int
let lit_ty_real = Triple.lit_ty_real
let mksrcres = Triple.mksrcres
let mkjres = Triple.mkjres
let mkcres = Triple.mkcres
let mkpres = Triple.mkpres
let mkvres = Triple.mkvres
let mkfres = Triple.mkfres
let mkcppres = Triple.mkcppres
let mkccxres = Triple.mkccxres
let mkver = mkver
let p_is_a = p_is_a
let p_parent = Triple.p_parent
let p_children = Triple.p_children
let p_child0 = Triple.p_child0
let p_childx = Triple.p_childx
let p_value = Triple.p_value
let p_tree_digest = Triple.p_tree_digest
let p_version = p_version
let p_file_digest = Triple.p_file_digest
let p_in_file = Triple.p_in_file
let p_in_project = Triple.p_in_project
let p_file_location = p_file_location
let p_binding = Triple.p_binding
let l_true = Triple.l_true
let l_false = Triple.l_false
let getlab nd = (Obj.obj nd#data#_label : L.t)
let getannot nd = (Obj.obj nd#data#_annotation : L.annotation)
let getloc nd = Loc.to_string nd#data#src_loc
exception Node_found of Spec.node_t
let rec find_node is_x nd =
if is_x (getlab nd) then
nd
else
try
Array.iter
(fun n ->
try
raise (Node_found (find_node is_x n))
with
Not_found -> ()
) nd#initial_children;
raise Not_found
with
Node_found res -> res
let get_surrounding_xxxs is_xxx nd =
let xxxs = ref [] in
let rec scan n =
try
let p = n#initial_parent in
let plab = getlab p in
if is_xxx plab then
xxxs := p::!xxxs;
scan p
with
Otreediff.Otree.Parent_not_found _ -> ()
in
scan nd;
!xxxs
let get_nearest_surrounding_xxx is_xxx nd =
let rec scan n =
try
let p = n#initial_parent in
let plab = getlab p in
if is_xxx plab then
p
else
scan p
with
Otreediff.Otree.Parent_not_found _ -> raise Not_found
in
scan nd
class extractor_base options cache_path tree =
let enc = options#fact_enc in
object (self)
inherit fact_store options cache_path as super
val mutable lang_prefix = ""
method set_lang_prefix p = lang_prefix <- p
method set_version = super#_set_version (tree#vkind, tree#version)
method set_file_location ent =
let floc = Triple.get_proj_rel_path tree#proj_root tree#source_path in
super#_set_file_location (tree#vkind, tree#version) ent floc
val mutable fileentity = Triple.ghost
val enc_str = Entity.encoding_to_string enc
val fid_str = Triple.encode_fid options tree
val mkextname = Triple.make_extname options tree
method mkentity (nd : Spec.node_t) =
let loc = nd#data#src_loc in
DEBUG_MSG "%s" nd#to_string;
if loc = Loc.dummy then begin
self#warning_msg "location not defined: %s@%s" nd#data#to_string tree#source_path;
Triple.ghost
end
else if Triple.is_ghost_ast_node nd then begin
Triple.ghost
end
else
let range_str = Triple.get_range_str enc loc in
let fid_str =
let fid = nd#data#source_fid in
DEBUG_MSG "fid=%s" fid;
if fid = "" then
fid_str
else
fid
in
Triple.mkent
(Triple.__make_entity
enc_str fid_str range_str nd#data#is_phantom nd#data#is_special)
method private mkfileentity =
Triple.make_file_entity options tree
method fileentity =
if fileentity = Triple.ghost then begin
fileentity <- self#mkfileentity;
fileentity
end
else
fileentity
method mkbinding ?(loc_opt=None) bid = Triple.make_binding ~loc_opt options tree bid
method mkextname lname = mkextname ~lang:lang_prefix lname
method add_surrounding_xxx is_xxx (nd : Spec.node_t) ent pred =
if not (Triple.is_ghost_node ent || Triple.is_ghost_ast_node nd) then begin
try
let pnd = tree#find_true_parent nd#uid in
if is_xxx (getlab pnd) then
self#add (ent, pred, self#mkentity pnd)
else
raise Not_found
with
Not_found ->
try
let xxx = get_nearest_surrounding_xxx is_xxx nd in
self#add (ent, pred, self#mkentity xxx);
with
Not_found -> ()
end
method scanner_body_before_subscan
(nd : Spec.node_t) (lab : L.t) (entity : Triple.node)
= ()
method scanner_body_after_subscan
(nd : Spec.node_t) (lab : L.t) (entity : Triple.node)
= ()
currently MD5 is used
method get_tree_digest nd =
match nd#data#_digest with
| Some d -> String.concat Entity.sub_sep [hash_algo; Xhash.to_hex d]
| _ -> raise Not_found
method scan ?(parent_ent=None) nd =
DEBUG_MSG "nd=\"%s\"" nd#to_string;
let entity = self#mkentity nd in
let lab = getlab nd in
let is_ghost = Triple.is_ghost_node entity in
if is_ghost then begin
let entl =
Array.fold_left
(fun l n ->
l @ (self#scan ~parent_ent n)
) [] nd#initial_children
in
entl
end
else begin
self#scanner_body_before_subscan nd lab entity;
begin
try
let v = nd#data#get_value in
self#add (entity, p_value, mklit v)
with
Not_found -> ()
end;
begin
try
let d = self#get_tree_digest nd in
self#add (entity, p_tree_digest, mklit d)
with
Not_found -> ()
end;
let ent_a =
Array.of_list
(Array.fold_left
(fun l n ->
l @ (self#scan ~parent_ent:(Some entity) n)
) [] nd#initial_children
)
in
if options#fact_for_ast_flag then begin
begin
match parent_ent with
| None -> ()
| Some pent -> self#add (entity, p_parent, pent)
end;
if ent_a <> [||] then begin
let target, ts = Triple.make_rdf_list ent_a in
self#add_group ((entity, p_children, target) :: ts)
end
end;
self#scanner_body_after_subscan nd lab entity;
[entity]
end
method extract_before_scan =
let ent = self#fileentity in
self#add (ent, p_is_a, Triple.c_file);
self#_set_ver_class (tree#vkind, tree#version);
self#set_version ent;
self#set_file_location ent;
self#add (ent, p_file_digest, mklit tree#encoded_source_digest);
method extract =
self#verbose_msg "fact compression: %B" options#fact_compress_flag;
self#extract_before_scan;
ignore (self#scan tree#root);
self#close
end (* of class Fact_base.F.extractor_base *)
of functor . F
| null | https://raw.githubusercontent.com/codinuum/cca/88ea07f3fe3671b78518769d804fdebabcd28e90/src/ast/analyzing/common/fact_base.ml | ocaml | fact_base.ml
try
with
| Triple.Lock_failed -> Triple.dummy_buffer
try
with
| Triple.Lock_failed -> Triple.dummy_buffer
of class fact_store
of class Fact_base.F.extractor_base |
Copyright 2012 - 2020 Codinuum Software Lab < >
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 .
Copyright 2012-2020 Codinuum Software Lab <>
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.
*)
let mkver vkind ver = Triple.make_version_entity (vkind, ver)
let mklit = Triple.make_literal
let p_is_a = Triple.p_is_a
let p_version = Triple.p_version
let p_file_location = Triple.p_file_location
class virtual fact_buffer_tbl = object (self)
method virtual find : string -> Triple.buffer
method virtual add : string -> Triple.buffer -> unit
method virtual iter : (string -> Triple.buffer -> unit) -> unit
end
class separate_fact_buffer_tbl = object (self)
inherit fact_buffer_tbl
val tbl = Hashtbl.create 0
method find key = Hashtbl.find tbl key
method add key buf = Hashtbl.add tbl key buf
method iter f = Hashtbl.iter f tbl
end
class unified_fact_buffer_tbl = object (self)
inherit fact_buffer_tbl
val mutable _buf = Triple.dummy_buffer
method find key = _buf
method add key buf = _buf <- buf
method iter f = f "" _buf
end
let _apply_to_vkey_v vkind ver =
if not (Entity.vkind_is_unknown vkind) && ver <> "" then
let vkey = Entity.mkvkey vkind ver in
let v = mkver vkind ver in
fun f -> f vkind vkey v
else
fun f -> ()
let create_fact_buf
options
?(acquire_lock=(fun () -> ()))
?(fact_file_path="")
?(cache_name="")
~into_virtuoso
~into_directory
cache_path
=
let fact_file_path =
if fact_file_path = "" then
Filename.concat cache_path Stat.fact_file_name
else
fact_file_path
in
let cache_name =
if cache_name = "" then
Cache.get_cache_name options cache_path
else
cache_name
in
let buf =
if into_virtuoso then begin
DEBUG_MSG "preparing fact buffer for virtuoso...";
assert (not into_directory);
acquire_lock();
new Triple.buffer_virtuoso options
end
else if into_directory then begin
DEBUG_MSG "preparing fact buffer for directory...";
acquire_lock();
new Triple.buffer_directory options cache_name
end
else begin
DEBUG_MSG "preparing fact buffer...";
try
new Triple.buffer ~overwrite:false options fact_file_path
with
| Triple.File_exists s ->
Xprint.warning "file exists: \"%s\"" s;
Triple.dummy_buffer
end
in
DEBUG_MSG "done.";
buf
class fact_store ?(lock=true) options cache_path =
let fact_file_path =
Filename.concat cache_path Stat.fact_file_name
in
let _ = DEBUG_MSG "cache_path: %s" cache_path in
let _ = DEBUG_MSG "fact_file_path: %s" fact_file_path in
let cache_name = Cache.get_cache_name options cache_path in
let lock_fd = ref None in
let acquire_lock() =
if lock then
let fd = Triple.lock_fact cache_path in
lock_fd := Some fd
in
let into_virtuoso = options#fact_into_virtuoso <> "" in
let into_directory = options#fact_into_directory <> "" in
object (self)
method id = ""
method warning_msg : 'a. ('a, unit, string, unit) format4 -> 'a =
Xprint.warning ~head:(if self#id = "" then "" else "["^self#id^"]") ~out:stderr
method verbose_msg : 'a. ('a, unit, string, unit) format4 -> 'a =
Xprint.verbose options#verbose_flag
val fact_buf =
create_fact_buf
options
~acquire_lock ~fact_file_path ~into_virtuoso ~into_directory
cache_path
val a_fact_buf_tbl =
if into_virtuoso || into_directory then begin
let tbl = new unified_fact_buffer_tbl in
if into_virtuoso then
tbl#add "" (new Triple.buffer_virtuoso options)
else if into_directory then
tbl#add "" (new Triple.buffer_directory options cache_name);
tbl
end
else
new separate_fact_buffer_tbl
method close =
fact_buf#close;
a_fact_buf_tbl#iter (fun _ buf -> buf#close);
match !lock_fd with
| None -> ()
| Some fd -> Triple.unlock_fact fd
method add (tri : Triple.t) =
if not (Triple.is_ghost tri) then
fact_buf#add tri
method add_group (tri_list : Triple.t list) =
if List.for_all (fun t -> not (Triple.is_ghost t)) tri_list then
fact_buf#add_group tri_list
method add_a (key : string) (tri_list : Triple.t list) =
if List.for_all (fun t -> not (Triple.is_ghost t)) tri_list then
try
let buf = a_fact_buf_tbl#find key in
buf#add_group tri_list
with
| Not_found -> begin
let buf =
try
new Triple.buffer ~overwrite:false options (Triple.make_a_name key fact_file_path)
with
Triple.File_exists s ->
self#warning_msg "file exists: \"%s\"" s;
Triple.dummy_buffer
in
buf#add_group tri_list;
a_fact_buf_tbl#add key buf
end
method add_vg key ((s, p, o) as tri : Triple.t) v =
if not (Triple.is_ghost tri) then begin
let gp = Triple.p_guard p in
let bn = Triple.gen_blank_node() in
let tri_l = [tri;(bn, gp, s);(bn, gp, o);(bn, p_version, v)] in
self#add_a key tri_l
end
method _set_version (vkind, ver) ent =
(_apply_to_vkey_v vkind ver)
(fun vkind vkey v -> self#add_a vkey [ent, p_version, v])
method _set_file_location (vkind, ver) ent floc =
let setfloc vkind vkey v =
if floc <> "" then
let floc_lit = mklit floc in
self#add_vg vkey (ent, p_file_location, floc_lit) v
in
(_apply_to_vkey_v vkind ver) setfloc
method _set_ver_class (vkind, ver) =
let set_v_class vkind vkey v =
let get_ver_class = function
| Entity.V_REL -> Triple.c_release
| Entity.V_SVNREV -> Triple.c_svnrev
| Entity.V_GITREV -> Triple.c_gitrev
| Entity.V_VARIANT -> Triple.c_variant
| _ -> raise Not_found
in
try
self#add_a vkey [v, p_is_a, get_ver_class vkind]
with
Not_found -> ()
in
(_apply_to_vkey_v vkind ver) set_v_class;
module F (L : Spec.LABEL_T) = struct
let mkent = Triple.mkent
let mkproj = Triple.mkproj
let mkrel = Triple.mkrel
let mksvnrev = Triple.mksvnrev
let mkgitrev = Triple.mksvnrev
let mkext = Triple.mkext
let mklit = mklit
let lit_ty_string = Triple.lit_ty_string
let lit_ty_int = Triple.lit_ty_int
let lit_ty_nn_int = Triple.lit_ty_nn_int
let lit_ty_real = Triple.lit_ty_real
let mksrcres = Triple.mksrcres
let mkjres = Triple.mkjres
let mkcres = Triple.mkcres
let mkpres = Triple.mkpres
let mkvres = Triple.mkvres
let mkfres = Triple.mkfres
let mkcppres = Triple.mkcppres
let mkccxres = Triple.mkccxres
let mkver = mkver
let p_is_a = p_is_a
let p_parent = Triple.p_parent
let p_children = Triple.p_children
let p_child0 = Triple.p_child0
let p_childx = Triple.p_childx
let p_value = Triple.p_value
let p_tree_digest = Triple.p_tree_digest
let p_version = p_version
let p_file_digest = Triple.p_file_digest
let p_in_file = Triple.p_in_file
let p_in_project = Triple.p_in_project
let p_file_location = p_file_location
let p_binding = Triple.p_binding
let l_true = Triple.l_true
let l_false = Triple.l_false
let getlab nd = (Obj.obj nd#data#_label : L.t)
let getannot nd = (Obj.obj nd#data#_annotation : L.annotation)
let getloc nd = Loc.to_string nd#data#src_loc
exception Node_found of Spec.node_t
let rec find_node is_x nd =
if is_x (getlab nd) then
nd
else
try
Array.iter
(fun n ->
try
raise (Node_found (find_node is_x n))
with
Not_found -> ()
) nd#initial_children;
raise Not_found
with
Node_found res -> res
let get_surrounding_xxxs is_xxx nd =
let xxxs = ref [] in
let rec scan n =
try
let p = n#initial_parent in
let plab = getlab p in
if is_xxx plab then
xxxs := p::!xxxs;
scan p
with
Otreediff.Otree.Parent_not_found _ -> ()
in
scan nd;
!xxxs
let get_nearest_surrounding_xxx is_xxx nd =
let rec scan n =
try
let p = n#initial_parent in
let plab = getlab p in
if is_xxx plab then
p
else
scan p
with
Otreediff.Otree.Parent_not_found _ -> raise Not_found
in
scan nd
class extractor_base options cache_path tree =
let enc = options#fact_enc in
object (self)
inherit fact_store options cache_path as super
val mutable lang_prefix = ""
method set_lang_prefix p = lang_prefix <- p
method set_version = super#_set_version (tree#vkind, tree#version)
method set_file_location ent =
let floc = Triple.get_proj_rel_path tree#proj_root tree#source_path in
super#_set_file_location (tree#vkind, tree#version) ent floc
val mutable fileentity = Triple.ghost
val enc_str = Entity.encoding_to_string enc
val fid_str = Triple.encode_fid options tree
val mkextname = Triple.make_extname options tree
method mkentity (nd : Spec.node_t) =
let loc = nd#data#src_loc in
DEBUG_MSG "%s" nd#to_string;
if loc = Loc.dummy then begin
self#warning_msg "location not defined: %s@%s" nd#data#to_string tree#source_path;
Triple.ghost
end
else if Triple.is_ghost_ast_node nd then begin
Triple.ghost
end
else
let range_str = Triple.get_range_str enc loc in
let fid_str =
let fid = nd#data#source_fid in
DEBUG_MSG "fid=%s" fid;
if fid = "" then
fid_str
else
fid
in
Triple.mkent
(Triple.__make_entity
enc_str fid_str range_str nd#data#is_phantom nd#data#is_special)
method private mkfileentity =
Triple.make_file_entity options tree
method fileentity =
if fileentity = Triple.ghost then begin
fileentity <- self#mkfileentity;
fileentity
end
else
fileentity
method mkbinding ?(loc_opt=None) bid = Triple.make_binding ~loc_opt options tree bid
method mkextname lname = mkextname ~lang:lang_prefix lname
method add_surrounding_xxx is_xxx (nd : Spec.node_t) ent pred =
if not (Triple.is_ghost_node ent || Triple.is_ghost_ast_node nd) then begin
try
let pnd = tree#find_true_parent nd#uid in
if is_xxx (getlab pnd) then
self#add (ent, pred, self#mkentity pnd)
else
raise Not_found
with
Not_found ->
try
let xxx = get_nearest_surrounding_xxx is_xxx nd in
self#add (ent, pred, self#mkentity xxx);
with
Not_found -> ()
end
method scanner_body_before_subscan
(nd : Spec.node_t) (lab : L.t) (entity : Triple.node)
= ()
method scanner_body_after_subscan
(nd : Spec.node_t) (lab : L.t) (entity : Triple.node)
= ()
currently MD5 is used
method get_tree_digest nd =
match nd#data#_digest with
| Some d -> String.concat Entity.sub_sep [hash_algo; Xhash.to_hex d]
| _ -> raise Not_found
method scan ?(parent_ent=None) nd =
DEBUG_MSG "nd=\"%s\"" nd#to_string;
let entity = self#mkentity nd in
let lab = getlab nd in
let is_ghost = Triple.is_ghost_node entity in
if is_ghost then begin
let entl =
Array.fold_left
(fun l n ->
l @ (self#scan ~parent_ent n)
) [] nd#initial_children
in
entl
end
else begin
self#scanner_body_before_subscan nd lab entity;
begin
try
let v = nd#data#get_value in
self#add (entity, p_value, mklit v)
with
Not_found -> ()
end;
begin
try
let d = self#get_tree_digest nd in
self#add (entity, p_tree_digest, mklit d)
with
Not_found -> ()
end;
let ent_a =
Array.of_list
(Array.fold_left
(fun l n ->
l @ (self#scan ~parent_ent:(Some entity) n)
) [] nd#initial_children
)
in
if options#fact_for_ast_flag then begin
begin
match parent_ent with
| None -> ()
| Some pent -> self#add (entity, p_parent, pent)
end;
if ent_a <> [||] then begin
let target, ts = Triple.make_rdf_list ent_a in
self#add_group ((entity, p_children, target) :: ts)
end
end;
self#scanner_body_after_subscan nd lab entity;
[entity]
end
method extract_before_scan =
let ent = self#fileentity in
self#add (ent, p_is_a, Triple.c_file);
self#_set_ver_class (tree#vkind, tree#version);
self#set_version ent;
self#set_file_location ent;
self#add (ent, p_file_digest, mklit tree#encoded_source_digest);
method extract =
self#verbose_msg "fact compression: %B" options#fact_compress_flag;
self#extract_before_scan;
ignore (self#scan tree#root);
self#close
of functor . F
|
fc8005fcb90c2f7dbd3f603cee484be6ac9569cc76a83a47d0a6e422ed3b957c | larrychristensen/orcpub | routes_test.clj | (ns orcpub.routes-test
(:require [orcpub.routes :as routes]
[orcpub.dnd.e5.magic-items :as mi]
[orcpub.dnd.e5.character :as char]
[orcpub.modifiers :as mod]
[orcpub.entity :as entity]
[clojure.test :refer [deftest is testing]]
[orcpub.errors :as errors]
[io.pedestal.http :as http]
[io.pedestal.test :refer [response-for]]
[orcpub.db.schema :as schema]
[datomic.api :as d]
[datomock.core :as dm]
[clojure.set :refer [intersection]])
(:import [java.util UUID]))
#_(def service
(::http/service-fn (http/create-servlet {::http/routes routes/routes
::http/type :jetty
::http/port 8080})))
#_(deftest test-index
(let [response (response-for service :get "/")]
(prn "RESPONSE" response)
(is (= (:status response)
200))))
(defmacro with-conn [conn-binding & body]
`(let [uri# (str "datomic:mem:orcpub-test-" (UUID/randomUUID))
~conn-binding (do (d/create-database uri#)
(d/connect uri#))]
(try ~@body
(finally (d/delete-database uri#)))))
(deftest test-save-entity
(with-conn conn
(let [mocked-conn (dm/fork-conn conn)]
@(d/transact mocked-conn schema/all-schemas)
@(d/transact mocked-conn [{:orcpub.user/username "testy"
:orcpub.user/email ""}
{:orcpub.user/username "testy-2"
:orcpub.user/email ""}])
(testing "Save new entity"
(let [entity {::mi/name "Cool Item"}
saved-entity (routes/save-entity mocked-conn "testy" entity ::mi/owner)]
(is (= "testy" (::mi/owner saved-entity)))
(is (int? (:db/id saved-entity)))
(is (= "Cool Item" (::mi/name saved-entity)))))
(testing "Create and update entity"
(let [entity {::mi/modifiers [{::mod/key :saving-throw-bonus
::mod/args [{::mod/keyword-arg ::char/str}
{::mod/int-arg 1}]}]}
saved-entity (routes/save-entity mocked-conn "testy" entity ::mi/owner)]
(is (= "testy" (::mi/owner saved-entity)))
(is (int? (:db/id saved-entity)))
(is (int? (get-in saved-entity [::mi/modifiers 0 ::mod/args 1 :db/id])))
(is (= saved-entity (routes/save-entity mocked-conn "testy" saved-entity ::mi/owner)))))
(testing "Update other user's entity"
(let [entity {::mi/modifiers [{::mod/key :saving-throw-bonus
::mod/args [{::mod/keyword-arg ::char/str}
{::mod/int-arg 1}]}]}
saved-entity (routes/save-entity mocked-conn "testy" entity ::mi/owner)
saved-entity-2 (routes/save-entity mocked-conn "testy-2" entity ::mi/owner)]
(is (not= saved-entity saved-entity-2))
(is (thrown? Throwable (routes/save-entity mocked-conn "testy" (update saved-entity :db/id (:db/id saved-entity-2)) ::mi/owner)))))
(testing "Removal of orphans"
(let [entity {::mi/modifiers [{::mod/key :saving-throw-bonus
::mod/args [{::mod/keyword-arg ::char/str}
{::mod/int-arg 1}]}]}
saved-entity (routes/save-entity mocked-conn "testy" entity ::mi/owner)
root-id (:db/id saved-entity)
child-ids (disj (entity/db-ids saved-entity) root-id)
update-entity (assoc-in saved-entity [::mi/modifiers 0 :db/id] nil)
updated-entity (routes/save-entity mocked-conn "testy" update-entity ::mi/owner)
updated-entity-ids (entity/db-ids updated-entity)]
(is (= root-id (:db/id updated-entity)))
(is (empty? (intersection updated-entity-ids child-ids)))))
(testing "Removal of non-children ids"
(let [entity {::mi/modifiers [{::mod/key :saving-throw-bonus
::mod/args [{::mod/keyword-arg ::char/str}
{::mod/int-arg 1}]}]}
saved-entity (routes/save-entity mocked-conn "testy" entity ::mi/owner)
root-id (:db/id saved-entity)
child-ids (disj (entity/db-ids saved-entity) root-id)
saved-entity-2 (routes/save-entity mocked-conn "testy-2" entity ::mi/owner)
update-entity (assoc-in saved-entity [::mi/modifiers 0 :db/id] (:db/id saved-entity-2))
updated-entity (routes/save-entity mocked-conn "testy" update-entity ::mi/owner)
updated-entity-ids (entity/db-ids updated-entity)]
(is (= root-id (:db/id updated-entity)))
(is (empty? (intersection updated-entity-ids child-ids)))
(is (not (updated-entity-ids (:db/id saved-entity-2)))))))))
(deftest test-db-ids
(let [e-1 {:db/id 1
:x {:db/id 2
:y [{:db/id 3
:z {:db/id 4}}]}}]
(is (= (entity/db-ids e-1) #{1 2 3 4}))
(is (= (entity/db-ids e-1 (routes/diff-branch #{1 2})) #{1 2 3}))))
(deftest test-remove-specific-ids
(let [e {:db/id 2
:y {:db/id 3
:z {:db/id 4}
:x [{:db/id 5} {:db/id 6 :xx 2}]}}]
(is (= (entity/remove-specific-ids e #{4 6})
{:db/id 2
:y {:db/id 3
:z {}
:x [{:db/id 5} {:xx 2}]}}))))
(deftest test-remove-ids
(let [e-1 {:db/id 1
:s "sere"
:v 12324
:x {:db/id 2
:y [{:db/id 3
:s "xx"
:z {:db/id 4}}]
:yy [{:db/id 5
:v 34
:zz {:db/id 6
:v 78
:zzz [{:db/id 7
:s "String"}]}}]}}
e-2 {:s "sere"
:v 12324
:x {:y [{:s "xx"
:z {}}]
:yy [{:v 34
:zz {:v 78
:zzz [{:s "String"}]}}]}}]
(is (= e-2 (entity/remove-ids e-1)))))
(deftest test-remove-orphan-ids
(let [e-1 {:db/id 1
:s "sere"
:v 12324
:x {:db/id 2
:y [{:db/id 3
:s "xx"
:z {:db/id 4}}]
:yy [{:db/id 5
:v 34
:zz {:db/id 6
:v 78
:zzz [{:db/id 7
:s "String"}]}}]}}
e-2 {:db/id 1
:s "sere"
:v 12324
:x {:y [{:db/id 3
:s "xx"
:z {:db/id 4}}]
:yy [{:db/id 5
:v 34
:zz {:db/id 6
:v 78
:zzz [{:db/id 7
:s "String"}]}}]}}
e-3 {:db/id 1
:s "sere"
:v 12324
:x {:db/id 2
:y [{:s "xx"
:z {:db/id 4}}]
:yy [{:db/id 5
:v 34
:zz {:v 78
:zzz [{:db/id 7
:s "String"}]}}]}}]
(is (= (entity/remove-orphan-ids e-1) e-1))
(is (= (entity/remove-orphan-ids e-2) {:db/id 1
:s "sere"
:v 12324
:x {:y [{:s "xx"
:z {}}]
:yy [{:v 34
:zz {:v 78
:zzz [{:s "String"}]}}]}}))
(is (= (entity/remove-orphan-ids e-3) {:db/id 1
:s "sere"
:v 12324
:x {:db/id 2
:y [{:s "xx"
:z {}}]
:yy [{:db/id 5
:v 34
:zz {:v 78
:zzz [{:s "String"}]}}]}}))))
| null | https://raw.githubusercontent.com/larrychristensen/orcpub/e83995857f7e64af1798009a45a0b03abcd3a4be/test/clj/orcpub/routes_test.clj | clojure | (ns orcpub.routes-test
(:require [orcpub.routes :as routes]
[orcpub.dnd.e5.magic-items :as mi]
[orcpub.dnd.e5.character :as char]
[orcpub.modifiers :as mod]
[orcpub.entity :as entity]
[clojure.test :refer [deftest is testing]]
[orcpub.errors :as errors]
[io.pedestal.http :as http]
[io.pedestal.test :refer [response-for]]
[orcpub.db.schema :as schema]
[datomic.api :as d]
[datomock.core :as dm]
[clojure.set :refer [intersection]])
(:import [java.util UUID]))
#_(def service
(::http/service-fn (http/create-servlet {::http/routes routes/routes
::http/type :jetty
::http/port 8080})))
#_(deftest test-index
(let [response (response-for service :get "/")]
(prn "RESPONSE" response)
(is (= (:status response)
200))))
(defmacro with-conn [conn-binding & body]
`(let [uri# (str "datomic:mem:orcpub-test-" (UUID/randomUUID))
~conn-binding (do (d/create-database uri#)
(d/connect uri#))]
(try ~@body
(finally (d/delete-database uri#)))))
(deftest test-save-entity
(with-conn conn
(let [mocked-conn (dm/fork-conn conn)]
@(d/transact mocked-conn schema/all-schemas)
@(d/transact mocked-conn [{:orcpub.user/username "testy"
:orcpub.user/email ""}
{:orcpub.user/username "testy-2"
:orcpub.user/email ""}])
(testing "Save new entity"
(let [entity {::mi/name "Cool Item"}
saved-entity (routes/save-entity mocked-conn "testy" entity ::mi/owner)]
(is (= "testy" (::mi/owner saved-entity)))
(is (int? (:db/id saved-entity)))
(is (= "Cool Item" (::mi/name saved-entity)))))
(testing "Create and update entity"
(let [entity {::mi/modifiers [{::mod/key :saving-throw-bonus
::mod/args [{::mod/keyword-arg ::char/str}
{::mod/int-arg 1}]}]}
saved-entity (routes/save-entity mocked-conn "testy" entity ::mi/owner)]
(is (= "testy" (::mi/owner saved-entity)))
(is (int? (:db/id saved-entity)))
(is (int? (get-in saved-entity [::mi/modifiers 0 ::mod/args 1 :db/id])))
(is (= saved-entity (routes/save-entity mocked-conn "testy" saved-entity ::mi/owner)))))
(testing "Update other user's entity"
(let [entity {::mi/modifiers [{::mod/key :saving-throw-bonus
::mod/args [{::mod/keyword-arg ::char/str}
{::mod/int-arg 1}]}]}
saved-entity (routes/save-entity mocked-conn "testy" entity ::mi/owner)
saved-entity-2 (routes/save-entity mocked-conn "testy-2" entity ::mi/owner)]
(is (not= saved-entity saved-entity-2))
(is (thrown? Throwable (routes/save-entity mocked-conn "testy" (update saved-entity :db/id (:db/id saved-entity-2)) ::mi/owner)))))
(testing "Removal of orphans"
(let [entity {::mi/modifiers [{::mod/key :saving-throw-bonus
::mod/args [{::mod/keyword-arg ::char/str}
{::mod/int-arg 1}]}]}
saved-entity (routes/save-entity mocked-conn "testy" entity ::mi/owner)
root-id (:db/id saved-entity)
child-ids (disj (entity/db-ids saved-entity) root-id)
update-entity (assoc-in saved-entity [::mi/modifiers 0 :db/id] nil)
updated-entity (routes/save-entity mocked-conn "testy" update-entity ::mi/owner)
updated-entity-ids (entity/db-ids updated-entity)]
(is (= root-id (:db/id updated-entity)))
(is (empty? (intersection updated-entity-ids child-ids)))))
(testing "Removal of non-children ids"
(let [entity {::mi/modifiers [{::mod/key :saving-throw-bonus
::mod/args [{::mod/keyword-arg ::char/str}
{::mod/int-arg 1}]}]}
saved-entity (routes/save-entity mocked-conn "testy" entity ::mi/owner)
root-id (:db/id saved-entity)
child-ids (disj (entity/db-ids saved-entity) root-id)
saved-entity-2 (routes/save-entity mocked-conn "testy-2" entity ::mi/owner)
update-entity (assoc-in saved-entity [::mi/modifiers 0 :db/id] (:db/id saved-entity-2))
updated-entity (routes/save-entity mocked-conn "testy" update-entity ::mi/owner)
updated-entity-ids (entity/db-ids updated-entity)]
(is (= root-id (:db/id updated-entity)))
(is (empty? (intersection updated-entity-ids child-ids)))
(is (not (updated-entity-ids (:db/id saved-entity-2)))))))))
(deftest test-db-ids
(let [e-1 {:db/id 1
:x {:db/id 2
:y [{:db/id 3
:z {:db/id 4}}]}}]
(is (= (entity/db-ids e-1) #{1 2 3 4}))
(is (= (entity/db-ids e-1 (routes/diff-branch #{1 2})) #{1 2 3}))))
(deftest test-remove-specific-ids
(let [e {:db/id 2
:y {:db/id 3
:z {:db/id 4}
:x [{:db/id 5} {:db/id 6 :xx 2}]}}]
(is (= (entity/remove-specific-ids e #{4 6})
{:db/id 2
:y {:db/id 3
:z {}
:x [{:db/id 5} {:xx 2}]}}))))
(deftest test-remove-ids
(let [e-1 {:db/id 1
:s "sere"
:v 12324
:x {:db/id 2
:y [{:db/id 3
:s "xx"
:z {:db/id 4}}]
:yy [{:db/id 5
:v 34
:zz {:db/id 6
:v 78
:zzz [{:db/id 7
:s "String"}]}}]}}
e-2 {:s "sere"
:v 12324
:x {:y [{:s "xx"
:z {}}]
:yy [{:v 34
:zz {:v 78
:zzz [{:s "String"}]}}]}}]
(is (= e-2 (entity/remove-ids e-1)))))
(deftest test-remove-orphan-ids
(let [e-1 {:db/id 1
:s "sere"
:v 12324
:x {:db/id 2
:y [{:db/id 3
:s "xx"
:z {:db/id 4}}]
:yy [{:db/id 5
:v 34
:zz {:db/id 6
:v 78
:zzz [{:db/id 7
:s "String"}]}}]}}
e-2 {:db/id 1
:s "sere"
:v 12324
:x {:y [{:db/id 3
:s "xx"
:z {:db/id 4}}]
:yy [{:db/id 5
:v 34
:zz {:db/id 6
:v 78
:zzz [{:db/id 7
:s "String"}]}}]}}
e-3 {:db/id 1
:s "sere"
:v 12324
:x {:db/id 2
:y [{:s "xx"
:z {:db/id 4}}]
:yy [{:db/id 5
:v 34
:zz {:v 78
:zzz [{:db/id 7
:s "String"}]}}]}}]
(is (= (entity/remove-orphan-ids e-1) e-1))
(is (= (entity/remove-orphan-ids e-2) {:db/id 1
:s "sere"
:v 12324
:x {:y [{:s "xx"
:z {}}]
:yy [{:v 34
:zz {:v 78
:zzz [{:s "String"}]}}]}}))
(is (= (entity/remove-orphan-ids e-3) {:db/id 1
:s "sere"
:v 12324
:x {:db/id 2
:y [{:s "xx"
:z {}}]
:yy [{:db/id 5
:v 34
:zz {:v 78
:zzz [{:s "String"}]}}]}}))))
|
|
91fc8b5ffdf6d52cba14e4196705d3ac9c198e66c87673bce882746db65ca6fa | ragkousism/Guix-on-Hurd | cran.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2015 , 2016 < >
Copyright © 2015 , 2016 , 2017 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (guix import cran)
#:use-module (ice-9 match)
#:use-module (ice-9 regex)
#:use-module ((ice-9 rdelim) #:select (read-string))
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-26)
#:use-module (srfi srfi-34)
#:use-module (srfi srfi-41)
#:use-module (ice-9 receive)
#:use-module (web uri)
#:use-module (guix memoization)
#:use-module (guix http-client)
#:use-module (guix hash)
#:use-module (guix store)
#:use-module (guix base32)
#:use-module ((guix download) #:select (download-to-store))
#:use-module (guix import utils)
#:use-module ((guix build-system r) #:select (cran-uri bioconductor-uri))
#:use-module (guix upstream)
#:use-module (guix packages)
#:use-module (gnu packages)
#:export (cran->guix-package
bioconductor->guix-package
recursive-import
%cran-updater
%bioconductor-updater))
;;; Commentary:
;;;
;;; Generate a package declaration template for the latest version of an R
package on CRAN , using the DESCRIPTION file downloaded from
;;; cran.r-project.org.
;;;
;;; Code:
(define string->license
(match-lambda
("AGPL-3" 'agpl3+)
("Artistic-2.0" 'artistic2.0)
("Apache License 2.0" 'asl2.0)
("BSD_2_clause" 'bsd-2)
("BSD_2_clause + file LICENSE" 'bsd-2)
("BSD_3_clause" 'bsd-3)
("BSD_3_clause + file LICENSE" 'bsd-3)
("GPL" (list 'gpl2+ 'gpl3+))
("GPL (>= 2)" 'gpl2+)
("GPL (>= 3)" 'gpl3+)
("GPL-2" 'gpl2)
("GPL-3" 'gpl3)
("LGPL-2" 'lgpl2.0)
("LGPL-2.1" 'lgpl2.1)
("LGPL-3" 'lgpl3)
("LGPL (>= 2)" 'lgpl2.0+)
("LGPL (>= 3)" 'lgpl3+)
("MIT" 'expat)
("MIT + file LICENSE" 'expat)
((x) (string->license x))
((lst ...) `(list ,@(map string->license lst)))
(_ #f)))
(define (description->alist description)
"Convert a DESCRIPTION string into an alist."
(let ((lines (string-split description #\newline))
(parse (lambda (line acc)
(if (string-null? line) acc
;; Keys usually start with a capital letter and end with
;; ":". There are some exceptions, unfortunately (such
;; as "biocViews"). There are no blanks in a key.
(if (string-match "^[A-Za-z][^ :]+:( |\n|$)" line)
;; New key/value pair
(let* ((pos (string-index line #\:))
(key (string-take line pos))
(value (string-drop line (+ 1 pos))))
(cons (cons key
(string-trim-both value))
acc))
;; This is a continuation of the previous pair
(match-let ((((key . value) . rest) acc))
(cons (cons key (string-join
(list value
(string-trim-both line))))
rest)))))))
(fold parse '() lines)))
(define (format-inputs names)
"Generate a sorted list of package inputs from a list of package NAMES."
(map (lambda (name)
(list name (list 'unquote (string->symbol name))))
(sort names string-ci<?)))
(define* (maybe-inputs package-inputs #:optional (type 'inputs))
"Given a list of PACKAGE-INPUTS, tries to generate the TYPE field of a
package definition."
(match package-inputs
(()
'())
((package-inputs ...)
`((,type (,'quasiquote ,(format-inputs package-inputs)))))))
(define %cran-url "-project.org/web/packages/")
(define %bioconductor-url "/")
The latest Bioconductor release is 3.4 . Bioconductor packages should be
;; updated together.
(define %bioconductor-svn-url
(string-append ":readonly@"
"hedgehog.fhcrc.org/bioconductor/branches/RELEASE_3_4/"
"madman/Rpacks/"))
(define (fetch-description base-url name)
"Return an alist of the contents of the DESCRIPTION file for the R package
NAME, or #f in case of failure. NAME is case-sensitive."
;; This API always returns the latest release of the module.
(let ((url (string-append base-url name "/DESCRIPTION")))
(guard (c ((http-get-error? c)
(format (current-error-port)
"error: failed to retrieve package information \
from ~s: ~a (~s)~%"
(uri->string (http-get-error-uri c))
(http-get-error-code c)
(http-get-error-reason c))
#f))
(description->alist (read-string (http-fetch url))))))
(define (listify meta field)
"Look up FIELD in the alist META. If FIELD contains a comma-separated
string, turn it into a list and strip off parenthetic expressions. Return the
empty list when the FIELD cannot be found."
(let ((value (assoc-ref meta field)))
(if (not value)
'()
Strip off parentheses
(let ((items (string-split (regexp-substitute/global
#f "( *\\([^\\)]+\\)) *"
value 'pre 'post)
#\,)))
(remove (lambda (item)
(or (string-null? item)
;; When there is whitespace inside of items it is
;; probably because this was not an actual list to
;; begin with.
(string-any char-set:whitespace item)))
(map string-trim-both items))))))
(define default-r-packages
(list "KernSmooth"
"MASS"
"Matrix"
"base"
"boot"
"class"
"cluster"
"codetools"
"compiler"
"datasets"
"foreign"
"grDevices"
"graphics"
"grid"
"lattice"
"methods"
"mgcv"
"nlme"
"nnet"
"parallel"
"rpart"
"spatial"
"splines"
"stats"
"stats4"
"survival"
"tcltk"
"tools"
"translations"
"utils"))
(define (guix-name name)
"Return a Guix package name for a given R package name."
(string-append "r-" (string-map (match-lambda
(#\_ #\-)
(#\. #\-)
(chr (char-downcase chr)))
name)))
(define (description->package repository meta)
"Return the `package' s-expression for an R package published on REPOSITORY
from the alist META, which was derived from the R package's DESCRIPTION file."
(let* ((base-url (case repository
((cran) %cran-url)
((bioconductor) %bioconductor-url)))
(uri-helper (case repository
((cran) cran-uri)
((bioconductor) bioconductor-uri)))
(name (assoc-ref meta "Package"))
(synopsis (assoc-ref meta "Title"))
(version (assoc-ref meta "Version"))
(license (string->license (assoc-ref meta "License")))
;; Some packages have multiple home pages. Some have none.
(home-page (match (listify meta "URL")
((url rest ...) url)
(_ (string-append base-url name))))
(source-url (match (uri-helper name version)
((url rest ...) url)
((? string? url) url)
(_ #f)))
(tarball (with-store store (download-to-store store source-url)))
(sysdepends (map string-downcase (listify meta "SystemRequirements")))
(propagate (filter (lambda (name)
(not (member name default-r-packages)))
(lset-union equal?
(listify meta "Imports")
(listify meta "LinkingTo")
(delete "R"
(listify meta "Depends"))))))
(values
`(package
(name ,(guix-name name))
(version ,version)
(source (origin
(method url-fetch)
(uri (,(procedure-name uri-helper) ,name version))
(sha256
(base32
,(bytevector->nix-base32-string (file-sha256 tarball))))))
,@(if (not (equal? (string-append "r-" name)
(guix-name name)))
`((properties ,`(,'quasiquote ((,'upstream-name . ,name)))))
'())
(build-system r-build-system)
,@(maybe-inputs sysdepends)
,@(maybe-inputs (map guix-name propagate) 'propagated-inputs)
(home-page ,(if (string-null? home-page)
(string-append base-url name)
home-page))
(synopsis ,synopsis)
(description ,(beautify-description (or (assoc-ref meta "Description")
"")))
(license ,license))
propagate)))
(define cran->guix-package
(memoize
(lambda* (package-name #:optional (repo 'cran))
"Fetch the metadata for PACKAGE-NAME from REPO and return the `package'
s-expression corresponding to that package, or #f on failure."
(let* ((url (case repo
((cran) %cran-url)
((bioconductor) %bioconductor-svn-url)))
(module-meta (fetch-description url package-name)))
(and=> module-meta (cut description->package repo <>))))))
(define* (recursive-import package-name #:optional (repo 'cran))
"Generate a stream of package expressions for PACKAGE-NAME and all its
dependencies."
(receive (package . dependencies)
(cran->guix-package package-name repo)
(if (not package)
stream-null
;; Generate a lazy stream of package expressions for all unknown
;; dependencies in the graph.
(let* ((make-state (lambda (queue done)
(cons queue done)))
(next (match-lambda
(((next . rest) . done) next)))
(imported (match-lambda
((queue . done) done)))
(done? (match-lambda
((queue . done)
(zero? (length queue)))))
(unknown? (lambda* (dependency #:optional (done '()))
(and (not (member dependency
done))
(null? (find-packages-by-name
(guix-name dependency))))))
(update (lambda (state new-queue)
(match state
(((head . tail) . done)
(make-state (lset-difference
equal?
(lset-union equal? new-queue tail)
done)
(cons head done)))))))
(stream-cons
package
(stream-unfold
;; map: produce a stream element
(lambda (state)
(cran->guix-package (next state) repo))
;; predicate
(compose not done?)
;; generator: update the queue
(lambda (state)
(receive (package . dependencies)
(cran->guix-package (next state) repo)
(if package
(update state (filter (cut unknown? <>
(cons (next state)
(imported state)))
(car dependencies)))
;; TODO: Try the other archives before giving up
(update state (imported state)))))
;; initial state
(make-state (filter unknown? (car dependencies))
(list package-name))))))))
;;;
;;; Updater.
;;;
(define (package->upstream-name package)
"Return the upstream name of the PACKAGE."
(let* ((properties (package-properties package))
(upstream-name (and=> properties
(cut assoc-ref <> 'upstream-name))))
(if upstream-name
upstream-name
(match (package-source package)
((? origin? origin)
(match (origin-uri origin)
((or (? string? url) (url _ ...))
(let ((end (string-rindex url #\_))
(start (string-rindex url #\/)))
;; The URL ends on
;; (string-append "/" name "_" version ".tar.gz")
(substring url (+ start 1) end)))
(_ #f)))
(_ #f)))))
(define (latest-cran-release package)
"Return an <upstream-source> for the latest release of PACKAGE."
(define upstream-name
(package->upstream-name package))
(define meta
(fetch-description %cran-url upstream-name))
(and meta
(let ((version (assoc-ref meta "Version")))
;; CRAN does not provide signatures.
(upstream-source
(package (package-name package))
(version version)
(urls (cran-uri upstream-name version))))))
(define (latest-bioconductor-release package)
"Return an <upstream-source> for the latest release of PACKAGE."
(define upstream-name
(package->upstream-name package))
(define meta
(fetch-description %bioconductor-svn-url upstream-name))
(and meta
(let ((version (assoc-ref meta "Version")))
;; Bioconductor does not provide signatures.
(upstream-source
(package (package-name package))
(version version)
(urls (list (bioconductor-uri upstream-name version)))))))
(define (cran-package? package)
"Return true if PACKAGE is an R package from CRAN."
(and (string-prefix? "r-" (package-name package))
(match (and=> (package-source package) origin-uri)
((? string? uri)
(string-prefix? "mirror" uri))
((? list? uris)
(any (cut string-prefix? "mirror" <>) uris))
(_ #f))))
(define (bioconductor-package? package)
"Return true if PACKAGE is an R package from Bioconductor."
(and (string-prefix? "r-" (package-name package))
(match (and=> (package-source package) origin-uri)
((? string? uri)
(string-prefix? "" uri))
((? list? uris)
(any (cut string-prefix? "" <>) uris))
(_ #f))))
(define %cran-updater
(upstream-updater
(name 'cran)
(description "Updater for CRAN packages")
(pred cran-package?)
(latest latest-cran-release)))
(define %bioconductor-updater
(upstream-updater
(name 'bioconductor)
(description "Updater for Bioconductor packages")
(pred bioconductor-package?)
(latest latest-bioconductor-release)))
;;; cran.scm ends here
| null | https://raw.githubusercontent.com/ragkousism/Guix-on-Hurd/e951bb2c0c4961dc6ac2bda8f331b9c4cee0da95/guix/import/cran.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Commentary:
Generate a package declaration template for the latest version of an R
cran.r-project.org.
Code:
Keys usually start with a capital letter and end with
":". There are some exceptions, unfortunately (such
as "biocViews"). There are no blanks in a key.
New key/value pair
This is a continuation of the previous pair
updated together.
This API always returns the latest release of the module.
When there is whitespace inside of items it is
probably because this was not an actual list to
begin with.
Some packages have multiple home pages. Some have none.
Generate a lazy stream of package expressions for all unknown
dependencies in the graph.
map: produce a stream element
predicate
generator: update the queue
TODO: Try the other archives before giving up
initial state
Updater.
The URL ends on
(string-append "/" name "_" version ".tar.gz")
CRAN does not provide signatures.
Bioconductor does not provide signatures.
cran.scm ends here | Copyright © 2015 , 2016 < >
Copyright © 2015 , 2016 , 2017 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (guix import cran)
#:use-module (ice-9 match)
#:use-module (ice-9 regex)
#:use-module ((ice-9 rdelim) #:select (read-string))
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-26)
#:use-module (srfi srfi-34)
#:use-module (srfi srfi-41)
#:use-module (ice-9 receive)
#:use-module (web uri)
#:use-module (guix memoization)
#:use-module (guix http-client)
#:use-module (guix hash)
#:use-module (guix store)
#:use-module (guix base32)
#:use-module ((guix download) #:select (download-to-store))
#:use-module (guix import utils)
#:use-module ((guix build-system r) #:select (cran-uri bioconductor-uri))
#:use-module (guix upstream)
#:use-module (guix packages)
#:use-module (gnu packages)
#:export (cran->guix-package
bioconductor->guix-package
recursive-import
%cran-updater
%bioconductor-updater))
package on CRAN , using the DESCRIPTION file downloaded from
(define string->license
(match-lambda
("AGPL-3" 'agpl3+)
("Artistic-2.0" 'artistic2.0)
("Apache License 2.0" 'asl2.0)
("BSD_2_clause" 'bsd-2)
("BSD_2_clause + file LICENSE" 'bsd-2)
("BSD_3_clause" 'bsd-3)
("BSD_3_clause + file LICENSE" 'bsd-3)
("GPL" (list 'gpl2+ 'gpl3+))
("GPL (>= 2)" 'gpl2+)
("GPL (>= 3)" 'gpl3+)
("GPL-2" 'gpl2)
("GPL-3" 'gpl3)
("LGPL-2" 'lgpl2.0)
("LGPL-2.1" 'lgpl2.1)
("LGPL-3" 'lgpl3)
("LGPL (>= 2)" 'lgpl2.0+)
("LGPL (>= 3)" 'lgpl3+)
("MIT" 'expat)
("MIT + file LICENSE" 'expat)
((x) (string->license x))
((lst ...) `(list ,@(map string->license lst)))
(_ #f)))
(define (description->alist description)
"Convert a DESCRIPTION string into an alist."
(let ((lines (string-split description #\newline))
(parse (lambda (line acc)
(if (string-null? line) acc
(if (string-match "^[A-Za-z][^ :]+:( |\n|$)" line)
(let* ((pos (string-index line #\:))
(key (string-take line pos))
(value (string-drop line (+ 1 pos))))
(cons (cons key
(string-trim-both value))
acc))
(match-let ((((key . value) . rest) acc))
(cons (cons key (string-join
(list value
(string-trim-both line))))
rest)))))))
(fold parse '() lines)))
(define (format-inputs names)
"Generate a sorted list of package inputs from a list of package NAMES."
(map (lambda (name)
(list name (list 'unquote (string->symbol name))))
(sort names string-ci<?)))
(define* (maybe-inputs package-inputs #:optional (type 'inputs))
"Given a list of PACKAGE-INPUTS, tries to generate the TYPE field of a
package definition."
(match package-inputs
(()
'())
((package-inputs ...)
`((,type (,'quasiquote ,(format-inputs package-inputs)))))))
(define %cran-url "-project.org/web/packages/")
(define %bioconductor-url "/")
The latest Bioconductor release is 3.4 . Bioconductor packages should be
(define %bioconductor-svn-url
(string-append ":readonly@"
"hedgehog.fhcrc.org/bioconductor/branches/RELEASE_3_4/"
"madman/Rpacks/"))
(define (fetch-description base-url name)
"Return an alist of the contents of the DESCRIPTION file for the R package
NAME, or #f in case of failure. NAME is case-sensitive."
(let ((url (string-append base-url name "/DESCRIPTION")))
(guard (c ((http-get-error? c)
(format (current-error-port)
"error: failed to retrieve package information \
from ~s: ~a (~s)~%"
(uri->string (http-get-error-uri c))
(http-get-error-code c)
(http-get-error-reason c))
#f))
(description->alist (read-string (http-fetch url))))))
(define (listify meta field)
"Look up FIELD in the alist META. If FIELD contains a comma-separated
string, turn it into a list and strip off parenthetic expressions. Return the
empty list when the FIELD cannot be found."
(let ((value (assoc-ref meta field)))
(if (not value)
'()
Strip off parentheses
(let ((items (string-split (regexp-substitute/global
#f "( *\\([^\\)]+\\)) *"
value 'pre 'post)
#\,)))
(remove (lambda (item)
(or (string-null? item)
(string-any char-set:whitespace item)))
(map string-trim-both items))))))
(define default-r-packages
(list "KernSmooth"
"MASS"
"Matrix"
"base"
"boot"
"class"
"cluster"
"codetools"
"compiler"
"datasets"
"foreign"
"grDevices"
"graphics"
"grid"
"lattice"
"methods"
"mgcv"
"nlme"
"nnet"
"parallel"
"rpart"
"spatial"
"splines"
"stats"
"stats4"
"survival"
"tcltk"
"tools"
"translations"
"utils"))
(define (guix-name name)
"Return a Guix package name for a given R package name."
(string-append "r-" (string-map (match-lambda
(#\_ #\-)
(#\. #\-)
(chr (char-downcase chr)))
name)))
(define (description->package repository meta)
"Return the `package' s-expression for an R package published on REPOSITORY
from the alist META, which was derived from the R package's DESCRIPTION file."
(let* ((base-url (case repository
((cran) %cran-url)
((bioconductor) %bioconductor-url)))
(uri-helper (case repository
((cran) cran-uri)
((bioconductor) bioconductor-uri)))
(name (assoc-ref meta "Package"))
(synopsis (assoc-ref meta "Title"))
(version (assoc-ref meta "Version"))
(license (string->license (assoc-ref meta "License")))
(home-page (match (listify meta "URL")
((url rest ...) url)
(_ (string-append base-url name))))
(source-url (match (uri-helper name version)
((url rest ...) url)
((? string? url) url)
(_ #f)))
(tarball (with-store store (download-to-store store source-url)))
(sysdepends (map string-downcase (listify meta "SystemRequirements")))
(propagate (filter (lambda (name)
(not (member name default-r-packages)))
(lset-union equal?
(listify meta "Imports")
(listify meta "LinkingTo")
(delete "R"
(listify meta "Depends"))))))
(values
`(package
(name ,(guix-name name))
(version ,version)
(source (origin
(method url-fetch)
(uri (,(procedure-name uri-helper) ,name version))
(sha256
(base32
,(bytevector->nix-base32-string (file-sha256 tarball))))))
,@(if (not (equal? (string-append "r-" name)
(guix-name name)))
`((properties ,`(,'quasiquote ((,'upstream-name . ,name)))))
'())
(build-system r-build-system)
,@(maybe-inputs sysdepends)
,@(maybe-inputs (map guix-name propagate) 'propagated-inputs)
(home-page ,(if (string-null? home-page)
(string-append base-url name)
home-page))
(synopsis ,synopsis)
(description ,(beautify-description (or (assoc-ref meta "Description")
"")))
(license ,license))
propagate)))
(define cran->guix-package
(memoize
(lambda* (package-name #:optional (repo 'cran))
"Fetch the metadata for PACKAGE-NAME from REPO and return the `package'
s-expression corresponding to that package, or #f on failure."
(let* ((url (case repo
((cran) %cran-url)
((bioconductor) %bioconductor-svn-url)))
(module-meta (fetch-description url package-name)))
(and=> module-meta (cut description->package repo <>))))))
(define* (recursive-import package-name #:optional (repo 'cran))
"Generate a stream of package expressions for PACKAGE-NAME and all its
dependencies."
(receive (package . dependencies)
(cran->guix-package package-name repo)
(if (not package)
stream-null
(let* ((make-state (lambda (queue done)
(cons queue done)))
(next (match-lambda
(((next . rest) . done) next)))
(imported (match-lambda
((queue . done) done)))
(done? (match-lambda
((queue . done)
(zero? (length queue)))))
(unknown? (lambda* (dependency #:optional (done '()))
(and (not (member dependency
done))
(null? (find-packages-by-name
(guix-name dependency))))))
(update (lambda (state new-queue)
(match state
(((head . tail) . done)
(make-state (lset-difference
equal?
(lset-union equal? new-queue tail)
done)
(cons head done)))))))
(stream-cons
package
(stream-unfold
(lambda (state)
(cran->guix-package (next state) repo))
(compose not done?)
(lambda (state)
(receive (package . dependencies)
(cran->guix-package (next state) repo)
(if package
(update state (filter (cut unknown? <>
(cons (next state)
(imported state)))
(car dependencies)))
(update state (imported state)))))
(make-state (filter unknown? (car dependencies))
(list package-name))))))))
(define (package->upstream-name package)
"Return the upstream name of the PACKAGE."
(let* ((properties (package-properties package))
(upstream-name (and=> properties
(cut assoc-ref <> 'upstream-name))))
(if upstream-name
upstream-name
(match (package-source package)
((? origin? origin)
(match (origin-uri origin)
((or (? string? url) (url _ ...))
(let ((end (string-rindex url #\_))
(start (string-rindex url #\/)))
(substring url (+ start 1) end)))
(_ #f)))
(_ #f)))))
(define (latest-cran-release package)
"Return an <upstream-source> for the latest release of PACKAGE."
(define upstream-name
(package->upstream-name package))
(define meta
(fetch-description %cran-url upstream-name))
(and meta
(let ((version (assoc-ref meta "Version")))
(upstream-source
(package (package-name package))
(version version)
(urls (cran-uri upstream-name version))))))
(define (latest-bioconductor-release package)
"Return an <upstream-source> for the latest release of PACKAGE."
(define upstream-name
(package->upstream-name package))
(define meta
(fetch-description %bioconductor-svn-url upstream-name))
(and meta
(let ((version (assoc-ref meta "Version")))
(upstream-source
(package (package-name package))
(version version)
(urls (list (bioconductor-uri upstream-name version)))))))
(define (cran-package? package)
"Return true if PACKAGE is an R package from CRAN."
(and (string-prefix? "r-" (package-name package))
(match (and=> (package-source package) origin-uri)
((? string? uri)
(string-prefix? "mirror" uri))
((? list? uris)
(any (cut string-prefix? "mirror" <>) uris))
(_ #f))))
(define (bioconductor-package? package)
"Return true if PACKAGE is an R package from Bioconductor."
(and (string-prefix? "r-" (package-name package))
(match (and=> (package-source package) origin-uri)
((? string? uri)
(string-prefix? "" uri))
((? list? uris)
(any (cut string-prefix? "" <>) uris))
(_ #f))))
(define %cran-updater
(upstream-updater
(name 'cran)
(description "Updater for CRAN packages")
(pred cran-package?)
(latest latest-cran-release)))
(define %bioconductor-updater
(upstream-updater
(name 'bioconductor)
(description "Updater for Bioconductor packages")
(pred bioconductor-package?)
(latest latest-bioconductor-release)))
|
c268389e1994f082d5660ca07561d3cf253d378628f2a71f1710930551a9fe80 | ocaml/ocaml | odoc_messages.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 2001 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(** The messages of the application. *)
let ok = "Ok"
let software = "OCamldoc"
let config_version = Config.version
let magic = config_version^""
(** Messages for command line *)
let usage = "Usage: "^(Sys.argv.(0))^" [options] <files>\n"
let options_are = "Options are:"
let latex_only = "(LaTeX only)"
let texi_only = "(TeXinfo only)"
let latex_texi_only = "(LaTeX and TeXinfo only)"
let html_only = "(HTML only)"
let html_latex_only = "(HTML and LaTeX only)"
let html_latex_texi_only = "(HTML, LaTeX and TeXinfo only)"
let man_only = "(man only)"
let option_impl ="<file> Consider <file> as a .ml file"
let option_intf ="<file> Consider <file> as a .mli file"
let option_text ="<file> Consider <file> as a .txt file"
let display_custom_generators_dir = "Display custom generators standard directory and exit"
let add_load_dir = "<dir> Add the given directory to the search path for custom\n"^
"\t\tgenerators"
let load_file = "<file.cm[o|a|xs]> Load file defining a new documentation generator"
let werr = " Treat ocamldoc warnings as errors"
let show_missed_crossref = " Show missed cross-reference opportunities"
let hide_warnings = " do not print ocamldoc warnings"
let target_dir = "<dir> Generate files in directory <dir>, rather than in current\n"^
"\t\tdirectory (for man and HTML generators)"
let dump = "<file> Dump collected information into <file>"
let load = "<file> Load information from <file> ; may be used several times"
let css_style = "<file> Use content of <file> as CSS style definition "^html_only
let index_only = " Generate index files only "^html_only
let colorize_code = " Colorize code even in documentation pages "^html_only
let html_short_functors = " Use short form to display functor types "^html_only
let charset c = Printf.sprintf
"<s> Add information about character encoding being s\n\t\t(default is %s)"
c
let no_navbar = " Do not include the navigation bar "^html_only
let generate_html = " Generate HTML documentation"
let generate_latex = " Generate LaTeX documentation"
let generate_texinfo = " Generate TeXinfo documentation"
let generate_man = " Generate man pages"
let generate_dot = " Generate dot code of top modules dependencies"
let option_not_in_native_code op = "Option "^op^" not available in native code version."
let default_out_file = "ocamldoc.out"
let out_file =
"<file> Set the output file name, used by texi, latex and dot generators\n"^
"\t\t(default is "^default_out_file^")\n"^
"\t\tor the prefix of index files for the HTML generator\n"^
"\t\t(default is index)"
let dot_include_all =
" Include all modules in the dot output, not only the\n"^
"\t\tmodules given on the command line"
let dot_types = " Generate dependency graph for types instead of modules"
let default_dot_colors =
[ [ "darkturquoise" ; "darkgoldenrod2" ; "cyan" ; "green" ; ] ;
[ "magenta" ; "yellow" ; "burlywood1" ; "aquamarine" ; "floralwhite" ; "lightpink" ] ;
[ "lightblue" ; "mediumturquoise" ; "salmon" ; "slategray3"] ;
]
let dot_colors =
" <c1,c2,...,cn>\n"^
"\t\tUse colors c1,c1,...,cn in the dot output\n"^
"\t\t(default list is "^
(String.concat ",\n\t\t" (List.map (String.concat ",") default_dot_colors))^")"
let dot_reduce =
" Perform a transitive reduction on the selected dependency graph\n"^
"\t\tbefore the dot output"
let man_mini = " Generate man pages only for modules, module types, classes\n"^
"\t\tand class types "^man_only
let default_man_section = "3"
let man_section = "<section> Use <section> in man page files "^
"(default is "^default_man_section^") "^man_only^"\n"
let default_man_suffix = default_man_section^"o"
let man_suffix = "<suffix> Use <suffix> for man page files "^
"(default is "^default_man_suffix^") "^man_only^"\n"
let option_title = "<title> Use <title> as title for the generated documentation"
let option_intro =
"<file> Use content of <file> as ocamldoc text to use as introduction\n"^
"\t\t"^(html_latex_texi_only)
let with_parameter_list = " Display the complete list of parameters for functions and\n"^
"\t\tmethods "^html_only
let hide_modules = "<M1,M2.M3,...> Hide the given complete module names in generated doc"
let no_header = " Suppress header in generated documentation\n\t\t"^latex_texi_only
let no_trailer = " Suppress trailer in generated documentation\n\t\t"^latex_texi_only
let separate_files = " Generate one file per toplevel module "^latex_only
let latex_title ref_titles =
"n,style Associate {n } to the given sectioning style\n"^
"\t\t(e.g. 'section') in the latex output "^latex_only^"\n"^
"\t\tDefault sectioning is:\n\t\t"^
(String.concat "\n\t\t"
(List.map (fun (n,t) -> Printf.sprintf " %d -> %s" n t) !ref_titles))
let default_latex_value_prefix = "val:"
let latex_value_prefix =
"<string>\n"^
"\t\tUse <string> as prefix for the LaTeX labels of values.\n"^
"\t\t(default is \""^default_latex_value_prefix^"\")"
let default_latex_type_prefix = "type:"
let latex_type_prefix =
"<string>\n"^
"\t\tUse <string> as prefix for the LaTeX labels of types.\n"^
"\t\t(default is \""^default_latex_type_prefix^"\")"
let default_latex_type_elt_prefix = "typeelt:"
let latex_type_elt_prefix =
"<string>\n"^
"\t\tUse <string> as prefix for the LaTeX labels of type elements.\n"^
"\t\t(default is \""^default_latex_type_elt_prefix^"\")"
let default_latex_extension_prefix = "extension:"
let latex_extension_prefix =
"<string>\n"^
"\t\tUse <string> as prefix for the LaTeX labels of extensions.\n"^
"\t\t(default is \""^default_latex_extension_prefix^"\")"
let default_latex_exception_prefix = "exception:"
let latex_exception_prefix =
"<string>\n"^
"\t\tUse <string> as prefix for the LaTeX labels of exceptions.\n"^
"\t\t(default is \""^default_latex_exception_prefix^"\")"
let default_latex_module_prefix = "module:"
let latex_module_prefix =
"<string>\n"^
"\t\tUse <string> as prefix for the LaTeX labels of modules.\n"^
"\t\t(default is \""^default_latex_module_prefix^"\")"
let default_latex_module_type_prefix = "moduletype:"
let latex_module_type_prefix =
"<string>\n"^
"\t\tUse <string> as prefix for the LaTeX labels of module types.\n"^
"\t\t(default is \""^default_latex_module_type_prefix^"\")"
let default_latex_class_prefix = "class:"
let latex_class_prefix =
"<string>\n"^
"\t\tUse <string> as prefix for the LaTeX labels of classes.\n"^
"\t\t(default is \""^default_latex_class_prefix^"\")"
let default_latex_class_type_prefix = "classtype:"
let latex_class_type_prefix =
"<string>\n"^
"\t\tUse <string> as prefix for the LaTeX labels of class types.\n"^
"\t\t(default is \""^default_latex_class_type_prefix^"\")"
let default_latex_attribute_prefix = "val:"
let latex_attribute_prefix =
"<string>\n"^
"\t\tUse <string> as prefix for the LaTeX labels of attributes.\n"^
"\t\t(default is \""^default_latex_attribute_prefix^"\")"
let default_latex_method_prefix = "method:"
let latex_method_prefix =
"<string>\n"^
"\t\tUse <string> as prefix for the LaTeX labels of methods.\n"^
"\t\t(default is \""^default_latex_method_prefix^"\")"
let no_toc = " Do not generate table of contents "^latex_only
let sort_modules = " Sort the list of top modules before generating the documentation"
let no_stop = " Do not stop at (**/**) comments"
let no_custom_tags = " Do not allow custom @-tags"
let remove_stars = " Remove beginning blanks of comment lines, until the first '*'"
let keep_code = " Always keep code when available"
let inverse_merge_ml_mli = " Inverse implementations and interfaces when merging"
let no_filter_with_module_constraints = "Do not filter module elements using module type constraints"
let merge_description = ('d', "merge description")
let merge_author = ('a', "merge @author")
let merge_version = ('v', "merge @version")
let merge_see = ('l', "merge @see")
let merge_since = ('s', "merge @since")
let merge_before = ('b', "merge @before")
let merge_deprecated = ('o', "merge @deprecated")
let merge_param = ('p', "merge @param")
let merge_raised_exception = ('e', "merge @raise")
let merge_return_value = ('r', "merge @return")
let merge_custom = ('c', "merge custom @-tags")
let merge_all = ('A', "merge all")
let no_index = " Do not build index for Info files "^texi_only
let esc_8bits = " Escape accentuated characters in Info files "^texi_only
let texinfo_title r=
"n,style Associate {n } to the given sectioning style\n"^
"\t\t(e.g. 'section') in the texInfo output "^texi_only^"\n"^
"\t\tDefault sectioning is:\n\t\t"^
(String.concat "\n\t\t"
(List.map (fun (n,(t,h)) ->
Printf.sprintf " %d -> %s, %s " n t h) !r))
let info_section = " Specify section of Info directory "^texi_only
let info_entry = " Specify Info directory entry "^texi_only
let options_can_be = "<options> can be one or more of the following characters:"
let string_of_options_list l =
List.fold_left (fun acc -> fun (c, m) -> acc^"\n\t\t"^(String.make 1 c)^" "^m)
""
l
let merge_options =
"<options> specify merge options between .mli and .ml\n\t\t"^
options_can_be^
(string_of_options_list
[ merge_description ;
merge_author ;
merge_version ;
merge_see ;
merge_since ;
merge_before ;
merge_deprecated ;
merge_param ;
merge_raised_exception ;
merge_return_value ;
merge_custom ;
merge_all ]
)
let initially_opened_module = "<module> Name of the module that is initially opened"
let library_namespace =
"<module> Name of the library namespace for a prefixed library.\
Note: very experimental."
let help = " Display this list of options"
(** Error and warning messages *)
let warning = "Warning"
let error_location file l c =
Printf.sprintf "File \"%s\", line %d, character %d:\n" file l c
let bad_magic_number =
"Bad magic number for this ocamldoc dump!\n"^
"This dump was not created by this version of OCamldoc."
let not_a_module_name s = s^" is not a valid module name"
let load_file_error f e = "Error while loading file "^f^":\n"^e
let wrong_format s = "Wrong format for \""^s^"\""
let errors_occured n = (Int.to_string n)^" error(s) encountered"
let parse_error = "Parse error"
let text_parse_error l c s =
let lines = Str.split (Str.regexp_string "\n") s in
"Error parsing text:\n"
^ (List.nth lines l) ^ "\n"
^ (String.make c ' ') ^ "^"
let file_not_found_in_paths paths name =
Printf.sprintf "No file %s found in the load paths: \n%s"
name
(String.concat "\n" paths)
let tag_not_handled tag = "Tag @"^tag^" not handled by this generator"
let should_escape_at_sign = "The character @ has a special meaning in ocamldoc comments, for commands such as @raise or @since. \
If you want to write a single @, you must escape it as \\@."
let bad_tree = "Incorrect tree structure."
let not_a_valid_tag s = s^" is not a valid tag."
let fun_without_param f = "Function "^f^" has no parameter."
let method_without_param f = "Method "^f^" has no parameter."
let anonymous_parameters f = "Function "^f^" has anonymous parameters."
let function_colon f = "Function "^f^": "
let implicit_match_in_parameter = "Parameters contain implicit pattern matching."
let unknown_extension f = "Unknown extension for file "^f^"."
let two_implementations name = "There are two implementations of module "^name^"."
let two_interfaces name = "There are two interfaces of module "^name^"."
let too_many_module_objects name = "There are too many interfaces/implementation of module "^name^"."
let extension_not_found_in_implementation ext m = "Extension "^ext^" was not found in implementation of module "^m^"."
let exception_not_found_in_implementation exc m = "Exception "^exc^" was not found in implementation of module "^m^"."
let type_not_found_in_implementation exc m = "Type "^exc^" was not found in implementation of module "^m^"."
let module_not_found_in_implementation m m2 = "Module "^m^" was not found in implementation of module "^m2^"."
let value_not_found_in_implementation v m = "Value "^v^" was not found in implementation of module "^m^"."
let class_not_found_in_implementation c m = "Class "^c^" was not found in implementation of module "^m^"."
let attribute_not_found_in_implementation a c = "Attribute "^a^" was not found in implementation of class "^c^"."
let method_not_found_in_implementation m c = "Method "^m^" was not found in implementation of class "^c^"."
let different_types t = "Definition of type "^t^" doesn't match from interface to implementation."
let attribute_type_not_found cl att = "The type of the attribute "^att^" could not be found in the signature of class "^cl^"."
let method_type_not_found cl met = "The type of the method "^met^" could not be found in the signature of class "^cl^"."
let module_not_found m m2 = "The module "^m2^" could not be found in the signature of module "^m^"."
let module_type_not_found m mt = "The module type "^mt^" could not be found in the signature of module "^m^"."
let value_not_found m v = "The value "^v^" could not be found in the signature of module "^m^"."
let extension_not_found m e = "The extension "^e^" could not be found in the signature of module "^m^"."
let exception_not_found m e = "The exception "^e^" could not be found in the signature of module "^m^"."
let type_not_found m t = "The type "^t^" could not be found in the signature of module "^m^"."
let class_not_found m c = "The class "^c^" could not be found in the signature of module "^m^"."
let class_type_not_found m c = "The class type "^c^" could not be found in the signature of module "^m^"."
let type_not_found_in_typedtree t = "Type "^t^" was not found in typed tree."
let extension_not_found_in_typedtree x = "Extension "^x^" was not found in typed tree."
let exception_not_found_in_typedtree e = "Exception "^e^" was not found in typed tree."
let module_type_not_found_in_typedtree mt = "Module type "^mt^" was not found in typed tree."
let module_not_found_in_typedtree m = "Module "^m^" was not found in typed tree."
let class_not_found_in_typedtree c = "Class "^c^" was not found in typed tree."
let class_type_not_found_in_typedtree ct = "Class type "^ct^" was not found in typed tree."
let inherit_classexp_not_found_in_typedtree n =
"Inheritance class expression number "^(Int.to_string n)^" was not found in typed tree."
let attribute_not_found_in_typedtree att = "Class attribute "^att^" was not found in typed tree."
let method_not_found_in_typedtree met = "Class method "^met^" was not found in typed tree."
let misplaced_comment file pos =
Printf.sprintf "Misplaced special comment in file %s, character %d." file pos
let cross_module_not_found n = "Module "^n^" not found"
let cross_module_type_not_found n = "Module type "^n^" not found"
let cross_module_or_module_type_not_found n = "Module or module type "^n^" not found"
let cross_class_not_found n = "Class "^n^" not found"
let cross_class_type_not_found n = "class type "^n^" not found"
let cross_class_or_class_type_not_found n = "Class or class type "^n^" not found"
let cross_extension_not_found n = "Extension "^n^" not found"
let cross_exception_not_found n = "Exception "^n^" not found"
let cross_element_not_found n = "Element "^n^" not found"
let cross_method_not_found n = "Method "^n^" not found"
let cross_attribute_not_found n = "Attribute "^n^" not found"
let cross_section_not_found n = "Section "^n^" not found"
let cross_value_not_found n = "Value "^n^" not found"
let cross_type_not_found n = "Type "^n^" not found"
let cross_recfield_not_found n = Printf.sprintf "Record field %s not found" n
let cross_const_not_found n = Printf.sprintf "Constructor %s not found" n
let code_could_be_cross_reference n parent =
Printf.sprintf "Code element [%s] in %s corresponds to a known \
cross-referenceable element, it might be worthwhile to replace it \
with {!%s}" n parent n
let object_end = "object ... end"
let struct_end = "struct ... end"
let sig_end = "sig ... end"
let current_generator_is_not kind =
Printf.sprintf "Current generator is not a %s generator" kind
(** Messages for verbose mode. *)
let analysing f = "Analysing file "^f^"..."
let merging = "Merging..."
let cross_referencing = "Cross referencing..."
let generating_doc = "Generating documentation..."
let loading f = "Loading "^f^"..."
let file_generated f = "File "^f^" generated."
let file_exists_dont_generate f =
"File "^f^" exists, we don't generate it."
(** Messages for documentation generation.*)
let modul = "Module"
let modules = "Modules"
let functors = "Functors"
let values = "Simple values"
let types = "Types"
let extensions = "Extensions"
let exceptions = "Exceptions"
let record = "Record"
let variant = "Variant"
let mutab = "mutable"
let functions = "Functions"
let parameters = "Parameters"
let abstract = "Abstract"
let functo = "Functor"
let clas = "Class"
let classes = "Classes"
let attributes = "Attributes"
let methods = "Methods"
let authors = "Author(s)"
let version = "Version"
let since = "Since"
let before = "Before"
let deprecated = "Deprecated"
let alert = "Alert"
let raises = "Raises"
let returns = "Returns"
let inherits = "Inherits"
let inheritance = "Inheritance"
let privat = "private"
let module_type = "Module type"
let class_type = "Class type"
let description = "Description"
let interface = "Interface"
let type_parameters = "Type parameters"
let class_types = "Class types"
let module_types = "Module types"
let see_also = "See also"
let documentation = "Documentation"
let index_of = "Index of"
let top = "Top"
let index_of_values = index_of^" values"
let index_of_extensions = index_of^" extensions"
let index_of_exceptions = index_of^" exceptions"
let index_of_types = index_of^" types"
let index_of_attributes = index_of^" class attributes"
let index_of_methods = index_of^" class methods"
let index_of_classes = index_of^" classes"
let index_of_class_types = index_of^" class types"
let index_of_modules = index_of^" modules"
let index_of_module_types = index_of^" module types"
let previous = "Previous"
let next = "Next"
let up = "Up"
| null | https://raw.githubusercontent.com/ocaml/ocaml/04ddddd0e1d2bf2acb5091f434b93387243d4624/ocamldoc/odoc_messages.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
* The messages of the application.
* Messages for command line
* Error and warning messages
* Messages for verbose mode.
* Messages for documentation generation. | , projet Cristal , INRIA Rocquencourt
Copyright 2001 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
let ok = "Ok"
let software = "OCamldoc"
let config_version = Config.version
let magic = config_version^""
let usage = "Usage: "^(Sys.argv.(0))^" [options] <files>\n"
let options_are = "Options are:"
let latex_only = "(LaTeX only)"
let texi_only = "(TeXinfo only)"
let latex_texi_only = "(LaTeX and TeXinfo only)"
let html_only = "(HTML only)"
let html_latex_only = "(HTML and LaTeX only)"
let html_latex_texi_only = "(HTML, LaTeX and TeXinfo only)"
let man_only = "(man only)"
let option_impl ="<file> Consider <file> as a .ml file"
let option_intf ="<file> Consider <file> as a .mli file"
let option_text ="<file> Consider <file> as a .txt file"
let display_custom_generators_dir = "Display custom generators standard directory and exit"
let add_load_dir = "<dir> Add the given directory to the search path for custom\n"^
"\t\tgenerators"
let load_file = "<file.cm[o|a|xs]> Load file defining a new documentation generator"
let werr = " Treat ocamldoc warnings as errors"
let show_missed_crossref = " Show missed cross-reference opportunities"
let hide_warnings = " do not print ocamldoc warnings"
let target_dir = "<dir> Generate files in directory <dir>, rather than in current\n"^
"\t\tdirectory (for man and HTML generators)"
let dump = "<file> Dump collected information into <file>"
let load = "<file> Load information from <file> ; may be used several times"
let css_style = "<file> Use content of <file> as CSS style definition "^html_only
let index_only = " Generate index files only "^html_only
let colorize_code = " Colorize code even in documentation pages "^html_only
let html_short_functors = " Use short form to display functor types "^html_only
let charset c = Printf.sprintf
"<s> Add information about character encoding being s\n\t\t(default is %s)"
c
let no_navbar = " Do not include the navigation bar "^html_only
let generate_html = " Generate HTML documentation"
let generate_latex = " Generate LaTeX documentation"
let generate_texinfo = " Generate TeXinfo documentation"
let generate_man = " Generate man pages"
let generate_dot = " Generate dot code of top modules dependencies"
let option_not_in_native_code op = "Option "^op^" not available in native code version."
let default_out_file = "ocamldoc.out"
let out_file =
"<file> Set the output file name, used by texi, latex and dot generators\n"^
"\t\t(default is "^default_out_file^")\n"^
"\t\tor the prefix of index files for the HTML generator\n"^
"\t\t(default is index)"
let dot_include_all =
" Include all modules in the dot output, not only the\n"^
"\t\tmodules given on the command line"
let dot_types = " Generate dependency graph for types instead of modules"
let default_dot_colors =
[ [ "darkturquoise" ; "darkgoldenrod2" ; "cyan" ; "green" ; ] ;
[ "magenta" ; "yellow" ; "burlywood1" ; "aquamarine" ; "floralwhite" ; "lightpink" ] ;
[ "lightblue" ; "mediumturquoise" ; "salmon" ; "slategray3"] ;
]
let dot_colors =
" <c1,c2,...,cn>\n"^
"\t\tUse colors c1,c1,...,cn in the dot output\n"^
"\t\t(default list is "^
(String.concat ",\n\t\t" (List.map (String.concat ",") default_dot_colors))^")"
let dot_reduce =
" Perform a transitive reduction on the selected dependency graph\n"^
"\t\tbefore the dot output"
let man_mini = " Generate man pages only for modules, module types, classes\n"^
"\t\tand class types "^man_only
let default_man_section = "3"
let man_section = "<section> Use <section> in man page files "^
"(default is "^default_man_section^") "^man_only^"\n"
let default_man_suffix = default_man_section^"o"
let man_suffix = "<suffix> Use <suffix> for man page files "^
"(default is "^default_man_suffix^") "^man_only^"\n"
let option_title = "<title> Use <title> as title for the generated documentation"
let option_intro =
"<file> Use content of <file> as ocamldoc text to use as introduction\n"^
"\t\t"^(html_latex_texi_only)
let with_parameter_list = " Display the complete list of parameters for functions and\n"^
"\t\tmethods "^html_only
let hide_modules = "<M1,M2.M3,...> Hide the given complete module names in generated doc"
let no_header = " Suppress header in generated documentation\n\t\t"^latex_texi_only
let no_trailer = " Suppress trailer in generated documentation\n\t\t"^latex_texi_only
let separate_files = " Generate one file per toplevel module "^latex_only
let latex_title ref_titles =
"n,style Associate {n } to the given sectioning style\n"^
"\t\t(e.g. 'section') in the latex output "^latex_only^"\n"^
"\t\tDefault sectioning is:\n\t\t"^
(String.concat "\n\t\t"
(List.map (fun (n,t) -> Printf.sprintf " %d -> %s" n t) !ref_titles))
let default_latex_value_prefix = "val:"
let latex_value_prefix =
"<string>\n"^
"\t\tUse <string> as prefix for the LaTeX labels of values.\n"^
"\t\t(default is \""^default_latex_value_prefix^"\")"
let default_latex_type_prefix = "type:"
let latex_type_prefix =
"<string>\n"^
"\t\tUse <string> as prefix for the LaTeX labels of types.\n"^
"\t\t(default is \""^default_latex_type_prefix^"\")"
let default_latex_type_elt_prefix = "typeelt:"
let latex_type_elt_prefix =
"<string>\n"^
"\t\tUse <string> as prefix for the LaTeX labels of type elements.\n"^
"\t\t(default is \""^default_latex_type_elt_prefix^"\")"
let default_latex_extension_prefix = "extension:"
let latex_extension_prefix =
"<string>\n"^
"\t\tUse <string> as prefix for the LaTeX labels of extensions.\n"^
"\t\t(default is \""^default_latex_extension_prefix^"\")"
let default_latex_exception_prefix = "exception:"
let latex_exception_prefix =
"<string>\n"^
"\t\tUse <string> as prefix for the LaTeX labels of exceptions.\n"^
"\t\t(default is \""^default_latex_exception_prefix^"\")"
let default_latex_module_prefix = "module:"
let latex_module_prefix =
"<string>\n"^
"\t\tUse <string> as prefix for the LaTeX labels of modules.\n"^
"\t\t(default is \""^default_latex_module_prefix^"\")"
let default_latex_module_type_prefix = "moduletype:"
let latex_module_type_prefix =
"<string>\n"^
"\t\tUse <string> as prefix for the LaTeX labels of module types.\n"^
"\t\t(default is \""^default_latex_module_type_prefix^"\")"
let default_latex_class_prefix = "class:"
let latex_class_prefix =
"<string>\n"^
"\t\tUse <string> as prefix for the LaTeX labels of classes.\n"^
"\t\t(default is \""^default_latex_class_prefix^"\")"
let default_latex_class_type_prefix = "classtype:"
let latex_class_type_prefix =
"<string>\n"^
"\t\tUse <string> as prefix for the LaTeX labels of class types.\n"^
"\t\t(default is \""^default_latex_class_type_prefix^"\")"
let default_latex_attribute_prefix = "val:"
let latex_attribute_prefix =
"<string>\n"^
"\t\tUse <string> as prefix for the LaTeX labels of attributes.\n"^
"\t\t(default is \""^default_latex_attribute_prefix^"\")"
let default_latex_method_prefix = "method:"
let latex_method_prefix =
"<string>\n"^
"\t\tUse <string> as prefix for the LaTeX labels of methods.\n"^
"\t\t(default is \""^default_latex_method_prefix^"\")"
let no_toc = " Do not generate table of contents "^latex_only
let sort_modules = " Sort the list of top modules before generating the documentation"
let no_stop = " Do not stop at (**/**) comments"
let no_custom_tags = " Do not allow custom @-tags"
let remove_stars = " Remove beginning blanks of comment lines, until the first '*'"
let keep_code = " Always keep code when available"
let inverse_merge_ml_mli = " Inverse implementations and interfaces when merging"
let no_filter_with_module_constraints = "Do not filter module elements using module type constraints"
let merge_description = ('d', "merge description")
let merge_author = ('a', "merge @author")
let merge_version = ('v', "merge @version")
let merge_see = ('l', "merge @see")
let merge_since = ('s', "merge @since")
let merge_before = ('b', "merge @before")
let merge_deprecated = ('o', "merge @deprecated")
let merge_param = ('p', "merge @param")
let merge_raised_exception = ('e', "merge @raise")
let merge_return_value = ('r', "merge @return")
let merge_custom = ('c', "merge custom @-tags")
let merge_all = ('A', "merge all")
let no_index = " Do not build index for Info files "^texi_only
let esc_8bits = " Escape accentuated characters in Info files "^texi_only
let texinfo_title r=
"n,style Associate {n } to the given sectioning style\n"^
"\t\t(e.g. 'section') in the texInfo output "^texi_only^"\n"^
"\t\tDefault sectioning is:\n\t\t"^
(String.concat "\n\t\t"
(List.map (fun (n,(t,h)) ->
Printf.sprintf " %d -> %s, %s " n t h) !r))
let info_section = " Specify section of Info directory "^texi_only
let info_entry = " Specify Info directory entry "^texi_only
let options_can_be = "<options> can be one or more of the following characters:"
let string_of_options_list l =
List.fold_left (fun acc -> fun (c, m) -> acc^"\n\t\t"^(String.make 1 c)^" "^m)
""
l
let merge_options =
"<options> specify merge options between .mli and .ml\n\t\t"^
options_can_be^
(string_of_options_list
[ merge_description ;
merge_author ;
merge_version ;
merge_see ;
merge_since ;
merge_before ;
merge_deprecated ;
merge_param ;
merge_raised_exception ;
merge_return_value ;
merge_custom ;
merge_all ]
)
let initially_opened_module = "<module> Name of the module that is initially opened"
let library_namespace =
"<module> Name of the library namespace for a prefixed library.\
Note: very experimental."
let help = " Display this list of options"
let warning = "Warning"
let error_location file l c =
Printf.sprintf "File \"%s\", line %d, character %d:\n" file l c
let bad_magic_number =
"Bad magic number for this ocamldoc dump!\n"^
"This dump was not created by this version of OCamldoc."
let not_a_module_name s = s^" is not a valid module name"
let load_file_error f e = "Error while loading file "^f^":\n"^e
let wrong_format s = "Wrong format for \""^s^"\""
let errors_occured n = (Int.to_string n)^" error(s) encountered"
let parse_error = "Parse error"
let text_parse_error l c s =
let lines = Str.split (Str.regexp_string "\n") s in
"Error parsing text:\n"
^ (List.nth lines l) ^ "\n"
^ (String.make c ' ') ^ "^"
let file_not_found_in_paths paths name =
Printf.sprintf "No file %s found in the load paths: \n%s"
name
(String.concat "\n" paths)
let tag_not_handled tag = "Tag @"^tag^" not handled by this generator"
let should_escape_at_sign = "The character @ has a special meaning in ocamldoc comments, for commands such as @raise or @since. \
If you want to write a single @, you must escape it as \\@."
let bad_tree = "Incorrect tree structure."
let not_a_valid_tag s = s^" is not a valid tag."
let fun_without_param f = "Function "^f^" has no parameter."
let method_without_param f = "Method "^f^" has no parameter."
let anonymous_parameters f = "Function "^f^" has anonymous parameters."
let function_colon f = "Function "^f^": "
let implicit_match_in_parameter = "Parameters contain implicit pattern matching."
let unknown_extension f = "Unknown extension for file "^f^"."
let two_implementations name = "There are two implementations of module "^name^"."
let two_interfaces name = "There are two interfaces of module "^name^"."
let too_many_module_objects name = "There are too many interfaces/implementation of module "^name^"."
let extension_not_found_in_implementation ext m = "Extension "^ext^" was not found in implementation of module "^m^"."
let exception_not_found_in_implementation exc m = "Exception "^exc^" was not found in implementation of module "^m^"."
let type_not_found_in_implementation exc m = "Type "^exc^" was not found in implementation of module "^m^"."
let module_not_found_in_implementation m m2 = "Module "^m^" was not found in implementation of module "^m2^"."
let value_not_found_in_implementation v m = "Value "^v^" was not found in implementation of module "^m^"."
let class_not_found_in_implementation c m = "Class "^c^" was not found in implementation of module "^m^"."
let attribute_not_found_in_implementation a c = "Attribute "^a^" was not found in implementation of class "^c^"."
let method_not_found_in_implementation m c = "Method "^m^" was not found in implementation of class "^c^"."
let different_types t = "Definition of type "^t^" doesn't match from interface to implementation."
let attribute_type_not_found cl att = "The type of the attribute "^att^" could not be found in the signature of class "^cl^"."
let method_type_not_found cl met = "The type of the method "^met^" could not be found in the signature of class "^cl^"."
let module_not_found m m2 = "The module "^m2^" could not be found in the signature of module "^m^"."
let module_type_not_found m mt = "The module type "^mt^" could not be found in the signature of module "^m^"."
let value_not_found m v = "The value "^v^" could not be found in the signature of module "^m^"."
let extension_not_found m e = "The extension "^e^" could not be found in the signature of module "^m^"."
let exception_not_found m e = "The exception "^e^" could not be found in the signature of module "^m^"."
let type_not_found m t = "The type "^t^" could not be found in the signature of module "^m^"."
let class_not_found m c = "The class "^c^" could not be found in the signature of module "^m^"."
let class_type_not_found m c = "The class type "^c^" could not be found in the signature of module "^m^"."
let type_not_found_in_typedtree t = "Type "^t^" was not found in typed tree."
let extension_not_found_in_typedtree x = "Extension "^x^" was not found in typed tree."
let exception_not_found_in_typedtree e = "Exception "^e^" was not found in typed tree."
let module_type_not_found_in_typedtree mt = "Module type "^mt^" was not found in typed tree."
let module_not_found_in_typedtree m = "Module "^m^" was not found in typed tree."
let class_not_found_in_typedtree c = "Class "^c^" was not found in typed tree."
let class_type_not_found_in_typedtree ct = "Class type "^ct^" was not found in typed tree."
let inherit_classexp_not_found_in_typedtree n =
"Inheritance class expression number "^(Int.to_string n)^" was not found in typed tree."
let attribute_not_found_in_typedtree att = "Class attribute "^att^" was not found in typed tree."
let method_not_found_in_typedtree met = "Class method "^met^" was not found in typed tree."
let misplaced_comment file pos =
Printf.sprintf "Misplaced special comment in file %s, character %d." file pos
let cross_module_not_found n = "Module "^n^" not found"
let cross_module_type_not_found n = "Module type "^n^" not found"
let cross_module_or_module_type_not_found n = "Module or module type "^n^" not found"
let cross_class_not_found n = "Class "^n^" not found"
let cross_class_type_not_found n = "class type "^n^" not found"
let cross_class_or_class_type_not_found n = "Class or class type "^n^" not found"
let cross_extension_not_found n = "Extension "^n^" not found"
let cross_exception_not_found n = "Exception "^n^" not found"
let cross_element_not_found n = "Element "^n^" not found"
let cross_method_not_found n = "Method "^n^" not found"
let cross_attribute_not_found n = "Attribute "^n^" not found"
let cross_section_not_found n = "Section "^n^" not found"
let cross_value_not_found n = "Value "^n^" not found"
let cross_type_not_found n = "Type "^n^" not found"
let cross_recfield_not_found n = Printf.sprintf "Record field %s not found" n
let cross_const_not_found n = Printf.sprintf "Constructor %s not found" n
let code_could_be_cross_reference n parent =
Printf.sprintf "Code element [%s] in %s corresponds to a known \
cross-referenceable element, it might be worthwhile to replace it \
with {!%s}" n parent n
let object_end = "object ... end"
let struct_end = "struct ... end"
let sig_end = "sig ... end"
let current_generator_is_not kind =
Printf.sprintf "Current generator is not a %s generator" kind
let analysing f = "Analysing file "^f^"..."
let merging = "Merging..."
let cross_referencing = "Cross referencing..."
let generating_doc = "Generating documentation..."
let loading f = "Loading "^f^"..."
let file_generated f = "File "^f^" generated."
let file_exists_dont_generate f =
"File "^f^" exists, we don't generate it."
let modul = "Module"
let modules = "Modules"
let functors = "Functors"
let values = "Simple values"
let types = "Types"
let extensions = "Extensions"
let exceptions = "Exceptions"
let record = "Record"
let variant = "Variant"
let mutab = "mutable"
let functions = "Functions"
let parameters = "Parameters"
let abstract = "Abstract"
let functo = "Functor"
let clas = "Class"
let classes = "Classes"
let attributes = "Attributes"
let methods = "Methods"
let authors = "Author(s)"
let version = "Version"
let since = "Since"
let before = "Before"
let deprecated = "Deprecated"
let alert = "Alert"
let raises = "Raises"
let returns = "Returns"
let inherits = "Inherits"
let inheritance = "Inheritance"
let privat = "private"
let module_type = "Module type"
let class_type = "Class type"
let description = "Description"
let interface = "Interface"
let type_parameters = "Type parameters"
let class_types = "Class types"
let module_types = "Module types"
let see_also = "See also"
let documentation = "Documentation"
let index_of = "Index of"
let top = "Top"
let index_of_values = index_of^" values"
let index_of_extensions = index_of^" extensions"
let index_of_exceptions = index_of^" exceptions"
let index_of_types = index_of^" types"
let index_of_attributes = index_of^" class attributes"
let index_of_methods = index_of^" class methods"
let index_of_classes = index_of^" classes"
let index_of_class_types = index_of^" class types"
let index_of_modules = index_of^" modules"
let index_of_module_types = index_of^" module types"
let previous = "Previous"
let next = "Next"
let up = "Up"
|
b430686f779133b7624e271be42176bc23924373b40ef60fea26016e2fdd4afe | blarney-lang/blarney | RAM.hs | import Blarney
import Blarney.Stmt
import System.Environment
-- Top-level module
top :: Module ()
top = do
-- RAM
ram :: RAM (Bit 8) (Bit 128) <- makeRAM
-- Counter
i :: Reg (Bit 8) <- makeReg 0
-- Simple test sequence
runStmt do
while (i.val .<. 100) do
action do
ram.store i.val (1 .<<. i.val)
i <== i.val + 1
action do
i <== 0
while (i.val .<. 100) do
action do
ram.load i.val
action do
display "ram[" i.val "] = 0x" (formatHex 32 ram.out)
i <== i.val + 1
action do
finish
return ()
-- Main function
main :: IO ()
main = do
args <- getArgs
if | "--simulate" `elem` args -> simulate top
| otherwise -> writeVerilogTop top "RAM" "RAM-Verilog/"
| null | https://raw.githubusercontent.com/blarney-lang/blarney/e80a547b092462f1beb9378e6c806db679ff62b4/Examples/RAM/RAM.hs | haskell | Top-level module
RAM
Counter
Simple test sequence
Main function | import Blarney
import Blarney.Stmt
import System.Environment
top :: Module ()
top = do
ram :: RAM (Bit 8) (Bit 128) <- makeRAM
i :: Reg (Bit 8) <- makeReg 0
runStmt do
while (i.val .<. 100) do
action do
ram.store i.val (1 .<<. i.val)
i <== i.val + 1
action do
i <== 0
while (i.val .<. 100) do
action do
ram.load i.val
action do
display "ram[" i.val "] = 0x" (formatHex 32 ram.out)
i <== i.val + 1
action do
finish
return ()
main :: IO ()
main = do
args <- getArgs
if | "--simulate" `elem` args -> simulate top
| otherwise -> writeVerilogTop top "RAM" "RAM-Verilog/"
|
0aeb24fd3cb42599c92debe493624cd97bca88f4c5e35ec1424fb93a67c64b73 | erlyvideo/publisher | rtmp_handshake.erl | @private
@author < > [ ]
@author Thanks to all those guys , that have found how to sign handshake .
2010
%%% @doc RTMP handshake module
%%% @reference See <a href="" target="_top"></a> for more information
also good reference is
%%% @end
%%%
This file is part of erlang - rtmp .
%%%
%%% erlang-rtmp is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
%%% (at your option) any later version.
%%%
%%% erlang-rtmp 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 erlang - rtmp . If not , see < / > .
%%%
%%%---------------------------------------------------------------------------------------
-module(rtmp_handshake).
-version(1.0).
-export([server/1, c1/0, c2/1, client_scheme_version/1]).
-include("../include/rtmp.hrl").
-include("rtmp_private.hrl").
-include_lib("eunit/include/eunit.hrl").
-define(DIGEST_SIZE, 32).
-define(GENUINE_FMS_KEY, <<"Genuine Adobe Flash Media Server 001",
16#f0,16#ee,16#c2,16#4a,16#80,16#68,16#be,16#e8,16#2e,16#00,16#d0,16#d1,
16#02,16#9e,16#7e,16#57,16#6e,16#ec,16#5d,16#2d,16#29,16#80,16#6f,16#ab,16#93,16#b8,16#e6,16#36,
16#cf,16#eb,16#31,16#ae>>).
-define(GENUINE_FP_KEY, <<"Genuine Adobe Flash Player 001",
16#F0, 16#EE, 16#C2, 16#4A, 16#80, 16#68, 16#BE, 16#E8,
16#2E, 16#00, 16#D0, 16#D1, 16#02, 16#9E, 16#7E, 16#57,
16#6E, 16#EC, 16#5D, 16#2D, 16#29, 16#80, 16#6F, 16#AB,
16#93, 16#B8, 16#E6, 16#36, 16#CF, 16#EB, 16#31, 16#AE>>).
-spec clientDigest(Handshake::binary(), handshake_version()) -> {First::binary(), Seed::binary(), Last::binary()}.
Flash before 10.0.32.18
clientDigest(<<_:8/binary, P1, P2, P3, P4, _/binary>> = C1, version1) ->
Offset = (P1+P2+P3+P4) rem 728 + 12,
<<First:Offset/binary, Seed:?DIGEST_SIZE/binary, Last/binary>> = C1,
{First, Seed, Last};
Flash from 10.0.32.18
clientDigest(<<_:772/binary, P1, P2, P3, P4, _/binary>> = C1, version2) ->
Offset = (P1+P2+P3+P4) rem 728 + 776,
<<First:Offset/binary, Seed:?DIGEST_SIZE/binary, Last/binary>> = C1,
{First, Seed, Last}.
-spec validate_scheme_version(C1::binary(), Version::handshake_version()) -> boolean().
validate_scheme_version(C1, Version) ->
{First, ClientDigest, Last} = clientDigest(C1, Version),
{Key, _} = erlang:split_binary(?GENUINE_FP_KEY, 30),
ClientDigest == hmac256:digest_bin(Key, <<First/binary, Last/binary>>).
-spec client_scheme_version(C1::binary()) -> handshake_version().
client_scheme_version(C1) ->
case validate_scheme_version(C1, version1) of
true -> version1;
false -> case validate_scheme_version(C1, version2) of
true -> version2;
false -> version1
end
end.
c1() ->
[?HS_UNCRYPTED, <<0:32, 0:32>>, crypto:rand_bytes(?HS_BODY_LEN - 8)].
c2(<<_Time:32, _V1,_V2,_V3,_V4, _Rand/binary>> = S1) ->
io : format("Server : ~p , ~p.~p.~p.~p ~ n " , [ Time , V1 , V2 , V3 , V4 ] ) ,
S1.
server(<<?HS_UNCRYPTED , C1:?HS_BODY_LEN / binary > > ) - >
{ uncrypted , [ ? HS_UNCRYPTED , s1 ( ) , s2(C1 ) ] } ;
%
server(<<Encryption, C2:?HS_BODY_LEN/binary>>) ->
SchemeVersion = client_scheme_version(C2),
{KeyIn, KeyOut, Response2} = case Encryption of
?HS_CRYPTED ->
rtmpe:s2(C2, Encryption);
?HS_UNCRYPTED ->
{undefined, undefined, <<0:32, 3,0,2,1, (crypto:rand_bytes(?HS_BODY_LEN - 8))/binary>>}
end,
%% Now generate digest of S2
{Digest1, _, Digest2} = clientDigest(Response2, SchemeVersion),
{ServerFMSKey, _} = erlang:split_binary(?GENUINE_FMS_KEY, 36),
ServerDigest = hmac256:digest_bin(ServerFMSKey, <<Digest1/binary, Digest2/binary>>),
S2 = <<Digest1/binary, ServerDigest/binary, Digest2/binary>>,
? D({serverDH , size(ServerFirst ) , serverDigest , size(Digest1 ) } ) ,
%% ------ S3
Response4 = crypto:rand_bytes(?HS_BODY_LEN - 32),
{_, ClientDigest, _} = clientDigest(C2, SchemeVersion),
TempHash = hmac256:digest_bin(?GENUINE_FMS_KEY, ClientDigest),
ClientHash = hmac256:digest_bin(TempHash, Response4),
S3 = <<Response4/binary, ClientHash/binary>>,
case Encryption of
?HS_CRYPTED ->
{crypted, [?HS_CRYPTED, S2, S3], KeyIn, KeyOut};
?HS_UNCRYPTED ->
{uncrypted, [?HS_UNCRYPTED, S2, S3]}
end.
| null | https://raw.githubusercontent.com/erlyvideo/publisher/5bb2dfa6477c46160dc5fafcc030fc3f5340ec80/apps/rtmp/src/rtmp_handshake.erl | erlang | @doc RTMP handshake module
@reference See <a href="" target="_top"></a> for more information
@end
erlang-rtmp is free software: you can redistribute it and/or modify
(at your option) any later version.
erlang-rtmp 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.
---------------------------------------------------------------------------------------
Now generate digest of S2
------ S3 | @private
@author < > [ ]
@author Thanks to all those guys , that have found how to sign handshake .
2010
also good reference is
This file is part of erlang - rtmp .
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
along with erlang - rtmp . If not , see < / > .
-module(rtmp_handshake).
-version(1.0).
-export([server/1, c1/0, c2/1, client_scheme_version/1]).
-include("../include/rtmp.hrl").
-include("rtmp_private.hrl").
-include_lib("eunit/include/eunit.hrl").
-define(DIGEST_SIZE, 32).
-define(GENUINE_FMS_KEY, <<"Genuine Adobe Flash Media Server 001",
16#f0,16#ee,16#c2,16#4a,16#80,16#68,16#be,16#e8,16#2e,16#00,16#d0,16#d1,
16#02,16#9e,16#7e,16#57,16#6e,16#ec,16#5d,16#2d,16#29,16#80,16#6f,16#ab,16#93,16#b8,16#e6,16#36,
16#cf,16#eb,16#31,16#ae>>).
-define(GENUINE_FP_KEY, <<"Genuine Adobe Flash Player 001",
16#F0, 16#EE, 16#C2, 16#4A, 16#80, 16#68, 16#BE, 16#E8,
16#2E, 16#00, 16#D0, 16#D1, 16#02, 16#9E, 16#7E, 16#57,
16#6E, 16#EC, 16#5D, 16#2D, 16#29, 16#80, 16#6F, 16#AB,
16#93, 16#B8, 16#E6, 16#36, 16#CF, 16#EB, 16#31, 16#AE>>).
-spec clientDigest(Handshake::binary(), handshake_version()) -> {First::binary(), Seed::binary(), Last::binary()}.
Flash before 10.0.32.18
clientDigest(<<_:8/binary, P1, P2, P3, P4, _/binary>> = C1, version1) ->
Offset = (P1+P2+P3+P4) rem 728 + 12,
<<First:Offset/binary, Seed:?DIGEST_SIZE/binary, Last/binary>> = C1,
{First, Seed, Last};
Flash from 10.0.32.18
clientDigest(<<_:772/binary, P1, P2, P3, P4, _/binary>> = C1, version2) ->
Offset = (P1+P2+P3+P4) rem 728 + 776,
<<First:Offset/binary, Seed:?DIGEST_SIZE/binary, Last/binary>> = C1,
{First, Seed, Last}.
-spec validate_scheme_version(C1::binary(), Version::handshake_version()) -> boolean().
validate_scheme_version(C1, Version) ->
{First, ClientDigest, Last} = clientDigest(C1, Version),
{Key, _} = erlang:split_binary(?GENUINE_FP_KEY, 30),
ClientDigest == hmac256:digest_bin(Key, <<First/binary, Last/binary>>).
-spec client_scheme_version(C1::binary()) -> handshake_version().
client_scheme_version(C1) ->
case validate_scheme_version(C1, version1) of
true -> version1;
false -> case validate_scheme_version(C1, version2) of
true -> version2;
false -> version1
end
end.
c1() ->
[?HS_UNCRYPTED, <<0:32, 0:32>>, crypto:rand_bytes(?HS_BODY_LEN - 8)].
c2(<<_Time:32, _V1,_V2,_V3,_V4, _Rand/binary>> = S1) ->
io : format("Server : ~p , ~p.~p.~p.~p ~ n " , [ Time , V1 , V2 , V3 , V4 ] ) ,
S1.
server(<<?HS_UNCRYPTED , C1:?HS_BODY_LEN / binary > > ) - >
{ uncrypted , [ ? HS_UNCRYPTED , s1 ( ) , s2(C1 ) ] } ;
server(<<Encryption, C2:?HS_BODY_LEN/binary>>) ->
SchemeVersion = client_scheme_version(C2),
{KeyIn, KeyOut, Response2} = case Encryption of
?HS_CRYPTED ->
rtmpe:s2(C2, Encryption);
?HS_UNCRYPTED ->
{undefined, undefined, <<0:32, 3,0,2,1, (crypto:rand_bytes(?HS_BODY_LEN - 8))/binary>>}
end,
{Digest1, _, Digest2} = clientDigest(Response2, SchemeVersion),
{ServerFMSKey, _} = erlang:split_binary(?GENUINE_FMS_KEY, 36),
ServerDigest = hmac256:digest_bin(ServerFMSKey, <<Digest1/binary, Digest2/binary>>),
S2 = <<Digest1/binary, ServerDigest/binary, Digest2/binary>>,
? D({serverDH , size(ServerFirst ) , serverDigest , size(Digest1 ) } ) ,
Response4 = crypto:rand_bytes(?HS_BODY_LEN - 32),
{_, ClientDigest, _} = clientDigest(C2, SchemeVersion),
TempHash = hmac256:digest_bin(?GENUINE_FMS_KEY, ClientDigest),
ClientHash = hmac256:digest_bin(TempHash, Response4),
S3 = <<Response4/binary, ClientHash/binary>>,
case Encryption of
?HS_CRYPTED ->
{crypted, [?HS_CRYPTED, S2, S3], KeyIn, KeyOut};
?HS_UNCRYPTED ->
{uncrypted, [?HS_UNCRYPTED, S2, S3]}
end.
|
e9ee75719772794eab80baa208332e0690fc65e27cda8f58321349919ebce550 | well-typed/plutonomy | Transform.hs | module Plutonomy.Hereditary.Transform (
-- * Transformations
splitDelay, splitDelay',
inlineSaturated, inlineSaturated', inlineSize,
commonBindings,
-- * Single rewrites
inlineConstants,
inlineUsedOnce,
letZero,
appError,
etaForce,
etaFun,
ifLambda,
floatOutLambda,
floatOutAppArg,
floatOutDelay,
commBuiltin,
) where
import Control.Applicative (Const (..))
import Data.Bifunctor (bimap)
import Data.Foldable (foldl')
import Data.Map.Strict (Map)
import Data.Monoid (Sum (..))
import Data.Sequence (pattern (:<|), pattern (:|>))
import PlutusCore.Default (DefaultFun (EqualsInteger, IfThenElse))
import Subst
(Nat (..), Rename (..), Var (..), Vars (..), bump, instantiate1, mkRen, rename, unusedVar, unusedVar2, unusedVar3, unvar,
weaken)
import qualified Data.Map.Strict as Map
import qualified Data.Sequence as Seq
import Plutonomy.Hereditary
import Plutonomy.Hereditary.Rewrite
import Plutonomy.Name
import Plutonomy.Raw.Transform (AppError (..), FloatOutAppArg (..))
-- $setup
> > > import Plutonomy . MissingH
> > > import Subst
> > > import Plutonomy . Hereditary
> > > import Plutonomy . Hereditary . Rewrite
> > > import Plutonomy . Raw . Transform ( AppError ( .. ) , ( .. ) )
> > > import Plutonomy . Pretty ( prettyRaw )
-- >>> import Data.Text (Text)
> > > import Control . ( forM _ )
> > > import PlutusCore . Default ( ( .. ) )
> > > import qualified as PP
--
-- >>> let pp t = prettyRaw PP.pretty (toRaw (t :: Term Text Z))
-------------------------------------------------------------------------------
-- Inline delayed bindings
-------------------------------------------------------------------------------
-- | Split delayed binding definitions.
--
-- >>> let term = let_ "fix" (delay_ (delay_ (lam_ "x" ("x" :@ "x" :@ "x")))) (force_ (force_ "fix") :@ "f")
-- >>> pp term
-- let* fix = \ ~ ~ x -> x x x
-- in fix ! ! f
--
-- >>> pp $ splitDelay' term
-- let* fix!! = \ x -> x x x
-- fix! = \ ~ -> fix!!
-- fix = \ ~ -> fix!
-- in fix ! ! f
--
-- Unused bindings will be removed by other passes.
--
-- >>> pp $ fixedpoint (inlineSaturated' 0) $ splitDelay' term
-- let* fix!! = \ x -> x x x
-- fix! = \ ~ -> fix!!
-- fix = \ ~ -> fix!
-- in fix!! f
--
-- If the just bound delayed term is forced immediately,
-- we can float it too
--
> > > let term = let _ " res " ( delay _ $ " f " : @ " arg1 " : @ " " ) $ let _ " foo " ( " g " : @ " bar " : @ force _ " res " ) " body "
-- >>> pp term
-- let* res = \ ~ -> f arg1 arg2
-- foo = g bar (res !)
-- in body
--
-- >>> pp $ splitDelay' term
-- let* res! = f arg1 arg2
-- res = \ ~ -> res!
-- foo = g bar (res !)
-- in body
--
-- >>> pp $ fixedpoint (inlineSaturated' 0) $ splitDelay' term
-- let* res! = f arg1 arg2
-- res = \ ~ -> res!
-- foo = g bar res!
-- in body
--
-- Unsaturated application:
--
> > > let term = let _ " f " ( lams _ [ " x","y","z " ] $ " x " : @ " y " : @ " z " ) $ let _ " res " ( delay _ $ " f " : @ " arg1 " : @ " " ) " body "
-- >>> pp term
-- let* f = \ x y z -> x y z
-- res = \ ~ -> f arg1 arg2
-- in body
--
-- >>> pp $ splitDelay' term
-- let* f = \ x y z -> x y z
-- res! = f arg1 arg2
-- res = \ ~ -> res!
-- in body
--
splitDelay :: Definitions a n -> Term a n -> Maybe (Term a n)
splitDelay _ctx (Let _n (Delay (Var _)) _s) = Nothing
splitDelay ctx (Let n (Delay (Defn t)) s)
| isValue (definitionArity ctx) (const 100) (Defn t) || VZ `isForcedIn` s
= Just $ Let (forcedName n) t $ Let n (Delay (Var VZ)) $ bump s
This destroyes some sharing atm
splitDelay ctx ( Let n ( Lam n ' ( Defn t ' ) ) s )
-- | Just t <- bound unusedVar t'
, isValue ( definitionArity ctx ) ( const 100 ) ( Defn t ) || VZ ` isForcedIn ` s
= Just $ Let ( unusedName n ) t $ Let n ( Lam n ' ( Var ( VS VZ ) ) ) $ bump s
splitDelay _ _ = Nothing
-- | Rewrite using 'splitDelay'.
splitDelay' :: Ord a => Term a n -> Term a n
splitDelay' = rewriteWithDefinitions splitDelay
-------------------------------------------------------------------------------
-- Variable usage traversals
-------------------------------------------------------------------------------
isForcedIn :: Var n -> Term a n -> Bool
isForcedIn x (Defn d) = isForcedInDefn x d
isForcedIn _ Error = False
isForcedIn x (Let _n t s) = isForcedInDefn x t || isForcedIn (VS x) s
isForcedInDefn :: Var n -> Defn a n -> Bool
isForcedInDefn x (Neutral h sp) = isForcedInHead x h sp || any (isForcedInElim x) sp
isForcedInDefn _ (Lam _ _ ) = False
isForcedInDefn _ (Delay _) = False
isForcedInDefn _ (Constant _) = False
isForcedInHead :: Var n -> Head a n -> Spine a n -> Bool
isForcedInHead x (HeadVar y) sp = x == y && not (null sp)
isForcedInHead _ _ _ = False
isForcedInElim :: Var n -> Elim a n -> Bool
isForcedInElim _ Force = False
isForcedInElim x (App t) = isForcedIn x t
isForcedInElim _ (E1 _) = False
isStrictIn :: Var n -> Term a n -> Bool
isStrictIn x (Defn d) = isStrictInDefn x d
isStrictIn _ Error = False
isStrictIn x (Let _n t s) = isStrictInDefn x t || isStrictIn (VS x) s
isStrictInDefn :: Var n -> Defn a n -> Bool
isStrictInDefn x (Neutral h sp) = isStrictInHead x h || any (isStrictInElim x) sp
isStrictInDefn _ (Lam _ _ ) = False
isStrictInDefn _ (Delay _) = False
isStrictInDefn _ (Constant _) = False
isStrictInHead :: Var n -> Head a n -> Bool
isStrictInHead x (HeadVar y) = x == y
isStrictInHead _ _ = False
isStrictInElim :: Var n -> Elim a n -> Bool
isStrictInElim _ Force = False
isStrictInElim x (App t) = isStrictIn x t
isStrictInElim _ (E1 _) = False
-------------------------------------------------------------------------------
-- Inline saturated
-------------------------------------------------------------------------------
-- | Inline linear saturated bindings.
--
-- >>> let term = let_ "const" (lams_ ["x","y"] "x") ("const" :@ "foo" :@ "bar")
-- >>> pp term
-- let* const = \ x y -> x
-- in const foo bar
--
-- >>> pp $ inlineSaturated' 0 term
-- let* const = \ x y -> x
-- in foo
--
-- With special eliminators:
--
-- >>> let term = let_ "fst" (lam_ "p" $ fst_ "p") $ "fst" :@ "somepair"
-- >>> pp term
-- let* fstPair!! = fstPair# ! !
-- fst = \ p -> fstPair!! p
-- in fst somepair
--
-- >>> pp $ inlineSaturated' 0 term
-- let* fstPair!! = fstPair# ! !
-- fst = \ p -> fstPair!! p
in fstPair ! !
--
-- TODO:
-- -- >>> pp $ rewriteWithDefinitions inlineUsedOnce $ simplify $ inlineSaturated' 0 term
-- -- foo
--
-- An example with @ERROR@:
--
-- >>> let term = let_ "const" (lam_ "x" $ lam_ "y" "x") ("const" :@ "foo" :@ Error)
-- >>> pp $ inlineSaturated' 0 term
-- let* const = \ x y -> x
-- in ERROR
--
-- TODO:
-- -- >>> pp $ rewriteWithDefinitions inlineUsedOnce $ inlineSaturated' 0 term
-- -- ERROR
--
inlineSaturated' :: Ord a => Integer -> Term a n -> Term a n
inlineSaturated' size = rewriteWithDefinitions (inlineSaturated size) where
inlineSaturated :: Ord a => Integer -> Definitions a m -> Term a m -> Maybe (Term a m)
inlineSaturated size ctx (Defn (Neutral (HeadVar f) args))
| Just (DefnWithArity a f') <- definitionLookup ctx f
, 0 < a, a <= length args
, inlineSize (Defn f') >= size
= Just (neutral_ (Defn f') args)
inlineSaturated _ _ _ = Nothing
| Inline size . Non - Negative means we want to inline this .
--
-- >>> inlineSize $ lam_ "x" "x"
2
--
> > > inlineSize _ [ " x","y " ] " x "
4
--
> > > inlineSize _ [ " f","x " ] $ " f " : @ " x "
2
--
> > > inlineSize _ [ " x","y","z " ] $ " fun " : @ " x " : @ " y " : @ " z "
0
--
> > > inlineSize _ [ " f","x " ] $ " f " : @ lams _ [ " i","j","k","l " ] " i "
-- -2
--
> > > inlineSize _ [ " f","x " ] $ " f " : @ " x " : @ " x "
0
--
> > > inlineSize _ [ " f","x " ] $ " f " : @ lams _ [ " i " ] " i "
1
--
-- >>> inlineSize $ lam_ "unused" Error
3
--
-- >>> inlineSize $ lam_ "p" $ fst_ "p"
1
--
-- Special cases:
--
-- >>> inlineSize $ delay_ $ force_ trace_ :@ lam_ "x" "x" :@ lam_ "y" "y"
-- -6
--
( TODO : why that returned -2 ) ?
--
inlineSize :: Term a n -> Integer
inlineSize term = top 1 term where
top :: Integer -> Term a n -> Integer
top !acc (Defn (Lam _n t)) = top (2 + acc) t
top !acc (Defn (Delay t)) = top (1 + acc) t
top !acc t = go acc t
go :: Integer -> Term a n -> Integer
go acc (Defn d) = goD acc d
go acc Error = acc
go acc (Let _n t s) = go (goD (acc - 1) t) s
goD :: Integer -> Defn a n -> Integer
goD acc (Neutral _ xs) = foldl' goE (acc - 1) xs
goD acc (Lam _n t) = go (acc - 1) t
goD acc (Delay t) = go (acc - 1) t
goD acc Constant {} = acc - 1
goE :: Integer -> Elim a n -> Integer
goE acc Force = acc - 1
goE acc (App t) = go (acc - 1) t
goE acc (E1 _) = acc - 1
-------------------------------------------------------------------------------
CSE : Common bindings
-------------------------------------------------------------------------------
-- | Combine common bindings.
--
-- >>> let term = let_ "x" (delay_ "foo") $ let_ "y" (delay_ "foo") $ "f" :@ "x" :@ "y"
-- >>> pp term
-- let* x = \ ~ -> foo
-- y = \ ~ -> foo
-- in f x y
--
-- >>> pp $ commonBindings term
-- let* x = \ ~ -> foo
in f x x
--
-- Also if the if the same term is used in the body of let,
-- we use the variable:
--
-- TODO:
--
-- >> let term = let_ "x" (delay_ "foo") $ delay_ "foo"
-- >> pp term
-- let* x = \ ~ -> foo
-- in \ ~ -> foo
--
-- >> pp $ commonBindings term
-- let* x = \ ~ -> foo
-- in x
--
-- This is done only if we are binding a value.
--
commonBindings :: forall n a. Ord a => Term a n -> Term a n
commonBindings = rewriteWith f onLet (DefnToVar Map.empty) where
onLet :: Name -> Defn a m -> DefnToVar a m -> DefnToVar a (S m)
onLet _ t ctx
| isValue (const 0) (const 0) (Defn t)
= DefnToVar $ Map.insert (weaken t) VZ (unDefnToVar ctx')
| otherwise
= ctx'
where
ctx' = weaken ctx
f :: DefnToVar a m -> Term a m -> Maybe (Term a m)
f (DefnToVar ctx) (Let _n t s)
| isValue (const 0) (const 0) (Defn t)
, Just x <- Map.lookup t ctx
= Just (instantiate1 (Var x) s)
f ( ctx ) ( Defn t )
-- | isValue (const 0) (const 0) (Defn t)
-- , Just x <- Map.lookup t ctx
= Just ( Var x )
f _ _ = Nothing
newtype DefnToVar a n = DefnToVar { unDefnToVar :: Map (Defn a n) (Var n) }
instance Ord a => Rename (DefnToVar a) where
r <@> DefnToVar m = DefnToVar $ Map.fromList . map (bimap (rename r) (rename r)) . Map.toList $ m
-------------------------------------------------------------------------------
-- Simple rewrites
-------------------------------------------------------------------------------
-- | Inline bindings used at most once.
--
-- >>> let term = let_ "x" (delay_ "unused") "body"
-- >>> pp term
-- let* x = \ ~ -> unused
-- in body
--
-- >>> pp $ rewriteWithDefinitions inlineUsedOnce term
-- body
--
-- >>> let term = let_ "x" (delay_ "used") ("f" :@ "x")
-- >>> pp term
-- let* x = \ ~ -> used
-- in f x
--
-- >>> pp $ rewriteWithDefinitions inlineUsedOnce term
-- f (\ ~ -> used)
--
-- >>> let term = let_ "x" (delay_ "used") $ "f" :@ "x" :@ "x"
-- >>> pp term
-- let* x = \ ~ -> used
in f x x
--
-- >>> pp $ rewriteWithDefinitions inlineUsedOnce term
-- let* x = \ ~ -> used
in f x x
--
-- When bound term is an unsaturated application, we can inline it still:
--
-- >>> let term = let_ "f" (lams_ ["x","y","z"] $ "foo" :@ "x" :@ "y" :@ "z") $ let_ "used" ("f" :@ "bar" :@ "f") (delay_ "used")
-- >>> pp term
-- let* f = \ x y z -> foo x y z
-- used = f bar f
-- in \ ~ -> used
--
-- >>> pp $ rewriteWithDefinitions inlineUsedOnce term
-- let* f = \ x y z -> foo x y z
-- in \ ~ -> f bar f
--
-- If bound value is used once and strictly, it's good reason to inline it:
--
-- >>> let term = let_ "f" ("foo" :@ "bar") $ "f" :@ "quu"
-- >>> pp term
-- let* f = foo bar
-- in f quu
--
-- >>> pp $ rewriteWithDefinitions inlineUsedOnce term
-- foo bar quu
--
inlineUsedOnce :: Definitions a n -> Term a n -> Maybe (Term a n)
inlineUsedOnce ctx (Let _n t s)
| isValue (definitionArity ctx) (const 0) (Defn t) || VZ `isStrictIn` s
, bound this s <= Const (Sum 1)
= Just (instantiate1 (Defn t) s)
where
this :: Var (S n) -> Const (Sum Int) (Var (S n))
this VZ = Const (Sum 1)
this (VS _) = Const (Sum 0)
inlineUsedOnce _ _ = Nothing
-- | 'Error' propagation.
--
-- >>> let term = Error :@ "foo" :@ "bar"
-- >>> pp term
-- ERROR
--
-- But also when 'Error' is an argument:
--
-- >>> let term = ("bar" :@ "foo") :@ Error
-- >>> pp term
-- bar foo ERROR
--
> > > pp $ rewriteWithDefinitions ( ) term
-- bar foo ERROR
--
> > > pp $ rewriteWithDefinitions ( appError AppErrorAll ) term
-- ERROR
--
-- |
--
-- >>> let term = let_ "f" (delay_ "ff") ("f" :@ Error)
-- >>> pp term
-- let* f = \ ~ -> ff
-- in f ERROR
--
> > > pp $ rewriteWithDefinitions ( ) term
-- let* f = \ ~ -> ff
-- in ERROR
--
> > > pp $ rewriteWithDefinitions ( appError AppErrorAll ) term
-- let* f = \ ~ -> ff
-- in ERROR
--
appError :: AppError -> Definitions a n -> Term a n -> Maybe (Term a n)
appError AppErrorValue ctx (Defn (Neutral h sp))
| (sp', App Error :<| _) <- Seq.breakl isErrorElim sp
, isValue (definitionArity ctx) (const 0) (Defn (Neutral h sp'))
= Just Error
appError AppErrorAll _ (Defn (Neutral _ sp))
| any isErrorElim sp
= Just Error
appError _ _ _ = Nothing
| Let zero
--
-- >>> let term = let_ "f" (lams_ ["x","y"] $ "y" :@ "x") $ "f" :@ "foo" :@ "bar"
-- >>> pp term
-- let* f = \ x y -> y x
-- in f foo bar
--
-- >>> pp $ rewrite letZero term
-- bar foo
--
letZero :: Term a n -> Maybe (Term a n)
letZero (Let _n t (Defn (Neutral (HeadVar VZ) sp)))
| Just sp' <- traverse (elimVars unusedVar pure) sp
= Just (neutral_ (Defn t) sp')
letZero _ = Nothing
| Eta - reduce delay force if the term is a value .
--
-- >>> let term = delay_ (force_ "foo")
-- >>> pp term
-- \ ~ -> foo !
--
> > > pp $ rewriteWithDefinitions etaForce term
-- foo
--
-- Non-values are not reduced:
--
-- >>> let term = delay_ (force_ ("f" :@ "x"))
-- >>> pp term
-- \ ~ -> f x !
--
> > > pp $ rewriteWithDefinitions etaForce term
-- \ ~ -> f x !
--
etaForce :: Definitions a n -> Term a n -> Maybe (Term a n)
etaForce ctx (Defn (Delay (Defn (Neutral h (ts :|> Force)))))
| isValue (definitionArity ctx) (const 0) v
= Just v
where
v = Defn (Neutral h ts)
etaForce _ _ = Nothing
| Eta reduce function .
--
-- >>> let term = lam_ "arg" $ "fun" :@ "arg"
-- >>> pp term
-- \ arg -> fun arg
--
-- >>> pp $ rewriteWithDefinitions etaFun term
-- fun
--
-- >>> let term = lams_ ["x","y","z"] $ "fun" :@ "x" :@ "y" :@ "z"
-- >>> pp term
-- \ x y z -> fun x y z
--
-- >>> pp $ rewriteWithDefinitions etaFun term
-- fun
--
-- Non-value functions are not reduced:
--
-- >>> let term = lam_ "arg" $ "g" :@ "y" :@ "arg"
-- >>> pp term
-- \ arg -> g y arg
--
-- >>> pp $ rewriteWithDefinitions etaFun term
-- \ arg -> g y arg
--
etaFun :: Definitions a n -> Term a n -> Maybe (Term a n)
etaFun _ctx (Defn (Lam _n (f :@ Var0)))
| isValue (const 0) (const 0) f -- TODO: using definitionArity breaks fix !?
, Just f' <- bound unusedVar f
= Just f'
etaFun _ctx (Defn (Lam _ (Defn (Lam _ (f :@ Var1 :@ Var0)))))
| isValue (const 0) (const 0) f
, Just f' <- bound unusedVar2 f
= Just f'
etaFun _ctx (Defn (Lam _ (Defn (Lam _ (Defn (Lam _ (f :@ Var2 :@ Var1 :@ Var0)))))))
| isValue (const 0) (const 0) f
, Just f' <- bound unusedVar3 f
= Just f'
etaFun _ _ = Nothing
-- | Replace if-then-else lambdas with delays
--
-- >>> let term = force_ ite_ :@ "condition" :@ lam_ "ds" "foo" :@ lam_ "ds" "bar" :@ "tt"
-- >>> pp term
-- ifThenElse# ! condition (\ ds -> foo) (\ ds_0 -> bar) tt
--
-- >>> pp $ rewriteWithDefinitions ifLambda term
-- ifThenElse# ! condition (\ ~ -> foo) (\ ~ -> bar) !
--
ifLambda :: Definitions a n -> Term a n -> Maybe (Term a n)
ifLambda ctx (Defn (Neutral (HeadBuiltin IfThenElse) (Force :<| App c :<| App (Defn (Lam _n1 t1)) :<| App (Defn (Lam _n2 t2)) :<| App v :<| sp)))
| isValue (definitionArity ctx) (const 0) v
, Just t1' <- bound unusedVar t1
, Just t2' <- bound unusedVar t2
= Just $ Defn (Neutral (HeadBuiltin IfThenElse) (Force :<| App c :<| App (Defn (Delay t1')) :<| App (Defn (Delay t2')) :<| Force :<| sp))
ifLambda _ _ = Nothing
-- | Lambda float.
--
-- >>> let term = lam_ "x" $ let_ "y" (lams_ ["z","w"] "z") $ "y" :@ "x"
-- >>> pp term
-- \ x -> let* y = \ z w -> z in y x
--
-- >>> pp $ rewriteWithDefinitions floatOutLambda term
-- let* y = \ z w -> z
-- in \ x -> y x
--
There might be @let@s in between ,
-- we still float out through them.
--
-- >>> let term = lam_ "x" $ let_ "foo" ("f" :@ "x") $ let_ "bar" ("g" :@ "x") $ let_ "y" (lams_ ["z","w"] "z") $ "foo" :@ "bar" :@ "y"
-- >>> pp term
-- \ x -> let* foo = f x; bar = g x; y = \ z w -> z in foo bar y
--
-- >>> pp $ rewriteWithDefinitions floatOutLambda term
-- let* y = \ z w -> z
-- in \ x -> let* foo = f x; bar = g x in foo bar y
--
floatOutLambda :: forall n a. Definitions a n -> Term a n -> Maybe (Term a n)
floatOutLambda ctx (Defn (Lam n0 t0)) = go unusedVar swap0 (Defn . Lam n0) t0
where
go :: (Var m -> Maybe (Var n)) -- whether term can be floated out, i.e. doesn't use local bindings
-> (Var (S m) -> Var (S m)) -- renaming
-> (Term a (S m) -> Term a (S n)) -- structure
-> Term a m -- term
-> Maybe (Term a n)
go unused ren mk (Let n t s)
| Just t' <- defnVars unused pure t
, isValue (definitionArity ctx) (const 0) (Defn t')
= Just $ Let n t' (mk (rename (mkRen ren) s))
| otherwise
= go (unvar Nothing unused)
(swap1 ren)
(mk . Let n (rename (mkRen (ren . VS)) t))
s
go _ _ _ _ = Nothing
swap0 :: Var (S (S m)) -> Var (S (S m))
swap0 VZ = VS VZ
swap0 (VS VZ) = VZ
swap0 v = v
swap1 :: (Var (S m) -> Var (S m)) -> Var (S (S m)) -> Var (S (S m))
swap1 f VZ = VS (f VZ)
swap1 _ (VS VZ) = VZ
swap1 f (VS (VS n)) = VS (f (VS n))
floatOutLambda _ _ = Nothing
-- | Delay float.
--
-- >>> let term = delay_ $ let_ "y" (delay_ "z") $ "y" :@ "x"
-- >>> pp term
-- \ ~ -> let* y = \ ~ -> z in y x
--
-- >>> pp $ rewriteWithDefinitions floatOutDelay term
-- let* y = \ ~ -> z
-- in \ ~ -> y x
--
-- >>> let term = delay_ $ let_ "fx" ("f" :@ "x") $ let_ "const" (lams_ ["y","z"] "y") $ "const" :@ "fx"
-- >>> pp term
-- \ ~ -> let* fx = f x; const = \ y z -> y in const fx
--
-- >>> pp $ rewriteWithDefinitions floatOutDelay term
-- let* const = \ y z -> y
-- in \ ~ -> let* fx = f x in const fx
--
floatOutDelay :: forall n a. Definitions a n -> Term a n -> Maybe (Term a n)
floatOutDelay ctx (Defn (Delay t0)) = go Just id (Defn . Delay) t0
where
go :: (Var m -> Maybe (Var n)) -- whether term can be floated out, i.e. doesn't use local bindings
-> (Var (S m) -> Var (S m)) -- renaming
-> (Term a (S m) -> Term a (S n)) -- structure
-> Term a m -- term
-> Maybe (Term a n)
go unused ren mk (Let n t s)
| Just t' <- defnVars unused pure t
, isValue (definitionArity ctx) (const 0) (Defn t')
= Just $ Let n t' (mk (rename (mkRen ren) s))
| otherwise
= go (unvar Nothing unused)
(swap1 ren)
(mk . Let n (rename (mkRen (ren . VS)) t))
s
go _ _ _ _ = Nothing
swap1 :: (Var (S m) -> Var (S m)) -> Var (S (S m)) -> Var (S (S m))
swap1 f VZ = VS (f VZ)
swap1 _ (VS VZ) = VZ
swap1 f (VS (VS n)) = VS (f (VS n))
floatOutDelay _ _ = Nothing
-- | App argument float.
--
-- Let is also floated from the argument.
-- This is not precisely semantics preserving as it may change order
-- of trace
--
-- >>> let term = "f" :@ "arg" :@ let_ "n" (delay_ "def") "x"
-- >>> pp term
-- f arg (let* n = \ ~ -> def in x)
--
-- >>> pp $ rewriteWithDefinitions (floatOutAppArg FloatOutAppArgValue) term
-- let* n = \ ~ -> def
-- in f arg x
--
-- >>> pp $ rewriteWithDefinitions (floatOutAppArg FloatOutAppArgAll) term
-- let* n = \ ~ -> def
-- in f arg x
--
-- Floats out of if then else too
--
-- >>> let term = force_ ite_ :@ let_ "n" (delay_ ("foo" :@ "bar")) ("n" :@ "n") :@ "consequence" :@ "alternative"
-- >>> pp term
--ifThenElse# ! (let* n = \ ~ -> foo bar in n n) consequence alternative
--
-- >>> pp $ rewriteWithDefinitions (floatOutAppArg FloatOutAppArgAll) term
-- let* n = \ ~ -> foo bar
-- in ifThenElse# ! (n n) consequence alternative
--
floatOutAppArg :: forall a n. FloatOutAppArg -> Definitions a n -> Term a n -> Maybe (Term a n)
floatOutAppArg FloatOutAppArgValue ctx0 (Defn (Neutral h sp)) =
go0 ctx0 id (Defn (Neutral h Seq.Empty)) sp
where
go0 :: Definitions a m -> (Term a m -> Term a n) -> Term a m -> Spine a m -> Maybe (Term a n)
go0 ctx mk f (App (Let n t s) :<| xs)
| isValue (definitionArity ctx) (const 0) f
|| isValue (definitionArity ctx) (const 0) (Defn t)
= go (definitionsOnLet n t ctx) (mk . Let n t) (weaken f :@ s) (fmap weaken xs)
go0 ctx mk f (x :<| xs) = go0 ctx mk (elim_ f x) xs
go0 _ _ _ Seq.Empty = Nothing
go :: Definitions a m -> (Term a m -> Term a n) -> Term a m -> Spine a m -> Maybe (Term a n)
go ctx mk f (App (Let n t s) :<| xs)
| isValue (definitionArity ctx) (const 0) f
|| isValue (definitionArity ctx) (const 0) (Defn t)
= go (definitionsOnLet n t ctx) (mk . Let n t) (weaken f :@ s) (fmap weaken xs)
go ctx mk f (x :<| xs) = go ctx mk (elim_ f x) xs
go _ mk f Seq.Empty = Just (mk f)
floatOutAppArg FloatOutAppArgAll _ctx (Defn (Neutral h sp)) =
go0 id (Defn (Neutral h Seq.Empty)) sp
where
go0 :: (Term a m -> Term a n) -> Term a m -> Spine a m -> Maybe (Term a n)
go0 mk f (App (Let n t s) :<| xs) = go (mk . Let n t) (weaken f :@ s) (fmap weaken xs)
go0 mk f (x :<| xs) = go0 mk (elim_ f x) xs
go0 _ _ Seq.Empty = Nothing
go :: (Term a m -> Term a n) -> Term a m -> Spine a m -> Maybe (Term a n)
go mk f (App (Let n t s) :<| xs) = go (mk . Let n t) (weaken f :@ s) (fmap weaken xs)
go mk f (x :<| xs) = go mk (elim_ f x) xs
go mk f Seq.Empty = Just (mk f)
floatOutAppArg _ _ _ = Nothing
| Commute commutative builtins so the constants are the first arguments .
commBuiltin :: Term a n -> Maybe (Term a n)
commBuiltin (Defn (Neutral (HeadBuiltin EqualsInteger) (App (Defn (Constant _)) :<| _))) =
Nothing
commBuiltin (Defn (Neutral (HeadBuiltin EqualsInteger) (x :<| y@(App (Defn (Constant _))) :<| sp))) =
Just $ Defn $ Neutral (HeadBuiltin EqualsInteger) (y :<| x :<| sp)
commBuiltin _ = Nothing
-- | Inline constants.
--
inlineConstants :: Term a n -> Maybe (Term a n)
inlineConstants (Let _n t@(Constant _) s) = Just (instantiate1 (Defn t) s)
inlineConstants _ = Nothing
| null | https://raw.githubusercontent.com/well-typed/plutonomy/6c01302ba8cf3be4f71617e106cd5ef7ed10fc63/src/Plutonomy/Hereditary/Transform.hs | haskell | * Transformations
* Single rewrites
$setup
>>> import Data.Text (Text)
>>> let pp t = prettyRaw PP.pretty (toRaw (t :: Term Text Z))
-----------------------------------------------------------------------------
Inline delayed bindings
-----------------------------------------------------------------------------
| Split delayed binding definitions.
>>> let term = let_ "fix" (delay_ (delay_ (lam_ "x" ("x" :@ "x" :@ "x")))) (force_ (force_ "fix") :@ "f")
>>> pp term
let* fix = \ ~ ~ x -> x x x
in fix ! ! f
>>> pp $ splitDelay' term
let* fix!! = \ x -> x x x
fix! = \ ~ -> fix!!
fix = \ ~ -> fix!
in fix ! ! f
Unused bindings will be removed by other passes.
>>> pp $ fixedpoint (inlineSaturated' 0) $ splitDelay' term
let* fix!! = \ x -> x x x
fix! = \ ~ -> fix!!
fix = \ ~ -> fix!
in fix!! f
If the just bound delayed term is forced immediately,
we can float it too
>>> pp term
let* res = \ ~ -> f arg1 arg2
foo = g bar (res !)
in body
>>> pp $ splitDelay' term
let* res! = f arg1 arg2
res = \ ~ -> res!
foo = g bar (res !)
in body
>>> pp $ fixedpoint (inlineSaturated' 0) $ splitDelay' term
let* res! = f arg1 arg2
res = \ ~ -> res!
foo = g bar res!
in body
Unsaturated application:
>>> pp term
let* f = \ x y z -> x y z
res = \ ~ -> f arg1 arg2
in body
>>> pp $ splitDelay' term
let* f = \ x y z -> x y z
res! = f arg1 arg2
res = \ ~ -> res!
in body
| Just t <- bound unusedVar t'
| Rewrite using 'splitDelay'.
-----------------------------------------------------------------------------
Variable usage traversals
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Inline saturated
-----------------------------------------------------------------------------
| Inline linear saturated bindings.
>>> let term = let_ "const" (lams_ ["x","y"] "x") ("const" :@ "foo" :@ "bar")
>>> pp term
let* const = \ x y -> x
in const foo bar
>>> pp $ inlineSaturated' 0 term
let* const = \ x y -> x
in foo
With special eliminators:
>>> let term = let_ "fst" (lam_ "p" $ fst_ "p") $ "fst" :@ "somepair"
>>> pp term
let* fstPair!! = fstPair# ! !
fst = \ p -> fstPair!! p
in fst somepair
>>> pp $ inlineSaturated' 0 term
let* fstPair!! = fstPair# ! !
fst = \ p -> fstPair!! p
TODO:
-- >>> pp $ rewriteWithDefinitions inlineUsedOnce $ simplify $ inlineSaturated' 0 term
-- foo
An example with @ERROR@:
>>> let term = let_ "const" (lam_ "x" $ lam_ "y" "x") ("const" :@ "foo" :@ Error)
>>> pp $ inlineSaturated' 0 term
let* const = \ x y -> x
in ERROR
TODO:
-- >>> pp $ rewriteWithDefinitions inlineUsedOnce $ inlineSaturated' 0 term
-- ERROR
>>> inlineSize $ lam_ "x" "x"
-2
>>> inlineSize $ lam_ "unused" Error
>>> inlineSize $ lam_ "p" $ fst_ "p"
Special cases:
>>> inlineSize $ delay_ $ force_ trace_ :@ lam_ "x" "x" :@ lam_ "y" "y"
-6
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
| Combine common bindings.
>>> let term = let_ "x" (delay_ "foo") $ let_ "y" (delay_ "foo") $ "f" :@ "x" :@ "y"
>>> pp term
let* x = \ ~ -> foo
y = \ ~ -> foo
in f x y
>>> pp $ commonBindings term
let* x = \ ~ -> foo
Also if the if the same term is used in the body of let,
we use the variable:
TODO:
>> let term = let_ "x" (delay_ "foo") $ delay_ "foo"
>> pp term
let* x = \ ~ -> foo
in \ ~ -> foo
>> pp $ commonBindings term
let* x = \ ~ -> foo
in x
This is done only if we are binding a value.
| isValue (const 0) (const 0) (Defn t)
, Just x <- Map.lookup t ctx
-----------------------------------------------------------------------------
Simple rewrites
-----------------------------------------------------------------------------
| Inline bindings used at most once.
>>> let term = let_ "x" (delay_ "unused") "body"
>>> pp term
let* x = \ ~ -> unused
in body
>>> pp $ rewriteWithDefinitions inlineUsedOnce term
body
>>> let term = let_ "x" (delay_ "used") ("f" :@ "x")
>>> pp term
let* x = \ ~ -> used
in f x
>>> pp $ rewriteWithDefinitions inlineUsedOnce term
f (\ ~ -> used)
>>> let term = let_ "x" (delay_ "used") $ "f" :@ "x" :@ "x"
>>> pp term
let* x = \ ~ -> used
>>> pp $ rewriteWithDefinitions inlineUsedOnce term
let* x = \ ~ -> used
When bound term is an unsaturated application, we can inline it still:
>>> let term = let_ "f" (lams_ ["x","y","z"] $ "foo" :@ "x" :@ "y" :@ "z") $ let_ "used" ("f" :@ "bar" :@ "f") (delay_ "used")
>>> pp term
let* f = \ x y z -> foo x y z
used = f bar f
in \ ~ -> used
>>> pp $ rewriteWithDefinitions inlineUsedOnce term
let* f = \ x y z -> foo x y z
in \ ~ -> f bar f
If bound value is used once and strictly, it's good reason to inline it:
>>> let term = let_ "f" ("foo" :@ "bar") $ "f" :@ "quu"
>>> pp term
let* f = foo bar
in f quu
>>> pp $ rewriteWithDefinitions inlineUsedOnce term
foo bar quu
| 'Error' propagation.
>>> let term = Error :@ "foo" :@ "bar"
>>> pp term
ERROR
But also when 'Error' is an argument:
>>> let term = ("bar" :@ "foo") :@ Error
>>> pp term
bar foo ERROR
bar foo ERROR
ERROR
|
>>> let term = let_ "f" (delay_ "ff") ("f" :@ Error)
>>> pp term
let* f = \ ~ -> ff
in f ERROR
let* f = \ ~ -> ff
in ERROR
let* f = \ ~ -> ff
in ERROR
>>> let term = let_ "f" (lams_ ["x","y"] $ "y" :@ "x") $ "f" :@ "foo" :@ "bar"
>>> pp term
let* f = \ x y -> y x
in f foo bar
>>> pp $ rewrite letZero term
bar foo
>>> let term = delay_ (force_ "foo")
>>> pp term
\ ~ -> foo !
foo
Non-values are not reduced:
>>> let term = delay_ (force_ ("f" :@ "x"))
>>> pp term
\ ~ -> f x !
\ ~ -> f x !
>>> let term = lam_ "arg" $ "fun" :@ "arg"
>>> pp term
\ arg -> fun arg
>>> pp $ rewriteWithDefinitions etaFun term
fun
>>> let term = lams_ ["x","y","z"] $ "fun" :@ "x" :@ "y" :@ "z"
>>> pp term
\ x y z -> fun x y z
>>> pp $ rewriteWithDefinitions etaFun term
fun
Non-value functions are not reduced:
>>> let term = lam_ "arg" $ "g" :@ "y" :@ "arg"
>>> pp term
\ arg -> g y arg
>>> pp $ rewriteWithDefinitions etaFun term
\ arg -> g y arg
TODO: using definitionArity breaks fix !?
| Replace if-then-else lambdas with delays
>>> let term = force_ ite_ :@ "condition" :@ lam_ "ds" "foo" :@ lam_ "ds" "bar" :@ "tt"
>>> pp term
ifThenElse# ! condition (\ ds -> foo) (\ ds_0 -> bar) tt
>>> pp $ rewriteWithDefinitions ifLambda term
ifThenElse# ! condition (\ ~ -> foo) (\ ~ -> bar) !
| Lambda float.
>>> let term = lam_ "x" $ let_ "y" (lams_ ["z","w"] "z") $ "y" :@ "x"
>>> pp term
\ x -> let* y = \ z w -> z in y x
>>> pp $ rewriteWithDefinitions floatOutLambda term
let* y = \ z w -> z
in \ x -> y x
we still float out through them.
>>> let term = lam_ "x" $ let_ "foo" ("f" :@ "x") $ let_ "bar" ("g" :@ "x") $ let_ "y" (lams_ ["z","w"] "z") $ "foo" :@ "bar" :@ "y"
>>> pp term
\ x -> let* foo = f x; bar = g x; y = \ z w -> z in foo bar y
>>> pp $ rewriteWithDefinitions floatOutLambda term
let* y = \ z w -> z
in \ x -> let* foo = f x; bar = g x in foo bar y
whether term can be floated out, i.e. doesn't use local bindings
renaming
structure
term
| Delay float.
>>> let term = delay_ $ let_ "y" (delay_ "z") $ "y" :@ "x"
>>> pp term
\ ~ -> let* y = \ ~ -> z in y x
>>> pp $ rewriteWithDefinitions floatOutDelay term
let* y = \ ~ -> z
in \ ~ -> y x
>>> let term = delay_ $ let_ "fx" ("f" :@ "x") $ let_ "const" (lams_ ["y","z"] "y") $ "const" :@ "fx"
>>> pp term
\ ~ -> let* fx = f x; const = \ y z -> y in const fx
>>> pp $ rewriteWithDefinitions floatOutDelay term
let* const = \ y z -> y
in \ ~ -> let* fx = f x in const fx
whether term can be floated out, i.e. doesn't use local bindings
renaming
structure
term
| App argument float.
Let is also floated from the argument.
This is not precisely semantics preserving as it may change order
of trace
>>> let term = "f" :@ "arg" :@ let_ "n" (delay_ "def") "x"
>>> pp term
f arg (let* n = \ ~ -> def in x)
>>> pp $ rewriteWithDefinitions (floatOutAppArg FloatOutAppArgValue) term
let* n = \ ~ -> def
in f arg x
>>> pp $ rewriteWithDefinitions (floatOutAppArg FloatOutAppArgAll) term
let* n = \ ~ -> def
in f arg x
Floats out of if then else too
>>> let term = force_ ite_ :@ let_ "n" (delay_ ("foo" :@ "bar")) ("n" :@ "n") :@ "consequence" :@ "alternative"
>>> pp term
ifThenElse# ! (let* n = \ ~ -> foo bar in n n) consequence alternative
>>> pp $ rewriteWithDefinitions (floatOutAppArg FloatOutAppArgAll) term
let* n = \ ~ -> foo bar
in ifThenElse# ! (n n) consequence alternative
| Inline constants.
| module Plutonomy.Hereditary.Transform (
splitDelay, splitDelay',
inlineSaturated, inlineSaturated', inlineSize,
commonBindings,
inlineConstants,
inlineUsedOnce,
letZero,
appError,
etaForce,
etaFun,
ifLambda,
floatOutLambda,
floatOutAppArg,
floatOutDelay,
commBuiltin,
) where
import Control.Applicative (Const (..))
import Data.Bifunctor (bimap)
import Data.Foldable (foldl')
import Data.Map.Strict (Map)
import Data.Monoid (Sum (..))
import Data.Sequence (pattern (:<|), pattern (:|>))
import PlutusCore.Default (DefaultFun (EqualsInteger, IfThenElse))
import Subst
(Nat (..), Rename (..), Var (..), Vars (..), bump, instantiate1, mkRen, rename, unusedVar, unusedVar2, unusedVar3, unvar,
weaken)
import qualified Data.Map.Strict as Map
import qualified Data.Sequence as Seq
import Plutonomy.Hereditary
import Plutonomy.Hereditary.Rewrite
import Plutonomy.Name
import Plutonomy.Raw.Transform (AppError (..), FloatOutAppArg (..))
> > > import Plutonomy . MissingH
> > > import Subst
> > > import Plutonomy . Hereditary
> > > import Plutonomy . Hereditary . Rewrite
> > > import Plutonomy . Raw . Transform ( AppError ( .. ) , ( .. ) )
> > > import Plutonomy . Pretty ( prettyRaw )
> > > import Control . ( forM _ )
> > > import PlutusCore . Default ( ( .. ) )
> > > import qualified as PP
> > > let term = let _ " res " ( delay _ $ " f " : @ " arg1 " : @ " " ) $ let _ " foo " ( " g " : @ " bar " : @ force _ " res " ) " body "
> > > let term = let _ " f " ( lams _ [ " x","y","z " ] $ " x " : @ " y " : @ " z " ) $ let _ " res " ( delay _ $ " f " : @ " arg1 " : @ " " ) " body "
splitDelay :: Definitions a n -> Term a n -> Maybe (Term a n)
splitDelay _ctx (Let _n (Delay (Var _)) _s) = Nothing
splitDelay ctx (Let n (Delay (Defn t)) s)
| isValue (definitionArity ctx) (const 100) (Defn t) || VZ `isForcedIn` s
= Just $ Let (forcedName n) t $ Let n (Delay (Var VZ)) $ bump s
This destroyes some sharing atm
splitDelay ctx ( Let n ( Lam n ' ( Defn t ' ) ) s )
, isValue ( definitionArity ctx ) ( const 100 ) ( Defn t ) || VZ ` isForcedIn ` s
= Just $ Let ( unusedName n ) t $ Let n ( Lam n ' ( Var ( VS VZ ) ) ) $ bump s
splitDelay _ _ = Nothing
splitDelay' :: Ord a => Term a n -> Term a n
splitDelay' = rewriteWithDefinitions splitDelay
isForcedIn :: Var n -> Term a n -> Bool
isForcedIn x (Defn d) = isForcedInDefn x d
isForcedIn _ Error = False
isForcedIn x (Let _n t s) = isForcedInDefn x t || isForcedIn (VS x) s
isForcedInDefn :: Var n -> Defn a n -> Bool
isForcedInDefn x (Neutral h sp) = isForcedInHead x h sp || any (isForcedInElim x) sp
isForcedInDefn _ (Lam _ _ ) = False
isForcedInDefn _ (Delay _) = False
isForcedInDefn _ (Constant _) = False
isForcedInHead :: Var n -> Head a n -> Spine a n -> Bool
isForcedInHead x (HeadVar y) sp = x == y && not (null sp)
isForcedInHead _ _ _ = False
isForcedInElim :: Var n -> Elim a n -> Bool
isForcedInElim _ Force = False
isForcedInElim x (App t) = isForcedIn x t
isForcedInElim _ (E1 _) = False
isStrictIn :: Var n -> Term a n -> Bool
isStrictIn x (Defn d) = isStrictInDefn x d
isStrictIn _ Error = False
isStrictIn x (Let _n t s) = isStrictInDefn x t || isStrictIn (VS x) s
isStrictInDefn :: Var n -> Defn a n -> Bool
isStrictInDefn x (Neutral h sp) = isStrictInHead x h || any (isStrictInElim x) sp
isStrictInDefn _ (Lam _ _ ) = False
isStrictInDefn _ (Delay _) = False
isStrictInDefn _ (Constant _) = False
isStrictInHead :: Var n -> Head a n -> Bool
isStrictInHead x (HeadVar y) = x == y
isStrictInHead _ _ = False
isStrictInElim :: Var n -> Elim a n -> Bool
isStrictInElim _ Force = False
isStrictInElim x (App t) = isStrictIn x t
isStrictInElim _ (E1 _) = False
in fstPair ! !
inlineSaturated' :: Ord a => Integer -> Term a n -> Term a n
inlineSaturated' size = rewriteWithDefinitions (inlineSaturated size) where
inlineSaturated :: Ord a => Integer -> Definitions a m -> Term a m -> Maybe (Term a m)
inlineSaturated size ctx (Defn (Neutral (HeadVar f) args))
| Just (DefnWithArity a f') <- definitionLookup ctx f
, 0 < a, a <= length args
, inlineSize (Defn f') >= size
= Just (neutral_ (Defn f') args)
inlineSaturated _ _ _ = Nothing
| Inline size . Non - Negative means we want to inline this .
2
> > > inlineSize _ [ " x","y " ] " x "
4
> > > inlineSize _ [ " f","x " ] $ " f " : @ " x "
2
> > > inlineSize _ [ " x","y","z " ] $ " fun " : @ " x " : @ " y " : @ " z "
0
> > > inlineSize _ [ " f","x " ] $ " f " : @ lams _ [ " i","j","k","l " ] " i "
> > > inlineSize _ [ " f","x " ] $ " f " : @ " x " : @ " x "
0
> > > inlineSize _ [ " f","x " ] $ " f " : @ lams _ [ " i " ] " i "
1
3
1
( TODO : why that returned -2 ) ?
inlineSize :: Term a n -> Integer
inlineSize term = top 1 term where
top :: Integer -> Term a n -> Integer
top !acc (Defn (Lam _n t)) = top (2 + acc) t
top !acc (Defn (Delay t)) = top (1 + acc) t
top !acc t = go acc t
go :: Integer -> Term a n -> Integer
go acc (Defn d) = goD acc d
go acc Error = acc
go acc (Let _n t s) = go (goD (acc - 1) t) s
goD :: Integer -> Defn a n -> Integer
goD acc (Neutral _ xs) = foldl' goE (acc - 1) xs
goD acc (Lam _n t) = go (acc - 1) t
goD acc (Delay t) = go (acc - 1) t
goD acc Constant {} = acc - 1
goE :: Integer -> Elim a n -> Integer
goE acc Force = acc - 1
goE acc (App t) = go (acc - 1) t
goE acc (E1 _) = acc - 1
CSE : Common bindings
in f x x
commonBindings :: forall n a. Ord a => Term a n -> Term a n
commonBindings = rewriteWith f onLet (DefnToVar Map.empty) where
onLet :: Name -> Defn a m -> DefnToVar a m -> DefnToVar a (S m)
onLet _ t ctx
| isValue (const 0) (const 0) (Defn t)
= DefnToVar $ Map.insert (weaken t) VZ (unDefnToVar ctx')
| otherwise
= ctx'
where
ctx' = weaken ctx
f :: DefnToVar a m -> Term a m -> Maybe (Term a m)
f (DefnToVar ctx) (Let _n t s)
| isValue (const 0) (const 0) (Defn t)
, Just x <- Map.lookup t ctx
= Just (instantiate1 (Var x) s)
f ( ctx ) ( Defn t )
= Just ( Var x )
f _ _ = Nothing
newtype DefnToVar a n = DefnToVar { unDefnToVar :: Map (Defn a n) (Var n) }
instance Ord a => Rename (DefnToVar a) where
r <@> DefnToVar m = DefnToVar $ Map.fromList . map (bimap (rename r) (rename r)) . Map.toList $ m
in f x x
in f x x
inlineUsedOnce :: Definitions a n -> Term a n -> Maybe (Term a n)
inlineUsedOnce ctx (Let _n t s)
| isValue (definitionArity ctx) (const 0) (Defn t) || VZ `isStrictIn` s
, bound this s <= Const (Sum 1)
= Just (instantiate1 (Defn t) s)
where
this :: Var (S n) -> Const (Sum Int) (Var (S n))
this VZ = Const (Sum 1)
this (VS _) = Const (Sum 0)
inlineUsedOnce _ _ = Nothing
> > > pp $ rewriteWithDefinitions ( ) term
> > > pp $ rewriteWithDefinitions ( appError AppErrorAll ) term
> > > pp $ rewriteWithDefinitions ( ) term
> > > pp $ rewriteWithDefinitions ( appError AppErrorAll ) term
appError :: AppError -> Definitions a n -> Term a n -> Maybe (Term a n)
appError AppErrorValue ctx (Defn (Neutral h sp))
| (sp', App Error :<| _) <- Seq.breakl isErrorElim sp
, isValue (definitionArity ctx) (const 0) (Defn (Neutral h sp'))
= Just Error
appError AppErrorAll _ (Defn (Neutral _ sp))
| any isErrorElim sp
= Just Error
appError _ _ _ = Nothing
| Let zero
letZero :: Term a n -> Maybe (Term a n)
letZero (Let _n t (Defn (Neutral (HeadVar VZ) sp)))
| Just sp' <- traverse (elimVars unusedVar pure) sp
= Just (neutral_ (Defn t) sp')
letZero _ = Nothing
| Eta - reduce delay force if the term is a value .
> > > pp $ rewriteWithDefinitions etaForce term
> > > pp $ rewriteWithDefinitions etaForce term
etaForce :: Definitions a n -> Term a n -> Maybe (Term a n)
etaForce ctx (Defn (Delay (Defn (Neutral h (ts :|> Force)))))
| isValue (definitionArity ctx) (const 0) v
= Just v
where
v = Defn (Neutral h ts)
etaForce _ _ = Nothing
| Eta reduce function .
etaFun :: Definitions a n -> Term a n -> Maybe (Term a n)
etaFun _ctx (Defn (Lam _n (f :@ Var0)))
, Just f' <- bound unusedVar f
= Just f'
etaFun _ctx (Defn (Lam _ (Defn (Lam _ (f :@ Var1 :@ Var0)))))
| isValue (const 0) (const 0) f
, Just f' <- bound unusedVar2 f
= Just f'
etaFun _ctx (Defn (Lam _ (Defn (Lam _ (Defn (Lam _ (f :@ Var2 :@ Var1 :@ Var0)))))))
| isValue (const 0) (const 0) f
, Just f' <- bound unusedVar3 f
= Just f'
etaFun _ _ = Nothing
ifLambda :: Definitions a n -> Term a n -> Maybe (Term a n)
ifLambda ctx (Defn (Neutral (HeadBuiltin IfThenElse) (Force :<| App c :<| App (Defn (Lam _n1 t1)) :<| App (Defn (Lam _n2 t2)) :<| App v :<| sp)))
| isValue (definitionArity ctx) (const 0) v
, Just t1' <- bound unusedVar t1
, Just t2' <- bound unusedVar t2
= Just $ Defn (Neutral (HeadBuiltin IfThenElse) (Force :<| App c :<| App (Defn (Delay t1')) :<| App (Defn (Delay t2')) :<| Force :<| sp))
ifLambda _ _ = Nothing
There might be @let@s in between ,
floatOutLambda :: forall n a. Definitions a n -> Term a n -> Maybe (Term a n)
floatOutLambda ctx (Defn (Lam n0 t0)) = go unusedVar swap0 (Defn . Lam n0) t0
where
-> Maybe (Term a n)
go unused ren mk (Let n t s)
| Just t' <- defnVars unused pure t
, isValue (definitionArity ctx) (const 0) (Defn t')
= Just $ Let n t' (mk (rename (mkRen ren) s))
| otherwise
= go (unvar Nothing unused)
(swap1 ren)
(mk . Let n (rename (mkRen (ren . VS)) t))
s
go _ _ _ _ = Nothing
swap0 :: Var (S (S m)) -> Var (S (S m))
swap0 VZ = VS VZ
swap0 (VS VZ) = VZ
swap0 v = v
swap1 :: (Var (S m) -> Var (S m)) -> Var (S (S m)) -> Var (S (S m))
swap1 f VZ = VS (f VZ)
swap1 _ (VS VZ) = VZ
swap1 f (VS (VS n)) = VS (f (VS n))
floatOutLambda _ _ = Nothing
floatOutDelay :: forall n a. Definitions a n -> Term a n -> Maybe (Term a n)
floatOutDelay ctx (Defn (Delay t0)) = go Just id (Defn . Delay) t0
where
-> Maybe (Term a n)
go unused ren mk (Let n t s)
| Just t' <- defnVars unused pure t
, isValue (definitionArity ctx) (const 0) (Defn t')
= Just $ Let n t' (mk (rename (mkRen ren) s))
| otherwise
= go (unvar Nothing unused)
(swap1 ren)
(mk . Let n (rename (mkRen (ren . VS)) t))
s
go _ _ _ _ = Nothing
swap1 :: (Var (S m) -> Var (S m)) -> Var (S (S m)) -> Var (S (S m))
swap1 f VZ = VS (f VZ)
swap1 _ (VS VZ) = VZ
swap1 f (VS (VS n)) = VS (f (VS n))
floatOutDelay _ _ = Nothing
floatOutAppArg :: forall a n. FloatOutAppArg -> Definitions a n -> Term a n -> Maybe (Term a n)
floatOutAppArg FloatOutAppArgValue ctx0 (Defn (Neutral h sp)) =
go0 ctx0 id (Defn (Neutral h Seq.Empty)) sp
where
go0 :: Definitions a m -> (Term a m -> Term a n) -> Term a m -> Spine a m -> Maybe (Term a n)
go0 ctx mk f (App (Let n t s) :<| xs)
| isValue (definitionArity ctx) (const 0) f
|| isValue (definitionArity ctx) (const 0) (Defn t)
= go (definitionsOnLet n t ctx) (mk . Let n t) (weaken f :@ s) (fmap weaken xs)
go0 ctx mk f (x :<| xs) = go0 ctx mk (elim_ f x) xs
go0 _ _ _ Seq.Empty = Nothing
go :: Definitions a m -> (Term a m -> Term a n) -> Term a m -> Spine a m -> Maybe (Term a n)
go ctx mk f (App (Let n t s) :<| xs)
| isValue (definitionArity ctx) (const 0) f
|| isValue (definitionArity ctx) (const 0) (Defn t)
= go (definitionsOnLet n t ctx) (mk . Let n t) (weaken f :@ s) (fmap weaken xs)
go ctx mk f (x :<| xs) = go ctx mk (elim_ f x) xs
go _ mk f Seq.Empty = Just (mk f)
floatOutAppArg FloatOutAppArgAll _ctx (Defn (Neutral h sp)) =
go0 id (Defn (Neutral h Seq.Empty)) sp
where
go0 :: (Term a m -> Term a n) -> Term a m -> Spine a m -> Maybe (Term a n)
go0 mk f (App (Let n t s) :<| xs) = go (mk . Let n t) (weaken f :@ s) (fmap weaken xs)
go0 mk f (x :<| xs) = go0 mk (elim_ f x) xs
go0 _ _ Seq.Empty = Nothing
go :: (Term a m -> Term a n) -> Term a m -> Spine a m -> Maybe (Term a n)
go mk f (App (Let n t s) :<| xs) = go (mk . Let n t) (weaken f :@ s) (fmap weaken xs)
go mk f (x :<| xs) = go mk (elim_ f x) xs
go mk f Seq.Empty = Just (mk f)
floatOutAppArg _ _ _ = Nothing
| Commute commutative builtins so the constants are the first arguments .
commBuiltin :: Term a n -> Maybe (Term a n)
commBuiltin (Defn (Neutral (HeadBuiltin EqualsInteger) (App (Defn (Constant _)) :<| _))) =
Nothing
commBuiltin (Defn (Neutral (HeadBuiltin EqualsInteger) (x :<| y@(App (Defn (Constant _))) :<| sp))) =
Just $ Defn $ Neutral (HeadBuiltin EqualsInteger) (y :<| x :<| sp)
commBuiltin _ = Nothing
inlineConstants :: Term a n -> Maybe (Term a n)
inlineConstants (Let _n t@(Constant _) s) = Just (instantiate1 (Defn t) s)
inlineConstants _ = Nothing
|
a7cc68d0bf5140d606f1105aba20c73b0277761a6a1e3e10bc0470147dd8d9c0 | RokLenarcic/clj-rest-client | conform.clj | (ns clj-rest-client.conform
(:require [clojure.spec.alpha :as s]
[cheshire.core :as json])
(:import (java.time.temporal TemporalAccessor ChronoField)
(java.time ZoneOffset Instant OffsetDateTime LocalDateTime ZonedDateTime LocalDate OffsetTime LocalTime YearMonth Year)
(java.util Date)
(java.time.format DateTimeFormatter)))
(def ^{:doc "A conformer that conforms to JSON" } ->json (s/conformer json/generate-string json/parse-string))
(def ^{:doc "A conformer that conforms to JSON, but it doesn't convert nil to \"null\"" } ->json?
(s/conformer #(some-> % json/generate-string) #(some-> % json/parse-string)))
(defn ->json*
"Create a new conformer that conforms to JSON with added params."
[cheshire-opts]
(s/conformer #(json/generate-string % cheshire-opts) #(json/parse-string % cheshire-opts)))
(defn ->json?*
"Create a new conformer that conforms to JSON with added params, but it doesn't convert nil to \"null\""
[cheshire-opts]
(s/conformer #(some-> % (json/generate-string cheshire-opts)) #(some-> % (json/parse-string cheshire-opts))))
(defn parse-dt
"Converts temporal accessor to java.time object depending on the availability of data:
- Instant
- LocalDate
- LocalTime, OffsetTime
- LocalDateTime, ZonedDateTime
- YearMonth
- Year"
[^TemporalAccessor parsed]
(let [[time date month zone instant] (map #(.isSupported parsed %) [ChronoField/NANO_OF_DAY ChronoField/EPOCH_DAY ChronoField/MONTH_OF_YEAR ChronoField/OFFSET_SECONDS ChronoField/INSTANT_SECONDS])]
(if time
(if date
(if zone (ZonedDateTime/from parsed) (LocalDateTime/from parsed))
(if zone (OffsetTime/from parsed) (LocalTime/from parsed)))
(if instant
(Instant/from parsed)
(if date
(LocalDate/from parsed)
(if month (YearMonth/from parsed) (Year/from parsed)))))))
(defmacro ->date-format
"Conformer for java.util.Date and java.time objects using the supplied formatter.
You can supply time object constructor fn for unform. This fn is called with java.time.TemporalAccessor parse object.
Defaults to `clj-rest-client.conform/parse-dt` (see its docs)."
([formatter]
`(->date-format ~formatter parse-dt))
([formatter parse-type-constructor]
`(letfn [(create-spec# [param-gfn#]
(reify
s/Spec
(conform* [spec# x#]
(cond
(nil? x#) nil
(instance? Date x#) (.format ~formatter (OffsetDateTime/ofInstant (Instant/ofEpochMilli (.getTime ^Date x#)) ZoneOffset/UTC))
(instance? TemporalAccessor x#) (.format ~formatter x#)
:default ::s/invalid))
(unform* [spec# y#]
(cond
(nil? y#) y#
(string? y#) (~parse-type-constructor (.parse ^DateTimeFormatter ~formatter y#))
:default ::s/invalid))
(explain* [spec# path# via# in# x#]
(when (= (s/conform* spec# x#) ::s/invalid)
[{:path path# :pred (list '->date-format '~formatter) :val x# :via via# :in in#}]))
(gen* [spec# overrides# path# rmap#]
(if param-gfn#
(param-gfn#)
(s/gen* (s/spec inst?) overrides# path# rmap#)))
(with-gen* [spec# gfn#]
(create-spec# gfn#))
(describe* [spec#] (list '->date-format '~formatter))))]
(create-spec# nil))))
| null | https://raw.githubusercontent.com/RokLenarcic/clj-rest-client/716ab51315499096c59db3a7349a60a7e41d35e0/src/clj_rest_client/conform.clj | clojure | (ns clj-rest-client.conform
(:require [clojure.spec.alpha :as s]
[cheshire.core :as json])
(:import (java.time.temporal TemporalAccessor ChronoField)
(java.time ZoneOffset Instant OffsetDateTime LocalDateTime ZonedDateTime LocalDate OffsetTime LocalTime YearMonth Year)
(java.util Date)
(java.time.format DateTimeFormatter)))
(def ^{:doc "A conformer that conforms to JSON" } ->json (s/conformer json/generate-string json/parse-string))
(def ^{:doc "A conformer that conforms to JSON, but it doesn't convert nil to \"null\"" } ->json?
(s/conformer #(some-> % json/generate-string) #(some-> % json/parse-string)))
(defn ->json*
"Create a new conformer that conforms to JSON with added params."
[cheshire-opts]
(s/conformer #(json/generate-string % cheshire-opts) #(json/parse-string % cheshire-opts)))
(defn ->json?*
"Create a new conformer that conforms to JSON with added params, but it doesn't convert nil to \"null\""
[cheshire-opts]
(s/conformer #(some-> % (json/generate-string cheshire-opts)) #(some-> % (json/parse-string cheshire-opts))))
(defn parse-dt
"Converts temporal accessor to java.time object depending on the availability of data:
- Instant
- LocalDate
- LocalTime, OffsetTime
- LocalDateTime, ZonedDateTime
- YearMonth
- Year"
[^TemporalAccessor parsed]
(let [[time date month zone instant] (map #(.isSupported parsed %) [ChronoField/NANO_OF_DAY ChronoField/EPOCH_DAY ChronoField/MONTH_OF_YEAR ChronoField/OFFSET_SECONDS ChronoField/INSTANT_SECONDS])]
(if time
(if date
(if zone (ZonedDateTime/from parsed) (LocalDateTime/from parsed))
(if zone (OffsetTime/from parsed) (LocalTime/from parsed)))
(if instant
(Instant/from parsed)
(if date
(LocalDate/from parsed)
(if month (YearMonth/from parsed) (Year/from parsed)))))))
(defmacro ->date-format
"Conformer for java.util.Date and java.time objects using the supplied formatter.
You can supply time object constructor fn for unform. This fn is called with java.time.TemporalAccessor parse object.
Defaults to `clj-rest-client.conform/parse-dt` (see its docs)."
([formatter]
`(->date-format ~formatter parse-dt))
([formatter parse-type-constructor]
`(letfn [(create-spec# [param-gfn#]
(reify
s/Spec
(conform* [spec# x#]
(cond
(nil? x#) nil
(instance? Date x#) (.format ~formatter (OffsetDateTime/ofInstant (Instant/ofEpochMilli (.getTime ^Date x#)) ZoneOffset/UTC))
(instance? TemporalAccessor x#) (.format ~formatter x#)
:default ::s/invalid))
(unform* [spec# y#]
(cond
(nil? y#) y#
(string? y#) (~parse-type-constructor (.parse ^DateTimeFormatter ~formatter y#))
:default ::s/invalid))
(explain* [spec# path# via# in# x#]
(when (= (s/conform* spec# x#) ::s/invalid)
[{:path path# :pred (list '->date-format '~formatter) :val x# :via via# :in in#}]))
(gen* [spec# overrides# path# rmap#]
(if param-gfn#
(param-gfn#)
(s/gen* (s/spec inst?) overrides# path# rmap#)))
(with-gen* [spec# gfn#]
(create-spec# gfn#))
(describe* [spec#] (list '->date-format '~formatter))))]
(create-spec# nil))))
|
|
3878fce5c90cf0f1288e81da6dcc396074cee3064e895979ac41b39d15c6a0ff | SNePS/SNePS2 | nrn-reports.lisp | -*- Mode : Lisp ; Syntax : Common - Lisp ; Package : SNIP ; Base : 10 -*-
Copyright ( C ) 1984 - -2013 Research Foundation of
;; State University of New York
Version : $ I d : nrn - reports.lisp , v 1.2 2013/08/28 19:07:27 shapiro Exp $
;; This file is part of SNePS.
$ BEGIN LICENSE$
The contents of this file are subject to the University at
Buffalo Public License Version 1.0 ( the " License " ) ; you may
;;; not use this file except in compliance with the License. You
;;; may obtain a copy of the License at
;;; . edu/sneps/Downloads/ubpl.pdf.
;;;
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 gov
;;; erning rights and limitations under the License.
;;;
The Original Code is SNePS 2.8 .
;;;
The Initial Developer of the Original Code is Research Foun
dation of State University of New York , on behalf of Univer
sity at Buffalo .
;;;
Portions created by the Initial Developer are Copyright ( C )
2011 Research Foundation of State University of New York , on
behalf of University at Buffalo . All Rights Reserved .
$ END LICENSE$
(in-package :snip)
; =============================================================================
;
; clear-incoming-reports
; ----------------------
;
; returns : <report set>
;
; nonlocal-vars : the *REPORTS* register of the current node
;
; description : clears the *REPORTS* register
;
; side-effects : updates the above register as described
;
written : rgh 10/06/85
modified : rgh 10/15/85
;
;
(defmacro clear-incoming-reports ()
`(setq *REPORTS* (new.repset)))
;
;
; =============================================================================
;
; process-reports.non-rule
; ------------------------
;
; nonlocal-vars : various registers of the current *NODE*
; *PENDING-FORWARD-INFERENCES*, *NODE*
;
; description : checks each incoming report, and does the
; following:
; - if the report is that of a previously
; unknown instance, that instance is built,
; asserted, and sent to all interested
; parties. If there were no interested, open
; outgoing channels, the report is placed in
; the *PENDING-FORWARD-INFERENCES* register.
; unless it was received through a match
; channel, in which case it need not be passed
; on. (Since any nodefun it may be passed on to
; should already have heard about it from the
; same source this one did.)
; - the incoming reports registers are cleared
; - if there are any pending forward inferences, the
; nodefun is rescheduled (to be handled after all
; reports have been processed.
;
; side-effects : the above mentioned registers are updated
;
written : rgh 10/06/85
modified : rgh 10/15/85
rgh 11/18/85
rgh 11/24/85
; rgh 11/29/85
; rgh 2/23/86
rgh 3/09/86
; rgh 3/30/86
;
;
(defun process-reports.non-rule ()
(let ((reports *REPORTS*))
(declare (special *PRIORITY*))
(clear-incoming-reports)
(do ()
((isnew.repset reports))
(process-one-report.non-rule (choose.repset reports))
(setq reports (others.repset reports)))
(cond ((not (isnew.repset *PENDING-FORWARD-INFERENCES*))
(setq *PRIORITY* 'LOW)
(initiate (activation.n *NODE*))))))
;
;
; =============================================================================
;
process - one - report.non - rule
; ---------------------------
;
; arguments : report - <report>
;
; nonlocal-vars : the *KNOWN-INSTANCES*, *NODE*, and PENDING-FORWARD-
; INFERENCES: registers, and *ADDED-NODES*
;
; description : if the instance reported by "report" is a previously
; unknown one, a new node is built and asserted, and
; the report is passed on to OUTGOING-CHANNELS:
;
; side-effects : *KNOWN-INSTANCES* and *PENDING-FORWARD-INFERENCES*
; registers, and *ADDED-NODES*, are updated
;
; written : rgh 3/30/86
; modified: scs 4/20/88
modified : scs 6/22/88
;
;
(defun process-one-report.non-rule (report)
(let ((instance (rep-to-instance report)))
(declare (special *ADDED-NODES*))
(when (unknown.inst instance)
(setq *ADDED-NODES* (insert.ns (node.rep report) *ADDED-NODES*)
*KNOWN-INSTANCES* (insert.iset instance *KNOWN-INSTANCES*))
(if (not (broadcast-one-report
(make.rep
(subst.rep report)
(support.rep report)
(sign.rep report)
*NODE*
nil
(context.rep report))))
(setq *PENDING-FORWARD-INFERENCES*
(insert.repset report *PENDING-FORWARD-INFERENCES*))))))
;
;
; =============================================================================
;
broadcast - one - report
; --------------------
;
; arguments : rep - <report>
;
; returns : <boolean>
;
; nonlocal-vars : *OUTGOING-CHANNELS* register
;
; description : broadcasts "rep" to each of the <channel>s in
; *OUTGOING-CHANNELS*
; returns "true" if "rep" was actually sent
through at least one of the channels , " false "
; otherwise.
; the signature of the report is updated
;
written : rgh 07/29/85
; modified: rgh 08/21/85
rgh 10/15/85
rgh 2/10/86
rgh 3/09/86
; rgh 3/30/86
;
(defun broadcast-one-report (rep)
(let (anysent)
(do.chset (ch *OUTGOING-CHANNELS* anysent)
(when (isopen.ch ch)
(setq anysent (or (try-to-send-report rep ch) anysent))))))
;
;
; =============================================================================
| null | https://raw.githubusercontent.com/SNePS/SNePS2/d3862108609b1879f2c546112072ad4caefc050d/snip/fns/nrn-reports.lisp | lisp | Syntax : Common - Lisp ; Package : SNIP ; Base : 10 -*-
State University of New York
This file is part of SNePS.
you may
not use this file except in compliance with the License. You
may obtain a copy of the License at
. edu/sneps/Downloads/ubpl.pdf.
or implied. See the License for the specific language gov
erning rights and limitations under the License.
=============================================================================
clear-incoming-reports
----------------------
returns : <report set>
nonlocal-vars : the *REPORTS* register of the current node
description : clears the *REPORTS* register
side-effects : updates the above register as described
=============================================================================
process-reports.non-rule
------------------------
nonlocal-vars : various registers of the current *NODE*
*PENDING-FORWARD-INFERENCES*, *NODE*
description : checks each incoming report, and does the
following:
- if the report is that of a previously
unknown instance, that instance is built,
asserted, and sent to all interested
parties. If there were no interested, open
outgoing channels, the report is placed in
the *PENDING-FORWARD-INFERENCES* register.
unless it was received through a match
channel, in which case it need not be passed
on. (Since any nodefun it may be passed on to
should already have heard about it from the
same source this one did.)
- the incoming reports registers are cleared
- if there are any pending forward inferences, the
nodefun is rescheduled (to be handled after all
reports have been processed.
side-effects : the above mentioned registers are updated
rgh 11/29/85
rgh 2/23/86
rgh 3/30/86
=============================================================================
---------------------------
arguments : report - <report>
nonlocal-vars : the *KNOWN-INSTANCES*, *NODE*, and PENDING-FORWARD-
INFERENCES: registers, and *ADDED-NODES*
description : if the instance reported by "report" is a previously
unknown one, a new node is built and asserted, and
the report is passed on to OUTGOING-CHANNELS:
side-effects : *KNOWN-INSTANCES* and *PENDING-FORWARD-INFERENCES*
registers, and *ADDED-NODES*, are updated
written : rgh 3/30/86
modified: scs 4/20/88
=============================================================================
--------------------
arguments : rep - <report>
returns : <boolean>
nonlocal-vars : *OUTGOING-CHANNELS* register
description : broadcasts "rep" to each of the <channel>s in
*OUTGOING-CHANNELS*
returns "true" if "rep" was actually sent
otherwise.
the signature of the report is updated
modified: rgh 08/21/85
rgh 3/30/86
============================================================================= |
Copyright ( C ) 1984 - -2013 Research Foundation of
Version : $ I d : nrn - reports.lisp , v 1.2 2013/08/28 19:07:27 shapiro Exp $
$ BEGIN LICENSE$
The contents of this file are subject to the University at
Software distributed under the License is distributed on an
" AS IS " basis , WITHOUT WARRANTY OF ANY KIND , either express
The Original Code is SNePS 2.8 .
The Initial Developer of the Original Code is Research Foun
dation of State University of New York , on behalf of Univer
sity at Buffalo .
Portions created by the Initial Developer are Copyright ( C )
2011 Research Foundation of State University of New York , on
behalf of University at Buffalo . All Rights Reserved .
$ END LICENSE$
(in-package :snip)
written : rgh 10/06/85
modified : rgh 10/15/85
(defmacro clear-incoming-reports ()
`(setq *REPORTS* (new.repset)))
written : rgh 10/06/85
modified : rgh 10/15/85
rgh 11/18/85
rgh 11/24/85
rgh 3/09/86
(defun process-reports.non-rule ()
(let ((reports *REPORTS*))
(declare (special *PRIORITY*))
(clear-incoming-reports)
(do ()
((isnew.repset reports))
(process-one-report.non-rule (choose.repset reports))
(setq reports (others.repset reports)))
(cond ((not (isnew.repset *PENDING-FORWARD-INFERENCES*))
(setq *PRIORITY* 'LOW)
(initiate (activation.n *NODE*))))))
process - one - report.non - rule
modified : scs 6/22/88
(defun process-one-report.non-rule (report)
(let ((instance (rep-to-instance report)))
(declare (special *ADDED-NODES*))
(when (unknown.inst instance)
(setq *ADDED-NODES* (insert.ns (node.rep report) *ADDED-NODES*)
*KNOWN-INSTANCES* (insert.iset instance *KNOWN-INSTANCES*))
(if (not (broadcast-one-report
(make.rep
(subst.rep report)
(support.rep report)
(sign.rep report)
*NODE*
nil
(context.rep report))))
(setq *PENDING-FORWARD-INFERENCES*
(insert.repset report *PENDING-FORWARD-INFERENCES*))))))
broadcast - one - report
through at least one of the channels , " false "
written : rgh 07/29/85
rgh 10/15/85
rgh 2/10/86
rgh 3/09/86
(defun broadcast-one-report (rep)
(let (anysent)
(do.chset (ch *OUTGOING-CHANNELS* anysent)
(when (isopen.ch ch)
(setq anysent (or (try-to-send-report rep ch) anysent))))))
|
cdd5c09ac318459eaf6f0698e5afcc45fc1c392995488212de5487c21410cea7 | dreyk/zraft_lib | zraft_client.erl | %% -------------------------------------------------------------------
@author < >
Copyright ( c ) 2015 . All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
-module(zraft_client).
-author("dreyk").
%% API
-export([
query/3,
write/3,
get_conf/1,
get_conf/2,
light_session/1,
light_session/3,
create/2,
create/3,
set_new_conf/4,
check_exists/1
]).
-export_type([
apply_conf_error/0
]).
-include("zraft.hrl").
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-define(TIMEOUT, 5000).
-define(CREATE_TIMEOUT, 5000).
-define(BACKOFF, 3000).
%%%===================================================================
%%% Read/Write
%%%===================================================================
-spec light_session(Conf) -> zraft_session_obj:light_session() | {error, Reason} when
Conf :: list(zraft_consensus:peer_id())|zraft_consensus:peer_id(),
Reason :: no_peers|term().
%% @doc Create light session for read/write operations.
@equiv light_session(Conf , zraft_consensus : get_election_timeout()*2,zraft_consensus : get_election_timeout ( ) )
%% @end
light_session(Conf) ->
E = zraft_consensus:get_election_timeout(),
light_session(Conf, E * 2, E).
-spec light_session(Conf, BackOff, Election) -> zraft_session_obj:light_session() | {error, Reason} when
Conf :: list(zraft_consensus:peer_id())|zraft_consensus:peer_id(),
BackOff :: timeout(),
Election :: timeout(),
Reason :: no_peers|term().
%% @doc Create light session for read/write operations
%%
%% Use it for create object that will be used to batch read/write operation.
%%
If Conf is single PeerID then quorum configuration will be read .
%% In that case it may return error.
%%
%% You must crate new object scine you know that quorum configuration has been changed.
%%
If Conf is empty list then { error , } will be returned .
%% @end
light_session([_F | _] = Peers, BackOff, Election) ->
zraft_session_obj:create(Peers, BackOff, Election);
light_session([], _BackOff, _Election) ->
{error, no_peers};
light_session(PeerID, BackOff, Election) ->
case get_conf(PeerID) of
{ok, {Leader, Peers}} ->
S1 = zraft_session_obj:create(Peers, BackOff, Election),
zraft_session_obj:set_leader(Leader, S1);
Error ->
Error
end.
-spec query(Raft, Query, Timeout) -> {Result, NewRaftConf}|RuntimeError when
Raft :: zraft_session_obj:light_session()|zraft_consensus:peer_id(),
Query :: term(),
Timeout :: timeout(),
Result :: term(),
NewRaftConf :: zraft_session_obj:light_session()|zraft_consensus:peer_id(),
RuntimeError :: {error, timeout}|{error, noproc}.
%% @doc Read data from state machine.
%%
%% Query parameter value depends on backend type used for state machine.
%%
%% If Raft is single peer than it will try to read data from it. Request will be redirected to leader
%% if that peer is follower or canditate. If peer is unreachable or is going down request will fail with error {error,noproc}.
%%
If Raft is light session object and current leader is going down it will retry requet to other peer and so on
%% until receive respose or timeout.
%% @end
query(Raft, Query, Timeout) ->
Fun = fun(ID) -> zraft_consensus:query(ID, Query, Timeout) end,
peer_execute(Raft, Fun, Timeout).
-spec write(Raft, Data, Timeout) -> {Result, NewRaftConf}|RuntimeError when
Raft :: zraft_session_obj:light_session()|zraft_consensus:peer_id(),
Data :: term(),
Timeout :: timeout(),
Result :: term(),
NewRaftConf :: zraft_session_obj:light_session()|zraft_consensus:peer_id(),
RuntimeError :: {error, timeout}|{error, noproc}.
%% @doc Write data to state machine.
%%
%% Data parameter value depends on backend type used for state machine.
%%
%% If Raft is single peer than it will try to write data from it. Request will be redirected to leader
%% if that peer is follower or canditate. If peer is unreachable or is going down request will fail with error {error,noproc}.
%%
If Raft is light session object and current leader is going down it will retry requet to other peer and so on
%% until receive respose or timeout.
%% @end
write(Raft, Data, Timeout) ->
Fun = fun(ID) -> zraft_consensus:write(ID, Data, Timeout) end,
peer_execute(Raft, Fun, Timeout).
%%%===================================================================
%%% Configuration
%%%===================================================================
-spec get_conf(PeerID) -> {ok, {Leader, Peers}}|{error, term()} when
PeerID :: zraft_consensus:peer_id(),
Leader :: zraft_consensus:peer_id(),%%Current leader
Peers :: list(zraft_consensus:peer_id()).
%% @doc Read raft consensus configuaration.
%% @equiv get_conf(PeerID,5000)
%% @end
get_conf(PeerID) ->
get_conf(PeerID, ?TIMEOUT).
-spec get_conf(PeerID, Timeout) -> {ok, {Leader, Peers}}|{error, term()} when
PeerID :: zraft_consensus:peer_id(),
Timeout :: timeout(),
Leader :: zraft_consensus:peer_id(),
Peers :: list(zraft_consensus:peer_id()).
%% @doc Read raft consensus configuaration.
%%
%% PeerID may be any peer in quorum. If it's not a leader, request will be redirected to the current leader
If leader or goes down during execution it may return runtime error or { error , timeout } .
%% In that case you may retry request.
%% @end
get_conf(PeerID, Timeout) ->
case wait_stable_conf(PeerID, Timeout) of
{ok, {Leader, _Index, Peers}} ->
{ok, {Leader, Peers}};
Error ->
Error
end.
-type apply_conf_error() :: leader_changed|not_stable|newer_exists|process_prev_change|timeout.
%%
-spec set_new_conf(Peer, NewPeers, OldPeers, Timeout) -> Result when
Peer :: zraft_consensus:peer_id(),
NewPeers :: list(zraft_consensus:peer_id()),
OldPeers :: list(zraft_consensus:peer_id()),
Timeout :: timeout(),
Result :: {ok, list(zraft_consensus:peer_id())}|{error, apply_conf_error()}.
set_new_conf(PeerID, NewPeers, OldPeers, Timeout) ->
NewSorted = ordsets:from_list(NewPeers),
case wait_stable_conf(PeerID, Timeout) of
{ok, {_Leader, _Index, NewSorted}} ->
{ok, NewPeers};
{ok, {Leader, Index, HasPeers}} ->
case ordsets:from_list(OldPeers) of
HasPeers ->
case catch zraft_consensus:set_new_configuration(Leader, Index, NewSorted, Timeout) of
ok -> {ok, NewPeers};
{leader, _NewLeader} ->
{error, leader_changed};
Else ->
format_error(Else)
end;
_ ->
{error, peers_changed}
end;
Else ->
Else
end.
%%%===================================================================
%%% Create new quorum
%%%===================================================================
-spec create(Peers, BackEnd) -> {ok, ResultPeers}|{error, term()} when
Peers :: list(zraft_consensus:peer_id()),
BackEnd :: module(),
ResultPeers :: list(zraft_consensus:peer_id()).
%% @doc Create new quorum.
@equiv create(lists : nth(1,Peers),Peers , UseBackend )
%% @end
create(Peers, UseBackend) ->
[FirstPeer | _] = Peers,
case FirstPeer of
{_, Node} when Node =:= node() ->
create(FirstPeer, Peers, UseBackend);
{_, Node} ->
rpc:call(Node, ?MODULE, create, [FirstPeer, Peers, UseBackend])
end.
-spec create(FirstPeer, Peers, BackEnd) -> {ok, ResultPeers}|{error, StartError|StartErrors}|{error, ApplyConfError} when
FirstPeer :: zraft_consensus:peer_id(),
Peers :: list(zraft_consensus:peer_id()),
BackEnd :: module(),
ResultPeers :: list(zraft_consensus:peer_id()),
StartError :: {zraft_consensus:peer_id(), already_present|nodedown, term()},
StartErrors :: list(StartError),
ApplyConfError :: apply_conf_error().
%% @doc Create new quorum.
%%
First it will be initialized FirstPeer . After that all other peers will be started and new configuration
will be applied to the FirstPeer and replicated to other .
%%
%% It returns error in following cases:
%%
1 . Some peer has been alredy started or ca n't be started
%%
2 . Ca n't apply new configuration to peers .
%% @end
create(FirstPeer, AllPeers, UseBackend) ->
case lists:foldl(fun(P, Acc) ->
case check_exists(P) of
ok ->
Acc;
{error, Error} ->
[{P, Error} | Acc]
end end, [], AllPeers) of
[] ->
case start_peers(UseBackend, AllPeers) of
ok ->
case catch zraft_consensus:initial_bootstrap(FirstPeer) of
ok ->
set_new_conf(FirstPeer, AllPeers, [FirstPeer], ?CREATE_TIMEOUT);
Else ->
format_error(Else)
end;
Else ->
Else
end;
Errors ->
{error, Errors}
end.
-spec start_peers(module(), list(zraft_consensus:peer_id())) ->
ok|{error, {already_present, zraft_consensus:peer_id()}}|{error, {zraft_consensus:peer_id(), term()}}.
start_peers(UseBackEnd, [P | T]) ->
Result = case P of
{_Name, Node} when Node =:= node() ->
zraft_lib_sup:start_consensus(P, UseBackEnd);
{_Name, Node} ->
rpc:call(Node, zraft_lib_sup, start_consensus, [P, UseBackEnd])
end,
case Result of
{ok, _} ->
start_peers(UseBackEnd, T);
{error, already_present} ->
{error, {P, already_present}};
{error, {'already_started', _}} ->
{error, {P, already_present}};
{badrpc, Error} ->
{error, {P, Error}};
{error, Reason} ->
{error, {P, Reason}}
end;
start_peers(_UseBackEnd, [])->
ok.
-spec check_exists(zraft_consensus:peer_id()) -> ok | {error, exists}.
check_exists(Peer = {Name, Node}) when Node =:= node() ->
PeerDir = filename:join([zraft_util:get_env(log_dir, "data"), zraft_util:peer_name(Peer)]),
case file:list_dir(PeerDir) of
{ok, _} ->
{error, already_present};
_ ->
case erlang:whereis(Name) of
P when is_pid(P) ->
{error, already_present};
_ ->
ok
end
end;
check_exists(Peer = {_Name, Node}) ->
case rpc:call(Node, ?MODULE, check_exists, [Peer]) of
{badrpc, Error} ->
{error, Error};
Result ->
Result
end.
%%%===================================================================
%%% Private
%%%===================================================================
peer_execute(Raft, Fun, Timeout) ->
Start = os:timestamp(),
case zraft_session_obj:is_session(Raft) of
true ->
peer_execute_sessions(Raft, Fun, Start, Timeout);
_ ->
peer_execute(Raft, Fun, Start, Timeout)
end.
peer_execute(PeerID, Fun, Start, Timeout) ->
case catch Fun(PeerID) of
{ok, Result} ->
{Result, PeerID};
{leader, NewLeader} ->
case zraft_util:is_expired(Start, Timeout) of
true ->
{error, timeout};
{false, _Timeout1} ->
peer_execute(NewLeader, Fun, os:timestamp(), Timeout)
end;
{error, loading}->
case zraft_util:is_expired(Start, Timeout) of
true ->
{error, timeout};
{false, _Timeout1} ->
peer_execute(PeerID, Fun, os:timestamp(), Timeout)
end;
Else ->
format_error(Else)
end.
peer_execute_sessions(Session, Fun, Start, Timeout) ->
Leader = zraft_session_obj:leader(Session),
Next = case catch Fun(Leader) of
{ok, Result} ->
{Result, Session};
{leader, NewLeader} when NewLeader /= undefined ->
case zraft_session_obj:change_leader(NewLeader, Session) of
{error, etimeout} ->
timer:sleep(zraft_consensus:get_election_timeout()),
{continue, Session};
{error, all_failed} ->
{error, all_failed};
Session1 ->
{continue, Session1}
end;
{error, loading}->
{continue, Session};
_Else ->
case zraft_session_obj:fail(Session) of
{error, Err} ->
{error, Err};
Session2 ->
{continue, Session2}
end
end,
case Next of
{continue, NextSession} ->
case zraft_util:is_expired(Start, Timeout) of
true ->
{error, timeout};
{false, _Timeout1} ->
peer_execute_sessions(NextSession, Fun, Start, Timeout)
end;
Else ->
Else
end.
@private
wait_stable_conf(Peer, Timeout) ->
wait_stable_conf(Peer,[], os:timestamp(), Timeout).
@private
wait_stable_conf(Peer,FallBack, Start, Timeout) ->
case zraft_util:is_expired(Start, Timeout) of
true ->
{error, timeout};
{false, _Timeout1} ->
case catch zraft_consensus:get_conf(Peer, Timeout) of
{leader, undefined} ->
timer:sleep(zraft_consensus:get_election_timeout()),
wait_stable_conf(Peer,FallBack, Start, Timeout);
{leader, NewLeader} ->
wait_stable_conf(NewLeader,[Peer|FallBack],Start, Timeout);
{error, loading}->
timer:sleep(zraft_consensus:get_election_timeout()),
wait_stable_conf(Peer,FallBack,Start, Timeout);
{ok, {0, _}} ->
timer:sleep(zraft_consensus:get_election_timeout()),
wait_stable_conf(Peer,FallBack,Start, Timeout);
{ok, {Index, Peers}} ->
{ok, {Peer, Index, Peers}};
retry ->
timer:sleep(zraft_consensus:get_election_timeout()),
wait_stable_conf(Peer,FallBack,Start, Timeout);
Error ->
lager:error("Can'r read conf from ~p:~p",[Peer,Error]),
case FallBack of
[]->
format_error(Error);
[TryOld|Other]->
wait_stable_conf(TryOld,Other,Start, Timeout)
end
end
end.
@private
format_error({'EXIT', _Reason}) ->
{error, noproc};
format_error({error, _} = Error) ->
Error;
format_error(Error) ->
{error, Error}.
| null | https://raw.githubusercontent.com/dreyk/zraft_lib/ead65c45df576be3758639e3fe3a46edefdeae1d/src/zraft_client.erl | erlang | -------------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
API
===================================================================
Read/Write
===================================================================
@doc Create light session for read/write operations.
@end
@doc Create light session for read/write operations
Use it for create object that will be used to batch read/write operation.
In that case it may return error.
You must crate new object scine you know that quorum configuration has been changed.
@end
@doc Read data from state machine.
Query parameter value depends on backend type used for state machine.
If Raft is single peer than it will try to read data from it. Request will be redirected to leader
if that peer is follower or canditate. If peer is unreachable or is going down request will fail with error {error,noproc}.
until receive respose or timeout.
@end
@doc Write data to state machine.
Data parameter value depends on backend type used for state machine.
If Raft is single peer than it will try to write data from it. Request will be redirected to leader
if that peer is follower or canditate. If peer is unreachable or is going down request will fail with error {error,noproc}.
until receive respose or timeout.
@end
===================================================================
Configuration
===================================================================
Current leader
@doc Read raft consensus configuaration.
@equiv get_conf(PeerID,5000)
@end
@doc Read raft consensus configuaration.
PeerID may be any peer in quorum. If it's not a leader, request will be redirected to the current leader
In that case you may retry request.
@end
===================================================================
Create new quorum
===================================================================
@doc Create new quorum.
@end
@doc Create new quorum.
It returns error in following cases:
@end
===================================================================
Private
=================================================================== | @author < >
Copyright ( c ) 2015 . All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(zraft_client).
-author("dreyk").
-export([
query/3,
write/3,
get_conf/1,
get_conf/2,
light_session/1,
light_session/3,
create/2,
create/3,
set_new_conf/4,
check_exists/1
]).
-export_type([
apply_conf_error/0
]).
-include("zraft.hrl").
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-define(TIMEOUT, 5000).
-define(CREATE_TIMEOUT, 5000).
-define(BACKOFF, 3000).
-spec light_session(Conf) -> zraft_session_obj:light_session() | {error, Reason} when
Conf :: list(zraft_consensus:peer_id())|zraft_consensus:peer_id(),
Reason :: no_peers|term().
@equiv light_session(Conf , zraft_consensus : get_election_timeout()*2,zraft_consensus : get_election_timeout ( ) )
light_session(Conf) ->
E = zraft_consensus:get_election_timeout(),
light_session(Conf, E * 2, E).
-spec light_session(Conf, BackOff, Election) -> zraft_session_obj:light_session() | {error, Reason} when
Conf :: list(zraft_consensus:peer_id())|zraft_consensus:peer_id(),
BackOff :: timeout(),
Election :: timeout(),
Reason :: no_peers|term().
If Conf is single PeerID then quorum configuration will be read .
If Conf is empty list then { error , } will be returned .
light_session([_F | _] = Peers, BackOff, Election) ->
zraft_session_obj:create(Peers, BackOff, Election);
light_session([], _BackOff, _Election) ->
{error, no_peers};
light_session(PeerID, BackOff, Election) ->
case get_conf(PeerID) of
{ok, {Leader, Peers}} ->
S1 = zraft_session_obj:create(Peers, BackOff, Election),
zraft_session_obj:set_leader(Leader, S1);
Error ->
Error
end.
-spec query(Raft, Query, Timeout) -> {Result, NewRaftConf}|RuntimeError when
Raft :: zraft_session_obj:light_session()|zraft_consensus:peer_id(),
Query :: term(),
Timeout :: timeout(),
Result :: term(),
NewRaftConf :: zraft_session_obj:light_session()|zraft_consensus:peer_id(),
RuntimeError :: {error, timeout}|{error, noproc}.
If Raft is light session object and current leader is going down it will retry requet to other peer and so on
query(Raft, Query, Timeout) ->
Fun = fun(ID) -> zraft_consensus:query(ID, Query, Timeout) end,
peer_execute(Raft, Fun, Timeout).
-spec write(Raft, Data, Timeout) -> {Result, NewRaftConf}|RuntimeError when
Raft :: zraft_session_obj:light_session()|zraft_consensus:peer_id(),
Data :: term(),
Timeout :: timeout(),
Result :: term(),
NewRaftConf :: zraft_session_obj:light_session()|zraft_consensus:peer_id(),
RuntimeError :: {error, timeout}|{error, noproc}.
If Raft is light session object and current leader is going down it will retry requet to other peer and so on
write(Raft, Data, Timeout) ->
Fun = fun(ID) -> zraft_consensus:write(ID, Data, Timeout) end,
peer_execute(Raft, Fun, Timeout).
-spec get_conf(PeerID) -> {ok, {Leader, Peers}}|{error, term()} when
PeerID :: zraft_consensus:peer_id(),
Peers :: list(zraft_consensus:peer_id()).
get_conf(PeerID) ->
get_conf(PeerID, ?TIMEOUT).
-spec get_conf(PeerID, Timeout) -> {ok, {Leader, Peers}}|{error, term()} when
PeerID :: zraft_consensus:peer_id(),
Timeout :: timeout(),
Leader :: zraft_consensus:peer_id(),
Peers :: list(zraft_consensus:peer_id()).
If leader or goes down during execution it may return runtime error or { error , timeout } .
get_conf(PeerID, Timeout) ->
case wait_stable_conf(PeerID, Timeout) of
{ok, {Leader, _Index, Peers}} ->
{ok, {Leader, Peers}};
Error ->
Error
end.
-type apply_conf_error() :: leader_changed|not_stable|newer_exists|process_prev_change|timeout.
-spec set_new_conf(Peer, NewPeers, OldPeers, Timeout) -> Result when
Peer :: zraft_consensus:peer_id(),
NewPeers :: list(zraft_consensus:peer_id()),
OldPeers :: list(zraft_consensus:peer_id()),
Timeout :: timeout(),
Result :: {ok, list(zraft_consensus:peer_id())}|{error, apply_conf_error()}.
set_new_conf(PeerID, NewPeers, OldPeers, Timeout) ->
NewSorted = ordsets:from_list(NewPeers),
case wait_stable_conf(PeerID, Timeout) of
{ok, {_Leader, _Index, NewSorted}} ->
{ok, NewPeers};
{ok, {Leader, Index, HasPeers}} ->
case ordsets:from_list(OldPeers) of
HasPeers ->
case catch zraft_consensus:set_new_configuration(Leader, Index, NewSorted, Timeout) of
ok -> {ok, NewPeers};
{leader, _NewLeader} ->
{error, leader_changed};
Else ->
format_error(Else)
end;
_ ->
{error, peers_changed}
end;
Else ->
Else
end.
-spec create(Peers, BackEnd) -> {ok, ResultPeers}|{error, term()} when
Peers :: list(zraft_consensus:peer_id()),
BackEnd :: module(),
ResultPeers :: list(zraft_consensus:peer_id()).
@equiv create(lists : nth(1,Peers),Peers , UseBackend )
create(Peers, UseBackend) ->
[FirstPeer | _] = Peers,
case FirstPeer of
{_, Node} when Node =:= node() ->
create(FirstPeer, Peers, UseBackend);
{_, Node} ->
rpc:call(Node, ?MODULE, create, [FirstPeer, Peers, UseBackend])
end.
-spec create(FirstPeer, Peers, BackEnd) -> {ok, ResultPeers}|{error, StartError|StartErrors}|{error, ApplyConfError} when
FirstPeer :: zraft_consensus:peer_id(),
Peers :: list(zraft_consensus:peer_id()),
BackEnd :: module(),
ResultPeers :: list(zraft_consensus:peer_id()),
StartError :: {zraft_consensus:peer_id(), already_present|nodedown, term()},
StartErrors :: list(StartError),
ApplyConfError :: apply_conf_error().
First it will be initialized FirstPeer . After that all other peers will be started and new configuration
will be applied to the FirstPeer and replicated to other .
1 . Some peer has been alredy started or ca n't be started
2 . Ca n't apply new configuration to peers .
create(FirstPeer, AllPeers, UseBackend) ->
case lists:foldl(fun(P, Acc) ->
case check_exists(P) of
ok ->
Acc;
{error, Error} ->
[{P, Error} | Acc]
end end, [], AllPeers) of
[] ->
case start_peers(UseBackend, AllPeers) of
ok ->
case catch zraft_consensus:initial_bootstrap(FirstPeer) of
ok ->
set_new_conf(FirstPeer, AllPeers, [FirstPeer], ?CREATE_TIMEOUT);
Else ->
format_error(Else)
end;
Else ->
Else
end;
Errors ->
{error, Errors}
end.
-spec start_peers(module(), list(zraft_consensus:peer_id())) ->
ok|{error, {already_present, zraft_consensus:peer_id()}}|{error, {zraft_consensus:peer_id(), term()}}.
start_peers(UseBackEnd, [P | T]) ->
Result = case P of
{_Name, Node} when Node =:= node() ->
zraft_lib_sup:start_consensus(P, UseBackEnd);
{_Name, Node} ->
rpc:call(Node, zraft_lib_sup, start_consensus, [P, UseBackEnd])
end,
case Result of
{ok, _} ->
start_peers(UseBackEnd, T);
{error, already_present} ->
{error, {P, already_present}};
{error, {'already_started', _}} ->
{error, {P, already_present}};
{badrpc, Error} ->
{error, {P, Error}};
{error, Reason} ->
{error, {P, Reason}}
end;
start_peers(_UseBackEnd, [])->
ok.
-spec check_exists(zraft_consensus:peer_id()) -> ok | {error, exists}.
check_exists(Peer = {Name, Node}) when Node =:= node() ->
PeerDir = filename:join([zraft_util:get_env(log_dir, "data"), zraft_util:peer_name(Peer)]),
case file:list_dir(PeerDir) of
{ok, _} ->
{error, already_present};
_ ->
case erlang:whereis(Name) of
P when is_pid(P) ->
{error, already_present};
_ ->
ok
end
end;
check_exists(Peer = {_Name, Node}) ->
case rpc:call(Node, ?MODULE, check_exists, [Peer]) of
{badrpc, Error} ->
{error, Error};
Result ->
Result
end.
peer_execute(Raft, Fun, Timeout) ->
Start = os:timestamp(),
case zraft_session_obj:is_session(Raft) of
true ->
peer_execute_sessions(Raft, Fun, Start, Timeout);
_ ->
peer_execute(Raft, Fun, Start, Timeout)
end.
peer_execute(PeerID, Fun, Start, Timeout) ->
case catch Fun(PeerID) of
{ok, Result} ->
{Result, PeerID};
{leader, NewLeader} ->
case zraft_util:is_expired(Start, Timeout) of
true ->
{error, timeout};
{false, _Timeout1} ->
peer_execute(NewLeader, Fun, os:timestamp(), Timeout)
end;
{error, loading}->
case zraft_util:is_expired(Start, Timeout) of
true ->
{error, timeout};
{false, _Timeout1} ->
peer_execute(PeerID, Fun, os:timestamp(), Timeout)
end;
Else ->
format_error(Else)
end.
peer_execute_sessions(Session, Fun, Start, Timeout) ->
Leader = zraft_session_obj:leader(Session),
Next = case catch Fun(Leader) of
{ok, Result} ->
{Result, Session};
{leader, NewLeader} when NewLeader /= undefined ->
case zraft_session_obj:change_leader(NewLeader, Session) of
{error, etimeout} ->
timer:sleep(zraft_consensus:get_election_timeout()),
{continue, Session};
{error, all_failed} ->
{error, all_failed};
Session1 ->
{continue, Session1}
end;
{error, loading}->
{continue, Session};
_Else ->
case zraft_session_obj:fail(Session) of
{error, Err} ->
{error, Err};
Session2 ->
{continue, Session2}
end
end,
case Next of
{continue, NextSession} ->
case zraft_util:is_expired(Start, Timeout) of
true ->
{error, timeout};
{false, _Timeout1} ->
peer_execute_sessions(NextSession, Fun, Start, Timeout)
end;
Else ->
Else
end.
@private
wait_stable_conf(Peer, Timeout) ->
wait_stable_conf(Peer,[], os:timestamp(), Timeout).
@private
wait_stable_conf(Peer,FallBack, Start, Timeout) ->
case zraft_util:is_expired(Start, Timeout) of
true ->
{error, timeout};
{false, _Timeout1} ->
case catch zraft_consensus:get_conf(Peer, Timeout) of
{leader, undefined} ->
timer:sleep(zraft_consensus:get_election_timeout()),
wait_stable_conf(Peer,FallBack, Start, Timeout);
{leader, NewLeader} ->
wait_stable_conf(NewLeader,[Peer|FallBack],Start, Timeout);
{error, loading}->
timer:sleep(zraft_consensus:get_election_timeout()),
wait_stable_conf(Peer,FallBack,Start, Timeout);
{ok, {0, _}} ->
timer:sleep(zraft_consensus:get_election_timeout()),
wait_stable_conf(Peer,FallBack,Start, Timeout);
{ok, {Index, Peers}} ->
{ok, {Peer, Index, Peers}};
retry ->
timer:sleep(zraft_consensus:get_election_timeout()),
wait_stable_conf(Peer,FallBack,Start, Timeout);
Error ->
lager:error("Can'r read conf from ~p:~p",[Peer,Error]),
case FallBack of
[]->
format_error(Error);
[TryOld|Other]->
wait_stable_conf(TryOld,Other,Start, Timeout)
end
end
end.
@private
format_error({'EXIT', _Reason}) ->
{error, noproc};
format_error({error, _} = Error) ->
Error;
format_error(Error) ->
{error, Error}.
|
0d6f5ca21722dc5ac1a3fb425ee6c27aed387da8d4612638ca0f42d5267c435f | IG-Group/Havoc | docker.clj | (ns ig.havoc.impl.docker
(:require
[clojure.string :as s]
[ig.havoc.impl.command-generator :as core]
[clj-http.client :as http-client]
[cheshire.core :as json]
byte-streams
[slingshot.slingshot :refer [try+ throw+]]
[selmer.parser :as selmer]
[clojure.tools.logging :as log])
(:import (java.nio ByteBuffer ByteOrder)
(java.io InputStream)))
(def resp-streams [:stdin :stdout :stderr])
(def ^int ^:const resp-buf-size 1024)
(defn read-record
[^InputStream dis]
(let [resp-buf (byte-array resp-buf-size)
^ByteBuffer hdr-bb (doto (ByteBuffer/wrap resp-buf)
(.order ByteOrder/BIG_ENDIAN))
n (.read dis resp-buf 0 8)]
(when (pos? n)
(assert (= n 8))
(.rewind hdr-bb)
skip 4 bytes
(let [t (int (aget ^bytes resp-buf 0))
n (.getInt hdr-bb)
s (loop [r ""
n n]
(if (pos? n)
(let [n2 (.read dis resp-buf 0 (min n resp-buf-size))
r (str r (String. ^bytes resp-buf 0 n2))]
(if (pos? n2)
(recur r (- n n2))
r))
r))]
[(resp-streams t) s]))))
(defn create-docker [docker-url docker-compose-project-name]
(letfn [(clean-project-name []
(s/replace docker-compose-project-name #"-" ""))
(container-info [idx full-container-info]
[(-> full-container-info :Labels :com.docker.compose.service keyword)
{:ip (-> full-container-info :NetworkSettings :Networks first val :IPAddress)
:name (.substring (-> full-container-info :Names first) 1)
:tc-number (* 10 (inc idx))}])
(correct-project? [full-container-info]
(= (clean-project-name)
(-> full-container-info :Labels :com.docker.compose.project)))]
{:docker-url docker-url
:project (clean-project-name)
:services (->> (http-client/get (str docker-url "/containers/json") {:as :json})
:body
(filter correct-project?)
(sort-by :name)
(map-indexed container-info)
(into {}))}))
(defn service->name [docker service]
(-> docker :services service :name))
(defn service->ip [docker service]
(-> docker :services service :ip))
(defn service->tc-number [docker service]
(-> docker :services service :tc-number))
(defn exec [{:keys [docker-url] :as docker} service cmd]
(let [request {:method :post
:url (str docker-url "/containers/" (service->name docker service) "/exec")
:as :json
:content-type :json
:body (json/generate-string {:AttachStdin false :AttachStdout true :AttachStderr true
:Tty false :Cmd cmd})}]
(if-let [exec (try+ (http-client/request request)
(catch [:status 500] {:keys [body]}
(if (.contains body "is not running")
(log/debug "Ignoring " cmd " as service is not running")
(throw+))
false))]
(if-let [exec-id (-> exec :body :Id)]
(->
(http-client/request {:method :post
:url (str docker-url "/exec/" exec-id "/start")
:content-type :json
:as :byte-array
:body (json/generate-string {:Detach false :Tty false})})
:body
byte-streams/to-input-stream
read-record
(log/debug "running" cmd))
(throw (ex-info "exec response has no id" {:request request
:response exec
:docker docker
:service service}))))))
(defn live-cycle! [docker service live-cycle-command]
(http-client/request {:method :post
:url (str (:docker-url docker)
"/containers/" (service->name docker service) "/" (name live-cycle-command))}))
(defmacro def-livecycle [x cmd]
`(defmethod core/exec! ~cmd [docker# params#]
(live-cycle! docker# (:host params#) ~x)))
(doseq [x [:start :stop :pause :unpause :kill :restart]]
(def-livecycle x (keyword "container" (name x))))
(defmethod core/exec! :link/cut [docker {:keys [from to]}]
(exec docker from ["su" "-c" (str "iptables -A INPUT -s " (service->ip docker to) " -j DROP")]))
(defmethod core/exec! :link/fix [docker {:keys [from to]}]
(exec docker from ["su" "-c" (str "iptables -D INPUT -s " (service->ip docker to) " -j DROP")]))
(def allow-all-traffic
"tc qdisc add dev eth0 root handle 1: htb default 99;
tc class add dev eth0 parent 1: classid 1:99 htb rate 1000mbit;
tc qdisc add dev eth0 parent 1:99 handle 99: pfifo limit 5000;")
(defmethod core/exec! :link/flaky [docker {:keys [from to delay loss corrupt rate]
:or {rate "1000mbit"}}]
(let [delay-str (when delay
(selmer/render
"delay {{time}}ms {{jitter|default:1}}ms {{correlation|default:0}}% distribution normal"
delay))
loss-str (when loss
(selmer/render
"loss {{percent}}% {{correlation|default:0}}%"
loss))
corrupt-str (when corrupt
(selmer/render
"corrupt {{percent}}%"
corrupt))]
(exec docker from
["su" "-c"
(selmer/render
(str allow-all-traffic
"tc class replace dev eth0 parent 1: classid 1:{{tc-number}} htb rate {{rate}};
tc filter replace dev eth0 parent 1: protocol ip prio {{tc-number}} u32 flowid 1:{{tc-number}} match ip dst {{ip}};
tc qdisc replace dev eth0 parent 1:{{tc-number}} handle {{handle-number}}: netem {{loss}} {{delay}} {{corrupt}}")
{:tc-number (service->tc-number docker to)
:ip (service->ip docker to)
:handle-number (service->tc-number docker to)
:loss loss-str
:delay delay-str
:corrupt corrupt-str
:rate rate})])))
(defmethod core/exec! :link/fast [docker {:keys [from to]}]
(exec docker from
["su" "-c"
(selmer/render
"tc filter del dev eth0 prio {{tc-number}};
tc qdisc del dev eth0 parent 1:{{tc-number}};"
{:ip (service->ip docker to)
:tc-number (service->tc-number docker to)})])) | null | https://raw.githubusercontent.com/IG-Group/Havoc/24c9d8409b273d791370593d131525f04ba2c9a1/src/ig/havoc/impl/docker.clj | clojure |
")
" | (ns ig.havoc.impl.docker
(:require
[clojure.string :as s]
[ig.havoc.impl.command-generator :as core]
[clj-http.client :as http-client]
[cheshire.core :as json]
byte-streams
[slingshot.slingshot :refer [try+ throw+]]
[selmer.parser :as selmer]
[clojure.tools.logging :as log])
(:import (java.nio ByteBuffer ByteOrder)
(java.io InputStream)))
(def resp-streams [:stdin :stdout :stderr])
(def ^int ^:const resp-buf-size 1024)
(defn read-record
[^InputStream dis]
(let [resp-buf (byte-array resp-buf-size)
^ByteBuffer hdr-bb (doto (ByteBuffer/wrap resp-buf)
(.order ByteOrder/BIG_ENDIAN))
n (.read dis resp-buf 0 8)]
(when (pos? n)
(assert (= n 8))
(.rewind hdr-bb)
skip 4 bytes
(let [t (int (aget ^bytes resp-buf 0))
n (.getInt hdr-bb)
s (loop [r ""
n n]
(if (pos? n)
(let [n2 (.read dis resp-buf 0 (min n resp-buf-size))
r (str r (String. ^bytes resp-buf 0 n2))]
(if (pos? n2)
(recur r (- n n2))
r))
r))]
[(resp-streams t) s]))))
(defn create-docker [docker-url docker-compose-project-name]
(letfn [(clean-project-name []
(s/replace docker-compose-project-name #"-" ""))
(container-info [idx full-container-info]
[(-> full-container-info :Labels :com.docker.compose.service keyword)
{:ip (-> full-container-info :NetworkSettings :Networks first val :IPAddress)
:name (.substring (-> full-container-info :Names first) 1)
:tc-number (* 10 (inc idx))}])
(correct-project? [full-container-info]
(= (clean-project-name)
(-> full-container-info :Labels :com.docker.compose.project)))]
{:docker-url docker-url
:project (clean-project-name)
:services (->> (http-client/get (str docker-url "/containers/json") {:as :json})
:body
(filter correct-project?)
(sort-by :name)
(map-indexed container-info)
(into {}))}))
(defn service->name [docker service]
(-> docker :services service :name))
(defn service->ip [docker service]
(-> docker :services service :ip))
(defn service->tc-number [docker service]
(-> docker :services service :tc-number))
(defn exec [{:keys [docker-url] :as docker} service cmd]
(let [request {:method :post
:url (str docker-url "/containers/" (service->name docker service) "/exec")
:as :json
:content-type :json
:body (json/generate-string {:AttachStdin false :AttachStdout true :AttachStderr true
:Tty false :Cmd cmd})}]
(if-let [exec (try+ (http-client/request request)
(catch [:status 500] {:keys [body]}
(if (.contains body "is not running")
(log/debug "Ignoring " cmd " as service is not running")
(throw+))
false))]
(if-let [exec-id (-> exec :body :Id)]
(->
(http-client/request {:method :post
:url (str docker-url "/exec/" exec-id "/start")
:content-type :json
:as :byte-array
:body (json/generate-string {:Detach false :Tty false})})
:body
byte-streams/to-input-stream
read-record
(log/debug "running" cmd))
(throw (ex-info "exec response has no id" {:request request
:response exec
:docker docker
:service service}))))))
(defn live-cycle! [docker service live-cycle-command]
(http-client/request {:method :post
:url (str (:docker-url docker)
"/containers/" (service->name docker service) "/" (name live-cycle-command))}))
(defmacro def-livecycle [x cmd]
`(defmethod core/exec! ~cmd [docker# params#]
(live-cycle! docker# (:host params#) ~x)))
(doseq [x [:start :stop :pause :unpause :kill :restart]]
(def-livecycle x (keyword "container" (name x))))
(defmethod core/exec! :link/cut [docker {:keys [from to]}]
(exec docker from ["su" "-c" (str "iptables -A INPUT -s " (service->ip docker to) " -j DROP")]))
(defmethod core/exec! :link/fix [docker {:keys [from to]}]
(exec docker from ["su" "-c" (str "iptables -D INPUT -s " (service->ip docker to) " -j DROP")]))
(def allow-all-traffic
(defmethod core/exec! :link/flaky [docker {:keys [from to delay loss corrupt rate]
:or {rate "1000mbit"}}]
(let [delay-str (when delay
(selmer/render
"delay {{time}}ms {{jitter|default:1}}ms {{correlation|default:0}}% distribution normal"
delay))
loss-str (when loss
(selmer/render
"loss {{percent}}% {{correlation|default:0}}%"
loss))
corrupt-str (when corrupt
(selmer/render
"corrupt {{percent}}%"
corrupt))]
(exec docker from
["su" "-c"
(selmer/render
(str allow-all-traffic
tc qdisc replace dev eth0 parent 1:{{tc-number}} handle {{handle-number}}: netem {{loss}} {{delay}} {{corrupt}}")
{:tc-number (service->tc-number docker to)
:ip (service->ip docker to)
:handle-number (service->tc-number docker to)
:loss loss-str
:delay delay-str
:corrupt corrupt-str
:rate rate})])))
(defmethod core/exec! :link/fast [docker {:keys [from to]}]
(exec docker from
["su" "-c"
(selmer/render
{:ip (service->ip docker to)
:tc-number (service->tc-number docker to)})])) |
fa3f83899794c66beeb4de53e2f63c49ceea22e4cd2d77be98e7cbd8242b58eb | mbuczko/revolt | plugin.clj | (ns revolt.plugin
"A home namespace for built-in plugins along with initialization functions."
(:require [clojure.tools.logging :as log]))
(defprotocol Plugin
(activate [this ctx] "Activates plugin within given context")
(deactivate [this ret] "Deactivates plugin"))
(defmulti create-plugin (fn [id config] id))
(defn resolve-from-symbol
"Loads the namespace denoted by given symbol and calls `init-plugin`
from within, passing plugin configuration as argument."
[sym config]
(require sym)
(when-let [initializer (ns-resolve sym 'init-plugin)]
(initializer config)))
(defn initialize-plugin
"Creates a plugin straight from qualified keyword.
Loads a corresponding namespace form qualified keyword and invokes
`create-plugin` multi-method with keyword itself as a dispatch value,
passing predefined plugin configuration as a second argument."
[kw config]
(log/debug "loading plugin" kw)
(if (qualified-keyword? kw)
(let [ns (symbol (namespace kw))]
(require ns)
(create-plugin kw config))
(log/errorf "Wrong keyword %s. Qualified keyword required." kw)))
;; default plugins
(defmethod create-plugin ::nrepl [_ config]
(resolve-from-symbol 'revolt.plugins.nrepl config))
(defmethod create-plugin ::rebel [_ config]
(resolve-from-symbol 'revolt.plugins.rebel config))
(defmethod create-plugin ::watch [_ config]
(resolve-from-symbol 'revolt.plugins.watch config))
(defmethod create-plugin ::figwheel [_ config]
(resolve-from-symbol 'revolt.plugins.figwheel config))
| null | https://raw.githubusercontent.com/mbuczko/revolt/65ef8de68d7aa77d1ced40e7d669ebcbba8a340e/src/revolt/plugin.clj | clojure | default plugins | (ns revolt.plugin
"A home namespace for built-in plugins along with initialization functions."
(:require [clojure.tools.logging :as log]))
(defprotocol Plugin
(activate [this ctx] "Activates plugin within given context")
(deactivate [this ret] "Deactivates plugin"))
(defmulti create-plugin (fn [id config] id))
(defn resolve-from-symbol
"Loads the namespace denoted by given symbol and calls `init-plugin`
from within, passing plugin configuration as argument."
[sym config]
(require sym)
(when-let [initializer (ns-resolve sym 'init-plugin)]
(initializer config)))
(defn initialize-plugin
"Creates a plugin straight from qualified keyword.
Loads a corresponding namespace form qualified keyword and invokes
`create-plugin` multi-method with keyword itself as a dispatch value,
passing predefined plugin configuration as a second argument."
[kw config]
(log/debug "loading plugin" kw)
(if (qualified-keyword? kw)
(let [ns (symbol (namespace kw))]
(require ns)
(create-plugin kw config))
(log/errorf "Wrong keyword %s. Qualified keyword required." kw)))
(defmethod create-plugin ::nrepl [_ config]
(resolve-from-symbol 'revolt.plugins.nrepl config))
(defmethod create-plugin ::rebel [_ config]
(resolve-from-symbol 'revolt.plugins.rebel config))
(defmethod create-plugin ::watch [_ config]
(resolve-from-symbol 'revolt.plugins.watch config))
(defmethod create-plugin ::figwheel [_ config]
(resolve-from-symbol 'revolt.plugins.figwheel config))
|
f2418fc2a5c7cadc1418fcad41d173a9bdfec4254be0e0917d377a7116c45109 | hbr/albatross | source_prover.mli | Copyright ( C ) < helmut dot brandl at gmx dot net >
This file is distributed under the terms of the GNU General Public License
version 2 ( GPLv2 ) as published by the Free Software Foundation .
This file is distributed under the terms of the GNU General Public License
version 2 (GPLv2) as published by the Free Software Foundation.
*)
open Support
module PC = Proof_context
val prove_and_store:
entities list withinfo
-> compound -> compound -> source_proof -> PC.t
-> unit
| null | https://raw.githubusercontent.com/hbr/albatross/8f28ef97951f92f30dc69cf94c0bbe20d64fba21/ocaml/alba1/source_prover.mli | ocaml | Copyright ( C ) < helmut dot brandl at gmx dot net >
This file is distributed under the terms of the GNU General Public License
version 2 ( GPLv2 ) as published by the Free Software Foundation .
This file is distributed under the terms of the GNU General Public License
version 2 (GPLv2) as published by the Free Software Foundation.
*)
open Support
module PC = Proof_context
val prove_and_store:
entities list withinfo
-> compound -> compound -> source_proof -> PC.t
-> unit
|
|
d2a6a996cdfc6d25d26a3ef524b6762528eb57fe367a48757990fb917f15a777 | LeventErkok/sbv | Index.hs | -----------------------------------------------------------------------------
-- |
-- Module : TestSuite.Basics.Index
Copyright : ( c )
-- License : BSD3
-- Maintainer:
-- Stability : experimental
--
-- Test suite for Examples.Basics.Index
-----------------------------------------------------------------------------
{-# OPTIONS_GHC -Wall -Werror #-}
module TestSuite.Basics.Index(tests) where
import Utils.SBVTestFramework
tests :: TestTree
tests =
testGroup "Basics.Index"
(zipWith
mkTest
[f x | f <- [test1, test2, test3], x <- [0..13]]
[(0::Int)..])
mkTest :: IO Bool -> Int -> TestTree
mkTest tst i =
testCase ("index-" ++ show i)
(assert tst)
-- prove that the "select" primitive is working correctly
test1 :: Int -> IO Bool
test1 n = isTheorem $ do
elts <- mkForallVars n
err <- sbvForall_
ind <- sbvForall_
ind2 <- sbvForall_
let r1 = (select :: [SWord8] -> SWord8 -> SInt8 -> SWord8) elts err ind
r2 = (select :: [SWord8] -> SWord8 -> SWord8 -> SWord8) elts err ind2
r3 = slowSearch elts err ind
r4 = slowSearch elts err ind2
return $ r1 .== r3 .&& r2 .== r4
where slowSearch elts err i = ite (i .< 0) err (go elts i)
where go [] _ = err
go (x:xs) curInd = ite (curInd .== 0) x (go xs (curInd - 1))
test2 :: Int -> IO Bool
test2 n = isTheorem $ do
elts1 <- mkForallVars n
elts2 <- mkForallVars n
let elts = zip elts1 elts2
err1 <- sbvForall_
err2 <- sbvForall_
let err = (err1, err2)
ind <- sbvForall_
ind2 <- sbvForall_
let r1 = (select :: [(SWord8, SWord8)] -> (SWord8, SWord8) -> SInt8 -> (SWord8, SWord8)) elts err ind
r2 = (select :: [(SWord8, SWord8)] -> (SWord8, SWord8) -> SWord8 -> (SWord8, SWord8)) elts err ind2
r3 = slowSearch elts err ind
r4 = slowSearch elts err ind2
return $ r1 .== r3 .&& r2 .== r4
where slowSearch elts err i = ite (i .< 0) err (go elts i)
where go [] _ = err
go (x:xs) curInd = ite (curInd .== 0) x (go xs (curInd - 1))
test3 :: Int -> IO Bool
test3 n = isTheorem $ do
eltsI <- mkForallVars n
let elts = map Left eltsI
errI <- sbvForall_
let err = Left errI
ind <- sbvForall_
let r1 = (select :: [Either SWord8 SWord8] -> Either SWord8 SWord8 -> SInt8 -> Either SWord8 SWord8) elts err ind
r2 = slowSearch elts err ind
return $ r1 .== r2
where slowSearch elts err i = ite (i .< 0) err (go elts i)
where go [] _ = err
go (x:xs) curInd = ite (curInd .== 0) x (go xs (curInd - 1))
| null | https://raw.githubusercontent.com/LeventErkok/sbv/0d791d9f4d1de6bd915b6d7d3f9a550385cb27a5/SBVTestSuite/TestSuite/Basics/Index.hs | haskell | ---------------------------------------------------------------------------
|
Module : TestSuite.Basics.Index
License : BSD3
Maintainer:
Stability : experimental
Test suite for Examples.Basics.Index
---------------------------------------------------------------------------
# OPTIONS_GHC -Wall -Werror #
prove that the "select" primitive is working correctly | Copyright : ( c )
module TestSuite.Basics.Index(tests) where
import Utils.SBVTestFramework
tests :: TestTree
tests =
testGroup "Basics.Index"
(zipWith
mkTest
[f x | f <- [test1, test2, test3], x <- [0..13]]
[(0::Int)..])
mkTest :: IO Bool -> Int -> TestTree
mkTest tst i =
testCase ("index-" ++ show i)
(assert tst)
test1 :: Int -> IO Bool
test1 n = isTheorem $ do
elts <- mkForallVars n
err <- sbvForall_
ind <- sbvForall_
ind2 <- sbvForall_
let r1 = (select :: [SWord8] -> SWord8 -> SInt8 -> SWord8) elts err ind
r2 = (select :: [SWord8] -> SWord8 -> SWord8 -> SWord8) elts err ind2
r3 = slowSearch elts err ind
r4 = slowSearch elts err ind2
return $ r1 .== r3 .&& r2 .== r4
where slowSearch elts err i = ite (i .< 0) err (go elts i)
where go [] _ = err
go (x:xs) curInd = ite (curInd .== 0) x (go xs (curInd - 1))
test2 :: Int -> IO Bool
test2 n = isTheorem $ do
elts1 <- mkForallVars n
elts2 <- mkForallVars n
let elts = zip elts1 elts2
err1 <- sbvForall_
err2 <- sbvForall_
let err = (err1, err2)
ind <- sbvForall_
ind2 <- sbvForall_
let r1 = (select :: [(SWord8, SWord8)] -> (SWord8, SWord8) -> SInt8 -> (SWord8, SWord8)) elts err ind
r2 = (select :: [(SWord8, SWord8)] -> (SWord8, SWord8) -> SWord8 -> (SWord8, SWord8)) elts err ind2
r3 = slowSearch elts err ind
r4 = slowSearch elts err ind2
return $ r1 .== r3 .&& r2 .== r4
where slowSearch elts err i = ite (i .< 0) err (go elts i)
where go [] _ = err
go (x:xs) curInd = ite (curInd .== 0) x (go xs (curInd - 1))
test3 :: Int -> IO Bool
test3 n = isTheorem $ do
eltsI <- mkForallVars n
let elts = map Left eltsI
errI <- sbvForall_
let err = Left errI
ind <- sbvForall_
let r1 = (select :: [Either SWord8 SWord8] -> Either SWord8 SWord8 -> SInt8 -> Either SWord8 SWord8) elts err ind
r2 = slowSearch elts err ind
return $ r1 .== r2
where slowSearch elts err i = ite (i .< 0) err (go elts i)
where go [] _ = err
go (x:xs) curInd = ite (curInd .== 0) x (go xs (curInd - 1))
|
200447447e598561804970bde479177f7ca0c991c05bfd3f7b072b24158f75cd | geoffder/dometyl-keyboard | niz.ml | open OCADml
open OSCADml
module Bottom = struct
let w = 17.5
let h = 17.5
let thickness = 4.
let bulge_thickness = 0.6
let bulge_length = 6.5
let bulge_height = 3.2
let ellipse_offset = -0.25
let ellipse_x = (w /. 2.) +. ellipse_offset
let ellipse_inset_x_rad = 1.6
let ellipse_inset_y_scale = 1.2
let corner_cut_rad = 3.
let corner_cut_off = 1.
let ellipse =
Scad.scale (v2 1. ellipse_inset_y_scale) (Scad.circle ~fn:32 ellipse_inset_x_rad)
let bulge = Scad.square ~center:true (v2 bulge_length (bulge_thickness +. 0.1))
let cutter = Scad.circle ~fn:64 corner_cut_rad
let corner x_sign y_sign =
let x = (w /. 2.) +. corner_cut_off
and y = (h /. 2.) +. corner_cut_off in
Scad.translate (v2 (x *. x_sign) (y *. y_sign)) cutter
let shadow =
Scad.union
[ Scad.difference
(Scad.square ~center:true (v2 w h))
[ Scad.translate (v2 ellipse_x 0.) ellipse
; Scad.translate (v2 (ellipse_x *. -1.) 0.) ellipse
; corner 1. 1.
; corner 1. (-1.)
; corner (-1.) 1.
; corner (-1.) (-1.)
]
; Scad.ytrans ((h /. 2.) +. (bulge_thickness /. 2.)) bulge
; Scad.ytrans ((h /. -2.) -. (bulge_thickness /. 2.) +. 0.001) bulge
; Scad.ytrans ((h /. 2.) +. (bulge_thickness /. 2.)) bulge
; Scad.ytrans ((h /. -2.) -. (bulge_thickness /. 2.) +. 0.001) bulge
]
let scad =
let bulges =
let b = Scad.extrude ~height:bulge_height bulge in
[ Scad.translate (v3 0. ((h /. 2.) -. 0.1) 0.) b
; Scad.translate (v3 0. ((h /. -2.) +. 0.1) 0.) b
]
in
Scad.difference
(Scad.square ~center:true (v2 w h))
[ Scad.xtrans ellipse_x ellipse
; Scad.xtrans (ellipse_x *. -1.) ellipse
; corner 1. 1.
; corner 1. (-1.)
; corner (-1.) 1.
; corner (-1.) (-1.)
]
|> Scad.extrude ~height:(thickness +. 0.001)
|> fun b -> Scad.union (b :: bulges)
end
module Config = struct
type t =
{ outer_w : float
; outer_h : float
; inner_w : float
; inner_h : float
; thickness : float
; cap_height : float
; cap_cutout_height : float option
; clearance : float
; corner : Path3.Round.corner option
; fn : int option
; dome_w : float
; dome_waist_clip : float
; dome_thickness : float
; base_thickness : float
; sensor_depth : float
; sensor_cutter : Sensor.cutter
}
let make
?(outer_w = 20.5)
?(outer_h = 20.5)
?(inner_w = 14.)
?(inner_h = 14.)
?(thickness = 5.6)
?(cap_height = 6.5)
?(cap_cutout_height = Some 1.5)
?(clearance = 4.)
?corner
?fn
?(dome_w = 19.5)
?(dome_waist_clip = 1.)
?(dome_thickness = 1.6)
?(base_thickness = 3.)
?(sensor_depth = 1.4)
?(sensor_cutter = Sensor.ThroughHole.tape_cutout ())
()
=
{ outer_w
; outer_h
; inner_w
; inner_h
; thickness
; cap_height
; cap_cutout_height
; clearance
; corner
; fn
; dome_w
; dome_waist_clip
; dome_thickness
; base_thickness
; sensor_depth
; sensor_cutter
}
let default = make ()
end
Dome thickness
- BKE ~= 0.85 mm
- DES ~= 0.70 mm
The actual value for [ dome_thickness ] though must account for FDM overhang
tolerance , thus it should be a good amount higher to ensure reliable fit .
Both and DES domes are roughly ~19x19 mm .
- BKE ~= 0.85mm
- DES ~= 0.70mm
The actual value for [dome_thickness] though must account for FDM overhang
tolerance, thus it should be a good amount higher to ensure reliable fit.
Both BKE and DES domes are roughly ~19x19mm. *)
Magnet size , with a sensor depth of 1.4 mm ( slightly below the thickness of a
standard through - hole sensor package ):
- 3x1 mm magnets actuate the AH3574 sensor at ~1.16 mm travel and are able to
deactivate by the top of the return with Niz rings
- 2x1 magnets actuate the AH3572 sensor at ~2.4 mm travel , deactivation
occurs by the top of the return with Niz rings .
- recommended : 2x1 magnet with sensor_depth = 1.4 . Easier to attach magnet
size , and should be no worries about hysteresis within FDM and gluing
tolerances with the stock Niz silencing rings . Thinner rings ( or no rings )
will increase the travel , so keep that in mind .
standard through-hole sensor package):
- 3x1mm magnets actuate the AH3574 sensor at ~1.16mm travel and are able to
deactivate by the top of the return with Niz rings
- 2x1 magnets actuate the AH3572 sensor at ~2.4mm travel, deactivation
occurs by the top of the return with Niz rings.
- recommended: 2x1 magnet with sensor_depth = 1.4. Easier to attach magnet
size, and should be no worries about hysteresis within FDM and gluing
tolerances with the stock Niz silencing rings. Thinner rings (or no rings)
will increase the travel, so keep that in mind. *)
(* TODO: better magnet / sensor break down notes *)
let hole_of_config
?render
?cap
Config.
{ outer_w
; outer_h
; inner_w
; inner_h
; thickness
; cap_height
; cap_cutout_height
; clearance
; corner
; fn
; dome_w
; dome_waist_clip
; dome_thickness
; base_thickness
; sensor_depth
; sensor_cutter
}
=
let thickness = Float.max thickness (Bottom.thickness +. dome_thickness) in
let clearance = Float.max clearance (base_thickness +. 0.5)
and bottom_z = (thickness /. 2.) -. Bottom.thickness
and bottom_cut = Scad.extrude ~height:(Bottom.thickness *. 2.) Bottom.shadow in
let dome_z = bottom_z -. dome_thickness in
let dome_cut =
let waist_clip sign =
Scad.difference
Bottom.ellipse
[ Scad.square
~center:true
(v2
(dome_waist_clip *. 2.)
(Bottom.ellipse_inset_x_rad *. Bottom.ellipse_inset_y_scale *. 2.) )
|> Scad.translate (v2 (Bottom.ellipse_inset_x_rad *. -.sign) 0.)
]
|> Scad.translate (v2 (Bottom.ellipse_x *. sign) 0.)
in
Scad.difference
(Scad.square ~center:true (v2 dome_w dome_w))
[ waist_clip 1.; waist_clip (-1.) ]
|> Scad.extrude ~height:(dome_thickness +. 0.001)
|> Scad.translate (v3 0. 0. dome_z)
and base =
let slab =
Scad.cube (v3 outer_w outer_h (base_thickness +. 0.001))
|> Scad.translate (v3 (outer_w /. -2.) (outer_h /. -2.) (dome_z -. base_thickness))
in
Scad.difference slab [ sensor_cutter ~z:(dome_z +. 0.01) (sensor_depth +. 0.01) ]
and pillars =
let cyl = Scad.extrude ~height:dome_thickness Bottom.ellipse in
Scad.(
union
[ translate (v3 Bottom.ellipse_x 0. 0.) cyl
; translate (v3 (Bottom.ellipse_x *. -1.) 0. 0.) cyl
]
|> translate (v3 0. 0. (bottom_z -. dome_thickness)))
in
let cutout =
let internals =
Scad.union [ Scad.translate (v3 0. 0. bottom_z) bottom_cut; dome_cut ]
in
match cap_cutout_height with
| Some h ->
Scad.union
[ Scad.ztrans
(2.5 +. h +. (thickness /. 2.))
(Scad.cube ~center:true (v3 20. 20. 7.))
; internals
]
| None -> internals
and clip hole = Scad.union [ base; hole; pillars ] in
Key.(
make
?render
?cap
~cutout
{ outer_w
; outer_h
; inner_w
; inner_h
; thickness
; clip
; cap_height
; clearance
; corner
; fn
})
let make_hole
?render
?cap
?outer_w
?outer_h
?inner_w
?inner_h
?thickness
?cap_height
?cap_cutout_height
?clearance
?corner
?fn
?dome_w
?dome_waist_clip
?dome_thickness
?base_thickness
?sensor_depth
?sensor_cutter
()
=
hole_of_config
?render
?cap
(Config.make
?outer_w
?outer_h
?inner_w
?inner_h
?thickness
?cap_height
?cap_cutout_height
?clearance
?corner
?fn
?dome_w
?dome_waist_clip
?dome_thickness
?base_thickness
?sensor_depth
?sensor_cutter
() )
let empty_hole_of_config
?render
?cap
Config.
{ outer_w
; outer_h
; inner_w
; inner_h
; thickness
; cap_height
; cap_cutout_height
; clearance
; corner
; fn
; _
}
=
Mx.make_hole
?render
?cap
~outer_w
~outer_h
~inner_w
~inner_h
~thickness
~cap_height
~cap_cutout_height
~clearance
?corner
?fn
()
let make_empty_hole
?render
?cap
?outer_w
?outer_h
?inner_w
?inner_h
?thickness
?cap_height
?cap_cutout_height
?clearance
?corner
?fn
()
=
empty_hole_of_config
?render
?cap
(Config.make
?outer_w
?outer_h
?inner_w
?inner_h
?thickness
?cap_height
?cap_cutout_height
?clearance
?corner
?fn
() )
| null | https://raw.githubusercontent.com/geoffder/dometyl-keyboard/1c11268ef4babe10a066ac83d6f488fa9ffad0ab/lib/niz.ml | ocaml | TODO: better magnet / sensor break down notes | open OCADml
open OSCADml
module Bottom = struct
let w = 17.5
let h = 17.5
let thickness = 4.
let bulge_thickness = 0.6
let bulge_length = 6.5
let bulge_height = 3.2
let ellipse_offset = -0.25
let ellipse_x = (w /. 2.) +. ellipse_offset
let ellipse_inset_x_rad = 1.6
let ellipse_inset_y_scale = 1.2
let corner_cut_rad = 3.
let corner_cut_off = 1.
let ellipse =
Scad.scale (v2 1. ellipse_inset_y_scale) (Scad.circle ~fn:32 ellipse_inset_x_rad)
let bulge = Scad.square ~center:true (v2 bulge_length (bulge_thickness +. 0.1))
let cutter = Scad.circle ~fn:64 corner_cut_rad
let corner x_sign y_sign =
let x = (w /. 2.) +. corner_cut_off
and y = (h /. 2.) +. corner_cut_off in
Scad.translate (v2 (x *. x_sign) (y *. y_sign)) cutter
let shadow =
Scad.union
[ Scad.difference
(Scad.square ~center:true (v2 w h))
[ Scad.translate (v2 ellipse_x 0.) ellipse
; Scad.translate (v2 (ellipse_x *. -1.) 0.) ellipse
; corner 1. 1.
; corner 1. (-1.)
; corner (-1.) 1.
; corner (-1.) (-1.)
]
; Scad.ytrans ((h /. 2.) +. (bulge_thickness /. 2.)) bulge
; Scad.ytrans ((h /. -2.) -. (bulge_thickness /. 2.) +. 0.001) bulge
; Scad.ytrans ((h /. 2.) +. (bulge_thickness /. 2.)) bulge
; Scad.ytrans ((h /. -2.) -. (bulge_thickness /. 2.) +. 0.001) bulge
]
let scad =
let bulges =
let b = Scad.extrude ~height:bulge_height bulge in
[ Scad.translate (v3 0. ((h /. 2.) -. 0.1) 0.) b
; Scad.translate (v3 0. ((h /. -2.) +. 0.1) 0.) b
]
in
Scad.difference
(Scad.square ~center:true (v2 w h))
[ Scad.xtrans ellipse_x ellipse
; Scad.xtrans (ellipse_x *. -1.) ellipse
; corner 1. 1.
; corner 1. (-1.)
; corner (-1.) 1.
; corner (-1.) (-1.)
]
|> Scad.extrude ~height:(thickness +. 0.001)
|> fun b -> Scad.union (b :: bulges)
end
module Config = struct
type t =
{ outer_w : float
; outer_h : float
; inner_w : float
; inner_h : float
; thickness : float
; cap_height : float
; cap_cutout_height : float option
; clearance : float
; corner : Path3.Round.corner option
; fn : int option
; dome_w : float
; dome_waist_clip : float
; dome_thickness : float
; base_thickness : float
; sensor_depth : float
; sensor_cutter : Sensor.cutter
}
let make
?(outer_w = 20.5)
?(outer_h = 20.5)
?(inner_w = 14.)
?(inner_h = 14.)
?(thickness = 5.6)
?(cap_height = 6.5)
?(cap_cutout_height = Some 1.5)
?(clearance = 4.)
?corner
?fn
?(dome_w = 19.5)
?(dome_waist_clip = 1.)
?(dome_thickness = 1.6)
?(base_thickness = 3.)
?(sensor_depth = 1.4)
?(sensor_cutter = Sensor.ThroughHole.tape_cutout ())
()
=
{ outer_w
; outer_h
; inner_w
; inner_h
; thickness
; cap_height
; cap_cutout_height
; clearance
; corner
; fn
; dome_w
; dome_waist_clip
; dome_thickness
; base_thickness
; sensor_depth
; sensor_cutter
}
let default = make ()
end
Dome thickness
- BKE ~= 0.85 mm
- DES ~= 0.70 mm
The actual value for [ dome_thickness ] though must account for FDM overhang
tolerance , thus it should be a good amount higher to ensure reliable fit .
Both and DES domes are roughly ~19x19 mm .
- BKE ~= 0.85mm
- DES ~= 0.70mm
The actual value for [dome_thickness] though must account for FDM overhang
tolerance, thus it should be a good amount higher to ensure reliable fit.
Both BKE and DES domes are roughly ~19x19mm. *)
Magnet size , with a sensor depth of 1.4 mm ( slightly below the thickness of a
standard through - hole sensor package ):
- 3x1 mm magnets actuate the AH3574 sensor at ~1.16 mm travel and are able to
deactivate by the top of the return with Niz rings
- 2x1 magnets actuate the AH3572 sensor at ~2.4 mm travel , deactivation
occurs by the top of the return with Niz rings .
- recommended : 2x1 magnet with sensor_depth = 1.4 . Easier to attach magnet
size , and should be no worries about hysteresis within FDM and gluing
tolerances with the stock Niz silencing rings . Thinner rings ( or no rings )
will increase the travel , so keep that in mind .
standard through-hole sensor package):
- 3x1mm magnets actuate the AH3574 sensor at ~1.16mm travel and are able to
deactivate by the top of the return with Niz rings
- 2x1 magnets actuate the AH3572 sensor at ~2.4mm travel, deactivation
occurs by the top of the return with Niz rings.
- recommended: 2x1 magnet with sensor_depth = 1.4. Easier to attach magnet
size, and should be no worries about hysteresis within FDM and gluing
tolerances with the stock Niz silencing rings. Thinner rings (or no rings)
will increase the travel, so keep that in mind. *)
let hole_of_config
?render
?cap
Config.
{ outer_w
; outer_h
; inner_w
; inner_h
; thickness
; cap_height
; cap_cutout_height
; clearance
; corner
; fn
; dome_w
; dome_waist_clip
; dome_thickness
; base_thickness
; sensor_depth
; sensor_cutter
}
=
let thickness = Float.max thickness (Bottom.thickness +. dome_thickness) in
let clearance = Float.max clearance (base_thickness +. 0.5)
and bottom_z = (thickness /. 2.) -. Bottom.thickness
and bottom_cut = Scad.extrude ~height:(Bottom.thickness *. 2.) Bottom.shadow in
let dome_z = bottom_z -. dome_thickness in
let dome_cut =
let waist_clip sign =
Scad.difference
Bottom.ellipse
[ Scad.square
~center:true
(v2
(dome_waist_clip *. 2.)
(Bottom.ellipse_inset_x_rad *. Bottom.ellipse_inset_y_scale *. 2.) )
|> Scad.translate (v2 (Bottom.ellipse_inset_x_rad *. -.sign) 0.)
]
|> Scad.translate (v2 (Bottom.ellipse_x *. sign) 0.)
in
Scad.difference
(Scad.square ~center:true (v2 dome_w dome_w))
[ waist_clip 1.; waist_clip (-1.) ]
|> Scad.extrude ~height:(dome_thickness +. 0.001)
|> Scad.translate (v3 0. 0. dome_z)
and base =
let slab =
Scad.cube (v3 outer_w outer_h (base_thickness +. 0.001))
|> Scad.translate (v3 (outer_w /. -2.) (outer_h /. -2.) (dome_z -. base_thickness))
in
Scad.difference slab [ sensor_cutter ~z:(dome_z +. 0.01) (sensor_depth +. 0.01) ]
and pillars =
let cyl = Scad.extrude ~height:dome_thickness Bottom.ellipse in
Scad.(
union
[ translate (v3 Bottom.ellipse_x 0. 0.) cyl
; translate (v3 (Bottom.ellipse_x *. -1.) 0. 0.) cyl
]
|> translate (v3 0. 0. (bottom_z -. dome_thickness)))
in
let cutout =
let internals =
Scad.union [ Scad.translate (v3 0. 0. bottom_z) bottom_cut; dome_cut ]
in
match cap_cutout_height with
| Some h ->
Scad.union
[ Scad.ztrans
(2.5 +. h +. (thickness /. 2.))
(Scad.cube ~center:true (v3 20. 20. 7.))
; internals
]
| None -> internals
and clip hole = Scad.union [ base; hole; pillars ] in
Key.(
make
?render
?cap
~cutout
{ outer_w
; outer_h
; inner_w
; inner_h
; thickness
; clip
; cap_height
; clearance
; corner
; fn
})
let make_hole
?render
?cap
?outer_w
?outer_h
?inner_w
?inner_h
?thickness
?cap_height
?cap_cutout_height
?clearance
?corner
?fn
?dome_w
?dome_waist_clip
?dome_thickness
?base_thickness
?sensor_depth
?sensor_cutter
()
=
hole_of_config
?render
?cap
(Config.make
?outer_w
?outer_h
?inner_w
?inner_h
?thickness
?cap_height
?cap_cutout_height
?clearance
?corner
?fn
?dome_w
?dome_waist_clip
?dome_thickness
?base_thickness
?sensor_depth
?sensor_cutter
() )
let empty_hole_of_config
?render
?cap
Config.
{ outer_w
; outer_h
; inner_w
; inner_h
; thickness
; cap_height
; cap_cutout_height
; clearance
; corner
; fn
; _
}
=
Mx.make_hole
?render
?cap
~outer_w
~outer_h
~inner_w
~inner_h
~thickness
~cap_height
~cap_cutout_height
~clearance
?corner
?fn
()
let make_empty_hole
?render
?cap
?outer_w
?outer_h
?inner_w
?inner_h
?thickness
?cap_height
?cap_cutout_height
?clearance
?corner
?fn
()
=
empty_hole_of_config
?render
?cap
(Config.make
?outer_w
?outer_h
?inner_w
?inner_h
?thickness
?cap_height
?cap_cutout_height
?clearance
?corner
?fn
() )
|
fa31e8f45a9e8733dc4589d2233d41c1f07d4fb258ebde86311286d91848eed2 | heroku/clojure-getting-started | web_test.clj | (ns clojure-getting-started.web-test
(:require [clojure.test :refer :all]
[clojure-getting-started.web :refer :all]))
(deftest first-test
(is false "Tests should be written"))
| null | https://raw.githubusercontent.com/heroku/clojure-getting-started/66b7456a4f2a42cbf4b9851283a9dc61b86af3e8/test/clojure_getting_started/web_test.clj | clojure | (ns clojure-getting-started.web-test
(:require [clojure.test :refer :all]
[clojure-getting-started.web :refer :all]))
(deftest first-test
(is false "Tests should be written"))
|
|
cf4d49bfb9149f73e7d9e4ec72391b4bb5202cc6d542cb5c9beae15ef5d77b3b | serioga/webapp-clojure-2020 | static_args.cljc | (ns app.rum.mixin.static-args)
#?(:clj (set! *warn-on-reflection* true)
:cljs (set! *warn-on-infer* true))
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
(defn static-args-mixin
"Avoid re-render if specific component’s arguments have not changed."
[get-arg]
{:should-update
(fn [old-state new-state]
(not= (get-arg (:rum/args old-state))
(get-arg (:rum/args new-state))))})
(def static-first-arg-mixin
"Avoid re-render if first component’s arguments have not changed."
(static-args-mixin first))
(def static-second-arg-mixin
"Avoid re-render if second component’s arguments have not changed."
(static-args-mixin second))
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
| null | https://raw.githubusercontent.com/serioga/webapp-clojure-2020/91a7170a1be287bbfa5b9279d697208f7f806f9b/src/app/rum/mixin/static_args.cljc | clojure | (ns app.rum.mixin.static-args)
#?(:clj (set! *warn-on-reflection* true)
:cljs (set! *warn-on-infer* true))
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
(defn static-args-mixin
"Avoid re-render if specific component’s arguments have not changed."
[get-arg]
{:should-update
(fn [old-state new-state]
(not= (get-arg (:rum/args old-state))
(get-arg (:rum/args new-state))))})
(def static-first-arg-mixin
"Avoid re-render if first component’s arguments have not changed."
(static-args-mixin first))
(def static-second-arg-mixin
"Avoid re-render if second component’s arguments have not changed."
(static-args-mixin second))
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
|
|
7f368bfe95dcd02d09a6950c78f4abc4737c34755081791dc0d16848bdd8a3b3 | hslua/tasty-lua | Translate.hs | |
Module : Test . Tasty . Lua . Translate
Copyright : © 2019–2020 : MIT
Maintainer : >
Stability : alpha
Portability : Requires GHC
Translate test results from Lua into a Tasty @'TestTree'@.
Module : Test.Tasty.Lua.Translate
Copyright : © 2019–2020 Albert Krewinkel
License : MIT
Maintainer : Albert Krewinkel <albert+>
Stability : alpha
Portability : Requires GHC
Translate test results from Lua into a Tasty @'TestTree'@.
-}
module Test.Tasty.Lua.Translate
( translateResultsFromFile
, pathFailure
)
where
import Foreign.Lua (Lua)
import Test.Tasty.Lua.Core (Outcome (..), ResultTree (..), UnnamedTree (..),
runTastyFile)
import qualified Test.Tasty as Tasty
import qualified Test.Tasty.Providers as Tasty
-- | Run tasty.lua tests from the given file and translate the result
-- into a mock Tasty @'TestTree'@.
translateResultsFromFile :: FilePath -> Lua Tasty.TestTree
translateResultsFromFile fp = do
result <- runTastyFile fp
case result of
Left errMsg -> return $ pathFailure fp errMsg
Right tree -> return $ Tasty.testGroup fp (map testTree tree)
-- | Report failure of testing a path.
pathFailure :: FilePath -> String -> Tasty.TestTree
pathFailure fp errMsg = Tasty.singleTest fp (MockTest (Failure errMsg))
-- | Convert internal (tasty.lua) result tree format into Tasty tree.
testTree :: ResultTree -> Tasty.TestTree
testTree (ResultTree name tree) =
case tree of
SingleTest outcome -> Tasty.singleTest name (MockTest outcome)
TestGroup results -> Tasty.testGroup name (map testTree results)
-- | Mock test which just returns the predetermined outcome. An
-- @'Outcome'@ can be treated like a Tasty test, as it encodes all
necessary information . Usually , calling @'run'@ would trigger the
-- execution of the test, but in this case, the test has already been
run when the Lua script was executed .
newtype MockTest = MockTest Outcome
instance Tasty.IsTest MockTest where
run _ (MockTest outcome) _ = return $ case outcome of
Success -> Tasty.testPassed ""
Failure msg -> Tasty.testFailed msg
testOptions = return []
| null | https://raw.githubusercontent.com/hslua/tasty-lua/8105036277e737227f18c475dc3e24cd7924b53a/src/Test/Tasty/Lua/Translate.hs | haskell | | Run tasty.lua tests from the given file and translate the result
into a mock Tasty @'TestTree'@.
| Report failure of testing a path.
| Convert internal (tasty.lua) result tree format into Tasty tree.
| Mock test which just returns the predetermined outcome. An
@'Outcome'@ can be treated like a Tasty test, as it encodes all
execution of the test, but in this case, the test has already been | |
Module : Test . Tasty . Lua . Translate
Copyright : © 2019–2020 : MIT
Maintainer : >
Stability : alpha
Portability : Requires GHC
Translate test results from Lua into a Tasty @'TestTree'@.
Module : Test.Tasty.Lua.Translate
Copyright : © 2019–2020 Albert Krewinkel
License : MIT
Maintainer : Albert Krewinkel <albert+>
Stability : alpha
Portability : Requires GHC
Translate test results from Lua into a Tasty @'TestTree'@.
-}
module Test.Tasty.Lua.Translate
( translateResultsFromFile
, pathFailure
)
where
import Foreign.Lua (Lua)
import Test.Tasty.Lua.Core (Outcome (..), ResultTree (..), UnnamedTree (..),
runTastyFile)
import qualified Test.Tasty as Tasty
import qualified Test.Tasty.Providers as Tasty
translateResultsFromFile :: FilePath -> Lua Tasty.TestTree
translateResultsFromFile fp = do
result <- runTastyFile fp
case result of
Left errMsg -> return $ pathFailure fp errMsg
Right tree -> return $ Tasty.testGroup fp (map testTree tree)
pathFailure :: FilePath -> String -> Tasty.TestTree
pathFailure fp errMsg = Tasty.singleTest fp (MockTest (Failure errMsg))
testTree :: ResultTree -> Tasty.TestTree
testTree (ResultTree name tree) =
case tree of
SingleTest outcome -> Tasty.singleTest name (MockTest outcome)
TestGroup results -> Tasty.testGroup name (map testTree results)
necessary information . Usually , calling @'run'@ would trigger the
run when the Lua script was executed .
newtype MockTest = MockTest Outcome
instance Tasty.IsTest MockTest where
run _ (MockTest outcome) _ = return $ case outcome of
Success -> Tasty.testPassed ""
Failure msg -> Tasty.testFailed msg
testOptions = return []
|
fe531ef2ba59dd93936e8cf823e6c8d5514656dcb8d3df3592d91b6d84a2532b | CloudI/CloudI | cloudi_service_name.erl | -*-Mode : erlang;coding : utf-8;tab - width:4;c - basic - offset:4;indent - tabs - mode:()-*-
ex : set utf-8 sts=4 ts=4 sw=4 et nomod :
%%%
%%%------------------------------------------------------------------------
%%% @doc
%%% ==CloudI Service Name Creation and Parsing==
%%% @end
%%%
MIT License
%%%
Copyright ( c ) 2014 - 2021 < mjtruog at protonmail dot com >
%%%
%%% Permission is hereby granted, free of charge, to any person obtaining a
%%% copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction , including without limitation
%%% the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software , and to permit persons to whom the
%%% Software is furnished to do so, subject to the following conditions:
%%%
%%% The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software .
%%%
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
%%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
%%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
%%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
%%% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
%%% DEALINGS IN THE SOFTWARE.
%%%
@author < mjtruog at protonmail dot com >
2014 - 2021
%%% @version 2.0.3 {@date} {@time}
%%%------------------------------------------------------------------------
-module(cloudi_service_name).
-author('mjtruog at protonmail dot com').
%% external interface
-export([new/2,
new/4,
parse/2,
parse_with_suffix/2,
pattern/1,
suffix/2,
utf8/1,
utf8_forced/1]).
%%%------------------------------------------------------------------------
%%% External interface functions
%%%------------------------------------------------------------------------
%%-------------------------------------------------------------------------
%% @doc
%% ===Transform a service name pattern with parameters into an exact service name.===
%% The pattern input can contain consecutive * wildcard characters because
%% they are only used for a template.
%% @end
%%-------------------------------------------------------------------------
-spec new(Pattern :: cloudi:bytestring(),
Parameters :: list(cloudi:bytestring())) ->
{ok, cloudi:bytestring()} |
{error, parameters_ignored | parameter_missing}.
new(Pattern, Parameters) ->
cloudi_x_trie:pattern2_fill(Pattern, Parameters).
%%-------------------------------------------------------------------------
%% @doc
%% ===Transform a service name pattern with parameters into an exact service name.===
%% The pattern input can contain consecutive * wildcard characters because
%% they are only used for a template.
%% @end
%%-------------------------------------------------------------------------
-spec new(Pattern :: cloudi:bytestring(),
Parameters :: list(cloudi:bytestring()),
ParametersSelected :: list(pos_integer()),
ParametersStrictMatching :: boolean()) ->
{ok, cloudi:bytestring()} |
{error,
parameters_ignored | parameter_missing | parameters_selected_empty |
{parameters_selected_ignored, list(pos_integer())} |
{parameters_selected_missing, pos_integer()}}.
new(Pattern, Parameters, ParametersSelected, ParametersStrictMatching) ->
cloudi_x_trie:pattern2_fill(Pattern, Parameters,
ParametersSelected, ParametersStrictMatching).
%%-------------------------------------------------------------------------
%% @doc
%% ===Parse a service name pattern to return parameters.===
%% @end
%%-------------------------------------------------------------------------
-spec parse(Name :: cloudi:bytestring(),
Pattern :: cloudi:bytestring()) ->
list(cloudi:nonempty_bytestring()) | error.
parse(Name, Pattern) ->
cloudi_x_trie:pattern2_parse(Pattern, Name).
%%-------------------------------------------------------------------------
%% @doc
= = = Parse a service name pattern and return the common suffix.===
%% @end
%%-------------------------------------------------------------------------
-spec parse_with_suffix(Name :: cloudi:bytestring(),
Pattern :: cloudi:bytestring()) ->
{list(cloudi:nonempty_bytestring()), cloudi:bytestring()} | error.
parse_with_suffix(Name, Pattern) ->
cloudi_x_trie:pattern2_parse(Pattern, Name, with_suffix).
%%-------------------------------------------------------------------------
%% @doc
%% ===Determine if a service name pattern contains wildcard characters.===
%% If not, the service name pattern would only be used with a service name
%% that is an exact match.
%% @end
%%-------------------------------------------------------------------------
-spec pattern(Pattern :: cloudi:bytestring()) ->
boolean().
pattern(Pattern) ->
cloudi_x_trie:is_pattern2_bytes(Pattern).
%%-------------------------------------------------------------------------
%% @doc
%% ===Provide the suffix of the service name or service pattern based on the service's configured prefix.===
%% @end
%%-------------------------------------------------------------------------
-spec suffix(Prefix :: cloudi:nonempty_bytestring(),
NameOrPattern :: cloudi:nonempty_bytestring()) ->
cloudi:bytestring().
suffix([PrefixC | _] = Prefix, [NameOrPatternC | _] = NameOrPattern)
when is_integer(PrefixC), is_integer(NameOrPatternC) ->
case cloudi_x_trie:is_pattern2_bytes(NameOrPattern) of
true ->
% handle as a pattern
suffix_pattern_parse(Prefix, NameOrPattern);
false ->
% handle as a name
case cloudi_x_trie:pattern2_suffix(Prefix, NameOrPattern) of
error ->
erlang:exit(badarg);
Suffix ->
Suffix
end
end;
suffix(_, _) ->
erlang:exit(badarg).
%%-------------------------------------------------------------------------
%% @doc
%% ===Convert the service name or service pattern type for interpretation as UTF8.===
%% Used for io formatting with ~ts.
%% @end
%%-------------------------------------------------------------------------
-spec utf8(NameOrPattern :: cloudi:nonempty_bytestring()) ->
<<_:_*8>>.
utf8([_ | _] = NameOrPattern) ->
erlang:list_to_binary(NameOrPattern).
%%-------------------------------------------------------------------------
%% @doc
%% ===Force conversion of the service name or service pattern type for interpretation as UTF8.===
%% Used for io formatting with ~ts.
%% @end
%%-------------------------------------------------------------------------
-spec utf8_forced(NameOrPattern :: cloudi:nonempty_bytestring()) ->
<<_:_*8>>.
utf8_forced([_ | _] = NameOrPattern) ->
try erlang:list_to_binary(NameOrPattern)
catch
error:badarg ->
cloudi_string:term_to_binary({invalid_utf8, NameOrPattern})
end.
%%%------------------------------------------------------------------------
%%% Private functions
%%%------------------------------------------------------------------------
suffix_pattern_parse([], Pattern) ->
Pattern;
suffix_pattern_parse([C | Prefix], [C | Pattern]) ->
suffix_pattern_parse(Prefix, Pattern);
suffix_pattern_parse([_ | _], _) ->
erlang:exit(badarg).
| null | https://raw.githubusercontent.com/CloudI/CloudI/28ccf4c7c3426d41c123fbf2a3e59d98cc91ddbf/src/lib/cloudi_core/src/cloudi_service_name.erl | erlang |
------------------------------------------------------------------------
@doc
==CloudI Service Name Creation and Parsing==
@end
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
@version 2.0.3 {@date} {@time}
------------------------------------------------------------------------
external interface
------------------------------------------------------------------------
External interface functions
------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
===Transform a service name pattern with parameters into an exact service name.===
The pattern input can contain consecutive * wildcard characters because
they are only used for a template.
@end
-------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
===Transform a service name pattern with parameters into an exact service name.===
The pattern input can contain consecutive * wildcard characters because
they are only used for a template.
@end
-------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
===Parse a service name pattern to return parameters.===
@end
-------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
===Determine if a service name pattern contains wildcard characters.===
If not, the service name pattern would only be used with a service name
that is an exact match.
@end
-------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
===Provide the suffix of the service name or service pattern based on the service's configured prefix.===
@end
-------------------------------------------------------------------------
handle as a pattern
handle as a name
-------------------------------------------------------------------------
@doc
===Convert the service name or service pattern type for interpretation as UTF8.===
Used for io formatting with ~ts.
@end
-------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
===Force conversion of the service name or service pattern type for interpretation as UTF8.===
Used for io formatting with ~ts.
@end
-------------------------------------------------------------------------
------------------------------------------------------------------------
Private functions
------------------------------------------------------------------------ | -*-Mode : erlang;coding : utf-8;tab - width:4;c - basic - offset:4;indent - tabs - mode:()-*-
ex : set utf-8 sts=4 ts=4 sw=4 et nomod :
MIT License
Copyright ( c ) 2014 - 2021 < mjtruog at protonmail dot com >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
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
@author < mjtruog at protonmail dot com >
2014 - 2021
-module(cloudi_service_name).
-author('mjtruog at protonmail dot com').
-export([new/2,
new/4,
parse/2,
parse_with_suffix/2,
pattern/1,
suffix/2,
utf8/1,
utf8_forced/1]).
-spec new(Pattern :: cloudi:bytestring(),
Parameters :: list(cloudi:bytestring())) ->
{ok, cloudi:bytestring()} |
{error, parameters_ignored | parameter_missing}.
new(Pattern, Parameters) ->
cloudi_x_trie:pattern2_fill(Pattern, Parameters).
-spec new(Pattern :: cloudi:bytestring(),
Parameters :: list(cloudi:bytestring()),
ParametersSelected :: list(pos_integer()),
ParametersStrictMatching :: boolean()) ->
{ok, cloudi:bytestring()} |
{error,
parameters_ignored | parameter_missing | parameters_selected_empty |
{parameters_selected_ignored, list(pos_integer())} |
{parameters_selected_missing, pos_integer()}}.
new(Pattern, Parameters, ParametersSelected, ParametersStrictMatching) ->
cloudi_x_trie:pattern2_fill(Pattern, Parameters,
ParametersSelected, ParametersStrictMatching).
-spec parse(Name :: cloudi:bytestring(),
Pattern :: cloudi:bytestring()) ->
list(cloudi:nonempty_bytestring()) | error.
parse(Name, Pattern) ->
cloudi_x_trie:pattern2_parse(Pattern, Name).
= = = Parse a service name pattern and return the common suffix.===
-spec parse_with_suffix(Name :: cloudi:bytestring(),
Pattern :: cloudi:bytestring()) ->
{list(cloudi:nonempty_bytestring()), cloudi:bytestring()} | error.
parse_with_suffix(Name, Pattern) ->
cloudi_x_trie:pattern2_parse(Pattern, Name, with_suffix).
-spec pattern(Pattern :: cloudi:bytestring()) ->
boolean().
pattern(Pattern) ->
cloudi_x_trie:is_pattern2_bytes(Pattern).
-spec suffix(Prefix :: cloudi:nonempty_bytestring(),
NameOrPattern :: cloudi:nonempty_bytestring()) ->
cloudi:bytestring().
suffix([PrefixC | _] = Prefix, [NameOrPatternC | _] = NameOrPattern)
when is_integer(PrefixC), is_integer(NameOrPatternC) ->
case cloudi_x_trie:is_pattern2_bytes(NameOrPattern) of
true ->
suffix_pattern_parse(Prefix, NameOrPattern);
false ->
case cloudi_x_trie:pattern2_suffix(Prefix, NameOrPattern) of
error ->
erlang:exit(badarg);
Suffix ->
Suffix
end
end;
suffix(_, _) ->
erlang:exit(badarg).
-spec utf8(NameOrPattern :: cloudi:nonempty_bytestring()) ->
<<_:_*8>>.
utf8([_ | _] = NameOrPattern) ->
erlang:list_to_binary(NameOrPattern).
-spec utf8_forced(NameOrPattern :: cloudi:nonempty_bytestring()) ->
<<_:_*8>>.
utf8_forced([_ | _] = NameOrPattern) ->
try erlang:list_to_binary(NameOrPattern)
catch
error:badarg ->
cloudi_string:term_to_binary({invalid_utf8, NameOrPattern})
end.
suffix_pattern_parse([], Pattern) ->
Pattern;
suffix_pattern_parse([C | Prefix], [C | Pattern]) ->
suffix_pattern_parse(Prefix, Pattern);
suffix_pattern_parse([_ | _], _) ->
erlang:exit(badarg).
|
7009e792274b0021b20e35c93a785bb3587fcedb921fc1979e293b15cb486fbc | kunstmusik/pink | node.clj | (ns pink.node
"Nodes aggregate audio from other audio-rate functions. Nodes can contain other nodes. Each Node is wrapped in pink.util.shared so that the output of Node may be used by multiple other audio-functions within the same time period.
In general, users will first call create-node to create a node map. node-processor will be used as the audio-rate function to add to an Engine, Node, or other audio-function.
"
(:require [pink.config :refer [*nchnls* *buffer-size*]]
[pink.event :refer :all]
[pink.util :refer :all]
[pink.dynamics :refer [db->amp]])
(:import [pink.event Event]
[pink.node MessageBuffer Message IFnList]
[clojure.lang IFn]
[java.util ArrayList]
))
;; Ensure unchecked math used for this namespace
(set! *unchecked-math* :warn-on-boxed)
(defprotocol Node
(node-add-func
[n func]
"Add function to pending adds list")
(node-remove-func
[n func]
"Add func to pending removes list")
(node-clear
[n]
"Clear out all active and pending funcs")
(node-empty?
[n]
"Checks whether active and pending add lists are empty")
(node-state
[n]
"Returns state map for Node"))
(defprotocol GainNode
(set-gain! [n gain-val] "Set gain [0,1] to apply to signal")
(get-gain [n] "Get gain value.")
)
(defprotocol StereoMixerNode
(set-pan! [n pan-val] "Set pan [-1,1] to apply to signal")
(get-pan [n] "Get pan value."))
NODE
(defn- create-node-state
([channels] (create-node-state channels 512))
([channels max-messages]
{:funcs (IFnList.)
:messages (MessageBuffer. max-messages)
:channels channels
}))
(defn create-node
[& { :keys [channels max-messages]
:or {channels *nchnls*
max-messages 512 }}]
(let [state (create-node-state channels max-messages)
^MessageBuffer mbuf (:messages state)
^IFnList node-funcs (:funcs state)]
(reify
Node
(node-add-func [this func]
(.postMessage mbuf :add func))
(node-remove-func [this func]
(.postMessage mbuf :remove func))
(node-clear [this]
(.postMessage mbuf :clear nil))
(node-empty? [this]
(and (.isEmpty mbuf)
(.isEmpty node-funcs)))
(node-state [this] state)
)))
(defn- process-messages!
[^IFnList node-funcs ^MessageBuffer mbuf]
(let [start (.getReadStart mbuf)
end (.getReadEnd mbuf)
capacity (.getCapacity mbuf)
adj-end (long (if (< end start) (+ end capacity) end))
^ArrayList active-funcs (.getActiveList node-funcs) ]
(when (< start adj-end)
(loop [indx start]
(if (< indx adj-end)
(let [^Message msg (.getMessage mbuf (rem indx capacity))
msgType (.getMsgType msg)
msgMsg (.getMsg msg)]
(.reset msg)
(case msgType
:add
(.add active-funcs msgMsg)
:remove
(.remove active-funcs msgMsg)
:clear
(.clear active-funcs)
(println "Error: Unknown msgType found for node: " msgType))
(recur (inc indx)))
(.setReadStart mbuf end))))))
(defn run-afuncs!
[^IFnList afs buffer]
(let [^ArrayList active-funcs (.getActiveList afs)
size (.size active-funcs)]
(when (> size 0)
(loop [i 0]
(when (< i size)
(let [^IFn x (.get active-funcs i)
b (try-func x)]
(when b
(mix-buffers b buffer)
(.putBack afs x)))
(recur (+ 1 i))))
(.swap afs)
)))
(defn- run-cfuncs!
[^IFnList cfuncs]
(let [^ArrayList active-funcs (.getActiveList cfuncs)
size (.size active-funcs)]
(when (> size 0)
(loop [i 0]
(when (< i size)
(let [^IFn x (.get active-funcs i)]
(when (try-func x)
(.putBack cfuncs x)))
(recur (+ 1 i))))
(.swap cfuncs))))
; currently will continue rendering even if afs are empty. need to have
; option to return nil when afs are empty, for the scenario of disk render.
; should add a *disk-render* flag to config and a default option here
; so that user can override behavior.
(defn node-processor
"An audio-rate function that renders child funcs and returns the
signals in an out-buffer."
[node]
(let [state (node-state node)
out-buffer (create-buffers (:channels state))
^MessageBuffer mbuf (:messages state)
^IFnList node-afuncs (:funcs state)
status (:status state)]
(fn []
(clear-buffer out-buffer)
(process-messages! node-afuncs mbuf)
(run-afuncs! node-afuncs out-buffer)
out-buffer)))
(defn control-node-processor
"Creates a control node processing functions that runs controls functions,
handling pending adds and removes, as well as filters out done functions."
[node]
(let [state (node-state node)
^IFnList node-funcs (:funcs state)
^MessageBuffer mbuf (:messages state)]
(fn []
(process-messages! node-funcs mbuf)
(run-cfuncs! node-funcs))))
(defn control-node
"Creates a Node that also adheres to control function convention (0-arity IFn that
returns true or nil)."
([& { :keys [channels max-messages]
:or {channels *nchnls*
max-messages 512} }]
(let [state (create-node-state *nchnls* max-messages)
^IFnList node-funcs (:funcs state)
^MessageBuffer mbuf (:messages state)]
(reify
Node
(node-add-func [this func]
(.postMessage mbuf :add func))
(node-remove-func [this func]
(.postMessage mbuf :remove func))
(node-clear [this]
(.postMessage mbuf :clear nil))
(node-empty? [this]
(and (.isEmpty mbuf)
(.isEmpty node-funcs)))
(node-state [this] state)
clojure.lang.IFn
(invoke [this]
(process-messages! node-funcs mbuf)
(run-cfuncs! node-funcs))))))
(defn audio-node
"Creates a Node that also adheres to audio function convention (0-arity IFn that
returns audio buffer or nil)."
[& { :keys [channels max-messages]
:or {channels *nchnls*
max-messages 512} }]
(let [state (create-node-state channels)
out-buffer (create-buffers (:channels state))
^MessageBuffer mbuf (:messages state)
^IFnList node-funcs (:funcs state)]
(reify
Node
(node-add-func [this func]
(.postMessage mbuf :add func))
(node-remove-func [this func]
(.postMessage mbuf :remove func))
(node-clear [this]
(.postMessage mbuf :clear nil))
(node-empty? [this]
(and (.isEmpty mbuf)
(.isEmpty node-funcs)))
(node-state [this] state)
clojure.lang.IFn
(invoke [this]
(clear-buffer out-buffer)
(process-messages! node-funcs mbuf)
(run-afuncs! node-funcs out-buffer)
out-buffer))))
(defn mixer-node
"Creates an audio node that accepts mono-signal audio functions. mixer-node
has properties for gain and panning which will be applied to all generated signals.
Output is a stereo signal."
[& { :keys [ max-messages]
:or {max-messages 512} }]
(let [state (create-node-state 1 max-messages)
mono-buffer (create-buffer)
^doubles left (create-buffer)
^doubles right (create-buffer)
out-buffer (into-array [left right])
^MessageBuffer mbuf (:messages state)
^IFnList node-funcs (:funcs state)
^doubles pan (double-array 1 0.0)
^doubles gain (double-array 1 1.0)
PI2 (/ Math/PI 2)]
(reify
Node
(node-add-func [this func]
(.postMessage mbuf :add func))
(node-remove-func [this func]
(.postMessage mbuf :remove func))
(node-clear [this]
(.postMessage mbuf :clear nil))
(node-empty? [this]
(and (.isEmpty mbuf)
(.isEmpty node-funcs)))
(node-state [this] state)
GainNode
(set-gain! [this gain-val]
(aset gain 0 (double gain-val))
nil)
(get-gain [this]
(aget gain 0))
StereoMixerNode
(set-pan! [this pan-val]
(aset pan 0 (double pan-val))
nil)
(get-pan [this]
(aget pan 0))
clojure.lang.IFn
(invoke [this]
(clear-buffer mono-buffer)
(process-messages! node-funcs mbuf)
(run-afuncs! node-funcs mono-buffer)
(let [ksmps (long *buffer-size*)
g (aget gain 0)
p (aget pan 0)
new-loc-v (+ 0.5 (* 0.5 p))
new-l (db->amp (* 20 (Math/log (Math/cos (* PI2 new-loc-v )))))
new-r (db->amp (* 20 (Math/log (Math/sin (* PI2 new-loc-v )))))]
(loop [indx 0]
(when (< indx ksmps)
(let [samp (* g (aget mono-buffer indx))]
(aset left indx (* new-l samp))
(aset right indx (* new-r samp))
(recur (+ indx 1))))))
out-buffer))))
(defn gain-node
"Creates an audio node that accepts stereo-signal audio functions. gain-node
sums the generated signals from the audio functions, multiplies by gain, and
outputs the stereo-signal output."
[& { :keys [channels max-messages]
:or {channels *nchnls*
max-messages 512} }]
(let [state (create-node-state 2 max-messages)
^doubles left (create-buffer)
^doubles right (create-buffer)
out-buffer (into-array [left right])
^IFnList node-funcs (:funcs state)
^MessageBuffer mbuf (:messages state)
^doubles gain (double-array 1 1.0)]
(reify
Node
(node-add-func [this func]
(.postMessage mbuf :add func))
(node-remove-func [this func]
(.postMessage mbuf :remove func))
(node-clear [this]
(.postMessage mbuf :clear nil))
(node-empty? [this]
(and (.isEmpty mbuf)
(.isEmpty node-funcs)))
(node-state [this] state)
GainNode
(set-gain! [this gain-val]
(aset gain 0 (double gain-val))
nil)
(get-gain [this]
(aget gain 0))
clojure.lang.IFn
(invoke [this]
(clear-buffer out-buffer)
(process-messages! node-funcs mbuf)
(run-afuncs! node-funcs out-buffer)
(let [ksmps (long *buffer-size*)
g (aget gain 0)]
(loop [indx 0]
(loop [indx 0]
(when (< indx ksmps)
(aset left indx (* g (aget left indx)))
(aset right indx (* g (aget right indx)))
(recur (+ indx 1))))))
out-buffer))))
;; Event functions dealing with nodes
(defn fire-node-event
"create an instance of an audio function and adds to the node"
[node evt]
(when-let [afunc (fire-event evt)]
(node-add-func node afunc)))
(defn wrap-node-event [node ^Event evt]
(wrap-event fire-node-event [node] evt))
(defn node-events
"Takes a node and series of events, wrapping the events as node-events.
If single arg given, assumes it is a list of events."
([node args]
(if (sequential? args)
(map #(wrap-node-event node %) args)
(map #(wrap-node-event node %) [args])))
([node x & args]
(node-events node (list* x args))))
| null | https://raw.githubusercontent.com/kunstmusik/pink/7d37764b6a036a68a4619c93546fa3887f9951a7/src/main/pink/node.clj | clojure | Ensure unchecked math used for this namespace
currently will continue rendering even if afs are empty. need to have
option to return nil when afs are empty, for the scenario of disk render.
should add a *disk-render* flag to config and a default option here
so that user can override behavior.
Event functions dealing with nodes | (ns pink.node
"Nodes aggregate audio from other audio-rate functions. Nodes can contain other nodes. Each Node is wrapped in pink.util.shared so that the output of Node may be used by multiple other audio-functions within the same time period.
In general, users will first call create-node to create a node map. node-processor will be used as the audio-rate function to add to an Engine, Node, or other audio-function.
"
(:require [pink.config :refer [*nchnls* *buffer-size*]]
[pink.event :refer :all]
[pink.util :refer :all]
[pink.dynamics :refer [db->amp]])
(:import [pink.event Event]
[pink.node MessageBuffer Message IFnList]
[clojure.lang IFn]
[java.util ArrayList]
))
(set! *unchecked-math* :warn-on-boxed)
(defprotocol Node
(node-add-func
[n func]
"Add function to pending adds list")
(node-remove-func
[n func]
"Add func to pending removes list")
(node-clear
[n]
"Clear out all active and pending funcs")
(node-empty?
[n]
"Checks whether active and pending add lists are empty")
(node-state
[n]
"Returns state map for Node"))
(defprotocol GainNode
(set-gain! [n gain-val] "Set gain [0,1] to apply to signal")
(get-gain [n] "Get gain value.")
)
(defprotocol StereoMixerNode
(set-pan! [n pan-val] "Set pan [-1,1] to apply to signal")
(get-pan [n] "Get pan value."))
NODE
(defn- create-node-state
([channels] (create-node-state channels 512))
([channels max-messages]
{:funcs (IFnList.)
:messages (MessageBuffer. max-messages)
:channels channels
}))
(defn create-node
[& { :keys [channels max-messages]
:or {channels *nchnls*
max-messages 512 }}]
(let [state (create-node-state channels max-messages)
^MessageBuffer mbuf (:messages state)
^IFnList node-funcs (:funcs state)]
(reify
Node
(node-add-func [this func]
(.postMessage mbuf :add func))
(node-remove-func [this func]
(.postMessage mbuf :remove func))
(node-clear [this]
(.postMessage mbuf :clear nil))
(node-empty? [this]
(and (.isEmpty mbuf)
(.isEmpty node-funcs)))
(node-state [this] state)
)))
(defn- process-messages!
[^IFnList node-funcs ^MessageBuffer mbuf]
(let [start (.getReadStart mbuf)
end (.getReadEnd mbuf)
capacity (.getCapacity mbuf)
adj-end (long (if (< end start) (+ end capacity) end))
^ArrayList active-funcs (.getActiveList node-funcs) ]
(when (< start adj-end)
(loop [indx start]
(if (< indx adj-end)
(let [^Message msg (.getMessage mbuf (rem indx capacity))
msgType (.getMsgType msg)
msgMsg (.getMsg msg)]
(.reset msg)
(case msgType
:add
(.add active-funcs msgMsg)
:remove
(.remove active-funcs msgMsg)
:clear
(.clear active-funcs)
(println "Error: Unknown msgType found for node: " msgType))
(recur (inc indx)))
(.setReadStart mbuf end))))))
(defn run-afuncs!
[^IFnList afs buffer]
(let [^ArrayList active-funcs (.getActiveList afs)
size (.size active-funcs)]
(when (> size 0)
(loop [i 0]
(when (< i size)
(let [^IFn x (.get active-funcs i)
b (try-func x)]
(when b
(mix-buffers b buffer)
(.putBack afs x)))
(recur (+ 1 i))))
(.swap afs)
)))
(defn- run-cfuncs!
[^IFnList cfuncs]
(let [^ArrayList active-funcs (.getActiveList cfuncs)
size (.size active-funcs)]
(when (> size 0)
(loop [i 0]
(when (< i size)
(let [^IFn x (.get active-funcs i)]
(when (try-func x)
(.putBack cfuncs x)))
(recur (+ 1 i))))
(.swap cfuncs))))
(defn node-processor
"An audio-rate function that renders child funcs and returns the
signals in an out-buffer."
[node]
(let [state (node-state node)
out-buffer (create-buffers (:channels state))
^MessageBuffer mbuf (:messages state)
^IFnList node-afuncs (:funcs state)
status (:status state)]
(fn []
(clear-buffer out-buffer)
(process-messages! node-afuncs mbuf)
(run-afuncs! node-afuncs out-buffer)
out-buffer)))
(defn control-node-processor
"Creates a control node processing functions that runs controls functions,
handling pending adds and removes, as well as filters out done functions."
[node]
(let [state (node-state node)
^IFnList node-funcs (:funcs state)
^MessageBuffer mbuf (:messages state)]
(fn []
(process-messages! node-funcs mbuf)
(run-cfuncs! node-funcs))))
(defn control-node
"Creates a Node that also adheres to control function convention (0-arity IFn that
returns true or nil)."
([& { :keys [channels max-messages]
:or {channels *nchnls*
max-messages 512} }]
(let [state (create-node-state *nchnls* max-messages)
^IFnList node-funcs (:funcs state)
^MessageBuffer mbuf (:messages state)]
(reify
Node
(node-add-func [this func]
(.postMessage mbuf :add func))
(node-remove-func [this func]
(.postMessage mbuf :remove func))
(node-clear [this]
(.postMessage mbuf :clear nil))
(node-empty? [this]
(and (.isEmpty mbuf)
(.isEmpty node-funcs)))
(node-state [this] state)
clojure.lang.IFn
(invoke [this]
(process-messages! node-funcs mbuf)
(run-cfuncs! node-funcs))))))
(defn audio-node
"Creates a Node that also adheres to audio function convention (0-arity IFn that
returns audio buffer or nil)."
[& { :keys [channels max-messages]
:or {channels *nchnls*
max-messages 512} }]
(let [state (create-node-state channels)
out-buffer (create-buffers (:channels state))
^MessageBuffer mbuf (:messages state)
^IFnList node-funcs (:funcs state)]
(reify
Node
(node-add-func [this func]
(.postMessage mbuf :add func))
(node-remove-func [this func]
(.postMessage mbuf :remove func))
(node-clear [this]
(.postMessage mbuf :clear nil))
(node-empty? [this]
(and (.isEmpty mbuf)
(.isEmpty node-funcs)))
(node-state [this] state)
clojure.lang.IFn
(invoke [this]
(clear-buffer out-buffer)
(process-messages! node-funcs mbuf)
(run-afuncs! node-funcs out-buffer)
out-buffer))))
(defn mixer-node
"Creates an audio node that accepts mono-signal audio functions. mixer-node
has properties for gain and panning which will be applied to all generated signals.
Output is a stereo signal."
[& { :keys [ max-messages]
:or {max-messages 512} }]
(let [state (create-node-state 1 max-messages)
mono-buffer (create-buffer)
^doubles left (create-buffer)
^doubles right (create-buffer)
out-buffer (into-array [left right])
^MessageBuffer mbuf (:messages state)
^IFnList node-funcs (:funcs state)
^doubles pan (double-array 1 0.0)
^doubles gain (double-array 1 1.0)
PI2 (/ Math/PI 2)]
(reify
Node
(node-add-func [this func]
(.postMessage mbuf :add func))
(node-remove-func [this func]
(.postMessage mbuf :remove func))
(node-clear [this]
(.postMessage mbuf :clear nil))
(node-empty? [this]
(and (.isEmpty mbuf)
(.isEmpty node-funcs)))
(node-state [this] state)
GainNode
(set-gain! [this gain-val]
(aset gain 0 (double gain-val))
nil)
(get-gain [this]
(aget gain 0))
StereoMixerNode
(set-pan! [this pan-val]
(aset pan 0 (double pan-val))
nil)
(get-pan [this]
(aget pan 0))
clojure.lang.IFn
(invoke [this]
(clear-buffer mono-buffer)
(process-messages! node-funcs mbuf)
(run-afuncs! node-funcs mono-buffer)
(let [ksmps (long *buffer-size*)
g (aget gain 0)
p (aget pan 0)
new-loc-v (+ 0.5 (* 0.5 p))
new-l (db->amp (* 20 (Math/log (Math/cos (* PI2 new-loc-v )))))
new-r (db->amp (* 20 (Math/log (Math/sin (* PI2 new-loc-v )))))]
(loop [indx 0]
(when (< indx ksmps)
(let [samp (* g (aget mono-buffer indx))]
(aset left indx (* new-l samp))
(aset right indx (* new-r samp))
(recur (+ indx 1))))))
out-buffer))))
(defn gain-node
"Creates an audio node that accepts stereo-signal audio functions. gain-node
sums the generated signals from the audio functions, multiplies by gain, and
outputs the stereo-signal output."
[& { :keys [channels max-messages]
:or {channels *nchnls*
max-messages 512} }]
(let [state (create-node-state 2 max-messages)
^doubles left (create-buffer)
^doubles right (create-buffer)
out-buffer (into-array [left right])
^IFnList node-funcs (:funcs state)
^MessageBuffer mbuf (:messages state)
^doubles gain (double-array 1 1.0)]
(reify
Node
(node-add-func [this func]
(.postMessage mbuf :add func))
(node-remove-func [this func]
(.postMessage mbuf :remove func))
(node-clear [this]
(.postMessage mbuf :clear nil))
(node-empty? [this]
(and (.isEmpty mbuf)
(.isEmpty node-funcs)))
(node-state [this] state)
GainNode
(set-gain! [this gain-val]
(aset gain 0 (double gain-val))
nil)
(get-gain [this]
(aget gain 0))
clojure.lang.IFn
(invoke [this]
(clear-buffer out-buffer)
(process-messages! node-funcs mbuf)
(run-afuncs! node-funcs out-buffer)
(let [ksmps (long *buffer-size*)
g (aget gain 0)]
(loop [indx 0]
(loop [indx 0]
(when (< indx ksmps)
(aset left indx (* g (aget left indx)))
(aset right indx (* g (aget right indx)))
(recur (+ indx 1))))))
out-buffer))))
(defn fire-node-event
"create an instance of an audio function and adds to the node"
[node evt]
(when-let [afunc (fire-event evt)]
(node-add-func node afunc)))
(defn wrap-node-event [node ^Event evt]
(wrap-event fire-node-event [node] evt))
(defn node-events
"Takes a node and series of events, wrapping the events as node-events.
If single arg given, assumes it is a list of events."
([node args]
(if (sequential? args)
(map #(wrap-node-event node %) args)
(map #(wrap-node-event node %) [args])))
([node x & args]
(node-events node (list* x args))))
|
bfae6093cf52471fa2ae249bd167d8e6629232fdde0123a1cbff19e37426032b | circuithub/rel8 | Window.hs | # language MonoLocalBinds #
module Rel8.Table.Window
( cumulative
, cumulative_
, currentRow
)
where
-- base
import Prelude
-- opaleye
import qualified Opaleye.Window as Opaleye
-- rel8
import Rel8.Aggregate ( Aggregates )
import qualified Rel8.Expr.Window as Expr
import Rel8.Schema.HTable ( hfield, htabulateA )
import Rel8.Table ( fromColumns, toColumns )
import Rel8.Window ( Window( Window ) )
-- | 'cumulative' allows the use of aggregation functions in 'Window'
-- expressions. In particular, @'cumulative' 'Rel8.sum'@
-- (when combined with 'Rel8.Window.orderPartitionBy') gives a running total,
also known as a \"cumulative sum\ " , hence the name @cumulative@.
cumulative :: Aggregates aggregates exprs => (a -> aggregates) -> Window a exprs
cumulative f =
fmap fromColumns $
htabulateA $ \field ->
Expr.cumulative ((`hfield` field) . toColumns . f)
-- | A version of 'cumulative' for use with nullary aggregators like
-- 'Rel8.Expr.Aggregate.countStar'.
cumulative_ :: Aggregates aggregates exprs => aggregates -> Window a exprs
cumulative_ = cumulative . const
-- | Return every column of the current row of a window query.
currentRow :: Window a a
currentRow = Window $ Opaleye.over (Opaleye.noWindowFunction id) mempty mempty
| null | https://raw.githubusercontent.com/circuithub/rel8/2e82fccb02470198297f4a71b9da8f535d8029b1/src/Rel8/Table/Window.hs | haskell | base
opaleye
rel8
| 'cumulative' allows the use of aggregation functions in 'Window'
expressions. In particular, @'cumulative' 'Rel8.sum'@
(when combined with 'Rel8.Window.orderPartitionBy') gives a running total,
| A version of 'cumulative' for use with nullary aggregators like
'Rel8.Expr.Aggregate.countStar'.
| Return every column of the current row of a window query. | # language MonoLocalBinds #
module Rel8.Table.Window
( cumulative
, cumulative_
, currentRow
)
where
import Prelude
import qualified Opaleye.Window as Opaleye
import Rel8.Aggregate ( Aggregates )
import qualified Rel8.Expr.Window as Expr
import Rel8.Schema.HTable ( hfield, htabulateA )
import Rel8.Table ( fromColumns, toColumns )
import Rel8.Window ( Window( Window ) )
also known as a \"cumulative sum\ " , hence the name @cumulative@.
cumulative :: Aggregates aggregates exprs => (a -> aggregates) -> Window a exprs
cumulative f =
fmap fromColumns $
htabulateA $ \field ->
Expr.cumulative ((`hfield` field) . toColumns . f)
cumulative_ :: Aggregates aggregates exprs => aggregates -> Window a exprs
cumulative_ = cumulative . const
currentRow :: Window a a
currentRow = Window $ Opaleye.over (Opaleye.noWindowFunction id) mempty mempty
|
aa634a2fe33e63002fb182a5860cfc09b517f83025e57e22748a8c0206763c82 | wdebeaum/step | weather.lisp | ;;;;
;;;; W::WEATHER
;;;;
(define-words :pos W::n :templ COUNT-PRED-TEMPL
:words (
(W::WEATHER
(SENSES
((meta-data :origin plow :entry-date 20060803 :change-date nil :comments nil :wn ("weather%1:19:00"))
(LF-PARENT ONT::weather)
)
)
)
))
| null | https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/LexiconManager/Data/new/weather.lisp | lisp |
W::WEATHER
|
(define-words :pos W::n :templ COUNT-PRED-TEMPL
:words (
(W::WEATHER
(SENSES
((meta-data :origin plow :entry-date 20060803 :change-date nil :comments nil :wn ("weather%1:19:00"))
(LF-PARENT ONT::weather)
)
)
)
))
|
284bbd8011a1d168647f2b9deb6a10ec5e5f63da9df00a7de8d76119f7c77b21 | clj-commons/cljss | css.clj | (ns cljss.css
(:require [clojure.spec.alpha :as s]
[cljss.css.props.background :as bg]
[cljss.css.props.border :as border]
[cljss.css.props.color :as color]
[cljss.css.props.dimensions :as dims]
[cljss.css.props.display :as display]
[cljss.css.props.margin :as margin]
[cljss.css.props.offset :as offset]
[cljss.css.props.padding :as padding]
[cljss.css.props.position :as pos]
[cljss.css.props.z-index :as zidx]))
| null | https://raw.githubusercontent.com/clj-commons/cljss/d2856688cf650babe518c798cf20e6bdb4227bb7/src/cljss/css.clj | clojure | (ns cljss.css
(:require [clojure.spec.alpha :as s]
[cljss.css.props.background :as bg]
[cljss.css.props.border :as border]
[cljss.css.props.color :as color]
[cljss.css.props.dimensions :as dims]
[cljss.css.props.display :as display]
[cljss.css.props.margin :as margin]
[cljss.css.props.offset :as offset]
[cljss.css.props.padding :as padding]
[cljss.css.props.position :as pos]
[cljss.css.props.z-index :as zidx]))
|
|
cb038d2791f58a24db7d2301e5a2dcb365944be906d1d1a16a864e1566312444 | tlaplus/tlapm | m_save.ml | Writing and loading of modules .
Copyright ( C ) 2008 - 2010 INRIA and Microsoft Corporation
Copyright (C) 2008-2010 INRIA and Microsoft Corporation
*)
open Property
open Util.Coll
open Tla_parser
open Tla_parser.P
open M_t
open M_parser
let debug = Printf.eprintf
exception Unknown_module_exception
exception Not_loadable_exception of string wrapped
let clocking cl fn x =
match cl with
| Some cl ->
Timing.start cl;
let ret = fn x in
Timing.stop ();
ret
| None ->
fn x
let file_search fh =
if Filename.is_implicit fh.core then
let rec scan = function
| [] -> None
| d :: ds ->
let f = Filename.concat d fh.core in
if Sys.file_exists f then
Some (f @@ fh)
else scan ds
in scan ("." :: List.rev !Params.rev_search_path)
else
if Sys.file_exists fh.core then
Some fh
else None
let really_parse_file fn =
match file_search fn with
| None ->
Util.eprintf ~at:fn
"Could not find file %S in the search path."
fn.core;
failwith "Module.Parser.parse_file"
| Some fn ->
let (flex, _) = Alexer.lex fn.core in
let hparse = use parse in
match P.run hparse ~init:Tla_parser.init ~source:flex with
| None ->
Util.eprintf ~at:fn
"Could not parse %S successfully."
fn.core;
failwith "Module.Parser.parse_file"
| Some mule ->
if !Params.verbose then begin
Util.printf
"(* module %S parsed from %S *)"
mule.core.name.core
fn.core;
end;
let rawname =
Filename.chop_suffix
(Filename.basename fn.core)
".tla" in
if mule.core.name.core <> rawname then begin
Errors.err ~at:mule
"Warning: module name %S does not match \
file name %S."
mule.core.name.core
(Filename.basename fn.core);
let newname = {mule.core.name with core=rawname} in
{mule with core={mule.core with name=newname}}
end else
mule
let validate mn inch =
let v: string = Marshal.from_channel inch in
if v = Params.rawversion () then
let h = Digest.input inch in
if h = Params.self_sum then
let csum = Digest.input inch in
let mule: mule = Marshal.from_channel inch in
(close_in inch;
Some (csum, mule))
else
(close_in inch;
None)
else
(close_in inch;
None)
let rec really_load_module mn fn fnx =
match fn, fnx with
| Some _, Some _ when not !Params.use_xtla ->
really_load_module mn fn None
| None, None ->
Util.eprintf ~at : mn
" Unknown module % S " mn.core ;
Errors.set mn ( Printf.sprintf " Unknown module % S " mn.core ) ;
failwith " Module . "
"Unknown module %S" mn.core;
Errors.set mn (Printf.sprintf "Unknown module %S" mn.core);
failwith "Module.Parser.load_module"
*)
raise Unknown_module_exception
| Some fn, None ->
really_parse_file fn
| None, Some fnx ->
begin match validate mn (open_in_bin fnx.core) with
| Some (_, m) ->
if !Params.verbose then
Util.printf
"(* module %S loaded from %S *)"
m.core.name.core
fnx.core;
m
| None ->
Util.eprintf ~at : fnx
" % S not loadable\nNo corresponding source found either ! "
fnx.core ;
failwith " Module . "
"%S not loadable\nNo corresponding source found either!"
fnx.core;
failwith "Module.Parser.load_module"
*)
raise (Not_loadable_exception fnx)
end
| Some fn, Some fnx ->
begin match validate mn (open_in_bin fnx.core) with
| Some (csum, m) when csum = Digest.file fn.core ->
if !Params.verbose then
Util.printf
"(* module %S loaded from %S *)"
m.core.name.core
fnx.core;
m
| _ ->
really_parse_file fn
end
let load_module ?clock ?root:(r="") mn =
clocking clock begin fun () ->
let fn = (Filename.concat r (mn.core ^ ".tla")) @@ mn in
let fnx = (Filename.concat r (mn.core ^ ".xtla")) @@ mn in
really_load_module mn (file_search fn) (file_search fnx)
end ()
let parse_file ?clock gfn =
clocking clock begin fun () ->
let fn = begin
if Filename.check_suffix gfn.core ".tla" then
Filename.chop_suffix gfn.core ".tla"
else
gfn.core
end @@ gfn in
let mn = (Filename.basename fn.core) @@ fn in
let fnx = file_search ((fn.core ^ ".xtla") @@ fn) in
let fn = file_search ((fn.core ^ ".tla") @@ fn) in
if fn = None && fnx = None then begin
Util.eprintf ~at:gfn
"File %S not found" gfn.core;
Errors.set
gfn (Printf.sprintf "File %s not found" gfn.core);
failwith "Module.Parser.parse_file"
end else
really_load_module mn fn fnx
end ()
let complete_load ?clock ?root:(r="") mcx =
clocking clock
begin fun () ->
let requested = ref Hs.empty in
(* suffices to compare to found modules by name.
`Module.Elab` will add submodules of extended modules to the
module context, before those are instantiated.
*)
let found = ref Hs.empty in
let mods = ref Deque.empty in
Sm.iter (fun _ mule -> mods := Deque.snoc !mods mule) mcx;
let rec spin mcx =
match Deque.front !mods with
| None -> mcx
| Some (mule, rest) ->
mods := rest;
let (eds, submodule_names, submodules) =
M_dep.external_deps mule in
found := Hs.union submodule_names !found;
let mcx = Sm.merge
(fun k v1 v2 -> if v1 = None then v2 else v1)
mcx submodules in
print_string " \n--------\n " ;
Hs.iter ( fun x - > print_string ( x.core ^ " \n " ) ) eds ;
print_string " \n--------\n " ;
print_string "\n--------\n";
Hs.iter (fun x -> print_string (x.core ^ "\n")) eds;
print_string "\n--------\n";
*)
let mcx = Hs.fold begin
fun ed mcx ->
(* let mn = ed in *)
(* if module name is also a name of
a standrd module, try to load it anyway
*)
if (Sm.mem ed.core M_standard.initctx) then
try
let emule = load_module ~root:r ed in
mods := Deque.snoc !mods emule;
Sm.add ed.core emule mcx
with Unknown_module_exception ->
(* expected behavior--standard module
will be used
*)
mcx
| Not_loadable_exception fnx ->
Util.eprintf ~at:fnx
"%S not loadable\n\
No corresponding source found either!"
fnx.core;
failwith "Module.Parser.load_module"
(* else load it only if it is not already defined
(either because a file already loaded, or
because a submodule of
the current module, or a submodule of
a module already loaded)
*)
else if (Sm.mem ed.core mcx) then mcx
else
try
let emule = load_module ~root:r ed in
mods := Deque.snoc !mods emule;
Sm.add ed.core emule mcx
with Unknown_module_exception ->
(* Modules from `INSTANCE` and `EXTENDS`
statements could be
submodules of a module that the
module extends, and is
itself another file.
*)
requested := Hs.add ed !requested;
mcx
Util.eprintf ~at : mn
" Unknown module % S " mn.core ;
Errors.set
mn
( Printf.sprintf
" Unknown module % S " mn.core ) ;
failwith " Module . "
Util.eprintf ~at:mn
"Unknown module %S" mn.core;
Errors.set
mn
(Printf.sprintf
"Unknown module %S" mn.core);
failwith "Module.Parser.load_module"
*)
| Not_loadable_exception fnx ->
Util.eprintf ~at:fnx
"%S not loadable\n\
No corresponding source found either!"
fnx.core;
failwith "Module.Parser.load_module"
end eds mcx in
spin mcx in
let res = spin mcx in
print_int ( Sm.cardinal res ) ;
print_int ( Hs.cardinal ! found ) ;
print_int ( Hs.cardinal ! requested ) ;
print_string " " ;
Sm.iter
( fun x y - > print_string ( y.core.name.core ^ " \n " ) )
res ;
print_string " \nFound modules:\n " ;
Hs.iter
( fun x - > print_string ( x.core ^ " \n " ) )
! found ;
print_string " \nRequested modules:\n " ;
Hs.iter
( fun x - > print_string ( x.core ^ " \n " ) )
! requested ;
print_int (Sm.cardinal res);
print_int (Hs.cardinal !found);
print_int (Hs.cardinal !requested);
print_string "\nResult:\n";
Sm.iter
(fun x y -> print_string (y.core.name.core ^ "\n"))
res;
print_string "\nFound modules:\n";
Hs.iter
(fun x -> print_string (x.core ^ "\n"))
!found;
print_string "\nRequested modules:\n";
Hs.iter
(fun x -> print_string (x.core ^ "\n"))
!requested;
*)
if not (Hs.subset !requested !found) then begin
let not_found = Hs.diff !requested !found in
Hs.iter (fun mn ->
Util.eprintf ~at:mn
"Unknown module %S" mn.core;
Errors.set
mn
(Printf.sprintf
"Unknown module %S" mn.core)
) not_found;
failwith "Module.Parser.load_module"
end;
res
end ()
let store_module ?clock mule =
if !Params.xtla then
clocking clock begin fun () ->
let fn = (Util.get_locus mule).Loc.file in
let fnx = Filename.chop_extension fn ^ ".xtla" in
let fx = open_out_bin fnx in
Marshal.to_channel fx Params.rawversion [];
Digest.output fx Params.self_sum;
Digest.output fx (Digest.file fn);
Marshal.to_channel fx mule [];
close_out fx;
if !Params.verbose then
Util.printf "(* compiled module %S saved to %S *)"
mule.core.name.core fnx
end ()
else ()
| null | https://raw.githubusercontent.com/tlaplus/tlapm/158386319f5b6cd299f95385a216ade2b85c9f72/src/module/m_save.ml | ocaml | suffices to compare to found modules by name.
`Module.Elab` will add submodules of extended modules to the
module context, before those are instantiated.
let mn = ed in
if module name is also a name of
a standrd module, try to load it anyway
expected behavior--standard module
will be used
else load it only if it is not already defined
(either because a file already loaded, or
because a submodule of
the current module, or a submodule of
a module already loaded)
Modules from `INSTANCE` and `EXTENDS`
statements could be
submodules of a module that the
module extends, and is
itself another file.
| Writing and loading of modules .
Copyright ( C ) 2008 - 2010 INRIA and Microsoft Corporation
Copyright (C) 2008-2010 INRIA and Microsoft Corporation
*)
open Property
open Util.Coll
open Tla_parser
open Tla_parser.P
open M_t
open M_parser
let debug = Printf.eprintf
exception Unknown_module_exception
exception Not_loadable_exception of string wrapped
let clocking cl fn x =
match cl with
| Some cl ->
Timing.start cl;
let ret = fn x in
Timing.stop ();
ret
| None ->
fn x
let file_search fh =
if Filename.is_implicit fh.core then
let rec scan = function
| [] -> None
| d :: ds ->
let f = Filename.concat d fh.core in
if Sys.file_exists f then
Some (f @@ fh)
else scan ds
in scan ("." :: List.rev !Params.rev_search_path)
else
if Sys.file_exists fh.core then
Some fh
else None
let really_parse_file fn =
match file_search fn with
| None ->
Util.eprintf ~at:fn
"Could not find file %S in the search path."
fn.core;
failwith "Module.Parser.parse_file"
| Some fn ->
let (flex, _) = Alexer.lex fn.core in
let hparse = use parse in
match P.run hparse ~init:Tla_parser.init ~source:flex with
| None ->
Util.eprintf ~at:fn
"Could not parse %S successfully."
fn.core;
failwith "Module.Parser.parse_file"
| Some mule ->
if !Params.verbose then begin
Util.printf
"(* module %S parsed from %S *)"
mule.core.name.core
fn.core;
end;
let rawname =
Filename.chop_suffix
(Filename.basename fn.core)
".tla" in
if mule.core.name.core <> rawname then begin
Errors.err ~at:mule
"Warning: module name %S does not match \
file name %S."
mule.core.name.core
(Filename.basename fn.core);
let newname = {mule.core.name with core=rawname} in
{mule with core={mule.core with name=newname}}
end else
mule
let validate mn inch =
let v: string = Marshal.from_channel inch in
if v = Params.rawversion () then
let h = Digest.input inch in
if h = Params.self_sum then
let csum = Digest.input inch in
let mule: mule = Marshal.from_channel inch in
(close_in inch;
Some (csum, mule))
else
(close_in inch;
None)
else
(close_in inch;
None)
let rec really_load_module mn fn fnx =
match fn, fnx with
| Some _, Some _ when not !Params.use_xtla ->
really_load_module mn fn None
| None, None ->
Util.eprintf ~at : mn
" Unknown module % S " mn.core ;
Errors.set mn ( Printf.sprintf " Unknown module % S " mn.core ) ;
failwith " Module . "
"Unknown module %S" mn.core;
Errors.set mn (Printf.sprintf "Unknown module %S" mn.core);
failwith "Module.Parser.load_module"
*)
raise Unknown_module_exception
| Some fn, None ->
really_parse_file fn
| None, Some fnx ->
begin match validate mn (open_in_bin fnx.core) with
| Some (_, m) ->
if !Params.verbose then
Util.printf
"(* module %S loaded from %S *)"
m.core.name.core
fnx.core;
m
| None ->
Util.eprintf ~at : fnx
" % S not loadable\nNo corresponding source found either ! "
fnx.core ;
failwith " Module . "
"%S not loadable\nNo corresponding source found either!"
fnx.core;
failwith "Module.Parser.load_module"
*)
raise (Not_loadable_exception fnx)
end
| Some fn, Some fnx ->
begin match validate mn (open_in_bin fnx.core) with
| Some (csum, m) when csum = Digest.file fn.core ->
if !Params.verbose then
Util.printf
"(* module %S loaded from %S *)"
m.core.name.core
fnx.core;
m
| _ ->
really_parse_file fn
end
let load_module ?clock ?root:(r="") mn =
clocking clock begin fun () ->
let fn = (Filename.concat r (mn.core ^ ".tla")) @@ mn in
let fnx = (Filename.concat r (mn.core ^ ".xtla")) @@ mn in
really_load_module mn (file_search fn) (file_search fnx)
end ()
let parse_file ?clock gfn =
clocking clock begin fun () ->
let fn = begin
if Filename.check_suffix gfn.core ".tla" then
Filename.chop_suffix gfn.core ".tla"
else
gfn.core
end @@ gfn in
let mn = (Filename.basename fn.core) @@ fn in
let fnx = file_search ((fn.core ^ ".xtla") @@ fn) in
let fn = file_search ((fn.core ^ ".tla") @@ fn) in
if fn = None && fnx = None then begin
Util.eprintf ~at:gfn
"File %S not found" gfn.core;
Errors.set
gfn (Printf.sprintf "File %s not found" gfn.core);
failwith "Module.Parser.parse_file"
end else
really_load_module mn fn fnx
end ()
let complete_load ?clock ?root:(r="") mcx =
clocking clock
begin fun () ->
let requested = ref Hs.empty in
let found = ref Hs.empty in
let mods = ref Deque.empty in
Sm.iter (fun _ mule -> mods := Deque.snoc !mods mule) mcx;
let rec spin mcx =
match Deque.front !mods with
| None -> mcx
| Some (mule, rest) ->
mods := rest;
let (eds, submodule_names, submodules) =
M_dep.external_deps mule in
found := Hs.union submodule_names !found;
let mcx = Sm.merge
(fun k v1 v2 -> if v1 = None then v2 else v1)
mcx submodules in
print_string " \n--------\n " ;
Hs.iter ( fun x - > print_string ( x.core ^ " \n " ) ) eds ;
print_string " \n--------\n " ;
print_string "\n--------\n";
Hs.iter (fun x -> print_string (x.core ^ "\n")) eds;
print_string "\n--------\n";
*)
let mcx = Hs.fold begin
fun ed mcx ->
if (Sm.mem ed.core M_standard.initctx) then
try
let emule = load_module ~root:r ed in
mods := Deque.snoc !mods emule;
Sm.add ed.core emule mcx
with Unknown_module_exception ->
mcx
| Not_loadable_exception fnx ->
Util.eprintf ~at:fnx
"%S not loadable\n\
No corresponding source found either!"
fnx.core;
failwith "Module.Parser.load_module"
else if (Sm.mem ed.core mcx) then mcx
else
try
let emule = load_module ~root:r ed in
mods := Deque.snoc !mods emule;
Sm.add ed.core emule mcx
with Unknown_module_exception ->
requested := Hs.add ed !requested;
mcx
Util.eprintf ~at : mn
" Unknown module % S " mn.core ;
Errors.set
mn
( Printf.sprintf
" Unknown module % S " mn.core ) ;
failwith " Module . "
Util.eprintf ~at:mn
"Unknown module %S" mn.core;
Errors.set
mn
(Printf.sprintf
"Unknown module %S" mn.core);
failwith "Module.Parser.load_module"
*)
| Not_loadable_exception fnx ->
Util.eprintf ~at:fnx
"%S not loadable\n\
No corresponding source found either!"
fnx.core;
failwith "Module.Parser.load_module"
end eds mcx in
spin mcx in
let res = spin mcx in
print_int ( Sm.cardinal res ) ;
print_int ( Hs.cardinal ! found ) ;
print_int ( Hs.cardinal ! requested ) ;
print_string " " ;
Sm.iter
( fun x y - > print_string ( y.core.name.core ^ " \n " ) )
res ;
print_string " \nFound modules:\n " ;
Hs.iter
( fun x - > print_string ( x.core ^ " \n " ) )
! found ;
print_string " \nRequested modules:\n " ;
Hs.iter
( fun x - > print_string ( x.core ^ " \n " ) )
! requested ;
print_int (Sm.cardinal res);
print_int (Hs.cardinal !found);
print_int (Hs.cardinal !requested);
print_string "\nResult:\n";
Sm.iter
(fun x y -> print_string (y.core.name.core ^ "\n"))
res;
print_string "\nFound modules:\n";
Hs.iter
(fun x -> print_string (x.core ^ "\n"))
!found;
print_string "\nRequested modules:\n";
Hs.iter
(fun x -> print_string (x.core ^ "\n"))
!requested;
*)
if not (Hs.subset !requested !found) then begin
let not_found = Hs.diff !requested !found in
Hs.iter (fun mn ->
Util.eprintf ~at:mn
"Unknown module %S" mn.core;
Errors.set
mn
(Printf.sprintf
"Unknown module %S" mn.core)
) not_found;
failwith "Module.Parser.load_module"
end;
res
end ()
let store_module ?clock mule =
if !Params.xtla then
clocking clock begin fun () ->
let fn = (Util.get_locus mule).Loc.file in
let fnx = Filename.chop_extension fn ^ ".xtla" in
let fx = open_out_bin fnx in
Marshal.to_channel fx Params.rawversion [];
Digest.output fx Params.self_sum;
Digest.output fx (Digest.file fn);
Marshal.to_channel fx mule [];
close_out fx;
if !Params.verbose then
Util.printf "(* compiled module %S saved to %S *)"
mule.core.name.core fnx
end ()
else ()
|
39b85251ee6aa7e2d0e64f5c49c038c96da2f239ccc3ddcb8a6b4175af8b6f18 | dgiot/dgiot | dgiot_tcpc_worker.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2020 - 2021 DGIOT Technologies Co. , Ltd. All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
-module(dgiot_tcpc_worker).
-include("dgiot_bridge.hrl").
-include_lib("dgiot/include/logger.hrl").
-include_lib("dgiot/include/dgiot_socket.hrl").
-include_lib("dgiot/include/dgiot_client.hrl").
-record(child_state, {buff = <<>>, product, hb = 30, device}).
%% tcp client callback
-define(MAX_BUFF_SIZE, 10 * 1024).
-export([init/1, handle_info/2, terminate/2]).
%% tcp client callback
init(#dclient{child = ChildState} = Dclient) when is_map(ChildState) ->
case maps:find(<<"productid">>, ChildState) of
{ok, ProductId} ->
case do_cmd(ProductId, init, ChildState, Dclient) of
default ->
{noreply, #child_state{product = ProductId}};
Result ->
Result
end;
_ ->
{stop, <<"not find product">>}
end;
init(#dclient{channel = ChannelId}) ->
case dgiot_product:get_channel(ChannelId) of
not_find ->
{stop, <<"not find product">>};
ProductId ->
io:format("~s ~p ~p ~p ~n", [?FILE, ?LINE, ChannelId, ProductId]),
{noreply, #child_state{product = ProductId}}
end.
handle_info(connection_ready, #dclient{child = #child_state{product = ProductId} = ChildState} = Dclient) ->
rand:seed(exs1024),
Time = erlang:round(rand:uniform() * 1 + 1) * 1000,
io : format("~s ~p ~p ~n " , [ ? FILE , ? LINE , ProductId ] ) ,
case do_cmd(ProductId, connection_ready, <<>>, Dclient) of
default ->
erlang:send_after(Time, self(), login),
{noreply, ChildState};
Result ->
Result
end;
handle_info(#{<<"cmd">> := Cmd, <<"data">> := Data, <<"productId">> := ProductId}, #dclient{child = #child_state{} = ChildState} = Dclient) ->
case do_cmd(ProductId, Cmd, Data, Dclient) of
default ->
{noreply, ChildState};
Result ->
Result
end;
handle_info(tcp_closed, #dclient{child = #child_state{product = ProductId} = ChildState} = Dclient) ->
case do_cmd(ProductId, tcp_closed, <<>>, Dclient) of
default ->
{noreply, ChildState};
Result ->
Result
end;
handle_info({tcp, Buff}, #dclient{child = #child_state{buff = Old, product = ProductId} = ChildState} = Dclient) ->
Data = <<Old/binary, Buff/binary>>,
case do_cmd(ProductId, tcp, Data, Dclient) of
default ->
{noreply, ChildState};
Result ->
Result
end;
handle_info({deliver, _Topic, _Msg}, #dclient{child = ChildState}) ->
{noreply, ChildState};
handle_info(login, #dclient{child = #child_state{hb = Hb} = ChildState}) ->
erlang:send_after(Hb * 1000, self(), heartbeat),
dgiot_tcp_client:send(<<"login">>),
{noreply, ChildState};
handle_info(heartbeat, #dclient{child = #child_state{hb = Hb} = ChildState}) ->
erlang:send_after(Hb * 1000, self(), heartbeat),
dgiot_tcp_client:send(<<"heartbeat">>),
{noreply, ChildState};
handle_info(_Info, Dclient) ->
{noreply, Dclient}.
terminate(_Reason, _Dclient) ->
ok.
do_cmd(ProductId, Cmd, Data, #dclient{child = ChildState} = Dclient) ->
io:format("~s ~p ~p Cmd ~p ~n", [?FILE, ?LINE, ProductId, Cmd]),
case dgiot_hook:run_hook({tcp, ProductId}, [Cmd, Data, Dclient]) of
{ok, Device} ->
{noreply, ChildState#child_state{device = Device}};
{noreply, Device} ->
{noreply, ChildState#child_state{device = Device}};
{noreply, Bin, Device} ->
{noreply, ChildState#child_state{buff = Bin, device = Device}};
{error, Reason, Device} ->
{stop, Reason, ChildState#child_state{device = Device}};
{stop, Reason, Device} ->
{stop, Reason, ChildState#child_state{device = Device}};
_ ->
default
end. | null | https://raw.githubusercontent.com/dgiot/dgiot/a6b816a094b1c9bd024ce40b8142375a0f0289d8/apps/dgiot_bridge/src/channel/dgiot_tcpc_worker.erl | erlang | --------------------------------------------------------------------
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--------------------------------------------------------------------
tcp client callback
tcp client callback | Copyright ( c ) 2020 - 2021 DGIOT Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(dgiot_tcpc_worker).
-include("dgiot_bridge.hrl").
-include_lib("dgiot/include/logger.hrl").
-include_lib("dgiot/include/dgiot_socket.hrl").
-include_lib("dgiot/include/dgiot_client.hrl").
-record(child_state, {buff = <<>>, product, hb = 30, device}).
-define(MAX_BUFF_SIZE, 10 * 1024).
-export([init/1, handle_info/2, terminate/2]).
init(#dclient{child = ChildState} = Dclient) when is_map(ChildState) ->
case maps:find(<<"productid">>, ChildState) of
{ok, ProductId} ->
case do_cmd(ProductId, init, ChildState, Dclient) of
default ->
{noreply, #child_state{product = ProductId}};
Result ->
Result
end;
_ ->
{stop, <<"not find product">>}
end;
init(#dclient{channel = ChannelId}) ->
case dgiot_product:get_channel(ChannelId) of
not_find ->
{stop, <<"not find product">>};
ProductId ->
io:format("~s ~p ~p ~p ~n", [?FILE, ?LINE, ChannelId, ProductId]),
{noreply, #child_state{product = ProductId}}
end.
handle_info(connection_ready, #dclient{child = #child_state{product = ProductId} = ChildState} = Dclient) ->
rand:seed(exs1024),
Time = erlang:round(rand:uniform() * 1 + 1) * 1000,
io : format("~s ~p ~p ~n " , [ ? FILE , ? LINE , ProductId ] ) ,
case do_cmd(ProductId, connection_ready, <<>>, Dclient) of
default ->
erlang:send_after(Time, self(), login),
{noreply, ChildState};
Result ->
Result
end;
handle_info(#{<<"cmd">> := Cmd, <<"data">> := Data, <<"productId">> := ProductId}, #dclient{child = #child_state{} = ChildState} = Dclient) ->
case do_cmd(ProductId, Cmd, Data, Dclient) of
default ->
{noreply, ChildState};
Result ->
Result
end;
handle_info(tcp_closed, #dclient{child = #child_state{product = ProductId} = ChildState} = Dclient) ->
case do_cmd(ProductId, tcp_closed, <<>>, Dclient) of
default ->
{noreply, ChildState};
Result ->
Result
end;
handle_info({tcp, Buff}, #dclient{child = #child_state{buff = Old, product = ProductId} = ChildState} = Dclient) ->
Data = <<Old/binary, Buff/binary>>,
case do_cmd(ProductId, tcp, Data, Dclient) of
default ->
{noreply, ChildState};
Result ->
Result
end;
handle_info({deliver, _Topic, _Msg}, #dclient{child = ChildState}) ->
{noreply, ChildState};
handle_info(login, #dclient{child = #child_state{hb = Hb} = ChildState}) ->
erlang:send_after(Hb * 1000, self(), heartbeat),
dgiot_tcp_client:send(<<"login">>),
{noreply, ChildState};
handle_info(heartbeat, #dclient{child = #child_state{hb = Hb} = ChildState}) ->
erlang:send_after(Hb * 1000, self(), heartbeat),
dgiot_tcp_client:send(<<"heartbeat">>),
{noreply, ChildState};
handle_info(_Info, Dclient) ->
{noreply, Dclient}.
terminate(_Reason, _Dclient) ->
ok.
do_cmd(ProductId, Cmd, Data, #dclient{child = ChildState} = Dclient) ->
io:format("~s ~p ~p Cmd ~p ~n", [?FILE, ?LINE, ProductId, Cmd]),
case dgiot_hook:run_hook({tcp, ProductId}, [Cmd, Data, Dclient]) of
{ok, Device} ->
{noreply, ChildState#child_state{device = Device}};
{noreply, Device} ->
{noreply, ChildState#child_state{device = Device}};
{noreply, Bin, Device} ->
{noreply, ChildState#child_state{buff = Bin, device = Device}};
{error, Reason, Device} ->
{stop, Reason, ChildState#child_state{device = Device}};
{stop, Reason, Device} ->
{stop, Reason, ChildState#child_state{device = Device}};
_ ->
default
end. |
27b25cc1f816ba223391a3ac7adc84e8897fbe9fe7d1822813569ff727599c4a | achirkin/vulkan | PolygonMode.hs | # OPTIONS_HADDOCK ignore - exports #
{-# LANGUAGE DataKinds #-}
# LANGUAGE GeneralizedNewtypeDeriving #
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE Strict #-}
module Graphics.Vulkan.Types.Enum.PolygonMode
(VkPolygonMode(VkPolygonMode, VK_POLYGON_MODE_FILL,
VK_POLYGON_MODE_LINE, VK_POLYGON_MODE_POINT))
where
import Foreign.Storable (Storable)
import GHC.Read (choose, expectP)
import Graphics.Vulkan.Marshal (Int32)
import Text.ParserCombinators.ReadPrec (prec, step, (+++))
import Text.Read (Read (..), parens)
import Text.Read.Lex (Lexeme (..))
-- | type = @enum@
--
-- <-extensions/html/vkspec.html#VkPolygonMode VkPolygonMode registry at www.khronos.org>
newtype VkPolygonMode = VkPolygonMode Int32
deriving (Eq, Ord, Enum, Storable)
instance Show VkPolygonMode where
showsPrec _ VK_POLYGON_MODE_FILL
= showString "VK_POLYGON_MODE_FILL"
showsPrec _ VK_POLYGON_MODE_LINE
= showString "VK_POLYGON_MODE_LINE"
showsPrec _ VK_POLYGON_MODE_POINT
= showString "VK_POLYGON_MODE_POINT"
showsPrec p (VkPolygonMode x)
= showParen (p >= 11)
(showString "VkPolygonMode " . showsPrec 11 x)
instance Read VkPolygonMode where
readPrec
= parens
(choose
[("VK_POLYGON_MODE_FILL", pure VK_POLYGON_MODE_FILL),
("VK_POLYGON_MODE_LINE", pure VK_POLYGON_MODE_LINE),
("VK_POLYGON_MODE_POINT", pure VK_POLYGON_MODE_POINT)]
+++
prec 10
(expectP (Ident "VkPolygonMode") >>
(VkPolygonMode <$> step readPrec)))
pattern VK_POLYGON_MODE_FILL :: VkPolygonMode
pattern VK_POLYGON_MODE_FILL = VkPolygonMode 0
pattern VK_POLYGON_MODE_LINE :: VkPolygonMode
pattern VK_POLYGON_MODE_LINE = VkPolygonMode 1
pattern VK_POLYGON_MODE_POINT :: VkPolygonMode
pattern VK_POLYGON_MODE_POINT = VkPolygonMode 2
| null | https://raw.githubusercontent.com/achirkin/vulkan/b2e0568c71b5135010f4bba939cd8dcf7a05c361/vulkan-api/src-gen/Graphics/Vulkan/Types/Enum/PolygonMode.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE PatternSynonyms #
# LANGUAGE Strict #
| type = @enum@
<-extensions/html/vkspec.html#VkPolygonMode VkPolygonMode registry at www.khronos.org> | # OPTIONS_HADDOCK ignore - exports #
# LANGUAGE GeneralizedNewtypeDeriving #
module Graphics.Vulkan.Types.Enum.PolygonMode
(VkPolygonMode(VkPolygonMode, VK_POLYGON_MODE_FILL,
VK_POLYGON_MODE_LINE, VK_POLYGON_MODE_POINT))
where
import Foreign.Storable (Storable)
import GHC.Read (choose, expectP)
import Graphics.Vulkan.Marshal (Int32)
import Text.ParserCombinators.ReadPrec (prec, step, (+++))
import Text.Read (Read (..), parens)
import Text.Read.Lex (Lexeme (..))
newtype VkPolygonMode = VkPolygonMode Int32
deriving (Eq, Ord, Enum, Storable)
instance Show VkPolygonMode where
showsPrec _ VK_POLYGON_MODE_FILL
= showString "VK_POLYGON_MODE_FILL"
showsPrec _ VK_POLYGON_MODE_LINE
= showString "VK_POLYGON_MODE_LINE"
showsPrec _ VK_POLYGON_MODE_POINT
= showString "VK_POLYGON_MODE_POINT"
showsPrec p (VkPolygonMode x)
= showParen (p >= 11)
(showString "VkPolygonMode " . showsPrec 11 x)
instance Read VkPolygonMode where
readPrec
= parens
(choose
[("VK_POLYGON_MODE_FILL", pure VK_POLYGON_MODE_FILL),
("VK_POLYGON_MODE_LINE", pure VK_POLYGON_MODE_LINE),
("VK_POLYGON_MODE_POINT", pure VK_POLYGON_MODE_POINT)]
+++
prec 10
(expectP (Ident "VkPolygonMode") >>
(VkPolygonMode <$> step readPrec)))
pattern VK_POLYGON_MODE_FILL :: VkPolygonMode
pattern VK_POLYGON_MODE_FILL = VkPolygonMode 0
pattern VK_POLYGON_MODE_LINE :: VkPolygonMode
pattern VK_POLYGON_MODE_LINE = VkPolygonMode 1
pattern VK_POLYGON_MODE_POINT :: VkPolygonMode
pattern VK_POLYGON_MODE_POINT = VkPolygonMode 2
|
e53974ef3b2cf3538f71b539a1a926c80b958d603f13602e28bf23ec90734e6c | byulparan/sc-extensions | client-side.lisp | (in-package :sc-extensions)
(named-readtables:in-readtable :sc)
(defvar *bpm-functions* nil)
(defun bpm (&optional bpm &key (relaunch nil) (lag 0) (pre-tick 0))
(unless (is-playing-p :metro)
(metro 60))
(if (not bpm) (clock-bpm)
(progn
(proxy-handle :bpm-changed
(let* ((tempo (in.kr (- (sc::server-options-num-control-bus (server-options *s*)) 2))))
(line.kr 0 0 (+ lag 1) :act :free)
[(impulse.kr 30) tempo])
(lambda (tempo)
(clock-bpm (* 1.0d0 (/ 60 tempo))))
:to :metro
:pos :after)
(metro bpm :relaunch relaunch :lag lag :pre-tick pre-tick)
(dolist (f *bpm-functions*)
(funcall f bpm :relaunch relaunch :lag lag)))))
(defun pp-synth (beat name &rest param &key &allow-other-keys)
(clock-add beat
(lambda ()
(at (sc::beats-to-secs (sc::tempo-clock *s*) beat)
(apply (if (or (keywordp name) (typep name 'sc::node)) #'ctrl #'synth) name param)))))
(defmacro pp (&body body)
(let* ((sym-beat (alexandria:symbolicate "BEAT"))
(sym-dur (alexandria:symbolicate "DUR"))
(has-beat-offset (evenp (length body)))
(params (if has-beat-offset (cddr body) (cdr body)))
(has-dur-p (getf params :dur)))
(when has-dur-p (setf params (alexandria:remove-from-plist params :dur)))
(if has-beat-offset
`(let ((,sym-beat (+ ,sym-beat ,(car body))))
(pp-synth ,sym-beat ,(second body) ,@params
:dur (clock-dur ,(if has-dur-p has-dur-p sym-dur))))
`(pp-synth ,sym-beat ,(car body) ,@params :dur (clock-dur ,(if has-dur-p has-dur-p sym-dur))))))
(defun rrand (n &optional p)
(cond (p (let* ((min (min n p))
(max (max n p)))
(+ min (random (- max (- min (if (every #'integerp (list n p)) 1 0)))))))
((numberp n) (random n))
((listp n) (alexandria:random-elt n))))
(defmacro sinr (offset gain ratio)
`(+ ,offset (* ,gain (sin (* pi ,(alexandria:symbolicate "BEAT") ,ratio)))))
(defmacro cosr (offset gain ratio)
`(+ ,offset (* ,gain (cos (* pi ,(alexandria:symbolicate "BEAT") ,ratio)))))
(defmacro once (form)
(let* ((result (eval form)))
`(quote ,result)))
(defmacro nth-beat (dur list)
(let ((sym-beat (alexandria:symbolicate "BEAT")))
`(nth (mod (floor ,sym-beat ,dur) (length ,list)) ,list)))
(defvar *schedule-object* (make-hash-table))
(flet ((reset-sched-object ()
(setf *schedule-object* (make-hash-table))))
(pushnew
#'reset-sched-object
*stop-hooks*))
(defstruct schedule-object
time running-p)
(defmacro schedule (name (quant &key (ahead 0) (count +inf+)) &body body)
(alexandria:with-gensyms (func execute next-time sched-time obj sched-obj q-time)
(let* ((sym-beat (alexandria:symbolicate "BEAT"))
(sym-dur (alexandria:symbolicate "DUR"))
(sym-count (alexandria:symbolicate "SCHED-COUNT")))
`(let* ((,obj (make-schedule-object))
(,func ,(when body
`(lambda (,sym-beat)
#+sbcl (declare (sb-ext:muffle-conditions style-warning))
(labels ((,execute (,sym-beat ,sym-count)
(declare (ignorable ,sym-beat ,sym-count))
(let* ((,sched-obj (gethash ',name *schedule-object*))
(,sched-time (schedule-object-time ,sched-obj)))
(if (< ,sym-count ,count)
(when (or (eql ,sched-obj ,obj)
(< ,sym-beat ,sched-time))
,(append (car body)
`((let* ((,next-time (+ ,sym-beat ,sym-dur)))
(when (or (eql ,sched-obj ,obj)
(< ,next-time ,sched-time))
(clock-add (- ,next-time ,ahead) #',execute ,next-time (+ ,sym-count 1)))))))
(setf (schedule-object-running-p ,sched-obj) nil)))))
(,execute ,sym-beat 0))))))
(declare (ignorable ,func))
(let* ((,q-time (if (typep sc::*s* 'sc::rt-server) (clock-quant ,quant) ,quant)))
(setf (schedule-object-time ,obj) ,q-time)
(setf (gethash ',name *schedule-object*) ,obj)
,@(when body
`((setf (schedule-object-running-p ,obj) t)
(clock-add (- ,q-time ,ahead) ,func ,q-time)))
',name)))))
(defun schedule-status ()
(loop for key being the hash-key of *schedule-object*
using (hash-value obj)
when (schedule-object-running-p obj)
collect key))
| null | https://raw.githubusercontent.com/byulparan/sc-extensions/5c3fcef921008ed75c482d7077cc2323575bc2b8/client-side.lisp | lisp | (in-package :sc-extensions)
(named-readtables:in-readtable :sc)
(defvar *bpm-functions* nil)
(defun bpm (&optional bpm &key (relaunch nil) (lag 0) (pre-tick 0))
(unless (is-playing-p :metro)
(metro 60))
(if (not bpm) (clock-bpm)
(progn
(proxy-handle :bpm-changed
(let* ((tempo (in.kr (- (sc::server-options-num-control-bus (server-options *s*)) 2))))
(line.kr 0 0 (+ lag 1) :act :free)
[(impulse.kr 30) tempo])
(lambda (tempo)
(clock-bpm (* 1.0d0 (/ 60 tempo))))
:to :metro
:pos :after)
(metro bpm :relaunch relaunch :lag lag :pre-tick pre-tick)
(dolist (f *bpm-functions*)
(funcall f bpm :relaunch relaunch :lag lag)))))
(defun pp-synth (beat name &rest param &key &allow-other-keys)
(clock-add beat
(lambda ()
(at (sc::beats-to-secs (sc::tempo-clock *s*) beat)
(apply (if (or (keywordp name) (typep name 'sc::node)) #'ctrl #'synth) name param)))))
(defmacro pp (&body body)
(let* ((sym-beat (alexandria:symbolicate "BEAT"))
(sym-dur (alexandria:symbolicate "DUR"))
(has-beat-offset (evenp (length body)))
(params (if has-beat-offset (cddr body) (cdr body)))
(has-dur-p (getf params :dur)))
(when has-dur-p (setf params (alexandria:remove-from-plist params :dur)))
(if has-beat-offset
`(let ((,sym-beat (+ ,sym-beat ,(car body))))
(pp-synth ,sym-beat ,(second body) ,@params
:dur (clock-dur ,(if has-dur-p has-dur-p sym-dur))))
`(pp-synth ,sym-beat ,(car body) ,@params :dur (clock-dur ,(if has-dur-p has-dur-p sym-dur))))))
(defun rrand (n &optional p)
(cond (p (let* ((min (min n p))
(max (max n p)))
(+ min (random (- max (- min (if (every #'integerp (list n p)) 1 0)))))))
((numberp n) (random n))
((listp n) (alexandria:random-elt n))))
(defmacro sinr (offset gain ratio)
`(+ ,offset (* ,gain (sin (* pi ,(alexandria:symbolicate "BEAT") ,ratio)))))
(defmacro cosr (offset gain ratio)
`(+ ,offset (* ,gain (cos (* pi ,(alexandria:symbolicate "BEAT") ,ratio)))))
(defmacro once (form)
(let* ((result (eval form)))
`(quote ,result)))
(defmacro nth-beat (dur list)
(let ((sym-beat (alexandria:symbolicate "BEAT")))
`(nth (mod (floor ,sym-beat ,dur) (length ,list)) ,list)))
(defvar *schedule-object* (make-hash-table))
(flet ((reset-sched-object ()
(setf *schedule-object* (make-hash-table))))
(pushnew
#'reset-sched-object
*stop-hooks*))
(defstruct schedule-object
time running-p)
(defmacro schedule (name (quant &key (ahead 0) (count +inf+)) &body body)
(alexandria:with-gensyms (func execute next-time sched-time obj sched-obj q-time)
(let* ((sym-beat (alexandria:symbolicate "BEAT"))
(sym-dur (alexandria:symbolicate "DUR"))
(sym-count (alexandria:symbolicate "SCHED-COUNT")))
`(let* ((,obj (make-schedule-object))
(,func ,(when body
`(lambda (,sym-beat)
#+sbcl (declare (sb-ext:muffle-conditions style-warning))
(labels ((,execute (,sym-beat ,sym-count)
(declare (ignorable ,sym-beat ,sym-count))
(let* ((,sched-obj (gethash ',name *schedule-object*))
(,sched-time (schedule-object-time ,sched-obj)))
(if (< ,sym-count ,count)
(when (or (eql ,sched-obj ,obj)
(< ,sym-beat ,sched-time))
,(append (car body)
`((let* ((,next-time (+ ,sym-beat ,sym-dur)))
(when (or (eql ,sched-obj ,obj)
(< ,next-time ,sched-time))
(clock-add (- ,next-time ,ahead) #',execute ,next-time (+ ,sym-count 1)))))))
(setf (schedule-object-running-p ,sched-obj) nil)))))
(,execute ,sym-beat 0))))))
(declare (ignorable ,func))
(let* ((,q-time (if (typep sc::*s* 'sc::rt-server) (clock-quant ,quant) ,quant)))
(setf (schedule-object-time ,obj) ,q-time)
(setf (gethash ',name *schedule-object*) ,obj)
,@(when body
`((setf (schedule-object-running-p ,obj) t)
(clock-add (- ,q-time ,ahead) ,func ,q-time)))
',name)))))
(defun schedule-status ()
(loop for key being the hash-key of *schedule-object*
using (hash-value obj)
when (schedule-object-running-p obj)
collect key))
|
|
c9dd71ea33e4aa4b8e329c3287d9548f8c480112334dc447554b9b64014961b4 | bit-ranger/scheme-bootstrap | or-eval.scm | (load "eval/core.scm")
(load "eval/analyze.scm")
(load "syntax/if.scm")
;对or的处理
(define (install-or-eval)
(define new-if ((make-if) 'construct))
and语句序列
(define (or-clauses exp)
(cdr exp))
;or转成if
(define (or->if exp)
(let ((value (expand-clauses (or-clauses exp))))
(display value)
value))
(define (expand-clauses clauses)
(if (null? clauses)
'false
(let ((first (car clauses))
(rest (cdr clauses)))
(new-if first
'true
(expand-clauses rest)))))
(define (eval exp env)
(interp (or->if exp) env))
(define (observe exp)
(analyze (or->if exp)))
(put eval eval-proc-key 'or)
(put eval eval-proc-key '||)
(put observe observe-proc-key 'or)
(put observe observe-proc-key '||)
'(or eval installed))
| null | https://raw.githubusercontent.com/bit-ranger/scheme-bootstrap/a9155ebd29efe1196854b2dcd76941357dab151e/eval/or-eval.scm | scheme | 对or的处理
or转成if | (load "eval/core.scm")
(load "eval/analyze.scm")
(load "syntax/if.scm")
(define (install-or-eval)
(define new-if ((make-if) 'construct))
and语句序列
(define (or-clauses exp)
(cdr exp))
(define (or->if exp)
(let ((value (expand-clauses (or-clauses exp))))
(display value)
value))
(define (expand-clauses clauses)
(if (null? clauses)
'false
(let ((first (car clauses))
(rest (cdr clauses)))
(new-if first
'true
(expand-clauses rest)))))
(define (eval exp env)
(interp (or->if exp) env))
(define (observe exp)
(analyze (or->if exp)))
(put eval eval-proc-key 'or)
(put eval eval-proc-key '||)
(put observe observe-proc-key 'or)
(put observe observe-proc-key '||)
'(or eval installed))
|
37667b4afe8160f2258ab0338849f4679eeac44478dcc7f1c50193b55378b2c3 | MyDataFlow/ttalk-server | http_chunked.erl | %% Feel free to use, reuse and abuse the code in this file.
-module(http_chunked).
-behaviour(cowboy_http_handler).
-export([init/3, handle/2, terminate/3]).
init({_Transport, http}, Req, _Opts) ->
{ok, Req, undefined}.
handle(Req, State) ->
{ok, Req2} = cowboy_req:chunked_reply(200, Req),
timer:sleep(100),
cowboy_req:chunk("chunked_handler\r\n", Req2),
timer:sleep(100),
cowboy_req:chunk("works fine!", Req2),
{ok, Req2, State}.
terminate(_, _, _) ->
ok.
| null | https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/deps/cowboy/test/http_SUITE_data/http_chunked.erl | erlang | Feel free to use, reuse and abuse the code in this file. |
-module(http_chunked).
-behaviour(cowboy_http_handler).
-export([init/3, handle/2, terminate/3]).
init({_Transport, http}, Req, _Opts) ->
{ok, Req, undefined}.
handle(Req, State) ->
{ok, Req2} = cowboy_req:chunked_reply(200, Req),
timer:sleep(100),
cowboy_req:chunk("chunked_handler\r\n", Req2),
timer:sleep(100),
cowboy_req:chunk("works fine!", Req2),
{ok, Req2, State}.
terminate(_, _, _) ->
ok.
|
9d7aa3583597b8f72a13a2f5ef02ab8c0c826a82bd4f06a777cc8b693692e50c | nunchaku-inria/nunchaku | ElimRecursion.mli |
(* This file is free software, part of nunchaku. See file "license" for more details. *)
* { 1 Encoding of Recursive Functions }
Useful for finite - model finding in CVC4 .
It encodes recursive functions as axioms , with a quantification over
an uninterpreted abstraction type .
Useful for finite-model finding in CVC4.
It encodes recursive functions as axioms, with a quantification over
an uninterpreted abstraction type. *)
open Nunchaku_core
val name : string
type term = Term.t
type decode_state
val elim_recursion :
(term, term) Problem.t ->
(term, term) Problem.t * decode_state
val decode_model :
state:decode_state ->
(term, term) Model.t ->
(term, term) Model.t
(** Pipeline component *)
val pipe :
print:bool ->
check:bool ->
((term, term) Problem.t,
(term, term) Problem.t,
(term, term) Problem.Res.t,
(term, term) Problem.Res.t) Transform.t
(** Generic Pipe Component
@param decode the decode function that takes an applied [(module S)]
in addition to the state *)
val pipe_with :
?on_decoded:('d -> unit) list ->
decode:(decode_state -> 'c -> 'd) ->
print:bool ->
check:bool ->
((term, term) Problem.t,
(term, term) Problem.t,
'c, 'd
) Transform.t
| null | https://raw.githubusercontent.com/nunchaku-inria/nunchaku/16f33db3f5e92beecfb679a13329063b194f753d/src/transformations/ElimRecursion.mli | ocaml | This file is free software, part of nunchaku. See file "license" for more details.
* Pipeline component
* Generic Pipe Component
@param decode the decode function that takes an applied [(module S)]
in addition to the state |
* { 1 Encoding of Recursive Functions }
Useful for finite - model finding in CVC4 .
It encodes recursive functions as axioms , with a quantification over
an uninterpreted abstraction type .
Useful for finite-model finding in CVC4.
It encodes recursive functions as axioms, with a quantification over
an uninterpreted abstraction type. *)
open Nunchaku_core
val name : string
type term = Term.t
type decode_state
val elim_recursion :
(term, term) Problem.t ->
(term, term) Problem.t * decode_state
val decode_model :
state:decode_state ->
(term, term) Model.t ->
(term, term) Model.t
val pipe :
print:bool ->
check:bool ->
((term, term) Problem.t,
(term, term) Problem.t,
(term, term) Problem.Res.t,
(term, term) Problem.Res.t) Transform.t
val pipe_with :
?on_decoded:('d -> unit) list ->
decode:(decode_state -> 'c -> 'd) ->
print:bool ->
check:bool ->
((term, term) Problem.t,
(term, term) Problem.t,
'c, 'd
) Transform.t
|
c50ce51ab98ab755195281d15d34fbf28219bf26c2e044cea338aa621c3b122a | RefactoringTools/HaRe | TiDerivedInstances.hs | module TiDerivedInstances(derivedInstances) where
import HasBaseStruct
import HsDecl
import TI
import TiSolve(expandSynonyms)
import TiContextReduction(contextReduction'')
import TiInstanceDB(addInstKind)
import TiSCC(sccD)
import SrcLoc1
import Deriving(derive)
import FreeNamesBase()
import Data.Maybe(mapMaybe)
import Data.List(nub,partition)
import MUtils
import PrettyPrint
--import IOExts(trace) -- debugging
-- Figuring out what the derived instances are, without generating the
-- derived code.
derivedInstances ks stdnames modmap env ds =
reduceInsts .
map inst0 .
concatMap (collectByFst.concatMap drv.mapMaybe basestruct) .
sccD . filter isBaseTypeDec $ ds
where
inst0 (cn,is) = [(n,((c t,map c ts),(s,code t)))|(n,(t,ts))<-is]
where c=app cn
s=srcLoc cn
code t=derive stdnames cn (definedTypeName t)
drv d =
case d of
HsNewTypeDecl s ctx t c cls -> drv' cls t [c]
HsDataDecl s ctx t cs cls -> drv' cls t cs
HsTypeDecl {} -> []
where
drv' cls t cons =
[(cl,(derivedInstName' modmap cl tn,(t,syn (conArgTypes=<<cons))))
|cl<-cls]
where tn=definedTypeName t
conArgTypes con =
case con of
HsConDecl s _ _ c bangts -> map unbang bangts -- !!!
HsRecDecl s _ _ c fields -> map (unbang.snd) fields -- !!!
app c t = hsTyCon c `hsTyApp` t
syn = tmap (expandSynonyms env)
isBaseTypeDec = maybe False isTypeDec . basestruct
isTypeDec d =
case d of
HsNewTypeDecl {} -> True
HsDataDecl {} -> True
HsTypeDecl {} -> True
_ -> False
-- TODO: need fixed point interation for mutually recursive types!!
reduceInsts [] = return []
reduceInsts ([i]:is) =
do i' <- reduce1 i
is' <- extendIEnv' [(fst i')] $ reduceInsts is
return (i':is')
reduceInsts (is1:is) =
do is1' <- mapM declare =<< instContext (instContext0 is1)
is' <- extendIEnv' (map fst is1') $ reduceInsts is
return (is1'++is')
old :
reduceInsts ( is1 : is ) =
if all ( null.freeTyvars.fst.fst.snd ) is1
then reduceInsts ( [ [ i]|i<-is1]++is )
else
fail.pp$
sep [ ppi " Deriving for mutually recursive types with parameters not implemented yet : " ,
nest 4 $ ppiFSeq ( map ( fst.fst.snd ) is1 ) ]
reduceInsts (is1:is) =
if all (null.freeTyvars.fst.fst.snd) is1
then reduceInsts ([[i]|i<-is1]++is)
else
fail.pp$
sep [ppi "Deriving for mutually recursive types with parameters not implemented yet:",
nest 4 $ ppiFSeq (map (fst.fst.snd) is1)]
-}
reduce1 (n,((p,ps),(s,mcode))) =
do _:>:ps' <- extendIEnv' [(p,(n,[]))] $ simplify s ps
--trace (pp (ps$$ps')) $ do
declare ((p,(n,ps')),(ps,(s,mcode)))
declare (i@(p,(n,ps')),(_,(s,mcode))) =
do methods <- posContext s mcode
let d = hsInstDecl s (Just n) ps' p (toDefs methods)
return (i,d)
simplify s ps =
do ns <- map (flip dictName' (Just s)) # freshlist (length ps)
unzipTyped # contextReduction'' (zipTyped (ns:>:ps))
--In progress: fix point iteration for mutually recursive types:
instContext is =
do is' <- mapM (instContext1 (map fst is)) is
if and (zipWith eqinst is is')
then return is
else instContext is'
instContext1 is (i@(p,(n,ctx)),j@(ps,(s,c))) =
do _:>:ctx' <- extendIEnv' is $ simplify s ps
return ((p,(n,ctx')),j)
instContext0 is = [((p,(n,[])),(ps,c))|(n,((p,ps),c))<-is]
extendIEnv' = extendIEnv . map (addInstKind ks)
+
If there was an instance for predicates , we could just nub and sort
and compare for equality . Since we only have , it 's a bit more clumpsy ...
If there was an Ord instance for predicates, we could just nub and sort
and compare for equality. Since we only have Eq, it's a bit more clumpsy...
-}
eqinst i1 i2 = eqctx (ctx i1) (ctx i2)
where
ctx ((_,(_,c)),_) = nub c
eqctx [] ps2 = null ps2
eqctx (p1:ps1) ps2 =
case partition (==p1) ps2 of
([p2],ps2') -> eqctx ps1 ps2'
_ -> False
| null | https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/old/tools/base/TI/TiDerivedInstances.hs | haskell | import IOExts(trace) -- debugging
Figuring out what the derived instances are, without generating the
derived code.
!!!
!!!
TODO: need fixed point interation for mutually recursive types!!
trace (pp (ps$$ps')) $ do
In progress: fix point iteration for mutually recursive types: | module TiDerivedInstances(derivedInstances) where
import HasBaseStruct
import HsDecl
import TI
import TiSolve(expandSynonyms)
import TiContextReduction(contextReduction'')
import TiInstanceDB(addInstKind)
import TiSCC(sccD)
import SrcLoc1
import Deriving(derive)
import FreeNamesBase()
import Data.Maybe(mapMaybe)
import Data.List(nub,partition)
import MUtils
import PrettyPrint
derivedInstances ks stdnames modmap env ds =
reduceInsts .
map inst0 .
concatMap (collectByFst.concatMap drv.mapMaybe basestruct) .
sccD . filter isBaseTypeDec $ ds
where
inst0 (cn,is) = [(n,((c t,map c ts),(s,code t)))|(n,(t,ts))<-is]
where c=app cn
s=srcLoc cn
code t=derive stdnames cn (definedTypeName t)
drv d =
case d of
HsNewTypeDecl s ctx t c cls -> drv' cls t [c]
HsDataDecl s ctx t cs cls -> drv' cls t cs
HsTypeDecl {} -> []
where
drv' cls t cons =
[(cl,(derivedInstName' modmap cl tn,(t,syn (conArgTypes=<<cons))))
|cl<-cls]
where tn=definedTypeName t
conArgTypes con =
case con of
app c t = hsTyCon c `hsTyApp` t
syn = tmap (expandSynonyms env)
isBaseTypeDec = maybe False isTypeDec . basestruct
isTypeDec d =
case d of
HsNewTypeDecl {} -> True
HsDataDecl {} -> True
HsTypeDecl {} -> True
_ -> False
reduceInsts [] = return []
reduceInsts ([i]:is) =
do i' <- reduce1 i
is' <- extendIEnv' [(fst i')] $ reduceInsts is
return (i':is')
reduceInsts (is1:is) =
do is1' <- mapM declare =<< instContext (instContext0 is1)
is' <- extendIEnv' (map fst is1') $ reduceInsts is
return (is1'++is')
old :
reduceInsts ( is1 : is ) =
if all ( null.freeTyvars.fst.fst.snd ) is1
then reduceInsts ( [ [ i]|i<-is1]++is )
else
fail.pp$
sep [ ppi " Deriving for mutually recursive types with parameters not implemented yet : " ,
nest 4 $ ppiFSeq ( map ( fst.fst.snd ) is1 ) ]
reduceInsts (is1:is) =
if all (null.freeTyvars.fst.fst.snd) is1
then reduceInsts ([[i]|i<-is1]++is)
else
fail.pp$
sep [ppi "Deriving for mutually recursive types with parameters not implemented yet:",
nest 4 $ ppiFSeq (map (fst.fst.snd) is1)]
-}
reduce1 (n,((p,ps),(s,mcode))) =
do _:>:ps' <- extendIEnv' [(p,(n,[]))] $ simplify s ps
declare ((p,(n,ps')),(ps,(s,mcode)))
declare (i@(p,(n,ps')),(_,(s,mcode))) =
do methods <- posContext s mcode
let d = hsInstDecl s (Just n) ps' p (toDefs methods)
return (i,d)
simplify s ps =
do ns <- map (flip dictName' (Just s)) # freshlist (length ps)
unzipTyped # contextReduction'' (zipTyped (ns:>:ps))
instContext is =
do is' <- mapM (instContext1 (map fst is)) is
if and (zipWith eqinst is is')
then return is
else instContext is'
instContext1 is (i@(p,(n,ctx)),j@(ps,(s,c))) =
do _:>:ctx' <- extendIEnv' is $ simplify s ps
return ((p,(n,ctx')),j)
instContext0 is = [((p,(n,[])),(ps,c))|(n,((p,ps),c))<-is]
extendIEnv' = extendIEnv . map (addInstKind ks)
+
If there was an instance for predicates , we could just nub and sort
and compare for equality . Since we only have , it 's a bit more clumpsy ...
If there was an Ord instance for predicates, we could just nub and sort
and compare for equality. Since we only have Eq, it's a bit more clumpsy...
-}
eqinst i1 i2 = eqctx (ctx i1) (ctx i2)
where
ctx ((_,(_,c)),_) = nub c
eqctx [] ps2 = null ps2
eqctx (p1:ps1) ps2 =
case partition (==p1) ps2 of
([p2],ps2') -> eqctx ps1 ps2'
_ -> False
|
f95f15934344af583470feb5b780d4556998f1fe7cdaee4181b98e3796820f33 | karen/haskell-book | ch17.hs | import Control.Applicative
import Data.Monoid
import Test.QuickCheck
import Test.QuickCheck.Checkers
import Test.QuickCheck.Classes
data List a =
Nil
| Cons a (List a)
deriving (Eq, Show)
instance Functor List where
fmap _ Nil = Nil
fmap f (Cons x xs) = Cons (f x) (fmap f xs)
( < * > ) flst lst = flatMap ( ` fmap ` lst ) flst
-- For each function from flst
fmap over lst
-- then concat them together
instance Applicative List where
pure x = Cons x Nil
Nil <*> _ = Nil
_ <*> Nil = Nil
(<*>) flst lst = flatMap (\f -> fmap f lst) flst
instance (Arbitrary a) => Arbitrary (List a) where
arbitrary = do
a <- arbitrary
elements [Nil, Cons a Nil]
instance Eq a => EqProp (List a) where
(=-=) = eq
newtype ZipList' a =
ZipList' (List a)
deriving (Eq, Show)
instance Eq a => EqProp (ZipList' a) where
xs =-= ys = xs' `eq` ys'
where xs' = let (ZipList' l) = xs
in take' 3000 l
ys' = let (ZipList' l) = ys
in take' 3000 l
instance Functor ZipList' where
fmap f (ZipList' xs) = ZipList' $ fmap f xs
instance Applicative ZipList' where
pure x = ZipList' (Cons x Nil)
(<*>) (ZipList' flst) (ZipList' lst) = ZipList' (zip' flst lst)
instance (Arbitrary a) => Arbitrary (ZipList' a) where
arbitrary = fmap ZipList' arbitrary
zip' :: List (t -> a) -> List t -> List a
zip' Nil _ = Nil
zip' _ Nil = Nil
zip' (Cons f fs) (Cons x xs) = Cons (f x) (zip' fs xs)
take' :: Int -> List a -> List a
take' 0 _ = Nil
take' _ Nil = Nil
take' n (Cons x xs) = Cons x (take' (n-1) xs)
append :: List a -> List a -> List a
append Nil ys = ys
append (Cons x xs) ys = Cons x $ xs `append` ys
fold :: (a->b->b) -> b -> List a -> b
fold _ b Nil = b
fold f b (Cons h t) = f h (fold f b t)
concat' :: List (List a) -> List a
concat' = fold append Nil
flatMap :: (a -> List b) -> List a -> List b
flatMap f as = concat' $ fmap f as
--------------------------------------------------------------------------------
newtype Identity a = Identity a deriving (Eq, Show)
instance Functor Identity where
fmap f (Identity x) = Identity $ f x
instance Applicative Identity where
pure x = Identity x
(<*>) (Identity f) x = fmap f x
instance Arbitrary a => Arbitrary (Identity a) where
arbitrary = do
x <- arbitrary
return $ Identity x
instance Eq a => EqProp (Identity a) where
(=-=) = eq
identityCheck = undefined :: (Identity (String, String, String))
--------------------------------------------------------------------------------
data Pair a = Pair a a deriving (Eq, Show)
instance Functor Pair where
fmap f (Pair x x') = Pair (f x) (f x')
instance Applicative Pair where
pure x = Pair x x
(<*>) (Pair f g) (Pair x x') = Pair (f x) (g x')
instance Arbitrary a => Arbitrary (Pair a) where
arbitrary = do
x <- arbitrary
y <- arbitrary
return $ Pair x y
instance Eq a => EqProp (Pair a) where
(=-=) = eq
pairCheck = undefined :: (Pair (String, String, String))
--------------------------------------------------------------------------------
data Two a b = Two a b deriving (Eq, Show)
instance Functor (Two a) where
fmap f (Two x y) = Two x (f y)
instance (Monoid a) => Applicative (Two a) where
pure x = Two mempty x
(<*>) (Two f g) (Two x y) = Two (x `mappend` f) (g y)
instance (Arbitrary a, Arbitrary b) => Arbitrary (Two a b) where
arbitrary = do
x <- arbitrary
y <- arbitrary
return $ Two x y
instance (Eq a, Eq b) => EqProp (Two a b) where
(=-=) = eq
twoCheck = undefined :: (Two (String, String, String) (String, String, String))
--------------------------------------------------------------------------------
data Three' a b = Three' a b b deriving (Eq, Show)
instance Functor (Three' a) where
fmap f (Three' x y y') = Three' x (f y) (f y')
instance (Monoid a) => Applicative (Three' a) where
pure x = Three' mempty x x
(<*>) (Three' a f g) (Three' a' x x') = Three' (a `mappend` a') (f x) (g x')
instance (Arbitrary a, Arbitrary b) => Arbitrary (Three' a b) where
arbitrary = do
x <- arbitrary
y <- arbitrary
z <- arbitrary
return $ Three' x y z
instance (Eq a, Eq b) => EqProp (Three' a b) where
(=-=) = eq
threeCheck = undefined :: (Three' (String, String, String) (String, String, String))
--------------------------------------------------------------------------------
main :: IO ()
main = do
quickBatch $ applicative (Cons (1:: Int, 2 :: Int, 3 :: Int) Nil)
quickBatch $ applicative (ZipList' (Cons (1:: Int, 2 :: Int, 3 :: Int) Nil))
quickBatch $ applicative identityCheck
quickBatch $ applicative pairCheck
quickBatch $ applicative twoCheck
quickBatch $ applicative threeCheck
| null | https://raw.githubusercontent.com/karen/haskell-book/90bb80ec3203fde68fc7fda1662d9fc8b509d179/src/ch17/ch17.hs | haskell | For each function from flst
then concat them together
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------ | import Control.Applicative
import Data.Monoid
import Test.QuickCheck
import Test.QuickCheck.Checkers
import Test.QuickCheck.Classes
data List a =
Nil
| Cons a (List a)
deriving (Eq, Show)
instance Functor List where
fmap _ Nil = Nil
fmap f (Cons x xs) = Cons (f x) (fmap f xs)
( < * > ) flst lst = flatMap ( ` fmap ` lst ) flst
fmap over lst
instance Applicative List where
pure x = Cons x Nil
Nil <*> _ = Nil
_ <*> Nil = Nil
(<*>) flst lst = flatMap (\f -> fmap f lst) flst
instance (Arbitrary a) => Arbitrary (List a) where
arbitrary = do
a <- arbitrary
elements [Nil, Cons a Nil]
instance Eq a => EqProp (List a) where
(=-=) = eq
newtype ZipList' a =
ZipList' (List a)
deriving (Eq, Show)
instance Eq a => EqProp (ZipList' a) where
xs =-= ys = xs' `eq` ys'
where xs' = let (ZipList' l) = xs
in take' 3000 l
ys' = let (ZipList' l) = ys
in take' 3000 l
instance Functor ZipList' where
fmap f (ZipList' xs) = ZipList' $ fmap f xs
instance Applicative ZipList' where
pure x = ZipList' (Cons x Nil)
(<*>) (ZipList' flst) (ZipList' lst) = ZipList' (zip' flst lst)
instance (Arbitrary a) => Arbitrary (ZipList' a) where
arbitrary = fmap ZipList' arbitrary
zip' :: List (t -> a) -> List t -> List a
zip' Nil _ = Nil
zip' _ Nil = Nil
zip' (Cons f fs) (Cons x xs) = Cons (f x) (zip' fs xs)
take' :: Int -> List a -> List a
take' 0 _ = Nil
take' _ Nil = Nil
take' n (Cons x xs) = Cons x (take' (n-1) xs)
append :: List a -> List a -> List a
append Nil ys = ys
append (Cons x xs) ys = Cons x $ xs `append` ys
fold :: (a->b->b) -> b -> List a -> b
fold _ b Nil = b
fold f b (Cons h t) = f h (fold f b t)
concat' :: List (List a) -> List a
concat' = fold append Nil
flatMap :: (a -> List b) -> List a -> List b
flatMap f as = concat' $ fmap f as
newtype Identity a = Identity a deriving (Eq, Show)
instance Functor Identity where
fmap f (Identity x) = Identity $ f x
instance Applicative Identity where
pure x = Identity x
(<*>) (Identity f) x = fmap f x
instance Arbitrary a => Arbitrary (Identity a) where
arbitrary = do
x <- arbitrary
return $ Identity x
instance Eq a => EqProp (Identity a) where
(=-=) = eq
identityCheck = undefined :: (Identity (String, String, String))
data Pair a = Pair a a deriving (Eq, Show)
instance Functor Pair where
fmap f (Pair x x') = Pair (f x) (f x')
instance Applicative Pair where
pure x = Pair x x
(<*>) (Pair f g) (Pair x x') = Pair (f x) (g x')
instance Arbitrary a => Arbitrary (Pair a) where
arbitrary = do
x <- arbitrary
y <- arbitrary
return $ Pair x y
instance Eq a => EqProp (Pair a) where
(=-=) = eq
pairCheck = undefined :: (Pair (String, String, String))
data Two a b = Two a b deriving (Eq, Show)
instance Functor (Two a) where
fmap f (Two x y) = Two x (f y)
instance (Monoid a) => Applicative (Two a) where
pure x = Two mempty x
(<*>) (Two f g) (Two x y) = Two (x `mappend` f) (g y)
instance (Arbitrary a, Arbitrary b) => Arbitrary (Two a b) where
arbitrary = do
x <- arbitrary
y <- arbitrary
return $ Two x y
instance (Eq a, Eq b) => EqProp (Two a b) where
(=-=) = eq
twoCheck = undefined :: (Two (String, String, String) (String, String, String))
data Three' a b = Three' a b b deriving (Eq, Show)
instance Functor (Three' a) where
fmap f (Three' x y y') = Three' x (f y) (f y')
instance (Monoid a) => Applicative (Three' a) where
pure x = Three' mempty x x
(<*>) (Three' a f g) (Three' a' x x') = Three' (a `mappend` a') (f x) (g x')
instance (Arbitrary a, Arbitrary b) => Arbitrary (Three' a b) where
arbitrary = do
x <- arbitrary
y <- arbitrary
z <- arbitrary
return $ Three' x y z
instance (Eq a, Eq b) => EqProp (Three' a b) where
(=-=) = eq
threeCheck = undefined :: (Three' (String, String, String) (String, String, String))
main :: IO ()
main = do
quickBatch $ applicative (Cons (1:: Int, 2 :: Int, 3 :: Int) Nil)
quickBatch $ applicative (ZipList' (Cons (1:: Int, 2 :: Int, 3 :: Int) Nil))
quickBatch $ applicative identityCheck
quickBatch $ applicative pairCheck
quickBatch $ applicative twoCheck
quickBatch $ applicative threeCheck
|
618e7e10a6d745e97b3ab35b4082a6ee29b584075942a6e716050f55deae56d4 | archimag/rulisp | pref.lisp | ;;;; pref.lisp
;;;;
This file is part of the rulisp application , released under GNU Affero General Public License , Version 3.0
;;;; See file COPYING for details.
;;;;
Author : < >
(defpackage :rulisp.preferences
(:use :cl)
(:export #:*rulisp-path*
#:*skindir*
#:*rulisp-db*
#:*host*
#:*cookie-cipher-key*
#:*noreply-mail-account*
#:*vardir*
#:*cachedir*
#:*default-skin*
#:*pcl-dir*
#:*wiki-dir*
#:*pcl-snapshot-url*
#:*pcl-snapshot-dir*
#:*pcl-load-snapshot-p*
#:*jscl-snapshot-url*
#:*jscl-snapshot-dir*
#:*jscl-load-snapshot-p*
#:*corefonts-dir*
#:*cm-fonts-dir*))
(in-package :rulisp.preferences)
(defparameter *vardir* #P"/var/rulisp/")
(defparameter *cachedir* #P"/var/cache/rulisp/")
(defparameter *rulisp-path* (asdf:component-pathname (asdf:find-system :rulisp)))
(defparameter *skindir* (merge-pathnames "static/skins/" *rulisp-path*))
(defparameter *default-theme* "archimag")
(defparameter *rulisp-db* '("rulisp" "lisp" "123" "localhost"))
(defparameter *host* "localhost:8080")
(defparameter *cookie-cipher-key* (ironclad:ascii-string-to-byte-array "Specify the secure key"))
(defparameter *noreply-mail-account* "")
(defparameter *default-skin* "fine")
(defparameter *pcl-dir* #P"/var/rulisp/pcl/dwiki/")
(defparameter *pcl-snapshot-url* #u"")
(defparameter *pcl-snapshot-dir* #P"/var/rulisp/pcl/")
(defparameter *pcl-load-snapshot-p* nil)
(defparameter *jscl-snapshot-url* "")
(defparameter *jscl-snapshot-dir* #P"/var/rulisp/")
(defparameter *jscl-load-snapshot-p* t)
(defparameter *wiki-dir* #P"/var/rulisp/wiki/")
(defparameter *corefonts-dir* #P"/usr/share/fonts/corefonts/")
(defparameter *cm-fonts-dir* #P"/usr/share/fonts/cm/")
| null | https://raw.githubusercontent.com/archimag/rulisp/2af0d92066572c4665d14dc3ee001c0c5ff84e84/pref.lisp | lisp | pref.lisp
See file COPYING for details.
| This file is part of the rulisp application , released under GNU Affero General Public License , Version 3.0
Author : < >
(defpackage :rulisp.preferences
(:use :cl)
(:export #:*rulisp-path*
#:*skindir*
#:*rulisp-db*
#:*host*
#:*cookie-cipher-key*
#:*noreply-mail-account*
#:*vardir*
#:*cachedir*
#:*default-skin*
#:*pcl-dir*
#:*wiki-dir*
#:*pcl-snapshot-url*
#:*pcl-snapshot-dir*
#:*pcl-load-snapshot-p*
#:*jscl-snapshot-url*
#:*jscl-snapshot-dir*
#:*jscl-load-snapshot-p*
#:*corefonts-dir*
#:*cm-fonts-dir*))
(in-package :rulisp.preferences)
(defparameter *vardir* #P"/var/rulisp/")
(defparameter *cachedir* #P"/var/cache/rulisp/")
(defparameter *rulisp-path* (asdf:component-pathname (asdf:find-system :rulisp)))
(defparameter *skindir* (merge-pathnames "static/skins/" *rulisp-path*))
(defparameter *default-theme* "archimag")
(defparameter *rulisp-db* '("rulisp" "lisp" "123" "localhost"))
(defparameter *host* "localhost:8080")
(defparameter *cookie-cipher-key* (ironclad:ascii-string-to-byte-array "Specify the secure key"))
(defparameter *noreply-mail-account* "")
(defparameter *default-skin* "fine")
(defparameter *pcl-dir* #P"/var/rulisp/pcl/dwiki/")
(defparameter *pcl-snapshot-url* #u"")
(defparameter *pcl-snapshot-dir* #P"/var/rulisp/pcl/")
(defparameter *pcl-load-snapshot-p* nil)
(defparameter *jscl-snapshot-url* "")
(defparameter *jscl-snapshot-dir* #P"/var/rulisp/")
(defparameter *jscl-load-snapshot-p* t)
(defparameter *wiki-dir* #P"/var/rulisp/wiki/")
(defparameter *corefonts-dir* #P"/usr/share/fonts/corefonts/")
(defparameter *cm-fonts-dir* #P"/usr/share/fonts/cm/")
|
db39a070e5964ef633093233421606849cc6326223f00b1c6bb728d6f5a902c3 | esl/MongooseIM | service_mongoose_system_metrics_SUITE.erl | -module(service_mongoose_system_metrics_SUITE).
-compile([export_all, nowarn_export_all]).
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
-define(SERVER_URL, ":8765").
-define(ETS_TABLE, qs).
-define(TRACKING_ID, "UA-151671255-2").
-define(TRACKING_ID_CI, "UA-151671255-1").
-define(TRACKING_ID_EXTRA, "UA-EXTRA-TRACKING-ID").
-record(event, {
cid = "",
tid = "",
ec = "",
ea = "",
ev = "",
el = "" }).
-import(distributed_helper, [mim/0, mim2/0, mim3/0, rpc/4,
require_rpc_nodes/1
]).
-import(component_helper, [connect_component/1,
disconnect_component/2,
spec/2,
common/1]).
-import(domain_helper, [host_type/0]).
-import(config_parser_helper, [mod_config/2, config/2]).
suite() ->
require_rpc_nodes([mim]).
all() ->
[
system_metrics_are_not_reported_when_not_allowed,
periodic_report_available,
all_clustered_mongooses_report_the_same_client_id,
system_metrics_are_reported_to_google_analytics_when_mim_starts,
system_metrics_are_reported_to_configurable_google_analytics,
system_metrics_are_reported_to_a_json_file,
mongoose_version_is_reported,
cluster_uptime_is_reported,
xmpp_components_are_reported,
api_are_reported,
transport_mechanisms_are_reported,
outgoing_pools_are_reported,
xmpp_stanzas_counts_are_reported,
config_type_is_reported,
{group, module_opts},
{group, log_transparency}
].
groups() ->
[
{module_opts, [], [
module_opts_are_reported,
rdbms_module_opts_are_reported
]},
{log_transparency, [], [
just_removed_from_config_logs_question,
in_config_unmodified_logs_request_for_agreement,
in_config_with_explicit_no_report_goes_off_silently,
in_config_with_explicit_reporting_goes_on_silently
]}
].
-define(APPS, [inets, crypto, ssl, ranch, cowlib, cowboy]).
%%--------------------------------------------------------------------
%% Suite configuration
%%--------------------------------------------------------------------
init_per_suite(Config) ->
[ {ok, _} = application:ensure_all_started(App) || App <- ?APPS ],
http_helper:start(8765, "/[...]", fun handler_init/1),
Config1 = escalus:init_per_suite(Config),
Config2 = dynamic_services:save_services([mim(), mim2()], Config1),
ejabberd_node_utils:init(Config2).
end_per_suite(Config) ->
http_helper:stop(),
dynamic_services:restore_services(Config),
escalus:end_per_suite(Config).
%%--------------------------------------------------------------------
Init & teardown
%%--------------------------------------------------------------------
init_per_group(module_opts, Config) ->
dynamic_modules:save_modules(host_type(), Config);
init_per_group(log_transparency, Config) ->
logger_ct_backend:start(),
logger_ct_backend:capture(warning),
Config;
init_per_group(_GroupName, Config) ->
Config.
end_per_group(module_opts, Config) ->
dynamic_modules:restore_modules(Config);
end_per_group(log_transparency, Config) ->
logger_ct_backend:stop_capture(),
Config;
end_per_group(_GroupName, Config) ->
Config.
init_per_testcase(system_metrics_are_not_reported_when_not_allowed, Config) ->
create_events_collection(),
disable_system_metrics(mim()),
delete_prev_client_id(mim()),
Config;
init_per_testcase(all_clustered_mongooses_report_the_same_client_id, Config) ->
create_events_collection(),
distributed_helper:add_node_to_cluster(mim2(), Config),
enable_system_metrics(mim()),
enable_system_metrics(mim2()),
Config;
init_per_testcase(system_metrics_are_reported_to_configurable_google_analytics, Config) ->
create_events_collection(),
enable_system_metrics_with_configurable_tracking_id(mim()),
Config;
init_per_testcase(xmpp_components_are_reported, Config) ->
create_events_collection(),
Config1 = get_components(common(Config), Config),
enable_system_metrics(mim()),
Config1;
init_per_testcase(xmpp_stanzas_counts_are_reported = CN, Config) ->
create_events_collection(),
enable_system_metrics(mim()),
Config1 = escalus:create_users(Config, escalus:get_users([alice, bob])),
escalus:init_per_testcase(CN, Config1);
init_per_testcase(rdbms_module_opts_are_reported = CN, Config) ->
case mongoose_helper:is_rdbms_enabled(host_type()) of
false ->
{skip, "RDBMS is not available"};
true ->
create_events_collection(),
dynamic_modules:ensure_modules(host_type(), required_modules(CN)),
enable_system_metrics(mim()),
Config
end;
init_per_testcase(module_opts_are_reported = CN, Config) ->
create_events_collection(),
dynamic_modules:ensure_modules(host_type(), required_modules(CN)),
enable_system_metrics(mim()),
Config;
init_per_testcase(_TestcaseName, Config) ->
create_events_collection(),
enable_system_metrics(mim()),
Config.
end_per_testcase(system_metrics_are_not_reported_when_not_allowed, Config) ->
clear_events_collection(),
delete_prev_client_id(mim()),
Config;
end_per_testcase(all_clustered_mongooses_report_the_same_client_id , Config) ->
clear_events_collection(),
delete_prev_client_id(mim()),
Nodes = [mim(), mim2()],
[ begin delete_prev_client_id(Node), disable_system_metrics(Node) end || Node <- Nodes ],
distributed_helper:remove_node_from_cluster(mim2(), Config),
Config;
end_per_testcase(xmpp_stanzas_counts_are_reported = CN, Config) ->
clear_events_collection(),
disable_system_metrics(mim()),
escalus:delete_users(Config, escalus:get_users([alice, bob])),
escalus:end_per_testcase(CN, Config);
end_per_testcase(_TestcaseName, Config) ->
clear_events_collection(),
disable_system_metrics(mim()),
delete_prev_client_id(mim()),
Config.
%%--------------------------------------------------------------------
%% Tests
%%--------------------------------------------------------------------
system_metrics_are_not_reported_when_not_allowed(_Config) ->
true = system_metrics_service_is_disabled(mim()).
periodic_report_available(_Config) ->
ReportsNumber = get_events_collection_size(),
mongoose_helper:wait_until(
fun() ->
NewReportsNumber = get_events_collection_size(),
NewReportsNumber > ReportsNumber + 1
end,
true).
all_clustered_mongooses_report_the_same_client_id(_Config) ->
mongoose_helper:wait_until(fun is_host_count_reported/0, true),
all_event_have_the_same_client_id().
system_metrics_are_reported_to_google_analytics_when_mim_starts(_Config) ->
mongoose_helper:wait_until(fun is_host_count_reported/0, true),
mongoose_helper:wait_until(fun are_modules_reported/0, true),
events_are_reported_to_primary_tracking_id(),
all_event_have_the_same_client_id().
system_metrics_are_reported_to_configurable_google_analytics(_Config) ->
mongoose_helper:wait_until(fun is_host_count_reported/0, true),
mongoose_helper:wait_until(fun are_modules_reported/0, true),
events_are_reported_to_both_tracking_ids(),
all_event_have_the_same_client_id().
system_metrics_are_reported_to_a_json_file(_Config) ->
ReportFilePath = rpc(mim(), mongoose_system_metrics_file, location, []),
ReportLastModified = rpc(mim(), filelib, last_modified, [ReportFilePath]),
Fun = fun() ->
ReportLastModified < rpc(mim(), filelib, last_modified, [ReportFilePath])
end,
mongoose_helper:wait_until(Fun, true),
%% now we read the content of the file and check if it's a valid JSON
{ok, File} = rpc(mim(), file, read_file, [ReportFilePath]),
jiffy:decode(File).
module_opts_are_reported(_Config) ->
mongoose_helper:wait_until(fun are_modules_reported/0, true),
Backend = mongoose_helper:mnesia_or_rdbms_backend(),
check_module_backend(mod_bosh, mnesia),
check_module_backend(mod_event_pusher, push),
check_module_backend(mod_event_pusher_push, Backend),
check_module_backend(mod_http_upload, s3),
check_module_backend(mod_last, Backend),
check_module_backend(mod_muc, Backend),
check_module_backend(mod_muc_light, Backend),
check_module_backend(mod_offline, Backend),
check_module_backend(mod_privacy, Backend),
check_module_backend(mod_private, Backend),
check_module_backend(mod_pubsub, Backend),
check_module_opt(mod_push_service_mongoosepush, api_version, <<"\"v3\"">>),
check_module_backend(mod_roster, Backend),
check_module_backend(mod_vcard, Backend).
rdbms_module_opts_are_reported(_Config) ->
mongoose_helper:wait_until(fun are_modules_reported/0, true),
check_module_backend(mod_auth_token, rdbms),
check_module_backend(mod_inbox, rdbms),
check_module_backend(mod_mam, rdbms).
check_module_backend(Module, Backend) ->
check_module_opt(Module, backend, atom_to_binary(Backend)).
mongoose_version_is_reported(_Config) ->
mongoose_helper:wait_until(fun is_mongoose_version_reported/0, true).
cluster_uptime_is_reported(_Config) ->
mongoose_helper:wait_until(fun is_cluster_uptime_reported/0, true).
xmpp_components_are_reported(Config) ->
CompOpts = ?config(component1, Config),
{Component, Addr, _} = connect_component(CompOpts),
mongoose_helper:wait_until(fun are_xmpp_components_reported/0, true),
mongoose_helper:wait_until(fun more_than_one_component_is_reported/0, true),
disconnect_component(Component, Addr).
api_are_reported(_Config) ->
mongoose_helper:wait_until(fun is_api_reported/0, true).
transport_mechanisms_are_reported(_Config) ->
mongoose_helper:wait_until(fun are_transport_mechanisms_reported/0, true).
outgoing_pools_are_reported(_Config) ->
mongoose_helper:wait_until(fun are_outgoing_pools_reported/0, true).
xmpp_stanzas_counts_are_reported(Config) ->
escalus:story(Config, [{alice,1}, {bob,1}], fun(Alice, Bob) ->
mongoose_helper:wait_until(fun is_message_count_reported/0, true),
mongoose_helper:wait_until(fun is_iq_count_reported/0, true),
Sent = get_metric_value(<<"xmppMessageSent">>),
Received = get_metric_value(<<"xmppMessageReceived">>),
escalus:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi">>)),
escalus:assert(is_chat_message, [<<"Hi">>], escalus:wait_for_stanza(Bob)),
F = fun() -> assert_message_count_is_incremented(Sent, Received) end,
mongoose_helper:wait_until(F, ok)
end).
config_type_is_reported(_Config) ->
mongoose_helper:wait_until(fun is_config_type_reported/0, true).
just_removed_from_config_logs_question(_Config) ->
disable_system_metrics(mim3()),
%% WHEN
Result = distributed_helper:rpc(
mim3(), service_mongoose_system_metrics, verify_if_configured, []),
%% THEN
?assertEqual(ignore, Result).
in_config_unmodified_logs_request_for_agreement(_Config) ->
%% WHEN
disable_system_metrics(mim()),
logger_ct_backend:capture(warning),
enable_system_metrics(mim()),
%% THEN
FilterFun = fun(_, Msg) ->
re:run(Msg, "MongooseIM docs", [global]) /= nomatch
end,
mongoose_helper:wait_until(fun() -> length(logger_ct_backend:recv(FilterFun)) end, 1),
%% CLEAN
logger_ct_backend:stop_capture(),
disable_system_metrics(mim()).
in_config_with_explicit_no_report_goes_off_silently(_Config) ->
%% WHEN
logger_ct_backend:capture(warning),
start_system_metrics_service(mim(), #{report => false}),
logger_ct_backend:stop_capture(),
%% THEN
FilterFun = fun(warning, Msg) ->
re:run(Msg, "MongooseIM docs", [global]) /= nomatch;
(_,_) -> false
end,
[] = logger_ct_backend:recv(FilterFun),
%% CLEAN
disable_system_metrics(mim()).
in_config_with_explicit_reporting_goes_on_silently(_Config) ->
%% WHEN
logger_ct_backend:capture(warning),
start_system_metrics_service(mim(), #{report => true}),
logger_ct_backend:stop_capture(),
%% THEN
FilterFun = fun(warning, Msg) ->
re:run(Msg, "MongooseIM docs", [global]) /= nomatch;
(_,_) -> false
end,
[] = logger_ct_backend:recv(FilterFun),
%% CLEAN
disable_system_metrics(mim()).
%%--------------------------------------------------------------------
%% Helpers
%%--------------------------------------------------------------------
required_modules(CaseName) ->
lists:filter(fun({Module, _Opts}) -> is_module_supported(Module) end,
modules_to_test(CaseName)).
modules_to_test(module_opts_are_reported) ->
Backend = mongoose_helper:mnesia_or_rdbms_backend(),
[required_module(mod_bosh),
required_module(mod_event_pusher,
#{push => config([modules, mod_event_pusher, push], #{backend => Backend})}),
required_module(mod_http_upload, s3),
required_module(mod_last, Backend),
required_module(mod_muc, Backend),
required_module(mod_muc_light, Backend),
required_module(mod_offline, Backend),
required_module(mod_privacy, Backend),
required_module(mod_private, Backend),
required_module(mod_pubsub, Backend),
required_module(mod_push_service_mongoosepush),
required_module(mod_roster, Backend),
required_module(mod_vcard, Backend)];
modules_to_test(rdbms_module_opts_are_reported) ->
[required_module(mod_auth_token),
required_module(mod_inbox),
required_module(mod_mam)].
required_module(Module) ->
required_module(Module, #{}).
required_module(Module, Backend) when is_atom(Backend) ->
{Module, mod_config(Module, #{backend => Backend})};
required_module(Module, Opts) ->
{Module, mod_config(Module, Opts)}.
check_module_opt(Module, Key, Value) ->
case is_module_supported(Module) of
true ->
?assertEqual(true, is_module_opt_reported(Module, Key, Value));
false ->
ct:log("Skipping unsupported module ~p", [Module])
end.
is_module_supported(Module) ->
is_host_type_static() orelse supports_dynamic_domains(Module).
is_host_type_static() ->
rpc(mim(), mongoose_domain_core, is_static, [host_type()]).
supports_dynamic_domains(Module) ->
rpc(mim(), gen_mod, does_module_support, [Module, dynamic_domains]).
all_event_have_the_same_client_id() ->
Tab = ets:tab2list(?ETS_TABLE),
UniqueSortedTab = lists:usort([Cid || #event{cid = Cid} <- Tab]),
1 = length(UniqueSortedTab).
is_host_count_reported() ->
is_in_table(<<"hosts">>).
are_modules_reported() ->
is_in_table(<<"module">>).
is_in_table(EventCategory) ->
Tab = ets:tab2list(?ETS_TABLE),
lists:any(
fun(#event{ec = EC}) ->
verify_category(EC, EventCategory)
end, Tab).
verify_category(EC, <<"module">>) ->
Result = re:run(EC, "^mod_.*"),
case Result of
{match, _Captured} -> true;
nomatch -> false
end;
verify_category(EC, EC) ->
true;
verify_category(_EC, _EventCategory) ->
false.
get_events_collection_size() ->
ets:info(?ETS_TABLE, size).
enable_system_metrics(Node) ->
enable_system_metrics(Node, #{initial_report => 100, periodic_report => 100}).
enable_system_metrics_with_configurable_tracking_id(Node) ->
enable_system_metrics(Node, #{initial_report => 100, periodic_report => 100,
tracking_id => ?TRACKING_ID_EXTRA}).
enable_system_metrics(Node, Opts) ->
UrlArgs = [google_analytics_url, ?SERVER_URL],
ok = mongoose_helper:successful_rpc(Node, mongoose_config, set_opt, UrlArgs),
start_system_metrics_service(Node, Opts).
start_system_metrics_service(Node, ExtraOpts) ->
Opts = config([services, service_mongoose_system_metrics], ExtraOpts),
dynamic_services:ensure_started(Node, service_mongoose_system_metrics, Opts).
disable_system_metrics(Node) ->
dynamic_services:ensure_stopped(Node, service_mongoose_system_metrics),
mongoose_helper:successful_rpc(Node, mongoose_config, unset_opt, [ google_analytics_url ]).
delete_prev_client_id(Node) ->
mongoose_helper:successful_rpc(Node, mnesia, delete_table, [service_mongoose_system_metrics]).
create_events_collection() ->
ets:new(?ETS_TABLE, [duplicate_bag, named_table, public]).
clear_events_collection() ->
ets:delete_all_objects(?ETS_TABLE).
system_metrics_service_is_enabled(Node) ->
Pid = distributed_helper:rpc(Node, erlang, whereis, [service_mongoose_system_metrics]),
erlang:is_pid(Pid).
system_metrics_service_is_disabled(Node) ->
not system_metrics_service_is_enabled(Node).
events_are_reported_to_primary_tracking_id() ->
events_are_reported_to_tracking_ids([primary_tracking_id()]).
events_are_reported_to_both_tracking_ids() ->
events_are_reported_to_tracking_ids([primary_tracking_id(), ?TRACKING_ID_EXTRA]).
primary_tracking_id() ->
case os:getenv("CI") of
"true" -> ?TRACKING_ID_CI;
_ -> ?TRACKING_ID
end.
events_are_reported_to_tracking_ids(ConfiguredTrackingIds) ->
Tab = ets:tab2list(?ETS_TABLE),
ActualTrackingIds = lists:usort([Tid || #event{tid = Tid} <- Tab]),
ExpectedTrackingIds = lists:sort([list_to_binary(Tid) || Tid <- ConfiguredTrackingIds]),
?assertEqual(ExpectedTrackingIds, ActualTrackingIds).
is_feature_reported(EventCategory, EventAction) ->
length(match_events(EventCategory, EventAction)) > 0.
is_feature_reported(EventCategory, EventAction, EventLabel) ->
length(match_events(EventCategory, EventAction, EventLabel)) > 0.
is_module_backend_reported(Module, Backend) ->
is_feature_reported(atom_to_binary(Module), <<"backend">>, atom_to_binary(Backend)).
is_module_opt_reported(Module, Key, Value) ->
is_feature_reported(atom_to_binary(Module), atom_to_binary(Key), Value).
is_mongoose_version_reported() ->
is_feature_reported(<<"cluster">>, <<"mim_version">>).
is_cluster_uptime_reported() ->
is_feature_reported(<<"cluster">>, <<"uptime">>).
are_xmpp_components_reported() ->
is_feature_reported(<<"cluster">>, <<"number_of_components">>).
is_config_type_reported() ->
IsToml = is_feature_reported(<<"cluster">>, <<"config_type">>, <<"toml">>),
IsCfg = is_feature_reported(<<"cluster">>, <<"config_type">>, <<"cfg">>),
IsToml orelse IsCfg.
is_api_reported() ->
is_in_table(<<"http_api">>).
are_transport_mechanisms_reported() ->
is_in_table(<<"transport_mechanism">>).
are_outgoing_pools_reported() ->
is_in_table(<<"outgoing_pools">>).
is_iq_count_reported() ->
is_in_table(<<"xmppIqSent">>).
is_message_count_reported() ->
is_in_table(<<"xmppMessageSent">>) andalso is_in_table(<<"xmppMessageReceived">>).
assert_message_count_is_incremented(Sent, Received) ->
assert_increment(<<"xmppMessageSent">>, Sent),
assert_increment(<<"xmppMessageReceived">>, Received).
assert_increment(EventCategory, InitialValue) ->
Events = match_events(EventCategory, integer_to_binary(InitialValue + 1), <<$1>>),
expect exactly one event with an increment of 1
get_metric_value(EventCategory) ->
[#event{ea = Value} | _] = match_events(EventCategory),
binary_to_integer(Value).
more_than_one_component_is_reported() ->
Events = match_events(<<"cluster">>, <<"number_of_components">>),
lists:any(fun(#event{el = EL}) ->
binary_to_integer(EL) > 0
end, Events).
match_events(EC) ->
ets:match_object(?ETS_TABLE, #event{ec = EC, _ = '_'}).
match_events(EC, EA) ->
ets:match_object(?ETS_TABLE, #event{ec = EC, ea = EA, _ = '_'}).
match_events(EC, EA, EL) ->
ets:match_object(?ETS_TABLE, #event{ec = EC, ea = EA, el = EL, _ = '_'}).
%%--------------------------------------------------------------------
%% Cowboy handlers
%%--------------------------------------------------------------------
handler_init(Req0) ->
{ok, Body, Req} = cowboy_req:read_body(Req0),
StrEvents = string:split(Body, "\n", all),
lists:map(
fun(StrEvent) ->
Event = str_to_event(StrEvent),
TODO there is a race condition when table is not available
ets:insert(?ETS_TABLE, Event)
end, StrEvents),
Req1 = cowboy_req:reply(200, #{}, <<"">>, Req),
{ok, Req1, no_state}.
str_to_event(Qs) ->
StrParams = string:split(Qs, "&", all),
Params = lists:map(
fun(StrParam) ->
[StrKey, StrVal] = string:split(StrParam, "="),
{binary_to_atom(StrKey, utf8), StrVal}
end, StrParams),
#event{
cid = get_el(cid, Params),
tid = get_el(tid, Params),
ec = get_el(ec, Params),
ea = get_el(ea, Params),
el = get_el(el, Params),
ev = get_el(ev, Params)
}.
get_el(Key, Proplist) ->
proplists:get_value(Key, Proplist, undef).
get_components(Opts, Config) ->
Components = [component1, component2, vjud_component],
[ {C, Opts ++ spec(C, Config)} || C <- Components ] ++ Config.
| null | https://raw.githubusercontent.com/esl/MongooseIM/c213d44a0ccdf38fcec5e0d5b2ccab70cbb9407f/big_tests/tests/service_mongoose_system_metrics_SUITE.erl | erlang | --------------------------------------------------------------------
Suite configuration
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
Tests
--------------------------------------------------------------------
now we read the content of the file and check if it's a valid JSON
WHEN
THEN
WHEN
THEN
CLEAN
WHEN
THEN
CLEAN
WHEN
THEN
CLEAN
--------------------------------------------------------------------
Helpers
--------------------------------------------------------------------
--------------------------------------------------------------------
Cowboy handlers
-------------------------------------------------------------------- | -module(service_mongoose_system_metrics_SUITE).
-compile([export_all, nowarn_export_all]).
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
-define(SERVER_URL, ":8765").
-define(ETS_TABLE, qs).
-define(TRACKING_ID, "UA-151671255-2").
-define(TRACKING_ID_CI, "UA-151671255-1").
-define(TRACKING_ID_EXTRA, "UA-EXTRA-TRACKING-ID").
-record(event, {
cid = "",
tid = "",
ec = "",
ea = "",
ev = "",
el = "" }).
-import(distributed_helper, [mim/0, mim2/0, mim3/0, rpc/4,
require_rpc_nodes/1
]).
-import(component_helper, [connect_component/1,
disconnect_component/2,
spec/2,
common/1]).
-import(domain_helper, [host_type/0]).
-import(config_parser_helper, [mod_config/2, config/2]).
suite() ->
require_rpc_nodes([mim]).
all() ->
[
system_metrics_are_not_reported_when_not_allowed,
periodic_report_available,
all_clustered_mongooses_report_the_same_client_id,
system_metrics_are_reported_to_google_analytics_when_mim_starts,
system_metrics_are_reported_to_configurable_google_analytics,
system_metrics_are_reported_to_a_json_file,
mongoose_version_is_reported,
cluster_uptime_is_reported,
xmpp_components_are_reported,
api_are_reported,
transport_mechanisms_are_reported,
outgoing_pools_are_reported,
xmpp_stanzas_counts_are_reported,
config_type_is_reported,
{group, module_opts},
{group, log_transparency}
].
groups() ->
[
{module_opts, [], [
module_opts_are_reported,
rdbms_module_opts_are_reported
]},
{log_transparency, [], [
just_removed_from_config_logs_question,
in_config_unmodified_logs_request_for_agreement,
in_config_with_explicit_no_report_goes_off_silently,
in_config_with_explicit_reporting_goes_on_silently
]}
].
-define(APPS, [inets, crypto, ssl, ranch, cowlib, cowboy]).
init_per_suite(Config) ->
[ {ok, _} = application:ensure_all_started(App) || App <- ?APPS ],
http_helper:start(8765, "/[...]", fun handler_init/1),
Config1 = escalus:init_per_suite(Config),
Config2 = dynamic_services:save_services([mim(), mim2()], Config1),
ejabberd_node_utils:init(Config2).
end_per_suite(Config) ->
http_helper:stop(),
dynamic_services:restore_services(Config),
escalus:end_per_suite(Config).
Init & teardown
init_per_group(module_opts, Config) ->
dynamic_modules:save_modules(host_type(), Config);
init_per_group(log_transparency, Config) ->
logger_ct_backend:start(),
logger_ct_backend:capture(warning),
Config;
init_per_group(_GroupName, Config) ->
Config.
end_per_group(module_opts, Config) ->
dynamic_modules:restore_modules(Config);
end_per_group(log_transparency, Config) ->
logger_ct_backend:stop_capture(),
Config;
end_per_group(_GroupName, Config) ->
Config.
init_per_testcase(system_metrics_are_not_reported_when_not_allowed, Config) ->
create_events_collection(),
disable_system_metrics(mim()),
delete_prev_client_id(mim()),
Config;
init_per_testcase(all_clustered_mongooses_report_the_same_client_id, Config) ->
create_events_collection(),
distributed_helper:add_node_to_cluster(mim2(), Config),
enable_system_metrics(mim()),
enable_system_metrics(mim2()),
Config;
init_per_testcase(system_metrics_are_reported_to_configurable_google_analytics, Config) ->
create_events_collection(),
enable_system_metrics_with_configurable_tracking_id(mim()),
Config;
init_per_testcase(xmpp_components_are_reported, Config) ->
create_events_collection(),
Config1 = get_components(common(Config), Config),
enable_system_metrics(mim()),
Config1;
init_per_testcase(xmpp_stanzas_counts_are_reported = CN, Config) ->
create_events_collection(),
enable_system_metrics(mim()),
Config1 = escalus:create_users(Config, escalus:get_users([alice, bob])),
escalus:init_per_testcase(CN, Config1);
init_per_testcase(rdbms_module_opts_are_reported = CN, Config) ->
case mongoose_helper:is_rdbms_enabled(host_type()) of
false ->
{skip, "RDBMS is not available"};
true ->
create_events_collection(),
dynamic_modules:ensure_modules(host_type(), required_modules(CN)),
enable_system_metrics(mim()),
Config
end;
init_per_testcase(module_opts_are_reported = CN, Config) ->
create_events_collection(),
dynamic_modules:ensure_modules(host_type(), required_modules(CN)),
enable_system_metrics(mim()),
Config;
init_per_testcase(_TestcaseName, Config) ->
create_events_collection(),
enable_system_metrics(mim()),
Config.
end_per_testcase(system_metrics_are_not_reported_when_not_allowed, Config) ->
clear_events_collection(),
delete_prev_client_id(mim()),
Config;
end_per_testcase(all_clustered_mongooses_report_the_same_client_id , Config) ->
clear_events_collection(),
delete_prev_client_id(mim()),
Nodes = [mim(), mim2()],
[ begin delete_prev_client_id(Node), disable_system_metrics(Node) end || Node <- Nodes ],
distributed_helper:remove_node_from_cluster(mim2(), Config),
Config;
end_per_testcase(xmpp_stanzas_counts_are_reported = CN, Config) ->
clear_events_collection(),
disable_system_metrics(mim()),
escalus:delete_users(Config, escalus:get_users([alice, bob])),
escalus:end_per_testcase(CN, Config);
end_per_testcase(_TestcaseName, Config) ->
clear_events_collection(),
disable_system_metrics(mim()),
delete_prev_client_id(mim()),
Config.
system_metrics_are_not_reported_when_not_allowed(_Config) ->
true = system_metrics_service_is_disabled(mim()).
periodic_report_available(_Config) ->
ReportsNumber = get_events_collection_size(),
mongoose_helper:wait_until(
fun() ->
NewReportsNumber = get_events_collection_size(),
NewReportsNumber > ReportsNumber + 1
end,
true).
all_clustered_mongooses_report_the_same_client_id(_Config) ->
mongoose_helper:wait_until(fun is_host_count_reported/0, true),
all_event_have_the_same_client_id().
system_metrics_are_reported_to_google_analytics_when_mim_starts(_Config) ->
mongoose_helper:wait_until(fun is_host_count_reported/0, true),
mongoose_helper:wait_until(fun are_modules_reported/0, true),
events_are_reported_to_primary_tracking_id(),
all_event_have_the_same_client_id().
system_metrics_are_reported_to_configurable_google_analytics(_Config) ->
mongoose_helper:wait_until(fun is_host_count_reported/0, true),
mongoose_helper:wait_until(fun are_modules_reported/0, true),
events_are_reported_to_both_tracking_ids(),
all_event_have_the_same_client_id().
system_metrics_are_reported_to_a_json_file(_Config) ->
ReportFilePath = rpc(mim(), mongoose_system_metrics_file, location, []),
ReportLastModified = rpc(mim(), filelib, last_modified, [ReportFilePath]),
Fun = fun() ->
ReportLastModified < rpc(mim(), filelib, last_modified, [ReportFilePath])
end,
mongoose_helper:wait_until(Fun, true),
{ok, File} = rpc(mim(), file, read_file, [ReportFilePath]),
jiffy:decode(File).
module_opts_are_reported(_Config) ->
mongoose_helper:wait_until(fun are_modules_reported/0, true),
Backend = mongoose_helper:mnesia_or_rdbms_backend(),
check_module_backend(mod_bosh, mnesia),
check_module_backend(mod_event_pusher, push),
check_module_backend(mod_event_pusher_push, Backend),
check_module_backend(mod_http_upload, s3),
check_module_backend(mod_last, Backend),
check_module_backend(mod_muc, Backend),
check_module_backend(mod_muc_light, Backend),
check_module_backend(mod_offline, Backend),
check_module_backend(mod_privacy, Backend),
check_module_backend(mod_private, Backend),
check_module_backend(mod_pubsub, Backend),
check_module_opt(mod_push_service_mongoosepush, api_version, <<"\"v3\"">>),
check_module_backend(mod_roster, Backend),
check_module_backend(mod_vcard, Backend).
rdbms_module_opts_are_reported(_Config) ->
mongoose_helper:wait_until(fun are_modules_reported/0, true),
check_module_backend(mod_auth_token, rdbms),
check_module_backend(mod_inbox, rdbms),
check_module_backend(mod_mam, rdbms).
check_module_backend(Module, Backend) ->
check_module_opt(Module, backend, atom_to_binary(Backend)).
mongoose_version_is_reported(_Config) ->
mongoose_helper:wait_until(fun is_mongoose_version_reported/0, true).
cluster_uptime_is_reported(_Config) ->
mongoose_helper:wait_until(fun is_cluster_uptime_reported/0, true).
xmpp_components_are_reported(Config) ->
CompOpts = ?config(component1, Config),
{Component, Addr, _} = connect_component(CompOpts),
mongoose_helper:wait_until(fun are_xmpp_components_reported/0, true),
mongoose_helper:wait_until(fun more_than_one_component_is_reported/0, true),
disconnect_component(Component, Addr).
api_are_reported(_Config) ->
mongoose_helper:wait_until(fun is_api_reported/0, true).
transport_mechanisms_are_reported(_Config) ->
mongoose_helper:wait_until(fun are_transport_mechanisms_reported/0, true).
outgoing_pools_are_reported(_Config) ->
mongoose_helper:wait_until(fun are_outgoing_pools_reported/0, true).
xmpp_stanzas_counts_are_reported(Config) ->
escalus:story(Config, [{alice,1}, {bob,1}], fun(Alice, Bob) ->
mongoose_helper:wait_until(fun is_message_count_reported/0, true),
mongoose_helper:wait_until(fun is_iq_count_reported/0, true),
Sent = get_metric_value(<<"xmppMessageSent">>),
Received = get_metric_value(<<"xmppMessageReceived">>),
escalus:send(Alice, escalus_stanza:chat_to(Bob, <<"Hi">>)),
escalus:assert(is_chat_message, [<<"Hi">>], escalus:wait_for_stanza(Bob)),
F = fun() -> assert_message_count_is_incremented(Sent, Received) end,
mongoose_helper:wait_until(F, ok)
end).
config_type_is_reported(_Config) ->
mongoose_helper:wait_until(fun is_config_type_reported/0, true).
just_removed_from_config_logs_question(_Config) ->
disable_system_metrics(mim3()),
Result = distributed_helper:rpc(
mim3(), service_mongoose_system_metrics, verify_if_configured, []),
?assertEqual(ignore, Result).
in_config_unmodified_logs_request_for_agreement(_Config) ->
disable_system_metrics(mim()),
logger_ct_backend:capture(warning),
enable_system_metrics(mim()),
FilterFun = fun(_, Msg) ->
re:run(Msg, "MongooseIM docs", [global]) /= nomatch
end,
mongoose_helper:wait_until(fun() -> length(logger_ct_backend:recv(FilterFun)) end, 1),
logger_ct_backend:stop_capture(),
disable_system_metrics(mim()).
in_config_with_explicit_no_report_goes_off_silently(_Config) ->
logger_ct_backend:capture(warning),
start_system_metrics_service(mim(), #{report => false}),
logger_ct_backend:stop_capture(),
FilterFun = fun(warning, Msg) ->
re:run(Msg, "MongooseIM docs", [global]) /= nomatch;
(_,_) -> false
end,
[] = logger_ct_backend:recv(FilterFun),
disable_system_metrics(mim()).
in_config_with_explicit_reporting_goes_on_silently(_Config) ->
logger_ct_backend:capture(warning),
start_system_metrics_service(mim(), #{report => true}),
logger_ct_backend:stop_capture(),
FilterFun = fun(warning, Msg) ->
re:run(Msg, "MongooseIM docs", [global]) /= nomatch;
(_,_) -> false
end,
[] = logger_ct_backend:recv(FilterFun),
disable_system_metrics(mim()).
required_modules(CaseName) ->
lists:filter(fun({Module, _Opts}) -> is_module_supported(Module) end,
modules_to_test(CaseName)).
modules_to_test(module_opts_are_reported) ->
Backend = mongoose_helper:mnesia_or_rdbms_backend(),
[required_module(mod_bosh),
required_module(mod_event_pusher,
#{push => config([modules, mod_event_pusher, push], #{backend => Backend})}),
required_module(mod_http_upload, s3),
required_module(mod_last, Backend),
required_module(mod_muc, Backend),
required_module(mod_muc_light, Backend),
required_module(mod_offline, Backend),
required_module(mod_privacy, Backend),
required_module(mod_private, Backend),
required_module(mod_pubsub, Backend),
required_module(mod_push_service_mongoosepush),
required_module(mod_roster, Backend),
required_module(mod_vcard, Backend)];
modules_to_test(rdbms_module_opts_are_reported) ->
[required_module(mod_auth_token),
required_module(mod_inbox),
required_module(mod_mam)].
required_module(Module) ->
required_module(Module, #{}).
required_module(Module, Backend) when is_atom(Backend) ->
{Module, mod_config(Module, #{backend => Backend})};
required_module(Module, Opts) ->
{Module, mod_config(Module, Opts)}.
check_module_opt(Module, Key, Value) ->
case is_module_supported(Module) of
true ->
?assertEqual(true, is_module_opt_reported(Module, Key, Value));
false ->
ct:log("Skipping unsupported module ~p", [Module])
end.
is_module_supported(Module) ->
is_host_type_static() orelse supports_dynamic_domains(Module).
is_host_type_static() ->
rpc(mim(), mongoose_domain_core, is_static, [host_type()]).
supports_dynamic_domains(Module) ->
rpc(mim(), gen_mod, does_module_support, [Module, dynamic_domains]).
all_event_have_the_same_client_id() ->
Tab = ets:tab2list(?ETS_TABLE),
UniqueSortedTab = lists:usort([Cid || #event{cid = Cid} <- Tab]),
1 = length(UniqueSortedTab).
is_host_count_reported() ->
is_in_table(<<"hosts">>).
are_modules_reported() ->
is_in_table(<<"module">>).
is_in_table(EventCategory) ->
Tab = ets:tab2list(?ETS_TABLE),
lists:any(
fun(#event{ec = EC}) ->
verify_category(EC, EventCategory)
end, Tab).
verify_category(EC, <<"module">>) ->
Result = re:run(EC, "^mod_.*"),
case Result of
{match, _Captured} -> true;
nomatch -> false
end;
verify_category(EC, EC) ->
true;
verify_category(_EC, _EventCategory) ->
false.
get_events_collection_size() ->
ets:info(?ETS_TABLE, size).
enable_system_metrics(Node) ->
enable_system_metrics(Node, #{initial_report => 100, periodic_report => 100}).
enable_system_metrics_with_configurable_tracking_id(Node) ->
enable_system_metrics(Node, #{initial_report => 100, periodic_report => 100,
tracking_id => ?TRACKING_ID_EXTRA}).
enable_system_metrics(Node, Opts) ->
UrlArgs = [google_analytics_url, ?SERVER_URL],
ok = mongoose_helper:successful_rpc(Node, mongoose_config, set_opt, UrlArgs),
start_system_metrics_service(Node, Opts).
start_system_metrics_service(Node, ExtraOpts) ->
Opts = config([services, service_mongoose_system_metrics], ExtraOpts),
dynamic_services:ensure_started(Node, service_mongoose_system_metrics, Opts).
disable_system_metrics(Node) ->
dynamic_services:ensure_stopped(Node, service_mongoose_system_metrics),
mongoose_helper:successful_rpc(Node, mongoose_config, unset_opt, [ google_analytics_url ]).
delete_prev_client_id(Node) ->
mongoose_helper:successful_rpc(Node, mnesia, delete_table, [service_mongoose_system_metrics]).
create_events_collection() ->
ets:new(?ETS_TABLE, [duplicate_bag, named_table, public]).
clear_events_collection() ->
ets:delete_all_objects(?ETS_TABLE).
system_metrics_service_is_enabled(Node) ->
Pid = distributed_helper:rpc(Node, erlang, whereis, [service_mongoose_system_metrics]),
erlang:is_pid(Pid).
system_metrics_service_is_disabled(Node) ->
not system_metrics_service_is_enabled(Node).
events_are_reported_to_primary_tracking_id() ->
events_are_reported_to_tracking_ids([primary_tracking_id()]).
events_are_reported_to_both_tracking_ids() ->
events_are_reported_to_tracking_ids([primary_tracking_id(), ?TRACKING_ID_EXTRA]).
primary_tracking_id() ->
case os:getenv("CI") of
"true" -> ?TRACKING_ID_CI;
_ -> ?TRACKING_ID
end.
events_are_reported_to_tracking_ids(ConfiguredTrackingIds) ->
Tab = ets:tab2list(?ETS_TABLE),
ActualTrackingIds = lists:usort([Tid || #event{tid = Tid} <- Tab]),
ExpectedTrackingIds = lists:sort([list_to_binary(Tid) || Tid <- ConfiguredTrackingIds]),
?assertEqual(ExpectedTrackingIds, ActualTrackingIds).
is_feature_reported(EventCategory, EventAction) ->
length(match_events(EventCategory, EventAction)) > 0.
is_feature_reported(EventCategory, EventAction, EventLabel) ->
length(match_events(EventCategory, EventAction, EventLabel)) > 0.
is_module_backend_reported(Module, Backend) ->
is_feature_reported(atom_to_binary(Module), <<"backend">>, atom_to_binary(Backend)).
is_module_opt_reported(Module, Key, Value) ->
is_feature_reported(atom_to_binary(Module), atom_to_binary(Key), Value).
is_mongoose_version_reported() ->
is_feature_reported(<<"cluster">>, <<"mim_version">>).
is_cluster_uptime_reported() ->
is_feature_reported(<<"cluster">>, <<"uptime">>).
are_xmpp_components_reported() ->
is_feature_reported(<<"cluster">>, <<"number_of_components">>).
is_config_type_reported() ->
IsToml = is_feature_reported(<<"cluster">>, <<"config_type">>, <<"toml">>),
IsCfg = is_feature_reported(<<"cluster">>, <<"config_type">>, <<"cfg">>),
IsToml orelse IsCfg.
is_api_reported() ->
is_in_table(<<"http_api">>).
are_transport_mechanisms_reported() ->
is_in_table(<<"transport_mechanism">>).
are_outgoing_pools_reported() ->
is_in_table(<<"outgoing_pools">>).
is_iq_count_reported() ->
is_in_table(<<"xmppIqSent">>).
is_message_count_reported() ->
is_in_table(<<"xmppMessageSent">>) andalso is_in_table(<<"xmppMessageReceived">>).
assert_message_count_is_incremented(Sent, Received) ->
assert_increment(<<"xmppMessageSent">>, Sent),
assert_increment(<<"xmppMessageReceived">>, Received).
assert_increment(EventCategory, InitialValue) ->
Events = match_events(EventCategory, integer_to_binary(InitialValue + 1), <<$1>>),
expect exactly one event with an increment of 1
get_metric_value(EventCategory) ->
[#event{ea = Value} | _] = match_events(EventCategory),
binary_to_integer(Value).
more_than_one_component_is_reported() ->
Events = match_events(<<"cluster">>, <<"number_of_components">>),
lists:any(fun(#event{el = EL}) ->
binary_to_integer(EL) > 0
end, Events).
match_events(EC) ->
ets:match_object(?ETS_TABLE, #event{ec = EC, _ = '_'}).
match_events(EC, EA) ->
ets:match_object(?ETS_TABLE, #event{ec = EC, ea = EA, _ = '_'}).
match_events(EC, EA, EL) ->
ets:match_object(?ETS_TABLE, #event{ec = EC, ea = EA, el = EL, _ = '_'}).
handler_init(Req0) ->
{ok, Body, Req} = cowboy_req:read_body(Req0),
StrEvents = string:split(Body, "\n", all),
lists:map(
fun(StrEvent) ->
Event = str_to_event(StrEvent),
TODO there is a race condition when table is not available
ets:insert(?ETS_TABLE, Event)
end, StrEvents),
Req1 = cowboy_req:reply(200, #{}, <<"">>, Req),
{ok, Req1, no_state}.
str_to_event(Qs) ->
StrParams = string:split(Qs, "&", all),
Params = lists:map(
fun(StrParam) ->
[StrKey, StrVal] = string:split(StrParam, "="),
{binary_to_atom(StrKey, utf8), StrVal}
end, StrParams),
#event{
cid = get_el(cid, Params),
tid = get_el(tid, Params),
ec = get_el(ec, Params),
ea = get_el(ea, Params),
el = get_el(el, Params),
ev = get_el(ev, Params)
}.
get_el(Key, Proplist) ->
proplists:get_value(Key, Proplist, undef).
get_components(Opts, Config) ->
Components = [component1, component2, vjud_component],
[ {C, Opts ++ spec(C, Config)} || C <- Components ] ++ Config.
|
0e95554a5c1e96b573c578cd596e231168dd8b0b24fd13e2b892070014a49caf | haskell-servant/servant | Capture.hs | {-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE PolyKinds #
{-# OPTIONS_HADDOCK not-home #-}
module Servant.API.Capture (Capture, Capture', CaptureAll) where
import Data.Typeable
(Typeable)
import GHC.TypeLits
(Symbol)
| Capture a value from the request path under a certain type
--
-- Example:
--
-- >>> -- GET /books/:isbn
> > > type MyApi = " books " :> Capture " isbn " Text :> Get ' [ JSON ] Book
type Capture = Capture' '[] -- todo
-- | 'Capture' which can be modified. For example with 'Description'.
data Capture' (mods :: [*]) (sym :: Symbol) (a :: *)
deriving (Typeable)
-- | Capture all remaining values from the request path under a certain type
--
-- Example:
--
-- >>> -- GET /src/*
> > > type MyAPI = " src " :> CaptureAll " segments " Text :> Get ' [ JSON ] SourceFile
data CaptureAll (sym :: Symbol) (a :: *)
deriving (Typeable)
-- $setup
-- >>> import Servant.API
-- >>> import Data.Aeson
-- >>> import Data.Text
> > > data Book
> > > instance ToJSON Book where { toJSON = undefined }
-- >>> data SourceFile
> > > instance ToJSON SourceFile where { toJSON = undefined }
| null | https://raw.githubusercontent.com/haskell-servant/servant/d06b65c4e6116f992debbac2eeeb83eafb960321/servant/src/Servant/API/Capture.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE DeriveDataTypeable #
# OPTIONS_HADDOCK not-home #
Example:
>>> -- GET /books/:isbn
todo
| 'Capture' which can be modified. For example with 'Description'.
| Capture all remaining values from the request path under a certain type
Example:
>>> -- GET /src/*
$setup
>>> import Servant.API
>>> import Data.Aeson
>>> import Data.Text
>>> data SourceFile | # LANGUAGE PolyKinds #
module Servant.API.Capture (Capture, Capture', CaptureAll) where
import Data.Typeable
(Typeable)
import GHC.TypeLits
(Symbol)
| Capture a value from the request path under a certain type
> > > type MyApi = " books " :> Capture " isbn " Text :> Get ' [ JSON ] Book
data Capture' (mods :: [*]) (sym :: Symbol) (a :: *)
deriving (Typeable)
> > > type MyAPI = " src " :> CaptureAll " segments " Text :> Get ' [ JSON ] SourceFile
data CaptureAll (sym :: Symbol) (a :: *)
deriving (Typeable)
> > > data Book
> > > instance ToJSON Book where { toJSON = undefined }
> > > instance ToJSON SourceFile where { toJSON = undefined }
|
22f6ee822c2fe499d95866ca77a633f3d12e666be0ad85a82276168a6fc9c01d | avsm/platform | uucp_tmap4bytes.ml | ---------------------------------------------------------------------------
Copyright ( c ) 2014 . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
% % NAME%% % % ---------------------------------------------------------------------------
Copyright (c) 2014 Daniel C. Bünzli. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
%%NAME%% %%VERSION%%
---------------------------------------------------------------------------*)
uchar to 4 bytes trie maps .
let str = Printf.sprintf
let pp = Format.fprintf
let err_default l = str "default value length is %d, must be at least 4" l
type t =
{ default : string; (* default value. *)
0x1FFFFF as 0x1FF - 0xF - 0xFF
let nil = [||]
let snil = ""
let l0_shift = 12
let l0_size = 0x10F + 1
let l1_shift = 8
let l1_mask = 0xF
let l1_size = 0xF + 1
let l2_mask = 0xFF
let l2_size = (0xFF + 1) * 4
let create default =
let dlen = String.length default in
if dlen >= 4 then { default; l0 = Array.make l0_size nil } else
invalid_arg (err_default dlen)
let word_size m = match m.l0 with
| [||] -> 3 + 4 + 1
| l0 ->
let size = ref (3 + 4 + 1 + Array.length l0) in
for i = 0 to Array.length l0 - 1 do match l0.(i) with
| [||] -> ()
| l1 ->
size := !size + 1 + Array.length l1;
for j = 0 to Array.length l1 - 1 do
size := !size + 1 + ((String.length l1.(j) * 8) / Sys.word_size)
done;
done;
!size
let dump ppf m =
pp ppf "{ default =@ %S;@, l0 =@ " m.default;
begin match m.l0 with
| [||] -> pp ppf "nil"
| l0 ->
pp ppf "@,[|@,";
for i = 0 to Array.length l0 - 1 do match l0.(i) with
| [||] -> pp ppf "@,nil;@,"
| l1 ->
pp ppf "@,[|@,";
for j = 0 to Array.length l1 - 1 do match l1.(j) with
| "" -> pp ppf "@,snil;@,"
| l2 ->
pp ppf "@,\"";
for k = 0 to String.length l2 - 1 do
if k mod 16 = 0 && k > 0 then pp ppf "\\@\n ";
pp ppf "\\x%02X" (Char.code l2.[k])
done;
pp ppf "\";@,";
done;
pp ppf "|];"
done;
pp ppf "|]"
end;
pp ppf "}"
Four bytes as an uint16 pair
let create_uint16_pair (d0, d1) =
let default = Bytes.create 4 in
Bytes.set default 0 (Char.unsafe_chr ((d0 lsr 8 land 0xFF)));
Bytes.set default 1 (Char.unsafe_chr ((d0 land 0xFF)));
Bytes.set default 2 (Char.unsafe_chr ((d1 lsr 8 land 0xFF)));
Bytes.set default 3 (Char.unsafe_chr ((d1 land 0xFF)));
create (Bytes.unsafe_to_string default)
let get_uint16_pair m u =
let l1 = Array.unsafe_get m.l0 (u lsr l0_shift) in
let s, k =
if l1 == nil then m.default, 0 else
let l2 = Array.unsafe_get l1 (u lsr l1_shift land l1_mask) in
if l2 == snil then m.default, 0 else
l2, (u land l2_mask) * 4
in
let i01 = Char.code (String.unsafe_get s (k )) in
let i00 = Char.code (String.unsafe_get s (k + 1)) in
let i11 = Char.code (String.unsafe_get s (k + 2)) in
let i10 = Char.code (String.unsafe_get s (k + 3)) in
let i0 = (i01 lsl 8) lor i00 in
let i1 = (i11 lsl 8) lor i10 in
i0, i1
let set_uint16_pair m u (i0, i1) =
let l2_make m =
let s = Bytes.create l2_size in
for i = 0 to l2_size - 1 do Bytes.set s i (m.default.[i mod 4]) done;
s
in
let d0 = (Char.code m.default.[0] lsl 8) lor (Char.code m.default.[1]) in
let d1 = (Char.code m.default.[2] lsl 8) lor (Char.code m.default.[3]) in
if d0 = i0 && d1 = i1 then () else
let i = u lsr l0_shift in
if m.l0.(i) == nil then m.l0.(i) <- Array.make l1_size snil;
let j = u lsr l1_shift land l1_mask in
if m.l0.(i).(j) == snil then
m.l0.(i).(j) <- Bytes.unsafe_to_string (l2_make m);
let k = (u land l2_mask) * 4 in
let s = Bytes.unsafe_of_string (m.l0.(i).(j)) in
Bytes.set s (k ) (Char.unsafe_chr ((i0 lsr 8 land 0xFF)));
Bytes.set s (k + 1) (Char.unsafe_chr ((i0 land 0xFF)));
Bytes.set s (k + 2) (Char.unsafe_chr ((i1 lsr 8 land 0xFF)));
Bytes.set s (k + 3) (Char.unsafe_chr ((i1 land 0xFF)));
()
---------------------------------------------------------------------------
Copyright ( c ) 2014
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
---------------------------------------------------------------------------
Copyright (c) 2014 Daniel C. Bünzli
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
| null | https://raw.githubusercontent.com/avsm/platform/b254e3c6b60f3c0c09dfdcde92eb1abdc267fa1c/duniverse/uucp.12.0.0%2Bdune/src/uucp_tmap4bytes.ml | ocaml | default value. | ---------------------------------------------------------------------------
Copyright ( c ) 2014 . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
% % NAME%% % % ---------------------------------------------------------------------------
Copyright (c) 2014 Daniel C. Bünzli. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
%%NAME%% %%VERSION%%
---------------------------------------------------------------------------*)
uchar to 4 bytes trie maps .
let str = Printf.sprintf
let pp = Format.fprintf
let err_default l = str "default value length is %d, must be at least 4" l
type t =
0x1FFFFF as 0x1FF - 0xF - 0xFF
let nil = [||]
let snil = ""
let l0_shift = 12
let l0_size = 0x10F + 1
let l1_shift = 8
let l1_mask = 0xF
let l1_size = 0xF + 1
let l2_mask = 0xFF
let l2_size = (0xFF + 1) * 4
let create default =
let dlen = String.length default in
if dlen >= 4 then { default; l0 = Array.make l0_size nil } else
invalid_arg (err_default dlen)
let word_size m = match m.l0 with
| [||] -> 3 + 4 + 1
| l0 ->
let size = ref (3 + 4 + 1 + Array.length l0) in
for i = 0 to Array.length l0 - 1 do match l0.(i) with
| [||] -> ()
| l1 ->
size := !size + 1 + Array.length l1;
for j = 0 to Array.length l1 - 1 do
size := !size + 1 + ((String.length l1.(j) * 8) / Sys.word_size)
done;
done;
!size
let dump ppf m =
pp ppf "{ default =@ %S;@, l0 =@ " m.default;
begin match m.l0 with
| [||] -> pp ppf "nil"
| l0 ->
pp ppf "@,[|@,";
for i = 0 to Array.length l0 - 1 do match l0.(i) with
| [||] -> pp ppf "@,nil;@,"
| l1 ->
pp ppf "@,[|@,";
for j = 0 to Array.length l1 - 1 do match l1.(j) with
| "" -> pp ppf "@,snil;@,"
| l2 ->
pp ppf "@,\"";
for k = 0 to String.length l2 - 1 do
if k mod 16 = 0 && k > 0 then pp ppf "\\@\n ";
pp ppf "\\x%02X" (Char.code l2.[k])
done;
pp ppf "\";@,";
done;
pp ppf "|];"
done;
pp ppf "|]"
end;
pp ppf "}"
Four bytes as an uint16 pair
let create_uint16_pair (d0, d1) =
let default = Bytes.create 4 in
Bytes.set default 0 (Char.unsafe_chr ((d0 lsr 8 land 0xFF)));
Bytes.set default 1 (Char.unsafe_chr ((d0 land 0xFF)));
Bytes.set default 2 (Char.unsafe_chr ((d1 lsr 8 land 0xFF)));
Bytes.set default 3 (Char.unsafe_chr ((d1 land 0xFF)));
create (Bytes.unsafe_to_string default)
let get_uint16_pair m u =
let l1 = Array.unsafe_get m.l0 (u lsr l0_shift) in
let s, k =
if l1 == nil then m.default, 0 else
let l2 = Array.unsafe_get l1 (u lsr l1_shift land l1_mask) in
if l2 == snil then m.default, 0 else
l2, (u land l2_mask) * 4
in
let i01 = Char.code (String.unsafe_get s (k )) in
let i00 = Char.code (String.unsafe_get s (k + 1)) in
let i11 = Char.code (String.unsafe_get s (k + 2)) in
let i10 = Char.code (String.unsafe_get s (k + 3)) in
let i0 = (i01 lsl 8) lor i00 in
let i1 = (i11 lsl 8) lor i10 in
i0, i1
let set_uint16_pair m u (i0, i1) =
let l2_make m =
let s = Bytes.create l2_size in
for i = 0 to l2_size - 1 do Bytes.set s i (m.default.[i mod 4]) done;
s
in
let d0 = (Char.code m.default.[0] lsl 8) lor (Char.code m.default.[1]) in
let d1 = (Char.code m.default.[2] lsl 8) lor (Char.code m.default.[3]) in
if d0 = i0 && d1 = i1 then () else
let i = u lsr l0_shift in
if m.l0.(i) == nil then m.l0.(i) <- Array.make l1_size snil;
let j = u lsr l1_shift land l1_mask in
if m.l0.(i).(j) == snil then
m.l0.(i).(j) <- Bytes.unsafe_to_string (l2_make m);
let k = (u land l2_mask) * 4 in
let s = Bytes.unsafe_of_string (m.l0.(i).(j)) in
Bytes.set s (k ) (Char.unsafe_chr ((i0 lsr 8 land 0xFF)));
Bytes.set s (k + 1) (Char.unsafe_chr ((i0 land 0xFF)));
Bytes.set s (k + 2) (Char.unsafe_chr ((i1 lsr 8 land 0xFF)));
Bytes.set s (k + 3) (Char.unsafe_chr ((i1 land 0xFF)));
()
---------------------------------------------------------------------------
Copyright ( c ) 2014
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
---------------------------------------------------------------------------
Copyright (c) 2014 Daniel C. Bünzli
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
|
b72eba163fdbea75150353d358b5df1ebe14f1e799aa2184354e7da8a3b4f356 | runtimeverification/haskell-backend | MockSymbols.hs | # OPTIONS_GHC -Wno - incomplete - uni - patterns #
# OPTIONS_GHC -Wno - missing - export - lists #
module Test.Kore.Rewrite.MockSymbols where
Intended usage :
* Import qualified .
* use attributesMapping to build mock MetadataTools .
* Use things like a , b , c , x , y , z for testing .
RULES :
* Everything that does not obey the default rules must be clearly
specified in the name , e.g. ' constantNotTotal ' .
* constant symbols are , by default , total .
* constant functions are called cf , cg , ch .
* constant constructors are called a , b , c , ...
* one - element functions are called f , , h.
* constructors are called " constr < n><k > " where n is the arity and k is used
to differentiate between them ( both are one - digit ) .
* total constructors are called " totalConstr < n><k > "
* total symbols are called " total < n><k > "
* symbols without any special attribute are called " plain < n><k > "
* variables are called x , y , z ...
* Import qualified.
* use attributesMapping to build mock MetadataTools.
* Use things like a, b, c, x, y, z for testing.
RULES:
* Everything that does not obey the default rules must be clearly
specified in the name, e.g. 'constantNotTotal'.
* constant symbols are, by default, total.
* constant functions are called cf, cg, ch.
* constant constructors are called a, b, c, ...
* one-element functions are called f, g, h.
* constructors are called "constr<n><k>" where n is the arity and k is used
to differentiate between them (both are one-digit).
* total constructors are called "totalConstr<n><k>"
* total symbols are called "total<n><k>"
* symbols without any special attribute are called "plain<n><k>"
* variables are called x, y, z...
-}
import Control.Lens qualified as Lens
import Control.Monad qualified as Monad
import Data.Bifunctor qualified as Bifunctor
import Data.Default qualified as Default
import Data.Generics.Product
import Data.HashMap.Strict qualified as HashMap
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Sequence qualified as Seq
import Data.Set qualified as Set
import Data.Sup
import Data.Text (
Text,
)
import Data.Text qualified as Text
import Hedgehog (diff, forAll, property, withTests)
import Hedgehog.Gen qualified as Gen
import Hedgehog.Range qualified as Range
import Kore.Attribute.Hook (
Hook (..),
)
import Kore.Attribute.Pattern.ConstructorLike (
isConstructorLike,
)
import Kore.Attribute.Sort qualified as Attribute
import Kore.Attribute.Sort qualified as AttributeSort
import Kore.Attribute.Sort.Concat qualified as Attribute
import Kore.Attribute.Sort.Constructors qualified as Attribute (
Constructors,
)
import Kore.Attribute.Sort.Element qualified as Attribute
import Kore.Attribute.Sort.HasDomainValues qualified as Attribute
import Kore.Attribute.Sort.Unit qualified as Attribute
import Kore.Attribute.Subsort
import Kore.Attribute.Symbol qualified as Attribute
import Kore.Attribute.Synthetic (
synthesize,
)
import Kore.Builtin qualified as Builtin
import Kore.Builtin.Bool qualified as Builtin.Bool
import Kore.Builtin.Int qualified as Builtin.Int
import Kore.Builtin.KEqual qualified as Builtin.KEqual
import Kore.Builtin.List qualified as List
import Kore.Builtin.Map.Map qualified as Map
import Kore.Builtin.Set.Set qualified as Set
import Kore.Builtin.String qualified as Builtin.String
import Kore.Equation (Equation)
import Kore.IndexedModule.IndexedModule qualified as IndexedModule
import Kore.IndexedModule.MetadataTools (
SmtMetadataTools,
)
import Kore.IndexedModule.OverloadGraph qualified as OverloadGraph
import Kore.IndexedModule.SortGraph qualified as SortGraph
import Kore.Internal.InternalList
import Kore.Internal.InternalMap
import Kore.Internal.InternalSet
import Kore.Internal.Symbol hiding (
isConstructorLike,
sortInjection,
)
import Kore.Internal.TermLike (
InternalVariable,
TermLike,
retractKey,
)
import Kore.Internal.TermLike qualified as Internal
import Kore.Rewrite.Axiom.Identifier (AxiomIdentifier)
import Kore.Rewrite.Function.Memo qualified as Memo
import Kore.Rewrite.RewritingVariable (
RewritingVariableName,
mkConfigVariable,
mkEquationVariable,
mkRuleVariable,
)
import Kore.Rewrite.SMT.AST qualified as SMT
import Kore.Rewrite.SMT.Representation.Resolve qualified as SMT (
resolve,
)
import Kore.Simplify.Condition qualified as Simplifier.Condition
import Kore.Simplify.InjSimplifier
import Kore.Simplify.OverloadSimplifier
import Kore.Simplify.Pattern qualified as Pattern
import Kore.Simplify.Simplify (
ConditionSimplifier,
Env (..),
Simplifier,
)
import Kore.Simplify.SubstitutionSimplifier qualified as SubstitutionSimplifier
import Kore.Simplify.TermLike qualified as TermLike
import Kore.Sort
import Kore.Syntax.Application
import Kore.Syntax.Module (ModuleName (..))
import Kore.Syntax.Sentence (SentenceSort (..), SentenceSymbol (..))
import Kore.Syntax.Sentence qualified
import Kore.Syntax.Variable
import Kore.Validate.PatternVerifier qualified as PatternVerifier
import Prelude.Kore
import SMT.AST qualified as SMT
import SMT.SimpleSMT qualified as SMT
import Test.ConsistentKore qualified as ConsistentKore (
CollectionSorts (..),
Setup (..),
runKoreGen,
termLikeGenWithSort,
)
import Test.Kore (
testId,
)
import Test.Kore.IndexedModule.MockMetadataTools qualified as Mock
import Test.Tasty
import Test.Tasty.HUnit.Ext
import Test.Tasty.Hedgehog (testProperty)
aId :: Id
aId = testId "a"
aSort0Id :: Id
aSort0Id = testId "aSort0"
aSort1Id :: Id
aSort1Id = testId "aSort1"
aSubsortId :: Id
aSubsortId = testId "aSubsort"
aSubOthersortId :: Id
aSubOthersortId = testId "aSubOthersort"
aSubSubsortId :: Id
aSubSubsortId = testId "aSubSubsort"
aTopSortId :: Id
aTopSortId = testId "aTopSort"
aOtherSortId :: Id
aOtherSortId = testId "aOtherSort"
bId :: Id
bId = testId "b"
bSort0Id :: Id
bSort0Id = testId "bSort0"
cId :: Id
cId = testId "c"
dId :: Id
dId = testId "d"
eId :: Id
eId = testId "e"
fId :: Id
fId = testId "f"
fMapId :: Id
fMapId = testId "fMap"
fSort0Id :: Id
fSort0Id = testId "fSort0"
gId :: Id
gId = testId "g"
gSort0Id :: Id
gSort0Id = testId "gSort0"
hId :: Id
hId = testId "h"
cfId :: Id
cfId = testId "cf"
cfSort0Id :: Id
cfSort0Id = testId "cfSort0"
cfSort1Id :: Id
cfSort1Id = testId "cfSort1"
cgId :: Id
cgId = testId "cg"
cgSort0Id :: Id
cgSort0Id = testId "cgSort0"
chId :: Id
chId = testId "ch"
fSetId :: Id
fSetId = testId "fSet"
fSet2Id :: Id
fSet2Id = testId "fSet2"
fIntId :: Id
fIntId = testId "fInt"
fBoolId :: Id
fBoolId = testId "fBool"
fStringId :: Id
fStringId = testId "fString"
fTestIntId :: Id
fTestIntId = testId "fTestInt"
fTestFunctionalIntId :: Id
fTestFunctionalIntId = testId "fTestFunctionalInt"
plain00Id :: Id
plain00Id = testId "plain00"
plain00Sort0Id :: Id
plain00Sort0Id = testId "plain00Sort0"
plain00SubsortId :: Id
plain00SubsortId = testId "plain00Subsort"
plain00OtherSortId :: Id
plain00OtherSortId = testId "plain00OtherSort"
plain00SubSubsortId :: Id
plain00SubSubsortId = testId "plain00SubSubsort"
plain10Id :: Id
plain10Id = testId "plain10"
plain11Id :: Id
plain11Id = testId "plain11"
plain20Id :: Id
plain20Id = testId "plain20"
constr00Id :: Id
constr00Id = testId "constr00"
constr10Id :: Id
constr10Id = testId "constr10"
constr11Id :: Id
constr11Id = testId "constr11"
constr20Id :: Id
constr20Id = testId "constr20"
constrFunct20TestMapId :: Id
constrFunct20TestMapId = testId "constrFunct20TestMap"
function20MapTestId :: Id
function20MapTestId = testId "function20MapTest"
functional00Id :: Id
functional00Id = testId "functional00"
functional01Id :: Id
functional01Id = testId "functional01"
functional10Id :: Id
functional10Id = testId "functional10"
functional11Id :: Id
functional11Id = testId "functional11"
functional20Id :: Id
functional20Id = testId "functional20"
functional00SubSubSortId :: Id
functional00SubSubSortId = testId "functional00SubSubSort"
functionalInjective00Id :: Id
functionalInjective00Id = testId "functionalInjective00"
functionalConstr10Id :: Id
functionalConstr10Id = testId "functionalConstr10"
functionalConstr11Id :: Id
functionalConstr11Id = testId "functionalConstr11"
functionalConstr12Id :: Id
functionalConstr12Id = testId "functionalConstr12"
functionalConstr20Id :: Id
functionalConstr20Id = testId "functionalConstr20"
functionalConstr21Id :: Id
functionalConstr21Id = testId "functionalConstr21"
functionalConstr30Id :: Id
functionalConstr30Id = testId "functionalConstr30"
functionalTopConstr20Id :: Id
functionalTopConstr20Id = testId "functionalTopConstr20"
functionalTopConstr21Id :: Id
functionalTopConstr21Id = testId "functionalTopConstr21"
injective10Id :: Id
injective10Id = testId "injective10"
injective11Id :: Id
injective11Id = testId "injective11"
sortInjectionId :: Id
sortInjectionId = testId "sortInjection"
unitMapId :: Id
unitMapId = testId "unitMap"
elementMapId :: Id
elementMapId = testId "elementMap"
concatMapId :: Id
concatMapId = testId "concatMap"
opaqueMapId :: Id
opaqueMapId = testId "opaqueMap"
inKeysMapId :: Id
inKeysMapId = testId "inKeys"
lessIntId :: Id
lessIntId = testId "lessIntId"
greaterEqIntId :: Id
greaterEqIntId = testId "greaterEqIntId"
tdivIntId :: Id
tdivIntId = testId "tdivIntId"
concatListId :: Id
concatListId = testId "concatList"
elementListId :: Id
elementListId = testId "elementList"
unitListId :: Id
unitListId = testId "unitList"
concatSetId :: Id
concatSetId = testId "concatSet"
opaqueSetId :: Id
opaqueSetId = testId "opaqueSet"
elementSetId :: Id
elementSetId = testId "elementSet"
unitSetId :: Id
unitSetId = testId "unitSet"
keqBoolId :: Id
keqBoolId = testId "keqBool"
sigmaId :: Id
sigmaId = testId "sigma"
anywhereId :: Id
anywhereId = testId "anywhere"
subsubOverloadId :: Id
subsubOverloadId = testId "subsubOverload"
subOverloadId :: Id
subOverloadId = testId "subOverload"
otherOverloadId :: Id
otherOverloadId = testId "otherOverload"
topOverloadId :: Id
topOverloadId = testId "topOverload"
functionSMTId :: Id
functionSMTId = testId "functionSMT"
functionalSMTId :: Id
functionalSMTId = testId "functionalSMT"
symbol :: Id -> [Sort] -> Sort -> Symbol
symbol name operands result =
Symbol
{ symbolConstructor = name
, symbolParams = []
, symbolAttributes = Default.def
, symbolSorts = applicationSorts operands result
}
aSymbol :: Symbol
aSymbol = symbol aId [] testSort & total & constructor
aSort0Symbol :: Symbol
aSort0Symbol = symbol aSort0Id [] testSort0 & total & constructor
aSort1Symbol :: Symbol
aSort1Symbol = symbol aSort1Id [] testSort1 & total & constructor
aSubsortSymbol :: Symbol
aSubsortSymbol = symbol aSubsortId [] subSort & total & constructor
aSubOthersortSymbol :: Symbol
aSubOthersortSymbol =
symbol aSubOthersortId [] subOthersort & total & constructor
aSubSubsortSymbol :: Symbol
aSubSubsortSymbol =
symbol aSubSubsortId [] subSubsort & total & constructor
aTopSortSymbol :: Symbol
aTopSortSymbol = symbol aTopSortId [] topSort & total & constructor
aOtherSortSymbol :: Symbol
aOtherSortSymbol = symbol aOtherSortId [] otherSort & total & constructor
bSymbol :: Symbol
bSymbol = symbol bId [] testSort & total & constructor
bSort0Symbol :: Symbol
bSort0Symbol = symbol bSort0Id [] testSort0 & total & constructor
cSymbol :: Symbol
cSymbol = symbol cId [] testSort & total & constructor
dSymbol :: Symbol
dSymbol = symbol dId [] testSort & total & constructor
eSymbol :: Symbol
eSymbol = symbol eId [] testSort & total & constructor
fSymbol :: Symbol
fSymbol = symbol fId [testSort] testSort & function
fSort0Symbol :: Symbol
fSort0Symbol = symbol fSort0Id [testSort0] testSort0 & function
gSymbol :: Symbol
gSymbol = symbol gId [testSort] testSort & function
gSort0Symbol :: Symbol
gSort0Symbol = symbol gSort0Id [testSort0] testSort0 & function
hSymbol :: Symbol
hSymbol = symbol hId [testSort] testSort & function
cfSymbol :: Symbol
cfSymbol = symbol cfId [] testSort & function
cfSort0Symbol :: Symbol
cfSort0Symbol = symbol cfSort0Id [] testSort0 & function
cfSort1Symbol :: Symbol
cfSort1Symbol = symbol cfSort1Id [] testSort1 & function
cgSymbol :: Symbol
cgSymbol = symbol cgId [] testSort & function
cgSort0Symbol :: Symbol
cgSort0Symbol = symbol cgSort0Id [] testSort0 & function
chSymbol :: Symbol
chSymbol = symbol chId [] testSort & function
fSetSymbol :: Symbol
fSetSymbol = symbol fSetId [setSort] setSort & function
fSet2Symbol :: Symbol
fSet2Symbol = symbol fSet2Id [setSort, setSort] setSort & function
fIntSymbol :: Symbol
fIntSymbol = symbol fIntId [intSort] intSort & function
fBoolSymbol :: Symbol
fBoolSymbol = symbol fBoolId [boolSort] boolSort & function
fStringSymbol :: Symbol
fStringSymbol = symbol fStringId [stringSort] stringSort & function
fTestIntSymbol :: Symbol
fTestIntSymbol = symbol fTestIntId [testSort] intSort & function
fTestFunctionalIntSymbol :: Symbol
fTestFunctionalIntSymbol =
symbol fTestFunctionalIntId [testSort] intSort & function & total
plain00Symbol :: Symbol
plain00Symbol = symbol plain00Id [] testSort
plain00Sort0Symbol :: Symbol
plain00Sort0Symbol = symbol plain00Sort0Id [] testSort0
plain00SubsortSymbol :: Symbol
plain00SubsortSymbol = symbol plain00SubsortId [] subSort
plain00OtherSortSymbol :: Symbol
plain00OtherSortSymbol = symbol plain00OtherSortId [] otherSort
plain00SubSubsortSymbol :: Symbol
plain00SubSubsortSymbol = symbol plain00SubSubsortId [] subSubsort
plain10Symbol :: Symbol
plain10Symbol = symbol plain10Id [testSort] testSort
plain11Symbol :: Symbol
plain11Symbol = symbol plain11Id [testSort] testSort
plain20Symbol :: Symbol
plain20Symbol = symbol plain20Id [testSort, testSort] testSort
constr00Symbol :: Symbol
constr00Symbol = symbol constr00Id [] testSort & constructor
constr10Symbol :: Symbol
constr10Symbol = symbol constr10Id [testSort] testSort & constructor
constr11Symbol :: Symbol
constr11Symbol = symbol constr11Id [testSort] testSort & constructor
constr20Symbol :: Symbol
constr20Symbol = symbol constr20Id [testSort, testSort] testSort & constructor
constrIntSymbol :: Symbol
constrIntSymbol = symbol constr10Id [intSort] intSort & constructor
constrFunct20TestMapSymbol :: Symbol
constrFunct20TestMapSymbol =
symbol constrFunct20TestMapId [testSort, mapSort] testSort
& constructor
& function
function20MapTestSymbol :: Symbol
function20MapTestSymbol =
symbol function20MapTestId [mapSort, testSort] testSort & function
functional00Symbol :: Symbol
functional00Symbol = symbol functional00Id [] testSort & total
functional01Symbol :: Symbol
functional01Symbol = symbol functional01Id [] testSort & total
functional10Symbol :: Symbol
functional10Symbol = symbol functional10Id [testSort] testSort & total
functional11Symbol :: Symbol
functional11Symbol = symbol functional11Id [testSort] testSort & total
functional20Symbol :: Symbol
functional20Symbol =
symbol functional20Id [testSort, testSort] testSort & total
functional00SubSubSortSymbol :: Symbol
functional00SubSubSortSymbol =
symbol functional00SubSubSortId [] subSubsort & total
functionalInjective00Symbol :: Symbol
functionalInjective00Symbol =
symbol functionalInjective00Id [] testSort & total & injective
functionalConstr10Symbol :: Symbol
functionalConstr10Symbol =
symbol functionalConstr10Id [testSort] testSort & total & constructor
functionalConstr11Symbol :: Symbol
functionalConstr11Symbol =
symbol functionalConstr11Id [testSort] testSort & total & constructor
functionalConstr12Symbol :: Symbol
functionalConstr12Symbol =
symbol functionalConstr12Id [testSort] testSort & total & constructor
functionalConstr20Symbol :: Symbol
functionalConstr20Symbol =
symbol functionalConstr20Id [testSort, testSort] testSort
& total
& constructor
functionalConstr21Symbol :: Symbol
functionalConstr21Symbol =
symbol functionalConstr21Id [testSort, testSort] testSort
& total
& constructor
functionalConstr30Symbol :: Symbol
functionalConstr30Symbol =
symbol functionalConstr30Id [testSort, testSort, testSort] testSort
& total
& constructor
functionalTopConstr20Symbol :: Symbol
functionalTopConstr20Symbol =
symbol functionalTopConstr20Id [topSort, testSort] testSort
& total
& constructor
functionalTopConstr21Symbol :: Symbol
functionalTopConstr21Symbol =
symbol functionalTopConstr21Id [testSort, topSort] testSort
& total
& constructor
fMapSymbol :: Symbol
fMapSymbol =
symbol fMapId [mapSort] testSort & function
injective10Symbol :: Symbol
injective10Symbol = symbol injective10Id [testSort] testSort & injective
injective11Symbol :: Symbol
injective11Symbol = symbol injective11Id [testSort] testSort & injective
sortInjectionSymbol :: Sort -> Sort -> Symbol
sortInjectionSymbol fromSort toSort =
Symbol
{ symbolConstructor = sortInjectionId
, symbolParams = [fromSort, toSort]
, symbolAttributes = Mock.sortInjectionAttributes
, symbolSorts = applicationSorts [fromSort] toSort
}
sortInjection10Symbol :: Symbol
sortInjection10Symbol = sortInjectionSymbol testSort0 testSort
sortInjection11Symbol :: Symbol
sortInjection11Symbol = sortInjectionSymbol testSort1 testSort
sortInjection0ToTopSymbol :: Symbol
sortInjection0ToTopSymbol = sortInjectionSymbol testSort0 topSort
sortInjectionSubToTopSymbol :: Symbol
sortInjectionSubToTopSymbol = sortInjectionSymbol subSort topSort
sortInjectionSubSubToTopSymbol :: Symbol
sortInjectionSubSubToTopSymbol = sortInjectionSymbol subSubsort topSort
sortInjectionSubSubToSubSymbol :: Symbol
sortInjectionSubSubToSubSymbol = sortInjectionSymbol subSubsort subSort
sortInjectionSubSubToOtherSymbol :: Symbol
sortInjectionSubSubToOtherSymbol = sortInjectionSymbol subSubsort otherSort
sortInjectionSubOtherToOtherSymbol :: Symbol
sortInjectionSubOtherToOtherSymbol = sortInjectionSymbol subOthersort otherSort
sortInjectionSubOtherToTopSymbol :: Symbol
sortInjectionSubOtherToTopSymbol = sortInjectionSymbol subOthersort topSort
sortInjectionSubToTestSymbol :: Symbol
sortInjectionSubToTestSymbol = sortInjectionSymbol testSort topSort
sortInjectionTestToTopSymbol :: Symbol
sortInjectionTestToTopSymbol = sortInjectionSymbol subSort testSort
sortInjectionOtherToTopSymbol :: Symbol
sortInjectionOtherToTopSymbol = sortInjectionSymbol otherSort topSort
sortInjectionOtherToOverTheTopSymbol :: Symbol
sortInjectionOtherToOverTheTopSymbol =
sortInjectionSymbol otherSort overTheTopSort
sortInjectionSubToOverTheTopSymbol :: Symbol
sortInjectionSubToOverTheTopSymbol = sortInjectionSymbol subSort overTheTopSort
sortInjectionTopToOverTheTopSymbol :: Symbol
sortInjectionTopToOverTheTopSymbol = sortInjectionSymbol topSort overTheTopSort
sortInjectionOtherToOtherTopSymbol :: Symbol
sortInjectionOtherToOtherTopSymbol = sortInjectionSymbol otherSort otherTopSort
sortInjectionSubToOtherTopSymbol :: Symbol
sortInjectionSubToOtherTopSymbol = sortInjectionSymbol subSort otherTopSort
subsubOverloadSymbol :: Symbol
subsubOverloadSymbol =
symbol subsubOverloadId [subSubsort] subSubsort & total & injective
subOverloadSymbol :: Symbol
subOverloadSymbol =
symbol subOverloadId [subSort] subSort & total & injective
otherOverloadSymbol :: Symbol
otherOverloadSymbol =
symbol otherOverloadId [otherSort] otherSort & total & injective
topOverloadSymbol :: Symbol
topOverloadSymbol =
symbol topOverloadId [topSort] topSort & total & injective
unitMapSymbol :: Symbol
unitMapSymbol =
symbol unitMapId [] mapSort
& total
& hook "MAP.unit"
elementMapSymbol :: Symbol
elementMapSymbol =
symbol elementMapId [testSort, testSort] mapSort
& total
& hook "MAP.element"
concatMapSymbol :: Symbol
concatMapSymbol =
symbol concatMapId [mapSort, mapSort] mapSort
& function
& hook "MAP.concat"
opaqueMapSymbol :: Symbol
opaqueMapSymbol =
symbol opaqueMapId [testSort] mapSort
& function
inKeysMapSymbol :: Symbol
inKeysMapSymbol =
symbol inKeysMapId [testSort, mapSort] boolSort
& hook "MAP.in_keys"
lessIntSymbol :: Symbol
lessIntSymbol =
symbol lessIntId [intSort, intSort] boolSort
& total
& hook "INT.lt"
& smthook "<"
greaterEqIntSymbol :: Symbol
greaterEqIntSymbol =
symbol greaterEqIntId [intSort, intSort] boolSort
& total
& hook "INT.ge"
& smthook ">="
tdivIntSymbol :: Symbol
tdivIntSymbol =
symbol tdivIntId [intSort, intSort] intSort
& function
& hook "INT.tdiv"
& smthook "div"
concatListSymbol :: Symbol
concatListSymbol =
symbol concatListId [listSort, listSort] listSort
& total
& hook "LIST.concat"
elementListSymbol :: Symbol
elementListSymbol =
symbol elementListId [testSort] listSort
& total
& hook "LIST.element"
unitListSymbol :: Symbol
unitListSymbol = symbol unitListId [] listSort & total & hook "LIST.unit"
concatSetSymbol :: Symbol
concatSetSymbol =
symbol concatSetId [setSort, setSort] setSort
& function
& hook "SET.concat"
elementSetSymbol :: Symbol
elementSetSymbol =
symbol elementSetId [testSort] setSort & total & hook "SET.element"
unitSetSymbol :: Symbol
unitSetSymbol =
symbol unitSetId [] setSort & total & hook "SET.unit"
keqBoolSymbol :: Symbol
keqBoolSymbol =
symbol keqBoolId [testSort, testSort] boolSort
& function
& total
& hook "KEQUAL.eq"
opaqueSetSymbol :: Symbol
opaqueSetSymbol =
symbol opaqueSetId [testSort] setSort
& function
sigmaSymbol :: Symbol
sigmaSymbol =
symbol sigmaId [testSort, testSort] testSort
& total
& constructor
anywhereSymbol :: Symbol
anywhereSymbol =
symbol anywhereId [] testSort
& total
& Lens.set
(typed @Attribute.Symbol . typed @Attribute.Anywhere)
(Attribute.Anywhere True)
functionSMTSymbol :: Symbol
functionSMTSymbol =
symbol functionSMTId [testSort] testSort & function
functionalSMTSymbol :: Symbol
functionalSMTSymbol =
symbol functionalSMTId [testSort] testSort & function & total
type MockElementVariable = ElementVariable VariableName
pattern MockElementVariable ::
Id -> VariableCounter -> Sort -> MockElementVariable
pattern MockElementVariable base counter variableSort =
Variable
{ variableName = ElementVariableName VariableName{base, counter}
, variableSort
}
type MockRewritingElementVariable = ElementVariable RewritingVariableName
mkRuleElementVariable ::
Id -> VariableCounter -> Sort -> MockRewritingElementVariable
mkRuleElementVariable base counter variableSort =
Variable
{ variableName =
ElementVariableName $
mkRuleVariable VariableName{base, counter}
, variableSort
}
mkConfigElementVariable ::
Id -> VariableCounter -> Sort -> MockRewritingElementVariable
mkConfigElementVariable base counter variableSort =
Variable
{ variableName =
ElementVariableName $
mkConfigVariable VariableName{base, counter}
, variableSort
}
mkEquationElementVariable ::
Id -> VariableCounter -> Sort -> MockRewritingElementVariable
mkEquationElementVariable base counter variableSort =
Variable
{ variableName =
ElementVariableName $
mkEquationVariable VariableName{base, counter}
, variableSort
}
type MockSetVariable = SetVariable VariableName
pattern MockSetVariable ::
Id -> VariableCounter -> Sort -> MockSetVariable
pattern MockSetVariable base counter variableSort =
Variable
{ variableName = SetVariableName VariableName{base, counter}
, variableSort
}
type MockRewritingSetVariable = SetVariable RewritingVariableName
mkRuleSetVariable ::
Id -> VariableCounter -> Sort -> MockRewritingSetVariable
mkRuleSetVariable base counter variableSort =
Variable
{ variableName =
SetVariableName $
mkRuleVariable VariableName{base, counter}
, variableSort
}
mkConfigSetVariable ::
Id -> VariableCounter -> Sort -> MockRewritingSetVariable
mkConfigSetVariable base counter variableSort =
Variable
{ variableName =
SetVariableName $
mkConfigVariable VariableName{base, counter}
, variableSort
}
var_x_0 :: MockElementVariable
var_x_0 = MockElementVariable (testId "x") (Just (Element 0)) testSort
var_xRule_0 :: MockRewritingElementVariable
var_xRule_0 = mkRuleElementVariable (testId "x") (Just (Element 0)) testSort
var_xConfig_0 :: MockRewritingElementVariable
var_xConfig_0 = mkConfigElementVariable (testId "x") (Just (Element 0)) testSort
var_x_1 :: MockElementVariable
var_x_1 = MockElementVariable (testId "x") (Just (Element 1)) testSort
var_xRule_1 :: MockRewritingElementVariable
var_xRule_1 = mkRuleElementVariable (testId "x") (Just (Element 1)) testSort
var_xConfig_1 :: MockRewritingElementVariable
var_xConfig_1 = mkConfigElementVariable (testId "x") (Just (Element 1)) testSort
var_y_1 :: MockElementVariable
var_y_1 = MockElementVariable (testId "y") (Just (Element 1)) testSort
var_yRule_1 :: MockRewritingElementVariable
var_yRule_1 = mkRuleElementVariable (testId "y") (Just (Element 1)) testSort
var_yConfig_1 :: MockRewritingElementVariable
var_yConfig_1 = mkConfigElementVariable (testId "y") (Just (Element 1)) testSort
var_z_1 :: MockElementVariable
var_z_1 = MockElementVariable (testId "z") (Just (Element 1)) testSort
var_zRule_1 :: MockRewritingElementVariable
var_zRule_1 = mkRuleElementVariable (testId "z") (Just (Element 1)) testSort
var_zConfig_1 :: MockRewritingElementVariable
var_zConfig_1 = mkConfigElementVariable (testId "z") (Just (Element 1)) testSort
x :: MockElementVariable
x = MockElementVariable (testId "x") mempty testSort
xRule :: MockRewritingElementVariable
xRule = mkRuleElementVariable (testId "x") mempty testSort
xConfig :: MockRewritingElementVariable
xConfig = mkConfigElementVariable (testId "x") mempty testSort
setX :: MockSetVariable
setX = MockSetVariable (testId "@x") mempty testSort
setXRule :: MockRewritingSetVariable
setXRule = mkRuleSetVariable (testId "@x") mempty testSort
setXConfig :: MockRewritingSetVariable
setXConfig = mkConfigSetVariable (testId "@x") mempty testSort
var_setX_0 :: MockSetVariable
var_setX_0 = MockSetVariable (testId "@x") (Just (Element 0)) testSort
var_setXConfig_0 :: MockRewritingSetVariable
var_setXConfig_0 =
mkConfigSetVariable (testId "@x") (Just (Element 0)) testSort
var_setXRule_0 :: MockRewritingSetVariable
var_setXRule_0 =
mkRuleSetVariable (testId "@x") (Just (Element 0)) testSort
x0 :: MockElementVariable
x0 = MockElementVariable (testId "x0") mempty testSort0
xConfig0 :: MockRewritingElementVariable
xConfig0 = mkConfigElementVariable (testId "x0") mempty testSort0
y :: MockElementVariable
y = MockElementVariable (testId "y") mempty testSort
yRule :: MockRewritingElementVariable
yRule = mkRuleElementVariable (testId "y") mempty testSort
yConfig :: MockRewritingElementVariable
yConfig = mkConfigElementVariable (testId "y") mempty testSort
setY :: MockSetVariable
setY = MockSetVariable (testId "@y") mempty testSort
setYRule :: MockRewritingSetVariable
setYRule = mkRuleSetVariable (testId "@y") mempty testSort
setYConfig :: MockRewritingSetVariable
setYConfig = mkConfigSetVariable (testId "@y") mempty testSort
z :: MockElementVariable
z = MockElementVariable (testId "z") mempty testSort
zRule :: MockRewritingElementVariable
zRule = mkRuleElementVariable (testId "z") mempty testSort
zConfig :: MockRewritingElementVariable
zConfig = mkConfigElementVariable (testId "z") mempty testSort
zEquation :: MockRewritingElementVariable
zEquation = mkEquationElementVariable (testId "z") mempty testSort
t :: MockElementVariable
t = MockElementVariable (testId "t") mempty testSort
tRule :: MockRewritingElementVariable
tRule = mkRuleElementVariable (testId "t") mempty testSort
tConfig :: MockRewritingElementVariable
tConfig = mkConfigElementVariable (testId "t") mempty testSort
u :: MockElementVariable
u = MockElementVariable (testId "u") mempty testSort
uRule :: MockRewritingElementVariable
uRule = mkRuleElementVariable (testId "u") mempty testSort
uConfig :: MockRewritingElementVariable
uConfig = mkConfigElementVariable (testId "u") mempty testSort
m :: MockElementVariable
m = MockElementVariable (testId "m") mempty mapSort
mRule :: MockRewritingElementVariable
mRule = mkRuleElementVariable (testId "m") mempty mapSort
mConfig :: MockRewritingElementVariable
mConfig = mkConfigElementVariable (testId "m") mempty mapSort
xSet :: MockElementVariable
xSet = MockElementVariable (testId "xSet") mempty setSort
xRuleSet :: MockRewritingElementVariable
xRuleSet = mkRuleElementVariable (testId "xSet") mempty setSort
xConfigSet :: MockRewritingElementVariable
xConfigSet = mkConfigElementVariable (testId "xSet") mempty setSort
yConfigSet :: MockRewritingElementVariable
yConfigSet = mkConfigElementVariable (testId "ySet") mempty setSort
xEquationSet :: MockRewritingElementVariable
xEquationSet = mkEquationElementVariable (testId "xSet") mempty setSort
ySet :: MockElementVariable
ySet = MockElementVariable (testId "ySet") mempty setSort
yEquationSet :: MockRewritingElementVariable
yEquationSet = mkEquationElementVariable (testId "ySet") mempty setSort
xInt :: MockElementVariable
xInt = MockElementVariable (testId "xInt") mempty intSort
xRuleInt :: MockRewritingElementVariable
xRuleInt = mkRuleElementVariable (testId "xInt") mempty intSort
xConfigInt :: MockRewritingElementVariable
xConfigInt = mkConfigElementVariable (testId "xInt") mempty intSort
xEquationInt :: MockRewritingElementVariable
xEquationInt = mkEquationElementVariable (testId "xInt") mempty intSort
yInt :: MockElementVariable
yInt = MockElementVariable (testId "yInt") mempty intSort
yRuleInt :: MockRewritingElementVariable
yRuleInt = mkRuleElementVariable (testId "yInt") mempty intSort
yEquationInt :: MockRewritingElementVariable
yEquationInt = mkEquationElementVariable (testId "yInt") mempty intSort
xBool :: MockElementVariable
xBool = MockElementVariable (testId "xBool") mempty boolSort
xRuleBool :: MockRewritingElementVariable
xRuleBool = mkRuleElementVariable (testId "xBool") mempty boolSort
xConfigBool :: MockRewritingElementVariable
xConfigBool = mkConfigElementVariable (testId "xBool") mempty boolSort
xString :: MockElementVariable
xString = MockElementVariable (testId "xString") mempty stringSort
xRuleString :: MockRewritingElementVariable
xRuleString = mkRuleElementVariable (testId "xString") mempty stringSort
xConfigString :: MockRewritingElementVariable
xConfigString = mkConfigElementVariable (testId "xString") mempty stringSort
xList :: MockElementVariable
xList = MockElementVariable (testId "xList") mempty listSort
xConfigList :: MockRewritingElementVariable
xConfigList = mkConfigElementVariable (testId "xList") mempty listSort
xMap :: MockElementVariable
xMap = MockElementVariable (testId "xMap") mempty mapSort
yMap :: MockElementVariable
yMap = MockElementVariable (testId "yMap") mempty mapSort
zMap :: MockElementVariable
zMap = MockElementVariable (testId "zMap") mempty mapSort
xMapRule :: MockRewritingElementVariable
xMapRule = mkRuleElementVariable (testId "xMap") mempty mapSort
xMapConfig :: MockRewritingElementVariable
xMapConfig = mkConfigElementVariable (testId "xMap") mempty mapSort
yMapRule :: MockRewritingElementVariable
yMapRule = mkRuleElementVariable (testId "yMap") mempty mapSort
yMapConfig :: MockRewritingElementVariable
yMapConfig = mkConfigElementVariable (testId "yMap") mempty mapSort
zMapRule :: MockRewritingElementVariable
zMapRule = mkRuleElementVariable (testId "zMap") mempty mapSort
zMapConfig :: MockRewritingElementVariable
zMapConfig = mkConfigElementVariable (testId "zMap") mempty mapSort
xSubSort :: MockElementVariable
xSubSort = MockElementVariable (testId "xSubSort") mempty subSort
xRuleSubSort :: MockRewritingElementVariable
xRuleSubSort = mkRuleElementVariable (testId "xSubSort") mempty subSort
xConfigSubSort :: MockRewritingElementVariable
xConfigSubSort = mkConfigElementVariable (testId "xSubSort") mempty subSort
xSubSubSort :: MockElementVariable
xSubSubSort =
MockElementVariable (testId "xSubSubSort") mempty subSubsort
xConfigSubSubSort :: MockRewritingElementVariable
xConfigSubSubSort =
mkConfigElementVariable (testId "xSubSubSort") mempty subSubsort
xSubOtherSort :: MockElementVariable
xSubOtherSort =
MockElementVariable (testId "xSubOtherSort") mempty subOthersort
xRuleSubOtherSort :: MockRewritingElementVariable
xRuleSubOtherSort =
mkRuleElementVariable (testId "xSubOtherSort") mempty subOthersort
xConfigSubOtherSort :: MockRewritingElementVariable
xConfigSubOtherSort =
mkConfigElementVariable (testId "xSubOtherSort") mempty subOthersort
xOtherSort :: MockElementVariable
xOtherSort = MockElementVariable (testId "xOtherSort") mempty otherSort
xConfigOtherSort :: MockRewritingElementVariable
xConfigOtherSort = mkConfigElementVariable (testId "xOtherSort") mempty otherSort
xTopSort :: MockElementVariable
xTopSort = MockElementVariable (testId "xTopSort") mempty topSort
xConfigTopSort :: MockRewritingElementVariable
xConfigTopSort = mkConfigElementVariable (testId "xTopSort") mempty topSort
xStringMetaSort :: MockSetVariable
xStringMetaSort = MockSetVariable (testId "xStringMetaSort") mempty stringMetaSort
xRuleStringMetaSort :: MockRewritingSetVariable
xRuleStringMetaSort =
mkRuleSetVariable (testId "xStringMetaSort") mempty stringMetaSort
xConfigStringMetaSort :: MockRewritingSetVariable
xConfigStringMetaSort =
mkConfigSetVariable (testId "xStringMetaSort") mempty stringMetaSort
eConfigSubSubsort :: MockRewritingSetVariable
eConfigSubSubsort =
mkConfigSetVariable (testId "eConfigSubSubsort") mempty subSubsort
e2ConfigSubSubsort :: MockRewritingSetVariable
e2ConfigSubSubsort =
mkConfigSetVariable (testId "e2ConfigSubSubsort") mempty subSubsort
setXConfigSetSort :: MockRewritingSetVariable
setXConfigSetSort =
mkConfigSetVariable (testId "XSetSort") mempty setSort
setYConfigSetSort :: MockRewritingSetVariable
setYConfigSetSort =
mkConfigSetVariable (testId "YSetSort") mempty setSort
makeSomeVariable :: Text -> Sort -> SomeVariable VariableName
makeSomeVariable name variableSort =
Variable
{ variableSort
, variableName
}
where
variableName =
injectVariableName VariableName{base = testId name, counter = mempty}
injectVariableName
| Text.head name == '@' = inject . SetVariableName
| otherwise = inject . ElementVariableName
makeSomeConfigVariable :: Text -> Sort -> SomeVariable RewritingVariableName
makeSomeConfigVariable name variableSort =
Variable
{ variableSort
, variableName
}
where
variableName =
injectVariableName $
mkConfigVariable VariableName{base = testId name, counter = mempty}
injectVariableName
| Text.head name == '@' = inject . SetVariableName
| otherwise = inject . ElementVariableName
makeTestSomeVariable :: Text -> SomeVariable VariableName
makeTestSomeVariable = (`makeSomeVariable` testSort)
makeTestSomeConfigVariable :: Text -> SomeVariable RewritingVariableName
makeTestSomeConfigVariable = (`makeSomeConfigVariable` testSort)
mkTestSomeVariable :: Text -> TermLike VariableName
mkTestSomeVariable = Internal.mkVar . makeTestSomeVariable
mkTestSomeConfigVariable :: Text -> TermLike RewritingVariableName
mkTestSomeConfigVariable = Internal.mkVar . makeTestSomeConfigVariable
a :: InternalVariable variable => TermLike variable
a = Internal.mkApplySymbol aSymbol []
aConcrete :: TermLike Concrete
Just aConcrete = Internal.asConcrete (a :: TermLike VariableName)
aSort0 :: InternalVariable variable => TermLike variable
aSort0 = Internal.mkApplySymbol aSort0Symbol []
aSort1 :: InternalVariable variable => TermLike variable
aSort1 = Internal.mkApplySymbol aSort1Symbol []
aSubsort :: InternalVariable variable => TermLike variable
aSubsort = Internal.mkApplySymbol aSubsortSymbol []
aSubOthersort :: InternalVariable variable => TermLike variable
aSubOthersort = Internal.mkApplySymbol aSubOthersortSymbol []
aSubSubsort :: InternalVariable variable => TermLike variable
aSubSubsort = Internal.mkApplySymbol aSubSubsortSymbol []
aTopSort :: InternalVariable variable => TermLike variable
aTopSort = Internal.mkApplySymbol aTopSortSymbol []
aOtherSort :: InternalVariable variable => TermLike variable
aOtherSort = Internal.mkApplySymbol aOtherSortSymbol []
b :: InternalVariable variable => TermLike variable
b = Internal.mkApplySymbol bSymbol []
bConcrete :: TermLike Concrete
Just bConcrete = Internal.asConcrete (b :: TermLike VariableName)
bSort0 :: InternalVariable variable => TermLike variable
bSort0 = Internal.mkApplySymbol bSort0Symbol []
c :: InternalVariable variable => TermLike variable
c = Internal.mkApplySymbol cSymbol []
d :: InternalVariable variable => TermLike variable
d = Internal.mkApplySymbol dSymbol []
e :: InternalVariable variable => TermLike variable
e = Internal.mkApplySymbol eSymbol []
f
, g
, h ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
f arg = Internal.mkApplySymbol fSymbol [arg]
g arg = Internal.mkApplySymbol gSymbol [arg]
h arg = Internal.mkApplySymbol hSymbol [arg]
fSort0
, gSort0 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
fSort0 arg = Internal.mkApplySymbol fSort0Symbol [arg]
gSort0 arg = Internal.mkApplySymbol gSort0Symbol [arg]
cf :: InternalVariable variable => TermLike variable
cf = Internal.mkApplySymbol cfSymbol []
cfSort0 :: InternalVariable variable => TermLike variable
cfSort0 = Internal.mkApplySymbol cfSort0Symbol []
cfSort1 :: InternalVariable variable => TermLike variable
cfSort1 = Internal.mkApplySymbol cfSort1Symbol []
cg :: InternalVariable variable => TermLike variable
cg = Internal.mkApplySymbol cgSymbol []
cgSort0 :: InternalVariable variable => TermLike variable
cgSort0 = Internal.mkApplySymbol cgSort0Symbol []
ch :: InternalVariable variable => TermLike variable
ch = Internal.mkApplySymbol chSymbol []
fSet ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
fSet arg = Internal.mkApplySymbol fSetSymbol [arg]
fSet2 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
fSet2 arg1 arg2 = Internal.mkApplySymbol fSet2Symbol [arg1, arg2]
fTestInt ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
fTestInt arg = Internal.mkApplySymbol fTestIntSymbol [arg]
fTestFunctionalInt ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
fTestFunctionalInt arg =
Internal.mkApplySymbol fTestFunctionalIntSymbol [arg]
fInt ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
fInt arg = Internal.mkApplySymbol fIntSymbol [arg]
fBool ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
fBool arg = Internal.mkApplySymbol fBoolSymbol [arg]
fString ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
fString arg = Internal.mkApplySymbol fStringSymbol [arg]
plain00 :: InternalVariable variable => TermLike variable
plain00 = Internal.mkApplySymbol plain00Symbol []
plain00Sort0 :: InternalVariable variable => TermLike variable
plain00Sort0 = Internal.mkApplySymbol plain00Sort0Symbol []
plain00Subsort :: InternalVariable variable => TermLike variable
plain00Subsort = Internal.mkApplySymbol plain00SubsortSymbol []
plain00OtherSort :: InternalVariable variable => TermLike variable
plain00OtherSort = Internal.mkApplySymbol plain00OtherSortSymbol []
plain00SubSubsort :: InternalVariable variable => TermLike variable
plain00SubSubsort = Internal.mkApplySymbol plain00SubSubsortSymbol []
plain10
, plain11 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
plain10 arg = Internal.mkApplySymbol plain10Symbol [arg]
plain11 arg = Internal.mkApplySymbol plain11Symbol [arg]
plain20 ::
InternalVariable variable =>
TermLike variable ->
TermLike variable ->
TermLike variable
plain20 arg1 arg2 = Internal.mkApplySymbol plain20Symbol [arg1, arg2]
constr00 :: InternalVariable variable => HasCallStack => TermLike variable
constr00 = Internal.mkApplySymbol constr00Symbol []
constr10
, constr11
, constrInt ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
constr10 arg = Internal.mkApplySymbol constr10Symbol [arg]
constr11 arg = Internal.mkApplySymbol constr11Symbol [arg]
constrInt arg = Internal.mkApplySymbol constrIntSymbol [arg]
constr20 ::
InternalVariable variable =>
TermLike variable ->
TermLike variable ->
TermLike variable
constr20 arg1 arg2 = Internal.mkApplySymbol constr20Symbol [arg1, arg2]
constrFunct20TestMap ::
InternalVariable variable =>
TermLike variable ->
TermLike variable ->
TermLike variable
constrFunct20TestMap arg1 arg2 =
Internal.mkApplySymbol constrFunct20TestMapSymbol [arg1, arg2]
function20MapTest ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
function20MapTest arg1 arg2 =
Internal.mkApplySymbol function20MapTestSymbol [arg1, arg2]
functional00 :: InternalVariable variable => TermLike variable
functional00 = Internal.mkApplySymbol functional00Symbol []
functional01 :: InternalVariable variable => TermLike variable
functional01 = Internal.mkApplySymbol functional01Symbol []
functional10 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
functional10 arg = Internal.mkApplySymbol functional10Symbol [arg]
functional11 ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
functional11 arg = Internal.mkApplySymbol functional11Symbol [arg]
functional20 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
functional20 arg1 arg2 = Internal.mkApplySymbol functional20Symbol [arg1, arg2]
functional00SubSubSort :: InternalVariable variable => TermLike variable
functional00SubSubSort =
Internal.mkApplySymbol functional00SubSubSortSymbol []
functionalInjective00 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable
functionalInjective00 =
Internal.mkApplySymbol functionalInjective00Symbol []
functionalConstr10 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
functionalConstr10 arg =
Internal.mkApplySymbol functionalConstr10Symbol [arg]
functionalConstr11 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
functionalConstr11 arg = Internal.mkApplySymbol functionalConstr11Symbol [arg]
functionalConstr12 ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
functionalConstr12 arg = Internal.mkApplySymbol functionalConstr12Symbol [arg]
functionalConstr20 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
functionalConstr20 arg1 arg2 =
Internal.mkApplySymbol functionalConstr20Symbol [arg1, arg2]
functionalConstr21 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
functionalConstr21 arg1 arg2 =
Internal.mkApplySymbol functionalConstr21Symbol [arg1, arg2]
functionalConstr30 ::
InternalVariable variable =>
TermLike variable ->
TermLike variable ->
TermLike variable ->
TermLike variable
functionalConstr30 arg1 arg2 arg3 =
Internal.mkApplySymbol functionalConstr30Symbol [arg1, arg2, arg3]
functionalTopConstr20 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
functionalTopConstr20 arg1 arg2 =
Internal.mkApplySymbol functionalTopConstr20Symbol [arg1, arg2]
functionalTopConstr21 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
functionalTopConstr21 arg1 arg2 =
Internal.mkApplySymbol functionalTopConstr21Symbol [arg1, arg2]
subsubOverload ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
subsubOverload arg1 =
Internal.mkApplySymbol subsubOverloadSymbol [arg1]
subOverload ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
subOverload arg1 =
Internal.mkApplySymbol subOverloadSymbol [arg1]
otherOverload ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
otherOverload arg1 =
Internal.mkApplySymbol otherOverloadSymbol [arg1]
topOverload ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
topOverload arg1 =
Internal.mkApplySymbol topOverloadSymbol [arg1]
injective10 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
injective10 arg = Internal.mkApplySymbol injective10Symbol [arg]
injective11 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
injective11 arg = Internal.mkApplySymbol injective11Symbol [arg]
sortInjection ::
InternalVariable variable =>
Sort ->
TermLike variable ->
TermLike variable
sortInjection injTo termLike =
(synthesize . Internal.InjF)
Internal.Inj
{ injConstructor
, injFrom
, injTo
, injChild = termLike
, injAttributes
}
where
injFrom = Internal.termLikeSort termLike
Symbol{symbolConstructor = injConstructor} = symbol'
Symbol{symbolAttributes = injAttributes} = symbol'
symbol' = sortInjectionSymbol injFrom injTo
sortInjection10 ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjection10 = sortInjection testSort
sortInjection11 ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjection11 = sortInjection testSort
sortInjection0ToTop ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjection0ToTop = sortInjection topSort
sortInjectionSubToTop ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionSubToTop = sortInjection topSort
sortInjectionSubSubToTop ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionSubSubToTop = sortInjection topSort
sortInjectionSubSubToSub ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionSubSubToSub = sortInjection subSort
sortInjectionSubSubToOther ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionSubSubToOther = sortInjection otherSort
sortInjectionSubOtherToOther ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionSubOtherToOther = sortInjection otherSort
sortInjectionSubOtherToTop ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionSubOtherToTop = sortInjection topSort
sortInjectionOtherToOverTheTop ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionOtherToOverTheTop = sortInjection overTheTopSort
sortInjectionSubToOverTheTop ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionSubToOverTheTop = sortInjection overTheTopSort
sortInjectionTopToOverTheTop ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionTopToOverTheTop = sortInjection overTheTopSort
sortInjectionSubToTest ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionSubToTest = sortInjection testSort
sortInjectionTestToTop ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionTestToTop = sortInjection topSort
sortInjectionOtherToTop ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionOtherToTop = sortInjection topSort
sortInjectionOtherToOtherTop ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionOtherToOtherTop = sortInjection otherTopSort
sortInjectionSubToOtherTop ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionSubToOtherTop = sortInjection otherTopSort
unitMap :: InternalVariable variable => TermLike variable
unitMap = Internal.mkApplySymbol unitMapSymbol []
elementMap ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
elementMap m1 m2 = Internal.mkApplySymbol elementMapSymbol [m1, m2]
concatMap ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
concatMap m1 m2 = Internal.mkApplySymbol concatMapSymbol [m1, m2]
opaqueMap ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
opaqueMap term = Internal.mkApplySymbol opaqueMapSymbol [term]
inKeysMap ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
inKeysMap element m1 = Internal.mkApplySymbol inKeysMapSymbol [element, m1]
unitSet :: InternalVariable variable => TermLike variable
unitSet = Internal.mkApplySymbol unitSetSymbol []
elementSet ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
elementSet s1 = Internal.mkApplySymbol elementSetSymbol [s1]
concatSet ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
concatSet s1 s2 = Internal.mkApplySymbol concatSetSymbol [s1, s2]
opaqueSet ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
opaqueSet term = Internal.mkApplySymbol opaqueSetSymbol [term]
lessInt ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
lessInt i1 i2 = Internal.mkApplySymbol lessIntSymbol [i1, i2]
greaterEqInt ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
greaterEqInt i1 i2 = Internal.mkApplySymbol greaterEqIntSymbol [i1, i2]
tdivInt ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
tdivInt i1 i2 = Internal.mkApplySymbol tdivIntSymbol [i1, i2]
concatList ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
concatList l1 l2 = Internal.mkApplySymbol concatListSymbol [l1, l2]
elementList ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
elementList element = Internal.mkApplySymbol elementListSymbol [element]
unitList ::
InternalVariable variable =>
HasCallStack =>
TermLike variable
unitList = Internal.mkApplySymbol unitListSymbol []
keqBool ::
InternalVariable variable =>
TermLike variable ->
TermLike variable ->
TermLike variable
keqBool t1 t2 = Internal.mkApplySymbol keqBoolSymbol [t1, t2]
sigma ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
sigma child1 child2 = Internal.mkApplySymbol sigmaSymbol [child1, child2]
anywhere :: InternalVariable variable => TermLike variable
anywhere = Internal.mkApplySymbol anywhereSymbol []
functionSMT
, functionalSMT ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
functionSMT arg =
Internal.mkApplySymbol functionSMTSymbol [arg]
functionalSMT arg =
Internal.mkApplySymbol functionalSMTSymbol [arg]
attributesMapping :: [(SymbolOrAlias, Attribute.Symbol)]
attributesMapping =
map (liftA2 (,) toSymbolOrAlias symbolAttributes) symbols
symbols :: [Symbol]
symbols =
[ aSymbol
, aSort0Symbol
, aSort1Symbol
, aSubsortSymbol
, aSubOthersortSymbol
, aSubSubsortSymbol
, aTopSortSymbol
, aOtherSortSymbol
, bSymbol
, bSort0Symbol
, cSymbol
, dSymbol
, eSymbol
, fSymbol
, fSort0Symbol
, gSymbol
, gSort0Symbol
, hSymbol
, cfSymbol
, cfSort0Symbol
, cfSort1Symbol
, cgSymbol
, cgSort0Symbol
, chSymbol
, fSetSymbol
, fIntSymbol
, fTestIntSymbol
, plain00Symbol
, plain00Sort0Symbol
, plain00SubsortSymbol
, plain00SubSubsortSymbol
, plain00OtherSortSymbol
, plain10Symbol
, plain11Symbol
, plain20Symbol
, constr00Symbol
, constr10Symbol
, constr11Symbol
, constr20Symbol
, constrFunct20TestMapSymbol
, function20MapTestSymbol
, functional00Symbol
, functional01Symbol
, functional10Symbol
, functional11Symbol
, functional20Symbol
, functional00SubSubSortSymbol
, functionalInjective00Symbol
, functionalConstr10Symbol
, functionalConstr11Symbol
, functionalConstr12Symbol
, functionalConstr20Symbol
, functionalConstr21Symbol
, functionalConstr30Symbol
, functionalTopConstr20Symbol
, functionalTopConstr21Symbol
, injective10Symbol
, injective11Symbol
, sortInjection10Symbol
, sortInjection11Symbol
, sortInjection0ToTopSymbol
, sortInjectionSubToTopSymbol
, sortInjectionSubSubToTopSymbol
, sortInjectionSubSubToSubSymbol
, sortInjectionSubSubToOtherSymbol
, sortInjectionSubOtherToOtherSymbol
, sortInjectionSubOtherToTopSymbol
, sortInjectionSubToTestSymbol
, sortInjectionTestToTopSymbol
, sortInjectionOtherToTopSymbol
, sortInjectionOtherToOverTheTopSymbol
, sortInjectionSubToOverTheTopSymbol
, sortInjectionTopToOverTheTopSymbol
, sortInjectionSubToOtherTopSymbol
, sortInjectionOtherToOtherTopSymbol
, unitMapSymbol
, elementMapSymbol
, concatMapSymbol
, opaqueMapSymbol
, concatListSymbol
, elementListSymbol
, unitListSymbol
, concatSetSymbol
, elementSetSymbol
, unitSetSymbol
, opaqueSetSymbol
, lessIntSymbol
, greaterEqIntSymbol
, tdivIntSymbol
, keqBoolSymbol
, sigmaSymbol
, anywhereSymbol
, subsubOverloadSymbol
, subOverloadSymbol
, otherOverloadSymbol
, topOverloadSymbol
, functionSMTSymbol
, functionalSMTSymbol
]
sortAttributesMapping :: [(Sort, Attribute.Sort)]
sortAttributesMapping =
[
( testSort
, Default.def
)
,
( testSort0
, Default.def
)
,
( testSort1
, Default.def
)
,
( topSort
, Default.def
)
,
( subSort
, Default.def
)
,
( subOthersort
, Default.def
)
,
( subSubsort
, Default.def
)
,
( otherSort
, Default.def
)
,
( otherTopSort
, Default.def
)
,
( mapSort
, Default.def
{ AttributeSort.hook = Hook (Just "MAP.Map")
, Attribute.unit =
Attribute.Unit (Just $ toSymbolOrAlias unitMapSymbol)
, Attribute.element =
Attribute.Element (Just $ toSymbolOrAlias elementMapSymbol)
, Attribute.concat =
Attribute.Concat (Just $ toSymbolOrAlias concatMapSymbol)
}
)
,
( listSort
, Default.def
{ AttributeSort.hook = Hook (Just "LIST.List")
, Attribute.unit =
Attribute.Unit (Just $ toSymbolOrAlias unitListSymbol)
, Attribute.element =
Attribute.Element (Just $ toSymbolOrAlias elementListSymbol)
, Attribute.concat =
Attribute.Concat (Just $ toSymbolOrAlias concatListSymbol)
}
)
,
( setSort
, Default.def
{ AttributeSort.hook = Hook (Just "SET.Set")
, Attribute.unit =
Attribute.Unit (Just $ toSymbolOrAlias unitSetSymbol)
, Attribute.element =
Attribute.Element (Just $ toSymbolOrAlias elementSetSymbol)
, Attribute.concat =
Attribute.Concat (Just $ toSymbolOrAlias concatSetSymbol)
}
)
,
( intSort
, Default.def{AttributeSort.hook = Hook (Just "INT.Int")}
)
,
( boolSort
, Default.def{AttributeSort.hook = Hook (Just "BOOL.Bool")}
)
,
( stringSort
, Default.def{AttributeSort.hook = Hook (Just "STRING.String")}
)
, -- Also add attributes for the implicitly defined sorts.
( stringMetaSort
, Default.def{AttributeSort.hook = Hook (Just "STRING.String")}
)
]
headSortsMapping :: [(SymbolOrAlias, ApplicationSorts)]
headSortsMapping =
map ((,) <$> toSymbolOrAlias <*> symbolSorts) symbols
zeroarySmtSort :: Id -> SMT.UnresolvedSort
zeroarySmtSort sortId =
SMT.Sort
{ sortData = SMT.ConstSExpr encodedId
, sortDeclaration =
SMT.SortDeclarationSort
SMT.SortDeclaration
{ name = SMT.encodable sortId
, arity = 0
}
}
where
encodedId = SMT.encode (SMT.encodable sortId)
builtinZeroarySmtSort :: SMT.SExpr -> SMT.UnresolvedSort
builtinZeroarySmtSort sExpr =
SMT.Sort
{ sortData = SMT.ConstSExpr sExpr
, sortDeclaration = SMT.SortDeclaredIndirectly (SMT.AlreadyEncoded sExpr)
}
smtBuiltinSymbol ::
Text -> [Sort] -> Sort -> SMT.UnresolvedSymbol
smtBuiltinSymbol builtin argumentSorts resultSort =
SMT.Symbol
{ symbolData = SMT.Atom builtin
, symbolDeclaration =
SMT.SymbolBuiltin
SMT.IndirectSymbolDeclaration
{ name = SMT.AlreadyEncoded $ SMT.Atom builtin
, sortDependencies =
SMT.SortReference <$> resultSort : argumentSorts
}
}
smtDeclaredSymbol ::
Text -> Id -> [Sort] -> Sort -> SMT.UnresolvedSymbol
smtDeclaredSymbol smtName id' argumentSorts resultSort =
SMT.Symbol
{ symbolData = SMT.Atom smtName
, symbolDeclaration =
SMT.SymbolDeclaredDirectly
SMT.FunctionDeclaration
{ name = SMT.encodable id'
, inputSorts = SMT.SortReference <$> argumentSorts
, resultSort = SMT.SortReference resultSort
}
}
emptySmtDeclarations :: SMT.SmtDeclarations
emptySmtDeclarations =
SMT.Declarations
{ sorts = Map.empty
, symbols = Map.empty
}
smtDeclarations :: SMT.SmtDeclarations
smtDeclarations = SMT.resolve smtUnresolvedDeclarations
smtUnresolvedDeclarations :: SMT.UnresolvedDeclarations
smtUnresolvedDeclarations =
SMT.Declarations
{ sorts =
Map.fromList
[ (testSort0Id, zeroarySmtSort testSort0Id)
, (testSort1Id, zeroarySmtSort testSort1Id)
, (topSortId, zeroarySmtSort topSortId)
, (topSortId, zeroarySmtSort subSortId)
, (topSortId, zeroarySmtSort subSubsortId)
, (topSortId, zeroarySmtSort otherSortId)
, -- TODO(virgil): testSort has constructors, it should have a
-- constructor-based definition. The same for others.
(testSortId, zeroarySmtSort testSortId)
, (intSortId, builtinZeroarySmtSort SMT.tInt)
, (boolSortId, builtinZeroarySmtSort SMT.tBool)
]
, symbols =
Map.fromList
[ (lessIntId, smtBuiltinSymbol "<" [intSort, intSort] boolSort)
, (greaterEqIntId, smtBuiltinSymbol ">=" [intSort, intSort] boolSort)
, (tdivIntId, smtBuiltinSymbol "div" [intSort, intSort] intSort)
,
( functional00Id
, smtDeclaredSymbol "functional00" functional00Id [] testSort
)
,
( functionSMTId
, smtDeclaredSymbol "functionSMT" functionSMTId [testSort] testSort
)
,
( functionalSMTId
, smtDeclaredSymbol "functionalSMT" functionalSMTId [testSort] testSort
)
]
}
sortConstructors :: Map.Map Id Attribute.Constructors
sortConstructors =
-- TODO(virgil): testSort has constructors, it should have a
-- constructor-based definition. The same for others.
Map.empty
testSortId :: Id
testSortId = testId "testSort"
testSort0Id :: Id
testSort0Id = testId "testSort0"
testSort1Id :: Id
testSort1Id = testId "testSort1"
topSortId :: Id
topSortId = testId "topSort"
overTheTopSortId :: Id
overTheTopSortId = testId "overTheTopSort"
subSortId :: Id
subSortId = testId "subSort"
subOthersortId :: Id
subOthersortId = testId "subOthersort"
subSubsortId :: Id
subSubsortId = testId "subSubsort"
otherSortId :: Id
otherSortId = testId "otherSort"
otherTopSortId :: Id
otherTopSortId = testId "otherTopSort"
intSortId :: Id
intSortId = testId "intSort"
boolSortId :: Id
boolSortId = testId "boolSort"
stringSortId :: Id
stringSortId = testId "stringSort"
testSort :: Sort
testSort =
SortActualSort
SortActual
{ sortActualName = testSortId
, sortActualSorts = []
}
testSort0 :: Sort
testSort0 =
SortActualSort
SortActual
{ sortActualName = testSort0Id
, sortActualSorts = []
}
testSort1 :: Sort
testSort1 =
SortActualSort
SortActual
{ sortActualName = testSort1Id
, sortActualSorts = []
}
topSort :: Sort
topSort =
SortActualSort
SortActual
{ sortActualName = topSortId
, sortActualSorts = []
}
overTheTopSort :: Sort
overTheTopSort =
SortActualSort
SortActual
{ sortActualName = overTheTopSortId
, sortActualSorts = []
}
subSort :: Sort
subSort =
SortActualSort
SortActual
{ sortActualName = subSortId
, sortActualSorts = []
}
subOthersort :: Sort
subOthersort =
SortActualSort
SortActual
{ sortActualName = subOthersortId
, sortActualSorts = []
}
subSubsort :: Sort
subSubsort =
SortActualSort
SortActual
{ sortActualName = subSubsortId
, sortActualSorts = []
}
otherSort :: Sort
otherSort =
SortActualSort
SortActual
{ sortActualName = otherSortId
, sortActualSorts = []
}
otherTopSort :: Sort
otherTopSort =
SortActualSort
SortActual
{ sortActualName = otherTopSortId
, sortActualSorts = []
}
mapSort :: Sort
mapSort =
SortActualSort
SortActual
{ sortActualName = testId "mapSort"
, sortActualSorts = []
}
setSort :: Sort
setSort =
SortActualSort
SortActual
{ sortActualName = testId "setSort"
, sortActualSorts = []
}
listSort :: Sort
listSort =
SortActualSort
SortActual
{ sortActualName = testId "listSort"
, sortActualSorts = []
}
intSort :: Sort
intSort =
SortActualSort
SortActual
{ sortActualName = intSortId
, sortActualSorts = []
}
stringSort :: Sort
stringSort =
SortActualSort
SortActual
{ sortActualName = stringSortId
, sortActualSorts = []
}
boolSort :: Sort
boolSort =
SortActualSort
SortActual
{ sortActualName = boolSortId
, sortActualSorts = []
}
subsorts :: [(Sort, Sort)]
subsorts =
[ (subSubsort, subSort)
, (subSubsort, topSort)
, (subSort, topSort)
, (testSort, topSort)
, (subSubsort, otherSort)
, (subOthersort, otherSort)
, (otherSort, topSort)
, (otherSort, otherTopSort)
, (subSort, otherTopSort)
, (subSort, testSort)
, (testSort0, testSort)
, (mapSort, testSort)
, (listSort, testSort)
, (topSort, overTheTopSort)
]
overloads :: [(Symbol, Symbol)]
overloads =
[ (subOverloadSymbol, subsubOverloadSymbol)
, (otherOverloadSymbol, subsubOverloadSymbol)
, (topOverloadSymbol, subsubOverloadSymbol)
, (topOverloadSymbol, subOverloadSymbol)
, (topOverloadSymbol, otherOverloadSymbol)
]
builtinMap ::
InternalVariable variable =>
[(TermLike variable, TermLike variable)] ->
TermLike variable
builtinMap elements = framedMap elements []
test_builtinMap :: [TestTree]
test_builtinMap =
[ testCase "constructor-like keys" $ do
let input = builtinMap [(a, a), (b, b)] :: TermLike VariableName
assertBool "" (isConstructorLike input)
, testCase "symbolic keys" $ do
let input = builtinMap [(f a, a), (f b, b)] :: TermLike VariableName
assertBool "" (not $ isConstructorLike input)
]
framedMap ::
InternalVariable variable =>
[(TermLike variable, TermLike variable)] ->
[TermLike variable] ->
TermLike variable
framedMap elements opaque =
framedInternalMap elements opaque & Internal.mkInternalMap
framedInternalMap ::
[(TermLike variable, TermLike variable)] ->
[TermLike variable] ->
InternalMap Internal.Key (TermLike variable)
framedInternalMap elements opaque =
InternalAc
{ builtinAcSort = mapSort
, builtinAcUnit = unitMapSymbol
, builtinAcElement = elementMapSymbol
, builtinAcConcat = concatMapSymbol
, builtinAcChild =
NormalizedMap
NormalizedAc
{ elementsWithVariables = wrapElement <$> abstractElements
, concreteElements
, opaque
}
}
where
asConcrete element@(key, value) =
(,) <$> retractKey key <*> pure value
& maybe (Left element) Right
(abstractElements, HashMap.fromList -> concreteElements) =
asConcrete . Bifunctor.second MapValue <$> elements
& partitionEithers
builtinList ::
InternalVariable variable =>
[TermLike variable] ->
TermLike variable
builtinList child =
Internal.mkInternalList
InternalList
{ internalListSort = listSort
, internalListUnit = unitListSymbol
, internalListElement = elementListSymbol
, internalListConcat = concatListSymbol
, internalListChild = Seq.fromList child
}
builtinSet ::
InternalVariable variable =>
[TermLike variable] ->
TermLike variable
builtinSet elements = framedSet elements []
test_builtinSet :: [TestTree]
test_builtinSet =
[ testCase "constructor-like keys" $ do
let input = builtinSet [a, b] :: TermLike VariableName
assertBool "" (isConstructorLike input)
, testCase "symbolic keys" $ do
let input = builtinSet [f a, f b] :: TermLike VariableName
assertBool "" (not $ isConstructorLike input)
]
framedSet ::
InternalVariable variable =>
[TermLike variable] ->
[TermLike variable] ->
TermLike variable
framedSet elements opaque =
framedInternalSet elements opaque & Internal.mkInternalSet
framedInternalSet ::
[TermLike variable] ->
[TermLike variable] ->
InternalSet Internal.Key (TermLike variable)
framedInternalSet elements opaque =
InternalAc
{ builtinAcSort = setSort
, builtinAcUnit = unitSetSymbol
, builtinAcElement = elementSetSymbol
, builtinAcConcat = concatSetSymbol
, builtinAcChild =
NormalizedSet
NormalizedAc
{ elementsWithVariables = wrapElement <$> abstractElements
, concreteElements
, opaque
}
}
where
asConcrete key =
do
Monad.guard (isConstructorLike key)
(,) <$> retractKey key <*> pure SetValue
& maybe (Left (key, SetValue)) Right
(abstractElements, HashMap.fromList -> concreteElements) =
asConcrete <$> elements
& partitionEithers
builtinInt ::
Integer ->
TermLike variable
builtinInt = Builtin.Int.asInternal intSort
builtinBool ::
InternalVariable variable =>
Bool ->
TermLike variable
builtinBool = Builtin.Bool.asInternal boolSort
builtinString ::
Text ->
TermLike variable
builtinString = Builtin.String.asInternal stringSort
emptyMetadataTools :: SmtMetadataTools Attribute.Symbol
emptyMetadataTools =
Mock.makeMetadataTools
[] -- attributesMapping
[] -- headTypeMapping
[] -- sortAttributesMapping
emptySmtDeclarations
Map.empty -- sortConstructors
metadataTools :: SmtMetadataTools Attribute.Symbol
metadataTools =
Mock.makeMetadataTools
attributesMapping
sortAttributesMapping
headSortsMapping
smtDeclarations
sortConstructors
axiomEquations :: Map AxiomIdentifier [Equation RewritingVariableName]
axiomEquations = Map.empty
predicateSimplifier :: ConditionSimplifier Simplifier
predicateSimplifier =
Simplifier.Condition.create SubstitutionSimplifier.substitutionSimplifier
sortGraph :: SortGraph.SortGraph
sortGraph =
SortGraph.fromSubsorts
[Subsort{subsort, supersort} | (subsort, supersort) <- subsorts]
injSimplifier :: InjSimplifier
injSimplifier = mkInjSimplifier sortGraph
overloadGraph :: OverloadGraph.OverloadGraph
overloadGraph = OverloadGraph.fromOverloads overloads
overloadSimplifier :: OverloadSimplifier
overloadSimplifier = mkOverloadSimplifier overloadGraph Test.Kore.Rewrite.MockSymbols.injSimplifier
TODO(Ana ): if needed , create copy with experimental simplifier
-- enabled
env :: Env
env =
Env
{ metadataTools = Test.Kore.Rewrite.MockSymbols.metadataTools
, simplifierCondition = predicateSimplifier
, simplifierPattern = Pattern.makeEvaluate
, simplifierTerm = TermLike.simplify
, axiomEquations = Test.Kore.Rewrite.MockSymbols.axiomEquations
, memo = Memo.forgetful
, injSimplifier = Test.Kore.Rewrite.MockSymbols.injSimplifier
, overloadSimplifier = Test.Kore.Rewrite.MockSymbols.overloadSimplifier
, hookedSymbols = Map.empty
}
generatorSetup :: ConsistentKore.Setup
generatorSetup =
ConsistentKore.Setup
{ allSymbols = filter doesNotHaveArguments symbols
, allAliases = []
, allSorts = filter (/= otherTopSort) $ map fst sortAttributesMapping
, freeElementVariables = Set.empty
, freeSetVariables = Set.empty
, maybeIntSort = Just intSort
, maybeBoolSort = Just boolSort
, maybeListSorts =
Just
ConsistentKore.CollectionSorts
{ collectionSort = listSort
, elementSort = testSort
}
, maybeMapSorts = Nothing
, -- TODO(virgil): fill the maybeMapSorts field after implementing
-- map generators.
maybeSetSorts = Nothing
, -- TODO(virgil): fill the maybeSetSorts field after implementing
-- map generators
maybeStringLiteralSort = Just stringMetaSort
, maybeStringBuiltinSort = Just stringSort
, metadataTools = Test.Kore.Rewrite.MockSymbols.metadataTools
}
where
doesNotHaveArguments Symbol{symbolParams} = null symbolParams
-- | ensure that test data can be generated using the above setup
test_canGenerateConsistentTerms :: TestTree
test_canGenerateConsistentTerms =
testGroup "can generate consistent terms for all given sorts" $
map mkTest testSorts
where
testSorts = ConsistentKore.allSorts generatorSetup
sizes = map Range.Size [1 .. 10]
mkTest :: Sort -> TestTree
mkTest sort@(SortActualSort SortActual{sortActualName = InternedId{getInternedId}}) =
testGroup
(show getInternedId)
[ testProperty (show size) . withTests 1 . property $ do
r <-
forAll . Gen.resize size $
ConsistentKore.runKoreGen
generatorSetup
(ConsistentKore.termLikeGenWithSort sort)
-- just test that this works
Hedgehog.diff 0 (<) (length $ show r)
| size <- sizes
]
mkTest SortVariableSort{} =
error "Found a sort variable in the generator setup"
builtinSimplifiers :: Map Id Text
builtinSimplifiers =
Map.fromList
[
( unitMapId
, Map.unitKey
)
,
( elementMapId
, Map.elementKey
)
,
( concatMapId
, Map.concatKey
)
,
( unitSetId
, Set.unitKey
)
,
( elementSetId
, Set.elementKey
)
,
( concatSetId
, Set.concatKey
)
,
( unitListId
, List.unitKey
)
,
( elementListId
, List.elementKey
)
,
( concatListId
, List.concatKey
)
,
( tdivIntId
, Builtin.Int.tdivKey
)
,
( lessIntId
, Builtin.Int.ltKey
)
,
( greaterEqIntId
, Builtin.Int.geKey
)
,
( keqBoolId
, Builtin.KEqual.eqKey
)
]
verifiedModuleContext :: PatternVerifier.Context
verifiedModuleContext =
PatternVerifier.verifiedModuleContext
IndexedModule.IndexedModuleSyntax
{ indexedModuleName = ModuleName "MOCK"
, indexedModuleAliasSentences = mempty
, indexedModuleSymbolSentences =
Map.fromList
[ ( symbolConstructor
,
( symbolAttributes
, SentenceSymbol
{ sentenceSymbolSymbol =
Kore.Syntax.Sentence.Symbol
{ symbolConstructor
, symbolParams = []
}
, sentenceSymbolSorts = applicationSortsOperands
, sentenceSymbolResultSort = applicationSortsResult
, sentenceSymbolAttributes = Default.def
}
)
)
| Symbol
{ symbolConstructor
, symbolAttributes
, symbolSorts =
ApplicationSorts
{ applicationSortsOperands
, applicationSortsResult
}
} <-
allSymbols
]
, indexedModuleSortDescriptions =
Map.fromList
[ (sortActualName, (attr{Attribute.hasDomainValues = Attribute.HasDomainValues True}, SentenceSort sortActualName [] Default.def))
| (SortActualSort (SortActual{sortActualName}), attr) <- sortAttributesMapping
]
, indexedModuleImportsSyntax = mempty
, indexedModuleHookedIdentifiers = mempty
}
& PatternVerifier.withBuiltinVerifiers Builtin.koreVerifiers
where
ConsistentKore.Setup{allSymbols} = generatorSetup
| null | https://raw.githubusercontent.com/runtimeverification/haskell-backend/93a705112305a2d7e084e98dca93ec33e0d661d5/kore/test/Test/Kore/Rewrite/MockSymbols.hs | haskell | Also add attributes for the implicitly defined sorts.
TODO(virgil): testSort has constructors, it should have a
constructor-based definition. The same for others.
TODO(virgil): testSort has constructors, it should have a
constructor-based definition. The same for others.
attributesMapping
headTypeMapping
sortAttributesMapping
sortConstructors
enabled
TODO(virgil): fill the maybeMapSorts field after implementing
map generators.
TODO(virgil): fill the maybeSetSorts field after implementing
map generators
| ensure that test data can be generated using the above setup
just test that this works | # OPTIONS_GHC -Wno - incomplete - uni - patterns #
# OPTIONS_GHC -Wno - missing - export - lists #
module Test.Kore.Rewrite.MockSymbols where
Intended usage :
* Import qualified .
* use attributesMapping to build mock MetadataTools .
* Use things like a , b , c , x , y , z for testing .
RULES :
* Everything that does not obey the default rules must be clearly
specified in the name , e.g. ' constantNotTotal ' .
* constant symbols are , by default , total .
* constant functions are called cf , cg , ch .
* constant constructors are called a , b , c , ...
* one - element functions are called f , , h.
* constructors are called " constr < n><k > " where n is the arity and k is used
to differentiate between them ( both are one - digit ) .
* total constructors are called " totalConstr < n><k > "
* total symbols are called " total < n><k > "
* symbols without any special attribute are called " plain < n><k > "
* variables are called x , y , z ...
* Import qualified.
* use attributesMapping to build mock MetadataTools.
* Use things like a, b, c, x, y, z for testing.
RULES:
* Everything that does not obey the default rules must be clearly
specified in the name, e.g. 'constantNotTotal'.
* constant symbols are, by default, total.
* constant functions are called cf, cg, ch.
* constant constructors are called a, b, c, ...
* one-element functions are called f, g, h.
* constructors are called "constr<n><k>" where n is the arity and k is used
to differentiate between them (both are one-digit).
* total constructors are called "totalConstr<n><k>"
* total symbols are called "total<n><k>"
* symbols without any special attribute are called "plain<n><k>"
* variables are called x, y, z...
-}
import Control.Lens qualified as Lens
import Control.Monad qualified as Monad
import Data.Bifunctor qualified as Bifunctor
import Data.Default qualified as Default
import Data.Generics.Product
import Data.HashMap.Strict qualified as HashMap
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Sequence qualified as Seq
import Data.Set qualified as Set
import Data.Sup
import Data.Text (
Text,
)
import Data.Text qualified as Text
import Hedgehog (diff, forAll, property, withTests)
import Hedgehog.Gen qualified as Gen
import Hedgehog.Range qualified as Range
import Kore.Attribute.Hook (
Hook (..),
)
import Kore.Attribute.Pattern.ConstructorLike (
isConstructorLike,
)
import Kore.Attribute.Sort qualified as Attribute
import Kore.Attribute.Sort qualified as AttributeSort
import Kore.Attribute.Sort.Concat qualified as Attribute
import Kore.Attribute.Sort.Constructors qualified as Attribute (
Constructors,
)
import Kore.Attribute.Sort.Element qualified as Attribute
import Kore.Attribute.Sort.HasDomainValues qualified as Attribute
import Kore.Attribute.Sort.Unit qualified as Attribute
import Kore.Attribute.Subsort
import Kore.Attribute.Symbol qualified as Attribute
import Kore.Attribute.Synthetic (
synthesize,
)
import Kore.Builtin qualified as Builtin
import Kore.Builtin.Bool qualified as Builtin.Bool
import Kore.Builtin.Int qualified as Builtin.Int
import Kore.Builtin.KEqual qualified as Builtin.KEqual
import Kore.Builtin.List qualified as List
import Kore.Builtin.Map.Map qualified as Map
import Kore.Builtin.Set.Set qualified as Set
import Kore.Builtin.String qualified as Builtin.String
import Kore.Equation (Equation)
import Kore.IndexedModule.IndexedModule qualified as IndexedModule
import Kore.IndexedModule.MetadataTools (
SmtMetadataTools,
)
import Kore.IndexedModule.OverloadGraph qualified as OverloadGraph
import Kore.IndexedModule.SortGraph qualified as SortGraph
import Kore.Internal.InternalList
import Kore.Internal.InternalMap
import Kore.Internal.InternalSet
import Kore.Internal.Symbol hiding (
isConstructorLike,
sortInjection,
)
import Kore.Internal.TermLike (
InternalVariable,
TermLike,
retractKey,
)
import Kore.Internal.TermLike qualified as Internal
import Kore.Rewrite.Axiom.Identifier (AxiomIdentifier)
import Kore.Rewrite.Function.Memo qualified as Memo
import Kore.Rewrite.RewritingVariable (
RewritingVariableName,
mkConfigVariable,
mkEquationVariable,
mkRuleVariable,
)
import Kore.Rewrite.SMT.AST qualified as SMT
import Kore.Rewrite.SMT.Representation.Resolve qualified as SMT (
resolve,
)
import Kore.Simplify.Condition qualified as Simplifier.Condition
import Kore.Simplify.InjSimplifier
import Kore.Simplify.OverloadSimplifier
import Kore.Simplify.Pattern qualified as Pattern
import Kore.Simplify.Simplify (
ConditionSimplifier,
Env (..),
Simplifier,
)
import Kore.Simplify.SubstitutionSimplifier qualified as SubstitutionSimplifier
import Kore.Simplify.TermLike qualified as TermLike
import Kore.Sort
import Kore.Syntax.Application
import Kore.Syntax.Module (ModuleName (..))
import Kore.Syntax.Sentence (SentenceSort (..), SentenceSymbol (..))
import Kore.Syntax.Sentence qualified
import Kore.Syntax.Variable
import Kore.Validate.PatternVerifier qualified as PatternVerifier
import Prelude.Kore
import SMT.AST qualified as SMT
import SMT.SimpleSMT qualified as SMT
import Test.ConsistentKore qualified as ConsistentKore (
CollectionSorts (..),
Setup (..),
runKoreGen,
termLikeGenWithSort,
)
import Test.Kore (
testId,
)
import Test.Kore.IndexedModule.MockMetadataTools qualified as Mock
import Test.Tasty
import Test.Tasty.HUnit.Ext
import Test.Tasty.Hedgehog (testProperty)
aId :: Id
aId = testId "a"
aSort0Id :: Id
aSort0Id = testId "aSort0"
aSort1Id :: Id
aSort1Id = testId "aSort1"
aSubsortId :: Id
aSubsortId = testId "aSubsort"
aSubOthersortId :: Id
aSubOthersortId = testId "aSubOthersort"
aSubSubsortId :: Id
aSubSubsortId = testId "aSubSubsort"
aTopSortId :: Id
aTopSortId = testId "aTopSort"
aOtherSortId :: Id
aOtherSortId = testId "aOtherSort"
bId :: Id
bId = testId "b"
bSort0Id :: Id
bSort0Id = testId "bSort0"
cId :: Id
cId = testId "c"
dId :: Id
dId = testId "d"
eId :: Id
eId = testId "e"
fId :: Id
fId = testId "f"
fMapId :: Id
fMapId = testId "fMap"
fSort0Id :: Id
fSort0Id = testId "fSort0"
gId :: Id
gId = testId "g"
gSort0Id :: Id
gSort0Id = testId "gSort0"
hId :: Id
hId = testId "h"
cfId :: Id
cfId = testId "cf"
cfSort0Id :: Id
cfSort0Id = testId "cfSort0"
cfSort1Id :: Id
cfSort1Id = testId "cfSort1"
cgId :: Id
cgId = testId "cg"
cgSort0Id :: Id
cgSort0Id = testId "cgSort0"
chId :: Id
chId = testId "ch"
fSetId :: Id
fSetId = testId "fSet"
fSet2Id :: Id
fSet2Id = testId "fSet2"
fIntId :: Id
fIntId = testId "fInt"
fBoolId :: Id
fBoolId = testId "fBool"
fStringId :: Id
fStringId = testId "fString"
fTestIntId :: Id
fTestIntId = testId "fTestInt"
fTestFunctionalIntId :: Id
fTestFunctionalIntId = testId "fTestFunctionalInt"
plain00Id :: Id
plain00Id = testId "plain00"
plain00Sort0Id :: Id
plain00Sort0Id = testId "plain00Sort0"
plain00SubsortId :: Id
plain00SubsortId = testId "plain00Subsort"
plain00OtherSortId :: Id
plain00OtherSortId = testId "plain00OtherSort"
plain00SubSubsortId :: Id
plain00SubSubsortId = testId "plain00SubSubsort"
plain10Id :: Id
plain10Id = testId "plain10"
plain11Id :: Id
plain11Id = testId "plain11"
plain20Id :: Id
plain20Id = testId "plain20"
constr00Id :: Id
constr00Id = testId "constr00"
constr10Id :: Id
constr10Id = testId "constr10"
constr11Id :: Id
constr11Id = testId "constr11"
constr20Id :: Id
constr20Id = testId "constr20"
constrFunct20TestMapId :: Id
constrFunct20TestMapId = testId "constrFunct20TestMap"
function20MapTestId :: Id
function20MapTestId = testId "function20MapTest"
functional00Id :: Id
functional00Id = testId "functional00"
functional01Id :: Id
functional01Id = testId "functional01"
functional10Id :: Id
functional10Id = testId "functional10"
functional11Id :: Id
functional11Id = testId "functional11"
functional20Id :: Id
functional20Id = testId "functional20"
functional00SubSubSortId :: Id
functional00SubSubSortId = testId "functional00SubSubSort"
functionalInjective00Id :: Id
functionalInjective00Id = testId "functionalInjective00"
functionalConstr10Id :: Id
functionalConstr10Id = testId "functionalConstr10"
functionalConstr11Id :: Id
functionalConstr11Id = testId "functionalConstr11"
functionalConstr12Id :: Id
functionalConstr12Id = testId "functionalConstr12"
functionalConstr20Id :: Id
functionalConstr20Id = testId "functionalConstr20"
functionalConstr21Id :: Id
functionalConstr21Id = testId "functionalConstr21"
functionalConstr30Id :: Id
functionalConstr30Id = testId "functionalConstr30"
functionalTopConstr20Id :: Id
functionalTopConstr20Id = testId "functionalTopConstr20"
functionalTopConstr21Id :: Id
functionalTopConstr21Id = testId "functionalTopConstr21"
injective10Id :: Id
injective10Id = testId "injective10"
injective11Id :: Id
injective11Id = testId "injective11"
sortInjectionId :: Id
sortInjectionId = testId "sortInjection"
unitMapId :: Id
unitMapId = testId "unitMap"
elementMapId :: Id
elementMapId = testId "elementMap"
concatMapId :: Id
concatMapId = testId "concatMap"
opaqueMapId :: Id
opaqueMapId = testId "opaqueMap"
inKeysMapId :: Id
inKeysMapId = testId "inKeys"
lessIntId :: Id
lessIntId = testId "lessIntId"
greaterEqIntId :: Id
greaterEqIntId = testId "greaterEqIntId"
tdivIntId :: Id
tdivIntId = testId "tdivIntId"
concatListId :: Id
concatListId = testId "concatList"
elementListId :: Id
elementListId = testId "elementList"
unitListId :: Id
unitListId = testId "unitList"
concatSetId :: Id
concatSetId = testId "concatSet"
opaqueSetId :: Id
opaqueSetId = testId "opaqueSet"
elementSetId :: Id
elementSetId = testId "elementSet"
unitSetId :: Id
unitSetId = testId "unitSet"
keqBoolId :: Id
keqBoolId = testId "keqBool"
sigmaId :: Id
sigmaId = testId "sigma"
anywhereId :: Id
anywhereId = testId "anywhere"
subsubOverloadId :: Id
subsubOverloadId = testId "subsubOverload"
subOverloadId :: Id
subOverloadId = testId "subOverload"
otherOverloadId :: Id
otherOverloadId = testId "otherOverload"
topOverloadId :: Id
topOverloadId = testId "topOverload"
functionSMTId :: Id
functionSMTId = testId "functionSMT"
functionalSMTId :: Id
functionalSMTId = testId "functionalSMT"
symbol :: Id -> [Sort] -> Sort -> Symbol
symbol name operands result =
Symbol
{ symbolConstructor = name
, symbolParams = []
, symbolAttributes = Default.def
, symbolSorts = applicationSorts operands result
}
aSymbol :: Symbol
aSymbol = symbol aId [] testSort & total & constructor
aSort0Symbol :: Symbol
aSort0Symbol = symbol aSort0Id [] testSort0 & total & constructor
aSort1Symbol :: Symbol
aSort1Symbol = symbol aSort1Id [] testSort1 & total & constructor
aSubsortSymbol :: Symbol
aSubsortSymbol = symbol aSubsortId [] subSort & total & constructor
aSubOthersortSymbol :: Symbol
aSubOthersortSymbol =
symbol aSubOthersortId [] subOthersort & total & constructor
aSubSubsortSymbol :: Symbol
aSubSubsortSymbol =
symbol aSubSubsortId [] subSubsort & total & constructor
aTopSortSymbol :: Symbol
aTopSortSymbol = symbol aTopSortId [] topSort & total & constructor
aOtherSortSymbol :: Symbol
aOtherSortSymbol = symbol aOtherSortId [] otherSort & total & constructor
bSymbol :: Symbol
bSymbol = symbol bId [] testSort & total & constructor
bSort0Symbol :: Symbol
bSort0Symbol = symbol bSort0Id [] testSort0 & total & constructor
cSymbol :: Symbol
cSymbol = symbol cId [] testSort & total & constructor
dSymbol :: Symbol
dSymbol = symbol dId [] testSort & total & constructor
eSymbol :: Symbol
eSymbol = symbol eId [] testSort & total & constructor
fSymbol :: Symbol
fSymbol = symbol fId [testSort] testSort & function
fSort0Symbol :: Symbol
fSort0Symbol = symbol fSort0Id [testSort0] testSort0 & function
gSymbol :: Symbol
gSymbol = symbol gId [testSort] testSort & function
gSort0Symbol :: Symbol
gSort0Symbol = symbol gSort0Id [testSort0] testSort0 & function
hSymbol :: Symbol
hSymbol = symbol hId [testSort] testSort & function
cfSymbol :: Symbol
cfSymbol = symbol cfId [] testSort & function
cfSort0Symbol :: Symbol
cfSort0Symbol = symbol cfSort0Id [] testSort0 & function
cfSort1Symbol :: Symbol
cfSort1Symbol = symbol cfSort1Id [] testSort1 & function
cgSymbol :: Symbol
cgSymbol = symbol cgId [] testSort & function
cgSort0Symbol :: Symbol
cgSort0Symbol = symbol cgSort0Id [] testSort0 & function
chSymbol :: Symbol
chSymbol = symbol chId [] testSort & function
fSetSymbol :: Symbol
fSetSymbol = symbol fSetId [setSort] setSort & function
fSet2Symbol :: Symbol
fSet2Symbol = symbol fSet2Id [setSort, setSort] setSort & function
fIntSymbol :: Symbol
fIntSymbol = symbol fIntId [intSort] intSort & function
fBoolSymbol :: Symbol
fBoolSymbol = symbol fBoolId [boolSort] boolSort & function
fStringSymbol :: Symbol
fStringSymbol = symbol fStringId [stringSort] stringSort & function
fTestIntSymbol :: Symbol
fTestIntSymbol = symbol fTestIntId [testSort] intSort & function
fTestFunctionalIntSymbol :: Symbol
fTestFunctionalIntSymbol =
symbol fTestFunctionalIntId [testSort] intSort & function & total
plain00Symbol :: Symbol
plain00Symbol = symbol plain00Id [] testSort
plain00Sort0Symbol :: Symbol
plain00Sort0Symbol = symbol plain00Sort0Id [] testSort0
plain00SubsortSymbol :: Symbol
plain00SubsortSymbol = symbol plain00SubsortId [] subSort
plain00OtherSortSymbol :: Symbol
plain00OtherSortSymbol = symbol plain00OtherSortId [] otherSort
plain00SubSubsortSymbol :: Symbol
plain00SubSubsortSymbol = symbol plain00SubSubsortId [] subSubsort
plain10Symbol :: Symbol
plain10Symbol = symbol plain10Id [testSort] testSort
plain11Symbol :: Symbol
plain11Symbol = symbol plain11Id [testSort] testSort
plain20Symbol :: Symbol
plain20Symbol = symbol plain20Id [testSort, testSort] testSort
constr00Symbol :: Symbol
constr00Symbol = symbol constr00Id [] testSort & constructor
constr10Symbol :: Symbol
constr10Symbol = symbol constr10Id [testSort] testSort & constructor
constr11Symbol :: Symbol
constr11Symbol = symbol constr11Id [testSort] testSort & constructor
constr20Symbol :: Symbol
constr20Symbol = symbol constr20Id [testSort, testSort] testSort & constructor
constrIntSymbol :: Symbol
constrIntSymbol = symbol constr10Id [intSort] intSort & constructor
constrFunct20TestMapSymbol :: Symbol
constrFunct20TestMapSymbol =
symbol constrFunct20TestMapId [testSort, mapSort] testSort
& constructor
& function
function20MapTestSymbol :: Symbol
function20MapTestSymbol =
symbol function20MapTestId [mapSort, testSort] testSort & function
functional00Symbol :: Symbol
functional00Symbol = symbol functional00Id [] testSort & total
functional01Symbol :: Symbol
functional01Symbol = symbol functional01Id [] testSort & total
functional10Symbol :: Symbol
functional10Symbol = symbol functional10Id [testSort] testSort & total
functional11Symbol :: Symbol
functional11Symbol = symbol functional11Id [testSort] testSort & total
functional20Symbol :: Symbol
functional20Symbol =
symbol functional20Id [testSort, testSort] testSort & total
functional00SubSubSortSymbol :: Symbol
functional00SubSubSortSymbol =
symbol functional00SubSubSortId [] subSubsort & total
functionalInjective00Symbol :: Symbol
functionalInjective00Symbol =
symbol functionalInjective00Id [] testSort & total & injective
functionalConstr10Symbol :: Symbol
functionalConstr10Symbol =
symbol functionalConstr10Id [testSort] testSort & total & constructor
functionalConstr11Symbol :: Symbol
functionalConstr11Symbol =
symbol functionalConstr11Id [testSort] testSort & total & constructor
functionalConstr12Symbol :: Symbol
functionalConstr12Symbol =
symbol functionalConstr12Id [testSort] testSort & total & constructor
functionalConstr20Symbol :: Symbol
functionalConstr20Symbol =
symbol functionalConstr20Id [testSort, testSort] testSort
& total
& constructor
functionalConstr21Symbol :: Symbol
functionalConstr21Symbol =
symbol functionalConstr21Id [testSort, testSort] testSort
& total
& constructor
functionalConstr30Symbol :: Symbol
functionalConstr30Symbol =
symbol functionalConstr30Id [testSort, testSort, testSort] testSort
& total
& constructor
functionalTopConstr20Symbol :: Symbol
functionalTopConstr20Symbol =
symbol functionalTopConstr20Id [topSort, testSort] testSort
& total
& constructor
functionalTopConstr21Symbol :: Symbol
functionalTopConstr21Symbol =
symbol functionalTopConstr21Id [testSort, topSort] testSort
& total
& constructor
fMapSymbol :: Symbol
fMapSymbol =
symbol fMapId [mapSort] testSort & function
injective10Symbol :: Symbol
injective10Symbol = symbol injective10Id [testSort] testSort & injective
injective11Symbol :: Symbol
injective11Symbol = symbol injective11Id [testSort] testSort & injective
sortInjectionSymbol :: Sort -> Sort -> Symbol
sortInjectionSymbol fromSort toSort =
Symbol
{ symbolConstructor = sortInjectionId
, symbolParams = [fromSort, toSort]
, symbolAttributes = Mock.sortInjectionAttributes
, symbolSorts = applicationSorts [fromSort] toSort
}
sortInjection10Symbol :: Symbol
sortInjection10Symbol = sortInjectionSymbol testSort0 testSort
sortInjection11Symbol :: Symbol
sortInjection11Symbol = sortInjectionSymbol testSort1 testSort
sortInjection0ToTopSymbol :: Symbol
sortInjection0ToTopSymbol = sortInjectionSymbol testSort0 topSort
sortInjectionSubToTopSymbol :: Symbol
sortInjectionSubToTopSymbol = sortInjectionSymbol subSort topSort
sortInjectionSubSubToTopSymbol :: Symbol
sortInjectionSubSubToTopSymbol = sortInjectionSymbol subSubsort topSort
sortInjectionSubSubToSubSymbol :: Symbol
sortInjectionSubSubToSubSymbol = sortInjectionSymbol subSubsort subSort
sortInjectionSubSubToOtherSymbol :: Symbol
sortInjectionSubSubToOtherSymbol = sortInjectionSymbol subSubsort otherSort
sortInjectionSubOtherToOtherSymbol :: Symbol
sortInjectionSubOtherToOtherSymbol = sortInjectionSymbol subOthersort otherSort
sortInjectionSubOtherToTopSymbol :: Symbol
sortInjectionSubOtherToTopSymbol = sortInjectionSymbol subOthersort topSort
sortInjectionSubToTestSymbol :: Symbol
sortInjectionSubToTestSymbol = sortInjectionSymbol testSort topSort
sortInjectionTestToTopSymbol :: Symbol
sortInjectionTestToTopSymbol = sortInjectionSymbol subSort testSort
sortInjectionOtherToTopSymbol :: Symbol
sortInjectionOtherToTopSymbol = sortInjectionSymbol otherSort topSort
sortInjectionOtherToOverTheTopSymbol :: Symbol
sortInjectionOtherToOverTheTopSymbol =
sortInjectionSymbol otherSort overTheTopSort
sortInjectionSubToOverTheTopSymbol :: Symbol
sortInjectionSubToOverTheTopSymbol = sortInjectionSymbol subSort overTheTopSort
sortInjectionTopToOverTheTopSymbol :: Symbol
sortInjectionTopToOverTheTopSymbol = sortInjectionSymbol topSort overTheTopSort
sortInjectionOtherToOtherTopSymbol :: Symbol
sortInjectionOtherToOtherTopSymbol = sortInjectionSymbol otherSort otherTopSort
sortInjectionSubToOtherTopSymbol :: Symbol
sortInjectionSubToOtherTopSymbol = sortInjectionSymbol subSort otherTopSort
subsubOverloadSymbol :: Symbol
subsubOverloadSymbol =
symbol subsubOverloadId [subSubsort] subSubsort & total & injective
subOverloadSymbol :: Symbol
subOverloadSymbol =
symbol subOverloadId [subSort] subSort & total & injective
otherOverloadSymbol :: Symbol
otherOverloadSymbol =
symbol otherOverloadId [otherSort] otherSort & total & injective
topOverloadSymbol :: Symbol
topOverloadSymbol =
symbol topOverloadId [topSort] topSort & total & injective
unitMapSymbol :: Symbol
unitMapSymbol =
symbol unitMapId [] mapSort
& total
& hook "MAP.unit"
elementMapSymbol :: Symbol
elementMapSymbol =
symbol elementMapId [testSort, testSort] mapSort
& total
& hook "MAP.element"
concatMapSymbol :: Symbol
concatMapSymbol =
symbol concatMapId [mapSort, mapSort] mapSort
& function
& hook "MAP.concat"
opaqueMapSymbol :: Symbol
opaqueMapSymbol =
symbol opaqueMapId [testSort] mapSort
& function
inKeysMapSymbol :: Symbol
inKeysMapSymbol =
symbol inKeysMapId [testSort, mapSort] boolSort
& hook "MAP.in_keys"
lessIntSymbol :: Symbol
lessIntSymbol =
symbol lessIntId [intSort, intSort] boolSort
& total
& hook "INT.lt"
& smthook "<"
greaterEqIntSymbol :: Symbol
greaterEqIntSymbol =
symbol greaterEqIntId [intSort, intSort] boolSort
& total
& hook "INT.ge"
& smthook ">="
tdivIntSymbol :: Symbol
tdivIntSymbol =
symbol tdivIntId [intSort, intSort] intSort
& function
& hook "INT.tdiv"
& smthook "div"
concatListSymbol :: Symbol
concatListSymbol =
symbol concatListId [listSort, listSort] listSort
& total
& hook "LIST.concat"
elementListSymbol :: Symbol
elementListSymbol =
symbol elementListId [testSort] listSort
& total
& hook "LIST.element"
unitListSymbol :: Symbol
unitListSymbol = symbol unitListId [] listSort & total & hook "LIST.unit"
concatSetSymbol :: Symbol
concatSetSymbol =
symbol concatSetId [setSort, setSort] setSort
& function
& hook "SET.concat"
elementSetSymbol :: Symbol
elementSetSymbol =
symbol elementSetId [testSort] setSort & total & hook "SET.element"
unitSetSymbol :: Symbol
unitSetSymbol =
symbol unitSetId [] setSort & total & hook "SET.unit"
keqBoolSymbol :: Symbol
keqBoolSymbol =
symbol keqBoolId [testSort, testSort] boolSort
& function
& total
& hook "KEQUAL.eq"
opaqueSetSymbol :: Symbol
opaqueSetSymbol =
symbol opaqueSetId [testSort] setSort
& function
sigmaSymbol :: Symbol
sigmaSymbol =
symbol sigmaId [testSort, testSort] testSort
& total
& constructor
anywhereSymbol :: Symbol
anywhereSymbol =
symbol anywhereId [] testSort
& total
& Lens.set
(typed @Attribute.Symbol . typed @Attribute.Anywhere)
(Attribute.Anywhere True)
functionSMTSymbol :: Symbol
functionSMTSymbol =
symbol functionSMTId [testSort] testSort & function
functionalSMTSymbol :: Symbol
functionalSMTSymbol =
symbol functionalSMTId [testSort] testSort & function & total
type MockElementVariable = ElementVariable VariableName
pattern MockElementVariable ::
Id -> VariableCounter -> Sort -> MockElementVariable
pattern MockElementVariable base counter variableSort =
Variable
{ variableName = ElementVariableName VariableName{base, counter}
, variableSort
}
type MockRewritingElementVariable = ElementVariable RewritingVariableName
mkRuleElementVariable ::
Id -> VariableCounter -> Sort -> MockRewritingElementVariable
mkRuleElementVariable base counter variableSort =
Variable
{ variableName =
ElementVariableName $
mkRuleVariable VariableName{base, counter}
, variableSort
}
mkConfigElementVariable ::
Id -> VariableCounter -> Sort -> MockRewritingElementVariable
mkConfigElementVariable base counter variableSort =
Variable
{ variableName =
ElementVariableName $
mkConfigVariable VariableName{base, counter}
, variableSort
}
mkEquationElementVariable ::
Id -> VariableCounter -> Sort -> MockRewritingElementVariable
mkEquationElementVariable base counter variableSort =
Variable
{ variableName =
ElementVariableName $
mkEquationVariable VariableName{base, counter}
, variableSort
}
type MockSetVariable = SetVariable VariableName
pattern MockSetVariable ::
Id -> VariableCounter -> Sort -> MockSetVariable
pattern MockSetVariable base counter variableSort =
Variable
{ variableName = SetVariableName VariableName{base, counter}
, variableSort
}
type MockRewritingSetVariable = SetVariable RewritingVariableName
mkRuleSetVariable ::
Id -> VariableCounter -> Sort -> MockRewritingSetVariable
mkRuleSetVariable base counter variableSort =
Variable
{ variableName =
SetVariableName $
mkRuleVariable VariableName{base, counter}
, variableSort
}
mkConfigSetVariable ::
Id -> VariableCounter -> Sort -> MockRewritingSetVariable
mkConfigSetVariable base counter variableSort =
Variable
{ variableName =
SetVariableName $
mkConfigVariable VariableName{base, counter}
, variableSort
}
var_x_0 :: MockElementVariable
var_x_0 = MockElementVariable (testId "x") (Just (Element 0)) testSort
var_xRule_0 :: MockRewritingElementVariable
var_xRule_0 = mkRuleElementVariable (testId "x") (Just (Element 0)) testSort
var_xConfig_0 :: MockRewritingElementVariable
var_xConfig_0 = mkConfigElementVariable (testId "x") (Just (Element 0)) testSort
var_x_1 :: MockElementVariable
var_x_1 = MockElementVariable (testId "x") (Just (Element 1)) testSort
var_xRule_1 :: MockRewritingElementVariable
var_xRule_1 = mkRuleElementVariable (testId "x") (Just (Element 1)) testSort
var_xConfig_1 :: MockRewritingElementVariable
var_xConfig_1 = mkConfigElementVariable (testId "x") (Just (Element 1)) testSort
var_y_1 :: MockElementVariable
var_y_1 = MockElementVariable (testId "y") (Just (Element 1)) testSort
var_yRule_1 :: MockRewritingElementVariable
var_yRule_1 = mkRuleElementVariable (testId "y") (Just (Element 1)) testSort
var_yConfig_1 :: MockRewritingElementVariable
var_yConfig_1 = mkConfigElementVariable (testId "y") (Just (Element 1)) testSort
var_z_1 :: MockElementVariable
var_z_1 = MockElementVariable (testId "z") (Just (Element 1)) testSort
var_zRule_1 :: MockRewritingElementVariable
var_zRule_1 = mkRuleElementVariable (testId "z") (Just (Element 1)) testSort
var_zConfig_1 :: MockRewritingElementVariable
var_zConfig_1 = mkConfigElementVariable (testId "z") (Just (Element 1)) testSort
x :: MockElementVariable
x = MockElementVariable (testId "x") mempty testSort
xRule :: MockRewritingElementVariable
xRule = mkRuleElementVariable (testId "x") mempty testSort
xConfig :: MockRewritingElementVariable
xConfig = mkConfigElementVariable (testId "x") mempty testSort
setX :: MockSetVariable
setX = MockSetVariable (testId "@x") mempty testSort
setXRule :: MockRewritingSetVariable
setXRule = mkRuleSetVariable (testId "@x") mempty testSort
setXConfig :: MockRewritingSetVariable
setXConfig = mkConfigSetVariable (testId "@x") mempty testSort
var_setX_0 :: MockSetVariable
var_setX_0 = MockSetVariable (testId "@x") (Just (Element 0)) testSort
var_setXConfig_0 :: MockRewritingSetVariable
var_setXConfig_0 =
mkConfigSetVariable (testId "@x") (Just (Element 0)) testSort
var_setXRule_0 :: MockRewritingSetVariable
var_setXRule_0 =
mkRuleSetVariable (testId "@x") (Just (Element 0)) testSort
x0 :: MockElementVariable
x0 = MockElementVariable (testId "x0") mempty testSort0
xConfig0 :: MockRewritingElementVariable
xConfig0 = mkConfigElementVariable (testId "x0") mempty testSort0
y :: MockElementVariable
y = MockElementVariable (testId "y") mempty testSort
yRule :: MockRewritingElementVariable
yRule = mkRuleElementVariable (testId "y") mempty testSort
yConfig :: MockRewritingElementVariable
yConfig = mkConfigElementVariable (testId "y") mempty testSort
setY :: MockSetVariable
setY = MockSetVariable (testId "@y") mempty testSort
setYRule :: MockRewritingSetVariable
setYRule = mkRuleSetVariable (testId "@y") mempty testSort
setYConfig :: MockRewritingSetVariable
setYConfig = mkConfigSetVariable (testId "@y") mempty testSort
z :: MockElementVariable
z = MockElementVariable (testId "z") mempty testSort
zRule :: MockRewritingElementVariable
zRule = mkRuleElementVariable (testId "z") mempty testSort
zConfig :: MockRewritingElementVariable
zConfig = mkConfigElementVariable (testId "z") mempty testSort
zEquation :: MockRewritingElementVariable
zEquation = mkEquationElementVariable (testId "z") mempty testSort
t :: MockElementVariable
t = MockElementVariable (testId "t") mempty testSort
tRule :: MockRewritingElementVariable
tRule = mkRuleElementVariable (testId "t") mempty testSort
tConfig :: MockRewritingElementVariable
tConfig = mkConfigElementVariable (testId "t") mempty testSort
u :: MockElementVariable
u = MockElementVariable (testId "u") mempty testSort
uRule :: MockRewritingElementVariable
uRule = mkRuleElementVariable (testId "u") mempty testSort
uConfig :: MockRewritingElementVariable
uConfig = mkConfigElementVariable (testId "u") mempty testSort
m :: MockElementVariable
m = MockElementVariable (testId "m") mempty mapSort
mRule :: MockRewritingElementVariable
mRule = mkRuleElementVariable (testId "m") mempty mapSort
mConfig :: MockRewritingElementVariable
mConfig = mkConfigElementVariable (testId "m") mempty mapSort
xSet :: MockElementVariable
xSet = MockElementVariable (testId "xSet") mempty setSort
xRuleSet :: MockRewritingElementVariable
xRuleSet = mkRuleElementVariable (testId "xSet") mempty setSort
xConfigSet :: MockRewritingElementVariable
xConfigSet = mkConfigElementVariable (testId "xSet") mempty setSort
yConfigSet :: MockRewritingElementVariable
yConfigSet = mkConfigElementVariable (testId "ySet") mempty setSort
xEquationSet :: MockRewritingElementVariable
xEquationSet = mkEquationElementVariable (testId "xSet") mempty setSort
ySet :: MockElementVariable
ySet = MockElementVariable (testId "ySet") mempty setSort
yEquationSet :: MockRewritingElementVariable
yEquationSet = mkEquationElementVariable (testId "ySet") mempty setSort
xInt :: MockElementVariable
xInt = MockElementVariable (testId "xInt") mempty intSort
xRuleInt :: MockRewritingElementVariable
xRuleInt = mkRuleElementVariable (testId "xInt") mempty intSort
xConfigInt :: MockRewritingElementVariable
xConfigInt = mkConfigElementVariable (testId "xInt") mempty intSort
xEquationInt :: MockRewritingElementVariable
xEquationInt = mkEquationElementVariable (testId "xInt") mempty intSort
yInt :: MockElementVariable
yInt = MockElementVariable (testId "yInt") mempty intSort
yRuleInt :: MockRewritingElementVariable
yRuleInt = mkRuleElementVariable (testId "yInt") mempty intSort
yEquationInt :: MockRewritingElementVariable
yEquationInt = mkEquationElementVariable (testId "yInt") mempty intSort
xBool :: MockElementVariable
xBool = MockElementVariable (testId "xBool") mempty boolSort
xRuleBool :: MockRewritingElementVariable
xRuleBool = mkRuleElementVariable (testId "xBool") mempty boolSort
xConfigBool :: MockRewritingElementVariable
xConfigBool = mkConfigElementVariable (testId "xBool") mempty boolSort
xString :: MockElementVariable
xString = MockElementVariable (testId "xString") mempty stringSort
xRuleString :: MockRewritingElementVariable
xRuleString = mkRuleElementVariable (testId "xString") mempty stringSort
xConfigString :: MockRewritingElementVariable
xConfigString = mkConfigElementVariable (testId "xString") mempty stringSort
xList :: MockElementVariable
xList = MockElementVariable (testId "xList") mempty listSort
xConfigList :: MockRewritingElementVariable
xConfigList = mkConfigElementVariable (testId "xList") mempty listSort
xMap :: MockElementVariable
xMap = MockElementVariable (testId "xMap") mempty mapSort
yMap :: MockElementVariable
yMap = MockElementVariable (testId "yMap") mempty mapSort
zMap :: MockElementVariable
zMap = MockElementVariable (testId "zMap") mempty mapSort
xMapRule :: MockRewritingElementVariable
xMapRule = mkRuleElementVariable (testId "xMap") mempty mapSort
xMapConfig :: MockRewritingElementVariable
xMapConfig = mkConfigElementVariable (testId "xMap") mempty mapSort
yMapRule :: MockRewritingElementVariable
yMapRule = mkRuleElementVariable (testId "yMap") mempty mapSort
yMapConfig :: MockRewritingElementVariable
yMapConfig = mkConfigElementVariable (testId "yMap") mempty mapSort
zMapRule :: MockRewritingElementVariable
zMapRule = mkRuleElementVariable (testId "zMap") mempty mapSort
zMapConfig :: MockRewritingElementVariable
zMapConfig = mkConfigElementVariable (testId "zMap") mempty mapSort
xSubSort :: MockElementVariable
xSubSort = MockElementVariable (testId "xSubSort") mempty subSort
xRuleSubSort :: MockRewritingElementVariable
xRuleSubSort = mkRuleElementVariable (testId "xSubSort") mempty subSort
xConfigSubSort :: MockRewritingElementVariable
xConfigSubSort = mkConfigElementVariable (testId "xSubSort") mempty subSort
xSubSubSort :: MockElementVariable
xSubSubSort =
MockElementVariable (testId "xSubSubSort") mempty subSubsort
xConfigSubSubSort :: MockRewritingElementVariable
xConfigSubSubSort =
mkConfigElementVariable (testId "xSubSubSort") mempty subSubsort
xSubOtherSort :: MockElementVariable
xSubOtherSort =
MockElementVariable (testId "xSubOtherSort") mempty subOthersort
xRuleSubOtherSort :: MockRewritingElementVariable
xRuleSubOtherSort =
mkRuleElementVariable (testId "xSubOtherSort") mempty subOthersort
xConfigSubOtherSort :: MockRewritingElementVariable
xConfigSubOtherSort =
mkConfigElementVariable (testId "xSubOtherSort") mempty subOthersort
xOtherSort :: MockElementVariable
xOtherSort = MockElementVariable (testId "xOtherSort") mempty otherSort
xConfigOtherSort :: MockRewritingElementVariable
xConfigOtherSort = mkConfigElementVariable (testId "xOtherSort") mempty otherSort
xTopSort :: MockElementVariable
xTopSort = MockElementVariable (testId "xTopSort") mempty topSort
xConfigTopSort :: MockRewritingElementVariable
xConfigTopSort = mkConfigElementVariable (testId "xTopSort") mempty topSort
xStringMetaSort :: MockSetVariable
xStringMetaSort = MockSetVariable (testId "xStringMetaSort") mempty stringMetaSort
xRuleStringMetaSort :: MockRewritingSetVariable
xRuleStringMetaSort =
mkRuleSetVariable (testId "xStringMetaSort") mempty stringMetaSort
xConfigStringMetaSort :: MockRewritingSetVariable
xConfigStringMetaSort =
mkConfigSetVariable (testId "xStringMetaSort") mempty stringMetaSort
eConfigSubSubsort :: MockRewritingSetVariable
eConfigSubSubsort =
mkConfigSetVariable (testId "eConfigSubSubsort") mempty subSubsort
e2ConfigSubSubsort :: MockRewritingSetVariable
e2ConfigSubSubsort =
mkConfigSetVariable (testId "e2ConfigSubSubsort") mempty subSubsort
setXConfigSetSort :: MockRewritingSetVariable
setXConfigSetSort =
mkConfigSetVariable (testId "XSetSort") mempty setSort
setYConfigSetSort :: MockRewritingSetVariable
setYConfigSetSort =
mkConfigSetVariable (testId "YSetSort") mempty setSort
makeSomeVariable :: Text -> Sort -> SomeVariable VariableName
makeSomeVariable name variableSort =
Variable
{ variableSort
, variableName
}
where
variableName =
injectVariableName VariableName{base = testId name, counter = mempty}
injectVariableName
| Text.head name == '@' = inject . SetVariableName
| otherwise = inject . ElementVariableName
makeSomeConfigVariable :: Text -> Sort -> SomeVariable RewritingVariableName
makeSomeConfigVariable name variableSort =
Variable
{ variableSort
, variableName
}
where
variableName =
injectVariableName $
mkConfigVariable VariableName{base = testId name, counter = mempty}
injectVariableName
| Text.head name == '@' = inject . SetVariableName
| otherwise = inject . ElementVariableName
makeTestSomeVariable :: Text -> SomeVariable VariableName
makeTestSomeVariable = (`makeSomeVariable` testSort)
makeTestSomeConfigVariable :: Text -> SomeVariable RewritingVariableName
makeTestSomeConfigVariable = (`makeSomeConfigVariable` testSort)
mkTestSomeVariable :: Text -> TermLike VariableName
mkTestSomeVariable = Internal.mkVar . makeTestSomeVariable
mkTestSomeConfigVariable :: Text -> TermLike RewritingVariableName
mkTestSomeConfigVariable = Internal.mkVar . makeTestSomeConfigVariable
a :: InternalVariable variable => TermLike variable
a = Internal.mkApplySymbol aSymbol []
aConcrete :: TermLike Concrete
Just aConcrete = Internal.asConcrete (a :: TermLike VariableName)
aSort0 :: InternalVariable variable => TermLike variable
aSort0 = Internal.mkApplySymbol aSort0Symbol []
aSort1 :: InternalVariable variable => TermLike variable
aSort1 = Internal.mkApplySymbol aSort1Symbol []
aSubsort :: InternalVariable variable => TermLike variable
aSubsort = Internal.mkApplySymbol aSubsortSymbol []
aSubOthersort :: InternalVariable variable => TermLike variable
aSubOthersort = Internal.mkApplySymbol aSubOthersortSymbol []
aSubSubsort :: InternalVariable variable => TermLike variable
aSubSubsort = Internal.mkApplySymbol aSubSubsortSymbol []
aTopSort :: InternalVariable variable => TermLike variable
aTopSort = Internal.mkApplySymbol aTopSortSymbol []
aOtherSort :: InternalVariable variable => TermLike variable
aOtherSort = Internal.mkApplySymbol aOtherSortSymbol []
b :: InternalVariable variable => TermLike variable
b = Internal.mkApplySymbol bSymbol []
bConcrete :: TermLike Concrete
Just bConcrete = Internal.asConcrete (b :: TermLike VariableName)
bSort0 :: InternalVariable variable => TermLike variable
bSort0 = Internal.mkApplySymbol bSort0Symbol []
c :: InternalVariable variable => TermLike variable
c = Internal.mkApplySymbol cSymbol []
d :: InternalVariable variable => TermLike variable
d = Internal.mkApplySymbol dSymbol []
e :: InternalVariable variable => TermLike variable
e = Internal.mkApplySymbol eSymbol []
f
, g
, h ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
f arg = Internal.mkApplySymbol fSymbol [arg]
g arg = Internal.mkApplySymbol gSymbol [arg]
h arg = Internal.mkApplySymbol hSymbol [arg]
fSort0
, gSort0 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
fSort0 arg = Internal.mkApplySymbol fSort0Symbol [arg]
gSort0 arg = Internal.mkApplySymbol gSort0Symbol [arg]
cf :: InternalVariable variable => TermLike variable
cf = Internal.mkApplySymbol cfSymbol []
cfSort0 :: InternalVariable variable => TermLike variable
cfSort0 = Internal.mkApplySymbol cfSort0Symbol []
cfSort1 :: InternalVariable variable => TermLike variable
cfSort1 = Internal.mkApplySymbol cfSort1Symbol []
cg :: InternalVariable variable => TermLike variable
cg = Internal.mkApplySymbol cgSymbol []
cgSort0 :: InternalVariable variable => TermLike variable
cgSort0 = Internal.mkApplySymbol cgSort0Symbol []
ch :: InternalVariable variable => TermLike variable
ch = Internal.mkApplySymbol chSymbol []
fSet ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
fSet arg = Internal.mkApplySymbol fSetSymbol [arg]
fSet2 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
fSet2 arg1 arg2 = Internal.mkApplySymbol fSet2Symbol [arg1, arg2]
fTestInt ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
fTestInt arg = Internal.mkApplySymbol fTestIntSymbol [arg]
fTestFunctionalInt ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
fTestFunctionalInt arg =
Internal.mkApplySymbol fTestFunctionalIntSymbol [arg]
fInt ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
fInt arg = Internal.mkApplySymbol fIntSymbol [arg]
fBool ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
fBool arg = Internal.mkApplySymbol fBoolSymbol [arg]
fString ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
fString arg = Internal.mkApplySymbol fStringSymbol [arg]
plain00 :: InternalVariable variable => TermLike variable
plain00 = Internal.mkApplySymbol plain00Symbol []
plain00Sort0 :: InternalVariable variable => TermLike variable
plain00Sort0 = Internal.mkApplySymbol plain00Sort0Symbol []
plain00Subsort :: InternalVariable variable => TermLike variable
plain00Subsort = Internal.mkApplySymbol plain00SubsortSymbol []
plain00OtherSort :: InternalVariable variable => TermLike variable
plain00OtherSort = Internal.mkApplySymbol plain00OtherSortSymbol []
plain00SubSubsort :: InternalVariable variable => TermLike variable
plain00SubSubsort = Internal.mkApplySymbol plain00SubSubsortSymbol []
plain10
, plain11 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
plain10 arg = Internal.mkApplySymbol plain10Symbol [arg]
plain11 arg = Internal.mkApplySymbol plain11Symbol [arg]
plain20 ::
InternalVariable variable =>
TermLike variable ->
TermLike variable ->
TermLike variable
plain20 arg1 arg2 = Internal.mkApplySymbol plain20Symbol [arg1, arg2]
constr00 :: InternalVariable variable => HasCallStack => TermLike variable
constr00 = Internal.mkApplySymbol constr00Symbol []
constr10
, constr11
, constrInt ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
constr10 arg = Internal.mkApplySymbol constr10Symbol [arg]
constr11 arg = Internal.mkApplySymbol constr11Symbol [arg]
constrInt arg = Internal.mkApplySymbol constrIntSymbol [arg]
constr20 ::
InternalVariable variable =>
TermLike variable ->
TermLike variable ->
TermLike variable
constr20 arg1 arg2 = Internal.mkApplySymbol constr20Symbol [arg1, arg2]
constrFunct20TestMap ::
InternalVariable variable =>
TermLike variable ->
TermLike variable ->
TermLike variable
constrFunct20TestMap arg1 arg2 =
Internal.mkApplySymbol constrFunct20TestMapSymbol [arg1, arg2]
function20MapTest ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
function20MapTest arg1 arg2 =
Internal.mkApplySymbol function20MapTestSymbol [arg1, arg2]
functional00 :: InternalVariable variable => TermLike variable
functional00 = Internal.mkApplySymbol functional00Symbol []
functional01 :: InternalVariable variable => TermLike variable
functional01 = Internal.mkApplySymbol functional01Symbol []
functional10 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
functional10 arg = Internal.mkApplySymbol functional10Symbol [arg]
functional11 ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
functional11 arg = Internal.mkApplySymbol functional11Symbol [arg]
functional20 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
functional20 arg1 arg2 = Internal.mkApplySymbol functional20Symbol [arg1, arg2]
functional00SubSubSort :: InternalVariable variable => TermLike variable
functional00SubSubSort =
Internal.mkApplySymbol functional00SubSubSortSymbol []
functionalInjective00 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable
functionalInjective00 =
Internal.mkApplySymbol functionalInjective00Symbol []
functionalConstr10 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
functionalConstr10 arg =
Internal.mkApplySymbol functionalConstr10Symbol [arg]
functionalConstr11 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
functionalConstr11 arg = Internal.mkApplySymbol functionalConstr11Symbol [arg]
functionalConstr12 ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
functionalConstr12 arg = Internal.mkApplySymbol functionalConstr12Symbol [arg]
functionalConstr20 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
functionalConstr20 arg1 arg2 =
Internal.mkApplySymbol functionalConstr20Symbol [arg1, arg2]
functionalConstr21 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
functionalConstr21 arg1 arg2 =
Internal.mkApplySymbol functionalConstr21Symbol [arg1, arg2]
functionalConstr30 ::
InternalVariable variable =>
TermLike variable ->
TermLike variable ->
TermLike variable ->
TermLike variable
functionalConstr30 arg1 arg2 arg3 =
Internal.mkApplySymbol functionalConstr30Symbol [arg1, arg2, arg3]
functionalTopConstr20 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
functionalTopConstr20 arg1 arg2 =
Internal.mkApplySymbol functionalTopConstr20Symbol [arg1, arg2]
functionalTopConstr21 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
functionalTopConstr21 arg1 arg2 =
Internal.mkApplySymbol functionalTopConstr21Symbol [arg1, arg2]
subsubOverload ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
subsubOverload arg1 =
Internal.mkApplySymbol subsubOverloadSymbol [arg1]
subOverload ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
subOverload arg1 =
Internal.mkApplySymbol subOverloadSymbol [arg1]
otherOverload ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
otherOverload arg1 =
Internal.mkApplySymbol otherOverloadSymbol [arg1]
topOverload ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
topOverload arg1 =
Internal.mkApplySymbol topOverloadSymbol [arg1]
injective10 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
injective10 arg = Internal.mkApplySymbol injective10Symbol [arg]
injective11 ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
injective11 arg = Internal.mkApplySymbol injective11Symbol [arg]
sortInjection ::
InternalVariable variable =>
Sort ->
TermLike variable ->
TermLike variable
sortInjection injTo termLike =
(synthesize . Internal.InjF)
Internal.Inj
{ injConstructor
, injFrom
, injTo
, injChild = termLike
, injAttributes
}
where
injFrom = Internal.termLikeSort termLike
Symbol{symbolConstructor = injConstructor} = symbol'
Symbol{symbolAttributes = injAttributes} = symbol'
symbol' = sortInjectionSymbol injFrom injTo
sortInjection10 ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjection10 = sortInjection testSort
sortInjection11 ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjection11 = sortInjection testSort
sortInjection0ToTop ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjection0ToTop = sortInjection topSort
sortInjectionSubToTop ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionSubToTop = sortInjection topSort
sortInjectionSubSubToTop ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionSubSubToTop = sortInjection topSort
sortInjectionSubSubToSub ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionSubSubToSub = sortInjection subSort
sortInjectionSubSubToOther ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionSubSubToOther = sortInjection otherSort
sortInjectionSubOtherToOther ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionSubOtherToOther = sortInjection otherSort
sortInjectionSubOtherToTop ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionSubOtherToTop = sortInjection topSort
sortInjectionOtherToOverTheTop ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionOtherToOverTheTop = sortInjection overTheTopSort
sortInjectionSubToOverTheTop ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionSubToOverTheTop = sortInjection overTheTopSort
sortInjectionTopToOverTheTop ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionTopToOverTheTop = sortInjection overTheTopSort
sortInjectionSubToTest ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionSubToTest = sortInjection testSort
sortInjectionTestToTop ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionTestToTop = sortInjection topSort
sortInjectionOtherToTop ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionOtherToTop = sortInjection topSort
sortInjectionOtherToOtherTop ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionOtherToOtherTop = sortInjection otherTopSort
sortInjectionSubToOtherTop ::
InternalVariable variable =>
TermLike variable ->
TermLike variable
sortInjectionSubToOtherTop = sortInjection otherTopSort
unitMap :: InternalVariable variable => TermLike variable
unitMap = Internal.mkApplySymbol unitMapSymbol []
elementMap ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
elementMap m1 m2 = Internal.mkApplySymbol elementMapSymbol [m1, m2]
concatMap ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
concatMap m1 m2 = Internal.mkApplySymbol concatMapSymbol [m1, m2]
opaqueMap ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
opaqueMap term = Internal.mkApplySymbol opaqueMapSymbol [term]
inKeysMap ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
inKeysMap element m1 = Internal.mkApplySymbol inKeysMapSymbol [element, m1]
unitSet :: InternalVariable variable => TermLike variable
unitSet = Internal.mkApplySymbol unitSetSymbol []
elementSet ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
elementSet s1 = Internal.mkApplySymbol elementSetSymbol [s1]
concatSet ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
concatSet s1 s2 = Internal.mkApplySymbol concatSetSymbol [s1, s2]
opaqueSet ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
opaqueSet term = Internal.mkApplySymbol opaqueSetSymbol [term]
lessInt ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
lessInt i1 i2 = Internal.mkApplySymbol lessIntSymbol [i1, i2]
greaterEqInt ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
greaterEqInt i1 i2 = Internal.mkApplySymbol greaterEqIntSymbol [i1, i2]
tdivInt ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
tdivInt i1 i2 = Internal.mkApplySymbol tdivIntSymbol [i1, i2]
concatList ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
concatList l1 l2 = Internal.mkApplySymbol concatListSymbol [l1, l2]
elementList ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
elementList element = Internal.mkApplySymbol elementListSymbol [element]
unitList ::
InternalVariable variable =>
HasCallStack =>
TermLike variable
unitList = Internal.mkApplySymbol unitListSymbol []
keqBool ::
InternalVariable variable =>
TermLike variable ->
TermLike variable ->
TermLike variable
keqBool t1 t2 = Internal.mkApplySymbol keqBoolSymbol [t1, t2]
sigma ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable ->
TermLike variable
sigma child1 child2 = Internal.mkApplySymbol sigmaSymbol [child1, child2]
anywhere :: InternalVariable variable => TermLike variable
anywhere = Internal.mkApplySymbol anywhereSymbol []
functionSMT
, functionalSMT ::
InternalVariable variable =>
HasCallStack =>
TermLike variable ->
TermLike variable
functionSMT arg =
Internal.mkApplySymbol functionSMTSymbol [arg]
functionalSMT arg =
Internal.mkApplySymbol functionalSMTSymbol [arg]
attributesMapping :: [(SymbolOrAlias, Attribute.Symbol)]
attributesMapping =
map (liftA2 (,) toSymbolOrAlias symbolAttributes) symbols
symbols :: [Symbol]
symbols =
[ aSymbol
, aSort0Symbol
, aSort1Symbol
, aSubsortSymbol
, aSubOthersortSymbol
, aSubSubsortSymbol
, aTopSortSymbol
, aOtherSortSymbol
, bSymbol
, bSort0Symbol
, cSymbol
, dSymbol
, eSymbol
, fSymbol
, fSort0Symbol
, gSymbol
, gSort0Symbol
, hSymbol
, cfSymbol
, cfSort0Symbol
, cfSort1Symbol
, cgSymbol
, cgSort0Symbol
, chSymbol
, fSetSymbol
, fIntSymbol
, fTestIntSymbol
, plain00Symbol
, plain00Sort0Symbol
, plain00SubsortSymbol
, plain00SubSubsortSymbol
, plain00OtherSortSymbol
, plain10Symbol
, plain11Symbol
, plain20Symbol
, constr00Symbol
, constr10Symbol
, constr11Symbol
, constr20Symbol
, constrFunct20TestMapSymbol
, function20MapTestSymbol
, functional00Symbol
, functional01Symbol
, functional10Symbol
, functional11Symbol
, functional20Symbol
, functional00SubSubSortSymbol
, functionalInjective00Symbol
, functionalConstr10Symbol
, functionalConstr11Symbol
, functionalConstr12Symbol
, functionalConstr20Symbol
, functionalConstr21Symbol
, functionalConstr30Symbol
, functionalTopConstr20Symbol
, functionalTopConstr21Symbol
, injective10Symbol
, injective11Symbol
, sortInjection10Symbol
, sortInjection11Symbol
, sortInjection0ToTopSymbol
, sortInjectionSubToTopSymbol
, sortInjectionSubSubToTopSymbol
, sortInjectionSubSubToSubSymbol
, sortInjectionSubSubToOtherSymbol
, sortInjectionSubOtherToOtherSymbol
, sortInjectionSubOtherToTopSymbol
, sortInjectionSubToTestSymbol
, sortInjectionTestToTopSymbol
, sortInjectionOtherToTopSymbol
, sortInjectionOtherToOverTheTopSymbol
, sortInjectionSubToOverTheTopSymbol
, sortInjectionTopToOverTheTopSymbol
, sortInjectionSubToOtherTopSymbol
, sortInjectionOtherToOtherTopSymbol
, unitMapSymbol
, elementMapSymbol
, concatMapSymbol
, opaqueMapSymbol
, concatListSymbol
, elementListSymbol
, unitListSymbol
, concatSetSymbol
, elementSetSymbol
, unitSetSymbol
, opaqueSetSymbol
, lessIntSymbol
, greaterEqIntSymbol
, tdivIntSymbol
, keqBoolSymbol
, sigmaSymbol
, anywhereSymbol
, subsubOverloadSymbol
, subOverloadSymbol
, otherOverloadSymbol
, topOverloadSymbol
, functionSMTSymbol
, functionalSMTSymbol
]
sortAttributesMapping :: [(Sort, Attribute.Sort)]
sortAttributesMapping =
[
( testSort
, Default.def
)
,
( testSort0
, Default.def
)
,
( testSort1
, Default.def
)
,
( topSort
, Default.def
)
,
( subSort
, Default.def
)
,
( subOthersort
, Default.def
)
,
( subSubsort
, Default.def
)
,
( otherSort
, Default.def
)
,
( otherTopSort
, Default.def
)
,
( mapSort
, Default.def
{ AttributeSort.hook = Hook (Just "MAP.Map")
, Attribute.unit =
Attribute.Unit (Just $ toSymbolOrAlias unitMapSymbol)
, Attribute.element =
Attribute.Element (Just $ toSymbolOrAlias elementMapSymbol)
, Attribute.concat =
Attribute.Concat (Just $ toSymbolOrAlias concatMapSymbol)
}
)
,
( listSort
, Default.def
{ AttributeSort.hook = Hook (Just "LIST.List")
, Attribute.unit =
Attribute.Unit (Just $ toSymbolOrAlias unitListSymbol)
, Attribute.element =
Attribute.Element (Just $ toSymbolOrAlias elementListSymbol)
, Attribute.concat =
Attribute.Concat (Just $ toSymbolOrAlias concatListSymbol)
}
)
,
( setSort
, Default.def
{ AttributeSort.hook = Hook (Just "SET.Set")
, Attribute.unit =
Attribute.Unit (Just $ toSymbolOrAlias unitSetSymbol)
, Attribute.element =
Attribute.Element (Just $ toSymbolOrAlias elementSetSymbol)
, Attribute.concat =
Attribute.Concat (Just $ toSymbolOrAlias concatSetSymbol)
}
)
,
( intSort
, Default.def{AttributeSort.hook = Hook (Just "INT.Int")}
)
,
( boolSort
, Default.def{AttributeSort.hook = Hook (Just "BOOL.Bool")}
)
,
( stringSort
, Default.def{AttributeSort.hook = Hook (Just "STRING.String")}
)
( stringMetaSort
, Default.def{AttributeSort.hook = Hook (Just "STRING.String")}
)
]
headSortsMapping :: [(SymbolOrAlias, ApplicationSorts)]
headSortsMapping =
map ((,) <$> toSymbolOrAlias <*> symbolSorts) symbols
zeroarySmtSort :: Id -> SMT.UnresolvedSort
zeroarySmtSort sortId =
SMT.Sort
{ sortData = SMT.ConstSExpr encodedId
, sortDeclaration =
SMT.SortDeclarationSort
SMT.SortDeclaration
{ name = SMT.encodable sortId
, arity = 0
}
}
where
encodedId = SMT.encode (SMT.encodable sortId)
builtinZeroarySmtSort :: SMT.SExpr -> SMT.UnresolvedSort
builtinZeroarySmtSort sExpr =
SMT.Sort
{ sortData = SMT.ConstSExpr sExpr
, sortDeclaration = SMT.SortDeclaredIndirectly (SMT.AlreadyEncoded sExpr)
}
smtBuiltinSymbol ::
Text -> [Sort] -> Sort -> SMT.UnresolvedSymbol
smtBuiltinSymbol builtin argumentSorts resultSort =
SMT.Symbol
{ symbolData = SMT.Atom builtin
, symbolDeclaration =
SMT.SymbolBuiltin
SMT.IndirectSymbolDeclaration
{ name = SMT.AlreadyEncoded $ SMT.Atom builtin
, sortDependencies =
SMT.SortReference <$> resultSort : argumentSorts
}
}
smtDeclaredSymbol ::
Text -> Id -> [Sort] -> Sort -> SMT.UnresolvedSymbol
smtDeclaredSymbol smtName id' argumentSorts resultSort =
SMT.Symbol
{ symbolData = SMT.Atom smtName
, symbolDeclaration =
SMT.SymbolDeclaredDirectly
SMT.FunctionDeclaration
{ name = SMT.encodable id'
, inputSorts = SMT.SortReference <$> argumentSorts
, resultSort = SMT.SortReference resultSort
}
}
emptySmtDeclarations :: SMT.SmtDeclarations
emptySmtDeclarations =
SMT.Declarations
{ sorts = Map.empty
, symbols = Map.empty
}
smtDeclarations :: SMT.SmtDeclarations
smtDeclarations = SMT.resolve smtUnresolvedDeclarations
smtUnresolvedDeclarations :: SMT.UnresolvedDeclarations
smtUnresolvedDeclarations =
SMT.Declarations
{ sorts =
Map.fromList
[ (testSort0Id, zeroarySmtSort testSort0Id)
, (testSort1Id, zeroarySmtSort testSort1Id)
, (topSortId, zeroarySmtSort topSortId)
, (topSortId, zeroarySmtSort subSortId)
, (topSortId, zeroarySmtSort subSubsortId)
, (topSortId, zeroarySmtSort otherSortId)
(testSortId, zeroarySmtSort testSortId)
, (intSortId, builtinZeroarySmtSort SMT.tInt)
, (boolSortId, builtinZeroarySmtSort SMT.tBool)
]
, symbols =
Map.fromList
[ (lessIntId, smtBuiltinSymbol "<" [intSort, intSort] boolSort)
, (greaterEqIntId, smtBuiltinSymbol ">=" [intSort, intSort] boolSort)
, (tdivIntId, smtBuiltinSymbol "div" [intSort, intSort] intSort)
,
( functional00Id
, smtDeclaredSymbol "functional00" functional00Id [] testSort
)
,
( functionSMTId
, smtDeclaredSymbol "functionSMT" functionSMTId [testSort] testSort
)
,
( functionalSMTId
, smtDeclaredSymbol "functionalSMT" functionalSMTId [testSort] testSort
)
]
}
sortConstructors :: Map.Map Id Attribute.Constructors
sortConstructors =
Map.empty
testSortId :: Id
testSortId = testId "testSort"
testSort0Id :: Id
testSort0Id = testId "testSort0"
testSort1Id :: Id
testSort1Id = testId "testSort1"
topSortId :: Id
topSortId = testId "topSort"
overTheTopSortId :: Id
overTheTopSortId = testId "overTheTopSort"
subSortId :: Id
subSortId = testId "subSort"
subOthersortId :: Id
subOthersortId = testId "subOthersort"
subSubsortId :: Id
subSubsortId = testId "subSubsort"
otherSortId :: Id
otherSortId = testId "otherSort"
otherTopSortId :: Id
otherTopSortId = testId "otherTopSort"
intSortId :: Id
intSortId = testId "intSort"
boolSortId :: Id
boolSortId = testId "boolSort"
stringSortId :: Id
stringSortId = testId "stringSort"
testSort :: Sort
testSort =
SortActualSort
SortActual
{ sortActualName = testSortId
, sortActualSorts = []
}
testSort0 :: Sort
testSort0 =
SortActualSort
SortActual
{ sortActualName = testSort0Id
, sortActualSorts = []
}
testSort1 :: Sort
testSort1 =
SortActualSort
SortActual
{ sortActualName = testSort1Id
, sortActualSorts = []
}
topSort :: Sort
topSort =
SortActualSort
SortActual
{ sortActualName = topSortId
, sortActualSorts = []
}
overTheTopSort :: Sort
overTheTopSort =
SortActualSort
SortActual
{ sortActualName = overTheTopSortId
, sortActualSorts = []
}
subSort :: Sort
subSort =
SortActualSort
SortActual
{ sortActualName = subSortId
, sortActualSorts = []
}
subOthersort :: Sort
subOthersort =
SortActualSort
SortActual
{ sortActualName = subOthersortId
, sortActualSorts = []
}
subSubsort :: Sort
subSubsort =
SortActualSort
SortActual
{ sortActualName = subSubsortId
, sortActualSorts = []
}
otherSort :: Sort
otherSort =
SortActualSort
SortActual
{ sortActualName = otherSortId
, sortActualSorts = []
}
otherTopSort :: Sort
otherTopSort =
SortActualSort
SortActual
{ sortActualName = otherTopSortId
, sortActualSorts = []
}
mapSort :: Sort
mapSort =
SortActualSort
SortActual
{ sortActualName = testId "mapSort"
, sortActualSorts = []
}
setSort :: Sort
setSort =
SortActualSort
SortActual
{ sortActualName = testId "setSort"
, sortActualSorts = []
}
listSort :: Sort
listSort =
SortActualSort
SortActual
{ sortActualName = testId "listSort"
, sortActualSorts = []
}
intSort :: Sort
intSort =
SortActualSort
SortActual
{ sortActualName = intSortId
, sortActualSorts = []
}
stringSort :: Sort
stringSort =
SortActualSort
SortActual
{ sortActualName = stringSortId
, sortActualSorts = []
}
boolSort :: Sort
boolSort =
SortActualSort
SortActual
{ sortActualName = boolSortId
, sortActualSorts = []
}
subsorts :: [(Sort, Sort)]
subsorts =
[ (subSubsort, subSort)
, (subSubsort, topSort)
, (subSort, topSort)
, (testSort, topSort)
, (subSubsort, otherSort)
, (subOthersort, otherSort)
, (otherSort, topSort)
, (otherSort, otherTopSort)
, (subSort, otherTopSort)
, (subSort, testSort)
, (testSort0, testSort)
, (mapSort, testSort)
, (listSort, testSort)
, (topSort, overTheTopSort)
]
overloads :: [(Symbol, Symbol)]
overloads =
[ (subOverloadSymbol, subsubOverloadSymbol)
, (otherOverloadSymbol, subsubOverloadSymbol)
, (topOverloadSymbol, subsubOverloadSymbol)
, (topOverloadSymbol, subOverloadSymbol)
, (topOverloadSymbol, otherOverloadSymbol)
]
builtinMap ::
InternalVariable variable =>
[(TermLike variable, TermLike variable)] ->
TermLike variable
builtinMap elements = framedMap elements []
test_builtinMap :: [TestTree]
test_builtinMap =
[ testCase "constructor-like keys" $ do
let input = builtinMap [(a, a), (b, b)] :: TermLike VariableName
assertBool "" (isConstructorLike input)
, testCase "symbolic keys" $ do
let input = builtinMap [(f a, a), (f b, b)] :: TermLike VariableName
assertBool "" (not $ isConstructorLike input)
]
framedMap ::
InternalVariable variable =>
[(TermLike variable, TermLike variable)] ->
[TermLike variable] ->
TermLike variable
framedMap elements opaque =
framedInternalMap elements opaque & Internal.mkInternalMap
framedInternalMap ::
[(TermLike variable, TermLike variable)] ->
[TermLike variable] ->
InternalMap Internal.Key (TermLike variable)
framedInternalMap elements opaque =
InternalAc
{ builtinAcSort = mapSort
, builtinAcUnit = unitMapSymbol
, builtinAcElement = elementMapSymbol
, builtinAcConcat = concatMapSymbol
, builtinAcChild =
NormalizedMap
NormalizedAc
{ elementsWithVariables = wrapElement <$> abstractElements
, concreteElements
, opaque
}
}
where
asConcrete element@(key, value) =
(,) <$> retractKey key <*> pure value
& maybe (Left element) Right
(abstractElements, HashMap.fromList -> concreteElements) =
asConcrete . Bifunctor.second MapValue <$> elements
& partitionEithers
builtinList ::
InternalVariable variable =>
[TermLike variable] ->
TermLike variable
builtinList child =
Internal.mkInternalList
InternalList
{ internalListSort = listSort
, internalListUnit = unitListSymbol
, internalListElement = elementListSymbol
, internalListConcat = concatListSymbol
, internalListChild = Seq.fromList child
}
builtinSet ::
InternalVariable variable =>
[TermLike variable] ->
TermLike variable
builtinSet elements = framedSet elements []
test_builtinSet :: [TestTree]
test_builtinSet =
[ testCase "constructor-like keys" $ do
let input = builtinSet [a, b] :: TermLike VariableName
assertBool "" (isConstructorLike input)
, testCase "symbolic keys" $ do
let input = builtinSet [f a, f b] :: TermLike VariableName
assertBool "" (not $ isConstructorLike input)
]
framedSet ::
InternalVariable variable =>
[TermLike variable] ->
[TermLike variable] ->
TermLike variable
framedSet elements opaque =
framedInternalSet elements opaque & Internal.mkInternalSet
framedInternalSet ::
[TermLike variable] ->
[TermLike variable] ->
InternalSet Internal.Key (TermLike variable)
framedInternalSet elements opaque =
InternalAc
{ builtinAcSort = setSort
, builtinAcUnit = unitSetSymbol
, builtinAcElement = elementSetSymbol
, builtinAcConcat = concatSetSymbol
, builtinAcChild =
NormalizedSet
NormalizedAc
{ elementsWithVariables = wrapElement <$> abstractElements
, concreteElements
, opaque
}
}
where
asConcrete key =
do
Monad.guard (isConstructorLike key)
(,) <$> retractKey key <*> pure SetValue
& maybe (Left (key, SetValue)) Right
(abstractElements, HashMap.fromList -> concreteElements) =
asConcrete <$> elements
& partitionEithers
builtinInt ::
Integer ->
TermLike variable
builtinInt = Builtin.Int.asInternal intSort
builtinBool ::
InternalVariable variable =>
Bool ->
TermLike variable
builtinBool = Builtin.Bool.asInternal boolSort
builtinString ::
Text ->
TermLike variable
builtinString = Builtin.String.asInternal stringSort
emptyMetadataTools :: SmtMetadataTools Attribute.Symbol
emptyMetadataTools =
Mock.makeMetadataTools
emptySmtDeclarations
metadataTools :: SmtMetadataTools Attribute.Symbol
metadataTools =
Mock.makeMetadataTools
attributesMapping
sortAttributesMapping
headSortsMapping
smtDeclarations
sortConstructors
axiomEquations :: Map AxiomIdentifier [Equation RewritingVariableName]
axiomEquations = Map.empty
predicateSimplifier :: ConditionSimplifier Simplifier
predicateSimplifier =
Simplifier.Condition.create SubstitutionSimplifier.substitutionSimplifier
sortGraph :: SortGraph.SortGraph
sortGraph =
SortGraph.fromSubsorts
[Subsort{subsort, supersort} | (subsort, supersort) <- subsorts]
injSimplifier :: InjSimplifier
injSimplifier = mkInjSimplifier sortGraph
overloadGraph :: OverloadGraph.OverloadGraph
overloadGraph = OverloadGraph.fromOverloads overloads
overloadSimplifier :: OverloadSimplifier
overloadSimplifier = mkOverloadSimplifier overloadGraph Test.Kore.Rewrite.MockSymbols.injSimplifier
TODO(Ana ): if needed , create copy with experimental simplifier
env :: Env
env =
Env
{ metadataTools = Test.Kore.Rewrite.MockSymbols.metadataTools
, simplifierCondition = predicateSimplifier
, simplifierPattern = Pattern.makeEvaluate
, simplifierTerm = TermLike.simplify
, axiomEquations = Test.Kore.Rewrite.MockSymbols.axiomEquations
, memo = Memo.forgetful
, injSimplifier = Test.Kore.Rewrite.MockSymbols.injSimplifier
, overloadSimplifier = Test.Kore.Rewrite.MockSymbols.overloadSimplifier
, hookedSymbols = Map.empty
}
generatorSetup :: ConsistentKore.Setup
generatorSetup =
ConsistentKore.Setup
{ allSymbols = filter doesNotHaveArguments symbols
, allAliases = []
, allSorts = filter (/= otherTopSort) $ map fst sortAttributesMapping
, freeElementVariables = Set.empty
, freeSetVariables = Set.empty
, maybeIntSort = Just intSort
, maybeBoolSort = Just boolSort
, maybeListSorts =
Just
ConsistentKore.CollectionSorts
{ collectionSort = listSort
, elementSort = testSort
}
, maybeMapSorts = Nothing
maybeSetSorts = Nothing
maybeStringLiteralSort = Just stringMetaSort
, maybeStringBuiltinSort = Just stringSort
, metadataTools = Test.Kore.Rewrite.MockSymbols.metadataTools
}
where
doesNotHaveArguments Symbol{symbolParams} = null symbolParams
test_canGenerateConsistentTerms :: TestTree
test_canGenerateConsistentTerms =
testGroup "can generate consistent terms for all given sorts" $
map mkTest testSorts
where
testSorts = ConsistentKore.allSorts generatorSetup
sizes = map Range.Size [1 .. 10]
mkTest :: Sort -> TestTree
mkTest sort@(SortActualSort SortActual{sortActualName = InternedId{getInternedId}}) =
testGroup
(show getInternedId)
[ testProperty (show size) . withTests 1 . property $ do
r <-
forAll . Gen.resize size $
ConsistentKore.runKoreGen
generatorSetup
(ConsistentKore.termLikeGenWithSort sort)
Hedgehog.diff 0 (<) (length $ show r)
| size <- sizes
]
mkTest SortVariableSort{} =
error "Found a sort variable in the generator setup"
builtinSimplifiers :: Map Id Text
builtinSimplifiers =
Map.fromList
[
( unitMapId
, Map.unitKey
)
,
( elementMapId
, Map.elementKey
)
,
( concatMapId
, Map.concatKey
)
,
( unitSetId
, Set.unitKey
)
,
( elementSetId
, Set.elementKey
)
,
( concatSetId
, Set.concatKey
)
,
( unitListId
, List.unitKey
)
,
( elementListId
, List.elementKey
)
,
( concatListId
, List.concatKey
)
,
( tdivIntId
, Builtin.Int.tdivKey
)
,
( lessIntId
, Builtin.Int.ltKey
)
,
( greaterEqIntId
, Builtin.Int.geKey
)
,
( keqBoolId
, Builtin.KEqual.eqKey
)
]
verifiedModuleContext :: PatternVerifier.Context
verifiedModuleContext =
PatternVerifier.verifiedModuleContext
IndexedModule.IndexedModuleSyntax
{ indexedModuleName = ModuleName "MOCK"
, indexedModuleAliasSentences = mempty
, indexedModuleSymbolSentences =
Map.fromList
[ ( symbolConstructor
,
( symbolAttributes
, SentenceSymbol
{ sentenceSymbolSymbol =
Kore.Syntax.Sentence.Symbol
{ symbolConstructor
, symbolParams = []
}
, sentenceSymbolSorts = applicationSortsOperands
, sentenceSymbolResultSort = applicationSortsResult
, sentenceSymbolAttributes = Default.def
}
)
)
| Symbol
{ symbolConstructor
, symbolAttributes
, symbolSorts =
ApplicationSorts
{ applicationSortsOperands
, applicationSortsResult
}
} <-
allSymbols
]
, indexedModuleSortDescriptions =
Map.fromList
[ (sortActualName, (attr{Attribute.hasDomainValues = Attribute.HasDomainValues True}, SentenceSort sortActualName [] Default.def))
| (SortActualSort (SortActual{sortActualName}), attr) <- sortAttributesMapping
]
, indexedModuleImportsSyntax = mempty
, indexedModuleHookedIdentifiers = mempty
}
& PatternVerifier.withBuiltinVerifiers Builtin.koreVerifiers
where
ConsistentKore.Setup{allSymbols} = generatorSetup
|
8db0afd25a30f5263636ae95b103653499880ab48a04335baa0f0e2febe0d428 | CRogers/obc | varsview.ml |
* varsview.ml
*
* This file is part of the Oxford Oberon-2 compiler
* Copyright ( c ) 2008
* All rights reserved
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are met :
*
* 1 . Redistributions of source code must retain the above copyright notice ,
* this list of conditions and the following disclaimer .
* 2 . Redistributions in binary form must reproduce the above copyright notice ,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution .
* 3 . The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission .
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS '' AND ANY EXPRESS OR
* IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED .
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL ,
* SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ;
* OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
* IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR
* OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
*
* $ I d : varsview.ml 1655 2010 - 12 - 31 22:30:49Z mike $
* varsview.ml
*
* This file is part of the Oxford Oberon-2 compiler
* Copyright (c) 2008 J. M. Spivey
* All rights reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* $Id: varsview.ml 1655 2010-12-31 22:30:49Z mike $
*)
open Symtab
open Binary
open Print
open Dict
open Data
open Util
open Mach
open Eval
let rcsid = "$Id: varsview.ml 1655 2010-12-31 22:30:49Z mike $"
type selector =
Name of ident (* Variable or field *)
| Subs of int (* Array element *)
| Module of ident (* Globals for module *)
Elided array elements
| Dummy (* Dummy child for unexpanded node *)
let fSel =
function
Name x -> fId x
| Subs n -> fMeta "[$]" [fNum n]
| Module m -> fMeta "Module $" [fId m]
| DotDotDot -> fStr "..."
| Dummy -> fStr "*dummy*"
in UTF-8
(*
For each module or procedure, we keep a tree of nodes that have been
expanded. The tree is represented as a list of paths. Also, for each
procedure, a path for the node that shows at the top of the scrolling
window.
*)
type context = ModCxt of ident | ProcCxt of string | GlobCxt
let expand_tbl = (Hashtbl.create 100 : (context, selector list list) Hashtbl.t)
let scroll_tbl = Hashtbl.create 100
let get_expand x = try Hashtbl.find expand_tbl x with Not_found -> []
let put_expand x t = Hashtbl.add expand_tbl x t
let get_scroll x = Hashtbl.find scroll_tbl x
let put_scroll x p = Hashtbl.add scroll_tbl x p
let rec prefix us vs =
match (us, vs) with
([], _) -> true
| (x::xs, []) -> false
| (x::xs, y::ys) -> x = y && prefix xs ys
let add_path p ps =
if List.exists (fun q -> prefix p q) ps then ps
else p :: List.filter (fun q -> not (prefix q p)) ps
let remove_path p ps =
let n = List.length p in
let qs = List.filter (fun q -> not (prefix p q)) ps in
if n = 0 then qs
else add_path (Util.take (n-1) p) qs
let remember f x p =
let remem y q = put_expand y (f q (get_expand y)) in
match p with
Module m :: p' -> remem (ModCxt m) p'
| _ -> remem x p
class type varsview =
object
method clear : unit -> unit
method show_frame : regs -> unit
method show_globals : unit -> unit
method as_widget : GObj.widget
end
let showable d =
match d.d_kind with VarDef | ParamDef | VParamDef -> true | _ -> false
let rec has_children x v =
match x with
(Name _ | Subs _) ->
let t = type_of v in
if is_pointer t then
not (null_pointer v) && has_children x (deref v)
else if is_array t then
bound t > 0
else if is_record t then
let r = get_record t in r.r_fields <> []
else
false
| Module m ->
List.exists showable (top_block (Info.get_module m))
| Dummy -> failwith "has_children"
| DotDotDot -> false
let rec do_children x v f =
match x with
(Name _ | Subs _) ->
let t = type_of v in
if is_pointer t then
do_children x (deref v) f
else if is_array t && not (is_flex t) then begin
let show i = f (Subs i) (subscript v i) in
let b = bound t in
let limit = 100 in
if b <= limit then
for i = 0 to b-1 do show i done
else begin
for i = 0 to limit-3 do show i done;
f DotDotDot void_value;
show (b-1)
end
end
else if is_record t then
let r = get_record t in
List.iter (fun d -> f (Name d.d_tag) (select v d)) r.r_fields
else
()
| Module m ->
let env = Info.get_module m in
do_block Int32.zero (top_block env) f
| Dummy | DotDotDot -> failwith "do_children"
and do_block bp ds f =
List.iter (fun d ->
if showable d then
f (Name d.d_tag) (def_value bp d)) ds
class varsview_impl (peer : GTree.view) =
let cols = new GTree.column_list in
let c_name = cols#add Gobject.Data.caml in
let c_value = cols#add Gobject.Data.caml in
let c_disp = cols#add Gobject.Data.string in
(* c_disp is a cache of the printed value: this avoids fetching
data repeatedly if the value is e.g. a string. *)
let store = GTree.tree_store cols in
let context = ref GlobCxt in
let cleared = ref true in
let vc_name = GTree.view_column ~title:"Name" () in
let vc_value = GTree.view_column ~title:"Value"
~renderer:(GTree.cell_renderer_text [], ["text", c_disp]) () in
let vc_type = GTree.view_column ~title:"Type" () in
let insert ?parent x v =
let iter = store#append ?parent () in
store#set ~row:iter ~column:c_name x;
store#set ~row:iter ~column:c_value v;
let s =
match x with
Name _ | Subs _ -> sprintf "$" [fLongVal v]
| Module _ | Dummy | DotDotDot -> "" in
store#set ~row:iter ~column:c_disp s;
if has_children x v then begin
let dummy = store#append ~parent:iter () in
store#set ~row:dummy ~column:c_name Dummy;
store#set ~row:dummy ~column:c_value void_value;
store#set ~row:dummy ~column:c_disp ""
end in
let insert_module ?parent m =
if List.exists showable (top_block (Info.get_module m)) then
insert ?parent (Module m) void_value in
let get_children iter =
List.map (fun i -> store#iter_children ~nth:i iter)
(Util.range 0 (store#iter_n_children iter - 1)) in
object (self)
method as_widget = (peer :> GObj.widget)
method show_globals () =
self#clear ();
List.iter (fun m ->
if not (List.mem m Debconf.lib_mods) then insert_module m)
(Binary.all_modules ());
self#expand_tree GlobCxt
method show_frame regs =
let p = curr_proc regs.cp in
let d = Info.get_debug p.s_name in
if d.d_tag = intern "MAIN" then
self#show_globals ()
else if d.d_tag = intern "*body*" then begin
self#clear ();
let env = Info.get_module d.d_module in
do_block Int32.zero (top_block env) insert;
self#expand_tree (ModCxt d.d_module)
end
else begin
self#clear ();
do_block regs.bp (top_block d.d_env) insert;
insert_module d.d_module;
self#expand_tree (ProcCxt p.s_name)
end
method expand_tree x =
context := x; cleared := false;
let rec expand itz =
function
[] -> ()
| x::xs ->
let kids = get_children itz in
try
let it' = List.find (fun it ->
store#get ~row:it ~column:c_name = x) kids in
self#populate it';
peer#expand_row (store#get_path it');
expand (Some it') xs
with Not_found -> () in
let expand_mod it =
match store#get ~row:it ~column:c_name with
Module m ->
List.iter
(fun p -> expand None (Module m :: p))
(get_expand (ModCxt m))
| _ -> () in
List.iter (expand None) (get_expand x);
List.iter expand_mod (get_children None);
try
let iter = self#iter_sel (get_scroll x) in
peer#scroll_to_cell ~align:(0.0, 0.0) (store#get_path iter) vc_name
with Not_found -> ()
(* sel_path -- convert tree iterator to selector path *)
method sel_path iter =
let rec loop itz xs =
match itz with
None -> xs
| Some it ->
let x = store#get ~row:it ~column:c_name in
loop (store#iter_parent it) (x::xs) in
loop (Some iter) []
(* iter_sel -- convert selector path to tree iterator *)
method iter_sel path =
let rec loop itz =
function
[] -> itz
| x::xs ->
let kids = get_children itz in
try
let it' = List.find (fun it ->
store#get ~row:it ~column:c_name = x) kids in
loop (Some it') xs
with Not_found ->
(* Truncated path *)
itz in
match loop None path with
Some it -> it
| None -> raise Not_found
method populate iter =
if store#iter_n_children (Some iter) = 1 then begin
let child = store#iter_children (Some iter) in
if store#get ~row:child ~column:c_name = Dummy then begin
let x = store#get ~row:iter ~column:c_name in
let v = store#get ~row:iter ~column:c_value in
do_children x v (insert ~parent:iter);
ignore (store#remove child)
end
end
method private open_node iter path =
remember add_path !context (self#sel_path iter);
self#populate iter
method private close_node iter path =
remember remove_path !context (self#sel_path iter)
method clear () =
if not !cleared then begin
let p =
match peer#get_visible_range () with
Some (start, _) -> self#sel_path (store#get_iter start)
| None -> [] in
put_scroll !context p;
store#clear ();
cleared := true
end
initializer
peer#set_model (Some store#coerce);
peer#misc#modify_font_by_name Debconf.sans_font;
let render_name = GTree.cell_renderer_text [] in
vc_name#pack render_name;
vc_name#set_cell_data_func render_name (fun model row ->
let x = model#get ~row ~column:c_name in
let v = model#get ~row ~column:c_value in
let t = type_of v in
let s = sprintf "$$"
[fSel x; if is_pointer t then fStr uparrow else fStr ""] in
render_name#set_properties [`TEXT s]);
let render_type = GTree.cell_renderer_text [] in
vc_type#pack render_type;
vc_type#set_cell_data_func render_type (fun model row ->
let v = model#get ~row ~column:c_value in
let t = type_of v in
let s =
if same_types t voidtype then ""
else sprintf "$" [fType t] in
render_type#set_properties [`TEXT s]);
ignore (peer#append_column vc_name); vc_name#set_resizable true;
ignore (peer#append_column vc_value); vc_value#set_resizable true;
ignore (peer#append_column vc_type); vc_type#set_resizable true;
ignore (peer#connect#row_expanded ~callback:self#open_node);
ignore (peer#connect#row_collapsed ~callback:self#close_node)
end
let varsview ?width ?height ?packing () =
(new varsview_impl (GTree.view ?width ?height ?packing ()) :> varsview)
| null | https://raw.githubusercontent.com/CRogers/obc/49064db244e0c9d2ec2a83420c8d0ee917b54196/debugger/varsview.ml | ocaml | Variable or field
Array element
Globals for module
Dummy child for unexpanded node
For each module or procedure, we keep a tree of nodes that have been
expanded. The tree is represented as a list of paths. Also, for each
procedure, a path for the node that shows at the top of the scrolling
window.
c_disp is a cache of the printed value: this avoids fetching
data repeatedly if the value is e.g. a string.
sel_path -- convert tree iterator to selector path
iter_sel -- convert selector path to tree iterator
Truncated path |
* varsview.ml
*
* This file is part of the Oxford Oberon-2 compiler
* Copyright ( c ) 2008
* All rights reserved
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are met :
*
* 1 . Redistributions of source code must retain the above copyright notice ,
* this list of conditions and the following disclaimer .
* 2 . Redistributions in binary form must reproduce the above copyright notice ,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution .
* 3 . The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission .
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS '' AND ANY EXPRESS OR
* IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED .
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL ,
* SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ;
* OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
* IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR
* OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
*
* $ I d : varsview.ml 1655 2010 - 12 - 31 22:30:49Z mike $
* varsview.ml
*
* This file is part of the Oxford Oberon-2 compiler
* Copyright (c) 2008 J. M. Spivey
* All rights reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* $Id: varsview.ml 1655 2010-12-31 22:30:49Z mike $
*)
open Symtab
open Binary
open Print
open Dict
open Data
open Util
open Mach
open Eval
let rcsid = "$Id: varsview.ml 1655 2010-12-31 22:30:49Z mike $"
type selector =
Elided array elements
let fSel =
function
Name x -> fId x
| Subs n -> fMeta "[$]" [fNum n]
| Module m -> fMeta "Module $" [fId m]
| DotDotDot -> fStr "..."
| Dummy -> fStr "*dummy*"
in UTF-8
type context = ModCxt of ident | ProcCxt of string | GlobCxt
let expand_tbl = (Hashtbl.create 100 : (context, selector list list) Hashtbl.t)
let scroll_tbl = Hashtbl.create 100
let get_expand x = try Hashtbl.find expand_tbl x with Not_found -> []
let put_expand x t = Hashtbl.add expand_tbl x t
let get_scroll x = Hashtbl.find scroll_tbl x
let put_scroll x p = Hashtbl.add scroll_tbl x p
let rec prefix us vs =
match (us, vs) with
([], _) -> true
| (x::xs, []) -> false
| (x::xs, y::ys) -> x = y && prefix xs ys
let add_path p ps =
if List.exists (fun q -> prefix p q) ps then ps
else p :: List.filter (fun q -> not (prefix q p)) ps
let remove_path p ps =
let n = List.length p in
let qs = List.filter (fun q -> not (prefix p q)) ps in
if n = 0 then qs
else add_path (Util.take (n-1) p) qs
let remember f x p =
let remem y q = put_expand y (f q (get_expand y)) in
match p with
Module m :: p' -> remem (ModCxt m) p'
| _ -> remem x p
class type varsview =
object
method clear : unit -> unit
method show_frame : regs -> unit
method show_globals : unit -> unit
method as_widget : GObj.widget
end
let showable d =
match d.d_kind with VarDef | ParamDef | VParamDef -> true | _ -> false
let rec has_children x v =
match x with
(Name _ | Subs _) ->
let t = type_of v in
if is_pointer t then
not (null_pointer v) && has_children x (deref v)
else if is_array t then
bound t > 0
else if is_record t then
let r = get_record t in r.r_fields <> []
else
false
| Module m ->
List.exists showable (top_block (Info.get_module m))
| Dummy -> failwith "has_children"
| DotDotDot -> false
let rec do_children x v f =
match x with
(Name _ | Subs _) ->
let t = type_of v in
if is_pointer t then
do_children x (deref v) f
else if is_array t && not (is_flex t) then begin
let show i = f (Subs i) (subscript v i) in
let b = bound t in
let limit = 100 in
if b <= limit then
for i = 0 to b-1 do show i done
else begin
for i = 0 to limit-3 do show i done;
f DotDotDot void_value;
show (b-1)
end
end
else if is_record t then
let r = get_record t in
List.iter (fun d -> f (Name d.d_tag) (select v d)) r.r_fields
else
()
| Module m ->
let env = Info.get_module m in
do_block Int32.zero (top_block env) f
| Dummy | DotDotDot -> failwith "do_children"
and do_block bp ds f =
List.iter (fun d ->
if showable d then
f (Name d.d_tag) (def_value bp d)) ds
class varsview_impl (peer : GTree.view) =
let cols = new GTree.column_list in
let c_name = cols#add Gobject.Data.caml in
let c_value = cols#add Gobject.Data.caml in
let c_disp = cols#add Gobject.Data.string in
let store = GTree.tree_store cols in
let context = ref GlobCxt in
let cleared = ref true in
let vc_name = GTree.view_column ~title:"Name" () in
let vc_value = GTree.view_column ~title:"Value"
~renderer:(GTree.cell_renderer_text [], ["text", c_disp]) () in
let vc_type = GTree.view_column ~title:"Type" () in
let insert ?parent x v =
let iter = store#append ?parent () in
store#set ~row:iter ~column:c_name x;
store#set ~row:iter ~column:c_value v;
let s =
match x with
Name _ | Subs _ -> sprintf "$" [fLongVal v]
| Module _ | Dummy | DotDotDot -> "" in
store#set ~row:iter ~column:c_disp s;
if has_children x v then begin
let dummy = store#append ~parent:iter () in
store#set ~row:dummy ~column:c_name Dummy;
store#set ~row:dummy ~column:c_value void_value;
store#set ~row:dummy ~column:c_disp ""
end in
let insert_module ?parent m =
if List.exists showable (top_block (Info.get_module m)) then
insert ?parent (Module m) void_value in
let get_children iter =
List.map (fun i -> store#iter_children ~nth:i iter)
(Util.range 0 (store#iter_n_children iter - 1)) in
object (self)
method as_widget = (peer :> GObj.widget)
method show_globals () =
self#clear ();
List.iter (fun m ->
if not (List.mem m Debconf.lib_mods) then insert_module m)
(Binary.all_modules ());
self#expand_tree GlobCxt
method show_frame regs =
let p = curr_proc regs.cp in
let d = Info.get_debug p.s_name in
if d.d_tag = intern "MAIN" then
self#show_globals ()
else if d.d_tag = intern "*body*" then begin
self#clear ();
let env = Info.get_module d.d_module in
do_block Int32.zero (top_block env) insert;
self#expand_tree (ModCxt d.d_module)
end
else begin
self#clear ();
do_block regs.bp (top_block d.d_env) insert;
insert_module d.d_module;
self#expand_tree (ProcCxt p.s_name)
end
method expand_tree x =
context := x; cleared := false;
let rec expand itz =
function
[] -> ()
| x::xs ->
let kids = get_children itz in
try
let it' = List.find (fun it ->
store#get ~row:it ~column:c_name = x) kids in
self#populate it';
peer#expand_row (store#get_path it');
expand (Some it') xs
with Not_found -> () in
let expand_mod it =
match store#get ~row:it ~column:c_name with
Module m ->
List.iter
(fun p -> expand None (Module m :: p))
(get_expand (ModCxt m))
| _ -> () in
List.iter (expand None) (get_expand x);
List.iter expand_mod (get_children None);
try
let iter = self#iter_sel (get_scroll x) in
peer#scroll_to_cell ~align:(0.0, 0.0) (store#get_path iter) vc_name
with Not_found -> ()
method sel_path iter =
let rec loop itz xs =
match itz with
None -> xs
| Some it ->
let x = store#get ~row:it ~column:c_name in
loop (store#iter_parent it) (x::xs) in
loop (Some iter) []
method iter_sel path =
let rec loop itz =
function
[] -> itz
| x::xs ->
let kids = get_children itz in
try
let it' = List.find (fun it ->
store#get ~row:it ~column:c_name = x) kids in
loop (Some it') xs
with Not_found ->
itz in
match loop None path with
Some it -> it
| None -> raise Not_found
method populate iter =
if store#iter_n_children (Some iter) = 1 then begin
let child = store#iter_children (Some iter) in
if store#get ~row:child ~column:c_name = Dummy then begin
let x = store#get ~row:iter ~column:c_name in
let v = store#get ~row:iter ~column:c_value in
do_children x v (insert ~parent:iter);
ignore (store#remove child)
end
end
method private open_node iter path =
remember add_path !context (self#sel_path iter);
self#populate iter
method private close_node iter path =
remember remove_path !context (self#sel_path iter)
method clear () =
if not !cleared then begin
let p =
match peer#get_visible_range () with
Some (start, _) -> self#sel_path (store#get_iter start)
| None -> [] in
put_scroll !context p;
store#clear ();
cleared := true
end
initializer
peer#set_model (Some store#coerce);
peer#misc#modify_font_by_name Debconf.sans_font;
let render_name = GTree.cell_renderer_text [] in
vc_name#pack render_name;
vc_name#set_cell_data_func render_name (fun model row ->
let x = model#get ~row ~column:c_name in
let v = model#get ~row ~column:c_value in
let t = type_of v in
let s = sprintf "$$"
[fSel x; if is_pointer t then fStr uparrow else fStr ""] in
render_name#set_properties [`TEXT s]);
let render_type = GTree.cell_renderer_text [] in
vc_type#pack render_type;
vc_type#set_cell_data_func render_type (fun model row ->
let v = model#get ~row ~column:c_value in
let t = type_of v in
let s =
if same_types t voidtype then ""
else sprintf "$" [fType t] in
render_type#set_properties [`TEXT s]);
ignore (peer#append_column vc_name); vc_name#set_resizable true;
ignore (peer#append_column vc_value); vc_value#set_resizable true;
ignore (peer#append_column vc_type); vc_type#set_resizable true;
ignore (peer#connect#row_expanded ~callback:self#open_node);
ignore (peer#connect#row_collapsed ~callback:self#close_node)
end
let varsview ?width ?height ?packing () =
(new varsview_impl (GTree.view ?width ?height ?packing ()) :> varsview)
|
6865b69c4e65a9a58a018be05e19aec6c66c6674c86f73732f241763814fcb8a | ds-wizard/engine-backend | DocumentTemplateSimpleDTO.hs | module Wizard.Api.Resource.DocumentTemplate.DocumentTemplateSimpleDTO where
import Data.Time
import GHC.Generics
import Shared.Api.Resource.Organization.OrganizationSimpleDTO
import Shared.Model.DocumentTemplate.DocumentTemplate
import Shared.Model.Package.PackagePattern
import Wizard.Api.Resource.Package.PackageSimpleDTO
import Wizard.Model.DocumentTemplate.DocumentTemplateState
data DocumentTemplateSimpleDTO = DocumentTemplateSimpleDTO
{ tId :: String
, name :: String
, organizationId :: String
, templateId :: String
, version :: String
, phase :: DocumentTemplatePhase
, remoteLatestVersion :: Maybe String
, metamodelVersion :: Int
, description :: String
, readme :: String
, license :: String
, allowedPackages :: [PackagePattern]
, formats :: [DocumentTemplateFormat]
, usablePackages :: [PackageSimpleDTO]
, state :: DocumentTemplateState
, organization :: Maybe OrganizationSimpleDTO
, createdAt :: UTCTime
}
deriving (Show, Eq, Generic)
| null | https://raw.githubusercontent.com/ds-wizard/engine-backend/d392b751192a646064305d3534c57becaa229f28/engine-wizard/src/Wizard/Api/Resource/DocumentTemplate/DocumentTemplateSimpleDTO.hs | haskell | module Wizard.Api.Resource.DocumentTemplate.DocumentTemplateSimpleDTO where
import Data.Time
import GHC.Generics
import Shared.Api.Resource.Organization.OrganizationSimpleDTO
import Shared.Model.DocumentTemplate.DocumentTemplate
import Shared.Model.Package.PackagePattern
import Wizard.Api.Resource.Package.PackageSimpleDTO
import Wizard.Model.DocumentTemplate.DocumentTemplateState
data DocumentTemplateSimpleDTO = DocumentTemplateSimpleDTO
{ tId :: String
, name :: String
, organizationId :: String
, templateId :: String
, version :: String
, phase :: DocumentTemplatePhase
, remoteLatestVersion :: Maybe String
, metamodelVersion :: Int
, description :: String
, readme :: String
, license :: String
, allowedPackages :: [PackagePattern]
, formats :: [DocumentTemplateFormat]
, usablePackages :: [PackageSimpleDTO]
, state :: DocumentTemplateState
, organization :: Maybe OrganizationSimpleDTO
, createdAt :: UTCTime
}
deriving (Show, Eq, Generic)
|
Subsets and Splits