_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
|
---|---|---|---|---|---|---|---|---|
4d45a8c591d0bbc32b4228402c3408c71e5d833b451467ed2ba987702c267d54 | yzhs/ocamlllvm | cmmgen.ml | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ I d : cmmgen.ml 10794 2010 - 11 - 11 17:08:07Z xleroy $
(* Translation from closed lambda to C-- *)
open Misc
open Arch
open Asttypes
open Primitive
open Types
open Lambda
open Clambda
open Cmm
open Cmx_format
(* Local binding of complex expressions *)
let bind name arg fn =
match arg with
Cvar _ | Cconst_int _ | Cconst_natint _ | Cconst_symbol _
| Cconst_pointer _ | Cconst_natpointer _ -> fn arg
| _ -> let id = Ident.create name in Clet(id, arg, fn (Cvar id))
let bind_nonvar name arg fn =
match arg with
Cconst_int _ | Cconst_natint _ | Cconst_symbol _
| Cconst_pointer _ | Cconst_natpointer _ -> fn arg
| _ -> let id = Ident.create name in Clet(id, arg, fn (Cvar id))
(* Block headers. Meaning of the tag field: see stdlib/obj.ml *)
let float_tag = Cconst_int Obj.double_tag
let floatarray_tag = Cconst_int Obj.double_array_tag
let block_header tag sz =
Nativeint.add (Nativeint.shift_left (Nativeint.of_int sz) 10)
(Nativeint.of_int tag)
let closure_header sz = block_header Obj.closure_tag sz
let infix_header ofs = block_header Obj.infix_tag ofs
let float_header = block_header Obj.double_tag (size_float / size_addr)
let floatarray_header len =
block_header Obj.double_array_tag (len * size_float / size_addr)
let string_header len =
block_header Obj.string_tag ((len + size_addr) / size_addr)
let boxedint32_header = block_header Obj.custom_tag 2
let boxedint64_header = block_header Obj.custom_tag (1 + 8 / size_addr)
let boxedintnat_header = block_header Obj.custom_tag 2
let alloc_block_header tag sz = Cconst_natint(block_header tag sz)
let alloc_float_header = Cconst_natint(float_header)
let alloc_floatarray_header len = Cconst_natint(floatarray_header len)
let alloc_closure_header sz = Cconst_natint(closure_header sz)
let alloc_infix_header ofs = Cconst_natint(infix_header ofs)
let alloc_boxedint32_header = Cconst_natint(boxedint32_header)
let alloc_boxedint64_header = Cconst_natint(boxedint64_header)
let alloc_boxedintnat_header = Cconst_natint(boxedintnat_header)
(* Integers *)
let max_repr_int = max_int asr 1
let min_repr_int = min_int asr 1
let int_const n =
if n <= max_repr_int && n >= min_repr_int
then Cconst_int((n lsl 1) + 1)
else Cconst_natint
(Nativeint.add (Nativeint.shift_left (Nativeint.of_int n) 1) 1n)
let add_const c n =
if n = 0 then c else Cop(Caddi, [c; Cconst_int n])
let incr_int = function
Cconst_int n when n < max_int -> Cconst_int(n+1)
| Cop(Caddi, [c; Cconst_int n]) when n < max_int -> add_const c (n + 1)
| c -> add_const c 1
let decr_int = function
Cconst_int n when n > min_int -> Cconst_int(n-1)
| Cop(Caddi, [c; Cconst_int n]) when n > min_int -> add_const c (n - 1)
| c -> add_const c (-1)
let add_int c1 c2 =
match (c1, c2) with
(Cop(Caddi, [c1; Cconst_int n1]),
Cop(Caddi, [c2; Cconst_int n2])) when no_overflow_add n1 n2 ->
add_const (Cop(Caddi, [c1; c2])) (n1 + n2)
| (Cop(Caddi, [c1; Cconst_int n1]), c2) ->
add_const (Cop(Caddi, [c1; c2])) n1
| (c1, Cop(Caddi, [c2; Cconst_int n2])) ->
add_const (Cop(Caddi, [c1; c2])) n2
| (Cconst_int _, _) ->
Cop(Caddi, [c2; c1])
| (_, _) ->
Cop(Caddi, [c1; c2])
let sub_int c1 c2 =
match (c1, c2) with
(Cop(Caddi, [c1; Cconst_int n1]),
Cop(Caddi, [c2; Cconst_int n2])) when no_overflow_sub n1 n2 ->
add_const (Cop(Csubi, [c1; c2])) (n1 - n2)
| (Cop(Caddi, [c1; Cconst_int n1]), c2) ->
add_const (Cop(Csubi, [c1; c2])) n1
| (c1, Cop(Caddi, [c2; Cconst_int n2])) when n2 <> min_int ->
add_const (Cop(Csubi, [c1; c2])) (-n2)
| (c1, Cconst_int n) when n <> min_int ->
add_const c1 (-n)
| (c1, c2) ->
Cop(Csubi, [c1; c2])
let mul_int c1 c2 =
match (c1, c2) with
(Cconst_int 0, _) -> c1
| (Cconst_int 1, _) -> c2
| (_, Cconst_int 0) -> c2
| (_, Cconst_int 1) -> c1
| (_, _) -> Cop(Cmuli, [c1; c2])
let tag_int = function
Cconst_int n -> int_const n
| c -> Cop(Caddi, [Cop(Clsl, [c; Cconst_int 1]); Cconst_int 1])
let force_tag_int = function
Cconst_int n -> int_const n
| c -> Cop(Cor, [Cop(Clsl, [c; Cconst_int 1]); Cconst_int 1])
let untag_int = function
Cconst_int n -> Cconst_int(n asr 1)
| Cop(Caddi, [Cop(Clsl, [c; Cconst_int 1]); Cconst_int 1]) -> c
| Cop(Cor, [Cop(Casr, [c; Cconst_int n]); Cconst_int 1])
when n > 0 && n < size_int * 8 ->
Cop(Casr, [c; Cconst_int (n+1)])
| Cop(Cor, [Cop(Clsr, [c; Cconst_int n]); Cconst_int 1])
when n > 0 && n < size_int * 8 ->
Cop(Clsr, [c; Cconst_int (n+1)])
| Cop(Cor, [c; Cconst_int 1]) -> Cop(Casr, [c; Cconst_int 1])
| c -> Cop(Casr, [c; Cconst_int 1])
let lsl_int c1 c2 =
match (c1, c2) with
(Cop(Clsl, [c; Cconst_int n1]), Cconst_int n2)
when n1 > 0 && n2 > 0 && n1 + n2 < size_int * 8 ->
Cop(Clsl, [c; Cconst_int (n1 + n2)])
| (_, _) ->
Cop(Clsl, [c1; c2])
let ignore_low_bit_int = function
Cop(Caddi, [(Cop(Clsl, [_; Cconst_int 1]) as c); Cconst_int 1]) -> c
| Cop(Cor, [c; Cconst_int 1]) -> c
| c -> c
let is_nonzero_constant = function
Cconst_int n -> n <> 0
| Cconst_natint n -> n <> 0n
| _ -> false
let safe_divmod op c1 c2 dbg =
if !Clflags.fast || is_nonzero_constant c2 then
Cop(op, [c1; c2])
else
bind "divisor" c2 (fun c2 ->
Cifthenelse(c2,
Cop(op, [c1; c2]),
Cop(Craise dbg,
[Cconst_symbol "caml_bucket_Division_by_zero"])))
(* Bool *)
let test_bool = function
Cop(Caddi, [Cop(Clsl, [c; Cconst_int 1]); Cconst_int 1]) -> c
| Cop(Clsl, [c; Cconst_int 1]) -> c
| c -> Cop(Ccmpi Cne, [c; Cconst_int 1])
(* Float *)
let box_float c = Cop(Calloc, [alloc_float_header; c])
let rec unbox_float = function
Cop(Calloc, [header; c]) -> c
| Clet(id, exp, body) -> Clet(id, exp, unbox_float body)
| Cifthenelse(cond, e1, e2) ->
Cifthenelse(cond, unbox_float e1, unbox_float e2)
| Csequence(e1, e2) -> Csequence(e1, unbox_float e2)
| Cswitch(e, tbl, el) -> Cswitch(e, tbl, Array.map unbox_float el)
| Ccatch(n, ids, e1, e2) -> Ccatch(n, ids, unbox_float e1, unbox_float e2)
| Ctrywith(e1, id, e2) -> Ctrywith(unbox_float e1, id, unbox_float e2)
| c -> Cop(Cload Double_u, [c])
Complex
let box_complex c_re c_im =
Cop(Calloc, [alloc_floatarray_header 2; c_re; c_im])
let complex_re c = Cop(Cload Double_u, [c])
let complex_im c = Cop(Cload Double_u,
[Cop(Cadda, [c; Cconst_int size_float])])
(* Unit *)
let return_unit c = Csequence(c, Cconst_pointer 1)
let rec remove_unit = function
Cconst_pointer 1 -> Ctuple []
| Csequence(c, Cconst_pointer 1) -> c
| Csequence(c1, c2) ->
Csequence(c1, remove_unit c2)
| Cifthenelse(cond, ifso, ifnot) ->
Cifthenelse(cond, remove_unit ifso, remove_unit ifnot)
| Cswitch(sel, index, cases) ->
Cswitch(sel, index, Array.map remove_unit cases)
| Ccatch(io, ids, body, handler) ->
Ccatch(io, ids, remove_unit body, remove_unit handler)
| Ctrywith(body, exn, handler) ->
Ctrywith(remove_unit body, exn, remove_unit handler)
| Clet(id, c1, c2) ->
Clet(id, c1, remove_unit c2)
| Cop(Capply (mty, dbg), args) ->
Cop(Capply (typ_void, dbg), args)
| Cop(Cextcall(proc, mty, alloc, dbg), args) ->
Cop(Cextcall(proc, typ_void, alloc, dbg), args)
| Cexit (_,_) as c -> c
| Ctuple [] as c -> c
| c -> Csequence(c, Ctuple [])
(* Access to block fields *)
let field_address ptr n =
if n = 0
then ptr
else Cop(Cadda, [ptr; Cconst_int(n * size_addr)])
let get_field ptr n =
Cop(Cload Word, [field_address ptr n])
let set_field ptr n newval =
Cop(Cstore Word, [field_address ptr n; newval])
let header ptr =
Cop(Cload Word, [Cop(Cadda, [ptr; Cconst_int(-size_int)])])
let tag_offset =
if big_endian then -1 else -size_int
let get_tag ptr =
if Arch.word_addressed then (* If byte loads are slow *)
Cop(Cand, [header ptr; Cconst_int 255])
else (* If byte loads are efficient *)
Cop(Cload Byte_unsigned,
[Cop(Cadda, [ptr; Cconst_int(tag_offset)])])
let get_size ptr =
Cop(Clsr, [header ptr; Cconst_int 10])
(* Array indexing *)
let log2_size_addr = Misc.log2 size_addr
let log2_size_float = Misc.log2 size_float
let wordsize_shift = 9
let numfloat_shift = 9 + log2_size_float - log2_size_addr
let is_addr_array_hdr hdr =
Cop(Ccmpi Cne, [Cop(Cand, [hdr; Cconst_int 255]); floatarray_tag])
let is_addr_array_ptr ptr =
Cop(Ccmpi Cne, [get_tag ptr; floatarray_tag])
let addr_array_length hdr = Cop(Clsr, [hdr; Cconst_int wordsize_shift])
let float_array_length hdr = Cop(Clsr, [hdr; Cconst_int numfloat_shift])
let lsl_const c n =
Cop(Clsl, [c; Cconst_int n])
let array_indexing log2size ptr ofs =
match ofs with
Cconst_int n ->
let i = n asr 1 in
if i = 0 then ptr else Cop(Cadda, [ptr; Cconst_int(i lsl log2size)])
| Cop(Caddi, [Cop(Clsl, [c; Cconst_int 1]); Cconst_int 1]) ->
Cop(Cadda, [ptr; lsl_const c log2size])
| Cop(Caddi, [c; Cconst_int n]) ->
Cop(Cadda, [Cop(Cadda, [ptr; lsl_const c (log2size - 1)]);
Cconst_int((n-1) lsl (log2size - 1))])
| _ ->
Cop(Cadda, [Cop(Cadda, [ptr; lsl_const ofs (log2size - 1)]);
Cconst_int((-1) lsl (log2size - 1))])
let addr_array_ref arr ofs =
Cop(Cload Word, [array_indexing log2_size_addr arr ofs])
let unboxed_float_array_ref arr ofs =
Cop(Cload Double_u, [array_indexing log2_size_float arr ofs])
let float_array_ref arr ofs =
box_float(unboxed_float_array_ref arr ofs)
let addr_array_set arr ofs newval =
Cop(Cextcall("caml_modify", typ_void, false, Debuginfo.none),
[array_indexing log2_size_addr arr ofs; newval])
let int_array_set arr ofs newval =
Cop(Cstore Word, [array_indexing log2_size_addr arr ofs; newval])
let float_array_set arr ofs newval =
Cop(Cstore Double_u, [array_indexing log2_size_float arr ofs; newval])
(* String length *)
let string_length exp =
bind "str" exp (fun str ->
let tmp_var = Ident.create "tmp" in
Clet(tmp_var,
Cop(Csubi,
[Cop(Clsl,
[Cop(Clsr, [header str; Cconst_int 10]);
Cconst_int log2_size_addr]);
Cconst_int 1]),
Cop(Csubi,
[Cvar tmp_var;
Cop(Cload Byte_unsigned,
[Cop(Cadda, [str; Cvar tmp_var])])])))
(* Message sending *)
let lookup_tag obj tag =
bind "tag" tag (fun tag ->
Cop(Cextcall("caml_get_public_method", typ_addr, false, Debuginfo.none),
[obj; tag]))
let lookup_label obj lab =
bind "lab" lab (fun lab ->
let table = Cop (Cload Word, [obj]) in
addr_array_ref table lab)
let call_cached_method obj tag cache pos args dbg =
let arity = List.length args in
let cache = array_indexing log2_size_addr cache pos in
Compilenv.need_send_fun arity;
Cop(Capply (typ_addr, dbg),
Cconst_symbol("caml_send" ^ string_of_int arity) ::
obj :: tag :: cache :: args)
(* Allocation *)
let make_alloc_generic set_fn tag wordsize args =
if wordsize <= Config.max_young_wosize then
Cop(Calloc, Cconst_natint(block_header tag wordsize) :: args)
else begin
let id = Ident.create "alloc" in
let rec fill_fields idx = function
[] -> Cvar id
| e1::el -> Csequence(set_fn (Cvar id) (Cconst_int idx) e1,
fill_fields (idx + 2) el) in
Clet(id,
Cop(Cextcall("caml_alloc", typ_addr, true, Debuginfo.none),
[Cconst_int wordsize; Cconst_int tag]),
fill_fields 1 args)
end
let make_alloc tag args =
make_alloc_generic addr_array_set tag (List.length args) args
let make_float_alloc tag args =
make_alloc_generic float_array_set tag
(List.length args * size_float / size_addr) args
(* To compile "let rec" over values *)
let fundecls_size fundecls =
let sz = ref (-1) in
List.iter
(fun (label, arity, params, body) ->
sz := !sz + 1 + (if arity = 1 then 2 else 3))
fundecls;
!sz
type rhs_kind =
| RHS_block of int
| RHS_nonrec
;;
let rec expr_size = function
| Uclosure(fundecls, clos_vars) ->
RHS_block (fundecls_size fundecls + List.length clos_vars)
| Ulet(id, exp, body) ->
expr_size body
| Uletrec(bindings, body) ->
expr_size body
| Uprim(Pmakeblock(tag, mut), args, _) ->
RHS_block (List.length args)
| Uprim(Pmakearray(Paddrarray | Pintarray), args, _) ->
RHS_block (List.length args)
| Usequence(exp, exp') ->
expr_size exp'
| _ -> RHS_nonrec
(* Record application and currying functions *)
let apply_function n =
Compilenv.need_apply_fun n; "caml_apply" ^ string_of_int n
let curry_function n =
Compilenv.need_curry_fun n;
if n >= 0
then "caml_curry" ^ string_of_int n
else "caml_tuplify" ^ string_of_int (-n)
(* Comparisons *)
let transl_comparison = function
Lambda.Ceq -> Ceq
| Lambda.Cneq -> Cne
| Lambda.Cge -> Cge
| Lambda.Cgt -> Cgt
| Lambda.Cle -> Cle
| Lambda.Clt -> Clt
(* Translate structured constants *)
let const_label = ref 0
let new_const_label () =
incr const_label;
!const_label
let new_const_symbol () =
incr const_label;
Compilenv.make_symbol (Some (string_of_int !const_label))
let structured_constants = ref ([] : (string * structured_constant) list)
let transl_constant = function
Const_base(Const_int n) ->
int_const n
| Const_base(Const_char c) ->
Cconst_int(((Char.code c) lsl 1) + 1)
| Const_pointer n ->
if n <= max_repr_int && n >= min_repr_int
then Cconst_pointer((n lsl 1) + 1)
else Cconst_natpointer
(Nativeint.add (Nativeint.shift_left (Nativeint.of_int n) 1) 1n)
| cst ->
let lbl = new_const_symbol() in
structured_constants := (lbl, cst) :: !structured_constants;
Cconst_symbol lbl
(* Translate constant closures *)
let constant_closures =
ref ([] : (string * (string * int * Ident.t list * ulambda) list) list)
(* Boxed integers *)
let box_int_constant bi n =
match bi with
Pnativeint -> Const_base(Const_nativeint n)
| Pint32 -> Const_base(Const_int32 (Nativeint.to_int32 n))
| Pint64 -> Const_base(Const_int64 (Int64.of_nativeint n))
let operations_boxed_int bi =
match bi with
Pnativeint -> "caml_nativeint_ops"
| Pint32 -> "caml_int32_ops"
| Pint64 -> "caml_int64_ops"
let alloc_header_boxed_int bi =
match bi with
Pnativeint -> alloc_boxedintnat_header
| Pint32 -> alloc_boxedint32_header
| Pint64 -> alloc_boxedint64_header
let box_int bi arg =
match arg with
Cconst_int n ->
transl_constant (box_int_constant bi (Nativeint.of_int n))
| Cconst_natint n ->
transl_constant (box_int_constant bi n)
| _ ->
let arg' =
if bi = Pint32 && size_int = 8 && big_endian
then Cop(Clsl, [arg; Cconst_int 32])
else arg in
Cop(Calloc, [alloc_header_boxed_int bi;
Cconst_symbol(operations_boxed_int bi);
arg'])
let rec unbox_int bi arg =
match arg with
Cop(Calloc, [hdr; ops; Cop(Clsl, [contents; Cconst_int 32])])
when bi = Pint32 && size_int = 8 && big_endian ->
Force sign - extension of low 32 bits
Cop(Casr, [Cop(Clsl, [contents; Cconst_int 32]); Cconst_int 32])
| Cop(Calloc, [hdr; ops; contents])
when bi = Pint32 && size_int = 8 && not big_endian ->
Force sign - extension of low 32 bits
Cop(Casr, [Cop(Clsl, [contents; Cconst_int 32]); Cconst_int 32])
| Cop(Calloc, [hdr; ops; contents]) ->
contents
| Clet(id, exp, body) -> Clet(id, exp, unbox_int bi body)
| Cifthenelse(cond, e1, e2) ->
Cifthenelse(cond, unbox_int bi e1, unbox_int bi e2)
| Csequence(e1, e2) -> Csequence(e1, unbox_int bi e2)
| Cswitch(e, tbl, el) -> Cswitch(e, tbl, Array.map (unbox_int bi) el)
| Ccatch(n, ids, e1, e2) -> Ccatch(n, ids, unbox_int bi e1, unbox_int bi e2)
| Ctrywith(e1, id, e2) -> Ctrywith(unbox_int bi e1, id, unbox_int bi e2)
| _ ->
Cop(Cload(if bi = Pint32 then Thirtytwo_signed else Word),
[Cop(Cadda, [arg; Cconst_int size_addr])])
let make_unsigned_int bi arg =
if bi = Pint32 && size_int = 8
then Cop(Cand, [arg; Cconst_natint 0xFFFFFFFFn])
else arg
(* Big arrays *)
let bigarray_elt_size = function
Pbigarray_unknown -> assert false
| Pbigarray_float32 -> 4
| Pbigarray_float64 -> 8
| Pbigarray_sint8 -> 1
| Pbigarray_uint8 -> 1
| Pbigarray_sint16 -> 2
| Pbigarray_uint16 -> 2
| Pbigarray_int32 -> 4
| Pbigarray_int64 -> 8
| Pbigarray_caml_int -> size_int
| Pbigarray_native_int -> size_int
| Pbigarray_complex32 -> 8
| Pbigarray_complex64 -> 16
let bigarray_indexing unsafe elt_kind layout b args dbg =
let check_bound a1 a2 k =
if unsafe then k else Csequence(Cop(Ccheckbound dbg, [a1;a2]), k) in
let rec ba_indexing dim_ofs delta_ofs = function
[] -> assert false
| [arg] ->
bind "idx" (untag_int arg)
(fun idx ->
check_bound (Cop(Cload Word,[field_address b dim_ofs])) idx idx)
| arg1 :: argl ->
let rem = ba_indexing (dim_ofs + delta_ofs) delta_ofs argl in
bind "idx" (untag_int arg1)
(fun idx ->
bind "bound" (Cop(Cload Word, [field_address b dim_ofs]))
(fun bound ->
check_bound bound idx (add_int (mul_int rem bound) idx))) in
let offset =
match layout with
Pbigarray_unknown_layout ->
assert false
| Pbigarray_c_layout ->
ba_indexing (4 + List.length args) (-1) (List.rev args)
| Pbigarray_fortran_layout ->
ba_indexing 5 1 (List.map (fun idx -> sub_int idx (Cconst_int 2)) args)
and elt_size =
bigarray_elt_size elt_kind in
let byte_offset =
if elt_size = 1
then offset
else Cop(Clsl, [offset; Cconst_int(log2 elt_size)]) in
Cop(Cadda, [Cop(Cload Word, [field_address b 1]); byte_offset])
let bigarray_word_kind = function
Pbigarray_unknown -> assert false
| Pbigarray_float32 -> Single
| Pbigarray_float64 -> Double
| Pbigarray_sint8 -> Byte_signed
| Pbigarray_uint8 -> Byte_unsigned
| Pbigarray_sint16 -> Sixteen_signed
| Pbigarray_uint16 -> Sixteen_unsigned
| Pbigarray_int32 -> Thirtytwo_signed
| Pbigarray_int64 -> Word
| Pbigarray_caml_int -> Word
| Pbigarray_native_int -> Word
| Pbigarray_complex32 -> Single
| Pbigarray_complex64 -> Double
let bigarray_get unsafe elt_kind layout b args dbg =
bind "ba" b (fun b ->
match elt_kind with
Pbigarray_complex32 | Pbigarray_complex64 ->
let kind = bigarray_word_kind elt_kind in
let sz = bigarray_elt_size elt_kind / 2 in
bind "addr" (bigarray_indexing unsafe elt_kind layout b args dbg) (fun addr ->
box_complex
(Cop(Cload kind, [addr]))
(Cop(Cload kind, [Cop(Cadda, [addr; Cconst_int sz])])))
| _ ->
Cop(Cload (bigarray_word_kind elt_kind),
[bigarray_indexing unsafe elt_kind layout b args dbg]))
let bigarray_set unsafe elt_kind layout b args newval dbg =
bind "ba" b (fun b ->
match elt_kind with
Pbigarray_complex32 | Pbigarray_complex64 ->
let kind = bigarray_word_kind elt_kind in
let sz = bigarray_elt_size elt_kind / 2 in
bind "newval" newval (fun newv ->
bind "addr" (bigarray_indexing unsafe elt_kind layout b args dbg) (fun addr ->
Csequence(
Cop(Cstore kind, [addr; complex_re newv]),
Cop(Cstore kind,
[Cop(Cadda, [addr; Cconst_int sz]); complex_im newv]))))
| _ ->
Cop(Cstore (bigarray_word_kind elt_kind),
[bigarray_indexing unsafe elt_kind layout b args dbg; newval]))
(* Simplification of some primitives into C calls *)
let default_prim name =
{ prim_name = name; prim_arity = 0 (*ignored*);
prim_alloc = true; prim_native_name = ""; prim_native_float = false }
let simplif_primitive_32bits = function
Pbintofint Pint64 -> Pccall (default_prim "caml_int64_of_int")
| Pintofbint Pint64 -> Pccall (default_prim "caml_int64_to_int")
| Pcvtbint(Pint32, Pint64) -> Pccall (default_prim "caml_int64_of_int32")
| Pcvtbint(Pint64, Pint32) -> Pccall (default_prim "caml_int64_to_int32")
| Pcvtbint(Pnativeint, Pint64) ->
Pccall (default_prim "caml_int64_of_nativeint")
| Pcvtbint(Pint64, Pnativeint) ->
Pccall (default_prim "caml_int64_to_nativeint")
| Pnegbint Pint64 -> Pccall (default_prim "caml_int64_neg")
| Paddbint Pint64 -> Pccall (default_prim "caml_int64_add")
| Psubbint Pint64 -> Pccall (default_prim "caml_int64_sub")
| Pmulbint Pint64 -> Pccall (default_prim "caml_int64_mul")
| Pdivbint Pint64 -> Pccall (default_prim "caml_int64_div")
| Pmodbint Pint64 -> Pccall (default_prim "caml_int64_mod")
| Pandbint Pint64 -> Pccall (default_prim "caml_int64_and")
| Porbint Pint64 -> Pccall (default_prim "caml_int64_or")
| Pxorbint Pint64 -> Pccall (default_prim "caml_int64_xor")
| Plslbint Pint64 -> Pccall (default_prim "caml_int64_shift_left")
| Plsrbint Pint64 -> Pccall (default_prim "caml_int64_shift_right_unsigned")
| Pasrbint Pint64 -> Pccall (default_prim "caml_int64_shift_right")
| Pbintcomp(Pint64, Lambda.Ceq) -> Pccall (default_prim "caml_equal")
| Pbintcomp(Pint64, Lambda.Cneq) -> Pccall (default_prim "caml_notequal")
| Pbintcomp(Pint64, Lambda.Clt) -> Pccall (default_prim "caml_lessthan")
| Pbintcomp(Pint64, Lambda.Cgt) -> Pccall (default_prim "caml_greaterthan")
| Pbintcomp(Pint64, Lambda.Cle) -> Pccall (default_prim "caml_lessequal")
| Pbintcomp(Pint64, Lambda.Cge) -> Pccall (default_prim "caml_greaterequal")
| Pbigarrayref(unsafe, n, Pbigarray_int64, layout) ->
Pccall (default_prim ("caml_ba_get_" ^ string_of_int n))
| Pbigarrayset(unsafe, n, Pbigarray_int64, layout) ->
Pccall (default_prim ("caml_ba_set_" ^ string_of_int n))
| p -> p
let simplif_primitive p =
match p with
| Pduprecord _ ->
Pccall (default_prim "caml_obj_dup")
| Pbigarrayref(unsafe, n, Pbigarray_unknown, layout) ->
Pccall (default_prim ("caml_ba_get_" ^ string_of_int n))
| Pbigarrayset(unsafe, n, Pbigarray_unknown, layout) ->
Pccall (default_prim ("caml_ba_set_" ^ string_of_int n))
| Pbigarrayref(unsafe, n, kind, Pbigarray_unknown_layout) ->
Pccall (default_prim ("caml_ba_get_" ^ string_of_int n))
| Pbigarrayset(unsafe, n, kind, Pbigarray_unknown_layout) ->
Pccall (default_prim ("caml_ba_set_" ^ string_of_int n))
| p ->
if size_int = 8 then p else simplif_primitive_32bits p
(* Build switchers both for constants and blocks *)
constants first
let transl_isout h arg = tag_int (Cop(Ccmpa Clt, [h ; arg]))
exception Found of int
let make_switch_gen arg cases acts =
let lcases = Array.length cases in
let new_cases = Array.create lcases 0 in
let store = Switch.mk_store (=) in
for i = 0 to Array.length cases-1 do
let act = cases.(i) in
let new_act = store.Switch.act_store act in
new_cases.(i) <- new_act
done ;
Cswitch
(arg, new_cases,
Array.map
(fun n -> acts.(n))
(store.Switch.act_get ()))
(* Then for blocks *)
module SArgBlocks =
struct
type primitive = operation
let eqint = Ccmpi Ceq
let neint = Ccmpi Cne
let leint = Ccmpi Cle
let ltint = Ccmpi Clt
let geint = Ccmpi Cge
let gtint = Ccmpi Cgt
type act = expression
let default = Cexit (0,[])
let make_prim p args = Cop (p,args)
let make_offset arg n = add_const arg n
let make_isout h arg = Cop (Ccmpa Clt, [h ; arg])
let make_isin h arg = Cop (Ccmpa Cge, [h ; arg])
let make_if cond ifso ifnot = Cifthenelse (cond, ifso, ifnot)
let make_switch arg cases actions =
make_switch_gen arg cases actions
let bind arg body = bind "switcher" arg body
end
module SwitcherBlocks = Switch.Make(SArgBlocks)
(* Auxiliary functions for optimizing "let" of boxed numbers (floats and
boxed integers *)
type unboxed_number_kind =
No_unboxing
| Boxed_float
| Boxed_integer of boxed_integer
let is_unboxed_number = function
Uconst(Const_base(Const_float f)) ->
Boxed_float
| Uprim(p, _, _) ->
begin match simplif_primitive p with
Pccall p -> if p.prim_native_float then Boxed_float else No_unboxing
| Pfloatfield _ -> Boxed_float
| Pfloatofint -> Boxed_float
| Pnegfloat -> Boxed_float
| Pabsfloat -> Boxed_float
| Paddfloat -> Boxed_float
| Psubfloat -> Boxed_float
| Pmulfloat -> Boxed_float
| Pdivfloat -> Boxed_float
| Parrayrefu Pfloatarray -> Boxed_float
| Parrayrefs Pfloatarray -> Boxed_float
| Pbintofint bi -> Boxed_integer bi
| Pcvtbint(src, dst) -> Boxed_integer dst
| Pnegbint bi -> Boxed_integer bi
| Paddbint bi -> Boxed_integer bi
| Psubbint bi -> Boxed_integer bi
| Pmulbint bi -> Boxed_integer bi
| Pdivbint bi -> Boxed_integer bi
| Pmodbint bi -> Boxed_integer bi
| Pandbint bi -> Boxed_integer bi
| Porbint bi -> Boxed_integer bi
| Pxorbint bi -> Boxed_integer bi
| Plslbint bi -> Boxed_integer bi
| Plsrbint bi -> Boxed_integer bi
| Pasrbint bi -> Boxed_integer bi
| Pbigarrayref(_, _, (Pbigarray_float32 | Pbigarray_float64), _) ->
Boxed_float
| Pbigarrayref(_, _, Pbigarray_int32, _) -> Boxed_integer Pint32
| Pbigarrayref(_, _, Pbigarray_int64, _) -> Boxed_integer Pint64
| Pbigarrayref(_, _, Pbigarray_native_int, _) -> Boxed_integer Pnativeint
| _ -> No_unboxing
end
| _ -> No_unboxing
let subst_boxed_number unbox_fn boxed_id unboxed_id exp =
let need_boxed = ref false in
let assigned = ref false in
let rec subst = function
Cvar id as e ->
if Ident.same id boxed_id then need_boxed := true; e
| Clet(id, arg, body) -> Clet(id, subst arg, subst body)
| Cassign(id, arg) ->
if Ident.same id boxed_id then begin
assigned := true;
Cassign(unboxed_id, subst(unbox_fn arg))
end else
Cassign(id, subst arg)
| Ctuple argv -> Ctuple(List.map subst argv)
| Cop(Cload _, [Cvar id]) as e ->
if Ident.same id boxed_id then Cvar unboxed_id else e
| Cop(Cload _, [Cop(Cadda, [Cvar id; _])]) as e ->
if Ident.same id boxed_id then Cvar unboxed_id else e
| Cop(op, argv) -> Cop(op, List.map subst argv)
| Csequence(e1, e2) -> Csequence(subst e1, subst e2)
| Cifthenelse(e1, e2, e3) -> Cifthenelse(subst e1, subst e2, subst e3)
| Cswitch(arg, index, cases) ->
Cswitch(subst arg, index, Array.map subst cases)
| Cloop e -> Cloop(subst e)
| Ccatch(nfail, ids, e1, e2) -> Ccatch(nfail, ids, subst e1, subst e2)
| Cexit (nfail, el) -> Cexit (nfail, List.map subst el)
| Ctrywith(e1, id, e2) -> Ctrywith(subst e1, id, subst e2)
| e -> e in
let res = subst exp in
(res, !need_boxed, !assigned)
(* Translate an expression *)
let functions = (Queue.create() : (string * Ident.t list * ulambda) Queue.t)
let rec transl = function
Uvar id ->
Cvar id
| Uconst sc ->
transl_constant sc
| Uclosure(fundecls, []) ->
let lbl = new_const_symbol() in
constant_closures := (lbl, fundecls) :: !constant_closures;
List.iter
(fun (label, arity, params, body) ->
Queue.add (label, params, body) functions)
fundecls;
Cconst_symbol lbl
| Uclosure(fundecls, clos_vars) ->
let block_size =
fundecls_size fundecls + List.length clos_vars in
let rec transl_fundecls pos = function
[] ->
List.map transl clos_vars
| (label, arity, params, body) :: rem ->
Queue.add (label, params, body) functions;
let header =
if pos = 0
then alloc_closure_header block_size
else alloc_infix_header pos in
if arity = 1 then
header ::
Cconst_symbol label ::
int_const 1 ::
transl_fundecls (pos + 3) rem
else
header ::
Cconst_symbol(curry_function arity) ::
int_const arity ::
Cconst_symbol label ::
transl_fundecls (pos + 4) rem in
Cop(Calloc, transl_fundecls 0 fundecls)
| Uoffset(arg, offset) ->
field_address (transl arg) offset
| Udirect_apply(lbl, args, dbg) ->
Cop(Capply(typ_addr, dbg), Cconst_symbol lbl :: List.map transl args)
| Ugeneric_apply(clos, [arg], dbg) ->
bind "fun" (transl clos) (fun clos ->
Cop(Capply(typ_addr, dbg), [get_field clos 0; transl arg; clos]))
| Ugeneric_apply(clos, args, dbg) ->
let arity = List.length args in
let cargs = Cconst_symbol(apply_function arity) ::
List.map transl (args @ [clos]) in
Cop(Capply(typ_addr, dbg), cargs)
| Usend(kind, met, obj, args, dbg) ->
let call_met obj args clos =
if args = [] then
Cop(Capply(typ_addr, dbg), [get_field clos 0;obj;clos])
else
let arity = List.length args + 1 in
let cargs = Cconst_symbol(apply_function arity) :: obj ::
(List.map transl args) @ [clos] in
Cop(Capply(typ_addr, dbg), cargs)
in
bind "obj" (transl obj) (fun obj ->
match kind, args with
Self, _ ->
bind "met" (lookup_label obj (transl met)) (call_met obj args)
| Cached, cache :: pos :: args ->
call_cached_method obj (transl met) (transl cache) (transl pos)
(List.map transl args) dbg
| _ ->
bind "met" (lookup_tag obj (transl met)) (call_met obj args))
| Ulet(id, exp, body) ->
begin match is_unboxed_number exp with
No_unboxing ->
Clet(id, transl exp, transl body)
| Boxed_float ->
transl_unbox_let box_float unbox_float transl_unbox_float
id exp body
| Boxed_integer bi ->
transl_unbox_let (box_int bi) (unbox_int bi) (transl_unbox_int bi)
id exp body
end
| Uletrec(bindings, body) ->
transl_letrec bindings (transl body)
(* Primitives *)
| Uprim(prim, args, dbg) ->
begin match (simplif_primitive prim, args) with
(Pgetglobal id, []) ->
Cconst_symbol (Ident.name id)
| (Pmakeblock(tag, mut), []) ->
transl_constant(Const_block(tag, []))
| (Pmakeblock(tag, mut), args) ->
make_alloc tag (List.map transl args)
| (Pccall prim, args) ->
if prim.prim_native_float then
box_float
(Cop(Cextcall(prim.prim_native_name, typ_float, false, dbg),
List.map transl_unbox_float args))
else
Cop(Cextcall(Primitive.native_name prim, typ_addr, prim.prim_alloc, dbg),
List.map transl args)
| (Pmakearray kind, []) ->
transl_constant(Const_block(0, []))
| (Pmakearray kind, args) ->
begin match kind with
Pgenarray ->
Cop(Cextcall("caml_make_array", typ_addr, true, Debuginfo.none),
[make_alloc 0 (List.map transl args)])
| Paddrarray | Pintarray ->
make_alloc 0 (List.map transl args)
| Pfloatarray ->
make_float_alloc Obj.double_array_tag
(List.map transl_unbox_float args)
end
| (Pbigarrayref(unsafe, num_dims, elt_kind, layout), arg1 :: argl) ->
let elt =
bigarray_get unsafe elt_kind layout
(transl arg1) (List.map transl argl) dbg in
begin match elt_kind with
Pbigarray_float32 | Pbigarray_float64 -> box_float elt
| Pbigarray_complex32 | Pbigarray_complex64 -> elt
| Pbigarray_int32 -> box_int Pint32 elt
| Pbigarray_int64 -> box_int Pint64 elt
| Pbigarray_native_int -> box_int Pnativeint elt
| Pbigarray_caml_int -> force_tag_int elt
| _ -> tag_int elt
end
| (Pbigarrayset(unsafe, num_dims, elt_kind, layout), arg1 :: argl) ->
let (argidx, argnewval) = split_last argl in
return_unit(bigarray_set unsafe elt_kind layout
(transl arg1)
(List.map transl argidx)
(match elt_kind with
Pbigarray_float32 | Pbigarray_float64 ->
transl_unbox_float argnewval
| Pbigarray_complex32 | Pbigarray_complex64 -> transl argnewval
| Pbigarray_int32 -> transl_unbox_int Pint32 argnewval
| Pbigarray_int64 -> transl_unbox_int Pint64 argnewval
| Pbigarray_native_int -> transl_unbox_int Pnativeint argnewval
| _ -> untag_int (transl argnewval))
dbg)
| (p, [arg]) ->
transl_prim_1 p arg dbg
| (p, [arg1; arg2]) ->
transl_prim_2 p arg1 arg2 dbg
| (p, [arg1; arg2; arg3]) ->
transl_prim_3 p arg1 arg2 arg3 dbg
| (_, _) ->
fatal_error "Cmmgen.transl:prim"
end
(* Control structures *)
| Uswitch(arg, s) ->
(* As in the bytecode interpreter, only matching against constants
can be checked *)
if Array.length s.us_index_blocks = 0 then
Cswitch
(untag_int (transl arg),
s.us_index_consts,
Array.map transl s.us_actions_consts)
else if Array.length s.us_index_consts = 0 then
transl_switch (get_tag (transl arg))
s.us_index_blocks s.us_actions_blocks
else
bind "switch" (transl arg) (fun arg ->
Cifthenelse(
Cop(Cand, [arg; Cconst_int 1]),
transl_switch
(untag_int arg) s.us_index_consts s.us_actions_consts,
transl_switch
(get_tag arg) s.us_index_blocks s.us_actions_blocks))
| Ustaticfail (nfail, args) ->
Cexit (nfail, List.map transl args)
| Ucatch(nfail, [], body, handler) ->
make_catch nfail (transl body) (transl handler)
| Ucatch(nfail, ids, body, handler) ->
Ccatch(nfail, ids, transl body, transl handler)
| Utrywith(body, exn, handler) ->
Ctrywith(transl body, exn, transl handler)
| Uifthenelse(Uprim(Pnot, [arg], _), ifso, ifnot) ->
transl (Uifthenelse(arg, ifnot, ifso))
| Uifthenelse(cond, ifso, Ustaticfail (nfail, [])) ->
exit_if_false cond (transl ifso) nfail
| Uifthenelse(cond, Ustaticfail (nfail, []), ifnot) ->
exit_if_true cond nfail (transl ifnot)
| Uifthenelse(Uprim(Psequand, _, _) as cond, ifso, ifnot) ->
let raise_num = next_raise_count () in
make_catch
raise_num
(exit_if_false cond (transl ifso) raise_num)
(transl ifnot)
| Uifthenelse(Uprim(Psequor, _, _) as cond, ifso, ifnot) ->
let raise_num = next_raise_count () in
make_catch
raise_num
(exit_if_true cond raise_num (transl ifnot))
(transl ifso)
| Uifthenelse (Uifthenelse (cond, condso, condnot), ifso, ifnot) ->
let num_true = next_raise_count () in
make_catch
num_true
(make_catch2
(fun shared_false ->
Cifthenelse
(test_bool (transl cond),
exit_if_true condso num_true shared_false,
exit_if_true condnot num_true shared_false))
(transl ifnot))
(transl ifso)
| Uifthenelse(cond, ifso, ifnot) ->
Cifthenelse(test_bool(transl cond), transl ifso, transl ifnot)
| Usequence(exp1, exp2) ->
Csequence(remove_unit(transl exp1), transl exp2)
| Uwhile(cond, body) ->
let raise_num = next_raise_count () in
return_unit
(Ccatch
(raise_num, [],
Cloop(exit_if_false cond (remove_unit(transl body)) raise_num),
Ctuple []))
| Ufor(id, low, high, dir, body) ->
let tst = match dir with Upto -> Cgt | Downto -> Clt in
let inc = match dir with Upto -> Caddi | Downto -> Csubi in
let raise_num = next_raise_count () in
let id_prev = Ident.rename id in
return_unit
(Clet
(id, transl low,
bind_nonvar "bound" (transl high) (fun high ->
Ccatch
(raise_num, [],
Cifthenelse
(Cop(Ccmpi tst, [Cvar id; high]), Cexit (raise_num, []),
Cloop
(Csequence
(remove_unit(transl body),
Clet(id_prev, Cvar id,
Csequence
(Cassign(id,
Cop(inc, [Cvar id; Cconst_int 2])),
Cifthenelse
(Cop(Ccmpi Ceq, [Cvar id_prev; high]),
Cexit (raise_num,[]), Ctuple [])))))),
Ctuple []))))
| Uassign(id, exp) ->
return_unit(Cassign(id, transl exp))
and transl_prim_1 p arg dbg =
match p with
Generic operations
Pidentity ->
transl arg
| Pignore ->
return_unit(remove_unit (transl arg))
Heap operations
| Pfield n ->
get_field (transl arg) n
| Pfloatfield n ->
let ptr = transl arg in
box_float(
Cop(Cload Double_u,
[if n = 0 then ptr
else Cop(Cadda, [ptr; Cconst_int(n * size_float)])]))
(* Exceptions *)
| Praise ->
Cop(Craise dbg, [transl arg])
Integer operations
| Pnegint ->
Cop(Csubi, [Cconst_int 2; transl arg])
| Poffsetint n ->
if no_overflow_lsl n then
add_const (transl arg) (n lsl 1)
else
transl_prim_2 Paddint arg (Uconst (Const_base(Const_int n))) Debuginfo.none
| Poffsetref n ->
return_unit
(bind "ref" (transl arg) (fun arg ->
Cop(Cstore Word,
[arg; add_const (Cop(Cload Word, [arg])) (n lsl 1)])))
(* Floating-point operations *)
| Pfloatofint ->
box_float(Cop(Cfloatofint, [untag_int(transl arg)]))
| Pintoffloat ->
tag_int(Cop(Cintoffloat, [transl_unbox_float arg]))
| Pnegfloat ->
box_float(Cop(Cnegf, [transl_unbox_float arg]))
| Pabsfloat ->
box_float(Cop(Cabsf, [transl_unbox_float arg]))
(* String operations *)
| Pstringlength ->
tag_int(string_length (transl arg))
(* Array operations *)
| Parraylength kind ->
begin match kind with
Pgenarray ->
let len =
if wordsize_shift = numfloat_shift then
Cop(Clsr, [header(transl arg); Cconst_int wordsize_shift])
else
bind "header" (header(transl arg)) (fun hdr ->
Cifthenelse(is_addr_array_hdr hdr,
Cop(Clsr, [hdr; Cconst_int wordsize_shift]),
Cop(Clsr, [hdr; Cconst_int numfloat_shift]))) in
Cop(Cor, [len; Cconst_int 1])
| Paddrarray | Pintarray ->
Cop(Cor, [addr_array_length(header(transl arg)); Cconst_int 1])
| Pfloatarray ->
Cop(Cor, [float_array_length(header(transl arg)); Cconst_int 1])
end
Boolean operations
| Pnot ->
1 - > 3 , 3 - > 1
(* Test integer/block *)
| Pisint ->
tag_int(Cop(Cand, [transl arg; Cconst_int 1]))
(* Boxed integers *)
| Pbintofint bi ->
box_int bi (untag_int (transl arg))
| Pintofbint bi ->
force_tag_int (transl_unbox_int bi arg)
| Pcvtbint(bi1, bi2) ->
box_int bi2 (transl_unbox_int bi1 arg)
| Pnegbint bi ->
box_int bi (Cop(Csubi, [Cconst_int 0; transl_unbox_int bi arg]))
| _ ->
fatal_error "Cmmgen.transl_prim_1"
and transl_prim_2 p arg1 arg2 dbg =
match p with
Heap operations
Psetfield(n, ptr) ->
if ptr then
return_unit(Cop(Cextcall("caml_modify", typ_void, false, Debuginfo.none),
[field_address (transl arg1) n; transl arg2]))
else
return_unit(set_field (transl arg1) n (transl arg2))
| Psetfloatfield n ->
let ptr = transl arg1 in
return_unit(
Cop(Cstore Double_u,
[if n = 0 then ptr
else Cop(Cadda, [ptr; Cconst_int(n * size_float)]);
transl_unbox_float arg2]))
Boolean operations
| Psequand ->
Cifthenelse(test_bool(transl arg1), transl arg2, Cconst_int 1)
let i d = Ident.create " res1 " in
Clet(id , transl arg1 ,
Cifthenelse(test_bool(Cvar i d ) , transl arg2 , Cvar i d ) )
Clet(id, transl arg1,
Cifthenelse(test_bool(Cvar id), transl arg2, Cvar id)) *)
| Psequor ->
Cifthenelse(test_bool(transl arg1), Cconst_int 3, transl arg2)
Integer operations
| Paddint ->
decr_int(add_int (transl arg1) (transl arg2))
| Psubint ->
incr_int(sub_int (transl arg1) (transl arg2))
| Pmulint ->
incr_int(Cop(Cmuli, [decr_int(transl arg1); untag_int(transl arg2)]))
| Pdivint ->
tag_int(safe_divmod Cdivi (untag_int(transl arg1)) (untag_int(transl arg2)) dbg)
| Pmodint ->
tag_int(safe_divmod Cmodi (untag_int(transl arg1)) (untag_int(transl arg2)) dbg)
| Pandint ->
Cop(Cand, [transl arg1; transl arg2])
| Porint ->
Cop(Cor, [transl arg1; transl arg2])
| Pxorint ->
Cop(Cor, [Cop(Cxor, [ignore_low_bit_int(transl arg1);
ignore_low_bit_int(transl arg2)]);
Cconst_int 1])
| Plslint ->
incr_int(lsl_int (decr_int(transl arg1)) (untag_int(transl arg2)))
| Plsrint ->
Cop(Cor, [Cop(Clsr, [transl arg1; untag_int(transl arg2)]);
Cconst_int 1])
| Pasrint ->
Cop(Cor, [Cop(Casr, [transl arg1; untag_int(transl arg2)]);
Cconst_int 1])
| Pintcomp cmp ->
tag_int(Cop(Ccmpi(transl_comparison cmp), [transl arg1; transl arg2]))
| Pisout ->
transl_isout (transl arg1) (transl arg2)
(* Float operations *)
| Paddfloat ->
box_float(Cop(Caddf,
[transl_unbox_float arg1; transl_unbox_float arg2]))
| Psubfloat ->
box_float(Cop(Csubf,
[transl_unbox_float arg1; transl_unbox_float arg2]))
| Pmulfloat ->
box_float(Cop(Cmulf,
[transl_unbox_float arg1; transl_unbox_float arg2]))
| Pdivfloat ->
box_float(Cop(Cdivf,
[transl_unbox_float arg1; transl_unbox_float arg2]))
| Pfloatcomp cmp ->
tag_int(Cop(Ccmpf(transl_comparison cmp),
[transl_unbox_float arg1; transl_unbox_float arg2]))
(* String operations *)
| Pstringrefu ->
tag_int(Cop(Cload Byte_unsigned,
[add_int (transl arg1) (untag_int(transl arg2))]))
| Pstringrefs ->
tag_int
(bind "str" (transl arg1) (fun str ->
bind "index" (untag_int (transl arg2)) (fun idx ->
Csequence(
Cop(Ccheckbound dbg, [string_length str; idx]),
Cop(Cload Byte_unsigned, [add_int str idx])))))
(* Array operations *)
| Parrayrefu kind ->
begin match kind with
Pgenarray ->
bind "arr" (transl arg1) (fun arr ->
bind "index" (transl arg2) (fun idx ->
Cifthenelse(is_addr_array_ptr arr,
addr_array_ref arr idx,
float_array_ref arr idx)))
| Paddrarray | Pintarray ->
addr_array_ref (transl arg1) (transl arg2)
| Pfloatarray ->
float_array_ref (transl arg1) (transl arg2)
end
| Parrayrefs kind ->
begin match kind with
Pgenarray ->
bind "index" (transl arg2) (fun idx ->
bind "arr" (transl arg1) (fun arr ->
bind "header" (header arr) (fun hdr ->
Cifthenelse(is_addr_array_hdr hdr,
Csequence(Cop(Ccheckbound dbg, [addr_array_length hdr; idx]),
addr_array_ref arr idx),
Csequence(Cop(Ccheckbound dbg, [float_array_length hdr; idx]),
float_array_ref arr idx)))))
| Paddrarray | Pintarray ->
bind "index" (transl arg2) (fun idx ->
bind "arr" (transl arg1) (fun arr ->
Csequence(Cop(Ccheckbound dbg, [addr_array_length(header arr); idx]),
addr_array_ref arr idx)))
| Pfloatarray ->
box_float(
bind "index" (transl arg2) (fun idx ->
bind "arr" (transl arg1) (fun arr ->
Csequence(Cop(Ccheckbound dbg,
[float_array_length(header arr); idx]),
unboxed_float_array_ref arr idx))))
end
Operations on bitvects
| Pbittest ->
bind "index" (untag_int(transl arg2)) (fun idx ->
tag_int(
Cop(Cand, [Cop(Clsr, [Cop(Cload Byte_unsigned,
[add_int (transl arg1)
(Cop(Clsr, [idx; Cconst_int 3]))]);
Cop(Cand, [idx; Cconst_int 7])]);
Cconst_int 1])))
(* Boxed integers *)
| Paddbint bi ->
box_int bi (Cop(Caddi,
[transl_unbox_int bi arg1; transl_unbox_int bi arg2]))
| Psubbint bi ->
box_int bi (Cop(Csubi,
[transl_unbox_int bi arg1; transl_unbox_int bi arg2]))
| Pmulbint bi ->
box_int bi (Cop(Cmuli,
[transl_unbox_int bi arg1; transl_unbox_int bi arg2]))
| Pdivbint bi ->
box_int bi (safe_divmod Cdivi
(transl_unbox_int bi arg1) (transl_unbox_int bi arg2)
dbg)
| Pmodbint bi ->
box_int bi (safe_divmod Cmodi
(transl_unbox_int bi arg1) (transl_unbox_int bi arg2)
dbg)
| Pandbint bi ->
box_int bi (Cop(Cand,
[transl_unbox_int bi arg1; transl_unbox_int bi arg2]))
| Porbint bi ->
box_int bi (Cop(Cor,
[transl_unbox_int bi arg1; transl_unbox_int bi arg2]))
| Pxorbint bi ->
box_int bi (Cop(Cxor,
[transl_unbox_int bi arg1; transl_unbox_int bi arg2]))
| Plslbint bi ->
box_int bi (Cop(Clsl,
[transl_unbox_int bi arg1; untag_int(transl arg2)]))
| Plsrbint bi ->
box_int bi (Cop(Clsr,
[make_unsigned_int bi (transl_unbox_int bi arg1);
untag_int(transl arg2)]))
| Pasrbint bi ->
box_int bi (Cop(Casr,
[transl_unbox_int bi arg1; untag_int(transl arg2)]))
| Pbintcomp(bi, cmp) ->
tag_int (Cop(Ccmpi(transl_comparison cmp),
[transl_unbox_int bi arg1; transl_unbox_int bi arg2]))
| _ ->
fatal_error "Cmmgen.transl_prim_2"
and transl_prim_3 p arg1 arg2 arg3 dbg =
match p with
(* String operations *)
Pstringsetu ->
return_unit(Cop(Cstore Byte_unsigned,
[add_int (transl arg1) (untag_int(transl arg2));
untag_int(transl arg3)]))
| Pstringsets ->
return_unit
(bind "str" (transl arg1) (fun str ->
bind "index" (untag_int (transl arg2)) (fun idx ->
Csequence(
Cop(Ccheckbound dbg, [string_length str; idx]),
Cop(Cstore Byte_unsigned,
[add_int str idx; untag_int(transl arg3)])))))
(* Array operations *)
| Parraysetu kind ->
return_unit(begin match kind with
Pgenarray ->
bind "newval" (transl arg3) (fun newval ->
bind "index" (transl arg2) (fun index ->
bind "arr" (transl arg1) (fun arr ->
Cifthenelse(is_addr_array_ptr arr,
addr_array_set arr index newval,
float_array_set arr index (unbox_float newval)))))
| Paddrarray ->
addr_array_set (transl arg1) (transl arg2) (transl arg3)
| Pintarray ->
int_array_set (transl arg1) (transl arg2) (transl arg3)
| Pfloatarray ->
float_array_set (transl arg1) (transl arg2) (transl_unbox_float arg3)
end)
| Parraysets kind ->
return_unit(begin match kind with
Pgenarray ->
bind "newval" (transl arg3) (fun newval ->
bind "index" (transl arg2) (fun idx ->
bind "arr" (transl arg1) (fun arr ->
bind "header" (header arr) (fun hdr ->
Cifthenelse(is_addr_array_hdr hdr,
Csequence(Cop(Ccheckbound dbg, [addr_array_length hdr; idx]),
addr_array_set arr idx newval),
Csequence(Cop(Ccheckbound dbg, [float_array_length hdr; idx]),
float_array_set arr idx
(unbox_float newval)))))))
| Paddrarray ->
bind "index" (transl arg2) (fun idx ->
bind "arr" (transl arg1) (fun arr ->
Csequence(Cop(Ccheckbound dbg, [addr_array_length(header arr); idx]),
addr_array_set arr idx (transl arg3))))
| Pintarray ->
bind "index" (transl arg2) (fun idx ->
bind "arr" (transl arg1) (fun arr ->
Csequence(Cop(Ccheckbound dbg, [addr_array_length(header arr); idx]),
int_array_set arr idx (transl arg3))))
| Pfloatarray ->
bind "index" (transl arg2) (fun idx ->
bind "arr" (transl arg1) (fun arr ->
Csequence(Cop(Ccheckbound dbg, [float_array_length(header arr);idx]),
float_array_set arr idx (transl_unbox_float arg3))))
end)
| _ ->
fatal_error "Cmmgen.transl_prim_3"
and transl_unbox_float = function
Uconst(Const_base(Const_float f)) -> Cconst_float f
| exp -> unbox_float(transl exp)
and transl_unbox_int bi = function
Uconst(Const_base(Const_int32 n)) ->
Cconst_natint (Nativeint.of_int32 n)
| Uconst(Const_base(Const_nativeint n)) ->
Cconst_natint n
| Uconst(Const_base(Const_int64 n)) ->
assert (size_int = 8); Cconst_natint (Int64.to_nativeint n)
| Uprim(Pbintofint bi', [Uconst(Const_base(Const_int i))], _) when bi = bi' ->
Cconst_int i
| exp -> unbox_int bi (transl exp)
and transl_unbox_let box_fn unbox_fn transl_unbox_fn id exp body =
let unboxed_id = Ident.create (Ident.name id) in
let trbody1 = transl body in
let (trbody2, need_boxed, is_assigned) =
subst_boxed_number unbox_fn id unboxed_id trbody1 in
if need_boxed && is_assigned then
Clet(id, transl exp, trbody1)
else
Clet(unboxed_id, transl_unbox_fn exp,
if need_boxed
then Clet(id, box_fn(Cvar unboxed_id), trbody2)
else trbody2)
and make_catch ncatch body handler = match body with
| Cexit (nexit,[]) when nexit=ncatch -> handler
| _ -> Ccatch (ncatch, [], body, handler)
and make_catch2 mk_body handler = match handler with
| Cexit (_,[])|Ctuple []|Cconst_int _|Cconst_pointer _ ->
mk_body handler
| _ ->
let nfail = next_raise_count () in
make_catch
nfail
(mk_body (Cexit (nfail,[])))
handler
and exit_if_true cond nfail otherwise =
match cond with
| Uconst (Const_pointer 0) -> otherwise
| Uconst (Const_pointer 1) -> Cexit (nfail,[])
| Uprim(Psequor, [arg1; arg2], _) ->
exit_if_true arg1 nfail (exit_if_true arg2 nfail otherwise)
| Uprim(Psequand, _, _) ->
begin match otherwise with
| Cexit (raise_num,[]) ->
exit_if_false cond (Cexit (nfail,[])) raise_num
| _ ->
let raise_num = next_raise_count () in
make_catch
raise_num
(exit_if_false cond (Cexit (nfail,[])) raise_num)
otherwise
end
| Uprim(Pnot, [arg], _) ->
exit_if_false arg otherwise nfail
| Uifthenelse (cond, ifso, ifnot) ->
make_catch2
(fun shared ->
Cifthenelse
(test_bool (transl cond),
exit_if_true ifso nfail shared,
exit_if_true ifnot nfail shared))
otherwise
| _ ->
Cifthenelse(test_bool(transl cond), Cexit (nfail, []), otherwise)
and exit_if_false cond otherwise nfail =
match cond with
| Uconst (Const_pointer 0) -> Cexit (nfail,[])
| Uconst (Const_pointer 1) -> otherwise
| Uprim(Psequand, [arg1; arg2], _) ->
exit_if_false arg1 (exit_if_false arg2 otherwise nfail) nfail
| Uprim(Psequor, _, _) ->
begin match otherwise with
| Cexit (raise_num,[]) ->
exit_if_true cond raise_num (Cexit (nfail,[]))
| _ ->
let raise_num = next_raise_count () in
make_catch
raise_num
(exit_if_true cond raise_num (Cexit (nfail,[])))
otherwise
end
| Uprim(Pnot, [arg], _) ->
exit_if_true arg nfail otherwise
| Uifthenelse (cond, ifso, ifnot) ->
make_catch2
(fun shared ->
Cifthenelse
(test_bool (transl cond),
exit_if_false ifso shared nfail,
exit_if_false ifnot shared nfail))
otherwise
| _ ->
Cifthenelse(test_bool(transl cond), otherwise, Cexit (nfail, []))
and transl_switch arg index cases = match Array.length cases with
| 0 -> fatal_error "Cmmgen.transl_switch"
| 1 -> transl cases.(0)
| _ ->
let n_index = Array.length index in
let actions = Array.map transl cases in
let inters = ref []
and this_high = ref (n_index-1)
and this_low = ref (n_index-1)
and this_act = ref index.(n_index-1) in
for i = n_index-2 downto 0 do
let act = index.(i) in
if act = !this_act then
decr this_low
else begin
inters := (!this_low, !this_high, !this_act) :: !inters ;
this_high := i ;
this_low := i ;
this_act := act
end
done ;
inters := (0, !this_high, !this_act) :: !inters ;
bind "switcher" arg
(fun a ->
SwitcherBlocks.zyva
(0,n_index-1)
(fun i -> Cconst_int i)
a
(Array.of_list !inters) actions)
and transl_letrec bindings cont =
let bsz = List.map (fun (id, exp) -> (id, exp, expr_size exp)) bindings in
let rec init_blocks = function
| [] -> fill_nonrec bsz
| (id, exp, RHS_block sz) :: rem ->
Clet(id, Cop(Cextcall("caml_alloc_dummy", typ_addr, true, Debuginfo.none),
[int_const sz]),
init_blocks rem)
| (id, exp, RHS_nonrec) :: rem ->
Clet (id, Cconst_int 0, init_blocks rem)
and fill_nonrec = function
| [] -> fill_blocks bsz
| (id, exp, RHS_block sz) :: rem -> fill_nonrec rem
| (id, exp, RHS_nonrec) :: rem ->
Clet (id, transl exp, fill_nonrec rem)
and fill_blocks = function
| [] -> cont
| (id, exp, RHS_block _) :: rem ->
Csequence(Cop(Cextcall("caml_update_dummy", typ_void, false, Debuginfo.none),
[Cvar id; transl exp]),
fill_blocks rem)
| (id, exp, RHS_nonrec) :: rem ->
fill_blocks rem
in init_blocks bsz
(* Translate a function definition *)
let transl_function lbl params body =
Cfunction {fun_name = lbl;
fun_args = List.map (fun id -> (id, typ_addr)) params;
fun_body = transl body;
fun_fast = !Clflags.optimize_for_speed}
(* Translate all function definitions *)
module StringSet =
Set.Make(struct
type t = string
let compare = compare
end)
let rec transl_all_functions already_translated cont =
try
let (lbl, params, body) = Queue.take functions in
if StringSet.mem lbl already_translated then
transl_all_functions already_translated cont
else begin
transl_all_functions (StringSet.add lbl already_translated)
(transl_function lbl params body :: cont)
end
with Queue.Empty ->
cont
(* Emit structured constants *)
let immstrings = Hashtbl.create 17
let rec emit_constant symb cst cont =
match cst with
Const_base(Const_float s) ->
Cint(float_header) :: Cdefine_symbol symb :: Cdouble s :: cont
| Const_base(Const_string s) | Const_immstring s ->
Cint(string_header (String.length s)) ::
Cdefine_symbol symb ::
emit_string_constant s cont
| Const_base(Const_int32 n) ->
Cint(boxedint32_header) :: Cdefine_symbol symb ::
emit_boxed_int32_constant n cont
| Const_base(Const_int64 n) ->
Cint(boxedint64_header) :: Cdefine_symbol symb ::
emit_boxed_int64_constant n cont
| Const_base(Const_nativeint n) ->
Cint(boxedintnat_header) :: Cdefine_symbol symb ::
emit_boxed_nativeint_constant n cont
| Const_block(tag, fields) ->
let (emit_fields, cont1) = emit_constant_fields fields cont in
Cint(block_header tag (List.length fields)) ::
Cdefine_symbol symb ::
emit_fields @ cont1
| Const_float_array(fields) ->
Cint(floatarray_header (List.length fields)) ::
Cdefine_symbol symb ::
Misc.map_end (fun f -> Cdouble f) fields cont
| _ -> fatal_error "gencmm.emit_constant"
and emit_constant_fields fields cont =
match fields with
[] -> ([], cont)
| f1 :: fl ->
let (data1, cont1) = emit_constant_field f1 cont in
let (datal, contl) = emit_constant_fields fl cont1 in
(data1 :: datal, contl)
and emit_constant_field field cont =
match field with
Const_base(Const_int n) ->
(Cint(Nativeint.add (Nativeint.shift_left (Nativeint.of_int n) 1) 1n),
cont)
| Const_base(Const_char c) ->
(Cint(Nativeint.of_int(((Char.code c) lsl 1) + 1)), cont)
| Const_base(Const_float s) ->
let lbl = new_const_label() in
(Clabel_address lbl,
Cint(float_header) :: Cdefine_label lbl :: Cdouble s :: cont)
| Const_base(Const_string s) ->
let lbl = new_const_label() in
(Clabel_address lbl,
Cint(string_header (String.length s)) :: Cdefine_label lbl ::
emit_string_constant s cont)
| Const_immstring s ->
begin try
(Clabel_address (Hashtbl.find immstrings s), cont)
with Not_found ->
let lbl = new_const_label() in
Hashtbl.add immstrings s lbl;
(Clabel_address lbl,
Cint(string_header (String.length s)) :: Cdefine_label lbl ::
emit_string_constant s cont)
end
| Const_base(Const_int32 n) ->
let lbl = new_const_label() in
(Clabel_address lbl,
Cint(boxedint32_header) :: Cdefine_label lbl ::
emit_boxed_int32_constant n cont)
| Const_base(Const_int64 n) ->
let lbl = new_const_label() in
(Clabel_address lbl,
Cint(boxedint64_header) :: Cdefine_label lbl ::
emit_boxed_int64_constant n cont)
| Const_base(Const_nativeint n) ->
let lbl = new_const_label() in
(Clabel_address lbl,
Cint(boxedintnat_header) :: Cdefine_label lbl ::
emit_boxed_nativeint_constant n cont)
| Const_pointer n ->
(Cint(Nativeint.add (Nativeint.shift_left (Nativeint.of_int n) 1) 1n),
cont)
| Const_block(tag, fields) ->
let lbl = new_const_label() in
let (emit_fields, cont1) = emit_constant_fields fields cont in
(Clabel_address lbl,
Cint(block_header tag (List.length fields)) :: Cdefine_label lbl ::
emit_fields @ cont1)
| Const_float_array(fields) ->
let lbl = new_const_label() in
(Clabel_address lbl,
Cint(floatarray_header (List.length fields)) :: Cdefine_label lbl ::
Misc.map_end (fun f -> Cdouble f) fields cont)
and emit_string_constant s cont =
let n = size_int - 1 - (String.length s) mod size_int in
Cstring s :: Cskip n :: Cint8 n :: cont
and emit_boxed_int32_constant n cont =
let n = Nativeint.of_int32 n in
if size_int = 8 then
Csymbol_address("caml_int32_ops") :: Cint32 n :: Cint32 0n :: cont
else
Csymbol_address("caml_int32_ops") :: Cint n :: cont
and emit_boxed_nativeint_constant n cont =
Csymbol_address("caml_nativeint_ops") :: Cint n :: cont
and emit_boxed_int64_constant n cont =
let lo = Int64.to_nativeint n in
if size_int = 8 then
Csymbol_address("caml_int64_ops") :: Cint lo :: cont
else begin
let hi = Int64.to_nativeint (Int64.shift_right n 32) in
if big_endian then
Csymbol_address("caml_int64_ops") :: Cint hi :: Cint lo :: cont
else
Csymbol_address("caml_int64_ops") :: Cint lo :: Cint hi :: cont
end
(* Emit constant closures *)
let emit_constant_closure symb fundecls cont =
match fundecls with
[] -> assert false
| (label, arity, params, body) :: remainder ->
let rec emit_others pos = function
[] -> cont
| (label, arity, params, body) :: rem ->
if arity = 1 then
Cint(infix_header pos) ::
Csymbol_address label ::
Cint 3n ::
emit_others (pos + 3) rem
else
Cint(infix_header pos) ::
Csymbol_address(curry_function arity) ::
Cint(Nativeint.of_int (arity lsl 1 + 1)) ::
Csymbol_address label ::
emit_others (pos + 4) rem in
Cint(closure_header (fundecls_size fundecls)) ::
Cdefine_symbol symb ::
if arity = 1 then
Csymbol_address label ::
Cint 3n ::
emit_others 3 remainder
else
Csymbol_address(curry_function arity) ::
Cint(Nativeint.of_int (arity lsl 1 + 1)) ::
Csymbol_address label ::
emit_others 4 remainder
(* Emit all structured constants *)
let emit_all_constants cont =
let c = ref cont in
List.iter
(fun (lbl, cst) -> c := Cdata(emit_constant lbl cst []) :: !c)
!structured_constants;
structured_constants := [];
PR#3979
List.iter
(fun (symb, fundecls) ->
c := Cdata(emit_constant_closure symb fundecls []) :: !c)
!constant_closures;
constant_closures := [];
!c
(* Translate a compilation unit *)
let compunit size ulam =
let glob = Compilenv.make_symbol None in
let init_code = transl ulam in
let c1 = [Cfunction {fun_name = Compilenv.make_symbol (Some "entry");
fun_args = [];
fun_body = init_code; fun_fast = false}] in
let c2 = transl_all_functions StringSet.empty c1 in
let c3 = emit_all_constants c2 in
Cdata [Cint(block_header 0 size);
Cglobal_symbol glob;
Cdefine_symbol glob;
Cskip(size * size_addr)] :: c3
CAMLprim value caml_cache_public_method ( value meths , value tag , value * cache )
{
int li = 3 , hi = Field(meths,0 ) , mi ;
while ( li < hi ) { // no need to check the 1st time
mi = ( ( li+hi ) > > 1 ) | 1 ;
if ( tag < Field(meths , mi ) ) hi = mi-2 ;
else li = mi ;
}
* cache = ( li-3)*sizeof(value)+1 ;
return Field ( meths , li-1 ) ;
}
CAMLprim value caml_cache_public_method (value meths, value tag, value *cache)
{
int li = 3, hi = Field(meths,0), mi;
while (li < hi) { // no need to check the 1st time
mi = ((li+hi) >> 1) | 1;
if (tag < Field(meths,mi)) hi = mi-2;
else li = mi;
}
*cache = (li-3)*sizeof(value)+1;
return Field (meths, li-1);
}
*)
let cache_public_method meths tag cache =
let raise_num = next_raise_count () in
let li = Ident.create "li" and hi = Ident.create "hi"
and mi = Ident.create "mi" and tagged = Ident.create "tagged" in
Clet (
li, Cconst_int 3,
Clet (
hi, Cop(Cload Word, [meths]),
Csequence(
Ccatch
(raise_num, [],
Cloop
(Clet(
mi,
Cop(Cor,
[Cop(Clsr, [Cop(Caddi, [Cvar li; Cvar hi]); Cconst_int 1]);
Cconst_int 1]),
Csequence(
Cifthenelse
(Cop (Ccmpi Clt,
[tag;
Cop(Cload Word,
[Cop(Cadda,
[meths; lsl_const (Cvar mi) log2_size_addr])])]),
Cassign(hi, Cop(Csubi, [Cvar mi; Cconst_int 2])),
Cassign(li, Cvar mi)),
Cifthenelse
(Cop(Ccmpi Cge, [Cvar li; Cvar hi]), Cexit (raise_num, []),
Ctuple [])))),
Ctuple []),
Clet (
tagged, Cop(Cadda, [lsl_const (Cvar li) log2_size_addr;
Cconst_int(1 - 3 * size_addr)]),
Csequence(Cop (Cstore Word, [cache; Cvar tagged]),
Cvar tagged)))))
Generate an application function :
( defun caml_applyN ( a1 ... aN clos )
( if (= clos.arity N )
( app clos.direct a1 ... aN clos )
( let ( clos1 ( app clos.code a1 clos )
clos2 ( app clos1.code a2 clos )
...
closN-1 ( app closN-2.code ) )
( app closN-1.code aN closN-1 ) ) ) )
(defun caml_applyN (a1 ... aN clos)
(if (= clos.arity N)
(app clos.direct a1 ... aN clos)
(let (clos1 (app clos.code a1 clos)
clos2 (app clos1.code a2 clos)
...
closN-1 (app closN-2.code aN-1 closN-2))
(app closN-1.code aN closN-1))))
*)
let apply_function_body arity =
let arg = Array.create arity (Ident.create "arg") in
for i = 1 to arity - 1 do arg.(i) <- Ident.create "arg" done;
let clos = Ident.create "clos" in
let rec app_fun clos n =
if n = arity-1 then
Cop(Capply(typ_addr, Debuginfo.none),
[get_field (Cvar clos) 0; Cvar arg.(n); Cvar clos])
else begin
let newclos = Ident.create "clos" in
Clet(newclos,
Cop(Capply(typ_addr, Debuginfo.none),
[get_field (Cvar clos) 0; Cvar arg.(n); Cvar clos]),
app_fun newclos (n+1))
end in
let args = Array.to_list arg in
let all_args = args @ [clos] in
(args, clos,
if arity = 1 then app_fun clos 0 else
Cifthenelse(
Cop(Ccmpi Ceq, [get_field (Cvar clos) 1; int_const arity]),
Cop(Capply(typ_addr, Debuginfo.none),
get_field (Cvar clos) 2 :: List.map (fun s -> Cvar s) all_args),
app_fun clos 0))
let send_function arity =
let (args, clos', body) = apply_function_body (1+arity) in
let cache = Ident.create "cache"
and obj = List.hd args
and tag = Ident.create "tag" in
let clos =
let cache = Cvar cache and obj = Cvar obj and tag = Cvar tag in
let meths = Ident.create "meths" and cached = Ident.create "cached" in
let real = Ident.create "real" in
let mask = get_field (Cvar meths) 1 in
let cached_pos = Cvar cached in
let tag_pos = Cop(Cadda, [Cop (Cadda, [cached_pos; Cvar meths]);
Cconst_int(3*size_addr-1)]) in
let tag' = Cop(Cload Word, [tag_pos]) in
Clet (
meths, Cop(Cload Word, [obj]),
Clet (
cached, Cop(Cand, [Cop(Cload Word, [cache]); mask]),
Clet (
real,
Cifthenelse(Cop(Ccmpa Cne, [tag'; tag]),
cache_public_method (Cvar meths) tag cache,
cached_pos),
Cop(Cload Word, [Cop(Cadda, [Cop (Cadda, [Cvar real; Cvar meths]);
Cconst_int(2*size_addr-1)])]))))
in
let body = Clet(clos', clos, body) in
let fun_args =
[obj, typ_addr; tag, typ_int; cache, typ_addr]
@ List.map (fun id -> (id, typ_addr)) (List.tl args) in
Cfunction
{fun_name = "caml_send" ^ string_of_int arity;
fun_args = fun_args;
fun_body = body;
fun_fast = true}
let apply_function arity =
let (args, clos, body) = apply_function_body arity in
let all_args = args @ [clos] in
Cfunction
{fun_name = "caml_apply" ^ string_of_int arity;
fun_args = List.map (fun id -> (id, typ_addr)) all_args;
fun_body = body;
fun_fast = true}
Generate tuplifying functions :
( defun caml_tuplifyN ( arg clos )
( app clos.direct # 0(arg ) ... # N-1(arg ) clos ) )
(defun caml_tuplifyN (arg clos)
(app clos.direct #0(arg) ... #N-1(arg) clos)) *)
let tuplify_function arity =
let arg = Ident.create "arg" in
let clos = Ident.create "clos" in
let rec access_components i =
if i >= arity
then []
else get_field (Cvar arg) i :: access_components(i+1) in
Cfunction
{fun_name = "caml_tuplify" ^ string_of_int arity;
fun_args = [arg, typ_addr; clos, typ_addr];
fun_body =
Cop(Capply(typ_addr, Debuginfo.none),
get_field (Cvar clos) 2 :: access_components 0 @ [Cvar clos]);
fun_fast = true}
Generate currying functions :
( defun caml_curryN ( arg clos )
( alloc HDR caml_curryN_1 arg clos ) )
( defun caml_curryN_1 ( arg clos )
( alloc HDR caml_curryN_2 arg clos ) )
...
( defun caml_curryN_N-1 ( arg clos )
( let ( closN-2 clos.cdr
closN-3 closN-2.cdr
...
clos1 clos2.cdr
clos clos1.cdr )
( app clos.direct
clos1.car clos2.car ... closN-2.car clos.car arg clos ) ) )
(defun caml_curryN (arg clos)
(alloc HDR caml_curryN_1 arg clos))
(defun caml_curryN_1 (arg clos)
(alloc HDR caml_curryN_2 arg clos))
...
(defun caml_curryN_N-1 (arg clos)
(let (closN-2 clos.cdr
closN-3 closN-2.cdr
...
clos1 clos2.cdr
clos clos1.cdr)
(app clos.direct
clos1.car clos2.car ... closN-2.car clos.car arg clos))) *)
let final_curry_function arity =
let last_arg = Ident.create "arg" in
let last_clos = Ident.create "clos" in
let rec curry_fun args clos n =
if n = 0 then
Cop(Capply(typ_addr, Debuginfo.none),
get_field (Cvar clos) 2 ::
args @ [Cvar last_arg; Cvar clos])
else begin
let newclos = Ident.create "clos" in
Clet(newclos,
get_field (Cvar clos) 3,
curry_fun (get_field (Cvar clos) 2 :: args) newclos (n-1))
end in
Cfunction
{fun_name = "caml_curry" ^ string_of_int arity ^
"_" ^ string_of_int (arity-1);
fun_args = [last_arg, typ_addr; last_clos, typ_addr];
fun_body = curry_fun [] last_clos (arity-1);
fun_fast = true}
let rec intermediate_curry_functions arity num =
if num = arity - 1 then
[final_curry_function arity]
else begin
let name1 = "caml_curry" ^ string_of_int arity in
let name2 = if num = 0 then name1 else name1 ^ "_" ^ string_of_int num in
let arg = Ident.create "arg" and clos = Ident.create "clos" in
Cfunction
{fun_name = name2;
fun_args = [arg, typ_addr; clos, typ_addr];
fun_body = Cop(Calloc,
[alloc_closure_header 4;
Cconst_symbol(name1 ^ "_" ^ string_of_int (num+1));
int_const 1; Cvar arg; Cvar clos]);
fun_fast = true}
:: intermediate_curry_functions arity (num+1)
end
let curry_function arity =
if arity >= 0
then intermediate_curry_functions arity 0
else [tuplify_function (-arity)]
module IntSet = Set.Make(
struct
type t = int
let compare = compare
end)
let default_apply = IntSet.add 2 (IntSet.add 3 IntSet.empty)
These apply funs are always present in the main program because
the run - time system needs them ( cf . .
the run-time system needs them (cf. asmrun/<arch>.S) . *)
let generic_functions shared units =
let (apply,send,curry) =
List.fold_left
(fun (apply,send,curry) ui ->
List.fold_right IntSet.add ui.ui_apply_fun apply,
List.fold_right IntSet.add ui.ui_send_fun send,
List.fold_right IntSet.add ui.ui_curry_fun curry)
(IntSet.empty,IntSet.empty,IntSet.empty)
units in
let apply = if shared then apply else IntSet.union apply default_apply in
let accu = IntSet.fold (fun n accu -> apply_function n :: accu) apply [] in
let accu = IntSet.fold (fun n accu -> send_function n :: accu) send accu in
IntSet.fold (fun n accu -> curry_function n @ accu) curry accu
(* Generate the entry point *)
let entry_point namelist =
let incr_global_inited =
Cop(Cstore Word,
[Cconst_symbol "caml_globals_inited";
Cop(Caddi, [Cop(Cload Word, [Cconst_symbol "caml_globals_inited"]);
Cconst_int 1])]) in
let body =
List.fold_right
(fun name next ->
let entry_sym = Compilenv.make_symbol ~unitname:name (Some "entry") in
Csequence(Cop(Capply(typ_void, Debuginfo.none),
[Cconst_symbol entry_sym]),
Csequence(incr_global_inited, next)))
namelist (Cconst_int 1) in
Cfunction {fun_name = "caml_program";
fun_args = [];
fun_body = body;
fun_fast = false}
(* Generate the table of globals *)
let cint_zero = Cint 0n
let global_table namelist =
let mksym name =
Csymbol_address (Compilenv.make_symbol ~unitname:name None)
in
Cdata(Cglobal_symbol "caml_globals" ::
Cdefine_symbol "caml_globals" ::
List.map mksym namelist @
[cint_zero])
let reference_symbols namelist =
let mksym name = Csymbol_address name in
Cdata(List.map mksym namelist)
let global_data name v =
Cdata(Cglobal_symbol name ::
emit_constant name
(Const_base (Const_string (Marshal.to_string v []))) [])
let globals_map v = global_data "caml_globals_map" v
(* Generate the master table of frame descriptors *)
let frame_table namelist =
let mksym name =
Csymbol_address (Compilenv.make_symbol ~unitname:name (Some "frametable"))
in
Cdata(Cglobal_symbol "caml_frametable" ::
Cdefine_symbol "caml_frametable" ::
List.map mksym namelist
@ [cint_zero])
(* Generate the table of module data and code segments *)
let segment_table namelist symbol begname endname =
let addsyms name lst =
Csymbol_address (Compilenv.make_symbol ~unitname:name (Some begname)) ::
Csymbol_address (Compilenv.make_symbol ~unitname:name (Some endname)) ::
lst
in
Cdata(Cglobal_symbol symbol ::
Cdefine_symbol symbol ::
List.fold_right addsyms namelist [cint_zero])
let data_segment_table namelist =
segment_table namelist "caml_data_segments" "data_begin" "data_end"
let code_segment_table namelist =
segment_table namelist "caml_code_segments" "code_begin" "code_end"
Initialize a predefined exception
let predef_exception name =
let bucketname = "caml_bucket_" ^ name in
let symname = "caml_exn_" ^ name in
Cdata(Cglobal_symbol symname ::
emit_constant symname (Const_block(0,[Const_base(Const_string name)]))
[ Cglobal_symbol bucketname;
Cint(block_header 0 1);
Cdefine_symbol bucketname;
Csymbol_address symname ])
(* Header for a plugin *)
let mapflat f l = List.flatten (List.map f l)
let plugin_header units =
let mk (ui,crc) =
{ dynu_name = ui.ui_name;
dynu_crc = crc;
dynu_imports_cmi = ui.ui_imports_cmi;
dynu_imports_cmx = ui.ui_imports_cmx;
dynu_defines = ui.ui_defines
} in
global_data "caml_plugin_header"
{ dynu_magic = Config.cmxs_magic_number; dynu_units = List.map mk units }
| null | https://raw.githubusercontent.com/yzhs/ocamlllvm/45cbf449d81f2ef9d234968e49a4305aaa39ace2/src/asmcomp/cmmgen.ml | ocaml | *********************************************************************
Objective Caml
*********************************************************************
Translation from closed lambda to C--
Local binding of complex expressions
Block headers. Meaning of the tag field: see stdlib/obj.ml
Integers
Bool
Float
Unit
Access to block fields
If byte loads are slow
If byte loads are efficient
Array indexing
String length
Message sending
Allocation
To compile "let rec" over values
Record application and currying functions
Comparisons
Translate structured constants
Translate constant closures
Boxed integers
Big arrays
Simplification of some primitives into C calls
ignored
Build switchers both for constants and blocks
Then for blocks
Auxiliary functions for optimizing "let" of boxed numbers (floats and
boxed integers
Translate an expression
Primitives
Control structures
As in the bytecode interpreter, only matching against constants
can be checked
Exceptions
Floating-point operations
String operations
Array operations
Test integer/block
Boxed integers
Float operations
String operations
Array operations
Boxed integers
String operations
Array operations
Translate a function definition
Translate all function definitions
Emit structured constants
Emit constant closures
Emit all structured constants
Translate a compilation unit
Generate the entry point
Generate the table of globals
Generate the master table of frame descriptors
Generate the table of module data and code segments
Header for a plugin | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ I d : cmmgen.ml 10794 2010 - 11 - 11 17:08:07Z xleroy $
open Misc
open Arch
open Asttypes
open Primitive
open Types
open Lambda
open Clambda
open Cmm
open Cmx_format
let bind name arg fn =
match arg with
Cvar _ | Cconst_int _ | Cconst_natint _ | Cconst_symbol _
| Cconst_pointer _ | Cconst_natpointer _ -> fn arg
| _ -> let id = Ident.create name in Clet(id, arg, fn (Cvar id))
let bind_nonvar name arg fn =
match arg with
Cconst_int _ | Cconst_natint _ | Cconst_symbol _
| Cconst_pointer _ | Cconst_natpointer _ -> fn arg
| _ -> let id = Ident.create name in Clet(id, arg, fn (Cvar id))
let float_tag = Cconst_int Obj.double_tag
let floatarray_tag = Cconst_int Obj.double_array_tag
let block_header tag sz =
Nativeint.add (Nativeint.shift_left (Nativeint.of_int sz) 10)
(Nativeint.of_int tag)
let closure_header sz = block_header Obj.closure_tag sz
let infix_header ofs = block_header Obj.infix_tag ofs
let float_header = block_header Obj.double_tag (size_float / size_addr)
let floatarray_header len =
block_header Obj.double_array_tag (len * size_float / size_addr)
let string_header len =
block_header Obj.string_tag ((len + size_addr) / size_addr)
let boxedint32_header = block_header Obj.custom_tag 2
let boxedint64_header = block_header Obj.custom_tag (1 + 8 / size_addr)
let boxedintnat_header = block_header Obj.custom_tag 2
let alloc_block_header tag sz = Cconst_natint(block_header tag sz)
let alloc_float_header = Cconst_natint(float_header)
let alloc_floatarray_header len = Cconst_natint(floatarray_header len)
let alloc_closure_header sz = Cconst_natint(closure_header sz)
let alloc_infix_header ofs = Cconst_natint(infix_header ofs)
let alloc_boxedint32_header = Cconst_natint(boxedint32_header)
let alloc_boxedint64_header = Cconst_natint(boxedint64_header)
let alloc_boxedintnat_header = Cconst_natint(boxedintnat_header)
let max_repr_int = max_int asr 1
let min_repr_int = min_int asr 1
let int_const n =
if n <= max_repr_int && n >= min_repr_int
then Cconst_int((n lsl 1) + 1)
else Cconst_natint
(Nativeint.add (Nativeint.shift_left (Nativeint.of_int n) 1) 1n)
let add_const c n =
if n = 0 then c else Cop(Caddi, [c; Cconst_int n])
let incr_int = function
Cconst_int n when n < max_int -> Cconst_int(n+1)
| Cop(Caddi, [c; Cconst_int n]) when n < max_int -> add_const c (n + 1)
| c -> add_const c 1
let decr_int = function
Cconst_int n when n > min_int -> Cconst_int(n-1)
| Cop(Caddi, [c; Cconst_int n]) when n > min_int -> add_const c (n - 1)
| c -> add_const c (-1)
let add_int c1 c2 =
match (c1, c2) with
(Cop(Caddi, [c1; Cconst_int n1]),
Cop(Caddi, [c2; Cconst_int n2])) when no_overflow_add n1 n2 ->
add_const (Cop(Caddi, [c1; c2])) (n1 + n2)
| (Cop(Caddi, [c1; Cconst_int n1]), c2) ->
add_const (Cop(Caddi, [c1; c2])) n1
| (c1, Cop(Caddi, [c2; Cconst_int n2])) ->
add_const (Cop(Caddi, [c1; c2])) n2
| (Cconst_int _, _) ->
Cop(Caddi, [c2; c1])
| (_, _) ->
Cop(Caddi, [c1; c2])
let sub_int c1 c2 =
match (c1, c2) with
(Cop(Caddi, [c1; Cconst_int n1]),
Cop(Caddi, [c2; Cconst_int n2])) when no_overflow_sub n1 n2 ->
add_const (Cop(Csubi, [c1; c2])) (n1 - n2)
| (Cop(Caddi, [c1; Cconst_int n1]), c2) ->
add_const (Cop(Csubi, [c1; c2])) n1
| (c1, Cop(Caddi, [c2; Cconst_int n2])) when n2 <> min_int ->
add_const (Cop(Csubi, [c1; c2])) (-n2)
| (c1, Cconst_int n) when n <> min_int ->
add_const c1 (-n)
| (c1, c2) ->
Cop(Csubi, [c1; c2])
let mul_int c1 c2 =
match (c1, c2) with
(Cconst_int 0, _) -> c1
| (Cconst_int 1, _) -> c2
| (_, Cconst_int 0) -> c2
| (_, Cconst_int 1) -> c1
| (_, _) -> Cop(Cmuli, [c1; c2])
let tag_int = function
Cconst_int n -> int_const n
| c -> Cop(Caddi, [Cop(Clsl, [c; Cconst_int 1]); Cconst_int 1])
let force_tag_int = function
Cconst_int n -> int_const n
| c -> Cop(Cor, [Cop(Clsl, [c; Cconst_int 1]); Cconst_int 1])
let untag_int = function
Cconst_int n -> Cconst_int(n asr 1)
| Cop(Caddi, [Cop(Clsl, [c; Cconst_int 1]); Cconst_int 1]) -> c
| Cop(Cor, [Cop(Casr, [c; Cconst_int n]); Cconst_int 1])
when n > 0 && n < size_int * 8 ->
Cop(Casr, [c; Cconst_int (n+1)])
| Cop(Cor, [Cop(Clsr, [c; Cconst_int n]); Cconst_int 1])
when n > 0 && n < size_int * 8 ->
Cop(Clsr, [c; Cconst_int (n+1)])
| Cop(Cor, [c; Cconst_int 1]) -> Cop(Casr, [c; Cconst_int 1])
| c -> Cop(Casr, [c; Cconst_int 1])
let lsl_int c1 c2 =
match (c1, c2) with
(Cop(Clsl, [c; Cconst_int n1]), Cconst_int n2)
when n1 > 0 && n2 > 0 && n1 + n2 < size_int * 8 ->
Cop(Clsl, [c; Cconst_int (n1 + n2)])
| (_, _) ->
Cop(Clsl, [c1; c2])
let ignore_low_bit_int = function
Cop(Caddi, [(Cop(Clsl, [_; Cconst_int 1]) as c); Cconst_int 1]) -> c
| Cop(Cor, [c; Cconst_int 1]) -> c
| c -> c
let is_nonzero_constant = function
Cconst_int n -> n <> 0
| Cconst_natint n -> n <> 0n
| _ -> false
let safe_divmod op c1 c2 dbg =
if !Clflags.fast || is_nonzero_constant c2 then
Cop(op, [c1; c2])
else
bind "divisor" c2 (fun c2 ->
Cifthenelse(c2,
Cop(op, [c1; c2]),
Cop(Craise dbg,
[Cconst_symbol "caml_bucket_Division_by_zero"])))
let test_bool = function
Cop(Caddi, [Cop(Clsl, [c; Cconst_int 1]); Cconst_int 1]) -> c
| Cop(Clsl, [c; Cconst_int 1]) -> c
| c -> Cop(Ccmpi Cne, [c; Cconst_int 1])
let box_float c = Cop(Calloc, [alloc_float_header; c])
let rec unbox_float = function
Cop(Calloc, [header; c]) -> c
| Clet(id, exp, body) -> Clet(id, exp, unbox_float body)
| Cifthenelse(cond, e1, e2) ->
Cifthenelse(cond, unbox_float e1, unbox_float e2)
| Csequence(e1, e2) -> Csequence(e1, unbox_float e2)
| Cswitch(e, tbl, el) -> Cswitch(e, tbl, Array.map unbox_float el)
| Ccatch(n, ids, e1, e2) -> Ccatch(n, ids, unbox_float e1, unbox_float e2)
| Ctrywith(e1, id, e2) -> Ctrywith(unbox_float e1, id, unbox_float e2)
| c -> Cop(Cload Double_u, [c])
Complex
let box_complex c_re c_im =
Cop(Calloc, [alloc_floatarray_header 2; c_re; c_im])
let complex_re c = Cop(Cload Double_u, [c])
let complex_im c = Cop(Cload Double_u,
[Cop(Cadda, [c; Cconst_int size_float])])
let return_unit c = Csequence(c, Cconst_pointer 1)
let rec remove_unit = function
Cconst_pointer 1 -> Ctuple []
| Csequence(c, Cconst_pointer 1) -> c
| Csequence(c1, c2) ->
Csequence(c1, remove_unit c2)
| Cifthenelse(cond, ifso, ifnot) ->
Cifthenelse(cond, remove_unit ifso, remove_unit ifnot)
| Cswitch(sel, index, cases) ->
Cswitch(sel, index, Array.map remove_unit cases)
| Ccatch(io, ids, body, handler) ->
Ccatch(io, ids, remove_unit body, remove_unit handler)
| Ctrywith(body, exn, handler) ->
Ctrywith(remove_unit body, exn, remove_unit handler)
| Clet(id, c1, c2) ->
Clet(id, c1, remove_unit c2)
| Cop(Capply (mty, dbg), args) ->
Cop(Capply (typ_void, dbg), args)
| Cop(Cextcall(proc, mty, alloc, dbg), args) ->
Cop(Cextcall(proc, typ_void, alloc, dbg), args)
| Cexit (_,_) as c -> c
| Ctuple [] as c -> c
| c -> Csequence(c, Ctuple [])
let field_address ptr n =
if n = 0
then ptr
else Cop(Cadda, [ptr; Cconst_int(n * size_addr)])
let get_field ptr n =
Cop(Cload Word, [field_address ptr n])
let set_field ptr n newval =
Cop(Cstore Word, [field_address ptr n; newval])
let header ptr =
Cop(Cload Word, [Cop(Cadda, [ptr; Cconst_int(-size_int)])])
let tag_offset =
if big_endian then -1 else -size_int
let get_tag ptr =
Cop(Cand, [header ptr; Cconst_int 255])
Cop(Cload Byte_unsigned,
[Cop(Cadda, [ptr; Cconst_int(tag_offset)])])
let get_size ptr =
Cop(Clsr, [header ptr; Cconst_int 10])
let log2_size_addr = Misc.log2 size_addr
let log2_size_float = Misc.log2 size_float
let wordsize_shift = 9
let numfloat_shift = 9 + log2_size_float - log2_size_addr
let is_addr_array_hdr hdr =
Cop(Ccmpi Cne, [Cop(Cand, [hdr; Cconst_int 255]); floatarray_tag])
let is_addr_array_ptr ptr =
Cop(Ccmpi Cne, [get_tag ptr; floatarray_tag])
let addr_array_length hdr = Cop(Clsr, [hdr; Cconst_int wordsize_shift])
let float_array_length hdr = Cop(Clsr, [hdr; Cconst_int numfloat_shift])
let lsl_const c n =
Cop(Clsl, [c; Cconst_int n])
let array_indexing log2size ptr ofs =
match ofs with
Cconst_int n ->
let i = n asr 1 in
if i = 0 then ptr else Cop(Cadda, [ptr; Cconst_int(i lsl log2size)])
| Cop(Caddi, [Cop(Clsl, [c; Cconst_int 1]); Cconst_int 1]) ->
Cop(Cadda, [ptr; lsl_const c log2size])
| Cop(Caddi, [c; Cconst_int n]) ->
Cop(Cadda, [Cop(Cadda, [ptr; lsl_const c (log2size - 1)]);
Cconst_int((n-1) lsl (log2size - 1))])
| _ ->
Cop(Cadda, [Cop(Cadda, [ptr; lsl_const ofs (log2size - 1)]);
Cconst_int((-1) lsl (log2size - 1))])
let addr_array_ref arr ofs =
Cop(Cload Word, [array_indexing log2_size_addr arr ofs])
let unboxed_float_array_ref arr ofs =
Cop(Cload Double_u, [array_indexing log2_size_float arr ofs])
let float_array_ref arr ofs =
box_float(unboxed_float_array_ref arr ofs)
let addr_array_set arr ofs newval =
Cop(Cextcall("caml_modify", typ_void, false, Debuginfo.none),
[array_indexing log2_size_addr arr ofs; newval])
let int_array_set arr ofs newval =
Cop(Cstore Word, [array_indexing log2_size_addr arr ofs; newval])
let float_array_set arr ofs newval =
Cop(Cstore Double_u, [array_indexing log2_size_float arr ofs; newval])
let string_length exp =
bind "str" exp (fun str ->
let tmp_var = Ident.create "tmp" in
Clet(tmp_var,
Cop(Csubi,
[Cop(Clsl,
[Cop(Clsr, [header str; Cconst_int 10]);
Cconst_int log2_size_addr]);
Cconst_int 1]),
Cop(Csubi,
[Cvar tmp_var;
Cop(Cload Byte_unsigned,
[Cop(Cadda, [str; Cvar tmp_var])])])))
let lookup_tag obj tag =
bind "tag" tag (fun tag ->
Cop(Cextcall("caml_get_public_method", typ_addr, false, Debuginfo.none),
[obj; tag]))
let lookup_label obj lab =
bind "lab" lab (fun lab ->
let table = Cop (Cload Word, [obj]) in
addr_array_ref table lab)
let call_cached_method obj tag cache pos args dbg =
let arity = List.length args in
let cache = array_indexing log2_size_addr cache pos in
Compilenv.need_send_fun arity;
Cop(Capply (typ_addr, dbg),
Cconst_symbol("caml_send" ^ string_of_int arity) ::
obj :: tag :: cache :: args)
let make_alloc_generic set_fn tag wordsize args =
if wordsize <= Config.max_young_wosize then
Cop(Calloc, Cconst_natint(block_header tag wordsize) :: args)
else begin
let id = Ident.create "alloc" in
let rec fill_fields idx = function
[] -> Cvar id
| e1::el -> Csequence(set_fn (Cvar id) (Cconst_int idx) e1,
fill_fields (idx + 2) el) in
Clet(id,
Cop(Cextcall("caml_alloc", typ_addr, true, Debuginfo.none),
[Cconst_int wordsize; Cconst_int tag]),
fill_fields 1 args)
end
let make_alloc tag args =
make_alloc_generic addr_array_set tag (List.length args) args
let make_float_alloc tag args =
make_alloc_generic float_array_set tag
(List.length args * size_float / size_addr) args
let fundecls_size fundecls =
let sz = ref (-1) in
List.iter
(fun (label, arity, params, body) ->
sz := !sz + 1 + (if arity = 1 then 2 else 3))
fundecls;
!sz
type rhs_kind =
| RHS_block of int
| RHS_nonrec
;;
let rec expr_size = function
| Uclosure(fundecls, clos_vars) ->
RHS_block (fundecls_size fundecls + List.length clos_vars)
| Ulet(id, exp, body) ->
expr_size body
| Uletrec(bindings, body) ->
expr_size body
| Uprim(Pmakeblock(tag, mut), args, _) ->
RHS_block (List.length args)
| Uprim(Pmakearray(Paddrarray | Pintarray), args, _) ->
RHS_block (List.length args)
| Usequence(exp, exp') ->
expr_size exp'
| _ -> RHS_nonrec
let apply_function n =
Compilenv.need_apply_fun n; "caml_apply" ^ string_of_int n
let curry_function n =
Compilenv.need_curry_fun n;
if n >= 0
then "caml_curry" ^ string_of_int n
else "caml_tuplify" ^ string_of_int (-n)
let transl_comparison = function
Lambda.Ceq -> Ceq
| Lambda.Cneq -> Cne
| Lambda.Cge -> Cge
| Lambda.Cgt -> Cgt
| Lambda.Cle -> Cle
| Lambda.Clt -> Clt
let const_label = ref 0
let new_const_label () =
incr const_label;
!const_label
let new_const_symbol () =
incr const_label;
Compilenv.make_symbol (Some (string_of_int !const_label))
let structured_constants = ref ([] : (string * structured_constant) list)
let transl_constant = function
Const_base(Const_int n) ->
int_const n
| Const_base(Const_char c) ->
Cconst_int(((Char.code c) lsl 1) + 1)
| Const_pointer n ->
if n <= max_repr_int && n >= min_repr_int
then Cconst_pointer((n lsl 1) + 1)
else Cconst_natpointer
(Nativeint.add (Nativeint.shift_left (Nativeint.of_int n) 1) 1n)
| cst ->
let lbl = new_const_symbol() in
structured_constants := (lbl, cst) :: !structured_constants;
Cconst_symbol lbl
let constant_closures =
ref ([] : (string * (string * int * Ident.t list * ulambda) list) list)
let box_int_constant bi n =
match bi with
Pnativeint -> Const_base(Const_nativeint n)
| Pint32 -> Const_base(Const_int32 (Nativeint.to_int32 n))
| Pint64 -> Const_base(Const_int64 (Int64.of_nativeint n))
let operations_boxed_int bi =
match bi with
Pnativeint -> "caml_nativeint_ops"
| Pint32 -> "caml_int32_ops"
| Pint64 -> "caml_int64_ops"
let alloc_header_boxed_int bi =
match bi with
Pnativeint -> alloc_boxedintnat_header
| Pint32 -> alloc_boxedint32_header
| Pint64 -> alloc_boxedint64_header
let box_int bi arg =
match arg with
Cconst_int n ->
transl_constant (box_int_constant bi (Nativeint.of_int n))
| Cconst_natint n ->
transl_constant (box_int_constant bi n)
| _ ->
let arg' =
if bi = Pint32 && size_int = 8 && big_endian
then Cop(Clsl, [arg; Cconst_int 32])
else arg in
Cop(Calloc, [alloc_header_boxed_int bi;
Cconst_symbol(operations_boxed_int bi);
arg'])
let rec unbox_int bi arg =
match arg with
Cop(Calloc, [hdr; ops; Cop(Clsl, [contents; Cconst_int 32])])
when bi = Pint32 && size_int = 8 && big_endian ->
Force sign - extension of low 32 bits
Cop(Casr, [Cop(Clsl, [contents; Cconst_int 32]); Cconst_int 32])
| Cop(Calloc, [hdr; ops; contents])
when bi = Pint32 && size_int = 8 && not big_endian ->
Force sign - extension of low 32 bits
Cop(Casr, [Cop(Clsl, [contents; Cconst_int 32]); Cconst_int 32])
| Cop(Calloc, [hdr; ops; contents]) ->
contents
| Clet(id, exp, body) -> Clet(id, exp, unbox_int bi body)
| Cifthenelse(cond, e1, e2) ->
Cifthenelse(cond, unbox_int bi e1, unbox_int bi e2)
| Csequence(e1, e2) -> Csequence(e1, unbox_int bi e2)
| Cswitch(e, tbl, el) -> Cswitch(e, tbl, Array.map (unbox_int bi) el)
| Ccatch(n, ids, e1, e2) -> Ccatch(n, ids, unbox_int bi e1, unbox_int bi e2)
| Ctrywith(e1, id, e2) -> Ctrywith(unbox_int bi e1, id, unbox_int bi e2)
| _ ->
Cop(Cload(if bi = Pint32 then Thirtytwo_signed else Word),
[Cop(Cadda, [arg; Cconst_int size_addr])])
let make_unsigned_int bi arg =
if bi = Pint32 && size_int = 8
then Cop(Cand, [arg; Cconst_natint 0xFFFFFFFFn])
else arg
let bigarray_elt_size = function
Pbigarray_unknown -> assert false
| Pbigarray_float32 -> 4
| Pbigarray_float64 -> 8
| Pbigarray_sint8 -> 1
| Pbigarray_uint8 -> 1
| Pbigarray_sint16 -> 2
| Pbigarray_uint16 -> 2
| Pbigarray_int32 -> 4
| Pbigarray_int64 -> 8
| Pbigarray_caml_int -> size_int
| Pbigarray_native_int -> size_int
| Pbigarray_complex32 -> 8
| Pbigarray_complex64 -> 16
let bigarray_indexing unsafe elt_kind layout b args dbg =
let check_bound a1 a2 k =
if unsafe then k else Csequence(Cop(Ccheckbound dbg, [a1;a2]), k) in
let rec ba_indexing dim_ofs delta_ofs = function
[] -> assert false
| [arg] ->
bind "idx" (untag_int arg)
(fun idx ->
check_bound (Cop(Cload Word,[field_address b dim_ofs])) idx idx)
| arg1 :: argl ->
let rem = ba_indexing (dim_ofs + delta_ofs) delta_ofs argl in
bind "idx" (untag_int arg1)
(fun idx ->
bind "bound" (Cop(Cload Word, [field_address b dim_ofs]))
(fun bound ->
check_bound bound idx (add_int (mul_int rem bound) idx))) in
let offset =
match layout with
Pbigarray_unknown_layout ->
assert false
| Pbigarray_c_layout ->
ba_indexing (4 + List.length args) (-1) (List.rev args)
| Pbigarray_fortran_layout ->
ba_indexing 5 1 (List.map (fun idx -> sub_int idx (Cconst_int 2)) args)
and elt_size =
bigarray_elt_size elt_kind in
let byte_offset =
if elt_size = 1
then offset
else Cop(Clsl, [offset; Cconst_int(log2 elt_size)]) in
Cop(Cadda, [Cop(Cload Word, [field_address b 1]); byte_offset])
let bigarray_word_kind = function
Pbigarray_unknown -> assert false
| Pbigarray_float32 -> Single
| Pbigarray_float64 -> Double
| Pbigarray_sint8 -> Byte_signed
| Pbigarray_uint8 -> Byte_unsigned
| Pbigarray_sint16 -> Sixteen_signed
| Pbigarray_uint16 -> Sixteen_unsigned
| Pbigarray_int32 -> Thirtytwo_signed
| Pbigarray_int64 -> Word
| Pbigarray_caml_int -> Word
| Pbigarray_native_int -> Word
| Pbigarray_complex32 -> Single
| Pbigarray_complex64 -> Double
let bigarray_get unsafe elt_kind layout b args dbg =
bind "ba" b (fun b ->
match elt_kind with
Pbigarray_complex32 | Pbigarray_complex64 ->
let kind = bigarray_word_kind elt_kind in
let sz = bigarray_elt_size elt_kind / 2 in
bind "addr" (bigarray_indexing unsafe elt_kind layout b args dbg) (fun addr ->
box_complex
(Cop(Cload kind, [addr]))
(Cop(Cload kind, [Cop(Cadda, [addr; Cconst_int sz])])))
| _ ->
Cop(Cload (bigarray_word_kind elt_kind),
[bigarray_indexing unsafe elt_kind layout b args dbg]))
let bigarray_set unsafe elt_kind layout b args newval dbg =
bind "ba" b (fun b ->
match elt_kind with
Pbigarray_complex32 | Pbigarray_complex64 ->
let kind = bigarray_word_kind elt_kind in
let sz = bigarray_elt_size elt_kind / 2 in
bind "newval" newval (fun newv ->
bind "addr" (bigarray_indexing unsafe elt_kind layout b args dbg) (fun addr ->
Csequence(
Cop(Cstore kind, [addr; complex_re newv]),
Cop(Cstore kind,
[Cop(Cadda, [addr; Cconst_int sz]); complex_im newv]))))
| _ ->
Cop(Cstore (bigarray_word_kind elt_kind),
[bigarray_indexing unsafe elt_kind layout b args dbg; newval]))
let default_prim name =
prim_alloc = true; prim_native_name = ""; prim_native_float = false }
let simplif_primitive_32bits = function
Pbintofint Pint64 -> Pccall (default_prim "caml_int64_of_int")
| Pintofbint Pint64 -> Pccall (default_prim "caml_int64_to_int")
| Pcvtbint(Pint32, Pint64) -> Pccall (default_prim "caml_int64_of_int32")
| Pcvtbint(Pint64, Pint32) -> Pccall (default_prim "caml_int64_to_int32")
| Pcvtbint(Pnativeint, Pint64) ->
Pccall (default_prim "caml_int64_of_nativeint")
| Pcvtbint(Pint64, Pnativeint) ->
Pccall (default_prim "caml_int64_to_nativeint")
| Pnegbint Pint64 -> Pccall (default_prim "caml_int64_neg")
| Paddbint Pint64 -> Pccall (default_prim "caml_int64_add")
| Psubbint Pint64 -> Pccall (default_prim "caml_int64_sub")
| Pmulbint Pint64 -> Pccall (default_prim "caml_int64_mul")
| Pdivbint Pint64 -> Pccall (default_prim "caml_int64_div")
| Pmodbint Pint64 -> Pccall (default_prim "caml_int64_mod")
| Pandbint Pint64 -> Pccall (default_prim "caml_int64_and")
| Porbint Pint64 -> Pccall (default_prim "caml_int64_or")
| Pxorbint Pint64 -> Pccall (default_prim "caml_int64_xor")
| Plslbint Pint64 -> Pccall (default_prim "caml_int64_shift_left")
| Plsrbint Pint64 -> Pccall (default_prim "caml_int64_shift_right_unsigned")
| Pasrbint Pint64 -> Pccall (default_prim "caml_int64_shift_right")
| Pbintcomp(Pint64, Lambda.Ceq) -> Pccall (default_prim "caml_equal")
| Pbintcomp(Pint64, Lambda.Cneq) -> Pccall (default_prim "caml_notequal")
| Pbintcomp(Pint64, Lambda.Clt) -> Pccall (default_prim "caml_lessthan")
| Pbintcomp(Pint64, Lambda.Cgt) -> Pccall (default_prim "caml_greaterthan")
| Pbintcomp(Pint64, Lambda.Cle) -> Pccall (default_prim "caml_lessequal")
| Pbintcomp(Pint64, Lambda.Cge) -> Pccall (default_prim "caml_greaterequal")
| Pbigarrayref(unsafe, n, Pbigarray_int64, layout) ->
Pccall (default_prim ("caml_ba_get_" ^ string_of_int n))
| Pbigarrayset(unsafe, n, Pbigarray_int64, layout) ->
Pccall (default_prim ("caml_ba_set_" ^ string_of_int n))
| p -> p
let simplif_primitive p =
match p with
| Pduprecord _ ->
Pccall (default_prim "caml_obj_dup")
| Pbigarrayref(unsafe, n, Pbigarray_unknown, layout) ->
Pccall (default_prim ("caml_ba_get_" ^ string_of_int n))
| Pbigarrayset(unsafe, n, Pbigarray_unknown, layout) ->
Pccall (default_prim ("caml_ba_set_" ^ string_of_int n))
| Pbigarrayref(unsafe, n, kind, Pbigarray_unknown_layout) ->
Pccall (default_prim ("caml_ba_get_" ^ string_of_int n))
| Pbigarrayset(unsafe, n, kind, Pbigarray_unknown_layout) ->
Pccall (default_prim ("caml_ba_set_" ^ string_of_int n))
| p ->
if size_int = 8 then p else simplif_primitive_32bits p
constants first
let transl_isout h arg = tag_int (Cop(Ccmpa Clt, [h ; arg]))
exception Found of int
let make_switch_gen arg cases acts =
let lcases = Array.length cases in
let new_cases = Array.create lcases 0 in
let store = Switch.mk_store (=) in
for i = 0 to Array.length cases-1 do
let act = cases.(i) in
let new_act = store.Switch.act_store act in
new_cases.(i) <- new_act
done ;
Cswitch
(arg, new_cases,
Array.map
(fun n -> acts.(n))
(store.Switch.act_get ()))
module SArgBlocks =
struct
type primitive = operation
let eqint = Ccmpi Ceq
let neint = Ccmpi Cne
let leint = Ccmpi Cle
let ltint = Ccmpi Clt
let geint = Ccmpi Cge
let gtint = Ccmpi Cgt
type act = expression
let default = Cexit (0,[])
let make_prim p args = Cop (p,args)
let make_offset arg n = add_const arg n
let make_isout h arg = Cop (Ccmpa Clt, [h ; arg])
let make_isin h arg = Cop (Ccmpa Cge, [h ; arg])
let make_if cond ifso ifnot = Cifthenelse (cond, ifso, ifnot)
let make_switch arg cases actions =
make_switch_gen arg cases actions
let bind arg body = bind "switcher" arg body
end
module SwitcherBlocks = Switch.Make(SArgBlocks)
type unboxed_number_kind =
No_unboxing
| Boxed_float
| Boxed_integer of boxed_integer
let is_unboxed_number = function
Uconst(Const_base(Const_float f)) ->
Boxed_float
| Uprim(p, _, _) ->
begin match simplif_primitive p with
Pccall p -> if p.prim_native_float then Boxed_float else No_unboxing
| Pfloatfield _ -> Boxed_float
| Pfloatofint -> Boxed_float
| Pnegfloat -> Boxed_float
| Pabsfloat -> Boxed_float
| Paddfloat -> Boxed_float
| Psubfloat -> Boxed_float
| Pmulfloat -> Boxed_float
| Pdivfloat -> Boxed_float
| Parrayrefu Pfloatarray -> Boxed_float
| Parrayrefs Pfloatarray -> Boxed_float
| Pbintofint bi -> Boxed_integer bi
| Pcvtbint(src, dst) -> Boxed_integer dst
| Pnegbint bi -> Boxed_integer bi
| Paddbint bi -> Boxed_integer bi
| Psubbint bi -> Boxed_integer bi
| Pmulbint bi -> Boxed_integer bi
| Pdivbint bi -> Boxed_integer bi
| Pmodbint bi -> Boxed_integer bi
| Pandbint bi -> Boxed_integer bi
| Porbint bi -> Boxed_integer bi
| Pxorbint bi -> Boxed_integer bi
| Plslbint bi -> Boxed_integer bi
| Plsrbint bi -> Boxed_integer bi
| Pasrbint bi -> Boxed_integer bi
| Pbigarrayref(_, _, (Pbigarray_float32 | Pbigarray_float64), _) ->
Boxed_float
| Pbigarrayref(_, _, Pbigarray_int32, _) -> Boxed_integer Pint32
| Pbigarrayref(_, _, Pbigarray_int64, _) -> Boxed_integer Pint64
| Pbigarrayref(_, _, Pbigarray_native_int, _) -> Boxed_integer Pnativeint
| _ -> No_unboxing
end
| _ -> No_unboxing
let subst_boxed_number unbox_fn boxed_id unboxed_id exp =
let need_boxed = ref false in
let assigned = ref false in
let rec subst = function
Cvar id as e ->
if Ident.same id boxed_id then need_boxed := true; e
| Clet(id, arg, body) -> Clet(id, subst arg, subst body)
| Cassign(id, arg) ->
if Ident.same id boxed_id then begin
assigned := true;
Cassign(unboxed_id, subst(unbox_fn arg))
end else
Cassign(id, subst arg)
| Ctuple argv -> Ctuple(List.map subst argv)
| Cop(Cload _, [Cvar id]) as e ->
if Ident.same id boxed_id then Cvar unboxed_id else e
| Cop(Cload _, [Cop(Cadda, [Cvar id; _])]) as e ->
if Ident.same id boxed_id then Cvar unboxed_id else e
| Cop(op, argv) -> Cop(op, List.map subst argv)
| Csequence(e1, e2) -> Csequence(subst e1, subst e2)
| Cifthenelse(e1, e2, e3) -> Cifthenelse(subst e1, subst e2, subst e3)
| Cswitch(arg, index, cases) ->
Cswitch(subst arg, index, Array.map subst cases)
| Cloop e -> Cloop(subst e)
| Ccatch(nfail, ids, e1, e2) -> Ccatch(nfail, ids, subst e1, subst e2)
| Cexit (nfail, el) -> Cexit (nfail, List.map subst el)
| Ctrywith(e1, id, e2) -> Ctrywith(subst e1, id, subst e2)
| e -> e in
let res = subst exp in
(res, !need_boxed, !assigned)
let functions = (Queue.create() : (string * Ident.t list * ulambda) Queue.t)
let rec transl = function
Uvar id ->
Cvar id
| Uconst sc ->
transl_constant sc
| Uclosure(fundecls, []) ->
let lbl = new_const_symbol() in
constant_closures := (lbl, fundecls) :: !constant_closures;
List.iter
(fun (label, arity, params, body) ->
Queue.add (label, params, body) functions)
fundecls;
Cconst_symbol lbl
| Uclosure(fundecls, clos_vars) ->
let block_size =
fundecls_size fundecls + List.length clos_vars in
let rec transl_fundecls pos = function
[] ->
List.map transl clos_vars
| (label, arity, params, body) :: rem ->
Queue.add (label, params, body) functions;
let header =
if pos = 0
then alloc_closure_header block_size
else alloc_infix_header pos in
if arity = 1 then
header ::
Cconst_symbol label ::
int_const 1 ::
transl_fundecls (pos + 3) rem
else
header ::
Cconst_symbol(curry_function arity) ::
int_const arity ::
Cconst_symbol label ::
transl_fundecls (pos + 4) rem in
Cop(Calloc, transl_fundecls 0 fundecls)
| Uoffset(arg, offset) ->
field_address (transl arg) offset
| Udirect_apply(lbl, args, dbg) ->
Cop(Capply(typ_addr, dbg), Cconst_symbol lbl :: List.map transl args)
| Ugeneric_apply(clos, [arg], dbg) ->
bind "fun" (transl clos) (fun clos ->
Cop(Capply(typ_addr, dbg), [get_field clos 0; transl arg; clos]))
| Ugeneric_apply(clos, args, dbg) ->
let arity = List.length args in
let cargs = Cconst_symbol(apply_function arity) ::
List.map transl (args @ [clos]) in
Cop(Capply(typ_addr, dbg), cargs)
| Usend(kind, met, obj, args, dbg) ->
let call_met obj args clos =
if args = [] then
Cop(Capply(typ_addr, dbg), [get_field clos 0;obj;clos])
else
let arity = List.length args + 1 in
let cargs = Cconst_symbol(apply_function arity) :: obj ::
(List.map transl args) @ [clos] in
Cop(Capply(typ_addr, dbg), cargs)
in
bind "obj" (transl obj) (fun obj ->
match kind, args with
Self, _ ->
bind "met" (lookup_label obj (transl met)) (call_met obj args)
| Cached, cache :: pos :: args ->
call_cached_method obj (transl met) (transl cache) (transl pos)
(List.map transl args) dbg
| _ ->
bind "met" (lookup_tag obj (transl met)) (call_met obj args))
| Ulet(id, exp, body) ->
begin match is_unboxed_number exp with
No_unboxing ->
Clet(id, transl exp, transl body)
| Boxed_float ->
transl_unbox_let box_float unbox_float transl_unbox_float
id exp body
| Boxed_integer bi ->
transl_unbox_let (box_int bi) (unbox_int bi) (transl_unbox_int bi)
id exp body
end
| Uletrec(bindings, body) ->
transl_letrec bindings (transl body)
| Uprim(prim, args, dbg) ->
begin match (simplif_primitive prim, args) with
(Pgetglobal id, []) ->
Cconst_symbol (Ident.name id)
| (Pmakeblock(tag, mut), []) ->
transl_constant(Const_block(tag, []))
| (Pmakeblock(tag, mut), args) ->
make_alloc tag (List.map transl args)
| (Pccall prim, args) ->
if prim.prim_native_float then
box_float
(Cop(Cextcall(prim.prim_native_name, typ_float, false, dbg),
List.map transl_unbox_float args))
else
Cop(Cextcall(Primitive.native_name prim, typ_addr, prim.prim_alloc, dbg),
List.map transl args)
| (Pmakearray kind, []) ->
transl_constant(Const_block(0, []))
| (Pmakearray kind, args) ->
begin match kind with
Pgenarray ->
Cop(Cextcall("caml_make_array", typ_addr, true, Debuginfo.none),
[make_alloc 0 (List.map transl args)])
| Paddrarray | Pintarray ->
make_alloc 0 (List.map transl args)
| Pfloatarray ->
make_float_alloc Obj.double_array_tag
(List.map transl_unbox_float args)
end
| (Pbigarrayref(unsafe, num_dims, elt_kind, layout), arg1 :: argl) ->
let elt =
bigarray_get unsafe elt_kind layout
(transl arg1) (List.map transl argl) dbg in
begin match elt_kind with
Pbigarray_float32 | Pbigarray_float64 -> box_float elt
| Pbigarray_complex32 | Pbigarray_complex64 -> elt
| Pbigarray_int32 -> box_int Pint32 elt
| Pbigarray_int64 -> box_int Pint64 elt
| Pbigarray_native_int -> box_int Pnativeint elt
| Pbigarray_caml_int -> force_tag_int elt
| _ -> tag_int elt
end
| (Pbigarrayset(unsafe, num_dims, elt_kind, layout), arg1 :: argl) ->
let (argidx, argnewval) = split_last argl in
return_unit(bigarray_set unsafe elt_kind layout
(transl arg1)
(List.map transl argidx)
(match elt_kind with
Pbigarray_float32 | Pbigarray_float64 ->
transl_unbox_float argnewval
| Pbigarray_complex32 | Pbigarray_complex64 -> transl argnewval
| Pbigarray_int32 -> transl_unbox_int Pint32 argnewval
| Pbigarray_int64 -> transl_unbox_int Pint64 argnewval
| Pbigarray_native_int -> transl_unbox_int Pnativeint argnewval
| _ -> untag_int (transl argnewval))
dbg)
| (p, [arg]) ->
transl_prim_1 p arg dbg
| (p, [arg1; arg2]) ->
transl_prim_2 p arg1 arg2 dbg
| (p, [arg1; arg2; arg3]) ->
transl_prim_3 p arg1 arg2 arg3 dbg
| (_, _) ->
fatal_error "Cmmgen.transl:prim"
end
| Uswitch(arg, s) ->
if Array.length s.us_index_blocks = 0 then
Cswitch
(untag_int (transl arg),
s.us_index_consts,
Array.map transl s.us_actions_consts)
else if Array.length s.us_index_consts = 0 then
transl_switch (get_tag (transl arg))
s.us_index_blocks s.us_actions_blocks
else
bind "switch" (transl arg) (fun arg ->
Cifthenelse(
Cop(Cand, [arg; Cconst_int 1]),
transl_switch
(untag_int arg) s.us_index_consts s.us_actions_consts,
transl_switch
(get_tag arg) s.us_index_blocks s.us_actions_blocks))
| Ustaticfail (nfail, args) ->
Cexit (nfail, List.map transl args)
| Ucatch(nfail, [], body, handler) ->
make_catch nfail (transl body) (transl handler)
| Ucatch(nfail, ids, body, handler) ->
Ccatch(nfail, ids, transl body, transl handler)
| Utrywith(body, exn, handler) ->
Ctrywith(transl body, exn, transl handler)
| Uifthenelse(Uprim(Pnot, [arg], _), ifso, ifnot) ->
transl (Uifthenelse(arg, ifnot, ifso))
| Uifthenelse(cond, ifso, Ustaticfail (nfail, [])) ->
exit_if_false cond (transl ifso) nfail
| Uifthenelse(cond, Ustaticfail (nfail, []), ifnot) ->
exit_if_true cond nfail (transl ifnot)
| Uifthenelse(Uprim(Psequand, _, _) as cond, ifso, ifnot) ->
let raise_num = next_raise_count () in
make_catch
raise_num
(exit_if_false cond (transl ifso) raise_num)
(transl ifnot)
| Uifthenelse(Uprim(Psequor, _, _) as cond, ifso, ifnot) ->
let raise_num = next_raise_count () in
make_catch
raise_num
(exit_if_true cond raise_num (transl ifnot))
(transl ifso)
| Uifthenelse (Uifthenelse (cond, condso, condnot), ifso, ifnot) ->
let num_true = next_raise_count () in
make_catch
num_true
(make_catch2
(fun shared_false ->
Cifthenelse
(test_bool (transl cond),
exit_if_true condso num_true shared_false,
exit_if_true condnot num_true shared_false))
(transl ifnot))
(transl ifso)
| Uifthenelse(cond, ifso, ifnot) ->
Cifthenelse(test_bool(transl cond), transl ifso, transl ifnot)
| Usequence(exp1, exp2) ->
Csequence(remove_unit(transl exp1), transl exp2)
| Uwhile(cond, body) ->
let raise_num = next_raise_count () in
return_unit
(Ccatch
(raise_num, [],
Cloop(exit_if_false cond (remove_unit(transl body)) raise_num),
Ctuple []))
| Ufor(id, low, high, dir, body) ->
let tst = match dir with Upto -> Cgt | Downto -> Clt in
let inc = match dir with Upto -> Caddi | Downto -> Csubi in
let raise_num = next_raise_count () in
let id_prev = Ident.rename id in
return_unit
(Clet
(id, transl low,
bind_nonvar "bound" (transl high) (fun high ->
Ccatch
(raise_num, [],
Cifthenelse
(Cop(Ccmpi tst, [Cvar id; high]), Cexit (raise_num, []),
Cloop
(Csequence
(remove_unit(transl body),
Clet(id_prev, Cvar id,
Csequence
(Cassign(id,
Cop(inc, [Cvar id; Cconst_int 2])),
Cifthenelse
(Cop(Ccmpi Ceq, [Cvar id_prev; high]),
Cexit (raise_num,[]), Ctuple [])))))),
Ctuple []))))
| Uassign(id, exp) ->
return_unit(Cassign(id, transl exp))
and transl_prim_1 p arg dbg =
match p with
Generic operations
Pidentity ->
transl arg
| Pignore ->
return_unit(remove_unit (transl arg))
Heap operations
| Pfield n ->
get_field (transl arg) n
| Pfloatfield n ->
let ptr = transl arg in
box_float(
Cop(Cload Double_u,
[if n = 0 then ptr
else Cop(Cadda, [ptr; Cconst_int(n * size_float)])]))
| Praise ->
Cop(Craise dbg, [transl arg])
Integer operations
| Pnegint ->
Cop(Csubi, [Cconst_int 2; transl arg])
| Poffsetint n ->
if no_overflow_lsl n then
add_const (transl arg) (n lsl 1)
else
transl_prim_2 Paddint arg (Uconst (Const_base(Const_int n))) Debuginfo.none
| Poffsetref n ->
return_unit
(bind "ref" (transl arg) (fun arg ->
Cop(Cstore Word,
[arg; add_const (Cop(Cload Word, [arg])) (n lsl 1)])))
| Pfloatofint ->
box_float(Cop(Cfloatofint, [untag_int(transl arg)]))
| Pintoffloat ->
tag_int(Cop(Cintoffloat, [transl_unbox_float arg]))
| Pnegfloat ->
box_float(Cop(Cnegf, [transl_unbox_float arg]))
| Pabsfloat ->
box_float(Cop(Cabsf, [transl_unbox_float arg]))
| Pstringlength ->
tag_int(string_length (transl arg))
| Parraylength kind ->
begin match kind with
Pgenarray ->
let len =
if wordsize_shift = numfloat_shift then
Cop(Clsr, [header(transl arg); Cconst_int wordsize_shift])
else
bind "header" (header(transl arg)) (fun hdr ->
Cifthenelse(is_addr_array_hdr hdr,
Cop(Clsr, [hdr; Cconst_int wordsize_shift]),
Cop(Clsr, [hdr; Cconst_int numfloat_shift]))) in
Cop(Cor, [len; Cconst_int 1])
| Paddrarray | Pintarray ->
Cop(Cor, [addr_array_length(header(transl arg)); Cconst_int 1])
| Pfloatarray ->
Cop(Cor, [float_array_length(header(transl arg)); Cconst_int 1])
end
Boolean operations
| Pnot ->
1 - > 3 , 3 - > 1
| Pisint ->
tag_int(Cop(Cand, [transl arg; Cconst_int 1]))
| Pbintofint bi ->
box_int bi (untag_int (transl arg))
| Pintofbint bi ->
force_tag_int (transl_unbox_int bi arg)
| Pcvtbint(bi1, bi2) ->
box_int bi2 (transl_unbox_int bi1 arg)
| Pnegbint bi ->
box_int bi (Cop(Csubi, [Cconst_int 0; transl_unbox_int bi arg]))
| _ ->
fatal_error "Cmmgen.transl_prim_1"
and transl_prim_2 p arg1 arg2 dbg =
match p with
Heap operations
Psetfield(n, ptr) ->
if ptr then
return_unit(Cop(Cextcall("caml_modify", typ_void, false, Debuginfo.none),
[field_address (transl arg1) n; transl arg2]))
else
return_unit(set_field (transl arg1) n (transl arg2))
| Psetfloatfield n ->
let ptr = transl arg1 in
return_unit(
Cop(Cstore Double_u,
[if n = 0 then ptr
else Cop(Cadda, [ptr; Cconst_int(n * size_float)]);
transl_unbox_float arg2]))
Boolean operations
| Psequand ->
Cifthenelse(test_bool(transl arg1), transl arg2, Cconst_int 1)
let i d = Ident.create " res1 " in
Clet(id , transl arg1 ,
Cifthenelse(test_bool(Cvar i d ) , transl arg2 , Cvar i d ) )
Clet(id, transl arg1,
Cifthenelse(test_bool(Cvar id), transl arg2, Cvar id)) *)
| Psequor ->
Cifthenelse(test_bool(transl arg1), Cconst_int 3, transl arg2)
Integer operations
| Paddint ->
decr_int(add_int (transl arg1) (transl arg2))
| Psubint ->
incr_int(sub_int (transl arg1) (transl arg2))
| Pmulint ->
incr_int(Cop(Cmuli, [decr_int(transl arg1); untag_int(transl arg2)]))
| Pdivint ->
tag_int(safe_divmod Cdivi (untag_int(transl arg1)) (untag_int(transl arg2)) dbg)
| Pmodint ->
tag_int(safe_divmod Cmodi (untag_int(transl arg1)) (untag_int(transl arg2)) dbg)
| Pandint ->
Cop(Cand, [transl arg1; transl arg2])
| Porint ->
Cop(Cor, [transl arg1; transl arg2])
| Pxorint ->
Cop(Cor, [Cop(Cxor, [ignore_low_bit_int(transl arg1);
ignore_low_bit_int(transl arg2)]);
Cconst_int 1])
| Plslint ->
incr_int(lsl_int (decr_int(transl arg1)) (untag_int(transl arg2)))
| Plsrint ->
Cop(Cor, [Cop(Clsr, [transl arg1; untag_int(transl arg2)]);
Cconst_int 1])
| Pasrint ->
Cop(Cor, [Cop(Casr, [transl arg1; untag_int(transl arg2)]);
Cconst_int 1])
| Pintcomp cmp ->
tag_int(Cop(Ccmpi(transl_comparison cmp), [transl arg1; transl arg2]))
| Pisout ->
transl_isout (transl arg1) (transl arg2)
| Paddfloat ->
box_float(Cop(Caddf,
[transl_unbox_float arg1; transl_unbox_float arg2]))
| Psubfloat ->
box_float(Cop(Csubf,
[transl_unbox_float arg1; transl_unbox_float arg2]))
| Pmulfloat ->
box_float(Cop(Cmulf,
[transl_unbox_float arg1; transl_unbox_float arg2]))
| Pdivfloat ->
box_float(Cop(Cdivf,
[transl_unbox_float arg1; transl_unbox_float arg2]))
| Pfloatcomp cmp ->
tag_int(Cop(Ccmpf(transl_comparison cmp),
[transl_unbox_float arg1; transl_unbox_float arg2]))
| Pstringrefu ->
tag_int(Cop(Cload Byte_unsigned,
[add_int (transl arg1) (untag_int(transl arg2))]))
| Pstringrefs ->
tag_int
(bind "str" (transl arg1) (fun str ->
bind "index" (untag_int (transl arg2)) (fun idx ->
Csequence(
Cop(Ccheckbound dbg, [string_length str; idx]),
Cop(Cload Byte_unsigned, [add_int str idx])))))
| Parrayrefu kind ->
begin match kind with
Pgenarray ->
bind "arr" (transl arg1) (fun arr ->
bind "index" (transl arg2) (fun idx ->
Cifthenelse(is_addr_array_ptr arr,
addr_array_ref arr idx,
float_array_ref arr idx)))
| Paddrarray | Pintarray ->
addr_array_ref (transl arg1) (transl arg2)
| Pfloatarray ->
float_array_ref (transl arg1) (transl arg2)
end
| Parrayrefs kind ->
begin match kind with
Pgenarray ->
bind "index" (transl arg2) (fun idx ->
bind "arr" (transl arg1) (fun arr ->
bind "header" (header arr) (fun hdr ->
Cifthenelse(is_addr_array_hdr hdr,
Csequence(Cop(Ccheckbound dbg, [addr_array_length hdr; idx]),
addr_array_ref arr idx),
Csequence(Cop(Ccheckbound dbg, [float_array_length hdr; idx]),
float_array_ref arr idx)))))
| Paddrarray | Pintarray ->
bind "index" (transl arg2) (fun idx ->
bind "arr" (transl arg1) (fun arr ->
Csequence(Cop(Ccheckbound dbg, [addr_array_length(header arr); idx]),
addr_array_ref arr idx)))
| Pfloatarray ->
box_float(
bind "index" (transl arg2) (fun idx ->
bind "arr" (transl arg1) (fun arr ->
Csequence(Cop(Ccheckbound dbg,
[float_array_length(header arr); idx]),
unboxed_float_array_ref arr idx))))
end
Operations on bitvects
| Pbittest ->
bind "index" (untag_int(transl arg2)) (fun idx ->
tag_int(
Cop(Cand, [Cop(Clsr, [Cop(Cload Byte_unsigned,
[add_int (transl arg1)
(Cop(Clsr, [idx; Cconst_int 3]))]);
Cop(Cand, [idx; Cconst_int 7])]);
Cconst_int 1])))
| Paddbint bi ->
box_int bi (Cop(Caddi,
[transl_unbox_int bi arg1; transl_unbox_int bi arg2]))
| Psubbint bi ->
box_int bi (Cop(Csubi,
[transl_unbox_int bi arg1; transl_unbox_int bi arg2]))
| Pmulbint bi ->
box_int bi (Cop(Cmuli,
[transl_unbox_int bi arg1; transl_unbox_int bi arg2]))
| Pdivbint bi ->
box_int bi (safe_divmod Cdivi
(transl_unbox_int bi arg1) (transl_unbox_int bi arg2)
dbg)
| Pmodbint bi ->
box_int bi (safe_divmod Cmodi
(transl_unbox_int bi arg1) (transl_unbox_int bi arg2)
dbg)
| Pandbint bi ->
box_int bi (Cop(Cand,
[transl_unbox_int bi arg1; transl_unbox_int bi arg2]))
| Porbint bi ->
box_int bi (Cop(Cor,
[transl_unbox_int bi arg1; transl_unbox_int bi arg2]))
| Pxorbint bi ->
box_int bi (Cop(Cxor,
[transl_unbox_int bi arg1; transl_unbox_int bi arg2]))
| Plslbint bi ->
box_int bi (Cop(Clsl,
[transl_unbox_int bi arg1; untag_int(transl arg2)]))
| Plsrbint bi ->
box_int bi (Cop(Clsr,
[make_unsigned_int bi (transl_unbox_int bi arg1);
untag_int(transl arg2)]))
| Pasrbint bi ->
box_int bi (Cop(Casr,
[transl_unbox_int bi arg1; untag_int(transl arg2)]))
| Pbintcomp(bi, cmp) ->
tag_int (Cop(Ccmpi(transl_comparison cmp),
[transl_unbox_int bi arg1; transl_unbox_int bi arg2]))
| _ ->
fatal_error "Cmmgen.transl_prim_2"
and transl_prim_3 p arg1 arg2 arg3 dbg =
match p with
Pstringsetu ->
return_unit(Cop(Cstore Byte_unsigned,
[add_int (transl arg1) (untag_int(transl arg2));
untag_int(transl arg3)]))
| Pstringsets ->
return_unit
(bind "str" (transl arg1) (fun str ->
bind "index" (untag_int (transl arg2)) (fun idx ->
Csequence(
Cop(Ccheckbound dbg, [string_length str; idx]),
Cop(Cstore Byte_unsigned,
[add_int str idx; untag_int(transl arg3)])))))
| Parraysetu kind ->
return_unit(begin match kind with
Pgenarray ->
bind "newval" (transl arg3) (fun newval ->
bind "index" (transl arg2) (fun index ->
bind "arr" (transl arg1) (fun arr ->
Cifthenelse(is_addr_array_ptr arr,
addr_array_set arr index newval,
float_array_set arr index (unbox_float newval)))))
| Paddrarray ->
addr_array_set (transl arg1) (transl arg2) (transl arg3)
| Pintarray ->
int_array_set (transl arg1) (transl arg2) (transl arg3)
| Pfloatarray ->
float_array_set (transl arg1) (transl arg2) (transl_unbox_float arg3)
end)
| Parraysets kind ->
return_unit(begin match kind with
Pgenarray ->
bind "newval" (transl arg3) (fun newval ->
bind "index" (transl arg2) (fun idx ->
bind "arr" (transl arg1) (fun arr ->
bind "header" (header arr) (fun hdr ->
Cifthenelse(is_addr_array_hdr hdr,
Csequence(Cop(Ccheckbound dbg, [addr_array_length hdr; idx]),
addr_array_set arr idx newval),
Csequence(Cop(Ccheckbound dbg, [float_array_length hdr; idx]),
float_array_set arr idx
(unbox_float newval)))))))
| Paddrarray ->
bind "index" (transl arg2) (fun idx ->
bind "arr" (transl arg1) (fun arr ->
Csequence(Cop(Ccheckbound dbg, [addr_array_length(header arr); idx]),
addr_array_set arr idx (transl arg3))))
| Pintarray ->
bind "index" (transl arg2) (fun idx ->
bind "arr" (transl arg1) (fun arr ->
Csequence(Cop(Ccheckbound dbg, [addr_array_length(header arr); idx]),
int_array_set arr idx (transl arg3))))
| Pfloatarray ->
bind "index" (transl arg2) (fun idx ->
bind "arr" (transl arg1) (fun arr ->
Csequence(Cop(Ccheckbound dbg, [float_array_length(header arr);idx]),
float_array_set arr idx (transl_unbox_float arg3))))
end)
| _ ->
fatal_error "Cmmgen.transl_prim_3"
and transl_unbox_float = function
Uconst(Const_base(Const_float f)) -> Cconst_float f
| exp -> unbox_float(transl exp)
and transl_unbox_int bi = function
Uconst(Const_base(Const_int32 n)) ->
Cconst_natint (Nativeint.of_int32 n)
| Uconst(Const_base(Const_nativeint n)) ->
Cconst_natint n
| Uconst(Const_base(Const_int64 n)) ->
assert (size_int = 8); Cconst_natint (Int64.to_nativeint n)
| Uprim(Pbintofint bi', [Uconst(Const_base(Const_int i))], _) when bi = bi' ->
Cconst_int i
| exp -> unbox_int bi (transl exp)
and transl_unbox_let box_fn unbox_fn transl_unbox_fn id exp body =
let unboxed_id = Ident.create (Ident.name id) in
let trbody1 = transl body in
let (trbody2, need_boxed, is_assigned) =
subst_boxed_number unbox_fn id unboxed_id trbody1 in
if need_boxed && is_assigned then
Clet(id, transl exp, trbody1)
else
Clet(unboxed_id, transl_unbox_fn exp,
if need_boxed
then Clet(id, box_fn(Cvar unboxed_id), trbody2)
else trbody2)
and make_catch ncatch body handler = match body with
| Cexit (nexit,[]) when nexit=ncatch -> handler
| _ -> Ccatch (ncatch, [], body, handler)
and make_catch2 mk_body handler = match handler with
| Cexit (_,[])|Ctuple []|Cconst_int _|Cconst_pointer _ ->
mk_body handler
| _ ->
let nfail = next_raise_count () in
make_catch
nfail
(mk_body (Cexit (nfail,[])))
handler
and exit_if_true cond nfail otherwise =
match cond with
| Uconst (Const_pointer 0) -> otherwise
| Uconst (Const_pointer 1) -> Cexit (nfail,[])
| Uprim(Psequor, [arg1; arg2], _) ->
exit_if_true arg1 nfail (exit_if_true arg2 nfail otherwise)
| Uprim(Psequand, _, _) ->
begin match otherwise with
| Cexit (raise_num,[]) ->
exit_if_false cond (Cexit (nfail,[])) raise_num
| _ ->
let raise_num = next_raise_count () in
make_catch
raise_num
(exit_if_false cond (Cexit (nfail,[])) raise_num)
otherwise
end
| Uprim(Pnot, [arg], _) ->
exit_if_false arg otherwise nfail
| Uifthenelse (cond, ifso, ifnot) ->
make_catch2
(fun shared ->
Cifthenelse
(test_bool (transl cond),
exit_if_true ifso nfail shared,
exit_if_true ifnot nfail shared))
otherwise
| _ ->
Cifthenelse(test_bool(transl cond), Cexit (nfail, []), otherwise)
and exit_if_false cond otherwise nfail =
match cond with
| Uconst (Const_pointer 0) -> Cexit (nfail,[])
| Uconst (Const_pointer 1) -> otherwise
| Uprim(Psequand, [arg1; arg2], _) ->
exit_if_false arg1 (exit_if_false arg2 otherwise nfail) nfail
| Uprim(Psequor, _, _) ->
begin match otherwise with
| Cexit (raise_num,[]) ->
exit_if_true cond raise_num (Cexit (nfail,[]))
| _ ->
let raise_num = next_raise_count () in
make_catch
raise_num
(exit_if_true cond raise_num (Cexit (nfail,[])))
otherwise
end
| Uprim(Pnot, [arg], _) ->
exit_if_true arg nfail otherwise
| Uifthenelse (cond, ifso, ifnot) ->
make_catch2
(fun shared ->
Cifthenelse
(test_bool (transl cond),
exit_if_false ifso shared nfail,
exit_if_false ifnot shared nfail))
otherwise
| _ ->
Cifthenelse(test_bool(transl cond), otherwise, Cexit (nfail, []))
and transl_switch arg index cases = match Array.length cases with
| 0 -> fatal_error "Cmmgen.transl_switch"
| 1 -> transl cases.(0)
| _ ->
let n_index = Array.length index in
let actions = Array.map transl cases in
let inters = ref []
and this_high = ref (n_index-1)
and this_low = ref (n_index-1)
and this_act = ref index.(n_index-1) in
for i = n_index-2 downto 0 do
let act = index.(i) in
if act = !this_act then
decr this_low
else begin
inters := (!this_low, !this_high, !this_act) :: !inters ;
this_high := i ;
this_low := i ;
this_act := act
end
done ;
inters := (0, !this_high, !this_act) :: !inters ;
bind "switcher" arg
(fun a ->
SwitcherBlocks.zyva
(0,n_index-1)
(fun i -> Cconst_int i)
a
(Array.of_list !inters) actions)
and transl_letrec bindings cont =
let bsz = List.map (fun (id, exp) -> (id, exp, expr_size exp)) bindings in
let rec init_blocks = function
| [] -> fill_nonrec bsz
| (id, exp, RHS_block sz) :: rem ->
Clet(id, Cop(Cextcall("caml_alloc_dummy", typ_addr, true, Debuginfo.none),
[int_const sz]),
init_blocks rem)
| (id, exp, RHS_nonrec) :: rem ->
Clet (id, Cconst_int 0, init_blocks rem)
and fill_nonrec = function
| [] -> fill_blocks bsz
| (id, exp, RHS_block sz) :: rem -> fill_nonrec rem
| (id, exp, RHS_nonrec) :: rem ->
Clet (id, transl exp, fill_nonrec rem)
and fill_blocks = function
| [] -> cont
| (id, exp, RHS_block _) :: rem ->
Csequence(Cop(Cextcall("caml_update_dummy", typ_void, false, Debuginfo.none),
[Cvar id; transl exp]),
fill_blocks rem)
| (id, exp, RHS_nonrec) :: rem ->
fill_blocks rem
in init_blocks bsz
let transl_function lbl params body =
Cfunction {fun_name = lbl;
fun_args = List.map (fun id -> (id, typ_addr)) params;
fun_body = transl body;
fun_fast = !Clflags.optimize_for_speed}
module StringSet =
Set.Make(struct
type t = string
let compare = compare
end)
let rec transl_all_functions already_translated cont =
try
let (lbl, params, body) = Queue.take functions in
if StringSet.mem lbl already_translated then
transl_all_functions already_translated cont
else begin
transl_all_functions (StringSet.add lbl already_translated)
(transl_function lbl params body :: cont)
end
with Queue.Empty ->
cont
let immstrings = Hashtbl.create 17
let rec emit_constant symb cst cont =
match cst with
Const_base(Const_float s) ->
Cint(float_header) :: Cdefine_symbol symb :: Cdouble s :: cont
| Const_base(Const_string s) | Const_immstring s ->
Cint(string_header (String.length s)) ::
Cdefine_symbol symb ::
emit_string_constant s cont
| Const_base(Const_int32 n) ->
Cint(boxedint32_header) :: Cdefine_symbol symb ::
emit_boxed_int32_constant n cont
| Const_base(Const_int64 n) ->
Cint(boxedint64_header) :: Cdefine_symbol symb ::
emit_boxed_int64_constant n cont
| Const_base(Const_nativeint n) ->
Cint(boxedintnat_header) :: Cdefine_symbol symb ::
emit_boxed_nativeint_constant n cont
| Const_block(tag, fields) ->
let (emit_fields, cont1) = emit_constant_fields fields cont in
Cint(block_header tag (List.length fields)) ::
Cdefine_symbol symb ::
emit_fields @ cont1
| Const_float_array(fields) ->
Cint(floatarray_header (List.length fields)) ::
Cdefine_symbol symb ::
Misc.map_end (fun f -> Cdouble f) fields cont
| _ -> fatal_error "gencmm.emit_constant"
and emit_constant_fields fields cont =
match fields with
[] -> ([], cont)
| f1 :: fl ->
let (data1, cont1) = emit_constant_field f1 cont in
let (datal, contl) = emit_constant_fields fl cont1 in
(data1 :: datal, contl)
and emit_constant_field field cont =
match field with
Const_base(Const_int n) ->
(Cint(Nativeint.add (Nativeint.shift_left (Nativeint.of_int n) 1) 1n),
cont)
| Const_base(Const_char c) ->
(Cint(Nativeint.of_int(((Char.code c) lsl 1) + 1)), cont)
| Const_base(Const_float s) ->
let lbl = new_const_label() in
(Clabel_address lbl,
Cint(float_header) :: Cdefine_label lbl :: Cdouble s :: cont)
| Const_base(Const_string s) ->
let lbl = new_const_label() in
(Clabel_address lbl,
Cint(string_header (String.length s)) :: Cdefine_label lbl ::
emit_string_constant s cont)
| Const_immstring s ->
begin try
(Clabel_address (Hashtbl.find immstrings s), cont)
with Not_found ->
let lbl = new_const_label() in
Hashtbl.add immstrings s lbl;
(Clabel_address lbl,
Cint(string_header (String.length s)) :: Cdefine_label lbl ::
emit_string_constant s cont)
end
| Const_base(Const_int32 n) ->
let lbl = new_const_label() in
(Clabel_address lbl,
Cint(boxedint32_header) :: Cdefine_label lbl ::
emit_boxed_int32_constant n cont)
| Const_base(Const_int64 n) ->
let lbl = new_const_label() in
(Clabel_address lbl,
Cint(boxedint64_header) :: Cdefine_label lbl ::
emit_boxed_int64_constant n cont)
| Const_base(Const_nativeint n) ->
let lbl = new_const_label() in
(Clabel_address lbl,
Cint(boxedintnat_header) :: Cdefine_label lbl ::
emit_boxed_nativeint_constant n cont)
| Const_pointer n ->
(Cint(Nativeint.add (Nativeint.shift_left (Nativeint.of_int n) 1) 1n),
cont)
| Const_block(tag, fields) ->
let lbl = new_const_label() in
let (emit_fields, cont1) = emit_constant_fields fields cont in
(Clabel_address lbl,
Cint(block_header tag (List.length fields)) :: Cdefine_label lbl ::
emit_fields @ cont1)
| Const_float_array(fields) ->
let lbl = new_const_label() in
(Clabel_address lbl,
Cint(floatarray_header (List.length fields)) :: Cdefine_label lbl ::
Misc.map_end (fun f -> Cdouble f) fields cont)
and emit_string_constant s cont =
let n = size_int - 1 - (String.length s) mod size_int in
Cstring s :: Cskip n :: Cint8 n :: cont
and emit_boxed_int32_constant n cont =
let n = Nativeint.of_int32 n in
if size_int = 8 then
Csymbol_address("caml_int32_ops") :: Cint32 n :: Cint32 0n :: cont
else
Csymbol_address("caml_int32_ops") :: Cint n :: cont
and emit_boxed_nativeint_constant n cont =
Csymbol_address("caml_nativeint_ops") :: Cint n :: cont
and emit_boxed_int64_constant n cont =
let lo = Int64.to_nativeint n in
if size_int = 8 then
Csymbol_address("caml_int64_ops") :: Cint lo :: cont
else begin
let hi = Int64.to_nativeint (Int64.shift_right n 32) in
if big_endian then
Csymbol_address("caml_int64_ops") :: Cint hi :: Cint lo :: cont
else
Csymbol_address("caml_int64_ops") :: Cint lo :: Cint hi :: cont
end
let emit_constant_closure symb fundecls cont =
match fundecls with
[] -> assert false
| (label, arity, params, body) :: remainder ->
let rec emit_others pos = function
[] -> cont
| (label, arity, params, body) :: rem ->
if arity = 1 then
Cint(infix_header pos) ::
Csymbol_address label ::
Cint 3n ::
emit_others (pos + 3) rem
else
Cint(infix_header pos) ::
Csymbol_address(curry_function arity) ::
Cint(Nativeint.of_int (arity lsl 1 + 1)) ::
Csymbol_address label ::
emit_others (pos + 4) rem in
Cint(closure_header (fundecls_size fundecls)) ::
Cdefine_symbol symb ::
if arity = 1 then
Csymbol_address label ::
Cint 3n ::
emit_others 3 remainder
else
Csymbol_address(curry_function arity) ::
Cint(Nativeint.of_int (arity lsl 1 + 1)) ::
Csymbol_address label ::
emit_others 4 remainder
let emit_all_constants cont =
let c = ref cont in
List.iter
(fun (lbl, cst) -> c := Cdata(emit_constant lbl cst []) :: !c)
!structured_constants;
structured_constants := [];
PR#3979
List.iter
(fun (symb, fundecls) ->
c := Cdata(emit_constant_closure symb fundecls []) :: !c)
!constant_closures;
constant_closures := [];
!c
let compunit size ulam =
let glob = Compilenv.make_symbol None in
let init_code = transl ulam in
let c1 = [Cfunction {fun_name = Compilenv.make_symbol (Some "entry");
fun_args = [];
fun_body = init_code; fun_fast = false}] in
let c2 = transl_all_functions StringSet.empty c1 in
let c3 = emit_all_constants c2 in
Cdata [Cint(block_header 0 size);
Cglobal_symbol glob;
Cdefine_symbol glob;
Cskip(size * size_addr)] :: c3
CAMLprim value caml_cache_public_method ( value meths , value tag , value * cache )
{
int li = 3 , hi = Field(meths,0 ) , mi ;
while ( li < hi ) { // no need to check the 1st time
mi = ( ( li+hi ) > > 1 ) | 1 ;
if ( tag < Field(meths , mi ) ) hi = mi-2 ;
else li = mi ;
}
* cache = ( li-3)*sizeof(value)+1 ;
return Field ( meths , li-1 ) ;
}
CAMLprim value caml_cache_public_method (value meths, value tag, value *cache)
{
int li = 3, hi = Field(meths,0), mi;
while (li < hi) { // no need to check the 1st time
mi = ((li+hi) >> 1) | 1;
if (tag < Field(meths,mi)) hi = mi-2;
else li = mi;
}
*cache = (li-3)*sizeof(value)+1;
return Field (meths, li-1);
}
*)
let cache_public_method meths tag cache =
let raise_num = next_raise_count () in
let li = Ident.create "li" and hi = Ident.create "hi"
and mi = Ident.create "mi" and tagged = Ident.create "tagged" in
Clet (
li, Cconst_int 3,
Clet (
hi, Cop(Cload Word, [meths]),
Csequence(
Ccatch
(raise_num, [],
Cloop
(Clet(
mi,
Cop(Cor,
[Cop(Clsr, [Cop(Caddi, [Cvar li; Cvar hi]); Cconst_int 1]);
Cconst_int 1]),
Csequence(
Cifthenelse
(Cop (Ccmpi Clt,
[tag;
Cop(Cload Word,
[Cop(Cadda,
[meths; lsl_const (Cvar mi) log2_size_addr])])]),
Cassign(hi, Cop(Csubi, [Cvar mi; Cconst_int 2])),
Cassign(li, Cvar mi)),
Cifthenelse
(Cop(Ccmpi Cge, [Cvar li; Cvar hi]), Cexit (raise_num, []),
Ctuple [])))),
Ctuple []),
Clet (
tagged, Cop(Cadda, [lsl_const (Cvar li) log2_size_addr;
Cconst_int(1 - 3 * size_addr)]),
Csequence(Cop (Cstore Word, [cache; Cvar tagged]),
Cvar tagged)))))
Generate an application function :
( defun caml_applyN ( a1 ... aN clos )
( if (= clos.arity N )
( app clos.direct a1 ... aN clos )
( let ( clos1 ( app clos.code a1 clos )
clos2 ( app clos1.code a2 clos )
...
closN-1 ( app closN-2.code ) )
( app closN-1.code aN closN-1 ) ) ) )
(defun caml_applyN (a1 ... aN clos)
(if (= clos.arity N)
(app clos.direct a1 ... aN clos)
(let (clos1 (app clos.code a1 clos)
clos2 (app clos1.code a2 clos)
...
closN-1 (app closN-2.code aN-1 closN-2))
(app closN-1.code aN closN-1))))
*)
let apply_function_body arity =
let arg = Array.create arity (Ident.create "arg") in
for i = 1 to arity - 1 do arg.(i) <- Ident.create "arg" done;
let clos = Ident.create "clos" in
let rec app_fun clos n =
if n = arity-1 then
Cop(Capply(typ_addr, Debuginfo.none),
[get_field (Cvar clos) 0; Cvar arg.(n); Cvar clos])
else begin
let newclos = Ident.create "clos" in
Clet(newclos,
Cop(Capply(typ_addr, Debuginfo.none),
[get_field (Cvar clos) 0; Cvar arg.(n); Cvar clos]),
app_fun newclos (n+1))
end in
let args = Array.to_list arg in
let all_args = args @ [clos] in
(args, clos,
if arity = 1 then app_fun clos 0 else
Cifthenelse(
Cop(Ccmpi Ceq, [get_field (Cvar clos) 1; int_const arity]),
Cop(Capply(typ_addr, Debuginfo.none),
get_field (Cvar clos) 2 :: List.map (fun s -> Cvar s) all_args),
app_fun clos 0))
let send_function arity =
let (args, clos', body) = apply_function_body (1+arity) in
let cache = Ident.create "cache"
and obj = List.hd args
and tag = Ident.create "tag" in
let clos =
let cache = Cvar cache and obj = Cvar obj and tag = Cvar tag in
let meths = Ident.create "meths" and cached = Ident.create "cached" in
let real = Ident.create "real" in
let mask = get_field (Cvar meths) 1 in
let cached_pos = Cvar cached in
let tag_pos = Cop(Cadda, [Cop (Cadda, [cached_pos; Cvar meths]);
Cconst_int(3*size_addr-1)]) in
let tag' = Cop(Cload Word, [tag_pos]) in
Clet (
meths, Cop(Cload Word, [obj]),
Clet (
cached, Cop(Cand, [Cop(Cload Word, [cache]); mask]),
Clet (
real,
Cifthenelse(Cop(Ccmpa Cne, [tag'; tag]),
cache_public_method (Cvar meths) tag cache,
cached_pos),
Cop(Cload Word, [Cop(Cadda, [Cop (Cadda, [Cvar real; Cvar meths]);
Cconst_int(2*size_addr-1)])]))))
in
let body = Clet(clos', clos, body) in
let fun_args =
[obj, typ_addr; tag, typ_int; cache, typ_addr]
@ List.map (fun id -> (id, typ_addr)) (List.tl args) in
Cfunction
{fun_name = "caml_send" ^ string_of_int arity;
fun_args = fun_args;
fun_body = body;
fun_fast = true}
let apply_function arity =
let (args, clos, body) = apply_function_body arity in
let all_args = args @ [clos] in
Cfunction
{fun_name = "caml_apply" ^ string_of_int arity;
fun_args = List.map (fun id -> (id, typ_addr)) all_args;
fun_body = body;
fun_fast = true}
Generate tuplifying functions :
( defun caml_tuplifyN ( arg clos )
( app clos.direct # 0(arg ) ... # N-1(arg ) clos ) )
(defun caml_tuplifyN (arg clos)
(app clos.direct #0(arg) ... #N-1(arg) clos)) *)
let tuplify_function arity =
let arg = Ident.create "arg" in
let clos = Ident.create "clos" in
let rec access_components i =
if i >= arity
then []
else get_field (Cvar arg) i :: access_components(i+1) in
Cfunction
{fun_name = "caml_tuplify" ^ string_of_int arity;
fun_args = [arg, typ_addr; clos, typ_addr];
fun_body =
Cop(Capply(typ_addr, Debuginfo.none),
get_field (Cvar clos) 2 :: access_components 0 @ [Cvar clos]);
fun_fast = true}
Generate currying functions :
( defun caml_curryN ( arg clos )
( alloc HDR caml_curryN_1 arg clos ) )
( defun caml_curryN_1 ( arg clos )
( alloc HDR caml_curryN_2 arg clos ) )
...
( defun caml_curryN_N-1 ( arg clos )
( let ( closN-2 clos.cdr
closN-3 closN-2.cdr
...
clos1 clos2.cdr
clos clos1.cdr )
( app clos.direct
clos1.car clos2.car ... closN-2.car clos.car arg clos ) ) )
(defun caml_curryN (arg clos)
(alloc HDR caml_curryN_1 arg clos))
(defun caml_curryN_1 (arg clos)
(alloc HDR caml_curryN_2 arg clos))
...
(defun caml_curryN_N-1 (arg clos)
(let (closN-2 clos.cdr
closN-3 closN-2.cdr
...
clos1 clos2.cdr
clos clos1.cdr)
(app clos.direct
clos1.car clos2.car ... closN-2.car clos.car arg clos))) *)
let final_curry_function arity =
let last_arg = Ident.create "arg" in
let last_clos = Ident.create "clos" in
let rec curry_fun args clos n =
if n = 0 then
Cop(Capply(typ_addr, Debuginfo.none),
get_field (Cvar clos) 2 ::
args @ [Cvar last_arg; Cvar clos])
else begin
let newclos = Ident.create "clos" in
Clet(newclos,
get_field (Cvar clos) 3,
curry_fun (get_field (Cvar clos) 2 :: args) newclos (n-1))
end in
Cfunction
{fun_name = "caml_curry" ^ string_of_int arity ^
"_" ^ string_of_int (arity-1);
fun_args = [last_arg, typ_addr; last_clos, typ_addr];
fun_body = curry_fun [] last_clos (arity-1);
fun_fast = true}
let rec intermediate_curry_functions arity num =
if num = arity - 1 then
[final_curry_function arity]
else begin
let name1 = "caml_curry" ^ string_of_int arity in
let name2 = if num = 0 then name1 else name1 ^ "_" ^ string_of_int num in
let arg = Ident.create "arg" and clos = Ident.create "clos" in
Cfunction
{fun_name = name2;
fun_args = [arg, typ_addr; clos, typ_addr];
fun_body = Cop(Calloc,
[alloc_closure_header 4;
Cconst_symbol(name1 ^ "_" ^ string_of_int (num+1));
int_const 1; Cvar arg; Cvar clos]);
fun_fast = true}
:: intermediate_curry_functions arity (num+1)
end
let curry_function arity =
if arity >= 0
then intermediate_curry_functions arity 0
else [tuplify_function (-arity)]
module IntSet = Set.Make(
struct
type t = int
let compare = compare
end)
let default_apply = IntSet.add 2 (IntSet.add 3 IntSet.empty)
These apply funs are always present in the main program because
the run - time system needs them ( cf . .
the run-time system needs them (cf. asmrun/<arch>.S) . *)
let generic_functions shared units =
let (apply,send,curry) =
List.fold_left
(fun (apply,send,curry) ui ->
List.fold_right IntSet.add ui.ui_apply_fun apply,
List.fold_right IntSet.add ui.ui_send_fun send,
List.fold_right IntSet.add ui.ui_curry_fun curry)
(IntSet.empty,IntSet.empty,IntSet.empty)
units in
let apply = if shared then apply else IntSet.union apply default_apply in
let accu = IntSet.fold (fun n accu -> apply_function n :: accu) apply [] in
let accu = IntSet.fold (fun n accu -> send_function n :: accu) send accu in
IntSet.fold (fun n accu -> curry_function n @ accu) curry accu
let entry_point namelist =
let incr_global_inited =
Cop(Cstore Word,
[Cconst_symbol "caml_globals_inited";
Cop(Caddi, [Cop(Cload Word, [Cconst_symbol "caml_globals_inited"]);
Cconst_int 1])]) in
let body =
List.fold_right
(fun name next ->
let entry_sym = Compilenv.make_symbol ~unitname:name (Some "entry") in
Csequence(Cop(Capply(typ_void, Debuginfo.none),
[Cconst_symbol entry_sym]),
Csequence(incr_global_inited, next)))
namelist (Cconst_int 1) in
Cfunction {fun_name = "caml_program";
fun_args = [];
fun_body = body;
fun_fast = false}
let cint_zero = Cint 0n
let global_table namelist =
let mksym name =
Csymbol_address (Compilenv.make_symbol ~unitname:name None)
in
Cdata(Cglobal_symbol "caml_globals" ::
Cdefine_symbol "caml_globals" ::
List.map mksym namelist @
[cint_zero])
let reference_symbols namelist =
let mksym name = Csymbol_address name in
Cdata(List.map mksym namelist)
let global_data name v =
Cdata(Cglobal_symbol name ::
emit_constant name
(Const_base (Const_string (Marshal.to_string v []))) [])
let globals_map v = global_data "caml_globals_map" v
let frame_table namelist =
let mksym name =
Csymbol_address (Compilenv.make_symbol ~unitname:name (Some "frametable"))
in
Cdata(Cglobal_symbol "caml_frametable" ::
Cdefine_symbol "caml_frametable" ::
List.map mksym namelist
@ [cint_zero])
let segment_table namelist symbol begname endname =
let addsyms name lst =
Csymbol_address (Compilenv.make_symbol ~unitname:name (Some begname)) ::
Csymbol_address (Compilenv.make_symbol ~unitname:name (Some endname)) ::
lst
in
Cdata(Cglobal_symbol symbol ::
Cdefine_symbol symbol ::
List.fold_right addsyms namelist [cint_zero])
let data_segment_table namelist =
segment_table namelist "caml_data_segments" "data_begin" "data_end"
let code_segment_table namelist =
segment_table namelist "caml_code_segments" "code_begin" "code_end"
Initialize a predefined exception
let predef_exception name =
let bucketname = "caml_bucket_" ^ name in
let symname = "caml_exn_" ^ name in
Cdata(Cglobal_symbol symname ::
emit_constant symname (Const_block(0,[Const_base(Const_string name)]))
[ Cglobal_symbol bucketname;
Cint(block_header 0 1);
Cdefine_symbol bucketname;
Csymbol_address symname ])
let mapflat f l = List.flatten (List.map f l)
let plugin_header units =
let mk (ui,crc) =
{ dynu_name = ui.ui_name;
dynu_crc = crc;
dynu_imports_cmi = ui.ui_imports_cmi;
dynu_imports_cmx = ui.ui_imports_cmx;
dynu_defines = ui.ui_defines
} in
global_data "caml_plugin_header"
{ dynu_magic = Config.cmxs_magic_number; dynu_units = List.map mk units }
|
60e456eb685443bf543daa46aee4ca30e6133e0a4de342e5755dccb067878db6 | dbuenzli/vg | arrowhead.ml | ---------------------------------------------------------------------------
Copyright ( c ) 2013 The vg programmers . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
---------------------------------------------------------------------------
Copyright (c) 2013 The vg programmers. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*)
open Gg
open Vg
;;
* curve
*)
Db.image "arrowhead" __POS__ ~author:Db.dbuenzli
~title:"Sierpiński Arrowhead curve levels 0-9"
~tags:["fractal"; "image"]
~note:(Printf.sprintf "Last curve made of %g segments" (3. ** (float 9)))
~size:(Size2.v 120. 255.)
~view:(Box2.v P2.o (Size2.v 2. 4.25))
begin fun _ ->
let arrowhead_path i len =
let angle = Float.pi /. 3. in
let rec loop i len sign turn p =
if i = 0 then p |> P.line ~rel:true V2.(polar len turn) else
p |>
loop (i - 1) (len /. 2.) (-. sign) (turn +. sign *. angle) |>
loop (i - 1) (len /. 2.) sign turn |>
loop (i - 1) (len /. 2.) (-. sign) (turn -. sign *. angle)
in
P.empty |> loop i len 1. 0.
in
let area = `O { P.o with P.width = 0.005 } in
let gray = I.const (Color.gray 0.2) in
let acc = ref I.void in
for i = 0 to 9 do
let x = float (i mod 2) +. 0.1 in
let y = 0.85 *. float (i / 2) +. 0.1 in
acc :=
gray |> I.cut ~area (arrowhead_path i 0.8) |> I.move (V2.v x y) |>
I.blend !acc
done;
!acc
end;
---------------------------------------------------------------------------
Copyright ( c ) 2013 The vg programmers
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) 2013 The vg programmers
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/dbuenzli/vg/2d0cd56636a17280fe938ecaafc6402383dca1f3/db/arrowhead.ml | ocaml | ---------------------------------------------------------------------------
Copyright ( c ) 2013 The vg programmers . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
---------------------------------------------------------------------------
Copyright (c) 2013 The vg programmers. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*)
open Gg
open Vg
;;
* curve
*)
Db.image "arrowhead" __POS__ ~author:Db.dbuenzli
~title:"Sierpiński Arrowhead curve levels 0-9"
~tags:["fractal"; "image"]
~note:(Printf.sprintf "Last curve made of %g segments" (3. ** (float 9)))
~size:(Size2.v 120. 255.)
~view:(Box2.v P2.o (Size2.v 2. 4.25))
begin fun _ ->
let arrowhead_path i len =
let angle = Float.pi /. 3. in
let rec loop i len sign turn p =
if i = 0 then p |> P.line ~rel:true V2.(polar len turn) else
p |>
loop (i - 1) (len /. 2.) (-. sign) (turn +. sign *. angle) |>
loop (i - 1) (len /. 2.) sign turn |>
loop (i - 1) (len /. 2.) (-. sign) (turn -. sign *. angle)
in
P.empty |> loop i len 1. 0.
in
let area = `O { P.o with P.width = 0.005 } in
let gray = I.const (Color.gray 0.2) in
let acc = ref I.void in
for i = 0 to 9 do
let x = float (i mod 2) +. 0.1 in
let y = 0.85 *. float (i / 2) +. 0.1 in
acc :=
gray |> I.cut ~area (arrowhead_path i 0.8) |> I.move (V2.v x y) |>
I.blend !acc
done;
!acc
end;
---------------------------------------------------------------------------
Copyright ( c ) 2013 The vg programmers
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) 2013 The vg programmers
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.
---------------------------------------------------------------------------*)
|
|
ed85aef3d6e5dff15940188a55926f093264dd9740c9539d6cdd789a4be51d0c | ygrek/mldonkey | commonComplexOptions.mli | Copyright 2001 , 2002 b8_bavard , b8_fee_carabine ,
This file is part of mldonkey .
mldonkey is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
mldonkey is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details .
You should have received a copy of the GNU General Public License
along with mldonkey ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This file is part of mldonkey.
mldonkey is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
mldonkey is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with mldonkey; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
val load : unit -> unit
val save : unit -> unit
val save_sources : unit -> unit
val backup_options : unit -> unit
val allow_saving_ini_files : bool ref
val done_files : CommonTypes.file list Options.option_record
val files : CommonTypes.file list Options.option_record
val servers : CommonTypes.server Intmap.t Options.option_record
val friends : CommonTypes.client list Options.option_record
val contacts : CommonTypes.client list ref
val customized_queries : unit ->
(string * CommonTypes.query_entry) list
val special_queries : (string * string) list Options.option_record
val sharing_strategies : (string * CommonTypes.sharing_strategy) list Options.option_record
val sharing_strategy : string -> CommonTypes.sharing_strategy
val shared_directories :
CommonTypes.shared_directory list Options.option_record
val incoming_dir : bool -> ?user:CommonTypes.userdb -> ?needed_space:int64 -> ?network:string -> unit -> CommonTypes.shared_directory
val search_incoming_files : unit -> CommonTypes.shared_directory list
val search_incoming_directories : unit -> CommonTypes.shared_directory list
val shared_directories_including_user_commit : unit -> CommonTypes.shared_directory list
val sharing_only_directory : CommonTypes.sharing_strategy
val swarmers_section : Options.options_section
| null | https://raw.githubusercontent.com/ygrek/mldonkey/333868a12bb6cd25fed49391dd2c3a767741cb51/src/daemon/common/commonComplexOptions.mli | ocaml | Copyright 2001 , 2002 b8_bavard , b8_fee_carabine ,
This file is part of mldonkey .
mldonkey is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
mldonkey is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details .
You should have received a copy of the GNU General Public License
along with mldonkey ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This file is part of mldonkey.
mldonkey is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
mldonkey is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with mldonkey; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
val load : unit -> unit
val save : unit -> unit
val save_sources : unit -> unit
val backup_options : unit -> unit
val allow_saving_ini_files : bool ref
val done_files : CommonTypes.file list Options.option_record
val files : CommonTypes.file list Options.option_record
val servers : CommonTypes.server Intmap.t Options.option_record
val friends : CommonTypes.client list Options.option_record
val contacts : CommonTypes.client list ref
val customized_queries : unit ->
(string * CommonTypes.query_entry) list
val special_queries : (string * string) list Options.option_record
val sharing_strategies : (string * CommonTypes.sharing_strategy) list Options.option_record
val sharing_strategy : string -> CommonTypes.sharing_strategy
val shared_directories :
CommonTypes.shared_directory list Options.option_record
val incoming_dir : bool -> ?user:CommonTypes.userdb -> ?needed_space:int64 -> ?network:string -> unit -> CommonTypes.shared_directory
val search_incoming_files : unit -> CommonTypes.shared_directory list
val search_incoming_directories : unit -> CommonTypes.shared_directory list
val shared_directories_including_user_commit : unit -> CommonTypes.shared_directory list
val sharing_only_directory : CommonTypes.sharing_strategy
val swarmers_section : Options.options_section
|
|
ed68fb15bb88d112fa999972b9b186a044f44981f110bb21ec66d159c3b0d46e | emqx/emqx | emqx_bridge_proto_v1.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2022 - 2023 EMQ 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(emqx_bridge_proto_v1).
-behaviour(emqx_bpapi).
-export([
introduced_in/0,
deprecated_since/0,
list_bridges/1,
restart_bridge_to_node/3,
stop_bridge_to_node/3,
lookup_from_all_nodes/3,
restart_bridges_to_all_nodes/3,
stop_bridges_to_all_nodes/3
]).
-include_lib("emqx/include/bpapi.hrl").
-define(TIMEOUT, 15000).
introduced_in() ->
"5.0.0".
deprecated_since() ->
"5.0.17".
-spec list_bridges(node()) -> list() | emqx_rpc:badrpc().
list_bridges(Node) ->
rpc:call(Node, emqx_bridge, list, [], ?TIMEOUT).
-type key() :: atom() | binary() | [byte()].
-spec restart_bridge_to_node(node(), key(), key()) ->
term().
restart_bridge_to_node(Node, BridgeType, BridgeName) ->
rpc:call(
Node,
emqx_bridge_resource,
restart,
[BridgeType, BridgeName],
?TIMEOUT
).
-spec stop_bridge_to_node(node(), key(), key()) ->
term().
stop_bridge_to_node(Node, BridgeType, BridgeName) ->
rpc:call(
Node,
emqx_bridge_resource,
stop,
[BridgeType, BridgeName],
?TIMEOUT
).
-spec restart_bridges_to_all_nodes([node()], key(), key()) ->
emqx_rpc:erpc_multicall().
restart_bridges_to_all_nodes(Nodes, BridgeType, BridgeName) ->
erpc:multicall(
Nodes,
emqx_bridge_resource,
restart,
[BridgeType, BridgeName],
?TIMEOUT
).
-spec stop_bridges_to_all_nodes([node()], key(), key()) ->
emqx_rpc:erpc_multicall().
stop_bridges_to_all_nodes(Nodes, BridgeType, BridgeName) ->
erpc:multicall(
Nodes,
emqx_bridge_resource,
stop,
[BridgeType, BridgeName],
?TIMEOUT
).
-spec lookup_from_all_nodes([node()], key(), key()) ->
emqx_rpc:erpc_multicall().
lookup_from_all_nodes(Nodes, BridgeType, BridgeName) ->
erpc:multicall(
Nodes,
emqx_bridge_api,
lookup_from_local_node,
[BridgeType, BridgeName],
?TIMEOUT
).
| null | https://raw.githubusercontent.com/emqx/emqx/42dfaf3ef2f2113d710c066894fe62c263190526/apps/emqx_bridge/src/proto/emqx_bridge_proto_v1.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.
-------------------------------------------------------------------- | Copyright ( c ) 2022 - 2023 EMQ 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(emqx_bridge_proto_v1).
-behaviour(emqx_bpapi).
-export([
introduced_in/0,
deprecated_since/0,
list_bridges/1,
restart_bridge_to_node/3,
stop_bridge_to_node/3,
lookup_from_all_nodes/3,
restart_bridges_to_all_nodes/3,
stop_bridges_to_all_nodes/3
]).
-include_lib("emqx/include/bpapi.hrl").
-define(TIMEOUT, 15000).
introduced_in() ->
"5.0.0".
deprecated_since() ->
"5.0.17".
-spec list_bridges(node()) -> list() | emqx_rpc:badrpc().
list_bridges(Node) ->
rpc:call(Node, emqx_bridge, list, [], ?TIMEOUT).
-type key() :: atom() | binary() | [byte()].
-spec restart_bridge_to_node(node(), key(), key()) ->
term().
restart_bridge_to_node(Node, BridgeType, BridgeName) ->
rpc:call(
Node,
emqx_bridge_resource,
restart,
[BridgeType, BridgeName],
?TIMEOUT
).
-spec stop_bridge_to_node(node(), key(), key()) ->
term().
stop_bridge_to_node(Node, BridgeType, BridgeName) ->
rpc:call(
Node,
emqx_bridge_resource,
stop,
[BridgeType, BridgeName],
?TIMEOUT
).
-spec restart_bridges_to_all_nodes([node()], key(), key()) ->
emqx_rpc:erpc_multicall().
restart_bridges_to_all_nodes(Nodes, BridgeType, BridgeName) ->
erpc:multicall(
Nodes,
emqx_bridge_resource,
restart,
[BridgeType, BridgeName],
?TIMEOUT
).
-spec stop_bridges_to_all_nodes([node()], key(), key()) ->
emqx_rpc:erpc_multicall().
stop_bridges_to_all_nodes(Nodes, BridgeType, BridgeName) ->
erpc:multicall(
Nodes,
emqx_bridge_resource,
stop,
[BridgeType, BridgeName],
?TIMEOUT
).
-spec lookup_from_all_nodes([node()], key(), key()) ->
emqx_rpc:erpc_multicall().
lookup_from_all_nodes(Nodes, BridgeType, BridgeName) ->
erpc:multicall(
Nodes,
emqx_bridge_api,
lookup_from_local_node,
[BridgeType, BridgeName],
?TIMEOUT
).
|
1b4102088fd5bedec2051c1785de0b34e7281fac5304fc2c4fd9630c29326a68 | bjorng/wings | wpc_shift.erl | %%
wpc_shift.erl --
%%
%% Plug-in for shifting vertices
%%
Copyright ( c ) 2005 - 2011
%%
%% See the file "license.terms" for information on usage and redistribution
%% of this file, and for a DISCLAIMER OF ALL WARRANTIES.
%%
%% $Id$
%%
-module(wpc_shift).
-export([init/0,menu/2,command/2]).
-import(lists, [foldl/3]).
-include_lib("wings/src/wings.hrl").
-define(HUGE, 1.0E307).
-define(EPSILON, 1.0E-6).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% Exported functions
%%
init() ->
true.
menu({Mode}, Menu) when Mode==vertex; Mode==edge; Mode==face; Mode==body ->
lists:reverse(parse(Menu, [], false));
menu(_,Menu) -> Menu.
parse([], NewMenu, true) ->
NewMenu;
parse([], NewMenu, false) ->
[menu_heading()|NewMenu];
parse([A = separator|Rest], NewMenu, false) ->
parse(Rest, [A, menu_heading()|NewMenu], true);
parse([Elem|Rest], NewMenu, Found) ->
parse(Rest, [Elem|NewMenu], Found).
menu_heading() ->
{?__(1,"Shift"), {shift,fun adv_submenu/2}}.
command({Mode,{shift,Type}}, St) when Mode==vertex; Mode==edge; Mode==face; Mode==body ->
shift_cmd(Type, St);
command(_,_) -> next.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% Create the menus
%%
submenu_items(1) ->
{{planar_shift}, {'ASK',{[{axis, ?__(1,"Pick axis")},
{point, ?__(2,"Pick point")}],[],[]}}};
submenu_items(2) ->
{{spherical_shift}, {'ASK',{[{point, ?__(3,"Pick center")}],[],[]}}};
submenu_items(3) ->
{{cylindrical_shift}, {'ASK',{[{axis, ?__(4,"Pick axis")},
{point, ?__(5,"Pick point")}],[],[]}}}.
adv_submenu(help, _) ->
{?__(1,"Planar Shift"),
?__(2,"Spherical Shift"),
?__(3,"Cylindrical Shift")};
adv_submenu(Button, NS) ->
wings_menu:build_command(submenu_items(Button), NS).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% Respond to commands
%%
shift_cmd({Mode, {'ASK',Ask}}, St) ->
wings:ask(Ask, St, fun (AskResult, St0) ->
shift_ask_callback({Mode, AskResult}, St0)
end);
%%% for repeat cmds
shift_cmd({Mode, Data}, St) ->
shift_ask_callback({Mode, Data}, St).
shift_ask_callback({{Mode}, Data}, St) ->
shift_verts(Mode, Data, St).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% Drag and iterate through the vertices
%%
shift_verts(Mode, Data, #st{selmode=body}=St) ->
F = fun(Vs, We) ->
Center = wings_vertex:center(Vs, We),
object_vector(Data, Center)
end,
shift_verts_1(F, Mode, St);
shift_verts(Mode, Data, St) ->
F = fun(_, _) -> Data end,
shift_verts_1(F, Mode, St).
shift_verts_1(F, ShiftMode, #st{selmode=SelMode}=St) ->
Shift = case ShiftMode of
planar_shift -> fun shift_planar/3;
cylindrical_shift -> fun shift_cylindrical/3;
spherical_shift -> fun shift_spherical/3
end,
DF = fun(Items, We) ->
Vs = convert_sel(SelMode, Items, We),
Data = F(Vs, We),
shift_verts_2(Shift, Data, Vs, We)
end,
wings_drag:fold(DF, [distance], St).
shift_verts_2(ShiftFun, Data, Vs, We) ->
VsPos = wings_util:add_vpos(Vs, We),
Fun = fun([Distance], A) ->
foldl(fun({V,Vpos}, VsAcc) ->
[{V,ShiftFun(Vpos, Distance, Data)}|VsAcc]
end, A, VsPos)
end,
{Vs,Fun}.
-spec convert_sel(SelMode, Items, #we{}) -> Vertices when
SelMode :: wings_sel:mode(),
Items :: [wings_sel:item_id()],
Vertices :: [wings_vertex:vertex_num()].
convert_sel(vertex, Vs, _We) ->
gb_sets:to_list(Vs);
convert_sel(edge, Es, We) ->
wings_vertex:from_edges(Es, We);
convert_sel(face, Fs, We) ->
wings_vertex:from_faces(Fs, We);
convert_sel(body, _, We) ->
wings_we:visible_vs(We).
object_vector({Axis,CenterPoint}, ObjCenter) ->
Vector = e3d_vec:norm_sub(ObjCenter, CenterPoint),
{object, Axis, Vector};
object_vector(CenterPoint, ObjCenter) ->
Vector = e3d_vec:norm_sub(ObjCenter, CenterPoint),
{object, Vector}.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% The Main Functions.
%%
%% The return value is the new position. {X,Y,Z}
%%
shift_planar(Pos, 0.0, _) -> Pos;
shift_planar(Pos, Dist, {Axis, Center}) ->
V = e3d_vec:sub(Pos,Center),
D = e3d_vec:dot(V,Axis),
if
D < -?EPSILON ->
N = e3d_vec:norm(Axis),
e3d_vec:add([Pos, e3d_vec:mul(N, -Dist)]);
D > +?EPSILON ->
N = e3d_vec:norm(Axis),
e3d_vec:add([Pos, e3d_vec:mul(N, +Dist)]);
true ->
Pos
end;
shift_planar(Pos, Dist, {object, Axis, V}) ->
D = e3d_vec:dot(V,Axis),
if
D < -?EPSILON ->
N = e3d_vec:norm(Axis),
e3d_vec:add([Pos, e3d_vec:mul(N, -Dist)]);
D > +?EPSILON ->
N = e3d_vec:norm(Axis),
e3d_vec:add([Pos, e3d_vec:mul(N, +Dist)]);
true ->
Pos
end.
shift_cylindrical(Pos, 0.0, _) -> Pos;
shift_cylindrical(Pos, Dist, {Axis, Center}) ->
V = e3d_vec:sub(Pos,Center),
OffDist = e3d_vec:dot(V,Axis),
OffVec = e3d_vec:sub(V,e3d_vec:mul(Axis, OffDist)),
N = e3d_vec:norm(OffVec),
e3d_vec:add([Pos, e3d_vec:mul(N, Dist)]);
shift_cylindrical(Pos, Dist, {object, Axis, V}) ->
OffDist = e3d_vec:dot(V,Axis),
OffVec = e3d_vec:sub(V,e3d_vec:mul(Axis, OffDist)),
N = e3d_vec:norm(OffVec),
e3d_vec:add([Pos, e3d_vec:mul(N, Dist)]).
shift_spherical(Pos, 0.0, _Center) -> Pos;
shift_spherical(Pos, Dist, {object, V}) ->
N = e3d_vec:norm(V),
e3d_vec:add([Pos, e3d_vec:mul(N, Dist)]);
shift_spherical(Pos, Dist, Center) ->
V = e3d_vec:sub(Pos,Center),
N = e3d_vec:norm(V),
e3d_vec:add([Pos, e3d_vec:mul(N, Dist)]).
| null | https://raw.githubusercontent.com/bjorng/wings/dec64a500220359dbc552600af486be47c45d301/plugins_src/commands/wpc_shift.erl | erlang |
Plug-in for shifting vertices
See the file "license.terms" for information on usage and redistribution
of this file, and for a DISCLAIMER OF ALL WARRANTIES.
$Id$
Exported functions
Create the menus
Respond to commands
for repeat cmds
Drag and iterate through the vertices
The Main Functions.
The return value is the new position. {X,Y,Z}
| wpc_shift.erl --
Copyright ( c ) 2005 - 2011
-module(wpc_shift).
-export([init/0,menu/2,command/2]).
-import(lists, [foldl/3]).
-include_lib("wings/src/wings.hrl").
-define(HUGE, 1.0E307).
-define(EPSILON, 1.0E-6).
init() ->
true.
menu({Mode}, Menu) when Mode==vertex; Mode==edge; Mode==face; Mode==body ->
lists:reverse(parse(Menu, [], false));
menu(_,Menu) -> Menu.
parse([], NewMenu, true) ->
NewMenu;
parse([], NewMenu, false) ->
[menu_heading()|NewMenu];
parse([A = separator|Rest], NewMenu, false) ->
parse(Rest, [A, menu_heading()|NewMenu], true);
parse([Elem|Rest], NewMenu, Found) ->
parse(Rest, [Elem|NewMenu], Found).
menu_heading() ->
{?__(1,"Shift"), {shift,fun adv_submenu/2}}.
command({Mode,{shift,Type}}, St) when Mode==vertex; Mode==edge; Mode==face; Mode==body ->
shift_cmd(Type, St);
command(_,_) -> next.
submenu_items(1) ->
{{planar_shift}, {'ASK',{[{axis, ?__(1,"Pick axis")},
{point, ?__(2,"Pick point")}],[],[]}}};
submenu_items(2) ->
{{spherical_shift}, {'ASK',{[{point, ?__(3,"Pick center")}],[],[]}}};
submenu_items(3) ->
{{cylindrical_shift}, {'ASK',{[{axis, ?__(4,"Pick axis")},
{point, ?__(5,"Pick point")}],[],[]}}}.
adv_submenu(help, _) ->
{?__(1,"Planar Shift"),
?__(2,"Spherical Shift"),
?__(3,"Cylindrical Shift")};
adv_submenu(Button, NS) ->
wings_menu:build_command(submenu_items(Button), NS).
shift_cmd({Mode, {'ASK',Ask}}, St) ->
wings:ask(Ask, St, fun (AskResult, St0) ->
shift_ask_callback({Mode, AskResult}, St0)
end);
shift_cmd({Mode, Data}, St) ->
shift_ask_callback({Mode, Data}, St).
shift_ask_callback({{Mode}, Data}, St) ->
shift_verts(Mode, Data, St).
shift_verts(Mode, Data, #st{selmode=body}=St) ->
F = fun(Vs, We) ->
Center = wings_vertex:center(Vs, We),
object_vector(Data, Center)
end,
shift_verts_1(F, Mode, St);
shift_verts(Mode, Data, St) ->
F = fun(_, _) -> Data end,
shift_verts_1(F, Mode, St).
shift_verts_1(F, ShiftMode, #st{selmode=SelMode}=St) ->
Shift = case ShiftMode of
planar_shift -> fun shift_planar/3;
cylindrical_shift -> fun shift_cylindrical/3;
spherical_shift -> fun shift_spherical/3
end,
DF = fun(Items, We) ->
Vs = convert_sel(SelMode, Items, We),
Data = F(Vs, We),
shift_verts_2(Shift, Data, Vs, We)
end,
wings_drag:fold(DF, [distance], St).
shift_verts_2(ShiftFun, Data, Vs, We) ->
VsPos = wings_util:add_vpos(Vs, We),
Fun = fun([Distance], A) ->
foldl(fun({V,Vpos}, VsAcc) ->
[{V,ShiftFun(Vpos, Distance, Data)}|VsAcc]
end, A, VsPos)
end,
{Vs,Fun}.
-spec convert_sel(SelMode, Items, #we{}) -> Vertices when
SelMode :: wings_sel:mode(),
Items :: [wings_sel:item_id()],
Vertices :: [wings_vertex:vertex_num()].
convert_sel(vertex, Vs, _We) ->
gb_sets:to_list(Vs);
convert_sel(edge, Es, We) ->
wings_vertex:from_edges(Es, We);
convert_sel(face, Fs, We) ->
wings_vertex:from_faces(Fs, We);
convert_sel(body, _, We) ->
wings_we:visible_vs(We).
object_vector({Axis,CenterPoint}, ObjCenter) ->
Vector = e3d_vec:norm_sub(ObjCenter, CenterPoint),
{object, Axis, Vector};
object_vector(CenterPoint, ObjCenter) ->
Vector = e3d_vec:norm_sub(ObjCenter, CenterPoint),
{object, Vector}.
shift_planar(Pos, 0.0, _) -> Pos;
shift_planar(Pos, Dist, {Axis, Center}) ->
V = e3d_vec:sub(Pos,Center),
D = e3d_vec:dot(V,Axis),
if
D < -?EPSILON ->
N = e3d_vec:norm(Axis),
e3d_vec:add([Pos, e3d_vec:mul(N, -Dist)]);
D > +?EPSILON ->
N = e3d_vec:norm(Axis),
e3d_vec:add([Pos, e3d_vec:mul(N, +Dist)]);
true ->
Pos
end;
shift_planar(Pos, Dist, {object, Axis, V}) ->
D = e3d_vec:dot(V,Axis),
if
D < -?EPSILON ->
N = e3d_vec:norm(Axis),
e3d_vec:add([Pos, e3d_vec:mul(N, -Dist)]);
D > +?EPSILON ->
N = e3d_vec:norm(Axis),
e3d_vec:add([Pos, e3d_vec:mul(N, +Dist)]);
true ->
Pos
end.
shift_cylindrical(Pos, 0.0, _) -> Pos;
shift_cylindrical(Pos, Dist, {Axis, Center}) ->
V = e3d_vec:sub(Pos,Center),
OffDist = e3d_vec:dot(V,Axis),
OffVec = e3d_vec:sub(V,e3d_vec:mul(Axis, OffDist)),
N = e3d_vec:norm(OffVec),
e3d_vec:add([Pos, e3d_vec:mul(N, Dist)]);
shift_cylindrical(Pos, Dist, {object, Axis, V}) ->
OffDist = e3d_vec:dot(V,Axis),
OffVec = e3d_vec:sub(V,e3d_vec:mul(Axis, OffDist)),
N = e3d_vec:norm(OffVec),
e3d_vec:add([Pos, e3d_vec:mul(N, Dist)]).
shift_spherical(Pos, 0.0, _Center) -> Pos;
shift_spherical(Pos, Dist, {object, V}) ->
N = e3d_vec:norm(V),
e3d_vec:add([Pos, e3d_vec:mul(N, Dist)]);
shift_spherical(Pos, Dist, Center) ->
V = e3d_vec:sub(Pos,Center),
N = e3d_vec:norm(V),
e3d_vec:add([Pos, e3d_vec:mul(N, Dist)]).
|
8caef8a880c50469ed3cc409bde73436c28d9adf23c1e9eec5d6311b276f705c | tisnik/clojure-examples | core.clj | (ns factorial.core
(:gen-class))
(defn factorial
[n]
(if (neg? n)
(throw (IllegalArgumentException. "negative numbers are not supported!"))
(apply * (range 1 (inc n)))))
(defn -main
"I don't do a whole lot ... yet."
[& args]
(doseq [i (range 0 10)]
(println i "! = " (factorial i))))
| null | https://raw.githubusercontent.com/tisnik/clojure-examples/984af4a3e20d994b4f4989678ee1330e409fdae3/factorial/src/factorial/core.clj | clojure | (ns factorial.core
(:gen-class))
(defn factorial
[n]
(if (neg? n)
(throw (IllegalArgumentException. "negative numbers are not supported!"))
(apply * (range 1 (inc n)))))
(defn -main
"I don't do a whole lot ... yet."
[& args]
(doseq [i (range 0 10)]
(println i "! = " (factorial i))))
|
|
b97915bf7e60fb65fb5629d58c94266b4ef1419a1280d10745615e49d37f9d03 | fragnix/fragnix | GHC.Word.hs | {-# LINE 1 "GHC.Word.hs" #-}
# LANGUAGE Trustworthy #
# LANGUAGE CPP , NoImplicitPrelude , BangPatterns , MagicHash , UnboxedTuples #
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Word
Copyright : ( c ) The University of Glasgow , 1997 - 2002
-- License : see libraries/base/LICENSE
--
-- Maintainer :
-- Stability : internal
Portability : non - portable ( GHC Extensions )
--
Sized unsigned integral types : ' Word ' , ' Word8 ' , ' Word16 ' , ' ' , and
-- 'Word64'.
--
-----------------------------------------------------------------------------
module GHC.Word (
Word(..), Word8(..), Word16(..), Word32(..), Word64(..),
-- * Shifts
uncheckedShiftL64#,
uncheckedShiftRL64#,
* Byte swapping
byteSwap16,
byteSwap32,
byteSwap64,
-- * Equality operators
-- | See GHC.Classes#matching_overloaded_methods_in_rules
eqWord, neWord, gtWord, geWord, ltWord, leWord,
eqWord8, neWord8, gtWord8, geWord8, ltWord8, leWord8,
eqWord16, neWord16, gtWord16, geWord16, ltWord16, leWord16,
eqWord32, neWord32, gtWord32, geWord32, ltWord32, leWord32,
eqWord64, neWord64, gtWord64, geWord64, ltWord64, leWord64
) where
import Data.Bits
import Data.Maybe
import GHC.Base
import GHC.Enum
import GHC.Num
import GHC.Real
import GHC.Read
import GHC.Arr
import GHC.Show
------------------------------------------------------------------------
-- type Word8
------------------------------------------------------------------------
Word8 is represented in the same way as Word . Operations may assume
-- and must ensure that it holds only values from its logical range.
data {-# CTYPE "HsWord8" #-} Word8 = W8# Word#
^ 8 - bit unsigned integer type
-- See GHC.Classes#matching_overloaded_methods_in_rules
instance Eq Word8 where
(==) = eqWord8
(/=) = neWord8
eqWord8, neWord8 :: Word8 -> Word8 -> Bool
eqWord8 (W8# x) (W8# y) = isTrue# (x `eqWord#` y)
neWord8 (W8# x) (W8# y) = isTrue# (x `neWord#` y)
# INLINE [ 1 ] eqWord8 #
{-# INLINE [1] neWord8 #-}
instance Ord Word8 where
(<) = ltWord8
(<=) = leWord8
(>=) = geWord8
(>) = gtWord8
{-# INLINE [1] gtWord8 #-}
{-# INLINE [1] geWord8 #-}
# INLINE [ 1 ] ltWord8 #
{-# INLINE [1] leWord8 #-}
gtWord8, geWord8, ltWord8, leWord8 :: Word8 -> Word8 -> Bool
(W8# x) `gtWord8` (W8# y) = isTrue# (x `gtWord#` y)
(W8# x) `geWord8` (W8# y) = isTrue# (x `geWord#` y)
(W8# x) `ltWord8` (W8# y) = isTrue# (x `ltWord#` y)
(W8# x) `leWord8` (W8# y) = isTrue# (x `leWord#` y)
instance Show Word8 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Num Word8 where
(W8# x#) + (W8# y#) = W8# (narrow8Word# (x# `plusWord#` y#))
(W8# x#) - (W8# y#) = W8# (narrow8Word# (x# `minusWord#` y#))
(W8# x#) * (W8# y#) = W8# (narrow8Word# (x# `timesWord#` y#))
negate (W8# x#) = W8# (narrow8Word# (int2Word# (negateInt# (word2Int# x#))))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W8# (narrow8Word# (integerToWord i))
instance Real Word8 where
toRational x = toInteger x % 1
instance Enum Word8 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word8"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word8"
toEnum i@(I# i#)
| i >= 0 && i <= fromIntegral (maxBound::Word8)
= W8# (int2Word# i#)
| otherwise = toEnumError "Word8" i (minBound::Word8, maxBound::Word8)
fromEnum (W8# x#) = I# (word2Int# x#)
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Word8 where
quot (W8# x#) y@(W8# y#)
| y /= 0 = W8# (x# `quotWord#` y#)
| otherwise = divZeroError
rem (W8# x#) y@(W8# y#)
| y /= 0 = W8# (x# `remWord#` y#)
| otherwise = divZeroError
div (W8# x#) y@(W8# y#)
| y /= 0 = W8# (x# `quotWord#` y#)
| otherwise = divZeroError
mod (W8# x#) y@(W8# y#)
| y /= 0 = W8# (x# `remWord#` y#)
| otherwise = divZeroError
quotRem (W8# x#) y@(W8# y#)
| y /= 0 = case x# `quotRemWord#` y# of
(# q, r #) ->
(W8# q, W8# r)
| otherwise = divZeroError
divMod (W8# x#) y@(W8# y#)
| y /= 0 = (W8# (x# `quotWord#` y#), W8# (x# `remWord#` y#))
| otherwise = divZeroError
toInteger (W8# x#) = smallInteger (word2Int# x#)
instance Bounded Word8 where
minBound = 0
maxBound = 0xFF
instance Ix Word8 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
instance Read Word8 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
instance Bits Word8 where
{-# INLINE shift #-}
# INLINE bit #
# INLINE testBit #
(W8# x#) .&. (W8# y#) = W8# (x# `and#` y#)
(W8# x#) .|. (W8# y#) = W8# (x# `or#` y#)
(W8# x#) `xor` (W8# y#) = W8# (x# `xor#` y#)
complement (W8# x#) = W8# (x# `xor#` mb#)
where !(W8# mb#) = maxBound
(W8# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W8# (narrow8Word# (x# `shiftL#` i#))
| otherwise = W8# (x# `shiftRL#` negateInt# i#)
(W8# x#) `shiftL` (I# i#) = W8# (narrow8Word# (x# `shiftL#` i#))
(W8# x#) `unsafeShiftL` (I# i#) =
W8# (narrow8Word# (x# `uncheckedShiftL#` i#))
(W8# x#) `shiftR` (I# i#) = W8# (x# `shiftRL#` i#)
(W8# x#) `unsafeShiftR` (I# i#) = W8# (x# `uncheckedShiftRL#` i#)
(W8# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W8# x#
| otherwise = W8# (narrow8Word# ((x# `uncheckedShiftL#` i'#) `or#`
(x# `uncheckedShiftRL#` (8# -# i'#))))
where
!i'# = word2Int# (int2Word# i# `and#` 7##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W8# x#) = I# (word2Int# (popCnt8# x#))
bit = bitDefault
testBit = testBitDefault
instance FiniteBits Word8 where
finiteBitSize _ = 8
countLeadingZeros (W8# x#) = I# (word2Int# (clz8# x#))
countTrailingZeros (W8# x#) = I# (word2Int# (ctz8# x#))
# RULES
" fromIntegral / Word8->Word8 " fromIntegral = i d : : Word8 - > Word8
" fromIntegral / Word8->Integer " fromIntegral = toInteger : : Word8 - > Integer
" fromIntegral / a->Word8 " fromIntegral = \x - > case fromIntegral x of W # x # - > W8 # ( narrow8Word # x # )
" fromIntegral / Word8->a " fromIntegral = \(W8 # x # ) - > fromIntegral ( W # x # )
#
"fromIntegral/Word8->Word8" fromIntegral = id :: Word8 -> Word8
"fromIntegral/Word8->Integer" fromIntegral = toInteger :: Word8 -> Integer
"fromIntegral/a->Word8" fromIntegral = \x -> case fromIntegral x of W# x# -> W8# (narrow8Word# x#)
"fromIntegral/Word8->a" fromIntegral = \(W8# x#) -> fromIntegral (W# x#)
#-}
# RULES
" properFraction / Float->(Word8,Float ) "
properFraction = \x - >
case properFraction x of {
( n , y ) - > ( ( fromIntegral : : Int - > Word8 ) n , y : : Float ) }
" truncate / Float->Word8 "
truncate = ( fromIntegral : : Int - > Word8 ) . ( truncate : : Float - > Int )
" floor / Float->Word8 "
floor = ( fromIntegral : : Int - > Word8 ) . ( floor : : Float - > Int )
" ceiling / Float->Word8 "
ceiling = ( fromIntegral : : Int - > Word8 ) . ( ceiling : : Float - > Int )
" round / Float->Word8 "
round = ( fromIntegral : : Int - > Word8 ) . ( round : : Float - > Int )
#
"properFraction/Float->(Word8,Float)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word8) n, y :: Float) }
"truncate/Float->Word8"
truncate = (fromIntegral :: Int -> Word8) . (truncate :: Float -> Int)
"floor/Float->Word8"
floor = (fromIntegral :: Int -> Word8) . (floor :: Float -> Int)
"ceiling/Float->Word8"
ceiling = (fromIntegral :: Int -> Word8) . (ceiling :: Float -> Int)
"round/Float->Word8"
round = (fromIntegral :: Int -> Word8) . (round :: Float -> Int)
#-}
# RULES
" properFraction / Double->(Word8,Double ) "
properFraction = \x - >
case properFraction x of {
( n , y ) - > ( ( fromIntegral : : Int - > Word8 ) n , y : : Double ) }
" truncate / Double->Word8 "
truncate = ( fromIntegral : : Int - > Word8 ) . ( truncate : : Double - > Int )
" floor / Double->Word8 "
floor = ( fromIntegral : : Int - > Word8 ) . ( floor : : Double - > Int )
" ceiling / Double->Word8 "
ceiling = ( fromIntegral : : Int - > Word8 ) . ( ceiling : : Double - > Int )
" round / Double->Word8 "
round = ( fromIntegral : : Int - > Word8 ) . ( round : : Double - > Int )
#
"properFraction/Double->(Word8,Double)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word8) n, y :: Double) }
"truncate/Double->Word8"
truncate = (fromIntegral :: Int -> Word8) . (truncate :: Double -> Int)
"floor/Double->Word8"
floor = (fromIntegral :: Int -> Word8) . (floor :: Double -> Int)
"ceiling/Double->Word8"
ceiling = (fromIntegral :: Int -> Word8) . (ceiling :: Double -> Int)
"round/Double->Word8"
round = (fromIntegral :: Int -> Word8) . (round :: Double -> Int)
#-}
------------------------------------------------------------------------
type Word16
------------------------------------------------------------------------
is represented in the same way as Word . Operations may assume
-- and must ensure that it holds only values from its logical range.
data {-# CTYPE "HsWord16" #-} Word16 = W16# Word#
^ 16 - bit unsigned integer type
-- See GHC.Classes#matching_overloaded_methods_in_rules
instance Eq Word16 where
(==) = eqWord16
(/=) = neWord16
eqWord16, neWord16 :: Word16 -> Word16 -> Bool
eqWord16 (W16# x) (W16# y) = isTrue# (x `eqWord#` y)
neWord16 (W16# x) (W16# y) = isTrue# (x `neWord#` y)
# INLINE [ 1 ] eqWord16 #
{-# INLINE [1] neWord16 #-}
instance Ord Word16 where
(<) = ltWord16
(<=) = leWord16
(>=) = geWord16
(>) = gtWord16
# INLINE [ 1 ] gtWord16 #
{-# INLINE [1] geWord16 #-}
# INLINE [ 1 ] ltWord16 #
{-# INLINE [1] leWord16 #-}
gtWord16, geWord16, ltWord16, leWord16 :: Word16 -> Word16 -> Bool
(W16# x) `gtWord16` (W16# y) = isTrue# (x `gtWord#` y)
(W16# x) `geWord16` (W16# y) = isTrue# (x `geWord#` y)
(W16# x) `ltWord16` (W16# y) = isTrue# (x `ltWord#` y)
(W16# x) `leWord16` (W16# y) = isTrue# (x `leWord#` y)
instance Show Word16 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Num Word16 where
(W16# x#) + (W16# y#) = W16# (narrow16Word# (x# `plusWord#` y#))
(W16# x#) - (W16# y#) = W16# (narrow16Word# (x# `minusWord#` y#))
(W16# x#) * (W16# y#) = W16# (narrow16Word# (x# `timesWord#` y#))
negate (W16# x#) = W16# (narrow16Word# (int2Word# (negateInt# (word2Int# x#))))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W16# (narrow16Word# (integerToWord i))
instance Real Word16 where
toRational x = toInteger x % 1
instance Enum Word16 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word16"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word16"
toEnum i@(I# i#)
| i >= 0 && i <= fromIntegral (maxBound::Word16)
= W16# (int2Word# i#)
| otherwise = toEnumError "Word16" i (minBound::Word16, maxBound::Word16)
fromEnum (W16# x#) = I# (word2Int# x#)
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Word16 where
quot (W16# x#) y@(W16# y#)
| y /= 0 = W16# (x# `quotWord#` y#)
| otherwise = divZeroError
rem (W16# x#) y@(W16# y#)
| y /= 0 = W16# (x# `remWord#` y#)
| otherwise = divZeroError
div (W16# x#) y@(W16# y#)
| y /= 0 = W16# (x# `quotWord#` y#)
| otherwise = divZeroError
mod (W16# x#) y@(W16# y#)
| y /= 0 = W16# (x# `remWord#` y#)
| otherwise = divZeroError
quotRem (W16# x#) y@(W16# y#)
| y /= 0 = case x# `quotRemWord#` y# of
(# q, r #) ->
(W16# q, W16# r)
| otherwise = divZeroError
divMod (W16# x#) y@(W16# y#)
| y /= 0 = (W16# (x# `quotWord#` y#), W16# (x# `remWord#` y#))
| otherwise = divZeroError
toInteger (W16# x#) = smallInteger (word2Int# x#)
instance Bounded Word16 where
minBound = 0
maxBound = 0xFFFF
instance Ix Word16 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
instance Read Word16 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
instance Bits Word16 where
{-# INLINE shift #-}
# INLINE bit #
# INLINE testBit #
(W16# x#) .&. (W16# y#) = W16# (x# `and#` y#)
(W16# x#) .|. (W16# y#) = W16# (x# `or#` y#)
(W16# x#) `xor` (W16# y#) = W16# (x# `xor#` y#)
complement (W16# x#) = W16# (x# `xor#` mb#)
where !(W16# mb#) = maxBound
(W16# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W16# (narrow16Word# (x# `shiftL#` i#))
| otherwise = W16# (x# `shiftRL#` negateInt# i#)
(W16# x#) `shiftL` (I# i#) = W16# (narrow16Word# (x# `shiftL#` i#))
(W16# x#) `unsafeShiftL` (I# i#) =
W16# (narrow16Word# (x# `uncheckedShiftL#` i#))
(W16# x#) `shiftR` (I# i#) = W16# (x# `shiftRL#` i#)
(W16# x#) `unsafeShiftR` (I# i#) = W16# (x# `uncheckedShiftRL#` i#)
(W16# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W16# x#
| otherwise = W16# (narrow16Word# ((x# `uncheckedShiftL#` i'#) `or#`
(x# `uncheckedShiftRL#` (16# -# i'#))))
where
!i'# = word2Int# (int2Word# i# `and#` 15##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W16# x#) = I# (word2Int# (popCnt16# x#))
bit = bitDefault
testBit = testBitDefault
instance FiniteBits Word16 where
finiteBitSize _ = 16
countLeadingZeros (W16# x#) = I# (word2Int# (clz16# x#))
countTrailingZeros (W16# x#) = I# (word2Int# (ctz16# x#))
| Swap bytes in ' Word16 ' .
--
-- @since 4.7.0.0
byteSwap16 :: Word16 -> Word16
byteSwap16 (W16# w#) = W16# (narrow16Word# (byteSwap16# w#))
# RULES
" fromIntegral / Word8->Word16 " fromIntegral = \(W8 # x # ) - > W16 # x #
" fromIntegral / Word16->Word16 " fromIntegral = i d : : Word16
" fromIntegral / Word16->Integer " fromIntegral = toInteger : : Integer
" fromIntegral / a->Word16 " fromIntegral = \x - > case fromIntegral x of W # x # - > W16 # ( narrow16Word # x # )
" fromIntegral / Word16->a " fromIntegral = \(W16 # x # ) - > fromIntegral ( W # x # )
#
"fromIntegral/Word8->Word16" fromIntegral = \(W8# x#) -> W16# x#
"fromIntegral/Word16->Word16" fromIntegral = id :: Word16 -> Word16
"fromIntegral/Word16->Integer" fromIntegral = toInteger :: Word16 -> Integer
"fromIntegral/a->Word16" fromIntegral = \x -> case fromIntegral x of W# x# -> W16# (narrow16Word# x#)
"fromIntegral/Word16->a" fromIntegral = \(W16# x#) -> fromIntegral (W# x#)
#-}
# RULES
" properFraction / Float->(Word16,Float ) "
properFraction = \x - >
case properFraction x of {
( n , y ) - > ( ( fromIntegral : : Int - > Word16 ) n , y : : Float ) }
" truncate / Float->Word16 "
truncate = ( fromIntegral : : Int - > Word16 ) . ( truncate : : Float - > Int )
" floor / Float->Word16 "
floor = ( fromIntegral : : Int - > Word16 ) . ( floor : : Float - > Int )
" ceiling / Float->Word16 "
ceiling = ( fromIntegral : : Int - > Word16 ) . ( ceiling : : Float - > Int )
" round / Float->Word16 "
round = ( fromIntegral : : Int - > Word16 ) . ( round : : Float - > Int )
#
"properFraction/Float->(Word16,Float)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word16) n, y :: Float) }
"truncate/Float->Word16"
truncate = (fromIntegral :: Int -> Word16) . (truncate :: Float -> Int)
"floor/Float->Word16"
floor = (fromIntegral :: Int -> Word16) . (floor :: Float -> Int)
"ceiling/Float->Word16"
ceiling = (fromIntegral :: Int -> Word16) . (ceiling :: Float -> Int)
"round/Float->Word16"
round = (fromIntegral :: Int -> Word16) . (round :: Float -> Int)
#-}
# RULES
" properFraction / Double->(Word16,Double ) "
properFraction = \x - >
case properFraction x of {
( n , y ) - > ( ( fromIntegral : : Int - > Word16 ) n , y : : Double ) }
" truncate / Double->Word16 "
truncate = ( fromIntegral : : Int - > Word16 ) . ( truncate : : Double - > Int )
" floor / Double->Word16 "
floor = ( fromIntegral : : Int - > Word16 ) . ( floor : : Double - > Int )
" ceiling / Double->Word16 "
ceiling = ( fromIntegral : : Int - > Word16 ) . ( ceiling : : Double - > Int )
" round / Double->Word16 "
round = ( fromIntegral : : Int - > Word16 ) . ( round : : Double - > Int )
#
"properFraction/Double->(Word16,Double)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word16) n, y :: Double) }
"truncate/Double->Word16"
truncate = (fromIntegral :: Int -> Word16) . (truncate :: Double -> Int)
"floor/Double->Word16"
floor = (fromIntegral :: Int -> Word16) . (floor :: Double -> Int)
"ceiling/Double->Word16"
ceiling = (fromIntegral :: Int -> Word16) . (ceiling :: Double -> Int)
"round/Double->Word16"
round = (fromIntegral :: Int -> Word16) . (round :: Double -> Int)
#-}
------------------------------------------------------------------------
type
------------------------------------------------------------------------
is represented in the same way as Word .
Operations may assume and must ensure that it holds only values
-- from its logical range.
We can use rewrite rules for the RealFrac methods
# RULES
" properFraction / Float->(Word32,Float ) "
properFraction = \x - >
case properFraction x of {
( n , y ) - > ( ( fromIntegral : : Int - > Word32 ) n , y : : Float ) }
" truncate / Float->Word32 "
truncate = ( fromIntegral : : Int - > Word32 ) . ( truncate : : Float - > Int )
" floor / Float->Word32 "
floor = ( fromIntegral : : Int - > Word32 ) . ( floor : : Float - > Int )
" ceiling / Float->Word32 "
ceiling = ( fromIntegral : : Int - > Word32 ) . ( ceiling : : Float - > Int )
" round / Float->Word32 "
round = ( fromIntegral : : Int - > Word32 ) . ( round : : Float - > Int )
#
"properFraction/Float->(Word32,Float)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word32) n, y :: Float) }
"truncate/Float->Word32"
truncate = (fromIntegral :: Int -> Word32) . (truncate :: Float -> Int)
"floor/Float->Word32"
floor = (fromIntegral :: Int -> Word32) . (floor :: Float -> Int)
"ceiling/Float->Word32"
ceiling = (fromIntegral :: Int -> Word32) . (ceiling :: Float -> Int)
"round/Float->Word32"
round = (fromIntegral :: Int -> Word32) . (round :: Float -> Int)
#-}
# RULES
" properFraction / Double->(Word32,Double ) "
properFraction = \x - >
case properFraction x of {
( n , y ) - > ( ( fromIntegral : : Int - > Word32 ) n , y : : Double ) }
" truncate / Double->Word32 "
truncate = ( fromIntegral : : Int - > Word32 ) . ( truncate : : Double - > Int )
" floor / Double->Word32 "
floor = ( fromIntegral : : Int - > Word32 ) . ( floor : : Double - > Int )
" ceiling / Double->Word32 "
ceiling = ( fromIntegral : : Int - > Word32 ) . ( ceiling : : Double - > Int )
" round / Double->Word32 "
round = ( fromIntegral : : Int - > Word32 ) . ( round : : Double - > Int )
#
"properFraction/Double->(Word32,Double)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word32) n, y :: Double) }
"truncate/Double->Word32"
truncate = (fromIntegral :: Int -> Word32) . (truncate :: Double -> Int)
"floor/Double->Word32"
floor = (fromIntegral :: Int -> Word32) . (floor :: Double -> Int)
"ceiling/Double->Word32"
ceiling = (fromIntegral :: Int -> Word32) . (ceiling :: Double -> Int)
"round/Double->Word32"
round = (fromIntegral :: Int -> Word32) . (round :: Double -> Int)
#-}
# CTYPE " HsWord32 " #
^ 32 - bit unsigned integer type
-- See GHC.Classes#matching_overloaded_methods_in_rules
instance Eq Word32 where
(==) = eqWord32
(/=) = neWord32
eqWord32, neWord32 :: Word32 -> Word32 -> Bool
eqWord32 (W32# x) (W32# y) = isTrue# (x `eqWord#` y)
neWord32 (W32# x) (W32# y) = isTrue# (x `neWord#` y)
# INLINE [ 1 ] eqWord32 #
{-# INLINE [1] neWord32 #-}
instance Ord Word32 where
(<) = ltWord32
(<=) = leWord32
(>=) = geWord32
(>) = gtWord32
{-# INLINE [1] gtWord32 #-}
{-# INLINE [1] geWord32 #-}
{-# INLINE [1] ltWord32 #-}
{-# INLINE [1] leWord32 #-}
gtWord32, geWord32, ltWord32, leWord32 :: Word32 -> Word32 -> Bool
(W32# x) `gtWord32` (W32# y) = isTrue# (x `gtWord#` y)
(W32# x) `geWord32` (W32# y) = isTrue# (x `geWord#` y)
(W32# x) `ltWord32` (W32# y) = isTrue# (x `ltWord#` y)
(W32# x) `leWord32` (W32# y) = isTrue# (x `leWord#` y)
instance Num Word32 where
(W32# x#) + (W32# y#) = W32# (narrow32Word# (x# `plusWord#` y#))
(W32# x#) - (W32# y#) = W32# (narrow32Word# (x# `minusWord#` y#))
(W32# x#) * (W32# y#) = W32# (narrow32Word# (x# `timesWord#` y#))
negate (W32# x#) = W32# (narrow32Word# (int2Word# (negateInt# (word2Int# x#))))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W32# (narrow32Word# (integerToWord i))
instance Enum Word32 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word32"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word32"
toEnum i@(I# i#)
| i >= 0
&& i <= fromIntegral (maxBound::Word32)
= W32# (int2Word# i#)
| otherwise = toEnumError "Word32" i (minBound::Word32, maxBound::Word32)
fromEnum (W32# x#) = I# (word2Int# x#)
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Word32 where
quot (W32# x#) y@(W32# y#)
| y /= 0 = W32# (x# `quotWord#` y#)
| otherwise = divZeroError
rem (W32# x#) y@(W32# y#)
| y /= 0 = W32# (x# `remWord#` y#)
| otherwise = divZeroError
div (W32# x#) y@(W32# y#)
| y /= 0 = W32# (x# `quotWord#` y#)
| otherwise = divZeroError
mod (W32# x#) y@(W32# y#)
| y /= 0 = W32# (x# `remWord#` y#)
| otherwise = divZeroError
quotRem (W32# x#) y@(W32# y#)
| y /= 0 = case x# `quotRemWord#` y# of
(# q, r #) ->
(W32# q, W32# r)
| otherwise = divZeroError
divMod (W32# x#) y@(W32# y#)
| y /= 0 = (W32# (x# `quotWord#` y#), W32# (x# `remWord#` y#))
| otherwise = divZeroError
toInteger (W32# x#)
= smallInteger (word2Int# x#)
instance Bits Word32 where
{-# INLINE shift #-}
# INLINE bit #
# INLINE testBit #
(W32# x#) .&. (W32# y#) = W32# (x# `and#` y#)
(W32# x#) .|. (W32# y#) = W32# (x# `or#` y#)
(W32# x#) `xor` (W32# y#) = W32# (x# `xor#` y#)
complement (W32# x#) = W32# (x# `xor#` mb#)
where !(W32# mb#) = maxBound
(W32# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W32# (narrow32Word# (x# `shiftL#` i#))
| otherwise = W32# (x# `shiftRL#` negateInt# i#)
(W32# x#) `shiftL` (I# i#) = W32# (narrow32Word# (x# `shiftL#` i#))
(W32# x#) `unsafeShiftL` (I# i#) =
W32# (narrow32Word# (x# `uncheckedShiftL#` i#))
(W32# x#) `shiftR` (I# i#) = W32# (x# `shiftRL#` i#)
(W32# x#) `unsafeShiftR` (I# i#) = W32# (x# `uncheckedShiftRL#` i#)
(W32# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W32# x#
| otherwise = W32# (narrow32Word# ((x# `uncheckedShiftL#` i'#) `or#`
(x# `uncheckedShiftRL#` (32# -# i'#))))
where
!i'# = word2Int# (int2Word# i# `and#` 31##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W32# x#) = I# (word2Int# (popCnt32# x#))
bit = bitDefault
testBit = testBitDefault
instance FiniteBits Word32 where
finiteBitSize _ = 32
countLeadingZeros (W32# x#) = I# (word2Int# (clz32# x#))
countTrailingZeros (W32# x#) = I# (word2Int# (ctz32# x#))
# RULES
" fromIntegral / Word8->Word32 " fromIntegral = \(W8 # x # ) - > W32 # x #
" fromIntegral / Word16->Word32 " fromIntegral = \(W16 # x # ) - > W32 # x #
" fromIntegral / Word32->Word32 " fromIntegral = i d : : Word32
" fromIntegral / Word32->Integer " fromIntegral = toInteger : : Integer
" fromIntegral / a->Word32 " fromIntegral = \x - > case fromIntegral x of W # x # - > W32 # ( narrow32Word # x # )
" fromIntegral / Word32->a " fromIntegral = \(W32 # x # ) - > fromIntegral ( W # x # )
#
"fromIntegral/Word8->Word32" fromIntegral = \(W8# x#) -> W32# x#
"fromIntegral/Word16->Word32" fromIntegral = \(W16# x#) -> W32# x#
"fromIntegral/Word32->Word32" fromIntegral = id :: Word32 -> Word32
"fromIntegral/Word32->Integer" fromIntegral = toInteger :: Word32 -> Integer
"fromIntegral/a->Word32" fromIntegral = \x -> case fromIntegral x of W# x# -> W32# (narrow32Word# x#)
"fromIntegral/Word32->a" fromIntegral = \(W32# x#) -> fromIntegral (W# x#)
#-}
instance Show Word32 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Real Word32 where
toRational x = toInteger x % 1
instance Bounded Word32 where
minBound = 0
maxBound = 0xFFFFFFFF
instance Ix Word32 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
instance Read Word32 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
| Reverse order of bytes in ' ' .
--
-- @since 4.7.0.0
byteSwap32 :: Word32 -> Word32
byteSwap32 (W32# w#) = W32# (narrow32Word# (byteSwap32# w#))
------------------------------------------------------------------------
-- type Word64
------------------------------------------------------------------------
Word64 is represented in the same way as Word .
Operations may assume and must ensure that it holds only values
-- from its logical range.
data {-# CTYPE "HsWord64" #-} Word64 = W64# Word#
^ 64 - bit unsigned integer type
-- See GHC.Classes#matching_overloaded_methods_in_rules
instance Eq Word64 where
(==) = eqWord64
(/=) = neWord64
eqWord64, neWord64 :: Word64 -> Word64 -> Bool
eqWord64 (W64# x) (W64# y) = isTrue# (x `eqWord#` y)
neWord64 (W64# x) (W64# y) = isTrue# (x `neWord#` y)
# INLINE [ 1 ] eqWord64 #
{-# INLINE [1] neWord64 #-}
instance Ord Word64 where
(<) = ltWord64
(<=) = leWord64
(>=) = geWord64
(>) = gtWord64
# INLINE [ 1 ] gtWord64 #
{-# INLINE [1] geWord64 #-}
{-# INLINE [1] ltWord64 #-}
# INLINE [ 1 ] leWord64 #
gtWord64, geWord64, ltWord64, leWord64 :: Word64 -> Word64 -> Bool
(W64# x) `gtWord64` (W64# y) = isTrue# (x `gtWord#` y)
(W64# x) `geWord64` (W64# y) = isTrue# (x `geWord#` y)
(W64# x) `ltWord64` (W64# y) = isTrue# (x `ltWord#` y)
(W64# x) `leWord64` (W64# y) = isTrue# (x `leWord#` y)
instance Num Word64 where
(W64# x#) + (W64# y#) = W64# (x# `plusWord#` y#)
(W64# x#) - (W64# y#) = W64# (x# `minusWord#` y#)
(W64# x#) * (W64# y#) = W64# (x# `timesWord#` y#)
negate (W64# x#) = W64# (int2Word# (negateInt# (word2Int# x#)))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W64# (integerToWord i)
instance Enum Word64 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word64"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word64"
toEnum i@(I# i#)
| i >= 0 = W64# (int2Word# i#)
| otherwise = toEnumError "Word64" i (minBound::Word64, maxBound::Word64)
fromEnum x@(W64# x#)
| x <= fromIntegral (maxBound::Int)
= I# (word2Int# x#)
| otherwise = fromEnumError "Word64" x
enumFrom = integralEnumFrom
enumFromThen = integralEnumFromThen
enumFromTo = integralEnumFromTo
enumFromThenTo = integralEnumFromThenTo
instance Integral Word64 where
quot (W64# x#) y@(W64# y#)
| y /= 0 = W64# (x# `quotWord#` y#)
| otherwise = divZeroError
rem (W64# x#) y@(W64# y#)
| y /= 0 = W64# (x# `remWord#` y#)
| otherwise = divZeroError
div (W64# x#) y@(W64# y#)
| y /= 0 = W64# (x# `quotWord#` y#)
| otherwise = divZeroError
mod (W64# x#) y@(W64# y#)
| y /= 0 = W64# (x# `remWord#` y#)
| otherwise = divZeroError
quotRem (W64# x#) y@(W64# y#)
| y /= 0 = case x# `quotRemWord#` y# of
(# q, r #) ->
(W64# q, W64# r)
| otherwise = divZeroError
divMod (W64# x#) y@(W64# y#)
| y /= 0 = (W64# (x# `quotWord#` y#), W64# (x# `remWord#` y#))
| otherwise = divZeroError
toInteger (W64# x#)
| isTrue# (i# >=# 0#) = smallInteger i#
| otherwise = wordToInteger x#
where
!i# = word2Int# x#
instance Bits Word64 where
{-# INLINE shift #-}
# INLINE bit #
# INLINE testBit #
(W64# x#) .&. (W64# y#) = W64# (x# `and#` y#)
(W64# x#) .|. (W64# y#) = W64# (x# `or#` y#)
(W64# x#) `xor` (W64# y#) = W64# (x# `xor#` y#)
complement (W64# x#) = W64# (x# `xor#` mb#)
where !(W64# mb#) = maxBound
(W64# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W64# (x# `shiftL#` i#)
| otherwise = W64# (x# `shiftRL#` negateInt# i#)
(W64# x#) `shiftL` (I# i#) = W64# (x# `shiftL#` i#)
(W64# x#) `unsafeShiftL` (I# i#) = W64# (x# `uncheckedShiftL#` i#)
(W64# x#) `shiftR` (I# i#) = W64# (x# `shiftRL#` i#)
(W64# x#) `unsafeShiftR` (I# i#) = W64# (x# `uncheckedShiftRL#` i#)
(W64# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W64# x#
| otherwise = W64# ((x# `uncheckedShiftL#` i'#) `or#`
(x# `uncheckedShiftRL#` (64# -# i'#)))
where
!i'# = word2Int# (int2Word# i# `and#` 63##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W64# x#) = I# (word2Int# (popCnt64# x#))
bit = bitDefault
testBit = testBitDefault
# RULES
" fromIntegral / a->Word64 " fromIntegral = \x - > case fromIntegral x of W # x # - > W64 # x #
" fromIntegral / Word64->a " fromIntegral = \(W64 # x # ) - > fromIntegral ( W # x # )
#
"fromIntegral/a->Word64" fromIntegral = \x -> case fromIntegral x of W# x# -> W64# x#
"fromIntegral/Word64->a" fromIntegral = \(W64# x#) -> fromIntegral (W# x#)
#-}
uncheckedShiftL64# :: Word# -> Int# -> Word#
uncheckedShiftL64# = uncheckedShiftL#
uncheckedShiftRL64# :: Word# -> Int# -> Word#
uncheckedShiftRL64# = uncheckedShiftRL#
instance FiniteBits Word64 where
finiteBitSize _ = 64
countLeadingZeros (W64# x#) = I# (word2Int# (clz64# x#))
countTrailingZeros (W64# x#) = I# (word2Int# (ctz64# x#))
instance Show Word64 where
showsPrec p x = showsPrec p (toInteger x)
instance Real Word64 where
toRational x = toInteger x % 1
instance Bounded Word64 where
minBound = 0
maxBound = 0xFFFFFFFFFFFFFFFF
instance Ix Word64 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
instance Read Word64 where
readsPrec p s = [(fromInteger x, r) | (x, r) <- readsPrec p s]
-- | Reverse order of bytes in 'Word64'.
--
-- @since 4.7.0.0
byteSwap64 :: Word64 -> Word64
byteSwap64 (W64# w#) = W64# (byteSwap# w#)
| null | https://raw.githubusercontent.com/fragnix/fragnix/b9969e9c6366e2917a782f3ac4e77cce0835448b/builtins/base/GHC.Word.hs | haskell | # LINE 1 "GHC.Word.hs" #
# OPTIONS_HADDOCK hide #
---------------------------------------------------------------------------
|
Module : GHC.Word
License : see libraries/base/LICENSE
Maintainer :
Stability : internal
'Word64'.
---------------------------------------------------------------------------
* Shifts
* Equality operators
| See GHC.Classes#matching_overloaded_methods_in_rules
----------------------------------------------------------------------
type Word8
----------------------------------------------------------------------
and must ensure that it holds only values from its logical range.
# CTYPE "HsWord8" #
See GHC.Classes#matching_overloaded_methods_in_rules
# INLINE [1] neWord8 #
# INLINE [1] gtWord8 #
# INLINE [1] geWord8 #
# INLINE [1] leWord8 #
# INLINE shift #
----------------------------------------------------------------------
----------------------------------------------------------------------
and must ensure that it holds only values from its logical range.
# CTYPE "HsWord16" #
See GHC.Classes#matching_overloaded_methods_in_rules
# INLINE [1] neWord16 #
# INLINE [1] geWord16 #
# INLINE [1] leWord16 #
# INLINE shift #
@since 4.7.0.0
----------------------------------------------------------------------
----------------------------------------------------------------------
from its logical range.
See GHC.Classes#matching_overloaded_methods_in_rules
# INLINE [1] neWord32 #
# INLINE [1] gtWord32 #
# INLINE [1] geWord32 #
# INLINE [1] ltWord32 #
# INLINE [1] leWord32 #
# INLINE shift #
@since 4.7.0.0
----------------------------------------------------------------------
type Word64
----------------------------------------------------------------------
from its logical range.
# CTYPE "HsWord64" #
See GHC.Classes#matching_overloaded_methods_in_rules
# INLINE [1] neWord64 #
# INLINE [1] geWord64 #
# INLINE [1] ltWord64 #
# INLINE shift #
| Reverse order of bytes in 'Word64'.
@since 4.7.0.0 |
# LANGUAGE Trustworthy #
# LANGUAGE CPP , NoImplicitPrelude , BangPatterns , MagicHash , UnboxedTuples #
Copyright : ( c ) The University of Glasgow , 1997 - 2002
Portability : non - portable ( GHC Extensions )
Sized unsigned integral types : ' Word ' , ' Word8 ' , ' Word16 ' , ' ' , and
module GHC.Word (
Word(..), Word8(..), Word16(..), Word32(..), Word64(..),
uncheckedShiftL64#,
uncheckedShiftRL64#,
* Byte swapping
byteSwap16,
byteSwap32,
byteSwap64,
eqWord, neWord, gtWord, geWord, ltWord, leWord,
eqWord8, neWord8, gtWord8, geWord8, ltWord8, leWord8,
eqWord16, neWord16, gtWord16, geWord16, ltWord16, leWord16,
eqWord32, neWord32, gtWord32, geWord32, ltWord32, leWord32,
eqWord64, neWord64, gtWord64, geWord64, ltWord64, leWord64
) where
import Data.Bits
import Data.Maybe
import GHC.Base
import GHC.Enum
import GHC.Num
import GHC.Real
import GHC.Read
import GHC.Arr
import GHC.Show
Word8 is represented in the same way as Word . Operations may assume
^ 8 - bit unsigned integer type
instance Eq Word8 where
(==) = eqWord8
(/=) = neWord8
eqWord8, neWord8 :: Word8 -> Word8 -> Bool
eqWord8 (W8# x) (W8# y) = isTrue# (x `eqWord#` y)
neWord8 (W8# x) (W8# y) = isTrue# (x `neWord#` y)
# INLINE [ 1 ] eqWord8 #
instance Ord Word8 where
(<) = ltWord8
(<=) = leWord8
(>=) = geWord8
(>) = gtWord8
# INLINE [ 1 ] ltWord8 #
gtWord8, geWord8, ltWord8, leWord8 :: Word8 -> Word8 -> Bool
(W8# x) `gtWord8` (W8# y) = isTrue# (x `gtWord#` y)
(W8# x) `geWord8` (W8# y) = isTrue# (x `geWord#` y)
(W8# x) `ltWord8` (W8# y) = isTrue# (x `ltWord#` y)
(W8# x) `leWord8` (W8# y) = isTrue# (x `leWord#` y)
instance Show Word8 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Num Word8 where
(W8# x#) + (W8# y#) = W8# (narrow8Word# (x# `plusWord#` y#))
(W8# x#) - (W8# y#) = W8# (narrow8Word# (x# `minusWord#` y#))
(W8# x#) * (W8# y#) = W8# (narrow8Word# (x# `timesWord#` y#))
negate (W8# x#) = W8# (narrow8Word# (int2Word# (negateInt# (word2Int# x#))))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W8# (narrow8Word# (integerToWord i))
instance Real Word8 where
toRational x = toInteger x % 1
instance Enum Word8 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word8"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word8"
toEnum i@(I# i#)
| i >= 0 && i <= fromIntegral (maxBound::Word8)
= W8# (int2Word# i#)
| otherwise = toEnumError "Word8" i (minBound::Word8, maxBound::Word8)
fromEnum (W8# x#) = I# (word2Int# x#)
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Word8 where
quot (W8# x#) y@(W8# y#)
| y /= 0 = W8# (x# `quotWord#` y#)
| otherwise = divZeroError
rem (W8# x#) y@(W8# y#)
| y /= 0 = W8# (x# `remWord#` y#)
| otherwise = divZeroError
div (W8# x#) y@(W8# y#)
| y /= 0 = W8# (x# `quotWord#` y#)
| otherwise = divZeroError
mod (W8# x#) y@(W8# y#)
| y /= 0 = W8# (x# `remWord#` y#)
| otherwise = divZeroError
quotRem (W8# x#) y@(W8# y#)
| y /= 0 = case x# `quotRemWord#` y# of
(# q, r #) ->
(W8# q, W8# r)
| otherwise = divZeroError
divMod (W8# x#) y@(W8# y#)
| y /= 0 = (W8# (x# `quotWord#` y#), W8# (x# `remWord#` y#))
| otherwise = divZeroError
toInteger (W8# x#) = smallInteger (word2Int# x#)
instance Bounded Word8 where
minBound = 0
maxBound = 0xFF
instance Ix Word8 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
instance Read Word8 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
instance Bits Word8 where
# INLINE bit #
# INLINE testBit #
(W8# x#) .&. (W8# y#) = W8# (x# `and#` y#)
(W8# x#) .|. (W8# y#) = W8# (x# `or#` y#)
(W8# x#) `xor` (W8# y#) = W8# (x# `xor#` y#)
complement (W8# x#) = W8# (x# `xor#` mb#)
where !(W8# mb#) = maxBound
(W8# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W8# (narrow8Word# (x# `shiftL#` i#))
| otherwise = W8# (x# `shiftRL#` negateInt# i#)
(W8# x#) `shiftL` (I# i#) = W8# (narrow8Word# (x# `shiftL#` i#))
(W8# x#) `unsafeShiftL` (I# i#) =
W8# (narrow8Word# (x# `uncheckedShiftL#` i#))
(W8# x#) `shiftR` (I# i#) = W8# (x# `shiftRL#` i#)
(W8# x#) `unsafeShiftR` (I# i#) = W8# (x# `uncheckedShiftRL#` i#)
(W8# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W8# x#
| otherwise = W8# (narrow8Word# ((x# `uncheckedShiftL#` i'#) `or#`
(x# `uncheckedShiftRL#` (8# -# i'#))))
where
!i'# = word2Int# (int2Word# i# `and#` 7##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W8# x#) = I# (word2Int# (popCnt8# x#))
bit = bitDefault
testBit = testBitDefault
instance FiniteBits Word8 where
finiteBitSize _ = 8
countLeadingZeros (W8# x#) = I# (word2Int# (clz8# x#))
countTrailingZeros (W8# x#) = I# (word2Int# (ctz8# x#))
# RULES
" fromIntegral / Word8->Word8 " fromIntegral = i d : : Word8 - > Word8
" fromIntegral / Word8->Integer " fromIntegral = toInteger : : Word8 - > Integer
" fromIntegral / a->Word8 " fromIntegral = \x - > case fromIntegral x of W # x # - > W8 # ( narrow8Word # x # )
" fromIntegral / Word8->a " fromIntegral = \(W8 # x # ) - > fromIntegral ( W # x # )
#
"fromIntegral/Word8->Word8" fromIntegral = id :: Word8 -> Word8
"fromIntegral/Word8->Integer" fromIntegral = toInteger :: Word8 -> Integer
"fromIntegral/a->Word8" fromIntegral = \x -> case fromIntegral x of W# x# -> W8# (narrow8Word# x#)
"fromIntegral/Word8->a" fromIntegral = \(W8# x#) -> fromIntegral (W# x#)
#-}
# RULES
" properFraction / Float->(Word8,Float ) "
properFraction = \x - >
case properFraction x of {
( n , y ) - > ( ( fromIntegral : : Int - > Word8 ) n , y : : Float ) }
" truncate / Float->Word8 "
truncate = ( fromIntegral : : Int - > Word8 ) . ( truncate : : Float - > Int )
" floor / Float->Word8 "
floor = ( fromIntegral : : Int - > Word8 ) . ( floor : : Float - > Int )
" ceiling / Float->Word8 "
ceiling = ( fromIntegral : : Int - > Word8 ) . ( ceiling : : Float - > Int )
" round / Float->Word8 "
round = ( fromIntegral : : Int - > Word8 ) . ( round : : Float - > Int )
#
"properFraction/Float->(Word8,Float)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word8) n, y :: Float) }
"truncate/Float->Word8"
truncate = (fromIntegral :: Int -> Word8) . (truncate :: Float -> Int)
"floor/Float->Word8"
floor = (fromIntegral :: Int -> Word8) . (floor :: Float -> Int)
"ceiling/Float->Word8"
ceiling = (fromIntegral :: Int -> Word8) . (ceiling :: Float -> Int)
"round/Float->Word8"
round = (fromIntegral :: Int -> Word8) . (round :: Float -> Int)
#-}
# RULES
" properFraction / Double->(Word8,Double ) "
properFraction = \x - >
case properFraction x of {
( n , y ) - > ( ( fromIntegral : : Int - > Word8 ) n , y : : Double ) }
" truncate / Double->Word8 "
truncate = ( fromIntegral : : Int - > Word8 ) . ( truncate : : Double - > Int )
" floor / Double->Word8 "
floor = ( fromIntegral : : Int - > Word8 ) . ( floor : : Double - > Int )
" ceiling / Double->Word8 "
ceiling = ( fromIntegral : : Int - > Word8 ) . ( ceiling : : Double - > Int )
" round / Double->Word8 "
round = ( fromIntegral : : Int - > Word8 ) . ( round : : Double - > Int )
#
"properFraction/Double->(Word8,Double)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word8) n, y :: Double) }
"truncate/Double->Word8"
truncate = (fromIntegral :: Int -> Word8) . (truncate :: Double -> Int)
"floor/Double->Word8"
floor = (fromIntegral :: Int -> Word8) . (floor :: Double -> Int)
"ceiling/Double->Word8"
ceiling = (fromIntegral :: Int -> Word8) . (ceiling :: Double -> Int)
"round/Double->Word8"
round = (fromIntegral :: Int -> Word8) . (round :: Double -> Int)
#-}
type Word16
is represented in the same way as Word . Operations may assume
^ 16 - bit unsigned integer type
instance Eq Word16 where
(==) = eqWord16
(/=) = neWord16
eqWord16, neWord16 :: Word16 -> Word16 -> Bool
eqWord16 (W16# x) (W16# y) = isTrue# (x `eqWord#` y)
neWord16 (W16# x) (W16# y) = isTrue# (x `neWord#` y)
# INLINE [ 1 ] eqWord16 #
instance Ord Word16 where
(<) = ltWord16
(<=) = leWord16
(>=) = geWord16
(>) = gtWord16
# INLINE [ 1 ] gtWord16 #
# INLINE [ 1 ] ltWord16 #
gtWord16, geWord16, ltWord16, leWord16 :: Word16 -> Word16 -> Bool
(W16# x) `gtWord16` (W16# y) = isTrue# (x `gtWord#` y)
(W16# x) `geWord16` (W16# y) = isTrue# (x `geWord#` y)
(W16# x) `ltWord16` (W16# y) = isTrue# (x `ltWord#` y)
(W16# x) `leWord16` (W16# y) = isTrue# (x `leWord#` y)
instance Show Word16 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Num Word16 where
(W16# x#) + (W16# y#) = W16# (narrow16Word# (x# `plusWord#` y#))
(W16# x#) - (W16# y#) = W16# (narrow16Word# (x# `minusWord#` y#))
(W16# x#) * (W16# y#) = W16# (narrow16Word# (x# `timesWord#` y#))
negate (W16# x#) = W16# (narrow16Word# (int2Word# (negateInt# (word2Int# x#))))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W16# (narrow16Word# (integerToWord i))
instance Real Word16 where
toRational x = toInteger x % 1
instance Enum Word16 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word16"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word16"
toEnum i@(I# i#)
| i >= 0 && i <= fromIntegral (maxBound::Word16)
= W16# (int2Word# i#)
| otherwise = toEnumError "Word16" i (minBound::Word16, maxBound::Word16)
fromEnum (W16# x#) = I# (word2Int# x#)
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Word16 where
quot (W16# x#) y@(W16# y#)
| y /= 0 = W16# (x# `quotWord#` y#)
| otherwise = divZeroError
rem (W16# x#) y@(W16# y#)
| y /= 0 = W16# (x# `remWord#` y#)
| otherwise = divZeroError
div (W16# x#) y@(W16# y#)
| y /= 0 = W16# (x# `quotWord#` y#)
| otherwise = divZeroError
mod (W16# x#) y@(W16# y#)
| y /= 0 = W16# (x# `remWord#` y#)
| otherwise = divZeroError
quotRem (W16# x#) y@(W16# y#)
| y /= 0 = case x# `quotRemWord#` y# of
(# q, r #) ->
(W16# q, W16# r)
| otherwise = divZeroError
divMod (W16# x#) y@(W16# y#)
| y /= 0 = (W16# (x# `quotWord#` y#), W16# (x# `remWord#` y#))
| otherwise = divZeroError
toInteger (W16# x#) = smallInteger (word2Int# x#)
instance Bounded Word16 where
minBound = 0
maxBound = 0xFFFF
instance Ix Word16 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
instance Read Word16 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
instance Bits Word16 where
# INLINE bit #
# INLINE testBit #
(W16# x#) .&. (W16# y#) = W16# (x# `and#` y#)
(W16# x#) .|. (W16# y#) = W16# (x# `or#` y#)
(W16# x#) `xor` (W16# y#) = W16# (x# `xor#` y#)
complement (W16# x#) = W16# (x# `xor#` mb#)
where !(W16# mb#) = maxBound
(W16# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W16# (narrow16Word# (x# `shiftL#` i#))
| otherwise = W16# (x# `shiftRL#` negateInt# i#)
(W16# x#) `shiftL` (I# i#) = W16# (narrow16Word# (x# `shiftL#` i#))
(W16# x#) `unsafeShiftL` (I# i#) =
W16# (narrow16Word# (x# `uncheckedShiftL#` i#))
(W16# x#) `shiftR` (I# i#) = W16# (x# `shiftRL#` i#)
(W16# x#) `unsafeShiftR` (I# i#) = W16# (x# `uncheckedShiftRL#` i#)
(W16# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W16# x#
| otherwise = W16# (narrow16Word# ((x# `uncheckedShiftL#` i'#) `or#`
(x# `uncheckedShiftRL#` (16# -# i'#))))
where
!i'# = word2Int# (int2Word# i# `and#` 15##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W16# x#) = I# (word2Int# (popCnt16# x#))
bit = bitDefault
testBit = testBitDefault
instance FiniteBits Word16 where
finiteBitSize _ = 16
countLeadingZeros (W16# x#) = I# (word2Int# (clz16# x#))
countTrailingZeros (W16# x#) = I# (word2Int# (ctz16# x#))
| Swap bytes in ' Word16 ' .
byteSwap16 :: Word16 -> Word16
byteSwap16 (W16# w#) = W16# (narrow16Word# (byteSwap16# w#))
# RULES
" fromIntegral / Word8->Word16 " fromIntegral = \(W8 # x # ) - > W16 # x #
" fromIntegral / Word16->Word16 " fromIntegral = i d : : Word16
" fromIntegral / Word16->Integer " fromIntegral = toInteger : : Integer
" fromIntegral / a->Word16 " fromIntegral = \x - > case fromIntegral x of W # x # - > W16 # ( narrow16Word # x # )
" fromIntegral / Word16->a " fromIntegral = \(W16 # x # ) - > fromIntegral ( W # x # )
#
"fromIntegral/Word8->Word16" fromIntegral = \(W8# x#) -> W16# x#
"fromIntegral/Word16->Word16" fromIntegral = id :: Word16 -> Word16
"fromIntegral/Word16->Integer" fromIntegral = toInteger :: Word16 -> Integer
"fromIntegral/a->Word16" fromIntegral = \x -> case fromIntegral x of W# x# -> W16# (narrow16Word# x#)
"fromIntegral/Word16->a" fromIntegral = \(W16# x#) -> fromIntegral (W# x#)
#-}
# RULES
" properFraction / Float->(Word16,Float ) "
properFraction = \x - >
case properFraction x of {
( n , y ) - > ( ( fromIntegral : : Int - > Word16 ) n , y : : Float ) }
" truncate / Float->Word16 "
truncate = ( fromIntegral : : Int - > Word16 ) . ( truncate : : Float - > Int )
" floor / Float->Word16 "
floor = ( fromIntegral : : Int - > Word16 ) . ( floor : : Float - > Int )
" ceiling / Float->Word16 "
ceiling = ( fromIntegral : : Int - > Word16 ) . ( ceiling : : Float - > Int )
" round / Float->Word16 "
round = ( fromIntegral : : Int - > Word16 ) . ( round : : Float - > Int )
#
"properFraction/Float->(Word16,Float)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word16) n, y :: Float) }
"truncate/Float->Word16"
truncate = (fromIntegral :: Int -> Word16) . (truncate :: Float -> Int)
"floor/Float->Word16"
floor = (fromIntegral :: Int -> Word16) . (floor :: Float -> Int)
"ceiling/Float->Word16"
ceiling = (fromIntegral :: Int -> Word16) . (ceiling :: Float -> Int)
"round/Float->Word16"
round = (fromIntegral :: Int -> Word16) . (round :: Float -> Int)
#-}
# RULES
" properFraction / Double->(Word16,Double ) "
properFraction = \x - >
case properFraction x of {
( n , y ) - > ( ( fromIntegral : : Int - > Word16 ) n , y : : Double ) }
" truncate / Double->Word16 "
truncate = ( fromIntegral : : Int - > Word16 ) . ( truncate : : Double - > Int )
" floor / Double->Word16 "
floor = ( fromIntegral : : Int - > Word16 ) . ( floor : : Double - > Int )
" ceiling / Double->Word16 "
ceiling = ( fromIntegral : : Int - > Word16 ) . ( ceiling : : Double - > Int )
" round / Double->Word16 "
round = ( fromIntegral : : Int - > Word16 ) . ( round : : Double - > Int )
#
"properFraction/Double->(Word16,Double)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word16) n, y :: Double) }
"truncate/Double->Word16"
truncate = (fromIntegral :: Int -> Word16) . (truncate :: Double -> Int)
"floor/Double->Word16"
floor = (fromIntegral :: Int -> Word16) . (floor :: Double -> Int)
"ceiling/Double->Word16"
ceiling = (fromIntegral :: Int -> Word16) . (ceiling :: Double -> Int)
"round/Double->Word16"
round = (fromIntegral :: Int -> Word16) . (round :: Double -> Int)
#-}
type
is represented in the same way as Word .
Operations may assume and must ensure that it holds only values
We can use rewrite rules for the RealFrac methods
# RULES
" properFraction / Float->(Word32,Float ) "
properFraction = \x - >
case properFraction x of {
( n , y ) - > ( ( fromIntegral : : Int - > Word32 ) n , y : : Float ) }
" truncate / Float->Word32 "
truncate = ( fromIntegral : : Int - > Word32 ) . ( truncate : : Float - > Int )
" floor / Float->Word32 "
floor = ( fromIntegral : : Int - > Word32 ) . ( floor : : Float - > Int )
" ceiling / Float->Word32 "
ceiling = ( fromIntegral : : Int - > Word32 ) . ( ceiling : : Float - > Int )
" round / Float->Word32 "
round = ( fromIntegral : : Int - > Word32 ) . ( round : : Float - > Int )
#
"properFraction/Float->(Word32,Float)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word32) n, y :: Float) }
"truncate/Float->Word32"
truncate = (fromIntegral :: Int -> Word32) . (truncate :: Float -> Int)
"floor/Float->Word32"
floor = (fromIntegral :: Int -> Word32) . (floor :: Float -> Int)
"ceiling/Float->Word32"
ceiling = (fromIntegral :: Int -> Word32) . (ceiling :: Float -> Int)
"round/Float->Word32"
round = (fromIntegral :: Int -> Word32) . (round :: Float -> Int)
#-}
# RULES
" properFraction / Double->(Word32,Double ) "
properFraction = \x - >
case properFraction x of {
( n , y ) - > ( ( fromIntegral : : Int - > Word32 ) n , y : : Double ) }
" truncate / Double->Word32 "
truncate = ( fromIntegral : : Int - > Word32 ) . ( truncate : : Double - > Int )
" floor / Double->Word32 "
floor = ( fromIntegral : : Int - > Word32 ) . ( floor : : Double - > Int )
" ceiling / Double->Word32 "
ceiling = ( fromIntegral : : Int - > Word32 ) . ( ceiling : : Double - > Int )
" round / Double->Word32 "
round = ( fromIntegral : : Int - > Word32 ) . ( round : : Double - > Int )
#
"properFraction/Double->(Word32,Double)"
properFraction = \x ->
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word32) n, y :: Double) }
"truncate/Double->Word32"
truncate = (fromIntegral :: Int -> Word32) . (truncate :: Double -> Int)
"floor/Double->Word32"
floor = (fromIntegral :: Int -> Word32) . (floor :: Double -> Int)
"ceiling/Double->Word32"
ceiling = (fromIntegral :: Int -> Word32) . (ceiling :: Double -> Int)
"round/Double->Word32"
round = (fromIntegral :: Int -> Word32) . (round :: Double -> Int)
#-}
# CTYPE " HsWord32 " #
^ 32 - bit unsigned integer type
instance Eq Word32 where
(==) = eqWord32
(/=) = neWord32
eqWord32, neWord32 :: Word32 -> Word32 -> Bool
eqWord32 (W32# x) (W32# y) = isTrue# (x `eqWord#` y)
neWord32 (W32# x) (W32# y) = isTrue# (x `neWord#` y)
# INLINE [ 1 ] eqWord32 #
instance Ord Word32 where
(<) = ltWord32
(<=) = leWord32
(>=) = geWord32
(>) = gtWord32
gtWord32, geWord32, ltWord32, leWord32 :: Word32 -> Word32 -> Bool
(W32# x) `gtWord32` (W32# y) = isTrue# (x `gtWord#` y)
(W32# x) `geWord32` (W32# y) = isTrue# (x `geWord#` y)
(W32# x) `ltWord32` (W32# y) = isTrue# (x `ltWord#` y)
(W32# x) `leWord32` (W32# y) = isTrue# (x `leWord#` y)
instance Num Word32 where
(W32# x#) + (W32# y#) = W32# (narrow32Word# (x# `plusWord#` y#))
(W32# x#) - (W32# y#) = W32# (narrow32Word# (x# `minusWord#` y#))
(W32# x#) * (W32# y#) = W32# (narrow32Word# (x# `timesWord#` y#))
negate (W32# x#) = W32# (narrow32Word# (int2Word# (negateInt# (word2Int# x#))))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W32# (narrow32Word# (integerToWord i))
instance Enum Word32 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word32"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word32"
toEnum i@(I# i#)
| i >= 0
&& i <= fromIntegral (maxBound::Word32)
= W32# (int2Word# i#)
| otherwise = toEnumError "Word32" i (minBound::Word32, maxBound::Word32)
fromEnum (W32# x#) = I# (word2Int# x#)
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Word32 where
quot (W32# x#) y@(W32# y#)
| y /= 0 = W32# (x# `quotWord#` y#)
| otherwise = divZeroError
rem (W32# x#) y@(W32# y#)
| y /= 0 = W32# (x# `remWord#` y#)
| otherwise = divZeroError
div (W32# x#) y@(W32# y#)
| y /= 0 = W32# (x# `quotWord#` y#)
| otherwise = divZeroError
mod (W32# x#) y@(W32# y#)
| y /= 0 = W32# (x# `remWord#` y#)
| otherwise = divZeroError
quotRem (W32# x#) y@(W32# y#)
| y /= 0 = case x# `quotRemWord#` y# of
(# q, r #) ->
(W32# q, W32# r)
| otherwise = divZeroError
divMod (W32# x#) y@(W32# y#)
| y /= 0 = (W32# (x# `quotWord#` y#), W32# (x# `remWord#` y#))
| otherwise = divZeroError
toInteger (W32# x#)
= smallInteger (word2Int# x#)
instance Bits Word32 where
# INLINE bit #
# INLINE testBit #
(W32# x#) .&. (W32# y#) = W32# (x# `and#` y#)
(W32# x#) .|. (W32# y#) = W32# (x# `or#` y#)
(W32# x#) `xor` (W32# y#) = W32# (x# `xor#` y#)
complement (W32# x#) = W32# (x# `xor#` mb#)
where !(W32# mb#) = maxBound
(W32# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W32# (narrow32Word# (x# `shiftL#` i#))
| otherwise = W32# (x# `shiftRL#` negateInt# i#)
(W32# x#) `shiftL` (I# i#) = W32# (narrow32Word# (x# `shiftL#` i#))
(W32# x#) `unsafeShiftL` (I# i#) =
W32# (narrow32Word# (x# `uncheckedShiftL#` i#))
(W32# x#) `shiftR` (I# i#) = W32# (x# `shiftRL#` i#)
(W32# x#) `unsafeShiftR` (I# i#) = W32# (x# `uncheckedShiftRL#` i#)
(W32# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W32# x#
| otherwise = W32# (narrow32Word# ((x# `uncheckedShiftL#` i'#) `or#`
(x# `uncheckedShiftRL#` (32# -# i'#))))
where
!i'# = word2Int# (int2Word# i# `and#` 31##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W32# x#) = I# (word2Int# (popCnt32# x#))
bit = bitDefault
testBit = testBitDefault
instance FiniteBits Word32 where
finiteBitSize _ = 32
countLeadingZeros (W32# x#) = I# (word2Int# (clz32# x#))
countTrailingZeros (W32# x#) = I# (word2Int# (ctz32# x#))
# RULES
" fromIntegral / Word8->Word32 " fromIntegral = \(W8 # x # ) - > W32 # x #
" fromIntegral / Word16->Word32 " fromIntegral = \(W16 # x # ) - > W32 # x #
" fromIntegral / Word32->Word32 " fromIntegral = i d : : Word32
" fromIntegral / Word32->Integer " fromIntegral = toInteger : : Integer
" fromIntegral / a->Word32 " fromIntegral = \x - > case fromIntegral x of W # x # - > W32 # ( narrow32Word # x # )
" fromIntegral / Word32->a " fromIntegral = \(W32 # x # ) - > fromIntegral ( W # x # )
#
"fromIntegral/Word8->Word32" fromIntegral = \(W8# x#) -> W32# x#
"fromIntegral/Word16->Word32" fromIntegral = \(W16# x#) -> W32# x#
"fromIntegral/Word32->Word32" fromIntegral = id :: Word32 -> Word32
"fromIntegral/Word32->Integer" fromIntegral = toInteger :: Word32 -> Integer
"fromIntegral/a->Word32" fromIntegral = \x -> case fromIntegral x of W# x# -> W32# (narrow32Word# x#)
"fromIntegral/Word32->a" fromIntegral = \(W32# x#) -> fromIntegral (W# x#)
#-}
instance Show Word32 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Real Word32 where
toRational x = toInteger x % 1
instance Bounded Word32 where
minBound = 0
maxBound = 0xFFFFFFFF
instance Ix Word32 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
instance Read Word32 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
| Reverse order of bytes in ' ' .
byteSwap32 :: Word32 -> Word32
byteSwap32 (W32# w#) = W32# (narrow32Word# (byteSwap32# w#))
Word64 is represented in the same way as Word .
Operations may assume and must ensure that it holds only values
^ 64 - bit unsigned integer type
instance Eq Word64 where
(==) = eqWord64
(/=) = neWord64
eqWord64, neWord64 :: Word64 -> Word64 -> Bool
eqWord64 (W64# x) (W64# y) = isTrue# (x `eqWord#` y)
neWord64 (W64# x) (W64# y) = isTrue# (x `neWord#` y)
# INLINE [ 1 ] eqWord64 #
instance Ord Word64 where
(<) = ltWord64
(<=) = leWord64
(>=) = geWord64
(>) = gtWord64
# INLINE [ 1 ] gtWord64 #
# INLINE [ 1 ] leWord64 #
gtWord64, geWord64, ltWord64, leWord64 :: Word64 -> Word64 -> Bool
(W64# x) `gtWord64` (W64# y) = isTrue# (x `gtWord#` y)
(W64# x) `geWord64` (W64# y) = isTrue# (x `geWord#` y)
(W64# x) `ltWord64` (W64# y) = isTrue# (x `ltWord#` y)
(W64# x) `leWord64` (W64# y) = isTrue# (x `leWord#` y)
instance Num Word64 where
(W64# x#) + (W64# y#) = W64# (x# `plusWord#` y#)
(W64# x#) - (W64# y#) = W64# (x# `minusWord#` y#)
(W64# x#) * (W64# y#) = W64# (x# `timesWord#` y#)
negate (W64# x#) = W64# (int2Word# (negateInt# (word2Int# x#)))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W64# (integerToWord i)
instance Enum Word64 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word64"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word64"
toEnum i@(I# i#)
| i >= 0 = W64# (int2Word# i#)
| otherwise = toEnumError "Word64" i (minBound::Word64, maxBound::Word64)
fromEnum x@(W64# x#)
| x <= fromIntegral (maxBound::Int)
= I# (word2Int# x#)
| otherwise = fromEnumError "Word64" x
enumFrom = integralEnumFrom
enumFromThen = integralEnumFromThen
enumFromTo = integralEnumFromTo
enumFromThenTo = integralEnumFromThenTo
instance Integral Word64 where
quot (W64# x#) y@(W64# y#)
| y /= 0 = W64# (x# `quotWord#` y#)
| otherwise = divZeroError
rem (W64# x#) y@(W64# y#)
| y /= 0 = W64# (x# `remWord#` y#)
| otherwise = divZeroError
div (W64# x#) y@(W64# y#)
| y /= 0 = W64# (x# `quotWord#` y#)
| otherwise = divZeroError
mod (W64# x#) y@(W64# y#)
| y /= 0 = W64# (x# `remWord#` y#)
| otherwise = divZeroError
quotRem (W64# x#) y@(W64# y#)
| y /= 0 = case x# `quotRemWord#` y# of
(# q, r #) ->
(W64# q, W64# r)
| otherwise = divZeroError
divMod (W64# x#) y@(W64# y#)
| y /= 0 = (W64# (x# `quotWord#` y#), W64# (x# `remWord#` y#))
| otherwise = divZeroError
toInteger (W64# x#)
| isTrue# (i# >=# 0#) = smallInteger i#
| otherwise = wordToInteger x#
where
!i# = word2Int# x#
instance Bits Word64 where
# INLINE bit #
# INLINE testBit #
(W64# x#) .&. (W64# y#) = W64# (x# `and#` y#)
(W64# x#) .|. (W64# y#) = W64# (x# `or#` y#)
(W64# x#) `xor` (W64# y#) = W64# (x# `xor#` y#)
complement (W64# x#) = W64# (x# `xor#` mb#)
where !(W64# mb#) = maxBound
(W64# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W64# (x# `shiftL#` i#)
| otherwise = W64# (x# `shiftRL#` negateInt# i#)
(W64# x#) `shiftL` (I# i#) = W64# (x# `shiftL#` i#)
(W64# x#) `unsafeShiftL` (I# i#) = W64# (x# `uncheckedShiftL#` i#)
(W64# x#) `shiftR` (I# i#) = W64# (x# `shiftRL#` i#)
(W64# x#) `unsafeShiftR` (I# i#) = W64# (x# `uncheckedShiftRL#` i#)
(W64# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W64# x#
| otherwise = W64# ((x# `uncheckedShiftL#` i'#) `or#`
(x# `uncheckedShiftRL#` (64# -# i'#)))
where
!i'# = word2Int# (int2Word# i# `and#` 63##)
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W64# x#) = I# (word2Int# (popCnt64# x#))
bit = bitDefault
testBit = testBitDefault
# RULES
" fromIntegral / a->Word64 " fromIntegral = \x - > case fromIntegral x of W # x # - > W64 # x #
" fromIntegral / Word64->a " fromIntegral = \(W64 # x # ) - > fromIntegral ( W # x # )
#
"fromIntegral/a->Word64" fromIntegral = \x -> case fromIntegral x of W# x# -> W64# x#
"fromIntegral/Word64->a" fromIntegral = \(W64# x#) -> fromIntegral (W# x#)
#-}
uncheckedShiftL64# :: Word# -> Int# -> Word#
uncheckedShiftL64# = uncheckedShiftL#
uncheckedShiftRL64# :: Word# -> Int# -> Word#
uncheckedShiftRL64# = uncheckedShiftRL#
instance FiniteBits Word64 where
finiteBitSize _ = 64
countLeadingZeros (W64# x#) = I# (word2Int# (clz64# x#))
countTrailingZeros (W64# x#) = I# (word2Int# (ctz64# x#))
instance Show Word64 where
showsPrec p x = showsPrec p (toInteger x)
instance Real Word64 where
toRational x = toInteger x % 1
instance Bounded Word64 where
minBound = 0
maxBound = 0xFFFFFFFFFFFFFFFF
instance Ix Word64 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
instance Read Word64 where
readsPrec p s = [(fromInteger x, r) | (x, r) <- readsPrec p s]
byteSwap64 :: Word64 -> Word64
byteSwap64 (W64# w#) = W64# (byteSwap# w#)
|
6792455fc2fbcbab40160b07d805838546b10bcab2401c93fd0ee067e743f215 | xysun/sbe-erlang | carexample.erl | % corresponds to ExampleUsingGeneratedStub.java
-module(carexample).
-export([main/0, readJava/0, encode/2]).
main() ->
io:format("****** SBE Car example ******", []),
Buffer = buffer:allocate(64),
BufferOffset = 0,
MessageTemplateVersion = 0,
% encode a message
% messageHeader
M = messageHeader:wrap(Buffer, BufferOffset, MessageTemplateVersion),
M1 = messageHeader:setBlockLength(M, car:sbeBlockLength()),
M2 = messageHeader:setTemplateId(M1, car:sbeTemplateId()),
M3 = messageHeader:setSchemaId(M2, car:sbeSchemaId()),
MessageHeader = messageHeader:setVersion(M3, car:sbeSchemaVersion()),
HeaderOffset = BufferOffset + messageHeader:size(),
{EncodeBuffer, _, _} = MessageHeader,
{MessageBuffer, _, _} = encode(EncodeBuffer, HeaderOffset),
% write the encoded buffer to a file for decoding
file:write_file("car_erlang", MessageBuffer),
% decode the encoded message
MessageHeaderForDecode = messageHeader:wrap(MessageBuffer , BufferOffset, MessageTemplateVersion),
% match template ID
TemplateId = messageHeader:getTemplateId(MessageHeaderForDecode),
CarTemplateId = car:sbeTemplateId(),
if TemplateId =/= CarTemplateId -> error(templateId_do_not_match);
true -> ok
end,
ActingBlockLength = messageHeader:getBlockLength(MessageHeaderForDecode),
SchemaId = messageHeader:getSchemaId(MessageHeaderForDecode),
ActingVersion = messageHeader:getVersion(MessageHeaderForDecode),
decode(MessageBuffer,
BufferOffset + messageHeader:size(),
ActingBlockLength,
SchemaId,
ActingVersion),
ok.
read and decode the binary encoded by Java implementation
readJava() ->
{ok, Binary} = file:read_file("car_java"),
MessageHeaderForDecode = messageHeader:wrap(Binary, 0, 0),
TemplateId = messageHeader:getTemplateId(MessageHeaderForDecode),
CarTemplateId = car:sbeTemplateId(),
if TemplateId =/= CarTemplateId -> error(templateId_do_not_match);
true -> ok
end,
ActingBlockLength = messageHeader:getBlockLength(MessageHeaderForDecode),
SchemaId = messageHeader:getSchemaId(MessageHeaderForDecode),
ActingVersion = messageHeader:getVersion(MessageHeaderForDecode),
decode(Binary,
0 + messageHeader:size(),
ActingBlockLength,
SchemaId,
ActingVersion),
ok.
encode(Buffer, Offset) ->
SrcOffset = 0,
VehicleCode = list_to_binary("abcdef"),
Make = <<"Honda">>,
Model = <<"Civic Vti">>,
M = car:wrapForEncode(Buffer, Offset),
M1 = car:setserialNumber(M, 1234),
M2 = car:setmodelYear(M1, 2023),
M3 = car:setvehicleCode(M2, VehicleCode, SrcOffset),
M4 = car:setmake(M3, Make, SrcOffset, byte_size(Make)),
Message = car:setmodel(M4, Model, SrcOffset, byte_size(Model)),
lists:foldl(fun(X, AccM) -> car:setsomeNumbers(AccM, X, X) end,
Message, lists:seq(0, car:someNumbersLength() - 1)).
decode(Buffer, Offset, ActingBlockLength, SchemaId, ActingVersion) ->
Message = car:wrapForDecode(Buffer, Offset, ActingBlockLength, ActingVersion),
io:format("~ncar.templateId = ~w", [car:sbeTemplateId()]),
io:format("~ncar.schemaId = ~w", [SchemaId]),
io:format("~ncar.schemaVersion = ~w", [car:sbeSchemaVersion()]),
io:format("~ncar.serialNumber = ~w", [car:getserialNumber(Message)]),
io:format("~ncar.modelYear = ~w", [car:getmodelYear(Message)]),
io:format("~ncar.someNumbers = "),
lists:foreach(fun(X) ->
io:format("~w,", [car:getsomeNumbers(Message, X)]) end,
lists:seq(0, car:someNumbersLength() - 1)),
VehicleCode = lists:reverse(
lists:foldl(fun(X, Acc) -> [car:getvehicleCode(Message, X)|Acc] end,
[],
lists:seq(0, car:vehicleCodeLength() - 1))),
io:format("~ncar.vehicleCode = ~p", [VehicleCode]),
io:format("~ncar.make.semanticType = ~p", [car:makeMetaAttribute(semanticType)]),
{Message2, Make} = car:getmake(Message, 128),
io:format("~ncar.make = ~p", [Make]),
{Message3, Model} = car:getmodel(Message2, 128),
io:format("~ncar.model = ~p", [Model]),
io:format("~ncar.size = ~p~n", [car:getSize(Message3)]),
ok.
| null | https://raw.githubusercontent.com/xysun/sbe-erlang/974a2b1a4c82402f377a397f4525995db283c918/examples/baselinesimple/carexample.erl | erlang | corresponds to ExampleUsingGeneratedStub.java
encode a message
messageHeader
write the encoded buffer to a file for decoding
decode the encoded message
match template ID | -module(carexample).
-export([main/0, readJava/0, encode/2]).
main() ->
io:format("****** SBE Car example ******", []),
Buffer = buffer:allocate(64),
BufferOffset = 0,
MessageTemplateVersion = 0,
M = messageHeader:wrap(Buffer, BufferOffset, MessageTemplateVersion),
M1 = messageHeader:setBlockLength(M, car:sbeBlockLength()),
M2 = messageHeader:setTemplateId(M1, car:sbeTemplateId()),
M3 = messageHeader:setSchemaId(M2, car:sbeSchemaId()),
MessageHeader = messageHeader:setVersion(M3, car:sbeSchemaVersion()),
HeaderOffset = BufferOffset + messageHeader:size(),
{EncodeBuffer, _, _} = MessageHeader,
{MessageBuffer, _, _} = encode(EncodeBuffer, HeaderOffset),
file:write_file("car_erlang", MessageBuffer),
MessageHeaderForDecode = messageHeader:wrap(MessageBuffer , BufferOffset, MessageTemplateVersion),
TemplateId = messageHeader:getTemplateId(MessageHeaderForDecode),
CarTemplateId = car:sbeTemplateId(),
if TemplateId =/= CarTemplateId -> error(templateId_do_not_match);
true -> ok
end,
ActingBlockLength = messageHeader:getBlockLength(MessageHeaderForDecode),
SchemaId = messageHeader:getSchemaId(MessageHeaderForDecode),
ActingVersion = messageHeader:getVersion(MessageHeaderForDecode),
decode(MessageBuffer,
BufferOffset + messageHeader:size(),
ActingBlockLength,
SchemaId,
ActingVersion),
ok.
read and decode the binary encoded by Java implementation
readJava() ->
{ok, Binary} = file:read_file("car_java"),
MessageHeaderForDecode = messageHeader:wrap(Binary, 0, 0),
TemplateId = messageHeader:getTemplateId(MessageHeaderForDecode),
CarTemplateId = car:sbeTemplateId(),
if TemplateId =/= CarTemplateId -> error(templateId_do_not_match);
true -> ok
end,
ActingBlockLength = messageHeader:getBlockLength(MessageHeaderForDecode),
SchemaId = messageHeader:getSchemaId(MessageHeaderForDecode),
ActingVersion = messageHeader:getVersion(MessageHeaderForDecode),
decode(Binary,
0 + messageHeader:size(),
ActingBlockLength,
SchemaId,
ActingVersion),
ok.
encode(Buffer, Offset) ->
SrcOffset = 0,
VehicleCode = list_to_binary("abcdef"),
Make = <<"Honda">>,
Model = <<"Civic Vti">>,
M = car:wrapForEncode(Buffer, Offset),
M1 = car:setserialNumber(M, 1234),
M2 = car:setmodelYear(M1, 2023),
M3 = car:setvehicleCode(M2, VehicleCode, SrcOffset),
M4 = car:setmake(M3, Make, SrcOffset, byte_size(Make)),
Message = car:setmodel(M4, Model, SrcOffset, byte_size(Model)),
lists:foldl(fun(X, AccM) -> car:setsomeNumbers(AccM, X, X) end,
Message, lists:seq(0, car:someNumbersLength() - 1)).
decode(Buffer, Offset, ActingBlockLength, SchemaId, ActingVersion) ->
Message = car:wrapForDecode(Buffer, Offset, ActingBlockLength, ActingVersion),
io:format("~ncar.templateId = ~w", [car:sbeTemplateId()]),
io:format("~ncar.schemaId = ~w", [SchemaId]),
io:format("~ncar.schemaVersion = ~w", [car:sbeSchemaVersion()]),
io:format("~ncar.serialNumber = ~w", [car:getserialNumber(Message)]),
io:format("~ncar.modelYear = ~w", [car:getmodelYear(Message)]),
io:format("~ncar.someNumbers = "),
lists:foreach(fun(X) ->
io:format("~w,", [car:getsomeNumbers(Message, X)]) end,
lists:seq(0, car:someNumbersLength() - 1)),
VehicleCode = lists:reverse(
lists:foldl(fun(X, Acc) -> [car:getvehicleCode(Message, X)|Acc] end,
[],
lists:seq(0, car:vehicleCodeLength() - 1))),
io:format("~ncar.vehicleCode = ~p", [VehicleCode]),
io:format("~ncar.make.semanticType = ~p", [car:makeMetaAttribute(semanticType)]),
{Message2, Make} = car:getmake(Message, 128),
io:format("~ncar.make = ~p", [Make]),
{Message3, Model} = car:getmodel(Message2, 128),
io:format("~ncar.model = ~p", [Model]),
io:format("~ncar.size = ~p~n", [car:getSize(Message3)]),
ok.
|
fe369c7aa68e16ba30fedaa3eede49f7898bb55f1c70f28461a99613d9cd7973 | Frama-C/Frama-C-snapshot | intset.ml | (**************************************************************************)
(* *)
This file is part of WP plug - in of Frama - C.
(* *)
Copyright ( C ) 2007 - 2019
CEA ( Commissariat a l'energie atomique et aux energies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
(* ---------------------------------------------------------------------- *)
--- By L. Correnson & P. Baudin ---
(* ---------------------------------------------------------------------- *)
type t = unit Intmap.t
let empty = Intmap.empty
let singleton x = Intmap.singleton x ()
let add x = Intmap.add x ()
let remove x = Intmap.remove x
let is_empty = Intmap.is_empty
let mem = Intmap.mem
let cardinal = Intmap.size
let compare = Intmap.compare (fun () () -> 0)
let equal = Intmap.equal (fun () () -> true)
let _keep _ _ _ = ()
let _keepq _ _ _ = Some ()
let _same _ () () = true
let union = Intmap.union _keep
let inter = Intmap.interq _keepq
let diff = Intmap.diffq _keepq
let subset = Intmap.subset _same
let intersect = Intmap.intersectf _same
let iter f = Intmap.iteri (fun i () -> f i)
let fold f = Intmap.foldi (fun i () e -> f i e)
let filter f = Intmap.filter (fun i () -> f i)
let partition f = Intmap.partition (fun i () -> f i)
let for_all f = Intmap.for_all (fun i () -> f i)
let exists f = Intmap.exists (fun i () -> f i)
let elements = Intmap.mapl (fun i () -> i)
| null | https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/qed/intset.ml | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
----------------------------------------------------------------------
---------------------------------------------------------------------- | This file is part of WP plug - in of Frama - C.
Copyright ( C ) 2007 - 2019
CEA ( Commissariat a l'energie atomique et aux energies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
--- By L. Correnson & P. Baudin ---
type t = unit Intmap.t
let empty = Intmap.empty
let singleton x = Intmap.singleton x ()
let add x = Intmap.add x ()
let remove x = Intmap.remove x
let is_empty = Intmap.is_empty
let mem = Intmap.mem
let cardinal = Intmap.size
let compare = Intmap.compare (fun () () -> 0)
let equal = Intmap.equal (fun () () -> true)
let _keep _ _ _ = ()
let _keepq _ _ _ = Some ()
let _same _ () () = true
let union = Intmap.union _keep
let inter = Intmap.interq _keepq
let diff = Intmap.diffq _keepq
let subset = Intmap.subset _same
let intersect = Intmap.intersectf _same
let iter f = Intmap.iteri (fun i () -> f i)
let fold f = Intmap.foldi (fun i () e -> f i e)
let filter f = Intmap.filter (fun i () -> f i)
let partition f = Intmap.partition (fun i () -> f i)
let for_all f = Intmap.for_all (fun i () -> f i)
let exists f = Intmap.exists (fun i () -> f i)
let elements = Intmap.mapl (fun i () -> i)
|
bb3cbacad82f02f2a5130c9b98010885dbcf478563b9e7c61c6ddc20cc918b48 | Bogdanp/racket-redis | info.rkt | #lang info
(define license 'MIT)
(define collection "tests")
(define deps '())
(define build-deps '("base"
"rackunit-lib"
"redis-lib"))
(define update-implies '("redis-lib"))
| null | https://raw.githubusercontent.com/Bogdanp/racket-redis/063664898fb6e99f24877cbb1b7fb19143293eb1/redis-test/info.rkt | racket | #lang info
(define license 'MIT)
(define collection "tests")
(define deps '())
(define build-deps '("base"
"rackunit-lib"
"redis-lib"))
(define update-implies '("redis-lib"))
|
|
67ce23b930c56c9dff81a73746fd360799224656211a1079e133490635a44335 | borodust/alien-works | packages.lisp | (cl:defpackage :%alien-works.tools.filament
(:local-nicknames (:a :alexandria)
(:! :alien-works.utils.empty)
(:u :alien-works.utils)
(:m :alien-works.math)
(:%aw.fm :%alien-works.filament))
(:use :cl)
(:export #:serialize-material
#:material-data-pointer
#:material-data-size
#:with-serialized-material-data
#:make-image
#:image-width
#:image-height
#:image-channels
#:image-data-ptr
#:image-data-size
#:destroy-image
#:decode-image
#:encode-image))
(cl:defpackage :alien-works.tools.graphics
(:local-nicknames (:a :alexandria)
(:%aw.fm :%alien-works.filament)
(:%gx :%alien-works.graphics)
(:gx :alien-works.graphics)
(:%gxs :%alien-works.tools.filament)
(:u :alien-works.utils)
(:sv :static-vectors)
(:cref :cffi-c-ref)
(:m :alien-works.math)
(:mem :alien-works.memory)
(:%mem :%alien-works.memory)
(:host :alien-works.host))
(:use :cl)
(:import-from :%alien-works.tools.filament
#:make-image
#:image-width
#:image-height
#:image-channels
#:destroy-image
#:decode-image
#:encode-image)
(:export #:make-material
#:serialize-material
#:make-image
#:image-width
#:image-height
#:image-channels
#:destroy-image
#:decode-image
#:encode-image))
| null | https://raw.githubusercontent.com/borodust/alien-works/27992c20ad3cecd47549793f3b923cbcf17c3241/tools/graphics/packages.lisp | lisp | (cl:defpackage :%alien-works.tools.filament
(:local-nicknames (:a :alexandria)
(:! :alien-works.utils.empty)
(:u :alien-works.utils)
(:m :alien-works.math)
(:%aw.fm :%alien-works.filament))
(:use :cl)
(:export #:serialize-material
#:material-data-pointer
#:material-data-size
#:with-serialized-material-data
#:make-image
#:image-width
#:image-height
#:image-channels
#:image-data-ptr
#:image-data-size
#:destroy-image
#:decode-image
#:encode-image))
(cl:defpackage :alien-works.tools.graphics
(:local-nicknames (:a :alexandria)
(:%aw.fm :%alien-works.filament)
(:%gx :%alien-works.graphics)
(:gx :alien-works.graphics)
(:%gxs :%alien-works.tools.filament)
(:u :alien-works.utils)
(:sv :static-vectors)
(:cref :cffi-c-ref)
(:m :alien-works.math)
(:mem :alien-works.memory)
(:%mem :%alien-works.memory)
(:host :alien-works.host))
(:use :cl)
(:import-from :%alien-works.tools.filament
#:make-image
#:image-width
#:image-height
#:image-channels
#:destroy-image
#:decode-image
#:encode-image)
(:export #:make-material
#:serialize-material
#:make-image
#:image-width
#:image-height
#:image-channels
#:destroy-image
#:decode-image
#:encode-image))
|
|
fe4d197a6b223523fb82458e7391301a73c2985d4d9308bd6bb0667acb0ecddc | silverbullettt/SICP | 3.50.rkt | (load "stream.rkt")
(define (stream-map proc . argstreams)
(if (stream-null? (car argstreams))
the-empty-stream
(cons-stream
(apply proc (map stream-car argstreams))
(apply stream-map
(cons proc (map stream-cdr argstreams))))))
(stream-map + (stream 1 2 3) (stream 4 5 6) (stream 7 8 9)) | null | https://raw.githubusercontent.com/silverbullettt/SICP/e773a8071ae2fae768846a2b295b5ed96b019f8d/3.50.rkt | racket | (load "stream.rkt")
(define (stream-map proc . argstreams)
(if (stream-null? (car argstreams))
the-empty-stream
(cons-stream
(apply proc (map stream-car argstreams))
(apply stream-map
(cons proc (map stream-cdr argstreams))))))
(stream-map + (stream 1 2 3) (stream 4 5 6) (stream 7 8 9)) |
|
d80d557566df6f991bf0f6b243ea69895ca1b8f37c58bd7374eac539f9d372e4 | GaloisInc/renovate | Chunk.hs | # LANGUAGE FlexibleContexts #
# LANGUAGE StandaloneDeriving #
# LANGUAGE UndecidableInstances #
module Renovate.Core.Chunk (
Chunk(..)
, chunkAddress
, chunkSize
) where
import qualified Data.ByteString as B
import qualified Data.Macaw.CFG as MC
import Data.Word ( Word64 )
import qualified Prettyprinter as PP
import qualified Renovate.Core.Address as RCA
import qualified Renovate.Core.BasicBlock as RCB
import qualified Renovate.ISA as RI
-- | A chunk is a unit of code managed during re-assembly
--
-- A chunk of code can either be a 'RCB.ConcretizedBlock' (i.e., a block that
-- has had a new address assigned to it) or raw bytes that have been assigned an
-- address (either raw injected code or padding bytes).
data Chunk arch = BlockChunk (RCB.ConcretizedBlock arch)
| RawChunk (RCA.ConcreteAddress arch) B.ByteString
deriving instance (MC.MemWidth (MC.ArchAddrWidth arch)) => Show (Chunk arch)
instance (MC.MemWidth (MC.ArchAddrWidth arch)) => PP.Pretty (Chunk arch) where
pretty (BlockChunk b) = PP.pretty b
pretty (RawChunk addr bs) = PP.pretty addr PP.<> PP.pretty "@" PP.<> PP.pretty (B.length bs)
-- | Get the address assigned to this 'Chunk'
chunkAddress :: Chunk arch -> RCA.ConcreteAddress arch
chunkAddress c =
case c of
BlockChunk b -> RCB.concretizedBlockAddress b
RawChunk addr _ -> addr
-- | Compute the size of this 'Chunk'
chunkSize :: RI.ISA arch -> Chunk arch -> Word64
chunkSize isa c =
case c of
BlockChunk b -> RCB.blockSize isa b
RawChunk _ b -> fromIntegral (B.length b)
| null | https://raw.githubusercontent.com/GaloisInc/renovate/89b82366f84be894c3437852e39c9b4e28666a37/renovate/src/Renovate/Core/Chunk.hs | haskell | | A chunk is a unit of code managed during re-assembly
A chunk of code can either be a 'RCB.ConcretizedBlock' (i.e., a block that
has had a new address assigned to it) or raw bytes that have been assigned an
address (either raw injected code or padding bytes).
| Get the address assigned to this 'Chunk'
| Compute the size of this 'Chunk' | # LANGUAGE FlexibleContexts #
# LANGUAGE StandaloneDeriving #
# LANGUAGE UndecidableInstances #
module Renovate.Core.Chunk (
Chunk(..)
, chunkAddress
, chunkSize
) where
import qualified Data.ByteString as B
import qualified Data.Macaw.CFG as MC
import Data.Word ( Word64 )
import qualified Prettyprinter as PP
import qualified Renovate.Core.Address as RCA
import qualified Renovate.Core.BasicBlock as RCB
import qualified Renovate.ISA as RI
data Chunk arch = BlockChunk (RCB.ConcretizedBlock arch)
| RawChunk (RCA.ConcreteAddress arch) B.ByteString
deriving instance (MC.MemWidth (MC.ArchAddrWidth arch)) => Show (Chunk arch)
instance (MC.MemWidth (MC.ArchAddrWidth arch)) => PP.Pretty (Chunk arch) where
pretty (BlockChunk b) = PP.pretty b
pretty (RawChunk addr bs) = PP.pretty addr PP.<> PP.pretty "@" PP.<> PP.pretty (B.length bs)
chunkAddress :: Chunk arch -> RCA.ConcreteAddress arch
chunkAddress c =
case c of
BlockChunk b -> RCB.concretizedBlockAddress b
RawChunk addr _ -> addr
chunkSize :: RI.ISA arch -> Chunk arch -> Word64
chunkSize isa c =
case c of
BlockChunk b -> RCB.blockSize isa b
RawChunk _ b -> fromIntegral (B.length b)
|
512b91086116ee7dfa5481a62a78c4f248c5b214484814c84631e8a486cdc985 | inhabitedtype/ocaml-aws | sendAutomationSignal.ml | open Types
open Aws
type input = SendAutomationSignalRequest.t
type output = unit
type error = Errors_internal.t
let service = "ssm"
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", [ "2014-11-06" ]; "Action", [ "SendAutomationSignal" ] ]
(Util.drop_empty
(Uri.query_of_encoded
(Query.render (SendAutomationSignalRequest.to_query req)))))
in
`POST, uri, []
let of_http body = `Ok ()
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/3bc554af7ae7ef9e2dcea44a1b72c9e687435fa9/libraries/ssm/lib/sendAutomationSignal.ml | ocaml | open Types
open Aws
type input = SendAutomationSignalRequest.t
type output = unit
type error = Errors_internal.t
let service = "ssm"
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", [ "2014-11-06" ]; "Action", [ "SendAutomationSignal" ] ]
(Util.drop_empty
(Uri.query_of_encoded
(Query.render (SendAutomationSignalRequest.to_query req)))))
in
`POST, uri, []
let of_http body = `Ok ()
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
|
|
dbbecc1b86553897b53bab470c9e7b49b090c6c04504b5cd353f1b7fbcc9c567 | juxt/site | cors_test.clj | Copyright © 2021 , JUXT LTD .
(ns juxt.site.cors-test
(:require
[clojure.test :refer [deftest is are testing]]
[juxt.site.alpha.handler :refer [access-control-match-origin]]))
(alias 'site (create-ns 'juxt.site.alpha))
(deftest access-control-origin-match-test
(let [allow-origins
{#":\p{Digit}+"
{::site/access-control-allow-methods #{:post}
::site/access-control-allow-headers #{"authorization" "content-type"}}}]
(is (= #{:post} (::site/access-control-allow-methods (access-control-match-origin allow-origins ":8080"))))
(is (nil? (access-control-match-origin allow-origins "")))))
| null | https://raw.githubusercontent.com/juxt/site/98bb331d90611f30fbe3d0aa0fe20da48cdf6691/test/juxt/site/cors_test.clj | clojure | Copyright © 2021 , JUXT LTD .
(ns juxt.site.cors-test
(:require
[clojure.test :refer [deftest is are testing]]
[juxt.site.alpha.handler :refer [access-control-match-origin]]))
(alias 'site (create-ns 'juxt.site.alpha))
(deftest access-control-origin-match-test
(let [allow-origins
{#":\p{Digit}+"
{::site/access-control-allow-methods #{:post}
::site/access-control-allow-headers #{"authorization" "content-type"}}}]
(is (= #{:post} (::site/access-control-allow-methods (access-control-match-origin allow-origins ":8080"))))
(is (nil? (access-control-match-origin allow-origins "")))))
|
|
f9e5808c6b16ebdb88cbc3fb24f4c3f1514437dc8a6e753616ffa26797f3763a | NorfairKing/sydtest | Client.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
# OPTIONS_GHC -fno - warn - redundant - constraints -fno - warn - unused - imports #
module Test.Syd.Yesod.Client where
import Control.Monad.Catch
import Control.Monad.Fail
import Control.Monad.Reader
import Control.Monad.State
import qualified Control.Monad.State as State
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as LB
import Data.Text (Text)
import qualified Data.Text as T
import GHC.Generics (Generic)
import Network.HTTP.Client as HTTP
import Network.HTTP.Types as HTTP
import Network.Socket (PortNumber)
import Network.URI
import Test.Syd
import Test.Syd.Wai.Client (lastRequestResponseContext)
import Yesod.Core as Yesod
| A client environment to call a Yesod app .
data YesodClient site = YesodClient
{ -- | The site itself
yesodClientSite :: !site,
-- | The 'HTTP.Manager' to make the requests
yesodClientManager :: !HTTP.Manager,
-- | The base 'URI' that the site is running on
yesodClientSiteURI :: !URI
}
deriving (Generic)
-- | The state that is maintained throughout a 'YesodClientM'
data YesodClientState = YesodClientState
{ -- | The last request and response pair
yesodClientStateLast :: !(Maybe (Request, Response LB.ByteString)),
-- | The cookies to pass along
yesodClientStateCookies :: !CookieJar
}
deriving (Generic)
-- | The starting point of the 'YesodClientState site' of a 'YesodClientM site'
initYesodClientState :: YesodClientState
initYesodClientState =
YesodClientState
{ yesodClientStateLast = Nothing,
yesodClientStateCookies = createCookieJar []
}
| A monad to call a Yesod app .
--
This has access to a ' YesodClient site ' .
newtype YesodClientM site a = YesodClientM
{ unYesodClientM :: StateT YesodClientState (ReaderT (YesodClient site) IO) a
}
deriving
( Functor,
Applicative,
Monad,
MonadIO,
MonadReader (YesodClient site),
MonadState YesodClientState,
MonadFail,
MonadThrow
)
instance IsTest (YesodClientM site ()) where
type Arg1 (YesodClientM site ()) = ()
type Arg2 (YesodClientM site ()) = YesodClient site
runTest func = runTest (\() -> func)
instance IsTest (outerArgs -> YesodClientM site ()) where
type Arg1 (outerArgs -> YesodClientM site ()) = outerArgs
type Arg2 (outerArgs -> YesodClientM site ()) = YesodClient site
runTest func = runTest (\outerArgs yesodClient -> runYesodClientM yesodClient (func outerArgs))
-- | For backward compatibility
type YesodExample site a = YesodClientM site a
| Run a YesodClientM site using a YesodClient site
runYesodClientM :: YesodClient site -> YesodClientM site a -> IO a
runYesodClientM cenv (YesodClientM func) = runReaderT (evalStateT func initYesodClientState) cenv
-- | Get the most recently sent request.
getRequest :: YesodClientM site (Maybe Request)
getRequest = fmap fst <$> getLast
-- | Get the most recently sent request.
requireRequest :: YesodClientM site Request
requireRequest = fst <$> requireLast
-- | Get the most recently received response.
getResponse :: YesodClientM site (Maybe (Response LB.ByteString))
getResponse = fmap snd <$> getLast
-- | Get the most recently received response, and assert that it already exists.
requireResponse :: YesodClientM site (Response LB.ByteString)
requireResponse = snd <$> requireLast
-- | Get the most recently sent request and the response to it.
getLast :: YesodClientM site (Maybe (Request, Response LB.ByteString))
getLast = State.gets yesodClientStateLast
-- | Get the most recently sent request and the response to it, and assert that they already exist.
requireLast :: YesodClientM site (Request, Response LB.ByteString)
requireLast = do
mTup <- getLast
case mTup of
Nothing -> liftIO $ expectationFailure "Should have had a latest request/response pair by now."
Just tup -> pure tup
-- | Get the status of the most recently received response.
getStatus :: YesodClientM site (Maybe Int)
getStatus = do
mResponse <- getResponse
pure $ statusCode . responseStatus <$> mResponse
-- | Get the status of the most recently received response, and assert that it already exists.
requireStatus :: YesodClientM site Int
requireStatus = statusCode . responseStatus <$> requireResponse
-- | Get the 'Location' header of most recently received response.
getLocation :: ParseRoute site => YesodClientM localSite (Either Text (Route site))
getLocation = do
mr <- getResponse
case mr of
Nothing -> return $ Left "getLocation called, but there was no previous response, so no Location header"
Just r -> case lookup "Location" (responseHeaders r) of
Nothing -> return $ Left "getLocation called, but the previous response has no Location header"
Just h -> case parseRoute $ decodePath' h of
Nothing -> return $ Left $ "getLocation called, but couldn’t parse it into a route: " <> T.pack (show h)
Just l -> return $ Right l
where
decodePath' :: ByteString -> ([Text], [(Text, Text)])
decodePath' b =
let (ss, q) = decodePath $ extractPath b
in (ss, map unJust $ queryToQueryText q)
unJust (a, Just b) = (a, b)
unJust (a, Nothing) = (a, mempty)
| Get the ' Location ' header of most recently received response , and assert that it is a valid Route .
requireLocation :: ParseRoute site => YesodClientM localSite (Route site)
requireLocation = do
errOrLocation <- getLocation
case errOrLocation of
Left err -> liftIO $ expectationFailure $ T.unpack err
Right location -> pure location
-- | Annotate the given test code with the last request and its response, if one has been made already.
withLastRequestContext :: YesodClientM site a -> YesodClientM site a
withLastRequestContext yfunc@(YesodClientM func) = do
mLast <- getLast
case mLast of
Nothing -> yfunc
Just (req, resp) ->
YesodClientM $ do
s <- get
c <- ask
let ctx = lastRequestResponseContext req resp
(r, s') <- liftIO $ context ctx $ runReaderT (runStateT func s) c
put s'
pure r
| null | https://raw.githubusercontent.com/NorfairKing/sydtest/9db39de44641f28a2c26de80fcfe08616fcf3054/sydtest-yesod/src/Test/Syd/Yesod/Client.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
| The site itself
| The 'HTTP.Manager' to make the requests
| The base 'URI' that the site is running on
| The state that is maintained throughout a 'YesodClientM'
| The last request and response pair
| The cookies to pass along
| The starting point of the 'YesodClientState site' of a 'YesodClientM site'
| For backward compatibility
| Get the most recently sent request.
| Get the most recently sent request.
| Get the most recently received response.
| Get the most recently received response, and assert that it already exists.
| Get the most recently sent request and the response to it.
| Get the most recently sent request and the response to it, and assert that they already exist.
| Get the status of the most recently received response.
| Get the status of the most recently received response, and assert that it already exists.
| Get the 'Location' header of most recently received response.
| Annotate the given test code with the last request and its response, if one has been made already. | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
# OPTIONS_GHC -fno - warn - redundant - constraints -fno - warn - unused - imports #
module Test.Syd.Yesod.Client where
import Control.Monad.Catch
import Control.Monad.Fail
import Control.Monad.Reader
import Control.Monad.State
import qualified Control.Monad.State as State
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as LB
import Data.Text (Text)
import qualified Data.Text as T
import GHC.Generics (Generic)
import Network.HTTP.Client as HTTP
import Network.HTTP.Types as HTTP
import Network.Socket (PortNumber)
import Network.URI
import Test.Syd
import Test.Syd.Wai.Client (lastRequestResponseContext)
import Yesod.Core as Yesod
| A client environment to call a Yesod app .
data YesodClient site = YesodClient
yesodClientSite :: !site,
yesodClientManager :: !HTTP.Manager,
yesodClientSiteURI :: !URI
}
deriving (Generic)
data YesodClientState = YesodClientState
yesodClientStateLast :: !(Maybe (Request, Response LB.ByteString)),
yesodClientStateCookies :: !CookieJar
}
deriving (Generic)
initYesodClientState :: YesodClientState
initYesodClientState =
YesodClientState
{ yesodClientStateLast = Nothing,
yesodClientStateCookies = createCookieJar []
}
| A monad to call a Yesod app .
This has access to a ' YesodClient site ' .
newtype YesodClientM site a = YesodClientM
{ unYesodClientM :: StateT YesodClientState (ReaderT (YesodClient site) IO) a
}
deriving
( Functor,
Applicative,
Monad,
MonadIO,
MonadReader (YesodClient site),
MonadState YesodClientState,
MonadFail,
MonadThrow
)
instance IsTest (YesodClientM site ()) where
type Arg1 (YesodClientM site ()) = ()
type Arg2 (YesodClientM site ()) = YesodClient site
runTest func = runTest (\() -> func)
instance IsTest (outerArgs -> YesodClientM site ()) where
type Arg1 (outerArgs -> YesodClientM site ()) = outerArgs
type Arg2 (outerArgs -> YesodClientM site ()) = YesodClient site
runTest func = runTest (\outerArgs yesodClient -> runYesodClientM yesodClient (func outerArgs))
type YesodExample site a = YesodClientM site a
| Run a YesodClientM site using a YesodClient site
runYesodClientM :: YesodClient site -> YesodClientM site a -> IO a
runYesodClientM cenv (YesodClientM func) = runReaderT (evalStateT func initYesodClientState) cenv
getRequest :: YesodClientM site (Maybe Request)
getRequest = fmap fst <$> getLast
requireRequest :: YesodClientM site Request
requireRequest = fst <$> requireLast
getResponse :: YesodClientM site (Maybe (Response LB.ByteString))
getResponse = fmap snd <$> getLast
requireResponse :: YesodClientM site (Response LB.ByteString)
requireResponse = snd <$> requireLast
getLast :: YesodClientM site (Maybe (Request, Response LB.ByteString))
getLast = State.gets yesodClientStateLast
requireLast :: YesodClientM site (Request, Response LB.ByteString)
requireLast = do
mTup <- getLast
case mTup of
Nothing -> liftIO $ expectationFailure "Should have had a latest request/response pair by now."
Just tup -> pure tup
getStatus :: YesodClientM site (Maybe Int)
getStatus = do
mResponse <- getResponse
pure $ statusCode . responseStatus <$> mResponse
requireStatus :: YesodClientM site Int
requireStatus = statusCode . responseStatus <$> requireResponse
getLocation :: ParseRoute site => YesodClientM localSite (Either Text (Route site))
getLocation = do
mr <- getResponse
case mr of
Nothing -> return $ Left "getLocation called, but there was no previous response, so no Location header"
Just r -> case lookup "Location" (responseHeaders r) of
Nothing -> return $ Left "getLocation called, but the previous response has no Location header"
Just h -> case parseRoute $ decodePath' h of
Nothing -> return $ Left $ "getLocation called, but couldn’t parse it into a route: " <> T.pack (show h)
Just l -> return $ Right l
where
decodePath' :: ByteString -> ([Text], [(Text, Text)])
decodePath' b =
let (ss, q) = decodePath $ extractPath b
in (ss, map unJust $ queryToQueryText q)
unJust (a, Just b) = (a, b)
unJust (a, Nothing) = (a, mempty)
| Get the ' Location ' header of most recently received response , and assert that it is a valid Route .
requireLocation :: ParseRoute site => YesodClientM localSite (Route site)
requireLocation = do
errOrLocation <- getLocation
case errOrLocation of
Left err -> liftIO $ expectationFailure $ T.unpack err
Right location -> pure location
withLastRequestContext :: YesodClientM site a -> YesodClientM site a
withLastRequestContext yfunc@(YesodClientM func) = do
mLast <- getLast
case mLast of
Nothing -> yfunc
Just (req, resp) ->
YesodClientM $ do
s <- get
c <- ask
let ctx = lastRequestResponseContext req resp
(r, s') <- liftIO $ context ctx $ runReaderT (runStateT func s) c
put s'
pure r
|
35c39c2dd5799eb198119f243475216d911c8ea7f56b3613ad3e49356164978a | OCamlPro/ocp-indent | let-open.ml |
let _ =
(* ... *)
let open Option in
indented_line
| null | https://raw.githubusercontent.com/OCamlPro/ocp-indent/9e26c0a2699b7076cebc04ece59fb354eb84c11c/tests/passing/let-open.ml | ocaml | ... |
let _ =
let open Option in
indented_line
|
7327e7da2c3e17e95e429f51fff399d42b8777debee7e56260694987f63b14df | apinf/proxy42 | toy_router.erl | Copyright ( c ) 2013 - 2015 , Heroku Inc < > .
%%% 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.
%%%
%%% * The names of its contributors may not 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.
-module(toy_router).
-behaviour(vegur_interface).
-export([init/2,
terminate/3,
lookup_domain_name/3,
checkout_service/3,
checkin_service/6,
service_backend/3,
feature/2,
additional_headers/4,
error_page/4]).
-record(state, {tries = [] :: list()}).
init(AcceptTime, Upstream) ->
RNGs require per - process seeding
{ok, Upstream, #state{}}. % state initialization here.
lookup_domain_name(_AllDomains, Upstream, State) ->
%% hardcoded values, we don't care about the domain
Servers = [{1, {127,0,0,1}, 8081},
{2, {127,0,0,1}, 8082}],
{ok, Servers, Upstream, State}.
checkout_service(Servers, Upstream, State=#state{tries=Tried}) ->
Available = Servers -- Tried,
case Available of
[] ->
{error, all_blocked, Upstream, State};
_ ->
N = random:uniform(length(Available)),
Pick = lists:nth(N, Available),
{service, Pick, Upstream, State#state{tries=[Pick | Tried]}}
end.
service_backend({_Id, IP, Port}, Upstream, State) ->
%% extract the IP:PORT from the chosen server.
%% To enable keep-alive, use:
` { , { default , { IP , Port } } } , Upstream , State } '
%% To force the use of a new keepalive connection, use:
` { , { new , { IP , Port } } } , Upstream , State } '
%% Otherwise, no keepalive is done to the back-end:
{{IP, Port}, Upstream, State}.
checkin_service(_Servers, _Pick, _Phase, _ServState, Upstream, State) ->
%% if we tracked total connections, we would decrement the counters here
{ok, Upstream, State}.
feature(_WhoCares, State) ->
{disabled, State}.
additional_headers(_Direction, _Log, _Upstream, State) ->
{[], State}.
Vegur - returned errors that should be handled no matter what .
%% Full list in src/vegur_stub.erl
error_page({upstream, _Reason}, _DomainGroup, Upstream, HandlerState) ->
%% Blame the caller
{{400, [], <<>>}, Upstream, HandlerState};
error_page({downstream, _Reason}, _DomainGroup, Upstream, HandlerState) ->
%% Blame the server
{{500, [], <<>>}, Upstream, HandlerState};
error_page({undefined, _Reason}, _DomainGroup, Upstream, HandlerState) ->
%% Who knows who was to blame!
{{500, [], <<>>}, Upstream, HandlerState};
%% Specific error codes from middleware
error_page(empty_host, _DomainGroup, Upstream, HandlerState) ->
{{400, [], <<>>}, Upstream, HandlerState};
error_page(bad_request, _DomainGroup, Upstream, HandlerState) ->
{{400, [], <<>>}, Upstream, HandlerState};
error_page(expectation_failed, _DomainGroup, Upstream, HandlerState) ->
{{417, [], <<>>}, Upstream, HandlerState};
%% Catch-all
error_page(_, _DomainGroup, Upstream, HandlerState) ->
{{500, [], <<>>}, Upstream, HandlerState}.
terminate(_, _, _) ->
ok.
| null | https://raw.githubusercontent.com/apinf/proxy42/01b483b711881391e8306bf64b83b4df9d0bc832/apps/vegur/demo/toy_router.erl | erlang | 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.
* The names of its contributors may not 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
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
state initialization here.
hardcoded values, we don't care about the domain
extract the IP:PORT from the chosen server.
To enable keep-alive, use:
To force the use of a new keepalive connection, use:
Otherwise, no keepalive is done to the back-end:
if we tracked total connections, we would decrement the counters here
Full list in src/vegur_stub.erl
Blame the caller
Blame the server
Who knows who was to blame!
Specific error codes from middleware
Catch-all | Copyright ( c ) 2013 - 2015 , Heroku Inc < > .
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
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 ,
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
-module(toy_router).
-behaviour(vegur_interface).
-export([init/2,
terminate/3,
lookup_domain_name/3,
checkout_service/3,
checkin_service/6,
service_backend/3,
feature/2,
additional_headers/4,
error_page/4]).
-record(state, {tries = [] :: list()}).
init(AcceptTime, Upstream) ->
RNGs require per - process seeding
lookup_domain_name(_AllDomains, Upstream, State) ->
Servers = [{1, {127,0,0,1}, 8081},
{2, {127,0,0,1}, 8082}],
{ok, Servers, Upstream, State}.
checkout_service(Servers, Upstream, State=#state{tries=Tried}) ->
Available = Servers -- Tried,
case Available of
[] ->
{error, all_blocked, Upstream, State};
_ ->
N = random:uniform(length(Available)),
Pick = lists:nth(N, Available),
{service, Pick, Upstream, State#state{tries=[Pick | Tried]}}
end.
service_backend({_Id, IP, Port}, Upstream, State) ->
` { , { default , { IP , Port } } } , Upstream , State } '
` { , { new , { IP , Port } } } , Upstream , State } '
{{IP, Port}, Upstream, State}.
checkin_service(_Servers, _Pick, _Phase, _ServState, Upstream, State) ->
{ok, Upstream, State}.
feature(_WhoCares, State) ->
{disabled, State}.
additional_headers(_Direction, _Log, _Upstream, State) ->
{[], State}.
Vegur - returned errors that should be handled no matter what .
error_page({upstream, _Reason}, _DomainGroup, Upstream, HandlerState) ->
{{400, [], <<>>}, Upstream, HandlerState};
error_page({downstream, _Reason}, _DomainGroup, Upstream, HandlerState) ->
{{500, [], <<>>}, Upstream, HandlerState};
error_page({undefined, _Reason}, _DomainGroup, Upstream, HandlerState) ->
{{500, [], <<>>}, Upstream, HandlerState};
error_page(empty_host, _DomainGroup, Upstream, HandlerState) ->
{{400, [], <<>>}, Upstream, HandlerState};
error_page(bad_request, _DomainGroup, Upstream, HandlerState) ->
{{400, [], <<>>}, Upstream, HandlerState};
error_page(expectation_failed, _DomainGroup, Upstream, HandlerState) ->
{{417, [], <<>>}, Upstream, HandlerState};
error_page(_, _DomainGroup, Upstream, HandlerState) ->
{{500, [], <<>>}, Upstream, HandlerState}.
terminate(_, _, _) ->
ok.
|
4b41772f4bb0d0d4fd5968598d7c6f789d27f4351a9be555c7c1b80ef9063bd5 | stchang/macrotypes | lin+cons.rkt | #lang turnstile/base
(extends "lin+tup.rkt")
(require (for-syntax racket/contract))
(provide (type-out MList MList0)
cons nil match-list)
(define-type-constructor MList #:arity = 1)
(define-base-type MList0)
(begin-for-syntax
(current-linear-type? (or/c MList? MList0? (current-linear-type?))))
(define-typed-syntax cons
#:datum-literals (@)
; implicit memory location created
[(_ e e_rest) ≫
[⊢ e ≫ e- ⇒ σ]
[⊢ e_rest ≫ e_rest- ⇐ (MList σ)]
--------
[⊢ (#%app- mcons- e- e_rest-) ⇒ (MList σ)]]
; with memory location given
[(_ e e_rest @ e_loc) ≫
[⊢ e ≫ e- ⇒ σ]
[⊢ e_rest ≫ e_rest- ⇐ (MList σ)]
[⊢ e_loc ≫ e_loc- ⇐ MList0]
#:with tmp (generate-temporary #'e_loc)
--------
[⊢ (let- ([tmp e_loc-])
(set-mcar!- tmp e-)
(set-mcdr!- tmp e_rest-)
tmp)
⇒ (MList σ)]])
(define-typed-syntax nil
[(_ {ty:type}) ≫
--------
[⊢ '() ⇒ (MList ty.norm)]]
[(_) ⇐ (~MList σ) ≫
--------
[⊢ '()]])
(define-typed-syntax match-list
#:datum-literals (cons nil @)
[(_ e_list
(~or [(cons x+:id xs+:id @ l+:id) e_cons+]
[(nil) e_nil+]) ...) ≫
#:with [(l x xs e_cons)] #'[(l+ x+ xs+ e_cons+) ...]
#:with [e_nil] #'[e_nil+ ...]
; list
[⊢ e_list ≫ e_list- ⇒ (~MList σ)]
#:with σ_xs ((current-type-eval) #'(MList σ))
#:with σ_l ((current-type-eval) #'MList0)
#:mode (make-linear-branch-mode 2)
(; cons branch
#:submode (branch-nth 0)
([[x ≫ x- : σ]
[xs ≫ xs- : σ_xs]
[l ≫ l- : σ_l]
⊢ e_cons ≫ e_cons- ⇒ σ_out]
#:do [(linear-out-of-scope! #'([x- : σ] [xs- : σ_xs] [l- : σ_l]))])
; nil branch
#:submode (branch-nth 1)
([⊢ [e_nil ≫ e_nil- ⇐ σ_out]]))
--------
[⊢ (let- ([l- e_list-])
(if- (null? l-)
e_nil-
(let- ([x- (mcar- l-)]
[xs- (mcdr- l-)])
e_cons-)))
⇒ σ_out]])
| null | https://raw.githubusercontent.com/stchang/macrotypes/05ec31f2e1fe0ddd653211e041e06c6c8071ffa6/turnstile-example/turnstile/examples/linear/lin%2Bcons.rkt | racket | implicit memory location created
with memory location given
list
cons branch
nil branch | #lang turnstile/base
(extends "lin+tup.rkt")
(require (for-syntax racket/contract))
(provide (type-out MList MList0)
cons nil match-list)
(define-type-constructor MList #:arity = 1)
(define-base-type MList0)
(begin-for-syntax
(current-linear-type? (or/c MList? MList0? (current-linear-type?))))
(define-typed-syntax cons
#:datum-literals (@)
[(_ e e_rest) ≫
[⊢ e ≫ e- ⇒ σ]
[⊢ e_rest ≫ e_rest- ⇐ (MList σ)]
--------
[⊢ (#%app- mcons- e- e_rest-) ⇒ (MList σ)]]
[(_ e e_rest @ e_loc) ≫
[⊢ e ≫ e- ⇒ σ]
[⊢ e_rest ≫ e_rest- ⇐ (MList σ)]
[⊢ e_loc ≫ e_loc- ⇐ MList0]
#:with tmp (generate-temporary #'e_loc)
--------
[⊢ (let- ([tmp e_loc-])
(set-mcar!- tmp e-)
(set-mcdr!- tmp e_rest-)
tmp)
⇒ (MList σ)]])
(define-typed-syntax nil
[(_ {ty:type}) ≫
--------
[⊢ '() ⇒ (MList ty.norm)]]
[(_) ⇐ (~MList σ) ≫
--------
[⊢ '()]])
(define-typed-syntax match-list
#:datum-literals (cons nil @)
[(_ e_list
(~or [(cons x+:id xs+:id @ l+:id) e_cons+]
[(nil) e_nil+]) ...) ≫
#:with [(l x xs e_cons)] #'[(l+ x+ xs+ e_cons+) ...]
#:with [e_nil] #'[e_nil+ ...]
[⊢ e_list ≫ e_list- ⇒ (~MList σ)]
#:with σ_xs ((current-type-eval) #'(MList σ))
#:with σ_l ((current-type-eval) #'MList0)
#:mode (make-linear-branch-mode 2)
#:submode (branch-nth 0)
([[x ≫ x- : σ]
[xs ≫ xs- : σ_xs]
[l ≫ l- : σ_l]
⊢ e_cons ≫ e_cons- ⇒ σ_out]
#:do [(linear-out-of-scope! #'([x- : σ] [xs- : σ_xs] [l- : σ_l]))])
#:submode (branch-nth 1)
([⊢ [e_nil ≫ e_nil- ⇐ σ_out]]))
--------
[⊢ (let- ([l- e_list-])
(if- (null? l-)
e_nil-
(let- ([x- (mcar- l-)]
[xs- (mcdr- l-)])
e_cons-)))
⇒ σ_out]])
|
1dd7a02c838ab7ea2dbc81171de1f942c10f26717ab5d9cc4e0ee4b4f42fbf5d | rtrusso/scp | constant-operand.scm | (need sasm/parse/syntax)
(need sasm/sasm-ast)
(define (sasm-parse-constant-operand expression)
(sasm-parse-by-case
expression
(sasm-syntax-case
:pattern (const (,integer? constant-integer))
:rewrite (constant-integer)
(sasm-ast-node <integer-constant-operand>
(:integer-value constant-integer)))
(sasm-syntax-case
:pattern (const (,symbol? label))
:rewrite (label)
(sasm-ast-node <label-constant-operand>
(:label-value label)
(:referenced-symbol label)
(:resolved-symbol #f)))
(sasm-syntax-case
:pattern (const (,string? constant-string))
:rewrite (constant-string)
(sasm-ast-node <string-constant-operand>
(:string-value constant-string)))
))
| null | https://raw.githubusercontent.com/rtrusso/scp/2051e76df14bd36aef81aba519ffafa62b260f5c/src/sasm/parse/constant-operand.scm | scheme | (need sasm/parse/syntax)
(need sasm/sasm-ast)
(define (sasm-parse-constant-operand expression)
(sasm-parse-by-case
expression
(sasm-syntax-case
:pattern (const (,integer? constant-integer))
:rewrite (constant-integer)
(sasm-ast-node <integer-constant-operand>
(:integer-value constant-integer)))
(sasm-syntax-case
:pattern (const (,symbol? label))
:rewrite (label)
(sasm-ast-node <label-constant-operand>
(:label-value label)
(:referenced-symbol label)
(:resolved-symbol #f)))
(sasm-syntax-case
:pattern (const (,string? constant-string))
:rewrite (constant-string)
(sasm-ast-node <string-constant-operand>
(:string-value constant-string)))
))
|
|
26c826281ba22eff26965752a3a233f7c495a9670c15cc0a2c53367dec3fb745 | hugoduncan/makejack | impl.clj | (ns makejack.deps.impl)
(defn lift-local-deps
"Return a basis with :mvn/local deps converted to source dependencies.
Adds transitive libs, and extends the paths."
[basis]
;; NOTE this could be simpler if we constructed a new deps map and used
;; b/create-basis, but that complains about non-local source paths.
(let [libs (:libs basis)
local-root #(:local/root (get libs %))
transitive-local (fn transitive-local
;; Predicate for lib being a transitive dependency
;; of a direct project dependency.
[lib]
(or (and (local-root lib)
(empty? (:dependents (libs lib))))
(some
transitive-local
(:dependents (libs lib)))))
transitive-deps (reduce-kv
(fn [deps lib {:keys [dependents] :as coords}]
(let [version (:mvn/version coords)]
(if (and version (some local-root dependents))
(assoc deps lib {:mvn/version version})
deps)))
{}
libs)
local-paths (reduce-kv
(fn [ps _lib {:keys [dependents paths] :as coords}]
(if (and (:local/root coords)
(or (empty? dependents)
(some transitive-local dependents)))
(into ps paths)
ps))
[]
libs)
transitive-libs (reduce-kv
(fn [deps lib coords]
(if (transitive-deps lib)
(assoc deps lib (assoc coords :dependents []))
deps))
{}
libs)]
(-> basis
(update :libs #(into {} (remove (comp :local/root val)) %))
(update :libs merge transitive-libs)
(update :deps merge transitive-deps)
(update :deps #(into {} (remove (comp :local/root val)) %))
(update :paths into local-paths))))
| null | https://raw.githubusercontent.com/hugoduncan/makejack/2d2c8950a3c0018899071f6c6d6d0062bbcca8c4/components/deps/src/makejack/deps/impl.clj | clojure | NOTE this could be simpler if we constructed a new deps map and used
b/create-basis, but that complains about non-local source paths.
Predicate for lib being a transitive dependency
of a direct project dependency. | (ns makejack.deps.impl)
(defn lift-local-deps
"Return a basis with :mvn/local deps converted to source dependencies.
Adds transitive libs, and extends the paths."
[basis]
(let [libs (:libs basis)
local-root #(:local/root (get libs %))
transitive-local (fn transitive-local
[lib]
(or (and (local-root lib)
(empty? (:dependents (libs lib))))
(some
transitive-local
(:dependents (libs lib)))))
transitive-deps (reduce-kv
(fn [deps lib {:keys [dependents] :as coords}]
(let [version (:mvn/version coords)]
(if (and version (some local-root dependents))
(assoc deps lib {:mvn/version version})
deps)))
{}
libs)
local-paths (reduce-kv
(fn [ps _lib {:keys [dependents paths] :as coords}]
(if (and (:local/root coords)
(or (empty? dependents)
(some transitive-local dependents)))
(into ps paths)
ps))
[]
libs)
transitive-libs (reduce-kv
(fn [deps lib coords]
(if (transitive-deps lib)
(assoc deps lib (assoc coords :dependents []))
deps))
{}
libs)]
(-> basis
(update :libs #(into {} (remove (comp :local/root val)) %))
(update :libs merge transitive-libs)
(update :deps merge transitive-deps)
(update :deps #(into {} (remove (comp :local/root val)) %))
(update :paths into local-paths))))
|
4fcec4bd3ca66de71ac8182bf541b09a28f7bea676bb749e12dc7f3fda5594fb | clj-kondo/clj-kondo.lsp | version.clj | (ns clj-kondo.lsp-server.impl.version
{:no-doc true}
(:require [clojure.java.io :as io]
[clojure.string :as str]))
(defn -main [& _args]
(let [version (str/trim (slurp (io/resource "CLJ_KONDO_VERSION")))
out-file (io/file ".." "vscode-extension" "CLJ_KONDO_VERSION")]
(println "Generation version file:" version ">" (.getPath out-file))
(io/copy version
out-file)))
| null | https://raw.githubusercontent.com/clj-kondo/clj-kondo.lsp/5a61fecae5b364e556afb59040c2d1a543918fec/server/src/clj_kondo/lsp_server/impl/version.clj | clojure | (ns clj-kondo.lsp-server.impl.version
{:no-doc true}
(:require [clojure.java.io :as io]
[clojure.string :as str]))
(defn -main [& _args]
(let [version (str/trim (slurp (io/resource "CLJ_KONDO_VERSION")))
out-file (io/file ".." "vscode-extension" "CLJ_KONDO_VERSION")]
(println "Generation version file:" version ">" (.getPath out-file))
(io/copy version
out-file)))
|
|
aa0c951ccc51d60e220954055e44c28f7c3817b07ff90309e6926681aaca7fc0 | synrc/shen | shen_app.erl | -module(shen_app).
-behaviour(application).
-export([start/2, stop/1]).
start(_StartType, _StartArgs) -> shen_sup:start_link().
stop(_State) -> ok.
| null | https://raw.githubusercontent.com/synrc/shen/fa954212d9270c4591aff0365b4672f165413315/src/shen_app.erl | erlang | -module(shen_app).
-behaviour(application).
-export([start/2, stop/1]).
start(_StartType, _StartArgs) -> shen_sup:start_link().
stop(_State) -> ok.
|
|
ba27a24a718763f12333ebf0a4f43c84edaad981f2fbb1258a4b20d1a48a334f | djblue/portal | json.cljs | (ns portal.ui.viewer.json
(:require [portal.ui.inspector :as ins]))
(defn- parse-json [json-string]
(try (js->clj (js/JSON.parse json-string) :keywordize-keys true)
(catch :default e (ins/error->data e))))
(defn json? [value] (string? value))
(defn inspect-json [json-string]
[ins/tabs
{:portal.viewer/json (parse-json json-string)
"..." json-string}])
(def viewer
{:predicate json?
:component inspect-json
:name :portal.viewer/json
:doc "Parse a string as JSON. Will render error if parsing fails."})
| null | https://raw.githubusercontent.com/djblue/portal/556bef27f9d3f22d7bf5ab805083e8d6e9e16095/src/portal/ui/viewer/json.cljs | clojure | (ns portal.ui.viewer.json
(:require [portal.ui.inspector :as ins]))
(defn- parse-json [json-string]
(try (js->clj (js/JSON.parse json-string) :keywordize-keys true)
(catch :default e (ins/error->data e))))
(defn json? [value] (string? value))
(defn inspect-json [json-string]
[ins/tabs
{:portal.viewer/json (parse-json json-string)
"..." json-string}])
(def viewer
{:predicate json?
:component inspect-json
:name :portal.viewer/json
:doc "Parse a string as JSON. Will render error if parsing fails."})
|
|
f301b421068247c1ae758576c6b1571606d4f384ba35594d4017db8328ba9a85 | mirage/mirage-qubes | dB.mli | Copyright ( C ) 2015 ,
See the README file for details .
See the README file for details. *)
(** A QubesDB client *)
include S.DB
val connect : domid:int -> unit -> t Lwt.t
* [ connect ~domid ( ) ] is a QubesDB agent which connects to a server in [ domid ] .
val disconnect : t -> unit Lwt.t
(** Close the underlying vchan. *)
| null | https://raw.githubusercontent.com/mirage/mirage-qubes/b2dcdfe29a90f86f9046788da4799abc451a0b9b/lib/dB.mli | ocaml | * A QubesDB client
* Close the underlying vchan. | Copyright ( C ) 2015 ,
See the README file for details .
See the README file for details. *)
include S.DB
val connect : domid:int -> unit -> t Lwt.t
* [ connect ~domid ( ) ] is a QubesDB agent which connects to a server in [ domid ] .
val disconnect : t -> unit Lwt.t
|
c2510dfa53e5ec5a8c9620618e7effc32c8e64f7cbd44ec4ffee2aaf3f679f78 | NelosG/fp-tests | ExceptState.hs | # LANGUAGE FlexibleInstances #
# LANGUAGE StandaloneDeriving #
module Test.ExceptState
( genExceptState
) where
import HW2.T1 (Annotated (..), Except (..))
import HW2.T5 (ExceptState (runES), throwExceptState, wrapExceptState)
import qualified Hedgehog as H
import qualified Hedgehog.Gen as Gen
genExceptState :: (H.Gen x) -> (H.Gen (ExceptState () () x))
genExceptState genX = Gen.choice [wrapExceptState <$> genX, throwExceptState <$> Gen.constant ()]
instance (Eq e, Eq x) => Eq (ExceptState e () x) where
(==) state1 state2 = case s1 of
Error e -> case s2 of
Error e' -> e == e'
Success _ -> False
Success (x1 :# _) -> case s2 of
Success (x2 :# _) -> x1 == x2
Error _ -> False
where
s1 = runES state1 ()
s2 = runES state2 ()
instance (Show e, Show x) => Show (ExceptState e () x) where
show state = show $ runES state ()
deriving instance (Show a, Show e) => Show (Annotated e a)
deriving instance (Show a, Show e) => Show (Except e a)
| null | https://raw.githubusercontent.com/NelosG/fp-tests/2c5da9743a9ed3c0234ad5517efb70a2efb03abd/hw2/test/T5/Test/ExceptState.hs | haskell | # LANGUAGE FlexibleInstances #
# LANGUAGE StandaloneDeriving #
module Test.ExceptState
( genExceptState
) where
import HW2.T1 (Annotated (..), Except (..))
import HW2.T5 (ExceptState (runES), throwExceptState, wrapExceptState)
import qualified Hedgehog as H
import qualified Hedgehog.Gen as Gen
genExceptState :: (H.Gen x) -> (H.Gen (ExceptState () () x))
genExceptState genX = Gen.choice [wrapExceptState <$> genX, throwExceptState <$> Gen.constant ()]
instance (Eq e, Eq x) => Eq (ExceptState e () x) where
(==) state1 state2 = case s1 of
Error e -> case s2 of
Error e' -> e == e'
Success _ -> False
Success (x1 :# _) -> case s2 of
Success (x2 :# _) -> x1 == x2
Error _ -> False
where
s1 = runES state1 ()
s2 = runES state2 ()
instance (Show e, Show x) => Show (ExceptState e () x) where
show state = show $ runES state ()
deriving instance (Show a, Show e) => Show (Annotated e a)
deriving instance (Show a, Show e) => Show (Except e a)
|
|
760047e7e39fb07e9c239d39937cb40fa49b50e673345edfbef4fdcb798fb5b4 | bitc/omegagb | GuiTests.hs | OmegaGB Copyright 2007 Bit
This program is distributed under the terms of the GNU General Public License
-----------------------------------------------------------------------------
-- |
Module : GuiTests
Copyright : ( c ) Bit Connor 2007 < >
-- License : GPL
-- Maintainer :
-- Stability : in-progress
--
-- OmegaGB
-- Game Boy Emulator
--
This module runs a gtk+ application that is some sort of Game Boy
-- debugger. It allows you to step through instructions and view the values
-- of registers, and graphics memory.
--
-----------------------------------------------------------------------------
module GuiTests where
import Maybe(fromJust)
import qualified Control.Exception as C
import Data.IORef
import Data.Bits
import Control.Monad
import Data.Array.MArray
import Data.Word
import Data.Int
import Graphics.UI.Gtk
import Graphics.UI.Gtk.Glade
import WordUtil
import Machine
import Memory
import RomImage
import CpuExecution
import GuiDrawUtil
type State = Maybe (((RegisterStates, Memory), IrqStates), Maybe HandlerId)
test01 :: IO ()
test01 = do
initGUI
windowXml <- C.catch
((xmlNew gladeFile) >>= return . fromJust)
(\e -> putStrLn ("Error Loading " ++ gladeFile) >> C.throwIO e)
return ()
let bindWidget x y = xmlGetWidget windowXml x y
window_main <- bindWidget castToWindow "window_main"
menu_open <- bindWidget castToMenuItem "menu_open"
menu_quit <- bindWidget castToMenuItem "menu_quit"
menu_step <- bindWidget castToMenuItem "menu_step"
menu_run <- bindWidget castToMenuItem "menu_run"
menu_pause <- bindWidget castToMenuItem "menu_pause"
menu_about <- bindWidget castToMenuItem "menu_about"
button_open <- bindWidget castToToolButton "button_open"
button_step <- bindWidget castToToolButton "button_step"
button_run <- bindWidget castToToolButton "button_run"
button_pause <- bindWidget castToToolButton "button_pause"
reg_a <- bindWidget castToEntry "reg_a"
reg_b <- bindWidget castToEntry "reg_b"
reg_c <- bindWidget castToEntry "reg_c"
reg_d <- bindWidget castToEntry "reg_d"
reg_e <- bindWidget castToEntry "reg_e"
reg_f <- bindWidget castToEntry "reg_f"
reg_h <- bindWidget castToEntry "reg_h"
reg_l <- bindWidget castToEntry "reg_l"
reg_pc <- bindWidget castToEntry "reg_pc"
reg_sp <- bindWidget castToEntry "reg_sp"
flag_ime <- bindWidget castToCheckButton "flag_ime"
flag_z <- bindWidget castToEntry "flag_z"
flag_n <- bindWidget castToEntry "flag_n"
flag_h <- bindWidget castToEntry "flag_h"
flag_c <- bindWidget castToEntry "flag_c"
reg_ie <- bindWidget castToEntry "reg_ie"
reg_stat <- bindWidget castToEntry "reg_stat"
dissassembler_textview <- bindWidget castToTextView "dissassembler_textview"
main_notebook <- bindWidget castToNotebook "main_notebook"
map_refresh <- bindWidget castToButton "map_refresh"
map_selector <- bindWidget castToComboBox "map_selector"
map_drawingarea <- bindWidget castToDrawingArea "map_drawingarea"
mapPixBuf <- pixbufNew ColorspaceRgb False 8 256 256
state <- newIORef (Nothing::State)
let setStepSensitivity s = mapM_ (`widgetSetSensitivity` s) [toWidget button_step, toWidget menu_step]
setRunSensitivity s = mapM_ (`widgetSetSensitivity` s) [toWidget button_run, toWidget menu_run]
setPauseSensitivity s = mapM_ (`widgetSetSensitivity` s) [toWidget button_pause, toWidget menu_pause]
------------------------------------------------------------------------
updateRunCommandsSensitivity = do
s <- readIORef state
case s of
Nothing -> do
setStepSensitivity False
setRunSensitivity False
setPauseSensitivity False
Just (_, Nothing) -> do
setStepSensitivity True
setRunSensitivity True
setPauseSensitivity False
Just (_, Just _) -> do
setStepSensitivity False
setRunSensitivity False
setPauseSensitivity True
------------------------------------------------------------------------
updateDebugPanel = do
s <- readIORef state
case s of
Nothing -> return ()
Just (((regS, memS), irqS), _) -> do
reg_a `entrySetText` showHex1 (getRegState regS M_A)
reg_b `entrySetText` showHex1 (getRegState regS M_B)
reg_c `entrySetText` showHex1 (getRegState regS M_C)
reg_d `entrySetText` showHex1 (getRegState regS M_D)
reg_e `entrySetText` showHex1 (getRegState regS M_E)
reg_f `entrySetText` showHex1 (getRegState regS M_F)
reg_h `entrySetText` showHex1 (getRegState regS M_H)
reg_l `entrySetText` showHex1 (getRegState regS M_L)
reg_pc `entrySetText` showHex2 (getReg2State regS M_PC)
reg_sp `entrySetText` showHex2 (getReg2State regS M_SP)
reg_ie `entrySetText` showHex1 (readMem memS 0xFFFF)
reg_stat ` entrySetText ` showHex1 ( readMem )
flag_ime `toggleButtonSetActive` irqStateIME irqS
flag_z `entrySetText` show (fromEnum (testBit (getRegState regS M_F) 7))
flag_n `entrySetText` show (fromEnum (testBit (getRegState regS M_F) 6))
flag_h `entrySetText` show (fromEnum (testBit (getRegState regS M_F) 5))
flag_c `entrySetText` show (fromEnum (testBit (getRegState regS M_F) 4))
------------------------------------------------------------------------
displayCurrentInstruction = do
s <- readIORef state
case s of
Nothing -> return ()
Just (((regS, memS), _), _) -> do
let pc = getReg2State regS M_PC
let instruction = fetchInstruction (regS, memS)
let s = (showHex2 pc) ++ " " ++ (show instruction) ++ "\n"
buffer <- textViewGetBuffer dissassembler_textview
n <- textBufferGetLineCount buffer
when (n > instructionHistoryCount)
(do iterStart <- textBufferGetStartIter buffer
iter1 <- textBufferGetIterAtLine buffer 1
textBufferDelete buffer iterStart iter1)
endIter <- textBufferGetEndIter buffer
textBufferInsert buffer endIter s
------------------------------------------------------------------------
clearInstructionDisplay = do
buffer <- textViewGetBuffer dissassembler_textview
startIter <- textBufferGetStartIter buffer
endIter <- textBufferGetEndIter buffer
textBufferDelete buffer startIter endIter
------------------------------------------------------------------------
step = do
modifyIORef state (\s -> case s of
Nothing -> Nothing
Just (m, b) -> Just (updateMachine m, b))
updateDebugPanel
displayCurrentInstruction
------------------------------------------------------------------------
run = do
handlerId <- idleAdd (replicateM_ 100 step >> return True) priorityDefaultIdle
modifyIORef state (\s -> case s of
Nothing -> Nothing
Just (m, _) -> Just (m, Just handlerId))
updateRunCommandsSensitivity
------------------------------------------------------------------------
pause = do
s <- readIORef state
case s of
Nothing -> return ()
Just (_, Nothing) -> return ()
Just (_, Just handlerId) -> idleRemove handlerId
modifyIORef state (\s -> case s of
Nothing -> Nothing
Just (m, _) -> Just (m, Nothing))
updateRunCommandsSensitivity
------------------------------------------------------------------------
open = do
fileSelect <- fileChooserDialogNew
(Just "Open Game Boy ROM")
(Just window_main)
FileChooserActionOpen
[("gtk-open", ResponseOk), ("gtk-cancel", ResponseDeleteEvent)]
response <- dialogRun fileSelect
case response of
ResponseOk -> do
romFile <- fileChooserGetFilename fileSelect
romImage <- loadRomImage (fromJust romFile)
writeIORef state $ Just (((initialRegisterStates, initMemory romImage),
initialIrqStates),
Nothing)
ResponseDeleteEvent -> do
return ()
widgetDestroy fileSelect
updateRunCommandsSensitivity
updateDebugPanel
clearInstructionDisplay
displayCurrentInstruction
------------------------------------------------------------------------
quit = widgetDestroy window_main >> mainQuit
------------------------------------------------------------------------
getMapViewerSelection :: IO Int
getMapViewerSelection = comboBoxGetActive map_selector >>= return . fromJust
------------------------------------------------------------------------
refreshMapViewer = do
s <- readIORef state
case s of
Nothing -> return ()
Just (((_, mem), _), _) -> do
pbData <- (pixbufGetPixels mapPixBuf :: IO (PixbufData Int Word8))
row <- pixbufGetRowstride mapPixBuf
chan <- pixbufGetNChannels mapPixBuf
bits <- pixbufGetBitsPerSample mapPixBuf
draw into the Pixbuf
mvs <- getMapViewerSelection
case mvs of
0 -> do
doFromTo 0 63 $ \y ->
doFromTo 0 255 $ \x -> do
let yrow = y `div` 8
xrow = x `div` 8
tileNum = yrow * 32 + xrow
tileStartMem = 0x8000 + (16 * tileNum)
xoff = 7 - (x `mod` 8)
yoff = y `mod` 8
hiByte = tileStartMem + (yoff * 2)
loByte = tileStartMem + (yoff * 2) + 1
hiByteValue = readMem mem (fromIntegral hiByte)
loByteValue = readMem mem (fromIntegral loByte)
color = (2 * (fromEnum (testBit loByteValue xoff))) + (fromEnum (testBit hiByteValue xoff))
colorByte = (fromIntegral color) * 85
writeArray pbData (x*chan+y*row) colorByte
writeArray pbData (1+x*chan+y*row) colorByte
writeArray pbData (2+x*chan+y*row) colorByte
doFromTo 64 127 $ \y ->
doFromTo 0 255 $ \x -> do
let yrow = (y-64) `div` 8
xrow = x `div` 8
tileNum = yrow * 32 + xrow
tileStartMem = 0x8F00 + (16 * tileNum)
xoff = 7 - (x `mod` 8)
yoff = (y-64) `mod` 8
hiByte = tileStartMem + (yoff * 2)
loByte = tileStartMem + (yoff * 2) + 1
hiByteValue = readMem mem (fromIntegral hiByte)
loByteValue = readMem mem (fromIntegral loByte)
color = (2 * (fromEnum (testBit loByteValue xoff))) + (fromEnum (testBit hiByteValue xoff))
colorByte = (fromIntegral color) * 85
writeArray pbData (x*chan+y*row) colorByte
writeArray pbData (1+x*chan+y*row) colorByte
writeArray pbData (2+x*chan+y*row) colorByte
1 -> do
doFromTo 0 255 $ \y ->
doFromTo 0 255 $ \x -> do
let yrow = y `div` 8
xrow = x `div` 8
tileNum = yrow * 32 + xrow
tileIndex = readMem mem ((fromIntegral tileNum) + 0x9800)
tileStartMem = 0x8000 + (16 * (fromIntegral tileIndex))
xoff = 7 - (x `mod` 8)
yoff = y `mod` 8
hiByte = tileStartMem + (yoff * 2)
loByte = tileStartMem + (yoff * 2) + 1
hiByteValue = readMem mem (fromIntegral hiByte)
loByteValue = readMem mem (fromIntegral loByte)
color = (2 * (fromEnum (testBit loByteValue xoff))) + (fromEnum (testBit hiByteValue xoff))
colorByte = (fromIntegral color) * 85
writeArray pbData (x*chan+y*row) colorByte
writeArray pbData (1+x*chan+y*row) colorByte
writeArray pbData (2+x*chan+y*row) colorByte
2 -> do
doFromTo 0 255 $ \y ->
doFromTo 0 255 $ \x -> do
let yrow = y `div` 8
xrow = x `div` 8
tileNum = yrow * 32 + xrow
tileIndex = (fromIntegral (readMem mem ((fromIntegral tileNum) + 0x9800)))::Int8
tileStartMem = 0x9000 + (16 * (fromIntegral tileIndex))
xoff = 7 - (x `mod` 8)
yoff = y `mod` 8
hiByte = tileStartMem + (yoff * 2)
loByte = tileStartMem + (yoff * 2) + 1
hiByteValue = readMem mem (fromIntegral hiByte)
loByteValue = readMem mem (fromIntegral loByte)
color = (2 * (fromEnum (testBit loByteValue xoff))) + (fromEnum (testBit hiByteValue xoff))
colorByte = (fromIntegral color) * 85
writeArray pbData (x*chan+y*row) colorByte
writeArray pbData (1+x*chan+y*row) colorByte
writeArray pbData (2+x*chan+y*row) colorByte
widgetQueueDraw map_drawingarea
------------------------------------------------------------------------
comboBoxSetActive map_selector 0
menu_quit `onActivateLeaf` quit
window_main `onDestroy` quit
menu_open `onActivateLeaf` open
button_open `onToolButtonClicked` open
menu_step `onActivateLeaf` step
button_step `onToolButtonClicked` step
menu_run `onActivateLeaf` run
button_run `onToolButtonClicked` run
menu_pause `onActivateLeaf` pause
button_pause `onToolButtonClicked` pause
menu_about `onActivateLeaf` do
dia <- aboutDialogNew
aboutDialogSetName dia "OmegaGB test01"
aboutDialogSetComments dia "Game Boy Emulator Development Test"
aboutDialogSetWebsite dia ""
dialogRun dia
widgetDestroy dia
map_drawingarea `onSizeRequest` return (Requisition 256 256)
map_drawingarea `onExpose` updateCanvas map_drawingarea mapPixBuf
map_refresh `onClicked` refreshMapViewer
main_notebook `onSwitchPage` (\pageNum -> when (pageNum == 1) refreshMapViewer)
map_selector `onChanged` refreshMapViewer
updateRunCommandsSensitivity
-- C.catchJust C.errorCalls
-- mainGUI
-- (\e -> do
" Error "
dialogAddButton dia " gtk - ok " ResponseOk
upper < - dialogGetUpper dia
-- message <- labelNew (Just ("Error: " ++ (show e)))
-- widgetShow message
-- boxPackStartDefaults upper message
-- dialogRun dia
)
mainGUI
return ()
where
gladeFile = "guis/test01/test01.glade"
instructionHistoryCount = 20
| null | https://raw.githubusercontent.com/bitc/omegagb/5ab9c3a22f5fc283906b8af53717d81fef96db7f/src/GuiTests.hs | haskell | ---------------------------------------------------------------------------
|
License : GPL
Maintainer :
Stability : in-progress
OmegaGB
Game Boy Emulator
debugger. It allows you to step through instructions and view the values
of registers, and graphics memory.
---------------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
C.catchJust C.errorCalls
mainGUI
(\e -> do
message <- labelNew (Just ("Error: " ++ (show e)))
widgetShow message
boxPackStartDefaults upper message
dialogRun dia | OmegaGB Copyright 2007 Bit
This program is distributed under the terms of the GNU General Public License
Module : GuiTests
Copyright : ( c ) Bit Connor 2007 < >
This module runs a gtk+ application that is some sort of Game Boy
module GuiTests where
import Maybe(fromJust)
import qualified Control.Exception as C
import Data.IORef
import Data.Bits
import Control.Monad
import Data.Array.MArray
import Data.Word
import Data.Int
import Graphics.UI.Gtk
import Graphics.UI.Gtk.Glade
import WordUtil
import Machine
import Memory
import RomImage
import CpuExecution
import GuiDrawUtil
type State = Maybe (((RegisterStates, Memory), IrqStates), Maybe HandlerId)
test01 :: IO ()
test01 = do
initGUI
windowXml <- C.catch
((xmlNew gladeFile) >>= return . fromJust)
(\e -> putStrLn ("Error Loading " ++ gladeFile) >> C.throwIO e)
return ()
let bindWidget x y = xmlGetWidget windowXml x y
window_main <- bindWidget castToWindow "window_main"
menu_open <- bindWidget castToMenuItem "menu_open"
menu_quit <- bindWidget castToMenuItem "menu_quit"
menu_step <- bindWidget castToMenuItem "menu_step"
menu_run <- bindWidget castToMenuItem "menu_run"
menu_pause <- bindWidget castToMenuItem "menu_pause"
menu_about <- bindWidget castToMenuItem "menu_about"
button_open <- bindWidget castToToolButton "button_open"
button_step <- bindWidget castToToolButton "button_step"
button_run <- bindWidget castToToolButton "button_run"
button_pause <- bindWidget castToToolButton "button_pause"
reg_a <- bindWidget castToEntry "reg_a"
reg_b <- bindWidget castToEntry "reg_b"
reg_c <- bindWidget castToEntry "reg_c"
reg_d <- bindWidget castToEntry "reg_d"
reg_e <- bindWidget castToEntry "reg_e"
reg_f <- bindWidget castToEntry "reg_f"
reg_h <- bindWidget castToEntry "reg_h"
reg_l <- bindWidget castToEntry "reg_l"
reg_pc <- bindWidget castToEntry "reg_pc"
reg_sp <- bindWidget castToEntry "reg_sp"
flag_ime <- bindWidget castToCheckButton "flag_ime"
flag_z <- bindWidget castToEntry "flag_z"
flag_n <- bindWidget castToEntry "flag_n"
flag_h <- bindWidget castToEntry "flag_h"
flag_c <- bindWidget castToEntry "flag_c"
reg_ie <- bindWidget castToEntry "reg_ie"
reg_stat <- bindWidget castToEntry "reg_stat"
dissassembler_textview <- bindWidget castToTextView "dissassembler_textview"
main_notebook <- bindWidget castToNotebook "main_notebook"
map_refresh <- bindWidget castToButton "map_refresh"
map_selector <- bindWidget castToComboBox "map_selector"
map_drawingarea <- bindWidget castToDrawingArea "map_drawingarea"
mapPixBuf <- pixbufNew ColorspaceRgb False 8 256 256
state <- newIORef (Nothing::State)
let setStepSensitivity s = mapM_ (`widgetSetSensitivity` s) [toWidget button_step, toWidget menu_step]
setRunSensitivity s = mapM_ (`widgetSetSensitivity` s) [toWidget button_run, toWidget menu_run]
setPauseSensitivity s = mapM_ (`widgetSetSensitivity` s) [toWidget button_pause, toWidget menu_pause]
updateRunCommandsSensitivity = do
s <- readIORef state
case s of
Nothing -> do
setStepSensitivity False
setRunSensitivity False
setPauseSensitivity False
Just (_, Nothing) -> do
setStepSensitivity True
setRunSensitivity True
setPauseSensitivity False
Just (_, Just _) -> do
setStepSensitivity False
setRunSensitivity False
setPauseSensitivity True
updateDebugPanel = do
s <- readIORef state
case s of
Nothing -> return ()
Just (((regS, memS), irqS), _) -> do
reg_a `entrySetText` showHex1 (getRegState regS M_A)
reg_b `entrySetText` showHex1 (getRegState regS M_B)
reg_c `entrySetText` showHex1 (getRegState regS M_C)
reg_d `entrySetText` showHex1 (getRegState regS M_D)
reg_e `entrySetText` showHex1 (getRegState regS M_E)
reg_f `entrySetText` showHex1 (getRegState regS M_F)
reg_h `entrySetText` showHex1 (getRegState regS M_H)
reg_l `entrySetText` showHex1 (getRegState regS M_L)
reg_pc `entrySetText` showHex2 (getReg2State regS M_PC)
reg_sp `entrySetText` showHex2 (getReg2State regS M_SP)
reg_ie `entrySetText` showHex1 (readMem memS 0xFFFF)
reg_stat ` entrySetText ` showHex1 ( readMem )
flag_ime `toggleButtonSetActive` irqStateIME irqS
flag_z `entrySetText` show (fromEnum (testBit (getRegState regS M_F) 7))
flag_n `entrySetText` show (fromEnum (testBit (getRegState regS M_F) 6))
flag_h `entrySetText` show (fromEnum (testBit (getRegState regS M_F) 5))
flag_c `entrySetText` show (fromEnum (testBit (getRegState regS M_F) 4))
displayCurrentInstruction = do
s <- readIORef state
case s of
Nothing -> return ()
Just (((regS, memS), _), _) -> do
let pc = getReg2State regS M_PC
let instruction = fetchInstruction (regS, memS)
let s = (showHex2 pc) ++ " " ++ (show instruction) ++ "\n"
buffer <- textViewGetBuffer dissassembler_textview
n <- textBufferGetLineCount buffer
when (n > instructionHistoryCount)
(do iterStart <- textBufferGetStartIter buffer
iter1 <- textBufferGetIterAtLine buffer 1
textBufferDelete buffer iterStart iter1)
endIter <- textBufferGetEndIter buffer
textBufferInsert buffer endIter s
clearInstructionDisplay = do
buffer <- textViewGetBuffer dissassembler_textview
startIter <- textBufferGetStartIter buffer
endIter <- textBufferGetEndIter buffer
textBufferDelete buffer startIter endIter
step = do
modifyIORef state (\s -> case s of
Nothing -> Nothing
Just (m, b) -> Just (updateMachine m, b))
updateDebugPanel
displayCurrentInstruction
run = do
handlerId <- idleAdd (replicateM_ 100 step >> return True) priorityDefaultIdle
modifyIORef state (\s -> case s of
Nothing -> Nothing
Just (m, _) -> Just (m, Just handlerId))
updateRunCommandsSensitivity
pause = do
s <- readIORef state
case s of
Nothing -> return ()
Just (_, Nothing) -> return ()
Just (_, Just handlerId) -> idleRemove handlerId
modifyIORef state (\s -> case s of
Nothing -> Nothing
Just (m, _) -> Just (m, Nothing))
updateRunCommandsSensitivity
open = do
fileSelect <- fileChooserDialogNew
(Just "Open Game Boy ROM")
(Just window_main)
FileChooserActionOpen
[("gtk-open", ResponseOk), ("gtk-cancel", ResponseDeleteEvent)]
response <- dialogRun fileSelect
case response of
ResponseOk -> do
romFile <- fileChooserGetFilename fileSelect
romImage <- loadRomImage (fromJust romFile)
writeIORef state $ Just (((initialRegisterStates, initMemory romImage),
initialIrqStates),
Nothing)
ResponseDeleteEvent -> do
return ()
widgetDestroy fileSelect
updateRunCommandsSensitivity
updateDebugPanel
clearInstructionDisplay
displayCurrentInstruction
quit = widgetDestroy window_main >> mainQuit
getMapViewerSelection :: IO Int
getMapViewerSelection = comboBoxGetActive map_selector >>= return . fromJust
refreshMapViewer = do
s <- readIORef state
case s of
Nothing -> return ()
Just (((_, mem), _), _) -> do
pbData <- (pixbufGetPixels mapPixBuf :: IO (PixbufData Int Word8))
row <- pixbufGetRowstride mapPixBuf
chan <- pixbufGetNChannels mapPixBuf
bits <- pixbufGetBitsPerSample mapPixBuf
draw into the Pixbuf
mvs <- getMapViewerSelection
case mvs of
0 -> do
doFromTo 0 63 $ \y ->
doFromTo 0 255 $ \x -> do
let yrow = y `div` 8
xrow = x `div` 8
tileNum = yrow * 32 + xrow
tileStartMem = 0x8000 + (16 * tileNum)
xoff = 7 - (x `mod` 8)
yoff = y `mod` 8
hiByte = tileStartMem + (yoff * 2)
loByte = tileStartMem + (yoff * 2) + 1
hiByteValue = readMem mem (fromIntegral hiByte)
loByteValue = readMem mem (fromIntegral loByte)
color = (2 * (fromEnum (testBit loByteValue xoff))) + (fromEnum (testBit hiByteValue xoff))
colorByte = (fromIntegral color) * 85
writeArray pbData (x*chan+y*row) colorByte
writeArray pbData (1+x*chan+y*row) colorByte
writeArray pbData (2+x*chan+y*row) colorByte
doFromTo 64 127 $ \y ->
doFromTo 0 255 $ \x -> do
let yrow = (y-64) `div` 8
xrow = x `div` 8
tileNum = yrow * 32 + xrow
tileStartMem = 0x8F00 + (16 * tileNum)
xoff = 7 - (x `mod` 8)
yoff = (y-64) `mod` 8
hiByte = tileStartMem + (yoff * 2)
loByte = tileStartMem + (yoff * 2) + 1
hiByteValue = readMem mem (fromIntegral hiByte)
loByteValue = readMem mem (fromIntegral loByte)
color = (2 * (fromEnum (testBit loByteValue xoff))) + (fromEnum (testBit hiByteValue xoff))
colorByte = (fromIntegral color) * 85
writeArray pbData (x*chan+y*row) colorByte
writeArray pbData (1+x*chan+y*row) colorByte
writeArray pbData (2+x*chan+y*row) colorByte
1 -> do
doFromTo 0 255 $ \y ->
doFromTo 0 255 $ \x -> do
let yrow = y `div` 8
xrow = x `div` 8
tileNum = yrow * 32 + xrow
tileIndex = readMem mem ((fromIntegral tileNum) + 0x9800)
tileStartMem = 0x8000 + (16 * (fromIntegral tileIndex))
xoff = 7 - (x `mod` 8)
yoff = y `mod` 8
hiByte = tileStartMem + (yoff * 2)
loByte = tileStartMem + (yoff * 2) + 1
hiByteValue = readMem mem (fromIntegral hiByte)
loByteValue = readMem mem (fromIntegral loByte)
color = (2 * (fromEnum (testBit loByteValue xoff))) + (fromEnum (testBit hiByteValue xoff))
colorByte = (fromIntegral color) * 85
writeArray pbData (x*chan+y*row) colorByte
writeArray pbData (1+x*chan+y*row) colorByte
writeArray pbData (2+x*chan+y*row) colorByte
2 -> do
doFromTo 0 255 $ \y ->
doFromTo 0 255 $ \x -> do
let yrow = y `div` 8
xrow = x `div` 8
tileNum = yrow * 32 + xrow
tileIndex = (fromIntegral (readMem mem ((fromIntegral tileNum) + 0x9800)))::Int8
tileStartMem = 0x9000 + (16 * (fromIntegral tileIndex))
xoff = 7 - (x `mod` 8)
yoff = y `mod` 8
hiByte = tileStartMem + (yoff * 2)
loByte = tileStartMem + (yoff * 2) + 1
hiByteValue = readMem mem (fromIntegral hiByte)
loByteValue = readMem mem (fromIntegral loByte)
color = (2 * (fromEnum (testBit loByteValue xoff))) + (fromEnum (testBit hiByteValue xoff))
colorByte = (fromIntegral color) * 85
writeArray pbData (x*chan+y*row) colorByte
writeArray pbData (1+x*chan+y*row) colorByte
writeArray pbData (2+x*chan+y*row) colorByte
widgetQueueDraw map_drawingarea
comboBoxSetActive map_selector 0
menu_quit `onActivateLeaf` quit
window_main `onDestroy` quit
menu_open `onActivateLeaf` open
button_open `onToolButtonClicked` open
menu_step `onActivateLeaf` step
button_step `onToolButtonClicked` step
menu_run `onActivateLeaf` run
button_run `onToolButtonClicked` run
menu_pause `onActivateLeaf` pause
button_pause `onToolButtonClicked` pause
menu_about `onActivateLeaf` do
dia <- aboutDialogNew
aboutDialogSetName dia "OmegaGB test01"
aboutDialogSetComments dia "Game Boy Emulator Development Test"
aboutDialogSetWebsite dia ""
dialogRun dia
widgetDestroy dia
map_drawingarea `onSizeRequest` return (Requisition 256 256)
map_drawingarea `onExpose` updateCanvas map_drawingarea mapPixBuf
map_refresh `onClicked` refreshMapViewer
main_notebook `onSwitchPage` (\pageNum -> when (pageNum == 1) refreshMapViewer)
map_selector `onChanged` refreshMapViewer
updateRunCommandsSensitivity
" Error "
dialogAddButton dia " gtk - ok " ResponseOk
upper < - dialogGetUpper dia
)
mainGUI
return ()
where
gladeFile = "guis/test01/test01.glade"
instructionHistoryCount = 20
|
00077994e676e573a7bdf07f5bc077c94aafe6df1549d84744e57648dc37baad | dbuenzli/jsonc | testing_backend.mli | ---------------------------------------------------------------------------
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%%
---------------------------------------------------------------------------*)
(** Testing for [Jsont_jsonm]. *)
val decoder : string -> Jsont_codec.decoder * (unit -> unit)
val encoder : unit -> Jsont_codec.encoder * (unit -> unit) *
(Jsont_codec.encoder -> string)
---------------------------------------------------------------------------
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/dbuenzli/jsonc/b6adf836a2812f25d934e85ba3b6daa5fe77fd14/test-jsonm/testing_backend.mli | ocaml | * Testing for [Jsont_jsonm]. | ---------------------------------------------------------------------------
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%%
---------------------------------------------------------------------------*)
val decoder : string -> Jsont_codec.decoder * (unit -> unit)
val encoder : unit -> Jsont_codec.encoder * (unit -> unit) *
(Jsont_codec.encoder -> string)
---------------------------------------------------------------------------
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.
---------------------------------------------------------------------------*)
|
14237eaa536cd234288c06e3a0353f021885df815bce94b76d5d58dfd69e834f | helium/blockchain-core | blockchain_state_channels_client.erl | %%%-------------------------------------------------------------------
%% @doc
%% == Blockchain State Channels Client ==
%% @end
%%%-------------------------------------------------------------------
-module(blockchain_state_channels_client).
-behavior(gen_server).
%% ------------------------------------------------------------------
%% API Function Exports
%% ------------------------------------------------------------------
-export([start_link/1,
packet/3,
purchase/2,
banner/2,
reject/2,
gc_state_channels/1,
get_known_channels/1,
response/1]).
%% ------------------------------------------------------------------
%% gen_server exports
%% ------------------------------------------------------------------
-export([init/1,
handle_call/3,
handle_info/2,
handle_cast/2,
terminate/2,
code_change/3]).
-include("blockchain.hrl").
-include("blockchain_rocks.hrl").
-include("blockchain_vars.hrl").
-include_lib("grpc/autogen/server/state_channel_pb.hrl").
-define(SERVER, ?MODULE).
-define(ROUTING_CACHE, sc_client_routing).
6 hours in seconds
-record(state,{
db :: rocksdb:db_handle(),
cf :: rocksdb:cf_handle(),
swarm :: pid(),
swarm_tid :: ets:tab(),
pubkey_bin :: libp2p_crypto:pubkey_bin(),
sig_fun :: libp2p_crypto:sig_fun(),
chain = undefined :: undefined | blockchain:blockchain(),
streams = #{} :: streams(),
packets = #{} :: #{pid() => queue:queue(blockchain_helium_packet_v1:packet())},
waiting = #{} :: waiting(),
TODO GC these
sc_client_transport_handler :: atom(),
routers = [] :: list(netid_to_oui())
}).
-type state() :: #state{}.
-type stream_key() :: non_neg_integer() | string().
-type stream_val() :: undefined | dialing | {unverified, pid()} | pid().
-type streams() :: #{stream_key() => stream_val()}.
-type waiting_packet() :: {Packet :: blockchain_helium_packet_v1:packet(), Region :: atom(), ReceivedTime :: non_neg_integer()}.
-type waiting_key() :: non_neg_integer() | string().
-type waiting() :: #{waiting_key() => [waiting_packet()]}.
-type netid_to_oui() :: {pos_integer(), pos_integer()}.
-ifdef(TEST).
-export([
set_routers/2,
get_routers/1,
get_waiting/1,
handle_route_by_netid/6
]).
-spec set_routers(list(string()), blockchain:blockchain()) -> state().
set_routers(Routers, Chain) -> #state{chain=Chain, routers=Routers}.
-spec get_routers(state()) -> list(netid_to_oui()).
get_routers(State) -> State#state.routers.
-spec get_waiting(state()) -> waiting().
get_waiting(State) -> State#state.waiting.
-endif.
%% ------------------------------------------------------------------
%% API Function Definitions
%% ------------------------------------------------------------------
start_link(Args) ->
gen_server:start_link({local, ?SERVER}, ?SERVER, Args, []).
-spec response(blockchain_state_channel_response_v1:response()) -> any().
response(Resp) ->
erlang:spawn(fun() ->
case application:get_env(blockchain, sc_client_handler, undefined) of
undefined ->
ok;
Mod when is_atom(Mod) ->
Mod:handle_response(Resp)
end
end).
-spec packet(Packet :: blockchain_helium_packet_v1:packet(),
DefaultRouters :: [string()],
Region :: atom()) -> ok.
packet(Packet, DefaultRouters, Region) ->
gen_server:cast(?SERVER, {packet, Packet, DefaultRouters, Region, erlang:system_time(millisecond)}).
-spec get_known_channels(SCID :: blockchain_state_channel_v1:id()) -> {ok, [blockchain_state_channel_v1:state_channel()]} | {error, any()}.
get_known_channels(SCID) ->
gen_server:call(?SERVER, {get_known_channels, SCID}).
-spec purchase(Purchase :: blockchain_state_channel_purchase_v1:purchase(),
HandlerPid :: pid()) -> ok.
purchase(Purchase, HandlerPid) ->
gen_server:cast(?SERVER, {purchase, Purchase, HandlerPid}).
-spec banner(Banner :: blockchain_state_channel_banner_v1:banner(),
HandlerPid :: pid()) -> ok.
banner(Banner, HandlerPid) ->
gen_server:cast(?SERVER, {banner, Banner, HandlerPid}).
-spec reject(Rejection :: blockchain_state_channel_rejection_v1:rejection(),
HandlerPid :: pid()) -> ok.
reject(Rejection, HandlerPid) ->
gen_server:cast(?SERVER, {reject, Rejection, HandlerPid}).
gc_state_channels([]) -> ok;
gc_state_channels(SCIDs) ->
gen_server:cast(?SERVER, {gc_state_channels, SCIDs}).
%% ------------------------------------------------------------------
%% init, terminate and code_change
%% ------------------------------------------------------------------
init(Args) ->
SCClientTransportHandler = application:get_env(blockchain, sc_client_transport_handler, blockchain_state_channel_handler),
lager:info("~p init with ~p hanlder: ~p", [?SERVER, Args, SCClientTransportHandler]),
ok = blockchain_event:add_handler(self()),
Swarm = maps:get(swarm, Args),
SwarmTID = libp2p_swarm:tid(Swarm),
DB = blockchain_state_channels_db_owner:db(),
CF = blockchain_state_channels_db_owner:sc_clients_cf(),
{PubkeyBin, SigFun} = blockchain_utils:get_pubkeybin_sigfun(Swarm),
erlang:send_after(500, self(), post_init),
State = #state{db=DB, cf=CF, swarm=Swarm, swarm_tid=SwarmTID, pubkey_bin=PubkeyBin, sig_fun=SigFun, sc_client_transport_handler = SCClientTransportHandler},
{ok, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%% ------------------------------------------------------------------
%% gen_server message handling
%% ------------------------------------------------------------------
handle_cast({banner, Banner, HandlerPid}, #state{sc_client_transport_handler = Handler} = State) ->
case blockchain_state_channel_banner_v1:sc(Banner) of
undefined ->
TODO in theory if you 're in the same OUI as the router this is ok
{noreply, State};
BannerSC ->
case is_valid_sc(BannerSC, State) of
{error, causal_conflict} ->
lager:error("causal_conflict for banner sc_id: ~p", [blockchain_state_channel_v1:id(BannerSC)]),
_ = Handler:close(HandlerPid),
ok = append_state_channel(BannerSC, State),
{noreply, State};
{error, Reason} ->
lager:error("reason: ~p", [Reason]),
_ = Handler:close(HandlerPid),
{noreply, State};
ok ->
overwrite_state_channel(BannerSC, State),
AddressOrOUI = lookup_stream_id(HandlerPid, State),
{noreply, maybe_send_packets(AddressOrOUI, HandlerPid, State)}
end
end;
%% Handle Uplink packets
handle_cast({packet,
#packet_pb{routing = #routing_information_pb{data = {devaddr, DevAddr}}} = Packet,
DefaultRouters, Region, ReceivedTime},
State)
when is_integer(DevAddr) andalso DevAddr > 0 ->
State2 =
handle_route_by_netid(Packet, DevAddr, DefaultRouters, Region, ReceivedTime, State),
{noreply, State2};
%% Handle Join packets
handle_cast({packet, Packet, DefaultRouters, Region, ReceivedTime}, #state{chain=Chain}=State) ->
State2 =
handle_packet_routing(Packet, Chain, DefaultRouters, Region, ReceivedTime, State),
{noreply, State2};
handle_cast({reject, Rejection, HandlerPid}, State) ->
lager:warning("Got rejection: ~p for: ~p, dropping packet", [Rejection, HandlerPid]),
NewState = case dequeue_packet(HandlerPid, State) of
{undefined, State} -> State;
{_, NS} -> NS
end,
{noreply, NewState};
handle_cast({gc_state_channels, SCIDs}, #state{pending_closes=P, db=DB, cf=CF}=State) ->
lists:foreach(fun(SCID) ->
rocksdb:delete(DB, CF, SCID, [])
end, SCIDs),
{noreply, State#state{pending_closes=P -- SCIDs}};
handle_cast({purchase, Purchase, HandlerPid}, State) ->
NewState = handle_purchase(Purchase, HandlerPid, State),
{noreply, NewState};
handle_cast(_Msg, State) ->
lager:debug("unhandled receive: ~p", [_Msg]),
{noreply, State}.
handle_call({get_known_channels, SCID}, _From, State) ->
{reply, get_state_channels(SCID, State), State};
handle_call(_, _, State) ->
{reply, ok, State}.
handle_info(post_init, #state{chain=undefined}=State) ->
case blockchain_worker:blockchain() of
undefined ->
erlang:send_after(500, self(), post_init),
{noreply, State};
Chain ->
%% Also scan incoming blocks for updates; see add_block event.
State1 = chain_var_routers_by_netid_to_oui(Chain, State),
{noreply, State1#state{chain=Chain}}
end;
handle_info({blockchain_event, {new_chain, NC}}, State) ->
State1 = chain_var_routers_by_netid_to_oui(NC, State),
{noreply, State1#state{chain=NC}};
handle_info({dial_fail, AddressOrOUI, _Reason}, State0) ->
Packets = get_waiting_packet(AddressOrOUI, State0),
lager:error("failed to dial ~p: ~p dropping ~p packets", [AddressOrOUI, _Reason, erlang:length(Packets)+1]),
State1 = remove_packet_from_waiting(AddressOrOUI, delete_stream(AddressOrOUI, State0)),
{noreply, State1};
handle_info({dial_success, AddressOrOUI, Stream}, #state{chain=undefined}=State) ->
%% We somehow lost the chain here, likely we were restarting and haven't gotten it yet
%% There really isn't anything we can do about it, but we should probably keep this stream
%% (if we don't already have it)
%%
%% NOTE: We don't keep the packets we were waiting on as we lost the chain, maybe we should?
NewState = case find_stream(AddressOrOUI, State) of
undefined ->
erlang:monitor(process, Stream),
add_stream(AddressOrOUI, Stream, State);
_ ->
State
end,
{noreply, NewState};
handle_info({dial_success, OUIOrAddress, Stream}, State0) ->
erlang:monitor(process, Stream),
State1 = add_stream(OUIOrAddress, Stream, State0),
case ?get_var(?sc_version, blockchain:ledger(State1#state.chain)) of
{ok, N} when N >= 2 ->
{noreply, State1};
_ ->
{noreply, maybe_send_packets(OUIOrAddress, Stream, State1)}
end;
handle_info({blockchain_event, {add_block, _BlockHash, true, Ledger}}, State)
when Ledger =/= undefined ->
SCs = state_channels(State),
{ok, LedgerHeight} = blockchain_ledger_v1:current_height(Ledger),
SCGrace = case ?get_var(?sc_grace_blocks, Ledger) of
{ok, G} -> G;
_ -> 0
end,
lists:foreach(fun([H|_]) ->
ExpireAt = blockchain_state_channel_v1:expire_at_block(H),
SCID = blockchain_state_channel_v1:id(H),
case LedgerHeight > ExpireAt + SCGrace of
true ->
%% it's dead, remove it
rocksdb:delete(State#state.db, State#state.cf, SCID, []);
false ->
ok
end
end, SCs),
State1 = chain_var_ledger_routers_by_netid_to_oui(Ledger, State),
{noreply, State1};
handle_info({blockchain_event, {add_block, BlockHash, false, Ledger}},
#state{chain=Chain, pubkey_bin=PubkeyBin, sig_fun=SigFun, pending_closes=PendingCloses}=State) when Chain /= undefined ->
Block =
case blockchain:get_block(BlockHash, Chain) of
{error, Reason} ->
lager:error("Couldn't get block with hash: ~p, reason: ~p", [BlockHash, Reason]),
undefined;
{ok, B} ->
B
end,
case Block of
undefined ->
ok;
Block ->
Txns = lists:filter(fun(T) -> blockchain_txn:type(T) == blockchain_txn_routing_v1 end,
blockchain_block:transactions(Block)),
case erlang:length(Txns) > 0 of
false -> ok;
true ->
Cache = persistent_term:get(?routing_cache),
cream:drain(Cache)
end
end,
ClosingChannels =
case Block of
undefined ->
[];
Block ->
lists:foldl(
fun(T, Acc) ->
case blockchain_txn:type(T) == blockchain_txn_state_channel_close_v1 of
true ->
SC = blockchain_txn_state_channel_close_v1:state_channel(T),
SCID = blockchain_txn_state_channel_close_v1:state_channel_id(T),
case lists:member(SCID, PendingCloses) orelse
is_causally_correct_sc(SC, State) of
true ->
ok;
false ->
%% submit our own close with the conflicting view(s)
close_state_channel(SC, State)
end,
%% add it to the list of closing channels so we don't try to double
%% close it below, irregardless of if we're disputing it
[SCID|Acc];
false ->
Acc
end
end,
[],
blockchain_block:transactions(Block))
end,
%% check if any other channels are expiring
SCGrace = case ?get_var(?sc_grace_blocks, Ledger) of
{ok, G} -> G;
_ -> 0
end,
SCs = state_channels(State),
{ok, LedgerHeight} = blockchain_ledger_v1:current_height(Ledger),
ExpiringChannels = lists:foldl(fun([H|_]=SC, Acc) ->
ExpireAt = blockchain_state_channel_v1:expire_at_block(H),
SCID = blockchain_state_channel_v1:id(H),
SCOwner = blockchain_state_channel_v1:owner(H),
case (not lists:member(SCID, PendingCloses ++ ClosingChannels)) andalso
divide by 3 here so we give the server a chance to file its close first
%% before the client tries to file a close
LedgerHeight >= ExpireAt + (SCGrace div 3) andalso
LedgerHeight =< ExpireAt + SCGrace of
true ->
case length(SC) of
1 ->
%% check in the ledger that this sc is not already closing
case blockchain_ledger_v1:find_state_channel(SCID, SCOwner, Ledger) of
{error, _} ->
%% don't do anything
ok;
{ok, LSC} ->
case blockchain_ledger_state_channel_v2:is_v2(LSC) of
false ->
%% ignore v1 state channels
ok;
true ->
case blockchain_ledger_state_channel_v2:close_state(LSC) of
undefined ->
Txn = blockchain_txn_state_channel_close_v1:new(H, PubkeyBin),
SignedTxn = blockchain_txn_state_channel_close_v1:sign(Txn, SigFun),
ok = blockchain_worker:submit_txn(SignedTxn);
_ ->
%% already in closed/dispute state in ledger, do nothing
ok
end
end
end;
_ ->
%% close with conflict
close_state_channel(H, State)
end,
[SCID|Acc];
false ->
Acc
end
end, [], SCs),
{noreply, State#state{pending_closes=lists:usort(PendingCloses ++ ClosingChannels ++ ExpiringChannels)}};
handle_info({blockchain_event, {add_block, _BlockHash, _Syncing, _Ledger}}, State) ->
{noreply, State};
handle_info({'DOWN', _Ref, process, Pid, _}, #state{streams=Streams, packets=Packets}=State) ->
FilteredStreams = maps:filter(fun(_Name, {unverified, Stream}) ->
Stream /= Pid;
(_Name, Stream) ->
Stream /= Pid
end, Streams),
%% Keep the streams which don't have downed pid, given we're monitoring correctly
FilteredPackets = maps:filter(fun(StreamPid, _PacketQueue) ->
StreamPid /= Pid
end, Packets),
{noreply, State#state{streams=FilteredStreams, packets=FilteredPackets}};
handle_info(_Msg, State) ->
lager:warning("rcvd unknown info msg: ~p", [_Msg]),
{noreply, State}.
%% ------------------------------------------------------------------
%% Internal Function Definitions
%% ------------------------------------------------------------------
-spec handle_packet(Packet :: blockchain_helium_packet_v1:packet(),
RoutesOrAddresses :: [string()] | [blockchain_ledger_routing_v1:routing()],
Region :: atom(),
ReceivedTime :: non_neg_integer(),
State :: state()) -> state().
handle_packet(Packet, RoutesOrAddresses, Region, ReceivedTime, #state{swarm_tid=SwarmTID,
sc_client_transport_handler = SCClientTransportHandler}=State0) ->
lager:info("handle_packet ~p to ~p with handler ~p", [lager:pr(Packet, blockchain_helium_packet_v1), print_routes(RoutesOrAddresses), SCClientTransportHandler]),
lists:foldl(
fun(RouteOrAddress, StateAcc) ->
StreamKey = case blockchain_ledger_routing_v1:is_routing(RouteOrAddress) of
false ->
{address, RouteOrAddress};
true ->
{oui, blockchain_ledger_routing_v1:oui(RouteOrAddress)}
end,
case StreamKey of
{address, Address} ->
case find_stream(Address, StateAcc) of
undefined ->
lager:debug("stream undef dialing first, address: ~p", [Address]),
ok = dial(SCClientTransportHandler, SwarmTID, RouteOrAddress),
add_packet_to_waiting(Address, {Packet, Region, ReceivedTime}, add_stream(Address, dialing, StateAcc));
dialing ->
lager:debug("stream is still dialing queueing packet, address: ~p", [Address]),
add_packet_to_waiting(Address, {Packet, Region, ReceivedTime}, StateAcc);
{unverified, _Stream} ->
%% queue it until we get a banner
lager:debug("unverified stream, add_packet_to_waiting, address: ~p", [Address]),
add_packet_to_waiting(Address, {Packet, Region, ReceivedTime}, StateAcc);
Stream ->
lager:debug("stream ~p, send_packet_when_v1, address: ~p", [Stream, Address]),
send_packet_when_v1(Stream, Packet, Region, ReceivedTime, StateAcc)
end;
{oui, OUI} ->
case find_stream(OUI, StateAcc) of
undefined ->
lager:debug("stream undef dialing first, oui: ~p", [OUI]),
ok = dial(SCClientTransportHandler, SwarmTID, RouteOrAddress),
add_packet_to_waiting(OUI, {Packet, Region, ReceivedTime}, add_stream(OUI, dialing, StateAcc));
dialing ->
lager:debug("stream is still dialing queueing packet, oui: ~p", [OUI]),
add_packet_to_waiting(OUI, {Packet, Region, ReceivedTime}, StateAcc);
{unverified, _Stream} ->
%% queue it until we get a banner
lager:debug("unverified stream, add_packet_to_waiting, oui: ~p", [OUI]),
add_packet_to_waiting(OUI, {Packet, Region, ReceivedTime}, StateAcc);
Stream ->
lager:debug("got stream: ~p, send_packet_or_offer, oui: ~p", [Stream, OUI]),
send_packet_or_offer(Stream, OUI, Packet, Region, ReceivedTime, StateAcc)
end
end
end,
State0,
RoutesOrAddresses
).
-spec handle_purchase(Purchase :: blockchain_state_channel_purchase_v1:purchase(),
Stream :: pid(),
State :: state()) -> state().
handle_purchase(Purchase, Stream,
#state{chain=Chain, pubkey_bin=PubkeyBin, sig_fun=SigFun}=State) ->
PurchaseSC = blockchain_state_channel_purchase_v1:sc(Purchase),
case is_valid_sc(PurchaseSC, State) of
{error, Reason} when Reason == inactive_sc orelse Reason == no_chain ->
lager:info("we don't know about ~p, lets send packet anyway", [blockchain_state_channel_v1:id(PurchaseSC)]),
case dequeue_packet(Stream, State) of
{undefined, State1} ->
lager:debug("failed dequeue_packet, stream: ~p, purchase: ~p", [Stream, Purchase]),
State1;
{{Packet, ReceivedTime}, State1} ->
Region = blockchain_state_channel_purchase_v1:region(Purchase),
ok = send_packet(PubkeyBin, SigFun, Stream, Packet, Region, ReceivedTime),
State1
end;
{error, causal_conflict} ->
lager:error("causal_conflict for purchase sc_id: ~p", [blockchain_state_channel_v1:id(PurchaseSC)]),
ok = append_state_channel(PurchaseSC, State),
_ = libp2p_framed_stream:close(Stream),
State;
{error, Reason} ->
lager:error("failed sc validation, closing stream: ~p, reason: ~p", [Stream, Reason]),
_ = libp2p_framed_stream:close(Stream),
State;
ok ->
Ledger = blockchain:ledger(Chain),
DCBudget = blockchain_state_channel_v1:amount(PurchaseSC),
TotalDCs = blockchain_state_channel_v1:total_dcs(PurchaseSC),
RemainingDCs = max(0, DCBudget - TotalDCs),
case blockchain_ledger_v1:is_state_channel_overpaid(PurchaseSC, Ledger) of
true ->
lager:error("insufficient dcs for purchase sc: ~p: ~p - ~p = ~p", [PurchaseSC, DCBudget, TotalDCs, RemainingDCs]),
_ = libp2p_framed_stream:close(Stream),
%% we don't need to keep a sibling here as proof of misbehaviour is standalone
%% this will conflict or dominate any later attempt to close within spec
ok = overwrite_state_channel(PurchaseSC, State),
State;
false ->
case dequeue_packet(Stream, State) of
{undefined, State0} ->
%% NOTE: We somehow don't have this packet in our queue,
%% All we do is store the state channel by overwriting instead of appending
%% since there was not a causal conflict
ok = overwrite_state_channel(PurchaseSC, State0),
lager:debug("failed dequeue_packet, stream: ~p, purchase: ~p", [Stream, Purchase]),
State0;
{{Packet, ReceivedTime}, NewState} ->
Payload = blockchain_helium_packet_v1:payload(Packet),
PacketDCs = blockchain_utils:calculate_dc_amount(Ledger, byte_size(Payload)),
case RemainingDCs >= PacketDCs of
false ->
lager:error("current packet (~p) (dc charge: ~p) will exceed remaining DCs (~p) in this SC, dropping",
[Packet, PacketDCs, RemainingDCs]),
_ = libp2p_framed_stream:close(Stream),
NewState;
true ->
now we need to make sure that our DC count between the previous
and the current SC is _ at least _ increased by this packet 's
%% DC cost.
PrevTotal = get_previous_total_dcs(PurchaseSC, NewState),
case (TotalDCs - PrevTotal) >= PacketDCs of
true ->
Region = blockchain_state_channel_purchase_v1:region(Purchase),
lager:debug("successful purchase validation, sending packet: ~p",
[blockchain_helium_packet_v1:packet_hash(Packet)]),
ok = send_packet(PubkeyBin, SigFun, Stream, Packet, Region, ReceivedTime),
ok = overwrite_state_channel(PurchaseSC, NewState),
NewState;
false ->
%% We are not getting paid, so drop this packet and
%% do not send it. Close the stream.
lager:error("purchase not valid - did not pay for packet: ~p, dropping.",
[Packet]),
_ = libp2p_framed_stream:close(Stream),
%% append this state channel, so we know about it later
ok = overwrite_state_channel(PurchaseSC, NewState),
NewState
end
end
end
end
end.
-spec find_stream(AddressOrOUI :: stream_key(), State :: state()) -> stream_val().
find_stream(AddressOrOUI, #state{streams=Streams}) ->
maps:get(AddressOrOUI, Streams, undefined).
-spec add_stream(AddressOrOUI :: non_neg_integer() | string(), Stream :: pid() | dialing, State :: state()) -> state().
add_stream(AddressOrOUI, Stream, #state{streams=Streams}=State) ->
State#state{streams=maps:put(AddressOrOUI, {unverified, Stream}, Streams)}.
-spec delete_stream(AddressOrOUI :: non_neg_integer() | string(), State :: state()) -> state().
delete_stream(AddressOrOUI, #state{streams=Streams}=State) ->
State#state{streams=maps:remove(AddressOrOUI, Streams)}.
lookup_stream_id(Pid, State) ->
Result = maps:filter(fun(_Name, {unverified, Stream}) ->
Stream == Pid;
(_Name, Stream) ->
Stream == Pid
end, State#state.streams),
case maps:size(Result) of
0 ->
undefined;
1 ->
hd(maps:keys(Result))
more than one is an error
end.
verify_stream(Stream, #state{streams=Streams}=State) ->
AddressOrOUI = lookup_stream_id(Stream, State),
State#state{streams=maps:update(AddressOrOUI, Stream, Streams)}.
-spec get_waiting_packet(AddressOrOUI :: waiting_key(), State :: state()) -> [waiting_packet()].
get_waiting_packet(AddressOrOUI, #state{waiting=Waiting}) ->
maps:get(AddressOrOUI, Waiting, []).
-spec add_packet_to_waiting(AddressOrOUI :: waiting_key(),
WaitingPacket :: waiting_packet(),
State :: state()) -> state().
add_packet_to_waiting(AddressOrOUI, {Packet, Region, ReceivedTime}, #state{waiting=Waiting}=State) ->
Q0 = get_waiting_packet(AddressOrOUI, State),
lager:debug("add_packet_to_waiting, AddressOrOUI: ~p", [AddressOrOUI]),
We should only ever keep 9 + 1 packet ( for each Router )
Q1 = lists:sublist(Q0, 9),
State#state{waiting=maps:put(AddressOrOUI, Q1 ++ [{Packet, Region, ReceivedTime}], Waiting)}. %%
-spec remove_packet_from_waiting(AddressOrOUI :: waiting_key(), State :: state()) -> state().
remove_packet_from_waiting(AddressOrOUI, #state{waiting=Waiting}=State) ->
State#state{waiting=maps:remove(AddressOrOUI, Waiting)}.
-spec enqueue_packet(Stream :: pid(),
Packet :: blockchain_helium_packet_v1:packet(),
ReceivedTime :: non_neg_integer(),
State :: state()) -> state().
enqueue_packet(Stream, Packet, ReceivedTime, #state{packets=Packets}=State) ->
lager:debug("enqueue_packet, stream: ~p, packet: ~p", [Stream, Packet]),
Value = {Packet, ReceivedTime},
State#state{packets=maps:update_with(Stream, fun(PacketList) -> queue:in(Value, PacketList) end, queue:in(Value, queue:new()), Packets)}.
-spec dequeue_packet(Stream :: pid(), State :: state()) -> {undefined | {blockchain_helium_packet_v1:packet(), non_neg_integer()}, state()}.
dequeue_packet(Stream, #state{packets=Packets}=State) ->
Queue = maps:get(Stream, Packets, queue:new()),
case queue:out(Queue) of
{empty, _} ->
{undefined, State};
{{value, ToPop}, NewQueue} ->
{ToPop, State#state{packets=maps:update(Stream, NewQueue, Packets)}}
end.
-spec find_routing(Packet :: blockchain_helium_packet_v1:packet(),
Chain :: blockchain:blockchain()) -> {ok, [blockchain_ledger_routing_v1:routing()]} | {error, any()}.
find_routing(_Packet, undefined) ->
{error, no_chain};
find_routing(Packet, Chain) ->
%% transitional shim for ignoring on-chain OUIs
case application:get_env(blockchain, use_oui_routers, true) of
true ->
RoutingInfo = blockchain_helium_packet_v1:routing_info(Packet),
Cache = persistent_term:get(?routing_cache),
cream:cache(
Cache,
RoutingInfo,
fun() ->
Ledger = blockchain:ledger(Chain),
case blockchain_ledger_v1:find_routing_for_packet(Packet, Ledger) of
{error, _}=Error ->
Error;
{ok, Routes} ->
{ok, Routes}
end
end);
false ->
{error, oui_routing_disabled}
end.
-spec dial(SCClientTransportHandler :: atom(),
SwarmTID :: ets:tab(),
Address :: string() | blockchain_ledger_routing_v1:routing()) -> ok.
dial(SCClientTransportHandler, SwarmTID, Address) when is_list(Address) ->
Self = self(),
erlang:spawn(
fun() ->
{P, R} =
erlang:spawn_monitor(
fun() ->
case SCClientTransportHandler:dial(SwarmTID, Address, []) of
{error, _Reason} ->
Self ! {dial_fail, Address, _Reason};
{ok, Stream} ->
unlink(Stream),
Self ! {dial_success, Address, Stream}
end
end),
receive
{'DOWN', R, process, P, normal} ->
ok;
{'DOWN', R, process, P, _Reason} ->
Self ! {dial_fail, Address, _Reason}
after application:get_env(blockchain, sc_packet_dial_timeout, 30000) ->
erlang:exit(P, kill),
Self ! {dial_fail, Address, timeout}
end
end),
ok;
dial(SCClientTransportHandler, SwarmTID, Route) ->
Self = self(),
erlang:spawn(
fun() ->
OUI = blockchain_ledger_routing_v1:oui(Route),
{P, R} =
erlang:spawn_monitor(
fun() ->
Dialed = lists:foldl(
fun(_PubkeyBin, {dialed, _}=Acc) ->
Acc;
(PubkeyBin, not_dialed) ->
Address = libp2p_crypto:pubkey_bin_to_p2p(PubkeyBin),
case SCClientTransportHandler:dial(SwarmTID, Address, []) of
{error, _Reason} ->
lager:error("failed to dial ~p:~p", [Address, _Reason]),
not_dialed;
{ok, Stream} ->
unlink(Stream),
{dialed, Stream}
end
end,
not_dialed,
blockchain_ledger_routing_v1:addresses(Route)
),
case Dialed of
not_dialed ->
Self ! {dial_fail, OUI, failed};
{dialed, Stream} ->
Self ! {dial_success, OUI, Stream}
end
end),
receive
{'DOWN', R, process, P, normal} ->
ok;
{'DOWN', R, process, P, _Reason} ->
Self ! {dial_fail, OUI, failed}
after application:get_env(blockchain, sc_packet_dial_timeout, 30000) ->
erlang:exit(P, kill),
Self ! {dial_fail, OUI, timeout}
end
end),
ok.
-spec send_packet(PubkeyBin :: libp2p_crypto:pubkey_bin(),
SigFun :: libp2p_crypto:sig_fun(),
Stream :: pid(),
Packet :: blockchain_helium_packet_v1:packet(),
Region :: atom(),
ReceivedTime :: non_neg_integer()) -> ok.
send_packet(PubkeyBin, SigFun, Stream, Packet, Region, ReceivedTime) ->
HoldTime = erlang:system_time(millisecond) - ReceivedTime,
PacketMsg0 = blockchain_state_channel_packet_v1:new(Packet, PubkeyBin, Region, HoldTime),
PacketMsg1 = blockchain_state_channel_packet_v1:sign(PacketMsg0, SigFun),
blockchain_state_channel_common:send_packet(Stream, PacketMsg1).
-spec send_offer(PubkeyBin :: libp2p_crypto:pubkey_bin(),
SigFun :: libp2p_crypto:sig_fun(),
Stream :: pid(),
Packet :: blockchain_helium_packet_v1:packet(),
Region :: atom() ) -> ok.
send_offer(PubkeyBin, SigFun, Stream, Packet, Region) ->
OfferMsg0 = blockchain_state_channel_offer_v1:from_packet(Packet, PubkeyBin, Region),
OfferMsg1 = blockchain_state_channel_offer_v1:sign(OfferMsg0, SigFun),
lager:debug("OfferMsg1: ~p", [OfferMsg1]),
blockchain_state_channel_common:send_offer(Stream, OfferMsg1).
-spec is_hotspot_in_router_oui(PubkeyBin :: libp2p_crypto:pubkey_bin(),
OUI :: pos_integer(),
Chain :: blockchain:blockchain()) -> boolean().
is_hotspot_in_router_oui(PubkeyBin, OUI, Chain) ->
Ledger = blockchain:ledger(Chain),
case blockchain_ledger_v1:find_gateway_info(PubkeyBin, Ledger) of
{error, _} ->
false;
{ok, Gw} ->
case blockchain_ledger_gateway_v2:oui(Gw) of
undefined ->
false;
OUI ->
true
end
end.
-spec send_packet_or_offer(Stream :: pid(),
OUI :: pos_integer(),
Packet :: blockchain_helium_packet_v1:packet(),
Region :: atom(),
ReceivedTime :: non_neg_integer(),
State :: #state{}) -> #state{}.
send_packet_or_offer(Stream, OUI, Packet, Region, ReceivedTime,
#state{pubkey_bin=PubkeyBin, sig_fun=SigFun, chain=Chain}=State) ->
SCVer = case ?get_var(?sc_version, blockchain:ledger(Chain)) of
{ok, N} -> N;
_ -> 1
end,
case (is_hotspot_in_router_oui(PubkeyBin, OUI, Chain) andalso SCVer >= 2) orelse SCVer == 1 of
false ->
ok = send_offer(PubkeyBin, SigFun, Stream, Packet, Region),
enqueue_packet(Stream, Packet, ReceivedTime, State);
true ->
ok = send_packet(PubkeyBin, SigFun, Stream, Packet, Region, ReceivedTime),
State
end.
-spec send_packet_when_v1(Stream :: pid(),
Packet :: blockchain_helium_packet_v1:packet(),
Region :: atom(),
ReceivedTime :: non_neg_integer(),
State :: #state{}) -> #state{}.
send_packet_when_v1(Stream, Packet, Region, ReceivedTime,
#state{pubkey_bin=PubkeyBin, sig_fun=SigFun, chain=Chain}=State) ->
case ?get_var(?sc_version, blockchain:ledger(Chain)) of
{ok, N} when N > 1 ->
lager:debug("got stream sending offer"),
ok = send_offer(PubkeyBin, SigFun, Stream, Packet, Region),
enqueue_packet(Stream, Packet, ReceivedTime, State);
_ ->
lager:debug("got stream sending packet"),
ok = send_packet(PubkeyBin, SigFun, Stream, Packet, Region, ReceivedTime),
State
end.
maybe_send_packets(AddressOrOUI, HandlerPid, #state{pubkey_bin=PubkeyBin, sig_fun=SigFun} = State) ->
Packets = get_waiting_packet(AddressOrOUI, State),
case AddressOrOUI of
OUI when is_integer(OUI) ->
lager:debug("dial_success sending ~p packets or offer depending on OUI", [erlang:length(Packets)]),
State1 = lists:foldl(
fun({Packet, Region, ReceivedTime}, Acc) ->
send_packet_or_offer(HandlerPid, OUI, Packet, Region, ReceivedTime, Acc)
end,
State,
Packets
),
verify_stream(HandlerPid, remove_packet_from_waiting(OUI, State1));
Address when is_list(Address) ->
State1 = case ?get_var(?sc_version, blockchain:ledger(State#state.chain)) of
{ok, N} when N >= 2 ->
lager:debug("valid banner for ~p, sending ~p packets", [AddressOrOUI, length(Packets)]),
lists:foldl(
fun({Packet, Region, ReceivedTime}, Acc) ->
ok = send_offer(PubkeyBin, SigFun, HandlerPid, Packet, Region),
enqueue_packet(HandlerPid, Packet, ReceivedTime, Acc)
end,
State,
Packets
);
_ ->
lists:foreach(
fun({Packet, Region, ReceivedTime}) ->
ok = send_packet(PubkeyBin, SigFun, HandlerPid, Packet, Region, ReceivedTime)
end,
Packets
),
State
end,
verify_stream(HandlerPid, remove_packet_from_waiting(Address, State1))
end.
%% ------------------------------------------------------------------
State channel validation functions
%% ------------------------------------------------------------------
-spec is_valid_sc(SC :: blockchain_state_channel_v1:state_channel(),
State :: state()) -> ok | {error, any()}.
is_valid_sc(SC, State) ->
check SC is even active first
case is_active_sc(SC, State) of
{error, _}=E -> E;
ok ->
case blockchain_state_channel_v1:quick_validate(SC, State#state.pubkey_bin) of
{error, Reason}=E ->
lager:error("invalid sc, reason: ~p", [Reason]),
E;
ok ->
case is_causally_correct_sc(SC, State) of
true ->
case is_overspent_sc(SC, State) of
true ->
{error, overspent};
false ->
ok
end;
false ->
{error, causal_conflict}
end
end
end.
-spec is_active_sc(SC :: blockchain_state_channel_v1:state_channel(),
State :: state()) -> ok | {error, no_chain} | {error, inactive_sc}.
is_active_sc(_, #state{chain=undefined}) ->
{error, no_chain};
is_active_sc(SC, #state{chain=Chain}) ->
Ledger = blockchain:ledger(Chain),
SCOwner = blockchain_state_channel_v1:owner(SC),
SCID = blockchain_state_channel_v1:id(SC),
case blockchain_ledger_v1:find_state_channel(SCID, SCOwner, Ledger) of
{ok, _SC} -> ok;
_ -> {error, inactive_sc}
end.
-spec is_causally_correct_sc(SC :: blockchain_state_channel_v1:state_channel(),
State :: state()) -> boolean().
is_causally_correct_sc(SC, #state{pubkey_bin=PubkeyBin}=State) ->
SCID = blockchain_state_channel_v1:id(SC),
case get_state_channels(SCID, State) of
{error, not_found} ->
true;
{error, _} ->
lager:error("rocks blew up"),
%% rocks blew up
false;
{ok, [KnownSC]} ->
Check if SC is causally correct
Check = blockchain_state_channel_v1:quick_compare_causality(KnownSC, SC, PubkeyBin),
case Check /= conflict of
true ->
true;
false ->
lager:notice("causality check: ~p, sc_id: ~p, same_sc_id: ~p, nonces: ~p ~p",
[Check, SCID, SCID == blockchain_state_channel_v1:id(KnownSC), blockchain_state_channel_v1:nonce(SC), blockchain_state_channel_v1:nonce(KnownSC)]),
false
end;
{ok, KnownSCs} ->
lager:error("multiple copies of state channels for id: ~p, found: ~p", [SCID, KnownSCs]),
%% We have a conflict among incoming state channels
ok = debug_multiple_scs(SC, KnownSCs),
false
end.
is_overspent_sc(SC, State=#state{chain=Chain}) ->
SCID = blockchain_state_channel_v1:id(SC),
Ledger = blockchain:ledger(Chain),
case get_state_channels(SCID, State) of
{error, not_found} ->
false;
{error, _} ->
lager:error("rocks blew up"),
%% rocks blew up
false;
{ok, KnownSCs} ->
lists:any(fun(E) -> blockchain_ledger_v1:is_state_channel_overpaid(E, Ledger) end, [SC|KnownSCs])
end.
get_previous_total_dcs(SC, State) ->
SCID = blockchain_state_channel_v1:id(SC),
case get_state_channels(SCID, State) of
{error, not_found} -> 0;
{error, _} ->
lager:error("rocks blew up"),
0;
{ok, [PreviousSC]} ->
blockchain_state_channel_v1:total_dcs(PreviousSC);
{ok, PrevSCs} ->
lager:error("multiple copies of state channels for id: ~p, returning current total",
[PrevSCs]),
%% returning this value will cause the test that we got paid to fail
%% and the packet will get re-enqueued.
blockchain_state_channel_v1:total_dcs(SC)
end.
%% ------------------------------------------------------------------
%% DB functions
%% ------------------------------------------------------------------
-spec get_state_channels(SCID :: blockchain_state_channel_v1:id(),
State :: state()) ->
{ok, [blockchain_state_channel_v1:state_channel()]} | {error, any()}.
get_state_channels(SCID, #state{db=DB, cf=CF}) ->
case rocksdb:get(DB, CF, SCID, []) of
{ok, Bin} ->
{ok, erlang:binary_to_term(Bin)};
not_found ->
{error, not_found};
Error ->
lager:error("error: ~p", [Error]),
Error
end.
-spec append_state_channel(SC :: blockchain_state_channel_v1:state_channel(),
State :: state()) -> ok | {error, any()}.
append_state_channel(SC, #state{db=DB, cf=CF}=State) ->
SCID = blockchain_state_channel_v1:id(SC),
case get_state_channels(SCID, State) of
{ok, SCs} ->
%% check we're not writing something we already have
case lists:member(SC, SCs) of
true ->
ok;
false ->
ToInsert = erlang:term_to_binary([SC | SCs]),
rocksdb:put(DB, CF, SCID, ToInsert, [])
end;
{error, not_found} ->
ToInsert = erlang:term_to_binary([SC]),
rocksdb:put(DB, CF, SCID, ToInsert, []);
{error, _}=E ->
E
end.
state_channels(#state{db=DB, cf=CF}) ->
{ok, Itr} = rocksdb:iterator(DB, CF, []),
state_channels(Itr, rocksdb:iterator_move(Itr, first), []).
state_channels(Itr, {error, invalid_iterator}, Acc) ->
?ROCKSDB_ITERATOR_CLOSE(Itr),
Acc;
state_channels(Itr, {ok, _, SCBin}, Acc) ->
state_channels(Itr, rocksdb:iterator_move(Itr, next), [binary_to_term(SCBin)|Acc]).
-spec overwrite_state_channel(SC :: blockchain_state_channel_v1:state_channel(),
State :: state()) -> ok | {error, any()}.
overwrite_state_channel(SC, State) ->
SCID = blockchain_state_channel_v1:id(SC),
case get_state_channels(SCID, State) of
%% If we somehow have multiple scs, blow up
{error, _} ->
write_sc(SC, State);
{ok, [KnownSC]} ->
case blockchain_state_channel_v1:is_causally_newer(SC, KnownSC) of
true -> write_sc(SC, State);
false -> ok
end
end.
-spec write_sc(SC :: blockchain_state_channel_v1:state_channel(),
State :: state()) -> ok.
write_sc(SC, #state{db=DB, cf=CF}) ->
SCID = blockchain_state_channel_v1:id(SC),
ToInsert = erlang:term_to_binary([SC]),
rocksdb:put(DB, CF, SCID, ToInsert, []).
-spec close_state_channel(SC :: blockchain_state_channel_v1:state_channel(), State :: state()) -> ok.
close_state_channel(SC, State=#state{pubkey_bin=PubkeyBin, sig_fun=SigFun}) ->
SCID = blockchain_state_channel_v1:id(SC),
case get_state_channels(SCID, State) of
{ok, [SC0]} ->
%% just a single conflict locally, we can just send it
Txn = blockchain_txn_state_channel_close_v1:new(SC0, SC, PubkeyBin),
SignedTxn = blockchain_txn_state_channel_close_v1:sign(Txn, SigFun),
ok = blockchain_worker:submit_txn(SignedTxn),
lager:info("closing state channel on conflict ~p: ~p",
[libp2p_crypto:bin_to_b58(blockchain_state_channel_v1:id(SC)), SignedTxn]);
{ok, SCs} ->
lager:warning("multiple conflicting SCs ~p", [length(SCs)]),
TODO check for ' overpaid ' state channels as well , not just causal conflicts
see if we have any conflicts with the supplied close SC :
case lists:filter(fun(E) -> conflicts(E, SC) end, SCs) of
[] ->
lager:debug("no direct conflict"),
%% find the latest state channel we have, and what it conflicts with
%%
%% first take the cartesian product of all the state channels, and select the conflicting ones
Conflicts = [ {A, B} || A <- SCs, B <- SCs, conflicts(A, B) ],
%% now try to find the ones with the highest balance (maximum refund guaranteed)
SortedConflicts = lists:sort(fun({A1, B1}, {A2, B2}) ->
V1 = num_dcs_for(PubkeyBin, A1),
V2 = num_dcs_for(PubkeyBin, B1),
V3 = num_dcs_for(PubkeyBin, A2),
V4 = num_dcs_for(PubkeyBin, B2),
max(V1, V2) =< max(V3, V4)
end, Conflicts),
case SortedConflicts of
[] ->
%% Only ever happens if a conflict has already been resolved during a core upgrade
ok;
L ->
{Conflict1, Conflict2} = lists:last(L),
Txn = blockchain_txn_state_channel_close_v1:new(Conflict1, Conflict2, PubkeyBin),
SignedTxn = blockchain_txn_state_channel_close_v1:sign(Txn, SigFun),
ok = blockchain_worker:submit_txn(SignedTxn)
end;
Conflicts ->
%% sort the conflicts by the number of DCs they'd send to us
SortedConflicts = lists:sort(fun(C1, C2) ->
%% tuples can sort fine
blockchain_state_channel_v1:num_dcs_for(PubkeyBin, C1) =<
blockchain_state_channel_v1:num_dcs_for(PubkeyBin, C2)
end, Conflicts),
create a close using the SC with the most DC in our favor
Txn = blockchain_txn_state_channel_close_v1:new(lists:last(SortedConflicts), SC, PubkeyBin),
SignedTxn = blockchain_txn_state_channel_close_v1:sign(Txn, SigFun),
ok = blockchain_worker:submit_txn(SignedTxn),
lager:info("closing state channel on conflict ~p: ~p",
[libp2p_crypto:bin_to_b58(blockchain_state_channel_v1:id(SC)), SignedTxn])
end;
_ ->
ok
end.
-spec conflicts(SCA :: blockchain_state_channel_v1:state_channel(),
SCB :: blockchain_state_channel_v1:state_channel()) -> boolean().
conflicts(SCA, SCB) ->
case blockchain_state_channel_v1:compare_causality(SCA, SCB) of
conflict ->
lager:info("sc_client reports state_channel conflict, SCA_ID: ~p, SCB_ID: ~p",
[libp2p_crypto:bin_to_b58(blockchain_state_channel_v1:id(SCA)),
libp2p_crypto:bin_to_b58(blockchain_state_channel_v1:id(SCB))]),
true;
_ ->
false
end.
num_dcs_for(PubkeyBin, SC) ->
case blockchain_state_channel_v1:num_dcs_for(PubkeyBin, SC) of
{ok, V} -> V;
{error, not_found} -> 0
end.
-spec debug_multiple_scs(SC :: blockchain_state_channel_v1:state_channel(),
KnownSCs :: [blockchain_state_channel_v1:state_channel()]) -> ok.
debug_multiple_scs(SC, KnownSCs) ->
case application:get_env(blockchain, debug_multiple_scs, false) of
false ->
%% false by default, don't write it out
ok;
true ->
BinSC = term_to_binary(SC),
BinKnownSCs = term_to_binary(KnownSCs),
ok = file:write_file("/tmp/bin_sc", BinSC),
ok = file:write_file("/tmp/known_scs", BinKnownSCs),
ok
end.
-spec chain_var_routers_by_netid_to_oui(
Chain :: undefined | blockchain:blockchain(),
State :: state()
) -> State1 :: state().
chain_var_routers_by_netid_to_oui(undefined, State) ->
Ledger = blockchain:ledger(),
chain_var_ledger_routers_by_netid_to_oui(Ledger, State);
chain_var_routers_by_netid_to_oui(Chain, State) ->
Ledger = blockchain:ledger(Chain),
chain_var_ledger_routers_by_netid_to_oui(Ledger, State).
-spec chain_var_ledger_routers_by_netid_to_oui(
Ledger :: blockchain:ledger(),
State :: state()
) -> State1 :: state().
chain_var_ledger_routers_by_netid_to_oui(Ledger, State) ->
Routers =
case ?get_var(?routers_by_netid_to_oui, Ledger) of
{ok, Bin} -> binary_to_term(Bin);
_ -> []
end,
State#state{routers=Routers}.
-spec handle_route_by_netid(
Packet :: blockchain_helium_packet_v1:packet(),
DevAddr :: number() | binary(),
DefaultRouters :: [blockchain_ledger_routing_v1:routing()],
Region :: atom(),
ReceivedTime :: non_neg_integer(),
State :: state()
) -> State1 :: state().
handle_route_by_netid(Packet, DevAddr, DefaultRouters, Region, ReceivedTime, State) ->
#state{chain=Chain, routers=RoamingRouters} = State,
OurNetID = application:get_env(blockchain, devaddr_prefix, $H),
case lora_subnet:parse_netid(DevAddr) of
{ok, OurNetID} ->
handle_packet_routing(Packet, Chain, DefaultRouters, Region, ReceivedTime, State);
{ok, ExtractedNetID} ->
FoldFn =
fun({NetID, OUI}, Acc) when NetID == ExtractedNetID ->
Ledger = blockchain:ledger(Chain),
case blockchain_ledger_v1:find_routing(OUI, Ledger) of
{ok, Route} -> [Route|Acc];
_ -> Acc
end;
({_OtherNetID, _}, Acc) ->
Acc
end,
RoutesOrAddresses =
case lists:foldl(FoldFn, [], RoamingRouters) of
[] ->
lager:debug("no routes found for netid ~p", [ExtractedNetID]),
DefaultRouters;
Routes ->
lager:debug("found ~p for netid ~p", [[blockchain_ledger_routing_v1:oui(R) || R <- Routes], ExtractedNetID]),
Routes
end,
handle_packet(Packet, RoutesOrAddresses, Region, ReceivedTime, State);
_Error ->
%% Drop undeliverable packet
lager:warning("failed to route ~p with devaddr=~p", [_Error, DevAddr]),
State
end.
-spec handle_packet_routing(
Packet :: blockchain_helium_packet_v1:packet(),
Chain :: blockchain:blockchain(),
DefaultRouters :: [string()] | [blockchain_ledger_routing_v1:routing()],
Region :: atom(),
ReceivedTime :: non_neg_integer(),
State :: state()
) -> state().
handle_packet_routing(Packet, Chain, DefaultRouters, Region, ReceivedTime, State) ->
case find_routing(Packet, Chain) of
{error, _Reason} ->
lager:warning(
"failed to find router for join packet with routing information ~p:~p, trying default routers",
[blockchain_helium_packet_v1:routing_info(Packet), _Reason]
),
handle_packet(Packet, DefaultRouters, Region, ReceivedTime, State);
{ok, Routes} ->
lager:debug("found routes ~p", [Routes]),
handle_packet(Packet, Routes, Region, ReceivedTime, State)
end.
print_routes(RoutesOrAddresses) ->
lists:map(fun(RouteOrAddress) ->
case blockchain_ledger_routing_v1:is_routing(RouteOrAddress) of
true ->
"OUI " ++ integer_to_list(blockchain_ledger_routing_v1:oui(RouteOrAddress));
false ->
RouteOrAddress
end
end, RoutesOrAddresses).
| null | https://raw.githubusercontent.com/helium/blockchain-core/0caf2295d0576c0ef803258e834bf6ec3b3e74bc/src/state_channel/blockchain_state_channels_client.erl | erlang | -------------------------------------------------------------------
@doc
== Blockchain State Channels Client ==
@end
-------------------------------------------------------------------
------------------------------------------------------------------
API Function Exports
------------------------------------------------------------------
------------------------------------------------------------------
gen_server exports
------------------------------------------------------------------
------------------------------------------------------------------
API Function Definitions
------------------------------------------------------------------
------------------------------------------------------------------
init, terminate and code_change
------------------------------------------------------------------
------------------------------------------------------------------
gen_server message handling
------------------------------------------------------------------
Handle Uplink packets
Handle Join packets
Also scan incoming blocks for updates; see add_block event.
We somehow lost the chain here, likely we were restarting and haven't gotten it yet
There really isn't anything we can do about it, but we should probably keep this stream
(if we don't already have it)
NOTE: We don't keep the packets we were waiting on as we lost the chain, maybe we should?
it's dead, remove it
submit our own close with the conflicting view(s)
add it to the list of closing channels so we don't try to double
close it below, irregardless of if we're disputing it
check if any other channels are expiring
before the client tries to file a close
check in the ledger that this sc is not already closing
don't do anything
ignore v1 state channels
already in closed/dispute state in ledger, do nothing
close with conflict
Keep the streams which don't have downed pid, given we're monitoring correctly
------------------------------------------------------------------
Internal Function Definitions
------------------------------------------------------------------
queue it until we get a banner
queue it until we get a banner
we don't need to keep a sibling here as proof of misbehaviour is standalone
this will conflict or dominate any later attempt to close within spec
NOTE: We somehow don't have this packet in our queue,
All we do is store the state channel by overwriting instead of appending
since there was not a causal conflict
DC cost.
We are not getting paid, so drop this packet and
do not send it. Close the stream.
append this state channel, so we know about it later
transitional shim for ignoring on-chain OUIs
------------------------------------------------------------------
------------------------------------------------------------------
rocks blew up
We have a conflict among incoming state channels
rocks blew up
returning this value will cause the test that we got paid to fail
and the packet will get re-enqueued.
------------------------------------------------------------------
DB functions
------------------------------------------------------------------
check we're not writing something we already have
If we somehow have multiple scs, blow up
just a single conflict locally, we can just send it
find the latest state channel we have, and what it conflicts with
first take the cartesian product of all the state channels, and select the conflicting ones
now try to find the ones with the highest balance (maximum refund guaranteed)
Only ever happens if a conflict has already been resolved during a core upgrade
sort the conflicts by the number of DCs they'd send to us
tuples can sort fine
false by default, don't write it out
Drop undeliverable packet | -module(blockchain_state_channels_client).
-behavior(gen_server).
-export([start_link/1,
packet/3,
purchase/2,
banner/2,
reject/2,
gc_state_channels/1,
get_known_channels/1,
response/1]).
-export([init/1,
handle_call/3,
handle_info/2,
handle_cast/2,
terminate/2,
code_change/3]).
-include("blockchain.hrl").
-include("blockchain_rocks.hrl").
-include("blockchain_vars.hrl").
-include_lib("grpc/autogen/server/state_channel_pb.hrl").
-define(SERVER, ?MODULE).
-define(ROUTING_CACHE, sc_client_routing).
6 hours in seconds
-record(state,{
db :: rocksdb:db_handle(),
cf :: rocksdb:cf_handle(),
swarm :: pid(),
swarm_tid :: ets:tab(),
pubkey_bin :: libp2p_crypto:pubkey_bin(),
sig_fun :: libp2p_crypto:sig_fun(),
chain = undefined :: undefined | blockchain:blockchain(),
streams = #{} :: streams(),
packets = #{} :: #{pid() => queue:queue(blockchain_helium_packet_v1:packet())},
waiting = #{} :: waiting(),
TODO GC these
sc_client_transport_handler :: atom(),
routers = [] :: list(netid_to_oui())
}).
-type state() :: #state{}.
-type stream_key() :: non_neg_integer() | string().
-type stream_val() :: undefined | dialing | {unverified, pid()} | pid().
-type streams() :: #{stream_key() => stream_val()}.
-type waiting_packet() :: {Packet :: blockchain_helium_packet_v1:packet(), Region :: atom(), ReceivedTime :: non_neg_integer()}.
-type waiting_key() :: non_neg_integer() | string().
-type waiting() :: #{waiting_key() => [waiting_packet()]}.
-type netid_to_oui() :: {pos_integer(), pos_integer()}.
-ifdef(TEST).
-export([
set_routers/2,
get_routers/1,
get_waiting/1,
handle_route_by_netid/6
]).
-spec set_routers(list(string()), blockchain:blockchain()) -> state().
set_routers(Routers, Chain) -> #state{chain=Chain, routers=Routers}.
-spec get_routers(state()) -> list(netid_to_oui()).
get_routers(State) -> State#state.routers.
-spec get_waiting(state()) -> waiting().
get_waiting(State) -> State#state.waiting.
-endif.
start_link(Args) ->
gen_server:start_link({local, ?SERVER}, ?SERVER, Args, []).
-spec response(blockchain_state_channel_response_v1:response()) -> any().
response(Resp) ->
erlang:spawn(fun() ->
case application:get_env(blockchain, sc_client_handler, undefined) of
undefined ->
ok;
Mod when is_atom(Mod) ->
Mod:handle_response(Resp)
end
end).
-spec packet(Packet :: blockchain_helium_packet_v1:packet(),
DefaultRouters :: [string()],
Region :: atom()) -> ok.
packet(Packet, DefaultRouters, Region) ->
gen_server:cast(?SERVER, {packet, Packet, DefaultRouters, Region, erlang:system_time(millisecond)}).
-spec get_known_channels(SCID :: blockchain_state_channel_v1:id()) -> {ok, [blockchain_state_channel_v1:state_channel()]} | {error, any()}.
get_known_channels(SCID) ->
gen_server:call(?SERVER, {get_known_channels, SCID}).
-spec purchase(Purchase :: blockchain_state_channel_purchase_v1:purchase(),
HandlerPid :: pid()) -> ok.
purchase(Purchase, HandlerPid) ->
gen_server:cast(?SERVER, {purchase, Purchase, HandlerPid}).
-spec banner(Banner :: blockchain_state_channel_banner_v1:banner(),
HandlerPid :: pid()) -> ok.
banner(Banner, HandlerPid) ->
gen_server:cast(?SERVER, {banner, Banner, HandlerPid}).
-spec reject(Rejection :: blockchain_state_channel_rejection_v1:rejection(),
HandlerPid :: pid()) -> ok.
reject(Rejection, HandlerPid) ->
gen_server:cast(?SERVER, {reject, Rejection, HandlerPid}).
gc_state_channels([]) -> ok;
gc_state_channels(SCIDs) ->
gen_server:cast(?SERVER, {gc_state_channels, SCIDs}).
init(Args) ->
SCClientTransportHandler = application:get_env(blockchain, sc_client_transport_handler, blockchain_state_channel_handler),
lager:info("~p init with ~p hanlder: ~p", [?SERVER, Args, SCClientTransportHandler]),
ok = blockchain_event:add_handler(self()),
Swarm = maps:get(swarm, Args),
SwarmTID = libp2p_swarm:tid(Swarm),
DB = blockchain_state_channels_db_owner:db(),
CF = blockchain_state_channels_db_owner:sc_clients_cf(),
{PubkeyBin, SigFun} = blockchain_utils:get_pubkeybin_sigfun(Swarm),
erlang:send_after(500, self(), post_init),
State = #state{db=DB, cf=CF, swarm=Swarm, swarm_tid=SwarmTID, pubkey_bin=PubkeyBin, sig_fun=SigFun, sc_client_transport_handler = SCClientTransportHandler},
{ok, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
handle_cast({banner, Banner, HandlerPid}, #state{sc_client_transport_handler = Handler} = State) ->
case blockchain_state_channel_banner_v1:sc(Banner) of
undefined ->
TODO in theory if you 're in the same OUI as the router this is ok
{noreply, State};
BannerSC ->
case is_valid_sc(BannerSC, State) of
{error, causal_conflict} ->
lager:error("causal_conflict for banner sc_id: ~p", [blockchain_state_channel_v1:id(BannerSC)]),
_ = Handler:close(HandlerPid),
ok = append_state_channel(BannerSC, State),
{noreply, State};
{error, Reason} ->
lager:error("reason: ~p", [Reason]),
_ = Handler:close(HandlerPid),
{noreply, State};
ok ->
overwrite_state_channel(BannerSC, State),
AddressOrOUI = lookup_stream_id(HandlerPid, State),
{noreply, maybe_send_packets(AddressOrOUI, HandlerPid, State)}
end
end;
handle_cast({packet,
#packet_pb{routing = #routing_information_pb{data = {devaddr, DevAddr}}} = Packet,
DefaultRouters, Region, ReceivedTime},
State)
when is_integer(DevAddr) andalso DevAddr > 0 ->
State2 =
handle_route_by_netid(Packet, DevAddr, DefaultRouters, Region, ReceivedTime, State),
{noreply, State2};
handle_cast({packet, Packet, DefaultRouters, Region, ReceivedTime}, #state{chain=Chain}=State) ->
State2 =
handle_packet_routing(Packet, Chain, DefaultRouters, Region, ReceivedTime, State),
{noreply, State2};
handle_cast({reject, Rejection, HandlerPid}, State) ->
lager:warning("Got rejection: ~p for: ~p, dropping packet", [Rejection, HandlerPid]),
NewState = case dequeue_packet(HandlerPid, State) of
{undefined, State} -> State;
{_, NS} -> NS
end,
{noreply, NewState};
handle_cast({gc_state_channels, SCIDs}, #state{pending_closes=P, db=DB, cf=CF}=State) ->
lists:foreach(fun(SCID) ->
rocksdb:delete(DB, CF, SCID, [])
end, SCIDs),
{noreply, State#state{pending_closes=P -- SCIDs}};
handle_cast({purchase, Purchase, HandlerPid}, State) ->
NewState = handle_purchase(Purchase, HandlerPid, State),
{noreply, NewState};
handle_cast(_Msg, State) ->
lager:debug("unhandled receive: ~p", [_Msg]),
{noreply, State}.
handle_call({get_known_channels, SCID}, _From, State) ->
{reply, get_state_channels(SCID, State), State};
handle_call(_, _, State) ->
{reply, ok, State}.
handle_info(post_init, #state{chain=undefined}=State) ->
case blockchain_worker:blockchain() of
undefined ->
erlang:send_after(500, self(), post_init),
{noreply, State};
Chain ->
State1 = chain_var_routers_by_netid_to_oui(Chain, State),
{noreply, State1#state{chain=Chain}}
end;
handle_info({blockchain_event, {new_chain, NC}}, State) ->
State1 = chain_var_routers_by_netid_to_oui(NC, State),
{noreply, State1#state{chain=NC}};
handle_info({dial_fail, AddressOrOUI, _Reason}, State0) ->
Packets = get_waiting_packet(AddressOrOUI, State0),
lager:error("failed to dial ~p: ~p dropping ~p packets", [AddressOrOUI, _Reason, erlang:length(Packets)+1]),
State1 = remove_packet_from_waiting(AddressOrOUI, delete_stream(AddressOrOUI, State0)),
{noreply, State1};
handle_info({dial_success, AddressOrOUI, Stream}, #state{chain=undefined}=State) ->
NewState = case find_stream(AddressOrOUI, State) of
undefined ->
erlang:monitor(process, Stream),
add_stream(AddressOrOUI, Stream, State);
_ ->
State
end,
{noreply, NewState};
handle_info({dial_success, OUIOrAddress, Stream}, State0) ->
erlang:monitor(process, Stream),
State1 = add_stream(OUIOrAddress, Stream, State0),
case ?get_var(?sc_version, blockchain:ledger(State1#state.chain)) of
{ok, N} when N >= 2 ->
{noreply, State1};
_ ->
{noreply, maybe_send_packets(OUIOrAddress, Stream, State1)}
end;
handle_info({blockchain_event, {add_block, _BlockHash, true, Ledger}}, State)
when Ledger =/= undefined ->
SCs = state_channels(State),
{ok, LedgerHeight} = blockchain_ledger_v1:current_height(Ledger),
SCGrace = case ?get_var(?sc_grace_blocks, Ledger) of
{ok, G} -> G;
_ -> 0
end,
lists:foreach(fun([H|_]) ->
ExpireAt = blockchain_state_channel_v1:expire_at_block(H),
SCID = blockchain_state_channel_v1:id(H),
case LedgerHeight > ExpireAt + SCGrace of
true ->
rocksdb:delete(State#state.db, State#state.cf, SCID, []);
false ->
ok
end
end, SCs),
State1 = chain_var_ledger_routers_by_netid_to_oui(Ledger, State),
{noreply, State1};
handle_info({blockchain_event, {add_block, BlockHash, false, Ledger}},
#state{chain=Chain, pubkey_bin=PubkeyBin, sig_fun=SigFun, pending_closes=PendingCloses}=State) when Chain /= undefined ->
Block =
case blockchain:get_block(BlockHash, Chain) of
{error, Reason} ->
lager:error("Couldn't get block with hash: ~p, reason: ~p", [BlockHash, Reason]),
undefined;
{ok, B} ->
B
end,
case Block of
undefined ->
ok;
Block ->
Txns = lists:filter(fun(T) -> blockchain_txn:type(T) == blockchain_txn_routing_v1 end,
blockchain_block:transactions(Block)),
case erlang:length(Txns) > 0 of
false -> ok;
true ->
Cache = persistent_term:get(?routing_cache),
cream:drain(Cache)
end
end,
ClosingChannels =
case Block of
undefined ->
[];
Block ->
lists:foldl(
fun(T, Acc) ->
case blockchain_txn:type(T) == blockchain_txn_state_channel_close_v1 of
true ->
SC = blockchain_txn_state_channel_close_v1:state_channel(T),
SCID = blockchain_txn_state_channel_close_v1:state_channel_id(T),
case lists:member(SCID, PendingCloses) orelse
is_causally_correct_sc(SC, State) of
true ->
ok;
false ->
close_state_channel(SC, State)
end,
[SCID|Acc];
false ->
Acc
end
end,
[],
blockchain_block:transactions(Block))
end,
SCGrace = case ?get_var(?sc_grace_blocks, Ledger) of
{ok, G} -> G;
_ -> 0
end,
SCs = state_channels(State),
{ok, LedgerHeight} = blockchain_ledger_v1:current_height(Ledger),
ExpiringChannels = lists:foldl(fun([H|_]=SC, Acc) ->
ExpireAt = blockchain_state_channel_v1:expire_at_block(H),
SCID = blockchain_state_channel_v1:id(H),
SCOwner = blockchain_state_channel_v1:owner(H),
case (not lists:member(SCID, PendingCloses ++ ClosingChannels)) andalso
divide by 3 here so we give the server a chance to file its close first
LedgerHeight >= ExpireAt + (SCGrace div 3) andalso
LedgerHeight =< ExpireAt + SCGrace of
true ->
case length(SC) of
1 ->
case blockchain_ledger_v1:find_state_channel(SCID, SCOwner, Ledger) of
{error, _} ->
ok;
{ok, LSC} ->
case blockchain_ledger_state_channel_v2:is_v2(LSC) of
false ->
ok;
true ->
case blockchain_ledger_state_channel_v2:close_state(LSC) of
undefined ->
Txn = blockchain_txn_state_channel_close_v1:new(H, PubkeyBin),
SignedTxn = blockchain_txn_state_channel_close_v1:sign(Txn, SigFun),
ok = blockchain_worker:submit_txn(SignedTxn);
_ ->
ok
end
end
end;
_ ->
close_state_channel(H, State)
end,
[SCID|Acc];
false ->
Acc
end
end, [], SCs),
{noreply, State#state{pending_closes=lists:usort(PendingCloses ++ ClosingChannels ++ ExpiringChannels)}};
handle_info({blockchain_event, {add_block, _BlockHash, _Syncing, _Ledger}}, State) ->
{noreply, State};
handle_info({'DOWN', _Ref, process, Pid, _}, #state{streams=Streams, packets=Packets}=State) ->
FilteredStreams = maps:filter(fun(_Name, {unverified, Stream}) ->
Stream /= Pid;
(_Name, Stream) ->
Stream /= Pid
end, Streams),
FilteredPackets = maps:filter(fun(StreamPid, _PacketQueue) ->
StreamPid /= Pid
end, Packets),
{noreply, State#state{streams=FilteredStreams, packets=FilteredPackets}};
handle_info(_Msg, State) ->
lager:warning("rcvd unknown info msg: ~p", [_Msg]),
{noreply, State}.
-spec handle_packet(Packet :: blockchain_helium_packet_v1:packet(),
RoutesOrAddresses :: [string()] | [blockchain_ledger_routing_v1:routing()],
Region :: atom(),
ReceivedTime :: non_neg_integer(),
State :: state()) -> state().
handle_packet(Packet, RoutesOrAddresses, Region, ReceivedTime, #state{swarm_tid=SwarmTID,
sc_client_transport_handler = SCClientTransportHandler}=State0) ->
lager:info("handle_packet ~p to ~p with handler ~p", [lager:pr(Packet, blockchain_helium_packet_v1), print_routes(RoutesOrAddresses), SCClientTransportHandler]),
lists:foldl(
fun(RouteOrAddress, StateAcc) ->
StreamKey = case blockchain_ledger_routing_v1:is_routing(RouteOrAddress) of
false ->
{address, RouteOrAddress};
true ->
{oui, blockchain_ledger_routing_v1:oui(RouteOrAddress)}
end,
case StreamKey of
{address, Address} ->
case find_stream(Address, StateAcc) of
undefined ->
lager:debug("stream undef dialing first, address: ~p", [Address]),
ok = dial(SCClientTransportHandler, SwarmTID, RouteOrAddress),
add_packet_to_waiting(Address, {Packet, Region, ReceivedTime}, add_stream(Address, dialing, StateAcc));
dialing ->
lager:debug("stream is still dialing queueing packet, address: ~p", [Address]),
add_packet_to_waiting(Address, {Packet, Region, ReceivedTime}, StateAcc);
{unverified, _Stream} ->
lager:debug("unverified stream, add_packet_to_waiting, address: ~p", [Address]),
add_packet_to_waiting(Address, {Packet, Region, ReceivedTime}, StateAcc);
Stream ->
lager:debug("stream ~p, send_packet_when_v1, address: ~p", [Stream, Address]),
send_packet_when_v1(Stream, Packet, Region, ReceivedTime, StateAcc)
end;
{oui, OUI} ->
case find_stream(OUI, StateAcc) of
undefined ->
lager:debug("stream undef dialing first, oui: ~p", [OUI]),
ok = dial(SCClientTransportHandler, SwarmTID, RouteOrAddress),
add_packet_to_waiting(OUI, {Packet, Region, ReceivedTime}, add_stream(OUI, dialing, StateAcc));
dialing ->
lager:debug("stream is still dialing queueing packet, oui: ~p", [OUI]),
add_packet_to_waiting(OUI, {Packet, Region, ReceivedTime}, StateAcc);
{unverified, _Stream} ->
lager:debug("unverified stream, add_packet_to_waiting, oui: ~p", [OUI]),
add_packet_to_waiting(OUI, {Packet, Region, ReceivedTime}, StateAcc);
Stream ->
lager:debug("got stream: ~p, send_packet_or_offer, oui: ~p", [Stream, OUI]),
send_packet_or_offer(Stream, OUI, Packet, Region, ReceivedTime, StateAcc)
end
end
end,
State0,
RoutesOrAddresses
).
-spec handle_purchase(Purchase :: blockchain_state_channel_purchase_v1:purchase(),
Stream :: pid(),
State :: state()) -> state().
handle_purchase(Purchase, Stream,
#state{chain=Chain, pubkey_bin=PubkeyBin, sig_fun=SigFun}=State) ->
PurchaseSC = blockchain_state_channel_purchase_v1:sc(Purchase),
case is_valid_sc(PurchaseSC, State) of
{error, Reason} when Reason == inactive_sc orelse Reason == no_chain ->
lager:info("we don't know about ~p, lets send packet anyway", [blockchain_state_channel_v1:id(PurchaseSC)]),
case dequeue_packet(Stream, State) of
{undefined, State1} ->
lager:debug("failed dequeue_packet, stream: ~p, purchase: ~p", [Stream, Purchase]),
State1;
{{Packet, ReceivedTime}, State1} ->
Region = blockchain_state_channel_purchase_v1:region(Purchase),
ok = send_packet(PubkeyBin, SigFun, Stream, Packet, Region, ReceivedTime),
State1
end;
{error, causal_conflict} ->
lager:error("causal_conflict for purchase sc_id: ~p", [blockchain_state_channel_v1:id(PurchaseSC)]),
ok = append_state_channel(PurchaseSC, State),
_ = libp2p_framed_stream:close(Stream),
State;
{error, Reason} ->
lager:error("failed sc validation, closing stream: ~p, reason: ~p", [Stream, Reason]),
_ = libp2p_framed_stream:close(Stream),
State;
ok ->
Ledger = blockchain:ledger(Chain),
DCBudget = blockchain_state_channel_v1:amount(PurchaseSC),
TotalDCs = blockchain_state_channel_v1:total_dcs(PurchaseSC),
RemainingDCs = max(0, DCBudget - TotalDCs),
case blockchain_ledger_v1:is_state_channel_overpaid(PurchaseSC, Ledger) of
true ->
lager:error("insufficient dcs for purchase sc: ~p: ~p - ~p = ~p", [PurchaseSC, DCBudget, TotalDCs, RemainingDCs]),
_ = libp2p_framed_stream:close(Stream),
ok = overwrite_state_channel(PurchaseSC, State),
State;
false ->
case dequeue_packet(Stream, State) of
{undefined, State0} ->
ok = overwrite_state_channel(PurchaseSC, State0),
lager:debug("failed dequeue_packet, stream: ~p, purchase: ~p", [Stream, Purchase]),
State0;
{{Packet, ReceivedTime}, NewState} ->
Payload = blockchain_helium_packet_v1:payload(Packet),
PacketDCs = blockchain_utils:calculate_dc_amount(Ledger, byte_size(Payload)),
case RemainingDCs >= PacketDCs of
false ->
lager:error("current packet (~p) (dc charge: ~p) will exceed remaining DCs (~p) in this SC, dropping",
[Packet, PacketDCs, RemainingDCs]),
_ = libp2p_framed_stream:close(Stream),
NewState;
true ->
now we need to make sure that our DC count between the previous
and the current SC is _ at least _ increased by this packet 's
PrevTotal = get_previous_total_dcs(PurchaseSC, NewState),
case (TotalDCs - PrevTotal) >= PacketDCs of
true ->
Region = blockchain_state_channel_purchase_v1:region(Purchase),
lager:debug("successful purchase validation, sending packet: ~p",
[blockchain_helium_packet_v1:packet_hash(Packet)]),
ok = send_packet(PubkeyBin, SigFun, Stream, Packet, Region, ReceivedTime),
ok = overwrite_state_channel(PurchaseSC, NewState),
NewState;
false ->
lager:error("purchase not valid - did not pay for packet: ~p, dropping.",
[Packet]),
_ = libp2p_framed_stream:close(Stream),
ok = overwrite_state_channel(PurchaseSC, NewState),
NewState
end
end
end
end
end.
-spec find_stream(AddressOrOUI :: stream_key(), State :: state()) -> stream_val().
find_stream(AddressOrOUI, #state{streams=Streams}) ->
maps:get(AddressOrOUI, Streams, undefined).
-spec add_stream(AddressOrOUI :: non_neg_integer() | string(), Stream :: pid() | dialing, State :: state()) -> state().
add_stream(AddressOrOUI, Stream, #state{streams=Streams}=State) ->
State#state{streams=maps:put(AddressOrOUI, {unverified, Stream}, Streams)}.
-spec delete_stream(AddressOrOUI :: non_neg_integer() | string(), State :: state()) -> state().
delete_stream(AddressOrOUI, #state{streams=Streams}=State) ->
State#state{streams=maps:remove(AddressOrOUI, Streams)}.
lookup_stream_id(Pid, State) ->
Result = maps:filter(fun(_Name, {unverified, Stream}) ->
Stream == Pid;
(_Name, Stream) ->
Stream == Pid
end, State#state.streams),
case maps:size(Result) of
0 ->
undefined;
1 ->
hd(maps:keys(Result))
more than one is an error
end.
verify_stream(Stream, #state{streams=Streams}=State) ->
AddressOrOUI = lookup_stream_id(Stream, State),
State#state{streams=maps:update(AddressOrOUI, Stream, Streams)}.
-spec get_waiting_packet(AddressOrOUI :: waiting_key(), State :: state()) -> [waiting_packet()].
get_waiting_packet(AddressOrOUI, #state{waiting=Waiting}) ->
maps:get(AddressOrOUI, Waiting, []).
-spec add_packet_to_waiting(AddressOrOUI :: waiting_key(),
WaitingPacket :: waiting_packet(),
State :: state()) -> state().
add_packet_to_waiting(AddressOrOUI, {Packet, Region, ReceivedTime}, #state{waiting=Waiting}=State) ->
Q0 = get_waiting_packet(AddressOrOUI, State),
lager:debug("add_packet_to_waiting, AddressOrOUI: ~p", [AddressOrOUI]),
We should only ever keep 9 + 1 packet ( for each Router )
Q1 = lists:sublist(Q0, 9),
-spec remove_packet_from_waiting(AddressOrOUI :: waiting_key(), State :: state()) -> state().
remove_packet_from_waiting(AddressOrOUI, #state{waiting=Waiting}=State) ->
State#state{waiting=maps:remove(AddressOrOUI, Waiting)}.
-spec enqueue_packet(Stream :: pid(),
Packet :: blockchain_helium_packet_v1:packet(),
ReceivedTime :: non_neg_integer(),
State :: state()) -> state().
enqueue_packet(Stream, Packet, ReceivedTime, #state{packets=Packets}=State) ->
lager:debug("enqueue_packet, stream: ~p, packet: ~p", [Stream, Packet]),
Value = {Packet, ReceivedTime},
State#state{packets=maps:update_with(Stream, fun(PacketList) -> queue:in(Value, PacketList) end, queue:in(Value, queue:new()), Packets)}.
-spec dequeue_packet(Stream :: pid(), State :: state()) -> {undefined | {blockchain_helium_packet_v1:packet(), non_neg_integer()}, state()}.
dequeue_packet(Stream, #state{packets=Packets}=State) ->
Queue = maps:get(Stream, Packets, queue:new()),
case queue:out(Queue) of
{empty, _} ->
{undefined, State};
{{value, ToPop}, NewQueue} ->
{ToPop, State#state{packets=maps:update(Stream, NewQueue, Packets)}}
end.
-spec find_routing(Packet :: blockchain_helium_packet_v1:packet(),
Chain :: blockchain:blockchain()) -> {ok, [blockchain_ledger_routing_v1:routing()]} | {error, any()}.
find_routing(_Packet, undefined) ->
{error, no_chain};
find_routing(Packet, Chain) ->
case application:get_env(blockchain, use_oui_routers, true) of
true ->
RoutingInfo = blockchain_helium_packet_v1:routing_info(Packet),
Cache = persistent_term:get(?routing_cache),
cream:cache(
Cache,
RoutingInfo,
fun() ->
Ledger = blockchain:ledger(Chain),
case blockchain_ledger_v1:find_routing_for_packet(Packet, Ledger) of
{error, _}=Error ->
Error;
{ok, Routes} ->
{ok, Routes}
end
end);
false ->
{error, oui_routing_disabled}
end.
-spec dial(SCClientTransportHandler :: atom(),
SwarmTID :: ets:tab(),
Address :: string() | blockchain_ledger_routing_v1:routing()) -> ok.
dial(SCClientTransportHandler, SwarmTID, Address) when is_list(Address) ->
Self = self(),
erlang:spawn(
fun() ->
{P, R} =
erlang:spawn_monitor(
fun() ->
case SCClientTransportHandler:dial(SwarmTID, Address, []) of
{error, _Reason} ->
Self ! {dial_fail, Address, _Reason};
{ok, Stream} ->
unlink(Stream),
Self ! {dial_success, Address, Stream}
end
end),
receive
{'DOWN', R, process, P, normal} ->
ok;
{'DOWN', R, process, P, _Reason} ->
Self ! {dial_fail, Address, _Reason}
after application:get_env(blockchain, sc_packet_dial_timeout, 30000) ->
erlang:exit(P, kill),
Self ! {dial_fail, Address, timeout}
end
end),
ok;
dial(SCClientTransportHandler, SwarmTID, Route) ->
Self = self(),
erlang:spawn(
fun() ->
OUI = blockchain_ledger_routing_v1:oui(Route),
{P, R} =
erlang:spawn_monitor(
fun() ->
Dialed = lists:foldl(
fun(_PubkeyBin, {dialed, _}=Acc) ->
Acc;
(PubkeyBin, not_dialed) ->
Address = libp2p_crypto:pubkey_bin_to_p2p(PubkeyBin),
case SCClientTransportHandler:dial(SwarmTID, Address, []) of
{error, _Reason} ->
lager:error("failed to dial ~p:~p", [Address, _Reason]),
not_dialed;
{ok, Stream} ->
unlink(Stream),
{dialed, Stream}
end
end,
not_dialed,
blockchain_ledger_routing_v1:addresses(Route)
),
case Dialed of
not_dialed ->
Self ! {dial_fail, OUI, failed};
{dialed, Stream} ->
Self ! {dial_success, OUI, Stream}
end
end),
receive
{'DOWN', R, process, P, normal} ->
ok;
{'DOWN', R, process, P, _Reason} ->
Self ! {dial_fail, OUI, failed}
after application:get_env(blockchain, sc_packet_dial_timeout, 30000) ->
erlang:exit(P, kill),
Self ! {dial_fail, OUI, timeout}
end
end),
ok.
-spec send_packet(PubkeyBin :: libp2p_crypto:pubkey_bin(),
SigFun :: libp2p_crypto:sig_fun(),
Stream :: pid(),
Packet :: blockchain_helium_packet_v1:packet(),
Region :: atom(),
ReceivedTime :: non_neg_integer()) -> ok.
send_packet(PubkeyBin, SigFun, Stream, Packet, Region, ReceivedTime) ->
HoldTime = erlang:system_time(millisecond) - ReceivedTime,
PacketMsg0 = blockchain_state_channel_packet_v1:new(Packet, PubkeyBin, Region, HoldTime),
PacketMsg1 = blockchain_state_channel_packet_v1:sign(PacketMsg0, SigFun),
blockchain_state_channel_common:send_packet(Stream, PacketMsg1).
-spec send_offer(PubkeyBin :: libp2p_crypto:pubkey_bin(),
SigFun :: libp2p_crypto:sig_fun(),
Stream :: pid(),
Packet :: blockchain_helium_packet_v1:packet(),
Region :: atom() ) -> ok.
send_offer(PubkeyBin, SigFun, Stream, Packet, Region) ->
OfferMsg0 = blockchain_state_channel_offer_v1:from_packet(Packet, PubkeyBin, Region),
OfferMsg1 = blockchain_state_channel_offer_v1:sign(OfferMsg0, SigFun),
lager:debug("OfferMsg1: ~p", [OfferMsg1]),
blockchain_state_channel_common:send_offer(Stream, OfferMsg1).
-spec is_hotspot_in_router_oui(PubkeyBin :: libp2p_crypto:pubkey_bin(),
OUI :: pos_integer(),
Chain :: blockchain:blockchain()) -> boolean().
is_hotspot_in_router_oui(PubkeyBin, OUI, Chain) ->
Ledger = blockchain:ledger(Chain),
case blockchain_ledger_v1:find_gateway_info(PubkeyBin, Ledger) of
{error, _} ->
false;
{ok, Gw} ->
case blockchain_ledger_gateway_v2:oui(Gw) of
undefined ->
false;
OUI ->
true
end
end.
-spec send_packet_or_offer(Stream :: pid(),
OUI :: pos_integer(),
Packet :: blockchain_helium_packet_v1:packet(),
Region :: atom(),
ReceivedTime :: non_neg_integer(),
State :: #state{}) -> #state{}.
send_packet_or_offer(Stream, OUI, Packet, Region, ReceivedTime,
#state{pubkey_bin=PubkeyBin, sig_fun=SigFun, chain=Chain}=State) ->
SCVer = case ?get_var(?sc_version, blockchain:ledger(Chain)) of
{ok, N} -> N;
_ -> 1
end,
case (is_hotspot_in_router_oui(PubkeyBin, OUI, Chain) andalso SCVer >= 2) orelse SCVer == 1 of
false ->
ok = send_offer(PubkeyBin, SigFun, Stream, Packet, Region),
enqueue_packet(Stream, Packet, ReceivedTime, State);
true ->
ok = send_packet(PubkeyBin, SigFun, Stream, Packet, Region, ReceivedTime),
State
end.
-spec send_packet_when_v1(Stream :: pid(),
Packet :: blockchain_helium_packet_v1:packet(),
Region :: atom(),
ReceivedTime :: non_neg_integer(),
State :: #state{}) -> #state{}.
send_packet_when_v1(Stream, Packet, Region, ReceivedTime,
#state{pubkey_bin=PubkeyBin, sig_fun=SigFun, chain=Chain}=State) ->
case ?get_var(?sc_version, blockchain:ledger(Chain)) of
{ok, N} when N > 1 ->
lager:debug("got stream sending offer"),
ok = send_offer(PubkeyBin, SigFun, Stream, Packet, Region),
enqueue_packet(Stream, Packet, ReceivedTime, State);
_ ->
lager:debug("got stream sending packet"),
ok = send_packet(PubkeyBin, SigFun, Stream, Packet, Region, ReceivedTime),
State
end.
maybe_send_packets(AddressOrOUI, HandlerPid, #state{pubkey_bin=PubkeyBin, sig_fun=SigFun} = State) ->
Packets = get_waiting_packet(AddressOrOUI, State),
case AddressOrOUI of
OUI when is_integer(OUI) ->
lager:debug("dial_success sending ~p packets or offer depending on OUI", [erlang:length(Packets)]),
State1 = lists:foldl(
fun({Packet, Region, ReceivedTime}, Acc) ->
send_packet_or_offer(HandlerPid, OUI, Packet, Region, ReceivedTime, Acc)
end,
State,
Packets
),
verify_stream(HandlerPid, remove_packet_from_waiting(OUI, State1));
Address when is_list(Address) ->
State1 = case ?get_var(?sc_version, blockchain:ledger(State#state.chain)) of
{ok, N} when N >= 2 ->
lager:debug("valid banner for ~p, sending ~p packets", [AddressOrOUI, length(Packets)]),
lists:foldl(
fun({Packet, Region, ReceivedTime}, Acc) ->
ok = send_offer(PubkeyBin, SigFun, HandlerPid, Packet, Region),
enqueue_packet(HandlerPid, Packet, ReceivedTime, Acc)
end,
State,
Packets
);
_ ->
lists:foreach(
fun({Packet, Region, ReceivedTime}) ->
ok = send_packet(PubkeyBin, SigFun, HandlerPid, Packet, Region, ReceivedTime)
end,
Packets
),
State
end,
verify_stream(HandlerPid, remove_packet_from_waiting(Address, State1))
end.
State channel validation functions
-spec is_valid_sc(SC :: blockchain_state_channel_v1:state_channel(),
State :: state()) -> ok | {error, any()}.
is_valid_sc(SC, State) ->
check SC is even active first
case is_active_sc(SC, State) of
{error, _}=E -> E;
ok ->
case blockchain_state_channel_v1:quick_validate(SC, State#state.pubkey_bin) of
{error, Reason}=E ->
lager:error("invalid sc, reason: ~p", [Reason]),
E;
ok ->
case is_causally_correct_sc(SC, State) of
true ->
case is_overspent_sc(SC, State) of
true ->
{error, overspent};
false ->
ok
end;
false ->
{error, causal_conflict}
end
end
end.
-spec is_active_sc(SC :: blockchain_state_channel_v1:state_channel(),
State :: state()) -> ok | {error, no_chain} | {error, inactive_sc}.
is_active_sc(_, #state{chain=undefined}) ->
{error, no_chain};
is_active_sc(SC, #state{chain=Chain}) ->
Ledger = blockchain:ledger(Chain),
SCOwner = blockchain_state_channel_v1:owner(SC),
SCID = blockchain_state_channel_v1:id(SC),
case blockchain_ledger_v1:find_state_channel(SCID, SCOwner, Ledger) of
{ok, _SC} -> ok;
_ -> {error, inactive_sc}
end.
-spec is_causally_correct_sc(SC :: blockchain_state_channel_v1:state_channel(),
State :: state()) -> boolean().
is_causally_correct_sc(SC, #state{pubkey_bin=PubkeyBin}=State) ->
SCID = blockchain_state_channel_v1:id(SC),
case get_state_channels(SCID, State) of
{error, not_found} ->
true;
{error, _} ->
lager:error("rocks blew up"),
false;
{ok, [KnownSC]} ->
Check if SC is causally correct
Check = blockchain_state_channel_v1:quick_compare_causality(KnownSC, SC, PubkeyBin),
case Check /= conflict of
true ->
true;
false ->
lager:notice("causality check: ~p, sc_id: ~p, same_sc_id: ~p, nonces: ~p ~p",
[Check, SCID, SCID == blockchain_state_channel_v1:id(KnownSC), blockchain_state_channel_v1:nonce(SC), blockchain_state_channel_v1:nonce(KnownSC)]),
false
end;
{ok, KnownSCs} ->
lager:error("multiple copies of state channels for id: ~p, found: ~p", [SCID, KnownSCs]),
ok = debug_multiple_scs(SC, KnownSCs),
false
end.
is_overspent_sc(SC, State=#state{chain=Chain}) ->
SCID = blockchain_state_channel_v1:id(SC),
Ledger = blockchain:ledger(Chain),
case get_state_channels(SCID, State) of
{error, not_found} ->
false;
{error, _} ->
lager:error("rocks blew up"),
false;
{ok, KnownSCs} ->
lists:any(fun(E) -> blockchain_ledger_v1:is_state_channel_overpaid(E, Ledger) end, [SC|KnownSCs])
end.
get_previous_total_dcs(SC, State) ->
SCID = blockchain_state_channel_v1:id(SC),
case get_state_channels(SCID, State) of
{error, not_found} -> 0;
{error, _} ->
lager:error("rocks blew up"),
0;
{ok, [PreviousSC]} ->
blockchain_state_channel_v1:total_dcs(PreviousSC);
{ok, PrevSCs} ->
lager:error("multiple copies of state channels for id: ~p, returning current total",
[PrevSCs]),
blockchain_state_channel_v1:total_dcs(SC)
end.
-spec get_state_channels(SCID :: blockchain_state_channel_v1:id(),
State :: state()) ->
{ok, [blockchain_state_channel_v1:state_channel()]} | {error, any()}.
get_state_channels(SCID, #state{db=DB, cf=CF}) ->
case rocksdb:get(DB, CF, SCID, []) of
{ok, Bin} ->
{ok, erlang:binary_to_term(Bin)};
not_found ->
{error, not_found};
Error ->
lager:error("error: ~p", [Error]),
Error
end.
-spec append_state_channel(SC :: blockchain_state_channel_v1:state_channel(),
State :: state()) -> ok | {error, any()}.
append_state_channel(SC, #state{db=DB, cf=CF}=State) ->
SCID = blockchain_state_channel_v1:id(SC),
case get_state_channels(SCID, State) of
{ok, SCs} ->
case lists:member(SC, SCs) of
true ->
ok;
false ->
ToInsert = erlang:term_to_binary([SC | SCs]),
rocksdb:put(DB, CF, SCID, ToInsert, [])
end;
{error, not_found} ->
ToInsert = erlang:term_to_binary([SC]),
rocksdb:put(DB, CF, SCID, ToInsert, []);
{error, _}=E ->
E
end.
state_channels(#state{db=DB, cf=CF}) ->
{ok, Itr} = rocksdb:iterator(DB, CF, []),
state_channels(Itr, rocksdb:iterator_move(Itr, first), []).
state_channels(Itr, {error, invalid_iterator}, Acc) ->
?ROCKSDB_ITERATOR_CLOSE(Itr),
Acc;
state_channels(Itr, {ok, _, SCBin}, Acc) ->
state_channels(Itr, rocksdb:iterator_move(Itr, next), [binary_to_term(SCBin)|Acc]).
-spec overwrite_state_channel(SC :: blockchain_state_channel_v1:state_channel(),
State :: state()) -> ok | {error, any()}.
overwrite_state_channel(SC, State) ->
SCID = blockchain_state_channel_v1:id(SC),
case get_state_channels(SCID, State) of
{error, _} ->
write_sc(SC, State);
{ok, [KnownSC]} ->
case blockchain_state_channel_v1:is_causally_newer(SC, KnownSC) of
true -> write_sc(SC, State);
false -> ok
end
end.
-spec write_sc(SC :: blockchain_state_channel_v1:state_channel(),
State :: state()) -> ok.
write_sc(SC, #state{db=DB, cf=CF}) ->
SCID = blockchain_state_channel_v1:id(SC),
ToInsert = erlang:term_to_binary([SC]),
rocksdb:put(DB, CF, SCID, ToInsert, []).
-spec close_state_channel(SC :: blockchain_state_channel_v1:state_channel(), State :: state()) -> ok.
close_state_channel(SC, State=#state{pubkey_bin=PubkeyBin, sig_fun=SigFun}) ->
SCID = blockchain_state_channel_v1:id(SC),
case get_state_channels(SCID, State) of
{ok, [SC0]} ->
Txn = blockchain_txn_state_channel_close_v1:new(SC0, SC, PubkeyBin),
SignedTxn = blockchain_txn_state_channel_close_v1:sign(Txn, SigFun),
ok = blockchain_worker:submit_txn(SignedTxn),
lager:info("closing state channel on conflict ~p: ~p",
[libp2p_crypto:bin_to_b58(blockchain_state_channel_v1:id(SC)), SignedTxn]);
{ok, SCs} ->
lager:warning("multiple conflicting SCs ~p", [length(SCs)]),
TODO check for ' overpaid ' state channels as well , not just causal conflicts
see if we have any conflicts with the supplied close SC :
case lists:filter(fun(E) -> conflicts(E, SC) end, SCs) of
[] ->
lager:debug("no direct conflict"),
Conflicts = [ {A, B} || A <- SCs, B <- SCs, conflicts(A, B) ],
SortedConflicts = lists:sort(fun({A1, B1}, {A2, B2}) ->
V1 = num_dcs_for(PubkeyBin, A1),
V2 = num_dcs_for(PubkeyBin, B1),
V3 = num_dcs_for(PubkeyBin, A2),
V4 = num_dcs_for(PubkeyBin, B2),
max(V1, V2) =< max(V3, V4)
end, Conflicts),
case SortedConflicts of
[] ->
ok;
L ->
{Conflict1, Conflict2} = lists:last(L),
Txn = blockchain_txn_state_channel_close_v1:new(Conflict1, Conflict2, PubkeyBin),
SignedTxn = blockchain_txn_state_channel_close_v1:sign(Txn, SigFun),
ok = blockchain_worker:submit_txn(SignedTxn)
end;
Conflicts ->
SortedConflicts = lists:sort(fun(C1, C2) ->
blockchain_state_channel_v1:num_dcs_for(PubkeyBin, C1) =<
blockchain_state_channel_v1:num_dcs_for(PubkeyBin, C2)
end, Conflicts),
create a close using the SC with the most DC in our favor
Txn = blockchain_txn_state_channel_close_v1:new(lists:last(SortedConflicts), SC, PubkeyBin),
SignedTxn = blockchain_txn_state_channel_close_v1:sign(Txn, SigFun),
ok = blockchain_worker:submit_txn(SignedTxn),
lager:info("closing state channel on conflict ~p: ~p",
[libp2p_crypto:bin_to_b58(blockchain_state_channel_v1:id(SC)), SignedTxn])
end;
_ ->
ok
end.
-spec conflicts(SCA :: blockchain_state_channel_v1:state_channel(),
SCB :: blockchain_state_channel_v1:state_channel()) -> boolean().
conflicts(SCA, SCB) ->
case blockchain_state_channel_v1:compare_causality(SCA, SCB) of
conflict ->
lager:info("sc_client reports state_channel conflict, SCA_ID: ~p, SCB_ID: ~p",
[libp2p_crypto:bin_to_b58(blockchain_state_channel_v1:id(SCA)),
libp2p_crypto:bin_to_b58(blockchain_state_channel_v1:id(SCB))]),
true;
_ ->
false
end.
num_dcs_for(PubkeyBin, SC) ->
case blockchain_state_channel_v1:num_dcs_for(PubkeyBin, SC) of
{ok, V} -> V;
{error, not_found} -> 0
end.
-spec debug_multiple_scs(SC :: blockchain_state_channel_v1:state_channel(),
KnownSCs :: [blockchain_state_channel_v1:state_channel()]) -> ok.
debug_multiple_scs(SC, KnownSCs) ->
case application:get_env(blockchain, debug_multiple_scs, false) of
false ->
ok;
true ->
BinSC = term_to_binary(SC),
BinKnownSCs = term_to_binary(KnownSCs),
ok = file:write_file("/tmp/bin_sc", BinSC),
ok = file:write_file("/tmp/known_scs", BinKnownSCs),
ok
end.
-spec chain_var_routers_by_netid_to_oui(
Chain :: undefined | blockchain:blockchain(),
State :: state()
) -> State1 :: state().
chain_var_routers_by_netid_to_oui(undefined, State) ->
Ledger = blockchain:ledger(),
chain_var_ledger_routers_by_netid_to_oui(Ledger, State);
chain_var_routers_by_netid_to_oui(Chain, State) ->
Ledger = blockchain:ledger(Chain),
chain_var_ledger_routers_by_netid_to_oui(Ledger, State).
-spec chain_var_ledger_routers_by_netid_to_oui(
Ledger :: blockchain:ledger(),
State :: state()
) -> State1 :: state().
chain_var_ledger_routers_by_netid_to_oui(Ledger, State) ->
Routers =
case ?get_var(?routers_by_netid_to_oui, Ledger) of
{ok, Bin} -> binary_to_term(Bin);
_ -> []
end,
State#state{routers=Routers}.
-spec handle_route_by_netid(
Packet :: blockchain_helium_packet_v1:packet(),
DevAddr :: number() | binary(),
DefaultRouters :: [blockchain_ledger_routing_v1:routing()],
Region :: atom(),
ReceivedTime :: non_neg_integer(),
State :: state()
) -> State1 :: state().
handle_route_by_netid(Packet, DevAddr, DefaultRouters, Region, ReceivedTime, State) ->
#state{chain=Chain, routers=RoamingRouters} = State,
OurNetID = application:get_env(blockchain, devaddr_prefix, $H),
case lora_subnet:parse_netid(DevAddr) of
{ok, OurNetID} ->
handle_packet_routing(Packet, Chain, DefaultRouters, Region, ReceivedTime, State);
{ok, ExtractedNetID} ->
FoldFn =
fun({NetID, OUI}, Acc) when NetID == ExtractedNetID ->
Ledger = blockchain:ledger(Chain),
case blockchain_ledger_v1:find_routing(OUI, Ledger) of
{ok, Route} -> [Route|Acc];
_ -> Acc
end;
({_OtherNetID, _}, Acc) ->
Acc
end,
RoutesOrAddresses =
case lists:foldl(FoldFn, [], RoamingRouters) of
[] ->
lager:debug("no routes found for netid ~p", [ExtractedNetID]),
DefaultRouters;
Routes ->
lager:debug("found ~p for netid ~p", [[blockchain_ledger_routing_v1:oui(R) || R <- Routes], ExtractedNetID]),
Routes
end,
handle_packet(Packet, RoutesOrAddresses, Region, ReceivedTime, State);
_Error ->
lager:warning("failed to route ~p with devaddr=~p", [_Error, DevAddr]),
State
end.
-spec handle_packet_routing(
Packet :: blockchain_helium_packet_v1:packet(),
Chain :: blockchain:blockchain(),
DefaultRouters :: [string()] | [blockchain_ledger_routing_v1:routing()],
Region :: atom(),
ReceivedTime :: non_neg_integer(),
State :: state()
) -> state().
handle_packet_routing(Packet, Chain, DefaultRouters, Region, ReceivedTime, State) ->
case find_routing(Packet, Chain) of
{error, _Reason} ->
lager:warning(
"failed to find router for join packet with routing information ~p:~p, trying default routers",
[blockchain_helium_packet_v1:routing_info(Packet), _Reason]
),
handle_packet(Packet, DefaultRouters, Region, ReceivedTime, State);
{ok, Routes} ->
lager:debug("found routes ~p", [Routes]),
handle_packet(Packet, Routes, Region, ReceivedTime, State)
end.
print_routes(RoutesOrAddresses) ->
lists:map(fun(RouteOrAddress) ->
case blockchain_ledger_routing_v1:is_routing(RouteOrAddress) of
true ->
"OUI " ++ integer_to_list(blockchain_ledger_routing_v1:oui(RouteOrAddress));
false ->
RouteOrAddress
end
end, RoutesOrAddresses).
|
097943764b0084a5a03b2f758ec5ba4f71def7eded1eec760bce236fb37b49bf | bscarlet/llvm-general | DataLayout.hs | module LLVM.General.Test.DataLayout where
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.HUnit
import LLVM.General.Test.Support
import Data.Maybe
import qualified Data.Set as Set
import qualified Data.Map as Map
import LLVM.General.Context
import LLVM.General.Module
import LLVM.General.AST
import LLVM.General.AST.DataLayout
import LLVM.General.AST.AddrSpace
import qualified LLVM.General.AST.Global as G
m s = "; ModuleID = '<string>'\n" ++ s
t s = "target datalayout = \"" ++ s ++ "\"\n"
ddl = defaultDataLayout BigEndian
tests = testGroup "DataLayout" [
testCase name $ strCheckC (Module "<string>" mdl Nothing []) (m sdl) (m sdlc)
| (name, mdl, sdl, sdlc) <- [
("none", Nothing, "", "")
] ++ [
(name, Just mdl, t sdl, t (fromMaybe sdl msdlc))
| (name, mdl, sdl, msdlc) <- [
("little-endian", defaultDataLayout LittleEndian, "e", Nothing),
("big-endian", defaultDataLayout BigEndian, "E", Nothing),
("native", ddl { nativeSizes = Just (Set.fromList [8,32]) }, "E-n8:32", Nothing),
(
"no pref",
ddl {
pointerLayouts =
Map.singleton
(AddrSpace 0)
(
8,
AlignmentInfo {
abiAlignment = 64,
preferredAlignment = Nothing
}
)
},
"E-p:8:64",
Nothing
), (
"no pref",
ddl {
pointerLayouts =
Map.insert (AddrSpace 1) (8, AlignmentInfo 32 (Just 64)) (pointerLayouts ddl)
},
"E-p1:8:32:64",
Nothing
), (
"big",
ddl {
endianness = LittleEndian,
mangling = Just ELFMangling,
stackAlignment = Just 128,
pointerLayouts = Map.fromList [
(AddrSpace 0, (8, AlignmentInfo {abiAlignment = 8, preferredAlignment = Just 16}))
],
typeLayouts = Map.fromList [
((IntegerAlign, 1), AlignmentInfo {abiAlignment = 8, preferredAlignment = Just 256}),
((IntegerAlign, 8), AlignmentInfo {abiAlignment = 8, preferredAlignment = Just 256}),
((IntegerAlign, 16), AlignmentInfo {abiAlignment = 16, preferredAlignment = Just 256}),
((IntegerAlign, 32), AlignmentInfo {abiAlignment = 32, preferredAlignment = Just 256}),
((IntegerAlign, 64), AlignmentInfo {abiAlignment = 64, preferredAlignment = Just 256}),
((VectorAlign, 64), AlignmentInfo {abiAlignment = 64, preferredAlignment = Just 256}),
((VectorAlign, 128), AlignmentInfo {abiAlignment = 128, preferredAlignment = Just 256}),
((FloatAlign, 32), AlignmentInfo {abiAlignment = 32, preferredAlignment = Just 256}),
((FloatAlign, 64), AlignmentInfo {abiAlignment = 64, preferredAlignment = Just 256}),
((FloatAlign, 80), AlignmentInfo {abiAlignment = 128, preferredAlignment = Just 256})
] `Map.union` typeLayouts ddl,
aggregateLayout = AlignmentInfo {abiAlignment = 0, preferredAlignment = Just 256},
nativeSizes = Just (Set.fromList [8,16,32,64])
},
"e-m:e-p:8:8:16-i1:8:256-i8:8:256-i16:16:256-i32:32:256-i64:64:256-f32:32:256-f64:64:256-v64:64:256-v128:128:256-a:0:256-f80:128:256-n8:16:32:64-S128",
Just "e-m:e-p:8:8:16-i1:8:256-i8:8:256-i16:16:256-i32:32:256-i64:64:256-f32:32:256-f64:64:256-v64:64:256-v128:128:256-a:0:256-f80:128:256-n8:16:32:64-S128"
)
]
]
]
| null | https://raw.githubusercontent.com/bscarlet/llvm-general/61fd03639063283e7dc617698265cc883baf0eec/llvm-general/test/LLVM/General/Test/DataLayout.hs | haskell | module LLVM.General.Test.DataLayout where
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.HUnit
import LLVM.General.Test.Support
import Data.Maybe
import qualified Data.Set as Set
import qualified Data.Map as Map
import LLVM.General.Context
import LLVM.General.Module
import LLVM.General.AST
import LLVM.General.AST.DataLayout
import LLVM.General.AST.AddrSpace
import qualified LLVM.General.AST.Global as G
m s = "; ModuleID = '<string>'\n" ++ s
t s = "target datalayout = \"" ++ s ++ "\"\n"
ddl = defaultDataLayout BigEndian
tests = testGroup "DataLayout" [
testCase name $ strCheckC (Module "<string>" mdl Nothing []) (m sdl) (m sdlc)
| (name, mdl, sdl, sdlc) <- [
("none", Nothing, "", "")
] ++ [
(name, Just mdl, t sdl, t (fromMaybe sdl msdlc))
| (name, mdl, sdl, msdlc) <- [
("little-endian", defaultDataLayout LittleEndian, "e", Nothing),
("big-endian", defaultDataLayout BigEndian, "E", Nothing),
("native", ddl { nativeSizes = Just (Set.fromList [8,32]) }, "E-n8:32", Nothing),
(
"no pref",
ddl {
pointerLayouts =
Map.singleton
(AddrSpace 0)
(
8,
AlignmentInfo {
abiAlignment = 64,
preferredAlignment = Nothing
}
)
},
"E-p:8:64",
Nothing
), (
"no pref",
ddl {
pointerLayouts =
Map.insert (AddrSpace 1) (8, AlignmentInfo 32 (Just 64)) (pointerLayouts ddl)
},
"E-p1:8:32:64",
Nothing
), (
"big",
ddl {
endianness = LittleEndian,
mangling = Just ELFMangling,
stackAlignment = Just 128,
pointerLayouts = Map.fromList [
(AddrSpace 0, (8, AlignmentInfo {abiAlignment = 8, preferredAlignment = Just 16}))
],
typeLayouts = Map.fromList [
((IntegerAlign, 1), AlignmentInfo {abiAlignment = 8, preferredAlignment = Just 256}),
((IntegerAlign, 8), AlignmentInfo {abiAlignment = 8, preferredAlignment = Just 256}),
((IntegerAlign, 16), AlignmentInfo {abiAlignment = 16, preferredAlignment = Just 256}),
((IntegerAlign, 32), AlignmentInfo {abiAlignment = 32, preferredAlignment = Just 256}),
((IntegerAlign, 64), AlignmentInfo {abiAlignment = 64, preferredAlignment = Just 256}),
((VectorAlign, 64), AlignmentInfo {abiAlignment = 64, preferredAlignment = Just 256}),
((VectorAlign, 128), AlignmentInfo {abiAlignment = 128, preferredAlignment = Just 256}),
((FloatAlign, 32), AlignmentInfo {abiAlignment = 32, preferredAlignment = Just 256}),
((FloatAlign, 64), AlignmentInfo {abiAlignment = 64, preferredAlignment = Just 256}),
((FloatAlign, 80), AlignmentInfo {abiAlignment = 128, preferredAlignment = Just 256})
] `Map.union` typeLayouts ddl,
aggregateLayout = AlignmentInfo {abiAlignment = 0, preferredAlignment = Just 256},
nativeSizes = Just (Set.fromList [8,16,32,64])
},
"e-m:e-p:8:8:16-i1:8:256-i8:8:256-i16:16:256-i32:32:256-i64:64:256-f32:32:256-f64:64:256-v64:64:256-v128:128:256-a:0:256-f80:128:256-n8:16:32:64-S128",
Just "e-m:e-p:8:8:16-i1:8:256-i8:8:256-i16:16:256-i32:32:256-i64:64:256-f32:32:256-f64:64:256-v64:64:256-v128:128:256-a:0:256-f80:128:256-n8:16:32:64-S128"
)
]
]
]
|
|
0a1bd44afedd6efc04a5703cf42e588d3d4a98421159622e48eb4a1f04d64109 | overtone/overtone | defaults.clj | (ns ^{:doc "Default vals and fns required to manipulate ugens."
:author "Jeff Rose"}
overtone.sc.machinery.ugen.defaults
(:use [overtone.helpers lib]))
;; Outputs have a specified calculation rate
0 = scalar rate - one sample is computed at initialization time only .
1 = control rate - one sample is computed each control period .
2 = audio rate - one sample is computed for each sample of audio output .
(def RATES {:ir 0
:kr 1
:ar 2
:dr 3
:auto :auto})
(def CONTROL-PROXY-RATES
[:ir :ar :kr :tr])
(def UGEN-RATE-SPEED {:ir 0
:dr 1
:kr 2
:ar 3})
(def REVERSE-RATES (invert-map RATES))
(def HUMAN-RATES {:ir "initial"
:kr "control"
:ar "audio"
:dr "demand"})
(def UGEN-DEFAULT-RATE-PRECEDENCE [:ir :dr :ar :kr])
(def UGEN-DEFAULT-RATES #{:ar :kr})
(def UGEN-RATE-SORT-FN
(zipmap UGEN-DEFAULT-RATE-PRECEDENCE (range (count UGEN-DEFAULT-RATE-PRECEDENCE))))
(defn default-ugen-rate
"Given a list of rates, returns the default rate based on UGEN-RATE-SORT-FN"
[rates]
(first (sort-by UGEN-RATE-SORT-FN rates)))
(def NO-ARG-DOC-FOUND "-")
(def DEFAULT-ARG-DOCS
{"bufnum" "A buffer or buffer index value."
"freq" "Frequency in hz (cycles per second)"
"freq1" "Frequency in hz (cycles per second)"
"freq2" "Frequency in hz (cycles per second)"
"freq3" "Frequency in hz (cycles per second)"
"phase" "The start point within a cycle"
"loop" "A boolean switch to turn on looping"
"in" "The input signal"
})
| null | https://raw.githubusercontent.com/overtone/overtone/02f8cdd2817bf810ff390b6f91d3e84d61afcc85/src/overtone/sc/machinery/ugen/defaults.clj | clojure | Outputs have a specified calculation rate | (ns ^{:doc "Default vals and fns required to manipulate ugens."
:author "Jeff Rose"}
overtone.sc.machinery.ugen.defaults
(:use [overtone.helpers lib]))
0 = scalar rate - one sample is computed at initialization time only .
1 = control rate - one sample is computed each control period .
2 = audio rate - one sample is computed for each sample of audio output .
(def RATES {:ir 0
:kr 1
:ar 2
:dr 3
:auto :auto})
(def CONTROL-PROXY-RATES
[:ir :ar :kr :tr])
(def UGEN-RATE-SPEED {:ir 0
:dr 1
:kr 2
:ar 3})
(def REVERSE-RATES (invert-map RATES))
(def HUMAN-RATES {:ir "initial"
:kr "control"
:ar "audio"
:dr "demand"})
(def UGEN-DEFAULT-RATE-PRECEDENCE [:ir :dr :ar :kr])
(def UGEN-DEFAULT-RATES #{:ar :kr})
(def UGEN-RATE-SORT-FN
(zipmap UGEN-DEFAULT-RATE-PRECEDENCE (range (count UGEN-DEFAULT-RATE-PRECEDENCE))))
(defn default-ugen-rate
"Given a list of rates, returns the default rate based on UGEN-RATE-SORT-FN"
[rates]
(first (sort-by UGEN-RATE-SORT-FN rates)))
(def NO-ARG-DOC-FOUND "-")
(def DEFAULT-ARG-DOCS
{"bufnum" "A buffer or buffer index value."
"freq" "Frequency in hz (cycles per second)"
"freq1" "Frequency in hz (cycles per second)"
"freq2" "Frequency in hz (cycles per second)"
"freq3" "Frequency in hz (cycles per second)"
"phase" "The start point within a cycle"
"loop" "A boolean switch to turn on looping"
"in" "The input signal"
})
|
cd71938dc13ec3274c40ee9edf55a5eaf80da1622a7737eb894b3ba5e6543829 | hexlet-codebattle/battle_asserts | nrzi_encoding.clj | (ns battle-asserts.issues.nrzi-encoding
(:require [clojure.string :as s]
[clojure.test.check.generators :as gen]))
(def level :easy)
(def tags ["strings"])
(def description
{:en "Non return to zero, inverted (NRZI) is a method of mapping a binary signal to a physical signal
for transmission over some transmission media. The two level NRZI signal has a transition at
a clock boundary if the bit being transmitted is a logical 1,
and does not have a transition if the bit being transmitted is a logical 0.
0 100 10000 100 1 1 1
¯|___|¯¯¯¯¯|___|¯|_|¯"
:ru "NRZI кодирование - метод сопоставления двоичного сигнала с физическим сигналом
для передачи через некоторую среду. Двухуровневый сигнал NRZI имеет переход на границе тактовой частоты,
если передаваемый бит является логической 1,
и не имеет перехода, если передаваемый бит является логическим 0.
0 100 10000 100 1 1 1
¯|___|¯¯¯¯¯|___|¯|_|¯"})
(def signature
{:input [{:argument-name "seq" :type {:name "string"}}]
:output {:type {:name "string"}}})
(defn arguments-generator []
(letfn [(input []
(let [alphabet ["_" "¯"]]
(->>
(repeatedly (+ (rand-int 20) 2) #(rand-nth alphabet))
(reduce #(if (or (empty? %1)
(= (last %1) %2))
(conj %1 %2)
(conj %1 "|" %2))
[])
s/join)))] (gen/tuple (gen/elements (repeatedly 50 input)))))
(def test-data
[{:expected "010010000100111"
:arguments ["¯|___|¯¯¯¯¯|___|¯|_|¯"]}
{:expected "010110010"
:arguments ["¯|__|¯|___|¯¯"]}
{:expected "010011000110"
:arguments ["_|¯¯¯|_|¯¯¯¯|_|¯¯"]}])
(defn solution [coded-seq]
(->
coded-seq
(s/replace #"\|_|\|¯" "1")
(s/replace #"[^\d]" "0")))
| null | https://raw.githubusercontent.com/hexlet-codebattle/battle_asserts/3c5c91acf1c479839b9d9ddd8befe1d3d72063d8/src/battle_asserts/issues/nrzi_encoding.clj | clojure | (ns battle-asserts.issues.nrzi-encoding
(:require [clojure.string :as s]
[clojure.test.check.generators :as gen]))
(def level :easy)
(def tags ["strings"])
(def description
{:en "Non return to zero, inverted (NRZI) is a method of mapping a binary signal to a physical signal
for transmission over some transmission media. The two level NRZI signal has a transition at
a clock boundary if the bit being transmitted is a logical 1,
and does not have a transition if the bit being transmitted is a logical 0.
0 100 10000 100 1 1 1
¯|___|¯¯¯¯¯|___|¯|_|¯"
:ru "NRZI кодирование - метод сопоставления двоичного сигнала с физическим сигналом
для передачи через некоторую среду. Двухуровневый сигнал NRZI имеет переход на границе тактовой частоты,
если передаваемый бит является логической 1,
и не имеет перехода, если передаваемый бит является логическим 0.
0 100 10000 100 1 1 1
¯|___|¯¯¯¯¯|___|¯|_|¯"})
(def signature
{:input [{:argument-name "seq" :type {:name "string"}}]
:output {:type {:name "string"}}})
(defn arguments-generator []
(letfn [(input []
(let [alphabet ["_" "¯"]]
(->>
(repeatedly (+ (rand-int 20) 2) #(rand-nth alphabet))
(reduce #(if (or (empty? %1)
(= (last %1) %2))
(conj %1 %2)
(conj %1 "|" %2))
[])
s/join)))] (gen/tuple (gen/elements (repeatedly 50 input)))))
(def test-data
[{:expected "010010000100111"
:arguments ["¯|___|¯¯¯¯¯|___|¯|_|¯"]}
{:expected "010110010"
:arguments ["¯|__|¯|___|¯¯"]}
{:expected "010011000110"
:arguments ["_|¯¯¯|_|¯¯¯¯|_|¯¯"]}])
(defn solution [coded-seq]
(->
coded-seq
(s/replace #"\|_|\|¯" "1")
(s/replace #"[^\d]" "0")))
|
|
0e69f2ca0127bbecf371293601ec211d52907d2f8d6c97f50bbccad12c6c2311 | skanev/playground | 40.scm | SICP exercise 2.40
;
; Define a procedure unique-pairs that, given an integer n, generates the
sequence of pairs ( i , j ) with 1 ≤ j < i ≤ n. Use unique - pairs to simplify the
; definition of prime-sum-pairs given above.
(define (unique-pairs n)
(flatmap (lambda (a)
(map (lambda (b) (list a b))
(enumerate-interval (+ a 1) n)))
(enumerate-interval 1 n)))
(define (prime-sum-pairs n)
(filter (lambda (pair)
(prime? (+ (car pair)
(cadr pair))))
(unique-pairs n)))
(define (enumerate-interval a b)
(if (> a b)
(list)
(cons a
(enumerate-interval (+ a 1) b))))
(define (flatmap proc seq)
(accumulate append nil (map proc seq)))
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op initial (cdr sequence)))))
(define (prime? n)
(null?
(filter (lambda (x) (= 0 (remainder n x)))
(enumerate-interval 2 (- n 1)))))
(define nil '())
| null | https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/sicp/02/40.scm | scheme |
Define a procedure unique-pairs that, given an integer n, generates the
definition of prime-sum-pairs given above. | SICP exercise 2.40
sequence of pairs ( i , j ) with 1 ≤ j < i ≤ n. Use unique - pairs to simplify the
(define (unique-pairs n)
(flatmap (lambda (a)
(map (lambda (b) (list a b))
(enumerate-interval (+ a 1) n)))
(enumerate-interval 1 n)))
(define (prime-sum-pairs n)
(filter (lambda (pair)
(prime? (+ (car pair)
(cadr pair))))
(unique-pairs n)))
(define (enumerate-interval a b)
(if (> a b)
(list)
(cons a
(enumerate-interval (+ a 1) b))))
(define (flatmap proc seq)
(accumulate append nil (map proc seq)))
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op initial (cdr sequence)))))
(define (prime? n)
(null?
(filter (lambda (x) (= 0 (remainder n x)))
(enumerate-interval 2 (- n 1)))))
(define nil '())
|
33bd31eef244af20df1acd526f735a620925782584e43f5026605f7a73111cab | scarvalhojr/haskellbook | section11.18.hs |
import Data.Char (toUpper)
isSubseqOf :: (Eq a) => [a] -> [a] -> Bool
isSubseqOf [] _ = True
isSubseqOf _ [] = False
isSubseqOf xs@(x:xt) (y:yt)
| x == y = isSubseqOf xt yt
| otherwise = isSubseqOf xs yt
isSubseqOfWorks = (isSubseqOf "blah" "blahwoot" == True)
&& (isSubseqOf "blah" "wootblah" == True)
&& (isSubseqOf "blah" "wboloath" == True)
&& (isSubseqOf "blah" "wootbla" == False)
&& (isSubseqOf "blah" "halbwoot" == False)
&& (isSubseqOf "blah" "blawhoot" == True)
&& (isSubseqOf "blah" "bbblahhh" == True)
&& (isSubseqOf "blah" "bbblaahh" == True)
isContiguousSubseqOf :: (Eq a) => [a] -> [a] -> Bool
isContiguousSubseqOf [] _ = True
isContiguousSubseqOf _ [] = False
isContiguousSubseqOf xs@(x:xt) (y:yt)
| x == y = isPrefixOf xt yt || isContiguousSubseqOf xs yt
| otherwise = isContiguousSubseqOf xs yt
where isPrefixOf [] _ = True
isPrefixOf _ [] = False
isPrefixOf (x:xt) (y:yt) = (x == y) && isPrefixOf xt yt
isContiguousSubseqOfWorks = (isContiguousSubseqOf "blah" "blahwoot" == True)
&& (isContiguousSubseqOf "blah" "wootblah" == True)
&& (isContiguousSubseqOf "blah" "wboloath" == False)
&& (isContiguousSubseqOf "blah" "wootbla" == False)
&& (isContiguousSubseqOf "blah" "halbwoot" == False)
&& (isContiguousSubseqOf "blah" "blawhoot" == False)
&& (isContiguousSubseqOf "blah" "bbblahhh" == True)
&& (isContiguousSubseqOf "blah" "bbblaahh" == False)
capitalizeWords :: String -> [(String, String)]
capitalizeWords s = map capitalize (words s)
where capitalize xs@(x:xt) = (xs, toUpper x : xt)
capitalizeWordsWorks = capitalizeWords "hello world" ==
[("hello", "Hello"), ("world", "World")]
capitalizeWord :: String -> String
capitalizeWord [] = []
capitalizeWord (' ':xt) = ' ' : capitalizeWord xt
capitalizeWord (x:xt) = toUpper x : xt
capitalizeWordWorks = (capitalizeWord "Chortle" == "Chortle")
&& (capitalizeWord "chortle" == "Chortle")
&& (capitalizeWord " chortle" == " Chortle")
splitOn :: Char -> String -> [String]
splitOn d = foldr f [[]]
where f c xs@(x:xt)
| c == d = [c]:xs
| otherwise = (c:x):xt
capitalizeParagraph :: String -> String
capitalizeParagraph t = concat (map capitalizeWord (splitOn '.' t))
capitalizeParagraphWorks = (capitalizeParagraph "blah. woot ha." ==
"Blah. Woot ha.")
&& (capitalizeParagraph " blah. woot ha. " ==
" Blah. Woot ha. ")
&& (capitalizeParagraph " blah. woot ha " ==
" Blah. Woot ha ")
main :: IO ()
main = do
putStrLn $ "isSubseqOfWorks: " ++ show isSubseqOfWorks
putStrLn $ "isContiguousSubseqOfWorks: " ++ show isContiguousSubseqOfWorks
putStrLn $ "capitalizeWordsWorks: " ++ show capitalizeWordsWorks
putStrLn $ "capitalizeWordWorks: " ++ show capitalizeWordWorks
putStrLn $ "capitalizeParagraphWorks: " ++ show capitalizeParagraphWorks
| null | https://raw.githubusercontent.com/scarvalhojr/haskellbook/6016a5a78da3fc4a29f5ea68b239563895c448d5/chapter11/section11.18.hs | haskell |
import Data.Char (toUpper)
isSubseqOf :: (Eq a) => [a] -> [a] -> Bool
isSubseqOf [] _ = True
isSubseqOf _ [] = False
isSubseqOf xs@(x:xt) (y:yt)
| x == y = isSubseqOf xt yt
| otherwise = isSubseqOf xs yt
isSubseqOfWorks = (isSubseqOf "blah" "blahwoot" == True)
&& (isSubseqOf "blah" "wootblah" == True)
&& (isSubseqOf "blah" "wboloath" == True)
&& (isSubseqOf "blah" "wootbla" == False)
&& (isSubseqOf "blah" "halbwoot" == False)
&& (isSubseqOf "blah" "blawhoot" == True)
&& (isSubseqOf "blah" "bbblahhh" == True)
&& (isSubseqOf "blah" "bbblaahh" == True)
isContiguousSubseqOf :: (Eq a) => [a] -> [a] -> Bool
isContiguousSubseqOf [] _ = True
isContiguousSubseqOf _ [] = False
isContiguousSubseqOf xs@(x:xt) (y:yt)
| x == y = isPrefixOf xt yt || isContiguousSubseqOf xs yt
| otherwise = isContiguousSubseqOf xs yt
where isPrefixOf [] _ = True
isPrefixOf _ [] = False
isPrefixOf (x:xt) (y:yt) = (x == y) && isPrefixOf xt yt
isContiguousSubseqOfWorks = (isContiguousSubseqOf "blah" "blahwoot" == True)
&& (isContiguousSubseqOf "blah" "wootblah" == True)
&& (isContiguousSubseqOf "blah" "wboloath" == False)
&& (isContiguousSubseqOf "blah" "wootbla" == False)
&& (isContiguousSubseqOf "blah" "halbwoot" == False)
&& (isContiguousSubseqOf "blah" "blawhoot" == False)
&& (isContiguousSubseqOf "blah" "bbblahhh" == True)
&& (isContiguousSubseqOf "blah" "bbblaahh" == False)
capitalizeWords :: String -> [(String, String)]
capitalizeWords s = map capitalize (words s)
where capitalize xs@(x:xt) = (xs, toUpper x : xt)
capitalizeWordsWorks = capitalizeWords "hello world" ==
[("hello", "Hello"), ("world", "World")]
capitalizeWord :: String -> String
capitalizeWord [] = []
capitalizeWord (' ':xt) = ' ' : capitalizeWord xt
capitalizeWord (x:xt) = toUpper x : xt
capitalizeWordWorks = (capitalizeWord "Chortle" == "Chortle")
&& (capitalizeWord "chortle" == "Chortle")
&& (capitalizeWord " chortle" == " Chortle")
splitOn :: Char -> String -> [String]
splitOn d = foldr f [[]]
where f c xs@(x:xt)
| c == d = [c]:xs
| otherwise = (c:x):xt
capitalizeParagraph :: String -> String
capitalizeParagraph t = concat (map capitalizeWord (splitOn '.' t))
capitalizeParagraphWorks = (capitalizeParagraph "blah. woot ha." ==
"Blah. Woot ha.")
&& (capitalizeParagraph " blah. woot ha. " ==
" Blah. Woot ha. ")
&& (capitalizeParagraph " blah. woot ha " ==
" Blah. Woot ha ")
main :: IO ()
main = do
putStrLn $ "isSubseqOfWorks: " ++ show isSubseqOfWorks
putStrLn $ "isContiguousSubseqOfWorks: " ++ show isContiguousSubseqOfWorks
putStrLn $ "capitalizeWordsWorks: " ++ show capitalizeWordsWorks
putStrLn $ "capitalizeWordWorks: " ++ show capitalizeWordWorks
putStrLn $ "capitalizeParagraphWorks: " ++ show capitalizeParagraphWorks
|
|
b4f2a3596261cc7d35fe7e4d6091ab8e3992cf6795185290e34d3a83e3fd51f2 | Naproche-SAD/Naproche-SAD | Thesis.hs |
Authors : ( 2001 - 2008 ) , ( 2017 - 2018 )
Maintain the current thesis .
Authors: Andrei Paskevich (2001 - 2008), Steffen Frerix (2017 - 2018)
Maintain the current thesis.
-}
module SAD.Core.Thesis (inferNewThesis) where
import SAD.Data.Formula
import SAD.Data.Definition (Definitions)
import SAD.Data.Text.Context (Context)
import qualified SAD.Data.Text.Context as Context
import SAD.Core.Base
import SAD.Core.Reason
import Control.Monad
import Data.List
import Data.Maybe
import Control.Applicative
import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import qualified Data.Map as Map
-- Infer new thesis
Infer the newThesis . Also report whether it is motivated and whether it has
changed at all
changed at all -}
inferNewThesis :: Definitions -> [Context] -> Context -> (Bool, Bool, Context)
inferNewThesis definitions wholeContext@(context:_) thesis
| isFunctionMacro context = functionTaskThesis context thesis
| otherwise = (motivated, changed, newThesis)
where
-- a thesis can only become unmotivated through an assumption
motivated = notAnAssumption || isJust usefulVariation
newThesis = Context.setForm thesis $ reduceWithEvidence $ getObj postReductionThesis
changed = hasChanged postReductionThesis
postReductionThesis
| notAnAssumption = -- enable destruction of defined symbols in this case
reduceThesis definitions (Context.formula context) preReductionThesis
| otherwise =
reductionInViewOf (Context.formula context) preReductionThesis
preReductionThesis
| notAnAssumption = thesisFormula
| otherwise = fromMaybe thesisFormula usefulVariation
usefulVariation = findUsefulVariation definitions wholeContext thesisFormula
thesisFormula = strip $ Context.formula thesis
notAnAssumption = not $ Context.isAssumption context
-- Reduce f in view of g
{- contraction in view of a set of formulae -}
reductionInViewOf :: Formula -> Formula -> ChangeInfo Formula
reductionInViewOf = reduce . externalConjuncts
where
reduce hs f
| isTop f = return Top
| isBot f = return Bot
| any (equivalentTo f) hs = changed Top
| any (equivalentTo $ Not f) hs = changed Bot
| isExi f && f `hasInstantiationIn` hs = changed Top
| isAll f && (albet $ Not f) `hasInstantiationIn` hs = changed Bot
| isTrm f = return f
| isIff f = reduce hs $ albet f
| otherwise = bool <$> mapFM (reduce hs) f
{- the equivalence test used here is quite crude, but cheap:
syntactic equality modulo alpha-beta normalization -}
equivalentTo :: Formula -> Formula -> Bool
equivalentTo = normalizedCheck 0
where
normalizedCheck n f g = check n (albet f) (albet g)
check n (All _ a) (All _ b) = let freshVariable = show n in
normalizedCheck (succ n) (inst freshVariable a) (inst freshVariable b)
check n (Exi _ a) (Exi _ b) = let freshVariable = show n in
normalizedCheck (succ n) (inst freshVariable a) (inst freshVariable b)
check n (And a b) (And c d) = normalizedCheck n a c && normalizedCheck n b d
check n (Or a b) (Or c d) = normalizedCheck n a c && normalizedCheck n b d
check n (Not a) (Not b) = normalizedCheck n a b
check n (Tag _ a) b = normalizedCheck n a b
check n a (Tag _ b) = normalizedCheck n a b
check _ Top Top = True
check _ Bot Bot = True
check _ a b = twins a b
{- checks whether an instantitation of f (modulo local properties collected)
can be patched together from the hs. Important to be able to reduce an
existential thesis. -}
hasInstantiationIn:: Formula -> [Formula] -> Bool
hasInstantiationIn (Exi _ f) = not . null . listOfInstantiations f
hasInstantiation _ _ =
error "SAD.Core.Thesis.hasInstantiationIn:\
\non-existentially quantified argument"
type Instantiation = Map.Map String Formula
{- the actual process of finding an instantiation. -}
listOfInstantiations :: Formula -> [Formula] -> [Instantiation]
listOfInstantiations f = instantiations 1 Map.empty (albet $ inst "i0" f)
worker function for SAD.Core . Thesis.listOfInstantiations
-- FIXME This functions needs a better way to generate free variables. The
-- explicit parameter passing is inadequate.
instantiations n currentInst f hs =
[ newInst | h <- hs, newInst <- extendInstantiation currentInst f h ] ++
patchTogether (albet f)
where
patchTogether (And f g) = -- find instantiation of g then extend them to f
[ fInst | gInst <- instantiations n currentInst (albet g) hs,
fInst <- instantiations n gInst (albet f) $
subInfo gInst (pred n) ++ hs ]--add collected local properties
patchTogether (Exi _ f) =
instantiations (succ n) currentInst (albet $ inst ('i':show n) f) hs
patchTogether _ = []
subInfo sb n =
let sub = applySb sb $ zVar $ 'i':show n
in map (replace sub ThisT) $ trInfo $ sub
finds an instantiation to make a formula equal to a second formula .
An initial instantiation is given which is then tried to be extended .
Result is returned within the list monad .
An initial instantiation is given which is then tried to be extended.
Result is returned within the list monad. -}
extendInstantiation :: Instantiation -> Formula -> Formula -> [Instantiation]
extendInstantiation sb f g = snd <$> runStateT (normalizedDive 0 f g) sb
where
normalizedDive n f g = dive n (albet f) (albet g)
dive n (All _ f) (All _ g)
= let nn = show n in normalizedDive (succ n) (inst nn f) (inst nn g)
dive n (Exi _ f) (Exi _ g)
= let nn = show n in normalizedDive (succ n) (inst nn f) (inst nn g)
dive n (And f1 g1) (And f2 g2) =
normalizedDive n f1 f2 >> normalizedDive n g1 g2
dive n (Or f1 g1) (Or f2 g2) =
normalizedDive n f1 f2 >> normalizedDive n g1 g2
dive n (Not f) (Not g) = dive n f g
dive n Trm {trId = t1, trArgs = ts1} Trm {trId = t2, trArgs = ts2}
= lift (guard $ t1 == t2) >> mapM_ (uncurry $ dive n) (zip ts1 ts2)
dive _ v@Var {trName = s@('i':_)} t = do
mp <- get; case Map.lookup s mp of
Nothing -> modify (Map.insert s t)
Just t' -> lift $ guard (twins t t')
dive _ v@Var{} w@Var{} = lift $ guard (twins v w)
dive _ _ _ = lift mzero
-- External conjuncts
{- find all external conjuncts of a formula -}
externalConjuncts :: Formula -> [Formula]
externalConjuncts = normalizedDive
where
normalizedDive = dive . albet
dive h@(And f g) = h : (normalizedDive f ++ normalizedDive g)
dive h@(Exi _ f) = h : filter closed (normalizedDive f)
dive h@(All _ f) = h : filter closed (normalizedDive f)
dive (Tag _ f) = normalizedDive f
dive f = [f]
{- find a useful variation of the thesis (with respect to a given assumption)-}
findUsefulVariation :: Definitions -> [Context] -> Formula -> Maybe Formula
findUsefulVariation definitions (assumption:restContext) thesis =
find useful variations
where
variations = map snd $
runVM (generateVariations definitions thesis) $ Context.declaredNames assumption
useful variation = isTop $ getObj $
reductionInViewOf (Not variation) $ Context.formula assumption
findUsefulVariation _ _ _ =
error "SAD.Core.Thesis.findUsefulVariation: empty context"
--- improved reduction
reduce the thesis and possibly look behind symbol definitions . Only one
layer of definition can be stripped away .
layer of definition can be stripped away. -}
reduceThesis :: Definitions -> Formula -> Formula -> ChangeInfo Formula
reduceThesis definitions affirmation thesis =
let reducedThesis = reductionInViewOf affirmation thesis
expandedThesis = expandSymbols thesis
reducedExpandedThesis =
reductionInViewOf affirmation expandedThesis
in if (not . hasChanged) reducedThesis -- if reduction does not work
then if (not . hasChanged) reducedExpandedThesis--try it after expansion
then return thesis -- if it still does nothing -> give up
else reducedExpandedThesis
else reducedThesis
where
expandSymbols t@Trm{}= fromMaybe t $ defForm definitions t
expandSymbols f = mapF expandSymbols f
-- Find possible variations
{- Generate all possible variations-}
generateVariations :: Definitions -> Formula -> VariationMonad Formula
generateVariations definitions = pass [] (Just True) 0
where
pass localContext sign n = dive
where
dive h@(All _ f) = case sign of
Just True -> liberateVariableIn f `mplus` roundThrough h
_ -> return h
dive h@(Exi _ f) = case sign of
Just False -> liberateVariableIn f `mplus` roundThrough h
_ -> return h
dive h@Trm{} = return h `mplus` lookBehindDefinition h
dive h@(And f g) = case sign of
Just True -> And f <$> pass (f:localContext) sign n g
_ -> roundThrough h
dive h@(Or f g) = case sign of
Just False -> Or f <$> pass (Not f:localContext) sign n g
_ -> roundThrough h
dive h@(Imp f g) = case sign of
Just False -> Imp f <$> pass (f:localContext) sign n g
_ -> roundThrough h
dive (Tag GenericMark f) = return f
dive h = roundThrough h
liberateVariableIn f = generateInstantiations f >>= dive
roundThrough = roundFM 'z' pass localContext sign n
lookBehindDefinition t = msum . map (dive . reduceWithEvidence .
markRecursive (trId t)) . maybeToList . defForm definitions $ t
{- mark symbols that are recursively defined in their defining formula, so that
the definition is not infinitely expanded -}
markRecursive n t@Trm{trId = m}
| n == m = Tag GenericMark t
| otherwise = t
markRecursive n f = mapF (markRecursive n) f
{- generate all instantiations with as of yet unused variables -}
generateInstantiations f = VM (tryAllVars [])
where
tryAllVars accumulator (v:vs) =
(accumulator ++ vs, inst v f) : tryAllVars (v:accumulator) vs
tryAllVars _ [] = []
-- Variation monad
{- monad to do bookkeeping during the search for a variation, i.e. keep track
of which variables have already been used for an instantiation -}
newtype VariationMonad res =
VM { runVM :: [String] -> [([String], res)] }
instance Functor VariationMonad where
fmap = liftM
instance Applicative VariationMonad where
pure = return
(<*>) = ap
instance Monad VariationMonad where
return r = VM $ \ s -> [(s, r)]
m >>= k = VM $ \ s -> concatMap apply (runVM m s)
where apply (s, r) = runVM (k r) s
instance Alternative VariationMonad where
empty = mzero
(<|>) = mplus
instance MonadPlus VariationMonad where
mzero = VM $ \ _ -> []
mplus m k = VM $ \ s -> runVM m s ++ runVM k s
-- special reduction of function thesis
isFunctionMacro = isMacro . Context.formula
where
isMacro (Tag tg _ ) = fnTag tg
isMacro _ = False
functionTaskThesis context thesis = (True, changed, newThesis)
where
newThesis = Context.setForm thesis $ getObj reducedThesis
changed = hasChanged reducedThesis
thesisFormula = Context.formula thesis
reducedThesis = reduceFunctionTask (Context.formula context) thesisFormula
reduceFunctionTask (Tag tg _) = fmap boolSimp . dive
where
dive (Tag tg' _) | tg' == tg = changed Top
dive f = mapFM dive f
reduceFuntionTask _ = error "SAD.Core.Thesis.reduceFunctionTask:\
\argument is not a function task"
-- Change Monad
{- a simple monad to keep track of whether a function has changed its
input or returns it unchanged -}
-- FIXME This bookkeeping monad is superfluous. A simple syntactic equality
-- check to determine the changedness status should suffice and should
-- not be noticable performancewise.
data ChangeInfo a = Change {getObj :: a, hasChanged :: Bool}
instance Functor ChangeInfo where
fmap = liftM
instance Applicative ChangeInfo where
pure = return
(<*>) = ap
instance Monad ChangeInfo where
return a = Change a False
Change a p >>= f = let Change b q = f a in Change b (p || q)
changed :: a -> ChangeInfo a -- declare a change to an object
changed a = Change a True
| null | https://raw.githubusercontent.com/Naproche-SAD/Naproche-SAD/da131a6eaf65d4e02e82082a50a4febb6d42db3d/src/SAD/Core/Thesis.hs | haskell | Infer new thesis
a thesis can only become unmotivated through an assumption
enable destruction of defined symbols in this case
Reduce f in view of g
contraction in view of a set of formulae
the equivalence test used here is quite crude, but cheap:
syntactic equality modulo alpha-beta normalization
checks whether an instantitation of f (modulo local properties collected)
can be patched together from the hs. Important to be able to reduce an
existential thesis.
the actual process of finding an instantiation.
FIXME This functions needs a better way to generate free variables. The
explicit parameter passing is inadequate.
find instantiation of g then extend them to f
add collected local properties
External conjuncts
find all external conjuncts of a formula
find a useful variation of the thesis (with respect to a given assumption)
- improved reduction
if reduction does not work
try it after expansion
if it still does nothing -> give up
Find possible variations
Generate all possible variations
mark symbols that are recursively defined in their defining formula, so that
the definition is not infinitely expanded
generate all instantiations with as of yet unused variables
Variation monad
monad to do bookkeeping during the search for a variation, i.e. keep track
of which variables have already been used for an instantiation
special reduction of function thesis
Change Monad
a simple monad to keep track of whether a function has changed its
input or returns it unchanged
FIXME This bookkeeping monad is superfluous. A simple syntactic equality
check to determine the changedness status should suffice and should
not be noticable performancewise.
declare a change to an object |
Authors : ( 2001 - 2008 ) , ( 2017 - 2018 )
Maintain the current thesis .
Authors: Andrei Paskevich (2001 - 2008), Steffen Frerix (2017 - 2018)
Maintain the current thesis.
-}
module SAD.Core.Thesis (inferNewThesis) where
import SAD.Data.Formula
import SAD.Data.Definition (Definitions)
import SAD.Data.Text.Context (Context)
import qualified SAD.Data.Text.Context as Context
import SAD.Core.Base
import SAD.Core.Reason
import Control.Monad
import Data.List
import Data.Maybe
import Control.Applicative
import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import qualified Data.Map as Map
Infer the newThesis . Also report whether it is motivated and whether it has
changed at all
changed at all -}
inferNewThesis :: Definitions -> [Context] -> Context -> (Bool, Bool, Context)
inferNewThesis definitions wholeContext@(context:_) thesis
| isFunctionMacro context = functionTaskThesis context thesis
| otherwise = (motivated, changed, newThesis)
where
motivated = notAnAssumption || isJust usefulVariation
newThesis = Context.setForm thesis $ reduceWithEvidence $ getObj postReductionThesis
changed = hasChanged postReductionThesis
postReductionThesis
reduceThesis definitions (Context.formula context) preReductionThesis
| otherwise =
reductionInViewOf (Context.formula context) preReductionThesis
preReductionThesis
| notAnAssumption = thesisFormula
| otherwise = fromMaybe thesisFormula usefulVariation
usefulVariation = findUsefulVariation definitions wholeContext thesisFormula
thesisFormula = strip $ Context.formula thesis
notAnAssumption = not $ Context.isAssumption context
reductionInViewOf :: Formula -> Formula -> ChangeInfo Formula
reductionInViewOf = reduce . externalConjuncts
where
reduce hs f
| isTop f = return Top
| isBot f = return Bot
| any (equivalentTo f) hs = changed Top
| any (equivalentTo $ Not f) hs = changed Bot
| isExi f && f `hasInstantiationIn` hs = changed Top
| isAll f && (albet $ Not f) `hasInstantiationIn` hs = changed Bot
| isTrm f = return f
| isIff f = reduce hs $ albet f
| otherwise = bool <$> mapFM (reduce hs) f
equivalentTo :: Formula -> Formula -> Bool
equivalentTo = normalizedCheck 0
where
normalizedCheck n f g = check n (albet f) (albet g)
check n (All _ a) (All _ b) = let freshVariable = show n in
normalizedCheck (succ n) (inst freshVariable a) (inst freshVariable b)
check n (Exi _ a) (Exi _ b) = let freshVariable = show n in
normalizedCheck (succ n) (inst freshVariable a) (inst freshVariable b)
check n (And a b) (And c d) = normalizedCheck n a c && normalizedCheck n b d
check n (Or a b) (Or c d) = normalizedCheck n a c && normalizedCheck n b d
check n (Not a) (Not b) = normalizedCheck n a b
check n (Tag _ a) b = normalizedCheck n a b
check n a (Tag _ b) = normalizedCheck n a b
check _ Top Top = True
check _ Bot Bot = True
check _ a b = twins a b
hasInstantiationIn:: Formula -> [Formula] -> Bool
hasInstantiationIn (Exi _ f) = not . null . listOfInstantiations f
hasInstantiation _ _ =
error "SAD.Core.Thesis.hasInstantiationIn:\
\non-existentially quantified argument"
type Instantiation = Map.Map String Formula
listOfInstantiations :: Formula -> [Formula] -> [Instantiation]
listOfInstantiations f = instantiations 1 Map.empty (albet $ inst "i0" f)
worker function for SAD.Core . Thesis.listOfInstantiations
instantiations n currentInst f hs =
[ newInst | h <- hs, newInst <- extendInstantiation currentInst f h ] ++
patchTogether (albet f)
where
[ fInst | gInst <- instantiations n currentInst (albet g) hs,
fInst <- instantiations n gInst (albet f) $
patchTogether (Exi _ f) =
instantiations (succ n) currentInst (albet $ inst ('i':show n) f) hs
patchTogether _ = []
subInfo sb n =
let sub = applySb sb $ zVar $ 'i':show n
in map (replace sub ThisT) $ trInfo $ sub
finds an instantiation to make a formula equal to a second formula .
An initial instantiation is given which is then tried to be extended .
Result is returned within the list monad .
An initial instantiation is given which is then tried to be extended.
Result is returned within the list monad. -}
extendInstantiation :: Instantiation -> Formula -> Formula -> [Instantiation]
extendInstantiation sb f g = snd <$> runStateT (normalizedDive 0 f g) sb
where
normalizedDive n f g = dive n (albet f) (albet g)
dive n (All _ f) (All _ g)
= let nn = show n in normalizedDive (succ n) (inst nn f) (inst nn g)
dive n (Exi _ f) (Exi _ g)
= let nn = show n in normalizedDive (succ n) (inst nn f) (inst nn g)
dive n (And f1 g1) (And f2 g2) =
normalizedDive n f1 f2 >> normalizedDive n g1 g2
dive n (Or f1 g1) (Or f2 g2) =
normalizedDive n f1 f2 >> normalizedDive n g1 g2
dive n (Not f) (Not g) = dive n f g
dive n Trm {trId = t1, trArgs = ts1} Trm {trId = t2, trArgs = ts2}
= lift (guard $ t1 == t2) >> mapM_ (uncurry $ dive n) (zip ts1 ts2)
dive _ v@Var {trName = s@('i':_)} t = do
mp <- get; case Map.lookup s mp of
Nothing -> modify (Map.insert s t)
Just t' -> lift $ guard (twins t t')
dive _ v@Var{} w@Var{} = lift $ guard (twins v w)
dive _ _ _ = lift mzero
externalConjuncts :: Formula -> [Formula]
externalConjuncts = normalizedDive
where
normalizedDive = dive . albet
dive h@(And f g) = h : (normalizedDive f ++ normalizedDive g)
dive h@(Exi _ f) = h : filter closed (normalizedDive f)
dive h@(All _ f) = h : filter closed (normalizedDive f)
dive (Tag _ f) = normalizedDive f
dive f = [f]
findUsefulVariation :: Definitions -> [Context] -> Formula -> Maybe Formula
findUsefulVariation definitions (assumption:restContext) thesis =
find useful variations
where
variations = map snd $
runVM (generateVariations definitions thesis) $ Context.declaredNames assumption
useful variation = isTop $ getObj $
reductionInViewOf (Not variation) $ Context.formula assumption
findUsefulVariation _ _ _ =
error "SAD.Core.Thesis.findUsefulVariation: empty context"
reduce the thesis and possibly look behind symbol definitions . Only one
layer of definition can be stripped away .
layer of definition can be stripped away. -}
reduceThesis :: Definitions -> Formula -> Formula -> ChangeInfo Formula
reduceThesis definitions affirmation thesis =
let reducedThesis = reductionInViewOf affirmation thesis
expandedThesis = expandSymbols thesis
reducedExpandedThesis =
reductionInViewOf affirmation expandedThesis
else reducedExpandedThesis
else reducedThesis
where
expandSymbols t@Trm{}= fromMaybe t $ defForm definitions t
expandSymbols f = mapF expandSymbols f
generateVariations :: Definitions -> Formula -> VariationMonad Formula
generateVariations definitions = pass [] (Just True) 0
where
pass localContext sign n = dive
where
dive h@(All _ f) = case sign of
Just True -> liberateVariableIn f `mplus` roundThrough h
_ -> return h
dive h@(Exi _ f) = case sign of
Just False -> liberateVariableIn f `mplus` roundThrough h
_ -> return h
dive h@Trm{} = return h `mplus` lookBehindDefinition h
dive h@(And f g) = case sign of
Just True -> And f <$> pass (f:localContext) sign n g
_ -> roundThrough h
dive h@(Or f g) = case sign of
Just False -> Or f <$> pass (Not f:localContext) sign n g
_ -> roundThrough h
dive h@(Imp f g) = case sign of
Just False -> Imp f <$> pass (f:localContext) sign n g
_ -> roundThrough h
dive (Tag GenericMark f) = return f
dive h = roundThrough h
liberateVariableIn f = generateInstantiations f >>= dive
roundThrough = roundFM 'z' pass localContext sign n
lookBehindDefinition t = msum . map (dive . reduceWithEvidence .
markRecursive (trId t)) . maybeToList . defForm definitions $ t
markRecursive n t@Trm{trId = m}
| n == m = Tag GenericMark t
| otherwise = t
markRecursive n f = mapF (markRecursive n) f
generateInstantiations f = VM (tryAllVars [])
where
tryAllVars accumulator (v:vs) =
(accumulator ++ vs, inst v f) : tryAllVars (v:accumulator) vs
tryAllVars _ [] = []
newtype VariationMonad res =
VM { runVM :: [String] -> [([String], res)] }
instance Functor VariationMonad where
fmap = liftM
instance Applicative VariationMonad where
pure = return
(<*>) = ap
instance Monad VariationMonad where
return r = VM $ \ s -> [(s, r)]
m >>= k = VM $ \ s -> concatMap apply (runVM m s)
where apply (s, r) = runVM (k r) s
instance Alternative VariationMonad where
empty = mzero
(<|>) = mplus
instance MonadPlus VariationMonad where
mzero = VM $ \ _ -> []
mplus m k = VM $ \ s -> runVM m s ++ runVM k s
isFunctionMacro = isMacro . Context.formula
where
isMacro (Tag tg _ ) = fnTag tg
isMacro _ = False
functionTaskThesis context thesis = (True, changed, newThesis)
where
newThesis = Context.setForm thesis $ getObj reducedThesis
changed = hasChanged reducedThesis
thesisFormula = Context.formula thesis
reducedThesis = reduceFunctionTask (Context.formula context) thesisFormula
reduceFunctionTask (Tag tg _) = fmap boolSimp . dive
where
dive (Tag tg' _) | tg' == tg = changed Top
dive f = mapFM dive f
reduceFuntionTask _ = error "SAD.Core.Thesis.reduceFunctionTask:\
\argument is not a function task"
data ChangeInfo a = Change {getObj :: a, hasChanged :: Bool}
instance Functor ChangeInfo where
fmap = liftM
instance Applicative ChangeInfo where
pure = return
(<*>) = ap
instance Monad ChangeInfo where
return a = Change a False
Change a p >>= f = let Change b q = f a in Change b (p || q)
changed a = Change a True
|
924398f94e91ea614cf6b58563c47d0fd57b53216f595acb500069f06833bc6a | EFanZh/EOPL-Exercises | exercise-1.27.rkt | #lang eopl
Exercise 1.27 [ ★ ★ ] ( flatten slist ) returns a list of the symbols contained in slist in the order in which they occur
when is printed . Intuitively , flatten removes all the inner parentheses from its argument .
;;
;; > (flatten '(a b c))
;; (a b c)
;; > (flatten '((a) () (b ()) () (c)))
;; (a b c)
;; > (flatten '((a b) c (((d)) e)))
;; (a b c d e)
;; > (flatten '(a b (() (c))))
;; (a b c)
(define flatten-element
(lambda (tail element)
(if (list? element)
(flatten-helper tail element)
(cons element tail))))
(define flatten-helper
(lambda (tail slist)
(if (null? slist)
tail
(flatten-element (flatten-helper tail (cdr slist))
(car slist)))))
(define flatten
(lambda (slist)
(flatten-helper '() slist)))
(provide flatten)
| null | https://raw.githubusercontent.com/EFanZh/EOPL-Exercises/11667f1e84a1a3e300c2182630b56db3e3d9246a/solutions/exercise-1.27.rkt | racket |
> (flatten '(a b c))
(a b c)
> (flatten '((a) () (b ()) () (c)))
(a b c)
> (flatten '((a b) c (((d)) e)))
(a b c d e)
> (flatten '(a b (() (c))))
(a b c) | #lang eopl
Exercise 1.27 [ ★ ★ ] ( flatten slist ) returns a list of the symbols contained in slist in the order in which they occur
when is printed . Intuitively , flatten removes all the inner parentheses from its argument .
(define flatten-element
(lambda (tail element)
(if (list? element)
(flatten-helper tail element)
(cons element tail))))
(define flatten-helper
(lambda (tail slist)
(if (null? slist)
tail
(flatten-element (flatten-helper tail (cdr slist))
(car slist)))))
(define flatten
(lambda (slist)
(flatten-helper '() slist)))
(provide flatten)
|
d0569d630762b0a85ce92b149299fbea47c1e6fc1f5c685849c1b7b428d6ee86 | CryptoKami/cryptokami-core | Util.hs | # LANGUAGE PolyKinds #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE TypeOperators #
module Pos.Util.Util
(
-- * Exceptions/errors
maybeThrow
, eitherToThrow
, leftToPanic
, toAesonError
, aesonError
, toCborError
, cborError
, toTemplateHaskellError
, templateHaskellError
, toParsecError
, parsecError
, toCerealError
, cerealError
-- * Ether
, ether
, Ether.TaggedTrans
, HasLens(..)
, HasLens'
, lensOf'
, lensOfProxy
-- * Lifting monads
, PowerLift(..)
*
, MinMax(..)
, _MinMax
, mkMinMax
, minMaxOf
*
, parseJSONWithRead
* NonEmpty
, neZipWith3
, neZipWith4
, spanSafe
, takeLastNE
-- * Logging helpers
, buildListBounds
, multilineBounds
, logException
, bracketWithLogging
-- * Misc
, mconcatPair
, microsecondsToUTC
, Sign (..)
, getKeys
, sortWithMDesc
, dumpSplices
, histogram
, median
, (<//>)
, divRoundUp
, sleep
) where
import Universum
import qualified Codec.CBOR.Decoding as CBOR
import Control.Concurrent (threadDelay)
import qualified Control.Exception.Safe as E
import Control.Lens (Getting, Iso', coerced, foldMapOf, ( # ))
import Control.Monad.Trans.Class (MonadTrans)
import Data.Aeson (FromJSON (..))
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as A
import Data.HashSet (fromMap)
import Data.List (span, zipWith3, zipWith4)
import qualified Data.List.NonEmpty as NE
import qualified Data.Map as M
import Data.Ratio ((%))
import qualified Data.Semigroup as Smg
import qualified Data.Serialize as Cereal
import Data.Time.Clock (NominalDiffTime, UTCTime)
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
import Data.Time.Units (Microsecond, toMicroseconds)
import qualified Ether
import Ether.Internal (HasLens (..))
import qualified Formatting as F
import qualified Language.Haskell.TH as TH
import qualified Prelude
import Serokell.Util (listJson)
import Serokell.Util.Exceptions ()
import System.Wlog (LoggerName, WithLogger, logError, logInfo, usingLoggerName)
import qualified Text.Megaparsec as P
----------------------------------------------------------------------------
-- Exceptions/errors
----------------------------------------------------------------------------
maybeThrow :: (MonadThrow m, Exception e) => e -> Maybe a -> m a
maybeThrow e = maybe (throwM e) pure
-- | Throw exception or return result depending on what is stored in 'Either'
eitherToThrow
:: (MonadThrow m, Exception e)
=> Either e a -> m a
eitherToThrow = either throwM pure
-- | Partial function which calls 'error' with meaningful message if
-- given 'Left' and returns some value if given 'Right'.
-- Intended usage is when you're sure that value must be right.
leftToPanic :: Buildable a => Text -> Either a b -> b
leftToPanic msgPrefix = either (error . mappend msgPrefix . pretty) identity
type f ~> g = forall x. f x -> g x
| This unexported helper is used to define conversions to ' MonadFail '
-- forced on us by external APIs. I also used underscores in its name, so don't
-- you think about exporting it -- define a specialized helper instead.
--
This must be the only place in our codebase where we allow ' MonadFail ' .
external_api_fail :: MonadFail m => Either Text ~> m
external_api_fail = either (fail . toString) return
-- | Convert an 'Either'-encoded failure to an 'aeson' parser failure. The
return monad is intentionally specialized because we avoid ' MonadFail ' .
toAesonError :: Either Text ~> A.Parser
toAesonError = external_api_fail
aesonError :: Text -> A.Parser a
aesonError = toAesonError . Left
-- | Convert an 'Either'-encoded failure to a 'cborg' decoder failure. The
return monad is intentionally specialized because we avoid ' MonadFail ' .
toCborError :: Either Text ~> CBOR.Decoder s
toCborError = external_api_fail
cborError :: Text -> CBOR.Decoder s a
cborError = toCborError . Left
-- | Convert an 'Either'-encoded failure to a 'TH' Q-monad failure. The
return monad is intentionally specialized because we avoid ' MonadFail ' .
toTemplateHaskellError :: Either Text ~> TH.Q
toTemplateHaskellError = external_api_fail
templateHaskellError :: Text -> TH.Q a
templateHaskellError = toTemplateHaskellError . Left
-- | Convert an 'Either'-encoded failure to a 'cereal' failure. The
return monad is intentionally specialized because we avoid ' MonadFail ' .
toCerealError :: Either Text ~> Cereal.Get
toCerealError = external_api_fail
cerealError :: Text -> Cereal.Get a
cerealError = toCerealError . Left
-- | Convert an 'Either'-encoded failure to a 'megaparsec' failure. The
return monad is intentionally specialized because we avoid ' MonadFail ' .
toParsecError :: P.Stream s => Either Text ~> P.ParsecT e s m
toParsecError = external_api_fail
parsecError :: P.Stream s => Text -> P.ParsecT e s m a
parsecError = toParsecError . Left
----------------------------------------------------------------------------
-- Ether
----------------------------------------------------------------------------
-- | Make a Reader or State computation work in an Ether transformer. Useful
-- to make lenses work with Ether.
ether :: trans m a -> Ether.TaggedTrans tag trans m a
ether = Ether.TaggedTrans
-- | Convenient shortcut for 'HasLens' constraint when lens is to the
-- same type as the tag.
type HasLens' s a = HasLens a s a
-- | Version of 'lensOf' which is used when lens is to the same type
-- as the tag.
lensOf' :: forall a s. HasLens' s a => Lens' s a
lensOf' = lensOf @a
-- | Version of 'lensOf' which uses proxy.
lensOfProxy :: forall proxy tag a b. HasLens tag a b => proxy tag -> Lens' a b
lensOfProxy _ = lensOf @tag
----------------------------------------------------------------------------
-- PowerLift
----------------------------------------------------------------------------
class PowerLift m n where
powerLift :: m a -> n a
instance {-# OVERLAPPING #-} PowerLift m m where
powerLift = identity
instance (MonadTrans t, PowerLift m n, Monad n) => PowerLift m (t n) where
powerLift = lift . powerLift @m @n
----------------------------------------------------------------------------
MinMax
----------------------------------------------------------------------------
newtype MinMax a = MinMax (Smg.Option (Smg.Min a, Smg.Max a))
deriving (Monoid)
_MinMax :: Iso' (MinMax a) (Maybe (a, a))
_MinMax = coerced
mkMinMax :: a -> MinMax a
mkMinMax a = _MinMax # Just (a, a)
minMaxOf :: Getting (MinMax a) s a -> s -> Maybe (a, a)
minMaxOf l = view _MinMax . foldMapOf l mkMinMax
----------------------------------------------------------------------------
-- Aeson
----------------------------------------------------------------------------
-- | Parse a value represented as a 'show'-ed string in JSON.
parseJSONWithRead :: Read a => A.Value -> A.Parser a
parseJSONWithRead =
toAesonError . readEither @String <=<
parseJSON
----------------------------------------------------------------------------
NonEmpty
----------------------------------------------------------------------------
neZipWith3 :: (x -> y -> z -> q) -> NonEmpty x -> NonEmpty y -> NonEmpty z -> NonEmpty q
neZipWith3 f (x :| xs) (y :| ys) (z :| zs) = f x y z :| zipWith3 f xs ys zs
neZipWith4 ::
(x -> y -> i -> z -> q)
-> NonEmpty x
-> NonEmpty y
-> NonEmpty i
-> NonEmpty z
-> NonEmpty q
neZipWith4 f (x :| xs) (y :| ys) (i :| is) (z :| zs) = f x y i z :| zipWith4 f xs ys is zs
-- | Makes a span on the list, considering tail only. Predicate has
list head as first argument . Used to take non - null prefix that
depends on the first element .
spanSafe :: (a -> a -> Bool) -> NonEmpty a -> (NonEmpty a, [a])
spanSafe p (x:|xs) = let (a,b) = span (p x) xs in (x:|a,b)
-- | Takes last N elements of the list
takeLastNE :: Int -> NonEmpty a -> [a]
takeLastNE n = reverse . NE.take n . NE.reverse
----------------------------------------------------------------------------
-- Logging helpers
----------------------------------------------------------------------------
| Formats two values as first and last elements of a list
buildListBounds :: Buildable a => F.Format r (NonEmpty a -> r)
buildListBounds = F.later formatList
where
formatList (x:|[]) = F.bprint ("[" F.% F.build F.% "]") x
formatList xs = F.bprint ("[" F.% F.build F.% ".." F.% F.build F.% "]")
(NE.head xs)
(NE.last xs)
-- | Formats only start and the end of the list according to the maximum size
multilineBounds :: Buildable a => Int -> F.Format r (NonEmpty a -> r)
multilineBounds maxSize = F.later formatList
where
formatList xs = if length xs <= maxSize'
then F.bprint listJson xs
else F.bprint
("First " F.% F.int F.% ": " F.% listJson F.% "\nLast " F.% F.int F.% ": " F.% listJson)
half
(NE.take half xs)
remaining
(takeLastNE remaining xs)
splitting list into two with maximum size below 2 does n't make sense
half = maxSize' `div` 2
remaining = maxSize' - half
-- | Catch and log an exception, then rethrow it
logException :: LoggerName -> IO a -> IO a
logException name = E.handleAsync (\e -> handler e >> E.throw e)
where
handler :: E.SomeException -> IO ()
handler exc = do
let message = "logException: " <> pretty exc
usingLoggerName name (logError message) `E.catchAny` \loggingExc -> do
putStrLn message
putStrLn $
"logException failed to use logging: " <> pretty loggingExc
-- | 'bracket' which logs given message after acquiring the resource
-- and before calling the callback with 'Info' severity.
bracketWithLogging ::
(MonadMask m, WithLogger m)
=> Text
-> m a
-> (a -> m b)
-> (a -> m c)
-> m c
bracketWithLogging msg acquire release = bracket acquire release . addLogging
where
addLogging callback resource = do
logInfo $ "<bracketWithLogging:before> " <> msg
callback resource <*
logInfo ("<bracketWithLogging:after> " <> msg)
----------------------------------------------------------------------------
-- Misc
----------------------------------------------------------------------------
| Specialized version of ' mconcat ' ( or ' Data.Foldable.fold ' )
-- for restricting type to list of pairs.
mconcatPair :: (Monoid a, Monoid b) => [(a, b)] -> (a, b)
mconcatPair = mconcat
microsecondsToUTC :: Microsecond -> UTCTime
microsecondsToUTC = posixSecondsToUTCTime . fromRational . (% 1000000) . toMicroseconds
data Sign = Plus | Minus
| Create HashSet from HashMap 's keys
getKeys :: HashMap k v -> HashSet k
getKeys = fromMap . void
-- | Use some monadic action to evaluate priority of value and sort a
-- list of values based on this priority. The order is descending
-- because I need it.
sortWithMDesc :: (Monad m, Ord b) => (a -> m b) -> [a] -> m [a]
sortWithMDesc f = fmap (map fst . sortWith (Down . snd)) . mapM f'
where
f' x = (x, ) <$> f x
| Concatenates two url parts using regular slash ' / ' .
-- E.g. @"./dir/" <//> "/file" = "./dir/file"@.
(<//>) :: String -> String -> String
(<//>) lhs rhs = lhs' ++ "/" ++ rhs'
where
isSlash = (== '/')
lhs' = reverse $ dropWhile isSlash $ reverse lhs
rhs' = dropWhile isSlash rhs
-- | To be used with paging of any kind.
The pages should contain N elements ( we use 10 by default ):
-- - 1 - 10
-- - 11 - 20
-- - 21 - 30
divRoundUp :: Integral a => a -> a -> a
divRoundUp a b = (a + b - 1) `div` b
| Print splices generated by a TH splice ( the printing will happen during
compilation , as a GHC warning ) . Useful for debugging .
--
-- For instance, you can dump splices generated with 'makeLenses' by
-- replacing a top-level invocation of 'makeLenses' in your code with:
--
-- @dumpSplices $ makeLenses ''Foo@
--
dumpSplices :: TH.DecsQ -> TH.DecsQ
dumpSplices x = do
ds <- x
let code = Prelude.lines (TH.pprint ds)
TH.reportWarning ("\n" ++ Prelude.unlines (map (" " ++) code))
return ds
-- | Count elements in a list.
histogram :: forall a. Ord a => [a] -> Map a Int
histogram = foldl' step M.empty
where
step :: Map a Int -> a -> Map a Int
step m x = M.insertWith (+) x 1 m
median :: Ord a => NonEmpty a -> a
median l = NE.sort l NE.!! middle
where
len = NE.length l
middle = (len - 1) `div` 2
| Sleep for the given duration
A numeric literal argument is interpreted as seconds . In other words ,
@(sleep 2.0)@ will sleep for two seconds .
Taken from , BSD3 licence .
A numeric literal argument is interpreted as seconds. In other words,
@(sleep 2.0)@ will sleep for two seconds.
Taken from , BSD3 licence.
-}
sleep :: MonadIO m => NominalDiffTime -> m ()
sleep n = liftIO (threadDelay (truncate (n * 10^(6::Int))))
| null | https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/util/Pos/Util/Util.hs | haskell | # LANGUAGE RankNTypes #
* Exceptions/errors
* Ether
* Lifting monads
* Logging helpers
* Misc
--------------------------------------------------------------------------
Exceptions/errors
--------------------------------------------------------------------------
| Throw exception or return result depending on what is stored in 'Either'
| Partial function which calls 'error' with meaningful message if
given 'Left' and returns some value if given 'Right'.
Intended usage is when you're sure that value must be right.
forced on us by external APIs. I also used underscores in its name, so don't
you think about exporting it -- define a specialized helper instead.
| Convert an 'Either'-encoded failure to an 'aeson' parser failure. The
| Convert an 'Either'-encoded failure to a 'cborg' decoder failure. The
| Convert an 'Either'-encoded failure to a 'TH' Q-monad failure. The
| Convert an 'Either'-encoded failure to a 'cereal' failure. The
| Convert an 'Either'-encoded failure to a 'megaparsec' failure. The
--------------------------------------------------------------------------
Ether
--------------------------------------------------------------------------
| Make a Reader or State computation work in an Ether transformer. Useful
to make lenses work with Ether.
| Convenient shortcut for 'HasLens' constraint when lens is to the
same type as the tag.
| Version of 'lensOf' which is used when lens is to the same type
as the tag.
| Version of 'lensOf' which uses proxy.
--------------------------------------------------------------------------
PowerLift
--------------------------------------------------------------------------
# OVERLAPPING #
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--------------------------------------------------------------------------
Aeson
--------------------------------------------------------------------------
| Parse a value represented as a 'show'-ed string in JSON.
--------------------------------------------------------------------------
--------------------------------------------------------------------------
| Makes a span on the list, considering tail only. Predicate has
| Takes last N elements of the list
--------------------------------------------------------------------------
Logging helpers
--------------------------------------------------------------------------
| Formats only start and the end of the list according to the maximum size
| Catch and log an exception, then rethrow it
| 'bracket' which logs given message after acquiring the resource
and before calling the callback with 'Info' severity.
--------------------------------------------------------------------------
Misc
--------------------------------------------------------------------------
for restricting type to list of pairs.
| Use some monadic action to evaluate priority of value and sort a
list of values based on this priority. The order is descending
because I need it.
E.g. @"./dir/" <//> "/file" = "./dir/file"@.
| To be used with paging of any kind.
- 1 - 10
- 11 - 20
- 21 - 30
For instance, you can dump splices generated with 'makeLenses' by
replacing a top-level invocation of 'makeLenses' in your code with:
@dumpSplices $ makeLenses ''Foo@
| Count elements in a list. | # LANGUAGE PolyKinds #
# LANGUAGE TypeOperators #
module Pos.Util.Util
(
maybeThrow
, eitherToThrow
, leftToPanic
, toAesonError
, aesonError
, toCborError
, cborError
, toTemplateHaskellError
, templateHaskellError
, toParsecError
, parsecError
, toCerealError
, cerealError
, ether
, Ether.TaggedTrans
, HasLens(..)
, HasLens'
, lensOf'
, lensOfProxy
, PowerLift(..)
*
, MinMax(..)
, _MinMax
, mkMinMax
, minMaxOf
*
, parseJSONWithRead
* NonEmpty
, neZipWith3
, neZipWith4
, spanSafe
, takeLastNE
, buildListBounds
, multilineBounds
, logException
, bracketWithLogging
, mconcatPair
, microsecondsToUTC
, Sign (..)
, getKeys
, sortWithMDesc
, dumpSplices
, histogram
, median
, (<//>)
, divRoundUp
, sleep
) where
import Universum
import qualified Codec.CBOR.Decoding as CBOR
import Control.Concurrent (threadDelay)
import qualified Control.Exception.Safe as E
import Control.Lens (Getting, Iso', coerced, foldMapOf, ( # ))
import Control.Monad.Trans.Class (MonadTrans)
import Data.Aeson (FromJSON (..))
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as A
import Data.HashSet (fromMap)
import Data.List (span, zipWith3, zipWith4)
import qualified Data.List.NonEmpty as NE
import qualified Data.Map as M
import Data.Ratio ((%))
import qualified Data.Semigroup as Smg
import qualified Data.Serialize as Cereal
import Data.Time.Clock (NominalDiffTime, UTCTime)
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
import Data.Time.Units (Microsecond, toMicroseconds)
import qualified Ether
import Ether.Internal (HasLens (..))
import qualified Formatting as F
import qualified Language.Haskell.TH as TH
import qualified Prelude
import Serokell.Util (listJson)
import Serokell.Util.Exceptions ()
import System.Wlog (LoggerName, WithLogger, logError, logInfo, usingLoggerName)
import qualified Text.Megaparsec as P
maybeThrow :: (MonadThrow m, Exception e) => e -> Maybe a -> m a
maybeThrow e = maybe (throwM e) pure
eitherToThrow
:: (MonadThrow m, Exception e)
=> Either e a -> m a
eitherToThrow = either throwM pure
leftToPanic :: Buildable a => Text -> Either a b -> b
leftToPanic msgPrefix = either (error . mappend msgPrefix . pretty) identity
type f ~> g = forall x. f x -> g x
| This unexported helper is used to define conversions to ' MonadFail '
This must be the only place in our codebase where we allow ' MonadFail ' .
external_api_fail :: MonadFail m => Either Text ~> m
external_api_fail = either (fail . toString) return
return monad is intentionally specialized because we avoid ' MonadFail ' .
toAesonError :: Either Text ~> A.Parser
toAesonError = external_api_fail
aesonError :: Text -> A.Parser a
aesonError = toAesonError . Left
return monad is intentionally specialized because we avoid ' MonadFail ' .
toCborError :: Either Text ~> CBOR.Decoder s
toCborError = external_api_fail
cborError :: Text -> CBOR.Decoder s a
cborError = toCborError . Left
return monad is intentionally specialized because we avoid ' MonadFail ' .
toTemplateHaskellError :: Either Text ~> TH.Q
toTemplateHaskellError = external_api_fail
templateHaskellError :: Text -> TH.Q a
templateHaskellError = toTemplateHaskellError . Left
return monad is intentionally specialized because we avoid ' MonadFail ' .
toCerealError :: Either Text ~> Cereal.Get
toCerealError = external_api_fail
cerealError :: Text -> Cereal.Get a
cerealError = toCerealError . Left
return monad is intentionally specialized because we avoid ' MonadFail ' .
toParsecError :: P.Stream s => Either Text ~> P.ParsecT e s m
toParsecError = external_api_fail
parsecError :: P.Stream s => Text -> P.ParsecT e s m a
parsecError = toParsecError . Left
ether :: trans m a -> Ether.TaggedTrans tag trans m a
ether = Ether.TaggedTrans
type HasLens' s a = HasLens a s a
lensOf' :: forall a s. HasLens' s a => Lens' s a
lensOf' = lensOf @a
lensOfProxy :: forall proxy tag a b. HasLens tag a b => proxy tag -> Lens' a b
lensOfProxy _ = lensOf @tag
class PowerLift m n where
powerLift :: m a -> n a
powerLift = identity
instance (MonadTrans t, PowerLift m n, Monad n) => PowerLift m (t n) where
powerLift = lift . powerLift @m @n
MinMax
newtype MinMax a = MinMax (Smg.Option (Smg.Min a, Smg.Max a))
deriving (Monoid)
_MinMax :: Iso' (MinMax a) (Maybe (a, a))
_MinMax = coerced
mkMinMax :: a -> MinMax a
mkMinMax a = _MinMax # Just (a, a)
minMaxOf :: Getting (MinMax a) s a -> s -> Maybe (a, a)
minMaxOf l = view _MinMax . foldMapOf l mkMinMax
parseJSONWithRead :: Read a => A.Value -> A.Parser a
parseJSONWithRead =
toAesonError . readEither @String <=<
parseJSON
NonEmpty
neZipWith3 :: (x -> y -> z -> q) -> NonEmpty x -> NonEmpty y -> NonEmpty z -> NonEmpty q
neZipWith3 f (x :| xs) (y :| ys) (z :| zs) = f x y z :| zipWith3 f xs ys zs
neZipWith4 ::
(x -> y -> i -> z -> q)
-> NonEmpty x
-> NonEmpty y
-> NonEmpty i
-> NonEmpty z
-> NonEmpty q
neZipWith4 f (x :| xs) (y :| ys) (i :| is) (z :| zs) = f x y i z :| zipWith4 f xs ys is zs
list head as first argument . Used to take non - null prefix that
depends on the first element .
spanSafe :: (a -> a -> Bool) -> NonEmpty a -> (NonEmpty a, [a])
spanSafe p (x:|xs) = let (a,b) = span (p x) xs in (x:|a,b)
takeLastNE :: Int -> NonEmpty a -> [a]
takeLastNE n = reverse . NE.take n . NE.reverse
| Formats two values as first and last elements of a list
buildListBounds :: Buildable a => F.Format r (NonEmpty a -> r)
buildListBounds = F.later formatList
where
formatList (x:|[]) = F.bprint ("[" F.% F.build F.% "]") x
formatList xs = F.bprint ("[" F.% F.build F.% ".." F.% F.build F.% "]")
(NE.head xs)
(NE.last xs)
multilineBounds :: Buildable a => Int -> F.Format r (NonEmpty a -> r)
multilineBounds maxSize = F.later formatList
where
formatList xs = if length xs <= maxSize'
then F.bprint listJson xs
else F.bprint
("First " F.% F.int F.% ": " F.% listJson F.% "\nLast " F.% F.int F.% ": " F.% listJson)
half
(NE.take half xs)
remaining
(takeLastNE remaining xs)
splitting list into two with maximum size below 2 does n't make sense
half = maxSize' `div` 2
remaining = maxSize' - half
logException :: LoggerName -> IO a -> IO a
logException name = E.handleAsync (\e -> handler e >> E.throw e)
where
handler :: E.SomeException -> IO ()
handler exc = do
let message = "logException: " <> pretty exc
usingLoggerName name (logError message) `E.catchAny` \loggingExc -> do
putStrLn message
putStrLn $
"logException failed to use logging: " <> pretty loggingExc
bracketWithLogging ::
(MonadMask m, WithLogger m)
=> Text
-> m a
-> (a -> m b)
-> (a -> m c)
-> m c
bracketWithLogging msg acquire release = bracket acquire release . addLogging
where
addLogging callback resource = do
logInfo $ "<bracketWithLogging:before> " <> msg
callback resource <*
logInfo ("<bracketWithLogging:after> " <> msg)
| Specialized version of ' mconcat ' ( or ' Data.Foldable.fold ' )
mconcatPair :: (Monoid a, Monoid b) => [(a, b)] -> (a, b)
mconcatPair = mconcat
microsecondsToUTC :: Microsecond -> UTCTime
microsecondsToUTC = posixSecondsToUTCTime . fromRational . (% 1000000) . toMicroseconds
data Sign = Plus | Minus
| Create HashSet from HashMap 's keys
getKeys :: HashMap k v -> HashSet k
getKeys = fromMap . void
sortWithMDesc :: (Monad m, Ord b) => (a -> m b) -> [a] -> m [a]
sortWithMDesc f = fmap (map fst . sortWith (Down . snd)) . mapM f'
where
f' x = (x, ) <$> f x
| Concatenates two url parts using regular slash ' / ' .
(<//>) :: String -> String -> String
(<//>) lhs rhs = lhs' ++ "/" ++ rhs'
where
isSlash = (== '/')
lhs' = reverse $ dropWhile isSlash $ reverse lhs
rhs' = dropWhile isSlash rhs
The pages should contain N elements ( we use 10 by default ):
divRoundUp :: Integral a => a -> a -> a
divRoundUp a b = (a + b - 1) `div` b
| Print splices generated by a TH splice ( the printing will happen during
compilation , as a GHC warning ) . Useful for debugging .
dumpSplices :: TH.DecsQ -> TH.DecsQ
dumpSplices x = do
ds <- x
let code = Prelude.lines (TH.pprint ds)
TH.reportWarning ("\n" ++ Prelude.unlines (map (" " ++) code))
return ds
histogram :: forall a. Ord a => [a] -> Map a Int
histogram = foldl' step M.empty
where
step :: Map a Int -> a -> Map a Int
step m x = M.insertWith (+) x 1 m
median :: Ord a => NonEmpty a -> a
median l = NE.sort l NE.!! middle
where
len = NE.length l
middle = (len - 1) `div` 2
| Sleep for the given duration
A numeric literal argument is interpreted as seconds . In other words ,
@(sleep 2.0)@ will sleep for two seconds .
Taken from , BSD3 licence .
A numeric literal argument is interpreted as seconds. In other words,
@(sleep 2.0)@ will sleep for two seconds.
Taken from , BSD3 licence.
-}
sleep :: MonadIO m => NominalDiffTime -> m ()
sleep n = liftIO (threadDelay (truncate (n * 10^(6::Int))))
|
b4101e3ff46bd1a300db6c922a0fd228d213a1da648daa8e19d9494801e96649 | ramsdell/ocaml-datalog | datalog.ml | An implementation of Datalog .
Copyright ( C ) 2005 The MITRE Corporation
This library is free software ; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation ; either
version 2 of the License , or ( at your option ) any later version .
This library is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public
License along with this library ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
Copyright (C) 2005 The MITRE Corporation
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
(* The inference engine uses tabled logic programming to ensure that
all queries terminate. *)
(* See the interface for comments *)
module type DatalogType = Hashtbl.HashedType
(* See the interface for comments *)
module type T =
sig
type value
type term
val mkvar : string -> term
val mkval : value -> term
val spreadterm : (string -> 'a) -> (value -> 'a) -> term -> 'a
type literal
val mkliteral : string -> term list -> literal
val getpred : literal -> string
val getterms : literal -> term list
type clause
val mkclause : literal -> literal list -> clause
val gethead : clause -> literal
val getbody : clause -> literal list
type primitive = int -> value list -> value list option
val add_primitive : string -> int -> primitive -> unit
type theory
val create : int -> theory
val copy : theory -> theory
exception Unsafe_clause
val assume : theory -> clause -> unit
val retract : theory -> clause -> unit
val prove : theory -> literal -> literal list
end
module Make(D: DatalogType):
T with type value = D.t =
struct
module Stringtbl =
Weak.Make(struct
type t = string
let equal = (=)
let hash = Hashtbl.hash
end)
(* table used to intern varibles and predicate names *)
let stringtbl = Stringtbl.create 101
let intern string =
Stringtbl.merge stringtbl string
let same = intern "="
type value = D.t
type variable = string
type term =
Var of variable
| Val of value
let eqv (v: variable) (v': variable) = v == v'
let eqt (t: term) (t': term) =
match t, t' with
Var v, Var v' -> eqv v v'
| Val v, Val v' -> D.equal v v'
| _ -> false
let mkvar id = Var (intern id)
let mkval v = Val v
let spreadterm getvar getval term =
match term with
Var v -> getvar v
| Val v -> getval v
(* variables *)
let id = ref 0
(* generates fresh variables *)
(* assumes normal variables are not numbers *)
let fresh () =
let n = !id in
id := n + 1;
Var (string_of_int n) (* don't intern fresh vars *)
(* enviroments *)
let extend env var term =
(var, term) :: env
let rec lookup env var =
match env with
[] -> None
| (var', term) :: env ->
if eqv var var' then
Some term
else
lookup env var
(* literals *)
type predicate = string
type literal = predicate * term list
let eqp (p: predicate) (p': predicate) = p == p'
let hash_pred (p: predicate) = Hashtbl.hash p
let mkliteral pred terms = intern pred, terms
let getpred (pred, _) = pred
let getterms (_, terms) = terms
(* variant checking between literals *)
Two literals are variants of each other if there is a one - to - one
mapping of variables such that the substitions defined by the map
transform one literal into the other .
mapping of variables such that the substitions defined by the map
transform one literal into the other. *)
(* This routine constructs a map and its inverse to ensure the map is
one-to-one. *)
let rec variant_terms env env' terms terms' =
match terms, terms' with
[], [] -> true
| term :: terms, term' :: terms' ->
variant_term env env' term term' terms terms'
| _, _ -> false
and variant_term env env' term term' terms terms' =
match term, term' with
Var var, Var var' ->
variant_var env env' var var' terms terms'
| _, _ ->
eqt term term' && variant_terms env env' terms terms'
and variant_var env env' var var' terms terms' =
match lookup env var, lookup env' var' with
None, None ->
let env = extend env var (Var var') in
let env' = extend env' var' (Var var) in
variant_terms env env' terms terms'
| Some (Var v), Some (Var v') ->
eqv v var' && eqv v' var && variant_terms env env' terms terms'
| _, _ -> false
let variant (pred, terms) (pred', terms') =
if not (eqp pred pred') then
false
else
variant_terms [] [] terms terms'
(* A hash function for literals that respects variants *)
(* A variable is always hashed to the same number to ensure that the
hash function respects variants *)
let hash_term term =
match term with
Var _ -> 101
| Val value -> D.hash value
let hash_literal (pred, terms) =
let rec loop code i terms =
match terms with
[] -> code
| term :: terms ->
let code = code + (hash_term term) - i * 7 in
loop code (i + 1) terms in
loop (hash_pred pred) 0 terms
(* Literal tables -- tables with literals as keys, where literals are
considered the same if one is a variant of the other. *)
module Literaltbl =
Hashtbl.Make(struct
type t = literal
let equal = (variant : literal -> literal -> bool)
let hash = (hash_literal : literal -> int)
end)
(* substitution *)
(* substitute a value for variable in a term if it is bound in the
environment *)
let subst_term env term =
match term with
Var var ->
(match lookup env var with
None -> term
| Some term' -> term')
| _ -> term
(* substitute values for variables in a literal *)
let subst_literal env (pred, terms) =
(pred, List.map (subst_term env) terms)
(* rename variables in a literal *)
let shuffle env (_, terms) =
let rec loop env terms =
match terms with
[] -> env
| Val _ :: terms -> loop env terms
| Var var :: terms ->
match lookup env var with
None -> loop (extend env var (fresh())) terms
| Some _ -> loop env terms in
loop env terms
let rename_literal literal =
subst_literal (shuffle [] literal) literal
(* unification *)
let rec chase env term =
match term with
Var var ->
(match lookup env var with
None -> Var var
| Some term -> chase env term)
| term -> term
let unify_term env term term' =
let term = chase env term in
let term' = chase env term' in
if eqt term term' then
Some env
else
match term with
Var var -> Some (extend env var term')
| _ ->
match term' with
Var var -> Some (extend env var term)
| _ -> None
let rec unify_terms env terms terms' =
match terms, terms' with
[], [] -> Some env
| term::terms, term'::terms' ->
(match unify_term env term term' with
None -> None
| Some env -> unify_terms env terms terms')
| _ -> None
let unify (pred, terms) (pred', terms') =
if not (eqp pred pred') then
None
else
unify_terms [] terms terms'
(* clauses *)
type clause = literal * literal list
let mkclause head body = head, body
let gethead (head, _) = head
let getbody (_, body) = body
(* A clause is safe if every variable in the head is also in the body. *)
let rec safe_var var body =
match body with
[] -> false
| (_, terms) :: body ->
List.mem (Var var) terms || safe_var var body
let safe_term term body =
match term with
Var var -> safe_var var body
| _ -> true
let safe ((_, terms), body) =
let rec loop terms =
match terms with
[] -> true
| term :: terms ->
safe_term term body && loop terms in
loop terms
(* rename variables in a clause *)
let subst_clause env (literal, literals) =
(subst_literal env literal, List.map (subst_literal env) literals)
let rename_clause (literal, literals) =
let env = List.fold_left shuffle (shuffle [] literal) literals in
subst_clause env (literal, literals)
(* primitives *)
type primitive = int -> value list -> value list option
let prims = Hashtbl.create 7
let add_primitive symbol in_arity prim =
let symbol = intern symbol in
if in_arity < 0 then
failwith "bad arity in add_primitive"
else
Hashtbl.replace prims symbol (symbol, in_arity, prim)
(* theory *)
(* A theory is implemented as a hash table. *)
type theory = (string, clause list) Hashtbl.t
let create = Hashtbl.create ~random:false
let copy = Hashtbl.copy
let literal_key (pred, terms) =
pred ^ "/" ^ string_of_int (List.length terms)
let clause_key (literal, _) =
literal_key literal
let get_with_key tbl key =
try Hashtbl.find tbl key with Not_found -> []
let get tbl literal =
get_with_key tbl (literal_key literal)
exception Unsafe_clause
let assume tbl clause =
if not (safe clause) then
raise Unsafe_clause;
let key = clause_key clause in
let clauses = get_with_key tbl key in
if not (List.mem clause clauses) then
Hashtbl.replace tbl key (clause :: clauses)
let retract tbl clause =
let key = clause_key clause in
let pred c = c <> clause in
let clauses = List.filter pred (get_with_key tbl key) in
match clauses with
[] -> Hashtbl.remove tbl key
| _ :: _ -> Hashtbl.replace tbl key clauses
(* prover *)
The remaining functions in this file implement the tabled logic
programming algorithm described in " Efficient Top - Down Computation of
Queries under the Well - Founded Semantics " , , , T. , and
, , J. Logic Prog . Vol . 24 , No . 3 , pp . 161 - 199 . Another
important reference is " Tabled Evaluation with Delaying for General
Logic Programs " , , , and , , , Vol . 43 , No . 1 ,
Jan. 1996 , pp . 20 - 74 .
programming algorithm described in "Efficient Top-Down Computation of
Queries under the Well-Founded Semantics", Chen, W., Swift, T., and
Warren, D. S., J. Logic Prog. Vol. 24, No. 3, pp. 161-199. Another
important reference is "Tabled Evaluation with Delaying for General
Logic Programs", Chen, W., and Warren, D. S., J. ACM, Vol. 43, No. 1,
Jan. 1996, pp. 20-74. *)
A subgoal is the item that is tabled by this algorithm .
type subgoal =
the subgoal
mutable facts: literal list; (* derived facts *)
seen: unit Literaltbl.t; (* hashed facts for quick lookup *)
mutable waiters: waiter list } (* waiters of this subgoals *)
and waiter =
subgoal of clause waiting
* clause (* clause awaiting result *)
let init_seen_table_size = 13
(* resolve a clause with a literal *)
let resolve (head, body) literal =
match body with
[] -> None
| selected :: body ->
let renamed = rename_literal literal in
match unify selected renamed with
None -> None
| Some env ->
Some (subst_clause env (head, body))
let prove theory literal =
let subgoals = Literaltbl.create 128 in (* table of subgoals *)
let rec fact subgoal literal = (* handle a derived fact *)
if not (Literaltbl.mem subgoal.seen literal) then begin
subgoal.facts <- literal :: subgoal.facts; (* record fact *)
Literaltbl.add subgoal.seen literal ();
let use_fact (sg, cs) =
match resolve cs literal with
None -> ()
| Some cs' -> add_clause sg cs' in (* tell waiters *)
List.iter use_fact subgoal.waiters (* about new fact *)
end
and rule subgoal clause selected = (* handle a derived rule *)
try
let sg = Literaltbl.find subgoals selected in
sg.waiters <- (subgoal, clause) :: sg.waiters; (* add to waiters *)
let use_clause fact = (* so told about new facts *)
match resolve clause fact with
None -> ()
| Some cs -> add_clause subgoal cs in (* tell waiters about *)
List.iter use_clause sg.facts (* current facts *)
with Not_found ->
let sg = {
create new subgoal
facts = [];
seen = Literaltbl.create init_seen_table_size;
waiters = [subgoal, clause]; (* to prove clause *)
} in
Literaltbl.replace subgoals selected sg;
search sg
and add_clause subgoal clause =
match clause with
(literal, []) -> fact subgoal literal
| (_, selected :: _) -> rule subgoal clause selected
and search_theory subgoal = (* search for proofs *)
of the subgoal using
let renamed = rename_clause clause in (* relevant assumptions *)
let selected, _ = renamed in (* from the theory *)
let env = unify subgoal.literal selected in
match env with
None -> ()
| Some env ->
add_clause subgoal (subst_clause env renamed) in
List.iter search_clause (get theory subgoal.literal)
and equal_primitive subgoal a b = (* the equality predicate *)
let equal_test a b =
match a, b with (* the equal tests *)
Val x, Val y -> (* passes when both *)
if D.equal x y then (* arguments are the *)
fact subgoal (same, [a; b]) (* same constant *)
| _ -> () in
match unify_term [] a b with (* unify the arguments *)
None -> equal_test a b (* and substitute the *)
| Some env -> (* resulting environment *)
equal_test (subst_term env a) (subst_term env b)
and apply_prim subgoal symbol in_arity out_arity prim l =
let rec tag_values acc values = (* found a fact *)
match values with (* reverse list and *)
[] -> (* tag values *)
fact subgoal (symbol, acc)
| v :: values ->
tag_values (Val v :: acc) values in
let unify_results acc args results =
let results = List.map (fun v -> Val v) results in
match unify_terms [] args results with
None -> ()
| Some _ -> tag_values results acc in
let result acc args results =
match results with
None -> () (* Predicate failed *)
| Some results ->
unify_results acc args results in
let rec loop acc in_arity args =
if in_arity <= 0 then
result acc args (prim out_arity (List.rev acc))
else
match args with (* extract values from args *)
Val v :: args ->
loop (v :: acc) (in_arity - 1) args
| _ -> () in (* fail when variable is an arg *)
loop [] in_arity l
and search subgoal = (* search for proofs *)
of the subgoal by
pred, [a; b] when eqp pred same -> (* evaluating primitives *)
equal_primitive subgoal a b
| pred, l ->
try
let symbol, in_arity, prim = Hashtbl.find prims pred in
let arity = List.length l in
if arity >= in_arity then
let out_arity = arity - in_arity in (* use prim *)
apply_prim subgoal symbol in_arity out_arity prim l
with Not_found ->
search_theory subgoal in (* otherwise use theory *)
let subgoal = { (* initiate a proof *)
by creating a subgoal
facts = []; (* with no waiters *)
seen = Literaltbl.create init_seen_table_size;
waiters = [];
} in
Literaltbl.replace subgoals literal subgoal;
search subgoal; (* search for proofs and *)
subgoal.facts (* then return derived facts *)
end
| null | https://raw.githubusercontent.com/ramsdell/ocaml-datalog/058728203184a5fd54333a442b55d215a080dfaf/datalog.ml | ocaml | The inference engine uses tabled logic programming to ensure that
all queries terminate.
See the interface for comments
See the interface for comments
table used to intern varibles and predicate names
variables
generates fresh variables
assumes normal variables are not numbers
don't intern fresh vars
enviroments
literals
variant checking between literals
This routine constructs a map and its inverse to ensure the map is
one-to-one.
A hash function for literals that respects variants
A variable is always hashed to the same number to ensure that the
hash function respects variants
Literal tables -- tables with literals as keys, where literals are
considered the same if one is a variant of the other.
substitution
substitute a value for variable in a term if it is bound in the
environment
substitute values for variables in a literal
rename variables in a literal
unification
clauses
A clause is safe if every variable in the head is also in the body.
rename variables in a clause
primitives
theory
A theory is implemented as a hash table.
prover
derived facts
hashed facts for quick lookup
waiters of this subgoals
clause awaiting result
resolve a clause with a literal
table of subgoals
handle a derived fact
record fact
tell waiters
about new fact
handle a derived rule
add to waiters
so told about new facts
tell waiters about
current facts
to prove clause
search for proofs
relevant assumptions
from the theory
the equality predicate
the equal tests
passes when both
arguments are the
same constant
unify the arguments
and substitute the
resulting environment
found a fact
reverse list and
tag values
Predicate failed
extract values from args
fail when variable is an arg
search for proofs
evaluating primitives
use prim
otherwise use theory
initiate a proof
with no waiters
search for proofs and
then return derived facts | An implementation of Datalog .
Copyright ( C ) 2005 The MITRE Corporation
This library is free software ; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation ; either
version 2 of the License , or ( at your option ) any later version .
This library is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public
License along with this library ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
Copyright (C) 2005 The MITRE Corporation
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
module type DatalogType = Hashtbl.HashedType
module type T =
sig
type value
type term
val mkvar : string -> term
val mkval : value -> term
val spreadterm : (string -> 'a) -> (value -> 'a) -> term -> 'a
type literal
val mkliteral : string -> term list -> literal
val getpred : literal -> string
val getterms : literal -> term list
type clause
val mkclause : literal -> literal list -> clause
val gethead : clause -> literal
val getbody : clause -> literal list
type primitive = int -> value list -> value list option
val add_primitive : string -> int -> primitive -> unit
type theory
val create : int -> theory
val copy : theory -> theory
exception Unsafe_clause
val assume : theory -> clause -> unit
val retract : theory -> clause -> unit
val prove : theory -> literal -> literal list
end
module Make(D: DatalogType):
T with type value = D.t =
struct
module Stringtbl =
Weak.Make(struct
type t = string
let equal = (=)
let hash = Hashtbl.hash
end)
let stringtbl = Stringtbl.create 101
let intern string =
Stringtbl.merge stringtbl string
let same = intern "="
type value = D.t
type variable = string
type term =
Var of variable
| Val of value
let eqv (v: variable) (v': variable) = v == v'
let eqt (t: term) (t': term) =
match t, t' with
Var v, Var v' -> eqv v v'
| Val v, Val v' -> D.equal v v'
| _ -> false
let mkvar id = Var (intern id)
let mkval v = Val v
let spreadterm getvar getval term =
match term with
Var v -> getvar v
| Val v -> getval v
let id = ref 0
let fresh () =
let n = !id in
id := n + 1;
let extend env var term =
(var, term) :: env
let rec lookup env var =
match env with
[] -> None
| (var', term) :: env ->
if eqv var var' then
Some term
else
lookup env var
type predicate = string
type literal = predicate * term list
let eqp (p: predicate) (p': predicate) = p == p'
let hash_pred (p: predicate) = Hashtbl.hash p
let mkliteral pred terms = intern pred, terms
let getpred (pred, _) = pred
let getterms (_, terms) = terms
Two literals are variants of each other if there is a one - to - one
mapping of variables such that the substitions defined by the map
transform one literal into the other .
mapping of variables such that the substitions defined by the map
transform one literal into the other. *)
let rec variant_terms env env' terms terms' =
match terms, terms' with
[], [] -> true
| term :: terms, term' :: terms' ->
variant_term env env' term term' terms terms'
| _, _ -> false
and variant_term env env' term term' terms terms' =
match term, term' with
Var var, Var var' ->
variant_var env env' var var' terms terms'
| _, _ ->
eqt term term' && variant_terms env env' terms terms'
and variant_var env env' var var' terms terms' =
match lookup env var, lookup env' var' with
None, None ->
let env = extend env var (Var var') in
let env' = extend env' var' (Var var) in
variant_terms env env' terms terms'
| Some (Var v), Some (Var v') ->
eqv v var' && eqv v' var && variant_terms env env' terms terms'
| _, _ -> false
let variant (pred, terms) (pred', terms') =
if not (eqp pred pred') then
false
else
variant_terms [] [] terms terms'
let hash_term term =
match term with
Var _ -> 101
| Val value -> D.hash value
let hash_literal (pred, terms) =
let rec loop code i terms =
match terms with
[] -> code
| term :: terms ->
let code = code + (hash_term term) - i * 7 in
loop code (i + 1) terms in
loop (hash_pred pred) 0 terms
module Literaltbl =
Hashtbl.Make(struct
type t = literal
let equal = (variant : literal -> literal -> bool)
let hash = (hash_literal : literal -> int)
end)
let subst_term env term =
match term with
Var var ->
(match lookup env var with
None -> term
| Some term' -> term')
| _ -> term
let subst_literal env (pred, terms) =
(pred, List.map (subst_term env) terms)
let shuffle env (_, terms) =
let rec loop env terms =
match terms with
[] -> env
| Val _ :: terms -> loop env terms
| Var var :: terms ->
match lookup env var with
None -> loop (extend env var (fresh())) terms
| Some _ -> loop env terms in
loop env terms
let rename_literal literal =
subst_literal (shuffle [] literal) literal
let rec chase env term =
match term with
Var var ->
(match lookup env var with
None -> Var var
| Some term -> chase env term)
| term -> term
let unify_term env term term' =
let term = chase env term in
let term' = chase env term' in
if eqt term term' then
Some env
else
match term with
Var var -> Some (extend env var term')
| _ ->
match term' with
Var var -> Some (extend env var term)
| _ -> None
let rec unify_terms env terms terms' =
match terms, terms' with
[], [] -> Some env
| term::terms, term'::terms' ->
(match unify_term env term term' with
None -> None
| Some env -> unify_terms env terms terms')
| _ -> None
let unify (pred, terms) (pred', terms') =
if not (eqp pred pred') then
None
else
unify_terms [] terms terms'
type clause = literal * literal list
let mkclause head body = head, body
let gethead (head, _) = head
let getbody (_, body) = body
let rec safe_var var body =
match body with
[] -> false
| (_, terms) :: body ->
List.mem (Var var) terms || safe_var var body
let safe_term term body =
match term with
Var var -> safe_var var body
| _ -> true
let safe ((_, terms), body) =
let rec loop terms =
match terms with
[] -> true
| term :: terms ->
safe_term term body && loop terms in
loop terms
let subst_clause env (literal, literals) =
(subst_literal env literal, List.map (subst_literal env) literals)
let rename_clause (literal, literals) =
let env = List.fold_left shuffle (shuffle [] literal) literals in
subst_clause env (literal, literals)
type primitive = int -> value list -> value list option
let prims = Hashtbl.create 7
let add_primitive symbol in_arity prim =
let symbol = intern symbol in
if in_arity < 0 then
failwith "bad arity in add_primitive"
else
Hashtbl.replace prims symbol (symbol, in_arity, prim)
type theory = (string, clause list) Hashtbl.t
let create = Hashtbl.create ~random:false
let copy = Hashtbl.copy
let literal_key (pred, terms) =
pred ^ "/" ^ string_of_int (List.length terms)
let clause_key (literal, _) =
literal_key literal
let get_with_key tbl key =
try Hashtbl.find tbl key with Not_found -> []
let get tbl literal =
get_with_key tbl (literal_key literal)
exception Unsafe_clause
let assume tbl clause =
if not (safe clause) then
raise Unsafe_clause;
let key = clause_key clause in
let clauses = get_with_key tbl key in
if not (List.mem clause clauses) then
Hashtbl.replace tbl key (clause :: clauses)
let retract tbl clause =
let key = clause_key clause in
let pred c = c <> clause in
let clauses = List.filter pred (get_with_key tbl key) in
match clauses with
[] -> Hashtbl.remove tbl key
| _ :: _ -> Hashtbl.replace tbl key clauses
The remaining functions in this file implement the tabled logic
programming algorithm described in " Efficient Top - Down Computation of
Queries under the Well - Founded Semantics " , , , T. , and
, , J. Logic Prog . Vol . 24 , No . 3 , pp . 161 - 199 . Another
important reference is " Tabled Evaluation with Delaying for General
Logic Programs " , , , and , , , Vol . 43 , No . 1 ,
Jan. 1996 , pp . 20 - 74 .
programming algorithm described in "Efficient Top-Down Computation of
Queries under the Well-Founded Semantics", Chen, W., Swift, T., and
Warren, D. S., J. Logic Prog. Vol. 24, No. 3, pp. 161-199. Another
important reference is "Tabled Evaluation with Delaying for General
Logic Programs", Chen, W., and Warren, D. S., J. ACM, Vol. 43, No. 1,
Jan. 1996, pp. 20-74. *)
A subgoal is the item that is tabled by this algorithm .
type subgoal =
the subgoal
and waiter =
subgoal of clause waiting
let init_seen_table_size = 13
let resolve (head, body) literal =
match body with
[] -> None
| selected :: body ->
let renamed = rename_literal literal in
match unify selected renamed with
None -> None
| Some env ->
Some (subst_clause env (head, body))
let prove theory literal =
if not (Literaltbl.mem subgoal.seen literal) then begin
Literaltbl.add subgoal.seen literal ();
let use_fact (sg, cs) =
match resolve cs literal with
None -> ()
end
try
let sg = Literaltbl.find subgoals selected in
match resolve clause fact with
None -> ()
with Not_found ->
let sg = {
create new subgoal
facts = [];
seen = Literaltbl.create init_seen_table_size;
} in
Literaltbl.replace subgoals selected sg;
search sg
and add_clause subgoal clause =
match clause with
(literal, []) -> fact subgoal literal
| (_, selected :: _) -> rule subgoal clause selected
of the subgoal using
let env = unify subgoal.literal selected in
match env with
None -> ()
| Some env ->
add_clause subgoal (subst_clause env renamed) in
List.iter search_clause (get theory subgoal.literal)
let equal_test a b =
| _ -> () in
equal_test (subst_term env a) (subst_term env b)
and apply_prim subgoal symbol in_arity out_arity prim l =
fact subgoal (symbol, acc)
| v :: values ->
tag_values (Val v :: acc) values in
let unify_results acc args results =
let results = List.map (fun v -> Val v) results in
match unify_terms [] args results with
None -> ()
| Some _ -> tag_values results acc in
let result acc args results =
match results with
| Some results ->
unify_results acc args results in
let rec loop acc in_arity args =
if in_arity <= 0 then
result acc args (prim out_arity (List.rev acc))
else
Val v :: args ->
loop (v :: acc) (in_arity - 1) args
loop [] in_arity l
of the subgoal by
equal_primitive subgoal a b
| pred, l ->
try
let symbol, in_arity, prim = Hashtbl.find prims pred in
let arity = List.length l in
if arity >= in_arity then
apply_prim subgoal symbol in_arity out_arity prim l
with Not_found ->
by creating a subgoal
seen = Literaltbl.create init_seen_table_size;
waiters = [];
} in
Literaltbl.replace subgoals literal subgoal;
end
|
6967f02048998ee598760c84b973b4377c85f5522ce194541a55a88f64ee1012 | Cumulus/Cumulus | feed.mli |
Copyright ( c ) 2012
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 .
Copyright (c) 2012 Enguerrand Decorne
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*)
open CalendarLib
type feed = Db_feed.feed =
{ author : int32
; id : int32
; date : CalendarLib.Calendar.t
; description : string
; url : string option
; parent: int32 option
; root : int32 option
; tags : string list
; score : int
; user : < email_digest : string; name : string >
; fav : bool
; vote : int
; count : int
; leftBound : int32
; rightBound : int32
}
type feed_generator =
starting:int32 ->
number:int32 ->
user:int32 option ->
unit ->
feed list Lwt.t
val get_edit_infos : int32 ->
(string * string option * string) Lwt.t
val delete_feed_check :
feedid:int32 ->
userid:int32 ->
unit ->
unit Lwt.t
val add_fav : int32 -> [`Ok | `NotConnected] Lwt.t
val del_fav : int32 -> [`Ok | `NotConnected] Lwt.t
val upvote : int32 -> [`Ok of (int * int) | `NoRight | `NotConnected] Lwt.t
val downvote : int32 -> [`Ok of (int * int) | `NoRight | `NotConnected] Lwt.t
val cancel_vote : int32 -> [`Ok of (int * int) | `NoRight | `NotConnected] Lwt.t
val is_author : feed:feed -> User.user option -> bool
(* TODO: Remove the following functions *)
val get_root_feeds : feed_generator
val get_feeds_with_author : string -> feed_generator
val get_feeds_with_tag : string -> feed_generator
val get_fav_with_username : string -> feed_generator
val exist : feedid:int32 -> unit -> bool Lwt.t
val is_feed_author : feedid:int32 -> userid:int32 -> unit -> bool Lwt.t
val get_feed_with_id : user:int32 option -> int32 -> feed Lwt.t
val get_tree_feeds : int32 -> feed_generator
val get_links_feeds : feed_generator
val get_comments_feeds : feed_generator
val get_feeds_of_interval :
user:int32 option ->
int32 -> int32 ->
feed list Lwt.t
| null | https://raw.githubusercontent.com/Cumulus/Cumulus/3b6de05d76c57d528e052aa382f98e40354cf581/src/base/feed.mli | ocaml | TODO: Remove the following functions |
Copyright ( c ) 2012
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 .
Copyright (c) 2012 Enguerrand Decorne
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*)
open CalendarLib
type feed = Db_feed.feed =
{ author : int32
; id : int32
; date : CalendarLib.Calendar.t
; description : string
; url : string option
; parent: int32 option
; root : int32 option
; tags : string list
; score : int
; user : < email_digest : string; name : string >
; fav : bool
; vote : int
; count : int
; leftBound : int32
; rightBound : int32
}
type feed_generator =
starting:int32 ->
number:int32 ->
user:int32 option ->
unit ->
feed list Lwt.t
val get_edit_infos : int32 ->
(string * string option * string) Lwt.t
val delete_feed_check :
feedid:int32 ->
userid:int32 ->
unit ->
unit Lwt.t
val add_fav : int32 -> [`Ok | `NotConnected] Lwt.t
val del_fav : int32 -> [`Ok | `NotConnected] Lwt.t
val upvote : int32 -> [`Ok of (int * int) | `NoRight | `NotConnected] Lwt.t
val downvote : int32 -> [`Ok of (int * int) | `NoRight | `NotConnected] Lwt.t
val cancel_vote : int32 -> [`Ok of (int * int) | `NoRight | `NotConnected] Lwt.t
val is_author : feed:feed -> User.user option -> bool
val get_root_feeds : feed_generator
val get_feeds_with_author : string -> feed_generator
val get_feeds_with_tag : string -> feed_generator
val get_fav_with_username : string -> feed_generator
val exist : feedid:int32 -> unit -> bool Lwt.t
val is_feed_author : feedid:int32 -> userid:int32 -> unit -> bool Lwt.t
val get_feed_with_id : user:int32 option -> int32 -> feed Lwt.t
val get_tree_feeds : int32 -> feed_generator
val get_links_feeds : feed_generator
val get_comments_feeds : feed_generator
val get_feeds_of_interval :
user:int32 option ->
int32 -> int32 ->
feed list Lwt.t
|
611fbc8feb9566993b6f8c03938b27a5609136705b59410b9c9b668d271b0f10 | np/ling | Layout.hs | File generated by the BNF Converter ( bnfc 2.9.4.1 ) .
# OPTIONS_GHC -fno - warn - incomplete - patterns #
# LANGUAGE LambdaCase #
# LANGUAGE PatternGuards #
{-# LANGUAGE OverloadedStrings #-}
# OPTIONS_GHC -fno - warn - unused - matches -fno - warn - unused - binds #
module Ling.Layout where
import Prelude
import Data.Maybe ( fromMaybe, listToMaybe, mapMaybe )
import qualified Data.List as List
import Ling.Lex
( Posn(..), Tok(..), Token(..), TokSymbol(..)
, prToken, tokenLineCol, tokenPos, tokenPosn
)
-- local parameters
data LayoutDelimiters
= LayoutDelimiters
{ delimSep :: TokSymbol
, delimOpen :: Maybe TokSymbol -- ^ Nothing for toplevel layout.
, delimClose :: Maybe TokSymbol -- ^ Nothing for toplevel layout.
}
layoutWords :: [(TokSymbol, LayoutDelimiters)]
layoutWords = [( TokSymbol "of" 37
, LayoutDelimiters (TokSymbol "," 5) (Just (TokSymbol "{" 45)) (Just (TokSymbol "}" 47))
)]
layoutStopWords :: [TokSymbol]
layoutStopWords = []
-- layout separators
layoutOpen, layoutClose, layoutSep :: [TokSymbol]
layoutOpen = List.nub $ mapMaybe (delimOpen . snd) layoutWords
layoutClose = List.nub $ mapMaybe (delimClose . snd) layoutWords
layoutSep = List.nub $ TokSymbol "," 5 : map (delimSep . snd) layoutWords
parenOpen, parenClose :: [TokSymbol]
parenOpen =
[ TokSymbol "(" 2
, TokSymbol "[" 21
]
parenClose =
[ TokSymbol ")" 3
, TokSymbol "]" 24
]
-- | Report an error during layout resolution.
layoutError
:: [Token] -- ^ Remaining tokens.
-> String -- ^ Error message.
-> a
layoutError ts msg
| null ts = error $ concat [ "Layout error: ", msg, "." ]
| otherwise = error $ unlines
[ concat [ "Layout error at ", tokenPos ts, ": ", msg, "." ]
, unwords $ concat
[ [ "Remaining tokens:" ]
, map prToken $ take 10 ts
, [ "..." | not $ null $ drop 10 ts ]
]
]
-- | Replace layout syntax with explicit layout tokens.
resolveLayout
:: Bool -- ^ Whether to use top-level layout.
-> [Token] -- ^ Token stream before layout resolution.
-> [Token] -- ^ Token stream after layout resolution.
resolveLayout topLayout =
res Nothing [if topLayout then Implicit topDelim Definitive 1 else Explicit]
where
topDelim :: LayoutDelimiters
topDelim = LayoutDelimiters (TokSymbol "," 5) Nothing Nothing
res :: Maybe Token -- ^ The previous token, if any.
-> [Block] -- ^ A stack of layout blocks.
-> [Token] -> [Token]
-- The stack should never be empty.
res _ [] ts = layoutError ts "layout stack empty"
-- Handling explicit blocks:
res _ st (t0 : ts)
-- We found an open brace in the input,
-- put an explicit layout block on the stack.
-- This is done even if there was no layout word,
-- to keep opening and closing braces.
| isLayoutOpen t0 || isParenOpen t0
= t0 : res (Just t0) (Explicit : st) ts
If we encounter a closing brace , exit the first explicit layout block .
| isLayoutClose t0 || isParenClose t0
, let (imps, rest) = span isImplicit st
, let st' = drop 1 rest
= if null st'
then layoutError ts $ unwords
[ "found", prToken t0, "at" , tokenPos [t0]
, "without an explicit layout block"
]
else map (closingToken ts (tokenPosn t0)) imps ++ t0 : res (Just t0) st' ts
-- Ending or confirming implicit layout blocks:
res pt (b@(Implicit delim status col) : bs) (t0 : ts)
-- Do not end top-level layout block by layout stop word.
| isStop t0, col <= 1
= t0 : res (Just t0) (b : bs) ts
-- End of implicit block by a layout stop word.
| isStop t0
-- Exit the current block and all implicit blocks
-- more indented than the current token.
, let (ebs, st') = span ((column t0 <) . indentation) bs
-- Insert block-closers after the previous token.
= map (closingToken ts (afterPrev pt)) (b : ebs) ++ t0 : res (Just t0) st' ts
-- End of an implicit layout block by dedentation.
| newLine pt t0
, column t0 < col
-- Insert a block closer after the previous token.
-- Repeat, with the current block removed from the stack.
, let c = closingToken ts (afterPrev pt) b
= c : res (Just c) bs (t0 : ts)
-- If we are on a newline, confirm the last tentative blocks.
| newLine pt t0, Tentative{} <- status
= res pt (Implicit delim Definitive col : confirm col bs) (t0 : ts)
-- Starting and processing implicit layout blocks:
res pt st (t0 : ts)
Start a new layout block if the first token is a layout word .
| Just delim@(LayoutDelimiters _ mopen _) <- isLayout t0
= maybeInsertSeparator pt t0 st $
case ts of
-- Explicit layout, just move on. The next step
-- will push an explicit layout block.
t1 : _ | isLayoutOpen t1 ->
t0 : res (Just t0) st ts
-- Otherwise, insert an open brace after the layout word
_ ->
t0 : b : res (Just b) (addImplicit delim (tokenPosn t0) pos st) ts
where
b = sToken (nextPos t0) $ fromMaybe undefined mopen
-- At the end of the file, the start column does not matter.
-- So if there is no token t1 after t0, just use the position of t0.
pos = tokenPosn $ fromMaybe t0 $ listToMaybe ts
-- Insert separator if necessary.
| otherwise
= maybeInsertSeparator pt t0 st $
t0 : res (Just t0) st ts
At EOF : skip explicit blocks .
res (Just _) [Explicit] [] = []
res (Just t) (Explicit : bs) [] = res (Just t) bs []
-- If we are using top-level layout, insert a semicolon after
-- the last token, if there isn't one already
res (Just t) [Implicit (LayoutDelimiters sep _ _) _ _] []
| isLayoutSep t = []
| otherwise = [sToken (nextPos t) sep]
At EOF in an implicit , non - top - level block : close the block
res (Just t) (Implicit (LayoutDelimiters _ _ (Just close)) _ _ : bs) []
= b : res (Just b) bs []
where b = sToken (nextPos t) close
-- This should only happen if the input is empty.
res Nothing _st []
= []
-- | Insert a 'layoutSep' if we are on a new line on the current
-- implicit layout column.
maybeInsertSeparator
:: Maybe Token -- ^ The previous token.
-> Token -- ^ The current token.
-> [Block] -- ^ The layout stack.
-> [Token] -- ^ The result token stream.
-> [Token] -- ^ Maybe prepended with a 'layoutSep'.
maybeInsertSeparator pt t0 = \case
Implicit (LayoutDelimiters sep _ _) _ n : _
| newLine pt t0
, column t0 == n
, maybe False (not . isTokenIn (layoutSep ++ layoutOpen)) pt
-- Insert a semicolon after the previous token
-- unless we are the beginning of the file,
-- or the previous token is a semicolon or open brace.
-> (sToken (afterPrev pt) sep :)
_ -> id
closingToken :: [Token] -> Position -> Block -> Token
closingToken ts pos = sToken pos . \case
Implicit (LayoutDelimiters _ _ (Just sy)) _ _ -> sy
_ -> layoutError ts "trying to close a top level block"
type Position = Posn
type Line = Int
type Column = Int
-- | Entry of the layout stack.
data Block
= Implicit LayoutDelimiters Status Column
-- ^ An implicit layout block with its start column.
| Explicit
-- | Get current indentation. 0 if we are in an explicit block.
indentation :: Block -> Column
indentation = \case
Implicit _ _ n -> n
Explicit -> 0
-- | Check if s block is implicit.
isImplicit :: Block -> Bool
isImplicit = \case
Implicit{} -> True
Explicit{} -> False
data Status
= Tentative -- ^ A layout column that has not been confirmed by a line break
| Definitive -- ^ A layout column that has been confirmed by a line break.
-- | Add a new implicit layout block.
addImplicit
^ of the new block .
-> Position -- ^ Position of the layout keyword.
^ Position of the token following the layout keword .
-> [Block]
-> [Block]
addImplicit delim (Pn _ l0 _) (Pn _ l1 c1) st
-- Case: layout keyword was at the end of the line:
-- New implicit block is definitive.
| l1 > l0 = Implicit delim Definitive (col st') : st'
-- Case: staying on the same line:
-- New implicit block is tentative.
| otherwise = Implicit delim Tentative (col st) : st
where
st' = confirm c1 st
col bs = max c1 $ 1 + definiteIndentation bs
-- The column of the next token determines the starting column
-- of the implicit layout block.
-- However, the next block needs to be strictly more indented
-- than the previous block.
-- | Get the current confirmed indentation level.
definiteIndentation :: [Block] -> Int
definiteIndentation bs =
case dropWhile isTentative bs of
Implicit _ Definitive n : _ -> n
0 enables a first unindented block , see 194_layout / good05.in
isTentative :: Block -> Bool
isTentative = \case
Implicit _ Tentative _ -> True
_ -> False
-- | Confirm tentative blocks that are not more indented than @col@.
confirm :: Column -> [Block] -> [Block]
confirm c0 = loop
where
loop = \case
Implicit delim Tentative c : bs
| c <= c0 -> Implicit delim Definitive c : loop bs
bs -> bs
-- | Get the position immediately to the right of the given token.
If no token is given , gets the first position in the file .
afterPrev :: Maybe Token -> Position
afterPrev = maybe (Pn 0 1 1) nextPos
-- | Get the position immediately to the right of the given token.
nextPos :: Token -> Position
nextPos t = Pn (g + s) l (c + s + 1)
where
Pn g l c = tokenPosn t
s = tokenLength t
-- | Get the number of characters in the token.
tokenLength :: Token -> Int
tokenLength = length . prToken
-- | Create a position symbol token.
sToken :: Position -> TokSymbol -> Token
sToken p t = PT p $ TK t
-- | Get the line number of a token.
line :: Token -> Line
line = fst . tokenLineCol
-- | Get the column number of a token.
column :: Token -> Column
column = snd . tokenLineCol
-- | Is the following token on a new line?
newLine :: Maybe Token -> Token -> Bool
newLine pt t0 = maybe True ((line t0 >) . line) pt
-- | Check if a word is a layout start token.
isLayout :: Token -> Maybe LayoutDelimiters
isLayout = \case
PT _ (TK t) -> lookup t layoutWords
_ -> Nothing
-- | Check if a token is one of the given symbols.
isTokenIn :: [TokSymbol] -> Token -> Bool
isTokenIn ts = \case
PT _ (TK t) -> t `elem` ts
_ -> False
-- | Check if a token is a layout stop token.
isStop :: Token -> Bool
isStop = isTokenIn layoutStopWords
-- | Check if a token is the layout open token.
isLayoutOpen :: Token -> Bool
isLayoutOpen = isTokenIn layoutOpen
-- | Check if a token is the layout separator token.
isLayoutSep :: Token -> Bool
isLayoutSep = isTokenIn layoutSep
-- | Check if a token is the layout close token.
isLayoutClose :: Token -> Bool
isLayoutClose = isTokenIn layoutClose
-- | Check if a token is an opening parenthesis.
isParenOpen :: Token -> Bool
isParenOpen = isTokenIn parenOpen
-- | Check if a token is a closing parenthesis.
isParenClose :: Token -> Bool
isParenClose = isTokenIn parenClose
| null | https://raw.githubusercontent.com/np/ling/5a49fb5fdaef04b56e26c3ff1cd613e2800b4c23/Ling/Layout.hs | haskell | # LANGUAGE OverloadedStrings #
local parameters
^ Nothing for toplevel layout.
^ Nothing for toplevel layout.
layout separators
| Report an error during layout resolution.
^ Remaining tokens.
^ Error message.
| Replace layout syntax with explicit layout tokens.
^ Whether to use top-level layout.
^ Token stream before layout resolution.
^ Token stream after layout resolution.
^ The previous token, if any.
^ A stack of layout blocks.
The stack should never be empty.
Handling explicit blocks:
We found an open brace in the input,
put an explicit layout block on the stack.
This is done even if there was no layout word,
to keep opening and closing braces.
Ending or confirming implicit layout blocks:
Do not end top-level layout block by layout stop word.
End of implicit block by a layout stop word.
Exit the current block and all implicit blocks
more indented than the current token.
Insert block-closers after the previous token.
End of an implicit layout block by dedentation.
Insert a block closer after the previous token.
Repeat, with the current block removed from the stack.
If we are on a newline, confirm the last tentative blocks.
Starting and processing implicit layout blocks:
Explicit layout, just move on. The next step
will push an explicit layout block.
Otherwise, insert an open brace after the layout word
At the end of the file, the start column does not matter.
So if there is no token t1 after t0, just use the position of t0.
Insert separator if necessary.
If we are using top-level layout, insert a semicolon after
the last token, if there isn't one already
This should only happen if the input is empty.
| Insert a 'layoutSep' if we are on a new line on the current
implicit layout column.
^ The previous token.
^ The current token.
^ The layout stack.
^ The result token stream.
^ Maybe prepended with a 'layoutSep'.
Insert a semicolon after the previous token
unless we are the beginning of the file,
or the previous token is a semicolon or open brace.
| Entry of the layout stack.
^ An implicit layout block with its start column.
| Get current indentation. 0 if we are in an explicit block.
| Check if s block is implicit.
^ A layout column that has not been confirmed by a line break
^ A layout column that has been confirmed by a line break.
| Add a new implicit layout block.
^ Position of the layout keyword.
Case: layout keyword was at the end of the line:
New implicit block is definitive.
Case: staying on the same line:
New implicit block is tentative.
The column of the next token determines the starting column
of the implicit layout block.
However, the next block needs to be strictly more indented
than the previous block.
| Get the current confirmed indentation level.
| Confirm tentative blocks that are not more indented than @col@.
| Get the position immediately to the right of the given token.
| Get the position immediately to the right of the given token.
| Get the number of characters in the token.
| Create a position symbol token.
| Get the line number of a token.
| Get the column number of a token.
| Is the following token on a new line?
| Check if a word is a layout start token.
| Check if a token is one of the given symbols.
| Check if a token is a layout stop token.
| Check if a token is the layout open token.
| Check if a token is the layout separator token.
| Check if a token is the layout close token.
| Check if a token is an opening parenthesis.
| Check if a token is a closing parenthesis. | File generated by the BNF Converter ( bnfc 2.9.4.1 ) .
# OPTIONS_GHC -fno - warn - incomplete - patterns #
# LANGUAGE LambdaCase #
# LANGUAGE PatternGuards #
# OPTIONS_GHC -fno - warn - unused - matches -fno - warn - unused - binds #
module Ling.Layout where
import Prelude
import Data.Maybe ( fromMaybe, listToMaybe, mapMaybe )
import qualified Data.List as List
import Ling.Lex
( Posn(..), Tok(..), Token(..), TokSymbol(..)
, prToken, tokenLineCol, tokenPos, tokenPosn
)
data LayoutDelimiters
= LayoutDelimiters
{ delimSep :: TokSymbol
}
layoutWords :: [(TokSymbol, LayoutDelimiters)]
layoutWords = [( TokSymbol "of" 37
, LayoutDelimiters (TokSymbol "," 5) (Just (TokSymbol "{" 45)) (Just (TokSymbol "}" 47))
)]
layoutStopWords :: [TokSymbol]
layoutStopWords = []
layoutOpen, layoutClose, layoutSep :: [TokSymbol]
layoutOpen = List.nub $ mapMaybe (delimOpen . snd) layoutWords
layoutClose = List.nub $ mapMaybe (delimClose . snd) layoutWords
layoutSep = List.nub $ TokSymbol "," 5 : map (delimSep . snd) layoutWords
parenOpen, parenClose :: [TokSymbol]
parenOpen =
[ TokSymbol "(" 2
, TokSymbol "[" 21
]
parenClose =
[ TokSymbol ")" 3
, TokSymbol "]" 24
]
layoutError
-> a
layoutError ts msg
| null ts = error $ concat [ "Layout error: ", msg, "." ]
| otherwise = error $ unlines
[ concat [ "Layout error at ", tokenPos ts, ": ", msg, "." ]
, unwords $ concat
[ [ "Remaining tokens:" ]
, map prToken $ take 10 ts
, [ "..." | not $ null $ drop 10 ts ]
]
]
resolveLayout
resolveLayout topLayout =
res Nothing [if topLayout then Implicit topDelim Definitive 1 else Explicit]
where
topDelim :: LayoutDelimiters
topDelim = LayoutDelimiters (TokSymbol "," 5) Nothing Nothing
-> [Token] -> [Token]
res _ [] ts = layoutError ts "layout stack empty"
res _ st (t0 : ts)
| isLayoutOpen t0 || isParenOpen t0
= t0 : res (Just t0) (Explicit : st) ts
If we encounter a closing brace , exit the first explicit layout block .
| isLayoutClose t0 || isParenClose t0
, let (imps, rest) = span isImplicit st
, let st' = drop 1 rest
= if null st'
then layoutError ts $ unwords
[ "found", prToken t0, "at" , tokenPos [t0]
, "without an explicit layout block"
]
else map (closingToken ts (tokenPosn t0)) imps ++ t0 : res (Just t0) st' ts
res pt (b@(Implicit delim status col) : bs) (t0 : ts)
| isStop t0, col <= 1
= t0 : res (Just t0) (b : bs) ts
| isStop t0
, let (ebs, st') = span ((column t0 <) . indentation) bs
= map (closingToken ts (afterPrev pt)) (b : ebs) ++ t0 : res (Just t0) st' ts
| newLine pt t0
, column t0 < col
, let c = closingToken ts (afterPrev pt) b
= c : res (Just c) bs (t0 : ts)
| newLine pt t0, Tentative{} <- status
= res pt (Implicit delim Definitive col : confirm col bs) (t0 : ts)
res pt st (t0 : ts)
Start a new layout block if the first token is a layout word .
| Just delim@(LayoutDelimiters _ mopen _) <- isLayout t0
= maybeInsertSeparator pt t0 st $
case ts of
t1 : _ | isLayoutOpen t1 ->
t0 : res (Just t0) st ts
_ ->
t0 : b : res (Just b) (addImplicit delim (tokenPosn t0) pos st) ts
where
b = sToken (nextPos t0) $ fromMaybe undefined mopen
pos = tokenPosn $ fromMaybe t0 $ listToMaybe ts
| otherwise
= maybeInsertSeparator pt t0 st $
t0 : res (Just t0) st ts
At EOF : skip explicit blocks .
res (Just _) [Explicit] [] = []
res (Just t) (Explicit : bs) [] = res (Just t) bs []
res (Just t) [Implicit (LayoutDelimiters sep _ _) _ _] []
| isLayoutSep t = []
| otherwise = [sToken (nextPos t) sep]
At EOF in an implicit , non - top - level block : close the block
res (Just t) (Implicit (LayoutDelimiters _ _ (Just close)) _ _ : bs) []
= b : res (Just b) bs []
where b = sToken (nextPos t) close
res Nothing _st []
= []
maybeInsertSeparator
maybeInsertSeparator pt t0 = \case
Implicit (LayoutDelimiters sep _ _) _ n : _
| newLine pt t0
, column t0 == n
, maybe False (not . isTokenIn (layoutSep ++ layoutOpen)) pt
-> (sToken (afterPrev pt) sep :)
_ -> id
closingToken :: [Token] -> Position -> Block -> Token
closingToken ts pos = sToken pos . \case
Implicit (LayoutDelimiters _ _ (Just sy)) _ _ -> sy
_ -> layoutError ts "trying to close a top level block"
type Position = Posn
type Line = Int
type Column = Int
data Block
= Implicit LayoutDelimiters Status Column
| Explicit
indentation :: Block -> Column
indentation = \case
Implicit _ _ n -> n
Explicit -> 0
isImplicit :: Block -> Bool
isImplicit = \case
Implicit{} -> True
Explicit{} -> False
data Status
addImplicit
^ of the new block .
^ Position of the token following the layout keword .
-> [Block]
-> [Block]
addImplicit delim (Pn _ l0 _) (Pn _ l1 c1) st
| l1 > l0 = Implicit delim Definitive (col st') : st'
| otherwise = Implicit delim Tentative (col st) : st
where
st' = confirm c1 st
col bs = max c1 $ 1 + definiteIndentation bs
definiteIndentation :: [Block] -> Int
definiteIndentation bs =
case dropWhile isTentative bs of
Implicit _ Definitive n : _ -> n
0 enables a first unindented block , see 194_layout / good05.in
isTentative :: Block -> Bool
isTentative = \case
Implicit _ Tentative _ -> True
_ -> False
confirm :: Column -> [Block] -> [Block]
confirm c0 = loop
where
loop = \case
Implicit delim Tentative c : bs
| c <= c0 -> Implicit delim Definitive c : loop bs
bs -> bs
If no token is given , gets the first position in the file .
afterPrev :: Maybe Token -> Position
afterPrev = maybe (Pn 0 1 1) nextPos
nextPos :: Token -> Position
nextPos t = Pn (g + s) l (c + s + 1)
where
Pn g l c = tokenPosn t
s = tokenLength t
tokenLength :: Token -> Int
tokenLength = length . prToken
sToken :: Position -> TokSymbol -> Token
sToken p t = PT p $ TK t
line :: Token -> Line
line = fst . tokenLineCol
column :: Token -> Column
column = snd . tokenLineCol
newLine :: Maybe Token -> Token -> Bool
newLine pt t0 = maybe True ((line t0 >) . line) pt
isLayout :: Token -> Maybe LayoutDelimiters
isLayout = \case
PT _ (TK t) -> lookup t layoutWords
_ -> Nothing
isTokenIn :: [TokSymbol] -> Token -> Bool
isTokenIn ts = \case
PT _ (TK t) -> t `elem` ts
_ -> False
isStop :: Token -> Bool
isStop = isTokenIn layoutStopWords
isLayoutOpen :: Token -> Bool
isLayoutOpen = isTokenIn layoutOpen
isLayoutSep :: Token -> Bool
isLayoutSep = isTokenIn layoutSep
isLayoutClose :: Token -> Bool
isLayoutClose = isTokenIn layoutClose
isParenOpen :: Token -> Bool
isParenOpen = isTokenIn parenOpen
isParenClose :: Token -> Bool
isParenClose = isTokenIn parenClose
|
3bc51805bbd1b6bdc768f86056f17c4cf2f5611dd569bdd7d728a44d32d90c11 | hkupty/defteron | runner.clj | (ns bench.runner
(:require [criterium.core :as crit]
[bench.defteron :as lib]
[bench.native :as native])
(:import (defteron Proto$Header Proto$Size))
(:gen-class))
(def base (.build (doto (Proto$Header/newBuilder)
(.setMsgSize Proto$Size/large)
(.setData "Some data")
(.addAllMeta ["a" "really" "short" "list"]))))
(defn -main []
(set! *warn-on-reflection* true)
(println ::msg)
(crit/report-result (crit/quick-benchmark (lib/serialize-msg) {}))
(crit/report-result (crit/quick-benchmark (native/serialize-msg) {}))
(println ::enum)
(crit/report-result (crit/quick-benchmark (lib/serialize-enum-only) {}))
(crit/report-result (crit/quick-benchmark (native/serialize-enum-only) {}))
(println ::msg)
(crit/report-result (crit/quick-benchmark (lib/deserialize-msg base) {}))
(crit/report-result (crit/quick-benchmark (native/deserialize-msg base) {})))
| null | https://raw.githubusercontent.com/hkupty/defteron/d14ae8bf7f8f7ff3c4b63bbe2ac8d28ed078e97e/bench/bench/runner.clj | clojure | (ns bench.runner
(:require [criterium.core :as crit]
[bench.defteron :as lib]
[bench.native :as native])
(:import (defteron Proto$Header Proto$Size))
(:gen-class))
(def base (.build (doto (Proto$Header/newBuilder)
(.setMsgSize Proto$Size/large)
(.setData "Some data")
(.addAllMeta ["a" "really" "short" "list"]))))
(defn -main []
(set! *warn-on-reflection* true)
(println ::msg)
(crit/report-result (crit/quick-benchmark (lib/serialize-msg) {}))
(crit/report-result (crit/quick-benchmark (native/serialize-msg) {}))
(println ::enum)
(crit/report-result (crit/quick-benchmark (lib/serialize-enum-only) {}))
(crit/report-result (crit/quick-benchmark (native/serialize-enum-only) {}))
(println ::msg)
(crit/report-result (crit/quick-benchmark (lib/deserialize-msg base) {}))
(crit/report-result (crit/quick-benchmark (native/deserialize-msg base) {})))
|
|
c4be09de57bdb04a1be69390890ad9fe8b03dda104c73f39114c100ac4f58905 | ekmett/linear | Coincides.hs | {-# LANGUAGE GADTs #-}
---------------------------------------------------------------------------------
-- |
Copyright : ( C ) 2012 - 2015
-- License : BSD-style (see the file LICENSE)
--
Maintainer : < >
-- Stability : experimental
-- Portability : non-portable
--
-- Utility for working with Plücker coordinates for lines in 3d homogeneous space.
----------------------------------------------------------------------------------
module Linear.Plucker.Coincides
( Coincides(..)
) where
import Linear.Epsilon
import Linear.Plucker
-- | When lines are represented as Plücker coordinates, we have the
-- ability to check for both directed and undirected
-- equality. Undirected equality between 'Line's (or a 'Line' and a
' ' ) checks that the two lines coincide in 3D space . Directed
equality , between two ' 's , checks that two lines coincide in 3D ,
and have the same direction . To accomodate these two notions of
equality , we use an ' Eq ' instance on the ' Coincides ' data type .
--
For example , to check the /directed/ equality between two lines ,
@p1@ and @p2@ , we write , p1 = =
data Coincides a where
Line :: (Epsilon a, Fractional a) => Plucker a -> Coincides a
Ray :: (Epsilon a, Fractional a, Ord a) => Plucker a -> Coincides a
instance Eq (Coincides a) where
Line a == Line b = coincides a b
Line a == Ray b = coincides a b
Ray a == Line b = coincides a b
Ray a == Ray b = coincides' a b
| null | https://raw.githubusercontent.com/ekmett/linear/9bb5d69d25f96dd338769f81927d5101b90663af/src/Linear/Plucker/Coincides.hs | haskell | # LANGUAGE GADTs #
-------------------------------------------------------------------------------
|
License : BSD-style (see the file LICENSE)
Stability : experimental
Portability : non-portable
Utility for working with Plücker coordinates for lines in 3d homogeneous space.
--------------------------------------------------------------------------------
| When lines are represented as Plücker coordinates, we have the
ability to check for both directed and undirected
equality. Undirected equality between 'Line's (or a 'Line' and a
| Copyright : ( C ) 2012 - 2015
Maintainer : < >
module Linear.Plucker.Coincides
( Coincides(..)
) where
import Linear.Epsilon
import Linear.Plucker
' ' ) checks that the two lines coincide in 3D space . Directed
equality , between two ' 's , checks that two lines coincide in 3D ,
and have the same direction . To accomodate these two notions of
equality , we use an ' Eq ' instance on the ' Coincides ' data type .
For example , to check the /directed/ equality between two lines ,
@p1@ and @p2@ , we write , p1 = =
data Coincides a where
Line :: (Epsilon a, Fractional a) => Plucker a -> Coincides a
Ray :: (Epsilon a, Fractional a, Ord a) => Plucker a -> Coincides a
instance Eq (Coincides a) where
Line a == Line b = coincides a b
Line a == Ray b = coincides a b
Ray a == Line b = coincides a b
Ray a == Ray b = coincides' a b
|
b22fc75c394c2d6297c01819d94b5729196b56fd883d274a3e193d0d598cf0d6 | f-f/dhall-clj | test_utils.clj | (ns dhall-clj.test-utils
(:require [medley.core :refer [map-vals]]
[dhall-clj.binary :refer [slurp-bytes]]
[clojure.string :as string]
[clojure.java.io :as io]))
;; Credit: -seq#example-54d33991e4b0e2ac61831d15
(defn list-files [basepath]
(let [directory (clojure.java.io/file basepath)
dir? #(.isDirectory %)]
;; we want only files, therefore filter items that are not directories.
(filter (comp not dir?)
(tree-seq dir? #(.listFiles %) directory))))
(defn failure-case?
"Given a `File`, will return true if it's a failure test case.
Note: we try to match both Windows and *nix paths."
[file]
(or (string/includes? (str file) "/failure/")
(string/includes? (str file) "\\failure\\")))
(defn success-testcases
"Returns a record of records {'testcase name' {:actual Text, :expected Text}}
for the 'successful' test cases."
[test-folder]
(let [files (->> (list-files test-folder)
(remove failure-case?)
(remove #(string/includes? (str %) ".md")))
map-of-testcases (group-by #(-> % str
(string/replace #"A.dhall" "")
(string/replace #"B.dhall" ""))
files)]
(map-vals
(fn [a-and-b]
We sort so we get the A.dhall file first
(let [[actual expected] (sort a-and-b)]
{:actual (slurp actual)
:expected (slurp expected)}))
map-of-testcases)))
(defn failure-testcases
"Returns a record of all testcases that should fail.
The keys are the path to the file, and the values are the
associated Dhall expression."
[test-folder]
(let [files (->> (list-files test-folder)
(filter failure-case?)
(remove #(string/includes? (str %) ".md")))]
(into {} (mapv #(vector (str %) (slurp %)) files))))
(defn success-binary-testcases
"Returns a record of records {'testcase name' {:actual Text, :expected ByteArray}}
for the 'successful' test cases."
[test-folder]
(let [files (->> (list-files test-folder)
(remove failure-case?))
map-of-testcases (group-by #(-> % str
(string/replace #"A.dhall" "")
(string/replace #"B.dhallb" ""))
files)]
(map-vals
(fn [a-and-b]
We sort so we get the A.dhall file first
(let [[actual expected] (sort a-and-b)]
{:actual (slurp actual)
:expected (slurp-bytes expected)}))
map-of-testcases)))
| null | https://raw.githubusercontent.com/f-f/dhall-clj/05d25d2464972bbeae46d828b478b4cfd59836dc/test/dhall_clj/test_utils.clj | clojure | Credit: -seq#example-54d33991e4b0e2ac61831d15
we want only files, therefore filter items that are not directories. | (ns dhall-clj.test-utils
(:require [medley.core :refer [map-vals]]
[dhall-clj.binary :refer [slurp-bytes]]
[clojure.string :as string]
[clojure.java.io :as io]))
(defn list-files [basepath]
(let [directory (clojure.java.io/file basepath)
dir? #(.isDirectory %)]
(filter (comp not dir?)
(tree-seq dir? #(.listFiles %) directory))))
(defn failure-case?
"Given a `File`, will return true if it's a failure test case.
Note: we try to match both Windows and *nix paths."
[file]
(or (string/includes? (str file) "/failure/")
(string/includes? (str file) "\\failure\\")))
(defn success-testcases
"Returns a record of records {'testcase name' {:actual Text, :expected Text}}
for the 'successful' test cases."
[test-folder]
(let [files (->> (list-files test-folder)
(remove failure-case?)
(remove #(string/includes? (str %) ".md")))
map-of-testcases (group-by #(-> % str
(string/replace #"A.dhall" "")
(string/replace #"B.dhall" ""))
files)]
(map-vals
(fn [a-and-b]
We sort so we get the A.dhall file first
(let [[actual expected] (sort a-and-b)]
{:actual (slurp actual)
:expected (slurp expected)}))
map-of-testcases)))
(defn failure-testcases
"Returns a record of all testcases that should fail.
The keys are the path to the file, and the values are the
associated Dhall expression."
[test-folder]
(let [files (->> (list-files test-folder)
(filter failure-case?)
(remove #(string/includes? (str %) ".md")))]
(into {} (mapv #(vector (str %) (slurp %)) files))))
(defn success-binary-testcases
"Returns a record of records {'testcase name' {:actual Text, :expected ByteArray}}
for the 'successful' test cases."
[test-folder]
(let [files (->> (list-files test-folder)
(remove failure-case?))
map-of-testcases (group-by #(-> % str
(string/replace #"A.dhall" "")
(string/replace #"B.dhallb" ""))
files)]
(map-vals
(fn [a-and-b]
We sort so we get the A.dhall file first
(let [[actual expected] (sort a-and-b)]
{:actual (slurp actual)
:expected (slurp-bytes expected)}))
map-of-testcases)))
|
dd9a2efae316865e6dbb2f79236b93c275dc0eb06a72df7b52af955063297a73 | acl2/acl2 | (ABNF::PRETTY-PRINT-NUMBER)
(ABNF::STRINGP-OF-PRETTY-PRINT-NUMBER)
(ABNF::PRETTY-PRINT-NUM-BASE)
(ABNF::STRINGP-OF-PRETTY-PRINT-NUM-BASE)
(ABNF::PRETTY-PRINT-NUM-VAL-DIRECT-AUX
(381 3 (:DEFINITION ABNF::PRETTY-PRINT-NUM-VAL-DIRECT-AUX))
(366 3 (:DEFINITION STR::FAST-STRING-APPEND-LST))
(363 9 (:DEFINITION STRING-APPEND-LST))
(171 9 (:DEFINITION STRING-APPEND))
(138 6 (:DEFINITION BINARY-APPEND))
(106 11 (:REWRITE INTEGERP-OF-CAR-WHEN-INTEGER-LISTP))
(96 24 (:REWRITE STR::CONSP-OF-EXPLODE))
(93 7 (:DEFINITION INTEGER-LISTP))
(92 68 (:REWRITE DEFAULT-CDR))
(87 15 (:REWRITE APPEND-WHEN-NOT-CONSP))
(72 72 (:TYPE-PRESCRIPTION STR::TRUE-LISTP-OF-EXPLODE))
(68 44 (:REWRITE DEFAULT-CAR))
(41 11 (:REWRITE INTEGER-LISTP-OF-CDR-WHEN-INTEGER-LISTP))
(36 18 (:REWRITE STR::EXPLODE-WHEN-NOT-STRINGP))
(36 12 (:REWRITE STR::COERCE-TO-LIST-REMOVAL))
(15 9 (:REWRITE STR::COERCE-TO-STRING-REMOVAL))
(15 2 (:REWRITE NATP-OF-CAR-WHEN-NAT-LISTP))
(14 14 (:REWRITE NAT-LISTP-WHEN-NOT-CONSP))
(14 14 (:REWRITE INTEGER-LISTP-WHEN-NOT-CONSP))
(12 6 (:REWRITE APPEND-ATOM-UNDER-LIST-EQUIV))
(9 3 (:REWRITE STR::EXPLODE-OF-IMPLODE))
(9 3 (:REWRITE APPEND-OF-NIL))
(6 6 (:TYPE-PRESCRIPTION STRING-APPEND-LST))
(6 3 (:REWRITE LIST-FIX-WHEN-TRUE-LISTP))
(6 3 (:REWRITE STR::IMPLODE-OF-EXPLODE))
(6 3 (:REWRITE APPEND-OF-CONS))
(3 3 (:REWRITE STR::MAKE-CHARACTER-LIST-IS-IDENTITY-UNDER-CHARLISTEQV))
(3 3 (:REWRITE DEFAULT-<-2))
(3 3 (:REWRITE DEFAULT-<-1))
)
(ABNF::STRINGP-OF-PRETTY-PRINT-NUM-VAL-DIRECT-AUX)
(ABNF::PRETTY-PRINT-NUM-VAL-DIRECT)
(ABNF::STRINGP-OF-PRETTY-PRINT-NUM-VAL-DIRECT)
(ABNF::PRETTY-PRINT-NUM-VAL-RANGE
(4 4 (:REWRITE DEFAULT-CDR))
(4 4 (:REWRITE DEFAULT-CAR))
(2 2 (:REWRITE DEFAULT-<-2))
(2 2 (:REWRITE DEFAULT-<-1))
)
(ABNF::STRINGP-OF-PRETTY-PRINT-NUM-VAL-RANGE)
(ABNF::PRETTY-PRINT-NUM-VAL)
(ABNF::STRINGP-OF-PRETTY-PRINT-NUM-VAL)
(ABNF::PRETTY-PRINT-CHAR-VAL
(5 5 (:REWRITE DEFAULT-CDR))
(5 5 (:REWRITE DEFAULT-CAR))
)
(ABNF::STRINGP-OF-PRETTY-PRINT-CHAR-VAL)
(ABNF::PRETTY-PRINT-PROSE-VAL
(2 2 (:REWRITE DEFAULT-CDR))
(2 2 (:REWRITE DEFAULT-CAR))
)
(ABNF::STRINGP-OF-PRETTY-PRINT-PROSE-VAL)
(ABNF::PRETTY-PRINT-REPEAT-RANGE
(41 22 (:REWRITE DEFAULT-CDR))
(41 22 (:REWRITE DEFAULT-CAR))
(12 6 (:REWRITE DEFAULT-<-1))
(6 6 (:REWRITE DEFAULT-<-2))
)
(ABNF::STRINGP-OF-PRETTY-PRINT-REPEAT-RANGE)
(ABNF::PRETTY-PRINT-ELEMENT
(1466 13 (:DEFINITION STR::FAST-STRING-APPEND-LST))
(1453 37 (:DEFINITION STRING-APPEND-LST))
(899 7 (:DEFINITION ABNF::PRETTY-PRINT-ALTERNATION))
(771 38 (:DEFINITION STRING-APPEND))
(572 25 (:DEFINITION BINARY-APPEND))
(508 4 (:DEFINITION ABNF::PRETTY-PRINT-CONCATENATION))
(400 100 (:REWRITE STR::CONSP-OF-EXPLODE))
(363 63 (:REWRITE APPEND-WHEN-NOT-CONSP))
(296 296 (:TYPE-PRESCRIPTION STR::TRUE-LISTP-OF-EXPLODE))
(264 164 (:REWRITE DEFAULT-CDR))
(218 118 (:REWRITE DEFAULT-CAR))
(150 50 (:REWRITE STR::COERCE-TO-LIST-REMOVAL))
(144 72 (:REWRITE STR::EXPLODE-WHEN-NOT-STRINGP))
(133 1 (:DEFINITION ABNF::PRETTY-PRINT-ELEMENT))
(60 38 (:REWRITE STR::COERCE-TO-STRING-REMOVAL))
(44 22 (:REWRITE APPEND-ATOM-UNDER-LIST-EQUIV))
(43 13 (:REWRITE STR::EXPLODE-OF-IMPLODE))
(42 29 (:REWRITE APPEND-OF-CONS))
(42 1 (:DEFINITION ABNF::PRETTY-PRINT-REPETITION))
(41 1 (:DEFINITION STR::FAST-STRING-APPEND))
(33 11 (:REWRITE APPEND-OF-NIL))
(24 24 (:TYPE-PRESCRIPTION STRING-APPEND-LST))
(22 11 (:REWRITE LIST-FIX-WHEN-TRUE-LISTP))
(22 11 (:REWRITE STR::IMPLODE-OF-EXPLODE))
(21 7 (:REWRITE DEFAULT-<-2))
(21 7 (:REWRITE DEFAULT-<-1))
(13 13 (:REWRITE STR::MAKE-CHARACTER-LIST-IS-IDENTITY-UNDER-CHARLISTEQV))
(4 4 (:REWRITE SUBSETP-TRANS2))
(4 4 (:REWRITE SUBSETP-TRANS))
(4 2 (:TYPE-PRESCRIPTION TRUE-LISTP-APPEND))
(3 3 (:REWRITE ABNF::CONCATENATIONP-WHEN-NOT-CONSP))
(2 2 (:TYPE-PRESCRIPTION BINARY-APPEND))
(1 1 (:REWRITE ABNF::ALTERNATIONP-WHEN-NOT-CONSP))
)
(ABNF::PRETTY-PRINT-ALT/CONC/REP/ELEM-FLAG
(21 7 (:REWRITE DEFAULT-<-2))
(21 7 (:REWRITE DEFAULT-<-1))
(6 6 (:REWRITE DEFAULT-CDR))
(4 4 (:REWRITE DEFAULT-CAR))
)
(FLAG::FLAG-EQUIV-LEMMA)
(ABNF::PRETTY-PRINT-ALT/CONC/REP/ELEM-FLAG-EQUIVALENCES)
(ABNF::FLAG-LEMMA-FOR-RETURN-TYPE-OF-PRETTY-PRINT-ELEMENT.STRING)
(ABNF::RETURN-TYPE-OF-PRETTY-PRINT-ELEMENT.STRING)
(ABNF::RETURN-TYPE-OF-PRETTY-PRINT-ALTERNATION.STRING)
(ABNF::RETURN-TYPE-OF-PRETTY-PRINT-CONCATENATION.STRING)
(ABNF::RETURN-TYPE-OF-PRETTY-PRINT-REPETITION.STRING)
(ABNF::PRETTY-PRINT-RULE
(10 10 (:REWRITE ABNF::RULEP-WHEN-MEMBER-EQUAL-OF-RULELISTP))
(3 3 (:REWRITE DEFAULT-CDR))
(3 3 (:REWRITE DEFAULT-CAR))
)
(ABNF::STRINGP-OF-PRETTY-PRINT-RULE)
(ABNF::PRETTY-PRINT-RULELIST
(498 3 (:DEFINITION ABNF::PRETTY-PRINT-RULELIST))
(369 3 (:DEFINITION STR::FAST-STRING-APPEND-LST))
(366 9 (:DEFINITION STRING-APPEND-LST))
(285 12 (:DEFINITION STRING-APPEND))
(204 9 (:DEFINITION BINARY-APPEND))
(144 36 (:REWRITE STR::CONSP-OF-EXPLODE))
(129 21 (:REWRITE APPEND-WHEN-NOT-CONSP))
(114 3 (:DEFINITION STR::FAST-STRING-APPEND))
(102 102 (:TYPE-PRESCRIPTION STR::TRUE-LISTP-OF-EXPLODE))
(90 54 (:REWRITE DEFAULT-CDR))
(69 33 (:REWRITE DEFAULT-CAR))
(45 15 (:REWRITE STR::COERCE-TO-LIST-REMOVAL))
(42 21 (:REWRITE STR::EXPLODE-WHEN-NOT-STRINGP))
(18 12 (:REWRITE STR::COERCE-TO-STRING-REMOVAL))
(12 6 (:REWRITE APPEND-ATOM-UNDER-LIST-EQUIV))
(9 6 (:REWRITE APPEND-OF-CONS))
(9 3 (:REWRITE STR::EXPLODE-OF-IMPLODE))
(9 3 (:REWRITE APPEND-OF-NIL))
(6 6 (:TYPE-PRESCRIPTION STRING-APPEND-LST))
(6 3 (:REWRITE LIST-FIX-WHEN-TRUE-LISTP))
(6 3 (:REWRITE STR::IMPLODE-OF-EXPLODE))
(3 3 (:REWRITE STR::MAKE-CHARACTER-LIST-IS-IDENTITY-UNDER-CHARLISTEQV))
(2 2 (:REWRITE SUBSETP-TRANS2))
(2 2 (:REWRITE SUBSETP-TRANS))
(1 1 (:REWRITE ABNF::RULELISTP-WHEN-NOT-CONSP))
)
(ABNF::STRINGP-OF-PRETTY-PRINT-RULELIST)
| null | https://raw.githubusercontent.com/acl2/acl2/f64742cc6d41c35f9d3f94e154cd5fd409105d34/books/kestrel/abnf/grammar-printer/.sys/executable%40useless-runes.lsp | lisp | (ABNF::PRETTY-PRINT-NUMBER)
(ABNF::STRINGP-OF-PRETTY-PRINT-NUMBER)
(ABNF::PRETTY-PRINT-NUM-BASE)
(ABNF::STRINGP-OF-PRETTY-PRINT-NUM-BASE)
(ABNF::PRETTY-PRINT-NUM-VAL-DIRECT-AUX
(381 3 (:DEFINITION ABNF::PRETTY-PRINT-NUM-VAL-DIRECT-AUX))
(366 3 (:DEFINITION STR::FAST-STRING-APPEND-LST))
(363 9 (:DEFINITION STRING-APPEND-LST))
(171 9 (:DEFINITION STRING-APPEND))
(138 6 (:DEFINITION BINARY-APPEND))
(106 11 (:REWRITE INTEGERP-OF-CAR-WHEN-INTEGER-LISTP))
(96 24 (:REWRITE STR::CONSP-OF-EXPLODE))
(93 7 (:DEFINITION INTEGER-LISTP))
(92 68 (:REWRITE DEFAULT-CDR))
(87 15 (:REWRITE APPEND-WHEN-NOT-CONSP))
(72 72 (:TYPE-PRESCRIPTION STR::TRUE-LISTP-OF-EXPLODE))
(68 44 (:REWRITE DEFAULT-CAR))
(41 11 (:REWRITE INTEGER-LISTP-OF-CDR-WHEN-INTEGER-LISTP))
(36 18 (:REWRITE STR::EXPLODE-WHEN-NOT-STRINGP))
(36 12 (:REWRITE STR::COERCE-TO-LIST-REMOVAL))
(15 9 (:REWRITE STR::COERCE-TO-STRING-REMOVAL))
(15 2 (:REWRITE NATP-OF-CAR-WHEN-NAT-LISTP))
(14 14 (:REWRITE NAT-LISTP-WHEN-NOT-CONSP))
(14 14 (:REWRITE INTEGER-LISTP-WHEN-NOT-CONSP))
(12 6 (:REWRITE APPEND-ATOM-UNDER-LIST-EQUIV))
(9 3 (:REWRITE STR::EXPLODE-OF-IMPLODE))
(9 3 (:REWRITE APPEND-OF-NIL))
(6 6 (:TYPE-PRESCRIPTION STRING-APPEND-LST))
(6 3 (:REWRITE LIST-FIX-WHEN-TRUE-LISTP))
(6 3 (:REWRITE STR::IMPLODE-OF-EXPLODE))
(6 3 (:REWRITE APPEND-OF-CONS))
(3 3 (:REWRITE STR::MAKE-CHARACTER-LIST-IS-IDENTITY-UNDER-CHARLISTEQV))
(3 3 (:REWRITE DEFAULT-<-2))
(3 3 (:REWRITE DEFAULT-<-1))
)
(ABNF::STRINGP-OF-PRETTY-PRINT-NUM-VAL-DIRECT-AUX)
(ABNF::PRETTY-PRINT-NUM-VAL-DIRECT)
(ABNF::STRINGP-OF-PRETTY-PRINT-NUM-VAL-DIRECT)
(ABNF::PRETTY-PRINT-NUM-VAL-RANGE
(4 4 (:REWRITE DEFAULT-CDR))
(4 4 (:REWRITE DEFAULT-CAR))
(2 2 (:REWRITE DEFAULT-<-2))
(2 2 (:REWRITE DEFAULT-<-1))
)
(ABNF::STRINGP-OF-PRETTY-PRINT-NUM-VAL-RANGE)
(ABNF::PRETTY-PRINT-NUM-VAL)
(ABNF::STRINGP-OF-PRETTY-PRINT-NUM-VAL)
(ABNF::PRETTY-PRINT-CHAR-VAL
(5 5 (:REWRITE DEFAULT-CDR))
(5 5 (:REWRITE DEFAULT-CAR))
)
(ABNF::STRINGP-OF-PRETTY-PRINT-CHAR-VAL)
(ABNF::PRETTY-PRINT-PROSE-VAL
(2 2 (:REWRITE DEFAULT-CDR))
(2 2 (:REWRITE DEFAULT-CAR))
)
(ABNF::STRINGP-OF-PRETTY-PRINT-PROSE-VAL)
(ABNF::PRETTY-PRINT-REPEAT-RANGE
(41 22 (:REWRITE DEFAULT-CDR))
(41 22 (:REWRITE DEFAULT-CAR))
(12 6 (:REWRITE DEFAULT-<-1))
(6 6 (:REWRITE DEFAULT-<-2))
)
(ABNF::STRINGP-OF-PRETTY-PRINT-REPEAT-RANGE)
(ABNF::PRETTY-PRINT-ELEMENT
(1466 13 (:DEFINITION STR::FAST-STRING-APPEND-LST))
(1453 37 (:DEFINITION STRING-APPEND-LST))
(899 7 (:DEFINITION ABNF::PRETTY-PRINT-ALTERNATION))
(771 38 (:DEFINITION STRING-APPEND))
(572 25 (:DEFINITION BINARY-APPEND))
(508 4 (:DEFINITION ABNF::PRETTY-PRINT-CONCATENATION))
(400 100 (:REWRITE STR::CONSP-OF-EXPLODE))
(363 63 (:REWRITE APPEND-WHEN-NOT-CONSP))
(296 296 (:TYPE-PRESCRIPTION STR::TRUE-LISTP-OF-EXPLODE))
(264 164 (:REWRITE DEFAULT-CDR))
(218 118 (:REWRITE DEFAULT-CAR))
(150 50 (:REWRITE STR::COERCE-TO-LIST-REMOVAL))
(144 72 (:REWRITE STR::EXPLODE-WHEN-NOT-STRINGP))
(133 1 (:DEFINITION ABNF::PRETTY-PRINT-ELEMENT))
(60 38 (:REWRITE STR::COERCE-TO-STRING-REMOVAL))
(44 22 (:REWRITE APPEND-ATOM-UNDER-LIST-EQUIV))
(43 13 (:REWRITE STR::EXPLODE-OF-IMPLODE))
(42 29 (:REWRITE APPEND-OF-CONS))
(42 1 (:DEFINITION ABNF::PRETTY-PRINT-REPETITION))
(41 1 (:DEFINITION STR::FAST-STRING-APPEND))
(33 11 (:REWRITE APPEND-OF-NIL))
(24 24 (:TYPE-PRESCRIPTION STRING-APPEND-LST))
(22 11 (:REWRITE LIST-FIX-WHEN-TRUE-LISTP))
(22 11 (:REWRITE STR::IMPLODE-OF-EXPLODE))
(21 7 (:REWRITE DEFAULT-<-2))
(21 7 (:REWRITE DEFAULT-<-1))
(13 13 (:REWRITE STR::MAKE-CHARACTER-LIST-IS-IDENTITY-UNDER-CHARLISTEQV))
(4 4 (:REWRITE SUBSETP-TRANS2))
(4 4 (:REWRITE SUBSETP-TRANS))
(4 2 (:TYPE-PRESCRIPTION TRUE-LISTP-APPEND))
(3 3 (:REWRITE ABNF::CONCATENATIONP-WHEN-NOT-CONSP))
(2 2 (:TYPE-PRESCRIPTION BINARY-APPEND))
(1 1 (:REWRITE ABNF::ALTERNATIONP-WHEN-NOT-CONSP))
)
(ABNF::PRETTY-PRINT-ALT/CONC/REP/ELEM-FLAG
(21 7 (:REWRITE DEFAULT-<-2))
(21 7 (:REWRITE DEFAULT-<-1))
(6 6 (:REWRITE DEFAULT-CDR))
(4 4 (:REWRITE DEFAULT-CAR))
)
(FLAG::FLAG-EQUIV-LEMMA)
(ABNF::PRETTY-PRINT-ALT/CONC/REP/ELEM-FLAG-EQUIVALENCES)
(ABNF::FLAG-LEMMA-FOR-RETURN-TYPE-OF-PRETTY-PRINT-ELEMENT.STRING)
(ABNF::RETURN-TYPE-OF-PRETTY-PRINT-ELEMENT.STRING)
(ABNF::RETURN-TYPE-OF-PRETTY-PRINT-ALTERNATION.STRING)
(ABNF::RETURN-TYPE-OF-PRETTY-PRINT-CONCATENATION.STRING)
(ABNF::RETURN-TYPE-OF-PRETTY-PRINT-REPETITION.STRING)
(ABNF::PRETTY-PRINT-RULE
(10 10 (:REWRITE ABNF::RULEP-WHEN-MEMBER-EQUAL-OF-RULELISTP))
(3 3 (:REWRITE DEFAULT-CDR))
(3 3 (:REWRITE DEFAULT-CAR))
)
(ABNF::STRINGP-OF-PRETTY-PRINT-RULE)
(ABNF::PRETTY-PRINT-RULELIST
(498 3 (:DEFINITION ABNF::PRETTY-PRINT-RULELIST))
(369 3 (:DEFINITION STR::FAST-STRING-APPEND-LST))
(366 9 (:DEFINITION STRING-APPEND-LST))
(285 12 (:DEFINITION STRING-APPEND))
(204 9 (:DEFINITION BINARY-APPEND))
(144 36 (:REWRITE STR::CONSP-OF-EXPLODE))
(129 21 (:REWRITE APPEND-WHEN-NOT-CONSP))
(114 3 (:DEFINITION STR::FAST-STRING-APPEND))
(102 102 (:TYPE-PRESCRIPTION STR::TRUE-LISTP-OF-EXPLODE))
(90 54 (:REWRITE DEFAULT-CDR))
(69 33 (:REWRITE DEFAULT-CAR))
(45 15 (:REWRITE STR::COERCE-TO-LIST-REMOVAL))
(42 21 (:REWRITE STR::EXPLODE-WHEN-NOT-STRINGP))
(18 12 (:REWRITE STR::COERCE-TO-STRING-REMOVAL))
(12 6 (:REWRITE APPEND-ATOM-UNDER-LIST-EQUIV))
(9 6 (:REWRITE APPEND-OF-CONS))
(9 3 (:REWRITE STR::EXPLODE-OF-IMPLODE))
(9 3 (:REWRITE APPEND-OF-NIL))
(6 6 (:TYPE-PRESCRIPTION STRING-APPEND-LST))
(6 3 (:REWRITE LIST-FIX-WHEN-TRUE-LISTP))
(6 3 (:REWRITE STR::IMPLODE-OF-EXPLODE))
(3 3 (:REWRITE STR::MAKE-CHARACTER-LIST-IS-IDENTITY-UNDER-CHARLISTEQV))
(2 2 (:REWRITE SUBSETP-TRANS2))
(2 2 (:REWRITE SUBSETP-TRANS))
(1 1 (:REWRITE ABNF::RULELISTP-WHEN-NOT-CONSP))
)
(ABNF::STRINGP-OF-PRETTY-PRINT-RULELIST)
|
||
3092623647bdebd2433d9dce5e9a675cc1ec43fb8052c8db0dc3abca0c188d6d | facundoolano/cljsbin | project.clj | (defproject cljsbin "0.1.0-SNAPSHOT"
:description "httpbin implemented in ClojureScript"
:url ""
:dependencies [[bidi "2.0.16"]
[com.cemerick/piggieback "0.2.1"]
[com.taoensso/timbre "4.8.0"]
[hiccups "0.3.0"]
[macchiato/core "0.1.6"]
[macchiato/env "0.0.5"]
[mount "0.1.11"]
[org.clojure/clojure "1.8.0"]
[org.clojure/clojurescript "1.9.456"]
[camel-snake-kebab "0.4.0"]]
:jvm-opts ^:replace ["-Xmx1g" "-server"]
:plugins [[lein-doo "0.1.7"]
[macchiato/lein-npm "0.6.2"]
[lein-figwheel "0.5.9"]
[lein-cljsbuild "1.1.4"]]
:npm {:dependencies [[source-map-support "0.4.6"]
[compression "^1.6.2"]
[morgan "^1.8.1"]
[passport "^0.3.2"]
[passport-http "facundoolano/passport-http"]
[response-time "^2.3.2"]
[serve-favicon "^2.4.0"]
[body-parser "^1.16.1"]]
:write-package-json true}
:source-paths ["src" "target/classes"]
:clean-targets ["target"]
:target-path "target"
:profiles
{:dev
{:npm {:package {:main "target/out/cljsbin.js"
:scripts {:start "node target/out/cljsbin.js"}}}
:cljsbuild
{:builds {:dev
{:source-paths ["env/dev" "src"]
:figwheel true
:compiler {:main cljsbin.app
:output-to "target/out/cljsbin.js"
:output-dir "target/out"
:target :nodejs
:optimizations :none
:pretty-print true
:source-map true
:source-map-timestamp false}}}}
:figwheel
{:http-server-root "public"
:nrepl-port 7000
:reload-clj-files {:clj false :cljc true}
:nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]}
:source-paths ["env/dev"]
:repl-options {:init-ns user}}
:test
{:cljsbuild
{:builds
{:test
{:source-paths ["env/test" "src" "test"]
:compiler {:main cljsbin.app
:output-to "target/test/cljsbin.js"
:target :nodejs
:optimizations :none
:pretty-print true
:source-map true}}}}
:doo {:build "test"}}
:release
{:npm {:package {:main "target/release/cljsbin.js"
:scripts {:start "node target/release/cljsbin.js"}}}
:cljsbuild
{:builds
{:release
{:source-paths ["env/prod" "src"]
:compiler {:main cljsbin.app
:output-to "target/release/cljsbin.js"
:target :nodejs
:optimizations :simple
:pretty-print false}}}}}}
:aliases
{"build" ["do"
["clean"]
["npm" "install"]
["figwheel" "dev"]]
"package" ["do"
["clean"]
["npm" "install"]
["with-profile" "release" "npm" "init" "-y"]
["with-profile" "release" "cljsbuild" "once"]]
"test" ["do"
["npm" "install"]
["with-profile" "test" "doo" "node"]]})
| null | https://raw.githubusercontent.com/facundoolano/cljsbin/d48be25a9c57522f1dc29e1e520b43ea408cf864/project.clj | clojure | (defproject cljsbin "0.1.0-SNAPSHOT"
:description "httpbin implemented in ClojureScript"
:url ""
:dependencies [[bidi "2.0.16"]
[com.cemerick/piggieback "0.2.1"]
[com.taoensso/timbre "4.8.0"]
[hiccups "0.3.0"]
[macchiato/core "0.1.6"]
[macchiato/env "0.0.5"]
[mount "0.1.11"]
[org.clojure/clojure "1.8.0"]
[org.clojure/clojurescript "1.9.456"]
[camel-snake-kebab "0.4.0"]]
:jvm-opts ^:replace ["-Xmx1g" "-server"]
:plugins [[lein-doo "0.1.7"]
[macchiato/lein-npm "0.6.2"]
[lein-figwheel "0.5.9"]
[lein-cljsbuild "1.1.4"]]
:npm {:dependencies [[source-map-support "0.4.6"]
[compression "^1.6.2"]
[morgan "^1.8.1"]
[passport "^0.3.2"]
[passport-http "facundoolano/passport-http"]
[response-time "^2.3.2"]
[serve-favicon "^2.4.0"]
[body-parser "^1.16.1"]]
:write-package-json true}
:source-paths ["src" "target/classes"]
:clean-targets ["target"]
:target-path "target"
:profiles
{:dev
{:npm {:package {:main "target/out/cljsbin.js"
:scripts {:start "node target/out/cljsbin.js"}}}
:cljsbuild
{:builds {:dev
{:source-paths ["env/dev" "src"]
:figwheel true
:compiler {:main cljsbin.app
:output-to "target/out/cljsbin.js"
:output-dir "target/out"
:target :nodejs
:optimizations :none
:pretty-print true
:source-map true
:source-map-timestamp false}}}}
:figwheel
{:http-server-root "public"
:nrepl-port 7000
:reload-clj-files {:clj false :cljc true}
:nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]}
:source-paths ["env/dev"]
:repl-options {:init-ns user}}
:test
{:cljsbuild
{:builds
{:test
{:source-paths ["env/test" "src" "test"]
:compiler {:main cljsbin.app
:output-to "target/test/cljsbin.js"
:target :nodejs
:optimizations :none
:pretty-print true
:source-map true}}}}
:doo {:build "test"}}
:release
{:npm {:package {:main "target/release/cljsbin.js"
:scripts {:start "node target/release/cljsbin.js"}}}
:cljsbuild
{:builds
{:release
{:source-paths ["env/prod" "src"]
:compiler {:main cljsbin.app
:output-to "target/release/cljsbin.js"
:target :nodejs
:optimizations :simple
:pretty-print false}}}}}}
:aliases
{"build" ["do"
["clean"]
["npm" "install"]
["figwheel" "dev"]]
"package" ["do"
["clean"]
["npm" "install"]
["with-profile" "release" "npm" "init" "-y"]
["with-profile" "release" "cljsbuild" "once"]]
"test" ["do"
["npm" "install"]
["with-profile" "test" "doo" "node"]]})
|
|
64130393b1bdb0cf8a4d135d602542c423069069d9463b892a5543c5e111d700 | larcenists/larceny | sumfp.scm | ;;; SUMFP -- Compute sum of integers from 0 to n using floating point
(import (scheme base)
(scheme read)
(scheme write)
(scheme time))
(define (run n)
(let loop ((i n) (sum 0.))
(if (< i 0.)
sum
(loop (- i 1.) (+ i sum)))))
(define (main)
(let* ((count (read))
(input1 (read))
(output (read))
(s2 (number->string count))
(s1 (number->string input1))
(name "sumfp"))
(run-r7rs-benchmark
(string-append name ":" s1 ":" s2)
count
(lambda () (run (hide count input1)))
(lambda (result) (equal? result output)))))
| null | https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/test/Benchmarking/R7RS/src/sumfp.scm | scheme | SUMFP -- Compute sum of integers from 0 to n using floating point |
(import (scheme base)
(scheme read)
(scheme write)
(scheme time))
(define (run n)
(let loop ((i n) (sum 0.))
(if (< i 0.)
sum
(loop (- i 1.) (+ i sum)))))
(define (main)
(let* ((count (read))
(input1 (read))
(output (read))
(s2 (number->string count))
(s1 (number->string input1))
(name "sumfp"))
(run-r7rs-benchmark
(string-append name ":" s1 ":" s2)
count
(lambda () (run (hide count input1)))
(lambda (result) (equal? result output)))))
|
e03d15f1ba046d7110b333a796cb1dba4b7a51658c31a0aec20e40b882eba2dd | ghc/packages-Cabal | Capture.hs | module Capture (capture) where
import Language.Haskell.TH
import Language.Haskell.TH.Syntax (NameFlavour (..), Name (..))
import Control.Monad.IO.Class
import Data.Generics as SYB
-- | Capture the source code of declarations in the variable
capture
:: String -- ^ variable name
-> Q [Dec] -- ^ definitions
-> Q [Dec]
capture name decls = do
decls1 <- decls
-- mangle all names to drop unique suffixes and module prefixes
let decls2 = SYB.everywhere (SYB.mkT mangleName) decls1
let declsStr = pprint decls2
-- liftIO (putStrLn declsStr)
let nameTyDecl :: Dec
nameTyDecl = SigD (mkName name) (ConT (mkName "String"))
nameDecl :: Dec
nameDecl = ValD (VarP $ mkName name) (NormalB (LitE (StringL declsStr))) []
return $ nameTyDecl : nameDecl : decls1
where
mangleName :: Name -> Name
mangleName (Name occ _) = Name occ NameS
| null | https://raw.githubusercontent.com/ghc/packages-Cabal/6f22f2a789fa23edb210a2591d74ea6a5f767872/cabal-dev-scripts/src/Capture.hs | haskell | | Capture the source code of declarations in the variable
^ variable name
^ definitions
mangle all names to drop unique suffixes and module prefixes
liftIO (putStrLn declsStr) | module Capture (capture) where
import Language.Haskell.TH
import Language.Haskell.TH.Syntax (NameFlavour (..), Name (..))
import Control.Monad.IO.Class
import Data.Generics as SYB
capture
-> Q [Dec]
capture name decls = do
decls1 <- decls
let decls2 = SYB.everywhere (SYB.mkT mangleName) decls1
let declsStr = pprint decls2
let nameTyDecl :: Dec
nameTyDecl = SigD (mkName name) (ConT (mkName "String"))
nameDecl :: Dec
nameDecl = ValD (VarP $ mkName name) (NormalB (LitE (StringL declsStr))) []
return $ nameTyDecl : nameDecl : decls1
where
mangleName :: Name -> Name
mangleName (Name occ _) = Name occ NameS
|
5259fba90496e15026be19c80286d32d7e42f4710612a64620bfdea8645123c1 | lambdamikel/DLMAPS | creators.lisp | ;;; -*- Mode: LISP; Syntax: Common-Lisp; Package: PROVER -*-
(in-package :PROVER)
;;;
;;;
;;;
;;;
(defmethod create-abox-node ((abox abox) name-for-node
&rest args)
(apply #'create-node
abox name-for-node
(make-node-description (get-standard-node-description-class abox) nil)
args))
(defmethod create-node ((abox abox) (name-for-node symbol) (description node-label)
&rest args
&key
depends-on created-by
(old-p t)
&allow-other-keys)
(let ((*start-time* (get-internal-run-time)))
(let* ((created-by (or created-by depends-on))
(node (apply #'call-next-method
abox name-for-node description
:delete-if-exists-p nil
:old-p old-p
:created-by created-by
:edge-constructor #'(lambda (node ref-role)
(create-edge abox
node node
(make-edge-description
(get-standard-edge-description-class abox)
ref-role)
:created-by created-by
:create-inverse-p nil
:error-p nil))
args)))
(setf (slot-value (description node) 'of-node) node
(slot-value node 'cluster-nodes) (list node))
(when created-by
(register-action create created-by node))
(incf *time-for-node-creation*
(- (get-internal-run-time)
*start-time*))
node)))
(defmethod register-node ((node abox-node))
(let ((abox (in-graph node)))
(with-slots (all-nodes old-nodes node-table) abox
(when (is-abox1-p abox)
(if (not *use-avl-trees-for-abox1-p*)
(push node all-nodes)
(insert-into-avl-tree node all-nodes :key #'id))
(when (and *maintain-old-nodes-p* (old-p node))
(push node old-nodes)))
(activate-node abox node)
(when (or (old-p node)
(root-p node)
(not (is-abox1-p abox)))
(unless node-table
(setf node-table
(make-weak-hash-table :size 10 :rehash-size 100)))
(call-next-method)))))
;;;
;;;
;;;
(defmethod create-edge ((abox abox)
(from abox-node) (to abox-node)
(description edge-label)
&rest args
&key
(old-p t)
depends-on created-by
(new-choice-point 0)
&allow-other-keys)
(let ((*start-time* (get-internal-run-time)))
(let ((created-by (or created-by depends-on))
(edge (apply #'call-next-method abox from to
description
:created-by created-by
:old-p old-p
args)))
(unless *dont-invalidate-store-p*
(note-abox-has-changed abox)
(reset-sat-status from)
(reset-sat-status to)
( reset - sat - status ( concept - store ( ) ) )
)
;;;
Adresse verwalten
;;;
(incf (slot-value from 'succ-counter))
(setf (slot-value to 'address)
(cons (slot-value from 'succ-counter)
(slot-value from 'address)))
(setf (slot-value to 'rev-address)
(reverse (slot-value to 'address)))
;;;
;;; Blaetter
;;;
(apply #'register-as-unexpanded edge
:new-choice-point new-choice-point
args)
(when (inverse-edge edge)
(apply #'register-as-unexpanded (inverse-edge edge)
:new-choice-point new-choice-point
args))
(when created-by
(let ((created-by
(if (eq created-by t)
nil
created-by)))
(register-action create
created-by
edge)
(when (and (inverse-edge edge)
(not (eq (inverse-edge edge) edge)))
(register-action create
created-by
(inverse-edge edge)))))
(incf *time-for-edge-creation*
(- (get-internal-run-time)
*start-time*))
edge)))
(defmethod register-edge ((edge abox-edge))
(let ((abox (in-graph edge))
(from (from edge))
(to (to edge)))
(with-slots (all-edges edge-table) abox
(when (is-abox1-p abox)
(unless (cdr (outgoing from))
(setf (slot-value abox 'leaf-nodes)
(delete from (slot-value abox 'leaf-nodes))))
(if (not *use-avl-trees-for-abox1-p*)
(push edge all-edges)
(insert-into-avl-tree edge all-edges :key #'id)))
(if (or (old-p edge)
(not (is-abox1-p abox)))
(progn
(unless edge-table
(setf edge-table
(make-weak-hash-table :size 10 :rehash-size 100 :test #'equal)))
(call-next-method))
(progn
(push to (slot-value from 'successors))
(push from (slot-value to 'predecessors))
(push edge (slot-value from 'outgoing))
(push edge (slot-value to 'incoming)))))))
;;;
;;;
;;;
(defmethod relate ((from abox-node) (to abox-node) (description edge-label) &rest args)
(apply #'create-edge *cur-abox* from to description args))
(defmethod relate ((from abox-node) (to abox-node) role &rest args
&key description-type
&allow-other-keys)
(let* ((descr (make-edge-description
(or description-type
(get-standard-edge-description-class *cur-abox*)) role))
(role (textual-description descr)))
(declare (ignorable role))
(apply #'create-edge *cur-abox* from to descr args)))
(defmethod relate ((from symbol) (to symbol) role
&rest args &key (create-nodes-p t)
(node-type (get-standard-node-class *cur-abox*)) &allow-other-keys)
(apply #'relate
(or (apply #'find-node *cur-abox* from :error-p nil args)
(when create-nodes-p
(apply #'create-abox-node *cur-abox* from :type node-type args)))
(or (apply #'find-node *cur-abox* to :error-p nil args)
(when create-nodes-p
(apply #'create-abox-node *cur-abox* to :type node-type args)))
role
args))
;;;
;;;
;;;
(defmethod unrelate ((from abox-node) (to abox-node) role &rest args)
(unless (eq (in-graph from)
(in-graph to))
(error "Individuals must be in same ABox!"))
(let* ((abox (in-graph from))
(role (parse-role role))
(edges
(remove-if-not #'(lambda (edge)
(eq (role edge) role))
(apply #'get-edges-between abox from to args))))
(dolist (edge edges)
(apply #'delete-edge abox edge
:update-db-p t
args))))
(defmethod unrelate ((from symbol) (to symbol) role &rest args)
(apply #'unrelate
(apply #'find-node *cur-abox* from :error-p t args)
(apply #'find-node *cur-abox* to :error-p t args)
(parse-role role)
args))
;;;
;;;
;;;
(defun create-anonymous-node (abox &rest args)
(incf *created-nodes*)
(apply #'create-abox-node abox nil :old-p nil args))
| null | https://raw.githubusercontent.com/lambdamikel/DLMAPS/7f8dbb9432069d41e6a7d9c13dc5b25602ad35dc/src/prover/creators.lisp | lisp | -*- Mode: LISP; Syntax: Common-Lisp; Package: PROVER -*-
Blaetter
|
(in-package :PROVER)
(defmethod create-abox-node ((abox abox) name-for-node
&rest args)
(apply #'create-node
abox name-for-node
(make-node-description (get-standard-node-description-class abox) nil)
args))
(defmethod create-node ((abox abox) (name-for-node symbol) (description node-label)
&rest args
&key
depends-on created-by
(old-p t)
&allow-other-keys)
(let ((*start-time* (get-internal-run-time)))
(let* ((created-by (or created-by depends-on))
(node (apply #'call-next-method
abox name-for-node description
:delete-if-exists-p nil
:old-p old-p
:created-by created-by
:edge-constructor #'(lambda (node ref-role)
(create-edge abox
node node
(make-edge-description
(get-standard-edge-description-class abox)
ref-role)
:created-by created-by
:create-inverse-p nil
:error-p nil))
args)))
(setf (slot-value (description node) 'of-node) node
(slot-value node 'cluster-nodes) (list node))
(when created-by
(register-action create created-by node))
(incf *time-for-node-creation*
(- (get-internal-run-time)
*start-time*))
node)))
(defmethod register-node ((node abox-node))
(let ((abox (in-graph node)))
(with-slots (all-nodes old-nodes node-table) abox
(when (is-abox1-p abox)
(if (not *use-avl-trees-for-abox1-p*)
(push node all-nodes)
(insert-into-avl-tree node all-nodes :key #'id))
(when (and *maintain-old-nodes-p* (old-p node))
(push node old-nodes)))
(activate-node abox node)
(when (or (old-p node)
(root-p node)
(not (is-abox1-p abox)))
(unless node-table
(setf node-table
(make-weak-hash-table :size 10 :rehash-size 100)))
(call-next-method)))))
(defmethod create-edge ((abox abox)
(from abox-node) (to abox-node)
(description edge-label)
&rest args
&key
(old-p t)
depends-on created-by
(new-choice-point 0)
&allow-other-keys)
(let ((*start-time* (get-internal-run-time)))
(let ((created-by (or created-by depends-on))
(edge (apply #'call-next-method abox from to
description
:created-by created-by
:old-p old-p
args)))
(unless *dont-invalidate-store-p*
(note-abox-has-changed abox)
(reset-sat-status from)
(reset-sat-status to)
( reset - sat - status ( concept - store ( ) ) )
)
Adresse verwalten
(incf (slot-value from 'succ-counter))
(setf (slot-value to 'address)
(cons (slot-value from 'succ-counter)
(slot-value from 'address)))
(setf (slot-value to 'rev-address)
(reverse (slot-value to 'address)))
(apply #'register-as-unexpanded edge
:new-choice-point new-choice-point
args)
(when (inverse-edge edge)
(apply #'register-as-unexpanded (inverse-edge edge)
:new-choice-point new-choice-point
args))
(when created-by
(let ((created-by
(if (eq created-by t)
nil
created-by)))
(register-action create
created-by
edge)
(when (and (inverse-edge edge)
(not (eq (inverse-edge edge) edge)))
(register-action create
created-by
(inverse-edge edge)))))
(incf *time-for-edge-creation*
(- (get-internal-run-time)
*start-time*))
edge)))
(defmethod register-edge ((edge abox-edge))
(let ((abox (in-graph edge))
(from (from edge))
(to (to edge)))
(with-slots (all-edges edge-table) abox
(when (is-abox1-p abox)
(unless (cdr (outgoing from))
(setf (slot-value abox 'leaf-nodes)
(delete from (slot-value abox 'leaf-nodes))))
(if (not *use-avl-trees-for-abox1-p*)
(push edge all-edges)
(insert-into-avl-tree edge all-edges :key #'id)))
(if (or (old-p edge)
(not (is-abox1-p abox)))
(progn
(unless edge-table
(setf edge-table
(make-weak-hash-table :size 10 :rehash-size 100 :test #'equal)))
(call-next-method))
(progn
(push to (slot-value from 'successors))
(push from (slot-value to 'predecessors))
(push edge (slot-value from 'outgoing))
(push edge (slot-value to 'incoming)))))))
(defmethod relate ((from abox-node) (to abox-node) (description edge-label) &rest args)
(apply #'create-edge *cur-abox* from to description args))
(defmethod relate ((from abox-node) (to abox-node) role &rest args
&key description-type
&allow-other-keys)
(let* ((descr (make-edge-description
(or description-type
(get-standard-edge-description-class *cur-abox*)) role))
(role (textual-description descr)))
(declare (ignorable role))
(apply #'create-edge *cur-abox* from to descr args)))
(defmethod relate ((from symbol) (to symbol) role
&rest args &key (create-nodes-p t)
(node-type (get-standard-node-class *cur-abox*)) &allow-other-keys)
(apply #'relate
(or (apply #'find-node *cur-abox* from :error-p nil args)
(when create-nodes-p
(apply #'create-abox-node *cur-abox* from :type node-type args)))
(or (apply #'find-node *cur-abox* to :error-p nil args)
(when create-nodes-p
(apply #'create-abox-node *cur-abox* to :type node-type args)))
role
args))
(defmethod unrelate ((from abox-node) (to abox-node) role &rest args)
(unless (eq (in-graph from)
(in-graph to))
(error "Individuals must be in same ABox!"))
(let* ((abox (in-graph from))
(role (parse-role role))
(edges
(remove-if-not #'(lambda (edge)
(eq (role edge) role))
(apply #'get-edges-between abox from to args))))
(dolist (edge edges)
(apply #'delete-edge abox edge
:update-db-p t
args))))
(defmethod unrelate ((from symbol) (to symbol) role &rest args)
(apply #'unrelate
(apply #'find-node *cur-abox* from :error-p t args)
(apply #'find-node *cur-abox* to :error-p t args)
(parse-role role)
args))
(defun create-anonymous-node (abox &rest args)
(incf *created-nodes*)
(apply #'create-abox-node abox nil :old-p nil args))
|
17756f8728fe4c6b2b6c1b7b541b7fde46d1d4a22dd00d298be14fff46019ee4 | borkdude/aoc2017 | template.clj | (ns template
(:require
[clojure.edn :as edn]
[clojure.string :as str]
[criterium.core :refer [quick-bench]]
[util :refer [resource-reducible
parse-int find-first]]))
(defn data
[])
(defn part-1
[])
(defn part-2
[])
;;;; Scratch
(comment
(set! *print-length* 20)
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(time (part-1))
(time (part-2))
(quick-bench (part-2))
)
| null | https://raw.githubusercontent.com/borkdude/aoc2017/0f5bce5e496d65d0e53a8983e71ea3462aa0569c/src/template.clj | clojure | Scratch | (ns template
(:require
[clojure.edn :as edn]
[clojure.string :as str]
[criterium.core :refer [quick-bench]]
[util :refer [resource-reducible
parse-int find-first]]))
(defn data
[])
(defn part-1
[])
(defn part-2
[])
(comment
(set! *print-length* 20)
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(time (part-1))
(time (part-2))
(quick-bench (part-2))
)
|
edfe7079b2281d61e42bf8c017e2d67653ac07b605a02fa67f5cc31476bd76b1 | ghcjs/ghcjs | Main.hs | From , Oct 99
This pretends to be the " fair " improved Cryptarithm solver test for
the performance comparison between Haskell and C++ .
--------------------------------------------------------------------
Compilation : g++ -O3 t.cc
ghc-4.04 -c -fvia - C -O2 -O2 - for - C t.hs
RESULTS : Platform1 - C++ is 15 times faster ,
Platform2 - 10 times faster ,
Platform1 : PC i-586 , Linux Debian
g++ version :
g++ -v says
` gcc version egcs-2.90.29 980515 ( egcs-1.0.3 release ) '
Platform2 : some machine with larger Cache .
I thank < >
for the improvements in the C++ program and for suggesting to use the
list comprehensions in ` permutations ' ( this saved another 10 - 15 % of
cost ) .
The test shows the performance ratio
CC++ / Haskell ( ghc-4.04 ) between 10 and 15
- it varies depending on the platform and other features .
It would be interesting to observe your running results , remarks ,
comparison to other systems .
What is the meaning of such test ?
Comparing what is better an orange or an apple ?
To my mind , this reflects the performance cost of the benefits of
a higher level , functional language .
And it is chosen an unlucky task example for .
The nature of this task is so that it allows to generate
permutations " in place " , by updating the C++ vector .
I expect the smaller ratio for other , " average " tasks .
And it is interesting , how the functional compiler of future might
optimize the below program . How essentially it could reduce the
cost ratio ?
--------------------------------------------------------------------
The Cryptarithm solver test was proposed to the e - mail list
by < >
on 17 September 1999 .
This is actually the test for the speed of the permutation
generator program .
spoke of the task of finding first permutation
satisfying certain equation .
And he compared the program with the C++ program that uses
the next_permutation library function .
This comparison was incorrect , because it was not known whether the
and C++ programs test the same number of permutations before
finding the solution . For , it was not known in what order
next_permutation generates the permutations .
------------------------------------------------------------------
Below follow the programs for the improved test :
find ALL the permutations on [ 0 .. 9 ] satisfying the condition
\[t , h , i , r , y , w , e , l , v , n ] - >
expand t h i r t y + 5 * expand t w e l v e = =
expand n i n e t y
where
expand a b c d e f = f + e*10 + d*100 + c*1000 + b*10000 + a*100000
------------------------------------------------------------------
The real difference makes only this " ALL " part :
all the permutations are tested - though only one satisfies the
condition .
The differences to the original programs are as follows .
* Both programs test each of 10 ! permutations .
* The below program seems to generate the permutations 2 - 3
times faster than the original program .
* The C++ program uses the loop
do { ... } while ( next_permutation ( ... ) )
to list the solutions ( it terminates when all the permutations
are listed ) .
One amazing point : consider the last equation of ` permutations ' :
... = ( j : k : ks ): [ ( k : aks ) | aks < - addj ks ]
Replacing it with ... ... : ( map ( k :) $ addj ks )
slows it down in 20 % in ghc-4.04 .
also tried Mercury , which showed somewhat higher
performance , especially , whith " memory recover by backtracking " .
Fergus , could you show the test results ?
I mean the final source program in Mercury , timings , platform ,
versions .
------------------
This pretends to be the "fair" improved Cryptarithm solver test for
the performance comparison between Haskell and C++.
--------------------------------------------------------------------
Compilation: g++ -O3 t.cc
ghc-4.04 -c -fvia-C -O2 -O2-for-C t.hs
RESULTS: Platform1 - C++ is 15 times faster,
Platform2 - 10 times faster,
Platform1: PC i-586, Linux Debian
g++ version:
g++ -v says
`gcc version egcs-2.90.29 980515 (egcs-1.0.3 release)'
Platform2: some machine with larger Cache.
I thank Fergus Henderson <>
for the improvements in the C++ program and for suggesting to use the
list comprehensions in `permutations' (this saved another 10-15% of
cost).
The test shows the performance ratio
CC++ / Haskell (ghc-4.04) between 10 and 15
- it varies depending on the platform and other features.
It would be interesting to observe your running results, remarks,
comparison to other systems.
What is the meaning of such test?
Comparing what is better an orange or an apple?
To my mind, this reflects the performance cost of the benefits of
a higher level, functional language.
And it is chosen an unlucky task example for Haskell.
The nature of this task is so that it allows to generate
permutations "in place", by updating the C++ vector.
I expect the smaller ratio for other, "average" tasks.
And it is interesting, how the functional compiler of future might
optimize the below program. How essentially it could reduce the
cost ratio?
--------------------------------------------------------------------
The Cryptarithm solver test was proposed to the Haskell e-mail list
by Mark Engelberg <>
on 17 September 1999.
This is actually the test for the speed of the permutation
generator program.
Mark Engelberg spoke of the task of finding first permutation
satisfying certain equation.
And he compared the Haskell program with the C++ program that uses
the next_permutation library function.
This comparison was incorrect, because it was not known whether the
Haskell and C++ programs test the same number of permutations before
finding the solution. For, it was not known in what order
next_permutation generates the permutations.
------------------------------------------------------------------
Below follow the programs for the improved test:
find ALL the permutations on [0..9] satisfying the condition
\[t,h,i,r,y,w,e,l,v,n] ->
expand t h i r t y + 5 * expand t w e l v e ==
expand n i n e t y
where
expand a b c d e f = f +e*10 +d*100 +c*1000 +b*10000 +a*100000
------------------------------------------------------------------
The real difference makes only this "ALL" part:
all the permutations are tested - though only one satisfies the
condition.
The differences to the original programs are as follows.
* Both programs test each of 10! permutations.
* The below Haskell program seems to generate the permutations 2-3
times faster than the original program.
* The C++ program uses the loop
do {...} while (next_permutation(...))
to list the solutions (it terminates when all the permutations
are listed).
One amazing point: consider the last equation of `permutations':
...= (j:k:ks): [(k:aks) | aks <- addj ks]
Replacing it with ... ... : (map (k:) $ addj ks)
slows it down in 20% in ghc-4.04.
Fergus Henderson also tried Mercury, which showed somewhat higher
performance, especially, whith "memory recover by backtracking".
Fergus, could you show the test results?
I mean the final source program in Mercury, timings, platform,
versions.
------------------
Sergey Mechveliani
-}
Haskell ---------------------------------------------------------
main = putStr $ shows (filter condition $ permutations p0) "\n"
where
p0 = [0..9] :: [Int]
condition [t,h,i,r,y,w,e,l,v,n] =
expand t h i r t y + 5 * expand t w e l v e ==
expand n i n e t y
expand a b c d e f = f + e*10 + d*100 + c*1000 + b*10000 + a*100000
:: Int
permutations :: [Int] -> [[Int]]
-- build the full permutation list given an ordered list
permutations [] = [[]]
permutations (j:js) = [r | pjs <- permutations js, r <- addj pjs]
where
addj [] = [[j]]
addj (k:ks) = (j:k:ks): [(k:aks) | aks <- addj ks]
-- C++ ------------------------------------------------------------
# include < vector >
# include < algorithm >
# include < iostream >
using namespace std ;
inline long expand ( long a , long b , long c , long d , long e , long f )
{
return f+10*e+100*d+1000*c+10000*b+100000*a ;
}
int main ( )
{
long t , h , i , r , y , w , e , l , v , n ;
long temp[10 ] = { 0,1,2,3,4,5,6,7,8,9 } ;
vector < long > x(temp , temp+10 ) ;
do
{ t = x[0 ] ; h = x[1 ] ; i = x[2 ] ; r = x[3 ] ; y = x[4 ] ;
w = x[5 ] ; e = x[6 ] ; l = x[7 ] ; v = x[8 ] ; n = x[9 ] ;
if ( expand(n , i , n , e , t , y ) = =
expand(t , h , i , r , t , y ) + 5*expand(t , w , e , l , v , e )
)
cout < < t < < h < < i < < r < < y < < w < < e < < l < < v < < n < < ' \n ' ;
}
while ( next_permutation(x.begin ( ) , x.end ( ) ) ) ;
cout < < " FINISHED\n " ;
}
-- C++ ------------------------------------------------------------
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
inline long expand (long a, long b, long c, long d, long e, long f)
{
return f+10*e+100*d+1000*c+10000*b+100000*a;
}
int main()
{
long t,h,i,r,y,w,e,l,v,n;
long temp[10] = {0,1,2,3,4,5,6,7,8,9};
vector<long> x(temp,temp+10);
do
{t = x[0]; h = x[1]; i = x[2]; r = x[3]; y = x[4];
w = x[5]; e = x[6]; l = x[7]; v = x[8]; n = x[9];
if (expand(n,i,n,e,t,y) ==
expand(t,h,i,r,t,y) + 5*expand(t,w,e,l,v,e)
)
cout << t << h << i << r << y << w << e << l << v << n << '\n';
}
while ( next_permutation(x.begin(), x.end()) );
cout << "FINISHED\n";
}
-}
| null | https://raw.githubusercontent.com/ghcjs/ghcjs/e4cd4232a31f6371c761acd93853702f4c7ca74c/test/nofib/spectral/cryptarithm1/Main.hs | haskell | ------------------------------------------------------------------
------------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
----------------
------------------------------------------------------------------
------------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
----------------
-------------------------------------------------------
build the full permutation list given an ordered list
C++ ------------------------------------------------------------
C++ ------------------------------------------------------------ | From , Oct 99
This pretends to be the " fair " improved Cryptarithm solver test for
the performance comparison between Haskell and C++ .
Compilation : g++ -O3 t.cc
ghc-4.04 -c -fvia - C -O2 -O2 - for - C t.hs
RESULTS : Platform1 - C++ is 15 times faster ,
Platform2 - 10 times faster ,
Platform1 : PC i-586 , Linux Debian
g++ version :
g++ -v says
` gcc version egcs-2.90.29 980515 ( egcs-1.0.3 release ) '
Platform2 : some machine with larger Cache .
I thank < >
for the improvements in the C++ program and for suggesting to use the
list comprehensions in ` permutations ' ( this saved another 10 - 15 % of
cost ) .
The test shows the performance ratio
CC++ / Haskell ( ghc-4.04 ) between 10 and 15
- it varies depending on the platform and other features .
It would be interesting to observe your running results , remarks ,
comparison to other systems .
What is the meaning of such test ?
Comparing what is better an orange or an apple ?
To my mind , this reflects the performance cost of the benefits of
a higher level , functional language .
And it is chosen an unlucky task example for .
The nature of this task is so that it allows to generate
permutations " in place " , by updating the C++ vector .
I expect the smaller ratio for other , " average " tasks .
And it is interesting , how the functional compiler of future might
optimize the below program . How essentially it could reduce the
cost ratio ?
The Cryptarithm solver test was proposed to the e - mail list
by < >
on 17 September 1999 .
This is actually the test for the speed of the permutation
generator program .
spoke of the task of finding first permutation
satisfying certain equation .
And he compared the program with the C++ program that uses
the next_permutation library function .
This comparison was incorrect , because it was not known whether the
and C++ programs test the same number of permutations before
finding the solution . For , it was not known in what order
next_permutation generates the permutations .
Below follow the programs for the improved test :
find ALL the permutations on [ 0 .. 9 ] satisfying the condition
\[t , h , i , r , y , w , e , l , v , n ] - >
expand t h i r t y + 5 * expand t w e l v e = =
expand n i n e t y
where
expand a b c d e f = f + e*10 + d*100 + c*1000 + b*10000 + a*100000
The real difference makes only this " ALL " part :
all the permutations are tested - though only one satisfies the
condition .
The differences to the original programs are as follows .
* Both programs test each of 10 ! permutations .
* The below program seems to generate the permutations 2 - 3
times faster than the original program .
* The C++ program uses the loop
do { ... } while ( next_permutation ( ... ) )
to list the solutions ( it terminates when all the permutations
are listed ) .
One amazing point : consider the last equation of ` permutations ' :
... = ( j : k : ks ): [ ( k : aks ) | aks < - addj ks ]
Replacing it with ... ... : ( map ( k :) $ addj ks )
slows it down in 20 % in ghc-4.04 .
also tried Mercury , which showed somewhat higher
performance , especially , whith " memory recover by backtracking " .
Fergus , could you show the test results ?
I mean the final source program in Mercury , timings , platform ,
versions .
This pretends to be the "fair" improved Cryptarithm solver test for
the performance comparison between Haskell and C++.
Compilation: g++ -O3 t.cc
ghc-4.04 -c -fvia-C -O2 -O2-for-C t.hs
RESULTS: Platform1 - C++ is 15 times faster,
Platform2 - 10 times faster,
Platform1: PC i-586, Linux Debian
g++ version:
g++ -v says
`gcc version egcs-2.90.29 980515 (egcs-1.0.3 release)'
Platform2: some machine with larger Cache.
I thank Fergus Henderson <>
for the improvements in the C++ program and for suggesting to use the
list comprehensions in `permutations' (this saved another 10-15% of
cost).
The test shows the performance ratio
CC++ / Haskell (ghc-4.04) between 10 and 15
- it varies depending on the platform and other features.
It would be interesting to observe your running results, remarks,
comparison to other systems.
What is the meaning of such test?
Comparing what is better an orange or an apple?
To my mind, this reflects the performance cost of the benefits of
a higher level, functional language.
And it is chosen an unlucky task example for Haskell.
The nature of this task is so that it allows to generate
permutations "in place", by updating the C++ vector.
I expect the smaller ratio for other, "average" tasks.
And it is interesting, how the functional compiler of future might
optimize the below program. How essentially it could reduce the
cost ratio?
The Cryptarithm solver test was proposed to the Haskell e-mail list
by Mark Engelberg <>
on 17 September 1999.
This is actually the test for the speed of the permutation
generator program.
Mark Engelberg spoke of the task of finding first permutation
satisfying certain equation.
And he compared the Haskell program with the C++ program that uses
the next_permutation library function.
This comparison was incorrect, because it was not known whether the
Haskell and C++ programs test the same number of permutations before
finding the solution. For, it was not known in what order
next_permutation generates the permutations.
Below follow the programs for the improved test:
find ALL the permutations on [0..9] satisfying the condition
\[t,h,i,r,y,w,e,l,v,n] ->
expand t h i r t y + 5 * expand t w e l v e ==
expand n i n e t y
where
expand a b c d e f = f +e*10 +d*100 +c*1000 +b*10000 +a*100000
The real difference makes only this "ALL" part:
all the permutations are tested - though only one satisfies the
condition.
The differences to the original programs are as follows.
* Both programs test each of 10! permutations.
* The below Haskell program seems to generate the permutations 2-3
times faster than the original program.
* The C++ program uses the loop
do {...} while (next_permutation(...))
to list the solutions (it terminates when all the permutations
are listed).
One amazing point: consider the last equation of `permutations':
...= (j:k:ks): [(k:aks) | aks <- addj ks]
Replacing it with ... ... : (map (k:) $ addj ks)
slows it down in 20% in ghc-4.04.
Fergus Henderson also tried Mercury, which showed somewhat higher
performance, especially, whith "memory recover by backtracking".
Fergus, could you show the test results?
I mean the final source program in Mercury, timings, platform,
versions.
Sergey Mechveliani
-}
main = putStr $ shows (filter condition $ permutations p0) "\n"
where
p0 = [0..9] :: [Int]
condition [t,h,i,r,y,w,e,l,v,n] =
expand t h i r t y + 5 * expand t w e l v e ==
expand n i n e t y
expand a b c d e f = f + e*10 + d*100 + c*1000 + b*10000 + a*100000
:: Int
permutations :: [Int] -> [[Int]]
permutations [] = [[]]
permutations (j:js) = [r | pjs <- permutations js, r <- addj pjs]
where
addj [] = [[j]]
addj (k:ks) = (j:k:ks): [(k:aks) | aks <- addj ks]
# include < vector >
# include < algorithm >
# include < iostream >
using namespace std ;
inline long expand ( long a , long b , long c , long d , long e , long f )
{
return f+10*e+100*d+1000*c+10000*b+100000*a ;
}
int main ( )
{
long t , h , i , r , y , w , e , l , v , n ;
long temp[10 ] = { 0,1,2,3,4,5,6,7,8,9 } ;
vector < long > x(temp , temp+10 ) ;
do
{ t = x[0 ] ; h = x[1 ] ; i = x[2 ] ; r = x[3 ] ; y = x[4 ] ;
w = x[5 ] ; e = x[6 ] ; l = x[7 ] ; v = x[8 ] ; n = x[9 ] ;
if ( expand(n , i , n , e , t , y ) = =
expand(t , h , i , r , t , y ) + 5*expand(t , w , e , l , v , e )
)
cout < < t < < h < < i < < r < < y < < w < < e < < l < < v < < n < < ' \n ' ;
}
while ( next_permutation(x.begin ( ) , x.end ( ) ) ) ;
cout < < " FINISHED\n " ;
}
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
inline long expand (long a, long b, long c, long d, long e, long f)
{
return f+10*e+100*d+1000*c+10000*b+100000*a;
}
int main()
{
long t,h,i,r,y,w,e,l,v,n;
long temp[10] = {0,1,2,3,4,5,6,7,8,9};
vector<long> x(temp,temp+10);
do
{t = x[0]; h = x[1]; i = x[2]; r = x[3]; y = x[4];
w = x[5]; e = x[6]; l = x[7]; v = x[8]; n = x[9];
if (expand(n,i,n,e,t,y) ==
expand(t,h,i,r,t,y) + 5*expand(t,w,e,l,v,e)
)
cout << t << h << i << r << y << w << e << l << v << n << '\n';
}
while ( next_permutation(x.begin(), x.end()) );
cout << "FINISHED\n";
}
-}
|
bd3f5513a862818a9f5a629a3f30184b130ec340fd149f99d6ea3f697147cdb4 | sonowz/advent-of-code-haskell | Day07.hs | module Y2019.Day07 where
import Relude
import Relude.Extra.Bifunctor
import Relude.Extra.CallStack
import Relude.Extra.Foldable1
import Relude.Extra.Map hiding ((!?))
import Relude.Extra.Newtype
import Relude.Extra.Tuple
import Relude.Unsafe ((!!))
import Data.Vector (Vector, (!?))
import qualified Data.Vector as V
import Data.Maybe (fromJust)
import qualified Data.List.NonEmpty as NE
import Control.Concurrent.Async
import Control.Concurrent.STM.TChan
import Control.Monad
import Lib.Types
import Lib.IO
import Lib.NonEmpty
-----------------------
-- Type declarations --
-----------------------
type Program = Vector Int
data ProgramLine
= P0 Opcode
| P1 Opcode Param
| P2 Opcode Param Param
| P3 Opcode Param Param Param
deriving (Show)
data Opcode = OpAdd | OpMul | OpHalt | OpInput | OpOutput | OpJumpTrue | OpJumpFalse | OpLT | OpE deriving (Show)
data Param = PImm Int | PAddr Addr deriving (Show)
newtype Addr = Addr Int deriving (Show) deriving (Num) via Int
type PC = Addr
parseProgramLine :: Program -> PC -> ProgramLine
parseProgramLine program (un -> i :: Int) = programLine where
programLine = case op of
1 -> P3 OpAdd p1 p2 p3
2 -> P3 OpMul p1 p2 p3
3 -> P1 OpInput p1
4 -> P1 OpOutput p1
5 -> P2 OpJumpTrue p1 p2
6 -> P2 OpJumpFalse p1 p2
7 -> P3 OpLT p1 p2 p3
8 -> P3 OpE p1 p2 p3
99 -> P0 OpHalt
_ -> error $ "program parse error: " <> show op
(modes, op) = parseInstruction $ program `V.unsafeIndex` i
p1 = modes !! 0 $ program `V.unsafeIndex` (i + 1)
p2 = modes !! 1 $ program `V.unsafeIndex` (i + 2)
p3 = modes !! 2 $ program `V.unsafeIndex` (i + 3)
parseInstruction ins = (modes, op) where
op = ins `mod` 100
modes = parseMode $ ins `div` 100
parseMode x
| x == 0 = repeat (PAddr . Addr)
| x `mod` 2 == 1 = PImm : parseMode (x `div` 10)
| x `mod` 2 == 0 = PAddr . Addr : parseMode (x `div` 10)
Emulates program I / O
data StdEnv = StdEnv IChan IChan
type IChan = TChan Int
readIn (StdEnv input output) = readTChan input
writeOut (StdEnv input output) = writeTChan output
------------
-- Part 1 --
------------
solve1 :: Program -> IO Int
solve1 program = maximum1 <$> outputs where
ne = fromJust . nonEmpty
(<<>>) = liftM2 (<>)
phaseSettings = ne $ ne <$> permutations [0 .. 4] :: NonEmpty (NonEmpty Int)
makeChannels phases =
(initIChan `mapM` phases) <<>> (one <$> newTChanIO) :: IO (NonEmpty IChan)
outputs = mapM (makeChannels >=> runAmplifiers program) phaseSettings :: IO (NonEmpty Int)
amplifier[i ] takes ichan[i ] as stdin , and ichan[i+1 ] as stdout
runAmplifiers :: Program -> NonEmpty IChan -> IO Int
runAmplifiers program ichans = runAmplifiers' where
runAmplifiers' = do
amplifiers <- forkAmplifier (toList ichans)
atomically $ writeTChan (head ichans) 0 -- input
waitAll amplifiers
atomically $ readTChan (last ichans) -- thruster output
waitAll [] = pass
waitAll asyncs = waitAny asyncs >>= \(x, _) -> waitAll (filter (/= x) asyncs)
forkAmplifier :: [IChan] -> IO [Async Program]
forkAmplifier (chan1 : chan2 : chans) = do
let stdenv = StdEnv chan1 chan2
newAmp <- async $ runReaderT (runProgram program (Addr 0)) stdenv
otherAmps <- forkAmplifier (chan2 : chans)
return $ newAmp : otherAmps
forkAmplifier _ = return []
initIChan :: Int -> IO IChan
initIChan phaseSetting = atomically $ do
chan <- newTChan
writeTChan chan phaseSetting
return chan
runProgram :: Program -> PC -> ReaderT StdEnv IO Program
runProgram program i = ask >>= program' where
program' inout = case parseProgramLine program i of
P3 OpAdd p1 p2 p3 -> runBinaryOp program (+) p1 p2 p3 & continueProgram 4
P3 OpMul p1 p2 p3 -> runBinaryOp program (*) p1 p2 p3 & continueProgram 4
P1 OpInput (PAddr addr) -> atomically (readIn inout) >>= continueProgram 2 . write addr
P1 OpOutput p1 -> atomically (writeOut inout $ value p1) >> continueProgram 2 program
P2 OpJumpTrue p1 p2 ->
if value p1 /= 0 then jumpProgram (value p2) program else continueProgram 3 program
P2 OpJumpFalse p1 p2 ->
if value p1 == 0 then jumpProgram (value p2) program else continueProgram 3 program
P3 OpLT p1 p2 (PAddr a3) ->
write a3 (if value p1 < value p2 then 1 else 0) & continueProgram 4
P3 OpE p1 p2 (PAddr a3) ->
write a3 (if value p1 == value p2 then 1 else 0) & continueProgram 4
P0 OpHalt -> return program
continueProgram n p = runProgram p (i + n)
jumpProgram n p = runProgram p (Addr n)
value = getParamValue program
write = writeValue program
runBinaryOp :: Program -> (Int -> Int -> Int) -> Param -> Param -> Param -> Program
runBinaryOp program f p1 p2 (PAddr a3) = program' where
v1 = getParamValue program p1
v2 = getParamValue program p2
v3 = v1 `f` v2
program' = writeValue program a3 v3
runBinaryOp _ _ _ _ _ = error "parameter 3 is not address"
getParamValue :: Program -> Param -> Int
getParamValue program (PAddr (Addr addr)) =
fromMaybe (error "program address error") $ program !? addr
getParamValue program (PImm imm) = imm
writeValue :: Program -> Addr -> Int -> Program
writeValue program (Addr addr) x = V.update program $ one (addr, x)
------------
Part 2 --
------------
solve2 :: Program -> IO Int
solve2 program = maximum1 <$> outputs where
ne = fromJust . nonEmpty
phaseSettings = ne $ ne <$> permutations [5 .. 9] :: NonEmpty (NonEmpty Int)
makeChannels phases = ntake 6 . NE.cycle <$> initIChan `mapM` phases :: IO (NonEmpty IChan)
outputs = mapM (makeChannels >=> runAmplifiers program) phaseSettings :: IO (NonEmpty Int)
--------------------
Main & Parsing --
--------------------
main' :: IO ()
main' = do
program <- parseProgram <$> readFile "inputs/Y2019/Day07.txt" :: IO Program
print =<< solve1 program
print =<< solve2 program
parseProgram :: String -> Program
parseProgram line = V.fromList $ map readInt textList
where textList = words . toText $ map (\c -> if c == ',' then ' ' else c) line
| null | https://raw.githubusercontent.com/sonowz/advent-of-code-haskell/6cec825c5172bbec687aab510e43832e6f2c0372/src/Y2019/Day07.hs | haskell | ---------------------
Type declarations --
---------------------
----------
Part 1 --
----------
input
thruster output
----------
----------
------------------
------------------ | module Y2019.Day07 where
import Relude
import Relude.Extra.Bifunctor
import Relude.Extra.CallStack
import Relude.Extra.Foldable1
import Relude.Extra.Map hiding ((!?))
import Relude.Extra.Newtype
import Relude.Extra.Tuple
import Relude.Unsafe ((!!))
import Data.Vector (Vector, (!?))
import qualified Data.Vector as V
import Data.Maybe (fromJust)
import qualified Data.List.NonEmpty as NE
import Control.Concurrent.Async
import Control.Concurrent.STM.TChan
import Control.Monad
import Lib.Types
import Lib.IO
import Lib.NonEmpty
type Program = Vector Int
data ProgramLine
= P0 Opcode
| P1 Opcode Param
| P2 Opcode Param Param
| P3 Opcode Param Param Param
deriving (Show)
data Opcode = OpAdd | OpMul | OpHalt | OpInput | OpOutput | OpJumpTrue | OpJumpFalse | OpLT | OpE deriving (Show)
data Param = PImm Int | PAddr Addr deriving (Show)
newtype Addr = Addr Int deriving (Show) deriving (Num) via Int
type PC = Addr
parseProgramLine :: Program -> PC -> ProgramLine
parseProgramLine program (un -> i :: Int) = programLine where
programLine = case op of
1 -> P3 OpAdd p1 p2 p3
2 -> P3 OpMul p1 p2 p3
3 -> P1 OpInput p1
4 -> P1 OpOutput p1
5 -> P2 OpJumpTrue p1 p2
6 -> P2 OpJumpFalse p1 p2
7 -> P3 OpLT p1 p2 p3
8 -> P3 OpE p1 p2 p3
99 -> P0 OpHalt
_ -> error $ "program parse error: " <> show op
(modes, op) = parseInstruction $ program `V.unsafeIndex` i
p1 = modes !! 0 $ program `V.unsafeIndex` (i + 1)
p2 = modes !! 1 $ program `V.unsafeIndex` (i + 2)
p3 = modes !! 2 $ program `V.unsafeIndex` (i + 3)
parseInstruction ins = (modes, op) where
op = ins `mod` 100
modes = parseMode $ ins `div` 100
parseMode x
| x == 0 = repeat (PAddr . Addr)
| x `mod` 2 == 1 = PImm : parseMode (x `div` 10)
| x `mod` 2 == 0 = PAddr . Addr : parseMode (x `div` 10)
Emulates program I / O
data StdEnv = StdEnv IChan IChan
type IChan = TChan Int
readIn (StdEnv input output) = readTChan input
writeOut (StdEnv input output) = writeTChan output
solve1 :: Program -> IO Int
solve1 program = maximum1 <$> outputs where
ne = fromJust . nonEmpty
(<<>>) = liftM2 (<>)
phaseSettings = ne $ ne <$> permutations [0 .. 4] :: NonEmpty (NonEmpty Int)
makeChannels phases =
(initIChan `mapM` phases) <<>> (one <$> newTChanIO) :: IO (NonEmpty IChan)
outputs = mapM (makeChannels >=> runAmplifiers program) phaseSettings :: IO (NonEmpty Int)
amplifier[i ] takes ichan[i ] as stdin , and ichan[i+1 ] as stdout
runAmplifiers :: Program -> NonEmpty IChan -> IO Int
runAmplifiers program ichans = runAmplifiers' where
runAmplifiers' = do
amplifiers <- forkAmplifier (toList ichans)
waitAll amplifiers
waitAll [] = pass
waitAll asyncs = waitAny asyncs >>= \(x, _) -> waitAll (filter (/= x) asyncs)
forkAmplifier :: [IChan] -> IO [Async Program]
forkAmplifier (chan1 : chan2 : chans) = do
let stdenv = StdEnv chan1 chan2
newAmp <- async $ runReaderT (runProgram program (Addr 0)) stdenv
otherAmps <- forkAmplifier (chan2 : chans)
return $ newAmp : otherAmps
forkAmplifier _ = return []
initIChan :: Int -> IO IChan
initIChan phaseSetting = atomically $ do
chan <- newTChan
writeTChan chan phaseSetting
return chan
runProgram :: Program -> PC -> ReaderT StdEnv IO Program
runProgram program i = ask >>= program' where
program' inout = case parseProgramLine program i of
P3 OpAdd p1 p2 p3 -> runBinaryOp program (+) p1 p2 p3 & continueProgram 4
P3 OpMul p1 p2 p3 -> runBinaryOp program (*) p1 p2 p3 & continueProgram 4
P1 OpInput (PAddr addr) -> atomically (readIn inout) >>= continueProgram 2 . write addr
P1 OpOutput p1 -> atomically (writeOut inout $ value p1) >> continueProgram 2 program
P2 OpJumpTrue p1 p2 ->
if value p1 /= 0 then jumpProgram (value p2) program else continueProgram 3 program
P2 OpJumpFalse p1 p2 ->
if value p1 == 0 then jumpProgram (value p2) program else continueProgram 3 program
P3 OpLT p1 p2 (PAddr a3) ->
write a3 (if value p1 < value p2 then 1 else 0) & continueProgram 4
P3 OpE p1 p2 (PAddr a3) ->
write a3 (if value p1 == value p2 then 1 else 0) & continueProgram 4
P0 OpHalt -> return program
continueProgram n p = runProgram p (i + n)
jumpProgram n p = runProgram p (Addr n)
value = getParamValue program
write = writeValue program
runBinaryOp :: Program -> (Int -> Int -> Int) -> Param -> Param -> Param -> Program
runBinaryOp program f p1 p2 (PAddr a3) = program' where
v1 = getParamValue program p1
v2 = getParamValue program p2
v3 = v1 `f` v2
program' = writeValue program a3 v3
runBinaryOp _ _ _ _ _ = error "parameter 3 is not address"
getParamValue :: Program -> Param -> Int
getParamValue program (PAddr (Addr addr)) =
fromMaybe (error "program address error") $ program !? addr
getParamValue program (PImm imm) = imm
writeValue :: Program -> Addr -> Int -> Program
writeValue program (Addr addr) x = V.update program $ one (addr, x)
solve2 :: Program -> IO Int
solve2 program = maximum1 <$> outputs where
ne = fromJust . nonEmpty
phaseSettings = ne $ ne <$> permutations [5 .. 9] :: NonEmpty (NonEmpty Int)
makeChannels phases = ntake 6 . NE.cycle <$> initIChan `mapM` phases :: IO (NonEmpty IChan)
outputs = mapM (makeChannels >=> runAmplifiers program) phaseSettings :: IO (NonEmpty Int)
main' :: IO ()
main' = do
program <- parseProgram <$> readFile "inputs/Y2019/Day07.txt" :: IO Program
print =<< solve1 program
print =<< solve2 program
parseProgram :: String -> Program
parseProgram line = V.fromList $ map readInt textList
where textList = words . toText $ map (\c -> if c == ',' then ' ' else c) line
|
6317889b5deb74c9e689cbeafcd957d69854431252fde53e7340a89c73d2aa04 | flowyourmoney/malli-ts | core.cljc | (ns malli-ts.core
(:require [malli-ts.ast :refer [->ast]]
[malli-ts.core-schema :as core-schemas]
[malli.core :as m]
[malli.registry :as mr]
[camel-snake-kebab.core :as csk]
[clojure.string :as string]
[clojure.set :as set]
#?(:cljs ["path" :as path])))
#?(:clj
(defn- get-path
[f]
(java.nio.file.Paths/get f (into-array String []))))
(defn- import-path-relative
[f1 f2]
(if-let [absolute (get f2 :absolute)]
absolute
(str "./"
#?(:cljs (path/relative (path/dirname f1) f2)
:clj (let [p1 (.resolve (get-path f1)
quick way to get the parent directory if import has .d.ts extension
(if-not (re-matches #"[.]" f1) ".." "."))
p2 (get-path f2)]
(.relativize p1 p2))))))
(defn- -schema-properties
[?schema options]
(if ?schema
(-> (if (= (m/type ?schema options) ::m/val)
(-> ?schema (m/children options) first)
?schema)
(m/properties options))
nil))
(defn- -dispatch-parse-ast-node
[node options]
(cond
(if-let [{:keys [schema]} node]
(-> schema (-schema-properties options) ::external-type)
nil)
:external-type
(not (some? node)) :nil-node
(:$ref node) :$ref
(:type node) [:type (:type node)]
(:union node) :union
(:intersection node) :intersection
(some? (:const node)) :const
:else [:type :any]))
(defmulti ^:private -parse-ast-node
#'-dispatch-parse-ast-node)
(defn parse-ast-node
([node options]
(-parse-ast-node node options))
([node]
(-parse-ast-node node {})))
(defmethod -parse-ast-node :$ref
[{:keys [$ref] :as node} {:keys [deref-type
schema-id->type-options
files-import-alias*
file-imports*
file]
:as options}]
(if (or (= deref-type $ref) (not (get schema-id->type-options $ref)))
(-parse-ast-node
(or (get-in node [:definitions $ref])
(->ast (:schema node)))
(dissoc options :deref-type))
(let [ref-file (get-in schema-id->type-options [$ref :file])
import-alias (or (get @files-import-alias* ref-file)
(get
(swap!
files-import-alias* assoc ref-file
(as-> ref-file $
(string/split $ #"[./]")
(if (= (take-last 2 $) ["d" "ts"])
(drop-last 2 $)
$)
(string/join "_" $)))
ref-file))
ref-type-name (get-in schema-id->type-options [$ref :t-name])
same-file? (= file ref-file)]
(when-not same-file?
(swap! file-imports* update file set/union #{ref-file}))
(str (if-not same-file? (str import-alias ".") nil) ref-type-name))))
(defmethod -parse-ast-node [:type :number] [_ _] "number")
(defmethod -parse-ast-node [:type :string] [_ _] "string")
(defmethod -parse-ast-node [:type :boolean] [_ _] "boolean")
(defmethod -parse-ast-node [:type :date] [_ _] "Date")
(defmethod -parse-ast-node [:type :any] [_ _] "any")
(defmethod -parse-ast-node [:type :undefined] [_ _] "undefined")
(defmethod -parse-ast-node :const [{:keys [const]} options]
(cond
(keyword? const) (str \" (name const) \")
(string? const) (str \" const \")
(some #(% const) [boolean? number?]) (str const)
:else (-parse-ast-node {:type :any} options)))
(defmethod -parse-ast-node [:type :array] [{:keys [items]} options]
(str "Array<" (-parse-ast-node items options) ">"))
(comment
(-parse-ast-node {:type :array :items {:type :number}} nil))
(defmethod -parse-ast-node [:type :tuple] [{:keys [items]} options]
(str "[" (string/join "," (map #(-parse-ast-node % options) items)) "]"))
(defmethod -parse-ast-node :union [{items :union} options]
(str "(" (string/join "|" (map #(-parse-ast-node % options) items)) ")"))
(defmethod -parse-ast-node :intersection [{items :intersection} options]
(str "(" (string/join "&" (map #(-parse-ast-node % options) items)) ")"))
(defmethod -parse-ast-node [:type :object] [{:keys [properties
index-signature]}
options]
(let [idx-sign-literal (if index-signature
(str "[k:" (-parse-ast-node (first index-signature) options) "]:"
(-parse-ast-node (second index-signature) options))
nil)
properties-literal (if-not (empty? properties)
(string/join
","
(map (fn [[k [v opts]]]
(let [property-name (name k)]
(str \" property-name \"
(if (:optional opts) "?" nil) ":"
(-parse-ast-node v options))))
properties))
nil)]
(str "{" (string/join "," (filter (comp not string/blank?)
[idx-sign-literal properties-literal]))
"}")))
(comment
(-parse-ast-node
(->ast [:map [:a :int] [:b {:optional true} :string]])
{})
(-parse-ast-node
(->ast [:map [:a :int] [:b {"optional" true} :string]])
{}))
(defmethod -parse-ast-node :external-type [{:keys [schema]}
{:keys [deref-type
file
files-import-alias*
file-imports*
schema-id->type-options]
:as options}]
(let [{:keys [::external-type ::t-path ::t-alias]} (-schema-properties schema options)
{:keys [external-type t-path t-alias]
:or {external-type external-type t-path t-path t-alias t-alias}}
(get schema-id->type-options deref-type)
t-path-str (or (:absolute t-path) t-path)
is-imported-already (if t-path-str (@file-imports* t-path) nil)
canonical-alias (if t-path-str (get @files-import-alias* t-path-str) nil)
import-alias (or canonical-alias
(cond
t-alias t-alias
t-path-str (as-> t-path-str $
(string/replace $ #"\.d\.ts" "")
(string/split $ #"[./]")
(string/join "-" $)
(csk/->snake_case $))
:else nil))]
(when (and t-path-str (not is-imported-already))
(swap! file-imports* update file set/union #{t-path}))
(when (and import-alias (not canonical-alias))
(swap! files-import-alias* assoc t-path-str import-alias))
(str (if import-alias (str import-alias ".") nil) external-type)))
(defn- letter-args
([letter-arg]
(if letter-arg
(let [letter-count (.substring letter-arg 1)
next-count (if-not (empty? letter-count)
(-> letter-count
#?(:cljs js/Number
:clj Integer/parseInt)
inc)
1)
char-code #?(:cljs (.charCodeAt letter-arg 0)
:clj (int (.charAt letter-arg 0)))
z? (= char-code 122)
next-letter (if-not z?
(let [next-char-code (inc char-code)]
#?(:cljs (.fromCharCode js/String next-char-code)
:clj (char next-char-code)))
"a")
next-letter-arg (str next-letter (if z? next-count letter-count))]
(cons next-letter-arg
(lazy-seq (letter-args next-letter-arg))))
(cons "a" (lazy-seq (letter-args "a")))))
([] (letter-args nil)))
(comment (->> (take 69 (letter-args)) (take-last 5)))
(defmethod -parse-ast-node [:type :=>] [{:keys [args ret]}
{:keys [args-names]
:as options}]
(let [args-type (get args :type)
args-items (get args :items)
args-names (cond
args-names args-names
(= args-type :catn) (map (fn [[n]] (csk/->camelCaseString n))
args-items)
:else (take (count args) (letter-args)))
args (if (= args-type :catn)
(map (fn [[_ a]] a) args-items)
args-items)]
(str "("
(string/join ", " (map (fn [arg-name arg]
(str arg-name ":" (-parse-ast-node arg options)))
args-names args))
") => " (-parse-ast-node ret options))))
(comment
(-parse-ast-node
(->ast [:=> [:cat :string :int] [:map [:a :int] [:b :string]]]) {}))
(defn import-literal
[from alias]
(str "import * as " alias " from " \' from \' \;))
(comment
#?(:cljs (import-literal
(path/relative (path/dirname "flow/person/index.d.ts") "flow/index.d.ts")
"flow")))
(defn ->type-declaration-str
[type-name literal jsdoc-literal options]
(let [{:keys [export declare]} options]
(str (if jsdoc-literal (str jsdoc-literal \newline) nil)
(if export "export " nil)
(if declare "var " "type ")
type-name (if declare ": " " = ") literal ";")))
(defn -dispatch-provide-jsdoc [jsdoc-k _ _ _] jsdoc-k)
(defmulti provide-jsdoc #'-dispatch-provide-jsdoc)
#_{:clj-kondo/ignore [:unused-binding]}
(defmethod provide-jsdoc ::schema
[jsdoc-k schema-id t-options options]
["schema" (binding [*print-namespace-maps* true] (-> schema-id (m/deref options) m/form str))])
(defn -jsdoc-literal
[jsdoc-pairs]
(if-not (empty? jsdoc-pairs)
(str "/**\n"
(->> jsdoc-pairs
(map (fn [[attribute value]] (str " * @" attribute " " value)))
(string/join "\n"))
"\n */")
nil))
(comment
(println (-jsdoc-literal [["schema" (str '[:map-of any?])]
["author" "Mr. Poopybutthole"]])))
(m/=> transform-parse-files-input-into-schema-id->type-options
[:=>
[:catn
[:file->schema-type-vectors core-schemas/file->schema-type-vectors]
[:options core-schemas/parse-files-options]]
core-schemas/schema-id->type-options])
(defn- transform-parse-files-input-into-schema-id->type-options
[file->schema-type-vectors options]
(reduce
(fn [m [file schema-type-vectors]]
(merge m (reduce
(fn [m schema-type-vector]
(let [[schema-id type-options] (if (seqable? schema-type-vector)
schema-type-vector
[schema-type-vector])
schema-type-options
(into {}
(comp
(filter (fn [[k _]] (= (namespace k) "malli-ts.core")))
(map (fn [[k v]] [(-> k name keyword) v])))
(m/properties (m/deref schema-id options)))
type-options (merge type-options
schema-type-options)
type-options (if-not (:t-name type-options)
(assoc type-options :t-name (csk/->snake_case (name schema-id)))
type-options)]
(assoc m schema-id (assoc type-options :file file))))
{} schema-type-vectors)))
{} file->schema-type-vectors))
(m/=> assoc-literals
[:=>
[:catn
[:file->schema-type-vectors core-schemas/file->schema-type-vectors]
[:options core-schemas/assoc-literals-options]]
core-schemas/schema-id->type-options])
(defn- assoc-literals
[file->schema-type-vectors
{:keys [schema-id->type-options jsdoc-default] :as options}]
(reduce
(fn [m [file schema-type-vectors]]
(reduce
(fn [m schema-type-vector]
(let [[schema-id type-options] (if (seqable? schema-type-vector)
schema-type-vector
[schema-type-vector])
{:keys [jsdoc] :as type-options} (merge type-options (get m schema-id))
literal
(-parse-ast-node
(->ast schema-id options)
(merge options
{:deref-type schema-id
:file file
:t-options type-options}))
jsdoc-literal
(->> (concat jsdoc-default jsdoc)
(map #(provide-jsdoc % schema-id type-options options))
-jsdoc-literal)]
(-> m
(assoc-in [schema-id :literal] literal)
(assoc-in [schema-id :jsdoc-literal] jsdoc-literal))))
m schema-type-vectors))
schema-id->type-options file->schema-type-vectors))
(m/=> aggregate-into-file-maps
[:=>
[:catn
[:file->schema-type-vectors core-schemas/file->schema-type-vectors]
[:options core-schemas/assoc-literals-options]]
[:catn
[:file->import-literals [:map-of string? [:sequential string?]]]
[:file->type-literals [:map-of string? [:sequential string?]]]]])
(defn- aggregate-into-file-maps
[file->schema-type-vectors
{:keys [schema-id->type-options export-default files-import-alias* file-imports*]}]
(reduce
(fn [[m-import m-type] [file scheva-type-vectors]]
[(assoc
m-import file
(sort (map
(fn [import-file]
(import-literal
(import-path-relative file import-file)
(get @files-import-alias* (or (:absolute import-file) import-file))))
(get @file-imports* file))))
(assoc
m-type file
(map
(fn [schema-type-vector]
(let [[schema-id _] (if (seqable? schema-type-vector)
schema-type-vector
[schema-type-vector])
{:keys [t-name literal jsdoc-literal export] :as t-options}
(get schema-id->type-options schema-id)
t-name (or t-name
(munge (name schema-id)))]
(->type-declaration-str
t-name literal jsdoc-literal
(merge t-options
{:export (if (some? export) export export-default)}))))
scheva-type-vectors))])
[{} {}] file->schema-type-vectors))
(m/=> parse-files
[:=>
[:catn
[:file->schema-type-vectors core-schemas/file->schema-type-vectors]
[:options core-schemas/assoc-literals-options]]
core-schemas/parse-files-return])
(defn parse-files
[file->schema-type-vectors options]
(let [{:keys [registry use-default-schemas files-import-alias]
:or {registry {}, use-default-schemas true, files-import-alias {}}} options
options (merge options {:registry (if use-default-schemas
(merge registry (m/default-schemas))
registry)})
schema-id->type-options
(transform-parse-files-input-into-schema-id->type-options
file->schema-type-vectors options)
;; Normalize symbols to strings
files-import-alias (into {} (map (fn [[k v]] [(str k) (str v)]) files-import-alias))
options (merge options {:schema-id->type-options schema-id->type-options
:file-imports* (atom {})
:files-import-alias* (atom files-import-alias)})
schema-id->type-options
(assoc-literals file->schema-type-vectors options)
options (assoc options :schema-id->type-options schema-id->type-options)
[file->import-literals file->type-literals]
(aggregate-into-file-maps file->schema-type-vectors options)
file-contents
(reduce (fn [m [file]]
(assoc
m (str file (if-not (re-matches #".*\.d\.ts$" file) ".d.ts" nil))
(let [import (string/join "\n" (get file->import-literals file))
types (string/join "\n" (get file->type-literals file))]
(str (if-not (string/blank? import) (str import "\n\n") nil)
types))))
{} file->schema-type-vectors)]
file-contents))
(defn parse-matching-schemas
"Only applicable to qualified schema-types and not defined in malli.core"
{:arglists '([options]
[pred options])}
([pred {:keys [registry transform] :as options}]
(let [schemas (into []
(comp (filter (fn [[k s]]
(and (qualified-keyword? k)
(not= "malli.core" (namespace k))
(pred k s))))
(map (fn [[k _]] [k {}]))
(map (or transform identity)))
(mr/schemas (mr/composite-registry registry m/default-registry)))
parse-files-arg (persistent!
(reduce
(fn [acc [k opts]]
(let [file-name (csk/->snake_case (namespace k))]
(if-let [asdf (get acc file-name)]
(assoc! acc file-name (conj asdf [k opts]))
(assoc! acc file-name [[k opts]]))))
(transient {}) schemas))]
(parse-files parse-files-arg options)))
([options]
(parse-matching-schemas (constantly true) options))
([]
(parse-matching-schemas (constantly true) {})))
(defn parse-ns-schemas
([ns-coll options]
(parse-matching-schemas
(let [ns-set (into #{} (map str) ns-coll)]
(fn [k _]
(let [k-ns (namespace k)]
(contains? ns-set k-ns))))
options))
([ns-coll]
(parse-ns-schemas ns-coll {})))
(defn external-type
[external-type-name & {:keys [import-path import-alias type-name schema]}]
(letfn [(?assoc [m k v] (if v (assoc m k v) m))]
[(or schema any?)
(-> (?assoc {} ::external-type external-type-name)
(?assoc ::t-name type-name)
(?assoc ::t-path (cond
(nil? import-path) nil
(map? import-path) import-path
:else {:absolute import-path}))
(?assoc ::t-alias import-alias))]))
| null | https://raw.githubusercontent.com/flowyourmoney/malli-ts/478b5dd190cbdc7a494c03e958ec65d53232441a/src/malli_ts/core.cljc | clojure | ))
Normalize symbols to strings | (ns malli-ts.core
(:require [malli-ts.ast :refer [->ast]]
[malli-ts.core-schema :as core-schemas]
[malli.core :as m]
[malli.registry :as mr]
[camel-snake-kebab.core :as csk]
[clojure.string :as string]
[clojure.set :as set]
#?(:cljs ["path" :as path])))
#?(:clj
(defn- get-path
[f]
(java.nio.file.Paths/get f (into-array String []))))
(defn- import-path-relative
[f1 f2]
(if-let [absolute (get f2 :absolute)]
absolute
(str "./"
#?(:cljs (path/relative (path/dirname f1) f2)
:clj (let [p1 (.resolve (get-path f1)
quick way to get the parent directory if import has .d.ts extension
(if-not (re-matches #"[.]" f1) ".." "."))
p2 (get-path f2)]
(.relativize p1 p2))))))
(defn- -schema-properties
[?schema options]
(if ?schema
(-> (if (= (m/type ?schema options) ::m/val)
(-> ?schema (m/children options) first)
?schema)
(m/properties options))
nil))
(defn- -dispatch-parse-ast-node
[node options]
(cond
(if-let [{:keys [schema]} node]
(-> schema (-schema-properties options) ::external-type)
nil)
:external-type
(not (some? node)) :nil-node
(:$ref node) :$ref
(:type node) [:type (:type node)]
(:union node) :union
(:intersection node) :intersection
(some? (:const node)) :const
:else [:type :any]))
(defmulti ^:private -parse-ast-node
#'-dispatch-parse-ast-node)
(defn parse-ast-node
([node options]
(-parse-ast-node node options))
([node]
(-parse-ast-node node {})))
(defmethod -parse-ast-node :$ref
[{:keys [$ref] :as node} {:keys [deref-type
schema-id->type-options
files-import-alias*
file-imports*
file]
:as options}]
(if (or (= deref-type $ref) (not (get schema-id->type-options $ref)))
(-parse-ast-node
(or (get-in node [:definitions $ref])
(->ast (:schema node)))
(dissoc options :deref-type))
(let [ref-file (get-in schema-id->type-options [$ref :file])
import-alias (or (get @files-import-alias* ref-file)
(get
(swap!
files-import-alias* assoc ref-file
(as-> ref-file $
(string/split $ #"[./]")
(if (= (take-last 2 $) ["d" "ts"])
(drop-last 2 $)
$)
(string/join "_" $)))
ref-file))
ref-type-name (get-in schema-id->type-options [$ref :t-name])
same-file? (= file ref-file)]
(when-not same-file?
(swap! file-imports* update file set/union #{ref-file}))
(str (if-not same-file? (str import-alias ".") nil) ref-type-name))))
(defmethod -parse-ast-node [:type :number] [_ _] "number")
(defmethod -parse-ast-node [:type :string] [_ _] "string")
(defmethod -parse-ast-node [:type :boolean] [_ _] "boolean")
(defmethod -parse-ast-node [:type :date] [_ _] "Date")
(defmethod -parse-ast-node [:type :any] [_ _] "any")
(defmethod -parse-ast-node [:type :undefined] [_ _] "undefined")
(defmethod -parse-ast-node :const [{:keys [const]} options]
(cond
(keyword? const) (str \" (name const) \")
(string? const) (str \" const \")
(some #(% const) [boolean? number?]) (str const)
:else (-parse-ast-node {:type :any} options)))
(defmethod -parse-ast-node [:type :array] [{:keys [items]} options]
(str "Array<" (-parse-ast-node items options) ">"))
(comment
(-parse-ast-node {:type :array :items {:type :number}} nil))
(defmethod -parse-ast-node [:type :tuple] [{:keys [items]} options]
(str "[" (string/join "," (map #(-parse-ast-node % options) items)) "]"))
(defmethod -parse-ast-node :union [{items :union} options]
(str "(" (string/join "|" (map #(-parse-ast-node % options) items)) ")"))
(defmethod -parse-ast-node :intersection [{items :intersection} options]
(str "(" (string/join "&" (map #(-parse-ast-node % options) items)) ")"))
(defmethod -parse-ast-node [:type :object] [{:keys [properties
index-signature]}
options]
(let [idx-sign-literal (if index-signature
(str "[k:" (-parse-ast-node (first index-signature) options) "]:"
(-parse-ast-node (second index-signature) options))
nil)
properties-literal (if-not (empty? properties)
(string/join
","
(map (fn [[k [v opts]]]
(let [property-name (name k)]
(str \" property-name \"
(if (:optional opts) "?" nil) ":"
(-parse-ast-node v options))))
properties))
nil)]
(str "{" (string/join "," (filter (comp not string/blank?)
[idx-sign-literal properties-literal]))
"}")))
(comment
(-parse-ast-node
(->ast [:map [:a :int] [:b {:optional true} :string]])
{})
(-parse-ast-node
(->ast [:map [:a :int] [:b {"optional" true} :string]])
{}))
(defmethod -parse-ast-node :external-type [{:keys [schema]}
{:keys [deref-type
file
files-import-alias*
file-imports*
schema-id->type-options]
:as options}]
(let [{:keys [::external-type ::t-path ::t-alias]} (-schema-properties schema options)
{:keys [external-type t-path t-alias]
:or {external-type external-type t-path t-path t-alias t-alias}}
(get schema-id->type-options deref-type)
t-path-str (or (:absolute t-path) t-path)
is-imported-already (if t-path-str (@file-imports* t-path) nil)
canonical-alias (if t-path-str (get @files-import-alias* t-path-str) nil)
import-alias (or canonical-alias
(cond
t-alias t-alias
t-path-str (as-> t-path-str $
(string/replace $ #"\.d\.ts" "")
(string/split $ #"[./]")
(string/join "-" $)
(csk/->snake_case $))
:else nil))]
(when (and t-path-str (not is-imported-already))
(swap! file-imports* update file set/union #{t-path}))
(when (and import-alias (not canonical-alias))
(swap! files-import-alias* assoc t-path-str import-alias))
(str (if import-alias (str import-alias ".") nil) external-type)))
(defn- letter-args
([letter-arg]
(if letter-arg
(let [letter-count (.substring letter-arg 1)
next-count (if-not (empty? letter-count)
(-> letter-count
#?(:cljs js/Number
:clj Integer/parseInt)
inc)
1)
char-code #?(:cljs (.charCodeAt letter-arg 0)
:clj (int (.charAt letter-arg 0)))
z? (= char-code 122)
next-letter (if-not z?
(let [next-char-code (inc char-code)]
#?(:cljs (.fromCharCode js/String next-char-code)
:clj (char next-char-code)))
"a")
next-letter-arg (str next-letter (if z? next-count letter-count))]
(cons next-letter-arg
(lazy-seq (letter-args next-letter-arg))))
(cons "a" (lazy-seq (letter-args "a")))))
([] (letter-args nil)))
(comment (->> (take 69 (letter-args)) (take-last 5)))
(defmethod -parse-ast-node [:type :=>] [{:keys [args ret]}
{:keys [args-names]
:as options}]
(let [args-type (get args :type)
args-items (get args :items)
args-names (cond
args-names args-names
(= args-type :catn) (map (fn [[n]] (csk/->camelCaseString n))
args-items)
:else (take (count args) (letter-args)))
args (if (= args-type :catn)
(map (fn [[_ a]] a) args-items)
args-items)]
(str "("
(string/join ", " (map (fn [arg-name arg]
(str arg-name ":" (-parse-ast-node arg options)))
args-names args))
") => " (-parse-ast-node ret options))))
(comment
(-parse-ast-node
(->ast [:=> [:cat :string :int] [:map [:a :int] [:b :string]]]) {}))
(defn import-literal
[from alias]
(comment
#?(:cljs (import-literal
(path/relative (path/dirname "flow/person/index.d.ts") "flow/index.d.ts")
"flow")))
(defn ->type-declaration-str
[type-name literal jsdoc-literal options]
(let [{:keys [export declare]} options]
(str (if jsdoc-literal (str jsdoc-literal \newline) nil)
(if export "export " nil)
(if declare "var " "type ")
type-name (if declare ": " " = ") literal ";")))
(defn -dispatch-provide-jsdoc [jsdoc-k _ _ _] jsdoc-k)
(defmulti provide-jsdoc #'-dispatch-provide-jsdoc)
#_{:clj-kondo/ignore [:unused-binding]}
(defmethod provide-jsdoc ::schema
[jsdoc-k schema-id t-options options]
["schema" (binding [*print-namespace-maps* true] (-> schema-id (m/deref options) m/form str))])
(defn -jsdoc-literal
[jsdoc-pairs]
(if-not (empty? jsdoc-pairs)
(str "/**\n"
(->> jsdoc-pairs
(map (fn [[attribute value]] (str " * @" attribute " " value)))
(string/join "\n"))
"\n */")
nil))
(comment
(println (-jsdoc-literal [["schema" (str '[:map-of any?])]
["author" "Mr. Poopybutthole"]])))
(m/=> transform-parse-files-input-into-schema-id->type-options
[:=>
[:catn
[:file->schema-type-vectors core-schemas/file->schema-type-vectors]
[:options core-schemas/parse-files-options]]
core-schemas/schema-id->type-options])
(defn- transform-parse-files-input-into-schema-id->type-options
[file->schema-type-vectors options]
(reduce
(fn [m [file schema-type-vectors]]
(merge m (reduce
(fn [m schema-type-vector]
(let [[schema-id type-options] (if (seqable? schema-type-vector)
schema-type-vector
[schema-type-vector])
schema-type-options
(into {}
(comp
(filter (fn [[k _]] (= (namespace k) "malli-ts.core")))
(map (fn [[k v]] [(-> k name keyword) v])))
(m/properties (m/deref schema-id options)))
type-options (merge type-options
schema-type-options)
type-options (if-not (:t-name type-options)
(assoc type-options :t-name (csk/->snake_case (name schema-id)))
type-options)]
(assoc m schema-id (assoc type-options :file file))))
{} schema-type-vectors)))
{} file->schema-type-vectors))
(m/=> assoc-literals
[:=>
[:catn
[:file->schema-type-vectors core-schemas/file->schema-type-vectors]
[:options core-schemas/assoc-literals-options]]
core-schemas/schema-id->type-options])
(defn- assoc-literals
[file->schema-type-vectors
{:keys [schema-id->type-options jsdoc-default] :as options}]
(reduce
(fn [m [file schema-type-vectors]]
(reduce
(fn [m schema-type-vector]
(let [[schema-id type-options] (if (seqable? schema-type-vector)
schema-type-vector
[schema-type-vector])
{:keys [jsdoc] :as type-options} (merge type-options (get m schema-id))
literal
(-parse-ast-node
(->ast schema-id options)
(merge options
{:deref-type schema-id
:file file
:t-options type-options}))
jsdoc-literal
(->> (concat jsdoc-default jsdoc)
(map #(provide-jsdoc % schema-id type-options options))
-jsdoc-literal)]
(-> m
(assoc-in [schema-id :literal] literal)
(assoc-in [schema-id :jsdoc-literal] jsdoc-literal))))
m schema-type-vectors))
schema-id->type-options file->schema-type-vectors))
(m/=> aggregate-into-file-maps
[:=>
[:catn
[:file->schema-type-vectors core-schemas/file->schema-type-vectors]
[:options core-schemas/assoc-literals-options]]
[:catn
[:file->import-literals [:map-of string? [:sequential string?]]]
[:file->type-literals [:map-of string? [:sequential string?]]]]])
(defn- aggregate-into-file-maps
[file->schema-type-vectors
{:keys [schema-id->type-options export-default files-import-alias* file-imports*]}]
(reduce
(fn [[m-import m-type] [file scheva-type-vectors]]
[(assoc
m-import file
(sort (map
(fn [import-file]
(import-literal
(import-path-relative file import-file)
(get @files-import-alias* (or (:absolute import-file) import-file))))
(get @file-imports* file))))
(assoc
m-type file
(map
(fn [schema-type-vector]
(let [[schema-id _] (if (seqable? schema-type-vector)
schema-type-vector
[schema-type-vector])
{:keys [t-name literal jsdoc-literal export] :as t-options}
(get schema-id->type-options schema-id)
t-name (or t-name
(munge (name schema-id)))]
(->type-declaration-str
t-name literal jsdoc-literal
(merge t-options
{:export (if (some? export) export export-default)}))))
scheva-type-vectors))])
[{} {}] file->schema-type-vectors))
(m/=> parse-files
[:=>
[:catn
[:file->schema-type-vectors core-schemas/file->schema-type-vectors]
[:options core-schemas/assoc-literals-options]]
core-schemas/parse-files-return])
(defn parse-files
[file->schema-type-vectors options]
(let [{:keys [registry use-default-schemas files-import-alias]
:or {registry {}, use-default-schemas true, files-import-alias {}}} options
options (merge options {:registry (if use-default-schemas
(merge registry (m/default-schemas))
registry)})
schema-id->type-options
(transform-parse-files-input-into-schema-id->type-options
file->schema-type-vectors options)
files-import-alias (into {} (map (fn [[k v]] [(str k) (str v)]) files-import-alias))
options (merge options {:schema-id->type-options schema-id->type-options
:file-imports* (atom {})
:files-import-alias* (atom files-import-alias)})
schema-id->type-options
(assoc-literals file->schema-type-vectors options)
options (assoc options :schema-id->type-options schema-id->type-options)
[file->import-literals file->type-literals]
(aggregate-into-file-maps file->schema-type-vectors options)
file-contents
(reduce (fn [m [file]]
(assoc
m (str file (if-not (re-matches #".*\.d\.ts$" file) ".d.ts" nil))
(let [import (string/join "\n" (get file->import-literals file))
types (string/join "\n" (get file->type-literals file))]
(str (if-not (string/blank? import) (str import "\n\n") nil)
types))))
{} file->schema-type-vectors)]
file-contents))
(defn parse-matching-schemas
"Only applicable to qualified schema-types and not defined in malli.core"
{:arglists '([options]
[pred options])}
([pred {:keys [registry transform] :as options}]
(let [schemas (into []
(comp (filter (fn [[k s]]
(and (qualified-keyword? k)
(not= "malli.core" (namespace k))
(pred k s))))
(map (fn [[k _]] [k {}]))
(map (or transform identity)))
(mr/schemas (mr/composite-registry registry m/default-registry)))
parse-files-arg (persistent!
(reduce
(fn [acc [k opts]]
(let [file-name (csk/->snake_case (namespace k))]
(if-let [asdf (get acc file-name)]
(assoc! acc file-name (conj asdf [k opts]))
(assoc! acc file-name [[k opts]]))))
(transient {}) schemas))]
(parse-files parse-files-arg options)))
([options]
(parse-matching-schemas (constantly true) options))
([]
(parse-matching-schemas (constantly true) {})))
(defn parse-ns-schemas
([ns-coll options]
(parse-matching-schemas
(let [ns-set (into #{} (map str) ns-coll)]
(fn [k _]
(let [k-ns (namespace k)]
(contains? ns-set k-ns))))
options))
([ns-coll]
(parse-ns-schemas ns-coll {})))
(defn external-type
[external-type-name & {:keys [import-path import-alias type-name schema]}]
(letfn [(?assoc [m k v] (if v (assoc m k v) m))]
[(or schema any?)
(-> (?assoc {} ::external-type external-type-name)
(?assoc ::t-name type-name)
(?assoc ::t-path (cond
(nil? import-path) nil
(map? import-path) import-path
:else {:absolute import-path}))
(?assoc ::t-alias import-alias))]))
|
d09bf0c6dd12dd31226e6ce6564ad52803b3f098e970c1be35d60b85f80a62e6 | haskell-foundation/foundation | Unix.hs | -- |
-- Module : Foundation.System.Entropy.Unix
-- License : BSD-style
Maintainer : < >
-- Stability : experimental
-- Portability : Good
--
# LANGUAGE ScopedTypeVariables #
# LANGUAGE ForeignFunctionInterface #
module Foundation.System.Entropy.Unix
( EntropyCtx
, entropyOpen
, entropyGather
, entropyClose
, entropyMaximumSize
) where
import Foreign.Ptr
import Control.Exception as E
import Control.Monad
import System.IO
import System.IO.Unsafe (unsafePerformIO)
import Basement.Compat.Base
import Basement.Compat.C.Types
import Prelude (fromIntegral)
import Foundation.System.Entropy.Common
import Foundation.Numerical
data EntropyCtx =
EntropyCtx Handle
| EntropySyscall
entropyOpen :: IO EntropyCtx
entropyOpen = do
if supportSyscall
then return EntropySyscall
else do
mh <- openDev "/dev/urandom"
case mh of
Nothing -> E.throwIO EntropySystemMissing
Just h -> return $ EntropyCtx h
| try to fill the ptr with the amount of data required .
-- Return the number of bytes, or a negative number otherwise
entropyGather :: EntropyCtx -> Ptr Word8 -> Int -> IO Bool
entropyGather (EntropyCtx h) ptr n = gatherDevEntropy h ptr n
entropyGather EntropySyscall ptr n = (==) 0 <$> c_sysrandom_linux ptr (fromIntegral n)
entropyClose :: EntropyCtx -> IO ()
entropyClose (EntropyCtx h) = hClose h
entropyClose EntropySyscall = return ()
entropyMaximumSize :: Int
entropyMaximumSize = 4096
openDev :: [Char] -> IO (Maybe Handle)
openDev filepath = (Just `fmap` openAndNoBuffering) `E.catch` \(_ :: IOException) -> return Nothing
where openAndNoBuffering = do
h <- openBinaryFile filepath ReadMode
hSetBuffering h NoBuffering
return h
gatherDevEntropy :: Handle -> Ptr Word8 -> Int -> IO Bool
gatherDevEntropy h ptr sz = loop ptr sz `E.catch` failOnException
where
loop _ 0 = return True
loop p n = do
r <- hGetBufSome h p n
if r >= 0
then loop (p `plusPtr` r) (n - r)
else return False
failOnException :: E.IOException -> IO Bool
failOnException _ = return False
supportSyscall :: Bool
supportSyscall = unsafePerformIO ((==) 0 <$> c_sysrandom_linux nullPtr 0)
# NOINLINE supportSyscall #
-- return 0 on success, !0 for failure
foreign import ccall unsafe "foundation_sysrandom_linux"
c_sysrandom_linux :: Ptr Word8 -> CSize -> IO Int
| null | https://raw.githubusercontent.com/haskell-foundation/foundation/58568e9f5368170d272000ecf16ef64fb91d0732/foundation/Foundation/System/Entropy/Unix.hs | haskell | |
Module : Foundation.System.Entropy.Unix
License : BSD-style
Stability : experimental
Portability : Good
Return the number of bytes, or a negative number otherwise
return 0 on success, !0 for failure | Maintainer : < >
# LANGUAGE ScopedTypeVariables #
# LANGUAGE ForeignFunctionInterface #
module Foundation.System.Entropy.Unix
( EntropyCtx
, entropyOpen
, entropyGather
, entropyClose
, entropyMaximumSize
) where
import Foreign.Ptr
import Control.Exception as E
import Control.Monad
import System.IO
import System.IO.Unsafe (unsafePerformIO)
import Basement.Compat.Base
import Basement.Compat.C.Types
import Prelude (fromIntegral)
import Foundation.System.Entropy.Common
import Foundation.Numerical
data EntropyCtx =
EntropyCtx Handle
| EntropySyscall
entropyOpen :: IO EntropyCtx
entropyOpen = do
if supportSyscall
then return EntropySyscall
else do
mh <- openDev "/dev/urandom"
case mh of
Nothing -> E.throwIO EntropySystemMissing
Just h -> return $ EntropyCtx h
| try to fill the ptr with the amount of data required .
entropyGather :: EntropyCtx -> Ptr Word8 -> Int -> IO Bool
entropyGather (EntropyCtx h) ptr n = gatherDevEntropy h ptr n
entropyGather EntropySyscall ptr n = (==) 0 <$> c_sysrandom_linux ptr (fromIntegral n)
entropyClose :: EntropyCtx -> IO ()
entropyClose (EntropyCtx h) = hClose h
entropyClose EntropySyscall = return ()
entropyMaximumSize :: Int
entropyMaximumSize = 4096
openDev :: [Char] -> IO (Maybe Handle)
openDev filepath = (Just `fmap` openAndNoBuffering) `E.catch` \(_ :: IOException) -> return Nothing
where openAndNoBuffering = do
h <- openBinaryFile filepath ReadMode
hSetBuffering h NoBuffering
return h
gatherDevEntropy :: Handle -> Ptr Word8 -> Int -> IO Bool
gatherDevEntropy h ptr sz = loop ptr sz `E.catch` failOnException
where
loop _ 0 = return True
loop p n = do
r <- hGetBufSome h p n
if r >= 0
then loop (p `plusPtr` r) (n - r)
else return False
failOnException :: E.IOException -> IO Bool
failOnException _ = return False
supportSyscall :: Bool
supportSyscall = unsafePerformIO ((==) 0 <$> c_sysrandom_linux nullPtr 0)
# NOINLINE supportSyscall #
foreign import ccall unsafe "foundation_sysrandom_linux"
c_sysrandom_linux :: Ptr Word8 -> CSize -> IO Int
|
535250a1ac6ed6204d028d719281000662a8b86521f3fa4723fdd81b7ecbbb1f | lexi-lambda/hackett | info.rkt | #lang info
(define collection 'multi)
(define deps
'(["base" #:version "7.0.0.2"]
"curly-fn-lib"
"data-lib"
"syntax-classes-lib"
"threading-lib"))
(define build-deps
'())
| null | https://raw.githubusercontent.com/lexi-lambda/hackett/e90ace9e4a056ec0a2a267f220cb29b756cbefce/hackett-lib/info.rkt | racket | #lang info
(define collection 'multi)
(define deps
'(["base" #:version "7.0.0.2"]
"curly-fn-lib"
"data-lib"
"syntax-classes-lib"
"threading-lib"))
(define build-deps
'())
|
|
203fe076db11709c245d9eff629e5028bc98d7b06bb9112634f56e5647b0a629 | comptekki/esysman | ecom.erl | Copyright ( c ) 2012 , < >
%% 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 "ESysMan" 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
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(ecom).
-export([start/0, rec_com/0]).
-include("ecom.hrl").
start() ->
register(rec_com, spawn(ecom, rec_com, [])).
rec_com() ->
{ok, [{MSG_TIMER}, {SERVERS}, {WEBCLIENTS}, {DOMAIN}, ConfVars]} = file:consult(?CONF),
receive
finished ->
io:format("finished~n", []);
{Box, Com, Args} ->
process_msg(SERVERS, WEBCLIENTS, ConfVars, Box, Com, Args),
rec_com()
after MSG_TIMER ->
send_msgt(SERVERS, WEBCLIENTS, DOMAIN, ConfVars),
rec_com()
end.
send_msgt([Server|Rest], WEBCLIENTS, DOMAIN, ConfVars) ->
msg_to_webclients(Server, WEBCLIENTS, DOMAIN, ConfVars),
send_msgt(Rest, WEBCLIENTS, DOMAIN, ConfVars);
send_msgt([], _, _, _) ->
[].
msg_to_webclients(Server, [WebClient|Rest], DOMAIN, ConfVars) ->
{WebClient, Server} ! {comp_name(ConfVars)++DOMAIN++"/pong",self()},
{WebClient, Server} ! {comp_name(ConfVars)++DOMAIN++"/loggedon/"++logged_on(ConfVars),self()},
msg_to_webclients(Server, Rest, DOMAIN, ConfVars);
msg_to_webclients(_Server, [], _, _) ->
[].
send_msg([Server|Rest], WEBCLIENTS, Msg) ->
msg_to_webclientsm(Server, WEBCLIENTS, Msg),
send_msg(Rest, WEBCLIENTS, Msg);
send_msg([], _, _Msg) ->
[].
msg_to_webclientsm(Server, [WebClient|Rest], Msg) ->
{WebClient, Server} ! Msg,
msg_to_webclientsm(Server, Rest, Msg);
msg_to_webclientsm(_Server, [], _Msg) ->
[].
process_msg(SERVERS, WEBCLIENTS, ConfVars, Box, Com, Args) ->
{DFC_DIR, DFC_PASSWD, ERL_DIR, UPLOADS_DIR, _, _, _, PLATFORM, WOLNAME, WOLLIST, BROADCAST_ADDR} = ConfVars,
io : format("~nBox : ~p - > Com : ~p - > args : ~p - > pid : ~p ~ n",[Box , Com , , self ( ) ] ) ,
case Com of
<<"com">> ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":com <- ",Args/binary>>),
case Args of
<<"mkuploads">> ->
os:cmd("mkdir "++UPLOADS_DIR),
case PLATFORM of
"w" -> ok;
_ ->
os:cmd("chmod 700 "++UPLOADS_DIR)
end,
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,(list_to_binary(":mkdir "++UPLOADS_DIR))/binary>>);
<<"anycmd">> ->
Res =
case PLATFORM of
"w" ->
list_to_binary(os:cmd(UPLOADS_DIR++"any.cmd"));
_ ->
list_to_binary(os:cmd("sh "++UPLOADS_DIR++"any.cmd"))
end,
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":anycmd - Results -> ", Res/binary>>);
<<"viewanycmd">> ->
Res =
case PLATFORM of
"w" ->
list_to_binary(os:cmd("type " ++UPLOADS_DIR++"any.cmd"));
_ ->
list_to_binary(os:cmd("cat "++UPLOADS_DIR++"any.cmd"))
end,
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":viewanycmd - Results -> ", Res/binary>>);
<<"listupfls">> ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary, (list_to_binary(":listupfls:<br>"++list_up_fls(ConfVars)))/binary>>);
<<"ninitecmd">> ->
case PLATFORM of
"w" ->
os:cmd(UPLOADS_DIR++"ninite.cmd"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":ninitecmd">>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"ninite">> ->
case PLATFORM of
"w" ->
Date=get_date(),
os:cmd(UPLOADS_DIR++"NiniteOne.exe /updateonly /exclude Python Edge /disableshortcuts /silent "++UPLOADS_DIR++"ninite_"++Date++"_log.txt"),
os:cmd("echo "++Date++" >> "++UPLOADS_DIR++"ninite_log.txt"),
os:cmd("type "++UPLOADS_DIR++"ninite_"++Date++"_log.txt >> "++UPLOADS_DIR++"ninite_log.txt"),
os:cmd("del /F /Q "++UPLOADS_DIR++"ninite_"++Date++"_log.txt"),
os:cmd("rmdir "++UPLOADS_DIR++"NiniteDownloads /S /Q"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary, (list_to_binary(":ninite date -> "++Date))/binary>>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"ninitelog">> ->
case PLATFORM of
"w" ->
{ok,Files}=file:list_dir(UPLOADS_DIR),
Log=get_files(Files, n, UPLOADS_DIR),
case size(Log) of
0 ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":no ninite logs">>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":ninitemlog -> ",Log/binary>>)
end;
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"unamea">> ->
case PLATFORM of
"x" ->
Res = os:cmd("/bin/uname -a"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,(list_to_binary(":unamea -> done..."))/binary, (fix_log(Res))/binary>>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"lsbra">> ->
case PLATFORM of
"x" ->
Res = os:cmd("/usr/bin/lsb_release -a"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":ubuntuver -> done...", (fix_log(Res))/binary>>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"aptcheck">> ->
case PLATFORM of
"x" ->
Res = os:cmd("/usr/bin/apt update; /usr/lib/update-notifier/apt-check --human-readable"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary, ":aptcheck -> done...", (fix_log(Res))/binary>>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary, ":error - no function on this platform...">>)
end;
<<"aptlistupgradable">> ->
case PLATFORM of
"x" ->
Res = os:cmd("/usr/bin/apt update; /usr/bin/apt list --upgradable"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary, ":aptlistupgradable -> done...", (fix_log(Res))/binary>>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary, ":error - no function on this platform...">>)
end;
<<"aptupgrade">> ->
case PLATFORM of
"x" ->
os:cmd("/usr/bin/apt-get update >"++UPLOADS_DIR++"aptu_log.txt;/usr/bin/apt-get -y upgrade >>"++UPLOADS_DIR++"aptu_log.txt"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,(list_to_binary(":aptupgrade -> done..."))/binary>>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"aptdistupgrade">> ->
case PLATFORM of
"x" ->
os:cmd("/usr/bin/apt-get update >"++UPLOADS_DIR++"aptu_log.txt;/usr/bin/apt-get -y dist-upgrade >>"++UPLOADS_DIR++"aptu_log.txt"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,(list_to_binary(":aptdistupgrade -> done..."))/binary>>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"aptupgrade-list">> ->
case PLATFORM of
"x" ->
os:cmd("/usr/bin/apt-get update >"++UPLOADS_DIR++"aptu_log.txt;/usr/bin/apt-get -s upgrade >>"++UPLOADS_DIR++"aptu_log.txt"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,(list_to_binary(":aptupgrade-list -> done..."))/binary>>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"aptdistupgrade-list">> ->
case PLATFORM of
"x" ->
os:cmd("/usr/bin/apt-get update >"++UPLOADS_DIR++"aptu_log.txt;/usr/bin/apt-get -s dist-upgrade >>"++UPLOADS_DIR++"aptu_log.txt"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,(list_to_binary(":aptdistupgrade-list -> done..."))/binary>>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"aptulog">> ->
case PLATFORM of
"x" ->
{ok,Files}=file:list_dir(UPLOADS_DIR),
Log=get_files(Files, a, UPLOADS_DIR),
case size(Log) of
0 ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":no apt update log ">>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":apt-update-log -> ",Log/binary>>)
end;
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"osxsupdate">> ->
case PLATFORM of
"m" ->
os:cmd("/usr/sbin/softwareupdate -ia >/tmp/uploads/osxsu_log.txt"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,(list_to_binary(":osxupdate -> "))/binary>>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"osxsulog">> ->
case PLATFORM of
"m" ->
{ok,Files}=file:list_dir(UPLOADS_DIR),
Log=get_files(Files, m, UPLOADS_DIR),
case size(Log) of
0 ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":no osx softwareupdate log ">>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":osx-softwareupdate-log -> ",Log/binary>>)
end;
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"wuinstall">> ->
case PLATFORM of
"w" ->
Date=get_date(),
os:cmd(UPLOADS_DIR++"wuinstall.exe /install /criteria \"IsInstalled=0 and Type='Software'\" >"++UPLOADS_DIR++"wui_"++Date++"_log.txt"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,(list_to_binary(":wuinstall date -> "++Date))/binary>>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"wuilog">> ->
case PLATFORM of
"w" ->
{ok,Files}=file:list_dir(UPLOADS_DIR),
Log=get_files(Files, w, UPLOADS_DIR),
case size(Log) of
0 ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":no wui logs">>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":wuilog -> ",Log/binary>>)
end;
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
WOLNAME ->
case PLATFORM of
"x" ->
list of addresses in different subnet
wol(WOLLIST, BROADCAST_ADDR),
io:format("~n done wol - ~p ~n",[Box]),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":",WOLNAME," -> ">>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
Unsupported -> Unsupported
end;
<<"loggedon">> ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,(list_to_binary(":loggedon:"++logged_on(ConfVars)))/binary>>);
<<"copy">> ->
{FileName, Data} = Args,
{ok, File} =
case FileName of
<<"ecom.beam">> ->
file:open(<<(list_to_binary(ERL_DIR))/binary,FileName/binary>>, [write]);
<<"ecom.conf">> ->
file:open(<<(list_to_binary(ERL_DIR))/binary,FileName/binary>>, [write]);
_ ->
file:open(<<(list_to_binary(UPLOADS_DIR))/binary,FileName/binary>>, [write])
end,
file:write(File,Data),
file:close(File),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":copied ",FileName/binary>>);
<<"dffreeze">> ->
case PLATFORM of
"w" ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":dffreeze">>),
os:cmd(DFC_DIR++" "++DFC_PASSWD++" /BOOTFROZEN");
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"dfthaw">> ->
case PLATFORM of
"w" ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":dfthaw">>),
os:cmd(DFC_DIR++" "++DFC_PASSWD++" /BOOTTHAWED");
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"dfstatus">> ->
case PLATFORM of
"w" ->
Output=os:cmd(ERL_DIR++"df-status.cmd"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,(list_to_binary(":dfstatus:"++string:left(Output,length(Output)-2)))/binary>>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"ping">> ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":pong">>);
<<"net_stop">> ->
init:stop(),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":net_stop">>);
<<"net_restart">> ->
init:restart(),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":net_restart">>);
<<"reboot">> ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary, ":reboot">>),
case PLATFORM of
"w" ->
os:cmd("shutdown -r -f -t 0");
_ ->
os:cmd("shutdown -r now")
end;
<<"shutdown">> ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":shutdown">>),
case PLATFORM of
"w" ->
os:cmd("shutdown -s -f -t 0");
_ ->
os:cmd("shutdown -h now")
end;
_ ->
send_msg(SERVERS, WEBCLIENTS, <<"Unknown command: '",Com/binary,"'">>)
end.
wol([MacAddr|Macs], BROADCAST_ADDR) ->
MacAddrBin= <<<<(list_to_integer(X, 16))>> || X <- string:tokens(MacAddr,"-")>>,
io:format("~nmac: ~p~n",[MacAddrBin]),
MagicPacket= << (dup(<<16#FF>>, 6))/binary, (dup(MacAddrBin, 16))/binary >>,
{ok,S} = gen_udp:open(0, [{broadcast, true}]),
gen_udp:send(S, BROADCAST_ADDR, 9, MagicPacket),
gen_udp:close(S),
wol(Macs, BROADCAST_ADDR);
wol([], _) ->
[].
dup(B,Acc) when Acc > 1 ->
B2=dup(B, Acc-1),
<< B/binary, B2/binary >>;
dup(B,1) ->
B.
get_files([File|Rest], T, UPLOADS_DIR) ->
case string:str(File,"log") of
0 ->
get_files(Rest, T, UPLOADS_DIR);
_ ->
case T of
a ->
case string:str(File,"apt") of
0 ->
get_files(Rest, T, UPLOADS_DIR);
_ ->
{ok,Log}=file:read_file(UPLOADS_DIR++File),
fix_log(Log)
end;
n ->
case string:str(File,"ninite") of
0 ->
get_files(Rest, T, UPLOADS_DIR);
_ ->
{ok,Log}=file:read_file(UPLOADS_DIR++File),
fix_log(Log)
end;
m ->
case string:str(File,"osxsu") of
0 ->
get_files(Rest, T, UPLOADS_DIR);
_ ->
{ok,Log}=file:read_file(UPLOADS_DIR++File),
fix_log(Log)
end;
w ->
case string:str(File,"wui") of
0 ->
get_files(Rest, T, UPLOADS_DIR);
_ ->
{ok,Log}=file:read_file(UPLOADS_DIR++File),
fix_log(Log)
end
end
end;
get_files([],_T, _) ->
<<>>.
fix_log(PreLog) ->
PostLog = case is_binary(PreLog) of
false ->
list_to_binary(PreLog);
_ ->
PreLog
end,
<<"<br><br>----------------------------------------<br>",
(binary:replace(binary:replace(binary:replace(PostLog, <<":">>, <<"-">>, [global]), <<"\n">>, <<"<br>">>, [global]), <<"\r">>, <<"">>, [global]))/binary,
"<br>----------------------------------------<br>">>.
get_date() ->
{Year,Month,Day}=date(),
{Hour,Min,Sec}=time(),
lists:flatten(io_lib:format("~p~2..0B~2..0B_~2..0B~2..0B~2..0B",[Year,Month,Day,Hour,Min,Sec])).
logged_on(ConfVars) ->
{_, _, _, _, USERS_DIR, USERS, _, PLATFORM, _, _, _} = ConfVars,
case PLATFORM of
"w" ->
case file:list_dir(USERS_DIR) of
{ok, UserDirs} -> get_user(UserDirs, PLATFORM, USERS);
{error, Reason} -> atom_to_list(Reason)
end;
_ ->
get_user(string:tokens(os:cmd("who"),"\n"), PLATFORM, USERS)
end.
get_user([UserInfo|Rest], PLATFORM, USERS) ->
case PLATFORM of
"w" ->
case lists:member(UserInfo, USERS) of
true ->
case Rest of
[] ->
[];
_ ->
get_user(Rest, PLATFORM, USERS)
end;
_ ->
case Rest of
[] ->
UserInfo;
_ ->
UserInfo++
case get_user(Rest, PLATFORM, USERS) of
[] ->
get_user(Rest, PLATFORM, USERS);
_ ->
"|"++get_user(Rest, PLATFORM, USERS)
end
end
end;
_ ->
User =
case string:tokens(UserInfo, " ") of
[Usert,_,_,_] ->
Usert;
[Usert,_,_,_,_] ->
Usert;
[Usert,_,_,_,_,_] ->
Usert
end,
case Rest of
[] ->
User;
_ ->
User++
case get_user(Rest, PLATFORM, USERS) of
[] ->
get_user(Rest, PLATFORM, USERS);
_ ->
"|"++get_user(Rest, PLATFORM, USERS)
end
end
end;
get_user([], _, _) ->
"".
comp_name(ConfVars) ->
{_, _, _, _, _, _, NODE_NAME, PLATFORM, _, _, _} = ConfVars,
case PLATFORM of
"w" ->
[NBName, _] = string:tokens(os:cmd("echo %computername%"), "\r"),
NODE_NAME ++ string:to_lower(NBName);
_ ->
[Hostname]=string:tokens(os:cmd("hostname -s"), "\n"),
NODE_NAME ++ Hostname
end.
list_up_fls(ConfVars) ->
{_, _, _, UPLOADS_DIR, _, _, _, _, _, _, _} = ConfVars,
{ok, Files}=file:list_dir(UPLOADS_DIR),
[ X++"<br>" || X <- Files].
| null | https://raw.githubusercontent.com/comptekki/esysman/2d6c9d0d2c3711d18e81beb933309e174d03d948/src/ecom.erl | erlang | 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 "ESysMan" nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
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 ) 2012 , < >
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN
-module(ecom).
-export([start/0, rec_com/0]).
-include("ecom.hrl").
start() ->
register(rec_com, spawn(ecom, rec_com, [])).
rec_com() ->
{ok, [{MSG_TIMER}, {SERVERS}, {WEBCLIENTS}, {DOMAIN}, ConfVars]} = file:consult(?CONF),
receive
finished ->
io:format("finished~n", []);
{Box, Com, Args} ->
process_msg(SERVERS, WEBCLIENTS, ConfVars, Box, Com, Args),
rec_com()
after MSG_TIMER ->
send_msgt(SERVERS, WEBCLIENTS, DOMAIN, ConfVars),
rec_com()
end.
send_msgt([Server|Rest], WEBCLIENTS, DOMAIN, ConfVars) ->
msg_to_webclients(Server, WEBCLIENTS, DOMAIN, ConfVars),
send_msgt(Rest, WEBCLIENTS, DOMAIN, ConfVars);
send_msgt([], _, _, _) ->
[].
msg_to_webclients(Server, [WebClient|Rest], DOMAIN, ConfVars) ->
{WebClient, Server} ! {comp_name(ConfVars)++DOMAIN++"/pong",self()},
{WebClient, Server} ! {comp_name(ConfVars)++DOMAIN++"/loggedon/"++logged_on(ConfVars),self()},
msg_to_webclients(Server, Rest, DOMAIN, ConfVars);
msg_to_webclients(_Server, [], _, _) ->
[].
send_msg([Server|Rest], WEBCLIENTS, Msg) ->
msg_to_webclientsm(Server, WEBCLIENTS, Msg),
send_msg(Rest, WEBCLIENTS, Msg);
send_msg([], _, _Msg) ->
[].
msg_to_webclientsm(Server, [WebClient|Rest], Msg) ->
{WebClient, Server} ! Msg,
msg_to_webclientsm(Server, Rest, Msg);
msg_to_webclientsm(_Server, [], _Msg) ->
[].
process_msg(SERVERS, WEBCLIENTS, ConfVars, Box, Com, Args) ->
{DFC_DIR, DFC_PASSWD, ERL_DIR, UPLOADS_DIR, _, _, _, PLATFORM, WOLNAME, WOLLIST, BROADCAST_ADDR} = ConfVars,
io : format("~nBox : ~p - > Com : ~p - > args : ~p - > pid : ~p ~ n",[Box , Com , , self ( ) ] ) ,
case Com of
<<"com">> ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":com <- ",Args/binary>>),
case Args of
<<"mkuploads">> ->
os:cmd("mkdir "++UPLOADS_DIR),
case PLATFORM of
"w" -> ok;
_ ->
os:cmd("chmod 700 "++UPLOADS_DIR)
end,
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,(list_to_binary(":mkdir "++UPLOADS_DIR))/binary>>);
<<"anycmd">> ->
Res =
case PLATFORM of
"w" ->
list_to_binary(os:cmd(UPLOADS_DIR++"any.cmd"));
_ ->
list_to_binary(os:cmd("sh "++UPLOADS_DIR++"any.cmd"))
end,
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":anycmd - Results -> ", Res/binary>>);
<<"viewanycmd">> ->
Res =
case PLATFORM of
"w" ->
list_to_binary(os:cmd("type " ++UPLOADS_DIR++"any.cmd"));
_ ->
list_to_binary(os:cmd("cat "++UPLOADS_DIR++"any.cmd"))
end,
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":viewanycmd - Results -> ", Res/binary>>);
<<"listupfls">> ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary, (list_to_binary(":listupfls:<br>"++list_up_fls(ConfVars)))/binary>>);
<<"ninitecmd">> ->
case PLATFORM of
"w" ->
os:cmd(UPLOADS_DIR++"ninite.cmd"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":ninitecmd">>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"ninite">> ->
case PLATFORM of
"w" ->
Date=get_date(),
os:cmd(UPLOADS_DIR++"NiniteOne.exe /updateonly /exclude Python Edge /disableshortcuts /silent "++UPLOADS_DIR++"ninite_"++Date++"_log.txt"),
os:cmd("echo "++Date++" >> "++UPLOADS_DIR++"ninite_log.txt"),
os:cmd("type "++UPLOADS_DIR++"ninite_"++Date++"_log.txt >> "++UPLOADS_DIR++"ninite_log.txt"),
os:cmd("del /F /Q "++UPLOADS_DIR++"ninite_"++Date++"_log.txt"),
os:cmd("rmdir "++UPLOADS_DIR++"NiniteDownloads /S /Q"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary, (list_to_binary(":ninite date -> "++Date))/binary>>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"ninitelog">> ->
case PLATFORM of
"w" ->
{ok,Files}=file:list_dir(UPLOADS_DIR),
Log=get_files(Files, n, UPLOADS_DIR),
case size(Log) of
0 ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":no ninite logs">>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":ninitemlog -> ",Log/binary>>)
end;
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"unamea">> ->
case PLATFORM of
"x" ->
Res = os:cmd("/bin/uname -a"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,(list_to_binary(":unamea -> done..."))/binary, (fix_log(Res))/binary>>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"lsbra">> ->
case PLATFORM of
"x" ->
Res = os:cmd("/usr/bin/lsb_release -a"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":ubuntuver -> done...", (fix_log(Res))/binary>>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"aptcheck">> ->
case PLATFORM of
"x" ->
Res = os:cmd("/usr/bin/apt update; /usr/lib/update-notifier/apt-check --human-readable"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary, ":aptcheck -> done...", (fix_log(Res))/binary>>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary, ":error - no function on this platform...">>)
end;
<<"aptlistupgradable">> ->
case PLATFORM of
"x" ->
Res = os:cmd("/usr/bin/apt update; /usr/bin/apt list --upgradable"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary, ":aptlistupgradable -> done...", (fix_log(Res))/binary>>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary, ":error - no function on this platform...">>)
end;
<<"aptupgrade">> ->
case PLATFORM of
"x" ->
os:cmd("/usr/bin/apt-get update >"++UPLOADS_DIR++"aptu_log.txt;/usr/bin/apt-get -y upgrade >>"++UPLOADS_DIR++"aptu_log.txt"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,(list_to_binary(":aptupgrade -> done..."))/binary>>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"aptdistupgrade">> ->
case PLATFORM of
"x" ->
os:cmd("/usr/bin/apt-get update >"++UPLOADS_DIR++"aptu_log.txt;/usr/bin/apt-get -y dist-upgrade >>"++UPLOADS_DIR++"aptu_log.txt"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,(list_to_binary(":aptdistupgrade -> done..."))/binary>>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"aptupgrade-list">> ->
case PLATFORM of
"x" ->
os:cmd("/usr/bin/apt-get update >"++UPLOADS_DIR++"aptu_log.txt;/usr/bin/apt-get -s upgrade >>"++UPLOADS_DIR++"aptu_log.txt"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,(list_to_binary(":aptupgrade-list -> done..."))/binary>>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"aptdistupgrade-list">> ->
case PLATFORM of
"x" ->
os:cmd("/usr/bin/apt-get update >"++UPLOADS_DIR++"aptu_log.txt;/usr/bin/apt-get -s dist-upgrade >>"++UPLOADS_DIR++"aptu_log.txt"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,(list_to_binary(":aptdistupgrade-list -> done..."))/binary>>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"aptulog">> ->
case PLATFORM of
"x" ->
{ok,Files}=file:list_dir(UPLOADS_DIR),
Log=get_files(Files, a, UPLOADS_DIR),
case size(Log) of
0 ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":no apt update log ">>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":apt-update-log -> ",Log/binary>>)
end;
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"osxsupdate">> ->
case PLATFORM of
"m" ->
os:cmd("/usr/sbin/softwareupdate -ia >/tmp/uploads/osxsu_log.txt"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,(list_to_binary(":osxupdate -> "))/binary>>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"osxsulog">> ->
case PLATFORM of
"m" ->
{ok,Files}=file:list_dir(UPLOADS_DIR),
Log=get_files(Files, m, UPLOADS_DIR),
case size(Log) of
0 ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":no osx softwareupdate log ">>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":osx-softwareupdate-log -> ",Log/binary>>)
end;
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"wuinstall">> ->
case PLATFORM of
"w" ->
Date=get_date(),
os:cmd(UPLOADS_DIR++"wuinstall.exe /install /criteria \"IsInstalled=0 and Type='Software'\" >"++UPLOADS_DIR++"wui_"++Date++"_log.txt"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,(list_to_binary(":wuinstall date -> "++Date))/binary>>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"wuilog">> ->
case PLATFORM of
"w" ->
{ok,Files}=file:list_dir(UPLOADS_DIR),
Log=get_files(Files, w, UPLOADS_DIR),
case size(Log) of
0 ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":no wui logs">>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":wuilog -> ",Log/binary>>)
end;
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
WOLNAME ->
case PLATFORM of
"x" ->
list of addresses in different subnet
wol(WOLLIST, BROADCAST_ADDR),
io:format("~n done wol - ~p ~n",[Box]),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":",WOLNAME," -> ">>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
Unsupported -> Unsupported
end;
<<"loggedon">> ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,(list_to_binary(":loggedon:"++logged_on(ConfVars)))/binary>>);
<<"copy">> ->
{FileName, Data} = Args,
{ok, File} =
case FileName of
<<"ecom.beam">> ->
file:open(<<(list_to_binary(ERL_DIR))/binary,FileName/binary>>, [write]);
<<"ecom.conf">> ->
file:open(<<(list_to_binary(ERL_DIR))/binary,FileName/binary>>, [write]);
_ ->
file:open(<<(list_to_binary(UPLOADS_DIR))/binary,FileName/binary>>, [write])
end,
file:write(File,Data),
file:close(File),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":copied ",FileName/binary>>);
<<"dffreeze">> ->
case PLATFORM of
"w" ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":dffreeze">>),
os:cmd(DFC_DIR++" "++DFC_PASSWD++" /BOOTFROZEN");
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"dfthaw">> ->
case PLATFORM of
"w" ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":dfthaw">>),
os:cmd(DFC_DIR++" "++DFC_PASSWD++" /BOOTTHAWED");
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"dfstatus">> ->
case PLATFORM of
"w" ->
Output=os:cmd(ERL_DIR++"df-status.cmd"),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,(list_to_binary(":dfstatus:"++string:left(Output,length(Output)-2)))/binary>>);
_ ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":error - no function on this platform...">>)
end;
<<"ping">> ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":pong">>);
<<"net_stop">> ->
init:stop(),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":net_stop">>);
<<"net_restart">> ->
init:restart(),
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":net_restart">>);
<<"reboot">> ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary, ":reboot">>),
case PLATFORM of
"w" ->
os:cmd("shutdown -r -f -t 0");
_ ->
os:cmd("shutdown -r now")
end;
<<"shutdown">> ->
send_msg(SERVERS, WEBCLIENTS, <<Box/binary,":shutdown">>),
case PLATFORM of
"w" ->
os:cmd("shutdown -s -f -t 0");
_ ->
os:cmd("shutdown -h now")
end;
_ ->
send_msg(SERVERS, WEBCLIENTS, <<"Unknown command: '",Com/binary,"'">>)
end.
wol([MacAddr|Macs], BROADCAST_ADDR) ->
MacAddrBin= <<<<(list_to_integer(X, 16))>> || X <- string:tokens(MacAddr,"-")>>,
io:format("~nmac: ~p~n",[MacAddrBin]),
MagicPacket= << (dup(<<16#FF>>, 6))/binary, (dup(MacAddrBin, 16))/binary >>,
{ok,S} = gen_udp:open(0, [{broadcast, true}]),
gen_udp:send(S, BROADCAST_ADDR, 9, MagicPacket),
gen_udp:close(S),
wol(Macs, BROADCAST_ADDR);
wol([], _) ->
[].
dup(B,Acc) when Acc > 1 ->
B2=dup(B, Acc-1),
<< B/binary, B2/binary >>;
dup(B,1) ->
B.
get_files([File|Rest], T, UPLOADS_DIR) ->
case string:str(File,"log") of
0 ->
get_files(Rest, T, UPLOADS_DIR);
_ ->
case T of
a ->
case string:str(File,"apt") of
0 ->
get_files(Rest, T, UPLOADS_DIR);
_ ->
{ok,Log}=file:read_file(UPLOADS_DIR++File),
fix_log(Log)
end;
n ->
case string:str(File,"ninite") of
0 ->
get_files(Rest, T, UPLOADS_DIR);
_ ->
{ok,Log}=file:read_file(UPLOADS_DIR++File),
fix_log(Log)
end;
m ->
case string:str(File,"osxsu") of
0 ->
get_files(Rest, T, UPLOADS_DIR);
_ ->
{ok,Log}=file:read_file(UPLOADS_DIR++File),
fix_log(Log)
end;
w ->
case string:str(File,"wui") of
0 ->
get_files(Rest, T, UPLOADS_DIR);
_ ->
{ok,Log}=file:read_file(UPLOADS_DIR++File),
fix_log(Log)
end
end
end;
get_files([],_T, _) ->
<<>>.
fix_log(PreLog) ->
PostLog = case is_binary(PreLog) of
false ->
list_to_binary(PreLog);
_ ->
PreLog
end,
<<"<br><br>----------------------------------------<br>",
(binary:replace(binary:replace(binary:replace(PostLog, <<":">>, <<"-">>, [global]), <<"\n">>, <<"<br>">>, [global]), <<"\r">>, <<"">>, [global]))/binary,
"<br>----------------------------------------<br>">>.
get_date() ->
{Year,Month,Day}=date(),
{Hour,Min,Sec}=time(),
lists:flatten(io_lib:format("~p~2..0B~2..0B_~2..0B~2..0B~2..0B",[Year,Month,Day,Hour,Min,Sec])).
logged_on(ConfVars) ->
{_, _, _, _, USERS_DIR, USERS, _, PLATFORM, _, _, _} = ConfVars,
case PLATFORM of
"w" ->
case file:list_dir(USERS_DIR) of
{ok, UserDirs} -> get_user(UserDirs, PLATFORM, USERS);
{error, Reason} -> atom_to_list(Reason)
end;
_ ->
get_user(string:tokens(os:cmd("who"),"\n"), PLATFORM, USERS)
end.
get_user([UserInfo|Rest], PLATFORM, USERS) ->
case PLATFORM of
"w" ->
case lists:member(UserInfo, USERS) of
true ->
case Rest of
[] ->
[];
_ ->
get_user(Rest, PLATFORM, USERS)
end;
_ ->
case Rest of
[] ->
UserInfo;
_ ->
UserInfo++
case get_user(Rest, PLATFORM, USERS) of
[] ->
get_user(Rest, PLATFORM, USERS);
_ ->
"|"++get_user(Rest, PLATFORM, USERS)
end
end
end;
_ ->
User =
case string:tokens(UserInfo, " ") of
[Usert,_,_,_] ->
Usert;
[Usert,_,_,_,_] ->
Usert;
[Usert,_,_,_,_,_] ->
Usert
end,
case Rest of
[] ->
User;
_ ->
User++
case get_user(Rest, PLATFORM, USERS) of
[] ->
get_user(Rest, PLATFORM, USERS);
_ ->
"|"++get_user(Rest, PLATFORM, USERS)
end
end
end;
get_user([], _, _) ->
"".
comp_name(ConfVars) ->
{_, _, _, _, _, _, NODE_NAME, PLATFORM, _, _, _} = ConfVars,
case PLATFORM of
"w" ->
[NBName, _] = string:tokens(os:cmd("echo %computername%"), "\r"),
NODE_NAME ++ string:to_lower(NBName);
_ ->
[Hostname]=string:tokens(os:cmd("hostname -s"), "\n"),
NODE_NAME ++ Hostname
end.
list_up_fls(ConfVars) ->
{_, _, _, UPLOADS_DIR, _, _, _, _, _, _, _} = ConfVars,
{ok, Files}=file:list_dir(UPLOADS_DIR),
[ X++"<br>" || X <- Files].
|
5def66377b5eab1d1b59fab1ad3bdff850f5787161ad912962909d2a8a065245 | dbuenzli/lit | demo.mli | ---------------------------------------------------------------------------
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%%
---------------------------------------------------------------------------*)
open Gg
open Lit
(** A few common, ad-hoc, tools for Lit's demos. *)
* { 1 Primitive cycler }
val prim_cycler :
?normals:bool -> ?prims:(Prim.t Lazy.t) list -> unit -> (unit -> Prim.t)
* { 1 Default commands }
type cmd =
[ `Init | `Exit | `Resize of size2 | `Tick of float
| `Toggle_fullscreen | `Cycle_prim | `None of Dapp.ev | `Move_in | `Move_out ]
val command_of_key : Dapp.keysym ->
[> `Toggle_fullscreen | `Cycle_prim | `Exit | `Move_in | `Move_out ] option
val event_to_command : Dapp.ev -> cmd
val ev_of_command_handler :
(Dapp.t -> [> cmd ] -> Dapp.ev_ret) -> Dapp.t -> Dapp.ev -> Dapp.ev_ret
val default_size : size2
* { 1 Terminal output }
val show_start : Lit.Renderer.t -> unit
(** [show_start r] prints basic information about [r] on [stdout]. *)
val show_stats : float -> ('a -> unit) -> 'a -> ('b -> unit) -> 'b -> unit
* [ show_stats t draw v update v ' ] calls and measures the time taken
by [ draw v ] and [ update v ' ] and uses the absolute time [ t ] to compute
the time between two calls to [ show_timings ] . All these timings
are reported by overwriting the last line of [ stdout ] .
by [draw v] and [update v'] and uses the absolute time [t] to compute
the time between two calls to [show_timings]. All these timings
are reported by overwriting the last line of [stdout]. *)
val show_stop : unit -> unit
(** [show_stop ()] just prints a final newline on [stdout]. *)
---------------------------------------------------------------------------
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/dbuenzli/lit/4058b8a133cd51d3bf756c66b9ab620e39e1d2c4/test/demo.mli | ocaml | * A few common, ad-hoc, tools for Lit's demos.
* [show_start r] prints basic information about [r] on [stdout].
* [show_stop ()] just prints a final newline on [stdout]. | ---------------------------------------------------------------------------
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%%
---------------------------------------------------------------------------*)
open Gg
open Lit
* { 1 Primitive cycler }
val prim_cycler :
?normals:bool -> ?prims:(Prim.t Lazy.t) list -> unit -> (unit -> Prim.t)
* { 1 Default commands }
type cmd =
[ `Init | `Exit | `Resize of size2 | `Tick of float
| `Toggle_fullscreen | `Cycle_prim | `None of Dapp.ev | `Move_in | `Move_out ]
val command_of_key : Dapp.keysym ->
[> `Toggle_fullscreen | `Cycle_prim | `Exit | `Move_in | `Move_out ] option
val event_to_command : Dapp.ev -> cmd
val ev_of_command_handler :
(Dapp.t -> [> cmd ] -> Dapp.ev_ret) -> Dapp.t -> Dapp.ev -> Dapp.ev_ret
val default_size : size2
* { 1 Terminal output }
val show_start : Lit.Renderer.t -> unit
val show_stats : float -> ('a -> unit) -> 'a -> ('b -> unit) -> 'b -> unit
* [ show_stats t draw v update v ' ] calls and measures the time taken
by [ draw v ] and [ update v ' ] and uses the absolute time [ t ] to compute
the time between two calls to [ show_timings ] . All these timings
are reported by overwriting the last line of [ stdout ] .
by [draw v] and [update v'] and uses the absolute time [t] to compute
the time between two calls to [show_timings]. All these timings
are reported by overwriting the last line of [stdout]. *)
val show_stop : unit -> unit
---------------------------------------------------------------------------
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.
---------------------------------------------------------------------------*)
|
7e352f32eb58b2e51ed0bd00a6cd633b67286e0c3f457e85676700a79ed420e2 | NorfairKing/easyspec | ToUpper.hs | # LANGUAGE NoImplicitPrelude #
module ToUpper where
import Data.Char (toUpper)
| null | https://raw.githubusercontent.com/NorfairKing/easyspec/b038b45a375cc0bed2b00c255b508bc06419c986/examples/toy/ToUpper.hs | haskell | # LANGUAGE NoImplicitPrelude #
module ToUpper where
import Data.Char (toUpper)
|
|
59fc0cbee77fdc1e82e25ad293d02279848b499c3ab8322368980be7a1c2fe90 | unclebob/AdventOfCode2022 | core.clj | (ns day12-hill-climing-algorithm.core
(:require [clojure.string :as string]))
(defn get-cell [grid [x y]]
(try
(-> grid (nth y) (nth x))
(catch Exception _e
"TILT")))
(defn get-bounds [grid]
[(count (first grid)) (count grid)])
(defn in-bounds [grid [x y]]
(let [[bx by] (get-bounds grid)]
(and
(< -1 x bx)
(< -1 y by))))
(defn ortho-from [grid [x y]]
(let [orthos [[x (dec y)]
[(inc x) y]
[x (inc y)]
[(dec x) y]]
orthos (filter (partial in-bounds grid) orthos)]
(set orthos)))
(defn parse-line [line]
(let [line (replace {\S \a \E \z} line)
line (map int line)
line (map #(- % (int \a)) line)]
line))
(defn find-in-lines [lines target]
(let [found (for [y (range (count lines)) x (range (count (first lines)))]
(if (= target (-> lines (nth y) (nth x)))
[x y]
nil))]
(first (remove nil? found)))
)
(defn parse-lines [lines]
(let [grid (map parse-line lines)
start (find-in-lines lines \S)
end (find-in-lines lines \E)]
[start end grid])
)
(defn make-height-map [file-name]
(let [lines (string/split-lines (slurp file-name))]
(parse-lines lines)))
(defn valid-climbing-step? [grid height pos]
(let [pos-height (get-cell grid pos)
diff (- pos-height height)]
(<= diff 1)))
(defn valid-descending-step? [grid height pos]
(let [pos-height (get-cell grid pos)
diff (- pos-height height)]
(>= diff -1)))
(defn possible-steps-while-climbing [grid pos]
(let [orthos (ortho-from grid pos)
height (get-cell grid pos)
steps (filter (partial valid-climbing-step? grid height) orthos)]
(set steps)))
(defn possible-steps-while-descending [grid pos]
(let [orthos (ortho-from grid pos)
height (get-cell grid pos)
steps (filter (partial valid-descending-step? grid height) orthos)]
(set steps)))
(defn distance [p1 p2]
(reduce + (map #(Math/abs ^int %) (map - p1 p2))))
(defn distance-3d [grid end step]
(let [distance-to-end (distance step end)
remaining-height (- 25 (get-cell grid step))]
(if (>= distance-to-end remaining-height)
distance-to-end
(+ distance-to-end (- remaining-height distance-to-end)))))
(defn prune-and-prioritize [end grid path shortest steps]
(let [steps (remove #(contains? (set path) %) steps)
max-distance (- (count shortest) (count path))
steps (remove #(> (distance % end) max-distance) steps)
distance-and-steps (map #(vector (distance-3d grid end %) %) steps)
sorted-by-distance (sort-by first distance-and-steps)]
(map second sorted-by-distance)))
(defn prune-path [path steps]
(let [steps (remove #(contains? (set path) %) steps)]
steps))
(defn make-shortest-map [grid max-path-length]
(let [[bx by] (get-bounds grid)
cell-positions (for [x (range bx) y (range by)] [x y])
shortest-map (apply hash-map (interleave cell-positions (repeat (* bx by) max-path-length)))]
shortest-map))
(defn find-shortest-path
([[start end grid]]
(let [shortest (atom (repeat 1000 0))
shortest-map (atom (make-shortest-map grid 1000))]
(find-shortest-path start end grid [start] shortest shortest-map)
@shortest))
([pos end grid path shortest shortest-map]
(let [path-length (count path)]
(when (< path-length (get @shortest-map pos))
(swap! shortest-map assoc pos path-length)
(cond
(= pos end)
(do
(prn path-length path)
(reset! shortest path))
(< path-length (count @shortest))
(let [steps (possible-steps-while-climbing grid pos)
prioritized-steps (prune-and-prioritize end grid path @shortest steps)]
(doseq [step prioritized-steps]
(find-shortest-path step end grid (conj path step) shortest shortest-map)))
:else
nil)))))
(defn shortest-path-length [file-name]
(let [height-map (parse-lines (string/split-lines (slurp file-name)))
shortest (find-shortest-path height-map)]
(dec (count shortest))))
(defn find-shortest-path-to-low-ground
([start grid]
(let [shortest (atom (repeat 1000 0))
shortest-map (atom (make-shortest-map grid 1000))]
(find-shortest-path-to-low-ground start grid [start] shortest shortest-map)
@shortest))
([pos grid path shortest shortest-map]
(let [path-length (count path)]
(when (< path-length (get @shortest-map pos))
(swap! shortest-map assoc pos path-length)
(cond
(zero? (get-cell grid pos))
(do
(prn path-length path)
(reset! shortest path))
(< path-length (count @shortest))
(let [steps (possible-steps-while-descending grid pos)
prioritized-steps (prune-path path steps)]
(doseq [step prioritized-steps]
(find-shortest-path-to-low-ground step grid (conj path step) shortest shortest-map)))
:else
nil)))))
(defn shortest-scenic-path [file-name]
(let [[_ end grid] (parse-lines (string/split-lines (slurp file-name)))
shortest (find-shortest-path-to-low-ground end grid)]
(dec (count shortest))))
| null | https://raw.githubusercontent.com/unclebob/AdventOfCode2022/f5eb954c336a547d56f6bc0efe3797d5884290ca/day12-hill-climing-algorithm/src/day12_hill_climing_algorithm/core.clj | clojure | (ns day12-hill-climing-algorithm.core
(:require [clojure.string :as string]))
(defn get-cell [grid [x y]]
(try
(-> grid (nth y) (nth x))
(catch Exception _e
"TILT")))
(defn get-bounds [grid]
[(count (first grid)) (count grid)])
(defn in-bounds [grid [x y]]
(let [[bx by] (get-bounds grid)]
(and
(< -1 x bx)
(< -1 y by))))
(defn ortho-from [grid [x y]]
(let [orthos [[x (dec y)]
[(inc x) y]
[x (inc y)]
[(dec x) y]]
orthos (filter (partial in-bounds grid) orthos)]
(set orthos)))
(defn parse-line [line]
(let [line (replace {\S \a \E \z} line)
line (map int line)
line (map #(- % (int \a)) line)]
line))
(defn find-in-lines [lines target]
(let [found (for [y (range (count lines)) x (range (count (first lines)))]
(if (= target (-> lines (nth y) (nth x)))
[x y]
nil))]
(first (remove nil? found)))
)
(defn parse-lines [lines]
(let [grid (map parse-line lines)
start (find-in-lines lines \S)
end (find-in-lines lines \E)]
[start end grid])
)
(defn make-height-map [file-name]
(let [lines (string/split-lines (slurp file-name))]
(parse-lines lines)))
(defn valid-climbing-step? [grid height pos]
(let [pos-height (get-cell grid pos)
diff (- pos-height height)]
(<= diff 1)))
(defn valid-descending-step? [grid height pos]
(let [pos-height (get-cell grid pos)
diff (- pos-height height)]
(>= diff -1)))
(defn possible-steps-while-climbing [grid pos]
(let [orthos (ortho-from grid pos)
height (get-cell grid pos)
steps (filter (partial valid-climbing-step? grid height) orthos)]
(set steps)))
(defn possible-steps-while-descending [grid pos]
(let [orthos (ortho-from grid pos)
height (get-cell grid pos)
steps (filter (partial valid-descending-step? grid height) orthos)]
(set steps)))
(defn distance [p1 p2]
(reduce + (map #(Math/abs ^int %) (map - p1 p2))))
(defn distance-3d [grid end step]
(let [distance-to-end (distance step end)
remaining-height (- 25 (get-cell grid step))]
(if (>= distance-to-end remaining-height)
distance-to-end
(+ distance-to-end (- remaining-height distance-to-end)))))
(defn prune-and-prioritize [end grid path shortest steps]
(let [steps (remove #(contains? (set path) %) steps)
max-distance (- (count shortest) (count path))
steps (remove #(> (distance % end) max-distance) steps)
distance-and-steps (map #(vector (distance-3d grid end %) %) steps)
sorted-by-distance (sort-by first distance-and-steps)]
(map second sorted-by-distance)))
(defn prune-path [path steps]
(let [steps (remove #(contains? (set path) %) steps)]
steps))
(defn make-shortest-map [grid max-path-length]
(let [[bx by] (get-bounds grid)
cell-positions (for [x (range bx) y (range by)] [x y])
shortest-map (apply hash-map (interleave cell-positions (repeat (* bx by) max-path-length)))]
shortest-map))
(defn find-shortest-path
([[start end grid]]
(let [shortest (atom (repeat 1000 0))
shortest-map (atom (make-shortest-map grid 1000))]
(find-shortest-path start end grid [start] shortest shortest-map)
@shortest))
([pos end grid path shortest shortest-map]
(let [path-length (count path)]
(when (< path-length (get @shortest-map pos))
(swap! shortest-map assoc pos path-length)
(cond
(= pos end)
(do
(prn path-length path)
(reset! shortest path))
(< path-length (count @shortest))
(let [steps (possible-steps-while-climbing grid pos)
prioritized-steps (prune-and-prioritize end grid path @shortest steps)]
(doseq [step prioritized-steps]
(find-shortest-path step end grid (conj path step) shortest shortest-map)))
:else
nil)))))
(defn shortest-path-length [file-name]
(let [height-map (parse-lines (string/split-lines (slurp file-name)))
shortest (find-shortest-path height-map)]
(dec (count shortest))))
(defn find-shortest-path-to-low-ground
([start grid]
(let [shortest (atom (repeat 1000 0))
shortest-map (atom (make-shortest-map grid 1000))]
(find-shortest-path-to-low-ground start grid [start] shortest shortest-map)
@shortest))
([pos grid path shortest shortest-map]
(let [path-length (count path)]
(when (< path-length (get @shortest-map pos))
(swap! shortest-map assoc pos path-length)
(cond
(zero? (get-cell grid pos))
(do
(prn path-length path)
(reset! shortest path))
(< path-length (count @shortest))
(let [steps (possible-steps-while-descending grid pos)
prioritized-steps (prune-path path steps)]
(doseq [step prioritized-steps]
(find-shortest-path-to-low-ground step grid (conj path step) shortest shortest-map)))
:else
nil)))))
(defn shortest-scenic-path [file-name]
(let [[_ end grid] (parse-lines (string/split-lines (slurp file-name)))
shortest (find-shortest-path-to-low-ground end grid)]
(dec (count shortest))))
|
|
68895c9253cd1dd41a15b5147f3a22fda50e3dadcc8207122a19feff9435841b | byorgey/BlogLiterately | Post.hs | # LANGUAGE FlexibleContexts #
# LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
-----------------------------------------------------------------------------
-- |
-- Module : Text.BlogLiterately.Post
Copyright : ( c ) 2008 - 2010 , 2012
-- License : GPL (see LICENSE)
Maintainer : < >
--
-- Uploading posts to the server and fetching posts from the server.
--
-----------------------------------------------------------------------------
module Text.BlogLiterately.Post
(
mkPost, mkArray, postIt, getPostURL, findTitle
) where
import Control.Lens (at, makePrisms, to, traverse,
(^.), (^..), (^?), _Just, _head)
import Data.Char (toLower)
import Data.Function (on)
import Data.List (isInfixOf)
import qualified Data.Map as M
import Network.XmlRpc.Client (remote)
import Network.XmlRpc.Internals (Value (..), XmlRpcType, toValue)
import Text.BlogLiterately.Options
The metaWeblog API defines ` newPost ` and ` editPost ` procedures that
look like :
[ other ]
metaWeblog.newPost ( blogid , username , password , struct , publish )
returns string
metaWeblog.editPost ( postid , username , password , struct , publish )
returns true
For WordPress blogs , the ` blogid ` is ignored . The user name and
password are simply strings , and ` publish ` is a flag indicating
whether to load the post as a draft , or to make it public immediately .
The ` postid ` is an identifier string which is assigned when you
initially create a post . The interesting bit is the ` struct ` field ,
which is an XML - RPC structure defining the post along with some
meta - data , like the title . I want be able to provide the post body , a
title , and lists of categories and tags . For the body and title , we
could just let HaXR convert the values automatically into the XML - RPC
` Value ` type , since they all have the same type ( ` String ` ) and
thus can be put into a list . But the categories and tags are lists of
strings , so we need to explicitly convert everything to a ` Value ` ,
then combine :
The metaWeblog API defines `newPost` and `editPost` procedures that
look like:
[other]
metaWeblog.newPost (blogid, username, password, struct, publish)
returns string
metaWeblog.editPost (postid, username, password, struct, publish)
returns true
For WordPress blogs, the `blogid` is ignored. The user name and
password are simply strings, and `publish` is a flag indicating
whether to load the post as a draft, or to make it public immediately.
The `postid` is an identifier string which is assigned when you
initially create a post. The interesting bit is the `struct` field,
which is an XML-RPC structure defining the post along with some
meta-data, like the title. I want be able to provide the post body, a
title, and lists of categories and tags. For the body and title, we
could just let HaXR convert the values automatically into the XML-RPC
`Value` type, since they all have the same Haskell type (`String`) and
thus can be put into a list. But the categories and tags are lists of
strings, so we need to explicitly convert everything to a `Value`,
then combine:
-}
-- | Prepare a post for uploading by creating something of the proper
-- form to be an argument to an XML-RPC call.
mkPost :: String -- ^ Post title
-> String -- ^ Post content
-> [String] -- ^ List of categories
-> [String] -- ^ List of tags
^ @True@ = page , @False@ = post
-> [(String, Value)]
mkPost title_ text_ categories_ tags_ page_ =
mkArray "categories" categories_
++ mkArray "mt_keywords" tags_
++ [ ("title", toValue title_)
, ("description", toValue text_)
]
++ [ ("post_type", toValue "page") | page_ ]
| Given a name and a list of values , create a named \"array\ " field
-- suitable for inclusion in an XML-RPC struct.
mkArray :: XmlRpcType [a] => String -> [a] -> [(String, Value)]
mkArray _ [] = []
mkArray name values = [(name, toValue values)]
The HaXR library exports a function for invoking XML - RPC procedures :
[ haskell ]
remote : : Remote a = >
String -- ^ Server URL . May contain username and password on
-- the format username : password\@ before the hostname .
- > String -- ^ Remote method name .
- > a -- ^ Any function
-- @(XmlRpcType t1 , ... , XmlRpcType tn , XmlRpcType r ) = >
-- t1 - > ... - > tn - > IO r@
The function requires an URL and a method name , and returns a function
of type ` Remote a = > a ` . Based on the instances defined for ` Remote ` ,
any function with zero or more parameters in the class ` XmlRpcType `
and a return type of ` XmlRpcType r = > IO r ` will work , which means you
can simply ' feed ' ` remote ` additional arguments as required by the
remote procedure , and as long as you make the call in an IO context ,
it will typecheck . ` postIt ` calls ` metaWeblog.newPost ` or
` metaWeblog.editPost ` ( or simply prints the HTML to stdout ) as
appropriate :
The HaXR library exports a function for invoking XML-RPC procedures:
[haskell]
remote :: Remote a =>
String -- ^ Server URL. May contain username and password on
-- the format username:password\@ before the hostname.
-> String -- ^ Remote method name.
-> a -- ^ Any function
-- @(XmlRpcType t1, ..., XmlRpcType tn, XmlRpcType r) =>
-- t1 -> ... -> tn -> IO r@
The function requires an URL and a method name, and returns a function
of type `Remote a => a`. Based on the instances defined for `Remote`,
any function with zero or more parameters in the class `XmlRpcType`
and a return type of `XmlRpcType r => IO r` will work, which means you
can simply 'feed' `remote` additional arguments as required by the
remote procedure, and as long as you make the call in an IO context,
it will typecheck. `postIt` calls `metaWeblog.newPost` or
`metaWeblog.editPost` (or simply prints the HTML to stdout) as
appropriate:
-}
makePrisms ''Value
-- | Get the URL for a given post.
getPostURL :: String -> String -> String -> String -> IO (Maybe String)
getPostURL url pid usr pwd = do
v <- remote url "metaWeblog.getPost" pid usr pwd
return (v ^? _ValueStruct . to M.fromList . at "link" . traverse . _ValueString)
-- | Look at the last n posts and find the most recent whose title
-- contains the search term (case insensitive); return its permalink
-- URL.
findTitle :: Int -> String -> String -> String -> String -> IO (Maybe String)
findTitle numPrev url search usr pwd = do
res <- remote url "metaWeblog.getRecentPosts" (0::Int) usr pwd numPrev
let matches s = (isInfixOf `on` map toLower) search s
posts = res ^.. _ValueArray . traverse . _ValueStruct . to M.fromList
posts' = filter (\p -> maybe False matches (p ^? at "title" . _Just . _ValueString)) posts
return (posts' ^? _head . at "link" . _Just . _ValueString)
-- | Given a configuration and a formatted post, upload it to the server.
postIt :: BlogLiterately -> String -> IO ()
postIt bl html =
case (bl^.blog, bl^.htmlOnly) of
(Nothing , _ ) -> putStr html
(_ , Just True ) -> putStr html
(Just url , _ ) -> do
let pwd = password' bl
case bl^.postid of
Nothing -> do
pid <- remote url "metaWeblog.newPost"
(blogid' bl)
(user' bl)
pwd
post
(publish' bl)
putStrLn $ "Post ID: " ++ pid
getPostURL url pid (user' bl) pwd >>= maybe (return ()) putStrLn
Just pid -> do
success <- remote url "metaWeblog.editPost" pid
(user' bl)
pwd
post
(publish' bl)
case success of
True -> getPostURL url pid (user' bl) pwd >>= maybe (return ()) putStrLn
False -> putStrLn "Update failed!"
where
post = mkPost
(title' bl)
html (bl^.categories) (bl^.tags)
(page' bl)
| null | https://raw.githubusercontent.com/byorgey/BlogLiterately/fbc8dc238c7e5bc570bef4d0c1dd9cf2f92de72a/src/Text/BlogLiterately/Post.hs | haskell | ---------------------------------------------------------------------------
|
Module : Text.BlogLiterately.Post
License : GPL (see LICENSE)
Uploading posts to the server and fetching posts from the server.
---------------------------------------------------------------------------
| Prepare a post for uploading by creating something of the proper
form to be an argument to an XML-RPC call.
^ Post title
^ Post content
^ List of categories
^ List of tags
suitable for inclusion in an XML-RPC struct.
^ Server URL . May contain username and password on
the format username : password\@ before the hostname .
^ Remote method name .
^ Any function
@(XmlRpcType t1 , ... , XmlRpcType tn , XmlRpcType r ) = >
t1 - > ... - > tn - > IO r@
^ Server URL. May contain username and password on
the format username:password\@ before the hostname.
^ Remote method name.
^ Any function
@(XmlRpcType t1, ..., XmlRpcType tn, XmlRpcType r) =>
t1 -> ... -> tn -> IO r@
| Get the URL for a given post.
| Look at the last n posts and find the most recent whose title
contains the search term (case insensitive); return its permalink
URL.
| Given a configuration and a formatted post, upload it to the server. | # LANGUAGE FlexibleContexts #
# LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
Copyright : ( c ) 2008 - 2010 , 2012
Maintainer : < >
module Text.BlogLiterately.Post
(
mkPost, mkArray, postIt, getPostURL, findTitle
) where
import Control.Lens (at, makePrisms, to, traverse,
(^.), (^..), (^?), _Just, _head)
import Data.Char (toLower)
import Data.Function (on)
import Data.List (isInfixOf)
import qualified Data.Map as M
import Network.XmlRpc.Client (remote)
import Network.XmlRpc.Internals (Value (..), XmlRpcType, toValue)
import Text.BlogLiterately.Options
The metaWeblog API defines ` newPost ` and ` editPost ` procedures that
look like :
[ other ]
metaWeblog.newPost ( blogid , username , password , struct , publish )
returns string
metaWeblog.editPost ( postid , username , password , struct , publish )
returns true
For WordPress blogs , the ` blogid ` is ignored . The user name and
password are simply strings , and ` publish ` is a flag indicating
whether to load the post as a draft , or to make it public immediately .
The ` postid ` is an identifier string which is assigned when you
initially create a post . The interesting bit is the ` struct ` field ,
which is an XML - RPC structure defining the post along with some
meta - data , like the title . I want be able to provide the post body , a
title , and lists of categories and tags . For the body and title , we
could just let HaXR convert the values automatically into the XML - RPC
` Value ` type , since they all have the same type ( ` String ` ) and
thus can be put into a list . But the categories and tags are lists of
strings , so we need to explicitly convert everything to a ` Value ` ,
then combine :
The metaWeblog API defines `newPost` and `editPost` procedures that
look like:
[other]
metaWeblog.newPost (blogid, username, password, struct, publish)
returns string
metaWeblog.editPost (postid, username, password, struct, publish)
returns true
For WordPress blogs, the `blogid` is ignored. The user name and
password are simply strings, and `publish` is a flag indicating
whether to load the post as a draft, or to make it public immediately.
The `postid` is an identifier string which is assigned when you
initially create a post. The interesting bit is the `struct` field,
which is an XML-RPC structure defining the post along with some
meta-data, like the title. I want be able to provide the post body, a
title, and lists of categories and tags. For the body and title, we
could just let HaXR convert the values automatically into the XML-RPC
`Value` type, since they all have the same Haskell type (`String`) and
thus can be put into a list. But the categories and tags are lists of
strings, so we need to explicitly convert everything to a `Value`,
then combine:
-}
^ @True@ = page , @False@ = post
-> [(String, Value)]
mkPost title_ text_ categories_ tags_ page_ =
mkArray "categories" categories_
++ mkArray "mt_keywords" tags_
++ [ ("title", toValue title_)
, ("description", toValue text_)
]
++ [ ("post_type", toValue "page") | page_ ]
| Given a name and a list of values , create a named \"array\ " field
mkArray :: XmlRpcType [a] => String -> [a] -> [(String, Value)]
mkArray _ [] = []
mkArray name values = [(name, toValue values)]
The HaXR library exports a function for invoking XML - RPC procedures :
[ haskell ]
remote : : Remote a = >
The function requires an URL and a method name , and returns a function
of type ` Remote a = > a ` . Based on the instances defined for ` Remote ` ,
any function with zero or more parameters in the class ` XmlRpcType `
and a return type of ` XmlRpcType r = > IO r ` will work , which means you
can simply ' feed ' ` remote ` additional arguments as required by the
remote procedure , and as long as you make the call in an IO context ,
it will typecheck . ` postIt ` calls ` metaWeblog.newPost ` or
` metaWeblog.editPost ` ( or simply prints the HTML to stdout ) as
appropriate :
The HaXR library exports a function for invoking XML-RPC procedures:
[haskell]
remote :: Remote a =>
The function requires an URL and a method name, and returns a function
of type `Remote a => a`. Based on the instances defined for `Remote`,
any function with zero or more parameters in the class `XmlRpcType`
and a return type of `XmlRpcType r => IO r` will work, which means you
can simply 'feed' `remote` additional arguments as required by the
remote procedure, and as long as you make the call in an IO context,
it will typecheck. `postIt` calls `metaWeblog.newPost` or
`metaWeblog.editPost` (or simply prints the HTML to stdout) as
appropriate:
-}
makePrisms ''Value
getPostURL :: String -> String -> String -> String -> IO (Maybe String)
getPostURL url pid usr pwd = do
v <- remote url "metaWeblog.getPost" pid usr pwd
return (v ^? _ValueStruct . to M.fromList . at "link" . traverse . _ValueString)
findTitle :: Int -> String -> String -> String -> String -> IO (Maybe String)
findTitle numPrev url search usr pwd = do
res <- remote url "metaWeblog.getRecentPosts" (0::Int) usr pwd numPrev
let matches s = (isInfixOf `on` map toLower) search s
posts = res ^.. _ValueArray . traverse . _ValueStruct . to M.fromList
posts' = filter (\p -> maybe False matches (p ^? at "title" . _Just . _ValueString)) posts
return (posts' ^? _head . at "link" . _Just . _ValueString)
postIt :: BlogLiterately -> String -> IO ()
postIt bl html =
case (bl^.blog, bl^.htmlOnly) of
(Nothing , _ ) -> putStr html
(_ , Just True ) -> putStr html
(Just url , _ ) -> do
let pwd = password' bl
case bl^.postid of
Nothing -> do
pid <- remote url "metaWeblog.newPost"
(blogid' bl)
(user' bl)
pwd
post
(publish' bl)
putStrLn $ "Post ID: " ++ pid
getPostURL url pid (user' bl) pwd >>= maybe (return ()) putStrLn
Just pid -> do
success <- remote url "metaWeblog.editPost" pid
(user' bl)
pwd
post
(publish' bl)
case success of
True -> getPostURL url pid (user' bl) pwd >>= maybe (return ()) putStrLn
False -> putStrLn "Update failed!"
where
post = mkPost
(title' bl)
html (bl^.categories) (bl^.tags)
(page' bl)
|
43fa4eedb46f1673d6af728b224164baeca338358c33515881a71bee552f06e2 | rems-project/lem | pset_using_lists.ml | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../LICENSE. *)
(* *)
(***********************************************************************)
Modified by 2010 - 10 - 28
Modified by 2013 - 04- ..
$ I d : set.ml 6694 2004 - 11 - 25 00:06:06Z doligez $
(* Sets over ordered types *)
(* Implementation of the set operations *)
type 'a rep = 'a list
exception Not_implemented
let rec add cmp x list =
x::list
let empty = []
let is_empty = function [] -> true | _ -> false
let rec mem cmp x = function
[] -> false
| v::l ->
let c = cmp x v in
c = 0 || mem cmp x l
let singleton x = [x]
let rec remove cmp x = function
[] -> []
| v::l ->
let c = cmp x v in
if c = 0 then remove cmp x l else
v::(remove cmp x l)
let compare cmp s1 s2 =
raise Not_implemented
let equal cmp s1 s2 =
compare cmp s1 s2 = 0
let rec iter f = function
[] -> ()
| v::l -> iter f l; f v
let rec fold f s accu =
match s with
[] -> accu
| v::l -> f v (fold f l accu)
let map cmp f s = fold (fun e s -> add cmp (f e) s) s empty
let rec for_all p = function
[] -> true
| v::l -> p v && for_all p l
let rec exists p = function
[] -> false
| v::l -> p v || exists p l
let rec subset cmp s1 s2 =
for_all (fun e -> mem cmp e s2) s1
let filter cmp p s =
let rec filt accu = function
| [] -> accu
| v::r ->
filt (if p v then add cmp v accu else accu) r in
filt [] s
let partition cmp p s =
let rec part (l, r as accu) = function
| [] -> accu
| h::t ->
part (if p h then (add cmp h l, r) else (l, add cmp h r)) t in
part ([], []) s
let rec union cmp s1 s2 =
match s1 with
[] -> s2
| v::l -> v::(union cmp l s2)
let rec inter cmp s1 s2 =
filter cmp (fun e -> mem cmp e s2) s1
let rec cardinal cmp = function
[] -> 0
| h::t -> (cardinal cmp (remove cmp h t)) + 1
let elements s =
s
let diff cmp s s =
raise Not_implemented
let min_elt s =
raise Not_implemented
let max_elt s =
raise Not_implemented
let split cmp x s =
raise Not_implemented
(* It's not determenistic in the sense that s1.choose = s2.choose given that s1 equals s2 *)
let choose = function
[] -> raise Not_found
| h::_ -> h
type 'a set = { cmp : 'a -> 'a -> int; s : 'a rep }
let empty c = { cmp = c; s = []; }
let is_empty s = is_empty s.s
let mem x s = mem s.cmp x s.s
let add x s = { s with s = add s.cmp x s.s }
let singleton c x = { cmp = c; s = singleton x }
let remove x s = { s with s = remove s.cmp x s.s }
let union s1 s2 = { s1 with s = union s1.cmp s1.s s2.s }
let inter s1 s2 = { s1 with s = inter s1.cmp s1.s s2.s }
let diff s1 s2 = { s1 with s = diff s1.cmp s1.s s2.s }
let compare s1 s2 = compare s1.cmp s1.s s2.s
let equal s1 s2 = equal s1.cmp s1.s s2.s
let subset s1 s2 = subset s1.cmp s1.s s2.s
let iter f s = iter f s.s
let fold f s a = fold f s.s a
let map c f s = {cmp = c; s = map c f s.s}
let for_all p s = for_all p s.s
let exists p s = exists p s.s
let filter p s = { s with s = filter s.cmp p s.s }
let partition p s =
let (r1,r2) = partition s.cmp p s.s in
({s with s = r1}, {s with s = r2})
let cardinal s = cardinal s.cmp s.s
let elements s = elements s.s
let min_elt s = min_elt s.s
let max_elt s = max_elt s.s
let choose s = choose s.s
let split x s =
let (l,present,r) = split s.cmp x s.s in
({ s with s = l }, present, { s with s = r })
let from_list c l =
{cmp = c; s = l}
let comprehension1 cmp f p s =
fold (fun x s -> if p x then add (f x) s else s) s (empty cmp)
let comprehension2 cmp f p s1 s2 =
fold
(fun x1 s ->
fold
(fun x2 s ->
if p x1 x2 then add (f x1 x2) s else s)
s2
s)
s1
(empty cmp)
let comprehension3 cmp f p s1 s2 s3 =
fold
(fun x1 s ->
fold
(fun x2 s ->
fold
(fun x3 s ->
if p x1 x2 x3 then add (f x1 x2 x3) s else s)
s3
s)
s2
s)
s1
(empty cmp)
let comprehension4 cmp f p s1 s2 s3 s4 =
fold
(fun x1 s ->
fold
(fun x2 s ->
fold
(fun x3 s ->
fold
(fun x4 s ->
if p x1 x2 x3 x4 then add (f x1 x2 x3 x4) s else s)
s4
s)
s3
s)
s2
s)
s1
(empty cmp)
let comprehension5 cmp f p s1 s2 s3 s4 s5 =
fold
(fun x1 s ->
fold
(fun x2 s ->
fold
(fun x3 s ->
fold
(fun x4 s ->
fold
(fun x5 s ->
if p x1 x2 x3 x4 x5 then add (f x1 x2 x3 x4 x5) s else s)
s5
s)
s4
s)
s3
s)
s2
s)
s1
(empty cmp)
let comprehension6 cmp f p s1 s2 s3 s4 s5 s6 =
fold
(fun x1 s ->
fold
(fun x2 s ->
fold
(fun x3 s ->
fold
(fun x4 s ->
fold
(fun x5 s ->
fold
(fun x6 s ->
if p x1 x2 x3 x4 x5 x6 then add (f x1 x2 x3 x4 x5 x6) s else s)
s6
s)
s5
s)
s4
s)
s3
s)
s2
s)
s1
(empty cmp)
let comprehension7 cmp f p s1 s2 s3 s4 s5 s6 s7 =
fold
(fun x1 s ->
fold
(fun x2 s ->
fold
(fun x3 s ->
fold
(fun x4 s ->
fold
(fun x5 s ->
fold
(fun x6 s ->
fold
(fun x7 s ->
if p x1 x2 x3 x4 x5 x6 x7 then add (f x1 x2 x3 x4 x5 x6 x7) s else s)
s7
s)
s6
s)
s5
s)
s4
s)
s3
s)
s2
s)
s1
(empty cmp)
let bigunion c xss =
fold union xss (empty c)
let rec lfp s f =
let s' = f s in
if subset s' s then
s
else
lfp (union s' s) f
let cross c xs ys =
fold (fun x xys -> fold (fun y xys -> add (x,y) xys) ys xys) xs (empty c)
let rec lfp s f =
let s' = f s in
if subset s' s then
s
else
lfp (union s' s) f
let tc c r =
let one_step r = fold (fun (x,y) xs -> fold (fun (y',z) xs ->
if y = y' then add (x,z) xs else xs) r xs) r (empty c) in
lfp r one_step
| null | https://raw.githubusercontent.com/rems-project/lem/a839114e468119d9ac0868d7dc53eae7f3cc3a6c/ocaml-lib/pset_using_lists.ml | ocaml | *********************************************************************
Objective Caml
the special exception on linking described in file ../LICENSE.
*********************************************************************
Sets over ordered types
Implementation of the set operations
It's not determenistic in the sense that s1.choose = s2.choose given that s1 equals s2 | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
Modified by 2010 - 10 - 28
Modified by 2013 - 04- ..
$ I d : set.ml 6694 2004 - 11 - 25 00:06:06Z doligez $
type 'a rep = 'a list
exception Not_implemented
let rec add cmp x list =
x::list
let empty = []
let is_empty = function [] -> true | _ -> false
let rec mem cmp x = function
[] -> false
| v::l ->
let c = cmp x v in
c = 0 || mem cmp x l
let singleton x = [x]
let rec remove cmp x = function
[] -> []
| v::l ->
let c = cmp x v in
if c = 0 then remove cmp x l else
v::(remove cmp x l)
let compare cmp s1 s2 =
raise Not_implemented
let equal cmp s1 s2 =
compare cmp s1 s2 = 0
let rec iter f = function
[] -> ()
| v::l -> iter f l; f v
let rec fold f s accu =
match s with
[] -> accu
| v::l -> f v (fold f l accu)
let map cmp f s = fold (fun e s -> add cmp (f e) s) s empty
let rec for_all p = function
[] -> true
| v::l -> p v && for_all p l
let rec exists p = function
[] -> false
| v::l -> p v || exists p l
let rec subset cmp s1 s2 =
for_all (fun e -> mem cmp e s2) s1
let filter cmp p s =
let rec filt accu = function
| [] -> accu
| v::r ->
filt (if p v then add cmp v accu else accu) r in
filt [] s
let partition cmp p s =
let rec part (l, r as accu) = function
| [] -> accu
| h::t ->
part (if p h then (add cmp h l, r) else (l, add cmp h r)) t in
part ([], []) s
let rec union cmp s1 s2 =
match s1 with
[] -> s2
| v::l -> v::(union cmp l s2)
let rec inter cmp s1 s2 =
filter cmp (fun e -> mem cmp e s2) s1
let rec cardinal cmp = function
[] -> 0
| h::t -> (cardinal cmp (remove cmp h t)) + 1
let elements s =
s
let diff cmp s s =
raise Not_implemented
let min_elt s =
raise Not_implemented
let max_elt s =
raise Not_implemented
let split cmp x s =
raise Not_implemented
let choose = function
[] -> raise Not_found
| h::_ -> h
type 'a set = { cmp : 'a -> 'a -> int; s : 'a rep }
let empty c = { cmp = c; s = []; }
let is_empty s = is_empty s.s
let mem x s = mem s.cmp x s.s
let add x s = { s with s = add s.cmp x s.s }
let singleton c x = { cmp = c; s = singleton x }
let remove x s = { s with s = remove s.cmp x s.s }
let union s1 s2 = { s1 with s = union s1.cmp s1.s s2.s }
let inter s1 s2 = { s1 with s = inter s1.cmp s1.s s2.s }
let diff s1 s2 = { s1 with s = diff s1.cmp s1.s s2.s }
let compare s1 s2 = compare s1.cmp s1.s s2.s
let equal s1 s2 = equal s1.cmp s1.s s2.s
let subset s1 s2 = subset s1.cmp s1.s s2.s
let iter f s = iter f s.s
let fold f s a = fold f s.s a
let map c f s = {cmp = c; s = map c f s.s}
let for_all p s = for_all p s.s
let exists p s = exists p s.s
let filter p s = { s with s = filter s.cmp p s.s }
let partition p s =
let (r1,r2) = partition s.cmp p s.s in
({s with s = r1}, {s with s = r2})
let cardinal s = cardinal s.cmp s.s
let elements s = elements s.s
let min_elt s = min_elt s.s
let max_elt s = max_elt s.s
let choose s = choose s.s
let split x s =
let (l,present,r) = split s.cmp x s.s in
({ s with s = l }, present, { s with s = r })
let from_list c l =
{cmp = c; s = l}
let comprehension1 cmp f p s =
fold (fun x s -> if p x then add (f x) s else s) s (empty cmp)
let comprehension2 cmp f p s1 s2 =
fold
(fun x1 s ->
fold
(fun x2 s ->
if p x1 x2 then add (f x1 x2) s else s)
s2
s)
s1
(empty cmp)
let comprehension3 cmp f p s1 s2 s3 =
fold
(fun x1 s ->
fold
(fun x2 s ->
fold
(fun x3 s ->
if p x1 x2 x3 then add (f x1 x2 x3) s else s)
s3
s)
s2
s)
s1
(empty cmp)
let comprehension4 cmp f p s1 s2 s3 s4 =
fold
(fun x1 s ->
fold
(fun x2 s ->
fold
(fun x3 s ->
fold
(fun x4 s ->
if p x1 x2 x3 x4 then add (f x1 x2 x3 x4) s else s)
s4
s)
s3
s)
s2
s)
s1
(empty cmp)
let comprehension5 cmp f p s1 s2 s3 s4 s5 =
fold
(fun x1 s ->
fold
(fun x2 s ->
fold
(fun x3 s ->
fold
(fun x4 s ->
fold
(fun x5 s ->
if p x1 x2 x3 x4 x5 then add (f x1 x2 x3 x4 x5) s else s)
s5
s)
s4
s)
s3
s)
s2
s)
s1
(empty cmp)
let comprehension6 cmp f p s1 s2 s3 s4 s5 s6 =
fold
(fun x1 s ->
fold
(fun x2 s ->
fold
(fun x3 s ->
fold
(fun x4 s ->
fold
(fun x5 s ->
fold
(fun x6 s ->
if p x1 x2 x3 x4 x5 x6 then add (f x1 x2 x3 x4 x5 x6) s else s)
s6
s)
s5
s)
s4
s)
s3
s)
s2
s)
s1
(empty cmp)
let comprehension7 cmp f p s1 s2 s3 s4 s5 s6 s7 =
fold
(fun x1 s ->
fold
(fun x2 s ->
fold
(fun x3 s ->
fold
(fun x4 s ->
fold
(fun x5 s ->
fold
(fun x6 s ->
fold
(fun x7 s ->
if p x1 x2 x3 x4 x5 x6 x7 then add (f x1 x2 x3 x4 x5 x6 x7) s else s)
s7
s)
s6
s)
s5
s)
s4
s)
s3
s)
s2
s)
s1
(empty cmp)
let bigunion c xss =
fold union xss (empty c)
let rec lfp s f =
let s' = f s in
if subset s' s then
s
else
lfp (union s' s) f
let cross c xs ys =
fold (fun x xys -> fold (fun y xys -> add (x,y) xys) ys xys) xs (empty c)
let rec lfp s f =
let s' = f s in
if subset s' s then
s
else
lfp (union s' s) f
let tc c r =
let one_step r = fold (fun (x,y) xs -> fold (fun (y',z) xs ->
if y = y' then add (x,z) xs else xs) r xs) r (empty c) in
lfp r one_step
|
c3379039094cb0140e702ec5712010d6217822ed8119260d41988696030e81ea | habibutsu/erlz | erlz_monad_error.erl | -module('erlz_monad_error').
-compile([export_all]).
%%====================================================================
%% Error (special case for Either)
%%====================================================================
instance Monad
return(V) ->
{ok, V}.
'>>='({error, Reason}, _) ->
{error, Reason};
'>>='({ok, V}, Fn) ->
Fn(V);
'>>='(Fn, V) ->
throw({bad_match, "could not prepare value", V, "for", Fn}).
%% instance Functor
fmap(_Fn, {error, V}) ->
{error, V};
fmap(Fn, {ok, V}) ->
{ok, Fn(V)}.
| null | https://raw.githubusercontent.com/habibutsu/erlz/eac1757905ca3c49483a86d9b72ab5e4f033fa29/src/erlz_monad_error.erl | erlang | ====================================================================
Error (special case for Either)
====================================================================
instance Functor | -module('erlz_monad_error').
-compile([export_all]).
instance Monad
return(V) ->
{ok, V}.
'>>='({error, Reason}, _) ->
{error, Reason};
'>>='({ok, V}, Fn) ->
Fn(V);
'>>='(Fn, V) ->
throw({bad_match, "could not prepare value", V, "for", Fn}).
fmap(_Fn, {error, V}) ->
{error, V};
fmap(Fn, {ok, V}) ->
{ok, Fn(V)}.
|
505cb413f6c29abddc755b29b8343df727926a8798a6c81a696b6c94afb13424 | kitlang/kit | EnumVariant.hs | module Kit.Ast.Definitions.EnumVariant (
EnumVariant (..),
newEnumVariant,
convertEnumVariant,
discriminantFieldName,
variantFieldName,
variantIsSimple
) where
import Control.Monad
import Kit.Ast.Definitions.ArgSpec
import Kit.Ast.Definitions.Base
import Kit.Ast.Metadata
import Kit.Ast.Modifier
import Kit.Ast.TypePath
import Kit.Ast.Span
import Kit.Str
data EnumVariant a b = EnumVariant {
variantName :: TypePath,
variantParent :: TypePath,
variantPos :: Span,
variantMeta :: [Metadata],
variantModifiers :: [Modifier],
variantArgs :: [ArgSpec a b],
variantValue :: Maybe a
} deriving (Eq, Show)
instance Positioned (EnumVariant a b) where
position = variantPos
variantRealName v = if hasNoMangle (variantMeta v)
then ([], tpName $ variantName v)
else subPath (variantParent v) (tpName $ variantName v)
newEnumVariant = EnumVariant
{ variantName = undefined
, variantParent = undefined
, variantMeta = []
, variantModifiers = []
, variantArgs = []
, variantValue = Nothing
, variantPos = NoPos
}
variantIsSimple = null . variantArgs
convertEnumVariant
:: (Monad m) => Converter m a b c d -> EnumVariant a b -> m (EnumVariant c d)
convertEnumVariant converter@(Converter { exprConverter = exprConverter }) v =
do
newArgs <- forM (variantArgs v) (convertArgSpec converter)
newValue <- maybeConvert exprConverter (variantValue v)
return $ newEnumVariant { variantName = variantName v
, variantParent = variantParent v
, variantMeta = variantMeta v
, variantModifiers = variantModifiers v
, variantArgs = newArgs
, variantValue = newValue
, variantPos = variantPos v
}
discriminantFieldName :: Str
discriminantFieldName = "__dsc"
variantFieldName :: Str
variantFieldName = "__var"
| null | https://raw.githubusercontent.com/kitlang/kit/2769a7a8e51fe4466c50439d1a1ebdad0fb79710/src/Kit/Ast/Definitions/EnumVariant.hs | haskell | module Kit.Ast.Definitions.EnumVariant (
EnumVariant (..),
newEnumVariant,
convertEnumVariant,
discriminantFieldName,
variantFieldName,
variantIsSimple
) where
import Control.Monad
import Kit.Ast.Definitions.ArgSpec
import Kit.Ast.Definitions.Base
import Kit.Ast.Metadata
import Kit.Ast.Modifier
import Kit.Ast.TypePath
import Kit.Ast.Span
import Kit.Str
data EnumVariant a b = EnumVariant {
variantName :: TypePath,
variantParent :: TypePath,
variantPos :: Span,
variantMeta :: [Metadata],
variantModifiers :: [Modifier],
variantArgs :: [ArgSpec a b],
variantValue :: Maybe a
} deriving (Eq, Show)
instance Positioned (EnumVariant a b) where
position = variantPos
variantRealName v = if hasNoMangle (variantMeta v)
then ([], tpName $ variantName v)
else subPath (variantParent v) (tpName $ variantName v)
newEnumVariant = EnumVariant
{ variantName = undefined
, variantParent = undefined
, variantMeta = []
, variantModifiers = []
, variantArgs = []
, variantValue = Nothing
, variantPos = NoPos
}
variantIsSimple = null . variantArgs
convertEnumVariant
:: (Monad m) => Converter m a b c d -> EnumVariant a b -> m (EnumVariant c d)
convertEnumVariant converter@(Converter { exprConverter = exprConverter }) v =
do
newArgs <- forM (variantArgs v) (convertArgSpec converter)
newValue <- maybeConvert exprConverter (variantValue v)
return $ newEnumVariant { variantName = variantName v
, variantParent = variantParent v
, variantMeta = variantMeta v
, variantModifiers = variantModifiers v
, variantArgs = newArgs
, variantValue = newValue
, variantPos = variantPos v
}
discriminantFieldName :: Str
discriminantFieldName = "__dsc"
variantFieldName :: Str
variantFieldName = "__var"
|
|
623ba99634fdda95bf2287456fc6902c3de81f3888b72b2a89f1eb7f2fd4b513 | renatoalencar/ocaml-socks-client | config.ml | open Mirage
let packages = [ package "socks"
; package "mirage_socks4" ]
let main = foreign ~packages "Unikernel.Main" (stackv4 @-> job)
let stack = generic_stackv4 default_network
let () =
register "example" [
main $ stack
]
| null | https://raw.githubusercontent.com/renatoalencar/ocaml-socks-client/0102279ba53bac3cdca7e611cac6472e7ecb1172/examples/mirage/config.ml | ocaml | open Mirage
let packages = [ package "socks"
; package "mirage_socks4" ]
let main = foreign ~packages "Unikernel.Main" (stackv4 @-> job)
let stack = generic_stackv4 default_network
let () =
register "example" [
main $ stack
]
|
|
4554f12c8cf347cc9d31050455d6d85e55eb2f13c5933ec5fe46d96155fa6eca | bcc32/advent-of-code | a.ml | open! Core
open! Async
open! Import
let re = Re.(compile (seq [ group (rep1 digit); str ", "; group (rep1 digit) ]))
let dist (x, y) (x', y') = Int.abs (x - x') + Int.abs (y - y')
let main () =
let%bind points =
Reader.with_file "input" ~f:(fun r ->
r
|> Reader.lines
|> Pipe.map ~f:(fun line ->
let group = Re.exec re line in
let x = Re.Group.get group 1 |> Int.of_string in
let y = Re.Group.get group 2 |> Int.of_string in
x, y)
|> Pipe.to_list)
in
let min_x, max_x, min_y, max_y =
let x0, y0 = List.hd_exn points in
List.fold points ~init:(x0, x0, y0, y0) ~f:(fun (min_x, max_x, min_y, max_y) (x, y) ->
Int.min min_x x, Int.max max_x x, Int.min min_y y, Int.max max_y y)
in
(* index to area *)
let territory = Int.Table.create () in
let infinite = Int.Hash_set.create () in
let find_closest p =
let min_dist =
List.map points ~f:(dist p) |> List.min_elt ~compare:Int.compare |> Option.value_exn
in
List.filter_mapi points ~f:(fun i p' -> Option.some_if (dist p p' = min_dist) i)
in
for x = min_x - 1 to max_x + 1 do
for y = min_y - 1 to max_y + 1 do
match find_closest (x, y) with
| [ i ] ->
Hashtbl.incr territory i;
if x < min_x || x > max_x || y < min_y || y > max_y then Hash_set.add infinite i
| [] -> assert false
| _ -> ()
(* tied *)
done
done;
if false
then
Debug.eprint_s
[%message
""
(points : (int * int) list)
(territory : (int, int) Hashtbl.t)
(infinite : int Hash_set.t)];
Hashtbl.filter_keys_inplace territory ~f:(Fn.non (Hash_set.mem infinite));
Hashtbl.data territory
|> List.max_elt ~compare:Int.compare
|> Option.value_exn
|> printf "%d\n";
return ()
;;
let%expect_test "a" =
let%bind () = main () in
[%expect {| 5532 |}];
return ()
;;
| null | https://raw.githubusercontent.com/bcc32/advent-of-code/86a9387c3d6be2afe07d2657a0607749217b1b77/2018/06/a.ml | ocaml | index to area
tied | open! Core
open! Async
open! Import
let re = Re.(compile (seq [ group (rep1 digit); str ", "; group (rep1 digit) ]))
let dist (x, y) (x', y') = Int.abs (x - x') + Int.abs (y - y')
let main () =
let%bind points =
Reader.with_file "input" ~f:(fun r ->
r
|> Reader.lines
|> Pipe.map ~f:(fun line ->
let group = Re.exec re line in
let x = Re.Group.get group 1 |> Int.of_string in
let y = Re.Group.get group 2 |> Int.of_string in
x, y)
|> Pipe.to_list)
in
let min_x, max_x, min_y, max_y =
let x0, y0 = List.hd_exn points in
List.fold points ~init:(x0, x0, y0, y0) ~f:(fun (min_x, max_x, min_y, max_y) (x, y) ->
Int.min min_x x, Int.max max_x x, Int.min min_y y, Int.max max_y y)
in
let territory = Int.Table.create () in
let infinite = Int.Hash_set.create () in
let find_closest p =
let min_dist =
List.map points ~f:(dist p) |> List.min_elt ~compare:Int.compare |> Option.value_exn
in
List.filter_mapi points ~f:(fun i p' -> Option.some_if (dist p p' = min_dist) i)
in
for x = min_x - 1 to max_x + 1 do
for y = min_y - 1 to max_y + 1 do
match find_closest (x, y) with
| [ i ] ->
Hashtbl.incr territory i;
if x < min_x || x > max_x || y < min_y || y > max_y then Hash_set.add infinite i
| [] -> assert false
| _ -> ()
done
done;
if false
then
Debug.eprint_s
[%message
""
(points : (int * int) list)
(territory : (int, int) Hashtbl.t)
(infinite : int Hash_set.t)];
Hashtbl.filter_keys_inplace territory ~f:(Fn.non (Hash_set.mem infinite));
Hashtbl.data territory
|> List.max_elt ~compare:Int.compare
|> Option.value_exn
|> printf "%d\n";
return ()
;;
let%expect_test "a" =
let%bind () = main () in
[%expect {| 5532 |}];
return ()
;;
|
bd2804911216bb598ebc548f9759af9ba3c0c70684939830da88953ad292a2ff | samrocketman/home | Shiny_painting.0.3.scm | ; The GIMP -- an image manipulation program
Copyright ( C ) 1995 and
;
A set of layer effects script for GIMP 1.2
Copyright ( C ) 2001
Copyright ( C ) 2001
Copyright ( C ) 2007 Paint corroded version for GIMP 2.4
;
; --------------------------------------------------------------------
version 0.2 2007 - october-21
; - Initial relase
; --------------------------------------------------------------------
;
; This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
; (at your option) any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
You should have received a copy of the GNU General Public License
; along with this program; if not, write to the Free Software
Foundation , Inc. , 675 Mass Ave , Cambridge , , USA .
;
; --------------------------------------------------------------------
;
This is the official English version you 'll find a french version at -fr.org/
;
; Script-fu Shiny corroded Painting an attempt to realise the Scott-Effect with painted surface
;
; Start : a selection in an image or a layer with a transparency area who will be transformed
; in selection
;
; See the manual at the tutorial section of the gug /
;
(define (Aply-script-fu-shiny img Bump-Layer fond-color damage LightA LightPX LightPY Bcolor Crackeled bumpmap_depth)
(let* ((sizeX (car (gimp-drawable-width Bump-Layer)))
(sizeY (car (gimp-drawable-height Bump-Layer)))
(Bunped_layer (car (gimp-layer-copy Bump-Layer FALSE)))
(seed (* 30 30))
(activ_selection (car (gimp-selection-is-empty img)))
(damage (* damage 2.55))
(calque1 (car (gimp-layer-new img sizeX sizeY RGBA-IMAGE "plasma" 100 NORMAL)))
(masque1 (car (gimp-layer-create-mask calque1 1)))
(old-fg (car (gimp-palette-get-foreground)))
(old-bg (car (gimp-palette-get-background)))
(blanc '(255 255 255))
(pick_color '(255 255 255))
)
; undo initialisation
(gimp-image-undo-group-start img)
(gimp-image-resize-to-layers img)
(gimp-selection-layer-alpha Bump-Layer)
(gimp-context-set-foreground '(0 0 0))
(gimp-bucket-fill Bump-Layer 0 0 100 0 FALSE 0 0)
(gimp-selection-invert img)
(gimp-context-set-foreground fond-color)
(gimp-bucket-fill Bump-Layer 0 0 100 0 FALSE 0 0)
(gimp-image-add-layer img Bunped_layer 0)
(gimp-selection-invert img)
layer 1
(gimp-image-add-layer img calque1 0)
(gimp-image-add-layer-mask img calque1 masque1)
; plasma
(set! seed (* 30 30))
(plug-in-plasma TRUE img calque1 TRUE 2.5)
(gimp-threshold calque1 damage 255)
(let* ((calque2 (car (gimp-layer-copy calque1 TRUE)))
(masque2 (car (gimp-layer-mask calque2))))
layer 2
(gimp-image-add-layer img calque2 0)
; fill the layer-mask
(gimp-palette-set-foreground blanc)
(set! activ_selection (car (gimp-selection-is-empty img)))
(cond
((= activ_selection 0) ; selection activ
(gimp-bucket-fill masque1 0 0 100 0 FALSE 0 0)
(gimp-bucket-fill masque2 0 0 100 0 FALSE 0 0)
(gimp-selection-none img))
((= activ_selection 1) ; no selection activ
(gimp-selection-layer-alpha Bump-Layer)
(gimp-bucket-fill masque1 0 0 100 0 FALSE 0 0)
(gimp-bucket-fill masque2 0 0 100 0 FALSE 0 0)
)
) ; end of cond
(gimp-by-color-select calque1 '(255 255 255) 0 0 FALSE FALSE 0 FALSE)
(gimp-context-set-background Bcolor)
(gimp-bucket-fill calque2 1 0 100 0 FALSE 0 0)
(gimp-selection-invert img)
(gimp-edit-clear calque2)
(gimp-selection-all img)
; Bumping the letters
(plug-in-gauss 1 img Bump-Layer 10 10 0)
(plug-in-bump-map TRUE img Bunped_layer Bump-Layer 125 30 bumpmap_depth 0 0 0 0 TRUE TRUE LINEAR)
bumpmap on layer 2
(plug-in-bump-map TRUE img calque2 Bump-Layer 125 30 bumpmap_depth 0 0 0 0 TRUE TRUE LINEAR)
(plug-in-bump-map TRUE img calque2 calque2 125 45 bumpmap_depth 0 0 0 0 TRUE FALSE LINEAR)
;Light efect
(plug-in-lighting 1 img calque2 calque2 0 TRUE FALSE 0 0 blanc LightPX LightPY LightA -1.19 -7.14 1.00 0.9 2 2 LightA 10 TRUE FALSE FALSE)
(gimp-layer-set-mode calque1 8)
(gimp-layer-set-offsets Bump-Layer 18 12)
(plug-in-gauss 1 img Bump-Layer 20 20 0)
(gimp-layer-resize-to-image-size Bump-Layer)
(gimp-selection-layer-alpha Bump-Layer)
(gimp-selection-invert img)
(gimp-context-set-foreground fond-color)
(gimp-bucket-fill Bump-Layer 0 0 100 0 FALSE 0 0)
(gimp-selection-all img)
; back to the initials colours and display the result
(gimp-palette-set-foreground old-fg)
(gimp-palette-set-background old-bg)
(if (= Crackeled TRUE)
layer 3
(let* ((calque3 (car (gimp-layer-copy calque2 TRUE))))
(gimp-image-add-layer img calque3 0)
(gimp-selection-layer-alpha calque2)
(gimp-palette-set-background Bcolor)
(plug-in-mosaic 1 img calque2 10 10 1 0 TRUE 175 0.3 TRUE FALSE 3 0 1)
(gimp-layer-set-mode calque3 21)))
(gimp-selection-all img)
(gimp-palette-set-foreground old-fg)
(gimp-palette-set-background old-bg)
;Finish the undo group for the process
(gimp-image-undo-group-end img)
(gimp-displays-flush))))
(define (script-fu-shiny-logo-alpha img Bump-Layer fond-color damage LightA LightPX LightPY Bcolor Crackeled bumpmap_depth)
(begin
(Aply-script-fu-shiny img Bump-Layer fond-color damage LightA LightPX LightPY Bcolor Crackeled bumpmap_depth)
(gimp-displays-flush)))
(script-fu-register "script-fu-shiny-logo-alpha"
_"<Image>/Filters/Alpha to Logo/Corroded Painting"
"Scott-effect : Shiny Corroded Painting"
"titix raymond and philippe"
"2001, titix and raymond 2007 Philippe Demartin"
"20.10.2007"
""
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
SF-COLOR "Background" '(178 178 178)
SF-ADJUSTMENT "Painting Damage %" '(70 10 100 1 0 0 0)
SF-ADJUSTMENT "Light Amount" '(0.70 0 10 0.1 1 2 0)
SF-ADJUSTMENT "Light Position X" '(0 -50 50 1 0 0 0)
SF-ADJUSTMENT "Light Position y" '(0 -50 50 1 0 0 0)
SF-COLOR "Painting Color" '(255 0 0)
SF-TOGGLE "Crackeled" FALSE
SF-ADJUSTMENT "Bumpmap depth" '(15 1 50 1 0 0 0))
(define (script-fu-shiny-logo font text Text-Color Back-color size damage LightA LightPX LightPY Bcolor Crackeled bumpmap_depth)
(let* ((img (car (gimp-image-new 256 256 RGB))) ; nouvelle image -> img
(border (/ size 4))
( background ( car ( gimp - layer - new img 256 256 RGBA - IMAGE " background " 90 0 ) ) )
(Text-Color (car (gimp-context-set-foreground Text-Color)))
; (Back-color (car (gimp-context-set-background Back-color)))
(text-layer (car (gimp-text-fontname img -1 0 0 text border TRUE size PIXELS font)))
)
(gimp-layer-new img 256 256 RGBA-IMAGE "background" 90 0)
( gimp - edit - bucket - fill - full background 1 0 100 255 FALSE FALSE 0 0 0 )
(gimp-image-undo-disable img)
;(gimp-drawable-set-name text-layer text)
(Aply-script-fu-shiny img text-layer Back-color damage LightA LightPX LightPY Bcolor Crackeled bumpmap_depth)
(gimp-image-undo-enable img)
(gimp-display-new img)
))
(script-fu-register "script-fu-shiny-logo"
"Corroded Painting"
"Create corroded painted logo"
"Philippe Demartin"
"Inspired from the Corrosion script from titix and raymond"
"10/21/2007"
""
SF-FONT "Font Name" "Tahoma Bold"
SF-STRING "Enter your text" "Corroded..."
SF-COLOR "Font Color" '(133 52 2)
SF-COLOR "Background" '(178 178 178)
SF-ADJUSTMENT "Font size (pixels)" '(150 2 1000 1 10 0 1)
SF-ADJUSTMENT "Painting Damage %" '(70 10 100 1 0 0 0)
SF-ADJUSTMENT "Light Amount" '(0.70 0 10 0.01 1 2 0)
SF-ADJUSTMENT "Light Position X" '(0 -2 2 0.1 1 1 0)
SF-ADJUSTMENT "Light Position y" '(0 -2 2 0.1 1 1 1)
SF-COLOR "Painting Color" '(255 0 0)
SF-TOGGLE _"Crackeled" FALSE
SF-ADJUSTMENT "Bumpmap depth" '(15 1 50 1 0 0 0) )
(script-fu-menu-register "script-fu-shiny-logo"
"<Toolbox>/Xtns/Logos")
| null | https://raw.githubusercontent.com/samrocketman/home/63a8668a71dc594ea9ed76ec56bf8ca43b2a86ca/dotfiles/.gimp/scripts/Shiny_painting.0.3.scm | scheme | The GIMP -- an image manipulation program
--------------------------------------------------------------------
- Initial relase
--------------------------------------------------------------------
This program is free software; you can redistribute it and/or modify
either version 2 of the License , or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program; if not, write to the Free Software
--------------------------------------------------------------------
Script-fu Shiny corroded Painting an attempt to realise the Scott-Effect with painted surface
Start : a selection in an image or a layer with a transparency area who will be transformed
in selection
See the manual at the tutorial section of the gug /
undo initialisation
plasma
fill the layer-mask
selection activ
no selection activ
end of cond
Bumping the letters
Light efect
back to the initials colours and display the result
Finish the undo group for the process
nouvelle image -> img
(Back-color (car (gimp-context-set-background Back-color)))
(gimp-drawable-set-name text-layer text) | Copyright ( C ) 1995 and
A set of layer effects script for GIMP 1.2
Copyright ( C ) 2001
Copyright ( C ) 2001
Copyright ( C ) 2007 Paint corroded version for GIMP 2.4
version 0.2 2007 - october-21
it under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
Foundation , Inc. , 675 Mass Ave , Cambridge , , USA .
This is the official English version you 'll find a french version at -fr.org/
(define (Aply-script-fu-shiny img Bump-Layer fond-color damage LightA LightPX LightPY Bcolor Crackeled bumpmap_depth)
(let* ((sizeX (car (gimp-drawable-width Bump-Layer)))
(sizeY (car (gimp-drawable-height Bump-Layer)))
(Bunped_layer (car (gimp-layer-copy Bump-Layer FALSE)))
(seed (* 30 30))
(activ_selection (car (gimp-selection-is-empty img)))
(damage (* damage 2.55))
(calque1 (car (gimp-layer-new img sizeX sizeY RGBA-IMAGE "plasma" 100 NORMAL)))
(masque1 (car (gimp-layer-create-mask calque1 1)))
(old-fg (car (gimp-palette-get-foreground)))
(old-bg (car (gimp-palette-get-background)))
(blanc '(255 255 255))
(pick_color '(255 255 255))
)
(gimp-image-undo-group-start img)
(gimp-image-resize-to-layers img)
(gimp-selection-layer-alpha Bump-Layer)
(gimp-context-set-foreground '(0 0 0))
(gimp-bucket-fill Bump-Layer 0 0 100 0 FALSE 0 0)
(gimp-selection-invert img)
(gimp-context-set-foreground fond-color)
(gimp-bucket-fill Bump-Layer 0 0 100 0 FALSE 0 0)
(gimp-image-add-layer img Bunped_layer 0)
(gimp-selection-invert img)
layer 1
(gimp-image-add-layer img calque1 0)
(gimp-image-add-layer-mask img calque1 masque1)
(set! seed (* 30 30))
(plug-in-plasma TRUE img calque1 TRUE 2.5)
(gimp-threshold calque1 damage 255)
(let* ((calque2 (car (gimp-layer-copy calque1 TRUE)))
(masque2 (car (gimp-layer-mask calque2))))
layer 2
(gimp-image-add-layer img calque2 0)
(gimp-palette-set-foreground blanc)
(set! activ_selection (car (gimp-selection-is-empty img)))
(cond
(gimp-bucket-fill masque1 0 0 100 0 FALSE 0 0)
(gimp-bucket-fill masque2 0 0 100 0 FALSE 0 0)
(gimp-selection-none img))
(gimp-selection-layer-alpha Bump-Layer)
(gimp-bucket-fill masque1 0 0 100 0 FALSE 0 0)
(gimp-bucket-fill masque2 0 0 100 0 FALSE 0 0)
)
(gimp-by-color-select calque1 '(255 255 255) 0 0 FALSE FALSE 0 FALSE)
(gimp-context-set-background Bcolor)
(gimp-bucket-fill calque2 1 0 100 0 FALSE 0 0)
(gimp-selection-invert img)
(gimp-edit-clear calque2)
(gimp-selection-all img)
(plug-in-gauss 1 img Bump-Layer 10 10 0)
(plug-in-bump-map TRUE img Bunped_layer Bump-Layer 125 30 bumpmap_depth 0 0 0 0 TRUE TRUE LINEAR)
bumpmap on layer 2
(plug-in-bump-map TRUE img calque2 Bump-Layer 125 30 bumpmap_depth 0 0 0 0 TRUE TRUE LINEAR)
(plug-in-bump-map TRUE img calque2 calque2 125 45 bumpmap_depth 0 0 0 0 TRUE FALSE LINEAR)
(plug-in-lighting 1 img calque2 calque2 0 TRUE FALSE 0 0 blanc LightPX LightPY LightA -1.19 -7.14 1.00 0.9 2 2 LightA 10 TRUE FALSE FALSE)
(gimp-layer-set-mode calque1 8)
(gimp-layer-set-offsets Bump-Layer 18 12)
(plug-in-gauss 1 img Bump-Layer 20 20 0)
(gimp-layer-resize-to-image-size Bump-Layer)
(gimp-selection-layer-alpha Bump-Layer)
(gimp-selection-invert img)
(gimp-context-set-foreground fond-color)
(gimp-bucket-fill Bump-Layer 0 0 100 0 FALSE 0 0)
(gimp-selection-all img)
(gimp-palette-set-foreground old-fg)
(gimp-palette-set-background old-bg)
(if (= Crackeled TRUE)
layer 3
(let* ((calque3 (car (gimp-layer-copy calque2 TRUE))))
(gimp-image-add-layer img calque3 0)
(gimp-selection-layer-alpha calque2)
(gimp-palette-set-background Bcolor)
(plug-in-mosaic 1 img calque2 10 10 1 0 TRUE 175 0.3 TRUE FALSE 3 0 1)
(gimp-layer-set-mode calque3 21)))
(gimp-selection-all img)
(gimp-palette-set-foreground old-fg)
(gimp-palette-set-background old-bg)
(gimp-image-undo-group-end img)
(gimp-displays-flush))))
(define (script-fu-shiny-logo-alpha img Bump-Layer fond-color damage LightA LightPX LightPY Bcolor Crackeled bumpmap_depth)
(begin
(Aply-script-fu-shiny img Bump-Layer fond-color damage LightA LightPX LightPY Bcolor Crackeled bumpmap_depth)
(gimp-displays-flush)))
(script-fu-register "script-fu-shiny-logo-alpha"
_"<Image>/Filters/Alpha to Logo/Corroded Painting"
"Scott-effect : Shiny Corroded Painting"
"titix raymond and philippe"
"2001, titix and raymond 2007 Philippe Demartin"
"20.10.2007"
""
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
SF-COLOR "Background" '(178 178 178)
SF-ADJUSTMENT "Painting Damage %" '(70 10 100 1 0 0 0)
SF-ADJUSTMENT "Light Amount" '(0.70 0 10 0.1 1 2 0)
SF-ADJUSTMENT "Light Position X" '(0 -50 50 1 0 0 0)
SF-ADJUSTMENT "Light Position y" '(0 -50 50 1 0 0 0)
SF-COLOR "Painting Color" '(255 0 0)
SF-TOGGLE "Crackeled" FALSE
SF-ADJUSTMENT "Bumpmap depth" '(15 1 50 1 0 0 0))
(define (script-fu-shiny-logo font text Text-Color Back-color size damage LightA LightPX LightPY Bcolor Crackeled bumpmap_depth)
(border (/ size 4))
( background ( car ( gimp - layer - new img 256 256 RGBA - IMAGE " background " 90 0 ) ) )
(Text-Color (car (gimp-context-set-foreground Text-Color)))
(text-layer (car (gimp-text-fontname img -1 0 0 text border TRUE size PIXELS font)))
)
(gimp-layer-new img 256 256 RGBA-IMAGE "background" 90 0)
( gimp - edit - bucket - fill - full background 1 0 100 255 FALSE FALSE 0 0 0 )
(gimp-image-undo-disable img)
(Aply-script-fu-shiny img text-layer Back-color damage LightA LightPX LightPY Bcolor Crackeled bumpmap_depth)
(gimp-image-undo-enable img)
(gimp-display-new img)
))
(script-fu-register "script-fu-shiny-logo"
"Corroded Painting"
"Create corroded painted logo"
"Philippe Demartin"
"Inspired from the Corrosion script from titix and raymond"
"10/21/2007"
""
SF-FONT "Font Name" "Tahoma Bold"
SF-STRING "Enter your text" "Corroded..."
SF-COLOR "Font Color" '(133 52 2)
SF-COLOR "Background" '(178 178 178)
SF-ADJUSTMENT "Font size (pixels)" '(150 2 1000 1 10 0 1)
SF-ADJUSTMENT "Painting Damage %" '(70 10 100 1 0 0 0)
SF-ADJUSTMENT "Light Amount" '(0.70 0 10 0.01 1 2 0)
SF-ADJUSTMENT "Light Position X" '(0 -2 2 0.1 1 1 0)
SF-ADJUSTMENT "Light Position y" '(0 -2 2 0.1 1 1 1)
SF-COLOR "Painting Color" '(255 0 0)
SF-TOGGLE _"Crackeled" FALSE
SF-ADJUSTMENT "Bumpmap depth" '(15 1 50 1 0 0 0) )
(script-fu-menu-register "script-fu-shiny-logo"
"<Toolbox>/Xtns/Logos")
|
0eff73bec9a096fb2b9d0932d2f7e9b8108c2384422a8656e3870b6767d64707 | lambdacube3d/lambdacube-edsl | LC_U_DeBruijn.hs | module LC_U_DeBruijn where
import Data.ByteString.Char8 (ByteString)
import Data.Generics.Fixplate
import LC_U_APIType
import LC_U_PrimFun
TODO :
represent these as tuples from specific types : Vertex , Fragment , FragmentDepth , FragmentRastDepth
TODO:
represent these as tuples from specific types: Vertex, Fragment, FragmentDepth, FragmentRastDepth
-}
data Exp e
-- Fun
= Lam !e
| Body !e
| Let !e !e
De Bruijn index
| Apply !e !e
-- Exp
| Const !ExpValue
| Input !ByteString
| Use !e
| Cond !e !e !e
| PrimApp !PrimFun !e
| Tup [e]
| Prj Int !e
| Loop !e !e !e !e
-- Array operations
| ArrayFromList [e]
| ArrayReplicate !e !e
| ArrayGenerate !e !e
| ArrayIterateN !e !e !e
| ArrayIndex !e !e
| ArrayFilter !e !e
| ArrayMap !e !e
| ArrayZipWith !e !e !e
| ArrayAccumulate !e !e !e
-- GPU pipeline model
| Fetch !FetchPrimitive !e !(Maybe e)
| Transform !e !e
| Reassemble !e !e
| Rasterize RasterContext !e !(Maybe e) !e
| FrameBuffer [Image]
| Accumulate AccumulationContext !(Maybe e) !(Maybe e) !e !e !e !e
-- Transform feedback support
| ArrayFromStream !e
FrameBuffer and Image helpers
| PrjFrameBuffer Int !e
| PrjImage Int !e
-- Special tuple expressions
| Vertex !e !e [e] [e]
| Fragment [e]
| FragmentDepth !e [e]
| FragmentRastDepth [e]
-- Interpolated
| Flat !e
| Smooth !e
| NoPerspective !e
| GeometryShader Int OutputPrimitive Int !e !e !e
-- Output
| Output ByteString !e
| ScreenOutput !e
deriving (Eq, Ord, Show, Functor, Foldable, Traversable)
instance ShowF Exp where showsPrecF = showsPrec
instance EqF Exp where equalF = (==)
instance OrdF Exp where compareF = compare
| null | https://raw.githubusercontent.com/lambdacube3d/lambdacube-edsl/4347bb0ed344e71c0333136cf2e162aec5941df7/lambdacube-core/tmp/sandbox/lambdacube-unified-input/LC_U_DeBruijn.hs | haskell | Fun
Exp
Array operations
GPU pipeline model
Transform feedback support
Special tuple expressions
Interpolated
Output | module LC_U_DeBruijn where
import Data.ByteString.Char8 (ByteString)
import Data.Generics.Fixplate
import LC_U_APIType
import LC_U_PrimFun
TODO :
represent these as tuples from specific types : Vertex , Fragment , FragmentDepth , FragmentRastDepth
TODO:
represent these as tuples from specific types: Vertex, Fragment, FragmentDepth, FragmentRastDepth
-}
data Exp e
= Lam !e
| Body !e
| Let !e !e
De Bruijn index
| Apply !e !e
| Const !ExpValue
| Input !ByteString
| Use !e
| Cond !e !e !e
| PrimApp !PrimFun !e
| Tup [e]
| Prj Int !e
| Loop !e !e !e !e
| ArrayFromList [e]
| ArrayReplicate !e !e
| ArrayGenerate !e !e
| ArrayIterateN !e !e !e
| ArrayIndex !e !e
| ArrayFilter !e !e
| ArrayMap !e !e
| ArrayZipWith !e !e !e
| ArrayAccumulate !e !e !e
| Fetch !FetchPrimitive !e !(Maybe e)
| Transform !e !e
| Reassemble !e !e
| Rasterize RasterContext !e !(Maybe e) !e
| FrameBuffer [Image]
| Accumulate AccumulationContext !(Maybe e) !(Maybe e) !e !e !e !e
| ArrayFromStream !e
FrameBuffer and Image helpers
| PrjFrameBuffer Int !e
| PrjImage Int !e
| Vertex !e !e [e] [e]
| Fragment [e]
| FragmentDepth !e [e]
| FragmentRastDepth [e]
| Flat !e
| Smooth !e
| NoPerspective !e
| GeometryShader Int OutputPrimitive Int !e !e !e
| Output ByteString !e
| ScreenOutput !e
deriving (Eq, Ord, Show, Functor, Foldable, Traversable)
instance ShowF Exp where showsPrecF = showsPrec
instance EqF Exp where equalF = (==)
instance OrdF Exp where compareF = compare
|
41aa9bd4212245e235f15c4786f085cfc1505cdf39f6925b65299e1fdc1df822 | TheLortex/mirage-monorepo | ctf.mli | (** This library is used to write event traces in mirage-profile's CTF format. *)
type id = private int
(** Each thread/fiber/promise is identified by a unique ID. *)
* { 2 Recording events }
Libraries and applications can use these functions to make the traces more useful .
Libraries and applications can use these functions to make the traces more useful. *)
val label : string -> unit
(** [label msg] attaches text [msg] to the current thread. *)
val note_increase : string -> int -> unit
(** [note_increase counter delta] records that [counter] increased by [delta].
If [delta] is negative, this records a decrease. *)
val note_counter_value : string -> int -> unit
* [ note_counter_value counter value ] records that [ counter ] is now [ value ] .
val should_resolve : id -> unit
(** [should_resolve id] records that [id] is expected to resolve, and should be highlighted if it doesn't. *)
* { 2 Recording system events }
These are normally only called by the scheduler .
These are normally only called by the scheduler. *)
type hiatus_reason =
| Wait_for_work
| Suspend
| Hibernate
type event =
| Wait
| Task
| Bind
| Try
| Choose
| Pick
| Join
| Map
| Condition
| On_success
| On_failure
| On_termination
| On_any
| Ignore_result
| Async
| Promise
| Semaphore
| Switch
| Stream
| Mutex
(** Types of threads or other recorded objects. *)
val mint_id : unit -> id
(** [mint_id ()] is a fresh unique [id]. *)
val note_created : ?label:string -> id -> event -> unit
(** [note_created t id ty] records the creation of [id]. *)
val note_read : ?reader:id -> id -> unit
* [ src ] records that promise [ src ] 's value was read .
@param reader The thread doing the read ( default is the current thread ) .
@param reader The thread doing the read (default is the current thread). *)
val note_try_read : id -> unit
(** [note_try_read src] records that the current thread wants to read from [src] (which is not currently ready). *)
val note_switch : id -> unit
(** [note_switch id] records that [id] is now the current thread. *)
val note_hiatus : hiatus_reason -> unit
* [ note_hiatus r ] records that the system will sleep for reason [ r ] .
val note_resume : id -> unit
* [ note_resume i d ] records that the system has resumed ( used after { ! } ) ,
and is now running [ i d ] .
and is now running [id]. *)
val note_fork : unit -> id
(** [note_fork ()] records that a new thread has been forked and returns a fresh ID for it. *)
val note_resolved : id -> ex:exn option -> unit
(** [note_resolved id ~ex] records that [id] is now resolved.
If [ex = None] then [id] was successful, otherwise it failed with exception [ex]. *)
val note_signal : ?src:id -> id -> unit
(** [note_signal ~src dst] records that [dst] was signalled.
@param src The thread sending the signal (default is the current thread). *)
* { 2 Controlling tracing }
type log_buffer = (char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t
module Control : sig
type t
val make : timestamper:(log_buffer -> int -> unit) -> log_buffer -> t
(** [make ~timestamper b] is a trace buffer that record events in [b].
In most cases, the {!Ctf_unix} module provides a simpler interface. *)
val start : t -> unit
(** [start t] begins recording events in [t]. *)
val stop : t -> unit
(** [stop t] stops recording to [t] (which must be the current trace buffer). *)
end
(**/**)
module BS : sig
val set_int8 : Cstruct.buffer -> int -> int -> unit
val set_int64_le : Cstruct.buffer -> int -> int64 -> unit
end
| null | https://raw.githubusercontent.com/TheLortex/mirage-monorepo/0c29acffaf08dc0008097d36225a14960769f132/duniverse/eio/lib_eio/core/ctf.mli | ocaml | * This library is used to write event traces in mirage-profile's CTF format.
* Each thread/fiber/promise is identified by a unique ID.
* [label msg] attaches text [msg] to the current thread.
* [note_increase counter delta] records that [counter] increased by [delta].
If [delta] is negative, this records a decrease.
* [should_resolve id] records that [id] is expected to resolve, and should be highlighted if it doesn't.
* Types of threads or other recorded objects.
* [mint_id ()] is a fresh unique [id].
* [note_created t id ty] records the creation of [id].
* [note_try_read src] records that the current thread wants to read from [src] (which is not currently ready).
* [note_switch id] records that [id] is now the current thread.
* [note_fork ()] records that a new thread has been forked and returns a fresh ID for it.
* [note_resolved id ~ex] records that [id] is now resolved.
If [ex = None] then [id] was successful, otherwise it failed with exception [ex].
* [note_signal ~src dst] records that [dst] was signalled.
@param src The thread sending the signal (default is the current thread).
* [make ~timestamper b] is a trace buffer that record events in [b].
In most cases, the {!Ctf_unix} module provides a simpler interface.
* [start t] begins recording events in [t].
* [stop t] stops recording to [t] (which must be the current trace buffer).
*/* |
type id = private int
* { 2 Recording events }
Libraries and applications can use these functions to make the traces more useful .
Libraries and applications can use these functions to make the traces more useful. *)
val label : string -> unit
val note_increase : string -> int -> unit
val note_counter_value : string -> int -> unit
* [ note_counter_value counter value ] records that [ counter ] is now [ value ] .
val should_resolve : id -> unit
* { 2 Recording system events }
These are normally only called by the scheduler .
These are normally only called by the scheduler. *)
type hiatus_reason =
| Wait_for_work
| Suspend
| Hibernate
type event =
| Wait
| Task
| Bind
| Try
| Choose
| Pick
| Join
| Map
| Condition
| On_success
| On_failure
| On_termination
| On_any
| Ignore_result
| Async
| Promise
| Semaphore
| Switch
| Stream
| Mutex
val mint_id : unit -> id
val note_created : ?label:string -> id -> event -> unit
val note_read : ?reader:id -> id -> unit
* [ src ] records that promise [ src ] 's value was read .
@param reader The thread doing the read ( default is the current thread ) .
@param reader The thread doing the read (default is the current thread). *)
val note_try_read : id -> unit
val note_switch : id -> unit
val note_hiatus : hiatus_reason -> unit
* [ note_hiatus r ] records that the system will sleep for reason [ r ] .
val note_resume : id -> unit
* [ note_resume i d ] records that the system has resumed ( used after { ! } ) ,
and is now running [ i d ] .
and is now running [id]. *)
val note_fork : unit -> id
val note_resolved : id -> ex:exn option -> unit
val note_signal : ?src:id -> id -> unit
* { 2 Controlling tracing }
type log_buffer = (char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t
module Control : sig
type t
val make : timestamper:(log_buffer -> int -> unit) -> log_buffer -> t
val start : t -> unit
val stop : t -> unit
end
module BS : sig
val set_int8 : Cstruct.buffer -> int -> int -> unit
val set_int64_le : Cstruct.buffer -> int -> int64 -> unit
end
|
57b69ca50cf163a940e36cd3b53907e07eee126d4da8a39e725f6e5f44dcf092 | xvw/muhokama | category_endpoints.ml | open Lib_service.Endpoint
let list () = get (~/"category" / "list")
| null | https://raw.githubusercontent.com/xvw/muhokama/dcfa488169677ff7f1a3ed71182524aeb0b13c53/app/endpoints/category_endpoints.ml | ocaml | open Lib_service.Endpoint
let list () = get (~/"category" / "list")
|
|
4d2ca200b1c5d1cee1cd89097426af705dcd478a58b1b186f25fe9b003d31b56 | ghcjs/ghcjs | t8280.hs | # LANGUAGE MagicHash #
module Main where
import GHC.Prim
data A = A Word# deriving Show
main = print (A (int2Word# 4#))
| null | https://raw.githubusercontent.com/ghcjs/ghcjs/e4cd4232a31f6371c761acd93853702f4c7ca74c/test/ghc/deriving/t8280.hs | haskell | # LANGUAGE MagicHash #
module Main where
import GHC.Prim
data A = A Word# deriving Show
main = print (A (int2Word# 4#))
|
|
46c102bb55fb1d41c91c3caa93480f90dff0cb5c4d29f3c8debefae04b3041ed | bschwind/earthquakes | project.clj | (defproject earthquakes "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.9.0-alpha10"]
[org.clojure/clojurescript "1.9.198"]
[cljs-ajax "0.5.9"]
[reagent "0.6.0" :exclusions [cljsjs/react cljsjs/react-dom cljsjs/react-dom-server]]
[re-frame "0.8.0"]]
:plugins [[lein-cljsbuild "1.1.4"]
[lein-figwheel "0.5.8"]]
:clean-targets ["target/" "index.ios.js" "index.android.js"]
:aliases {"prod-build" ^{:doc "Recompile code with prod profile."}
["do" "clean"
["with-profile" "prod" "cljsbuild" "once"]]}
:profiles {:dev {:dependencies [[figwheel-sidecar "0.5.8"]
[com.cemerick/piggieback "0.2.1"]]
:source-paths ["src" "env/dev"]
:cljsbuild {:builds [{:id "ios"
:source-paths ["src" "env/dev"]
:figwheel true
:compiler {:output-to "target/ios/not-used.js"
:main "env.ios.main"
:output-dir "target/ios"
:optimizations :none}}
{:id "android"
:source-paths ["src" "env/dev"]
:figwheel true
:compiler {:output-to "target/android/not-used.js"
:main "env.android.main"
:output-dir "target/android"
:optimizations :none}}]}
:repl-options {:nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]}}
:prod {:cljsbuild {:builds [{:id "ios"
:source-paths ["src" "env/prod"]
:compiler {:output-to "index.ios.js"
:main "env.ios.main"
:output-dir "target/ios"
:static-fns true
:optimize-constants true
:optimizations :simple
:closure-defines {"goog.DEBUG" false}}}
{:id "android"
:source-paths ["src" "env/prod"]
:compiler {:output-to "index.android.js"
:main "env.android.main"
:output-dir "target/android"
:static-fns true
:optimize-constants true
:optimizations :simple
:closure-defines {"goog.DEBUG" false}}}]}}})
| null | https://raw.githubusercontent.com/bschwind/earthquakes/265d2e27504ee50f1a815a89a85601e9715af1d7/project.clj | clojure | (defproject earthquakes "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.9.0-alpha10"]
[org.clojure/clojurescript "1.9.198"]
[cljs-ajax "0.5.9"]
[reagent "0.6.0" :exclusions [cljsjs/react cljsjs/react-dom cljsjs/react-dom-server]]
[re-frame "0.8.0"]]
:plugins [[lein-cljsbuild "1.1.4"]
[lein-figwheel "0.5.8"]]
:clean-targets ["target/" "index.ios.js" "index.android.js"]
:aliases {"prod-build" ^{:doc "Recompile code with prod profile."}
["do" "clean"
["with-profile" "prod" "cljsbuild" "once"]]}
:profiles {:dev {:dependencies [[figwheel-sidecar "0.5.8"]
[com.cemerick/piggieback "0.2.1"]]
:source-paths ["src" "env/dev"]
:cljsbuild {:builds [{:id "ios"
:source-paths ["src" "env/dev"]
:figwheel true
:compiler {:output-to "target/ios/not-used.js"
:main "env.ios.main"
:output-dir "target/ios"
:optimizations :none}}
{:id "android"
:source-paths ["src" "env/dev"]
:figwheel true
:compiler {:output-to "target/android/not-used.js"
:main "env.android.main"
:output-dir "target/android"
:optimizations :none}}]}
:repl-options {:nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]}}
:prod {:cljsbuild {:builds [{:id "ios"
:source-paths ["src" "env/prod"]
:compiler {:output-to "index.ios.js"
:main "env.ios.main"
:output-dir "target/ios"
:static-fns true
:optimize-constants true
:optimizations :simple
:closure-defines {"goog.DEBUG" false}}}
{:id "android"
:source-paths ["src" "env/prod"]
:compiler {:output-to "index.android.js"
:main "env.android.main"
:output-dir "target/android"
:static-fns true
:optimize-constants true
:optimizations :simple
:closure-defines {"goog.DEBUG" false}}}]}}})
|
|
cee3356ac1ed005e996a28356ce6073d6980876b61e25f8872dce170c3799e2d | pirapira/coq2rust | proof_using.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2013
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
[ minimize_hyps e s1 ] gives [ s2 ] [ Id.Set.subset s2 s1 ] is [ true ]
* and [ e s1 ] is equal to [ e s2 ] . Inefficient .
* and [keep_hyps e s1] is equal to [keep_hyps e s2]. Inefficient. *)
val minimize_hyps : Environ.env -> Names.Id.Set.t -> Names.Id.Set.t
[ e s1 ] gives [ s2 ] [ Id.Set.subset s2 s1 ] is [ true ]
* and calling [ clear s1 ] would do the same as [ clear s2 ] . Inefficient .
* and s.t. calling [clear s1] would do the same as [clear s2]. Inefficient. *)
val minimize_unused_hyps : Environ.env -> Names.Id.Set.t -> Names.Id.Set.t
val process_expr :
Environ.env -> Vernacexpr.section_subset_descr -> Constr.types list ->
Names.Id.t list
val name_set : Names.Id.t -> Vernacexpr.section_subset_descr -> unit
val to_string : Vernacexpr.section_subset_descr -> string
val get_default_proof_using : unit -> string option
| null | https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/proofs/proof_using.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
********************************************************************** | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2013
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
[ minimize_hyps e s1 ] gives [ s2 ] [ Id.Set.subset s2 s1 ] is [ true ]
* and [ e s1 ] is equal to [ e s2 ] . Inefficient .
* and [keep_hyps e s1] is equal to [keep_hyps e s2]. Inefficient. *)
val minimize_hyps : Environ.env -> Names.Id.Set.t -> Names.Id.Set.t
[ e s1 ] gives [ s2 ] [ Id.Set.subset s2 s1 ] is [ true ]
* and calling [ clear s1 ] would do the same as [ clear s2 ] . Inefficient .
* and s.t. calling [clear s1] would do the same as [clear s2]. Inefficient. *)
val minimize_unused_hyps : Environ.env -> Names.Id.Set.t -> Names.Id.Set.t
val process_expr :
Environ.env -> Vernacexpr.section_subset_descr -> Constr.types list ->
Names.Id.t list
val name_set : Names.Id.t -> Vernacexpr.section_subset_descr -> unit
val to_string : Vernacexpr.section_subset_descr -> string
val get_default_proof_using : unit -> string option
|
d5b5ea29f3e1e87605718069d8d7f95627ed3dcc48a64d29daa1d89c6f12bea7 | bellissimogiorno/nominal | Name.hs | |
Module : Name
Description : Nominal theory of names and swappings
Copyright : ( c ) , 2020
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
The basic framework : a nominal theory of names and swappings
Module : Name
Description : Nominal theory of names and swappings
Copyright : (c) Murdoch J. Gabbay, 2020
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
The basic framework: a nominal theory of names and swappings
-}
# LANGUAGE ConstraintKinds
, , DefaultSignatures
, , DeriveGeneric
, DerivingStrategies
, DerivingVia
, DeriveDataTypeable
, DeriveFunctor
, , , EmptyCase
, EmptyDataDeriving
, FlexibleContexts
, FlexibleInstances
, GADTs
, GeneralizedNewtypeDeriving
, InstanceSigs
, MultiParamTypeClasses
, PartialTypeSignatures
, , StandaloneDeriving
, TupleSections
#
, DataKinds
, DefaultSignatures
, DeriveAnyClass
, DeriveGeneric
, DerivingStrategies
, DerivingVia
, DeriveDataTypeable
, DeriveFunctor
, DeriveFoldable
, DeriveTraversable
, EmptyCase
, EmptyDataDeriving
, FlexibleContexts
, FlexibleInstances
, GADTs
, GeneralizedNewtypeDeriving
, InstanceSigs
, MultiParamTypeClasses
, PartialTypeSignatures
, ScopedTypeVariables
, StandaloneDeriving
, TupleSections
#-}
module Language.Nominal.Name
( -- $setup
-- * Atoms
KAtom (..)
, Atom
, Tom -- (..)
, atTom
-- * Creating atoms
, freshKAtomsIO
, freshAtomsIO
, freshKAtomIO
, freshAtomIO
-- * Atom swapping
, Swappable (..)
, swp
-- * Permutations
, KPerm
, Perm
, perm
-- * Names
, KName (..)
, Name
, withLabel
, withLabelOf
, justALabel
, justAnAtom
-- * Name swapping
, kswpN
, swpN
-- * Nameless types
, Nameless (..)
-- * Tests
-- $tests
)
where
import Data.Data hiding (typeRep, TypeRep)
import Data.List.NonEmpty (NonEmpty)
for testEquality
import qualified Data.Map as DM
import qualified Data.Set as S
import GHC.Generics hiding (Prefix)
import Type.Reflection
import Language.Nominal.Unique
import Language.Nominal.Utilities
{- $setup
-}
-- * Atoms
-- | An atom is a unique atomic token.
--
The argument @s@ of ' ' is part of facilities offered by this package for declaring types of atom @s@ ranging over kinds @k@. For usage see ' Language . Nominal . Examples . SystemF.ATyp ' , and ' Language . Nominal . Examples . SystemF.ATrm ' in " Language . Nominal . Examples . SystemF " .
--
/If your development requires just a single type of atomic tokens , ignore ' ' and use ' Atom'./
newtype KAtom s = Atom Unique
deriving (Eq, Ord, Generic, Typeable, Data)
-- | We provide a stock datatype @'Tom'@.
--
Using the @DataKinds@ package , this is then used to provide a stock type of atoms @'Atom'@.
data Tom
deriving (Eq, Ord, Generic, Typeable, Data)
| A proxy element for sort @'Tom'@. If we pass this , we tell the typechecker we are " at " .
atTom :: Proxy Tom
atTom = Proxy
-- | A distinguished type of atoms.
--
It is populated by @'Tom'@s ( below ) , thus an element of @'Atom'@ is " a " .
--
We provide @'Atom'@ as primitive for convenience . If you need more than one type of atom ( e.g. term atoms and type atoms ) , look at ' ' .
type Atom = KAtom Tom
-- | Display an atom by showing (the hash of) its unique id.
instance Show (KAtom s) where
show (Atom a) = "_" ++ show (hashUnique a)
-- * Creating atoms
| Make a fresh atom for each element of some list ( @a@ny list ) . /If you just want one fresh atom , use e.g. @[()]@./
--
-- This is an IO action; when executed, fresh identifiers get generated.
freshKAtomsIO :: Traversable m => m a -> IO (m (KAtom s))
freshKAtomsIO = mapM (const $ Atom <$> newUnique)
-- | Make a fresh atom at @'Tom'@ for each element of some list (@a@ny list).
freshAtomsIO :: Traversable m => m a -> IO (m Atom)
freshAtomsIO = freshKAtomsIO
| For convenience : generate a fresh katom
freshKAtomIO :: IO (KAtom s)
freshKAtomIO = head <$> freshKAtomsIO [()]
-- | For convenience: generate a fresh atom
--
-- >>> a <- freshAtomIO
-- >>> b <- freshAtomIO
-- >>> a == b
-- False
freshAtomIO :: IO Atom
freshAtomIO = head <$> freshAtomsIO [()]
-- * Atom swapping
-- | Types that admit a __swapping action__.
--
-- A swapping @(a b)@ maps
--
* @a@ to and
-- * @b@ to @a@ and
* any other @c@ to
--
Swappings are invertible , which allows them to commute through type - formers containing negative arities , e.g. the left - hand argument of function arrow . Swappings always distribute :
--
-- > swp a b (x, y) == (swp a b x, swp a b y)
-- > swp a b [x1, x2, x3] == [swp a b x1, swp a b x2, swp a b x3]
-- > swp a b (f x) == (swp a b f) (swp a b x)
> swp a b ( abst n x ) = = abst ( swp a b n ) ( swp a b x )
-- > swp a b (res [n] x) == res [swp a b n] (swp a b x)
-- > swp a b (Name t x) == Name (swp a b t) (swp a b x)
--
_ _ Technical note : _ _ The content of @Swappable a@ is that @a@ supports a swapping action by atoms of every @s@. Everything else , e.g. ' Language . Nominal . Nameset . ' , just uses @s@. So @k@ is a " world " of sorts of atoms , for a particular application .
This is invisible at our default world @'Tom'@ because @'Tom'@ has only one inhabitant , @''Tom'@. See ' Language . Nominal . Examples . SystemF.ASort ' and surrounding code for a more sophisticated atoms setup .
class Swappable a where
kswp :: Typeable s => KAtom s -> KAtom s -> a -> a -- swap n and n' in a
default kswp :: (Typeable s, Generic a, GSwappable (Rep a)) => KAtom s -> KAtom s -> a -> a
kswp n n' = to . gswp n n' . from
-- | A @'Tom'@-swapping
swp :: Swappable a => Atom -> Atom -> a -> a
swp = kswp
Do n't need ( ) instance because captured by @'Nameless'@ instance Swappable a = > Swappable ( )
instance Swappable a => Swappable (Maybe a)
instance Swappable a => Swappable [a]
instance Swappable a => Swappable (NonEmpty a)
instance (Ord a, Swappable a) => Swappable (S.Set a) where
kswp a1 a2 s = S.fromList $ kswp a1 a2 (S.toList s) -- Ord a so we can use fromList
instance (Swappable a, Swappable b) => Swappable (a, b)
instance (Swappable a, Swappable b, Swappable c) => Swappable (a,b,c)
instance (Swappable a, Swappable b, Swappable c, Swappable d) => Swappable (a,b,c,d)
instance (Swappable a, Swappable b, Swappable c, Swappable d, Swappable e) => Swappable (a,b,c,d,e)
instance (Swappable a, Swappable b) => Swappable (Either a b)
-- | Swap distributes over function types, because functions inherit swapping action pointwise (also called the /conjugation action/)
instance (Swappable a, Swappable b) => Swappable (a -> b) where
kswp a1 a2 f = kswp a1 a2 . f . kswp a1 a2
-- | Swap distributes over map types.
--
Note that maps store their keys ordered for quick lookup , so a swapping acting on a map is not a noop and can provoke reorderings .
instance (Swappable a, Swappable b, Ord a) => Swappable (DM.Map a b) where
kswp n1 n2 m = DM.fromList $ kswp n1 n2 (DM.toList m) -- This design treats a map explicitly as its graph (list of pairs). Could also view it as a function, and consider implementing conjugation action using DM.map and/or DM.mapKeys
-- | Base case for swapping: atoms acting on atoms.
instance Typeable s => Swappable (KAtom s) where -- typeable constraint gives us type representatives which allows the runtime type equality test (technically: type representation equality test) below.
kswp (a1 :: KAtom t) (a2 :: KAtom t) (a :: KAtom s) = -- explicit type annotations for clarity here
case testEquality (typeRep :: TypeRep t) (typeRep :: TypeRep s) of
Nothing -> a -- are s and t are different types
Just Refl -- are s and t the same type?
| a == a1 -> a2
| a == a2 -> a1
| otherwise -> a
-- * Permutations
-- | A permutation represented as a list of swappings (simple but inefficient).
type KPerm s = [(KAtom s, KAtom s)]
-- | A permutation at @'Tom'@.
type Perm = KPerm Tom
| A permutation acts as a list of swappings . Rightmost / innermost swapping acts first .
--
-- >>> a <- freshAtomIO
-- >>> b <- freshAtomIO
-- >>> c <- freshAtomIO
-- >>> perm [(c,b), (b,a)] a == c
-- True
perm :: (Typeable s, Swappable a) => KPerm s -> a -> a
perm = chain . map (uncurry kswp)
-- * Names
-- | A name is a pair of
--
-- * an atom, and
* a label
--
-- @t@ is intended to store semantic information about the atom. For instance, if implementing a simply-typed lambda-calculus then @t@ might be a dataype of (object-level) types.
--
A similar effect could be achieved by maintaining a monadic lookup context relating atoms to their semantic information ; the advantage of using a name is that this information is packaged up with the atom in a local datum of type @'Name'@.
data KName s t = Name { nameLabel :: t, nameAtom :: KAtom s}
deriving (Generic, Functor, Foldable, Traversable, Typeable, Data)
-- | Swapping atoms in names distributes normally; so we swap in the semantic label and also in the name's atom identifier. Operationally, it's just a tuple action:
--
-- > swp atm1 atm2 (Name t atm) = Name (swp atm1 atm2 t) (swp atm1 atm2 atm)
instance (Typeable s, Swappable t) => Swappable (KName s t)
-- | A @'Tom'@ instance of @'KName'@.
type Name = KName Tom
-- | Names are equal when they refer to the same atom.
--
-- WARNING: Labels are not considered!
-- In particular, @t@-names always have @'Eq'@, even if the type of labels @t@ does not.
instance Eq (KName s t) where
n1 == n2 = nameAtom n1 == nameAtom n2
| Names are leq when their atoms are leq .
--
-- WARNING: Labels are not considered!
-- In particular, @t@-names are always ordered even if /labels/ @t@ are unordered.
instance Ord (KName s t) where
n1 `compare` n2 = nameAtom n1 `compare` nameAtom n2
instance Show t => Show (KName s t) where
show nam = show (nameLabel nam) ++ show (nameAtom nam)
instance {-# OVERLAPPING #-} Show (KName s ()) where
show nam = "n" ++ show (nameAtom nam)
-- | As the name suggests: overwrite the name's label
withLabel :: KName s t -> t -> KName s t
n `withLabel` t = const t <$> n -- functorial action automatically derived
| Overwrite the name 's label . Intended to be read infix as @n ` withLabelOf n'@
withLabelOf :: KName s t -> KName s t -> KName s t
n `withLabelOf` n' = n `withLabel` (nameLabel n')
-- | Name with @'undefined'@ atom, so really just a label. Use with care!
justALabel :: t -> KName s t
justALabel = flip Name undefined
-- | Name with @'undefined'@ label, so really just an atom. Use with care!
justAnAtom :: KAtom s -> KName s t
justAnAtom = Name undefined
-- * Name swapping
| A name swap discards the names ' labels and calls the atom - swap @'kswp'@.
kswpN :: (Typeable s, Swappable a) => KName s t -> KName s t -> a -> a
kswpN n n' = kswp (nameAtom n) (nameAtom n')
| A name swap for a @'Tom'@-name . Discards the names ' labels and calls a swapping .
swpN :: Swappable a => Name t -> Name t -> a -> a
swpN = kswpN
-- * Nameless types
| Some types , like @'Bool'@ and @'String'@ , are @'Nameless'@. E.g. if we have a truth - value , we know it does n't have any names in it ; we might have used names to calculate the truth - value , but the truth - value itself @'True'@ or @'False'@ is nameless .
newtype Nameless a = Nameless {getNameless :: a}
deriving (Show, Read, Eq, Ord)
instance Swappable (Nameless a) where
kswp _ _ = id
-- TODO: KEquivar s (Nameless a) where
KEquivar s ( Nameless a ) where
_ = i d
-- deriving via is described in:
-- Deriving Via: or, How to Turn Hand-Written Instances into an Anti-Pattern
-- -via-paper.pdf
deriving via Nameless Bool instance Swappable Bool
deriving via Nameless Int instance Swappable Int
deriving via Nameless Integer instance Swappable Integer
deriving via Nameless () instance Swappable ()
deriving via Nameless Char instance Swappable Char
* Generics support for @'KSwappable'@
class GSwappable f where
gswp :: Typeable s => KAtom s -> KAtom s -> f x -> f x
instance GSwappable V1 where -- empty types, no instances
gswp _ _ x = case x of
one constructor , no arguments
gswp _ _ U1 = U1
instance Swappable c => GSwappable (K1 i c) where -- base case. wrapper for all of some type c so we escape back out to swp.
gswp m n x = K1 $ kswp m n $ unK1 x
instance (GSwappable f, GSwappable g) => GSwappable ((:*:) f g) where -- products
gswp m n (x :*: y) = gswp m n x :*: gswp m n y
instance (GSwappable f, GSwappable g) => GSwappable ((:+:) f g) where -- sums
gswp m n (L1 x) = L1 $ gswp m n x
gswp m n (R1 y) = R1 $ gswp m n y
meta - information . e.g. constructor names ( like for generic show method ) , fixity information ; all captured by M1 type . this is transparent for swappings
gswp m n = M1 . gswp m n . unM1
$ tests Property - based tests are in " Language . Nominal . Properties . NameSpec " .
| null | https://raw.githubusercontent.com/bellissimogiorno/nominal/ab3306ee349dc481d2e2e6d103d90ffdd14ccaa9/src/Language/Nominal/Name.hs | haskell | $setup
* Atoms
(..)
* Creating atoms
* Atom swapping
* Permutations
* Names
* Name swapping
* Nameless types
* Tests
$tests
$setup
* Atoms
| An atom is a unique atomic token.
| We provide a stock datatype @'Tom'@.
| A distinguished type of atoms.
| Display an atom by showing (the hash of) its unique id.
* Creating atoms
This is an IO action; when executed, fresh identifiers get generated.
| Make a fresh atom at @'Tom'@ for each element of some list (@a@ny list).
| For convenience: generate a fresh atom
>>> a <- freshAtomIO
>>> b <- freshAtomIO
>>> a == b
False
* Atom swapping
| Types that admit a __swapping action__.
A swapping @(a b)@ maps
* @b@ to @a@ and
> swp a b (x, y) == (swp a b x, swp a b y)
> swp a b [x1, x2, x3] == [swp a b x1, swp a b x2, swp a b x3]
> swp a b (f x) == (swp a b f) (swp a b x)
> swp a b (res [n] x) == res [swp a b n] (swp a b x)
> swp a b (Name t x) == Name (swp a b t) (swp a b x)
swap n and n' in a
| A @'Tom'@-swapping
Ord a so we can use fromList
| Swap distributes over function types, because functions inherit swapping action pointwise (also called the /conjugation action/)
| Swap distributes over map types.
This design treats a map explicitly as its graph (list of pairs). Could also view it as a function, and consider implementing conjugation action using DM.map and/or DM.mapKeys
| Base case for swapping: atoms acting on atoms.
typeable constraint gives us type representatives which allows the runtime type equality test (technically: type representation equality test) below.
explicit type annotations for clarity here
are s and t are different types
are s and t the same type?
* Permutations
| A permutation represented as a list of swappings (simple but inefficient).
| A permutation at @'Tom'@.
>>> a <- freshAtomIO
>>> b <- freshAtomIO
>>> c <- freshAtomIO
>>> perm [(c,b), (b,a)] a == c
True
* Names
| A name is a pair of
* an atom, and
@t@ is intended to store semantic information about the atom. For instance, if implementing a simply-typed lambda-calculus then @t@ might be a dataype of (object-level) types.
| Swapping atoms in names distributes normally; so we swap in the semantic label and also in the name's atom identifier. Operationally, it's just a tuple action:
> swp atm1 atm2 (Name t atm) = Name (swp atm1 atm2 t) (swp atm1 atm2 atm)
| A @'Tom'@ instance of @'KName'@.
| Names are equal when they refer to the same atom.
WARNING: Labels are not considered!
In particular, @t@-names always have @'Eq'@, even if the type of labels @t@ does not.
WARNING: Labels are not considered!
In particular, @t@-names are always ordered even if /labels/ @t@ are unordered.
# OVERLAPPING #
| As the name suggests: overwrite the name's label
functorial action automatically derived
| Name with @'undefined'@ atom, so really just a label. Use with care!
| Name with @'undefined'@ label, so really just an atom. Use with care!
* Name swapping
* Nameless types
TODO: KEquivar s (Nameless a) where
deriving via is described in:
Deriving Via: or, How to Turn Hand-Written Instances into an Anti-Pattern
-via-paper.pdf
empty types, no instances
base case. wrapper for all of some type c so we escape back out to swp.
products
sums | |
Module : Name
Description : Nominal theory of names and swappings
Copyright : ( c ) , 2020
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
The basic framework : a nominal theory of names and swappings
Module : Name
Description : Nominal theory of names and swappings
Copyright : (c) Murdoch J. Gabbay, 2020
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
The basic framework: a nominal theory of names and swappings
-}
# LANGUAGE ConstraintKinds
, , DefaultSignatures
, , DeriveGeneric
, DerivingStrategies
, DerivingVia
, DeriveDataTypeable
, DeriveFunctor
, , , EmptyCase
, EmptyDataDeriving
, FlexibleContexts
, FlexibleInstances
, GADTs
, GeneralizedNewtypeDeriving
, InstanceSigs
, MultiParamTypeClasses
, PartialTypeSignatures
, , StandaloneDeriving
, TupleSections
#
, DataKinds
, DefaultSignatures
, DeriveAnyClass
, DeriveGeneric
, DerivingStrategies
, DerivingVia
, DeriveDataTypeable
, DeriveFunctor
, DeriveFoldable
, DeriveTraversable
, EmptyCase
, EmptyDataDeriving
, FlexibleContexts
, FlexibleInstances
, GADTs
, GeneralizedNewtypeDeriving
, InstanceSigs
, MultiParamTypeClasses
, PartialTypeSignatures
, ScopedTypeVariables
, StandaloneDeriving
, TupleSections
#-}
module Language.Nominal.Name
KAtom (..)
, Atom
, atTom
, freshKAtomsIO
, freshAtomsIO
, freshKAtomIO
, freshAtomIO
, Swappable (..)
, swp
, KPerm
, Perm
, perm
, KName (..)
, Name
, withLabel
, withLabelOf
, justALabel
, justAnAtom
, kswpN
, swpN
, Nameless (..)
)
where
import Data.Data hiding (typeRep, TypeRep)
import Data.List.NonEmpty (NonEmpty)
for testEquality
import qualified Data.Map as DM
import qualified Data.Set as S
import GHC.Generics hiding (Prefix)
import Type.Reflection
import Language.Nominal.Unique
import Language.Nominal.Utilities
The argument @s@ of ' ' is part of facilities offered by this package for declaring types of atom @s@ ranging over kinds @k@. For usage see ' Language . Nominal . Examples . SystemF.ATyp ' , and ' Language . Nominal . Examples . SystemF.ATrm ' in " Language . Nominal . Examples . SystemF " .
/If your development requires just a single type of atomic tokens , ignore ' ' and use ' Atom'./
newtype KAtom s = Atom Unique
deriving (Eq, Ord, Generic, Typeable, Data)
Using the @DataKinds@ package , this is then used to provide a stock type of atoms @'Atom'@.
data Tom
deriving (Eq, Ord, Generic, Typeable, Data)
| A proxy element for sort @'Tom'@. If we pass this , we tell the typechecker we are " at " .
atTom :: Proxy Tom
atTom = Proxy
It is populated by @'Tom'@s ( below ) , thus an element of @'Atom'@ is " a " .
We provide @'Atom'@ as primitive for convenience . If you need more than one type of atom ( e.g. term atoms and type atoms ) , look at ' ' .
type Atom = KAtom Tom
instance Show (KAtom s) where
show (Atom a) = "_" ++ show (hashUnique a)
| Make a fresh atom for each element of some list ( @a@ny list ) . /If you just want one fresh atom , use e.g. @[()]@./
freshKAtomsIO :: Traversable m => m a -> IO (m (KAtom s))
freshKAtomsIO = mapM (const $ Atom <$> newUnique)
freshAtomsIO :: Traversable m => m a -> IO (m Atom)
freshAtomsIO = freshKAtomsIO
| For convenience : generate a fresh katom
freshKAtomIO :: IO (KAtom s)
freshKAtomIO = head <$> freshKAtomsIO [()]
freshAtomIO :: IO Atom
freshAtomIO = head <$> freshAtomsIO [()]
* @a@ to and
* any other @c@ to
Swappings are invertible , which allows them to commute through type - formers containing negative arities , e.g. the left - hand argument of function arrow . Swappings always distribute :
> swp a b ( abst n x ) = = abst ( swp a b n ) ( swp a b x )
_ _ Technical note : _ _ The content of @Swappable a@ is that @a@ supports a swapping action by atoms of every @s@. Everything else , e.g. ' Language . Nominal . Nameset . ' , just uses @s@. So @k@ is a " world " of sorts of atoms , for a particular application .
This is invisible at our default world @'Tom'@ because @'Tom'@ has only one inhabitant , @''Tom'@. See ' Language . Nominal . Examples . SystemF.ASort ' and surrounding code for a more sophisticated atoms setup .
class Swappable a where
default kswp :: (Typeable s, Generic a, GSwappable (Rep a)) => KAtom s -> KAtom s -> a -> a
kswp n n' = to . gswp n n' . from
swp :: Swappable a => Atom -> Atom -> a -> a
swp = kswp
Do n't need ( ) instance because captured by @'Nameless'@ instance Swappable a = > Swappable ( )
instance Swappable a => Swappable (Maybe a)
instance Swappable a => Swappable [a]
instance Swappable a => Swappable (NonEmpty a)
instance (Ord a, Swappable a) => Swappable (S.Set a) where
instance (Swappable a, Swappable b) => Swappable (a, b)
instance (Swappable a, Swappable b, Swappable c) => Swappable (a,b,c)
instance (Swappable a, Swappable b, Swappable c, Swappable d) => Swappable (a,b,c,d)
instance (Swappable a, Swappable b, Swappable c, Swappable d, Swappable e) => Swappable (a,b,c,d,e)
instance (Swappable a, Swappable b) => Swappable (Either a b)
instance (Swappable a, Swappable b) => Swappable (a -> b) where
kswp a1 a2 f = kswp a1 a2 . f . kswp a1 a2
Note that maps store their keys ordered for quick lookup , so a swapping acting on a map is not a noop and can provoke reorderings .
instance (Swappable a, Swappable b, Ord a) => Swappable (DM.Map a b) where
case testEquality (typeRep :: TypeRep t) (typeRep :: TypeRep s) of
| a == a1 -> a2
| a == a2 -> a1
| otherwise -> a
type KPerm s = [(KAtom s, KAtom s)]
type Perm = KPerm Tom
| A permutation acts as a list of swappings . Rightmost / innermost swapping acts first .
perm :: (Typeable s, Swappable a) => KPerm s -> a -> a
perm = chain . map (uncurry kswp)
* a label
A similar effect could be achieved by maintaining a monadic lookup context relating atoms to their semantic information ; the advantage of using a name is that this information is packaged up with the atom in a local datum of type @'Name'@.
data KName s t = Name { nameLabel :: t, nameAtom :: KAtom s}
deriving (Generic, Functor, Foldable, Traversable, Typeable, Data)
instance (Typeable s, Swappable t) => Swappable (KName s t)
type Name = KName Tom
instance Eq (KName s t) where
n1 == n2 = nameAtom n1 == nameAtom n2
| Names are leq when their atoms are leq .
instance Ord (KName s t) where
n1 `compare` n2 = nameAtom n1 `compare` nameAtom n2
instance Show t => Show (KName s t) where
show nam = show (nameLabel nam) ++ show (nameAtom nam)
show nam = "n" ++ show (nameAtom nam)
withLabel :: KName s t -> t -> KName s t
| Overwrite the name 's label . Intended to be read infix as @n ` withLabelOf n'@
withLabelOf :: KName s t -> KName s t -> KName s t
n `withLabelOf` n' = n `withLabel` (nameLabel n')
justALabel :: t -> KName s t
justALabel = flip Name undefined
justAnAtom :: KAtom s -> KName s t
justAnAtom = Name undefined
| A name swap discards the names ' labels and calls the atom - swap @'kswp'@.
kswpN :: (Typeable s, Swappable a) => KName s t -> KName s t -> a -> a
kswpN n n' = kswp (nameAtom n) (nameAtom n')
| A name swap for a @'Tom'@-name . Discards the names ' labels and calls a swapping .
swpN :: Swappable a => Name t -> Name t -> a -> a
swpN = kswpN
| Some types , like @'Bool'@ and @'String'@ , are @'Nameless'@. E.g. if we have a truth - value , we know it does n't have any names in it ; we might have used names to calculate the truth - value , but the truth - value itself @'True'@ or @'False'@ is nameless .
newtype Nameless a = Nameless {getNameless :: a}
deriving (Show, Read, Eq, Ord)
instance Swappable (Nameless a) where
kswp _ _ = id
KEquivar s ( Nameless a ) where
_ = i d
deriving via Nameless Bool instance Swappable Bool
deriving via Nameless Int instance Swappable Int
deriving via Nameless Integer instance Swappable Integer
deriving via Nameless () instance Swappable ()
deriving via Nameless Char instance Swappable Char
* Generics support for @'KSwappable'@
class GSwappable f where
gswp :: Typeable s => KAtom s -> KAtom s -> f x -> f x
gswp _ _ x = case x of
one constructor , no arguments
gswp _ _ U1 = U1
gswp m n x = K1 $ kswp m n $ unK1 x
gswp m n (x :*: y) = gswp m n x :*: gswp m n y
gswp m n (L1 x) = L1 $ gswp m n x
gswp m n (R1 y) = R1 $ gswp m n y
meta - information . e.g. constructor names ( like for generic show method ) , fixity information ; all captured by M1 type . this is transparent for swappings
gswp m n = M1 . gswp m n . unM1
$ tests Property - based tests are in " Language . Nominal . Properties . NameSpec " .
|
442487d253de1dfceb6ef70c7e863b547159095258f2193d81502402b8fa7932 | shayne-fletcher/zen | ml_typedtree.ml | open Ml_misc
open Ml_asttypes
open Ml_types
type partial = | Partial | Total
type pattern = {
pat_desc : pattern_desc;
pat_loc : Ml_location.t;
}
and pattern_desc =
| Tpat_any
(** _ *)
| Tpat_var of Ml_ident.t * string loc
(** x *)
| Tpat_alias of pattern * Ml_ident.t * string loc
(** P as a*)
| Tpat_constant of constant
* 1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n
| Tpat_tuple of pattern list
* ( P1 , ... , Pn )
Invariant : n > = 2
Invariant : n >= 2
*)
| Tpat_construct of
Ml_longident.t loc * constructor_description * pattern list
* C [ ]
C P [ P ]
C ( P1 , ... , Pn ) [ P1 ; ... ; Pn ]
C P [P]
C (P1, ..., Pn) [P1; ...; Pn]
*)
| Tpat_or of pattern * pattern
(** P1 | P2 *)
and expression =
{ exp_desc : expression_desc;
exp_loc : Ml_location.t;
}
and expression_desc =
| Texp_ident of Ml_path.t * Ml_longident.t loc * Ml_types.value_description
* x
M.x
*)
| Texp_constant of constant
* 1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n
| Texp_let of rec_flag * value_binding list * expression
* let P1 = E1 and ... and Pn = EN in E ( flag = )
let rec P1 = E1 and ... and Pn = EN in E ( flag = Recursive )
let rec P1 = E1 and ... and Pn = EN in E (flag = Recursive)
*)
| Texp_function of case list * partial
* [ Pexp_fun ] and [ Pexp_function ] both translate to [ Texp_function ] .
See { ! for more details .
partial =
[ Partial ] if the pattern match is partial
[ Total ] otherwise .
See {!Parsetree} for more details.
partial =
[Partial] if the pattern match is partial
[Total] otherwise.
*)
| Texp_apply of expression * expression list
* E0 E1 ... En
For example :
let f x y = x + y in
f 3
The resulting typedtree for the application is :
Texp_apply ( Texp_ident " f/1490 " ,
[ Texp_constant Const_int 3 ] )
For example:
let f x y = x + y in
f 3
The resulting typedtree for the application is:
Texp_apply (Texp_ident "f/1490",
[Texp_constant Const_int 3])
*)
| Texp_match of expression * case list * case list * partial
* match E0 with
| P1 - > E1
| P2 - > E2
| exception P3 - > E3
[ Texp_match ( E0 , [ ( P1 , E1 ) ; ( P2 , E2 ) ] , [ ( P3 , E3 ) ] , _ ) ]
| P1 -> E1
| P2 -> E2
| exception P3 -> E3
[Texp_match (E0, [(P1, E1); (P2, E2)], [(P3, E3)], _)]
*)
| Texp_tuple of expression list
(** (E1, ..., EN) *)
| Texp_construct of
Ml_longident.t loc * constructor_description * expression list
(** C []
C E [E]
C (E1, ..., En) [E1;...;En]
*)
| T_expifthenelse of expression * expression * expression
and case =
{
c_lhs : pattern;
c_rhs : expression;
}
and structure =
{
str_desc : structure_item_desc;
str_loc : Ml_location.t;
}
and structure_item_desc =
| Tstr_eval of expression
| Tstr_value of rec_flag * value_binding list
| Tstr_primitive of value_description
and value_binding =
{
vb_pat : pattern;
vb_expr : expression;
vb_loc : Ml_location.t;
}
let iter_pattern_desc f = function
| Tpat_alias (p, _, _) -> f p
| Tpat_tuple ps -> List.iter f ps
| Tpat_construct (_, _, ps) -> List.iter f ps
| Tpat_or (p1, p2) -> f p1; f p2
| Tpat_any | Tpat_var _ | Tpat_constant _ -> ()
let map_pattern_desc f d = match d with
| Tpat_alias (p, id, loc) -> Tpat_alias (f p, id, loc)
| Tpat_tuple ps -> Tpat_tuple (List.map f ps)
| Tpat_construct (lid, c, ps) -> Tpat_construct (lid, c, List.map f ps)
| Tpat_or (p1, p2) -> Tpat_or (f p1, f p2)
| Tpat_any | Tpat_var _ | Tpat_constant _ -> d
(*List the identifiers bound by a pattern or a let*)
let idents = ref ([] : (Ml_ident.t * string loc) list)
let rec bound_idents pat = match pat.pat_desc with
| Tpat_var (id, s) -> idents := (id, s) :: !idents
| Tpat_alias (p, id, s) ->
bound_idents p; idents := (id, s) :: !idents
| Tpat_or (p1, _) ->
(*Invariant : both arguments bind the same variables*)
bound_idents p1
| d -> iter_pattern_desc bound_idents d
let pat_bound_idents pat =
idents := [];
bound_idents pat;
let res = !idents in
idents := [];
List.map fst res
let rev_let_bound_idents_with_loc bindings =
idents := [];
List.iter (fun vb -> bound_idents vb.vb_pat) bindings;
let res = !idents in idents := []; res
let let_bound_idents_with_loc pat_expr_list =
List.rev (rev_let_bound_idents_with_loc pat_expr_list)
let rev_let_bound_idents pat = List.map fst (rev_let_bound_idents_with_loc pat)
let let_bound_idents pat = List.map fst (let_bound_idents_with_loc pat)
let alpha_var env id = List.assoc id env
let rec alpha_pat env p = match p.pat_desc with
| Tpat_var (id, s) -> (* note the [Not_found] case*)
{p with pat_desc =
try Tpat_var (alpha_var env id, s) with
| Not_found -> Tpat_any }
| Tpat_alias (p1, id, s) ->
let new_p = alpha_pat env p1 in
begin try
{p with pat_desc = Tpat_alias (new_p, alpha_var env id, s)}
with
| Not_found -> new_p
end
| d ->
{p with pat_desc = map_pattern_desc (alpha_pat env) d}
let mkloc = Ml_location.mkloc
let mknoloc = Ml_location.mknoloc
| null | https://raw.githubusercontent.com/shayne-fletcher/zen/10a1d0b9bf261bb133918dd62fb1593c3d4d21cb/ocaml/cos/src/typing/ml_typedtree.ml | ocaml | * _
* x
* P as a
* P1 | P2
* (E1, ..., EN)
* C []
C E [E]
C (E1, ..., En) [E1;...;En]
List the identifiers bound by a pattern or a let
Invariant : both arguments bind the same variables
note the [Not_found] case | open Ml_misc
open Ml_asttypes
open Ml_types
type partial = | Partial | Total
type pattern = {
pat_desc : pattern_desc;
pat_loc : Ml_location.t;
}
and pattern_desc =
| Tpat_any
| Tpat_var of Ml_ident.t * string loc
| Tpat_alias of pattern * Ml_ident.t * string loc
| Tpat_constant of constant
* 1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n
| Tpat_tuple of pattern list
* ( P1 , ... , Pn )
Invariant : n > = 2
Invariant : n >= 2
*)
| Tpat_construct of
Ml_longident.t loc * constructor_description * pattern list
* C [ ]
C P [ P ]
C ( P1 , ... , Pn ) [ P1 ; ... ; Pn ]
C P [P]
C (P1, ..., Pn) [P1; ...; Pn]
*)
| Tpat_or of pattern * pattern
and expression =
{ exp_desc : expression_desc;
exp_loc : Ml_location.t;
}
and expression_desc =
| Texp_ident of Ml_path.t * Ml_longident.t loc * Ml_types.value_description
* x
M.x
*)
| Texp_constant of constant
* 1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n
| Texp_let of rec_flag * value_binding list * expression
* let P1 = E1 and ... and Pn = EN in E ( flag = )
let rec P1 = E1 and ... and Pn = EN in E ( flag = Recursive )
let rec P1 = E1 and ... and Pn = EN in E (flag = Recursive)
*)
| Texp_function of case list * partial
* [ Pexp_fun ] and [ Pexp_function ] both translate to [ Texp_function ] .
See { ! for more details .
partial =
[ Partial ] if the pattern match is partial
[ Total ] otherwise .
See {!Parsetree} for more details.
partial =
[Partial] if the pattern match is partial
[Total] otherwise.
*)
| Texp_apply of expression * expression list
* E0 E1 ... En
For example :
let f x y = x + y in
f 3
The resulting typedtree for the application is :
Texp_apply ( Texp_ident " f/1490 " ,
[ Texp_constant Const_int 3 ] )
For example:
let f x y = x + y in
f 3
The resulting typedtree for the application is:
Texp_apply (Texp_ident "f/1490",
[Texp_constant Const_int 3])
*)
| Texp_match of expression * case list * case list * partial
* match E0 with
| P1 - > E1
| P2 - > E2
| exception P3 - > E3
[ Texp_match ( E0 , [ ( P1 , E1 ) ; ( P2 , E2 ) ] , [ ( P3 , E3 ) ] , _ ) ]
| P1 -> E1
| P2 -> E2
| exception P3 -> E3
[Texp_match (E0, [(P1, E1); (P2, E2)], [(P3, E3)], _)]
*)
| Texp_tuple of expression list
| Texp_construct of
Ml_longident.t loc * constructor_description * expression list
| T_expifthenelse of expression * expression * expression
and case =
{
c_lhs : pattern;
c_rhs : expression;
}
and structure =
{
str_desc : structure_item_desc;
str_loc : Ml_location.t;
}
and structure_item_desc =
| Tstr_eval of expression
| Tstr_value of rec_flag * value_binding list
| Tstr_primitive of value_description
and value_binding =
{
vb_pat : pattern;
vb_expr : expression;
vb_loc : Ml_location.t;
}
let iter_pattern_desc f = function
| Tpat_alias (p, _, _) -> f p
| Tpat_tuple ps -> List.iter f ps
| Tpat_construct (_, _, ps) -> List.iter f ps
| Tpat_or (p1, p2) -> f p1; f p2
| Tpat_any | Tpat_var _ | Tpat_constant _ -> ()
let map_pattern_desc f d = match d with
| Tpat_alias (p, id, loc) -> Tpat_alias (f p, id, loc)
| Tpat_tuple ps -> Tpat_tuple (List.map f ps)
| Tpat_construct (lid, c, ps) -> Tpat_construct (lid, c, List.map f ps)
| Tpat_or (p1, p2) -> Tpat_or (f p1, f p2)
| Tpat_any | Tpat_var _ | Tpat_constant _ -> d
let idents = ref ([] : (Ml_ident.t * string loc) list)
let rec bound_idents pat = match pat.pat_desc with
| Tpat_var (id, s) -> idents := (id, s) :: !idents
| Tpat_alias (p, id, s) ->
bound_idents p; idents := (id, s) :: !idents
| Tpat_or (p1, _) ->
bound_idents p1
| d -> iter_pattern_desc bound_idents d
let pat_bound_idents pat =
idents := [];
bound_idents pat;
let res = !idents in
idents := [];
List.map fst res
let rev_let_bound_idents_with_loc bindings =
idents := [];
List.iter (fun vb -> bound_idents vb.vb_pat) bindings;
let res = !idents in idents := []; res
let let_bound_idents_with_loc pat_expr_list =
List.rev (rev_let_bound_idents_with_loc pat_expr_list)
let rev_let_bound_idents pat = List.map fst (rev_let_bound_idents_with_loc pat)
let let_bound_idents pat = List.map fst (let_bound_idents_with_loc pat)
let alpha_var env id = List.assoc id env
let rec alpha_pat env p = match p.pat_desc with
{p with pat_desc =
try Tpat_var (alpha_var env id, s) with
| Not_found -> Tpat_any }
| Tpat_alias (p1, id, s) ->
let new_p = alpha_pat env p1 in
begin try
{p with pat_desc = Tpat_alias (new_p, alpha_var env id, s)}
with
| Not_found -> new_p
end
| d ->
{p with pat_desc = map_pattern_desc (alpha_pat env) d}
let mkloc = Ml_location.mkloc
let mknoloc = Ml_location.mknoloc
|
1d4cba558ae6765720c12c8a4e710cf9816dd58ea31784be736de9769841234b | scrintal/heroicons-reagent | megaphone.cljs | (ns com.scrintal.heroicons.mini.megaphone)
(defn render []
[:svg {:xmlns ""
:viewBox "0 0 20 20"
:fill "currentColor"
:aria-hidden "true"}
[:path {:d "M13.92 3.845a19.361 19.361 0 01-6.3 1.98C6.765 5.942 5.89 6 5 6a4 4 0 00-.504 7.969 15.974 15.974 0 001.271 3.341c.397.77 1.342 1 2.05.59l.867-.5c.726-.42.94-1.321.588-2.021-.166-.33-.315-.666-.448-1.004 1.8.358 3.511.964 5.096 1.78A17.964 17.964 0 0015 10c0-2.161-.381-4.234-1.08-6.155zM15.243 3.097A19.456 19.456 0 0116.5 10c0 2.431-.445 4.758-1.257 6.904l-.03.077a.75.75 0 001.401.537 20.902 20.902 0 001.312-5.745 1.999 1.999 0 000-3.545 20.902 20.902 0 00-1.312-5.745.75.75 0 00-1.4.537l.029.077z"}]]) | null | https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/mini/megaphone.cljs | clojure | (ns com.scrintal.heroicons.mini.megaphone)
(defn render []
[:svg {:xmlns ""
:viewBox "0 0 20 20"
:fill "currentColor"
:aria-hidden "true"}
[:path {:d "M13.92 3.845a19.361 19.361 0 01-6.3 1.98C6.765 5.942 5.89 6 5 6a4 4 0 00-.504 7.969 15.974 15.974 0 001.271 3.341c.397.77 1.342 1 2.05.59l.867-.5c.726-.42.94-1.321.588-2.021-.166-.33-.315-.666-.448-1.004 1.8.358 3.511.964 5.096 1.78A17.964 17.964 0 0015 10c0-2.161-.381-4.234-1.08-6.155zM15.243 3.097A19.456 19.456 0 0116.5 10c0 2.431-.445 4.758-1.257 6.904l-.03.077a.75.75 0 001.401.537 20.902 20.902 0 001.312-5.745 1.999 1.999 0 000-3.545 20.902 20.902 0 00-1.312-5.745.75.75 0 00-1.4.537l.029.077z"}]]) |
|
322657a4e1e4f68166c1990dccb1078277d9ed9458480be433358538c9874323 | death/constantia | chained-hash-table.lisp | ;;;; +----------------------------------------------------------------+
| |
;;;; +----------------------------------------------------------------+
(defpackage #:constantia/chained-hash-table
(:documentation
"A hierarchical hash-table that can have a single parent.")
(:use #:cl)
(:import-from #:alexandria
#:ensure-functionf)
(:export
#:chained-hash-table
#:chash-table-p
#:chash-table-parent
#:chash-table-test
#:chash-table-count
#:cgethash
#:cremhash
#:cclrhash
#:cmaphash))
(in-package #:constantia/chained-hash-table)
(defclass chained-hash-table ()
((parent :initarg :parent :reader chash-table-parent)
(contents :initarg :contents :reader chash-table-contents))
(:default-initargs :parent nil :contents nil))
(defmethod initialize-instance :after ((hash-table chained-hash-table) &key (test :parent))
(with-slots (contents) hash-table
(when (null contents)
(let ((test (if (eq test :parent)
(if (chash-table-parent hash-table)
(chash-table-test (chash-table-parent hash-table))
'eql)
test)))
(setf contents (make-hash-table :test test))))))
(defun chash-table-p (object)
(typep object 'chained-hash-table))
(defun chash-table-test (hash-table)
(check-type hash-table chained-hash-table)
(hash-table-test (chash-table-contents hash-table)))
(defun chash-table-count (hash-table &key (mode :shallow))
(check-type mode (member :deep :shallow))
(check-type hash-table chained-hash-table)
(+ (hash-table-count (chash-table-contents hash-table))
(if (and (eq mode :deep)
(chash-table-parent hash-table))
(chash-table-count (chash-table-parent hash-table) :mode :deep)
0)))
(defun cgethash (key hash-table &optional default)
(check-type hash-table chained-hash-table)
(multiple-value-bind (value exists)
(gethash key (chash-table-contents hash-table))
(cond (exists
(values value exists t))
((chash-table-parent hash-table)
(multiple-value-bind (value exists)
(cgethash key (chash-table-parent hash-table) default)
(values value exists nil)))
(t
(values default nil nil)))))
(defun (setf cgethash) (new-value key hash-table &optional default)
(declare (ignore default))
(check-type hash-table chained-hash-table)
(setf (gethash key (chash-table-contents hash-table)) new-value))
(defun cremhash (key hash-table &key (mode :shallow))
(check-type mode (member :deep :shallow))
(check-type hash-table chained-hash-table)
(let ((result (remhash key (chash-table-contents hash-table))))
(values
(if (and (eq mode :deep) (chash-table-parent hash-table))
(or (cremhash key (chash-table-parent hash-table) :mode :deep)
result)
result)
(if result t nil))))
(defun cclrhash (hash-table &key (mode :shallow))
(check-type mode (member :deep :shallow))
(check-type hash-table chained-hash-table)
(clrhash (chash-table-contents hash-table))
(when (and (eq mode :deep)
(chash-table-parent hash-table))
(cclrhash (chash-table-parent hash-table) :mode :deep))
hash-table)
(defun cmaphash (function-designator hash-table &key (mode :shallow))
(check-type mode (member :deep :shallow))
(check-type hash-table chained-hash-table)
(ensure-functionf function-designator)
(maphash function-designator (chash-table-contents hash-table))
(when (and (eq mode :deep)
(chash-table-parent hash-table))
(cmaphash function-designator (chash-table-parent hash-table) :mode :deep))
nil)
| null | https://raw.githubusercontent.com/death/constantia/87379e2cf46a2be335e099e24a114717e26d4e96/chained-hash-table.lisp | lisp | +----------------------------------------------------------------+
+----------------------------------------------------------------+ | | |
(defpackage #:constantia/chained-hash-table
(:documentation
"A hierarchical hash-table that can have a single parent.")
(:use #:cl)
(:import-from #:alexandria
#:ensure-functionf)
(:export
#:chained-hash-table
#:chash-table-p
#:chash-table-parent
#:chash-table-test
#:chash-table-count
#:cgethash
#:cremhash
#:cclrhash
#:cmaphash))
(in-package #:constantia/chained-hash-table)
(defclass chained-hash-table ()
((parent :initarg :parent :reader chash-table-parent)
(contents :initarg :contents :reader chash-table-contents))
(:default-initargs :parent nil :contents nil))
(defmethod initialize-instance :after ((hash-table chained-hash-table) &key (test :parent))
(with-slots (contents) hash-table
(when (null contents)
(let ((test (if (eq test :parent)
(if (chash-table-parent hash-table)
(chash-table-test (chash-table-parent hash-table))
'eql)
test)))
(setf contents (make-hash-table :test test))))))
(defun chash-table-p (object)
(typep object 'chained-hash-table))
(defun chash-table-test (hash-table)
(check-type hash-table chained-hash-table)
(hash-table-test (chash-table-contents hash-table)))
(defun chash-table-count (hash-table &key (mode :shallow))
(check-type mode (member :deep :shallow))
(check-type hash-table chained-hash-table)
(+ (hash-table-count (chash-table-contents hash-table))
(if (and (eq mode :deep)
(chash-table-parent hash-table))
(chash-table-count (chash-table-parent hash-table) :mode :deep)
0)))
(defun cgethash (key hash-table &optional default)
(check-type hash-table chained-hash-table)
(multiple-value-bind (value exists)
(gethash key (chash-table-contents hash-table))
(cond (exists
(values value exists t))
((chash-table-parent hash-table)
(multiple-value-bind (value exists)
(cgethash key (chash-table-parent hash-table) default)
(values value exists nil)))
(t
(values default nil nil)))))
(defun (setf cgethash) (new-value key hash-table &optional default)
(declare (ignore default))
(check-type hash-table chained-hash-table)
(setf (gethash key (chash-table-contents hash-table)) new-value))
(defun cremhash (key hash-table &key (mode :shallow))
(check-type mode (member :deep :shallow))
(check-type hash-table chained-hash-table)
(let ((result (remhash key (chash-table-contents hash-table))))
(values
(if (and (eq mode :deep) (chash-table-parent hash-table))
(or (cremhash key (chash-table-parent hash-table) :mode :deep)
result)
result)
(if result t nil))))
(defun cclrhash (hash-table &key (mode :shallow))
(check-type mode (member :deep :shallow))
(check-type hash-table chained-hash-table)
(clrhash (chash-table-contents hash-table))
(when (and (eq mode :deep)
(chash-table-parent hash-table))
(cclrhash (chash-table-parent hash-table) :mode :deep))
hash-table)
(defun cmaphash (function-designator hash-table &key (mode :shallow))
(check-type mode (member :deep :shallow))
(check-type hash-table chained-hash-table)
(ensure-functionf function-designator)
(maphash function-designator (chash-table-contents hash-table))
(when (and (eq mode :deep)
(chash-table-parent hash-table))
(cmaphash function-designator (chash-table-parent hash-table) :mode :deep))
nil)
|
d9b65881f12e9f2fe05771eed3f31ef5cebc7bd19d91d9789fe6fbe9c6791b39 | scicloj/metamorph.ml | tools.clj | (ns scicloj.metamorph.ml.tools
(:require
[clojure.pprint :as pprint]))
(defn dissoc-in
"Dissociate a value in a nested assocative structure, identified by a sequence
of keys. Any collections left empty by the operation will be dissociated from
their containing structures."
[m ks]
(if-let [[k & ks] (seq ks)]
(if (seq ks)
(let [v (dissoc-in (get m k) ks)]
(if (empty? v)
(dissoc m k)
(assoc m k v)))
(dissoc m k))
m))
(defn multi-dissoc-in [m kss]
(reduce (fn [x y]
(dissoc-in x y))
m
kss))
(defn pp-str [x]
(with-out-str (pprint/pprint x)))
| null | https://raw.githubusercontent.com/scicloj/metamorph.ml/795ac6b0618a510e91ca3e0c5c9a01523e32d827/src/scicloj/metamorph/ml/tools.clj | clojure | (ns scicloj.metamorph.ml.tools
(:require
[clojure.pprint :as pprint]))
(defn dissoc-in
"Dissociate a value in a nested assocative structure, identified by a sequence
of keys. Any collections left empty by the operation will be dissociated from
their containing structures."
[m ks]
(if-let [[k & ks] (seq ks)]
(if (seq ks)
(let [v (dissoc-in (get m k) ks)]
(if (empty? v)
(dissoc m k)
(assoc m k v)))
(dissoc m k))
m))
(defn multi-dissoc-in [m kss]
(reduce (fn [x y]
(dissoc-in x y))
m
kss))
(defn pp-str [x]
(with-out-str (pprint/pprint x)))
|
|
a349c89263a1638e3137e7d0a8d272dcaf9a13c02184e595e5a68388307d9a3b | repl-acement/repl-acement | analysis.clj | (ns replacement.server.analysis
(:require
[replacement.specs.messages :as messages]
[clj-kondo.core :as kondo]))
(set! *warn-on-reflection* true)
(defn- clj-kondo* [form]
(-> form
(with-in-str (kondo/run! {:lint ["-"] :config {:output {:analysis true}}}))
:analysis))
(defn clj-kondo [{::messages/keys [form]}]
{:analysis/form form
:analysis/clj-kondo (clj-kondo* form)})
(comment
(def nses {:funky (clj-kondo* "(ns funky)\n(defn x [a] (* a a))\n")
:funky2 (clj-kondo* "(ns funky2\n (:require [funky :refer [x]]))\n(defn y [z] (x z))")})
) | null | https://raw.githubusercontent.com/repl-acement/repl-acement/1416166b1fad1744ee8749a19ca5cd387a69feee/repl-server/replacement/server/analysis.clj | clojure | (ns replacement.server.analysis
(:require
[replacement.specs.messages :as messages]
[clj-kondo.core :as kondo]))
(set! *warn-on-reflection* true)
(defn- clj-kondo* [form]
(-> form
(with-in-str (kondo/run! {:lint ["-"] :config {:output {:analysis true}}}))
:analysis))
(defn clj-kondo [{::messages/keys [form]}]
{:analysis/form form
:analysis/clj-kondo (clj-kondo* form)})
(comment
(def nses {:funky (clj-kondo* "(ns funky)\n(defn x [a] (* a a))\n")
:funky2 (clj-kondo* "(ns funky2\n (:require [funky :refer [x]]))\n(defn y [z] (x z))")})
) |
|
9ae54f712dabfd7165599be510a8960fb15f894c2c8e793c8f70ebb43a8700d0 | clojure-interop/java-jdk | SynthStyleFactory.clj | (ns javax.swing.plaf.synth.SynthStyleFactory
"Factory used for obtaining SynthStyles. Each of the
Synth ComponentUIs will call into the current
SynthStyleFactory to obtain a SynthStyle
for each of the distinct regions they have.
The following example creates a custom SynthStyleFactory
that returns a different style based on the Region:
class MyStyleFactory extends SynthStyleFactory {
public SynthStyle getStyle(JComponent c, Region id) {
if (id == Region.BUTTON) {
return buttonStyle;
}
else if (id == Region.TREE) {
return treeStyle;
}
return defaultStyle;
}
}
SynthLookAndFeel laf = new SynthLookAndFeel();
UIManager.setLookAndFeel(laf);
SynthLookAndFeel.setStyleFactory(new MyStyleFactory());"
(:refer-clojure :only [require comment defn ->])
(:import [javax.swing.plaf.synth SynthStyleFactory]))
(defn ->synth-style-factory
"Constructor.
Creates a SynthStyleFactory."
(^SynthStyleFactory []
(new SynthStyleFactory )))
(defn get-style
"Returns the style for the specified Component.
c - Component asking for - `javax.swing.JComponent`
id - Region identifier - `javax.swing.plaf.synth.Region`
returns: SynthStyle for region. - `javax.swing.plaf.synth.SynthStyle`"
(^javax.swing.plaf.synth.SynthStyle [^SynthStyleFactory this ^javax.swing.JComponent c ^javax.swing.plaf.synth.Region id]
(-> this (.getStyle c id))))
| null | https://raw.githubusercontent.com/clojure-interop/java-jdk/8d7a223e0f9a0965eb0332fad595cf7649d9d96e/javax.swing/src/javax/swing/plaf/synth/SynthStyleFactory.clj | clojure |
" | (ns javax.swing.plaf.synth.SynthStyleFactory
"Factory used for obtaining SynthStyles. Each of the
Synth ComponentUIs will call into the current
SynthStyleFactory to obtain a SynthStyle
for each of the distinct regions they have.
The following example creates a custom SynthStyleFactory
that returns a different style based on the Region:
class MyStyleFactory extends SynthStyleFactory {
public SynthStyle getStyle(JComponent c, Region id) {
if (id == Region.BUTTON) {
}
else if (id == Region.TREE) {
}
}
}
(:refer-clojure :only [require comment defn ->])
(:import [javax.swing.plaf.synth SynthStyleFactory]))
(defn ->synth-style-factory
"Constructor.
Creates a SynthStyleFactory."
(^SynthStyleFactory []
(new SynthStyleFactory )))
(defn get-style
"Returns the style for the specified Component.
c - Component asking for - `javax.swing.JComponent`
id - Region identifier - `javax.swing.plaf.synth.Region`
returns: SynthStyle for region. - `javax.swing.plaf.synth.SynthStyle`"
(^javax.swing.plaf.synth.SynthStyle [^SynthStyleFactory this ^javax.swing.JComponent c ^javax.swing.plaf.synth.Region id]
(-> this (.getStyle c id))))
|
301a290cd61c553a2e497001a2bb7050c9bfbf6123318e314b243646d15d95df | dlowe-net/orcabot | panic-grammar.lisp | (sentence -> (or (panic panic)
(panic panic panic)
(panic panic panic)
(panic panic panic panic)))
(panic -> (or "OMG!!!!!"
"Game over, man!"
"Oh, God."
"It's too late!"
"We're all going to die!"
"Women and bots first!!"
"Whyyyy? Ohhh, whyyyy?"
"Please, save us!!!"
"Noooooooo!!"
"Run!! Run for your lives!!"
"We've gotta get out of here!!!"
"What can we do??"
"The horror! The horror!"
"I want to live!!!"
"We're doomed. Doooooooomed!"
"I'm too scared to die!!!"))
(panic-arg -> (or (problem "... " problem "...")
("Ahhhh! " problem "!")
("Help!! It's" problem "!")
("Save yourselves from" problem "!")
("Run away from" problem "!"))) | null | https://raw.githubusercontent.com/dlowe-net/orcabot/bf3c799337531e6b16086e8105906cc9f8808313/data/panic-grammar.lisp | lisp | (sentence -> (or (panic panic)
(panic panic panic)
(panic panic panic)
(panic panic panic panic)))
(panic -> (or "OMG!!!!!"
"Game over, man!"
"Oh, God."
"It's too late!"
"We're all going to die!"
"Women and bots first!!"
"Whyyyy? Ohhh, whyyyy?"
"Please, save us!!!"
"Noooooooo!!"
"Run!! Run for your lives!!"
"We've gotta get out of here!!!"
"What can we do??"
"The horror! The horror!"
"I want to live!!!"
"We're doomed. Doooooooomed!"
"I'm too scared to die!!!"))
(panic-arg -> (or (problem "... " problem "...")
("Ahhhh! " problem "!")
("Help!! It's" problem "!")
("Save yourselves from" problem "!")
("Run away from" problem "!"))) |
|
21aef281b0d9655d45af290958e2b2e6589215713722f701193678fbead26566 | e-wrks/edh | RuntimeM.hs | # LANGUAGE ImplicitParams #
module Language.Edh.RuntimeM
( createEdhWorld,
declareEdhOperators,
installModuleM_,
installModuleM,
runProgramM,
runProgramM_,
runProgramM',
createEdhModule,
runModuleM,
runModuleM',
runEdhFile,
runEdhFile',
)
where
-- import Debug.Trace
import Control.Concurrent.STM
import Control.Exception
import Control.Monad
import Control.Monad.IO.Class
import qualified Data.ByteString as B
import qualified Data.HashMap.Strict as Map
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding
import Data.Text.Encoding.Error
import Language.Edh.Control
import Language.Edh.Evaluate
import Language.Edh.Monad
import Language.Edh.PkgMan
import Language.Edh.RtTypes
import Language.Edh.Runtime
import System.FilePath
import Prelude
runProgramM :: EdhWorld -> Edh EdhValue -> IO (Either EdhError EdhValue)
runProgramM !world !prog =
tryJust edhKnownError $ runProgramM' world prog
runProgramM_ :: EdhWorld -> Edh a -> IO ()
runProgramM_ !world !prog =
void $
runProgramM' world $ do
void prog
return nil
runProgramM' :: EdhWorld -> Edh EdhValue -> IO EdhValue
runProgramM' !world !prog = do
!haltResult <- newEmptyTMVarIO
let exit :: EdhTxExit EdhValue
exit val _ets = void $ tryPutTMVar haltResult (Right val)
driveEdhProgram haltResult world $ \ !ets ->
unEdh prog rptEdhNotApplicable exit ets
atomically (tryReadTMVar haltResult) >>= \case
Nothing -> return nil
Just (Right v) -> return v
Just (Left e) -> throwIO e
runModuleM :: FilePath -> Edh EdhValue
runModuleM !impPath = runModuleM' impPath $ pure ()
runModuleM' :: FilePath -> Edh () -> Edh EdhValue
runModuleM' !impPath !preRun = do
!world <- edh'prog'world <$> edhProgramState
(modu, moduFile, moduSource) <-
liftIO $ let ?fileExt = ".edh" in prepareModu world
!moduCtx <- inlineSTM $ moduleContext world modu
inContext moduCtx $ do
preRun
evalSrcM moduFile moduSource
where
prepareModu :: (?fileExt :: FilePath) => EdhWorld -> IO (Object, Text, Text)
prepareModu !world =
locateEdhMainModule impPath >>= \case
Left !err ->
throwHostIO PackageError err
Right !moduFile -> do
!fileContent <- B.readFile moduFile
case streamDecodeUtf8With lenientDecode fileContent of
Some !moduSource _ _ ->
(,T.pack moduFile,moduSource)
<$> createEdhModule world (T.pack impPath) moduFile
installModuleM_ :: Text -> Edh () -> Edh ()
installModuleM_ !moduName !preInstall =
void $ installModuleM moduName preInstall
installModuleM :: Text -> Edh () -> Edh Object
installModuleM !moduName !preInstall = do
!world <- edh'prog'world <$> edhProgramState
!modu <-
liftIO $
createEdhModule world moduName $
T.unpack $ "<host:" <> moduName <> ">"
!moduCtx <- inlineSTM $ moduleContext world modu
inContext moduCtx preInstall
liftSTM $ do
!moduSlot <- newTVar $ ModuLoaded modu
!moduMap <- takeTMVar (edh'world'modules world)
putTMVar (edh'world'modules world) $
Map.insert (HostModule moduName) moduSlot moduMap
return modu
| null | https://raw.githubusercontent.com/e-wrks/edh/f6c9db18a32a7d97aa9ce32bcd64c7e9f8bc6b2e/host.hs/src/Language/Edh/RuntimeM.hs | haskell | import Debug.Trace | # LANGUAGE ImplicitParams #
module Language.Edh.RuntimeM
( createEdhWorld,
declareEdhOperators,
installModuleM_,
installModuleM,
runProgramM,
runProgramM_,
runProgramM',
createEdhModule,
runModuleM,
runModuleM',
runEdhFile,
runEdhFile',
)
where
import Control.Concurrent.STM
import Control.Exception
import Control.Monad
import Control.Monad.IO.Class
import qualified Data.ByteString as B
import qualified Data.HashMap.Strict as Map
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding
import Data.Text.Encoding.Error
import Language.Edh.Control
import Language.Edh.Evaluate
import Language.Edh.Monad
import Language.Edh.PkgMan
import Language.Edh.RtTypes
import Language.Edh.Runtime
import System.FilePath
import Prelude
runProgramM :: EdhWorld -> Edh EdhValue -> IO (Either EdhError EdhValue)
runProgramM !world !prog =
tryJust edhKnownError $ runProgramM' world prog
runProgramM_ :: EdhWorld -> Edh a -> IO ()
runProgramM_ !world !prog =
void $
runProgramM' world $ do
void prog
return nil
runProgramM' :: EdhWorld -> Edh EdhValue -> IO EdhValue
runProgramM' !world !prog = do
!haltResult <- newEmptyTMVarIO
let exit :: EdhTxExit EdhValue
exit val _ets = void $ tryPutTMVar haltResult (Right val)
driveEdhProgram haltResult world $ \ !ets ->
unEdh prog rptEdhNotApplicable exit ets
atomically (tryReadTMVar haltResult) >>= \case
Nothing -> return nil
Just (Right v) -> return v
Just (Left e) -> throwIO e
runModuleM :: FilePath -> Edh EdhValue
runModuleM !impPath = runModuleM' impPath $ pure ()
runModuleM' :: FilePath -> Edh () -> Edh EdhValue
runModuleM' !impPath !preRun = do
!world <- edh'prog'world <$> edhProgramState
(modu, moduFile, moduSource) <-
liftIO $ let ?fileExt = ".edh" in prepareModu world
!moduCtx <- inlineSTM $ moduleContext world modu
inContext moduCtx $ do
preRun
evalSrcM moduFile moduSource
where
prepareModu :: (?fileExt :: FilePath) => EdhWorld -> IO (Object, Text, Text)
prepareModu !world =
locateEdhMainModule impPath >>= \case
Left !err ->
throwHostIO PackageError err
Right !moduFile -> do
!fileContent <- B.readFile moduFile
case streamDecodeUtf8With lenientDecode fileContent of
Some !moduSource _ _ ->
(,T.pack moduFile,moduSource)
<$> createEdhModule world (T.pack impPath) moduFile
installModuleM_ :: Text -> Edh () -> Edh ()
installModuleM_ !moduName !preInstall =
void $ installModuleM moduName preInstall
installModuleM :: Text -> Edh () -> Edh Object
installModuleM !moduName !preInstall = do
!world <- edh'prog'world <$> edhProgramState
!modu <-
liftIO $
createEdhModule world moduName $
T.unpack $ "<host:" <> moduName <> ">"
!moduCtx <- inlineSTM $ moduleContext world modu
inContext moduCtx preInstall
liftSTM $ do
!moduSlot <- newTVar $ ModuLoaded modu
!moduMap <- takeTMVar (edh'world'modules world)
putTMVar (edh'world'modules world) $
Map.insert (HostModule moduName) moduSlot moduMap
return modu
|
47697152543ac613a2a82c10e04d541a9bf2b7b82b2aafafc414756855a583a1 | fujita-y/ypsilon | base.scm | #!nobacktrace
(library (rnrs base (6))
(export define define-syntax
quote lambda if set! cond case and or
let let* letrec letrec* let-values let*-values
begin quasiquote unquote unquote-splicing
let-syntax letrec-syntax syntax-rules
identifier-syntax assert
else => ... _
eq?
eqv?
equal?
procedure?
number? complex? real? rational? integer?
real-valued? rational-valued? integer-valued?
exact? inexact?
inexact exact
= < > <= >=
zero? positive? negative? odd? even?
finite? infinite? nan?
max min + * - / abs
div-and-mod div mod div0-and-mod0 div0 mod0
gcd lcm numerator denominator
floor ceiling truncate round
rationalize
exp log sin cos tan asin acos atan
sqrt
exact-integer-sqrt
expt
make-rectangular make-polar real-part imag-part
magnitude angle
number->string string->number
not boolean? boolean=?
pair? cons car cdr
caar cadr cdar cddr caaar caadr cadar
caddr cdaar cdadr cddar cdddr caaaar caaadr
caadar caaddr cadaar cadadr caddar cadddr cdaaar
cdaadr cdadar cdaddr cddaar cddadr cdddar cddddr
null? list? list length append reverse list-tail
list-ref map for-each
symbol? symbol->string string->symbol symbol=?
char? char->integer integer->char
char=? char<? char>? char<=? char>=?
string? make-string string string-length string-ref
string=? string<? string>? string<=? string>=?
substring string-append string->list list->string string-copy string-for-each
vector? make-vector vector vector-length vector-ref vector-set!
vector->list list->vector vector-fill!
vector-map vector-for-each
error assertion-violation
apply call-with-current-continuation call/cc
values call-with-values dynamic-wind)
(import (core intrinsics)))
| null | https://raw.githubusercontent.com/fujita-y/ypsilon/f742470e2810aabb7a7c898fd6c07227c14a725f/sitelib/rnrs/base.scm | scheme | #!nobacktrace
(library (rnrs base (6))
(export define define-syntax
quote lambda if set! cond case and or
let let* letrec letrec* let-values let*-values
begin quasiquote unquote unquote-splicing
let-syntax letrec-syntax syntax-rules
identifier-syntax assert
else => ... _
eq?
eqv?
equal?
procedure?
number? complex? real? rational? integer?
real-valued? rational-valued? integer-valued?
exact? inexact?
inexact exact
= < > <= >=
zero? positive? negative? odd? even?
finite? infinite? nan?
max min + * - / abs
div-and-mod div mod div0-and-mod0 div0 mod0
gcd lcm numerator denominator
floor ceiling truncate round
rationalize
exp log sin cos tan asin acos atan
sqrt
exact-integer-sqrt
expt
make-rectangular make-polar real-part imag-part
magnitude angle
number->string string->number
not boolean? boolean=?
pair? cons car cdr
caar cadr cdar cddr caaar caadr cadar
caddr cdaar cdadr cddar cdddr caaaar caaadr
caadar caaddr cadaar cadadr caddar cadddr cdaaar
cdaadr cdadar cdaddr cddaar cddadr cdddar cddddr
null? list? list length append reverse list-tail
list-ref map for-each
symbol? symbol->string string->symbol symbol=?
char? char->integer integer->char
char=? char<? char>? char<=? char>=?
string? make-string string string-length string-ref
string=? string<? string>? string<=? string>=?
substring string-append string->list list->string string-copy string-for-each
vector? make-vector vector vector-length vector-ref vector-set!
vector->list list->vector vector-fill!
vector-map vector-for-each
error assertion-violation
apply call-with-current-continuation call/cc
values call-with-values dynamic-wind)
(import (core intrinsics)))
|
|
a82ff81f01a6b20f96cbb958bc5cad255cd4039e539fb07b308cd6990225ab29 | zehnpaard/48hr-scheme-ocaml | ex.ml | open Lisp
let f env s =
try Lexing.from_string s
|> Parser.f Lexer.f
|> Eval.f env
|> Exp.to_string
|> print_endline
with
| Exception.NumArgs (n, s) -> Printf.printf "NumArgs %d %s\n" n s
| Exception.TypeMismatch (s1, s2) -> Printf.printf "TypeMismatch %s %s\n" s1 s2
| Exception.LexingFail s -> Printf.printf "LexingFail %s\n" s
| Exception.BadSpecialForm (s1, s2) -> Printf.printf "BadSpecialForm %s %s\n" s1 s2
| Exception.NotFunction (s1, s2) -> Printf.printf "NotFunction %s %s\n" s1 s2
| Exception.UnboundVar (s1, s2) -> Printf.printf "UnboundVar %s %s\n" s1 s2
| Exception.Default s -> Printf.printf "DefaultError %s\n" s
let rec repl env =
let s = (print_string "Lisp>>> "; read_line ()) in
if s = "quit" then ()
else (f env s; repl env)
let _ = repl (Env.create () |> Primitives.load)
| null | https://raw.githubusercontent.com/zehnpaard/48hr-scheme-ocaml/b1f710cb2cd73bd81de0fe3ea2a3e02d3295a296/bin/ex.ml | ocaml | open Lisp
let f env s =
try Lexing.from_string s
|> Parser.f Lexer.f
|> Eval.f env
|> Exp.to_string
|> print_endline
with
| Exception.NumArgs (n, s) -> Printf.printf "NumArgs %d %s\n" n s
| Exception.TypeMismatch (s1, s2) -> Printf.printf "TypeMismatch %s %s\n" s1 s2
| Exception.LexingFail s -> Printf.printf "LexingFail %s\n" s
| Exception.BadSpecialForm (s1, s2) -> Printf.printf "BadSpecialForm %s %s\n" s1 s2
| Exception.NotFunction (s1, s2) -> Printf.printf "NotFunction %s %s\n" s1 s2
| Exception.UnboundVar (s1, s2) -> Printf.printf "UnboundVar %s %s\n" s1 s2
| Exception.Default s -> Printf.printf "DefaultError %s\n" s
let rec repl env =
let s = (print_string "Lisp>>> "; read_line ()) in
if s = "quit" then ()
else (f env s; repl env)
let _ = repl (Env.create () |> Primitives.load)
|
|
cd53bbe43bb31c519262e3121a46835fb366fbdf6b8bf9ca1ac19da043ef801d | ucsd-progsys/liquidhaskell | MeasureContains.hs | {-@ LIQUID "--expect-any-error" @-}
module MeasureContains where
import Language.Haskell.Liquid.Prelude
{-@ LIQUID "--no-termination" @-}
{-@ measure binderContainsV @-}
binderContainsV :: Binder n -> Bool
binderContainsV B = True
binderContainsV (M x) = containsV x
data Binder n = B | M (TT n)
data TT n = V Int | Other | Bind (Binder n) (TT n)
{-@ measure containsV @-}
containsV :: TT n -> Bool
containsV (V i) = True
containsV (Bind b body) = (binderContainsV b) || (containsV body)
containsV _ = False
prop1 = liquidAssert (containsV $ Other)
| null | https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/f46dbafd6ce1f61af5b56f31924c21639c982a8a/tests/neg/MeasureContains.hs | haskell | @ LIQUID "--expect-any-error" @
@ LIQUID "--no-termination" @
@ measure binderContainsV @
@ measure containsV @ | module MeasureContains where
import Language.Haskell.Liquid.Prelude
binderContainsV :: Binder n -> Bool
binderContainsV B = True
binderContainsV (M x) = containsV x
data Binder n = B | M (TT n)
data TT n = V Int | Other | Bind (Binder n) (TT n)
containsV :: TT n -> Bool
containsV (V i) = True
containsV (Bind b body) = (binderContainsV b) || (containsV body)
containsV _ = False
prop1 = liquidAssert (containsV $ Other)
|
6b2394a1f2ad2190996cc1acfb0ac50f48733a6f0924b749c45ff5a28780df01 | Kappa-Dev/KappaTools | setMap.mli | (******************************************************************************)
(* _ __ * 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 *)
(******************************************************************************)
(** Our own implementattion of Set and Map
Purely functionnal.
Functions without _with_logs do NOT raise any exception.*)
module type OrderedType =
sig
type t
val compare : t -> t -> int
val print : Format.formatter -> t -> unit
end
type ('parameters,'error,'a) with_log_wrap =
('parameters -> 'error -> string -> string option -> exn -> 'error) ->
'parameters -> 'error -> 'a
module type Set =
sig
type elt
type t
val empty: t
val is_empty: t -> bool
val singleton: elt -> t
val is_singleton: t -> bool
val add: elt -> t -> t
val add_with_logs: ('parameters,'error,elt -> t -> 'error * t) with_log_wrap
val remove: elt -> t -> t
val add_while_testing_freshness:
('parameters,'error,elt -> t -> 'error * bool * t) with_log_wrap
val remove_while_testing_existence:
('parameters,'error,elt -> t -> 'error * bool * t) with_log_wrap
val remove_with_logs:
('parameters,'error,elt -> t -> 'error * t) with_log_wrap
val split: elt -> t -> (t * bool * t)
val union: t -> t -> t
val disjoint_union: t -> t -> t option
val inter: t -> t -> t
val minus: t -> t -> t
(** [minus a b] contains elements of [a] that are not in [b] *)
val diff: t -> t -> t
(** [diff a b] = [minus (union a b) (inter a b)] *)
val minus_with_logs: ('parameters,'error,t -> t -> 'error * t) with_log_wrap
val union_with_logs: ('parameters,'error,t -> t -> 'error * t) with_log_wrap
val disjoint_union_with_logs:
('parameters,'error,t -> t -> 'error * t) with_log_wrap
val inter_with_logs: ('parameters,'error,t -> t -> 'error * t) with_log_wrap
val diff_with_logs: ('parameters,'error,t -> t -> 'error * t) with_log_wrap
val size: t -> int
val mem: elt -> t -> bool
val exists: (elt -> bool) -> t -> bool
val filter: (elt -> bool) -> t -> t
val filter_with_logs:
('parameters,'error,(elt -> bool) -> t -> 'error * t) with_log_wrap
val for_all: (elt -> bool) -> t -> bool
val partition: (elt -> bool) -> t -> t * t
val partition_with_logs:
('parameters,'error,(elt -> bool) -> t -> 'error * t * t) with_log_wrap
val compare: t -> t -> int
val equal: t -> t -> bool
val subset: t -> t -> bool
val iter: (elt -> unit) -> t -> unit
val fold: (elt -> 'a -> 'a) -> t -> 'a -> 'a
val fold_inv: (elt -> 'a -> 'a) -> t -> 'a -> 'a
val elements: t -> elt list
val print: Format.formatter -> t -> unit
val choose: t -> elt option
val random: Random.State.t -> t -> elt option
val min_elt: t -> elt option
val max_elt: t -> elt option
end
module type Map =
sig
type elt
type set
type +'a t
val empty: 'a t
val is_empty: 'a t -> bool
val size: 'a t -> int
val root: 'a t -> (elt * 'a) option
val max_key: 'a t -> elt option
val add: elt -> 'a -> 'a t -> 'a t
val remove: elt -> 'a t -> 'a t
val add_while_testing_freshness:
('parameters,'error,
elt -> 'a -> 'a t -> 'error * bool * 'a t) with_log_wrap
val remove_while_testing_existence:
('parameters,'error,elt -> 'a t -> 'error * bool * 'a t) with_log_wrap
val pop: elt -> 'a t -> ('a option * 'a t)
val merge: 'a t -> 'a t -> 'a t
val min_elt: 'a t -> (elt * 'a) option
val find_option: elt -> 'a t -> 'a option
val find_default: 'a -> elt -> 'a t -> 'a
val find_option_with_logs:
('parameters,'error,elt -> 'a t -> 'error * 'a option) with_log_wrap
val find_default_with_logs:
('parameters,'error,'a -> elt -> 'a t -> 'error * 'a) with_log_wrap
val mem: elt -> 'a t -> bool
val diff: 'a t -> 'a t -> 'a t * 'a t
val union: 'a t -> 'a t -> 'a t
val update: 'a t -> 'a t -> 'a t
val diff_pred: ('a -> 'a -> bool) -> 'a t -> 'a t -> 'a t * 'a t
val add_with_logs:
('parameters,'error,elt -> 'a -> 'a t -> 'error * 'a t) with_log_wrap
val remove_with_logs:
('parameters,'error,elt -> 'a t -> 'error * 'a t) with_log_wrap
val join_with_logs:
('parameters,'error,
'a t -> elt -> 'a -> 'a t -> 'error * 'a t) with_log_wrap
val split_with_logs:
('parameters,'error,
elt -> 'a t -> 'error * ('a t * 'a option * 'a t)) with_log_wrap
val update_with_logs:
('parameters,'error,'a t -> 'a t -> 'error * 'a t) with_log_wrap
val map2_with_logs:
('parameters,'error,
('parameters -> 'error -> 'a -> 'error * 'c) ->
('parameters -> 'error -> 'b -> 'error * 'c) ->
('parameters -> 'error -> 'a -> 'b -> 'error * 'c) ->
'a t -> 'b t -> 'error * 'c t) with_log_wrap
val map2z_with_logs:
('parameters,'error,
('parameters -> 'error -> 'a -> 'a -> 'error * 'a) ->
'a t -> 'a t -> 'error * 'a t) with_log_wrap
val fold2z_with_logs:
('parameters,'error,
('parameters -> 'error -> elt -> 'a -> 'b -> 'c -> ('error * 'c)) ->
'a t -> 'b t -> 'c -> 'error * 'c) with_log_wrap
val fold2_with_logs:
('parameters,'error,
('parameters -> 'error -> elt -> 'a -> 'c -> 'error * 'c) ->
('parameters -> 'error -> elt -> 'b -> 'c -> 'error * 'c) ->
('parameters -> 'error -> elt -> 'a -> 'b -> 'c -> 'error * 'c) ->
'a t -> 'b t -> 'c -> 'error * 'c) with_log_wrap
val fold2_sparse_with_logs:
('parameters,'error,
('parameters -> 'error -> elt -> 'a -> 'b -> 'c -> ('error * 'c)) ->
'a t -> 'b t -> 'c -> 'error * 'c) with_log_wrap
val iter2_sparse_with_logs:
('parameters,'error,
('parameters -> 'error -> elt -> 'a -> 'b -> 'error) ->
'a t -> 'b t -> 'error) with_log_wrap
val diff_with_logs:
('parameters,'error,'a t -> 'a t -> 'error * 'a t * 'a t) with_log_wrap
val diff_pred_with_logs:
('parameters,'error,
('a -> 'a -> bool) -> 'a t -> 'a t -> 'error * 'a t * 'a t) with_log_wrap
val merge_with_logs :
('parameters,'error,'a t -> 'a t -> 'error * 'a t) with_log_wrap
val union_with_logs :
('parameters,'error,'a t -> 'a t -> 'error * 'a t) with_log_wrap
val fold_restriction_with_logs:
('parameters,'error,
(elt -> 'a -> ('error * 'b) -> ('error* 'b)) ->
set -> 'a t -> 'b -> 'error * 'b) with_log_wrap
val fold_restriction_with_missing_associations_with_logs:
('parameters,'error,
(elt -> 'a -> ('error * 'b) -> ('error* 'b)) ->
(elt -> ('error * 'b) -> ('error * 'b)) ->
set -> 'a t -> 'b -> 'error * 'b) with_log_wrap
val iter: (elt -> 'a -> unit) -> 'a t -> unit
val fold: (elt -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
val fold_with_interruption: (elt -> 'a -> 'b -> ('b,'c) Stop.stop) -> 'a t -> 'b -> ('b,'c) Stop.stop
val monadic_fold2:
'parameters -> 'method_handler ->
('parameters -> 'method_handler ->
elt -> 'a -> 'b -> 'c -> ('method_handler * 'c)) ->
('parameters -> 'method_handler ->
elt -> 'a -> 'c -> ('method_handler * 'c)) ->
('parameters -> 'method_handler ->
elt -> 'b -> 'c -> ('method_handler * 'c)) ->
'a t -> 'b t -> 'c -> ('method_handler * 'c)
val monadic_fold2_sparse:
'parameters -> 'method_handler ->
('parameters -> 'method_handler ->
elt -> 'a -> 'b -> 'c -> ('method_handler * 'c)) ->
'a t -> 'b t -> 'c -> ('method_handler * 'c)
val monadic_iter2_sparse:
'parameters -> 'method_handler ->
('parameters -> 'method_handler ->
elt -> 'a -> 'b -> 'method_handler) ->
'a t -> 'b t -> 'method_handler
val monadic_fold_restriction:
'parameters -> 'method_handler ->
('parameters -> 'method_handler ->
elt -> 'a -> 'b -> ('method_handler * 'b)) ->
set -> 'a t -> 'b -> 'method_handler * 'b
val mapi: (elt -> 'a -> 'b) -> 'a t -> 'b t
val map: ('a -> 'b) -> 'a t -> 'b t
val map2: ('a -> 'a -> 'a) -> 'a t -> 'a t -> 'a t
val for_all: (elt -> 'a -> bool) -> 'a t -> bool
val filter_one: (elt -> 'a -> bool) -> 'a t -> (elt * 'a) option
(* returns an element that respects the predicate (if any) *)
val compare: ('a -> 'a -> int) -> 'a t -> 'a t -> int
val equal: ('a -> 'a -> bool) -> 'a t -> 'a t -> bool
val bindings : 'a t -> (elt * 'a) list
val print:
(Format.formatter -> 'a -> unit) -> Format.formatter -> 'a t -> unit
val of_json:
?lab_key:string -> ?lab_value:string -> ?error_msg:string ->
(Yojson.Basic.t -> elt) ->
(Yojson.Basic.t -> 'value) ->
Yojson.Basic.t -> 'value t
val to_json:
?lab_key:string -> ?lab_value:string ->
(elt -> Yojson.Basic.t) ->
('value -> Yojson.Basic.t) ->
'value t -> Yojson.Basic.t
end
module type S = sig
type elt
module Set : Set with type elt = elt
module Map : Map with type elt = elt and type set = Set.t
end
module Make(Ord:OrderedType): S with type elt = Ord.t
module type Projection = sig
type elt_a
type elt_b
type 'a map_a
type 'a map_b
type set_a
type set_b
(** proj_map f init merge map is a map mapping each element b
to the result of the itteration of the function merge over the image in map of the element a in f such that f(a)=b, starting with the element init. *)
val proj_map: (elt_a -> elt_b) -> 'b -> ('b -> 'a -> 'b) -> 'a map_a -> 'b map_b
val proj_map_monadic:
'parameters -> 'method_handler -> (elt_a -> elt_b) -> 'b ->
('parameters -> 'method_handler -> 'b -> 'a -> 'method_handler * 'b) ->
'a map_a -> 'method_handler * 'b map_b
(** proj_set f set is the set \{f(a) | a\in S\} *)
val proj_set:
(elt_a -> elt_b) -> set_a -> set_b
val proj_set_monadic:
'parameters -> 'method_handler -> ('parameters -> 'method_handler -> elt_a -> 'method_handler * elt_b) -> set_a -> 'method_handler * set_b
* partition_set f set is the map mapping any element b with an antecedent for f in the set set , into the set of its antecedents , ie
to the set \{a\in set | f(a)=b\ } .
to the set \{a\in set | f(a)=b\}. *)
val partition_set:
(elt_a -> elt_b) -> set_a -> set_a map_b
val partition_set_monadic:
'parameters -> 'method_handler -> ('parameters -> 'method_handler -> elt_a -> 'method_handler * elt_b) -> set_a ->
'method_handler * set_a map_b
end
module Proj(A:S)(B:S): Projection with
type elt_a = A.elt and type elt_b = B.elt and
type 'a map_a = 'a A.Map.t and type 'a map_b = 'a B.Map.t
module type Projection2 = sig
type elt_a
type elt_b
type elt_c
type 'a map_a
type 'a map_b
type 'a map_c
val proj2:
(elt_a -> elt_b) -> (elt_a -> elt_c) ->
'b -> ('b -> 'a -> 'b) -> 'a map_a -> 'b map_c map_b
val proj2_monadic:
'parameters -> 'method_handler -> (elt_a -> elt_b) -> (elt_a -> elt_c) ->
'b ->
('parameters -> 'method_handler -> 'b -> 'a -> 'method_handler * 'b) ->
'a map_a -> 'method_handler * 'b map_c map_b
end
module Proj2(A:S)(B:S)(C:S): Projection2 with
type elt_a = A.elt and type elt_b = B.elt and
type 'a map_a = 'a A.Map.t and type 'a map_b = 'a B.Map.t and
type elt_c = C.elt and type 'a map_c = 'a C.Map.t
| null | https://raw.githubusercontent.com/Kappa-Dev/KappaTools/eef2337e8688018eda47ccc838aea809cae68de7/core/dataStructures/setMap.mli | ocaml | ****************************************************************************
_ __ * The Kappa Language
| ' / ********************************************************************
| . \ * This file is distributed under the terms of the
|_|\_\ * GNU Lesser General Public License Version 3
****************************************************************************
* Our own implementattion of Set and Map
Purely functionnal.
Functions without _with_logs do NOT raise any exception.
* [minus a b] contains elements of [a] that are not in [b]
* [diff a b] = [minus (union a b) (inter a b)]
returns an element that respects the predicate (if any)
* proj_map f init merge map is a map mapping each element b
to the result of the itteration of the function merge over the image in map of the element a in f such that f(a)=b, starting with the element init.
* proj_set f set is the set \{f(a) | a\in S\} | | |/ / * Copyright 2010 - 2020 CNRS - Harvard Medical School - INRIA - IRIF
module type OrderedType =
sig
type t
val compare : t -> t -> int
val print : Format.formatter -> t -> unit
end
type ('parameters,'error,'a) with_log_wrap =
('parameters -> 'error -> string -> string option -> exn -> 'error) ->
'parameters -> 'error -> 'a
module type Set =
sig
type elt
type t
val empty: t
val is_empty: t -> bool
val singleton: elt -> t
val is_singleton: t -> bool
val add: elt -> t -> t
val add_with_logs: ('parameters,'error,elt -> t -> 'error * t) with_log_wrap
val remove: elt -> t -> t
val add_while_testing_freshness:
('parameters,'error,elt -> t -> 'error * bool * t) with_log_wrap
val remove_while_testing_existence:
('parameters,'error,elt -> t -> 'error * bool * t) with_log_wrap
val remove_with_logs:
('parameters,'error,elt -> t -> 'error * t) with_log_wrap
val split: elt -> t -> (t * bool * t)
val union: t -> t -> t
val disjoint_union: t -> t -> t option
val inter: t -> t -> t
val minus: t -> t -> t
val diff: t -> t -> t
val minus_with_logs: ('parameters,'error,t -> t -> 'error * t) with_log_wrap
val union_with_logs: ('parameters,'error,t -> t -> 'error * t) with_log_wrap
val disjoint_union_with_logs:
('parameters,'error,t -> t -> 'error * t) with_log_wrap
val inter_with_logs: ('parameters,'error,t -> t -> 'error * t) with_log_wrap
val diff_with_logs: ('parameters,'error,t -> t -> 'error * t) with_log_wrap
val size: t -> int
val mem: elt -> t -> bool
val exists: (elt -> bool) -> t -> bool
val filter: (elt -> bool) -> t -> t
val filter_with_logs:
('parameters,'error,(elt -> bool) -> t -> 'error * t) with_log_wrap
val for_all: (elt -> bool) -> t -> bool
val partition: (elt -> bool) -> t -> t * t
val partition_with_logs:
('parameters,'error,(elt -> bool) -> t -> 'error * t * t) with_log_wrap
val compare: t -> t -> int
val equal: t -> t -> bool
val subset: t -> t -> bool
val iter: (elt -> unit) -> t -> unit
val fold: (elt -> 'a -> 'a) -> t -> 'a -> 'a
val fold_inv: (elt -> 'a -> 'a) -> t -> 'a -> 'a
val elements: t -> elt list
val print: Format.formatter -> t -> unit
val choose: t -> elt option
val random: Random.State.t -> t -> elt option
val min_elt: t -> elt option
val max_elt: t -> elt option
end
module type Map =
sig
type elt
type set
type +'a t
val empty: 'a t
val is_empty: 'a t -> bool
val size: 'a t -> int
val root: 'a t -> (elt * 'a) option
val max_key: 'a t -> elt option
val add: elt -> 'a -> 'a t -> 'a t
val remove: elt -> 'a t -> 'a t
val add_while_testing_freshness:
('parameters,'error,
elt -> 'a -> 'a t -> 'error * bool * 'a t) with_log_wrap
val remove_while_testing_existence:
('parameters,'error,elt -> 'a t -> 'error * bool * 'a t) with_log_wrap
val pop: elt -> 'a t -> ('a option * 'a t)
val merge: 'a t -> 'a t -> 'a t
val min_elt: 'a t -> (elt * 'a) option
val find_option: elt -> 'a t -> 'a option
val find_default: 'a -> elt -> 'a t -> 'a
val find_option_with_logs:
('parameters,'error,elt -> 'a t -> 'error * 'a option) with_log_wrap
val find_default_with_logs:
('parameters,'error,'a -> elt -> 'a t -> 'error * 'a) with_log_wrap
val mem: elt -> 'a t -> bool
val diff: 'a t -> 'a t -> 'a t * 'a t
val union: 'a t -> 'a t -> 'a t
val update: 'a t -> 'a t -> 'a t
val diff_pred: ('a -> 'a -> bool) -> 'a t -> 'a t -> 'a t * 'a t
val add_with_logs:
('parameters,'error,elt -> 'a -> 'a t -> 'error * 'a t) with_log_wrap
val remove_with_logs:
('parameters,'error,elt -> 'a t -> 'error * 'a t) with_log_wrap
val join_with_logs:
('parameters,'error,
'a t -> elt -> 'a -> 'a t -> 'error * 'a t) with_log_wrap
val split_with_logs:
('parameters,'error,
elt -> 'a t -> 'error * ('a t * 'a option * 'a t)) with_log_wrap
val update_with_logs:
('parameters,'error,'a t -> 'a t -> 'error * 'a t) with_log_wrap
val map2_with_logs:
('parameters,'error,
('parameters -> 'error -> 'a -> 'error * 'c) ->
('parameters -> 'error -> 'b -> 'error * 'c) ->
('parameters -> 'error -> 'a -> 'b -> 'error * 'c) ->
'a t -> 'b t -> 'error * 'c t) with_log_wrap
val map2z_with_logs:
('parameters,'error,
('parameters -> 'error -> 'a -> 'a -> 'error * 'a) ->
'a t -> 'a t -> 'error * 'a t) with_log_wrap
val fold2z_with_logs:
('parameters,'error,
('parameters -> 'error -> elt -> 'a -> 'b -> 'c -> ('error * 'c)) ->
'a t -> 'b t -> 'c -> 'error * 'c) with_log_wrap
val fold2_with_logs:
('parameters,'error,
('parameters -> 'error -> elt -> 'a -> 'c -> 'error * 'c) ->
('parameters -> 'error -> elt -> 'b -> 'c -> 'error * 'c) ->
('parameters -> 'error -> elt -> 'a -> 'b -> 'c -> 'error * 'c) ->
'a t -> 'b t -> 'c -> 'error * 'c) with_log_wrap
val fold2_sparse_with_logs:
('parameters,'error,
('parameters -> 'error -> elt -> 'a -> 'b -> 'c -> ('error * 'c)) ->
'a t -> 'b t -> 'c -> 'error * 'c) with_log_wrap
val iter2_sparse_with_logs:
('parameters,'error,
('parameters -> 'error -> elt -> 'a -> 'b -> 'error) ->
'a t -> 'b t -> 'error) with_log_wrap
val diff_with_logs:
('parameters,'error,'a t -> 'a t -> 'error * 'a t * 'a t) with_log_wrap
val diff_pred_with_logs:
('parameters,'error,
('a -> 'a -> bool) -> 'a t -> 'a t -> 'error * 'a t * 'a t) with_log_wrap
val merge_with_logs :
('parameters,'error,'a t -> 'a t -> 'error * 'a t) with_log_wrap
val union_with_logs :
('parameters,'error,'a t -> 'a t -> 'error * 'a t) with_log_wrap
val fold_restriction_with_logs:
('parameters,'error,
(elt -> 'a -> ('error * 'b) -> ('error* 'b)) ->
set -> 'a t -> 'b -> 'error * 'b) with_log_wrap
val fold_restriction_with_missing_associations_with_logs:
('parameters,'error,
(elt -> 'a -> ('error * 'b) -> ('error* 'b)) ->
(elt -> ('error * 'b) -> ('error * 'b)) ->
set -> 'a t -> 'b -> 'error * 'b) with_log_wrap
val iter: (elt -> 'a -> unit) -> 'a t -> unit
val fold: (elt -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
val fold_with_interruption: (elt -> 'a -> 'b -> ('b,'c) Stop.stop) -> 'a t -> 'b -> ('b,'c) Stop.stop
val monadic_fold2:
'parameters -> 'method_handler ->
('parameters -> 'method_handler ->
elt -> 'a -> 'b -> 'c -> ('method_handler * 'c)) ->
('parameters -> 'method_handler ->
elt -> 'a -> 'c -> ('method_handler * 'c)) ->
('parameters -> 'method_handler ->
elt -> 'b -> 'c -> ('method_handler * 'c)) ->
'a t -> 'b t -> 'c -> ('method_handler * 'c)
val monadic_fold2_sparse:
'parameters -> 'method_handler ->
('parameters -> 'method_handler ->
elt -> 'a -> 'b -> 'c -> ('method_handler * 'c)) ->
'a t -> 'b t -> 'c -> ('method_handler * 'c)
val monadic_iter2_sparse:
'parameters -> 'method_handler ->
('parameters -> 'method_handler ->
elt -> 'a -> 'b -> 'method_handler) ->
'a t -> 'b t -> 'method_handler
val monadic_fold_restriction:
'parameters -> 'method_handler ->
('parameters -> 'method_handler ->
elt -> 'a -> 'b -> ('method_handler * 'b)) ->
set -> 'a t -> 'b -> 'method_handler * 'b
val mapi: (elt -> 'a -> 'b) -> 'a t -> 'b t
val map: ('a -> 'b) -> 'a t -> 'b t
val map2: ('a -> 'a -> 'a) -> 'a t -> 'a t -> 'a t
val for_all: (elt -> 'a -> bool) -> 'a t -> bool
val filter_one: (elt -> 'a -> bool) -> 'a t -> (elt * 'a) option
val compare: ('a -> 'a -> int) -> 'a t -> 'a t -> int
val equal: ('a -> 'a -> bool) -> 'a t -> 'a t -> bool
val bindings : 'a t -> (elt * 'a) list
val print:
(Format.formatter -> 'a -> unit) -> Format.formatter -> 'a t -> unit
val of_json:
?lab_key:string -> ?lab_value:string -> ?error_msg:string ->
(Yojson.Basic.t -> elt) ->
(Yojson.Basic.t -> 'value) ->
Yojson.Basic.t -> 'value t
val to_json:
?lab_key:string -> ?lab_value:string ->
(elt -> Yojson.Basic.t) ->
('value -> Yojson.Basic.t) ->
'value t -> Yojson.Basic.t
end
module type S = sig
type elt
module Set : Set with type elt = elt
module Map : Map with type elt = elt and type set = Set.t
end
module Make(Ord:OrderedType): S with type elt = Ord.t
module type Projection = sig
type elt_a
type elt_b
type 'a map_a
type 'a map_b
type set_a
type set_b
val proj_map: (elt_a -> elt_b) -> 'b -> ('b -> 'a -> 'b) -> 'a map_a -> 'b map_b
val proj_map_monadic:
'parameters -> 'method_handler -> (elt_a -> elt_b) -> 'b ->
('parameters -> 'method_handler -> 'b -> 'a -> 'method_handler * 'b) ->
'a map_a -> 'method_handler * 'b map_b
val proj_set:
(elt_a -> elt_b) -> set_a -> set_b
val proj_set_monadic:
'parameters -> 'method_handler -> ('parameters -> 'method_handler -> elt_a -> 'method_handler * elt_b) -> set_a -> 'method_handler * set_b
* partition_set f set is the map mapping any element b with an antecedent for f in the set set , into the set of its antecedents , ie
to the set \{a\in set | f(a)=b\ } .
to the set \{a\in set | f(a)=b\}. *)
val partition_set:
(elt_a -> elt_b) -> set_a -> set_a map_b
val partition_set_monadic:
'parameters -> 'method_handler -> ('parameters -> 'method_handler -> elt_a -> 'method_handler * elt_b) -> set_a ->
'method_handler * set_a map_b
end
module Proj(A:S)(B:S): Projection with
type elt_a = A.elt and type elt_b = B.elt and
type 'a map_a = 'a A.Map.t and type 'a map_b = 'a B.Map.t
module type Projection2 = sig
type elt_a
type elt_b
type elt_c
type 'a map_a
type 'a map_b
type 'a map_c
val proj2:
(elt_a -> elt_b) -> (elt_a -> elt_c) ->
'b -> ('b -> 'a -> 'b) -> 'a map_a -> 'b map_c map_b
val proj2_monadic:
'parameters -> 'method_handler -> (elt_a -> elt_b) -> (elt_a -> elt_c) ->
'b ->
('parameters -> 'method_handler -> 'b -> 'a -> 'method_handler * 'b) ->
'a map_a -> 'method_handler * 'b map_c map_b
end
module Proj2(A:S)(B:S)(C:S): Projection2 with
type elt_a = A.elt and type elt_b = B.elt and
type 'a map_a = 'a A.Map.t and type 'a map_b = 'a B.Map.t and
type elt_c = C.elt and type 'a map_c = 'a C.Map.t
|
dd72d4c8f7facfcd336c3995e2a39a97d25e068b0d5239ae83b212824b94b0c2 | crosswire/xiphos | kddurtreeZ.scm | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; ;;
Centre for Speech Technology Research ; ;
University of Edinburgh , UK ; ;
;;; Copyright (c) 1996,1997 ;;
All Rights Reserved . ; ;
;;; ;;
;;; Permission is hereby granted, free of charge, to use and distribute ;;
;;; this software and its documentation without restriction, including ;;
;;; without limitation the rights to use, copy, modify, merge, publish, ;;
;;; distribute, sublicense, and/or sell copies of this work, and to ;;
;;; permit persons to whom this work is furnished to do so, subject to ;;
;;; the following conditions: ;;
;;; 1. The code must retain the above copyright notice, this list of ;;
;;; conditions and the following disclaimer. ;;
;;; 2. Any modifications must be clearly marked as such. ;;
3 . Original authors ' names are not deleted . ; ;
;;; 4. The authors' names are not used to endorse or promote products ;;
;;; derived from this software without specific prior written ;;
;;; permission. ;;
;;; ;;
;;; THE UNIVERSITY OF EDINBURGH AND THE CONTRIBUTORS TO THIS WORK ;;
;;; DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;;
;;; ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;;
;;; SHALL THE UNIVERSITY OF EDINBURGH NOR THE CONTRIBUTORS BE LIABLE ;;
;;; FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;;
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , IN ; ;
;;; AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;;
;;; ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;;
;;; THIS SOFTWARE. ;;
;;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; A tree to predict zcore durations build from f2b
;;; doesn't use actual phonemes so it can have better generalizations
;;;
(set! kd_durs
'(
(uh 0.067 0.025)
(hh 0.061 0.028)
(ao 0.138 0.046)
(hv 0.053 0.020)
(v 0.051 0.019)
(ih 0.058 0.023)
(el 0.111 0.043)
(ey 0.132 0.042)
(em 0.080 0.033)
(jh 0.094 0.024)
(w 0.054 0.023)
(uw 0.107 0.044)
(ae 0.120 0.036)
(en 0.117 0.056)
(k 0.089 0.034)
(y 0.048 0.025)
(axr 0.147 0.035)
(l 0.056 0.026)
(ng 0.064 0.024)
(zh 0.071 0.030)
(z 0.079 0.034)
(brth 0.246 0.046)
(m 0.069 0.028)
(iy 0.097 0.041)
(n 0.059 0.025)
(ah 0.087 0.031)
(er 0.086 0.010)
(b 0.069 0.024)
(pau 0.200 0.104)
(aw 0.166 0.053)
(p 0.088 0.030)
(ch 0.115 0.025)
(ow 0.134 0.039)
(dh 0.031 0.016)
(nx 0.049 0.100)
(d 0.048 0.021)
(ax 0.046 0.024)
(h# 0.060 0.083)
(r 0.053 0.031)
( r 0.043 0.021 )
(eh 0.095 0.036)
(ay 0.137 0.047)
(oy 0.183 0.050)
(f 0.095 0.033)
(sh 0.108 0.031)
(s 0.102 0.037)
(g 0.064 0.021)
(dx 0.031 0.016)
(th 0.093 0.050)
(aa 0.094 0.037)
(t 0.070 0.020)
)
)
(set! kd_duration_cart_tree
'
((name is pau)
((emph_sil is +)
((0.0 -0.5))
((p.R:SylStructure.parent.parent.pbreak is BB)
((0.0 2.0))
((0.0 0.0))))
((R:SylStructure.parent.accented is 0)
((n.ph_ctype is 0)
((p.ph_vlng is 0)
((R:SylStructure.parent.syl_codasize < 1.5)
((p.ph_ctype is n)
((ph_ctype is f)
((0.559208 -0.783163))
((1.05215 -0.222704)))
((ph_ctype is s)
((R:SylStructure.parent.syl_break is 2)
((0.589948 0.764459))
((R:SylStructure.parent.asyl_in < 0.7)
((1.06385 0.567944))
((0.691943 0.0530272))))
((ph_vlng is l)
((pp.ph_vfront is 1)
((1.06991 0.766486))
((R:SylStructure.parent.syl_break is 1)
((0.69665 0.279248))
((0.670353 0.0567774))))
((p.ph_ctype is s)
((seg_onsetcoda is coda)
((0.828638 -0.038356))
((ph_ctype is f)
((0.7631 -0.545853))
((0.49329 -0.765994))))
((R:SylStructure.parent.parent.gpos is det)
((R:SylStructure.parent.last_accent < 0.3)
((R:SylStructure.parent.sub_phrases < 1)
((0.811686 0.160195))
((0.799015 0.713958)))
((0.731599 -0.215472)))
((ph_ctype is r)
((0.673487 0.092772))
((R:SylStructure.parent.asyl_in < 1)
((0.745273 0.00132813))
((0.75457 -0.334898)))))))))
((pos_in_syl < 0.5)
((R:SylStructure.parent.R:Syllable.p.syl_break is 2)
((R:SylStructure.parent.R:Syllable.n.syl_onsetsize < 0.2)
((0.902446 -0.041618))
((R:SylStructure.parent.sub_phrases < 2.3)
((0.900629 0.262952))
((1.18474 0.594794))))
((seg_onset_stop is 0)
((R:SylStructure.parent.position_type is mid)
((0.512323 -0.760444))
((R:SylStructure.parent.syl_out < 6.8)
((pp.ph_vlng is a)
((0.640575 -0.450449))
((ph_ctype is f)
((R:SylStructure.parent.sub_phrases < 1.3)
((0.862876 -0.296956))
((R:SylStructure.parent.syl_out < 2.4)
((0.803215 0.0422868))
((0.877856 -0.154465))))
((R:SylStructure.parent.syl_out < 3.6)
((R:SylStructure.parent.syl_out < 1.2)
((0.567081 -0.264199))
((0.598043 -0.541738)))
((0.676843 -0.166623)))))
((0.691678 -0.57173))))
((R:SylStructure.parent.parent.gpos is cc)
((1.15995 0.313289))
((pp.ph_vfront is 1)
((0.555993 0.0695819))
((R:SylStructure.parent.asyl_in < 1.2)
((R:SylStructure.parent.sub_phrases < 2.7)
((0.721635 -0.367088))
((0.71919 -0.194887)))
((0.547052 -0.0637491)))))))
((ph_ctype is s)
((R:SylStructure.parent.syl_break is 0)
((R:SylStructure.parent.R:Syllable.p.syl_break is 1)
((0.650007 -0.333421))
((0.846301 -0.165383)))
((0.527756 -0.516332)))
((R:SylStructure.parent.syl_break is 0)
((p.ph_ctype is s)
((0.504414 -0.779112))
((0.812498 -0.337611)))
((pos_in_syl < 1.4)
((0.513041 -0.745807))
((p.ph_ctype is s)
((0.350582 -1.04907))
((0.362 -0.914974))))))))
((R:SylStructure.parent.syl_break is 0)
((ph_ctype is n)
((R:SylStructure.parent.position_type is initial)
((pos_in_syl < 1.2)
((0.580485 0.172658))
((0.630973 -0.101423)))
((0.577937 -0.360092)))
((R:SylStructure.parent.syl_out < 2.9)
((R:SylStructure.parent.syl_out < 1.1)
((R:SylStructure.parent.position_type is initial)
((0.896092 0.764189))
((R:SylStructure.parent.sub_phrases < 3.6)
((ph_ctype is s)
((0.877362 0.555132))
((0.604511 0.369882)))
((0.799982 0.666966))))
((seg_onsetcoda is coda)
((p.ph_vlng is a)
((R:SylStructure.parent.last_accent < 0.4)
((0.800736 0.240634))
((0.720606 0.486176)))
((1.18173 0.573811)))
((0.607147 0.194468))))
((ph_ctype is r)
((0.88377 0.499383))
((R:SylStructure.parent.last_accent < 0.5)
((R:SylStructure.parent.position_type is initial)
((R:SylStructure.parent.parent.word_numsyls < 2.4)
((0.62798 0.0737318))
((0.787334 0.331014)))
((ph_ctype is s)
((0.808368 0.0929299))
((0.527948 -0.0443271))))
((seg_coda_fric is 0)
((p.ph_vlng is a)
((0.679745 0.517681))
((R:SylStructure.parent.sub_phrases < 1.1)
((0.759979 0.128316))
((0.775233 0.361383))))
((R:SylStructure.parent.last_accent < 1.3)
((0.696255 0.054136))
((0.632425 0.246742))))))))
((pos_in_syl < 0.3)
((R:SylStructure.parent.R:Syllable.p.syl_break is 2)
((0.847602 0.621547))
((ph_ctype is s)
((0.880645 0.501679))
((R:SylStructure.parent.sub_phrases < 3.3)
((R:SylStructure.parent.sub_phrases < 0.3)
((0.901014 -0.042049))
((0.657493 0.183226)))
((0.680126 0.284799)))))
((ph_ctype is s)
((p.ph_vlng is s)
((0.670033 -0.820934))
((0.863306 -0.348735)))
((ph_ctype is n)
((R:SylStructure.parent.asyl_in < 1.2)
((0.656966 -0.40092))
((0.530966 -0.639366)))
((seg_coda_fric is 0)
((1.04153 0.364857))
((pos_in_syl < 1.2)
((R:SylStructure.parent.syl_out < 3.4)
((0.81503 -0.00768613))
((0.602665 -0.197753)))
((0.601844 -0.394632)))))))))
((n.ph_ctype is f)
((pos_in_syl < 1.5)
((R:SylStructure.parent.R:Syllable.p.syl_break is 2)
((pos_in_syl < 0.1)
((1.63863 0.938841))
((R:SylStructure.parent.position_type is initial)
((0.897722 -0.0796637))
((nn.ph_vheight is 0)
((0.781081 0.480026))
((0.779711 0.127175)))))
((ph_ctype is r)
((p.ph_ctype is s)
((0.581329 -0.708767))
((0.564366 -0.236212)))
((ph_vlng is a)
((p.ph_ctype is r)
((0.70992 -0.273389))
((R:SylStructure.parent.parent.gpos is in)
((0.764696 0.0581338))
((nn.ph_vheight is 0)
((0.977737 0.721904))
((R:SylStructure.parent.sub_phrases < 2.2)
((pp.ph_vfront is 0)
((0.586708 0.0161206))
((0.619949 0.227372)))
((0.707285 0.445569))))))
((ph_ctype is n)
((R:SylStructure.parent.syl_break is 1)
((nn.ph_vfront is 2)
((0.430295 -0.120097))
((0.741371 0.219042)))
((0.587492 0.321245)))
((p.ph_ctype is n)
((0.871586 0.134075))
((p.ph_ctype is r)
((0.490751 -0.466418))
((R:SylStructure.parent.syl_codasize < 1.3)
((R:SylStructure.parent.sub_phrases < 2.2)
((p.ph_ctype is s)
((0.407452 -0.425925))
((0.644771 -0.542809)))
((0.688772 -0.201899)))
((ph_vheight is 1)
((nn.ph_vheight is 0)
((0.692018 0.209018))
((0.751345 -0.178136)))
((R:SylStructure.parent.R:Syllable.n.syl_onsetsize < 0.3)
((R:SylStructure.parent.asyl_in < 1.5)
((0.599633 -0.235593))
((0.60042 0.126118)))
((p.ph_vlng is a)
((0.7148 -0.174812))
((R:SylStructure.parent.parent.gpos is content)
((0.761296 -0.231509))
((0.813081 -0.536405)))))))))))))
((ph_ctype is n)
((0.898844 0.163343))
((p.ph_vlng is s)
((seg_coda_fric is 0)
((0.752921 -0.45528))
((0.890079 -0.0998025)))
((ph_ctype is f)
((0.729376 -0.930547))
((ph_ctype is s)
((R:SylStructure.parent.R:Syllable.p.syl_break is 0)
((0.745052 -0.634119))
((0.521502 -0.760176)))
((R:SylStructure.parent.syl_break is 1)
((0.766575 -0.121355))
((0.795616 -0.557509))))))))
((p.ph_vlng is 0)
((p.ph_ctype is r)
((ph_vlng is 0)
((0.733659 -0.402734))
((R:SylStructure.parent.sub_phrases < 1.5)
((ph_vlng is s)
((0.326176 -0.988478))
((n.ph_ctype is s)
((0.276471 -0.802536))
((0.438283 -0.900628))))
((nn.ph_vheight is 0)
((ph_vheight is 2)
((0.521 -0.768992))
((0.615436 -0.574918)))
((ph_vheight is 1)
((0.387376 -0.756359))
((pos_in_syl < 0.3)
((0.417235 -0.808937))
((0.384043 -0.93315)))))))
((ph_vlng is a)
((ph_ctype is 0)
((n.ph_ctype is s)
((p.ph_ctype is f)
((R:SylStructure.parent.R:Syllable.n.syl_onsetsize < 0.2)
((0.415908 -0.428493))
((pos_in_syl < 0.1)
((0.790441 0.0211071))
((0.452465 -0.254485))))
((p.ph_ctype is s)
((R:SylStructure.parent.R:Syllable.n.syl_onsetsize < 0.2)
((0.582447 -0.389966))
((0.757648 0.185781)))
((R:SylStructure.parent.sub_phrases < 1.4)
((0.628965 0.422551))
((0.713613 0.145576)))))
((seg_onset_stop is 0)
((R:SylStructure.parent.R:Syllable.p.syl_break is 0)
((pp.ph_vfront is 1)
((0.412363 -0.62319))
((R:SylStructure.parent.syl_out < 3.6)
((0.729259 -0.317324))
((0.441633 -0.591051))))
((R:SylStructure.parent.syl_break is 1)
((R:SylStructure.parent.sub_phrases < 2.7)
((0.457728 -0.405607))
((0.532411 -0.313148)))
((R:SylStructure.parent.last_accent < 0.3)
((1.14175 0.159416))
((0.616396 -0.254651)))))
((R:SylStructure.parent.position_type is initial)
((0.264181 -0.799896))
((0.439801 -0.551309)))))
((R:SylStructure.parent.position_type is final)
((0.552027 -0.707084))
((0.585661 -0.901874))))
((ph_ctype is s)
((pos_in_syl < 1.2)
((R:SylStructure.parent.R:Syllable.n.syl_onsetsize < 0.2)
((pp.ph_vfront is 1)
((0.607449 0.196466))
((0.599662 0.00382414)))
((0.64109 -0.12859)))
((pp.ph_vfront is 1)
((0.720484 -0.219339))
((0.688707 -0.516734))))
((ph_vlng is s)
((n.ph_ctype is s)
((R:SylStructure.parent.parent.gpos is content)
((R:SylStructure.parent.position_type is single)
((0.659206 0.159445))
((R:SylStructure.parent.parent.word_numsyls < 3.5)
((R:SylStructure.parent.sub_phrases < 2)
((0.447186 -0.419103))
((0.631822 -0.0928561)))
((0.451623 -0.576116))))
((ph_vheight is 3)
((0.578626 -0.64583))
((0.56636 -0.4665))))
((R:SylStructure.parent.parent.gpos is in)
((0.771516 -0.217292))
((R:SylStructure.parent.R:Syllable.p.syl_break is 2)
((0.688571 -0.304382))
((R:SylStructure.parent.parent.gpos is content)
((R:SylStructure.parent.R:Syllable.p.syl_break is 1)
((n.ph_ctype is n)
((0.556085 -0.572203))
((0.820173 -0.240338)))
((R:SylStructure.parent.parent.word_numsyls < 2.2)
((0.595398 -0.588171))
((0.524737 -0.95797))))
((R:SylStructure.parent.sub_phrases < 3.9)
((0.371492 -0.959427))
((0.440479 -0.845747)))))))
((R:SylStructure.parent.R:Syllable.p.syl_break is 0)
((p.ph_ctype is f)
((0.524088 -0.482247))
((nn.ph_vheight is 1)
((0.587666 -0.632362))
((ph_vlng is l)
((R:SylStructure.parent.position_type is final)
((0.513286 -0.713117))
((0.604613 -0.924308)))
((R:SylStructure.parent.syl_codasize < 2.2)
((0.577997 -0.891342))
((0.659804 -1.15252))))))
((pp.ph_vlng is s)
((ph_ctype is f)
((0.813383 -0.599624))
((0.984027 -0.0771909)))
((p.ph_ctype is f)
((R:SylStructure.parent.parent.gpos is in)
((R:SylStructure.parent.R:Syllable.p.syl_break is 1)
((0.313572 -1.03242))
((0.525854 -0.542799)))
((R:SylStructure.parent.syl_out < 2.8)
((0.613007 -0.423979))
((0.570258 -0.766379))))
((R:SylStructure.parent.syl_break is 1)
((R:SylStructure.parent.parent.gpos is to)
((0.364585 -0.792895))
((ph_vlng is l)
((0.69143 -0.276816))
((0.65673 -0.523721))))
((R:SylStructure.parent.syl_out < 3.6)
((R:SylStructure.parent.position_type is initial)
((0.682096 -0.488102))
((0.406364 -0.731758)))
((0.584694 -0.822229)))))))))))
((n.ph_ctype is r)
((R:SylStructure.parent.position_type is initial)
((p.ph_vlng is a)
((0.797058 1.02334))
((ph_ctype is s)
((1.0548 0.536277))
((0.817253 0.138201))))
((R:SylStructure.parent.sub_phrases < 1.1)
((R:SylStructure.parent.syl_out < 3.3)
((0.884574 -0.23471))
((0.772063 -0.525292)))
((nn.ph_vfront is 1)
((1.25254 0.417485))
((0.955557 -0.0781996)))))
((pp.ph_vfront is 0)
((ph_ctype is f)
((n.ph_ctype is s)
((R:SylStructure.parent.parent.gpos is content)
((R:SylStructure.parent.R:Syllable.p.syl_break is 0)
((0.583506 -0.56941))
((0.525949 -0.289362)))
((0.749316 -0.0921038)))
((p.ph_vlng is s)
((0.734234 0.139463))
((0.680119 -0.0708717))))
((ph_vlng is s)
((ph_vheight is 1)
((0.908712 -0.618971))
((0.55344 -0.840495)))
((R:SylStructure.parent.R:Syllable.n.syl_onsetsize < 1.2)
((pos_in_syl < 1.2)
((R:SylStructure.parent.R:Syllable.p.syl_break is 2)
((0.838715 0.00913392))
((R:SylStructure.parent.R:Syllable.p.syl_break is 1)
((ph_vheight is 2)
((0.555513 -0.512523))
((R:SylStructure.parent.position_type is initial)
((0.758711 0.121704))
((0.737555 -0.25637))))
((R:SylStructure.parent.syl_out < 3.1)
((n.ph_ctype is s)
((0.611756 -0.474522))
((1.05437 -0.247206)))
((R:SylStructure.parent.syl_codasize < 2.2)
((R:SylStructure.parent.position_type is final)
((0.567761 -0.597866))
((0.785599 -0.407765)))
((0.575598 -0.741256))))))
((ph_ctype is s)
((n.ph_ctype is s)
((0.661069 -1.08426))
((0.783184 -0.39789)))
((R:SylStructure.parent.R:Syllable.p.syl_break is 1)
((R:SylStructure.parent.sub_phrases < 2.6)
((0.511323 -0.666011))
((0.691878 -0.499492)))
((ph_ctype is r)
((0.482131 -0.253186))
((0.852955 -0.372832))))))
((0.854447 -0.0936489)))))
((R:SylStructure.parent.position_type is final)
((0.685939 -0.249982))
((R:SylStructure.parent.syl_out < 3.2)
((0.989843 0.18086))
((0.686805 -0.0402908)))))))))
((R:SylStructure.parent.syl_out < 2.4)
((R:SylStructure.parent.syl_out < 0.2)
((seg_onsetcoda is coda)
((ph_ctype is s)
((R:SylStructure.parent.syl_break is 4)
((pp.ph_vlng is 0)
((0.959737 1.63203))
((1.20714 0.994933)))
((n.ph_ctype is 0)
((R:SylStructure.parent.syl_break is 2)
((0.864809 0.214457))
((0.874278 0.730381)))
((pp.ph_vfront is 0)
((seg_coda_fric is 0)
((1.20844 -0.336221))
((1.01357 0.468302)))
((0.658106 -0.799121)))))
((n.ph_ctype is f)
((ph_ctype is f)
((1.26332 0.0300613))
((ph_vlng is d)
((1.02719 1.1649))
((ph_ctype is 0)
((R:SylStructure.parent.asyl_in < 1.2)
((1.14048 2.2668))
((ph_vheight is 1)
((1.15528 1.50375))
((1.42406 2.07927))))
((R:SylStructure.parent.sub_phrases < 1.1)
((0.955892 1.10243))
((R:SylStructure.parent.syl_break is 2)
((1.32682 1.8432))
((1.27582 1.59853)))))))
((n.ph_ctype is 0)
((ph_ctype is n)
((R:SylStructure.parent.syl_break is 2)
((1.45399 1.12927))
((1.05543 0.442376)))
((R:SylStructure.parent.syl_break is 4)
((R:SylStructure.parent.position_type is final)
((ph_ctype is f)
((1.46434 1.76508))
((0.978055 0.7486)))
((1.2395 2.30826)))
((ph_ctype is 0)
((0.935325 1.69917))
((nn.ph_vfront is 1)
((1.20456 1.31128))
((R:SylStructure.parent.R:Syllable.n.syl_onsetsize < 0.2)
((nn.ph_vheight is 0)
((1.16907 0.212421))
((0.952091 0.653094)))
((p.ph_ctype is 0)
((1.05502 1.25802))
((0.818731 0.777568))))))))
((ph_ctype is f)
((p.ph_ctype is 0)
((1.03918 0.163941))
((0.737545 -0.167063)))
((R:SylStructure.parent.position_type is final)
((n.ph_ctype is n)
((R:SylStructure.parent.last_accent < 0.5)
((R:SylStructure.parent.sub_phrases < 2.8)
((0.826207 -0.000859005))
((0.871119 0.273433)))
((R:SylStructure.parent.parent.word_numsyls < 2.4)
((1.17405 1.05694))
((0.858394 0.244916))))
((R:SylStructure.parent.syl_codasize < 2.2)
((p.ph_ctype is 0)
((1.14092 1.21187))
((R:SylStructure.parent.syl_break is 2)
((1.02653 0.59865))
((0.94248 1.1634))))
((seg_coda_fric is 0)
((1.07441 0.292935))
((1.15736 0.92574)))))
((ph_vlng is s)
((R:SylStructure.parent.syl_break is 2)
((1.34638 1.23484))
((0.951514 2.02008)))
((ph_ctype is 0)
((p.ph_ctype is r)
((0.806106 0.697089))
((R:SylStructure.parent.syl_break is 2)
((1.10891 0.992197))
((1.04657 1.51093))))
((1.18165 0.520952)))))))))
((p.ph_vlng is 0)
((pos_in_syl < 0.7)
((R:SylStructure.parent.position_type is final)
((ph_ctype is r)
((0.966357 0.185827))
((ph_ctype is s)
((0.647163 0.0332298))
((0.692972 -0.534917))))
((ph_ctype is s)
((0.881521 0.575107))
((p.ph_ctype is f)
((0.8223 -0.111275))
((R:SylStructure.parent.last_accent < 0.3)
((0.969188 0.09447))
((0.894438 0.381947))))))
((p.ph_ctype is f)
((0.479748 -0.490108))
((0.813125 -0.201268))))
((ph_ctype is s)
((0.908566 1.20397))
((R:SylStructure.parent.last_accent < 1.2)
((0.88078 0.636568))
((0.978087 1.07763))))))
((pos_in_syl < 1.3)
((R:SylStructure.parent.syl_break is 0)
((pos_in_syl < 0.1)
((R:SylStructure.parent.position_type is initial)
((p.ph_ctype is n)
((0.801651 -0.0163359))
((ph_ctype is s)
((n.ph_ctype is r)
((0.893307 1.07253))
((p.ph_vlng is 0)
((0.92651 0.525806))
((0.652444 0.952792))))
((p.ph_vlng is 0)
((seg_onsetcoda is coda)
((0.820151 0.469117))
((p.ph_ctype is f)
((0.747972 -0.0716448))
((ph_ctype is f)
((0.770882 0.457137))
((0.840905 0.102492)))))
((R:SylStructure.parent.syl_out < 1.1)
((0.667824 0.697337))
((0.737967 0.375114))))))
((ph_vheight is 1)
((0.624353 0.410671))
((R:SylStructure.parent.asyl_in < 0.8)
((0.647905 -0.331055))
((p.ph_ctype is s)
((0.629039 -0.240616))
((0.749277 -0.0191273))))))
((ph_vheight is 3)
((p.ph_ctype is s)
((0.626922 0.556537))
((0.789357 0.153892)))
((seg_onsetcoda is coda)
((n.ph_ctype is 0)
((R:SylStructure.parent.parent.word_numsyls < 3.4)
((0.744714 0.123242))
((0.742039 0.295753)))
((seg_coda_fric is 0)
((R:SylStructure.parent.parent.word_numsyls < 2.4)
((ph_vheight is 1)
((0.549715 -0.341018))
((0.573641 -0.00893114)))
((nn.ph_vfront is 2)
((0.67099 -0.744625))
((0.664438 -0.302803))))
((p.ph_vlng is 0)
((0.630028 0.113815))
((0.632794 -0.128733)))))
((ph_ctype is r)
((0.367169 -0.854509))
((0.94334 -0.216179))))))
((n.ph_ctype is f)
((ph_vlng is 0)
((1.3089 0.46195))
((R:SylStructure.parent.syl_codasize < 1.3)
((1.07673 0.657169))
((pp.ph_vlng is 0)
((0.972319 1.08222))
((1.00038 1.46257)))))
((p.ph_vlng is l)
((1.03617 0.785204))
((p.ph_vlng is a)
((R:SylStructure.parent.position_type is final)
((1.00681 0.321168))
((0.928115 0.950834)))
((ph_vlng is 0)
((pos_in_syl < 0.1)
((R:SylStructure.parent.position_type is final)
((0.863682 -0.167374))
((nn.ph_vheight is 0)
((p.ph_ctype is f)
((0.773591 -0.00374425))
((R:SylStructure.parent.syl_out < 1.1)
((0.951802 0.228448))
((1.02282 0.504252))))
((1.09721 0.736476))))
((R:SylStructure.parent.position_type is final)
((1.04302 0.0590974))
((0.589208 -0.431535))))
((n.ph_ctype is 0)
((1.27879 1.00642))
((ph_vlng is s)
((R:SylStructure.parent.asyl_in < 1.4)
((0.935787 0.481652))
((0.9887 0.749861)))
((R:SylStructure.parent.syl_out < 1.1)
((R:SylStructure.parent.position_type is final)
((0.921307 0.0696307))
((0.83675 0.552212)))
((0.810076 -0.0479225))))))))))
((ph_ctype is s)
((n.ph_ctype is s)
((0.706959 -1.0609))
((p.ph_ctype is n)
((0.850614 -0.59933))
((n.ph_ctype is r)
((0.665947 0.00698725))
((n.ph_ctype is 0)
((R:SylStructure.parent.position_type is initial)
((0.762889 -0.0649044))
((0.723956 -0.248899)))
((R:SylStructure.parent.sub_phrases < 1.4)
((0.632957 -0.601987))
((0.889114 -0.302401)))))))
((ph_ctype is f)
((R:SylStructure.parent.syl_codasize < 2.2)
((R:SylStructure.parent.R:Syllable.n.syl_onsetsize < 0.2)
((R:SylStructure.parent.syl_out < 1.1)
((0.865267 0.164636))
((0.581827 -0.0989051)))
((nn.ph_vfront is 2)
((0.684459 -0.316836))
((0.778854 -0.0961191))))
((R:SylStructure.parent.syl_out < 1.1)
((p.ph_ctype is s)
((0.837964 -0.429437))
((0.875304 -0.0652743)))
((0.611071 -0.635089))))
((p.ph_ctype is r)
((R:SylStructure.parent.syl_out < 1.1)
((0.762012 0.0139361))
((0.567983 -0.454845)))
((R:SylStructure.parent.syl_codasize < 2.2)
((ph_ctype is l)
((1.18845 0.809091))
((R:SylStructure.parent.position_type is initial)
((ph_ctype is n)
((0.773548 -0.277092))
((1.01586 0.281001)))
((p.ph_ctype is 0)
((1.06831 0.699145))
((0.924189 0.241873)))))
((R:SylStructure.parent.syl_break is 0)
((ph_ctype is n)
((0.592321 -0.470784))
((0.778688 -0.072112)))
((n.ph_ctype is s)
((1.08848 0.0733489))
((1.25674 0.608371))))))))))
((pos_in_syl < 0.7)
((p.ph_vlng is 0)
((R:SylStructure.parent.position_type is mid)
((ph_ctype is 0)
((ph_vheight is 2)
((0.456225 -0.293282))
((0.561529 -0.0816115)))
((0.6537 -0.504024)))
((ph_ctype is s)
((R:SylStructure.parent.R:Syllable.p.syl_break is 2)
((1.31586 0.98395))
((R:SylStructure.parent.position_type is single)
((0.816869 0.634789))
((R:SylStructure.parent.syl_out < 4.4)
((1.05578 0.479029))
((R:SylStructure.parent.asyl_in < 0.4)
((1.11813 0.143214))
((0.87178 0.406834))))))
((n.ph_ctype is n)
((R:SylStructure.parent.last_accent < 0.6)
((0.838154 -0.415599))
((0.924024 0.110288)))
((seg_onsetcoda is coda)
((nn.ph_vfront is 2)
((0.670096 0.0314187))
((n.ph_ctype is f)
((1.00363 0.693893))
((R:SylStructure.parent.syl_out < 6)
((0.772363 0.215675))
((0.920313 0.574068)))))
((R:SylStructure.parent.position_type is final)
((0.673837 -0.458142))
((R:SylStructure.parent.sub_phrases < 2.8)
((R:SylStructure.parent.R:Syllable.p.syl_break is 2)
((0.894817 0.304628))
((ph_ctype is n)
((0.787302 -0.23094))
((R:SylStructure.parent.asyl_in < 1.2)
((ph_ctype is f)
((R:SylStructure.parent.last_accent < 0.5)
((1.12278 0.326954))
((0.802236 -0.100616)))
((0.791255 -0.0919132)))
((0.95233 0.219053)))))
((R:SylStructure.parent.position_type is initial)
((ph_ctype is f)
((1.0616 0.216118))
((0.703216 -0.00834086)))
((ph_ctype is f)
((1.22277 0.761763))
((0.904811 0.332721))))))))))
((ph_vheight is 0)
((p.ph_vlng is s)
((0.873379 0.217178))
((n.ph_ctype is r)
((0.723915 1.29451))
((n.ph_ctype is 0)
((R:SylStructure.parent.R:Syllable.p.syl_break is 1)
((R:SylStructure.parent.sub_phrases < 4)
((seg_coda_fric is 0)
((p.ph_vlng is l)
((0.849154 0.945261))
((0.633261 0.687498)))
((0.728546 0.403076)))
((0.850962 1.00255)))
((0.957999 1.09113)))
((0.85771 0.209045)))))
((ph_vheight is 2)
((0.803401 -0.0544067))
((0.681353 0.256045)))))
((n.ph_ctype is f)
((ph_ctype is s)
((p.ph_vlng is 0)
((0.479307 -0.9673))
((0.700477 -0.351397)))
((ph_ctype is f)
((0.73467 -0.6233))
((R:SylStructure.parent.syl_break is 0)
((p.ph_ctype is s)
((0.56282 0.266234))
((p.ph_ctype is r)
((0.446203 -0.302281))
((R:SylStructure.parent.sub_phrases < 2.7)
((ph_ctype is 0)
((0.572016 -0.0102436))
((0.497358 -0.274514)))
((0.545477 0.0482177)))))
((ph_vlng is s)
((0.805269 0.888495))
((ph_ctype is n)
((0.869854 0.653018))
((R:SylStructure.parent.sub_phrases < 2.2)
((0.735031 0.0612886))
((0.771859 0.346637))))))))
((R:SylStructure.parent.syl_codasize < 1.4)
((R:SylStructure.parent.R:Syllable.n.syl_onsetsize < 0.3)
((R:SylStructure.parent.position_type is initial)
((0.743458 0.0411808))
((1.13068 0.613305)))
((pos_in_syl < 1.2)
((R:SylStructure.parent.R:Syllable.p.syl_break is 1)
((1.11481 0.175467))
((0.937893 -0.276407)))
((0.74264 -0.550878))))
((pos_in_syl < 3.4)
((seg_onsetcoda is coda)
((ph_ctype is r)
((n.ph_ctype is s)
((0.714319 -0.240328))
((p.ph_ctype is 0)
((0.976987 0.330352))
((1.1781 -0.0816682))))
((ph_ctype is l)
((n.ph_ctype is 0)
((1.39137 0.383533))
((0.725585 -0.324515)))
((ph_vheight is 3)
((ph_vlng is d)
((0.802626 -0.62487))
((n.ph_ctype is r)
((0.661091 -0.513869))
((R:SylStructure.parent.position_type is initial)
((R:SylStructure.parent.parent.word_numsyls < 2.4)
((0.482285 0.207874))
((0.401601 -0.0204711)))
((0.733755 0.397372)))))
((n.ph_ctype is r)
((p.ph_ctype is 0)
((pos_in_syl < 1.2)
((0.666325 0.271734))
((nn.ph_vheight is 0)
((0.642401 -0.261466))
((0.783684 -0.00956571))))
((R:SylStructure.parent.R:Syllable.n.syl_onsetsize < 0.2)
((0.692225 -0.381895))
((0.741921 -0.0898767))))
((nn.ph_vfront is 2)
((ph_ctype is s)
((0.697527 -1.12626))
((n.ph_ctype is s)
((ph_vlng is 0)
((R:SylStructure.parent.sub_phrases < 2.4)
((0.498719 -0.906926))
((0.635342 -0.625651)))
((0.45886 -0.385089)))
((0.848596 -0.359702))))
((p.ph_vlng is a)
((p.ph_ctype is 0)
((0.947278 0.216904))
((0.637933 -0.394349)))
((p.ph_ctype is r)
((R:SylStructure.parent.syl_break is 0)
((0.529903 -0.860573))
((0.581378 -0.510488)))
((ph_vlng is 0)
((R:SylStructure.parent.R:Syllable.n.syl_onsetsize < 0.2)
((seg_onset_stop is 0)
((R:SylStructure.parent.syl_break is 0)
((p.ph_vlng is d)
((0.768363 0.0108428))
((ph_ctype is s)
((0.835756 -0.035054))
((ph_ctype is f)
((p.ph_vlng is s)
((0.602016 -0.179727))
((0.640126 -0.297341)))
((0.674628 -0.542602)))))
((ph_ctype is s)
((0.662261 -0.60496))
((0.662088 -0.432058))))
((R:SylStructure.parent.syl_out < 4.4)
((0.582448 -0.389079))
((ph_ctype is s)
((0.60413 -0.73564))
((0.567153 -0.605444)))))
((R:SylStructure.parent.R:Syllable.p.syl_break is 2)
((0.761115 -0.827377))
((ph_ctype is n)
((0.855183 -0.275338))
((R:SylStructure.parent.syl_break is 0)
((0.788288 -0.802801))
((R:SylStructure.parent.syl_codasize < 2.2)
((0.686134 -0.371234))
((0.840184 -0.772883)))))))
((pos_in_syl < 1.2)
((R:SylStructure.parent.syl_break is 0)
((n.ph_ctype is n)
((0.423592 -0.655006))
((R:SylStructure.parent.syl_out < 4.4)
((0.595269 -0.303751))
((0.478433 -0.456882))))
((0.688133 -0.133182)))
((seg_onset_stop is 0)
((1.27464 0.114442))
((0.406837 -0.167545))))))))))))
((ph_ctype is r)
((0.462874 -0.87695))
((R:SylStructure.parent.R:Syllable.n.syl_onsetsize < 0.2)
((0.645442 -0.640572))
((0.673717 -0.321322)))))
((0.61008 -0.925472))))))))
RMSE 0.8085 Correlation is 0.5899 Mean ( abs ) Error 0.6024 ( 0.5393 )
))
(provide 'kddurtreeZ)
| null | https://raw.githubusercontent.com/crosswire/xiphos/a9283769ef4d0d47f1d09a3ca4138610bb96a46c/win32/festival/lib/voices/english/ked_diphone/festvox/kddurtreeZ.scm | scheme |
;;
;
;
Copyright (c) 1996,1997 ;;
;
;;
Permission is hereby granted, free of charge, to use and distribute ;;
this software and its documentation without restriction, including ;;
without limitation the rights to use, copy, modify, merge, publish, ;;
distribute, sublicense, and/or sell copies of this work, and to ;;
permit persons to whom this work is furnished to do so, subject to ;;
the following conditions: ;;
1. The code must retain the above copyright notice, this list of ;;
conditions and the following disclaimer. ;;
2. Any modifications must be clearly marked as such. ;;
;
4. The authors' names are not used to endorse or promote products ;;
derived from this software without specific prior written ;;
permission. ;;
;;
THE UNIVERSITY OF EDINBURGH AND THE CONTRIBUTORS TO THIS WORK ;;
DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;;
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;;
SHALL THE UNIVERSITY OF EDINBURGH NOR THE CONTRIBUTORS BE LIABLE ;;
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;;
;
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;;
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;;
THIS SOFTWARE. ;;
;;
A tree to predict zcore durations build from f2b
doesn't use actual phonemes so it can have better generalizations
|
(set! kd_durs
'(
(uh 0.067 0.025)
(hh 0.061 0.028)
(ao 0.138 0.046)
(hv 0.053 0.020)
(v 0.051 0.019)
(ih 0.058 0.023)
(el 0.111 0.043)
(ey 0.132 0.042)
(em 0.080 0.033)
(jh 0.094 0.024)
(w 0.054 0.023)
(uw 0.107 0.044)
(ae 0.120 0.036)
(en 0.117 0.056)
(k 0.089 0.034)
(y 0.048 0.025)
(axr 0.147 0.035)
(l 0.056 0.026)
(ng 0.064 0.024)
(zh 0.071 0.030)
(z 0.079 0.034)
(brth 0.246 0.046)
(m 0.069 0.028)
(iy 0.097 0.041)
(n 0.059 0.025)
(ah 0.087 0.031)
(er 0.086 0.010)
(b 0.069 0.024)
(pau 0.200 0.104)
(aw 0.166 0.053)
(p 0.088 0.030)
(ch 0.115 0.025)
(ow 0.134 0.039)
(dh 0.031 0.016)
(nx 0.049 0.100)
(d 0.048 0.021)
(ax 0.046 0.024)
(h# 0.060 0.083)
(r 0.053 0.031)
( r 0.043 0.021 )
(eh 0.095 0.036)
(ay 0.137 0.047)
(oy 0.183 0.050)
(f 0.095 0.033)
(sh 0.108 0.031)
(s 0.102 0.037)
(g 0.064 0.021)
(dx 0.031 0.016)
(th 0.093 0.050)
(aa 0.094 0.037)
(t 0.070 0.020)
)
)
(set! kd_duration_cart_tree
'
((name is pau)
((emph_sil is +)
((0.0 -0.5))
((p.R:SylStructure.parent.parent.pbreak is BB)
((0.0 2.0))
((0.0 0.0))))
((R:SylStructure.parent.accented is 0)
((n.ph_ctype is 0)
((p.ph_vlng is 0)
((R:SylStructure.parent.syl_codasize < 1.5)
((p.ph_ctype is n)
((ph_ctype is f)
((0.559208 -0.783163))
((1.05215 -0.222704)))
((ph_ctype is s)
((R:SylStructure.parent.syl_break is 2)
((0.589948 0.764459))
((R:SylStructure.parent.asyl_in < 0.7)
((1.06385 0.567944))
((0.691943 0.0530272))))
((ph_vlng is l)
((pp.ph_vfront is 1)
((1.06991 0.766486))
((R:SylStructure.parent.syl_break is 1)
((0.69665 0.279248))
((0.670353 0.0567774))))
((p.ph_ctype is s)
((seg_onsetcoda is coda)
((0.828638 -0.038356))
((ph_ctype is f)
((0.7631 -0.545853))
((0.49329 -0.765994))))
((R:SylStructure.parent.parent.gpos is det)
((R:SylStructure.parent.last_accent < 0.3)
((R:SylStructure.parent.sub_phrases < 1)
((0.811686 0.160195))
((0.799015 0.713958)))
((0.731599 -0.215472)))
((ph_ctype is r)
((0.673487 0.092772))
((R:SylStructure.parent.asyl_in < 1)
((0.745273 0.00132813))
((0.75457 -0.334898)))))))))
((pos_in_syl < 0.5)
((R:SylStructure.parent.R:Syllable.p.syl_break is 2)
((R:SylStructure.parent.R:Syllable.n.syl_onsetsize < 0.2)
((0.902446 -0.041618))
((R:SylStructure.parent.sub_phrases < 2.3)
((0.900629 0.262952))
((1.18474 0.594794))))
((seg_onset_stop is 0)
((R:SylStructure.parent.position_type is mid)
((0.512323 -0.760444))
((R:SylStructure.parent.syl_out < 6.8)
((pp.ph_vlng is a)
((0.640575 -0.450449))
((ph_ctype is f)
((R:SylStructure.parent.sub_phrases < 1.3)
((0.862876 -0.296956))
((R:SylStructure.parent.syl_out < 2.4)
((0.803215 0.0422868))
((0.877856 -0.154465))))
((R:SylStructure.parent.syl_out < 3.6)
((R:SylStructure.parent.syl_out < 1.2)
((0.567081 -0.264199))
((0.598043 -0.541738)))
((0.676843 -0.166623)))))
((0.691678 -0.57173))))
((R:SylStructure.parent.parent.gpos is cc)
((1.15995 0.313289))
((pp.ph_vfront is 1)
((0.555993 0.0695819))
((R:SylStructure.parent.asyl_in < 1.2)
((R:SylStructure.parent.sub_phrases < 2.7)
((0.721635 -0.367088))
((0.71919 -0.194887)))
((0.547052 -0.0637491)))))))
((ph_ctype is s)
((R:SylStructure.parent.syl_break is 0)
((R:SylStructure.parent.R:Syllable.p.syl_break is 1)
((0.650007 -0.333421))
((0.846301 -0.165383)))
((0.527756 -0.516332)))
((R:SylStructure.parent.syl_break is 0)
((p.ph_ctype is s)
((0.504414 -0.779112))
((0.812498 -0.337611)))
((pos_in_syl < 1.4)
((0.513041 -0.745807))
((p.ph_ctype is s)
((0.350582 -1.04907))
((0.362 -0.914974))))))))
((R:SylStructure.parent.syl_break is 0)
((ph_ctype is n)
((R:SylStructure.parent.position_type is initial)
((pos_in_syl < 1.2)
((0.580485 0.172658))
((0.630973 -0.101423)))
((0.577937 -0.360092)))
((R:SylStructure.parent.syl_out < 2.9)
((R:SylStructure.parent.syl_out < 1.1)
((R:SylStructure.parent.position_type is initial)
((0.896092 0.764189))
((R:SylStructure.parent.sub_phrases < 3.6)
((ph_ctype is s)
((0.877362 0.555132))
((0.604511 0.369882)))
((0.799982 0.666966))))
((seg_onsetcoda is coda)
((p.ph_vlng is a)
((R:SylStructure.parent.last_accent < 0.4)
((0.800736 0.240634))
((0.720606 0.486176)))
((1.18173 0.573811)))
((0.607147 0.194468))))
((ph_ctype is r)
((0.88377 0.499383))
((R:SylStructure.parent.last_accent < 0.5)
((R:SylStructure.parent.position_type is initial)
((R:SylStructure.parent.parent.word_numsyls < 2.4)
((0.62798 0.0737318))
((0.787334 0.331014)))
((ph_ctype is s)
((0.808368 0.0929299))
((0.527948 -0.0443271))))
((seg_coda_fric is 0)
((p.ph_vlng is a)
((0.679745 0.517681))
((R:SylStructure.parent.sub_phrases < 1.1)
((0.759979 0.128316))
((0.775233 0.361383))))
((R:SylStructure.parent.last_accent < 1.3)
((0.696255 0.054136))
((0.632425 0.246742))))))))
((pos_in_syl < 0.3)
((R:SylStructure.parent.R:Syllable.p.syl_break is 2)
((0.847602 0.621547))
((ph_ctype is s)
((0.880645 0.501679))
((R:SylStructure.parent.sub_phrases < 3.3)
((R:SylStructure.parent.sub_phrases < 0.3)
((0.901014 -0.042049))
((0.657493 0.183226)))
((0.680126 0.284799)))))
((ph_ctype is s)
((p.ph_vlng is s)
((0.670033 -0.820934))
((0.863306 -0.348735)))
((ph_ctype is n)
((R:SylStructure.parent.asyl_in < 1.2)
((0.656966 -0.40092))
((0.530966 -0.639366)))
((seg_coda_fric is 0)
((1.04153 0.364857))
((pos_in_syl < 1.2)
((R:SylStructure.parent.syl_out < 3.4)
((0.81503 -0.00768613))
((0.602665 -0.197753)))
((0.601844 -0.394632)))))))))
((n.ph_ctype is f)
((pos_in_syl < 1.5)
((R:SylStructure.parent.R:Syllable.p.syl_break is 2)
((pos_in_syl < 0.1)
((1.63863 0.938841))
((R:SylStructure.parent.position_type is initial)
((0.897722 -0.0796637))
((nn.ph_vheight is 0)
((0.781081 0.480026))
((0.779711 0.127175)))))
((ph_ctype is r)
((p.ph_ctype is s)
((0.581329 -0.708767))
((0.564366 -0.236212)))
((ph_vlng is a)
((p.ph_ctype is r)
((0.70992 -0.273389))
((R:SylStructure.parent.parent.gpos is in)
((0.764696 0.0581338))
((nn.ph_vheight is 0)
((0.977737 0.721904))
((R:SylStructure.parent.sub_phrases < 2.2)
((pp.ph_vfront is 0)
((0.586708 0.0161206))
((0.619949 0.227372)))
((0.707285 0.445569))))))
((ph_ctype is n)
((R:SylStructure.parent.syl_break is 1)
((nn.ph_vfront is 2)
((0.430295 -0.120097))
((0.741371 0.219042)))
((0.587492 0.321245)))
((p.ph_ctype is n)
((0.871586 0.134075))
((p.ph_ctype is r)
((0.490751 -0.466418))
((R:SylStructure.parent.syl_codasize < 1.3)
((R:SylStructure.parent.sub_phrases < 2.2)
((p.ph_ctype is s)
((0.407452 -0.425925))
((0.644771 -0.542809)))
((0.688772 -0.201899)))
((ph_vheight is 1)
((nn.ph_vheight is 0)
((0.692018 0.209018))
((0.751345 -0.178136)))
((R:SylStructure.parent.R:Syllable.n.syl_onsetsize < 0.3)
((R:SylStructure.parent.asyl_in < 1.5)
((0.599633 -0.235593))
((0.60042 0.126118)))
((p.ph_vlng is a)
((0.7148 -0.174812))
((R:SylStructure.parent.parent.gpos is content)
((0.761296 -0.231509))
((0.813081 -0.536405)))))))))))))
((ph_ctype is n)
((0.898844 0.163343))
((p.ph_vlng is s)
((seg_coda_fric is 0)
((0.752921 -0.45528))
((0.890079 -0.0998025)))
((ph_ctype is f)
((0.729376 -0.930547))
((ph_ctype is s)
((R:SylStructure.parent.R:Syllable.p.syl_break is 0)
((0.745052 -0.634119))
((0.521502 -0.760176)))
((R:SylStructure.parent.syl_break is 1)
((0.766575 -0.121355))
((0.795616 -0.557509))))))))
((p.ph_vlng is 0)
((p.ph_ctype is r)
((ph_vlng is 0)
((0.733659 -0.402734))
((R:SylStructure.parent.sub_phrases < 1.5)
((ph_vlng is s)
((0.326176 -0.988478))
((n.ph_ctype is s)
((0.276471 -0.802536))
((0.438283 -0.900628))))
((nn.ph_vheight is 0)
((ph_vheight is 2)
((0.521 -0.768992))
((0.615436 -0.574918)))
((ph_vheight is 1)
((0.387376 -0.756359))
((pos_in_syl < 0.3)
((0.417235 -0.808937))
((0.384043 -0.93315)))))))
((ph_vlng is a)
((ph_ctype is 0)
((n.ph_ctype is s)
((p.ph_ctype is f)
((R:SylStructure.parent.R:Syllable.n.syl_onsetsize < 0.2)
((0.415908 -0.428493))
((pos_in_syl < 0.1)
((0.790441 0.0211071))
((0.452465 -0.254485))))
((p.ph_ctype is s)
((R:SylStructure.parent.R:Syllable.n.syl_onsetsize < 0.2)
((0.582447 -0.389966))
((0.757648 0.185781)))
((R:SylStructure.parent.sub_phrases < 1.4)
((0.628965 0.422551))
((0.713613 0.145576)))))
((seg_onset_stop is 0)
((R:SylStructure.parent.R:Syllable.p.syl_break is 0)
((pp.ph_vfront is 1)
((0.412363 -0.62319))
((R:SylStructure.parent.syl_out < 3.6)
((0.729259 -0.317324))
((0.441633 -0.591051))))
((R:SylStructure.parent.syl_break is 1)
((R:SylStructure.parent.sub_phrases < 2.7)
((0.457728 -0.405607))
((0.532411 -0.313148)))
((R:SylStructure.parent.last_accent < 0.3)
((1.14175 0.159416))
((0.616396 -0.254651)))))
((R:SylStructure.parent.position_type is initial)
((0.264181 -0.799896))
((0.439801 -0.551309)))))
((R:SylStructure.parent.position_type is final)
((0.552027 -0.707084))
((0.585661 -0.901874))))
((ph_ctype is s)
((pos_in_syl < 1.2)
((R:SylStructure.parent.R:Syllable.n.syl_onsetsize < 0.2)
((pp.ph_vfront is 1)
((0.607449 0.196466))
((0.599662 0.00382414)))
((0.64109 -0.12859)))
((pp.ph_vfront is 1)
((0.720484 -0.219339))
((0.688707 -0.516734))))
((ph_vlng is s)
((n.ph_ctype is s)
((R:SylStructure.parent.parent.gpos is content)
((R:SylStructure.parent.position_type is single)
((0.659206 0.159445))
((R:SylStructure.parent.parent.word_numsyls < 3.5)
((R:SylStructure.parent.sub_phrases < 2)
((0.447186 -0.419103))
((0.631822 -0.0928561)))
((0.451623 -0.576116))))
((ph_vheight is 3)
((0.578626 -0.64583))
((0.56636 -0.4665))))
((R:SylStructure.parent.parent.gpos is in)
((0.771516 -0.217292))
((R:SylStructure.parent.R:Syllable.p.syl_break is 2)
((0.688571 -0.304382))
((R:SylStructure.parent.parent.gpos is content)
((R:SylStructure.parent.R:Syllable.p.syl_break is 1)
((n.ph_ctype is n)
((0.556085 -0.572203))
((0.820173 -0.240338)))
((R:SylStructure.parent.parent.word_numsyls < 2.2)
((0.595398 -0.588171))
((0.524737 -0.95797))))
((R:SylStructure.parent.sub_phrases < 3.9)
((0.371492 -0.959427))
((0.440479 -0.845747)))))))
((R:SylStructure.parent.R:Syllable.p.syl_break is 0)
((p.ph_ctype is f)
((0.524088 -0.482247))
((nn.ph_vheight is 1)
((0.587666 -0.632362))
((ph_vlng is l)
((R:SylStructure.parent.position_type is final)
((0.513286 -0.713117))
((0.604613 -0.924308)))
((R:SylStructure.parent.syl_codasize < 2.2)
((0.577997 -0.891342))
((0.659804 -1.15252))))))
((pp.ph_vlng is s)
((ph_ctype is f)
((0.813383 -0.599624))
((0.984027 -0.0771909)))
((p.ph_ctype is f)
((R:SylStructure.parent.parent.gpos is in)
((R:SylStructure.parent.R:Syllable.p.syl_break is 1)
((0.313572 -1.03242))
((0.525854 -0.542799)))
((R:SylStructure.parent.syl_out < 2.8)
((0.613007 -0.423979))
((0.570258 -0.766379))))
((R:SylStructure.parent.syl_break is 1)
((R:SylStructure.parent.parent.gpos is to)
((0.364585 -0.792895))
((ph_vlng is l)
((0.69143 -0.276816))
((0.65673 -0.523721))))
((R:SylStructure.parent.syl_out < 3.6)
((R:SylStructure.parent.position_type is initial)
((0.682096 -0.488102))
((0.406364 -0.731758)))
((0.584694 -0.822229)))))))))))
((n.ph_ctype is r)
((R:SylStructure.parent.position_type is initial)
((p.ph_vlng is a)
((0.797058 1.02334))
((ph_ctype is s)
((1.0548 0.536277))
((0.817253 0.138201))))
((R:SylStructure.parent.sub_phrases < 1.1)
((R:SylStructure.parent.syl_out < 3.3)
((0.884574 -0.23471))
((0.772063 -0.525292)))
((nn.ph_vfront is 1)
((1.25254 0.417485))
((0.955557 -0.0781996)))))
((pp.ph_vfront is 0)
((ph_ctype is f)
((n.ph_ctype is s)
((R:SylStructure.parent.parent.gpos is content)
((R:SylStructure.parent.R:Syllable.p.syl_break is 0)
((0.583506 -0.56941))
((0.525949 -0.289362)))
((0.749316 -0.0921038)))
((p.ph_vlng is s)
((0.734234 0.139463))
((0.680119 -0.0708717))))
((ph_vlng is s)
((ph_vheight is 1)
((0.908712 -0.618971))
((0.55344 -0.840495)))
((R:SylStructure.parent.R:Syllable.n.syl_onsetsize < 1.2)
((pos_in_syl < 1.2)
((R:SylStructure.parent.R:Syllable.p.syl_break is 2)
((0.838715 0.00913392))
((R:SylStructure.parent.R:Syllable.p.syl_break is 1)
((ph_vheight is 2)
((0.555513 -0.512523))
((R:SylStructure.parent.position_type is initial)
((0.758711 0.121704))
((0.737555 -0.25637))))
((R:SylStructure.parent.syl_out < 3.1)
((n.ph_ctype is s)
((0.611756 -0.474522))
((1.05437 -0.247206)))
((R:SylStructure.parent.syl_codasize < 2.2)
((R:SylStructure.parent.position_type is final)
((0.567761 -0.597866))
((0.785599 -0.407765)))
((0.575598 -0.741256))))))
((ph_ctype is s)
((n.ph_ctype is s)
((0.661069 -1.08426))
((0.783184 -0.39789)))
((R:SylStructure.parent.R:Syllable.p.syl_break is 1)
((R:SylStructure.parent.sub_phrases < 2.6)
((0.511323 -0.666011))
((0.691878 -0.499492)))
((ph_ctype is r)
((0.482131 -0.253186))
((0.852955 -0.372832))))))
((0.854447 -0.0936489)))))
((R:SylStructure.parent.position_type is final)
((0.685939 -0.249982))
((R:SylStructure.parent.syl_out < 3.2)
((0.989843 0.18086))
((0.686805 -0.0402908)))))))))
((R:SylStructure.parent.syl_out < 2.4)
((R:SylStructure.parent.syl_out < 0.2)
((seg_onsetcoda is coda)
((ph_ctype is s)
((R:SylStructure.parent.syl_break is 4)
((pp.ph_vlng is 0)
((0.959737 1.63203))
((1.20714 0.994933)))
((n.ph_ctype is 0)
((R:SylStructure.parent.syl_break is 2)
((0.864809 0.214457))
((0.874278 0.730381)))
((pp.ph_vfront is 0)
((seg_coda_fric is 0)
((1.20844 -0.336221))
((1.01357 0.468302)))
((0.658106 -0.799121)))))
((n.ph_ctype is f)
((ph_ctype is f)
((1.26332 0.0300613))
((ph_vlng is d)
((1.02719 1.1649))
((ph_ctype is 0)
((R:SylStructure.parent.asyl_in < 1.2)
((1.14048 2.2668))
((ph_vheight is 1)
((1.15528 1.50375))
((1.42406 2.07927))))
((R:SylStructure.parent.sub_phrases < 1.1)
((0.955892 1.10243))
((R:SylStructure.parent.syl_break is 2)
((1.32682 1.8432))
((1.27582 1.59853)))))))
((n.ph_ctype is 0)
((ph_ctype is n)
((R:SylStructure.parent.syl_break is 2)
((1.45399 1.12927))
((1.05543 0.442376)))
((R:SylStructure.parent.syl_break is 4)
((R:SylStructure.parent.position_type is final)
((ph_ctype is f)
((1.46434 1.76508))
((0.978055 0.7486)))
((1.2395 2.30826)))
((ph_ctype is 0)
((0.935325 1.69917))
((nn.ph_vfront is 1)
((1.20456 1.31128))
((R:SylStructure.parent.R:Syllable.n.syl_onsetsize < 0.2)
((nn.ph_vheight is 0)
((1.16907 0.212421))
((0.952091 0.653094)))
((p.ph_ctype is 0)
((1.05502 1.25802))
((0.818731 0.777568))))))))
((ph_ctype is f)
((p.ph_ctype is 0)
((1.03918 0.163941))
((0.737545 -0.167063)))
((R:SylStructure.parent.position_type is final)
((n.ph_ctype is n)
((R:SylStructure.parent.last_accent < 0.5)
((R:SylStructure.parent.sub_phrases < 2.8)
((0.826207 -0.000859005))
((0.871119 0.273433)))
((R:SylStructure.parent.parent.word_numsyls < 2.4)
((1.17405 1.05694))
((0.858394 0.244916))))
((R:SylStructure.parent.syl_codasize < 2.2)
((p.ph_ctype is 0)
((1.14092 1.21187))
((R:SylStructure.parent.syl_break is 2)
((1.02653 0.59865))
((0.94248 1.1634))))
((seg_coda_fric is 0)
((1.07441 0.292935))
((1.15736 0.92574)))))
((ph_vlng is s)
((R:SylStructure.parent.syl_break is 2)
((1.34638 1.23484))
((0.951514 2.02008)))
((ph_ctype is 0)
((p.ph_ctype is r)
((0.806106 0.697089))
((R:SylStructure.parent.syl_break is 2)
((1.10891 0.992197))
((1.04657 1.51093))))
((1.18165 0.520952)))))))))
((p.ph_vlng is 0)
((pos_in_syl < 0.7)
((R:SylStructure.parent.position_type is final)
((ph_ctype is r)
((0.966357 0.185827))
((ph_ctype is s)
((0.647163 0.0332298))
((0.692972 -0.534917))))
((ph_ctype is s)
((0.881521 0.575107))
((p.ph_ctype is f)
((0.8223 -0.111275))
((R:SylStructure.parent.last_accent < 0.3)
((0.969188 0.09447))
((0.894438 0.381947))))))
((p.ph_ctype is f)
((0.479748 -0.490108))
((0.813125 -0.201268))))
((ph_ctype is s)
((0.908566 1.20397))
((R:SylStructure.parent.last_accent < 1.2)
((0.88078 0.636568))
((0.978087 1.07763))))))
((pos_in_syl < 1.3)
((R:SylStructure.parent.syl_break is 0)
((pos_in_syl < 0.1)
((R:SylStructure.parent.position_type is initial)
((p.ph_ctype is n)
((0.801651 -0.0163359))
((ph_ctype is s)
((n.ph_ctype is r)
((0.893307 1.07253))
((p.ph_vlng is 0)
((0.92651 0.525806))
((0.652444 0.952792))))
((p.ph_vlng is 0)
((seg_onsetcoda is coda)
((0.820151 0.469117))
((p.ph_ctype is f)
((0.747972 -0.0716448))
((ph_ctype is f)
((0.770882 0.457137))
((0.840905 0.102492)))))
((R:SylStructure.parent.syl_out < 1.1)
((0.667824 0.697337))
((0.737967 0.375114))))))
((ph_vheight is 1)
((0.624353 0.410671))
((R:SylStructure.parent.asyl_in < 0.8)
((0.647905 -0.331055))
((p.ph_ctype is s)
((0.629039 -0.240616))
((0.749277 -0.0191273))))))
((ph_vheight is 3)
((p.ph_ctype is s)
((0.626922 0.556537))
((0.789357 0.153892)))
((seg_onsetcoda is coda)
((n.ph_ctype is 0)
((R:SylStructure.parent.parent.word_numsyls < 3.4)
((0.744714 0.123242))
((0.742039 0.295753)))
((seg_coda_fric is 0)
((R:SylStructure.parent.parent.word_numsyls < 2.4)
((ph_vheight is 1)
((0.549715 -0.341018))
((0.573641 -0.00893114)))
((nn.ph_vfront is 2)
((0.67099 -0.744625))
((0.664438 -0.302803))))
((p.ph_vlng is 0)
((0.630028 0.113815))
((0.632794 -0.128733)))))
((ph_ctype is r)
((0.367169 -0.854509))
((0.94334 -0.216179))))))
((n.ph_ctype is f)
((ph_vlng is 0)
((1.3089 0.46195))
((R:SylStructure.parent.syl_codasize < 1.3)
((1.07673 0.657169))
((pp.ph_vlng is 0)
((0.972319 1.08222))
((1.00038 1.46257)))))
((p.ph_vlng is l)
((1.03617 0.785204))
((p.ph_vlng is a)
((R:SylStructure.parent.position_type is final)
((1.00681 0.321168))
((0.928115 0.950834)))
((ph_vlng is 0)
((pos_in_syl < 0.1)
((R:SylStructure.parent.position_type is final)
((0.863682 -0.167374))
((nn.ph_vheight is 0)
((p.ph_ctype is f)
((0.773591 -0.00374425))
((R:SylStructure.parent.syl_out < 1.1)
((0.951802 0.228448))
((1.02282 0.504252))))
((1.09721 0.736476))))
((R:SylStructure.parent.position_type is final)
((1.04302 0.0590974))
((0.589208 -0.431535))))
((n.ph_ctype is 0)
((1.27879 1.00642))
((ph_vlng is s)
((R:SylStructure.parent.asyl_in < 1.4)
((0.935787 0.481652))
((0.9887 0.749861)))
((R:SylStructure.parent.syl_out < 1.1)
((R:SylStructure.parent.position_type is final)
((0.921307 0.0696307))
((0.83675 0.552212)))
((0.810076 -0.0479225))))))))))
((ph_ctype is s)
((n.ph_ctype is s)
((0.706959 -1.0609))
((p.ph_ctype is n)
((0.850614 -0.59933))
((n.ph_ctype is r)
((0.665947 0.00698725))
((n.ph_ctype is 0)
((R:SylStructure.parent.position_type is initial)
((0.762889 -0.0649044))
((0.723956 -0.248899)))
((R:SylStructure.parent.sub_phrases < 1.4)
((0.632957 -0.601987))
((0.889114 -0.302401)))))))
((ph_ctype is f)
((R:SylStructure.parent.syl_codasize < 2.2)
((R:SylStructure.parent.R:Syllable.n.syl_onsetsize < 0.2)
((R:SylStructure.parent.syl_out < 1.1)
((0.865267 0.164636))
((0.581827 -0.0989051)))
((nn.ph_vfront is 2)
((0.684459 -0.316836))
((0.778854 -0.0961191))))
((R:SylStructure.parent.syl_out < 1.1)
((p.ph_ctype is s)
((0.837964 -0.429437))
((0.875304 -0.0652743)))
((0.611071 -0.635089))))
((p.ph_ctype is r)
((R:SylStructure.parent.syl_out < 1.1)
((0.762012 0.0139361))
((0.567983 -0.454845)))
((R:SylStructure.parent.syl_codasize < 2.2)
((ph_ctype is l)
((1.18845 0.809091))
((R:SylStructure.parent.position_type is initial)
((ph_ctype is n)
((0.773548 -0.277092))
((1.01586 0.281001)))
((p.ph_ctype is 0)
((1.06831 0.699145))
((0.924189 0.241873)))))
((R:SylStructure.parent.syl_break is 0)
((ph_ctype is n)
((0.592321 -0.470784))
((0.778688 -0.072112)))
((n.ph_ctype is s)
((1.08848 0.0733489))
((1.25674 0.608371))))))))))
((pos_in_syl < 0.7)
((p.ph_vlng is 0)
((R:SylStructure.parent.position_type is mid)
((ph_ctype is 0)
((ph_vheight is 2)
((0.456225 -0.293282))
((0.561529 -0.0816115)))
((0.6537 -0.504024)))
((ph_ctype is s)
((R:SylStructure.parent.R:Syllable.p.syl_break is 2)
((1.31586 0.98395))
((R:SylStructure.parent.position_type is single)
((0.816869 0.634789))
((R:SylStructure.parent.syl_out < 4.4)
((1.05578 0.479029))
((R:SylStructure.parent.asyl_in < 0.4)
((1.11813 0.143214))
((0.87178 0.406834))))))
((n.ph_ctype is n)
((R:SylStructure.parent.last_accent < 0.6)
((0.838154 -0.415599))
((0.924024 0.110288)))
((seg_onsetcoda is coda)
((nn.ph_vfront is 2)
((0.670096 0.0314187))
((n.ph_ctype is f)
((1.00363 0.693893))
((R:SylStructure.parent.syl_out < 6)
((0.772363 0.215675))
((0.920313 0.574068)))))
((R:SylStructure.parent.position_type is final)
((0.673837 -0.458142))
((R:SylStructure.parent.sub_phrases < 2.8)
((R:SylStructure.parent.R:Syllable.p.syl_break is 2)
((0.894817 0.304628))
((ph_ctype is n)
((0.787302 -0.23094))
((R:SylStructure.parent.asyl_in < 1.2)
((ph_ctype is f)
((R:SylStructure.parent.last_accent < 0.5)
((1.12278 0.326954))
((0.802236 -0.100616)))
((0.791255 -0.0919132)))
((0.95233 0.219053)))))
((R:SylStructure.parent.position_type is initial)
((ph_ctype is f)
((1.0616 0.216118))
((0.703216 -0.00834086)))
((ph_ctype is f)
((1.22277 0.761763))
((0.904811 0.332721))))))))))
((ph_vheight is 0)
((p.ph_vlng is s)
((0.873379 0.217178))
((n.ph_ctype is r)
((0.723915 1.29451))
((n.ph_ctype is 0)
((R:SylStructure.parent.R:Syllable.p.syl_break is 1)
((R:SylStructure.parent.sub_phrases < 4)
((seg_coda_fric is 0)
((p.ph_vlng is l)
((0.849154 0.945261))
((0.633261 0.687498)))
((0.728546 0.403076)))
((0.850962 1.00255)))
((0.957999 1.09113)))
((0.85771 0.209045)))))
((ph_vheight is 2)
((0.803401 -0.0544067))
((0.681353 0.256045)))))
((n.ph_ctype is f)
((ph_ctype is s)
((p.ph_vlng is 0)
((0.479307 -0.9673))
((0.700477 -0.351397)))
((ph_ctype is f)
((0.73467 -0.6233))
((R:SylStructure.parent.syl_break is 0)
((p.ph_ctype is s)
((0.56282 0.266234))
((p.ph_ctype is r)
((0.446203 -0.302281))
((R:SylStructure.parent.sub_phrases < 2.7)
((ph_ctype is 0)
((0.572016 -0.0102436))
((0.497358 -0.274514)))
((0.545477 0.0482177)))))
((ph_vlng is s)
((0.805269 0.888495))
((ph_ctype is n)
((0.869854 0.653018))
((R:SylStructure.parent.sub_phrases < 2.2)
((0.735031 0.0612886))
((0.771859 0.346637))))))))
((R:SylStructure.parent.syl_codasize < 1.4)
((R:SylStructure.parent.R:Syllable.n.syl_onsetsize < 0.3)
((R:SylStructure.parent.position_type is initial)
((0.743458 0.0411808))
((1.13068 0.613305)))
((pos_in_syl < 1.2)
((R:SylStructure.parent.R:Syllable.p.syl_break is 1)
((1.11481 0.175467))
((0.937893 -0.276407)))
((0.74264 -0.550878))))
((pos_in_syl < 3.4)
((seg_onsetcoda is coda)
((ph_ctype is r)
((n.ph_ctype is s)
((0.714319 -0.240328))
((p.ph_ctype is 0)
((0.976987 0.330352))
((1.1781 -0.0816682))))
((ph_ctype is l)
((n.ph_ctype is 0)
((1.39137 0.383533))
((0.725585 -0.324515)))
((ph_vheight is 3)
((ph_vlng is d)
((0.802626 -0.62487))
((n.ph_ctype is r)
((0.661091 -0.513869))
((R:SylStructure.parent.position_type is initial)
((R:SylStructure.parent.parent.word_numsyls < 2.4)
((0.482285 0.207874))
((0.401601 -0.0204711)))
((0.733755 0.397372)))))
((n.ph_ctype is r)
((p.ph_ctype is 0)
((pos_in_syl < 1.2)
((0.666325 0.271734))
((nn.ph_vheight is 0)
((0.642401 -0.261466))
((0.783684 -0.00956571))))
((R:SylStructure.parent.R:Syllable.n.syl_onsetsize < 0.2)
((0.692225 -0.381895))
((0.741921 -0.0898767))))
((nn.ph_vfront is 2)
((ph_ctype is s)
((0.697527 -1.12626))
((n.ph_ctype is s)
((ph_vlng is 0)
((R:SylStructure.parent.sub_phrases < 2.4)
((0.498719 -0.906926))
((0.635342 -0.625651)))
((0.45886 -0.385089)))
((0.848596 -0.359702))))
((p.ph_vlng is a)
((p.ph_ctype is 0)
((0.947278 0.216904))
((0.637933 -0.394349)))
((p.ph_ctype is r)
((R:SylStructure.parent.syl_break is 0)
((0.529903 -0.860573))
((0.581378 -0.510488)))
((ph_vlng is 0)
((R:SylStructure.parent.R:Syllable.n.syl_onsetsize < 0.2)
((seg_onset_stop is 0)
((R:SylStructure.parent.syl_break is 0)
((p.ph_vlng is d)
((0.768363 0.0108428))
((ph_ctype is s)
((0.835756 -0.035054))
((ph_ctype is f)
((p.ph_vlng is s)
((0.602016 -0.179727))
((0.640126 -0.297341)))
((0.674628 -0.542602)))))
((ph_ctype is s)
((0.662261 -0.60496))
((0.662088 -0.432058))))
((R:SylStructure.parent.syl_out < 4.4)
((0.582448 -0.389079))
((ph_ctype is s)
((0.60413 -0.73564))
((0.567153 -0.605444)))))
((R:SylStructure.parent.R:Syllable.p.syl_break is 2)
((0.761115 -0.827377))
((ph_ctype is n)
((0.855183 -0.275338))
((R:SylStructure.parent.syl_break is 0)
((0.788288 -0.802801))
((R:SylStructure.parent.syl_codasize < 2.2)
((0.686134 -0.371234))
((0.840184 -0.772883)))))))
((pos_in_syl < 1.2)
((R:SylStructure.parent.syl_break is 0)
((n.ph_ctype is n)
((0.423592 -0.655006))
((R:SylStructure.parent.syl_out < 4.4)
((0.595269 -0.303751))
((0.478433 -0.456882))))
((0.688133 -0.133182)))
((seg_onset_stop is 0)
((1.27464 0.114442))
((0.406837 -0.167545))))))))))))
((ph_ctype is r)
((0.462874 -0.87695))
((R:SylStructure.parent.R:Syllable.n.syl_onsetsize < 0.2)
((0.645442 -0.640572))
((0.673717 -0.321322)))))
((0.61008 -0.925472))))))))
RMSE 0.8085 Correlation is 0.5899 Mean ( abs ) Error 0.6024 ( 0.5393 )
))
(provide 'kddurtreeZ)
|
b5daf9401e634386e17ba09052edaacd0ac23219b9249418d077f8efce119f04 | neonsquare/mel-base | line-terminator-filter.lisp | -*- Mode : LISP ; Syntax : COMMON - LISP ; Package : CL - USER ; Base : 10 -*-
Copyright ( c ) 2004 , < > .
;;; 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.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; 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.
(in-package :mel.internal)
(defclass line-terminator-input-stream (encapsulating-input-stream)())
(defclass line-terminator-output-stream (encapsulating-output-stream)())
(defclass unix-line-terminator-input-stream (encapsulating-input-stream)())
(defclass mac-line-terminator-input-stream (encapsulating-input-stream)())
(defclass rfc-line-terminator-input-stream (encapsulating-input-stream)())
(defmethod mel.gray-stream:stream-read-char ((stream unix-line-terminator-input-stream))
(let* ((eis (encapsulated-input-stream stream))
(c (read-char eis nil :eof)))
(case c
(#\return (mel.gray-stream:stream-read-char stream))
(#\linefeed #\newline)
(otherwise c))))
(defmethod mel.gray-stream:stream-read-char ((stream mac-line-terminator-input-stream))
(let* ((eis (encapsulated-input-stream stream))
(c (read-char eis nil :eof)))
(case c
(#\linefeed (mel.gray-stream:stream-read-char stream))
(#\return #\newline)
(otherwise c))))
(defmethod mel.gray-stream:stream-read-char ((stream rfc-line-terminator-input-stream))
(let* ((eis (encapsulated-input-stream stream))
(c (read-char eis nil :eof)))
(case c
(#\return (mel.gray-stream:stream-read-char stream))
(#\linefeed #\newline)
(otherwise c))))
(defclass unix-line-terminator-output-stream (encapsulating-output-stream)())
(defclass mac-line-terminator-output-stream (encapsulating-output-stream)())
(defclass rfc-line-terminator-output-stream (encapsulating-output-stream)())
(defmethod mel.gray-stream:stream-write-char ((stream unix-line-terminator-output-stream) character)
(let ((eis (encapsulated-output-stream stream)))
(case character
(#\newline (write-char #\linefeed eis))
(#\return nil)
(otherwise (write-char character eis)))))
(defmethod mel.gray-stream:stream-write-char ((stream mac-line-terminator-output-stream) character)
(let ((eis (encapsulated-output-stream stream)))
(case character
(#\newline (write-char #\return eis))
on openmcl newline and linefeed are the same character
#-openmcl (#\linefeed nil)
(otherwise (write-char character eis)))))
(defmethod mel.gray-stream:stream-write-char ((stream rfc-line-terminator-output-stream) character)
(let ((eis (encapsulated-output-stream stream)))
(case character
(#\newline (write-char #\return eis) (write-char #\linefeed eis))
(#\return nil)
on openmcl newline and linefeed are the same character
#-openmcl(#\linefeed nil)
(otherwise (write-char character eis))))) | null | https://raw.githubusercontent.com/neonsquare/mel-base/7edc8fb94f30d29637bae0831c55825b0021e0f8/line-terminator-filter.lisp | lisp | Syntax : COMMON - LISP ; Package : CL - USER ; Base : 10 -*-
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.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
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
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
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 ) 2004 , < > .
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
(in-package :mel.internal)
(defclass line-terminator-input-stream (encapsulating-input-stream)())
(defclass line-terminator-output-stream (encapsulating-output-stream)())
(defclass unix-line-terminator-input-stream (encapsulating-input-stream)())
(defclass mac-line-terminator-input-stream (encapsulating-input-stream)())
(defclass rfc-line-terminator-input-stream (encapsulating-input-stream)())
(defmethod mel.gray-stream:stream-read-char ((stream unix-line-terminator-input-stream))
(let* ((eis (encapsulated-input-stream stream))
(c (read-char eis nil :eof)))
(case c
(#\return (mel.gray-stream:stream-read-char stream))
(#\linefeed #\newline)
(otherwise c))))
(defmethod mel.gray-stream:stream-read-char ((stream mac-line-terminator-input-stream))
(let* ((eis (encapsulated-input-stream stream))
(c (read-char eis nil :eof)))
(case c
(#\linefeed (mel.gray-stream:stream-read-char stream))
(#\return #\newline)
(otherwise c))))
(defmethod mel.gray-stream:stream-read-char ((stream rfc-line-terminator-input-stream))
(let* ((eis (encapsulated-input-stream stream))
(c (read-char eis nil :eof)))
(case c
(#\return (mel.gray-stream:stream-read-char stream))
(#\linefeed #\newline)
(otherwise c))))
(defclass unix-line-terminator-output-stream (encapsulating-output-stream)())
(defclass mac-line-terminator-output-stream (encapsulating-output-stream)())
(defclass rfc-line-terminator-output-stream (encapsulating-output-stream)())
(defmethod mel.gray-stream:stream-write-char ((stream unix-line-terminator-output-stream) character)
(let ((eis (encapsulated-output-stream stream)))
(case character
(#\newline (write-char #\linefeed eis))
(#\return nil)
(otherwise (write-char character eis)))))
(defmethod mel.gray-stream:stream-write-char ((stream mac-line-terminator-output-stream) character)
(let ((eis (encapsulated-output-stream stream)))
(case character
(#\newline (write-char #\return eis))
on openmcl newline and linefeed are the same character
#-openmcl (#\linefeed nil)
(otherwise (write-char character eis)))))
(defmethod mel.gray-stream:stream-write-char ((stream rfc-line-terminator-output-stream) character)
(let ((eis (encapsulated-output-stream stream)))
(case character
(#\newline (write-char #\return eis) (write-char #\linefeed eis))
(#\return nil)
on openmcl newline and linefeed are the same character
#-openmcl(#\linefeed nil)
(otherwise (write-char character eis))))) |
f6da5eb47166b43d8219b9e7047a5febe211ada7de718eb8f032752260e921b4 | runtimeverification/haskell-backend | StringLiteral.hs | module Test.Kore.Simplify.StringLiteral (
test_stringLiteralSimplification,
) where
import Kore.Internal.OrPattern (
OrPattern,
)
import Kore.Internal.OrPattern qualified as OrPattern
import Kore.Internal.Pattern (
Conditional (..),
)
import Kore.Internal.Predicate (
makeTruePredicate,
)
import Kore.Internal.TermLike
import Kore.Rewrite.RewritingVariable (
RewritingVariableName,
)
import Kore.Simplify.StringLiteral (
simplify,
)
import Prelude.Kore
import Test.Tasty
import Test.Tasty.HUnit.Ext
test_stringLiteralSimplification :: [TestTree]
test_stringLiteralSimplification =
[ testCase
"StringLiteral evaluates to StringLiteral"
( assertEqual
""
( OrPattern.fromPatterns
[ Conditional
{ term = mkStringLiteral "a"
, predicate = makeTruePredicate
, substitution = mempty
}
]
)
( evaluate
(StringLiteral "a")
)
)
]
evaluate :: StringLiteral -> OrPattern RewritingVariableName
evaluate = simplify
| null | https://raw.githubusercontent.com/runtimeverification/haskell-backend/b06757e252ee01fdd5ab8f07de2910711997d845/kore/test/Test/Kore/Simplify/StringLiteral.hs | haskell | module Test.Kore.Simplify.StringLiteral (
test_stringLiteralSimplification,
) where
import Kore.Internal.OrPattern (
OrPattern,
)
import Kore.Internal.OrPattern qualified as OrPattern
import Kore.Internal.Pattern (
Conditional (..),
)
import Kore.Internal.Predicate (
makeTruePredicate,
)
import Kore.Internal.TermLike
import Kore.Rewrite.RewritingVariable (
RewritingVariableName,
)
import Kore.Simplify.StringLiteral (
simplify,
)
import Prelude.Kore
import Test.Tasty
import Test.Tasty.HUnit.Ext
test_stringLiteralSimplification :: [TestTree]
test_stringLiteralSimplification =
[ testCase
"StringLiteral evaluates to StringLiteral"
( assertEqual
""
( OrPattern.fromPatterns
[ Conditional
{ term = mkStringLiteral "a"
, predicate = makeTruePredicate
, substitution = mempty
}
]
)
( evaluate
(StringLiteral "a")
)
)
]
evaluate :: StringLiteral -> OrPattern RewritingVariableName
evaluate = simplify
|
|
554422045a77ec34065839086b2cf440fb89e7dffce958fb5c730ca140aaee0a | chaoxu/fancy-walks | REVINPUT.hs | z(n:b)=unwords[x|x<-b,y<-[1..read n]];main=interact$reverse.z.words | null | https://raw.githubusercontent.com/chaoxu/fancy-walks/952fcc345883181144131f839aa61e36f488998d/spoj.pl/REVINPUT.hs | haskell | z(n:b)=unwords[x|x<-b,y<-[1..read n]];main=interact$reverse.z.words |
|
f546428cb8adc3fa7d5fdfe24d7319c41c7de71cedc7e511d8e1d935421b2e77 | eltex-ecss/chronica | chronica_manager.erl | %%%-------------------------------------------------------------------
-*- coding : utf-8 -*-
@author , ,
( C ) 2015 , Eltex , Novosibirsk , Russia
%%% @doc
%%%
%%% @end
%%%-------------------------------------------------------------------
-module(chronica_manager).
-behaviour(gen_server).
-include("chronica_int.hrl").
-include("chronica_config.hrl").
-include_lib("pt_scripts/include/pt_macro.hrl").
-include_lib("pt_lib/include/pt_lib.hrl").
-export(
[
active/1,
add_application/1,
add_rule/4,
add_rule/5,
add_tcp_connection/5,
clear_log/1,
free_resources/0,
get_config/0,
get_data_dir/0,
get_flow_list/0,
get_module_num/0,
get_root_dir/0,
init_sync/0,
load_config/1,
remove_tcp_connection/2,
rotate/0,
generate_iface_module/1,
update_rule_inwork/2,
update_rule_inwork/3
]).
-export(
[
init/1,
start_link/1,
code_change/3,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2
]).
-export_type(
[
rule/0
]
).
-define(wait_before_close_output_at_cfg_reload_timeout, 300000).
-define(wait_before_close_output_at_stop_timeout, 0).
-define(save_cache_timeout, 10000).
-define(check_log_backend_timeout, 60000).
-record(config_state,
{
loaded_config :: #chronica_config{},
rules :: [#rule{}] | null,
flows :: [term()] | null,
create_time :: {integer(), integer(), integer()},
registered_applications :: sets:set(module()),
cache = [],
config_hash = undefined,
cache_timer = false
}).
-record(initialize_sync, {}).
start_link(Params) ->
gen_server:start_link({local, ?MODULE}, ?MODULE, Params, [{spawn_opt, [{priority, low}]}]).
get_flow_list() ->
catch gen_server:call(?MODULE, get_flow_list).
get_root_dir() ->
gen_server:call(?MODULE, get_root_dir).
get_data_dir() ->
gen_server:call(?MODULE, get_data_dir).
add_tcp_connection(Mask, Priority, Type, Con, Continuation) ->
gen_server:cast(?MODULE, {add_tcp_connection, Mask, Priority, Type, Con, Continuation}).
remove_tcp_connection(Rule, Con) ->
gen_server:cast(?MODULE, {remove_tcp_connection, Rule, Con}).
init_sync() ->
gen_server:call(?MODULE, #initialize_sync{}, infinity).
init(Params) ->
try
?INT_DBG("Starting chronica_manager", []),
erlang:process_flag(trap_exit, true),
Now =
case proplists:get_value(now, Params, undefined) of
undefined ->
?INT_ERR("There is no \"now\" param in parameters to chronica_manager", []),
throw(no_now);
N -> N
end,
State =
#config_state{
loaded_config = #chronica_config{},
rules = null,
flows = null,
create_time = Now,
registered_applications = sets:from_list([chronica])
},
NewState =
case proplists:get_value(config, Params, undefined) of
undefined ->
?INT_ERR("No config in init params", []),
throw(no_config);
C ->
?INT_DBG("Init with config: ~p", [C]),
case start(State, C) of
{ok, NState} ->
?INT_DBG("Inited with State: ~p", [NState]),
gen_event:add_handler(error_logger, chronica_error_logger_handler, []),
gen_server:cast(?MODULE, cache_empty),
NState;
Err ->
?INT_ERR("Error when starting chronica_manager: ~p", [Err]),
throw(Err)
end
end,
после трех timeout - ов после старта системы .
timer:send_after(3 * ?check_log_backend_timeout, check_log_backend),
{ok, NewState}
catch
throw:E -> {stop, E};
_:E ->
?INT_ERR("manager failed to start: ~p~n~p", [E, erlang:get_stacktrace()]),
{stop, E}
end.
handle_cast({add_tcp_connection, Mask, Priority, Type, Con, Continuation},
State = #config_state{loaded_config =
Config = #chronica_config{rules = Rules, flows = Flows}}) ->
Name = erlang:list_to_atom(generate_name("tcp_")),
FlowName = erlang:list_to_atom(generate_name("tcp_flow_")),
NewRule = #chronica_rule{id = Name, mask = Mask,
priority = erlang:list_to_atom(Priority),
flow_ids = [FlowName], in_work = true},
Backends = [#chronica_backend{type = {tcp_con, Con}, format =
erlang:list_to_atom(Type)}],
NewFlow = #chronica_flow{flow_id = FlowName, backends = Backends},
NewConfig = Config#chronica_config{rules = [NewRule|Rules], flows = [NewFlow|Flows]},
case catch true_load_config(State, NewConfig) of
{ok, NewState} ->
Continuation({ok, {Name, FlowName}}),
{noreply, NewState};
{error, NewState, Reason} ->
Continuation({error, Reason}),
{noreply, NewState};
{stop, Reason} ->
Continuation({error, Reason}),
{stop, Reason, State};
Err ->
Continuation({error, Err}),
{stop, Err, State}
end;
handle_cast({remove_tcp_connection, {Name, FlowId}, _Con},
State = #config_state{loaded_config = Config =
#chronica_config{rules = Rules, flows = Flows}}) ->
case lists:keytake(FlowId, #chronica_flow.flow_id, Flows) of
false -> {noreply, State};
{_value, _, NewFlows} ->
NewRules = lists:keydelete(Name, #chronica_rule.id, Rules),
NewConfig = Config#chronica_config{rules = NewRules, flows = NewFlows},
case catch true_load_config(State, NewConfig) of
{ok, NewState} -> {noreply, NewState};
{error, NewState, _Reason} -> {noreply, NewState};
{stop, Reason} -> {stop, Reason, State};
Err -> {stop, Err, State}
end
end;
handle_cast(cache_empty, State) ->
set_configured_true(),
{noreply, State};
handle_cast(_Unknown, State) ->
?INT_ERR("Unhandled cast request ~p", [_Unknown]),
{noreply, State}.
handle_call(#initialize_sync{}, _Flows, State = #config_state{
registered_applications = RApps, rules = Rules,
loaded_config = #chronica_config{data_root = CacheDir, detail_info = Detail_info} = Config,
cache_timer = IsCacheTimerStarted}) ->
ConfigHash = config_hash(Config),
Cache = chronica_cache:load(CacheDir, ConfigHash),
AppListToRegister = application:loaded_applications(),
AddApplicationFun =
fun({AppL, _, _}, {RAppsL, CacheL}) ->
{_, {RAppsL2, CacheL2}} = add_application(AppL, RAppsL, Rules, CacheL, Detail_info),
{RAppsL2, CacheL2}
end,
{NewRApps, NewCache} = lists:foldl(AddApplicationFun, {RApps, Cache}, AppListToRegister),
NewIsCacheTimerStarted =
case NewCache == Cache of
true ->
IsCacheTimerStarted;
false ->
IsCacheTimerStarted orelse timer:send_after(?save_cache_timeout, save_cache),
true
end,
{reply, ok, State#config_state{registered_applications = NewRApps,
cache = NewCache, config_hash = ConfigHash, cache_timer = NewIsCacheTimerStarted}};
handle_call(get_root_dir, _Flows, State = #config_state{loaded_config =
#chronica_config{log_root = LogRoot}}) ->
{reply, LogRoot, State};
handle_call(get_data_dir, _Flows, State = #config_state{loaded_config =
#chronica_config{data_root = DataRoot}}) ->
{reply, DataRoot, State};
handle_call({load_config, Config}, _From, State) ->
?INT_DBG("load_config received", []),
case catch true_load_config(State, Config) of
{ok, NewState} -> {reply, ok, NewState};
{error, NewState, Reason} -> {reply, {error, Reason}, NewState};
{stop, Reason} -> {stop, Reason, State};
Err -> {stop, Err, State}
end;
handle_call({get_flows, Tags, Priority} = Msg, _From, State = #config_state{rules = Rules}) ->
?INT_DBG("get flows: Msg = ~p, Rules = ~w", [Msg, Rules]),
case Rules of
null -> {reply, [], State};
_ ->
UTags = lists:usort(Tags),
Res = chronica_iface:get_appropriate_flows(UTags, Priority, Rules),
{reply, Res, State}
end;
handle_call(get_flow_list, _From, State = #config_state{flows = Flows}) ->
{reply, {ok, [erlang:element(1, F) || F <- Flows]}, State};
handle_call({clear_log, _RuleId}, _From, State = #config_state{loaded_config =
#chronica_config{active = false}}) ->
{reply, {error, deactivated}, State};
handle_call({clear_log, RuleId} = Msg, _From, State = #config_state{flows = Flows}) ->
?INT_DBG("clear log: Msg = ~p, Flows = ~p", [Msg, Flows]),
Res = case RuleId of
'' when is_list(Flows) ->
OutputList = lists:usort(lists:foldl(fun ({_, L}, Acc) -> L ++ Acc end, [], Flows)),
case lists:foldl(
fun (#flow_handle{id = Handle}, Acc) ->
case chronica_gen_backend:clear(Handle) of
ok -> Acc;
Err -> [{failed, {Handle, Err}} | Acc]
end
end, [], OutputList) of
[] ->
ok;
Err2 -> Err2
end;
_ when is_list(Flows) ->
case lists:keyfind(RuleId, 1, Flows) of
false -> {error, not_found};
{_, Outputs} ->
case lists:foldl(
fun (#flow_handle{id = Handle}, Acc) ->
case chronica_gen_backend:clear(Handle) of
ok -> Acc;
Err -> [{failed, {Handle, Err}} | Acc]
end
end, [], lists:usort(Outputs)) of
[] -> ok;
Err2 -> Err2
end
end;
_ ->
ok
end,
{reply, Res, State};
handle_call(get_config, _From, State = #config_state{loaded_config = Config}) ->
{reply, Config, State};
handle_call({update_rule_inwork, IdList, InWork, TickFun}, _From,
State = #config_state{loaded_config = Config =
#chronica_config{rules = Rules}})
when is_list(IdList) ->
Fun = fun(OneId, Acc) ->
case lists:keyfind(OneId, #chronica_rule.id, Acc) of
false ->
Acc;
#chronica_rule{in_work = InWork} ->
Acc;
Rule ->
lists:keyreplace(OneId, #chronica_rule.id, Acc, Rule#chronica_rule{in_work = InWork})
end
end,
NewRules = lists:foldl(Fun, Rules, IdList),
case catch true_load_config(State, Config#chronica_config{rules = NewRules}, TickFun) of
{ok, NewState} -> {reply, ok, NewState};
{error, NewState, Reason} -> {reply, {error, Reason}, NewState};
{stop, Reason} -> {stop, Reason, {error, Reason}, State};
Err -> {stop, Err, State}
end;
handle_call({update_rule_inwork, Id, InWork, TickFun}, _From,
State = #config_state{loaded_config = Config = #chronica_config{rules = Rules}}) ->
case lists:keyfind(Id, #chronica_rule.id, Rules) of
false -> {reply, {error, not_found}, State};
#chronica_rule{in_work = InWork} -> {reply, {error, already_set}, State};
Rule ->
NewRules = lists:keyreplace(Id, #chronica_rule.id, Rules, Rule#chronica_rule{in_work = InWork}),
case catch true_load_config(State, Config#chronica_config{rules = NewRules}, TickFun) of
{ok, NewState} -> {reply, ok, NewState};
{error, NewState, Reason} -> {reply, {error, Reason}, NewState};
{stop, Reason} -> {stop, Reason, {error, Reason}, State};
Err -> {stop, Err, State}
end
end;
handle_call({add_rule, NameRule, Mask, Priority, Flow, TickFun}, _From,
State = #config_state{loaded_config = Config = #chronica_config{rules = Rules}}) ->
NewRule = #chronica_rule{id = NameRule, mask = Mask,
priority = Priority, flow_ids = [Flow], in_work = true},
case catch true_load_config(State, Config#chronica_config{rules = [NewRule|Rules]}, TickFun) of
{ok, NewState} -> {reply, ok, NewState};
{error, NewState, Reason} -> {reply, {error, Reason}, NewState};
{stop, Reason} -> {stop, Reason, {error, Reason}, State};
Err -> {stop, Err, State}
end;
handle_call(get_module_num, _From, State = #config_state{registered_applications = RegApps}) ->
{reply, sets:size(RegApps), State};
handle_call(get_flow_names, _From, State = #config_state{loaded_config = #chronica_config{flows = Flows}}) ->
Res = lists:foldl(
fun (#chronica_flow{flow_id = Name}, Acc) ->
[Name | Acc]
end, [], Flows),
{reply, Res, State};
handle_call(get_output_list, _From, State = #config_state{rules = Rules}) ->
try
Res =
case Rules of
null -> [];
_ -> get_all_flows(Rules)
end,
{reply, {ok, Res}, State}
catch
C:E ->
?INT_EXCEPT("Exception: ~p:~p", [C, E]),
{reply, {error, E}, State}
end;
handle_call(free_resources, _From, State = #config_state{rules = Rules}) ->
?INT_DBG("free_resources received", []),
try
case Rules of
null -> ok;
_ ->
FlowHandles = get_all_flows(Rules),
close_outputs(FlowHandles, ?wait_before_close_output_at_stop_timeout)
end
catch
C:E -> ?INT_EXCEPT("Exception: ~p:~p", [C, E])
end,
{reply, ok, State};
handle_call(rotate, _From, State = #config_state{rules = Rules}) ->
?INT_DBG("rotate received", []),
Res =
try
case Rules of
null -> throw(not_loaded);
_ -> ok
end,
Flows = get_all_flows(Rules),
lists:foreach(
fun (Handle) ->
case chronica_gen_backend:rotate(Handle) of
ok -> ok;
Err -> throw(Err)
end
end,
Flows)
catch
throw:not_loaded -> ok;
throw:E -> E
end,
{reply, Res, State};
handle_call({add_application, App}, _From, State =
#config_state{registered_applications = RApps, rules = Rules,
loaded_config = #chronica_config{detail_info = Detail_info},
cache = Cache, cache_timer = IsCacheTimerStarted}) ->
?INT_DBG("add_application received ~p", [App]),
{Res, {NewRApps, NewCache}} = add_application(App, RApps, Rules, Cache, Detail_info),
NewIsCacheTimerStarted =
case NewCache == Cache of
true -> IsCacheTimerStarted;
false -> IsCacheTimerStarted orelse timer:send_after(?save_cache_timeout, save_cache), true
end,
{reply, Res, State#config_state{registered_applications = NewRApps,
cache = NewCache, cache_timer = NewIsCacheTimerStarted}};
handle_call({generate_iface_module, Module}, _From, #config_state{rules = Rules} = State) ->
?INT_DBG("generate_iface_module received ~p", [Module]),
Code = chronica_iface:generate_iface_module(Module, Rules),
catch load_app_iface_modules([{Module, Code}]),
{reply, ok, State};
handle_call(print_state, _From, State) ->
io:format("manager's state:~n~p~n", [State]),
{reply, ok, State};
handle_call({active, NewActive}, _From, State = #config_state{loaded_config = Config}) ->
case catch true_load_config(State, Config#chronica_config{active = NewActive}) of
{ok, NewState} -> {reply, ok, NewState};
{error, NewState, Reason} -> {reply, {error, Reason}, NewState};
{stop, Reason} -> {stop, Reason, {error, Reason}, State};
Err -> {stop, Err, {error, Err}, State}
end;
handle_call(_Msg, _From, State) ->
?INT_ERR("Unhandled call request ~p", [_Msg]),
{reply, {error, bad_msg}, State}.
handle_info({'EXIT', Pid, normal}, State) ->
?INT_DBG("EXIT received from ~p with reason normal", [Pid]),
{noreply, State};
handle_info(check_log_backend, #config_state{flows = RawFlows, loaded_config = #chronica_config{}} = State) ->
Flows = lists:flatten([LFlows || {_, LFlows} <- RawFlows]),
CheckFun =
fun(#flow_handle{id = Handle, output_module = OutputModule, open_params = OpenParam, writer_options = WriterOptions} = LFlow) ->
case chronica_gen_backend:check(Handle) of
true ->
ok;
_ ->
?INT_WARN("Chronica backend ~p was closed. Try to reopening...", [Handle]),
case chronica_gen_backend:open(OutputModule, OpenParam, WriterOptions) of
{ok, Handle} ->
?INT_WARN("Chronica backend ~p was reopend.", [Handle]),
ok;
{error, Error} ->
?INT_WARN("Error open output: ~p Reason: ~p", [LFlow, Error]),
ok
end
end
end,
lists:foreach(CheckFun, Flows),
timer:send_after(?check_log_backend_timeout, check_log_backend),
{noreply, State};
handle_info(save_cache, State = #config_state{config_hash = undefined}) ->
{noreply, State};
handle_info(save_cache, State = #config_state{loaded_config =
#chronica_config{data_root = CacheDir}, cache = Cache, config_hash = ConfigHash}) ->
?INT_DBG("Save cache timer expired", []),
chronica_cache:save(CacheDir, ConfigHash, Cache),
{noreply, State#config_state{cache_timer = false}};
handle_info(_Info, State) ->
?INT_ERR("Unhandled info ~p", [_Info]),
{noreply, State}.
terminate(_Reason, State) ->
?INT_DBG("terminate: Reason = ~p", [_Reason]),
handle_call(free_resources, self(), State).
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
start(State, Config) ->
try
chronica_config:validate(Config)
catch
throw:Error -> ?INT_ERR("Config is not valid: ~p", [Error]), throw({bad_config, Error})
end,
case load_config(State, Config) of
{ok, NewNewState} -> {ok, NewNewState};
Err -> Err
end.
unload_config(S = #config_state{loaded_config = #chronica_config{}, flows = Flows}) when Flows =/= null ->
case catch destroy_flows(Flows, ?wait_before_close_output_at_cfg_reload_timeout) of
ok -> S#config_state{loaded_config = #chronica_config{}, flows = null};
E ->
?INT_ERR("Error while processing destoy flows: ~p", [E]),
S
end;
unload_config(S) ->
S.
true_load_config(S, NewConfig) ->
true_load_config(S, NewConfig, undefined).
TickFun is used to notify parent about events ,
for example : it is needed to support cocon progress bars
true_load_config(S = #config_state{loaded_config = OldConfig}, OldConfig, _) -> {ok, S};
true_load_config(S = #config_state{loaded_config = OldConfig}, NewConfig, TickFun) ->
Res =
try
chronica_config_validation:validate(NewConfig),
NewState = unload_config(S),
case load_config(NewState, NewConfig, TickFun) of
{ok, _} = RR -> RR;
LoadError ->
?INT_ERR("Load config error: ~p, falling back to old config...", [LoadError]),
case load_config(NewState, OldConfig) of
{ok, NewNewState} ->
{error, NewNewState, LoadError};
LoadError2 ->
?INT_ERR("Load old config error: ~p, gonna crash...", [LoadError2]),
{stop, {LoadError, LoadError2}}
end
end
catch
throw:Err -> {error, S, Err}
end,
Res.
load_config(State, NewConfig) -> load_config(State, NewConfig, undefined).
load_config(State = #config_state{loaded_config = LoadedConfig = #chronica_config{active = LoadedActive, formats = OldFormatsConfig}, registered_applications = RegApps, cache_timer = IsCacheTimerStarted},
NewConfig = #chronica_config{data_root = CacheDir},
TickFun) ->
?INT_DBG("load rules: NewConfig = ~p", [NewConfig]),
try
case LoadedConfig of
NewConfig ->
throw({ok, State});
_ -> ok
end,
#chronica_config{
rules = NewRulesConfig,
flows = NewFlowsConfig,
formats = NewFormatsConfig,
colors = NewColorsConfig,
data_root = DataRoot,
log_root = LogRoot,
max_file_size = NewMaxFileSize,
max_file_num = NewMaxFileNum,
rotate_at_start = NewRotateStartup,
active = Active,
detail_info = Detail_info,
tty_enabled = TTYEnabled,
backend_modules = BackendModules
} = NewConfig,
case Active of
true -> switch_on();
false ->
switch_off(),
ConfigHashForOff = config_hash(NewConfig),
CacheForOff = chronica_cache:load(CacheDir, ConfigHashForOff),
throw({ok, State#config_state{
loaded_config = NewConfig,
rules = [],
flows = [],
cache = CacheForOff,
config_hash = ConfigHashForOff
}})
end,
case NewFormatsConfig of
OldFormatsConfig when LoadedActive =:= true -> ok;
_ ->
FunctionList = parse_formats(NewFormatsConfig, [], NewColorsConfig),
case chronica_format_creator:reload_formats(FunctionList, chronica_format) of
ok -> ok;
Error ->
?INT_ERR("cant load formats cause format_creator error: ~p", [Error]),
throw({load_error, Error})
end
end,
% Do not add them to head!
BackendModules2 = BackendModules ++ [{tty, chronica_tty_backend},
{udp, chronica_udp_backend},
{tcp_con, chronica_tcp_con_backend},
{file, chronica_disk_log_backend}],
WriterOptions = [{log_root, LogRoot}, {data_root, DataRoot}, {max_file_size, NewMaxFileSize}, {max_file_num, NewMaxFileNum}, {tty_enabled, TTYEnabled}],
NewFlows = create_flows(NewFlowsConfig, WriterOptions, BackendModules2),
case NewRotateStartup of
true ->
lists:foreach(
fun (WHandle) ->
catch chronica_gen_backend:rotate(WHandle)
end,
get_writers(NewFlows));
false -> ok
end,
ClearFlowHandleFun =
fun({LName, LFlows}) ->
{LName, [LFlow#flow_handle{open_params = undefined, output_module = undefined, writer_options = undefined} || #flow_handle{} = LFlow <- LFlows]}
end,
ResFlows = lists:map(ClearFlowHandleFun, NewFlows),
NewRules = chronica_config:parse_rules(NewRulesConfig, ResFlows),
ConfigHash = config_hash(NewConfig),
Cache = chronica_cache:load(CacheDir, ConfigHash),
?INT_DBG("ADD ALL APPLICATIONS", []),
{NewRegApps, NewCache} = add_all_applications(RegApps, NewRules, Cache, Detail_info, TickFun),
erlang:garbage_collect(),
NewIsCacheTimerStarted =
case NewCache == Cache of
true ->
IsCacheTimerStarted;
false ->
IsCacheTimerStarted orelse timer:send_after(?save_cache_timeout, save_cache),
true
end,
{ok, State#config_state{
loaded_config = NewConfig,
rules = NewRules,
flows = NewFlows,
registered_applications = NewRegApps,
cache = NewCache,
cache_timer = NewIsCacheTimerStarted,
config_hash = ConfigHash
}}
catch
throw:{load_error, Reason} -> {error, Reason};
throw:{bad_config, _} = Err2 -> Err2;
throw:{ok, S} -> {ok, S};
throw:E -> {error, E};
_:E -> {error, {E, erlang:get_stacktrace()}}
end.
get_all_flows(Rules) ->
FlowHandlesDublicated = [ Handle || {_Format, Handle} <-
lists:foldl(
fun (#rule{flows = Flows}, Acc) -> Flows ++ Acc end, [], Rules)
],
lists:usort(FlowHandlesDublicated).
get_config() ->
gen_server:call(?MODULE, get_config).
update_rule_inwork(Id, InWork) ->
update_rule_inwork(Id, InWork, undefined).
update_rule_inwork(Id, InWork, TickFun) ->
gen_server:call(?MODULE, {update_rule_inwork, Id, InWork, TickFun}, infinity).
get_module_num() ->
gen_server:call(?MODULE, get_module_num, infinity).
load_config(Config) ->
gen_server:call(?MODULE, {load_config, Config}, infinity).
clear_log(RuleId) ->
gen_server:call(?MODULE, {clear_log, RuleId}).
active(Param) ->
gen_server:call(?MODULE, {active, Param}, infinity).
rotate() ->
gen_server:call(?MODULE, rotate).
free_resources() ->
gen_server:call(?MODULE, free_resources).
add_application(App) ->
gen_server:call(?MODULE, {add_application, App}, infinity).
-spec add_rule(NameRule :: atom(), Mask :: nonempty_string(),
Priority :: chronica_priority(), Flow :: atom()) -> ok | {error, _Reason}.
add_rule(NameRule, Mask, Priority, Flow) when is_atom(NameRule) ->
add_rule(NameRule, Mask, Priority, Flow, fun() -> ok end).
-spec add_rule(NameRule :: atom(), Mask :: nonempty_string(),
Priority :: chronica_priority(), Flow :: atom(), Fun :: fun(() -> any())) -> ok | {error, _Reason}.
add_rule(NameRule, Mask, Priority, Flow, Fun) when is_atom(NameRule) ->
gen_server:call(?MODULE, {add_rule, NameRule, Mask, Priority, Flow, Fun}, infinity).
generate_iface_module(Module) ->
gen_server:call(?MODULE, {generate_iface_module, Module}).
close_outputs([Handle | Tail], Timeout) ->
?INT_DBG("Close of output ~p cause termination", [Handle]),
chronica_gen_backend:close(Handle, Timeout),
close_outputs(Tail, Timeout);
close_outputs([], _Timeout) ->
ok.
switch_on() ->
?INT_DBG("switch_on", []),
Res = pt_recompilable:recompile_orig_module(chronica_core,
fun (AST, _Options) ->
AST
end
),
Res.
switch_off() ->
?INT_DBG("switch_off", []),
Res = pt_recompilable:recompile_orig_module(chronica_core,
fun (AST, _Options) ->
pt_lib:replace(AST, ast_pattern("log_fast(...$P...) -> ...$_... .", Line), ast("log_fast(...$P...) -> ok. ", Line))
end),
Res.
create_flows(ConfigFlows, WriterOptions, Backends) ->
FlowsList = chronica_config:parse_flows(ConfigFlows, WriterOptions, Backends),
{_, Doubling} = lists:foldl(
fun ({Name, _}, {S , D}) ->
case lists:member(Name, S) of
true -> {S, [Name | D]};
false -> {[Name | S], D}
end
end,
{[], []},
FlowsList),
case Doubling of
[] -> ok;
_ ->
?INT_ERR("following flows are doubling: ~p", [Doubling]),
erlang:throw({create_flows, doubling_flows})
end,
FlowsList.
destroy_flows(Flows, Timeout) ->
Writers = get_writers(Flows),
close_outputs(Writers, Timeout).
get_writers(null) -> [];
get_writers(Flows) ->
lists:foldl(
fun ({_Name, Outputs}, Acc) ->
[Handle || #flow_handle{id = Handle} <- Outputs] ++ Acc
end,
[],
Flows).
parse_formats([], Res, _) -> Res;
parse_formats([#chronica_format{format_id = Name, format = UserFormat} | Tail], Res, ColorsConfig) when is_atom(Name) and is_list(UserFormat) ->
parse_formats(Tail, [chronica_format_creator:create_format_function(Name, UserFormat, ColorsConfig) | Res], ColorsConfig);
parse_formats(BadFormated, _, _) ->
?INT_ERR("invalid formats param ~p", [BadFormated]),
erlang:throw({parse_formats, bad_format}).
add_application(App, RApps, Rules, Cache, Detail_info) ->
add_application(App, RApps, Rules, Cache, Detail_info, undefined).
add_application(App, RApps, Rules, Cache, Detail_info, TickFun) ->
try
add_application_(App, RApps, Rules, Cache, Detail_info, TickFun)
catch
throw:{Err, NRA} ->
?INT_ERR("reg ~p failed \\ ~p~n", [App, NRA]),
{Err, NRA}
end.
add_application_(App, RApps, Rules, Cache, Detail_info, TickFun) ->
?INT_DBG("-> rq add_application ~p \\ ~p", [App, RApps]),
case sets:is_element(App, RApps) of
true ->
{ok, {RApps, Cache}};
false ->
?INT_DBG("-> Rq Reg ~100000p \\ ~100000p \\ is_list(Cache): ~10000000000000p~n", [App, RApps, is_list(Cache)]),
case add_application_in_cache(App, RApps, Rules, Cache, Detail_info, TickFun) of
Applicatin successfully added in cache .
{ok, {NewRApps, NewCache}} ->
DepApps0 = case application:get_key(App, applications) of
{ok, L0} -> L0;
_ -> []
end,
DepApps = case application:get_key(App, included_applications) of
{ok, [_ | _] = L1} -> L1 ++ DepApps0;
_ -> DepApps0
end,
AddAppsRecurciveFun =
fun (A, {Added, CacheAcc}) ->
case add_application_(A, Added, Rules, CacheAcc, Detail_info, TickFun) of
{ok, {NewAdded, NewCacheAcc}} -> {NewAdded, NewCacheAcc};
{Error, {NewAdded, NewCacheAcc}} -> throw({Error, {NewAdded, NewCacheAcc}})
end
end,
{ResultRApps, ResultCache} = lists:foldl(AddAppsRecurciveFun, {NewRApps, NewCache}, DepApps),
{ok, {ResultRApps, ResultCache}};
% Error during add application in cache.
{Error, ErrorArgs} ->
{Error, ErrorArgs}
end
end.
%%--------------------------------------------------------------------
%%
%%--------------------------------------------------------------------
add_application_in_cache(App, RApps, Rules, Cache, Detail_info, TickFun) ->
?INT_DBG("Registering application ~100000p \\ ~1000000p \\ is_list(NewCache): ~10000000p", [App, RApps, is_list(Cache)]),
try
AppHash = app_hash(App),
is_function(TickFun) andalso TickFun(),
case proplists:get_value(App, Cache, undefined) of
% do not recompile, use cache
{AppHash, AppModulesCode} ->
?INT_DBG("~p chronica interface was loaded from cache", [App]),
load_app_iface_modules(AppModulesCode),
ResApps = sets:add_element(App, RApps),
?INT_DBG("Registered (from cache) \\ ~p~n", [ResApps]),
{ok, {ResApps, Cache}};
% no cache or old cache
_Cached ->
AppModulesCode = case Detail_info of
true ->
io:format("Compiling the cache: [~p] ", [App]),
T1 = erlang:system_time(millisecond),
Apps = chronica_iface:generate_app_iface_modules(App, Rules),
T2 = erlang:system_time(millisecond),
case Apps of
[] -> io:format("skipped~n");
_ -> io:format("~pms done.~n", [T2 - T1])
end,
Apps;
false ->
chronica_iface:generate_app_iface_modules(App, Rules)
end,
load_app_iface_modules(AppModulesCode),
ResApps = sets:add_element(App, RApps),
?INT_DBG("Registered \\ ~p~n", [ResApps]),
{ok, {ResApps, [{App, {AppHash, AppModulesCode}} | proplists:delete(App, Cache)]}}
end
catch
_:Error ->
?INT_ERR("Add application ~p failed cause: ~p~n~p", [App, Error, erlang:get_stacktrace()]),
{Error, {RApps, Cache}}
end.
%%++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
set_configured_true() ->
pt_recompilable:recompile_cur_module(
chronica_status,
fun (AST, _Options) ->
pt_lib:replace(AST,
ast_pattern("configured() -> ...$_... .", Line),
ast("configured() -> true.", Line))
end).
depended_from_chronica(lager) ->
true;
depended_from_chronica(chronica) ->
true;
depended_from_chronica(App) ->
CheckApplicationFun =
fun({ok, DependedApplications}) ->
lists:member(chronica, DependedApplications) orelse
lists:member(lager, DependedApplications);
(_) ->
false
end,
CheckApplicationFun(application:get_key(App, applications)) orelse
CheckApplicationFun(application:get_key(App, included_applications)).
app_hash(App) ->
Tags =
case depended_from_chronica(App) of
false ->
[];
true ->
case application:get_key(App, modules) of
{ok, L2} ->
lists:foldl(
fun (ModuleName, Acc) ->
case (catch ModuleName:get_log_tags()) of
Tags2 when is_list(Tags2) -> [{ModuleName, Tags2}|Acc];
_ -> Acc
end
end, [], L2);
Error -> erlang:error({no_modules_info, App, Error})
end
end,
erlang:md5(erlang:term_to_binary(Tags)).
config_hash(#chronica_config{active = Active, rules = Rules, flows = Flows}) ->
erlang:md5(erlang:term_to_binary({Active, Rules, Flows})).
add_all_applications(RegApps, NewRules, Cache, Detail_info, TickFun) ->
sets:fold(
fun (App, {RAAcc, CacheAcc}) ->
case add_application(App, RAAcc, NewRules, CacheAcc, Detail_info, TickFun) of
{ok, NRA} -> NRA;
{AAErr, _NRA} -> throw(AAErr)
end
end,
{sets:new(), Cache},
RegApps).
load_code_module(undefined) -> ok;
load_code_module({Module, Binary}) ->
case code:soft_purge(Module) of
true ->
case code:load_binary(Module, atom_to_list(Module) ++ ".erl", Binary) of
{module, Module} ->
?INT_DBG("~p: module reloaded", [Module]),
ok;
{error, Cause} -> {error, {cant_load, Module, Cause}}
end;
false ->
{error, soft_purge_failed}
end.
load_app_iface_modules(AppModulesCode) ->
lists:foreach(
fun ({Module, Code}) ->
case load_code_module(Code) of
ok ->
ok;
{error, Error} ->
?INT_ERR("Cant load module ~p chronica iface code binary, reason: ~p", [Module, Error]),
erlang:error({cant_load_module, Module, Error})
end
end, AppModulesCode).
-define(d2012_11_16_1_25_41, 63520248341000000).
generate_name(Prefix) ->
Now = {_, _, M} = os:timestamp(),
DT = calendar:now_to_universal_time(Now),
N = calendar:datetime_to_gregorian_seconds(DT) * 1000000 + M - ?d2012_11_16_1_25_41,
lists:flatten(io_lib:format("~s~.36.0b", [Prefix, N])).
| null | https://raw.githubusercontent.com/eltex-ecss/chronica/bdc9f37797cd74215a02aabedf03b09005e9b21f/src/chronica_manager.erl | erlang | -------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
Do not add them to head!
Error during add application in cache.
--------------------------------------------------------------------
--------------------------------------------------------------------
do not recompile, use cache
no cache or old cache
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ | -*- coding : utf-8 -*-
@author , ,
( C ) 2015 , Eltex , Novosibirsk , Russia
-module(chronica_manager).
-behaviour(gen_server).
-include("chronica_int.hrl").
-include("chronica_config.hrl").
-include_lib("pt_scripts/include/pt_macro.hrl").
-include_lib("pt_lib/include/pt_lib.hrl").
-export(
[
active/1,
add_application/1,
add_rule/4,
add_rule/5,
add_tcp_connection/5,
clear_log/1,
free_resources/0,
get_config/0,
get_data_dir/0,
get_flow_list/0,
get_module_num/0,
get_root_dir/0,
init_sync/0,
load_config/1,
remove_tcp_connection/2,
rotate/0,
generate_iface_module/1,
update_rule_inwork/2,
update_rule_inwork/3
]).
-export(
[
init/1,
start_link/1,
code_change/3,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2
]).
-export_type(
[
rule/0
]
).
-define(wait_before_close_output_at_cfg_reload_timeout, 300000).
-define(wait_before_close_output_at_stop_timeout, 0).
-define(save_cache_timeout, 10000).
-define(check_log_backend_timeout, 60000).
-record(config_state,
{
loaded_config :: #chronica_config{},
rules :: [#rule{}] | null,
flows :: [term()] | null,
create_time :: {integer(), integer(), integer()},
registered_applications :: sets:set(module()),
cache = [],
config_hash = undefined,
cache_timer = false
}).
-record(initialize_sync, {}).
start_link(Params) ->
gen_server:start_link({local, ?MODULE}, ?MODULE, Params, [{spawn_opt, [{priority, low}]}]).
get_flow_list() ->
catch gen_server:call(?MODULE, get_flow_list).
get_root_dir() ->
gen_server:call(?MODULE, get_root_dir).
get_data_dir() ->
gen_server:call(?MODULE, get_data_dir).
add_tcp_connection(Mask, Priority, Type, Con, Continuation) ->
gen_server:cast(?MODULE, {add_tcp_connection, Mask, Priority, Type, Con, Continuation}).
remove_tcp_connection(Rule, Con) ->
gen_server:cast(?MODULE, {remove_tcp_connection, Rule, Con}).
init_sync() ->
gen_server:call(?MODULE, #initialize_sync{}, infinity).
init(Params) ->
try
?INT_DBG("Starting chronica_manager", []),
erlang:process_flag(trap_exit, true),
Now =
case proplists:get_value(now, Params, undefined) of
undefined ->
?INT_ERR("There is no \"now\" param in parameters to chronica_manager", []),
throw(no_now);
N -> N
end,
State =
#config_state{
loaded_config = #chronica_config{},
rules = null,
flows = null,
create_time = Now,
registered_applications = sets:from_list([chronica])
},
NewState =
case proplists:get_value(config, Params, undefined) of
undefined ->
?INT_ERR("No config in init params", []),
throw(no_config);
C ->
?INT_DBG("Init with config: ~p", [C]),
case start(State, C) of
{ok, NState} ->
?INT_DBG("Inited with State: ~p", [NState]),
gen_event:add_handler(error_logger, chronica_error_logger_handler, []),
gen_server:cast(?MODULE, cache_empty),
NState;
Err ->
?INT_ERR("Error when starting chronica_manager: ~p", [Err]),
throw(Err)
end
end,
после трех timeout - ов после старта системы .
timer:send_after(3 * ?check_log_backend_timeout, check_log_backend),
{ok, NewState}
catch
throw:E -> {stop, E};
_:E ->
?INT_ERR("manager failed to start: ~p~n~p", [E, erlang:get_stacktrace()]),
{stop, E}
end.
handle_cast({add_tcp_connection, Mask, Priority, Type, Con, Continuation},
State = #config_state{loaded_config =
Config = #chronica_config{rules = Rules, flows = Flows}}) ->
Name = erlang:list_to_atom(generate_name("tcp_")),
FlowName = erlang:list_to_atom(generate_name("tcp_flow_")),
NewRule = #chronica_rule{id = Name, mask = Mask,
priority = erlang:list_to_atom(Priority),
flow_ids = [FlowName], in_work = true},
Backends = [#chronica_backend{type = {tcp_con, Con}, format =
erlang:list_to_atom(Type)}],
NewFlow = #chronica_flow{flow_id = FlowName, backends = Backends},
NewConfig = Config#chronica_config{rules = [NewRule|Rules], flows = [NewFlow|Flows]},
case catch true_load_config(State, NewConfig) of
{ok, NewState} ->
Continuation({ok, {Name, FlowName}}),
{noreply, NewState};
{error, NewState, Reason} ->
Continuation({error, Reason}),
{noreply, NewState};
{stop, Reason} ->
Continuation({error, Reason}),
{stop, Reason, State};
Err ->
Continuation({error, Err}),
{stop, Err, State}
end;
handle_cast({remove_tcp_connection, {Name, FlowId}, _Con},
State = #config_state{loaded_config = Config =
#chronica_config{rules = Rules, flows = Flows}}) ->
case lists:keytake(FlowId, #chronica_flow.flow_id, Flows) of
false -> {noreply, State};
{_value, _, NewFlows} ->
NewRules = lists:keydelete(Name, #chronica_rule.id, Rules),
NewConfig = Config#chronica_config{rules = NewRules, flows = NewFlows},
case catch true_load_config(State, NewConfig) of
{ok, NewState} -> {noreply, NewState};
{error, NewState, _Reason} -> {noreply, NewState};
{stop, Reason} -> {stop, Reason, State};
Err -> {stop, Err, State}
end
end;
handle_cast(cache_empty, State) ->
set_configured_true(),
{noreply, State};
handle_cast(_Unknown, State) ->
?INT_ERR("Unhandled cast request ~p", [_Unknown]),
{noreply, State}.
handle_call(#initialize_sync{}, _Flows, State = #config_state{
registered_applications = RApps, rules = Rules,
loaded_config = #chronica_config{data_root = CacheDir, detail_info = Detail_info} = Config,
cache_timer = IsCacheTimerStarted}) ->
ConfigHash = config_hash(Config),
Cache = chronica_cache:load(CacheDir, ConfigHash),
AppListToRegister = application:loaded_applications(),
AddApplicationFun =
fun({AppL, _, _}, {RAppsL, CacheL}) ->
{_, {RAppsL2, CacheL2}} = add_application(AppL, RAppsL, Rules, CacheL, Detail_info),
{RAppsL2, CacheL2}
end,
{NewRApps, NewCache} = lists:foldl(AddApplicationFun, {RApps, Cache}, AppListToRegister),
NewIsCacheTimerStarted =
case NewCache == Cache of
true ->
IsCacheTimerStarted;
false ->
IsCacheTimerStarted orelse timer:send_after(?save_cache_timeout, save_cache),
true
end,
{reply, ok, State#config_state{registered_applications = NewRApps,
cache = NewCache, config_hash = ConfigHash, cache_timer = NewIsCacheTimerStarted}};
handle_call(get_root_dir, _Flows, State = #config_state{loaded_config =
#chronica_config{log_root = LogRoot}}) ->
{reply, LogRoot, State};
handle_call(get_data_dir, _Flows, State = #config_state{loaded_config =
#chronica_config{data_root = DataRoot}}) ->
{reply, DataRoot, State};
handle_call({load_config, Config}, _From, State) ->
?INT_DBG("load_config received", []),
case catch true_load_config(State, Config) of
{ok, NewState} -> {reply, ok, NewState};
{error, NewState, Reason} -> {reply, {error, Reason}, NewState};
{stop, Reason} -> {stop, Reason, State};
Err -> {stop, Err, State}
end;
handle_call({get_flows, Tags, Priority} = Msg, _From, State = #config_state{rules = Rules}) ->
?INT_DBG("get flows: Msg = ~p, Rules = ~w", [Msg, Rules]),
case Rules of
null -> {reply, [], State};
_ ->
UTags = lists:usort(Tags),
Res = chronica_iface:get_appropriate_flows(UTags, Priority, Rules),
{reply, Res, State}
end;
handle_call(get_flow_list, _From, State = #config_state{flows = Flows}) ->
{reply, {ok, [erlang:element(1, F) || F <- Flows]}, State};
handle_call({clear_log, _RuleId}, _From, State = #config_state{loaded_config =
#chronica_config{active = false}}) ->
{reply, {error, deactivated}, State};
handle_call({clear_log, RuleId} = Msg, _From, State = #config_state{flows = Flows}) ->
?INT_DBG("clear log: Msg = ~p, Flows = ~p", [Msg, Flows]),
Res = case RuleId of
'' when is_list(Flows) ->
OutputList = lists:usort(lists:foldl(fun ({_, L}, Acc) -> L ++ Acc end, [], Flows)),
case lists:foldl(
fun (#flow_handle{id = Handle}, Acc) ->
case chronica_gen_backend:clear(Handle) of
ok -> Acc;
Err -> [{failed, {Handle, Err}} | Acc]
end
end, [], OutputList) of
[] ->
ok;
Err2 -> Err2
end;
_ when is_list(Flows) ->
case lists:keyfind(RuleId, 1, Flows) of
false -> {error, not_found};
{_, Outputs} ->
case lists:foldl(
fun (#flow_handle{id = Handle}, Acc) ->
case chronica_gen_backend:clear(Handle) of
ok -> Acc;
Err -> [{failed, {Handle, Err}} | Acc]
end
end, [], lists:usort(Outputs)) of
[] -> ok;
Err2 -> Err2
end
end;
_ ->
ok
end,
{reply, Res, State};
handle_call(get_config, _From, State = #config_state{loaded_config = Config}) ->
{reply, Config, State};
handle_call({update_rule_inwork, IdList, InWork, TickFun}, _From,
State = #config_state{loaded_config = Config =
#chronica_config{rules = Rules}})
when is_list(IdList) ->
Fun = fun(OneId, Acc) ->
case lists:keyfind(OneId, #chronica_rule.id, Acc) of
false ->
Acc;
#chronica_rule{in_work = InWork} ->
Acc;
Rule ->
lists:keyreplace(OneId, #chronica_rule.id, Acc, Rule#chronica_rule{in_work = InWork})
end
end,
NewRules = lists:foldl(Fun, Rules, IdList),
case catch true_load_config(State, Config#chronica_config{rules = NewRules}, TickFun) of
{ok, NewState} -> {reply, ok, NewState};
{error, NewState, Reason} -> {reply, {error, Reason}, NewState};
{stop, Reason} -> {stop, Reason, {error, Reason}, State};
Err -> {stop, Err, State}
end;
handle_call({update_rule_inwork, Id, InWork, TickFun}, _From,
State = #config_state{loaded_config = Config = #chronica_config{rules = Rules}}) ->
case lists:keyfind(Id, #chronica_rule.id, Rules) of
false -> {reply, {error, not_found}, State};
#chronica_rule{in_work = InWork} -> {reply, {error, already_set}, State};
Rule ->
NewRules = lists:keyreplace(Id, #chronica_rule.id, Rules, Rule#chronica_rule{in_work = InWork}),
case catch true_load_config(State, Config#chronica_config{rules = NewRules}, TickFun) of
{ok, NewState} -> {reply, ok, NewState};
{error, NewState, Reason} -> {reply, {error, Reason}, NewState};
{stop, Reason} -> {stop, Reason, {error, Reason}, State};
Err -> {stop, Err, State}
end
end;
handle_call({add_rule, NameRule, Mask, Priority, Flow, TickFun}, _From,
State = #config_state{loaded_config = Config = #chronica_config{rules = Rules}}) ->
NewRule = #chronica_rule{id = NameRule, mask = Mask,
priority = Priority, flow_ids = [Flow], in_work = true},
case catch true_load_config(State, Config#chronica_config{rules = [NewRule|Rules]}, TickFun) of
{ok, NewState} -> {reply, ok, NewState};
{error, NewState, Reason} -> {reply, {error, Reason}, NewState};
{stop, Reason} -> {stop, Reason, {error, Reason}, State};
Err -> {stop, Err, State}
end;
handle_call(get_module_num, _From, State = #config_state{registered_applications = RegApps}) ->
{reply, sets:size(RegApps), State};
handle_call(get_flow_names, _From, State = #config_state{loaded_config = #chronica_config{flows = Flows}}) ->
Res = lists:foldl(
fun (#chronica_flow{flow_id = Name}, Acc) ->
[Name | Acc]
end, [], Flows),
{reply, Res, State};
handle_call(get_output_list, _From, State = #config_state{rules = Rules}) ->
try
Res =
case Rules of
null -> [];
_ -> get_all_flows(Rules)
end,
{reply, {ok, Res}, State}
catch
C:E ->
?INT_EXCEPT("Exception: ~p:~p", [C, E]),
{reply, {error, E}, State}
end;
handle_call(free_resources, _From, State = #config_state{rules = Rules}) ->
?INT_DBG("free_resources received", []),
try
case Rules of
null -> ok;
_ ->
FlowHandles = get_all_flows(Rules),
close_outputs(FlowHandles, ?wait_before_close_output_at_stop_timeout)
end
catch
C:E -> ?INT_EXCEPT("Exception: ~p:~p", [C, E])
end,
{reply, ok, State};
handle_call(rotate, _From, State = #config_state{rules = Rules}) ->
?INT_DBG("rotate received", []),
Res =
try
case Rules of
null -> throw(not_loaded);
_ -> ok
end,
Flows = get_all_flows(Rules),
lists:foreach(
fun (Handle) ->
case chronica_gen_backend:rotate(Handle) of
ok -> ok;
Err -> throw(Err)
end
end,
Flows)
catch
throw:not_loaded -> ok;
throw:E -> E
end,
{reply, Res, State};
handle_call({add_application, App}, _From, State =
#config_state{registered_applications = RApps, rules = Rules,
loaded_config = #chronica_config{detail_info = Detail_info},
cache = Cache, cache_timer = IsCacheTimerStarted}) ->
?INT_DBG("add_application received ~p", [App]),
{Res, {NewRApps, NewCache}} = add_application(App, RApps, Rules, Cache, Detail_info),
NewIsCacheTimerStarted =
case NewCache == Cache of
true -> IsCacheTimerStarted;
false -> IsCacheTimerStarted orelse timer:send_after(?save_cache_timeout, save_cache), true
end,
{reply, Res, State#config_state{registered_applications = NewRApps,
cache = NewCache, cache_timer = NewIsCacheTimerStarted}};
handle_call({generate_iface_module, Module}, _From, #config_state{rules = Rules} = State) ->
?INT_DBG("generate_iface_module received ~p", [Module]),
Code = chronica_iface:generate_iface_module(Module, Rules),
catch load_app_iface_modules([{Module, Code}]),
{reply, ok, State};
handle_call(print_state, _From, State) ->
io:format("manager's state:~n~p~n", [State]),
{reply, ok, State};
handle_call({active, NewActive}, _From, State = #config_state{loaded_config = Config}) ->
case catch true_load_config(State, Config#chronica_config{active = NewActive}) of
{ok, NewState} -> {reply, ok, NewState};
{error, NewState, Reason} -> {reply, {error, Reason}, NewState};
{stop, Reason} -> {stop, Reason, {error, Reason}, State};
Err -> {stop, Err, {error, Err}, State}
end;
handle_call(_Msg, _From, State) ->
?INT_ERR("Unhandled call request ~p", [_Msg]),
{reply, {error, bad_msg}, State}.
handle_info({'EXIT', Pid, normal}, State) ->
?INT_DBG("EXIT received from ~p with reason normal", [Pid]),
{noreply, State};
handle_info(check_log_backend, #config_state{flows = RawFlows, loaded_config = #chronica_config{}} = State) ->
Flows = lists:flatten([LFlows || {_, LFlows} <- RawFlows]),
CheckFun =
fun(#flow_handle{id = Handle, output_module = OutputModule, open_params = OpenParam, writer_options = WriterOptions} = LFlow) ->
case chronica_gen_backend:check(Handle) of
true ->
ok;
_ ->
?INT_WARN("Chronica backend ~p was closed. Try to reopening...", [Handle]),
case chronica_gen_backend:open(OutputModule, OpenParam, WriterOptions) of
{ok, Handle} ->
?INT_WARN("Chronica backend ~p was reopend.", [Handle]),
ok;
{error, Error} ->
?INT_WARN("Error open output: ~p Reason: ~p", [LFlow, Error]),
ok
end
end
end,
lists:foreach(CheckFun, Flows),
timer:send_after(?check_log_backend_timeout, check_log_backend),
{noreply, State};
handle_info(save_cache, State = #config_state{config_hash = undefined}) ->
{noreply, State};
handle_info(save_cache, State = #config_state{loaded_config =
#chronica_config{data_root = CacheDir}, cache = Cache, config_hash = ConfigHash}) ->
?INT_DBG("Save cache timer expired", []),
chronica_cache:save(CacheDir, ConfigHash, Cache),
{noreply, State#config_state{cache_timer = false}};
handle_info(_Info, State) ->
?INT_ERR("Unhandled info ~p", [_Info]),
{noreply, State}.
terminate(_Reason, State) ->
?INT_DBG("terminate: Reason = ~p", [_Reason]),
handle_call(free_resources, self(), State).
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
start(State, Config) ->
try
chronica_config:validate(Config)
catch
throw:Error -> ?INT_ERR("Config is not valid: ~p", [Error]), throw({bad_config, Error})
end,
case load_config(State, Config) of
{ok, NewNewState} -> {ok, NewNewState};
Err -> Err
end.
unload_config(S = #config_state{loaded_config = #chronica_config{}, flows = Flows}) when Flows =/= null ->
case catch destroy_flows(Flows, ?wait_before_close_output_at_cfg_reload_timeout) of
ok -> S#config_state{loaded_config = #chronica_config{}, flows = null};
E ->
?INT_ERR("Error while processing destoy flows: ~p", [E]),
S
end;
unload_config(S) ->
S.
true_load_config(S, NewConfig) ->
true_load_config(S, NewConfig, undefined).
TickFun is used to notify parent about events ,
for example : it is needed to support cocon progress bars
true_load_config(S = #config_state{loaded_config = OldConfig}, OldConfig, _) -> {ok, S};
true_load_config(S = #config_state{loaded_config = OldConfig}, NewConfig, TickFun) ->
Res =
try
chronica_config_validation:validate(NewConfig),
NewState = unload_config(S),
case load_config(NewState, NewConfig, TickFun) of
{ok, _} = RR -> RR;
LoadError ->
?INT_ERR("Load config error: ~p, falling back to old config...", [LoadError]),
case load_config(NewState, OldConfig) of
{ok, NewNewState} ->
{error, NewNewState, LoadError};
LoadError2 ->
?INT_ERR("Load old config error: ~p, gonna crash...", [LoadError2]),
{stop, {LoadError, LoadError2}}
end
end
catch
throw:Err -> {error, S, Err}
end,
Res.
load_config(State, NewConfig) -> load_config(State, NewConfig, undefined).
load_config(State = #config_state{loaded_config = LoadedConfig = #chronica_config{active = LoadedActive, formats = OldFormatsConfig}, registered_applications = RegApps, cache_timer = IsCacheTimerStarted},
NewConfig = #chronica_config{data_root = CacheDir},
TickFun) ->
?INT_DBG("load rules: NewConfig = ~p", [NewConfig]),
try
case LoadedConfig of
NewConfig ->
throw({ok, State});
_ -> ok
end,
#chronica_config{
rules = NewRulesConfig,
flows = NewFlowsConfig,
formats = NewFormatsConfig,
colors = NewColorsConfig,
data_root = DataRoot,
log_root = LogRoot,
max_file_size = NewMaxFileSize,
max_file_num = NewMaxFileNum,
rotate_at_start = NewRotateStartup,
active = Active,
detail_info = Detail_info,
tty_enabled = TTYEnabled,
backend_modules = BackendModules
} = NewConfig,
case Active of
true -> switch_on();
false ->
switch_off(),
ConfigHashForOff = config_hash(NewConfig),
CacheForOff = chronica_cache:load(CacheDir, ConfigHashForOff),
throw({ok, State#config_state{
loaded_config = NewConfig,
rules = [],
flows = [],
cache = CacheForOff,
config_hash = ConfigHashForOff
}})
end,
case NewFormatsConfig of
OldFormatsConfig when LoadedActive =:= true -> ok;
_ ->
FunctionList = parse_formats(NewFormatsConfig, [], NewColorsConfig),
case chronica_format_creator:reload_formats(FunctionList, chronica_format) of
ok -> ok;
Error ->
?INT_ERR("cant load formats cause format_creator error: ~p", [Error]),
throw({load_error, Error})
end
end,
BackendModules2 = BackendModules ++ [{tty, chronica_tty_backend},
{udp, chronica_udp_backend},
{tcp_con, chronica_tcp_con_backend},
{file, chronica_disk_log_backend}],
WriterOptions = [{log_root, LogRoot}, {data_root, DataRoot}, {max_file_size, NewMaxFileSize}, {max_file_num, NewMaxFileNum}, {tty_enabled, TTYEnabled}],
NewFlows = create_flows(NewFlowsConfig, WriterOptions, BackendModules2),
case NewRotateStartup of
true ->
lists:foreach(
fun (WHandle) ->
catch chronica_gen_backend:rotate(WHandle)
end,
get_writers(NewFlows));
false -> ok
end,
ClearFlowHandleFun =
fun({LName, LFlows}) ->
{LName, [LFlow#flow_handle{open_params = undefined, output_module = undefined, writer_options = undefined} || #flow_handle{} = LFlow <- LFlows]}
end,
ResFlows = lists:map(ClearFlowHandleFun, NewFlows),
NewRules = chronica_config:parse_rules(NewRulesConfig, ResFlows),
ConfigHash = config_hash(NewConfig),
Cache = chronica_cache:load(CacheDir, ConfigHash),
?INT_DBG("ADD ALL APPLICATIONS", []),
{NewRegApps, NewCache} = add_all_applications(RegApps, NewRules, Cache, Detail_info, TickFun),
erlang:garbage_collect(),
NewIsCacheTimerStarted =
case NewCache == Cache of
true ->
IsCacheTimerStarted;
false ->
IsCacheTimerStarted orelse timer:send_after(?save_cache_timeout, save_cache),
true
end,
{ok, State#config_state{
loaded_config = NewConfig,
rules = NewRules,
flows = NewFlows,
registered_applications = NewRegApps,
cache = NewCache,
cache_timer = NewIsCacheTimerStarted,
config_hash = ConfigHash
}}
catch
throw:{load_error, Reason} -> {error, Reason};
throw:{bad_config, _} = Err2 -> Err2;
throw:{ok, S} -> {ok, S};
throw:E -> {error, E};
_:E -> {error, {E, erlang:get_stacktrace()}}
end.
get_all_flows(Rules) ->
FlowHandlesDublicated = [ Handle || {_Format, Handle} <-
lists:foldl(
fun (#rule{flows = Flows}, Acc) -> Flows ++ Acc end, [], Rules)
],
lists:usort(FlowHandlesDublicated).
get_config() ->
gen_server:call(?MODULE, get_config).
update_rule_inwork(Id, InWork) ->
update_rule_inwork(Id, InWork, undefined).
update_rule_inwork(Id, InWork, TickFun) ->
gen_server:call(?MODULE, {update_rule_inwork, Id, InWork, TickFun}, infinity).
get_module_num() ->
gen_server:call(?MODULE, get_module_num, infinity).
load_config(Config) ->
gen_server:call(?MODULE, {load_config, Config}, infinity).
clear_log(RuleId) ->
gen_server:call(?MODULE, {clear_log, RuleId}).
active(Param) ->
gen_server:call(?MODULE, {active, Param}, infinity).
rotate() ->
gen_server:call(?MODULE, rotate).
free_resources() ->
gen_server:call(?MODULE, free_resources).
add_application(App) ->
gen_server:call(?MODULE, {add_application, App}, infinity).
-spec add_rule(NameRule :: atom(), Mask :: nonempty_string(),
Priority :: chronica_priority(), Flow :: atom()) -> ok | {error, _Reason}.
add_rule(NameRule, Mask, Priority, Flow) when is_atom(NameRule) ->
add_rule(NameRule, Mask, Priority, Flow, fun() -> ok end).
-spec add_rule(NameRule :: atom(), Mask :: nonempty_string(),
Priority :: chronica_priority(), Flow :: atom(), Fun :: fun(() -> any())) -> ok | {error, _Reason}.
add_rule(NameRule, Mask, Priority, Flow, Fun) when is_atom(NameRule) ->
gen_server:call(?MODULE, {add_rule, NameRule, Mask, Priority, Flow, Fun}, infinity).
generate_iface_module(Module) ->
gen_server:call(?MODULE, {generate_iface_module, Module}).
close_outputs([Handle | Tail], Timeout) ->
?INT_DBG("Close of output ~p cause termination", [Handle]),
chronica_gen_backend:close(Handle, Timeout),
close_outputs(Tail, Timeout);
close_outputs([], _Timeout) ->
ok.
switch_on() ->
?INT_DBG("switch_on", []),
Res = pt_recompilable:recompile_orig_module(chronica_core,
fun (AST, _Options) ->
AST
end
),
Res.
switch_off() ->
?INT_DBG("switch_off", []),
Res = pt_recompilable:recompile_orig_module(chronica_core,
fun (AST, _Options) ->
pt_lib:replace(AST, ast_pattern("log_fast(...$P...) -> ...$_... .", Line), ast("log_fast(...$P...) -> ok. ", Line))
end),
Res.
create_flows(ConfigFlows, WriterOptions, Backends) ->
FlowsList = chronica_config:parse_flows(ConfigFlows, WriterOptions, Backends),
{_, Doubling} = lists:foldl(
fun ({Name, _}, {S , D}) ->
case lists:member(Name, S) of
true -> {S, [Name | D]};
false -> {[Name | S], D}
end
end,
{[], []},
FlowsList),
case Doubling of
[] -> ok;
_ ->
?INT_ERR("following flows are doubling: ~p", [Doubling]),
erlang:throw({create_flows, doubling_flows})
end,
FlowsList.
destroy_flows(Flows, Timeout) ->
Writers = get_writers(Flows),
close_outputs(Writers, Timeout).
get_writers(null) -> [];
get_writers(Flows) ->
lists:foldl(
fun ({_Name, Outputs}, Acc) ->
[Handle || #flow_handle{id = Handle} <- Outputs] ++ Acc
end,
[],
Flows).
parse_formats([], Res, _) -> Res;
parse_formats([#chronica_format{format_id = Name, format = UserFormat} | Tail], Res, ColorsConfig) when is_atom(Name) and is_list(UserFormat) ->
parse_formats(Tail, [chronica_format_creator:create_format_function(Name, UserFormat, ColorsConfig) | Res], ColorsConfig);
parse_formats(BadFormated, _, _) ->
?INT_ERR("invalid formats param ~p", [BadFormated]),
erlang:throw({parse_formats, bad_format}).
add_application(App, RApps, Rules, Cache, Detail_info) ->
add_application(App, RApps, Rules, Cache, Detail_info, undefined).
add_application(App, RApps, Rules, Cache, Detail_info, TickFun) ->
try
add_application_(App, RApps, Rules, Cache, Detail_info, TickFun)
catch
throw:{Err, NRA} ->
?INT_ERR("reg ~p failed \\ ~p~n", [App, NRA]),
{Err, NRA}
end.
add_application_(App, RApps, Rules, Cache, Detail_info, TickFun) ->
?INT_DBG("-> rq add_application ~p \\ ~p", [App, RApps]),
case sets:is_element(App, RApps) of
true ->
{ok, {RApps, Cache}};
false ->
?INT_DBG("-> Rq Reg ~100000p \\ ~100000p \\ is_list(Cache): ~10000000000000p~n", [App, RApps, is_list(Cache)]),
case add_application_in_cache(App, RApps, Rules, Cache, Detail_info, TickFun) of
Applicatin successfully added in cache .
{ok, {NewRApps, NewCache}} ->
DepApps0 = case application:get_key(App, applications) of
{ok, L0} -> L0;
_ -> []
end,
DepApps = case application:get_key(App, included_applications) of
{ok, [_ | _] = L1} -> L1 ++ DepApps0;
_ -> DepApps0
end,
AddAppsRecurciveFun =
fun (A, {Added, CacheAcc}) ->
case add_application_(A, Added, Rules, CacheAcc, Detail_info, TickFun) of
{ok, {NewAdded, NewCacheAcc}} -> {NewAdded, NewCacheAcc};
{Error, {NewAdded, NewCacheAcc}} -> throw({Error, {NewAdded, NewCacheAcc}})
end
end,
{ResultRApps, ResultCache} = lists:foldl(AddAppsRecurciveFun, {NewRApps, NewCache}, DepApps),
{ok, {ResultRApps, ResultCache}};
{Error, ErrorArgs} ->
{Error, ErrorArgs}
end
end.
add_application_in_cache(App, RApps, Rules, Cache, Detail_info, TickFun) ->
?INT_DBG("Registering application ~100000p \\ ~1000000p \\ is_list(NewCache): ~10000000p", [App, RApps, is_list(Cache)]),
try
AppHash = app_hash(App),
is_function(TickFun) andalso TickFun(),
case proplists:get_value(App, Cache, undefined) of
{AppHash, AppModulesCode} ->
?INT_DBG("~p chronica interface was loaded from cache", [App]),
load_app_iface_modules(AppModulesCode),
ResApps = sets:add_element(App, RApps),
?INT_DBG("Registered (from cache) \\ ~p~n", [ResApps]),
{ok, {ResApps, Cache}};
_Cached ->
AppModulesCode = case Detail_info of
true ->
io:format("Compiling the cache: [~p] ", [App]),
T1 = erlang:system_time(millisecond),
Apps = chronica_iface:generate_app_iface_modules(App, Rules),
T2 = erlang:system_time(millisecond),
case Apps of
[] -> io:format("skipped~n");
_ -> io:format("~pms done.~n", [T2 - T1])
end,
Apps;
false ->
chronica_iface:generate_app_iface_modules(App, Rules)
end,
load_app_iface_modules(AppModulesCode),
ResApps = sets:add_element(App, RApps),
?INT_DBG("Registered \\ ~p~n", [ResApps]),
{ok, {ResApps, [{App, {AppHash, AppModulesCode}} | proplists:delete(App, Cache)]}}
end
catch
_:Error ->
?INT_ERR("Add application ~p failed cause: ~p~n~p", [App, Error, erlang:get_stacktrace()]),
{Error, {RApps, Cache}}
end.
set_configured_true() ->
pt_recompilable:recompile_cur_module(
chronica_status,
fun (AST, _Options) ->
pt_lib:replace(AST,
ast_pattern("configured() -> ...$_... .", Line),
ast("configured() -> true.", Line))
end).
depended_from_chronica(lager) ->
true;
depended_from_chronica(chronica) ->
true;
depended_from_chronica(App) ->
CheckApplicationFun =
fun({ok, DependedApplications}) ->
lists:member(chronica, DependedApplications) orelse
lists:member(lager, DependedApplications);
(_) ->
false
end,
CheckApplicationFun(application:get_key(App, applications)) orelse
CheckApplicationFun(application:get_key(App, included_applications)).
app_hash(App) ->
Tags =
case depended_from_chronica(App) of
false ->
[];
true ->
case application:get_key(App, modules) of
{ok, L2} ->
lists:foldl(
fun (ModuleName, Acc) ->
case (catch ModuleName:get_log_tags()) of
Tags2 when is_list(Tags2) -> [{ModuleName, Tags2}|Acc];
_ -> Acc
end
end, [], L2);
Error -> erlang:error({no_modules_info, App, Error})
end
end,
erlang:md5(erlang:term_to_binary(Tags)).
config_hash(#chronica_config{active = Active, rules = Rules, flows = Flows}) ->
erlang:md5(erlang:term_to_binary({Active, Rules, Flows})).
add_all_applications(RegApps, NewRules, Cache, Detail_info, TickFun) ->
sets:fold(
fun (App, {RAAcc, CacheAcc}) ->
case add_application(App, RAAcc, NewRules, CacheAcc, Detail_info, TickFun) of
{ok, NRA} -> NRA;
{AAErr, _NRA} -> throw(AAErr)
end
end,
{sets:new(), Cache},
RegApps).
load_code_module(undefined) -> ok;
load_code_module({Module, Binary}) ->
case code:soft_purge(Module) of
true ->
case code:load_binary(Module, atom_to_list(Module) ++ ".erl", Binary) of
{module, Module} ->
?INT_DBG("~p: module reloaded", [Module]),
ok;
{error, Cause} -> {error, {cant_load, Module, Cause}}
end;
false ->
{error, soft_purge_failed}
end.
load_app_iface_modules(AppModulesCode) ->
lists:foreach(
fun ({Module, Code}) ->
case load_code_module(Code) of
ok ->
ok;
{error, Error} ->
?INT_ERR("Cant load module ~p chronica iface code binary, reason: ~p", [Module, Error]),
erlang:error({cant_load_module, Module, Error})
end
end, AppModulesCode).
-define(d2012_11_16_1_25_41, 63520248341000000).
generate_name(Prefix) ->
Now = {_, _, M} = os:timestamp(),
DT = calendar:now_to_universal_time(Now),
N = calendar:datetime_to_gregorian_seconds(DT) * 1000000 + M - ?d2012_11_16_1_25_41,
lists:flatten(io_lib:format("~s~.36.0b", [Prefix, N])).
|
67c7c67662818d7ff8d648615e8864df3c138af3638dad216eacce55bb27fe61 | ocaml/ocaml | coercions.ml | (* TEST
flags = " -w +A -strict-sequence "
* expect
*)
comment 9644 of PR#6000
fun b -> if b then format_of_string "x" else "y"
[%%expect {|
- : bool -> ('a, 'b, 'c, 'd, 'd, 'a) format6 = <fun>
|}, Principal{|
Line 1, characters 45-48:
1 | fun b -> if b then format_of_string "x" else "y"
^^^
Warning 18 [not-principal]: this coercion to format6 is not principal.
- : bool -> ('a, 'b, 'c, 'd, 'd, 'a) format6 = <fun>
|}]
;;
fun b -> if b then "x" else format_of_string "y"
[%%expect {|
Line 1, characters 28-48:
1 | fun b -> if b then "x" else format_of_string "y"
^^^^^^^^^^^^^^^^^^^^
Error: This expression has type
('a, 'b, 'c, 'd, 'd, 'a) format6 =
('a, 'b, 'c, 'd, 'd, 'a) CamlinternalFormatBasics.format6
but an expression was expected of type string
|}]
;;
fun b : (_,_,_) format -> if b then "x" else "y"
[%%expect {|
- : bool -> ('a, 'b, 'a) format = <fun>
|}]
;;
(* PR#7135 *)
module PR7135 = struct
module M : sig type t = private int end = struct type t = int end
include M
let lift2 (f : int -> int -> int) (x : t) (y : t) =
f (x :> int) (y :> int)
end;;
[%%expect {|
module PR7135 :
sig
module M : sig type t = private int end
type t = M.t
val lift2 : (int -> int -> int) -> t -> t -> int
end
|}]
(* example of non-ground coercion *)
module Test1 = struct
type t = private int
let f x = let y = if true then x else (x:t) in (y :> int)
end;;
[%%expect {|
module Test1 : sig type t = private int val f : t -> int end
|}, Principal{|
Line 3, characters 49-59:
3 | let f x = let y = if true then x else (x:t) in (y :> int)
^^^^^^^^^^
Warning 18 [not-principal]: this ground coercion is not principal.
module Test1 : sig type t = private int val f : t -> int end
|}]
| null | https://raw.githubusercontent.com/ocaml/ocaml/d71ea3d089ae3c338b8b6e2fb7beb08908076c7a/testsuite/tests/typing-warnings/coercions.ml | ocaml | TEST
flags = " -w +A -strict-sequence "
* expect
PR#7135
example of non-ground coercion |
comment 9644 of PR#6000
fun b -> if b then format_of_string "x" else "y"
[%%expect {|
- : bool -> ('a, 'b, 'c, 'd, 'd, 'a) format6 = <fun>
|}, Principal{|
Line 1, characters 45-48:
1 | fun b -> if b then format_of_string "x" else "y"
^^^
Warning 18 [not-principal]: this coercion to format6 is not principal.
- : bool -> ('a, 'b, 'c, 'd, 'd, 'a) format6 = <fun>
|}]
;;
fun b -> if b then "x" else format_of_string "y"
[%%expect {|
Line 1, characters 28-48:
1 | fun b -> if b then "x" else format_of_string "y"
^^^^^^^^^^^^^^^^^^^^
Error: This expression has type
('a, 'b, 'c, 'd, 'd, 'a) format6 =
('a, 'b, 'c, 'd, 'd, 'a) CamlinternalFormatBasics.format6
but an expression was expected of type string
|}]
;;
fun b : (_,_,_) format -> if b then "x" else "y"
[%%expect {|
- : bool -> ('a, 'b, 'a) format = <fun>
|}]
;;
module PR7135 = struct
module M : sig type t = private int end = struct type t = int end
include M
let lift2 (f : int -> int -> int) (x : t) (y : t) =
f (x :> int) (y :> int)
end;;
[%%expect {|
module PR7135 :
sig
module M : sig type t = private int end
type t = M.t
val lift2 : (int -> int -> int) -> t -> t -> int
end
|}]
module Test1 = struct
type t = private int
let f x = let y = if true then x else (x:t) in (y :> int)
end;;
[%%expect {|
module Test1 : sig type t = private int val f : t -> int end
|}, Principal{|
Line 3, characters 49-59:
3 | let f x = let y = if true then x else (x:t) in (y :> int)
^^^^^^^^^^
Warning 18 [not-principal]: this ground coercion is not principal.
module Test1 : sig type t = private int val f : t -> int end
|}]
|
57ee44fb0bb1147cd91a4b465beb32692f86c4472cfd8e960fe86bbbaf773814 | WormBase/wormbase_rest | reagents.clj | (ns rest-api.classes.cds.widgets.reagents
(:require
[clojure.string :as str]
[rest-api.formatters.object :as obj :refer [pack-obj]]
[rest-api.classes.generic-fields :as generic]))
(defn source-clone [c]
{:data (some->> (:sequence/clone
(:locatable/parent c))
(map pack-obj)
(first))
:description "The Source clone of the sequence"})
(defn pcr-products [c]
{:data (some->> (:cds/corresponding-pcr-product c)
(map pack-obj)
(sort-by (fn [s] (str/lower-case (:label s)))))
:description "PCR products for the sequence"})
(defn matching-cdnas [c]
{:data (some->> (:cds/matching-cdna c)
(map :cds.matching-cdna/sequence)
(map pack-obj)
(sort-by :label))
:description "cDNAs that match the sequence"})
(def widget
{:name generic/name-field
:microarray_assays generic/microarray-assays
:orfeome_assays generic/orfeome-assays
:source_clone source-clone
:pcr_products pcr-products
:matching_cdnas matching-cdnas})
| null | https://raw.githubusercontent.com/WormBase/wormbase_rest/e51026f35b87d96260b62ddb5458a81ee911bf3a/src/rest_api/classes/cds/widgets/reagents.clj | clojure | (ns rest-api.classes.cds.widgets.reagents
(:require
[clojure.string :as str]
[rest-api.formatters.object :as obj :refer [pack-obj]]
[rest-api.classes.generic-fields :as generic]))
(defn source-clone [c]
{:data (some->> (:sequence/clone
(:locatable/parent c))
(map pack-obj)
(first))
:description "The Source clone of the sequence"})
(defn pcr-products [c]
{:data (some->> (:cds/corresponding-pcr-product c)
(map pack-obj)
(sort-by (fn [s] (str/lower-case (:label s)))))
:description "PCR products for the sequence"})
(defn matching-cdnas [c]
{:data (some->> (:cds/matching-cdna c)
(map :cds.matching-cdna/sequence)
(map pack-obj)
(sort-by :label))
:description "cDNAs that match the sequence"})
(def widget
{:name generic/name-field
:microarray_assays generic/microarray-assays
:orfeome_assays generic/orfeome-assays
:source_clone source-clone
:pcr_products pcr-products
:matching_cdnas matching-cdnas})
|
|
8a39d912644a6d2a53d3092be2be1f1f0df7d4898ea1b1a77f7c2ebb9589b508 | meta-ex/ignite | petals.clj | (ns meta-ex.viz.petals
(:use quil.core
[overtone.helpers.ref]))
Modified version of " Mums " by
;;
(defonce num-petals-to-draw* (atom 0))
(def magenta [255 0 255])
(def orange [255 170 0])
(def chartreuse [127 255 0])
(def flower-colors [magenta orange chartreuse])
(def yellow [255 255 0])
(defn setup []
(smooth)
(background 0)) ; TODO: Need correct implementation
(defn- draw-streaks [petal-color petal-length]
(stroke-weight 2)
(apply stroke (map #(* % 0.9) petal-color))
(doseq [x (range 10)]
(curve 0 (- 25 (* x 10))
0 25
petal-length 25
petal-length (- 25 (* x 10)))
)
(stroke-weight 1)
)
(defn- draw-petal [petal-color initial-petal-length]
Randomize length of petal
(apply stroke (map #(* % 0.7) petal-color))
(let [petal-length (+ initial-petal-length (random 100 ))]
(push-matrix)
; This is done because ellipse() starts drawing from the top left corner
(translate 20 -20)
(ellipse 0 0 petal-length 40)
; (draw-streaks petal-color petal-length)
(pop-matrix)
(no-stroke)
)
)
(defn- draw-center []
; This is a cheat to make sure the petals don't show
; through the gaps in between the circles created below
(apply fill yellow)
(ellipse -30 -30 60 60)
(apply stroke (map #(/ % 2) yellow))
(apply fill yellow)
(doseq [ring-number (range 6)]
(let [ring-radius (+ (random 8) (* ring-number 5))
ring-size (+ 11 (* ring-number 5))]
(push-matrix)
(doseq [_ (range ring-size)]
(ellipse ring-radius 0 5 5)
(rotate (radians (/ 360 ring-size))))
(pop-matrix)))
(ellipse -3 -3 6 6)
)
(defn- draw-flower [flower-color]
; Algorithm is as follows
* Draw three rings of petals , outermost ring drawn first
; * Randomize number of petals per each ring; outermost ring will have largest number
; * Randomize angles of each petal per ring; they should not simply be spread evenly
(ellipse-mode :corner)
(push-matrix)
(doseq [ring-num (range 3 0 -1)]
(let [petal-count (+ 10 (int (random (* ring-num 4))))]
(doseq [_ (range petal-count)]
(rotate (radians (+ (/ 360 petal-count) (random 10))))
(apply fill flower-color)
(draw-petal flower-color (+ 50 (* ring-num 25)))
)
)
)
(pop-matrix)
(draw-center)
)
(defn draw []
;; (background 0)
(no-stroke)
(let [[n-petals _] (swap-returning-prev! num-petals-to-draw*
(fn [x] 0))]
(doseq [_ (range n-petals)]
(push-matrix)
(translate (random (screen-width)) (random (screen-height)))
( translate ( mod ( * 2 ( frame - count ) ) screen - h ) ( mod ( * 2 ( frame - count ) ) screen - h ) )
(draw-flower (flower-colors (int (random 3))))
(pop-matrix))))
(comment
(defsketch main
:title "mums"
:setup setup
:draw draw
:decor false
:renderer :opengl
:size [(screen-width) (screen-height)])
)
| null | https://raw.githubusercontent.com/meta-ex/ignite/b9b1ed7ae2fa01d017c23febabb714a6389a98dd/src/meta_ex/viz/petals.clj | clojure |
TODO: Need correct implementation
This is done because ellipse() starts drawing from the top left corner
(draw-streaks petal-color petal-length)
This is a cheat to make sure the petals don't show
through the gaps in between the circles created below
Algorithm is as follows
* Randomize number of petals per each ring; outermost ring will have largest number
* Randomize angles of each petal per ring; they should not simply be spread evenly
(background 0) | (ns meta-ex.viz.petals
(:use quil.core
[overtone.helpers.ref]))
Modified version of " Mums " by
(defonce num-petals-to-draw* (atom 0))
(def magenta [255 0 255])
(def orange [255 170 0])
(def chartreuse [127 255 0])
(def flower-colors [magenta orange chartreuse])
(def yellow [255 255 0])
(defn setup []
(smooth)
(defn- draw-streaks [petal-color petal-length]
(stroke-weight 2)
(apply stroke (map #(* % 0.9) petal-color))
(doseq [x (range 10)]
(curve 0 (- 25 (* x 10))
0 25
petal-length 25
petal-length (- 25 (* x 10)))
)
(stroke-weight 1)
)
(defn- draw-petal [petal-color initial-petal-length]
Randomize length of petal
(apply stroke (map #(* % 0.7) petal-color))
(let [petal-length (+ initial-petal-length (random 100 ))]
(push-matrix)
(translate 20 -20)
(ellipse 0 0 petal-length 40)
(pop-matrix)
(no-stroke)
)
)
(defn- draw-center []
(apply fill yellow)
(ellipse -30 -30 60 60)
(apply stroke (map #(/ % 2) yellow))
(apply fill yellow)
(doseq [ring-number (range 6)]
(let [ring-radius (+ (random 8) (* ring-number 5))
ring-size (+ 11 (* ring-number 5))]
(push-matrix)
(doseq [_ (range ring-size)]
(ellipse ring-radius 0 5 5)
(rotate (radians (/ 360 ring-size))))
(pop-matrix)))
(ellipse -3 -3 6 6)
)
(defn- draw-flower [flower-color]
* Draw three rings of petals , outermost ring drawn first
(ellipse-mode :corner)
(push-matrix)
(doseq [ring-num (range 3 0 -1)]
(let [petal-count (+ 10 (int (random (* ring-num 4))))]
(doseq [_ (range petal-count)]
(rotate (radians (+ (/ 360 petal-count) (random 10))))
(apply fill flower-color)
(draw-petal flower-color (+ 50 (* ring-num 25)))
)
)
)
(pop-matrix)
(draw-center)
)
(defn draw []
(no-stroke)
(let [[n-petals _] (swap-returning-prev! num-petals-to-draw*
(fn [x] 0))]
(doseq [_ (range n-petals)]
(push-matrix)
(translate (random (screen-width)) (random (screen-height)))
( translate ( mod ( * 2 ( frame - count ) ) screen - h ) ( mod ( * 2 ( frame - count ) ) screen - h ) )
(draw-flower (flower-colors (int (random 3))))
(pop-matrix))))
(comment
(defsketch main
:title "mums"
:setup setup
:draw draw
:decor false
:renderer :opengl
:size [(screen-width) (screen-height)])
)
|
1ffa20650818ead7c6112377132d87d8d06539a80fad4510f2ce44f6e8a64c20 | arohner/spectrum | z3_test.clj | (ns spectrum.z3-test
(:require [clojure.test :refer :all]
[spectrum.z3 :as z3 :refer [q]]))
(def a :a)
(def b :b)
(deftest q-works
(are [in out] (= out in)
(q (foo ~a)) '(foo :a)
(q (foo ~a ~b)) '(foo :a :b)
(let [bar [1 2 3]]
(q (foo ~@bar))) '(foo 1 2 3)
(let [bar [1 2 3]]
(q (foo ~@bar ~a))) '(foo 1 2 3 :a)
(let [bar [1 2 3]
bbq [:bbq]]
(q (foo ~@bar ~@bbq))) '(foo 1 2 3 :bbq)))
(deftest eval-works
(is (coll? (z3/eval (z3/new-context) '(get-info :version)))))
(deftest smt-fns-work
(is (coll? (z3/get-info :version))))
| null | https://raw.githubusercontent.com/arohner/spectrum/72b47a91a5ce4567eed547507d25b2528f48c2d1/test/spectrum/z3_test.clj | clojure | (ns spectrum.z3-test
(:require [clojure.test :refer :all]
[spectrum.z3 :as z3 :refer [q]]))
(def a :a)
(def b :b)
(deftest q-works
(are [in out] (= out in)
(q (foo ~a)) '(foo :a)
(q (foo ~a ~b)) '(foo :a :b)
(let [bar [1 2 3]]
(q (foo ~@bar))) '(foo 1 2 3)
(let [bar [1 2 3]]
(q (foo ~@bar ~a))) '(foo 1 2 3 :a)
(let [bar [1 2 3]
bbq [:bbq]]
(q (foo ~@bar ~@bbq))) '(foo 1 2 3 :bbq)))
(deftest eval-works
(is (coll? (z3/eval (z3/new-context) '(get-info :version)))))
(deftest smt-fns-work
(is (coll? (z3/get-info :version))))
|
|
04c26cc5cc45036e9a75d64a68c0fe4b4c5708da64408063487fe2370499e6f0 | craff/pacomb | Break.ml | open Pacomb
open Grammar
Blank function
let blank = Regexp.blank_regexp "\\(\\([#][^\n]*\\)\\|[ \r\t\026]+\\)*"
(* bug: "\\([ \r\t\026]\\|\\(\\(#[^\n]*\\)\\)*" *)
Parser for
let%parser char =
(i::RE"[0-9A-Fa-F]+") => Uchar.of_int (int_of_string ("0x" ^ i))
let%parser sep = "÷" => true ; "×" => false
let%parser rec sample_aux = (l::sample_aux) (c::char) (s::sep) => (c,s) :: l
; (c::char) (s::sep) => [(c,s)]
let%parser sample = sep (l::sample_aux) => List.rev l
let%parser rec break = () => []
; (g::GRAPHEME) (l::break) => g::l
let good = ref true
let test pos l0 =
try
let chars = List.map fst l0 in
let s = Utf8.of_list chars in
let rec fn = function
| [] -> []
| []::_ -> Printf.eprintf "unexpected empty at %a\n%!"
(Pos.print_pos ()) pos;
good := false;
raise Exit
| [x]::l -> (x,true)::fn l
| (x::l1)::l -> (x,false)::fn (l1::l)
in
let l = parse_string ~utf8:Utf8.UTF8 break Blank.none s in
let l = List.map (fun s -> Utf8.to_list s) l in
let l = fn l in
if l <> l0 then
begin
Printf.eprintf "break fail at %a\n%!" (Pos.print_pos ()) pos;
List.iter (fun (l,b) -> Printf.eprintf "%x %b " (Uchar.to_int l) b) l;
Printf.eprintf " <> ";
List.iter (fun (l,b) -> Printf.eprintf "%x %b " (Uchar.to_int l) b) l0;
Printf.eprintf "\n%!";
good := false;
raise Exit
end
with Exit -> ()
(* Single mapping parser *)
let%parser test = (l::sample) (~+ '\n' => ()) => test l_pos l
let%parser tests =
(star ('\n' => ())) (star test) => ()
let parse = parse_channel ~utf8:Utf8.UTF8 tests blank
let _ =
(* Command line args *)
if Array.length Sys.argv != 2 then
begin
let pn = Sys.argv.(0) in
Printf.eprintf "Usage: %s <GraphemeBreakTest.txt>" pn;
exit 1
end;
let infile = Sys.argv.(1) in
(* Parsing and preparing the data *)
let infile = open_in infile in
let _ = Pos.handle_exception parse infile in
close_in infile;
if not !good then exit 1
| null | https://raw.githubusercontent.com/craff/pacomb/3e83f56bc483f6b9c495ae91d773aa9b484eb321/tests/Break.ml | ocaml | bug: "\\([ \r\t\026]\\|\\(\\(#[^\n]*\\)\\)*"
Single mapping parser
Command line args
Parsing and preparing the data | open Pacomb
open Grammar
Blank function
let blank = Regexp.blank_regexp "\\(\\([#][^\n]*\\)\\|[ \r\t\026]+\\)*"
Parser for
let%parser char =
(i::RE"[0-9A-Fa-F]+") => Uchar.of_int (int_of_string ("0x" ^ i))
let%parser sep = "÷" => true ; "×" => false
let%parser rec sample_aux = (l::sample_aux) (c::char) (s::sep) => (c,s) :: l
; (c::char) (s::sep) => [(c,s)]
let%parser sample = sep (l::sample_aux) => List.rev l
let%parser rec break = () => []
; (g::GRAPHEME) (l::break) => g::l
let good = ref true
let test pos l0 =
try
let chars = List.map fst l0 in
let s = Utf8.of_list chars in
let rec fn = function
| [] -> []
| []::_ -> Printf.eprintf "unexpected empty at %a\n%!"
(Pos.print_pos ()) pos;
good := false;
raise Exit
| [x]::l -> (x,true)::fn l
| (x::l1)::l -> (x,false)::fn (l1::l)
in
let l = parse_string ~utf8:Utf8.UTF8 break Blank.none s in
let l = List.map (fun s -> Utf8.to_list s) l in
let l = fn l in
if l <> l0 then
begin
Printf.eprintf "break fail at %a\n%!" (Pos.print_pos ()) pos;
List.iter (fun (l,b) -> Printf.eprintf "%x %b " (Uchar.to_int l) b) l;
Printf.eprintf " <> ";
List.iter (fun (l,b) -> Printf.eprintf "%x %b " (Uchar.to_int l) b) l0;
Printf.eprintf "\n%!";
good := false;
raise Exit
end
with Exit -> ()
let%parser test = (l::sample) (~+ '\n' => ()) => test l_pos l
let%parser tests =
(star ('\n' => ())) (star test) => ()
let parse = parse_channel ~utf8:Utf8.UTF8 tests blank
let _ =
if Array.length Sys.argv != 2 then
begin
let pn = Sys.argv.(0) in
Printf.eprintf "Usage: %s <GraphemeBreakTest.txt>" pn;
exit 1
end;
let infile = Sys.argv.(1) in
let infile = open_in infile in
let _ = Pos.handle_exception parse infile in
close_in infile;
if not !good then exit 1
|
d403311df93c48dc24c75d8db2ef020e7076a8a475c1c4e8e67f8b7afa200a4a | gfour/gic | Lifter.hs | module SLIC.Front.LLifter.Lifter (lambdaLiftMod) where
import SLIC.AuxFun (ierr, lkUpSure)
import SLIC.Front.LLifter.Equations as Eqn
import SLIC.State
import SLIC.SyntaxAux
import SLIC.SyntaxFL
import SLIC.Types
import Data.List as List (concat, foldl, map, unzip, zip)
import Data.Set as Set (Set, delete, difference, elems, empty, fromList,
intersection, map, null, singleton, union)
import Data.Map as Map (Map, adjust, delete, empty, findWithDefault,
foldWithKey, fromList, insert, insertWith, keys,
map, null)
type Renamings = Map QName QName
type VarGrh = Map QName (Set QName)
-- | Same as Map.insert but raises an error when given key
-- is already present in the map so that silent updates
-- are avoided.
insertUnique :: Ord k => k -> a -> Map k a -> Map k a
insertUnique k a m =
Map.insertWith (\_ _ -> ierr $ "key already present in map") k a m
-- | Take a map from varnames to varname sets, a defined name and
an FL expression and add the free vars of the expression
-- to the set associated with the given defined name.
fvExprF :: VarGrh -> QName -> ExprF -> VarGrh
fvExprF vg vn exprF =
let augmentWith s = Map.insertWith Set.union vn s vg
removeDefinedNames defFL s = Set.difference s $ Set.fromList $
List.map defVarName defFL
in case exprF of
XF v -> augmentWith $ Set.singleton $ nameOfV v
ConF _ exprFL -> List.foldl (\vg' -> fvExprF vg' vn) vg exprFL
FF v exprFL _ -> List.foldl (\vg' -> fvExprF vg' vn)
(augmentWith $ Set.singleton $ nameOfV v)
exprFL
ConstrF _ exprFL -> List.foldl (\vg' -> fvExprF vg' vn) vg exprFL
CaseF _ exprF' vname patFL -> Map.adjust (Set.delete vname) vn $
List.foldl (\vg' -> fvPatF vg' vn)
(fvExprF vg vn exprF') patFL
LamF _ vname exprF' -> Map.adjust (Set.delete vname) vn $
fvExprF vg vn exprF'
LetF _ defFL exprF' -> Map.adjust (removeDefinedNames defFL) vn $
fvExprF
(List.foldl (\vg' -> fvDefF vg' vn)
vg defFL)
vn exprF'
-- | Take a map from varnames to varname sets, a defined name and
an FL pattern and add the free vars of the pattern
-- to the set associated with the given defined name.
fvPatF :: VarGrh -> QName -> PatF -> VarGrh
fvPatF vg vn (PatB (SPat _ vnameL, _) exprF) =
Map.adjust (\s1 -> Set.difference s1 $ Set.fromList vnameL)
vn $ fvExprF vg vn exprF
-- | Take a map from varnames to varname sets and a definition
-- and augment the map so that it associates the defined name
-- with the set of the names of the free variables appearing in its body.
fvDefF :: VarGrh -> QName -> DefF -> VarGrh
fvDefF vg vn (DefF vname frmL exprF) =
let vg' = Map.adjust
(\s1 -> Set.difference s1 $ Set.fromList $ vname:(frmsToNames frmL))
vname $ fvExprF (insertUnique vname Set.empty vg) vname exprF
in Map.insertWith Set.union vn
(lkUpSure vname vg') vg'
| Take an FL program and return a map that associates the defined
-- names with the free variables appearing in their definitions.
fvProgF :: ProgF -> VarGrh
fvProgF (Prog _ defFL) =
Map.delete pFV $
Map.adjust
(\s1 -> Set.difference s1 $ Set.fromList $ List.map defVarName defFL)
pFV $ List.foldl (\vg' -> fvDefF vg' pFV) Map.empty defFL
pFV :: QName
pFV = QN Nothing "*" -- special name representing the set of the program's free vars
| Alpha - rename an FL expression using the given map associating
-- names with names. Constructor and constant names are preserved.
aRenameExprF :: Renamings -> ExprF -> ExprF
aRenameExprF ren exprF =
case exprF of
XF v -> XF . V $ Map.findWithDefault (nameOfV v) (nameOfV v) ren
ConF cName exprFL ->
ConF cName $ List.map (aRenameExprF ren) exprFL
FF v exprFL ci ->
FF (V $ Map.findWithDefault (nameOfV v) (nameOfV v) ren)
(List.map (aRenameExprF ren) exprFL) ci
ConstrF cstrName exprFL ->
ConstrF cstrName $ List.map (aRenameExprF ren) exprFL
CaseF depth exprF' vname patFL ->
let vname' = Map.findWithDefault vname vname ren in
CaseF depth (aRenameExprF ren exprF') vname' $
List.map (aRenamePatF ren) patFL
LamF depth vname exprF' ->
let vname' = Map.findWithDefault vname vname ren in
LamF depth vname' $ aRenameExprF ren exprF'
LetF depth defFL exprF' ->
let defFL' = List.map (aRenameDefF ren) defFL
in LetF depth defFL' $ aRenameExprF ren exprF'
| Alpha - rename an FL pattern using the given map associating
-- names with names. Constructor and constant names are preserved.
aRenamePatF :: Renamings -> PatF -> PatF
aRenamePatF ren (PatB (SPat cstrName vnameL, pI) exprF) =
PatB (SPat cstrName
(List.map (\vn -> Map.findWithDefault vn vn ren) vnameL), pI) $
aRenameExprF ren exprF
| Alpha - rename an FL definition using the given map associating
-- names with names. Constructor and constant names are preserved.
aRenameDefF :: Renamings -> DefF -> DefF
aRenameDefF ren (DefF vname frmL exprF) =
DefF (Map.findWithDefault vname vname ren)
(List.map
(\(Frm vn stc) -> Frm (Map.findWithDefault vn vn ren) stc)
frmL) $
aRenameExprF ren exprF
-- | Take an expression and a map associating function names with
the extra parameters to be applied on them first and amend all
-- function applications.
-- ** All names are supposed to be unique at this point. **
preApplyExprF :: VarGrh -> ExprF -> ExprF
preApplyExprF vg exprF =
case exprF of
XF v ->
let extVarsS = Map.findWithDefault Set.empty (nameOfV v) vg
in if Set.null extVarsS then exprF
else FF v (List.map (XF . V) $ Set.elems extVarsS) NoCI
ConF cName exprFL ->
ConF cName $ List.map (preApplyExprF vg) exprFL
FF v exprFL ci ->
let exprFL' = List.map (preApplyExprF vg) exprFL
extVarsS = Map.findWithDefault Set.empty (nameOfV v) vg
in if Set.null extVarsS then FF v exprFL' ci
else FF v ((List.map (XF . V) $ Set.elems extVarsS) ++ exprFL') ci
ConstrF cstrName exprFL ->
ConstrF cstrName $ List.map (preApplyExprF vg) exprFL
CaseF depth exprF' vname patFL ->
CaseF depth (preApplyExprF vg exprF') vname $
List.map (\(PatB sPat exprF'') ->
PatB sPat $ preApplyExprF vg exprF'')
patFL
LamF depth vname exprF' ->
LamF depth vname $ preApplyExprF vg exprF'
LetF depth defFL exprF' ->
let defFL' = List.map (preApplyDefF vg) defFL
in LetF depth defFL' $ preApplyExprF vg exprF'
-- | Take a definition and a map associating function names with
the extra parameters to be applied on them first and amend all
-- function applications.
-- ** All names are supposed to be unique at this point. **
preApplyDefF :: VarGrh -> DefF -> DefF
preApplyDefF vg (DefF vname frmL exprF) =
DefF vname frmL $ preApplyExprF vg exprF
-- | Take a definition and a map associating function names with
the extra parameters to be applied on them first and amend all
-- function applications.
-- ** All names are supposed to be unique at this point. **
preApplyProgF :: VarGrh -> ProgF -> ProgF
preApplyProgF vg (Prog dataL defFL) =
Prog dataL $ List.map (preApplyDefF vg) defFL
-- | Take a definition and a list of extra formals, add the
-- extra formals to the definition and a-rename (the formals
-- and the bound variables in the definition body.
abstractDefWithFormals :: DefF -> [Frm] -> DefF
abstractDefWithFormals (DefF vname frmL exprF) frmL' =
let frmNameL' = frmsToNames frmL'
renFrmNameL' = List.map (\x -> procLName (\ln->ln ++ "_" ++ qName vname ++ "_Lifted") x)
frmNameL'
ren = Map.fromList $ List.zip frmNameL' renFrmNameL'
in aRenameDefF ren $ DefF vname (frmL'++frmL) exprF
| Add extra formals ( assumed lazy ) to FL definitions recursively .
abstractDefsDefF :: VarGrh -> DefF -> DefF
abstractDefsDefF vg (DefF vname frmL exprF) =
let mkFrm vn = Frm vn (defaultEvOrder False)
frmL' = List.map mkFrm $ Set.elems $ lkUpSure vname vg
in abstractDefWithFormals
(DefF vname frmL $ abstractDefsExprF vg exprF) frmL'
| Add extra formals to FL definitions recursively .
abstractDefsExprF :: VarGrh -> ExprF -> ExprF
abstractDefsExprF vg exprF =
case exprF of
XF _ -> exprF
ConF cName exprFL ->
ConF cName $ List.map (abstractDefsExprF vg) exprFL
ConstrF cstrName exprFL ->
ConstrF cstrName $ List.map (abstractDefsExprF vg) exprFL
FF v exprFL ci -> FF v (List.map (abstractDefsExprF vg) exprFL) ci
CaseF depth exprF' vname patFL ->
let abstractDefsPatF (PatB sPat exprF'') =
PatB sPat $ abstractDefsExprF vg exprF''
in CaseF depth (abstractDefsExprF vg exprF') vname $
List.map abstractDefsPatF patFL
LamF depth vname exprF' -> LamF depth vname $
abstractDefsExprF vg exprF'
LetF depth defFL exprF' ->
let defFL' = List.map (abstractDefsDefF vg) defFL
in LetF depth defFL' $ abstractDefsExprF vg exprF'
| Add extra formals to FL definitions recursively .
abstractDefsProgF :: VarGrh -> ProgF -> ProgF
abstractDefsProgF vg (Prog dataL defFL) =
Prog dataL $ List.map (abstractDefsDefF vg) defFL
| Take an expression and return the a tuple containing 1 ) all the
definitions that are nested in the original expression and 2 ) an
-- expression which is the original one with all nested definitions
-- removed.
liftDefsExprF :: ExprF -> ([DefF], ExprF)
liftDefsExprF exprF =
case exprF of
XF _ -> ([], exprF)
ConF cName exprFL ->
let (defFLL, exprFL') = List.unzip $ List.map liftDefsExprF exprFL
in (List.concat defFLL, ConF cName exprFL')
ConstrF cstrName exprFL ->
let (defFLL, exprFL') = List.unzip $ List.map liftDefsExprF exprFL
in (List.concat defFLL, ConstrF cstrName exprFL')
FF v exprFL ci ->
let (defFLL, exprFL') = List.unzip $ List.map liftDefsExprF exprFL
in (List.concat defFLL, FF v exprFL' ci)
CaseF depth exprF' vname patFL ->
let liftDefsPatF (PatB sPat exprF'') =
let (defFL', exprF''') = liftDefsExprF exprF''
in (defFL', PatB sPat exprF''')
(defFLL, patFL') = List.unzip $ List.map liftDefsPatF patFL
(defFL, exprF'''') = liftDefsExprF exprF'
in (defFL ++ (List.concat defFLL), CaseF depth exprF'''' vname patFL')
LamF depth vname exprF' ->
let (defFL, exprF'') = liftDefsExprF exprF'
in (defFL, LamF depth vname exprF'')
LetF _ defFL exprF' ->
let (defFL', exprF'') = liftDefsExprF exprF'
defFL'' = List.concat $ List.map liftDefsDefF defFL
in (defFL'' ++ defFL', exprF'')
-- | Take a definition and return the a list of definitions which
-- contains all nested definition and the original one with
-- all nested definitions removed.
liftDefsDefF :: DefF -> [DefF]
liftDefsDefF (DefF vname frmL exprF) =
let (defFL, exprF') = liftDefsExprF exprF
in (DefF vname frmL exprF'):defFL
| Take an FL program and lift all definitions at top level .
-- ** All definitions are supposed to be combinators
-- i.e. they should contain no free variables at this point. **
liftDefsProgF :: ProgF -> ProgF
liftDefsProgF (Prog dataL defFL) =
let liftDefsDefF ( DefF vname frmL exprF ) =
-- let (defFL', exprF') = liftDefsExprF exprF
in ( DefF vname frmL exprF'):defFL '
--in
Prog dataL $ List.concat $ List.map liftDefsDefF defFL
-- | Take a map associating defined names with free variable names
-- and a set of defined names and return an equation system
-- between defined names and variables to abstracted out of
definition bodies ( as described by ) .
--
* Note that normally : defnameS = = Set.fromList $ Map.keys vg
mkEquationsJ :: VarGrh -> Set QName -> EqnSys QName (EqE QName QName)
mkEquationsJ vg defnameS =
let --knowns vn knownS = Set.map EqV $ Set.intersection knownS $ Map.
f vn fvS eqnSys = Map.insert vn
(Set.union
(Set.map (\vn' -> EqU vn') $
Set.intersection fvS defnameS) $
Set.map (\vn' -> EqV vn') $
Set.difference fvS defnameS)
eqnSys
in Map.foldWithKey f Map.empty vg
| Take an FL program and returned a corresponding lambda - lifted
FL program containing no abstractions and , more generally ,
-- no local definitions. Lambda-lifting is performed in accordance
with .
lambdaLiftProgF :: ProgF -> [QName] -> ProgF
lambdaLiftProgF p llExcluded =
let defFV = Map.map
(\s -> Set.difference s $
Set.fromList llExcluded)
$ fvProgF p
eqnSys = mkEquationsJ defFV $ Set.fromList $ Map.keys defFV
solvedEqnSys = Eqn.solveEqs eqnSys
solvedEqnSysV = Map.map (Set.map $ \(EqV x) -> x) solvedEqnSys
in liftDefsProgF $
abstractDefsProgF solvedEqnSysV $
preApplyProgF solvedEqnSysV p
| This is the entry point of the lambda - lifter . It takes an FL module and
-- eliminates all let-bindings, introducing new top-level definitions.
lambdaLiftModF :: ModF -> ModF
lambdaLiftModF (Mod modName exports imports progF an ts) =
let importedNames = mergeImportFuns imports
vfnL = Map.keys importedNames
llExcluded = vfnL ++ cBuiltinFuncs
in Mod modName exports imports (lambdaLiftProgF progF llExcluded) an ts
| Runs the lambda lifter on a list of FL modules . Checks that the lifter
-- can be used with the type checking scheme selected.
lambdaLiftMod :: Options -> ModF -> ModF
lambdaLiftMod opts modF =
let usesLifter = hasLs $ modProg modF
hasTSigs = Map.null $ modTAnnot modF
lliftedMod = lambdaLiftModF modF
lliftedModIfNotL =
if usesLifter && hasTSigs then
error "lambda-lifting doesn't support type signatures, use -gic-tc-nsig"
else
lliftedMod
in case optTC opts of
GHCTypeInf -> lliftedModIfNotL
GICTypeInf True -> lliftedModIfNotL
GICTypeInf False -> lliftedMod
| null | https://raw.githubusercontent.com/gfour/gic/d5f2e506b31a1a28e02ca54af9610b3d8d618e9a/SLIC/Front/LLifter/Lifter.hs | haskell | | Same as Map.insert but raises an error when given key
is already present in the map so that silent updates
are avoided.
| Take a map from varnames to varname sets, a defined name and
to the set associated with the given defined name.
| Take a map from varnames to varname sets, a defined name and
to the set associated with the given defined name.
| Take a map from varnames to varname sets and a definition
and augment the map so that it associates the defined name
with the set of the names of the free variables appearing in its body.
names with the free variables appearing in their definitions.
special name representing the set of the program's free vars
names with names. Constructor and constant names are preserved.
names with names. Constructor and constant names are preserved.
names with names. Constructor and constant names are preserved.
| Take an expression and a map associating function names with
function applications.
** All names are supposed to be unique at this point. **
| Take a definition and a map associating function names with
function applications.
** All names are supposed to be unique at this point. **
| Take a definition and a map associating function names with
function applications.
** All names are supposed to be unique at this point. **
| Take a definition and a list of extra formals, add the
extra formals to the definition and a-rename (the formals
and the bound variables in the definition body.
expression which is the original one with all nested definitions
removed.
| Take a definition and return the a list of definitions which
contains all nested definition and the original one with
all nested definitions removed.
** All definitions are supposed to be combinators
i.e. they should contain no free variables at this point. **
let (defFL', exprF') = liftDefsExprF exprF
in
| Take a map associating defined names with free variable names
and a set of defined names and return an equation system
between defined names and variables to abstracted out of
knowns vn knownS = Set.map EqV $ Set.intersection knownS $ Map.
no local definitions. Lambda-lifting is performed in accordance
eliminates all let-bindings, introducing new top-level definitions.
can be used with the type checking scheme selected. | module SLIC.Front.LLifter.Lifter (lambdaLiftMod) where
import SLIC.AuxFun (ierr, lkUpSure)
import SLIC.Front.LLifter.Equations as Eqn
import SLIC.State
import SLIC.SyntaxAux
import SLIC.SyntaxFL
import SLIC.Types
import Data.List as List (concat, foldl, map, unzip, zip)
import Data.Set as Set (Set, delete, difference, elems, empty, fromList,
intersection, map, null, singleton, union)
import Data.Map as Map (Map, adjust, delete, empty, findWithDefault,
foldWithKey, fromList, insert, insertWith, keys,
map, null)
type Renamings = Map QName QName
type VarGrh = Map QName (Set QName)
insertUnique :: Ord k => k -> a -> Map k a -> Map k a
insertUnique k a m =
Map.insertWith (\_ _ -> ierr $ "key already present in map") k a m
an FL expression and add the free vars of the expression
fvExprF :: VarGrh -> QName -> ExprF -> VarGrh
fvExprF vg vn exprF =
let augmentWith s = Map.insertWith Set.union vn s vg
removeDefinedNames defFL s = Set.difference s $ Set.fromList $
List.map defVarName defFL
in case exprF of
XF v -> augmentWith $ Set.singleton $ nameOfV v
ConF _ exprFL -> List.foldl (\vg' -> fvExprF vg' vn) vg exprFL
FF v exprFL _ -> List.foldl (\vg' -> fvExprF vg' vn)
(augmentWith $ Set.singleton $ nameOfV v)
exprFL
ConstrF _ exprFL -> List.foldl (\vg' -> fvExprF vg' vn) vg exprFL
CaseF _ exprF' vname patFL -> Map.adjust (Set.delete vname) vn $
List.foldl (\vg' -> fvPatF vg' vn)
(fvExprF vg vn exprF') patFL
LamF _ vname exprF' -> Map.adjust (Set.delete vname) vn $
fvExprF vg vn exprF'
LetF _ defFL exprF' -> Map.adjust (removeDefinedNames defFL) vn $
fvExprF
(List.foldl (\vg' -> fvDefF vg' vn)
vg defFL)
vn exprF'
an FL pattern and add the free vars of the pattern
fvPatF :: VarGrh -> QName -> PatF -> VarGrh
fvPatF vg vn (PatB (SPat _ vnameL, _) exprF) =
Map.adjust (\s1 -> Set.difference s1 $ Set.fromList vnameL)
vn $ fvExprF vg vn exprF
fvDefF :: VarGrh -> QName -> DefF -> VarGrh
fvDefF vg vn (DefF vname frmL exprF) =
let vg' = Map.adjust
(\s1 -> Set.difference s1 $ Set.fromList $ vname:(frmsToNames frmL))
vname $ fvExprF (insertUnique vname Set.empty vg) vname exprF
in Map.insertWith Set.union vn
(lkUpSure vname vg') vg'
| Take an FL program and return a map that associates the defined
fvProgF :: ProgF -> VarGrh
fvProgF (Prog _ defFL) =
Map.delete pFV $
Map.adjust
(\s1 -> Set.difference s1 $ Set.fromList $ List.map defVarName defFL)
pFV $ List.foldl (\vg' -> fvDefF vg' pFV) Map.empty defFL
pFV :: QName
| Alpha - rename an FL expression using the given map associating
aRenameExprF :: Renamings -> ExprF -> ExprF
aRenameExprF ren exprF =
case exprF of
XF v -> XF . V $ Map.findWithDefault (nameOfV v) (nameOfV v) ren
ConF cName exprFL ->
ConF cName $ List.map (aRenameExprF ren) exprFL
FF v exprFL ci ->
FF (V $ Map.findWithDefault (nameOfV v) (nameOfV v) ren)
(List.map (aRenameExprF ren) exprFL) ci
ConstrF cstrName exprFL ->
ConstrF cstrName $ List.map (aRenameExprF ren) exprFL
CaseF depth exprF' vname patFL ->
let vname' = Map.findWithDefault vname vname ren in
CaseF depth (aRenameExprF ren exprF') vname' $
List.map (aRenamePatF ren) patFL
LamF depth vname exprF' ->
let vname' = Map.findWithDefault vname vname ren in
LamF depth vname' $ aRenameExprF ren exprF'
LetF depth defFL exprF' ->
let defFL' = List.map (aRenameDefF ren) defFL
in LetF depth defFL' $ aRenameExprF ren exprF'
| Alpha - rename an FL pattern using the given map associating
aRenamePatF :: Renamings -> PatF -> PatF
aRenamePatF ren (PatB (SPat cstrName vnameL, pI) exprF) =
PatB (SPat cstrName
(List.map (\vn -> Map.findWithDefault vn vn ren) vnameL), pI) $
aRenameExprF ren exprF
| Alpha - rename an FL definition using the given map associating
aRenameDefF :: Renamings -> DefF -> DefF
aRenameDefF ren (DefF vname frmL exprF) =
DefF (Map.findWithDefault vname vname ren)
(List.map
(\(Frm vn stc) -> Frm (Map.findWithDefault vn vn ren) stc)
frmL) $
aRenameExprF ren exprF
the extra parameters to be applied on them first and amend all
preApplyExprF :: VarGrh -> ExprF -> ExprF
preApplyExprF vg exprF =
case exprF of
XF v ->
let extVarsS = Map.findWithDefault Set.empty (nameOfV v) vg
in if Set.null extVarsS then exprF
else FF v (List.map (XF . V) $ Set.elems extVarsS) NoCI
ConF cName exprFL ->
ConF cName $ List.map (preApplyExprF vg) exprFL
FF v exprFL ci ->
let exprFL' = List.map (preApplyExprF vg) exprFL
extVarsS = Map.findWithDefault Set.empty (nameOfV v) vg
in if Set.null extVarsS then FF v exprFL' ci
else FF v ((List.map (XF . V) $ Set.elems extVarsS) ++ exprFL') ci
ConstrF cstrName exprFL ->
ConstrF cstrName $ List.map (preApplyExprF vg) exprFL
CaseF depth exprF' vname patFL ->
CaseF depth (preApplyExprF vg exprF') vname $
List.map (\(PatB sPat exprF'') ->
PatB sPat $ preApplyExprF vg exprF'')
patFL
LamF depth vname exprF' ->
LamF depth vname $ preApplyExprF vg exprF'
LetF depth defFL exprF' ->
let defFL' = List.map (preApplyDefF vg) defFL
in LetF depth defFL' $ preApplyExprF vg exprF'
the extra parameters to be applied on them first and amend all
preApplyDefF :: VarGrh -> DefF -> DefF
preApplyDefF vg (DefF vname frmL exprF) =
DefF vname frmL $ preApplyExprF vg exprF
the extra parameters to be applied on them first and amend all
preApplyProgF :: VarGrh -> ProgF -> ProgF
preApplyProgF vg (Prog dataL defFL) =
Prog dataL $ List.map (preApplyDefF vg) defFL
abstractDefWithFormals :: DefF -> [Frm] -> DefF
abstractDefWithFormals (DefF vname frmL exprF) frmL' =
let frmNameL' = frmsToNames frmL'
renFrmNameL' = List.map (\x -> procLName (\ln->ln ++ "_" ++ qName vname ++ "_Lifted") x)
frmNameL'
ren = Map.fromList $ List.zip frmNameL' renFrmNameL'
in aRenameDefF ren $ DefF vname (frmL'++frmL) exprF
| Add extra formals ( assumed lazy ) to FL definitions recursively .
abstractDefsDefF :: VarGrh -> DefF -> DefF
abstractDefsDefF vg (DefF vname frmL exprF) =
let mkFrm vn = Frm vn (defaultEvOrder False)
frmL' = List.map mkFrm $ Set.elems $ lkUpSure vname vg
in abstractDefWithFormals
(DefF vname frmL $ abstractDefsExprF vg exprF) frmL'
| Add extra formals to FL definitions recursively .
abstractDefsExprF :: VarGrh -> ExprF -> ExprF
abstractDefsExprF vg exprF =
case exprF of
XF _ -> exprF
ConF cName exprFL ->
ConF cName $ List.map (abstractDefsExprF vg) exprFL
ConstrF cstrName exprFL ->
ConstrF cstrName $ List.map (abstractDefsExprF vg) exprFL
FF v exprFL ci -> FF v (List.map (abstractDefsExprF vg) exprFL) ci
CaseF depth exprF' vname patFL ->
let abstractDefsPatF (PatB sPat exprF'') =
PatB sPat $ abstractDefsExprF vg exprF''
in CaseF depth (abstractDefsExprF vg exprF') vname $
List.map abstractDefsPatF patFL
LamF depth vname exprF' -> LamF depth vname $
abstractDefsExprF vg exprF'
LetF depth defFL exprF' ->
let defFL' = List.map (abstractDefsDefF vg) defFL
in LetF depth defFL' $ abstractDefsExprF vg exprF'
| Add extra formals to FL definitions recursively .
abstractDefsProgF :: VarGrh -> ProgF -> ProgF
abstractDefsProgF vg (Prog dataL defFL) =
Prog dataL $ List.map (abstractDefsDefF vg) defFL
| Take an expression and return the a tuple containing 1 ) all the
definitions that are nested in the original expression and 2 ) an
liftDefsExprF :: ExprF -> ([DefF], ExprF)
liftDefsExprF exprF =
case exprF of
XF _ -> ([], exprF)
ConF cName exprFL ->
let (defFLL, exprFL') = List.unzip $ List.map liftDefsExprF exprFL
in (List.concat defFLL, ConF cName exprFL')
ConstrF cstrName exprFL ->
let (defFLL, exprFL') = List.unzip $ List.map liftDefsExprF exprFL
in (List.concat defFLL, ConstrF cstrName exprFL')
FF v exprFL ci ->
let (defFLL, exprFL') = List.unzip $ List.map liftDefsExprF exprFL
in (List.concat defFLL, FF v exprFL' ci)
CaseF depth exprF' vname patFL ->
let liftDefsPatF (PatB sPat exprF'') =
let (defFL', exprF''') = liftDefsExprF exprF''
in (defFL', PatB sPat exprF''')
(defFLL, patFL') = List.unzip $ List.map liftDefsPatF patFL
(defFL, exprF'''') = liftDefsExprF exprF'
in (defFL ++ (List.concat defFLL), CaseF depth exprF'''' vname patFL')
LamF depth vname exprF' ->
let (defFL, exprF'') = liftDefsExprF exprF'
in (defFL, LamF depth vname exprF'')
LetF _ defFL exprF' ->
let (defFL', exprF'') = liftDefsExprF exprF'
defFL'' = List.concat $ List.map liftDefsDefF defFL
in (defFL'' ++ defFL', exprF'')
liftDefsDefF :: DefF -> [DefF]
liftDefsDefF (DefF vname frmL exprF) =
let (defFL, exprF') = liftDefsExprF exprF
in (DefF vname frmL exprF'):defFL
| Take an FL program and lift all definitions at top level .
liftDefsProgF :: ProgF -> ProgF
liftDefsProgF (Prog dataL defFL) =
let liftDefsDefF ( DefF vname frmL exprF ) =
in ( DefF vname frmL exprF'):defFL '
Prog dataL $ List.concat $ List.map liftDefsDefF defFL
definition bodies ( as described by ) .
* Note that normally : defnameS = = Set.fromList $ Map.keys vg
mkEquationsJ :: VarGrh -> Set QName -> EqnSys QName (EqE QName QName)
mkEquationsJ vg defnameS =
f vn fvS eqnSys = Map.insert vn
(Set.union
(Set.map (\vn' -> EqU vn') $
Set.intersection fvS defnameS) $
Set.map (\vn' -> EqV vn') $
Set.difference fvS defnameS)
eqnSys
in Map.foldWithKey f Map.empty vg
| Take an FL program and returned a corresponding lambda - lifted
FL program containing no abstractions and , more generally ,
with .
lambdaLiftProgF :: ProgF -> [QName] -> ProgF
lambdaLiftProgF p llExcluded =
let defFV = Map.map
(\s -> Set.difference s $
Set.fromList llExcluded)
$ fvProgF p
eqnSys = mkEquationsJ defFV $ Set.fromList $ Map.keys defFV
solvedEqnSys = Eqn.solveEqs eqnSys
solvedEqnSysV = Map.map (Set.map $ \(EqV x) -> x) solvedEqnSys
in liftDefsProgF $
abstractDefsProgF solvedEqnSysV $
preApplyProgF solvedEqnSysV p
| This is the entry point of the lambda - lifter . It takes an FL module and
lambdaLiftModF :: ModF -> ModF
lambdaLiftModF (Mod modName exports imports progF an ts) =
let importedNames = mergeImportFuns imports
vfnL = Map.keys importedNames
llExcluded = vfnL ++ cBuiltinFuncs
in Mod modName exports imports (lambdaLiftProgF progF llExcluded) an ts
| Runs the lambda lifter on a list of FL modules . Checks that the lifter
lambdaLiftMod :: Options -> ModF -> ModF
lambdaLiftMod opts modF =
let usesLifter = hasLs $ modProg modF
hasTSigs = Map.null $ modTAnnot modF
lliftedMod = lambdaLiftModF modF
lliftedModIfNotL =
if usesLifter && hasTSigs then
error "lambda-lifting doesn't support type signatures, use -gic-tc-nsig"
else
lliftedMod
in case optTC opts of
GHCTypeInf -> lliftedModIfNotL
GICTypeInf True -> lliftedModIfNotL
GICTypeInf False -> lliftedMod
|
a390afcbb5065e0e1e64915b2f9f9dac7f91940ac9cb54bb714305c615b651a9 | ocharles/haskell-opentracing | Main.hs | {-# language OverloadedStrings #-}
module Main where
import Web.Scotty
import Network.Wai.Handler.Warp
import Network.Wai.Middleware.OpenTracing
import Control.Monad.OpenTracing
import Jaeger
import qualified TestLib
main :: IO ()
main = do
t <-
openTracer TracerConfiguration { tracerServiceName = "test-exe" }
runTracingT TestLib.hello t
app <- scottyApp $
get "/:word" $ do
beam <- param "word"
html $ mconcat ["<h1>Scotty, ", beam, " me up!</h1>"]
run 3000 (openTracingMiddleware t app)
| null | https://raw.githubusercontent.com/ocharles/haskell-opentracing/8466a47b12fd5dbb7e9293c404c87e5f0222b285/test-exe/Main.hs | haskell | # language OverloadedStrings # |
module Main where
import Web.Scotty
import Network.Wai.Handler.Warp
import Network.Wai.Middleware.OpenTracing
import Control.Monad.OpenTracing
import Jaeger
import qualified TestLib
main :: IO ()
main = do
t <-
openTracer TracerConfiguration { tracerServiceName = "test-exe" }
runTracingT TestLib.hello t
app <- scottyApp $
get "/:word" $ do
beam <- param "word"
html $ mconcat ["<h1>Scotty, ", beam, " me up!</h1>"]
run 3000 (openTracingMiddleware t app)
|
bae1463f92aba966ccec992945bc0a25271a05d01ab844e68e86d3f817055c4f | runtimeverification/haskell-backend | Module.hs | |
Copyright : ( c ) Runtime Verification , 2019 - 2021
License : BSD-3 - Clause
Copyright : (c) Runtime Verification, 2019-2021
License : BSD-3-Clause
-}
module Kore.Syntax.Module (
ModuleName (..),
getModuleNameForError,
Module (..),
) where
import Data.Aeson (
FromJSON,
ToJSON,
)
import Data.Kind (
Type,
)
import Data.String (
IsString,
)
import Data.Text (
Text,
)
import Data.Text qualified as Text
import GHC.Generics qualified as GHC
import Generics.SOP qualified as SOP
import Kore.Attribute.Attributes
import Kore.Debug
import Kore.Unparser
import Prelude.Kore
import Pretty qualified
| ' ModuleName ' corresponds to the @module - name@ syntactic category from < -backend/blob/master/docs/kore-syntax.md#identifiers kore - syntax#identifiers > .
newtype ModuleName = ModuleName {getModuleName :: Text}
deriving stock (Eq, Ord, Show)
deriving stock (GHC.Generic)
deriving newtype (IsString, FromJSON, ToJSON)
deriving anyclass (Hashable, NFData)
deriving anyclass (SOP.Generic, SOP.HasDatatypeInfo)
deriving anyclass (Debug, Diff)
instance Unparse ModuleName where
unparse = Pretty.pretty . getModuleName
unparse2 = Pretty.pretty . getModuleName
getModuleNameForError :: ModuleName -> String
getModuleNameForError = Text.unpack . getModuleName
|A ' Module ' consists of a ' ModuleName ' a list of ' Sentence 's and some
' Attributes ' .
They correspond to the second , third and forth non - terminals of the @definition@
syntactic category from < -backend/blob/master/docs/kore-syntax.md#definition-modules kore - syntax#definition - modues > .
'Attributes'.
They correspond to the second, third and forth non-terminals of the @definition@
syntactic category from <-backend/blob/master/docs/kore-syntax.md#definition-modules kore-syntax#definition-modues>.
-}
data Module (sentence :: Type) = Module
{ moduleName :: !ModuleName
, moduleSentences :: ![sentence]
, moduleAttributes :: !Attributes
}
deriving stock (Eq, Ord, Show)
deriving stock (Functor, Foldable, Traversable)
deriving stock (GHC.Generic)
deriving anyclass (Hashable, NFData)
deriving anyclass (SOP.Generic, SOP.HasDatatypeInfo)
instance Debug sentence => Debug (Module sentence)
instance (Debug sentence, Diff sentence) => Diff (Module sentence)
instance Unparse sentence => Unparse (Module sentence) where
unparse
Module{moduleName, moduleSentences, moduleAttributes} =
(Pretty.vsep . catMaybes)
[ Just ("module" Pretty.<+> unparse moduleName)
, case moduleSentences of
[] -> Nothing
_ ->
(Just . Pretty.indent 4 . Pretty.vsep)
(unparse <$> moduleSentences)
, Just "endmodule"
, Just (unparse moduleAttributes)
]
unparse2
Module{moduleName, moduleSentences, moduleAttributes} =
(Pretty.vsep . catMaybes)
[ Just ("module" Pretty.<+> unparse2 moduleName)
, case moduleSentences of
[] -> Nothing
_ ->
(Just . Pretty.indent 4 . Pretty.vsep)
(unparse2 <$> moduleSentences)
, Just "endmodule"
, Just (unparse2 moduleAttributes)
]
| null | https://raw.githubusercontent.com/runtimeverification/haskell-backend/b74e9f8d5b88f4550145abf90d7fb3e69e072963/kore/src/Kore/Syntax/Module.hs | haskell | |
Copyright : ( c ) Runtime Verification , 2019 - 2021
License : BSD-3 - Clause
Copyright : (c) Runtime Verification, 2019-2021
License : BSD-3-Clause
-}
module Kore.Syntax.Module (
ModuleName (..),
getModuleNameForError,
Module (..),
) where
import Data.Aeson (
FromJSON,
ToJSON,
)
import Data.Kind (
Type,
)
import Data.String (
IsString,
)
import Data.Text (
Text,
)
import Data.Text qualified as Text
import GHC.Generics qualified as GHC
import Generics.SOP qualified as SOP
import Kore.Attribute.Attributes
import Kore.Debug
import Kore.Unparser
import Prelude.Kore
import Pretty qualified
| ' ModuleName ' corresponds to the @module - name@ syntactic category from < -backend/blob/master/docs/kore-syntax.md#identifiers kore - syntax#identifiers > .
newtype ModuleName = ModuleName {getModuleName :: Text}
deriving stock (Eq, Ord, Show)
deriving stock (GHC.Generic)
deriving newtype (IsString, FromJSON, ToJSON)
deriving anyclass (Hashable, NFData)
deriving anyclass (SOP.Generic, SOP.HasDatatypeInfo)
deriving anyclass (Debug, Diff)
instance Unparse ModuleName where
unparse = Pretty.pretty . getModuleName
unparse2 = Pretty.pretty . getModuleName
getModuleNameForError :: ModuleName -> String
getModuleNameForError = Text.unpack . getModuleName
|A ' Module ' consists of a ' ModuleName ' a list of ' Sentence 's and some
' Attributes ' .
They correspond to the second , third and forth non - terminals of the @definition@
syntactic category from < -backend/blob/master/docs/kore-syntax.md#definition-modules kore - syntax#definition - modues > .
'Attributes'.
They correspond to the second, third and forth non-terminals of the @definition@
syntactic category from <-backend/blob/master/docs/kore-syntax.md#definition-modules kore-syntax#definition-modues>.
-}
data Module (sentence :: Type) = Module
{ moduleName :: !ModuleName
, moduleSentences :: ![sentence]
, moduleAttributes :: !Attributes
}
deriving stock (Eq, Ord, Show)
deriving stock (Functor, Foldable, Traversable)
deriving stock (GHC.Generic)
deriving anyclass (Hashable, NFData)
deriving anyclass (SOP.Generic, SOP.HasDatatypeInfo)
instance Debug sentence => Debug (Module sentence)
instance (Debug sentence, Diff sentence) => Diff (Module sentence)
instance Unparse sentence => Unparse (Module sentence) where
unparse
Module{moduleName, moduleSentences, moduleAttributes} =
(Pretty.vsep . catMaybes)
[ Just ("module" Pretty.<+> unparse moduleName)
, case moduleSentences of
[] -> Nothing
_ ->
(Just . Pretty.indent 4 . Pretty.vsep)
(unparse <$> moduleSentences)
, Just "endmodule"
, Just (unparse moduleAttributes)
]
unparse2
Module{moduleName, moduleSentences, moduleAttributes} =
(Pretty.vsep . catMaybes)
[ Just ("module" Pretty.<+> unparse2 moduleName)
, case moduleSentences of
[] -> Nothing
_ ->
(Just . Pretty.indent 4 . Pretty.vsep)
(unparse2 <$> moduleSentences)
, Just "endmodule"
, Just (unparse2 moduleAttributes)
]
|
|
4163aca4d186832644b9fd42d30f6d72ea441d100a50e50409755aeb0a38dbb2 | nikita-volkov/rerebase | Internal.hs | module Data.ByteString.Lazy.Internal
(
module Rebase.Data.ByteString.Lazy.Internal
)
where
import Rebase.Data.ByteString.Lazy.Internal
| null | https://raw.githubusercontent.com/nikita-volkov/rerebase/25895e6d8b0c515c912c509ad8dd8868780a74b6/library/Data/ByteString/Lazy/Internal.hs | haskell | module Data.ByteString.Lazy.Internal
(
module Rebase.Data.ByteString.Lazy.Internal
)
where
import Rebase.Data.ByteString.Lazy.Internal
|
|
e1d821cc0fb4a1332e885b8aa08e3f17e29e267085ec3f2474c95c456f4f1c9a | na4zagin3/satyrographos | store.ml | open Core
type library_name = string
exception RegisteredAlready of library_name
type store = {
library_dir: string;
}
(* Basic operations *)
let list reg = FileUtil.ls reg.library_dir |> List.map ~f:FilePath.basename |> List.sort ~compare:String.compare
let directory reg name = Filename.concat reg.library_dir name
let mem reg name = directory reg name |> FileUtil.test FileUtil.Is_dir
let remove_multiple reg names =
List.map ~f:(directory reg) names |> FileUtil.rm ~force:Force ~recurse:true
let remove reg name =
remove_multiple reg [name]
let add_dir reg name dir =
let add_dir reg name dir = FileUtil.cp ~recurse:true [dir] (directory reg name) in
match mem reg name, FileUtil.test FileUtil.Is_dir dir with
| true, _ -> remove reg name; add_dir reg name dir
| _, false -> failwith (dir ^ " is not a directory")
| false, true -> add_dir reg name dir
(* | false, false -> FileUtil.cp ~recurse:true [dir] (directory reg name) *)
let add_library reg name library =
if mem reg name
then failwith (Printf.sprintf "%s is already registered. Please remove it first." name)
else Library.write_dir (directory reg name) library
let initialize libraries_dir =
FileUtil.mkdir ~parent:true libraries_dir
let read library_dir = {
library_dir = library_dir;
}
(* Tests *)
open Core
let create_new_reg dir =
let registry_dir = Filename.concat dir "registry" in
initialize registry_dir;
read registry_dir
let with_new_reg f =
let dir = Filename_unix.temp_dir "Satyrographos" "Store" in
protect ~f:(fun () -> create_new_reg dir |> f) ~finally:(fun () -> FileUtil.rm ~force:Force ~recurse:true [dir])
let test_library_list ~expect reg =
[%test_result: string list] ~expect (list reg)
let test_library_content ~expect reg p =
[%test_result: string list] ~expect begin
let target_dir = directory reg p in
target_dir |> FileUtil.ls |> List.map ~f:(FilePath.make_relative target_dir)
end
let%test "store: initialize" = with_new_reg (fun _ -> true)
let%test "store: list: empty" = with_new_reg begin fun reg ->
match list reg with [] -> true | _ :: _ -> false
end
let%test_unit "store: add empty dir" = with_new_reg begin fun reg ->
let dir = Filename_unix.temp_dir "Satyrographos" "Library" in
add_dir reg "a" dir;
test_library_list ~expect:["a"] reg;
[%test_result: bool] ~expect:true (mem reg "a");
[%test_result: bool] ~expect:false (mem reg "b");
[%test_result: bool] ~expect:true (directory reg "a" |> FileUtil.(test Is_dir ))
end
let%test_unit "store: add nonempty dir" = with_new_reg begin fun reg ->
let dir = Filename_unix.temp_dir "Satyrographos" "Library" in
FilePath.concat dir "c" |> FileUtil.touch;
add_dir reg "a" dir;
test_library_list ~expect:["a"] reg;
[%test_result: bool] ~expect:true (mem reg "a");
[%test_result: bool] ~expect:false (mem reg "b");
[%test_result: bool] ~expect:true (directory reg "a" |> FileUtil.(test Is_dir));
test_library_content ~expect:["c"] reg "a"
end
let%test_unit "store: add nonempty dir twice" = with_new_reg begin fun reg ->
let dir1 = Filename_unix.temp_dir "Satyrographos" "Library" in
FilePath.concat dir1 "c" |> FileUtil.touch;
add_dir reg "a" dir1;
test_library_list ~expect:["a"] reg;
test_library_content ~expect:["c"] reg "a";
let dir2 = Filename_unix.temp_dir "Satyrographos" "Library" in
FilePath.concat dir2 "d" |> FileUtil.touch;
add_dir reg "a" dir2;
test_library_list ~expect:["a"] reg;
test_library_content ~expect:["d"] reg "a"
end
let%test_unit "store: added dir must be copied" = with_new_reg begin fun reg ->
let dir = Filename_unix.temp_dir "Satyrographos" "Library" in
FilePath.concat dir "c" |> FileUtil.touch;
add_dir reg "a" dir;
test_library_list ~expect:["a"] reg;
test_library_content ~expect:["c"] reg "a";
FilePath.concat dir "d" |> FileUtil.touch;
test_library_list ~expect:["a"] reg;
test_library_content ~expect:["c"] reg "a";
FileUtil.rm [FilePath.concat dir "c"];
test_library_list ~expect:["a"] reg;
test_library_content ~expect:["c"] reg "a";
end
let%test_unit "store: add the same directory twice with different contents" = with_new_reg begin fun reg ->
let dir = Filename_unix.temp_dir "Satyrographos" "Library" in
FilePath.concat dir "c" |> FileUtil.touch;
add_dir reg "a" dir;
test_library_list ~expect:["a"] reg;
test_library_content ~expect:["c"] reg "a";
FilePath.concat dir "d" |> FileUtil.touch;
FileUtil.rm [FilePath.concat dir "c"];
add_dir reg "b" dir;
test_library_list ~expect:["a"; "b"] reg;
test_library_content ~expect:["c"] reg "a";
test_library_content ~expect:["d"] reg "b";
end
| null | https://raw.githubusercontent.com/na4zagin3/satyrographos/d2943bac9659d20746720ab36ebe11ae59203d32/src/store.ml | ocaml | Basic operations
| false, false -> FileUtil.cp ~recurse:true [dir] (directory reg name)
Tests | open Core
type library_name = string
exception RegisteredAlready of library_name
type store = {
library_dir: string;
}
let list reg = FileUtil.ls reg.library_dir |> List.map ~f:FilePath.basename |> List.sort ~compare:String.compare
let directory reg name = Filename.concat reg.library_dir name
let mem reg name = directory reg name |> FileUtil.test FileUtil.Is_dir
let remove_multiple reg names =
List.map ~f:(directory reg) names |> FileUtil.rm ~force:Force ~recurse:true
let remove reg name =
remove_multiple reg [name]
let add_dir reg name dir =
let add_dir reg name dir = FileUtil.cp ~recurse:true [dir] (directory reg name) in
match mem reg name, FileUtil.test FileUtil.Is_dir dir with
| true, _ -> remove reg name; add_dir reg name dir
| _, false -> failwith (dir ^ " is not a directory")
| false, true -> add_dir reg name dir
let add_library reg name library =
if mem reg name
then failwith (Printf.sprintf "%s is already registered. Please remove it first." name)
else Library.write_dir (directory reg name) library
let initialize libraries_dir =
FileUtil.mkdir ~parent:true libraries_dir
let read library_dir = {
library_dir = library_dir;
}
open Core
let create_new_reg dir =
let registry_dir = Filename.concat dir "registry" in
initialize registry_dir;
read registry_dir
let with_new_reg f =
let dir = Filename_unix.temp_dir "Satyrographos" "Store" in
protect ~f:(fun () -> create_new_reg dir |> f) ~finally:(fun () -> FileUtil.rm ~force:Force ~recurse:true [dir])
let test_library_list ~expect reg =
[%test_result: string list] ~expect (list reg)
let test_library_content ~expect reg p =
[%test_result: string list] ~expect begin
let target_dir = directory reg p in
target_dir |> FileUtil.ls |> List.map ~f:(FilePath.make_relative target_dir)
end
let%test "store: initialize" = with_new_reg (fun _ -> true)
let%test "store: list: empty" = with_new_reg begin fun reg ->
match list reg with [] -> true | _ :: _ -> false
end
let%test_unit "store: add empty dir" = with_new_reg begin fun reg ->
let dir = Filename_unix.temp_dir "Satyrographos" "Library" in
add_dir reg "a" dir;
test_library_list ~expect:["a"] reg;
[%test_result: bool] ~expect:true (mem reg "a");
[%test_result: bool] ~expect:false (mem reg "b");
[%test_result: bool] ~expect:true (directory reg "a" |> FileUtil.(test Is_dir ))
end
let%test_unit "store: add nonempty dir" = with_new_reg begin fun reg ->
let dir = Filename_unix.temp_dir "Satyrographos" "Library" in
FilePath.concat dir "c" |> FileUtil.touch;
add_dir reg "a" dir;
test_library_list ~expect:["a"] reg;
[%test_result: bool] ~expect:true (mem reg "a");
[%test_result: bool] ~expect:false (mem reg "b");
[%test_result: bool] ~expect:true (directory reg "a" |> FileUtil.(test Is_dir));
test_library_content ~expect:["c"] reg "a"
end
let%test_unit "store: add nonempty dir twice" = with_new_reg begin fun reg ->
let dir1 = Filename_unix.temp_dir "Satyrographos" "Library" in
FilePath.concat dir1 "c" |> FileUtil.touch;
add_dir reg "a" dir1;
test_library_list ~expect:["a"] reg;
test_library_content ~expect:["c"] reg "a";
let dir2 = Filename_unix.temp_dir "Satyrographos" "Library" in
FilePath.concat dir2 "d" |> FileUtil.touch;
add_dir reg "a" dir2;
test_library_list ~expect:["a"] reg;
test_library_content ~expect:["d"] reg "a"
end
let%test_unit "store: added dir must be copied" = with_new_reg begin fun reg ->
let dir = Filename_unix.temp_dir "Satyrographos" "Library" in
FilePath.concat dir "c" |> FileUtil.touch;
add_dir reg "a" dir;
test_library_list ~expect:["a"] reg;
test_library_content ~expect:["c"] reg "a";
FilePath.concat dir "d" |> FileUtil.touch;
test_library_list ~expect:["a"] reg;
test_library_content ~expect:["c"] reg "a";
FileUtil.rm [FilePath.concat dir "c"];
test_library_list ~expect:["a"] reg;
test_library_content ~expect:["c"] reg "a";
end
let%test_unit "store: add the same directory twice with different contents" = with_new_reg begin fun reg ->
let dir = Filename_unix.temp_dir "Satyrographos" "Library" in
FilePath.concat dir "c" |> FileUtil.touch;
add_dir reg "a" dir;
test_library_list ~expect:["a"] reg;
test_library_content ~expect:["c"] reg "a";
FilePath.concat dir "d" |> FileUtil.touch;
FileUtil.rm [FilePath.concat dir "c"];
add_dir reg "b" dir;
test_library_list ~expect:["a"; "b"] reg;
test_library_content ~expect:["c"] reg "a";
test_library_content ~expect:["d"] reg "b";
end
|
9187c0123bf05c9097997a57d52da1244079e085b5d40c4e6e4e5ad8c529a4ac | puzza007/openpoker | fixed_limit.erl | Copyright ( C ) 2005 Wager Labs , SA
%%%
This file is part of OpenPoker .
%%%
OpenPoker 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 library; if not, write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
%%%
Please visit or contact
%%% at for more information.
-module(fixed_limit).
-behaviour(gen_server).
-export([init/1, handle_call/3, handle_cast/2,
handle_info/2, terminate/2, code_change/3]).
-export([start/2, start_link/2, stop/1, test/0]).
-include("test.hrl").
-include("common.hrl").
-include("proto.hrl").
-record(fixed_limit, {
high,
low
}).
new(Low, High) ->
#fixed_limit {
high = High,
low = Low
}.
start(Low, High) ->
gen_server:start(fixed_limit, [Low, High], []).
start_link(Low, High) ->
gen_server:start_link(fixed_limit, [Low, High], []).
init([Low, High]) ->
process_flag(trap_exit, true),
{ok, new(Low, High)}.
stop(LimitRef) ->
gen_server:cast(LimitRef, stop).
terminate(_Reason, _Limit) ->
ok.
handle_cast(stop, Limit) ->
{stop, normal, Limit};
handle_cast(Event, Limit) ->
error_logger:info_report([{module, ?MODULE},
{line, ?LINE},
{self, self()},
{message, Event}]),
{noreply, Limit}.
handle_call('INFO', _From, Limit) ->
{reply, {?LT_FIXED_LIMIT,
Limit#fixed_limit.low,
Limit#fixed_limit.high}, Limit};
handle_call({'RAISE SIZE', _Game, _Player, Stage}, _From, Limit) ->
{reply, raise_size(Limit, Stage), Limit};
handle_call('BLINDS', _From, Limit) ->
{reply, {Limit#fixed_limit.low div 2, Limit#fixed_limit.low}, Limit};
handle_call(Event, From, Limit) ->
error_logger:info_report([{module, ?MODULE},
{line, ?LINE},
{self, self()},
{message, Event},
{from, From}]),
{noreply, Limit}.
handle_info({'EXIT', _Pid, _Reason}, Limit) ->
%% child exit?
{noreply, Limit};
handle_info(Info, Limit) ->
error_logger:info_report([{module, ?MODULE},
{line, ?LINE},
{self, self()},
{message, Info}]),
{noreply, Limit}.
code_change(_OldVsn, Limit, _Extra) ->
{ok, Limit}.
raise_size(Limit, Stage) when ?GS_PREFLOP =:= Stage;
?GS_FLOP =:= Stage ->
{Limit#fixed_limit.low, Limit#fixed_limit.low};
raise_size(Limit, _Stage) ->
{Limit#fixed_limit.high, Limit#fixed_limit.high}.
test() ->
ok.
| null | https://raw.githubusercontent.com/puzza007/openpoker/bbd7158c81ba869f9f04ac7295c9fb7ea099a9d2/src/fixed_limit.erl | erlang |
modify it under the terms of the GNU General Public
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.
License along with this library; if not, write to the Free Software
at for more information.
child exit? | Copyright ( C ) 2005 Wager Labs , SA
This file is part of OpenPoker .
OpenPoker is free software ; you can redistribute it and/or
License as published by the Free Software Foundation ; either
version 2 of the License , or ( at your option ) any later version .
You should have received a copy of the GNU General Public
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
Please visit or contact
-module(fixed_limit).
-behaviour(gen_server).
-export([init/1, handle_call/3, handle_cast/2,
handle_info/2, terminate/2, code_change/3]).
-export([start/2, start_link/2, stop/1, test/0]).
-include("test.hrl").
-include("common.hrl").
-include("proto.hrl").
-record(fixed_limit, {
high,
low
}).
new(Low, High) ->
#fixed_limit {
high = High,
low = Low
}.
start(Low, High) ->
gen_server:start(fixed_limit, [Low, High], []).
start_link(Low, High) ->
gen_server:start_link(fixed_limit, [Low, High], []).
init([Low, High]) ->
process_flag(trap_exit, true),
{ok, new(Low, High)}.
stop(LimitRef) ->
gen_server:cast(LimitRef, stop).
terminate(_Reason, _Limit) ->
ok.
handle_cast(stop, Limit) ->
{stop, normal, Limit};
handle_cast(Event, Limit) ->
error_logger:info_report([{module, ?MODULE},
{line, ?LINE},
{self, self()},
{message, Event}]),
{noreply, Limit}.
handle_call('INFO', _From, Limit) ->
{reply, {?LT_FIXED_LIMIT,
Limit#fixed_limit.low,
Limit#fixed_limit.high}, Limit};
handle_call({'RAISE SIZE', _Game, _Player, Stage}, _From, Limit) ->
{reply, raise_size(Limit, Stage), Limit};
handle_call('BLINDS', _From, Limit) ->
{reply, {Limit#fixed_limit.low div 2, Limit#fixed_limit.low}, Limit};
handle_call(Event, From, Limit) ->
error_logger:info_report([{module, ?MODULE},
{line, ?LINE},
{self, self()},
{message, Event},
{from, From}]),
{noreply, Limit}.
handle_info({'EXIT', _Pid, _Reason}, Limit) ->
{noreply, Limit};
handle_info(Info, Limit) ->
error_logger:info_report([{module, ?MODULE},
{line, ?LINE},
{self, self()},
{message, Info}]),
{noreply, Limit}.
code_change(_OldVsn, Limit, _Extra) ->
{ok, Limit}.
raise_size(Limit, Stage) when ?GS_PREFLOP =:= Stage;
?GS_FLOP =:= Stage ->
{Limit#fixed_limit.low, Limit#fixed_limit.low};
raise_size(Limit, _Stage) ->
{Limit#fixed_limit.high, Limit#fixed_limit.high}.
test() ->
ok.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.