_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 |
|---|---|---|---|---|---|---|---|---|
8308442616135a8cbdb8ba3770a1ff4d23fb61af4721a952c5418baba5f3821f | flexsurfer/conduitrn | api.cljs | (ns conduit.api
(:require [clojure.string :as string]))
(def api-url "")
(defn endpoint
"Concat any params to api-url separated by /"
[& params]
(string/join "/" (concat [api-url] params)))
(defn auth-header
"Get user token and format for API authorization"
[db]
(when-let [token (get-in db [:user :token])]
{"Authorization" (str "Token " token)})) | null | https://raw.githubusercontent.com/flexsurfer/conduitrn/e0c4860a24a7413b08d807b3aa3f1a76d93a444b/src/conduit/api.cljs | clojure | (ns conduit.api
(:require [clojure.string :as string]))
(def api-url "")
(defn endpoint
"Concat any params to api-url separated by /"
[& params]
(string/join "/" (concat [api-url] params)))
(defn auth-header
"Get user token and format for API authorization"
[db]
(when-let [token (get-in db [:user :token])]
{"Authorization" (str "Token " token)})) | |
9bd13d588098535e6e1f363d9460a0d85d517a0767c4b7f70b37bb620996fe38 | bomberstudios/mtasc | as3parse.ml |
* This file is part of SwfLib
* Copyright ( c)2004 - 2006
*
* 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. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* This file is part of SwfLib
* Copyright (c)2004-2006 Nicolas Cannasse
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open As3
let parse_idents = true
let parse_namespaces = true && parse_idents
let parse_ns_sets = true && parse_namespaces
let parse_names = true && parse_ns_sets
let parse_mtypes = true && parse_names
let parse_metadata = true && parse_mtypes
let parse_classes = true && parse_metadata
let parse_statics = true && parse_classes
let parse_inits = true && parse_statics
let parse_functions = true && parse_inits
let parse_bytecode = true && parse_functions
let magic_index (i : int) : 'a index =
Obj.magic i
let magic_index_nz (i : int) : 'a index_nz =
Obj.magic i
let index (t : 'a array) (i : int) : 'a index =
if i <= 0 || i - 1 >= Array.length t then assert false;
magic_index i
let index_opt t i =
if i = 0 then
None
else
Some (index t i)
let index_nz (t : 'a array) (i : int) : 'a index_nz =
if i < 0 || i >= Array.length t then assert false;
Obj.magic i
let index_int (i : 'a index) =
(Obj.magic i : int)
let index_nz_int (i : 'a index_nz) =
(Obj.magic i : int)
let iget (t : 'a array) (i : 'a index) : 'a =
t.(index_int i - 1)
let no_nz (i : 'a index_nz) : 'a index =
Obj.magic ((Obj.magic i) + 1)
(* ************************************************************************ *)
(* LENGTH *)
let as3_empty_index ctx =
let empty_index = ref 0 in
try
Array.iteri (fun i x -> if x = "" then begin empty_index := (i + 1); raise Exit; end) ctx.as3_idents;
if parse_idents then assert false;
magic_index 0
with Exit ->
index ctx.as3_idents (!empty_index)
let as3_int_length i =
if Int32.compare (Int32.shift_right_logical i 28) 0l > 0 then
5
else if Int32.compare (Int32.shift_right i 21) 0l > 0 then
4
else if Int32.compare (Int32.shift_right i 14) 0l > 0 then
3
else if Int32.compare (Int32.shift_right i 7) 0l > 0 then
2
else
1
let as3_uint_length i =
as3_int_length i
let sum f l =
List.fold_left (fun acc n -> acc + f n) 0 l
let int_length i =
as3_int_length (Int32.of_int i)
let idx_length i =
int_length (index_int i)
let idx_length_nz i =
int_length (index_nz_int i)
let idx_opt_length = function
| None -> int_length 0
| Some i -> idx_length i
let as3_ident_length s =
let n = String.length s in
n + int_length n
let as3_namespace_length ei = function
| A3NStaticProtected o
| A3NPrivate o ->
1 + (match o with None -> int_length 0 | Some n -> idx_length n)
| A3NPublic o
| A3NInternal o ->
1 + idx_length (match o with None -> ei | Some n -> n)
| A3NExplicit n
| A3NNamespace n
| A3NProtected n ->
1 + idx_length n
let as3_ns_set_length l =
int_length (List.length l) + sum idx_length l
let rec as3_name_length t =
1 +
match t with
| A3MMultiName (id,r) ->
idx_opt_length id + idx_length r
| A3MName (id,r) ->
idx_length r + idx_length id
| A3MRuntimeName i ->
idx_length i
| A3MRuntimeNameLate ->
0
| A3MMultiNameLate idx ->
idx_length idx
| A3MAttrib n ->
as3_name_length n - 1
| A3MParams (id,pl) ->
idx_length id + 1 + (sum idx_length pl)
let as3_value_length extra = function
| A3VNone -> if extra then 2 else 1
| A3VNull | A3VBool _ -> 2
| A3VString s -> 1 + idx_length s
| A3VInt s -> 1 + idx_length s
| A3VUInt s -> 1 + idx_length s
| A3VFloat s -> 1 + idx_length s
| A3VNamespace (_,s) -> 1 + idx_length s
let as3_method_type_length m =
1 +
idx_opt_length m.mt3_ret +
sum idx_opt_length m.mt3_args +
idx_opt_length m.mt3_debug_name +
1 +
(match m.mt3_dparams with None -> 0 | Some l -> 1 + sum (as3_value_length true) l) +
(match m.mt3_pnames with None -> 0 | Some l -> sum idx_opt_length l)
let list_length f l =
match Array.length l with
| 0 -> int_length 0
| n ->
Array.fold_left (fun acc x -> acc + f x) (int_length (n + 1)) l
let list2_length f l =
Array.fold_left (fun acc x -> acc + f x) (int_length (Array.length l)) l
let as3_field_length f =
idx_length f.f3_name +
1 +
int_length f.f3_slot +
(match f.f3_kind with
| A3FMethod m ->
idx_length_nz m.m3_type
| A3FClass c ->
idx_length_nz c
| A3FFunction id ->
idx_length_nz id
| A3FVar v ->
idx_opt_length v.v3_type + as3_value_length false v.v3_value) +
match f.f3_metas with
| None -> 0
| Some l -> list2_length idx_length_nz l
let as3_class_length c =
idx_length c.cl3_name +
idx_opt_length c.cl3_super +
1 +
(match c.cl3_namespace with None -> 0 | Some r -> idx_length r) +
list2_length idx_length c.cl3_implements +
idx_length_nz c.cl3_construct +
list2_length as3_field_length c.cl3_fields
let as3_static_length s =
idx_length_nz s.st3_method +
list2_length as3_field_length s.st3_fields
let as3_metadata_length m =
idx_length m.meta3_name +
list2_length (fun (i1,i2) -> idx_opt_length i1 + idx_length i2) m.meta3_data
let as3_try_catch_length t =
int_length t.tc3_start +
int_length t.tc3_end +
int_length t.tc3_handle +
idx_opt_length t.tc3_type +
idx_opt_length t.tc3_name
let as3_function_length f =
let clen = Array.fold_left (fun acc op -> acc + As3code.length op) 0 f.fun3_code in
idx_length_nz f.fun3_id +
int_length f.fun3_stack_size +
int_length f.fun3_nregs +
int_length f.fun3_init_scope +
int_length f.fun3_max_scope +
int_length clen +
clen +
list2_length as3_try_catch_length f.fun3_trys +
list2_length as3_field_length f.fun3_locals
let as3_length ctx =
let ei = as3_empty_index ctx in
String.length ctx.as3_unknown +
4 +
list_length as3_int_length ctx.as3_ints +
list_length as3_uint_length ctx.as3_uints +
list_length (fun _ -> 8) ctx.as3_floats
+ if parse_idents then list_length as3_ident_length ctx.as3_idents
+ if parse_namespaces then list_length (as3_namespace_length ei) ctx.as3_namespaces
+ if parse_ns_sets then list_length as3_ns_set_length ctx.as3_nsets
+ if parse_names then list_length as3_name_length ctx.as3_names
+ if parse_mtypes then list2_length as3_method_type_length ctx.as3_method_types
+ if parse_metadata then list2_length as3_metadata_length ctx.as3_metadatas
+ if parse_classes then list2_length as3_class_length ctx.as3_classes
+ if parse_statics then Array.fold_left (fun acc x -> acc + as3_static_length x) 0 ctx.as3_statics
+ if parse_inits then list2_length as3_static_length ctx.as3_inits
+ if parse_functions then list2_length as3_function_length ctx.as3_functions
else 0 else 0 else 0 else 0 else 0 else 0 else 0 else 0 else 0 else 0
(* ************************************************************************ *)
(* PARSING *)
let read_as3_int ch =
let a = IO.read_byte ch in
if a < 128 then
Int32.of_int a
else
let a = a land 127 in
let b = IO.read_byte ch in
if b < 128 then
Int32.of_int ((b lsl 7) lor a)
else
let b = b land 127 in
let c = IO.read_byte ch in
if c < 128 then
Int32.of_int ((c lsl 14) lor (b lsl 7) lor a)
else
let c = c land 127 in
let d = IO.read_byte ch in
if d < 128 then
Int32.of_int ((d lsl 21) lor (c lsl 14) lor (b lsl 7) lor a)
else
let d = d land 127 in
let e = IO.read_byte ch in
if e > 15 then assert false;
let small = Int32.of_int ((d lsl 21) lor (c lsl 14) lor (b lsl 7) lor a) in
let big = Int32.shift_left (Int32.of_int e) 28 in
Int32.logor big small
let read_as3_uint ch =
read_as3_int ch
let read_int ch =
Int32.to_int (read_as3_int ch)
let read_ident ch =
IO.nread ch (read_int ch)
let read_namespace idents ch =
let k = IO.read_byte ch in
let p = index_opt idents (read_int ch) in
match k with
| 0x05 ->
A3NPrivate p
| 0x08 ->
(match p with
| None -> assert false
| Some idx -> A3NNamespace idx)
| 0x16 ->
(match p with
| None -> assert false
| Some p when iget idents p = "" -> A3NPublic None
| _ -> A3NPublic p)
| 0x17 ->
(match p with
| None -> assert false
| Some p when iget idents p = "" -> A3NInternal None
| _ -> A3NInternal p)
| 0x18 ->
(match p with
| None -> assert false
| Some idx -> A3NProtected idx)
| 0x19 ->
(match p with
| None -> assert false
| Some idx -> A3NExplicit idx)
| 0x1A ->
A3NStaticProtected p
| _ ->
assert false
let read_ns_set namespaces ch =
let rec loop n =
if n = 0 then
[]
else
let r = index namespaces (read_int ch) in
r :: loop (n - 1)
in
loop (IO.read_byte ch)
let rec read_name ctx ?k ch =
let k = (match k with None -> IO.read_byte ch | Some k -> k) in
match k with
| 0x07 ->
let ns = index ctx.as3_namespaces (read_int ch) in
let id = index ctx.as3_idents (read_int ch) in
(* both ns and id can be 0 <=> '*' *)
A3MName (id,ns)
| 0x09 ->
let id = index_opt ctx.as3_idents (read_int ch) in
let ns = index ctx.as3_nsets (read_int ch) in
A3MMultiName (id,ns)
| 0x0D ->
A3MAttrib (read_name ctx ~k:0x07 ch)
| 0x0E ->
A3MAttrib (read_name ctx ~k:0x09 ch)
| 0x0F ->
let id = index ctx.as3_idents (read_int ch) in
A3MRuntimeName id
| 0x10 ->
A3MAttrib (read_name ctx ~k:0x0F ch)
| 0x11 ->
A3MRuntimeNameLate
| 0x12 ->
A3MAttrib (read_name ctx ~k:0x11 ch)
| 0x1B ->
let ns = index ctx.as3_nsets (read_int ch) in
A3MMultiNameLate ns
| 0x1C ->
A3MAttrib (read_name ctx ~k:0x1B ch)
| 0x1D ->
let rec loop n =
if n = 0 then
[]
else
let name = magic_index (read_int ch) in
name :: loop (n - 1)
in
let id = magic_index (read_int ch) in
A3MParams (id,loop (IO.read_byte ch))
| n ->
prerr_endline (string_of_int n);
assert false
let read_value ctx ch extra =
let idx = read_int ch in
if idx = 0 then begin
if extra && IO.read_byte ch <> 0 then assert false;
A3VNone
end else match IO.read_byte ch with
| 0x01 ->
A3VString (index ctx.as3_idents idx)
| 0x03 ->
A3VInt (index ctx.as3_ints idx)
| 0x04 ->
A3VUInt (index ctx.as3_uints idx)
| 0x06 ->
A3VFloat (index ctx.as3_floats idx)
| 0x08 | 0x16 | 0x17 | 0x18 | 0x19 | 0x1A | 0x05 as n->
A3VNamespace (n,index ctx.as3_namespaces idx)
| 0x0A ->
if idx <> 0x0A then assert false;
A3VBool false
| 0x0B ->
if idx <> 0x0B then assert false;
A3VBool true
| 0x0C ->
if idx <> 0x0C then assert false;
A3VNull
| _ ->
assert false
let read_method_type ctx ch =
let nargs = IO.read_byte ch in
let tret = index_opt ctx.as3_names (read_int ch) in
let targs = Array.to_list (Array.init nargs (fun _ -> index_opt ctx.as3_names (read_int ch))) in
let dname = index_opt ctx.as3_idents (read_int ch) in
let flags = IO.read_byte ch in
let dparams = (if flags land 0x08 <> 0 then
Some (Array.to_list (Array.init (IO.read_byte ch) (fun _ -> read_value ctx ch true)))
else
None
) in
let pnames = (if flags land 0x80 <> 0 then
Some (Array.to_list (Array.init nargs (fun _ -> index_opt ctx.as3_idents (read_int ch))))
else
None
) in
{
mt3_ret = tret;
mt3_args = targs;
mt3_var_args = flags land 0x04 <> 0;
mt3_native = flags land 0x20 <> 0;
mt3_new_block = flags land 0x02 <> 0;
mt3_debug_name = dname;
mt3_dparams = dparams;
mt3_pnames = pnames;
mt3_arguments_defined = flags land 0x01 <> 0;
mt3_uses_dxns = flags land 0x40 <> 0;
mt3_unused_flag = flags land 0x10 <> 0;
}
let read_list ch f =
match read_int ch with
| 0 -> [||]
| n -> Array.init (n - 1) (fun _ -> f ch)
let read_list2 ch f =
Array.init (read_int ch) (fun _ -> f ch)
let read_field ctx ch =
let name = index ctx.as3_names (read_int ch) in
let kind = IO.read_byte ch in
let has_meta = kind land 0x40 <> 0 in
let slot = read_int ch in
let kind = (match kind land 0xF with
| 0x00 | 0x06 ->
let t = index_opt ctx.as3_names (read_int ch) in
let value = read_value ctx ch false in
A3FVar {
v3_type = t;
v3_value = value;
v3_const = kind = 0x06;
}
| 0x02
| 0x03
| 0x01 ->
let meth = index_nz ctx.as3_method_types (read_int ch) in
let final = kind land 0x10 <> 0 in
let override = kind land 0x20 <> 0 in
A3FMethod {
m3_type = meth;
m3_final = final;
m3_override = override;
m3_kind = (match kind land 0xF with 0x01 -> MK3Normal | 0x02 -> MK3Getter | 0x03 -> MK3Setter | _ -> assert false);
}
| 0x04 ->
let c = index_nz ctx.as3_classes (read_int ch) in
A3FClass c
| 0x05 ->
let f = index_nz ctx.as3_method_types (read_int ch) in
A3FFunction f
| _ ->
assert false
) in
let metas = (if has_meta then
Some (read_list2 ch (fun _ -> index_nz ctx.as3_metadatas (read_int ch)))
else
None
) in
{
f3_name = name;
f3_slot = slot;
f3_kind = kind;
f3_metas = metas;
}
let read_class ctx ch =
let name = index ctx.as3_names (read_int ch) in
let csuper = index_opt ctx.as3_names (read_int ch) in
let flags = IO.read_byte ch in
let namespace =
if flags land 8 <> 0 then
let r = index ctx.as3_namespaces (read_int ch) in
Some r
else
None
in
let impls = read_list2 ch (fun _ -> index ctx.as3_names (read_int ch)) in
let construct = index_nz ctx.as3_method_types (read_int ch) in
let fields = read_list2 ch (read_field ctx) in
{
cl3_name = name;
cl3_super = csuper;
cl3_sealed = (flags land 1) <> 0;
cl3_final = (flags land 2) <> 0;
cl3_interface = (flags land 4) <> 0;
cl3_namespace = namespace;
cl3_implements = impls;
cl3_construct = construct;
cl3_fields = fields;
}
let read_static ctx ch =
let meth = index_nz ctx.as3_method_types (read_int ch) in
let fields = read_list2 ch (read_field ctx) in
{
st3_method = meth;
st3_fields = fields;
}
let read_metadata ctx ch =
let name = index ctx.as3_idents (read_int ch) in
let data = read_list2 ch (fun _ -> index_opt ctx.as3_idents (read_int ch)) in
let data = Array.map (fun i1 -> i1 , index ctx.as3_idents (read_int ch)) data in
{
meta3_name = name;
meta3_data = data;
}
let read_try_catch ctx ch =
let start = read_int ch in
let pend = read_int ch in
let handle = read_int ch in
let t = index_opt ctx.as3_names (read_int ch) in
let name = index_opt ctx.as3_names (read_int ch) in
{
tc3_start = start;
tc3_end = pend;
tc3_handle = handle;
tc3_type = t;
tc3_name = name;
}
let read_function ctx ch =
let id = index_nz ctx.as3_method_types (read_int ch) in
let ss = read_int ch in
let nregs = read_int ch in
let init_scope = read_int ch in
let max_scope = read_int ch in
let size = read_int ch in
let code = if parse_bytecode then As3code.parse ch size else Array.init size (fun _ -> A3Unk (IO.read ch)) in
let trys = read_list2 ch (read_try_catch ctx) in
let local_funs = read_list2 ch (read_field ctx) in
{
fun3_id = id;
fun3_stack_size = ss;
fun3_nregs = nregs;
fun3_init_scope = init_scope;
fun3_max_scope = max_scope;
fun3_code = code;
fun3_trys = trys;
fun3_locals = local_funs;
}
let header_magic = 0x002E0010
let parse ch len =
let data = IO.nread ch len in
let ch = IO.input_string data in
if IO.read_i32 ch <> header_magic then assert false;
let ints = read_list ch read_as3_int in
let uints = read_list ch read_as3_uint in
let floats = read_list ch IO.read_double in
let idents = (if parse_idents then read_list ch read_ident else [||]) in
let namespaces = (if parse_namespaces then read_list ch (read_namespace idents) else [||]) in
let nsets = (if parse_ns_sets then read_list ch (read_ns_set namespaces) else [||]) in
let ctx = {
as3_ints = ints;
as3_uints = uints;
as3_floats = floats;
as3_idents = idents;
as3_namespaces = namespaces;
as3_nsets = nsets;
as3_names = [||];
as3_method_types = [||];
as3_metadatas = [||];
as3_classes = [||];
as3_statics = [||];
as3_inits = [||];
as3_functions = [||];
as3_unknown = "";
} in
if parse_names then ctx.as3_names <- read_list ch (read_name ctx);
if parse_mtypes then ctx.as3_method_types <- read_list2 ch (read_method_type ctx);
if parse_metadata then ctx.as3_metadatas <- read_list2 ch (read_metadata ctx);
if parse_classes then ctx.as3_classes <- read_list2 ch (read_class ctx);
if parse_statics then ctx.as3_statics <- Array.map (fun _ -> read_static ctx ch) ctx.as3_classes;
if parse_inits then ctx.as3_inits <- read_list2 ch (read_static ctx);
if parse_functions then ctx.as3_functions <- read_list2 ch (read_function ctx);
ctx.as3_unknown <- IO.read_all ch;
if parse_functions && String.length ctx.as3_unknown <> 0 then assert false;
let len2 = as3_length ctx in
if len2 <> len then begin Printf.printf "%d != %d" len len2; assert false; end;
ctx
(* ************************************************************************ *)
(* WRITING *)
let write_as3_int ch i =
let e = Int32.to_int (Int32.shift_right_logical i 28) in
let d = Int32.to_int (Int32.shift_right i 21) land 0x7F in
let c = Int32.to_int (Int32.shift_right i 14) land 0x7F in
let b = Int32.to_int (Int32.shift_right i 7) land 0x7F in
let a = Int32.to_int (Int32.logand i 0x7Fl) in
if b <> 0 || c <> 0 || d <> 0 || e <> 0 then begin
IO.write_byte ch (a lor 0x80);
if c <> 0 || d <> 0 || e <> 0 then begin
IO.write_byte ch (b lor 0x80);
if d <> 0 || e <> 0 then begin
IO.write_byte ch (c lor 0x80);
if e <> 0 then begin
IO.write_byte ch (d lor 0x80);
IO.write_byte ch e;
end else
IO.write_byte ch d;
end else
IO.write_byte ch c;
end else
IO.write_byte ch b;
end else
IO.write_byte ch a
let write_as3_uint = write_as3_int
let write_int ch i =
write_as3_int ch (Int32.of_int i)
let write_index ch n =
write_int ch (index_int n)
let write_index_nz ch n =
write_int ch (index_nz_int n)
let write_index_opt ch = function
| None -> write_int ch 0
| Some n -> write_index ch n
let write_as3_ident ch id =
write_int ch (String.length id);
IO.nwrite ch id
let write_namespace empty_index ch = function
| A3NPrivate n ->
IO.write_byte ch 0x05;
(match n with
| None -> write_int ch 0
| Some n -> write_index ch n);
| A3NPublic n ->
IO.write_byte ch 0x16;
(match n with
| None -> write_index ch empty_index
| Some n -> write_index ch n);
| A3NInternal n ->
IO.write_byte ch 0x17;
(match n with
| None -> write_index ch empty_index
| Some n -> write_index ch n);
| A3NProtected n ->
IO.write_byte ch 0x18;
write_index ch n
| A3NNamespace n ->
IO.write_byte ch 0x08;
write_index ch n
| A3NExplicit n ->
IO.write_byte ch 0x19;
write_index ch n
| A3NStaticProtected n ->
IO.write_byte ch 0x1A;
(match n with
| None -> write_int ch 0
| Some n -> write_index ch n)
let write_rights ch l =
IO.write_byte ch (List.length l);
List.iter (write_index ch) l
let rec write_name ch ?k x =
let b n = match k with None -> n | Some v -> v in
match x with
| A3MMultiName (id,r) ->
IO.write_byte ch (b 0x09);
write_index_opt ch id;
write_index ch r;
| A3MName (id,r) ->
IO.write_byte ch (b 0x07);
write_index ch r;
write_index ch id
| A3MRuntimeName i ->
IO.write_byte ch (b 0x0F);
write_index ch i
| A3MRuntimeNameLate ->
IO.write_byte ch (b 0x11);
| A3MMultiNameLate id ->
IO.write_byte ch (b 0x1B);
write_index ch id
| A3MAttrib n ->
write_name ch ~k:(match n with
| A3MName _ -> 0x0D
| A3MMultiName _ -> 0x0E
| A3MRuntimeName _ -> 0x10
| A3MRuntimeNameLate -> 0x12
| A3MMultiNameLate _ -> 0x1C
| A3MAttrib _ | A3MParams _ -> assert false
) n
| A3MParams (id,pl) ->
IO.write_byte ch (b 0x1D);
write_index ch id;
IO.write_byte ch (List.length pl);
List.iter (write_index ch) pl
let write_value ch extra v =
match v with
| A3VNone ->
IO.write_byte ch 0x00;
if extra then IO.write_byte ch 0x00;
| A3VNull ->
IO.write_byte ch 0x0C;
IO.write_byte ch 0x0C;
| A3VBool b ->
IO.write_byte ch (if b then 0x0B else 0x0A);
IO.write_byte ch (if b then 0x0B else 0x0A);
| A3VString s ->
write_index ch s;
IO.write_byte ch 0x01;
| A3VInt s ->
write_index ch s;
IO.write_byte ch 0x03;
| A3VUInt s ->
write_index ch s;
IO.write_byte ch 0x04;
| A3VFloat s ->
write_index ch s;
IO.write_byte ch 0x06
| A3VNamespace (n,s) ->
write_index ch s;
IO.write_byte ch n
let write_method_type ch m =
let nargs = List.length m.mt3_args in
IO.write_byte ch nargs;
write_index_opt ch m.mt3_ret;
List.iter (write_index_opt ch) m.mt3_args;
write_index_opt ch m.mt3_debug_name;
let flags =
(if m.mt3_arguments_defined then 0x01 else 0) lor
(if m.mt3_new_block then 0x02 else 0) lor
(if m.mt3_var_args then 0x04 else 0) lor
(if m.mt3_dparams <> None then 0x08 else 0) lor
(if m.mt3_unused_flag then 0x10 else 0) lor
(if m.mt3_native then 0x20 else 0) lor
(if m.mt3_uses_dxns then 0x40 else 0) lor
(if m.mt3_pnames <> None then 0x80 else 0)
in
IO.write_byte ch flags;
(match m.mt3_dparams with
| None -> ()
| Some l ->
IO.write_byte ch (List.length l);
List.iter (write_value ch true) l);
match m.mt3_pnames with
| None -> ()
| Some l ->
if List.length l <> nargs then assert false;
List.iter (write_index_opt ch) l
let write_list ch f l =
match Array.length l with
| 0 -> IO.write_byte ch 0
| n ->
write_int ch (n + 1);
Array.iter (f ch) l
let write_list2 ch f l =
write_int ch (Array.length l);
Array.iter (f ch) l
let write_field ch f =
write_index ch f.f3_name;
let flags = (if f.f3_metas <> None then 0x40 else 0) in
(match f.f3_kind with
| A3FMethod m ->
let base = (match m.m3_kind with MK3Normal -> 0x01 | MK3Getter -> 0x02 | MK3Setter -> 0x03) in
let flags = flags lor (if m.m3_final then 0x10 else 0) lor (if m.m3_override then 0x20 else 0) in
IO.write_byte ch (base lor flags);
write_int ch f.f3_slot;
write_index_nz ch m.m3_type;
| A3FClass c ->
IO.write_byte ch (0x04 lor flags);
write_int ch f.f3_slot;
write_index_nz ch c
| A3FFunction i ->
IO.write_byte ch (0x05 lor flags);
write_int ch f.f3_slot;
write_index_nz ch i
| A3FVar v ->
IO.write_byte ch (flags lor (if v.v3_const then 0x06 else 0x00));
write_int ch f.f3_slot;
write_index_opt ch v.v3_type;
write_value ch false v.v3_value);
match f.f3_metas with
| None -> ()
| Some l ->
write_list2 ch write_index_nz l
let write_class ch c =
write_index ch c.cl3_name;
write_index_opt ch c.cl3_super;
let flags =
(if c.cl3_sealed then 1 else 0) lor
(if c.cl3_final then 2 else 0) lor
(if c.cl3_interface then 4 else 0) lor
(if c.cl3_namespace <> None then 8 else 0)
in
IO.write_byte ch flags;
(match c.cl3_namespace with
| None -> ()
| Some r -> write_index ch r);
write_list2 ch write_index c.cl3_implements;
write_index_nz ch c.cl3_construct;
write_list2 ch write_field c.cl3_fields
let write_static ch s =
write_index_nz ch s.st3_method;
write_list2 ch write_field s.st3_fields
let write_metadata ch m =
write_index ch m.meta3_name;
write_list2 ch (fun _ (i1,_) -> write_index_opt ch i1) m.meta3_data;
Array.iter (fun (_,i2) -> write_index ch i2) m.meta3_data
let write_try_catch ch t =
write_int ch t.tc3_start;
write_int ch t.tc3_end;
write_int ch t.tc3_handle;
write_index_opt ch t.tc3_type;
write_index_opt ch t.tc3_name
let write_function ch f =
write_index_nz ch f.fun3_id;
write_int ch f.fun3_stack_size;
write_int ch f.fun3_nregs;
write_int ch f.fun3_init_scope;
write_int ch f.fun3_max_scope;
let clen = Array.fold_left (fun acc op -> acc + As3code.length op) 0 f.fun3_code in
write_int ch clen;
Array.iter (As3code.write ch) f.fun3_code;
write_list2 ch write_try_catch f.fun3_trys;
write_list2 ch write_field f.fun3_locals
let write ch1 ctx =
let ch = IO.output_string() in
let empty_index = as3_empty_index ctx in
IO.write_i32 ch header_magic;
write_list ch write_as3_int ctx.as3_ints;
write_list ch write_as3_uint ctx.as3_uints;
write_list ch IO.write_double ctx.as3_floats;
if parse_idents then write_list ch write_as3_ident ctx.as3_idents;
if parse_namespaces then write_list ch (write_namespace empty_index) ctx.as3_namespaces;
if parse_ns_sets then write_list ch write_rights ctx.as3_nsets;
if parse_names then write_list ch (write_name ?k:None) ctx.as3_names;
if parse_mtypes then write_list2 ch write_method_type ctx.as3_method_types;
if parse_metadata then write_list2 ch write_metadata ctx.as3_metadatas;
if parse_classes then write_list2 ch write_class ctx.as3_classes;
if parse_statics then Array.iter (write_static ch) ctx.as3_statics;
if parse_inits then write_list2 ch write_static ctx.as3_inits;
if parse_functions then write_list2 ch write_function ctx.as3_functions;
IO.nwrite ch ctx.as3_unknown;
let str = IO.close_out ch in
IO.nwrite ch1 str
(* ************************************************************************ *)
DUMP
let dump_code_size = ref true
let ident_str ctx i =
iget ctx.as3_idents i
let namespace_str ctx i =
match iget ctx.as3_namespaces i with
| A3NPrivate None -> "private"
| A3NPrivate (Some n) -> "private:" ^ ident_str ctx n
| A3NPublic None -> "public"
| A3NPublic (Some n) -> "public:" ^ ident_str ctx n
| A3NInternal None -> "internal"
| A3NInternal (Some n) -> "internal:" ^ ident_str ctx n
| A3NProtected n -> "protected:" ^ ident_str ctx n
| A3NExplicit n -> "explicit:" ^ ident_str ctx n
| A3NStaticProtected None -> "static_protected"
| A3NStaticProtected (Some n) -> "static_protectec:" ^ ident_str ctx n
| A3NNamespace n -> "namespace:" ^ ident_str ctx n
let ns_set_str ctx i =
let l = iget ctx.as3_nsets i in
String.concat " " (List.map (fun r -> namespace_str ctx r) l)
let rec name_str ctx kind t =
let rec loop = function
| A3MName (id,r) -> Printf.sprintf "%s %s%s" (namespace_str ctx r) kind (ident_str ctx id)
| A3MMultiName (id,r) -> Printf.sprintf "[%s %s%s]" (ns_set_str ctx r) kind (match id with None -> "NO" | Some i -> ident_str ctx i)
| A3MRuntimeName id -> Printf.sprintf "'%s'" (ident_str ctx id)
| A3MRuntimeNameLate -> "RTLATE"
| A3MMultiNameLate id -> Printf.sprintf "late:(%s)" (ns_set_str ctx id)
| A3MAttrib n -> "attrib " ^ loop n
| A3MParams (id,pl) -> Printf.sprintf "%s<%s>" (name_str ctx kind id) (String.concat "," (List.map (name_str ctx kind) pl))
in
loop (iget ctx.as3_names t)
let value_str ctx v =
match v with
| A3VNone -> "<none>"
| A3VNull -> "null"
| A3VString s -> "\"" ^ ident_str ctx s ^ "\""
| A3VBool b -> if b then "true" else "false"
| A3VInt s -> Printf.sprintf "%ld" (iget ctx.as3_ints s)
| A3VUInt s -> Printf.sprintf "%ld" (iget ctx.as3_uints s)
| A3VFloat s -> Printf.sprintf "%f" (iget ctx.as3_floats s)
| A3VNamespace (_,s) -> "ns::" ^ namespace_str ctx s
let metadata_str ctx i =
let m = iget ctx.as3_metadatas i in
let data = List.map (fun (i1,i2) -> Printf.sprintf "%s=\"%s\"" (match i1 with None -> "NO" | Some i -> ident_str ctx i) (ident_str ctx i2)) (Array.to_list m.meta3_data) in
Printf.sprintf "%s(%s)" (ident_str ctx m.meta3_name) (String.concat ", " data)
let method_str ?(infos=false) ctx m =
let m = iget ctx.as3_method_types m in
let pcount = ref 0 in
Printf.sprintf "%s(%s%s)%s"
(if m.mt3_native then " native " else "")
(String.concat ", " (List.map (fun a ->
let id = (match m.mt3_pnames with
| None -> "p" ^ string_of_int !pcount
| Some l ->
match List.nth l !pcount with
| None -> "p" ^ string_of_int !pcount
| Some i -> ident_str ctx i
) in
let p = (match a with None -> id | Some t -> name_str ctx (id ^ " : ") t) in
let p = (match m.mt3_dparams with
| None -> p
| Some l ->
let vargs = List.length m.mt3_args - List.length l in
if !pcount >= vargs then
let v = List.nth l (!pcount - vargs) in
p ^ " = " ^ value_str ctx v
else
p
) in
incr pcount;
p
) m.mt3_args))
(if m.mt3_var_args then " ..." else "")
(match m.mt3_ret with None -> "" | Some t -> " : " ^ name_str ctx "" t)
^ (if infos then begin
let name = (match m.mt3_debug_name with None -> "" | Some idx -> Printf.sprintf " '%s'" (ident_str ctx idx)) in
Printf.sprintf "%s blk:%b args:%b dxns:%b%s" name m.mt3_new_block m.mt3_arguments_defined m.mt3_uses_dxns (if m.mt3_unused_flag then " SPECIAL-FLAG" else "")
end else "")
let dump_field ctx ch stat f =
( match f.f3_metas with
| None - > ( )
| Some l - > Array.iter ( fun i - > IO.printf ch " [ % s]\n " ( metadata_str ctx ( no_nz i ) ) ) l ) ;
| None -> ()
| Some l -> Array.iter (fun i -> IO.printf ch " [%s]\n" (metadata_str ctx (no_nz i))) l);
*) IO.printf ch " ";
if stat then IO.printf ch "static ";
(match f.f3_kind with
| A3FVar v ->
IO.printf ch "%s" (name_str ctx (if v.v3_const then "const " else "var ") f.f3_name);
(match v.v3_type with
| None -> ()
| Some id -> IO.printf ch " : %s" (name_str ctx "" id));
if v.v3_value <> A3VNone then IO.printf ch " = %s" (value_str ctx v.v3_value);
| A3FClass c ->
let c = iget ctx.as3_classes (no_nz c) in
IO.printf ch "%s = %s" (name_str ctx "CLASS " c.cl3_name) (name_str ctx "class " f.f3_name);
| A3FFunction id ->
IO.printf ch "%s = %s" (method_str ~infos:false ctx (no_nz id)) (name_str ctx "method " f.f3_name);
| A3FMethod m ->
if m.m3_final then IO.printf ch "final ";
if m.m3_override then IO.printf ch "override ";
let k = "function " ^ (match m.m3_kind with
| MK3Normal -> ""
| MK3Getter -> "get "
| MK3Setter -> "set "
) in
IO.printf ch "%s%s #%d" (name_str ctx k f.f3_name) (method_str ctx (no_nz m.m3_type)) (index_nz_int m.m3_type);
);
if f.f3_slot <> 0 then IO.printf ch " = [SLOT:%d]" f.f3_slot;
IO.printf ch ";\n"
let dump_class ctx ch idx c =
let st = if parse_statics then ctx.as3_statics.(idx) else { st3_method = magic_index_nz (-1); st3_fields = [||] } in
if not c.cl3_sealed then IO.printf ch "dynamic ";
if c.cl3_final then IO.printf ch "final ";
(match c.cl3_namespace with
| None -> ()
| Some r -> IO.printf ch "%s " (namespace_str ctx r));
let kind = (if c.cl3_interface then "interface " else "class ") in
IO.printf ch "%s " (name_str ctx kind c.cl3_name);
(match c.cl3_super with
| None -> ()
| Some s -> IO.printf ch "extends %s " (name_str ctx "" s));
(match Array.to_list c.cl3_implements with
| [] -> ()
| l ->
IO.printf ch "implements %s " (String.concat ", " (List.map (fun i -> name_str ctx "" i) l)));
IO.printf ch "{\n";
Array.iter (dump_field ctx ch false) c.cl3_fields;
Array.iter (dump_field ctx ch true) st.st3_fields;
IO.printf ch "} constructor#%d statics#%d\n\n" (index_nz_int c.cl3_construct) (index_nz_int st.st3_method)
let dump_init ctx ch idx s =
IO.printf ch "init #%d {\n" (index_nz_int s.st3_method);
Array.iter (dump_field ctx ch false) s.st3_fields;
IO.printf ch "}\n\n"
let dump_try_catch ctx ch t =
IO.printf ch " try %d %d %d (%s) (%s)\n"
t.tc3_start t.tc3_end t.tc3_handle
(match t.tc3_type with None -> "*" | Some idx -> name_str ctx "" idx)
(match t.tc3_name with None -> "NO" | Some idx -> name_str ctx "" idx)
let dump_function ctx ch idx f =
IO.printf ch "function #%d %s\n" (index_nz_int f.fun3_id) (method_str ~infos:true ctx (no_nz f.fun3_id));
IO.printf ch " stack:%d nregs:%d scope:%d-%d\n" f.fun3_stack_size f.fun3_nregs f.fun3_init_scope f.fun3_max_scope;
Array.iter (dump_field ctx ch false) f.fun3_locals;
Array.iter (dump_try_catch ctx ch) f.fun3_trys;
let pos = ref 0 in
Array.iter (fun op ->
IO.printf ch "%4d %s\n" !pos (As3code.dump ctx op);
if !dump_code_size then pos := !pos + As3code.length op else incr pos;
) f.fun3_code;
IO.printf ch "\n"
let dump_ident ctx ch idx _ =
IO.printf ch "I%d = %s\n" (idx + 1) (ident_str ctx (index ctx.as3_idents (idx + 1)))
let dump_namespace ctx ch idx _ =
IO.printf ch "N%d = %s\n" (idx + 1) (namespace_str ctx (index ctx.as3_namespaces (idx + 1)))
let dump_ns_set ctx ch idx _ =
IO.printf ch "S%d = %s\n" (idx + 1) (ns_set_str ctx (index ctx.as3_nsets (idx + 1)))
let dump_name ctx ch idx _ =
IO.printf ch "T%d = %s\n" (idx + 1) (name_str ctx "" (index ctx.as3_names (idx + 1)))
let dump_method_type ctx ch idx _ =
IO.printf ch "M%d = %s\n" (idx + 1) (method_str ~infos:true ctx (index ctx.as3_method_types (idx + 1)))
let dump_metadata ctx ch idx _ =
IO.printf ch "D%d = %s\n" (idx + 1) (metadata_str ctx (index ctx.as3_metadatas (idx + 1)))
let dump_int ctx ch idx i =
IO.printf ch "INT %d = 0x%lX\n" (idx + 1) i
let dump_float ctx ch idx f =
IO.printf ch "FLOAT %d = %f\n" (idx + 1) f
let dump ch ctx id =
(match id with
| None -> IO.printf ch "\n---------------- AS3 -------------------------\n\n";
| Some (id,f) -> IO.printf ch "\n---------------- AS3 %s [%d] -----------------\n\n" f id);
Array.iteri ( dump_int ctx ch ) ctx.as3_ints ;
Array.iteri ( dump_float ctx ch ) ctx.as3_floats ;
Array.iteri ( dump_ident ctx ch ) ctx.as3_idents ;
IO.printf ch " \n " ;
Array.iteri ( dump_namespace ctx ch ) ctx.as3_namespaces ;
IO.printf ch " \n " ;
Array.iteri ( dump_ns_set ctx ch ) ctx.as3_nsets ;
IO.printf ch " \n " ;
Array.iteri ( dump_name ctx ch ) ctx.as3_names ;
IO.printf ch " \n " ;
Array.iteri (dump_float ctx ch) ctx.as3_floats;
Array.iteri (dump_ident ctx ch) ctx.as3_idents;
IO.printf ch "\n";
Array.iteri (dump_namespace ctx ch) ctx.as3_namespaces;
IO.printf ch "\n";
Array.iteri (dump_ns_set ctx ch) ctx.as3_nsets;
IO.printf ch "\n";
Array.iteri (dump_name ctx ch) ctx.as3_names;
IO.printf ch "\n"; *)
Array.iteri ( dump_metadata ctx ch ) ctx.as3_metadatas ;
Array.iteri (dump_class ctx ch) ctx.as3_classes;
Array.iteri (dump_init ctx ch) ctx.as3_inits;
Array.iteri (dump_function ctx ch) ctx.as3_functions;
IO.printf ch "\n"
;;
As3code.f_int_length := int_length;
As3code.f_int_read := read_int;
As3code.f_int_write := write_int;
| null | https://raw.githubusercontent.com/bomberstudios/mtasc/d7c2441310248776aa89d60f9c8f98d539bfe8de/src/swflib/as3parse.ml | ocaml | ************************************************************************
LENGTH
************************************************************************
PARSING
both ns and id can be 0 <=> '*'
************************************************************************
WRITING
************************************************************************ |
* This file is part of SwfLib
* Copyright ( c)2004 - 2006
*
* 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. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* This file is part of SwfLib
* Copyright (c)2004-2006 Nicolas Cannasse
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open As3
let parse_idents = true
let parse_namespaces = true && parse_idents
let parse_ns_sets = true && parse_namespaces
let parse_names = true && parse_ns_sets
let parse_mtypes = true && parse_names
let parse_metadata = true && parse_mtypes
let parse_classes = true && parse_metadata
let parse_statics = true && parse_classes
let parse_inits = true && parse_statics
let parse_functions = true && parse_inits
let parse_bytecode = true && parse_functions
let magic_index (i : int) : 'a index =
Obj.magic i
let magic_index_nz (i : int) : 'a index_nz =
Obj.magic i
let index (t : 'a array) (i : int) : 'a index =
if i <= 0 || i - 1 >= Array.length t then assert false;
magic_index i
let index_opt t i =
if i = 0 then
None
else
Some (index t i)
let index_nz (t : 'a array) (i : int) : 'a index_nz =
if i < 0 || i >= Array.length t then assert false;
Obj.magic i
let index_int (i : 'a index) =
(Obj.magic i : int)
let index_nz_int (i : 'a index_nz) =
(Obj.magic i : int)
let iget (t : 'a array) (i : 'a index) : 'a =
t.(index_int i - 1)
let no_nz (i : 'a index_nz) : 'a index =
Obj.magic ((Obj.magic i) + 1)
let as3_empty_index ctx =
let empty_index = ref 0 in
try
Array.iteri (fun i x -> if x = "" then begin empty_index := (i + 1); raise Exit; end) ctx.as3_idents;
if parse_idents then assert false;
magic_index 0
with Exit ->
index ctx.as3_idents (!empty_index)
let as3_int_length i =
if Int32.compare (Int32.shift_right_logical i 28) 0l > 0 then
5
else if Int32.compare (Int32.shift_right i 21) 0l > 0 then
4
else if Int32.compare (Int32.shift_right i 14) 0l > 0 then
3
else if Int32.compare (Int32.shift_right i 7) 0l > 0 then
2
else
1
let as3_uint_length i =
as3_int_length i
let sum f l =
List.fold_left (fun acc n -> acc + f n) 0 l
let int_length i =
as3_int_length (Int32.of_int i)
let idx_length i =
int_length (index_int i)
let idx_length_nz i =
int_length (index_nz_int i)
let idx_opt_length = function
| None -> int_length 0
| Some i -> idx_length i
let as3_ident_length s =
let n = String.length s in
n + int_length n
let as3_namespace_length ei = function
| A3NStaticProtected o
| A3NPrivate o ->
1 + (match o with None -> int_length 0 | Some n -> idx_length n)
| A3NPublic o
| A3NInternal o ->
1 + idx_length (match o with None -> ei | Some n -> n)
| A3NExplicit n
| A3NNamespace n
| A3NProtected n ->
1 + idx_length n
let as3_ns_set_length l =
int_length (List.length l) + sum idx_length l
let rec as3_name_length t =
1 +
match t with
| A3MMultiName (id,r) ->
idx_opt_length id + idx_length r
| A3MName (id,r) ->
idx_length r + idx_length id
| A3MRuntimeName i ->
idx_length i
| A3MRuntimeNameLate ->
0
| A3MMultiNameLate idx ->
idx_length idx
| A3MAttrib n ->
as3_name_length n - 1
| A3MParams (id,pl) ->
idx_length id + 1 + (sum idx_length pl)
let as3_value_length extra = function
| A3VNone -> if extra then 2 else 1
| A3VNull | A3VBool _ -> 2
| A3VString s -> 1 + idx_length s
| A3VInt s -> 1 + idx_length s
| A3VUInt s -> 1 + idx_length s
| A3VFloat s -> 1 + idx_length s
| A3VNamespace (_,s) -> 1 + idx_length s
let as3_method_type_length m =
1 +
idx_opt_length m.mt3_ret +
sum idx_opt_length m.mt3_args +
idx_opt_length m.mt3_debug_name +
1 +
(match m.mt3_dparams with None -> 0 | Some l -> 1 + sum (as3_value_length true) l) +
(match m.mt3_pnames with None -> 0 | Some l -> sum idx_opt_length l)
let list_length f l =
match Array.length l with
| 0 -> int_length 0
| n ->
Array.fold_left (fun acc x -> acc + f x) (int_length (n + 1)) l
let list2_length f l =
Array.fold_left (fun acc x -> acc + f x) (int_length (Array.length l)) l
let as3_field_length f =
idx_length f.f3_name +
1 +
int_length f.f3_slot +
(match f.f3_kind with
| A3FMethod m ->
idx_length_nz m.m3_type
| A3FClass c ->
idx_length_nz c
| A3FFunction id ->
idx_length_nz id
| A3FVar v ->
idx_opt_length v.v3_type + as3_value_length false v.v3_value) +
match f.f3_metas with
| None -> 0
| Some l -> list2_length idx_length_nz l
let as3_class_length c =
idx_length c.cl3_name +
idx_opt_length c.cl3_super +
1 +
(match c.cl3_namespace with None -> 0 | Some r -> idx_length r) +
list2_length idx_length c.cl3_implements +
idx_length_nz c.cl3_construct +
list2_length as3_field_length c.cl3_fields
let as3_static_length s =
idx_length_nz s.st3_method +
list2_length as3_field_length s.st3_fields
let as3_metadata_length m =
idx_length m.meta3_name +
list2_length (fun (i1,i2) -> idx_opt_length i1 + idx_length i2) m.meta3_data
let as3_try_catch_length t =
int_length t.tc3_start +
int_length t.tc3_end +
int_length t.tc3_handle +
idx_opt_length t.tc3_type +
idx_opt_length t.tc3_name
let as3_function_length f =
let clen = Array.fold_left (fun acc op -> acc + As3code.length op) 0 f.fun3_code in
idx_length_nz f.fun3_id +
int_length f.fun3_stack_size +
int_length f.fun3_nregs +
int_length f.fun3_init_scope +
int_length f.fun3_max_scope +
int_length clen +
clen +
list2_length as3_try_catch_length f.fun3_trys +
list2_length as3_field_length f.fun3_locals
let as3_length ctx =
let ei = as3_empty_index ctx in
String.length ctx.as3_unknown +
4 +
list_length as3_int_length ctx.as3_ints +
list_length as3_uint_length ctx.as3_uints +
list_length (fun _ -> 8) ctx.as3_floats
+ if parse_idents then list_length as3_ident_length ctx.as3_idents
+ if parse_namespaces then list_length (as3_namespace_length ei) ctx.as3_namespaces
+ if parse_ns_sets then list_length as3_ns_set_length ctx.as3_nsets
+ if parse_names then list_length as3_name_length ctx.as3_names
+ if parse_mtypes then list2_length as3_method_type_length ctx.as3_method_types
+ if parse_metadata then list2_length as3_metadata_length ctx.as3_metadatas
+ if parse_classes then list2_length as3_class_length ctx.as3_classes
+ if parse_statics then Array.fold_left (fun acc x -> acc + as3_static_length x) 0 ctx.as3_statics
+ if parse_inits then list2_length as3_static_length ctx.as3_inits
+ if parse_functions then list2_length as3_function_length ctx.as3_functions
else 0 else 0 else 0 else 0 else 0 else 0 else 0 else 0 else 0 else 0
let read_as3_int ch =
let a = IO.read_byte ch in
if a < 128 then
Int32.of_int a
else
let a = a land 127 in
let b = IO.read_byte ch in
if b < 128 then
Int32.of_int ((b lsl 7) lor a)
else
let b = b land 127 in
let c = IO.read_byte ch in
if c < 128 then
Int32.of_int ((c lsl 14) lor (b lsl 7) lor a)
else
let c = c land 127 in
let d = IO.read_byte ch in
if d < 128 then
Int32.of_int ((d lsl 21) lor (c lsl 14) lor (b lsl 7) lor a)
else
let d = d land 127 in
let e = IO.read_byte ch in
if e > 15 then assert false;
let small = Int32.of_int ((d lsl 21) lor (c lsl 14) lor (b lsl 7) lor a) in
let big = Int32.shift_left (Int32.of_int e) 28 in
Int32.logor big small
let read_as3_uint ch =
read_as3_int ch
let read_int ch =
Int32.to_int (read_as3_int ch)
let read_ident ch =
IO.nread ch (read_int ch)
let read_namespace idents ch =
let k = IO.read_byte ch in
let p = index_opt idents (read_int ch) in
match k with
| 0x05 ->
A3NPrivate p
| 0x08 ->
(match p with
| None -> assert false
| Some idx -> A3NNamespace idx)
| 0x16 ->
(match p with
| None -> assert false
| Some p when iget idents p = "" -> A3NPublic None
| _ -> A3NPublic p)
| 0x17 ->
(match p with
| None -> assert false
| Some p when iget idents p = "" -> A3NInternal None
| _ -> A3NInternal p)
| 0x18 ->
(match p with
| None -> assert false
| Some idx -> A3NProtected idx)
| 0x19 ->
(match p with
| None -> assert false
| Some idx -> A3NExplicit idx)
| 0x1A ->
A3NStaticProtected p
| _ ->
assert false
let read_ns_set namespaces ch =
let rec loop n =
if n = 0 then
[]
else
let r = index namespaces (read_int ch) in
r :: loop (n - 1)
in
loop (IO.read_byte ch)
let rec read_name ctx ?k ch =
let k = (match k with None -> IO.read_byte ch | Some k -> k) in
match k with
| 0x07 ->
let ns = index ctx.as3_namespaces (read_int ch) in
let id = index ctx.as3_idents (read_int ch) in
A3MName (id,ns)
| 0x09 ->
let id = index_opt ctx.as3_idents (read_int ch) in
let ns = index ctx.as3_nsets (read_int ch) in
A3MMultiName (id,ns)
| 0x0D ->
A3MAttrib (read_name ctx ~k:0x07 ch)
| 0x0E ->
A3MAttrib (read_name ctx ~k:0x09 ch)
| 0x0F ->
let id = index ctx.as3_idents (read_int ch) in
A3MRuntimeName id
| 0x10 ->
A3MAttrib (read_name ctx ~k:0x0F ch)
| 0x11 ->
A3MRuntimeNameLate
| 0x12 ->
A3MAttrib (read_name ctx ~k:0x11 ch)
| 0x1B ->
let ns = index ctx.as3_nsets (read_int ch) in
A3MMultiNameLate ns
| 0x1C ->
A3MAttrib (read_name ctx ~k:0x1B ch)
| 0x1D ->
let rec loop n =
if n = 0 then
[]
else
let name = magic_index (read_int ch) in
name :: loop (n - 1)
in
let id = magic_index (read_int ch) in
A3MParams (id,loop (IO.read_byte ch))
| n ->
prerr_endline (string_of_int n);
assert false
let read_value ctx ch extra =
let idx = read_int ch in
if idx = 0 then begin
if extra && IO.read_byte ch <> 0 then assert false;
A3VNone
end else match IO.read_byte ch with
| 0x01 ->
A3VString (index ctx.as3_idents idx)
| 0x03 ->
A3VInt (index ctx.as3_ints idx)
| 0x04 ->
A3VUInt (index ctx.as3_uints idx)
| 0x06 ->
A3VFloat (index ctx.as3_floats idx)
| 0x08 | 0x16 | 0x17 | 0x18 | 0x19 | 0x1A | 0x05 as n->
A3VNamespace (n,index ctx.as3_namespaces idx)
| 0x0A ->
if idx <> 0x0A then assert false;
A3VBool false
| 0x0B ->
if idx <> 0x0B then assert false;
A3VBool true
| 0x0C ->
if idx <> 0x0C then assert false;
A3VNull
| _ ->
assert false
let read_method_type ctx ch =
let nargs = IO.read_byte ch in
let tret = index_opt ctx.as3_names (read_int ch) in
let targs = Array.to_list (Array.init nargs (fun _ -> index_opt ctx.as3_names (read_int ch))) in
let dname = index_opt ctx.as3_idents (read_int ch) in
let flags = IO.read_byte ch in
let dparams = (if flags land 0x08 <> 0 then
Some (Array.to_list (Array.init (IO.read_byte ch) (fun _ -> read_value ctx ch true)))
else
None
) in
let pnames = (if flags land 0x80 <> 0 then
Some (Array.to_list (Array.init nargs (fun _ -> index_opt ctx.as3_idents (read_int ch))))
else
None
) in
{
mt3_ret = tret;
mt3_args = targs;
mt3_var_args = flags land 0x04 <> 0;
mt3_native = flags land 0x20 <> 0;
mt3_new_block = flags land 0x02 <> 0;
mt3_debug_name = dname;
mt3_dparams = dparams;
mt3_pnames = pnames;
mt3_arguments_defined = flags land 0x01 <> 0;
mt3_uses_dxns = flags land 0x40 <> 0;
mt3_unused_flag = flags land 0x10 <> 0;
}
let read_list ch f =
match read_int ch with
| 0 -> [||]
| n -> Array.init (n - 1) (fun _ -> f ch)
let read_list2 ch f =
Array.init (read_int ch) (fun _ -> f ch)
let read_field ctx ch =
let name = index ctx.as3_names (read_int ch) in
let kind = IO.read_byte ch in
let has_meta = kind land 0x40 <> 0 in
let slot = read_int ch in
let kind = (match kind land 0xF with
| 0x00 | 0x06 ->
let t = index_opt ctx.as3_names (read_int ch) in
let value = read_value ctx ch false in
A3FVar {
v3_type = t;
v3_value = value;
v3_const = kind = 0x06;
}
| 0x02
| 0x03
| 0x01 ->
let meth = index_nz ctx.as3_method_types (read_int ch) in
let final = kind land 0x10 <> 0 in
let override = kind land 0x20 <> 0 in
A3FMethod {
m3_type = meth;
m3_final = final;
m3_override = override;
m3_kind = (match kind land 0xF with 0x01 -> MK3Normal | 0x02 -> MK3Getter | 0x03 -> MK3Setter | _ -> assert false);
}
| 0x04 ->
let c = index_nz ctx.as3_classes (read_int ch) in
A3FClass c
| 0x05 ->
let f = index_nz ctx.as3_method_types (read_int ch) in
A3FFunction f
| _ ->
assert false
) in
let metas = (if has_meta then
Some (read_list2 ch (fun _ -> index_nz ctx.as3_metadatas (read_int ch)))
else
None
) in
{
f3_name = name;
f3_slot = slot;
f3_kind = kind;
f3_metas = metas;
}
let read_class ctx ch =
let name = index ctx.as3_names (read_int ch) in
let csuper = index_opt ctx.as3_names (read_int ch) in
let flags = IO.read_byte ch in
let namespace =
if flags land 8 <> 0 then
let r = index ctx.as3_namespaces (read_int ch) in
Some r
else
None
in
let impls = read_list2 ch (fun _ -> index ctx.as3_names (read_int ch)) in
let construct = index_nz ctx.as3_method_types (read_int ch) in
let fields = read_list2 ch (read_field ctx) in
{
cl3_name = name;
cl3_super = csuper;
cl3_sealed = (flags land 1) <> 0;
cl3_final = (flags land 2) <> 0;
cl3_interface = (flags land 4) <> 0;
cl3_namespace = namespace;
cl3_implements = impls;
cl3_construct = construct;
cl3_fields = fields;
}
let read_static ctx ch =
let meth = index_nz ctx.as3_method_types (read_int ch) in
let fields = read_list2 ch (read_field ctx) in
{
st3_method = meth;
st3_fields = fields;
}
let read_metadata ctx ch =
let name = index ctx.as3_idents (read_int ch) in
let data = read_list2 ch (fun _ -> index_opt ctx.as3_idents (read_int ch)) in
let data = Array.map (fun i1 -> i1 , index ctx.as3_idents (read_int ch)) data in
{
meta3_name = name;
meta3_data = data;
}
let read_try_catch ctx ch =
let start = read_int ch in
let pend = read_int ch in
let handle = read_int ch in
let t = index_opt ctx.as3_names (read_int ch) in
let name = index_opt ctx.as3_names (read_int ch) in
{
tc3_start = start;
tc3_end = pend;
tc3_handle = handle;
tc3_type = t;
tc3_name = name;
}
let read_function ctx ch =
let id = index_nz ctx.as3_method_types (read_int ch) in
let ss = read_int ch in
let nregs = read_int ch in
let init_scope = read_int ch in
let max_scope = read_int ch in
let size = read_int ch in
let code = if parse_bytecode then As3code.parse ch size else Array.init size (fun _ -> A3Unk (IO.read ch)) in
let trys = read_list2 ch (read_try_catch ctx) in
let local_funs = read_list2 ch (read_field ctx) in
{
fun3_id = id;
fun3_stack_size = ss;
fun3_nregs = nregs;
fun3_init_scope = init_scope;
fun3_max_scope = max_scope;
fun3_code = code;
fun3_trys = trys;
fun3_locals = local_funs;
}
let header_magic = 0x002E0010
let parse ch len =
let data = IO.nread ch len in
let ch = IO.input_string data in
if IO.read_i32 ch <> header_magic then assert false;
let ints = read_list ch read_as3_int in
let uints = read_list ch read_as3_uint in
let floats = read_list ch IO.read_double in
let idents = (if parse_idents then read_list ch read_ident else [||]) in
let namespaces = (if parse_namespaces then read_list ch (read_namespace idents) else [||]) in
let nsets = (if parse_ns_sets then read_list ch (read_ns_set namespaces) else [||]) in
let ctx = {
as3_ints = ints;
as3_uints = uints;
as3_floats = floats;
as3_idents = idents;
as3_namespaces = namespaces;
as3_nsets = nsets;
as3_names = [||];
as3_method_types = [||];
as3_metadatas = [||];
as3_classes = [||];
as3_statics = [||];
as3_inits = [||];
as3_functions = [||];
as3_unknown = "";
} in
if parse_names then ctx.as3_names <- read_list ch (read_name ctx);
if parse_mtypes then ctx.as3_method_types <- read_list2 ch (read_method_type ctx);
if parse_metadata then ctx.as3_metadatas <- read_list2 ch (read_metadata ctx);
if parse_classes then ctx.as3_classes <- read_list2 ch (read_class ctx);
if parse_statics then ctx.as3_statics <- Array.map (fun _ -> read_static ctx ch) ctx.as3_classes;
if parse_inits then ctx.as3_inits <- read_list2 ch (read_static ctx);
if parse_functions then ctx.as3_functions <- read_list2 ch (read_function ctx);
ctx.as3_unknown <- IO.read_all ch;
if parse_functions && String.length ctx.as3_unknown <> 0 then assert false;
let len2 = as3_length ctx in
if len2 <> len then begin Printf.printf "%d != %d" len len2; assert false; end;
ctx
let write_as3_int ch i =
let e = Int32.to_int (Int32.shift_right_logical i 28) in
let d = Int32.to_int (Int32.shift_right i 21) land 0x7F in
let c = Int32.to_int (Int32.shift_right i 14) land 0x7F in
let b = Int32.to_int (Int32.shift_right i 7) land 0x7F in
let a = Int32.to_int (Int32.logand i 0x7Fl) in
if b <> 0 || c <> 0 || d <> 0 || e <> 0 then begin
IO.write_byte ch (a lor 0x80);
if c <> 0 || d <> 0 || e <> 0 then begin
IO.write_byte ch (b lor 0x80);
if d <> 0 || e <> 0 then begin
IO.write_byte ch (c lor 0x80);
if e <> 0 then begin
IO.write_byte ch (d lor 0x80);
IO.write_byte ch e;
end else
IO.write_byte ch d;
end else
IO.write_byte ch c;
end else
IO.write_byte ch b;
end else
IO.write_byte ch a
let write_as3_uint = write_as3_int
let write_int ch i =
write_as3_int ch (Int32.of_int i)
let write_index ch n =
write_int ch (index_int n)
let write_index_nz ch n =
write_int ch (index_nz_int n)
let write_index_opt ch = function
| None -> write_int ch 0
| Some n -> write_index ch n
let write_as3_ident ch id =
write_int ch (String.length id);
IO.nwrite ch id
let write_namespace empty_index ch = function
| A3NPrivate n ->
IO.write_byte ch 0x05;
(match n with
| None -> write_int ch 0
| Some n -> write_index ch n);
| A3NPublic n ->
IO.write_byte ch 0x16;
(match n with
| None -> write_index ch empty_index
| Some n -> write_index ch n);
| A3NInternal n ->
IO.write_byte ch 0x17;
(match n with
| None -> write_index ch empty_index
| Some n -> write_index ch n);
| A3NProtected n ->
IO.write_byte ch 0x18;
write_index ch n
| A3NNamespace n ->
IO.write_byte ch 0x08;
write_index ch n
| A3NExplicit n ->
IO.write_byte ch 0x19;
write_index ch n
| A3NStaticProtected n ->
IO.write_byte ch 0x1A;
(match n with
| None -> write_int ch 0
| Some n -> write_index ch n)
let write_rights ch l =
IO.write_byte ch (List.length l);
List.iter (write_index ch) l
let rec write_name ch ?k x =
let b n = match k with None -> n | Some v -> v in
match x with
| A3MMultiName (id,r) ->
IO.write_byte ch (b 0x09);
write_index_opt ch id;
write_index ch r;
| A3MName (id,r) ->
IO.write_byte ch (b 0x07);
write_index ch r;
write_index ch id
| A3MRuntimeName i ->
IO.write_byte ch (b 0x0F);
write_index ch i
| A3MRuntimeNameLate ->
IO.write_byte ch (b 0x11);
| A3MMultiNameLate id ->
IO.write_byte ch (b 0x1B);
write_index ch id
| A3MAttrib n ->
write_name ch ~k:(match n with
| A3MName _ -> 0x0D
| A3MMultiName _ -> 0x0E
| A3MRuntimeName _ -> 0x10
| A3MRuntimeNameLate -> 0x12
| A3MMultiNameLate _ -> 0x1C
| A3MAttrib _ | A3MParams _ -> assert false
) n
| A3MParams (id,pl) ->
IO.write_byte ch (b 0x1D);
write_index ch id;
IO.write_byte ch (List.length pl);
List.iter (write_index ch) pl
let write_value ch extra v =
match v with
| A3VNone ->
IO.write_byte ch 0x00;
if extra then IO.write_byte ch 0x00;
| A3VNull ->
IO.write_byte ch 0x0C;
IO.write_byte ch 0x0C;
| A3VBool b ->
IO.write_byte ch (if b then 0x0B else 0x0A);
IO.write_byte ch (if b then 0x0B else 0x0A);
| A3VString s ->
write_index ch s;
IO.write_byte ch 0x01;
| A3VInt s ->
write_index ch s;
IO.write_byte ch 0x03;
| A3VUInt s ->
write_index ch s;
IO.write_byte ch 0x04;
| A3VFloat s ->
write_index ch s;
IO.write_byte ch 0x06
| A3VNamespace (n,s) ->
write_index ch s;
IO.write_byte ch n
let write_method_type ch m =
let nargs = List.length m.mt3_args in
IO.write_byte ch nargs;
write_index_opt ch m.mt3_ret;
List.iter (write_index_opt ch) m.mt3_args;
write_index_opt ch m.mt3_debug_name;
let flags =
(if m.mt3_arguments_defined then 0x01 else 0) lor
(if m.mt3_new_block then 0x02 else 0) lor
(if m.mt3_var_args then 0x04 else 0) lor
(if m.mt3_dparams <> None then 0x08 else 0) lor
(if m.mt3_unused_flag then 0x10 else 0) lor
(if m.mt3_native then 0x20 else 0) lor
(if m.mt3_uses_dxns then 0x40 else 0) lor
(if m.mt3_pnames <> None then 0x80 else 0)
in
IO.write_byte ch flags;
(match m.mt3_dparams with
| None -> ()
| Some l ->
IO.write_byte ch (List.length l);
List.iter (write_value ch true) l);
match m.mt3_pnames with
| None -> ()
| Some l ->
if List.length l <> nargs then assert false;
List.iter (write_index_opt ch) l
let write_list ch f l =
match Array.length l with
| 0 -> IO.write_byte ch 0
| n ->
write_int ch (n + 1);
Array.iter (f ch) l
let write_list2 ch f l =
write_int ch (Array.length l);
Array.iter (f ch) l
let write_field ch f =
write_index ch f.f3_name;
let flags = (if f.f3_metas <> None then 0x40 else 0) in
(match f.f3_kind with
| A3FMethod m ->
let base = (match m.m3_kind with MK3Normal -> 0x01 | MK3Getter -> 0x02 | MK3Setter -> 0x03) in
let flags = flags lor (if m.m3_final then 0x10 else 0) lor (if m.m3_override then 0x20 else 0) in
IO.write_byte ch (base lor flags);
write_int ch f.f3_slot;
write_index_nz ch m.m3_type;
| A3FClass c ->
IO.write_byte ch (0x04 lor flags);
write_int ch f.f3_slot;
write_index_nz ch c
| A3FFunction i ->
IO.write_byte ch (0x05 lor flags);
write_int ch f.f3_slot;
write_index_nz ch i
| A3FVar v ->
IO.write_byte ch (flags lor (if v.v3_const then 0x06 else 0x00));
write_int ch f.f3_slot;
write_index_opt ch v.v3_type;
write_value ch false v.v3_value);
match f.f3_metas with
| None -> ()
| Some l ->
write_list2 ch write_index_nz l
let write_class ch c =
write_index ch c.cl3_name;
write_index_opt ch c.cl3_super;
let flags =
(if c.cl3_sealed then 1 else 0) lor
(if c.cl3_final then 2 else 0) lor
(if c.cl3_interface then 4 else 0) lor
(if c.cl3_namespace <> None then 8 else 0)
in
IO.write_byte ch flags;
(match c.cl3_namespace with
| None -> ()
| Some r -> write_index ch r);
write_list2 ch write_index c.cl3_implements;
write_index_nz ch c.cl3_construct;
write_list2 ch write_field c.cl3_fields
let write_static ch s =
write_index_nz ch s.st3_method;
write_list2 ch write_field s.st3_fields
let write_metadata ch m =
write_index ch m.meta3_name;
write_list2 ch (fun _ (i1,_) -> write_index_opt ch i1) m.meta3_data;
Array.iter (fun (_,i2) -> write_index ch i2) m.meta3_data
let write_try_catch ch t =
write_int ch t.tc3_start;
write_int ch t.tc3_end;
write_int ch t.tc3_handle;
write_index_opt ch t.tc3_type;
write_index_opt ch t.tc3_name
let write_function ch f =
write_index_nz ch f.fun3_id;
write_int ch f.fun3_stack_size;
write_int ch f.fun3_nregs;
write_int ch f.fun3_init_scope;
write_int ch f.fun3_max_scope;
let clen = Array.fold_left (fun acc op -> acc + As3code.length op) 0 f.fun3_code in
write_int ch clen;
Array.iter (As3code.write ch) f.fun3_code;
write_list2 ch write_try_catch f.fun3_trys;
write_list2 ch write_field f.fun3_locals
let write ch1 ctx =
let ch = IO.output_string() in
let empty_index = as3_empty_index ctx in
IO.write_i32 ch header_magic;
write_list ch write_as3_int ctx.as3_ints;
write_list ch write_as3_uint ctx.as3_uints;
write_list ch IO.write_double ctx.as3_floats;
if parse_idents then write_list ch write_as3_ident ctx.as3_idents;
if parse_namespaces then write_list ch (write_namespace empty_index) ctx.as3_namespaces;
if parse_ns_sets then write_list ch write_rights ctx.as3_nsets;
if parse_names then write_list ch (write_name ?k:None) ctx.as3_names;
if parse_mtypes then write_list2 ch write_method_type ctx.as3_method_types;
if parse_metadata then write_list2 ch write_metadata ctx.as3_metadatas;
if parse_classes then write_list2 ch write_class ctx.as3_classes;
if parse_statics then Array.iter (write_static ch) ctx.as3_statics;
if parse_inits then write_list2 ch write_static ctx.as3_inits;
if parse_functions then write_list2 ch write_function ctx.as3_functions;
IO.nwrite ch ctx.as3_unknown;
let str = IO.close_out ch in
IO.nwrite ch1 str
DUMP
let dump_code_size = ref true
let ident_str ctx i =
iget ctx.as3_idents i
let namespace_str ctx i =
match iget ctx.as3_namespaces i with
| A3NPrivate None -> "private"
| A3NPrivate (Some n) -> "private:" ^ ident_str ctx n
| A3NPublic None -> "public"
| A3NPublic (Some n) -> "public:" ^ ident_str ctx n
| A3NInternal None -> "internal"
| A3NInternal (Some n) -> "internal:" ^ ident_str ctx n
| A3NProtected n -> "protected:" ^ ident_str ctx n
| A3NExplicit n -> "explicit:" ^ ident_str ctx n
| A3NStaticProtected None -> "static_protected"
| A3NStaticProtected (Some n) -> "static_protectec:" ^ ident_str ctx n
| A3NNamespace n -> "namespace:" ^ ident_str ctx n
let ns_set_str ctx i =
let l = iget ctx.as3_nsets i in
String.concat " " (List.map (fun r -> namespace_str ctx r) l)
let rec name_str ctx kind t =
let rec loop = function
| A3MName (id,r) -> Printf.sprintf "%s %s%s" (namespace_str ctx r) kind (ident_str ctx id)
| A3MMultiName (id,r) -> Printf.sprintf "[%s %s%s]" (ns_set_str ctx r) kind (match id with None -> "NO" | Some i -> ident_str ctx i)
| A3MRuntimeName id -> Printf.sprintf "'%s'" (ident_str ctx id)
| A3MRuntimeNameLate -> "RTLATE"
| A3MMultiNameLate id -> Printf.sprintf "late:(%s)" (ns_set_str ctx id)
| A3MAttrib n -> "attrib " ^ loop n
| A3MParams (id,pl) -> Printf.sprintf "%s<%s>" (name_str ctx kind id) (String.concat "," (List.map (name_str ctx kind) pl))
in
loop (iget ctx.as3_names t)
let value_str ctx v =
match v with
| A3VNone -> "<none>"
| A3VNull -> "null"
| A3VString s -> "\"" ^ ident_str ctx s ^ "\""
| A3VBool b -> if b then "true" else "false"
| A3VInt s -> Printf.sprintf "%ld" (iget ctx.as3_ints s)
| A3VUInt s -> Printf.sprintf "%ld" (iget ctx.as3_uints s)
| A3VFloat s -> Printf.sprintf "%f" (iget ctx.as3_floats s)
| A3VNamespace (_,s) -> "ns::" ^ namespace_str ctx s
let metadata_str ctx i =
let m = iget ctx.as3_metadatas i in
let data = List.map (fun (i1,i2) -> Printf.sprintf "%s=\"%s\"" (match i1 with None -> "NO" | Some i -> ident_str ctx i) (ident_str ctx i2)) (Array.to_list m.meta3_data) in
Printf.sprintf "%s(%s)" (ident_str ctx m.meta3_name) (String.concat ", " data)
let method_str ?(infos=false) ctx m =
let m = iget ctx.as3_method_types m in
let pcount = ref 0 in
Printf.sprintf "%s(%s%s)%s"
(if m.mt3_native then " native " else "")
(String.concat ", " (List.map (fun a ->
let id = (match m.mt3_pnames with
| None -> "p" ^ string_of_int !pcount
| Some l ->
match List.nth l !pcount with
| None -> "p" ^ string_of_int !pcount
| Some i -> ident_str ctx i
) in
let p = (match a with None -> id | Some t -> name_str ctx (id ^ " : ") t) in
let p = (match m.mt3_dparams with
| None -> p
| Some l ->
let vargs = List.length m.mt3_args - List.length l in
if !pcount >= vargs then
let v = List.nth l (!pcount - vargs) in
p ^ " = " ^ value_str ctx v
else
p
) in
incr pcount;
p
) m.mt3_args))
(if m.mt3_var_args then " ..." else "")
(match m.mt3_ret with None -> "" | Some t -> " : " ^ name_str ctx "" t)
^ (if infos then begin
let name = (match m.mt3_debug_name with None -> "" | Some idx -> Printf.sprintf " '%s'" (ident_str ctx idx)) in
Printf.sprintf "%s blk:%b args:%b dxns:%b%s" name m.mt3_new_block m.mt3_arguments_defined m.mt3_uses_dxns (if m.mt3_unused_flag then " SPECIAL-FLAG" else "")
end else "")
let dump_field ctx ch stat f =
( match f.f3_metas with
| None - > ( )
| Some l - > Array.iter ( fun i - > IO.printf ch " [ % s]\n " ( metadata_str ctx ( no_nz i ) ) ) l ) ;
| None -> ()
| Some l -> Array.iter (fun i -> IO.printf ch " [%s]\n" (metadata_str ctx (no_nz i))) l);
*) IO.printf ch " ";
if stat then IO.printf ch "static ";
(match f.f3_kind with
| A3FVar v ->
IO.printf ch "%s" (name_str ctx (if v.v3_const then "const " else "var ") f.f3_name);
(match v.v3_type with
| None -> ()
| Some id -> IO.printf ch " : %s" (name_str ctx "" id));
if v.v3_value <> A3VNone then IO.printf ch " = %s" (value_str ctx v.v3_value);
| A3FClass c ->
let c = iget ctx.as3_classes (no_nz c) in
IO.printf ch "%s = %s" (name_str ctx "CLASS " c.cl3_name) (name_str ctx "class " f.f3_name);
| A3FFunction id ->
IO.printf ch "%s = %s" (method_str ~infos:false ctx (no_nz id)) (name_str ctx "method " f.f3_name);
| A3FMethod m ->
if m.m3_final then IO.printf ch "final ";
if m.m3_override then IO.printf ch "override ";
let k = "function " ^ (match m.m3_kind with
| MK3Normal -> ""
| MK3Getter -> "get "
| MK3Setter -> "set "
) in
IO.printf ch "%s%s #%d" (name_str ctx k f.f3_name) (method_str ctx (no_nz m.m3_type)) (index_nz_int m.m3_type);
);
if f.f3_slot <> 0 then IO.printf ch " = [SLOT:%d]" f.f3_slot;
IO.printf ch ";\n"
let dump_class ctx ch idx c =
let st = if parse_statics then ctx.as3_statics.(idx) else { st3_method = magic_index_nz (-1); st3_fields = [||] } in
if not c.cl3_sealed then IO.printf ch "dynamic ";
if c.cl3_final then IO.printf ch "final ";
(match c.cl3_namespace with
| None -> ()
| Some r -> IO.printf ch "%s " (namespace_str ctx r));
let kind = (if c.cl3_interface then "interface " else "class ") in
IO.printf ch "%s " (name_str ctx kind c.cl3_name);
(match c.cl3_super with
| None -> ()
| Some s -> IO.printf ch "extends %s " (name_str ctx "" s));
(match Array.to_list c.cl3_implements with
| [] -> ()
| l ->
IO.printf ch "implements %s " (String.concat ", " (List.map (fun i -> name_str ctx "" i) l)));
IO.printf ch "{\n";
Array.iter (dump_field ctx ch false) c.cl3_fields;
Array.iter (dump_field ctx ch true) st.st3_fields;
IO.printf ch "} constructor#%d statics#%d\n\n" (index_nz_int c.cl3_construct) (index_nz_int st.st3_method)
let dump_init ctx ch idx s =
IO.printf ch "init #%d {\n" (index_nz_int s.st3_method);
Array.iter (dump_field ctx ch false) s.st3_fields;
IO.printf ch "}\n\n"
let dump_try_catch ctx ch t =
IO.printf ch " try %d %d %d (%s) (%s)\n"
t.tc3_start t.tc3_end t.tc3_handle
(match t.tc3_type with None -> "*" | Some idx -> name_str ctx "" idx)
(match t.tc3_name with None -> "NO" | Some idx -> name_str ctx "" idx)
let dump_function ctx ch idx f =
IO.printf ch "function #%d %s\n" (index_nz_int f.fun3_id) (method_str ~infos:true ctx (no_nz f.fun3_id));
IO.printf ch " stack:%d nregs:%d scope:%d-%d\n" f.fun3_stack_size f.fun3_nregs f.fun3_init_scope f.fun3_max_scope;
Array.iter (dump_field ctx ch false) f.fun3_locals;
Array.iter (dump_try_catch ctx ch) f.fun3_trys;
let pos = ref 0 in
Array.iter (fun op ->
IO.printf ch "%4d %s\n" !pos (As3code.dump ctx op);
if !dump_code_size then pos := !pos + As3code.length op else incr pos;
) f.fun3_code;
IO.printf ch "\n"
let dump_ident ctx ch idx _ =
IO.printf ch "I%d = %s\n" (idx + 1) (ident_str ctx (index ctx.as3_idents (idx + 1)))
let dump_namespace ctx ch idx _ =
IO.printf ch "N%d = %s\n" (idx + 1) (namespace_str ctx (index ctx.as3_namespaces (idx + 1)))
let dump_ns_set ctx ch idx _ =
IO.printf ch "S%d = %s\n" (idx + 1) (ns_set_str ctx (index ctx.as3_nsets (idx + 1)))
let dump_name ctx ch idx _ =
IO.printf ch "T%d = %s\n" (idx + 1) (name_str ctx "" (index ctx.as3_names (idx + 1)))
let dump_method_type ctx ch idx _ =
IO.printf ch "M%d = %s\n" (idx + 1) (method_str ~infos:true ctx (index ctx.as3_method_types (idx + 1)))
let dump_metadata ctx ch idx _ =
IO.printf ch "D%d = %s\n" (idx + 1) (metadata_str ctx (index ctx.as3_metadatas (idx + 1)))
let dump_int ctx ch idx i =
IO.printf ch "INT %d = 0x%lX\n" (idx + 1) i
let dump_float ctx ch idx f =
IO.printf ch "FLOAT %d = %f\n" (idx + 1) f
let dump ch ctx id =
(match id with
| None -> IO.printf ch "\n---------------- AS3 -------------------------\n\n";
| Some (id,f) -> IO.printf ch "\n---------------- AS3 %s [%d] -----------------\n\n" f id);
Array.iteri ( dump_int ctx ch ) ctx.as3_ints ;
Array.iteri ( dump_float ctx ch ) ctx.as3_floats ;
Array.iteri ( dump_ident ctx ch ) ctx.as3_idents ;
IO.printf ch " \n " ;
Array.iteri ( dump_namespace ctx ch ) ctx.as3_namespaces ;
IO.printf ch " \n " ;
Array.iteri ( dump_ns_set ctx ch ) ctx.as3_nsets ;
IO.printf ch " \n " ;
Array.iteri ( dump_name ctx ch ) ctx.as3_names ;
IO.printf ch " \n " ;
Array.iteri (dump_float ctx ch) ctx.as3_floats;
Array.iteri (dump_ident ctx ch) ctx.as3_idents;
IO.printf ch "\n";
Array.iteri (dump_namespace ctx ch) ctx.as3_namespaces;
IO.printf ch "\n";
Array.iteri (dump_ns_set ctx ch) ctx.as3_nsets;
IO.printf ch "\n";
Array.iteri (dump_name ctx ch) ctx.as3_names;
IO.printf ch "\n"; *)
Array.iteri ( dump_metadata ctx ch ) ctx.as3_metadatas ;
Array.iteri (dump_class ctx ch) ctx.as3_classes;
Array.iteri (dump_init ctx ch) ctx.as3_inits;
Array.iteri (dump_function ctx ch) ctx.as3_functions;
IO.printf ch "\n"
;;
As3code.f_int_length := int_length;
As3code.f_int_read := read_int;
As3code.f_int_write := write_int;
|
9e1771987ab6e0f966d785aea6b37e89a9237a3f5d3a1c4709a6d0b432a5f71c | fulcrologic/fulcro-inspect | figwheel.clj | (use 'figwheel-sidecar.repl-api)
(start-figwheel! "devcards" "test")
(cljs-repl)
| null | https://raw.githubusercontent.com/fulcrologic/fulcro-inspect/a03b61cbd95384c0f03aa936368bcf5cf573fa32/script/figwheel.clj | clojure | (use 'figwheel-sidecar.repl-api)
(start-figwheel! "devcards" "test")
(cljs-repl)
| |
ae3586729e04b83e80b6bc1a3db8ccf542ea810964f7af011d571429d1547675 | Haskell-Things/ImplicitCAD | Spec.hs | {- ORMOLU_DISABLE -}
# OPTIONS_GHC -fno - warn - missing - import - lists #
# OPTIONS_GHC -fno - warn - type - defaults #
module GoldenSpec.Spec (spec) where
import GoldenSpec.Util (golden, goldenAllFormats)
import Graphics.Implicit
import Prelude
import Test.Hspec ( describe, Spec )
import Graphics.Implicit.Primitives (torus, ellipsoid, cone)
default (Int)
spec :: Spec
spec = describe "golden tests" $ do
golden "box" 1 $
cube True (V3 5 5 5)
goldenAllFormats "boxCylinder" 1 $
union
[ cube False (V3 5 5 5)
, translate (V3 2.5 2.5 5) $ cylinder2 2 1 3
]
golden "example13" 1 $
union [ rect3 (V3 0 0 0) (V3 20 20 20)
, translate (V3 20 20 20) (sphere 15)
]
golden "example16" 1 $
implicit
(\(V3 x y z) -> x^4 + y^4 + z^4 - 15000)
( V3 (-20) (-20) (-20) ,V3 20 20 20)
golden "example17" 1 $
let
squarePipe :: ℝ3 -> ℝ -> ℝ -> SymbolicObj3
squarePipe (V3 x y z) diameter precision =
union
((\(a, b, c) -> translate (V3 a b c)
$ rect3 (V3 0 0 0) (V3 diameter diameter diameter)
)
<$>
zip3 (fmap (\n->(fromIntegral n/precision)*x) [0..100])
(fmap (\n->(fromIntegral n/precision)*y) [0..100])
(fmap (\n->(fromIntegral n/precision)*z) [0..100]))
in squarePipe (V3 10 10 10) 1 100
golden "wheel-well" 1 $
differenceR 0.0
(translate (V3 6.0 (-0.0) (-44.5))
(unionR 0.0
[ translate (V3 (-17.0) 0.0 0.0)
(translate (V3 0.0 0.0 38.0)
(rotate3 (V3 0 (pi / 2) 0)
(translate (V3 3.0 (-0.0) (-17.0))
(unionR 0.0
[ translate (V3 0.0 0.0 (-0.0))
(intersectR 0.0
[ shell 2.0
(outset 5.0
(cylinder 35.0 28.0))
, cylinder 50.0 28.0
, translate (V3 11.0 0.0 0.0)
(translate (V3 (-50.0) 0.0 0.0)
(translate (V3 0.0 0.0 14.0)
(translate (V3 (-50.0) (-50.0) (-14.0))
(cube False (V3 100.0 100.0 28.0)))))
])
]))))
, translate (V3 (-2.0) 0.0 0.0)
(translate (V3 12.0 0.0 0.0)
(translate (V3 0.0 0.0 24.0)
(translate (V3 0.0 0.0 (-0.0))
(unionR 0.0
[ intersectR 0.0
[ translate (V3 0.0 0.0 31.5)
(shell 2.0
(scale (V3 1.1578947368421053 1.1363636363636365 1.0307692307692307)
(translate (V3 (-9.5) (-11.0) (-32.5))
(cube False (V3 19.0 22.0 65.0)))))
, translate (V3 (-12.0) (-13.500000000000002) 0.0)
(cube False (V3 24.0 27.0 2.0))
]
]))))
]))
[ translate (V3 6.0 (-0.0) (-44.5))
(unionR 0.0
[ translate (V3 (-17.0) 0.0 0.0)
(translate (V3 0.0 0.0 38.0)
(rotate3 (V3 0 (pi / 2) 0)
(translate (V3 3.0 (-0.0) (-17.0))
(unionR 0.0
[ translate (V3 0.0 0.0 0.0)
(translate (V3 0.0 0.0 17.0)
(translate (V3 (-0.0) (-0.0) 11.0)
(unionR 0.0
[ translate (V3 0.0 0.0 (-0.0))
(cylinder 3.0 6.0)
, translate (V3 0.0 0.0 0.0)
(translate (V3 0.0 0.0 (-28.0))
(cylinder 35.0 28.0))
])))
]))))
, translate (V3 (-2.0) 0.0 0.0)
(translate (V3 12.0 0.0 0.0)
(translate (V3 0.0 0.0 24.0)
(translate (V3 0.0 0.0 (-0.0))
(translate (V3 0.0 0.0 32.5)
(translate (V3 (-9.5) (-11.0) (-32.5))
(cube False (V3 19.0 22.0 65.0)))))))
])
]
These tests were generated by the Arbitrary instance
golden "arbitrary1" 1 $
cylinder 16.76324 21.02933
golden "arbitrary2" 1 $
translate (V3 24.07554 26.31483 24.96913)
. scale (V3 3.6096 4.9768 2.9848)
. translate (V3 (-1.2054) (-0.4034) (-0.725975))
$ withRounding 0.45186 $ cube False (V3 2.41095 0.8068 1.45195)
golden "arbitrary3" 1 $
differenceR 1.8 (sphere 4.6)
[ rotate3 (V3 (-0.3) 0.4 0.36)
$ scale (V3 1 1.3 1.4)
$ cylinder2 0.6 0.74 1
, sphere 1.2
, rotate3 (V3 0.54 (-0.45) (-0.58))
$ withRounding 1.4
$ cube True (V3 1.5 1.81 1.82)
, cylinder2 1.7 1.5 3.5
, sphere 1.54
]
golden "arbitrary4" 1 $
unionR 1.8
[ sphere 4.6
, rotate3 (V3 (-0.3) 0.4 0.36)
$ scale (V3 1 1.3 1.4)
$ cylinder2 0.6 0.74 1
, sphere 1.2
, rotate3 (V3 0.54 (-0.45) (-0.58))
$ withRounding 1.4
$ cube True (V3 1.5 1.81 1.82)
, cylinder2 1.7 1.5 3.5
, sphere 1.54
]
golden "hook" 2 $
union
[ translate (V3 0 60 0) $
rotateExtrude (3 * pi / 2) (Left 0) (Left 0) $
translate (V2 40 0) $
circle 10
, rotateExtrude (pi / 2) (Left 0) (Left 0) $
translate (V2 20 0) $
circle 10
, translate (V3 20 0 0) $
rotate3 (V3 (pi / 2) 0 0) $
cylinder 10 80
]
golden "torusEllipsoidCone" 2 $
union
[ torus 40 15
, ellipsoid 10 15 20
, translate (V3 0 0 25) $ cone 20 20
]
golden "closing-paths-1" 0.5 $
extrudeM
(Left 0)
(C1 1)
(Left 0)
(circle 1)
-- limit height or this races off to infinity
-- and makes the tests take forever, eating all
-- your RAM while it tries to calculate the surface
$ Right $ \(V2 x y) -> min 100 $ 1 / sqrt (x ^ 2 + y ^ 2)
golden "closing-paths-2" 1 $
extrudeM
-- Note, this have a gap from the base plane and the extruded
-- object, and the base of the extruded object is going to be
-- missing. This is because we are directly using haskell
functions rather than the clamped / Infinity / NaN checked
-- versions that the parser is set up to provide.
-- However, this is still useful in that it doesn't crash on
-- unclosed loops.
(pure $ \h -> 35 * log (h*2*pi/30))
(C1 1)
(Left 0)
(union [circle 10])
$ Left 40 | null | https://raw.githubusercontent.com/Haskell-Things/ImplicitCAD/f5cafa5ff074604f1721c89b9f611d391cdca186/tests/GoldenSpec/Spec.hs | haskell | ORMOLU_DISABLE
limit height or this races off to infinity
and makes the tests take forever, eating all
your RAM while it tries to calculate the surface
Note, this have a gap from the base plane and the extruded
object, and the base of the extruded object is going to be
missing. This is because we are directly using haskell
versions that the parser is set up to provide.
However, this is still useful in that it doesn't crash on
unclosed loops. | # OPTIONS_GHC -fno - warn - missing - import - lists #
# OPTIONS_GHC -fno - warn - type - defaults #
module GoldenSpec.Spec (spec) where
import GoldenSpec.Util (golden, goldenAllFormats)
import Graphics.Implicit
import Prelude
import Test.Hspec ( describe, Spec )
import Graphics.Implicit.Primitives (torus, ellipsoid, cone)
default (Int)
spec :: Spec
spec = describe "golden tests" $ do
golden "box" 1 $
cube True (V3 5 5 5)
goldenAllFormats "boxCylinder" 1 $
union
[ cube False (V3 5 5 5)
, translate (V3 2.5 2.5 5) $ cylinder2 2 1 3
]
golden "example13" 1 $
union [ rect3 (V3 0 0 0) (V3 20 20 20)
, translate (V3 20 20 20) (sphere 15)
]
golden "example16" 1 $
implicit
(\(V3 x y z) -> x^4 + y^4 + z^4 - 15000)
( V3 (-20) (-20) (-20) ,V3 20 20 20)
golden "example17" 1 $
let
squarePipe :: ℝ3 -> ℝ -> ℝ -> SymbolicObj3
squarePipe (V3 x y z) diameter precision =
union
((\(a, b, c) -> translate (V3 a b c)
$ rect3 (V3 0 0 0) (V3 diameter diameter diameter)
)
<$>
zip3 (fmap (\n->(fromIntegral n/precision)*x) [0..100])
(fmap (\n->(fromIntegral n/precision)*y) [0..100])
(fmap (\n->(fromIntegral n/precision)*z) [0..100]))
in squarePipe (V3 10 10 10) 1 100
golden "wheel-well" 1 $
differenceR 0.0
(translate (V3 6.0 (-0.0) (-44.5))
(unionR 0.0
[ translate (V3 (-17.0) 0.0 0.0)
(translate (V3 0.0 0.0 38.0)
(rotate3 (V3 0 (pi / 2) 0)
(translate (V3 3.0 (-0.0) (-17.0))
(unionR 0.0
[ translate (V3 0.0 0.0 (-0.0))
(intersectR 0.0
[ shell 2.0
(outset 5.0
(cylinder 35.0 28.0))
, cylinder 50.0 28.0
, translate (V3 11.0 0.0 0.0)
(translate (V3 (-50.0) 0.0 0.0)
(translate (V3 0.0 0.0 14.0)
(translate (V3 (-50.0) (-50.0) (-14.0))
(cube False (V3 100.0 100.0 28.0)))))
])
]))))
, translate (V3 (-2.0) 0.0 0.0)
(translate (V3 12.0 0.0 0.0)
(translate (V3 0.0 0.0 24.0)
(translate (V3 0.0 0.0 (-0.0))
(unionR 0.0
[ intersectR 0.0
[ translate (V3 0.0 0.0 31.5)
(shell 2.0
(scale (V3 1.1578947368421053 1.1363636363636365 1.0307692307692307)
(translate (V3 (-9.5) (-11.0) (-32.5))
(cube False (V3 19.0 22.0 65.0)))))
, translate (V3 (-12.0) (-13.500000000000002) 0.0)
(cube False (V3 24.0 27.0 2.0))
]
]))))
]))
[ translate (V3 6.0 (-0.0) (-44.5))
(unionR 0.0
[ translate (V3 (-17.0) 0.0 0.0)
(translate (V3 0.0 0.0 38.0)
(rotate3 (V3 0 (pi / 2) 0)
(translate (V3 3.0 (-0.0) (-17.0))
(unionR 0.0
[ translate (V3 0.0 0.0 0.0)
(translate (V3 0.0 0.0 17.0)
(translate (V3 (-0.0) (-0.0) 11.0)
(unionR 0.0
[ translate (V3 0.0 0.0 (-0.0))
(cylinder 3.0 6.0)
, translate (V3 0.0 0.0 0.0)
(translate (V3 0.0 0.0 (-28.0))
(cylinder 35.0 28.0))
])))
]))))
, translate (V3 (-2.0) 0.0 0.0)
(translate (V3 12.0 0.0 0.0)
(translate (V3 0.0 0.0 24.0)
(translate (V3 0.0 0.0 (-0.0))
(translate (V3 0.0 0.0 32.5)
(translate (V3 (-9.5) (-11.0) (-32.5))
(cube False (V3 19.0 22.0 65.0)))))))
])
]
These tests were generated by the Arbitrary instance
golden "arbitrary1" 1 $
cylinder 16.76324 21.02933
golden "arbitrary2" 1 $
translate (V3 24.07554 26.31483 24.96913)
. scale (V3 3.6096 4.9768 2.9848)
. translate (V3 (-1.2054) (-0.4034) (-0.725975))
$ withRounding 0.45186 $ cube False (V3 2.41095 0.8068 1.45195)
golden "arbitrary3" 1 $
differenceR 1.8 (sphere 4.6)
[ rotate3 (V3 (-0.3) 0.4 0.36)
$ scale (V3 1 1.3 1.4)
$ cylinder2 0.6 0.74 1
, sphere 1.2
, rotate3 (V3 0.54 (-0.45) (-0.58))
$ withRounding 1.4
$ cube True (V3 1.5 1.81 1.82)
, cylinder2 1.7 1.5 3.5
, sphere 1.54
]
golden "arbitrary4" 1 $
unionR 1.8
[ sphere 4.6
, rotate3 (V3 (-0.3) 0.4 0.36)
$ scale (V3 1 1.3 1.4)
$ cylinder2 0.6 0.74 1
, sphere 1.2
, rotate3 (V3 0.54 (-0.45) (-0.58))
$ withRounding 1.4
$ cube True (V3 1.5 1.81 1.82)
, cylinder2 1.7 1.5 3.5
, sphere 1.54
]
golden "hook" 2 $
union
[ translate (V3 0 60 0) $
rotateExtrude (3 * pi / 2) (Left 0) (Left 0) $
translate (V2 40 0) $
circle 10
, rotateExtrude (pi / 2) (Left 0) (Left 0) $
translate (V2 20 0) $
circle 10
, translate (V3 20 0 0) $
rotate3 (V3 (pi / 2) 0 0) $
cylinder 10 80
]
golden "torusEllipsoidCone" 2 $
union
[ torus 40 15
, ellipsoid 10 15 20
, translate (V3 0 0 25) $ cone 20 20
]
golden "closing-paths-1" 0.5 $
extrudeM
(Left 0)
(C1 1)
(Left 0)
(circle 1)
$ Right $ \(V2 x y) -> min 100 $ 1 / sqrt (x ^ 2 + y ^ 2)
golden "closing-paths-2" 1 $
extrudeM
functions rather than the clamped / Infinity / NaN checked
(pure $ \h -> 35 * log (h*2*pi/30))
(C1 1)
(Left 0)
(union [circle 10])
$ Left 40 |
4797dd2da0d4250cf35f2c7711f813398d853d14fb745da394717b37cf5d8dfe | binaryage/cljs-oops | circus.clj | (ns oops.circus
(:require [clojure.test :as test]
[cljs.util :as cljs-util]
[clj-logging-config.log4j :as log4j-config]
[environ.core :refer [env]]
[oops.circus.config :as config]
[oops.arena])
(:import (org.apache.log4j Level)))
(defn setup-logging! []
(let [level (Level/toLevel (config/get-log-level env) Level/INFO)]
(log4j-config/set-loggers! :root {:out :console
:level level})))
(defn print-banner! []
(let [banner (str "Running compiler output tests under "
"Clojure v" (clojure-version) " and "
"ClojureScript v" (cljs-util/clojurescript-version))]
(println)
(println banner)
(println "====================================================================================================")))
; -- main entry point -------------------------------------------------------------------------------------------------------
(defn -main []
(setup-logging!)
(print-banner!)
(let [summary (test/run-tests 'oops.arena)]
(if-not (test/successful? summary)
(System/exit 1)
(System/exit 0))))
| null | https://raw.githubusercontent.com/binaryage/cljs-oops/a2b48d59047c28decb0d6334e2debbf21848e29c/test/src/circus/oops/circus.clj | clojure | -- main entry point ------------------------------------------------------------------------------------------------------- | (ns oops.circus
(:require [clojure.test :as test]
[cljs.util :as cljs-util]
[clj-logging-config.log4j :as log4j-config]
[environ.core :refer [env]]
[oops.circus.config :as config]
[oops.arena])
(:import (org.apache.log4j Level)))
(defn setup-logging! []
(let [level (Level/toLevel (config/get-log-level env) Level/INFO)]
(log4j-config/set-loggers! :root {:out :console
:level level})))
(defn print-banner! []
(let [banner (str "Running compiler output tests under "
"Clojure v" (clojure-version) " and "
"ClojureScript v" (cljs-util/clojurescript-version))]
(println)
(println banner)
(println "====================================================================================================")))
(defn -main []
(setup-logging!)
(print-banner!)
(let [summary (test/run-tests 'oops.arena)]
(if-not (test/successful? summary)
(System/exit 1)
(System/exit 0))))
|
dc2e0462a0ee8c9f7395d851ab681a2349f7f421085f80d181e299dee71f338d | pavankumarbn/DroneGUIROS | navdata_vision_of.lisp | ; Auto-generated. Do not edit!
(cl:in-package ardrone_autonomy-msg)
;//! \htmlinclude navdata_vision_of.msg.html
(cl:defclass <navdata_vision_of> (roslisp-msg-protocol:ros-message)
((header
:reader header
:initarg :header
:type std_msgs-msg:Header
:initform (cl:make-instance 'std_msgs-msg:Header))
(drone_time
:reader drone_time
:initarg :drone_time
:type cl:float
:initform 0.0)
(tag
:reader tag
:initarg :tag
:type cl:fixnum
:initform 0)
(size
:reader size
:initarg :size
:type cl:fixnum
:initform 0)
(of_dx
:reader of_dx
:initarg :of_dx
:type (cl:vector cl:float)
:initform (cl:make-array 0 :element-type 'cl:float :initial-element 0.0))
(of_dy
:reader of_dy
:initarg :of_dy
:type (cl:vector cl:float)
:initform (cl:make-array 0 :element-type 'cl:float :initial-element 0.0)))
)
(cl:defclass navdata_vision_of (<navdata_vision_of>)
())
(cl:defmethod cl:initialize-instance :after ((m <navdata_vision_of>) cl:&rest args)
(cl:declare (cl:ignorable args))
(cl:unless (cl:typep m 'navdata_vision_of)
(roslisp-msg-protocol:msg-deprecation-warning "using old message class name ardrone_autonomy-msg:<navdata_vision_of> is deprecated: use ardrone_autonomy-msg:navdata_vision_of instead.")))
(cl:ensure-generic-function 'header-val :lambda-list '(m))
(cl:defmethod header-val ((m <navdata_vision_of>))
(roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader ardrone_autonomy-msg:header-val is deprecated. Use ardrone_autonomy-msg:header instead.")
(header m))
(cl:ensure-generic-function 'drone_time-val :lambda-list '(m))
(cl:defmethod drone_time-val ((m <navdata_vision_of>))
(roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader ardrone_autonomy-msg:drone_time-val is deprecated. Use ardrone_autonomy-msg:drone_time instead.")
(drone_time m))
(cl:ensure-generic-function 'tag-val :lambda-list '(m))
(cl:defmethod tag-val ((m <navdata_vision_of>))
(roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader ardrone_autonomy-msg:tag-val is deprecated. Use ardrone_autonomy-msg:tag instead.")
(tag m))
(cl:ensure-generic-function 'size-val :lambda-list '(m))
(cl:defmethod size-val ((m <navdata_vision_of>))
(roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader ardrone_autonomy-msg:size-val is deprecated. Use ardrone_autonomy-msg:size instead.")
(size m))
(cl:ensure-generic-function 'of_dx-val :lambda-list '(m))
(cl:defmethod of_dx-val ((m <navdata_vision_of>))
(roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader ardrone_autonomy-msg:of_dx-val is deprecated. Use ardrone_autonomy-msg:of_dx instead.")
(of_dx m))
(cl:ensure-generic-function 'of_dy-val :lambda-list '(m))
(cl:defmethod of_dy-val ((m <navdata_vision_of>))
(roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader ardrone_autonomy-msg:of_dy-val is deprecated. Use ardrone_autonomy-msg:of_dy instead.")
(of_dy m))
(cl:defmethod roslisp-msg-protocol:serialize ((msg <navdata_vision_of>) ostream)
"Serializes a message object of type '<navdata_vision_of>"
(roslisp-msg-protocol:serialize (cl:slot-value msg 'header) ostream)
(cl:let ((bits (roslisp-utils:encode-double-float-bits (cl:slot-value msg 'drone_time))))
(cl:write-byte (cl:ldb (cl:byte 8 0) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 8) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 16) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 24) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 32) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 40) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 48) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 56) bits) ostream))
(cl:write-byte (cl:ldb (cl:byte 8 0) (cl:slot-value msg 'tag)) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 8) (cl:slot-value msg 'tag)) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 0) (cl:slot-value msg 'size)) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 8) (cl:slot-value msg 'size)) ostream)
(cl:let ((__ros_arr_len (cl:length (cl:slot-value msg 'of_dx))))
(cl:write-byte (cl:ldb (cl:byte 8 0) __ros_arr_len) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 8) __ros_arr_len) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 16) __ros_arr_len) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 24) __ros_arr_len) ostream))
(cl:map cl:nil #'(cl:lambda (ele) (cl:let ((bits (roslisp-utils:encode-single-float-bits ele)))
(cl:write-byte (cl:ldb (cl:byte 8 0) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 8) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 16) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 24) bits) ostream)))
(cl:slot-value msg 'of_dx))
(cl:let ((__ros_arr_len (cl:length (cl:slot-value msg 'of_dy))))
(cl:write-byte (cl:ldb (cl:byte 8 0) __ros_arr_len) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 8) __ros_arr_len) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 16) __ros_arr_len) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 24) __ros_arr_len) ostream))
(cl:map cl:nil #'(cl:lambda (ele) (cl:let ((bits (roslisp-utils:encode-single-float-bits ele)))
(cl:write-byte (cl:ldb (cl:byte 8 0) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 8) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 16) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 24) bits) ostream)))
(cl:slot-value msg 'of_dy))
)
(cl:defmethod roslisp-msg-protocol:deserialize ((msg <navdata_vision_of>) istream)
"Deserializes a message object of type '<navdata_vision_of>"
(roslisp-msg-protocol:deserialize (cl:slot-value msg 'header) istream)
(cl:let ((bits 0))
(cl:setf (cl:ldb (cl:byte 8 0) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 8) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 16) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 24) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 32) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 40) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 48) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 56) bits) (cl:read-byte istream))
(cl:setf (cl:slot-value msg 'drone_time) (roslisp-utils:decode-double-float-bits bits)))
(cl:setf (cl:ldb (cl:byte 8 0) (cl:slot-value msg 'tag)) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 8) (cl:slot-value msg 'tag)) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 0) (cl:slot-value msg 'size)) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 8) (cl:slot-value msg 'size)) (cl:read-byte istream))
(cl:let ((__ros_arr_len 0))
(cl:setf (cl:ldb (cl:byte 8 0) __ros_arr_len) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 8) __ros_arr_len) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 16) __ros_arr_len) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 24) __ros_arr_len) (cl:read-byte istream))
(cl:setf (cl:slot-value msg 'of_dx) (cl:make-array __ros_arr_len))
(cl:let ((vals (cl:slot-value msg 'of_dx)))
(cl:dotimes (i __ros_arr_len)
(cl:let ((bits 0))
(cl:setf (cl:ldb (cl:byte 8 0) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 8) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 16) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 24) bits) (cl:read-byte istream))
(cl:setf (cl:aref vals i) (roslisp-utils:decode-single-float-bits bits))))))
(cl:let ((__ros_arr_len 0))
(cl:setf (cl:ldb (cl:byte 8 0) __ros_arr_len) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 8) __ros_arr_len) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 16) __ros_arr_len) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 24) __ros_arr_len) (cl:read-byte istream))
(cl:setf (cl:slot-value msg 'of_dy) (cl:make-array __ros_arr_len))
(cl:let ((vals (cl:slot-value msg 'of_dy)))
(cl:dotimes (i __ros_arr_len)
(cl:let ((bits 0))
(cl:setf (cl:ldb (cl:byte 8 0) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 8) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 16) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 24) bits) (cl:read-byte istream))
(cl:setf (cl:aref vals i) (roslisp-utils:decode-single-float-bits bits))))))
msg
)
(cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql '<navdata_vision_of>)))
"Returns string type for a message object of type '<navdata_vision_of>"
"ardrone_autonomy/navdata_vision_of")
(cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql 'navdata_vision_of)))
"Returns string type for a message object of type 'navdata_vision_of"
"ardrone_autonomy/navdata_vision_of")
(cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql '<navdata_vision_of>)))
"Returns md5sum for a message object of type '<navdata_vision_of>"
"76d31747173a842fbf71db03104edecd")
(cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql 'navdata_vision_of)))
"Returns md5sum for a message object of type 'navdata_vision_of"
"76d31747173a842fbf71db03104edecd")
(cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql '<navdata_vision_of>)))
"Returns full string definition for message of type '<navdata_vision_of>"
(cl:format cl:nil "Header header~%float64 drone_time~%uint16 tag~%uint16 size~%float32[] of_dx~%float32[] of_dy~%~%================================================================================~%MSG: std_msgs/Header~%# Standard metadata for higher-level stamped data types.~%# This is generally used to communicate timestamped data ~%# in a particular coordinate frame.~%# ~%# sequence ID: consecutively increasing ID ~%uint32 seq~%#Two-integer timestamp that is expressed as:~%# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')~%# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')~%# time-handling sugar is provided by the client library~%time stamp~%#Frame this data is associated with~%# 0: no frame~%# 1: global frame~%string frame_id~%~%~%"))
(cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql 'navdata_vision_of)))
"Returns full string definition for message of type 'navdata_vision_of"
(cl:format cl:nil "Header header~%float64 drone_time~%uint16 tag~%uint16 size~%float32[] of_dx~%float32[] of_dy~%~%================================================================================~%MSG: std_msgs/Header~%# Standard metadata for higher-level stamped data types.~%# This is generally used to communicate timestamped data ~%# in a particular coordinate frame.~%# ~%# sequence ID: consecutively increasing ID ~%uint32 seq~%#Two-integer timestamp that is expressed as:~%# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')~%# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')~%# time-handling sugar is provided by the client library~%time stamp~%#Frame this data is associated with~%# 0: no frame~%# 1: global frame~%string frame_id~%~%~%"))
(cl:defmethod roslisp-msg-protocol:serialization-length ((msg <navdata_vision_of>))
(cl:+ 0
(roslisp-msg-protocol:serialization-length (cl:slot-value msg 'header))
8
2
2
4 (cl:reduce #'cl:+ (cl:slot-value msg 'of_dx) :key #'(cl:lambda (ele) (cl:declare (cl:ignorable ele)) (cl:+ 4)))
4 (cl:reduce #'cl:+ (cl:slot-value msg 'of_dy) :key #'(cl:lambda (ele) (cl:declare (cl:ignorable ele)) (cl:+ 4)))
))
(cl:defmethod roslisp-msg-protocol:ros-message-to-list ((msg <navdata_vision_of>))
"Converts a ROS message object to a list"
(cl:list 'navdata_vision_of
(cl:cons ':header (header msg))
(cl:cons ':drone_time (drone_time msg))
(cl:cons ':tag (tag msg))
(cl:cons ':size (size msg))
(cl:cons ':of_dx (of_dx msg))
(cl:cons ':of_dy (of_dy msg))
))
| null | https://raw.githubusercontent.com/pavankumarbn/DroneGUIROS/745320d73035bc50ac4fea2699e22586e10be800/devel/share/common-lisp/ros/ardrone_autonomy/msg/navdata_vision_of.lisp | lisp | Auto-generated. Do not edit!
//! \htmlinclude navdata_vision_of.msg.html |
(cl:in-package ardrone_autonomy-msg)
(cl:defclass <navdata_vision_of> (roslisp-msg-protocol:ros-message)
((header
:reader header
:initarg :header
:type std_msgs-msg:Header
:initform (cl:make-instance 'std_msgs-msg:Header))
(drone_time
:reader drone_time
:initarg :drone_time
:type cl:float
:initform 0.0)
(tag
:reader tag
:initarg :tag
:type cl:fixnum
:initform 0)
(size
:reader size
:initarg :size
:type cl:fixnum
:initform 0)
(of_dx
:reader of_dx
:initarg :of_dx
:type (cl:vector cl:float)
:initform (cl:make-array 0 :element-type 'cl:float :initial-element 0.0))
(of_dy
:reader of_dy
:initarg :of_dy
:type (cl:vector cl:float)
:initform (cl:make-array 0 :element-type 'cl:float :initial-element 0.0)))
)
(cl:defclass navdata_vision_of (<navdata_vision_of>)
())
(cl:defmethod cl:initialize-instance :after ((m <navdata_vision_of>) cl:&rest args)
(cl:declare (cl:ignorable args))
(cl:unless (cl:typep m 'navdata_vision_of)
(roslisp-msg-protocol:msg-deprecation-warning "using old message class name ardrone_autonomy-msg:<navdata_vision_of> is deprecated: use ardrone_autonomy-msg:navdata_vision_of instead.")))
(cl:ensure-generic-function 'header-val :lambda-list '(m))
(cl:defmethod header-val ((m <navdata_vision_of>))
(roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader ardrone_autonomy-msg:header-val is deprecated. Use ardrone_autonomy-msg:header instead.")
(header m))
(cl:ensure-generic-function 'drone_time-val :lambda-list '(m))
(cl:defmethod drone_time-val ((m <navdata_vision_of>))
(roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader ardrone_autonomy-msg:drone_time-val is deprecated. Use ardrone_autonomy-msg:drone_time instead.")
(drone_time m))
(cl:ensure-generic-function 'tag-val :lambda-list '(m))
(cl:defmethod tag-val ((m <navdata_vision_of>))
(roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader ardrone_autonomy-msg:tag-val is deprecated. Use ardrone_autonomy-msg:tag instead.")
(tag m))
(cl:ensure-generic-function 'size-val :lambda-list '(m))
(cl:defmethod size-val ((m <navdata_vision_of>))
(roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader ardrone_autonomy-msg:size-val is deprecated. Use ardrone_autonomy-msg:size instead.")
(size m))
(cl:ensure-generic-function 'of_dx-val :lambda-list '(m))
(cl:defmethod of_dx-val ((m <navdata_vision_of>))
(roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader ardrone_autonomy-msg:of_dx-val is deprecated. Use ardrone_autonomy-msg:of_dx instead.")
(of_dx m))
(cl:ensure-generic-function 'of_dy-val :lambda-list '(m))
(cl:defmethod of_dy-val ((m <navdata_vision_of>))
(roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader ardrone_autonomy-msg:of_dy-val is deprecated. Use ardrone_autonomy-msg:of_dy instead.")
(of_dy m))
(cl:defmethod roslisp-msg-protocol:serialize ((msg <navdata_vision_of>) ostream)
"Serializes a message object of type '<navdata_vision_of>"
(roslisp-msg-protocol:serialize (cl:slot-value msg 'header) ostream)
(cl:let ((bits (roslisp-utils:encode-double-float-bits (cl:slot-value msg 'drone_time))))
(cl:write-byte (cl:ldb (cl:byte 8 0) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 8) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 16) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 24) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 32) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 40) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 48) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 56) bits) ostream))
(cl:write-byte (cl:ldb (cl:byte 8 0) (cl:slot-value msg 'tag)) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 8) (cl:slot-value msg 'tag)) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 0) (cl:slot-value msg 'size)) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 8) (cl:slot-value msg 'size)) ostream)
(cl:let ((__ros_arr_len (cl:length (cl:slot-value msg 'of_dx))))
(cl:write-byte (cl:ldb (cl:byte 8 0) __ros_arr_len) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 8) __ros_arr_len) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 16) __ros_arr_len) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 24) __ros_arr_len) ostream))
(cl:map cl:nil #'(cl:lambda (ele) (cl:let ((bits (roslisp-utils:encode-single-float-bits ele)))
(cl:write-byte (cl:ldb (cl:byte 8 0) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 8) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 16) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 24) bits) ostream)))
(cl:slot-value msg 'of_dx))
(cl:let ((__ros_arr_len (cl:length (cl:slot-value msg 'of_dy))))
(cl:write-byte (cl:ldb (cl:byte 8 0) __ros_arr_len) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 8) __ros_arr_len) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 16) __ros_arr_len) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 24) __ros_arr_len) ostream))
(cl:map cl:nil #'(cl:lambda (ele) (cl:let ((bits (roslisp-utils:encode-single-float-bits ele)))
(cl:write-byte (cl:ldb (cl:byte 8 0) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 8) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 16) bits) ostream)
(cl:write-byte (cl:ldb (cl:byte 8 24) bits) ostream)))
(cl:slot-value msg 'of_dy))
)
(cl:defmethod roslisp-msg-protocol:deserialize ((msg <navdata_vision_of>) istream)
"Deserializes a message object of type '<navdata_vision_of>"
(roslisp-msg-protocol:deserialize (cl:slot-value msg 'header) istream)
(cl:let ((bits 0))
(cl:setf (cl:ldb (cl:byte 8 0) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 8) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 16) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 24) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 32) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 40) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 48) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 56) bits) (cl:read-byte istream))
(cl:setf (cl:slot-value msg 'drone_time) (roslisp-utils:decode-double-float-bits bits)))
(cl:setf (cl:ldb (cl:byte 8 0) (cl:slot-value msg 'tag)) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 8) (cl:slot-value msg 'tag)) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 0) (cl:slot-value msg 'size)) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 8) (cl:slot-value msg 'size)) (cl:read-byte istream))
(cl:let ((__ros_arr_len 0))
(cl:setf (cl:ldb (cl:byte 8 0) __ros_arr_len) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 8) __ros_arr_len) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 16) __ros_arr_len) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 24) __ros_arr_len) (cl:read-byte istream))
(cl:setf (cl:slot-value msg 'of_dx) (cl:make-array __ros_arr_len))
(cl:let ((vals (cl:slot-value msg 'of_dx)))
(cl:dotimes (i __ros_arr_len)
(cl:let ((bits 0))
(cl:setf (cl:ldb (cl:byte 8 0) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 8) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 16) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 24) bits) (cl:read-byte istream))
(cl:setf (cl:aref vals i) (roslisp-utils:decode-single-float-bits bits))))))
(cl:let ((__ros_arr_len 0))
(cl:setf (cl:ldb (cl:byte 8 0) __ros_arr_len) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 8) __ros_arr_len) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 16) __ros_arr_len) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 24) __ros_arr_len) (cl:read-byte istream))
(cl:setf (cl:slot-value msg 'of_dy) (cl:make-array __ros_arr_len))
(cl:let ((vals (cl:slot-value msg 'of_dy)))
(cl:dotimes (i __ros_arr_len)
(cl:let ((bits 0))
(cl:setf (cl:ldb (cl:byte 8 0) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 8) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 16) bits) (cl:read-byte istream))
(cl:setf (cl:ldb (cl:byte 8 24) bits) (cl:read-byte istream))
(cl:setf (cl:aref vals i) (roslisp-utils:decode-single-float-bits bits))))))
msg
)
(cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql '<navdata_vision_of>)))
"Returns string type for a message object of type '<navdata_vision_of>"
"ardrone_autonomy/navdata_vision_of")
(cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql 'navdata_vision_of)))
"Returns string type for a message object of type 'navdata_vision_of"
"ardrone_autonomy/navdata_vision_of")
(cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql '<navdata_vision_of>)))
"Returns md5sum for a message object of type '<navdata_vision_of>"
"76d31747173a842fbf71db03104edecd")
(cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql 'navdata_vision_of)))
"Returns md5sum for a message object of type 'navdata_vision_of"
"76d31747173a842fbf71db03104edecd")
(cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql '<navdata_vision_of>)))
"Returns full string definition for message of type '<navdata_vision_of>"
(cl:format cl:nil "Header header~%float64 drone_time~%uint16 tag~%uint16 size~%float32[] of_dx~%float32[] of_dy~%~%================================================================================~%MSG: std_msgs/Header~%# Standard metadata for higher-level stamped data types.~%# This is generally used to communicate timestamped data ~%# in a particular coordinate frame.~%# ~%# sequence ID: consecutively increasing ID ~%uint32 seq~%#Two-integer timestamp that is expressed as:~%# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')~%# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')~%# time-handling sugar is provided by the client library~%time stamp~%#Frame this data is associated with~%# 0: no frame~%# 1: global frame~%string frame_id~%~%~%"))
(cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql 'navdata_vision_of)))
"Returns full string definition for message of type 'navdata_vision_of"
(cl:format cl:nil "Header header~%float64 drone_time~%uint16 tag~%uint16 size~%float32[] of_dx~%float32[] of_dy~%~%================================================================================~%MSG: std_msgs/Header~%# Standard metadata for higher-level stamped data types.~%# This is generally used to communicate timestamped data ~%# in a particular coordinate frame.~%# ~%# sequence ID: consecutively increasing ID ~%uint32 seq~%#Two-integer timestamp that is expressed as:~%# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')~%# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')~%# time-handling sugar is provided by the client library~%time stamp~%#Frame this data is associated with~%# 0: no frame~%# 1: global frame~%string frame_id~%~%~%"))
(cl:defmethod roslisp-msg-protocol:serialization-length ((msg <navdata_vision_of>))
(cl:+ 0
(roslisp-msg-protocol:serialization-length (cl:slot-value msg 'header))
8
2
2
4 (cl:reduce #'cl:+ (cl:slot-value msg 'of_dx) :key #'(cl:lambda (ele) (cl:declare (cl:ignorable ele)) (cl:+ 4)))
4 (cl:reduce #'cl:+ (cl:slot-value msg 'of_dy) :key #'(cl:lambda (ele) (cl:declare (cl:ignorable ele)) (cl:+ 4)))
))
(cl:defmethod roslisp-msg-protocol:ros-message-to-list ((msg <navdata_vision_of>))
"Converts a ROS message object to a list"
(cl:list 'navdata_vision_of
(cl:cons ':header (header msg))
(cl:cons ':drone_time (drone_time msg))
(cl:cons ':tag (tag msg))
(cl:cons ':size (size msg))
(cl:cons ':of_dx (of_dx msg))
(cl:cons ':of_dy (of_dy msg))
))
|
be882e861532391b7a481f02454cf9b0ed8e92bf8b36157d274ca469a1fc02f0 | pykello/racket-graphviz | example.rkt | #lang racket
(require pict)
(require graphviz)
(define examples
`(
graph 1
(["A" #:shape "diamond"]
["B" #:shape "box"]
["C" #:shape "circle"]
[("A" "B") #:style "dashed" #:color "grey"]
[("A" "C") #:color "black:invis:black"]
[("A" "D") #:penwidth "5" #:arrowhead "none"])
graph 2
([subgraph "process #1"
#:style "filled"
#:color "lightgrey"
("a0 -> a1 -> a2 -> a3")]
[subgraph "process #2"
#:color "blue"
("b0 -> b1 -> b2 -> b3")]
"start -> a0"
"start -> b0"
"a1 -> b3"
"b2 -> a3"
"a3 -> a0"
"a3 -> end"
"b3 -> end"
["start" #:shape "Mdiamond"]
["end" #:shape "Msquare"])
;;
(["a" #:shape "diamond" #:fillcolor "lightgray" #:style "filled"]
["b" #:shape ,(cloud 60 30) #:label "c"]
["c" #:shape ,(standard-fish 100 50 #:open-mouth #t #:color "Chartreuse")
#:label ""]
"d"
"a -> b -> c"
"a -> d -> c"
(subgraph "stdout" #:style "filled" #:fillcolor "cyan"
(["f" #:shape ,(file-icon 50 60 "bisque")]
"g"
"f -> g"))
"d -> g")))
(for/list ([d examples])
(digraph->pict (make-digraph d)))
| null | https://raw.githubusercontent.com/pykello/racket-graphviz/9486fa524e22e2a04ae20a36b0c1c426716981b5/example.rkt | racket | #lang racket
(require pict)
(require graphviz)
(define examples
`(
graph 1
(["A" #:shape "diamond"]
["B" #:shape "box"]
["C" #:shape "circle"]
[("A" "B") #:style "dashed" #:color "grey"]
[("A" "C") #:color "black:invis:black"]
[("A" "D") #:penwidth "5" #:arrowhead "none"])
graph 2
([subgraph "process #1"
#:style "filled"
#:color "lightgrey"
("a0 -> a1 -> a2 -> a3")]
[subgraph "process #2"
#:color "blue"
("b0 -> b1 -> b2 -> b3")]
"start -> a0"
"start -> b0"
"a1 -> b3"
"b2 -> a3"
"a3 -> a0"
"a3 -> end"
"b3 -> end"
["start" #:shape "Mdiamond"]
["end" #:shape "Msquare"])
(["a" #:shape "diamond" #:fillcolor "lightgray" #:style "filled"]
["b" #:shape ,(cloud 60 30) #:label "c"]
["c" #:shape ,(standard-fish 100 50 #:open-mouth #t #:color "Chartreuse")
#:label ""]
"d"
"a -> b -> c"
"a -> d -> c"
(subgraph "stdout" #:style "filled" #:fillcolor "cyan"
(["f" #:shape ,(file-icon 50 60 "bisque")]
"g"
"f -> g"))
"d -> g")))
(for/list ([d examples])
(digraph->pict (make-digraph d)))
| |
70694a5ab79e6e5ca10a1f52b706be4ab28b8c23c5aeaeea0b5bc70e22ea83c6 | TheLortex/mirage-monorepo | ppxlib_print_diff.ml | open StdLabels
let patdiff_cmd ~use_color ~extra_patdiff_args =
let args =
List.concat
[
[ "-keep-whitespace" ];
[ "-location-style omake" ];
(if use_color then [] else [ "-ascii" ]);
extra_patdiff_args;
]
in
String.concat ~sep:" " ("patdiff" :: args)
let print ?diff_command ?(extra_patdiff_args = []) ?(use_color = false) ~file1
~file2 () =
let exec cmd =
let cmd =
Printf.sprintf "%s %s %s 1>&2" cmd (Filename.quote file1)
(Filename.quote file2)
in
match Sys.command cmd with
| 0 -> `Same
| 1 -> `Different
| n -> `Error (n, cmd)
in
match diff_command with
| Some s -> ignore (exec s : [> `Same | `Different | `Error of int * string ])
| None -> (
match exec (patdiff_cmd ~use_color ~extra_patdiff_args) with
| `Same ->
(* patdiff produced no output, fallback to diff -u *)
Printf.eprintf "File \"%s\", line 1, characters 0-0:\n%!" file1;
ignore
(exec "diff -u" : [> `Same | `Different | `Error of int * string ])
| `Different ->
(* patdiff successfully found a difference *)
()
| `Error (err_code, cmd) ->
threw an error ... perhaps it was n't installed ? fallback to diff -u
Printf.eprintf
"Error:\n\
> %S exited with code %d\n\
> Perhaps patdiff is not installed? Hint, try: opam install patdiff\n\
> Falling back to diff -u\n\n"
cmd err_code;
Printf.eprintf "File \"%s\", line 1, characters 0-0:\n%!" file1;
ignore
(exec "diff -u" : [> `Same | `Different | `Error of int * string ]))
| null | https://raw.githubusercontent.com/TheLortex/mirage-monorepo/b557005dfe5a51fc50f0597d82c450291cfe8a2a/duniverse/ppxlib/print-diff/ppxlib_print_diff.ml | ocaml | patdiff produced no output, fallback to diff -u
patdiff successfully found a difference | open StdLabels
let patdiff_cmd ~use_color ~extra_patdiff_args =
let args =
List.concat
[
[ "-keep-whitespace" ];
[ "-location-style omake" ];
(if use_color then [] else [ "-ascii" ]);
extra_patdiff_args;
]
in
String.concat ~sep:" " ("patdiff" :: args)
let print ?diff_command ?(extra_patdiff_args = []) ?(use_color = false) ~file1
~file2 () =
let exec cmd =
let cmd =
Printf.sprintf "%s %s %s 1>&2" cmd (Filename.quote file1)
(Filename.quote file2)
in
match Sys.command cmd with
| 0 -> `Same
| 1 -> `Different
| n -> `Error (n, cmd)
in
match diff_command with
| Some s -> ignore (exec s : [> `Same | `Different | `Error of int * string ])
| None -> (
match exec (patdiff_cmd ~use_color ~extra_patdiff_args) with
| `Same ->
Printf.eprintf "File \"%s\", line 1, characters 0-0:\n%!" file1;
ignore
(exec "diff -u" : [> `Same | `Different | `Error of int * string ])
| `Different ->
()
| `Error (err_code, cmd) ->
threw an error ... perhaps it was n't installed ? fallback to diff -u
Printf.eprintf
"Error:\n\
> %S exited with code %d\n\
> Perhaps patdiff is not installed? Hint, try: opam install patdiff\n\
> Falling back to diff -u\n\n"
cmd err_code;
Printf.eprintf "File \"%s\", line 1, characters 0-0:\n%!" file1;
ignore
(exec "diff -u" : [> `Same | `Different | `Error of int * string ]))
|
5457090498ce21ad9492cd29ba51f77870c56fb06139971505ee4dbe37d96a89 | alvatar/spheres | util-profile.scm | (import ../src/profile)
(define (ring n)
(if (and (integer? n)
(exact? n)
(>= n 2)
(<= n 1000000))
(let ((m (quotient 1000000 n)))
(joes-challenge n m))
(error "invalid arg to ring")))
(define (joes-challenge n m)
(define (iota n)
(iota-aux n '()))
(define (iota-aux n lst)
(if (= n 0)
lst
(iota-aux (- n 1) (cons n lst))))
(define (create-processes)
(let* ((one-to-n
(iota n))
(channels
(list->vector
(map (lambda (i) (open-vector))
one-to-n)))
(processes
(map (lambda (i)
(let ((input (vector-ref channels (modulo (- i 1) n)))
(output (vector-ref channels (modulo i n))))
(make-thread
(lambda ()
(let loop ((j m))
(if (> j 0)
(let ((message (read input)))
(write message output)
(force-output output)
(loop (- j 1)))))))))
one-to-n)))
(write 'go (vector-ref channels 1))
(force-output (vector-ref channels 1))
processes))
(let* ((point1
(cpu-time))
(processes
(create-processes))
(point2
(cpu-time)))
(for-each thread-start! processes)
(thread-join! (car processes))
(let ((point3
(cpu-time)))
(display n)
(display " ")
(display (/ (- point2 point1) n))
(display " ")
(display (/ (- point3 point2) (* n m)))
(newline))))
(profile-start!)
(ring 10000)
(profile-stop!)
(write-profile-report "ring")
| null | https://raw.githubusercontent.com/alvatar/spheres/568836f234a469ef70c69f4a2d9b56d41c3fc5bd/test/util-profile.scm | scheme | (import ../src/profile)
(define (ring n)
(if (and (integer? n)
(exact? n)
(>= n 2)
(<= n 1000000))
(let ((m (quotient 1000000 n)))
(joes-challenge n m))
(error "invalid arg to ring")))
(define (joes-challenge n m)
(define (iota n)
(iota-aux n '()))
(define (iota-aux n lst)
(if (= n 0)
lst
(iota-aux (- n 1) (cons n lst))))
(define (create-processes)
(let* ((one-to-n
(iota n))
(channels
(list->vector
(map (lambda (i) (open-vector))
one-to-n)))
(processes
(map (lambda (i)
(let ((input (vector-ref channels (modulo (- i 1) n)))
(output (vector-ref channels (modulo i n))))
(make-thread
(lambda ()
(let loop ((j m))
(if (> j 0)
(let ((message (read input)))
(write message output)
(force-output output)
(loop (- j 1)))))))))
one-to-n)))
(write 'go (vector-ref channels 1))
(force-output (vector-ref channels 1))
processes))
(let* ((point1
(cpu-time))
(processes
(create-processes))
(point2
(cpu-time)))
(for-each thread-start! processes)
(thread-join! (car processes))
(let ((point3
(cpu-time)))
(display n)
(display " ")
(display (/ (- point2 point1) n))
(display " ")
(display (/ (- point3 point2) (* n m)))
(newline))))
(profile-start!)
(ring 10000)
(profile-stop!)
(write-profile-report "ring")
| |
ed775363ef41fe2f7b1f3864c78a1396753c32feb4edb6e6cdd95e2c0051952e | pepeiborra/term | Term.hs | # LANGUAGE TypeFamilies #
module Data.Term (
-- * Type Families
Term, Var, Id,
-- * Terms
TermF, TermFor, UnwrappedTermFor, foldTerm, foldTermM, mapTerm, evalTerm,
-- * Subterms
subterms, properSubterms, directSubterms, mapSubterms, mapMSubterms, collect,
someSubterm, someSubterm', someSubtermDeep,
-- * Positions
Position, positions, (!), (!*), (!?), updateAt, updateAt', updateAtM, occurrences,
-- * Variables
Rename(..), isVar, vars, isLinear,
-- * Annotating terms
WithNote(..), WithNote1(..), note, dropNote, noteV, annotateWithPos, annotateWithPosV, annotate,
-- * Ids
HasId(..), HasId1(..), MapId(..), rootSymbol, mapRootSymbol, mapTermSymbols, mapTermSymbolsM,
-- * Matching & Unification (without occurs check)
Match(..), Unify(..), unify, unifies, occursIn,
match, matches, equiv, equiv2, EqModulo(..),
-- * Substitutions
Substitution, Substitution_(..), SubstitutionFor,
mapSubst, fromListSubst, domain, codomain, subst, unSubst,
lookupSubst, applySubst, zonkTerm, zonkTermM, zonkSubst, isEmpty, isRenaming, restrictTo, liftSubst,
equiv, equiv2, EqModulo(..),
-- * Variables
GetVars(..), GetFresh(..), getFresh, getVariant, getFreshMdefault,
-- * Environment monad
MonadEnv(..), find', MEnvT, evalMEnv, execMEnv, runMEnv, evalMEnv, execMEnv, runMEnv,
-- * Fresh monad
MonadVariant(..), fresh, freshWith, freshWith', variant
) where
import Control.Monad.Env
import Control.Monad.Variant
import Data.Term.Base
import Data.Term.Family
import Data.Term.Substitutions
import Prelude.Extras
type instance Id (Lift1 f) = Id f
| null | https://raw.githubusercontent.com/pepeiborra/term/7644e0f8fbc81754fd5255602dd1f799adcd5938/Data/Term.hs | haskell | * Type Families
* Terms
* Subterms
* Positions
* Variables
* Annotating terms
* Ids
* Matching & Unification (without occurs check)
* Substitutions
* Variables
* Environment monad
* Fresh monad | # LANGUAGE TypeFamilies #
module Data.Term (
Term, Var, Id,
TermF, TermFor, UnwrappedTermFor, foldTerm, foldTermM, mapTerm, evalTerm,
subterms, properSubterms, directSubterms, mapSubterms, mapMSubterms, collect,
someSubterm, someSubterm', someSubtermDeep,
Position, positions, (!), (!*), (!?), updateAt, updateAt', updateAtM, occurrences,
Rename(..), isVar, vars, isLinear,
WithNote(..), WithNote1(..), note, dropNote, noteV, annotateWithPos, annotateWithPosV, annotate,
HasId(..), HasId1(..), MapId(..), rootSymbol, mapRootSymbol, mapTermSymbols, mapTermSymbolsM,
Match(..), Unify(..), unify, unifies, occursIn,
match, matches, equiv, equiv2, EqModulo(..),
Substitution, Substitution_(..), SubstitutionFor,
mapSubst, fromListSubst, domain, codomain, subst, unSubst,
lookupSubst, applySubst, zonkTerm, zonkTermM, zonkSubst, isEmpty, isRenaming, restrictTo, liftSubst,
equiv, equiv2, EqModulo(..),
GetVars(..), GetFresh(..), getFresh, getVariant, getFreshMdefault,
MonadEnv(..), find', MEnvT, evalMEnv, execMEnv, runMEnv, evalMEnv, execMEnv, runMEnv,
MonadVariant(..), fresh, freshWith, freshWith', variant
) where
import Control.Monad.Env
import Control.Monad.Variant
import Data.Term.Base
import Data.Term.Family
import Data.Term.Substitutions
import Prelude.Extras
type instance Id (Lift1 f) = Id f
|
01134088b47bef528ffc150170e068140ed0472872fa8206284f2ffe644f9e28 | postspectacular/devart-codefactory | tree.cljs | (ns codefactory.editor.tree
(:require
[codefactory.config :as config]
[codefactory.webgl :as webgl]
[thi.ng.cljs.async :as async]
[thi.ng.cljs.log :refer [debug info warn]]
[thi.ng.geom.core :as g]
[thi.ng.geom.core.vector :as v :refer [vec2 vec3]]
[thi.ng.geom.basicmesh :as bm]
[thi.ng.geom.aabb :as a]
[thi.ng.geom.cuboid :as cu]
[thi.ng.geom.types.utils :as tu]
[thi.ng.morphogen.core :as mg]
[thi.ng.common.math.core :as m]))
(def direction-ids [:x :y :z])
(def direction-idx {:x 0 :y 1 :z 2})
(def face-ids [:e :w :n :s :f :b])
(def face-idx {:e 0 :w 1 :n 2 :s 3 :f 4 :b 5})
(def face-labels ["east" "west" "north" "south" "front" "back"])
(def direction-labels ["x" "y" "z"])
(defn op-args-or-default
[id node default]
(:args (if (= id (:op node)) node default)))
(def child-path (memoize mg/child-path))
(defn node-at
[tree path]
(if (seq path) (get-in tree (child-path path)) tree))
(defn num-children-at
[tree path]
(count (:out (node-at tree path))))
(defn set-node-at
[tree path node]
(if (seq path) (assoc-in tree (child-path path) node) node))
(defn delete-node-at
[tree path]
(if (seq path) (assoc-in tree (child-path path) nil) {}))
(defn node-operator
[n] (cond (:op n) (:op n), n :leaf, :else :delete))
(defn select-sub-paths
[coll root]
(let [croot (count root)]
(->> (keys coll)
(reduce
(fn [acc k]
(if (> (count k) croot)
(if (every? #(= (nth % 0) (nth % 1)) (partition 2 (interleave root k)))
(conj acc k)
acc)
acc))
[])
(select-keys coll))))
(defn select-direct-children
[coll root]
(let [croot (inc (count root))]
(->> (keys coll)
(reduce
(fn [acc k]
(if (= (count k) croot)
(if (every? #(= (nth % 0) (nth % 1)) (partition 2 (interleave root k)))
(conj acc k)
acc)
acc))
[])
(select-keys coll))))
(defn delete-branch-meshes
[gl meshes root incl-root?]
(let [d-meshes (select-sub-paths meshes root)
d-meshes (if incl-root? (conj d-meshes [root (meshes root)]) d-meshes)
meshes (apply dissoc meshes (keys d-meshes))]
(webgl/delete-meshes gl (vals d-meshes))
meshes))
(defn compute-tree-depth
[nodes]
(->> nodes keys (mapv count) (reduce max) (inc)))
(defn compute-densest-branch
[tree path w min-w max-p]
(let [children (:out (node-at tree path))
n (count children)]
(if (pos? n)
(let [w' (/ w n)
[min-w max-p] (if (< w' min-w) [w' path] [min-w max-p])]
(loop [i 0, min-w min-w, max-p max-p]
(if (< i n)
(let [[min-w max-p] (compute-densest-branch
tree (conj path i) w' min-w max-p)]
(recur (inc i) min-w max-p))
[min-w max-p])))
[min-w max-p])))
(defn recompute-tree-with-seed
[state tree seed-id]
(let [nodes (mg/compute-tree-map (:seed (config/seeds (keyword seed-id))) tree)]
(merge
state
{:tree tree
:node-cache nodes
:meshes {}
:seed-id seed-id
:selection nil
:tree-depth (compute-tree-depth nodes)
:max-nodes-path (peek (compute-densest-branch tree [] 1 1 []))})))
(defn init-tree-with-seed
[state seed-id]
(recompute-tree-with-seed state {} seed-id))
(defn filter-leaves-and-selection
[coll tree sel]
(->> coll
(filter
(fn [[path]]
(or (= path sel) (= :leaf (mg/classify-node-at tree path)))))
(into {})))
(defn compute-branch-meshes
[gl meshes branch]
(->> branch
(reduce
(fn [acc [path node]]
(assoc!
acc path
(->> node
(g/faces)
(g/into (bm/basic-mesh))
(webgl/mesh-buffer gl))))
(transient meshes))
(persistent!)))
(defn update-meshes
[state incl-sel?]
(let [{:keys [gl tree node-cache selection meshes]} state
path (or selection [])
root (get node-cache path)
sub-tree (node-at tree path)
meshes (delete-branch-meshes gl meshes path incl-sel?)
branch (select-sub-paths node-cache path)
node-cache (apply dissoc node-cache (keys branch)) ;; delete all sub-paths
branch (->> path
(mg/compute-tree-map* root sub-tree (transient {}))
(persistent!))
meshes (compute-branch-meshes gl meshes branch)
node-cache (merge node-cache branch)
selection (if-not (and incl-sel? (nil? sub-tree)) selection)]
(debug :ct (keys node-cache) :meshes (keys meshes))
(merge
state
{:node-cache node-cache
:meshes meshes
:selection selection
:display-meshes (filter-leaves-and-selection meshes tree selection)})))
(defn update-stats
[state]
(let [{:keys [node-cache tree display-meshes]} @state
[min-w path] (compute-densest-branch tree [] 1 1 [])
depth (compute-tree-depth node-cache)
bounds (if (seq display-meshes)
(tu/coll-bounds (vals (select-keys node-cache (keys display-meshes))))
(a/aabb 0))]
(debug :path path :depth depth)
(swap!
state assoc
:max-nodes-path path
:tree-depth depth
:bounds bounds)))
(defn node-shortest-edge
[node]
(->> node
(:points)
(thi.ng.geom.types.Cuboid.)
(g/edges)
(reduce (fn [acc e] (min acc (apply g/dist-squared e))) 1e9)
(Math/sqrt)))
| null | https://raw.githubusercontent.com/postspectacular/devart-codefactory/9bccdc10e58fa4861a69767e9ae4be0bb8d7f650/src-cljs/codefactory/editor/tree.cljs | clojure | delete all sub-paths | (ns codefactory.editor.tree
(:require
[codefactory.config :as config]
[codefactory.webgl :as webgl]
[thi.ng.cljs.async :as async]
[thi.ng.cljs.log :refer [debug info warn]]
[thi.ng.geom.core :as g]
[thi.ng.geom.core.vector :as v :refer [vec2 vec3]]
[thi.ng.geom.basicmesh :as bm]
[thi.ng.geom.aabb :as a]
[thi.ng.geom.cuboid :as cu]
[thi.ng.geom.types.utils :as tu]
[thi.ng.morphogen.core :as mg]
[thi.ng.common.math.core :as m]))
(def direction-ids [:x :y :z])
(def direction-idx {:x 0 :y 1 :z 2})
(def face-ids [:e :w :n :s :f :b])
(def face-idx {:e 0 :w 1 :n 2 :s 3 :f 4 :b 5})
(def face-labels ["east" "west" "north" "south" "front" "back"])
(def direction-labels ["x" "y" "z"])
(defn op-args-or-default
[id node default]
(:args (if (= id (:op node)) node default)))
(def child-path (memoize mg/child-path))
(defn node-at
[tree path]
(if (seq path) (get-in tree (child-path path)) tree))
(defn num-children-at
[tree path]
(count (:out (node-at tree path))))
(defn set-node-at
[tree path node]
(if (seq path) (assoc-in tree (child-path path) node) node))
(defn delete-node-at
[tree path]
(if (seq path) (assoc-in tree (child-path path) nil) {}))
(defn node-operator
[n] (cond (:op n) (:op n), n :leaf, :else :delete))
(defn select-sub-paths
[coll root]
(let [croot (count root)]
(->> (keys coll)
(reduce
(fn [acc k]
(if (> (count k) croot)
(if (every? #(= (nth % 0) (nth % 1)) (partition 2 (interleave root k)))
(conj acc k)
acc)
acc))
[])
(select-keys coll))))
(defn select-direct-children
[coll root]
(let [croot (inc (count root))]
(->> (keys coll)
(reduce
(fn [acc k]
(if (= (count k) croot)
(if (every? #(= (nth % 0) (nth % 1)) (partition 2 (interleave root k)))
(conj acc k)
acc)
acc))
[])
(select-keys coll))))
(defn delete-branch-meshes
[gl meshes root incl-root?]
(let [d-meshes (select-sub-paths meshes root)
d-meshes (if incl-root? (conj d-meshes [root (meshes root)]) d-meshes)
meshes (apply dissoc meshes (keys d-meshes))]
(webgl/delete-meshes gl (vals d-meshes))
meshes))
(defn compute-tree-depth
[nodes]
(->> nodes keys (mapv count) (reduce max) (inc)))
(defn compute-densest-branch
[tree path w min-w max-p]
(let [children (:out (node-at tree path))
n (count children)]
(if (pos? n)
(let [w' (/ w n)
[min-w max-p] (if (< w' min-w) [w' path] [min-w max-p])]
(loop [i 0, min-w min-w, max-p max-p]
(if (< i n)
(let [[min-w max-p] (compute-densest-branch
tree (conj path i) w' min-w max-p)]
(recur (inc i) min-w max-p))
[min-w max-p])))
[min-w max-p])))
(defn recompute-tree-with-seed
[state tree seed-id]
(let [nodes (mg/compute-tree-map (:seed (config/seeds (keyword seed-id))) tree)]
(merge
state
{:tree tree
:node-cache nodes
:meshes {}
:seed-id seed-id
:selection nil
:tree-depth (compute-tree-depth nodes)
:max-nodes-path (peek (compute-densest-branch tree [] 1 1 []))})))
(defn init-tree-with-seed
[state seed-id]
(recompute-tree-with-seed state {} seed-id))
(defn filter-leaves-and-selection
[coll tree sel]
(->> coll
(filter
(fn [[path]]
(or (= path sel) (= :leaf (mg/classify-node-at tree path)))))
(into {})))
(defn compute-branch-meshes
[gl meshes branch]
(->> branch
(reduce
(fn [acc [path node]]
(assoc!
acc path
(->> node
(g/faces)
(g/into (bm/basic-mesh))
(webgl/mesh-buffer gl))))
(transient meshes))
(persistent!)))
(defn update-meshes
[state incl-sel?]
(let [{:keys [gl tree node-cache selection meshes]} state
path (or selection [])
root (get node-cache path)
sub-tree (node-at tree path)
meshes (delete-branch-meshes gl meshes path incl-sel?)
branch (select-sub-paths node-cache path)
branch (->> path
(mg/compute-tree-map* root sub-tree (transient {}))
(persistent!))
meshes (compute-branch-meshes gl meshes branch)
node-cache (merge node-cache branch)
selection (if-not (and incl-sel? (nil? sub-tree)) selection)]
(debug :ct (keys node-cache) :meshes (keys meshes))
(merge
state
{:node-cache node-cache
:meshes meshes
:selection selection
:display-meshes (filter-leaves-and-selection meshes tree selection)})))
(defn update-stats
[state]
(let [{:keys [node-cache tree display-meshes]} @state
[min-w path] (compute-densest-branch tree [] 1 1 [])
depth (compute-tree-depth node-cache)
bounds (if (seq display-meshes)
(tu/coll-bounds (vals (select-keys node-cache (keys display-meshes))))
(a/aabb 0))]
(debug :path path :depth depth)
(swap!
state assoc
:max-nodes-path path
:tree-depth depth
:bounds bounds)))
(defn node-shortest-edge
[node]
(->> node
(:points)
(thi.ng.geom.types.Cuboid.)
(g/edges)
(reduce (fn [acc e] (min acc (apply g/dist-squared e))) 1e9)
(Math/sqrt)))
|
45ea6a960d09d3fe830bcb5f63fa08562e7057eb17d394c651a81e5f30b5ed86 | yoshihiro503/ocamltter | conf.ml | (* Oauth_ex.Conf - [app] *)
let oauth_signature_method = `Hmac_sha1
let oauth_callback = None (* Some None (* oob *) *)
let host = "api.twitter.com"
let request_path = "/oauth/request_token"
let access_path = "/oauth/access_token"
let authorize_url = "="
| null | https://raw.githubusercontent.com/yoshihiro503/ocamltter/be7ac68c8076bc2ca8ccec216d6647c94ec9f814/twitter/conf.ml | ocaml | Oauth_ex.Conf - [app]
Some None (* oob |
let oauth_signature_method = `Hmac_sha1
let host = "api.twitter.com"
let request_path = "/oauth/request_token"
let access_path = "/oauth/access_token"
let authorize_url = "="
|
74dd57f3e6b226c0343ab7b73da2c4988bb051ba4147cd34b6a3f3a18e0a04d3 | lspitzner/brittany | Test526.hs | -- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft }
func = do
abc <- expr
abcccccccccccccccccc <- expr
abcccccccccccccccccccccccccccccccccccccccccc <- expr
abccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc <- expr
| null | https://raw.githubusercontent.com/lspitzner/brittany/a15eed5f3608bf1fa7084fcf008c6ecb79542562/data/Test526.hs | haskell | brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft } | func = do
abc <- expr
abcccccccccccccccccc <- expr
abcccccccccccccccccccccccccccccccccccccccccc <- expr
abccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc <- expr
|
9475335594b577406bed11093a8bd47ae613352d4eb003a7a10d73f305b2954f | hspec/quickcheck-io | IO.hs | # LANGUAGE CPP #
{-# LANGUAGE TypeSynonymInstances #-}
# LANGUAGE FlexibleInstances #
# OPTIONS_GHC -fno - warn - orphans #
module Test.QuickCheck.IO where
import qualified Control.Exception as E
import Test.HUnit.Lang
import Test.QuickCheck.Property
instance Testable Assertion where
property = propertyIO
#if !MIN_VERSION_QuickCheck(2,9,0)
exhaustive _ = True
#endif
propertyIO :: Assertion -> Property
propertyIO action = ioProperty $ do
(action >> return succeeded) `E.catch` \ e ->
return failed {theException = Just (E.toException e), reason = formatAssertion e}
where
formatAssertion e = case e of
#if MIN_VERSION_HUnit(1,3,0)
HUnitFailure _ err ->
#else
HUnitFailure err ->
#endif
#if MIN_VERSION_HUnit(1,5,0)
formatFailureReason err
#else
err
#endif
| null | https://raw.githubusercontent.com/hspec/quickcheck-io/7b8fb741efa277cfb772f72611e39b68b61aca15/src/Test/QuickCheck/IO.hs | haskell | # LANGUAGE TypeSynonymInstances # | # LANGUAGE CPP #
# LANGUAGE FlexibleInstances #
# OPTIONS_GHC -fno - warn - orphans #
module Test.QuickCheck.IO where
import qualified Control.Exception as E
import Test.HUnit.Lang
import Test.QuickCheck.Property
instance Testable Assertion where
property = propertyIO
#if !MIN_VERSION_QuickCheck(2,9,0)
exhaustive _ = True
#endif
propertyIO :: Assertion -> Property
propertyIO action = ioProperty $ do
(action >> return succeeded) `E.catch` \ e ->
return failed {theException = Just (E.toException e), reason = formatAssertion e}
where
formatAssertion e = case e of
#if MIN_VERSION_HUnit(1,3,0)
HUnitFailure _ err ->
#else
HUnitFailure err ->
#endif
#if MIN_VERSION_HUnit(1,5,0)
formatFailureReason err
#else
err
#endif
|
90a7694c3830eb416e33b2213946163ee2eb5683be783dc6e137cc069df15b90 | trskop/command-wrapper | Parser.hs | -- |
-- Module: $Header$
-- Description: Parser for environment variables.
Copyright : ( c ) 2018 - 2020
License : BSD3
--
-- Maintainer:
-- Stability: experimental
Portability : GHC specific language extensions .
--
Parser for environment variables .
module CommandWrapper.Core.Environment.Parser
(
* Environment
ParseEnv(..)
, ParseEnvError(..)
-- ** Evaluate Environment Parser
, parseEnv
, parseEnvIO
, parseEnvWithIO
-- ** Parsing Primitives
, var
, optionalVar
-- ** Parsing Primitives: Command Wrapper
, commandWrapperVar
, commandWrapperVar'
, commandWrapperVarName
, commandWrapperToolsetVarName
)
where
import Control.Monad ((>=>))
import Control.Monad.IO.Class (MonadIO)
import Data.Either (Either)
import Data.Functor ((<$>), (<&>))
import Control.Monad.Reader (ask)
import Data.HashMap.Strict (HashMap)
import System.Environment.Parser
( ParseEnv(..)
, ParseEnvError(..)
, optionalVar
, parseEnvWithIO
, var
)
import qualified System.Environment.Parser as Parser (parseEnv)
import CommandWrapper.Core.Environment.Variable
( CommandWrapperPrefix
, CommandWrapperVarName
, CommandWrapperToolsetVarName
, EnvVarName
, EnvVarValue
, defaultCommandWrapperPrefix
, getCommandWrapperVarName
, getCommandWrapperToolsetVarName
)
commandWrapperVar'
:: CommandWrapperVarName
-> ParseEnv CommandWrapperPrefix (EnvVarName, EnvVarValue)
commandWrapperVar' name = do
varName <- commandWrapperVarName name
(varName, ) <$> var varName
commandWrapperVar
:: CommandWrapperVarName
-> ParseEnv CommandWrapperPrefix EnvVarValue
commandWrapperVar = commandWrapperVarName >=> var
commandWrapperVarName
:: CommandWrapperVarName
-> ParseEnv CommandWrapperPrefix EnvVarName
commandWrapperVarName name =
ask <&> \prefix ->
getCommandWrapperVarName prefix name
commandWrapperToolsetVarName
:: CommandWrapperToolsetVarName
-> ParseEnv CommandWrapperPrefix EnvVarName
commandWrapperToolsetVarName name =
ask <&> \prefix ->
getCommandWrapperToolsetVarName prefix name
| Parse Command Wrapper environment variables using provided parser . It 's a
specialised version of ' Parser.parseEnv ' from " System . Environment . " :
--
-- @
-- 'parseEnv' = 'parseEnv' 'defaultCommandWrapperPrefix'
-- @
parseEnv
:: HashMap EnvVarName EnvVarValue
-> ParseEnv CommandWrapperPrefix a
-> Either ParseEnvError a
parseEnv = Parser.parseEnv defaultCommandWrapperPrefix
-- TODO: Get rid of hardcoded 'defaultCommandWrapperPrefix' at some point.
-- | Variant of 'parseEnv' that populates the environment by reading process
-- environment variables.
parseEnvIO
:: MonadIO io
=> (forall void. ParseEnvError -> io void)
-> ParseEnv CommandWrapperPrefix a
-> io a
parseEnvIO = parseEnvWithIO parseEnv
-- TODO: Get rid of hardcoded 'defaultCommandWrapperPrefix' (in 'parseEnv')
-- at some point.
| null | https://raw.githubusercontent.com/trskop/command-wrapper/4f2e2e1f63a3296ccfad9f216d75a708969890ed/command-wrapper-core/src/CommandWrapper/Core/Environment/Parser.hs | haskell | |
Module: $Header$
Description: Parser for environment variables.
Maintainer:
Stability: experimental
** Evaluate Environment Parser
** Parsing Primitives
** Parsing Primitives: Command Wrapper
@
'parseEnv' = 'parseEnv' 'defaultCommandWrapperPrefix'
@
TODO: Get rid of hardcoded 'defaultCommandWrapperPrefix' at some point.
| Variant of 'parseEnv' that populates the environment by reading process
environment variables.
TODO: Get rid of hardcoded 'defaultCommandWrapperPrefix' (in 'parseEnv')
at some point. | Copyright : ( c ) 2018 - 2020
License : BSD3
Portability : GHC specific language extensions .
Parser for environment variables .
module CommandWrapper.Core.Environment.Parser
(
* Environment
ParseEnv(..)
, ParseEnvError(..)
, parseEnv
, parseEnvIO
, parseEnvWithIO
, var
, optionalVar
, commandWrapperVar
, commandWrapperVar'
, commandWrapperVarName
, commandWrapperToolsetVarName
)
where
import Control.Monad ((>=>))
import Control.Monad.IO.Class (MonadIO)
import Data.Either (Either)
import Data.Functor ((<$>), (<&>))
import Control.Monad.Reader (ask)
import Data.HashMap.Strict (HashMap)
import System.Environment.Parser
( ParseEnv(..)
, ParseEnvError(..)
, optionalVar
, parseEnvWithIO
, var
)
import qualified System.Environment.Parser as Parser (parseEnv)
import CommandWrapper.Core.Environment.Variable
( CommandWrapperPrefix
, CommandWrapperVarName
, CommandWrapperToolsetVarName
, EnvVarName
, EnvVarValue
, defaultCommandWrapperPrefix
, getCommandWrapperVarName
, getCommandWrapperToolsetVarName
)
commandWrapperVar'
:: CommandWrapperVarName
-> ParseEnv CommandWrapperPrefix (EnvVarName, EnvVarValue)
commandWrapperVar' name = do
varName <- commandWrapperVarName name
(varName, ) <$> var varName
commandWrapperVar
:: CommandWrapperVarName
-> ParseEnv CommandWrapperPrefix EnvVarValue
commandWrapperVar = commandWrapperVarName >=> var
commandWrapperVarName
:: CommandWrapperVarName
-> ParseEnv CommandWrapperPrefix EnvVarName
commandWrapperVarName name =
ask <&> \prefix ->
getCommandWrapperVarName prefix name
commandWrapperToolsetVarName
:: CommandWrapperToolsetVarName
-> ParseEnv CommandWrapperPrefix EnvVarName
commandWrapperToolsetVarName name =
ask <&> \prefix ->
getCommandWrapperToolsetVarName prefix name
| Parse Command Wrapper environment variables using provided parser . It 's a
specialised version of ' Parser.parseEnv ' from " System . Environment . " :
parseEnv
:: HashMap EnvVarName EnvVarValue
-> ParseEnv CommandWrapperPrefix a
-> Either ParseEnvError a
parseEnv = Parser.parseEnv defaultCommandWrapperPrefix
parseEnvIO
:: MonadIO io
=> (forall void. ParseEnvError -> io void)
-> ParseEnv CommandWrapperPrefix a
-> io a
parseEnvIO = parseEnvWithIO parseEnv
|
3ffe97c7fc5cc66afbf5eb93d1f0343043376def7333eea549c0ef35414a9975 | thheller/shadow-experiments | env.cljs | (ns shadow.experiments.grove.examples.env
(:require
[cljs.env :as cljs-env]
[shadow.experiments.grove.runtime :as gr]
[shadow.experiments.grove.db :as db]
[shadow.experiments.grove.examples.model :as m]))
(defonce data-ref
(-> {::m/example-tab :result
::m/example-result "No Result yet."}
(db/configure m/schema)
(atom)))
(defonce rt-ref
(-> {::m/compile-state-ref (cljs-env/default-compiler-env)}
(gr/prepare data-ref ::app))) | null | https://raw.githubusercontent.com/thheller/shadow-experiments/f875c29bbda34d19ebdedf335b5a3ea40c7a4030/src/main/shadow/experiments/grove/examples/env.cljs | clojure | (ns shadow.experiments.grove.examples.env
(:require
[cljs.env :as cljs-env]
[shadow.experiments.grove.runtime :as gr]
[shadow.experiments.grove.db :as db]
[shadow.experiments.grove.examples.model :as m]))
(defonce data-ref
(-> {::m/example-tab :result
::m/example-result "No Result yet."}
(db/configure m/schema)
(atom)))
(defonce rt-ref
(-> {::m/compile-state-ref (cljs-env/default-compiler-env)}
(gr/prepare data-ref ::app))) | |
74d4878996dab5276f9916d010eca061d2f223b6a7fc0fc0d6816e51493e0505 | Metaxal/quickscript-extra | pasterack.rkt | #lang racket/base
(require browser/external
quickscript)
(script-help-string "Opens Pasterack in the browser.")
Launch / in browser
(define-script pasterack
#:label "Pasterack (browser)"
#:menu-path ("&Utils")
#:help-string "Opens 'PasteRack' An evaluating pastebin for Racket."
(λ (str)
(send-url "/")
#f))
| null | https://raw.githubusercontent.com/Metaxal/quickscript-extra/526b2eccd9f73ea30bbc013741fdd77f4e2724cf/scripts/pasterack.rkt | racket | #lang racket/base
(require browser/external
quickscript)
(script-help-string "Opens Pasterack in the browser.")
Launch / in browser
(define-script pasterack
#:label "Pasterack (browser)"
#:menu-path ("&Utils")
#:help-string "Opens 'PasteRack' An evaluating pastebin for Racket."
(λ (str)
(send-url "/")
#f))
| |
44c06eed074378428dff6fdbfab294d165df5e9a0f26b7fc0ec90db1fcc9fa37 | hanshuebner/clj-oauth2-token-generator | core.clj | (ns clj-oauth2-token-generator.core
(:require [clojure.java.io :as io]
[clojure.edn :as edn]
[clojure.pprint :refer [pprint]]
[clj-http.client :as http]
[clj-oauth2.client :as oauth2]
[ring.util.response :as response]
[ring.middleware.keyword-params :refer [wrap-keyword-params]]
[ring.middleware.params :refer [wrap-params]]
[compojure.core :refer (defroutes GET context)]
[ring.adapter.jetty :as jetty]))
(def config (edn/read-string (slurp (io/resource "config.edn"))))
(def oauth-params (merge {;; These should be set in the oauth-params.edn file
:redirect-uri ""
:client-id "*google-client-id*"
:client-secret "*google-client-secret*"
:scope ["" "/"]
;; These don't need changes
:authorization-uri ""
:access-token-uri ""
:access-query-param :access_token
:grant-type "authorization_code"
:access-type "online"
:approval_prompt ""}
(:oauth-params config)))
(def auth-request (oauth2/make-auth-request oauth-params))
(defn save-token [req]
(let [token (oauth2/get-access-token oauth-params
(:params req)
auth-request)
token-info (:body (http/get ""
{:query-params {:access_token (:access-token token)}
:as :json}))]
(with-open [out (io/writer (io/file (:token-directory config "/tmp") (:email token-info)))]
(pprint {:token token
:info token-info}
out))
(response/redirect (:success-url config "/"))))
(defroutes authentication-controller
(GET "/" []
(response/response "No browsable content on this server"))
(GET "/google-oauth" []
(response/redirect (:uri auth-request)))
(GET "/oauth2callback" []
save-token))
(defn -main []
(jetty/run-jetty (-> authentication-controller
wrap-keyword-params
wrap-params)
{:port (:port config 9492)}))
| null | https://raw.githubusercontent.com/hanshuebner/clj-oauth2-token-generator/a746a02208a7801ae2d6537344ce743028ba43dc/src/clj_oauth2_token_generator/core.clj | clojure | These should be set in the oauth-params.edn file
These don't need changes | (ns clj-oauth2-token-generator.core
(:require [clojure.java.io :as io]
[clojure.edn :as edn]
[clojure.pprint :refer [pprint]]
[clj-http.client :as http]
[clj-oauth2.client :as oauth2]
[ring.util.response :as response]
[ring.middleware.keyword-params :refer [wrap-keyword-params]]
[ring.middleware.params :refer [wrap-params]]
[compojure.core :refer (defroutes GET context)]
[ring.adapter.jetty :as jetty]))
(def config (edn/read-string (slurp (io/resource "config.edn"))))
:redirect-uri ""
:client-id "*google-client-id*"
:client-secret "*google-client-secret*"
:scope ["" "/"]
:authorization-uri ""
:access-token-uri ""
:access-query-param :access_token
:grant-type "authorization_code"
:access-type "online"
:approval_prompt ""}
(:oauth-params config)))
(def auth-request (oauth2/make-auth-request oauth-params))
(defn save-token [req]
(let [token (oauth2/get-access-token oauth-params
(:params req)
auth-request)
token-info (:body (http/get ""
{:query-params {:access_token (:access-token token)}
:as :json}))]
(with-open [out (io/writer (io/file (:token-directory config "/tmp") (:email token-info)))]
(pprint {:token token
:info token-info}
out))
(response/redirect (:success-url config "/"))))
(defroutes authentication-controller
(GET "/" []
(response/response "No browsable content on this server"))
(GET "/google-oauth" []
(response/redirect (:uri auth-request)))
(GET "/oauth2callback" []
save-token))
(defn -main []
(jetty/run-jetty (-> authentication-controller
wrap-keyword-params
wrap-params)
{:port (:port config 9492)}))
|
9ea7d80d07453c9a1706b1ca3fb37d017ab2f57cfe35cdd6297c5bd61b6a66c2 | SKS-Keyserver/sks-keyserver | channel.mli | (***********************************************************************)
(* channel.mli - A generic, object-based channel interface for binary *)
(* input/output *)
(* *)
Copyright ( C ) 2002 , 2003 , 2004 , 2005 , 2006 , 2007 , 2008 , 2009 , 2010 ,
2011 , 2012 , 2013 and Contributors
(* *)
This file is part of SKS . SKS 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. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307
USA or see < / > .
(***********************************************************************)
class virtual out_channel_obj :
object
method upcast : out_channel_obj
method virtual write_byte : int -> unit
method virtual write_char : char -> unit
method write_float : float -> unit
method write_int : int -> unit
method write_int32 : int32 -> unit
method write_int64 : int64 -> unit
method virtual write_string : string -> unit
method virtual write_string_pos :
buf:string -> pos:int -> len:int -> unit
end
class virtual in_channel_obj :
object
method virtual read_byte : int
method virtual read_char : char
method read_float : float
method read_int : int
method read_int32 : int32
method read_int64 : int64
method read_int64_size : int -> int64
method read_int_size : int -> int
method virtual read_string : int -> string
method virtual read_string_pos : buf:bytes -> pos:int -> len:int -> unit
method upcast : in_channel_obj
end
(******************************************************************)
class sys_out_channel :
out_channel ->
object
method close : unit
method fd : Unix.file_descr
method flush : unit
method outchan : out_channel
method skip : int -> unit
method upcast : out_channel_obj
method write_buf : Buffer.t -> unit
method write_byte : int -> unit
method write_char : char -> unit
method write_float : float -> unit
method write_int : int -> unit
method write_int32 : int32 -> unit
method write_int64 : int64 -> unit
method write_string : string -> unit
method write_string_pos : buf:string -> pos:int -> len:int -> unit
end
class sys_in_channel :
in_channel ->
object
method close : unit
method fd : Unix.file_descr
method inchan : in_channel
method read_all : string
method read_byte : int
method read_char : char
method read_float : float
method read_int : int
method read_int32 : int32
method read_int64 : int64
method read_int64_size : int -> int64
method read_int_size : int -> int
method read_string : int -> string
method read_string_pos : buf:bytes -> pos:int -> len:int -> unit
method upcast : in_channel_obj
end
class buffer_out_channel :
Buffer.t ->
object
method buffer_nocopy : Buffer.t
method contents : string
method upcast : out_channel_obj
method write_byte : int -> unit
method write_char : char -> unit
method write_float : float -> unit
method write_int : int -> unit
method write_int32 : int32 -> unit
method write_int64 : int64 -> unit
method write_string : string -> unit
method write_string_pos : buf:string -> pos:int -> len:int -> unit
end
class string_in_channel :
string ->
int ->
object
method read_byte : int
method read_char : char
method read_float : float
method read_int : int
method read_int32 : int32
method read_int64 : int64
method read_int64_size : int -> int64
method read_int_size : int -> int
method read_string : int -> string
method read_string_pos : buf:bytes -> pos:int -> len:int -> unit
method read_rest : string
method skip : int -> unit
method upcast : in_channel_obj
val mutable pos : int
end
(*******************************************************************)
val new_buffer_outc : int -> buffer_out_channel
val sys_out_from_fd : Unix.file_descr -> sys_out_channel
val sys_in_from_fd : Unix.file_descr -> sys_in_channel
class nonblocking_reader :
Unix.file_descr - >
object
method read : string_in_channel option
end
class nonblocking_writer :
Unix.file_descr - >
object
method set_data : string - > unit
method write :
class nonblocking_reader :
Unix.file_descr ->
object
method read : string_in_channel option
end
class nonblocking_writer :
Unix.file_descr ->
object
method set_data : string -> unit
method write : bool
end
*)
| null | https://raw.githubusercontent.com/SKS-Keyserver/sks-keyserver/a4e5267d817cddbdfee13d07a7fb38a9b94b3eee/channel.mli | ocaml | *********************************************************************
channel.mli - A generic, object-based channel interface for binary
input/output
redistribute it and/or modify it under the terms of the GNU General
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.
*********************************************************************
****************************************************************
***************************************************************** | Copyright ( C ) 2002 , 2003 , 2004 , 2005 , 2006 , 2007 , 2008 , 2009 , 2010 ,
2011 , 2012 , 2013 and Contributors
This file is part of SKS . SKS is free software ; you can
Public 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 License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307
USA or see < / > .
class virtual out_channel_obj :
object
method upcast : out_channel_obj
method virtual write_byte : int -> unit
method virtual write_char : char -> unit
method write_float : float -> unit
method write_int : int -> unit
method write_int32 : int32 -> unit
method write_int64 : int64 -> unit
method virtual write_string : string -> unit
method virtual write_string_pos :
buf:string -> pos:int -> len:int -> unit
end
class virtual in_channel_obj :
object
method virtual read_byte : int
method virtual read_char : char
method read_float : float
method read_int : int
method read_int32 : int32
method read_int64 : int64
method read_int64_size : int -> int64
method read_int_size : int -> int
method virtual read_string : int -> string
method virtual read_string_pos : buf:bytes -> pos:int -> len:int -> unit
method upcast : in_channel_obj
end
class sys_out_channel :
out_channel ->
object
method close : unit
method fd : Unix.file_descr
method flush : unit
method outchan : out_channel
method skip : int -> unit
method upcast : out_channel_obj
method write_buf : Buffer.t -> unit
method write_byte : int -> unit
method write_char : char -> unit
method write_float : float -> unit
method write_int : int -> unit
method write_int32 : int32 -> unit
method write_int64 : int64 -> unit
method write_string : string -> unit
method write_string_pos : buf:string -> pos:int -> len:int -> unit
end
class sys_in_channel :
in_channel ->
object
method close : unit
method fd : Unix.file_descr
method inchan : in_channel
method read_all : string
method read_byte : int
method read_char : char
method read_float : float
method read_int : int
method read_int32 : int32
method read_int64 : int64
method read_int64_size : int -> int64
method read_int_size : int -> int
method read_string : int -> string
method read_string_pos : buf:bytes -> pos:int -> len:int -> unit
method upcast : in_channel_obj
end
class buffer_out_channel :
Buffer.t ->
object
method buffer_nocopy : Buffer.t
method contents : string
method upcast : out_channel_obj
method write_byte : int -> unit
method write_char : char -> unit
method write_float : float -> unit
method write_int : int -> unit
method write_int32 : int32 -> unit
method write_int64 : int64 -> unit
method write_string : string -> unit
method write_string_pos : buf:string -> pos:int -> len:int -> unit
end
class string_in_channel :
string ->
int ->
object
method read_byte : int
method read_char : char
method read_float : float
method read_int : int
method read_int32 : int32
method read_int64 : int64
method read_int64_size : int -> int64
method read_int_size : int -> int
method read_string : int -> string
method read_string_pos : buf:bytes -> pos:int -> len:int -> unit
method read_rest : string
method skip : int -> unit
method upcast : in_channel_obj
val mutable pos : int
end
val new_buffer_outc : int -> buffer_out_channel
val sys_out_from_fd : Unix.file_descr -> sys_out_channel
val sys_in_from_fd : Unix.file_descr -> sys_in_channel
class nonblocking_reader :
Unix.file_descr - >
object
method read : string_in_channel option
end
class nonblocking_writer :
Unix.file_descr - >
object
method set_data : string - > unit
method write :
class nonblocking_reader :
Unix.file_descr ->
object
method read : string_in_channel option
end
class nonblocking_writer :
Unix.file_descr ->
object
method set_data : string -> unit
method write : bool
end
*)
|
2eba92f2c7915feaf4b800bca9f1cc03607d80abd1c3610ec890250afaee8df3 | mejgun/haskell-tdlib | SetChatPermissions.hs | {-# LANGUAGE OverloadedStrings #-}
-- |
module TD.Query.SetChatPermissions where
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as T
import qualified TD.Data.ChatPermissions as ChatPermissions
import qualified Utils as U
-- |
-- Changes the chat members permissions. Supported only for basic groups and supergroups. Requires can_restrict_members administrator right
data SetChatPermissions = SetChatPermissions
{ -- | New non-administrator members permissions in the chat
permissions :: Maybe ChatPermissions.ChatPermissions,
-- | Chat identifier
chat_id :: Maybe Int
}
deriving (Eq)
instance Show SetChatPermissions where
show
SetChatPermissions
{ permissions = permissions_,
chat_id = chat_id_
} =
"SetChatPermissions"
++ U.cc
[ U.p "permissions" permissions_,
U.p "chat_id" chat_id_
]
instance T.ToJSON SetChatPermissions where
toJSON
SetChatPermissions
{ permissions = permissions_,
chat_id = chat_id_
} =
A.object
[ "@type" A..= T.String "setChatPermissions",
"permissions" A..= permissions_,
"chat_id" A..= chat_id_
]
| null | https://raw.githubusercontent.com/mejgun/haskell-tdlib/dc380d18d49eaadc386a81dc98af2ce00f8797c2/src/TD/Query/SetChatPermissions.hs | haskell | # LANGUAGE OverloadedStrings #
|
|
Changes the chat members permissions. Supported only for basic groups and supergroups. Requires can_restrict_members administrator right
| New non-administrator members permissions in the chat
| Chat identifier |
module TD.Query.SetChatPermissions where
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as T
import qualified TD.Data.ChatPermissions as ChatPermissions
import qualified Utils as U
data SetChatPermissions = SetChatPermissions
permissions :: Maybe ChatPermissions.ChatPermissions,
chat_id :: Maybe Int
}
deriving (Eq)
instance Show SetChatPermissions where
show
SetChatPermissions
{ permissions = permissions_,
chat_id = chat_id_
} =
"SetChatPermissions"
++ U.cc
[ U.p "permissions" permissions_,
U.p "chat_id" chat_id_
]
instance T.ToJSON SetChatPermissions where
toJSON
SetChatPermissions
{ permissions = permissions_,
chat_id = chat_id_
} =
A.object
[ "@type" A..= T.String "setChatPermissions",
"permissions" A..= permissions_,
"chat_id" A..= chat_id_
]
|
6eb09aba55c50c3e592568f92bc678eaff1492fe788245a0d153371cc810e180 | tonyvanriet/clj-slack-client | reminders.clj | (ns clj-slack-client.reminders
(:require [clj-slack-client.web :as web])
(:refer-clojure :exclude [list]))
; these methods only accessible by user tokens. Bots and
; workspaces are not allowed
(defn add
"Creates a reminder."
([options]
(web/call-and-get-response "reminders.add" options))
([token text time]
(add {:token token :text text :time time}))
([token text time user]
(add {:token token :text text :time time :user user})))
(defn complete
"Marks a reminder as complete."
[token reminder-id]
(web/call-and-get-response "reminders.complete"
{:token token :reminder reminder-id}))
(defn delete
"Deletes a reminder."
[token reminder-id]
(web/call-and-get-response "reminders.delete"
{:token token :reminder reminder-id}))
(defn info
"Gets information about a reminder"
[token reminder-id]
(web/call-and-get-response "reminders.info"
{:token token :reminder reminder-id}))
(defn list
"Lists all reminders created by or for a given user."
[token]
(web/call-and-get-response "reminders.list" {:token token}))
| null | https://raw.githubusercontent.com/tonyvanriet/clj-slack-client/6783f003ab93adae057890421622eb5e61ab033d/src/clj_slack_client/reminders.clj | clojure | these methods only accessible by user tokens. Bots and
workspaces are not allowed | (ns clj-slack-client.reminders
(:require [clj-slack-client.web :as web])
(:refer-clojure :exclude [list]))
(defn add
"Creates a reminder."
([options]
(web/call-and-get-response "reminders.add" options))
([token text time]
(add {:token token :text text :time time}))
([token text time user]
(add {:token token :text text :time time :user user})))
(defn complete
"Marks a reminder as complete."
[token reminder-id]
(web/call-and-get-response "reminders.complete"
{:token token :reminder reminder-id}))
(defn delete
"Deletes a reminder."
[token reminder-id]
(web/call-and-get-response "reminders.delete"
{:token token :reminder reminder-id}))
(defn info
"Gets information about a reminder"
[token reminder-id]
(web/call-and-get-response "reminders.info"
{:token token :reminder reminder-id}))
(defn list
"Lists all reminders created by or for a given user."
[token]
(web/call-and-get-response "reminders.list" {:token token}))
|
4afd2f8ab93898ac010d8095a43ef3486a3d2d6749debf4617c181fdab61fe59 | Paczesiowa/virthualenv | Tar.hs | module Util.Tar ( unpack
, stripComponents
) where
import Codec.Archive.Tar.Entry
import Codec.Archive.Tar (Entries(..), mapEntries)
import Codec.Archive.Tar.Check (checkSecurity)
import qualified Data.ByteString.Lazy as BS
import System.FilePath ((</>), splitPath, joinPath, hasTrailingPathSeparator)
import qualified System.FilePath as FilePath.Native (takeDirectory)
import System.Directory (createDirectoryIfMissing, copyFile)
import Control.Monad (when)
import System.Posix.Files (ownerExecuteMode, intersectFileModes)
import Util.IO (makeExecutable)
isExecutable :: Permissions -> Bool
isExecutable perms = intersectFileModes ownerExecuteMode perms == ownerExecuteMode
unpack :: FilePath -> Entries -> IO ()
unpack baseDir entries = unpackEntries [] (checkSecurity entries)
>>= emulateLinks
where
unpackEntries _ (Fail err) = fail err
unpackEntries links Done = return links
unpackEntries links (Next entry es) = case entryContent entry of
NormalFile file _ -> extractFile path file (entryPermissions entry)
>> unpackEntries links es
Directory -> extractDir path
>> unpackEntries links es
HardLink link -> (unpackEntries $! saveLink path link links) es
SymbolicLink link -> (unpackEntries $! saveLink path link links) es
_ -> unpackEntries links es --ignore other file types
where
path = entryPath entry
extractFile path content perms = do
createDirectoryIfMissing True absDir
BS.writeFile absPath content
when (isExecutable perms) $ makeExecutable absPath
where
absDir = baseDir </> FilePath.Native.takeDirectory path
absPath = baseDir </> path
extractDir path = createDirectoryIfMissing True (baseDir </> path)
saveLink path link links = seq (length path)
$ seq (length link')
$ (path, link'):links
where link' = fromLinkTarget link
emulateLinks = mapM_ $ \(relPath, relLinkTarget) ->
let absPath = baseDir </> relPath
absTarget = FilePath.Native.takeDirectory absPath </> relLinkTarget
in copyFile absTarget absPath
stripComponents :: Int -> Entries -> Entries
stripComponents n = mapEntries aux
where aux entry@Entry{entryTarPath = oldTarPath} =
let isDirectory = hasTrailingPathSeparator $ fromTarPath oldTarPath
in case toTarPath isDirectory $ joinPath $ drop n $ splitPath $ fromTarPath oldTarPath of
Left err -> Left err
Right newTarPath -> Right entry{entryTarPath = newTarPath}
| null | https://raw.githubusercontent.com/Paczesiowa/virthualenv/aab89dad9de7dac5268472eaa50c11eb40b02380/src/Util/Tar.hs | haskell | ignore other file types | module Util.Tar ( unpack
, stripComponents
) where
import Codec.Archive.Tar.Entry
import Codec.Archive.Tar (Entries(..), mapEntries)
import Codec.Archive.Tar.Check (checkSecurity)
import qualified Data.ByteString.Lazy as BS
import System.FilePath ((</>), splitPath, joinPath, hasTrailingPathSeparator)
import qualified System.FilePath as FilePath.Native (takeDirectory)
import System.Directory (createDirectoryIfMissing, copyFile)
import Control.Monad (when)
import System.Posix.Files (ownerExecuteMode, intersectFileModes)
import Util.IO (makeExecutable)
isExecutable :: Permissions -> Bool
isExecutable perms = intersectFileModes ownerExecuteMode perms == ownerExecuteMode
unpack :: FilePath -> Entries -> IO ()
unpack baseDir entries = unpackEntries [] (checkSecurity entries)
>>= emulateLinks
where
unpackEntries _ (Fail err) = fail err
unpackEntries links Done = return links
unpackEntries links (Next entry es) = case entryContent entry of
NormalFile file _ -> extractFile path file (entryPermissions entry)
>> unpackEntries links es
Directory -> extractDir path
>> unpackEntries links es
HardLink link -> (unpackEntries $! saveLink path link links) es
SymbolicLink link -> (unpackEntries $! saveLink path link links) es
where
path = entryPath entry
extractFile path content perms = do
createDirectoryIfMissing True absDir
BS.writeFile absPath content
when (isExecutable perms) $ makeExecutable absPath
where
absDir = baseDir </> FilePath.Native.takeDirectory path
absPath = baseDir </> path
extractDir path = createDirectoryIfMissing True (baseDir </> path)
saveLink path link links = seq (length path)
$ seq (length link')
$ (path, link'):links
where link' = fromLinkTarget link
emulateLinks = mapM_ $ \(relPath, relLinkTarget) ->
let absPath = baseDir </> relPath
absTarget = FilePath.Native.takeDirectory absPath </> relLinkTarget
in copyFile absTarget absPath
stripComponents :: Int -> Entries -> Entries
stripComponents n = mapEntries aux
where aux entry@Entry{entryTarPath = oldTarPath} =
let isDirectory = hasTrailingPathSeparator $ fromTarPath oldTarPath
in case toTarPath isDirectory $ joinPath $ drop n $ splitPath $ fromTarPath oldTarPath of
Left err -> Left err
Right newTarPath -> Right entry{entryTarPath = newTarPath}
|
9924ab566021736b3aade78b7fc56cdf8d796abc552ebff1b94ff990bf22c70d | bcc32/projecteuler-ocaml | sol_054.ml | open! Core
open! Import
let main () =
Problem_054.data
|> Parse.space_separated_grid ~conv:Poker.Card.of_string
|> Array.map ~f:(fun line ->
let make_hand cards = cards |> Array.to_list |> Poker.Hand.of_card_list_exn in
let p1 = Array.subo line ~len:5 |> make_hand in
let p2 = Array.subo line ~pos:5 |> make_hand in
p1, p2)
|> Array.count ~f:(fun (p1, p2) ->
Poker.Hand_classification.( > ) (Poker.Hand.classify p1) (Poker.Hand.classify p2))
|> printf "%d\n"
;;
6.821ms
let%expect_test "answer" =
main ();
[%expect {| 376 |}]
;;
include (val Solution.make ~problem:(Number 54) ~main)
| null | https://raw.githubusercontent.com/bcc32/projecteuler-ocaml/712f85902c70adc1ec13dcbbee456c8bfa8450b2/sol/sol_054.ml | ocaml | open! Core
open! Import
let main () =
Problem_054.data
|> Parse.space_separated_grid ~conv:Poker.Card.of_string
|> Array.map ~f:(fun line ->
let make_hand cards = cards |> Array.to_list |> Poker.Hand.of_card_list_exn in
let p1 = Array.subo line ~len:5 |> make_hand in
let p2 = Array.subo line ~pos:5 |> make_hand in
p1, p2)
|> Array.count ~f:(fun (p1, p2) ->
Poker.Hand_classification.( > ) (Poker.Hand.classify p1) (Poker.Hand.classify p2))
|> printf "%d\n"
;;
6.821ms
let%expect_test "answer" =
main ();
[%expect {| 376 |}]
;;
include (val Solution.make ~problem:(Number 54) ~main)
| |
de7f74a0304642bcd770af3378c6153bee3d210b6fdc3fa43e857c9708c9f7cf | Helium4Haskell/Top | Qualification.hs | -----------------------------------------------------------------------------
-- | License : GPL
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
-- Qualification of types (for instance, predicates to deal with type classes).
--
-----------------------------------------------------------------------------
module Top.Types.Qualification where
import Top.Types.Primitive
import Top.Types.Substitution
import Data.List
-----------------------------------------------------------------------------
-- * Qualification
newtype Qualification q a = Qualification (q, a)
split :: Qualification q a -> (q, a)
split (Qualification t) = t
infixr 2 .=>.
(.=>.) :: q -> a -> Qualification q a
(.=>.) = curry Qualification
qualifiers :: Qualification q a -> q
qualifiers = fst . split
unqualify :: Qualification q a -> a
unqualify = snd . split
qualify :: (Substitutable context, Substitutable q, Substitutable a) => context -> [q] -> a -> Qualification [q] a
qualify context preds tp =
let is = ftv tp \\ ftv context
p = any (`elem` is) . ftv
in (filter p preds .=>. tp)
instance (Substitutable q, Substitutable a) => Substitutable (Qualification q a) where
sub |-> (Qualification t) = Qualification (sub |-> t)
ftv (Qualification t) = ftv t
instance (HasTypes q, HasTypes a) => HasTypes (Qualification q a) where
getTypes (Qualification t) = getTypes t
changeTypes f (Qualification t) = Qualification (changeTypes f t)
instance (ShowQualifiers q, Show a) => Show (Qualification q a) where
show (Qualification (q, a)) =
showContext q ++ show a
class Show a => ShowQualifiers a where
showQualifiers :: a -> [String]
-- default definition
showQualifiers = (:[]) . show
showContext :: ShowQualifiers a => a -> String
showContext = showContextSimple . showQualifiers
showContextSimple :: [String] -> String
showContextSimple [] = ""
showContextSimple [x] = x ++ " => "
showContextSimple xs = "(" ++ intercalate ", " xs ++ ") => "
instance (ShowQualifiers a, ShowQualifiers b) => ShowQualifiers (a, b) where
showQualifiers (a, b) = showQualifiers a ++ showQualifiers b
instance ShowQualifiers a => ShowQualifiers [a] where
showQualifiers = concatMap showQualifiers | null | https://raw.githubusercontent.com/Helium4Haskell/Top/5e900184d6b2ab6d7ce69945287d782252e5ea68/src/Top/Types/Qualification.hs | haskell | ---------------------------------------------------------------------------
| License : GPL
Maintainer :
Stability : provisional
Portability : portable
Qualification of types (for instance, predicates to deal with type classes).
---------------------------------------------------------------------------
---------------------------------------------------------------------------
* Qualification
default definition |
module Top.Types.Qualification where
import Top.Types.Primitive
import Top.Types.Substitution
import Data.List
newtype Qualification q a = Qualification (q, a)
split :: Qualification q a -> (q, a)
split (Qualification t) = t
infixr 2 .=>.
(.=>.) :: q -> a -> Qualification q a
(.=>.) = curry Qualification
qualifiers :: Qualification q a -> q
qualifiers = fst . split
unqualify :: Qualification q a -> a
unqualify = snd . split
qualify :: (Substitutable context, Substitutable q, Substitutable a) => context -> [q] -> a -> Qualification [q] a
qualify context preds tp =
let is = ftv tp \\ ftv context
p = any (`elem` is) . ftv
in (filter p preds .=>. tp)
instance (Substitutable q, Substitutable a) => Substitutable (Qualification q a) where
sub |-> (Qualification t) = Qualification (sub |-> t)
ftv (Qualification t) = ftv t
instance (HasTypes q, HasTypes a) => HasTypes (Qualification q a) where
getTypes (Qualification t) = getTypes t
changeTypes f (Qualification t) = Qualification (changeTypes f t)
instance (ShowQualifiers q, Show a) => Show (Qualification q a) where
show (Qualification (q, a)) =
showContext q ++ show a
class Show a => ShowQualifiers a where
showQualifiers :: a -> [String]
showQualifiers = (:[]) . show
showContext :: ShowQualifiers a => a -> String
showContext = showContextSimple . showQualifiers
showContextSimple :: [String] -> String
showContextSimple [] = ""
showContextSimple [x] = x ++ " => "
showContextSimple xs = "(" ++ intercalate ", " xs ++ ") => "
instance (ShowQualifiers a, ShowQualifiers b) => ShowQualifiers (a, b) where
showQualifiers (a, b) = showQualifiers a ++ showQualifiers b
instance ShowQualifiers a => ShowQualifiers [a] where
showQualifiers = concatMap showQualifiers |
bd533f4ca1544cba7f9f4d3884212762a2679c6f7a620e79cd74e1fa26551258 | ekmett/unboxed | Def.hs | {-# Language MagicHash #-}
{-# Language UnboxedSums #-}
# Language UnboxedTuples #
{-# Language TypeFamilies #-}
{-# Language PolyKinds #-}
{-# Language BangPatterns #-}
{-# Language DataKinds #-}
{-# Language PatternSynonyms #-}
{-# Language RankNTypes #-}
# Language NoImplicitPrelude #
{-# Language TypeApplications #-}
{-# Language RebindableSyntax #-}
{-# Language ImportQualifiedPost #-}
{-# Language FlexibleContexts #-}
{-# Language FlexibleInstances #-}
{-# Language StandaloneKindSignatures #-}
module Def where
import Unboxed.Internal.Class
import Unboxed.Internal.List
import Unboxed.Internal.Maybe
import Unboxed.Internal.Rebind
import GHC.Types
import Prelude (otherwise, not, (++), ShowS, (.), showString, showParen,($), (&&), (||))
import Prelude qualified
import System.IO qualified as IO
import Rep
instance EqRep Rep where
eqDef x y = not (x /= y)
neDef x y = not (x == y)
instance OrdRep Rep where
compareDef x y
| x == y = EQ
| x <= y = LT
| otherwise = GT
ltDef x y = case compare x y of LT -> True; _ -> False
leDef x y = case compare x y of GT -> False; _ -> True
gtDef x y = case compare x y of GT -> True; _ -> False
geDef x y = case compare x y of LT -> False; _ -> True
maxDef x y
| x <= y = y
| otherwise = x
minDef x y
| x <= y = x
| otherwise = y
instance NumRep Rep where
negateDef a = 0 - a
minusDef a b = a + negate b
instance FractionalRep Rep where
fractionalDef x y = x * recip y
recipDef x = 1 / x
instance RealRep Rep where
realToFracDef x = fromRational (toRational x)
instance EnumRep Rep where
{-
enumFromDef x = map toEnum [fromEnum x ..]
enumFromThenDef x y = map toEnum [fromEnum x, fromEnum y ..]
enumFromToDef x y = map toEnum [fromEnum x .. fromEnum y]
enumFromThenToDef x1 x2 y = map toEnum [fromEnum x1, fromEnum x2 .. fromEnum y]
-}
succDef x = toEnum (fromEnum x + 1)
predDef x = toEnum (fromEnum x - 1)
instance IntegralRep Rep where
n `quotDef` d = q where !(# q, _ #) = quotRem n d
n `remDef` d = r where !(# _, r #) = quotRem n d
n `divDef` d = q where !(# q, _ #) = divMod n d
n `modDef` d = r where !(# _, r #) = divMod n d
divModDef n d
| signum r == negate (signum d) = (# q - 1, r + d #)
| otherwise = qr
where !qr@(# q, r #) = quotRem n d
instance RealFracRep Rep where
truncateDef x = fromInteger m where
!(# m, _ #) = properFraction x
# INLINE truncateDef #
roundDef x =
let !(# n, r #) = properFraction x
m | r < 0 = n - 1
| otherwise = n + 1
in case signum (abs r - 0.5) of
-1 -> fromInteger n
0 | Prelude.even n -> fromInteger n
| otherwise -> fromInteger m
1 -> fromInteger m
_ -> Prelude.error "round default defn: Bad value"
ceilingDef x
| r > 0 = fromInteger (n + 1)
| otherwise = fromInteger n
where !(# n, r #) = properFraction x
floorDef x
| r < 0 = fromInteger (n - 1)
| otherwise = fromInteger n
where !(# n, r #) = properFraction x
instance FloatingRep Rep where
# INLINE powDef #
# INLINE logBaseDef #
# INLINE sqrtDef #
# INLINE tanDef #
# INLINE tanhDef #
powDef x y = exp (log x * y)
logBaseDef x y = log y / log x
sqrtDef x = x ** 0.5
tanDef x = sin x / cos x
tanhDef x = sinh x / cosh x
# INLINE log1pDef #
{-# INLINE expm1Def #-}
# INLINE log1pexpDef #
{-# INLINE log1mexpDef #-}
log1pDef x = log (1 + x)
expm1Def x = exp x - 1
log1pexpDef x = log1p (exp x)
log1mexpDef x = log1p (negate (exp x))
instance RealFloatRep Rep where
exponentDef x
| m == 0 = 0
| otherwise = n + floatDigits x
where !(# m, n #) = decodeFloat x
significandDef x = encodeFloat m (negate (floatDigits x))
where !(# m, _ #) = decodeFloat x
scaleFloatDef 0 x = x
scaleFloatDef k x
| isFix = x
| otherwise = encodeFloat m (n + clamp b k)
where
!(# m, n #) = decodeFloat x
!(# l, h #) = floatRange x
d = floatDigits x
b = h - l + 4 * d
isFix = x == 0 || isNaN x || isInfinite x
clamp :: Int -> Int -> Int
clamp bd k' = max (-bd) (min bd k')
atan2Def y x
| x > 0 = atan (y/x)
| x == 0 && y > 0 = pi/2
| x < 0 && y > 0 = pi + atan (y/x)
|(x <= 0 && y < 0) ||
(x < 0 && isNegativeZero y) ||
(isNegativeZero x && isNegativeZero y)
= -atan2 (-y) x
| y == 0 && (x < 0 || isNegativeZero x)
must be after the previous test on zero y
must be after the other double zero tests
x or y is a NaN , return a NaN ( via + )
data instance ListD (a :: TYPE Rep) = Nil | a :# List a
infixr 5 :#
instance ListRep Rep where
cons = (:#)
cons' a as = a :# as
nil = Nil
uncons# (a :# as) = Maybe# (# | (# a, as #) #)
uncons# Nil = Maybe# (# (##) | #)
instance Eq a => Prelude.Eq (ListD @Rep a) where
Nil == Nil = True
a :# as == b :# bs = a == b && as == bs
_ == _ = False
Nil /= Nil = True
a :# as /= b :# bs = a /= b || as /= bs
_ /= _ = False
instance Ord a => Prelude.Ord (ListD @Rep a) where
compare Nil Nil = EQ
compare Nil (:#){} = LT
compare (:#){} Nil = GT
compare (a:#as) (b:#bs) = compare a b <> compare as bs
instance ShowList a => Prelude.Show (ListD @Rep a) where
showsPrec _ = showList
data instance MaybeD (a :: TYPE Rep) = Nothing | Just a
instance Eq a => Prelude.Eq (MaybeD @Rep a) where
Nothing == Nothing = True
Just a == Just b = a == b
_ == _ = False
instance Ord a => Prelude.Ord (MaybeD @Rep a) where
compare Nothing Nothing = EQ
compare Nothing Just{} = LT
compare Just{} Nothing = GT
compare (Just a) (Just b) = compare a b
instance Show a => Prelude.Show (MaybeD @Rep a) where
showsPrec _ Nothing = showString "Nothing"
showsPrec d (Just a) = showParen (d >= 11) $ showString "Just " . showsPrec 11 a
instance MaybeRep Rep where
nothing = Nothing
just = Just
just' x = Just x
maybe n _ Nothing = n
maybe _ j (Just a) = j a
mapMaybe _ Nothing = nothing
mapMaybe f (Just a) = just' (f a)
instance MaybeRep# Rep where
nothing# = Maybe# (# (##) | #)
just# a = Maybe# (# | a #)
just'# a = Maybe# (# | a #)
maybe# n _ (Maybe# (# (##) | #)) = n
maybe# _ j (Maybe# (# | a #)) = j a
mapMaybe# _ (Maybe# (# (##) | #)) = nothing#
mapMaybe# f (Maybe# (# | a #)) = just'# (f a)
pattern Nothing# :: forall (a :: TYPE Rep). Maybe# a
pattern Nothing# = Maybe# (# (##) | #)
pattern Just# :: forall (a :: TYPE Rep). a -> Maybe# a
pattern Just# a = Maybe# (# | a #)
-- Maybe# can be made a monomorphic functor where the result rep must match the input rep
not very satisfying , but the best we can do until allows type families inside
-- TYPE.
unfortunately ghc is not able to be talked into this , even with type family helpers
type RebindMaybe# :: forall (r :: RuntimeRep). TYPE r -> TYPE ('SumRep '[ 'TupleRep '[], Rep ])
type family RebindMaybe# where
RebindMaybe# @Rep = Maybe# @Rep
-- no otherwise
type instance Rebind (Maybe# @Rep) r = RebindMaybe# @r
instance Functor (Maybe# @Rep) where
type FunctorRep (Maybe# @Rep) = (~) Rep
fmap _ Nothing# = Nothing#
fmap f (Just# a) = Just# (f a)
instance Show a => Show (Maybe# @Rep a) where
showsPrec _ Nothing# = showString "Nothing#"
showsPrec d (Just# a) = showParen (d >= 11) $ showString "Just# " . showsPrec 11 a
show x = shows x ""
-- this instance will probably not fire without a lot of help, because that body condition is harsh
We split ShowList into a separate class , even if this breaks compat with base because of this
-- instance
instance (ListRep ('SumRep '[ 'TupleRep '[], Rep ]), Show a) => ShowList (Maybe# @Rep a) where
showList = go shows where
go :: forall (a :: TYPE Rep). (Maybe# a -> ShowS) -> List (Maybe# a) -> ShowS
go showx l s = case uncons# l of
Maybe# (# (##) | #) -> "[]" ++ s
Maybe# (# | (# x, xs #) #) -> '[' : showx x (showl xs)
where
showl l' = case uncons# l' of
Maybe# (# (##) | #) -> ']' : s
Maybe# (# | (# y, ys #) #) -> ',' : showx y (showl ys)
# complete Nothing # , Just # : : Maybe # #
instance ShowRep Rep where
showsPrecDef _ x s = show x ++ s
showDef x = shows x ""
instance ShowListRep Rep where
showListDef = showList__ shows
showList__ :: forall (a :: TYPE Rep). (a -> ShowS) -> List a -> ShowS
showList__ _ Nil s = "[]" ++ s
showList__ showx (x :# xs) s = '[' : showx x (showl xs)
where
showl Nil = ']' : s
showl (y :# ys) = ',' : showx y (showl ys)
instance PrintRep Rep where
hPrint h x = IO.hPutStrLn h (show x)
| null | https://raw.githubusercontent.com/ekmett/unboxed/e4c6ca80fb8946b1abfe595ba1c36587a33931db/def/Def.hs | haskell | # Language MagicHash #
# Language UnboxedSums #
# Language TypeFamilies #
# Language PolyKinds #
# Language BangPatterns #
# Language DataKinds #
# Language PatternSynonyms #
# Language RankNTypes #
# Language TypeApplications #
# Language RebindableSyntax #
# Language ImportQualifiedPost #
# Language FlexibleContexts #
# Language FlexibleInstances #
# Language StandaloneKindSignatures #
enumFromDef x = map toEnum [fromEnum x ..]
enumFromThenDef x y = map toEnum [fromEnum x, fromEnum y ..]
enumFromToDef x y = map toEnum [fromEnum x .. fromEnum y]
enumFromThenToDef x1 x2 y = map toEnum [fromEnum x1, fromEnum x2 .. fromEnum y]
# INLINE expm1Def #
# INLINE log1mexpDef #
Maybe# can be made a monomorphic functor where the result rep must match the input rep
TYPE.
no otherwise
this instance will probably not fire without a lot of help, because that body condition is harsh
instance | # Language UnboxedTuples #
# Language NoImplicitPrelude #
module Def where
import Unboxed.Internal.Class
import Unboxed.Internal.List
import Unboxed.Internal.Maybe
import Unboxed.Internal.Rebind
import GHC.Types
import Prelude (otherwise, not, (++), ShowS, (.), showString, showParen,($), (&&), (||))
import Prelude qualified
import System.IO qualified as IO
import Rep
instance EqRep Rep where
eqDef x y = not (x /= y)
neDef x y = not (x == y)
instance OrdRep Rep where
compareDef x y
| x == y = EQ
| x <= y = LT
| otherwise = GT
ltDef x y = case compare x y of LT -> True; _ -> False
leDef x y = case compare x y of GT -> False; _ -> True
gtDef x y = case compare x y of GT -> True; _ -> False
geDef x y = case compare x y of LT -> False; _ -> True
maxDef x y
| x <= y = y
| otherwise = x
minDef x y
| x <= y = x
| otherwise = y
instance NumRep Rep where
negateDef a = 0 - a
minusDef a b = a + negate b
instance FractionalRep Rep where
fractionalDef x y = x * recip y
recipDef x = 1 / x
instance RealRep Rep where
realToFracDef x = fromRational (toRational x)
instance EnumRep Rep where
succDef x = toEnum (fromEnum x + 1)
predDef x = toEnum (fromEnum x - 1)
instance IntegralRep Rep where
n `quotDef` d = q where !(# q, _ #) = quotRem n d
n `remDef` d = r where !(# _, r #) = quotRem n d
n `divDef` d = q where !(# q, _ #) = divMod n d
n `modDef` d = r where !(# _, r #) = divMod n d
divModDef n d
| signum r == negate (signum d) = (# q - 1, r + d #)
| otherwise = qr
where !qr@(# q, r #) = quotRem n d
instance RealFracRep Rep where
truncateDef x = fromInteger m where
!(# m, _ #) = properFraction x
# INLINE truncateDef #
roundDef x =
let !(# n, r #) = properFraction x
m | r < 0 = n - 1
| otherwise = n + 1
in case signum (abs r - 0.5) of
-1 -> fromInteger n
0 | Prelude.even n -> fromInteger n
| otherwise -> fromInteger m
1 -> fromInteger m
_ -> Prelude.error "round default defn: Bad value"
ceilingDef x
| r > 0 = fromInteger (n + 1)
| otherwise = fromInteger n
where !(# n, r #) = properFraction x
floorDef x
| r < 0 = fromInteger (n - 1)
| otherwise = fromInteger n
where !(# n, r #) = properFraction x
instance FloatingRep Rep where
# INLINE powDef #
# INLINE logBaseDef #
# INLINE sqrtDef #
# INLINE tanDef #
# INLINE tanhDef #
powDef x y = exp (log x * y)
logBaseDef x y = log y / log x
sqrtDef x = x ** 0.5
tanDef x = sin x / cos x
tanhDef x = sinh x / cosh x
# INLINE log1pDef #
# INLINE log1pexpDef #
log1pDef x = log (1 + x)
expm1Def x = exp x - 1
log1pexpDef x = log1p (exp x)
log1mexpDef x = log1p (negate (exp x))
instance RealFloatRep Rep where
exponentDef x
| m == 0 = 0
| otherwise = n + floatDigits x
where !(# m, n #) = decodeFloat x
significandDef x = encodeFloat m (negate (floatDigits x))
where !(# m, _ #) = decodeFloat x
scaleFloatDef 0 x = x
scaleFloatDef k x
| isFix = x
| otherwise = encodeFloat m (n + clamp b k)
where
!(# m, n #) = decodeFloat x
!(# l, h #) = floatRange x
d = floatDigits x
b = h - l + 4 * d
isFix = x == 0 || isNaN x || isInfinite x
clamp :: Int -> Int -> Int
clamp bd k' = max (-bd) (min bd k')
atan2Def y x
| x > 0 = atan (y/x)
| x == 0 && y > 0 = pi/2
| x < 0 && y > 0 = pi + atan (y/x)
|(x <= 0 && y < 0) ||
(x < 0 && isNegativeZero y) ||
(isNegativeZero x && isNegativeZero y)
= -atan2 (-y) x
| y == 0 && (x < 0 || isNegativeZero x)
must be after the previous test on zero y
must be after the other double zero tests
x or y is a NaN , return a NaN ( via + )
data instance ListD (a :: TYPE Rep) = Nil | a :# List a
infixr 5 :#
instance ListRep Rep where
cons = (:#)
cons' a as = a :# as
nil = Nil
uncons# (a :# as) = Maybe# (# | (# a, as #) #)
uncons# Nil = Maybe# (# (##) | #)
instance Eq a => Prelude.Eq (ListD @Rep a) where
Nil == Nil = True
a :# as == b :# bs = a == b && as == bs
_ == _ = False
Nil /= Nil = True
a :# as /= b :# bs = a /= b || as /= bs
_ /= _ = False
instance Ord a => Prelude.Ord (ListD @Rep a) where
compare Nil Nil = EQ
compare Nil (:#){} = LT
compare (:#){} Nil = GT
compare (a:#as) (b:#bs) = compare a b <> compare as bs
instance ShowList a => Prelude.Show (ListD @Rep a) where
showsPrec _ = showList
data instance MaybeD (a :: TYPE Rep) = Nothing | Just a
instance Eq a => Prelude.Eq (MaybeD @Rep a) where
Nothing == Nothing = True
Just a == Just b = a == b
_ == _ = False
instance Ord a => Prelude.Ord (MaybeD @Rep a) where
compare Nothing Nothing = EQ
compare Nothing Just{} = LT
compare Just{} Nothing = GT
compare (Just a) (Just b) = compare a b
instance Show a => Prelude.Show (MaybeD @Rep a) where
showsPrec _ Nothing = showString "Nothing"
showsPrec d (Just a) = showParen (d >= 11) $ showString "Just " . showsPrec 11 a
instance MaybeRep Rep where
nothing = Nothing
just = Just
just' x = Just x
maybe n _ Nothing = n
maybe _ j (Just a) = j a
mapMaybe _ Nothing = nothing
mapMaybe f (Just a) = just' (f a)
instance MaybeRep# Rep where
nothing# = Maybe# (# (##) | #)
just# a = Maybe# (# | a #)
just'# a = Maybe# (# | a #)
maybe# n _ (Maybe# (# (##) | #)) = n
maybe# _ j (Maybe# (# | a #)) = j a
mapMaybe# _ (Maybe# (# (##) | #)) = nothing#
mapMaybe# f (Maybe# (# | a #)) = just'# (f a)
pattern Nothing# :: forall (a :: TYPE Rep). Maybe# a
pattern Nothing# = Maybe# (# (##) | #)
pattern Just# :: forall (a :: TYPE Rep). a -> Maybe# a
pattern Just# a = Maybe# (# | a #)
not very satisfying , but the best we can do until allows type families inside
unfortunately ghc is not able to be talked into this , even with type family helpers
type RebindMaybe# :: forall (r :: RuntimeRep). TYPE r -> TYPE ('SumRep '[ 'TupleRep '[], Rep ])
type family RebindMaybe# where
RebindMaybe# @Rep = Maybe# @Rep
type instance Rebind (Maybe# @Rep) r = RebindMaybe# @r
instance Functor (Maybe# @Rep) where
type FunctorRep (Maybe# @Rep) = (~) Rep
fmap _ Nothing# = Nothing#
fmap f (Just# a) = Just# (f a)
instance Show a => Show (Maybe# @Rep a) where
showsPrec _ Nothing# = showString "Nothing#"
showsPrec d (Just# a) = showParen (d >= 11) $ showString "Just# " . showsPrec 11 a
show x = shows x ""
We split ShowList into a separate class , even if this breaks compat with base because of this
instance (ListRep ('SumRep '[ 'TupleRep '[], Rep ]), Show a) => ShowList (Maybe# @Rep a) where
showList = go shows where
go :: forall (a :: TYPE Rep). (Maybe# a -> ShowS) -> List (Maybe# a) -> ShowS
go showx l s = case uncons# l of
Maybe# (# (##) | #) -> "[]" ++ s
Maybe# (# | (# x, xs #) #) -> '[' : showx x (showl xs)
where
showl l' = case uncons# l' of
Maybe# (# (##) | #) -> ']' : s
Maybe# (# | (# y, ys #) #) -> ',' : showx y (showl ys)
# complete Nothing # , Just # : : Maybe # #
instance ShowRep Rep where
showsPrecDef _ x s = show x ++ s
showDef x = shows x ""
instance ShowListRep Rep where
showListDef = showList__ shows
showList__ :: forall (a :: TYPE Rep). (a -> ShowS) -> List a -> ShowS
showList__ _ Nil s = "[]" ++ s
showList__ showx (x :# xs) s = '[' : showx x (showl xs)
where
showl Nil = ']' : s
showl (y :# ys) = ',' : showx y (showl ys)
instance PrintRep Rep where
hPrint h x = IO.hPutStrLn h (show x)
|
41a165fa1ee06ce6f454dd6c4cf4f42496c4b55a5e36f9ace1933048ec0eda6f | travisbrady/flajolet | odd_sketch.ml | open Core.Std
let printf = Printf.printf
type t = {
num_bits : int64;
sketch : Bitarray.t
}
let create num_bits =
{
num_bits;
sketch = Bitarray.create num_bits
}
let add t item =
let h = Int64.abs (Int64.rem (Farmhash.hash64 item) t.num_bits) in
printf "h = %Ld\n%!" h;
Bitarray.toggle_bit t.sketch h
let count t =
let pop_count = Float.of_int64 (Bitarray.num_bits_set t.sketch) in
let nf = Float.of_int64 t.num_bits in
let numer = log (1.0 -. 2.0 *. pop_count /. nf) in
let denom = log (1.0 -. 2.0 /. nf) in
numer /. denom
| null | https://raw.githubusercontent.com/travisbrady/flajolet/a6c530bf1dd73b9fa8b7185d84a5e20458a3d8af/lib/odd_sketch.ml | ocaml | open Core.Std
let printf = Printf.printf
type t = {
num_bits : int64;
sketch : Bitarray.t
}
let create num_bits =
{
num_bits;
sketch = Bitarray.create num_bits
}
let add t item =
let h = Int64.abs (Int64.rem (Farmhash.hash64 item) t.num_bits) in
printf "h = %Ld\n%!" h;
Bitarray.toggle_bit t.sketch h
let count t =
let pop_count = Float.of_int64 (Bitarray.num_bits_set t.sketch) in
let nf = Float.of_int64 t.num_bits in
let numer = log (1.0 -. 2.0 *. pop_count /. nf) in
let denom = log (1.0 -. 2.0 /. nf) in
numer /. denom
| |
db48c23c26dc3fa8b7f273d3fab0b128125fc0bd3533be434ef97d375f453905 | manuel-serrano/bigloo | etags.scm | ;*=====================================================================*/
* serrano / prgm / project / bigloo / bdl / src / etags.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : Tue Jun 8 10:23:12 1999 * /
* Last change : Fri Dec 9 11:13:58 2011 ( serrano ) * /
* Copyright : 2000 - 11 * /
;* ------------------------------------------------------------- */
;* The grammar parsing the etags file entries. */
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module __bdl_etags
(import __bdl_types
__bdl_misc
__bdl_env)
(export (read-etags! ::bdl-program ::pair-nil . ::obj)))
;*---------------------------------------------------------------------*/
;* *etags-default-keywords* ... */
;*---------------------------------------------------------------------*/
(define *etags-default-keywords*
'((define . DEFINE)
(define-inline . INLINE)
(define-method . METHOD)
(define-generic . GENERIC)
(define-macro . DEFMACRO)
(module . MODULE)
(class . CLASS) (final-class . CLASS) (wide-class . CLASS)
(extern . EXTERN) (macro . MACRO)
(define-struct . STRUCT)
(static . STATIC/EXPORT) (export . STATIC/EXPORT)
(include . INCLUDE)
(type . TYPE)))
;*---------------------------------------------------------------------*/
;* *etags-meta-keywords* ... */
;*---------------------------------------------------------------------*/
(define *etags-meta-keywords*
'(meta-define))
;*---------------------------------------------------------------------*/
;* Symbols keys ... */
;*---------------------------------------------------------------------*/
(define *keyword-key* #f)
(define *meta-key* #f)
;*---------------------------------------------------------------------*/
;* init-read-etags! ... */
;*---------------------------------------------------------------------*/
(define (init-read-etags! keywords-list)
(if (not *meta-key*)
(begin
(set! *meta-key* (gensym 'bdl))
(set! *keyword-key* (gensym 'bdl))
;; meta keywords initialization
(for-each (lambda (w)
(putprop! w *meta-key* 'META-DEFINE))
*etags-meta-keywords*)))
;; keywords initialization
(for-each (lambda (w)
(putprop! (car w) *keyword-key* (cdr w)))
keywords-list))
;*---------------------------------------------------------------------*/
;* read-etags! ... */
;* ------------------------------------------------------------- */
;* An etags file format is: */
;* ^L */
;* <file-name>,<etags-len> */
;* <definitions>+ */
;* <definition> : <keyword> <ident>^?<line-start>,<line-stop> */
;* <keyword> : (define */
;* | (define-generic */
;* | (define-method */
;* | (class */
;*---------------------------------------------------------------------*/
(define (read-etags! prgm mods . keywords)
init the etags keywords first
(init-read-etags! (if (null? keywords) *etags-default-keywords* keywords))
;; now, proceed to the reading
(with-access::bdl-program prgm (etags)
(let ((port (open-input-file etags)))
(if (not (input-port? port))
(bdl-error "read-etags" "Can't find `etags' file for input" etags)
(unwind-protect
(begin
;; we skip the ^L line
(read-line port)
;; then we read all file entries
(let loop ((entry (read-etags-file-entry prgm port mods))
(modules '()))
(cond
((eof-object? entry)
(sort modules
(lambda (l::bdl-module r::bdl-module)
(string>?
(-> l ident )
(-> r ident)))))
((not (isa? entry bdl-module))
(loop (read-etags-file-entry prgm port mods)
modules))
(else
(loop (read-etags-file-entry prgm port mods)
(cons entry modules))))))
(close-input-port port))))))
;*---------------------------------------------------------------------*/
;* read-etags-file-entry ... */
;* ------------------------------------------------------------- */
;* Because etags file format are just brain damaged, we rely on */
;* the assumption that reading at the end-of-file returns the */
;* eof-object. That is we read twice the end of file. In */
;* consequence it is impossible to use that function to read */
* in stdin . * /
;*---------------------------------------------------------------------*/
(define (read-etags-file-entry prgm port modules)
(define (fetch-file-name str)
;; fetch the file name of an etags file-name entry
(let ((port (open-input-string str))
(fetch (regular-grammar ()
((+ (out #\,))
(the-string))
(else
(bdl-error
"read-etags-file-entry"
"Illegal etags file format (can't find file name)"
str)))))
(let ((name (read/rp fetch port)))
(close-input-port port)
name)))
(define (find-module-name-from-file-name name modules)
;; from a list of modules, we search one implemented by name
(let loop ((modules modules))
(cond
((null? modules)
;; we have not been able to find the module associated
;; to that file. It could means that we are examining a C
;; module instead of the Scheme module. In consequence, we
;; will simply skip that file. This is denoted here by
;; returning #f instead of a module name.
#f)
((member name (cdr (car modules)))
(symbol->string (caar modules)))
(else
(loop (cdr modules))))))
;; we read the file name
(let ((line (read-line port)))
(cond
((eof-object? line)
line)
((string=? line "-,0")
;; this is a meta file
(let loop ((line (read-line port)))
(if (not (or (eof-object? line) (string=? line "")))
(match-case (parse-etags-meta-entry-line line)
;; a meta definition (i.e. a definition
introduced by btags that tell us to add
;; some new keyword recognition in the current
;; etags parsing).
((meta-define ?kind ?ident)
(let ((sym (string->symbol ident)))
(if (not (getprop sym *keyword-key*))
(putprop! sym
*keyword-key*
(string->symbol (string-upcase kind)))))
(loop (read-line port)))
(else
(bdl-error "read-etags-file-entry"
"Illegal entry format (can't find etags marker)"
line)))))
#unspecified)
(else
(let* ((fname (fetch-file-name line))
(mod (find-module-name-from-file-name fname modules)))
(if (not (string? mod))
#f
(read-etags-module prgm port fname mod)))))))
;*---------------------------------------------------------------------*/
;* read-etags-module ... */
;*---------------------------------------------------------------------*/
(define (read-etags-module prgm port fname mod::bstring)
(let ((minfo::bdl-module (new-module prgm
mod
(list fname)
(new-location fname 1))))
(let loop ((line (read-line port))
(fundef '())
(vardef '())
(metdef '())
(classdef '())
(structdef '())
(externdef '())
(macrodef '()))
(if (or (eof-object? line) (string=? line ""))
(begin
(set! (-> minfo functions) (reverse! fundef))
(set! (-> minfo variables) (reverse! vardef))
(set! (-> minfo classes) (reverse! classdef))
(set! (-> minfo methods) (reverse! metdef))
(set! (-> minfo structures) (reverse! structdef))
(set! (-> minfo externs) (reverse! externdef))
(set! (-> minfo macros) (reverse! macrodef))
minfo)
(match-case (parse-etags-entry-line line)
((define (?name ?line))
(multiple-value-bind (name rtype)
(parse-string-id name "obj")
;; a function definition
(loop (read-line port)
(cons (new-function prgm
name
minfo
(new-location fname line))
fundef)
vardef
metdef
classdef
structdef
externdef
macrodef)))
((define ?name ?line)
(multiple-value-bind (name type)
(parse-string-id name "obj")
;; a variable definition
(loop (read-line port)
fundef
(cons (new-variable prgm
name
minfo
(new-location fname line))
vardef)
metdef
classdef
structdef
externdef
macrodef)))
((define-generic (?name ?line))
;; a generic function definition
(loop (read-line port)
(cons (new-generic prgm
name
minfo
(new-location fname line))
fundef)
vardef
metdef
classdef
structdef
externdef
macrodef))
((define-method (?id ?arg ?line))
;; a method function definition
(multiple-value-bind (name rtype)
(parse-string-id id "obj")
(multiple-value-bind (- type)
(parse-string-id arg "obj")
(let ((met (new-method prgm
name
minfo
(new-location fname line)
type
rtype)))
(loop (read-line port)
fundef
vardef
(cons met metdef)
classdef
structdef
externdef
macrodef)))))
((class ?id ?line)
(multiple-value-bind (name type)
(parse-string-id id "object")
;; a class definition
(loop (read-line port)
fundef
vardef
metdef
(cons (new-class prgm
name
minfo
(new-location fname line)
(find-bdl-class prgm type)
'plain)
classdef)
structdef
externdef
macrodef)))
((wide-class ?id ?line)
(multiple-value-bind (name type)
(parse-string-id id "object")
;; a class definition
(loop (read-line port)
fundef
vardef
metdef
(cons (new-class prgm
name
minfo
(new-location fname line)
(find-bdl-class prgm type)
'wide)
classdef)
structdef
externdef
macrodef)))
((final-class ?id ?line)
(multiple-value-bind (name type)
(parse-string-id id "object")
;; a class definition
(loop (read-line port)
fundef
vardef
metdef
(cons (new-class prgm
name
minfo
(new-location fname line)
(find-bdl-class prgm type)
'final)
classdef)
structdef
externdef
macrodef)))
((define-struct ?name ?line)
;; a struct definition
(loop (read-line port)
fundef
vardef
metdef
classdef
(cons (new-structure prgm
name
minfo
(new-location fname line))
structdef)
externdef
macrodef))
((extern ?name ?line)
;; an extern definition
(loop (read-line port)
fundef
vardef
metdef
classdef
structdef
(cons (new-extern prgm
name
minfo
(new-location fname line))
externdef)
macrodef))
((define-macro (?name ?line))
;; a macro definition
(loop (read-line port)
fundef
vardef
metdef
classdef
structdef
externdef
(cons (new-macro prgm
name
minfo
(new-location fname line))
macrodef)))
((module ?name ?line)
(loop (read-line port)
fundef
vardef
metdef
classdef
structdef
externdef
macrodef))
((ignore)
;; an entry to be ignored
(loop (read-line port)
fundef
vardef
metdef
classdef
structdef
externdef
macrodef))
(else
(bdl-error "read-etags-file-entry"
"Illegal entry format (illegal line)"
line)
(loop (read-line port)
fundef
vardef
metdef
classdef
structdef
externdef
macrodef)))))))
;*---------------------------------------------------------------------*/
;* parse-etags-entry-line ... */
;*---------------------------------------------------------------------*/
(define (parse-etags-entry-line line::bstring)
(let ((port (open-input-string line))
(reg (regular-grammar ((letter (in ("azAZ") (#a128 #a255)))
(special (in "!@~$%^&*></-_+\\|=?.:"))
(kspecial (in "!@~$%^&*></-_+\\|=?."))
(id (: (* digit)
(or letter special)
(* (or letter
special
digit
(in ",'`"))))))
(blank
(ignore))
("("
(list 'PAR-OPEN))
(")"
(list 'PAR-CLO))
((+ digit)
(cons 'NUMBER (the-fixnum)))
(id
(let* ((string (the-string))
(symbol (the-symbol))
(kwd (getprop symbol *keyword-key*)))
(if kwd
;; this is a keyword
(cons kwd symbol)
;; this is a regular identifier
(cons 'IDENT string))))
((: #\" (* (out #\")) #\")
(list 'STRING))
(#a127
(list 'EOI))
(#\,
(ignore))
(else
(let ((c (the-failure)))
(if (eof-object? c)
c
(bdl-error "parse-etage-entry-line"
"Illegal char"
c))))))
(lalr (lalr-grammar
(IDENT PAR-OPEN PAR-CLO EOI NUMBER
DEFINE INLINE DEFMACRO MODULE
GENERIC METHOD
TYPESEP
CLASS STRUCT EXTERN MACRO STRING INCLUDE TYPE
STATIC/EXPORT)
;; the line we are to parse
(line
((function)
function)
((variable)
variable)
((genericdef)
genericdef)
((methoddef)
methoddef)
((classdef)
classdef)
((structdef)
structdef)
((externdef)
externdef)
((macrodef)
macrodef)
((moduledef)
moduledef))
;; function definitions
(function
((PAR-OPEN DEFINE PAR-OPEN IDENT EOI NUMBER@line NUMBER)
`(define (,IDENT ,line)))
((PAR-OPEN DEFINE PAR-OPEN TYPE EOI NUMBER@line NUMBER)
`(define ("TYPE" ,line)))
((PAR-OPEN INLINE PAR-OPEN IDENT EOI NUMBER@line NUMBER)
`(define (,IDENT ,line)))
((PAR-OPEN INLINE PAR-OPEN TYPE EOI NUMBER@line NUMBER)
`(define ("TYPE" ,line))))
;; variable definitions
(variable
((PAR-OPEN DEFINE IDENT EOI NUMBER@line NUMBER)
`(define ,IDENT ,line))
((PAR-OPEN DEFINE TYPE EOI NUMBER@line NUMBER)
`(define "TYPE" ,line)))
;; generic function definitions
(genericdef
((PAR-OPEN GENERIC PAR-OPEN IDENT EOI NUMBER@line NUMBER)
`(define-generic (,IDENT ,line)))
((PAR-OPEN GENERIC PAR-OPEN TYPE EOI NUMBER@line NUMBER)
`(define-generic ("TYPE" ,line))))
;; method definitions
(methoddef
((PAR-OPEN METHOD PAR-OPEN IDENT@mnane IDENT@aname dummys
EOI NUMBER@line NUMBER)
`(define-method (,mnane ,aname ,line)))
((PAR-OPEN METHOD PAR-OPEN TYPE IDENT@aname dummys
EOI NUMBER@line NUMBER)
`(define-method ("TYPE" ,aname ,line)))
((PAR-OPEN METHOD PAR-OPEN TYPE@type1 TYPE@type2 dummys
EOI NUMBER@line NUMBER)
`(define-method ("TYPE" "TYPE" ,line))))
(dummys
(()
'dummy)
((PAR-CLO dummys)
'dummy)
((PAR-OPEN dummys)
'dummy)
((IDENT dummys)
'dummy))
;; class definitions
(classdef
((PAR-OPEN CLASS IDENT dummys
EOI NUMBER@line NUMBER)
`(,CLASS ,IDENT ,line))
((PAR-OPEN CLASS EXTERN dummys
EOI NUMBER@line NUMBER)
`(,CLASS "extern" ,line))
((PAR-OPEN CLASS TYPE dummys
EOI NUMBER@line NUMBER)
`(,CLASS "type" ,line))
((PAR-OPEN STATIC/EXPORT
PAR-OPEN CLASS TYPE dummys
EOI NUMBER@line NUMBER)
`(,CLASS "type" ,line))
((PAR-OPEN STATIC/EXPORT
PAR-OPEN CLASS IDENT dummys
EOI NUMBER@line NUMBER)
`(,CLASS ,IDENT ,line)))
;; struct definitions
(structdef
((PAR-OPEN STRUCT IDENT EOI NUMBER@line NUMBER)
`(define-struct ,IDENT ,line))
((PAR-OPEN STRUCT TYPE EOI NUMBER@line NUMBER)
`(define-struct "type" ,line))
((PAR-OPEN STRUCT EXTERN EOI NUMBER@line NUMBER)
`(define-struct "extern" ,line)))
;; extern definitions
(externdef
((PAR-OPEN EXTERN extern-sans-clause)
extern-sans-clause)
((extern-sans-clause)
extern-sans-clause))
(extern-sans-clause
((PAR-OPEN MACRO IDENT EOI NUMBER@line NUMBER)
`(extern ,IDENT ,line))
((PAR-OPEN MACRO TYPE EOI NUMBER@line NUMBER)
`(extern "TYPE" ,line))
((PAR-OPEN INCLUDE EOI NUMBER@line NUMBER)
`(ignore))
((PAR-OPEN IDENT STRING EOI NUMBER@line NUMBER)
`(extern ,IDENT ,line))
((PAR-OPEN TYPE STRING EOI NUMBER@line NUMBER)
`(extern "TYPE" ,line))
((PAR-OPEN IDENT EOI NUMBER@line NUMBER)
`(extern ,IDENT ,line))
((PAR-OPEN STATIC/EXPORT IDENT STRING
EOI NUMBER@line NUMBER)
'(ignore))
((PAR-OPEN STATIC/EXPORT TYPE STRING
EOI NUMBER@line NUMBER)
'(ignore))
((PAR-OPEN TYPE EOI NUMBER NUMBER)
'(ignore)))
;; macro definitions
(macrodef
((PAR-OPEN DEFMACRO PAR-OPEN IDENT EOI NUMBER@line NUMBER)
`(define-macro (,IDENT ,line)))
((PAR-OPEN DEFMACRO PAR-OPEN DEFINE EOI NUMBER@line NUMBER)
`(define-macro (,(symbol->string DEFINE) ,line)))
((PAR-OPEN DEFMACRO PAR-OPEN TYPE EOI NUMBER@line NUMBER)
`(define-macro ("TYPE" ,line))))
;; module definitions
(moduledef
((PAR-OPEN MODULE IDENT EOI NUMBER@line NUMBER)
`(module ,IDENT ,line))))))
(try (read/lalrp lalr reg port)
(lambda (escape obj proc msg)
(escape #f)))))
;*---------------------------------------------------------------------*/
;* parse-etags-meta-entry-line ... */
;*---------------------------------------------------------------------*/
(define (parse-etags-meta-entry-line line)
(let ((port (open-input-string line))
(reg (regular-grammar ((letter (in ("azAZ") (#a128 #a255)))
(special (in "!@~$%^&*></-_+\\|=?.:"))
(id (: (* digit)
(or letter special)
(* (or letter
special
digit
(in ",'`"))))))
(blank
(ignore))
("("
(list 'PAR-OPEN))
((+ digit)
(cons 'NUMBER (the-fixnum)))
(id
(let* ((string (the-string))
(symbol (the-symbol))
(kwd (getprop symbol *meta-key*)))
(if kwd
;; this is a keyword
(cons kwd symbol)
;; this is a regular identifier
(cons 'IDENT string))))
(#a127
(list 'EOI))
(#\,
(ignore))
(else
(let ((c (the-failure)))
(if (eof-object? c)
c
(bdl-error "parse-etage-meta-entry-line"
"Illegal char"
c))))))
(lalr (lalr-grammar
(IDENT PAR-OPEN EOI NUMBER META-DEFINE)
;; variable keywords
(metadef
((PAR-OPEN META-DEFINE IDENT@kd IDENT@id EOI NUMBER NUMBER)
`(meta-define ,kd ,id))))))
(with-exception-handler
(lambda (e)
(error-notify e)
#f)
(lambda ()
(read/lalrp lalr reg port)))))
| null | https://raw.githubusercontent.com/manuel-serrano/bigloo/eb650ed4429155f795a32465e009706bbf1b8d74/bdl/src/etags.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
* The grammar parsing the etags file entries. */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* *etags-default-keywords* ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* *etags-meta-keywords* ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* Symbols keys ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* init-read-etags! ... */
*---------------------------------------------------------------------*/
meta keywords initialization
keywords initialization
*---------------------------------------------------------------------*/
* read-etags! ... */
* ------------------------------------------------------------- */
* An etags file format is: */
* ^L */
* <file-name>,<etags-len> */
* <definitions>+ */
* <definition> : <keyword> <ident>^?<line-start>,<line-stop> */
* <keyword> : (define */
* | (define-generic */
* | (define-method */
* | (class */
*---------------------------------------------------------------------*/
now, proceed to the reading
we skip the ^L line
then we read all file entries
*---------------------------------------------------------------------*/
* read-etags-file-entry ... */
* ------------------------------------------------------------- */
* Because etags file format are just brain damaged, we rely on */
* the assumption that reading at the end-of-file returns the */
* eof-object. That is we read twice the end of file. In */
* consequence it is impossible to use that function to read */
*---------------------------------------------------------------------*/
fetch the file name of an etags file-name entry
from a list of modules, we search one implemented by name
we have not been able to find the module associated
to that file. It could means that we are examining a C
module instead of the Scheme module. In consequence, we
will simply skip that file. This is denoted here by
returning #f instead of a module name.
we read the file name
this is a meta file
a meta definition (i.e. a definition
some new keyword recognition in the current
etags parsing).
*---------------------------------------------------------------------*/
* read-etags-module ... */
*---------------------------------------------------------------------*/
a function definition
a variable definition
a generic function definition
a method function definition
a class definition
a class definition
a class definition
a struct definition
an extern definition
a macro definition
an entry to be ignored
*---------------------------------------------------------------------*/
* parse-etags-entry-line ... */
*---------------------------------------------------------------------*/
this is a keyword
this is a regular identifier
the line we are to parse
function definitions
variable definitions
generic function definitions
method definitions
class definitions
struct definitions
extern definitions
macro definitions
module definitions
*---------------------------------------------------------------------*/
* parse-etags-meta-entry-line ... */
*---------------------------------------------------------------------*/
this is a keyword
this is a regular identifier
variable keywords | * serrano / prgm / project / bigloo / bdl / src / etags.scm * /
* Author : * /
* Creation : Tue Jun 8 10:23:12 1999 * /
* Last change : Fri Dec 9 11:13:58 2011 ( serrano ) * /
* Copyright : 2000 - 11 * /
(module __bdl_etags
(import __bdl_types
__bdl_misc
__bdl_env)
(export (read-etags! ::bdl-program ::pair-nil . ::obj)))
(define *etags-default-keywords*
'((define . DEFINE)
(define-inline . INLINE)
(define-method . METHOD)
(define-generic . GENERIC)
(define-macro . DEFMACRO)
(module . MODULE)
(class . CLASS) (final-class . CLASS) (wide-class . CLASS)
(extern . EXTERN) (macro . MACRO)
(define-struct . STRUCT)
(static . STATIC/EXPORT) (export . STATIC/EXPORT)
(include . INCLUDE)
(type . TYPE)))
(define *etags-meta-keywords*
'(meta-define))
(define *keyword-key* #f)
(define *meta-key* #f)
(define (init-read-etags! keywords-list)
(if (not *meta-key*)
(begin
(set! *meta-key* (gensym 'bdl))
(set! *keyword-key* (gensym 'bdl))
(for-each (lambda (w)
(putprop! w *meta-key* 'META-DEFINE))
*etags-meta-keywords*)))
(for-each (lambda (w)
(putprop! (car w) *keyword-key* (cdr w)))
keywords-list))
(define (read-etags! prgm mods . keywords)
init the etags keywords first
(init-read-etags! (if (null? keywords) *etags-default-keywords* keywords))
(with-access::bdl-program prgm (etags)
(let ((port (open-input-file etags)))
(if (not (input-port? port))
(bdl-error "read-etags" "Can't find `etags' file for input" etags)
(unwind-protect
(begin
(read-line port)
(let loop ((entry (read-etags-file-entry prgm port mods))
(modules '()))
(cond
((eof-object? entry)
(sort modules
(lambda (l::bdl-module r::bdl-module)
(string>?
(-> l ident )
(-> r ident)))))
((not (isa? entry bdl-module))
(loop (read-etags-file-entry prgm port mods)
modules))
(else
(loop (read-etags-file-entry prgm port mods)
(cons entry modules))))))
(close-input-port port))))))
* in stdin . * /
(define (read-etags-file-entry prgm port modules)
(define (fetch-file-name str)
(let ((port (open-input-string str))
(fetch (regular-grammar ()
((+ (out #\,))
(the-string))
(else
(bdl-error
"read-etags-file-entry"
"Illegal etags file format (can't find file name)"
str)))))
(let ((name (read/rp fetch port)))
(close-input-port port)
name)))
(define (find-module-name-from-file-name name modules)
(let loop ((modules modules))
(cond
((null? modules)
#f)
((member name (cdr (car modules)))
(symbol->string (caar modules)))
(else
(loop (cdr modules))))))
(let ((line (read-line port)))
(cond
((eof-object? line)
line)
((string=? line "-,0")
(let loop ((line (read-line port)))
(if (not (or (eof-object? line) (string=? line "")))
(match-case (parse-etags-meta-entry-line line)
introduced by btags that tell us to add
((meta-define ?kind ?ident)
(let ((sym (string->symbol ident)))
(if (not (getprop sym *keyword-key*))
(putprop! sym
*keyword-key*
(string->symbol (string-upcase kind)))))
(loop (read-line port)))
(else
(bdl-error "read-etags-file-entry"
"Illegal entry format (can't find etags marker)"
line)))))
#unspecified)
(else
(let* ((fname (fetch-file-name line))
(mod (find-module-name-from-file-name fname modules)))
(if (not (string? mod))
#f
(read-etags-module prgm port fname mod)))))))
(define (read-etags-module prgm port fname mod::bstring)
(let ((minfo::bdl-module (new-module prgm
mod
(list fname)
(new-location fname 1))))
(let loop ((line (read-line port))
(fundef '())
(vardef '())
(metdef '())
(classdef '())
(structdef '())
(externdef '())
(macrodef '()))
(if (or (eof-object? line) (string=? line ""))
(begin
(set! (-> minfo functions) (reverse! fundef))
(set! (-> minfo variables) (reverse! vardef))
(set! (-> minfo classes) (reverse! classdef))
(set! (-> minfo methods) (reverse! metdef))
(set! (-> minfo structures) (reverse! structdef))
(set! (-> minfo externs) (reverse! externdef))
(set! (-> minfo macros) (reverse! macrodef))
minfo)
(match-case (parse-etags-entry-line line)
((define (?name ?line))
(multiple-value-bind (name rtype)
(parse-string-id name "obj")
(loop (read-line port)
(cons (new-function prgm
name
minfo
(new-location fname line))
fundef)
vardef
metdef
classdef
structdef
externdef
macrodef)))
((define ?name ?line)
(multiple-value-bind (name type)
(parse-string-id name "obj")
(loop (read-line port)
fundef
(cons (new-variable prgm
name
minfo
(new-location fname line))
vardef)
metdef
classdef
structdef
externdef
macrodef)))
((define-generic (?name ?line))
(loop (read-line port)
(cons (new-generic prgm
name
minfo
(new-location fname line))
fundef)
vardef
metdef
classdef
structdef
externdef
macrodef))
((define-method (?id ?arg ?line))
(multiple-value-bind (name rtype)
(parse-string-id id "obj")
(multiple-value-bind (- type)
(parse-string-id arg "obj")
(let ((met (new-method prgm
name
minfo
(new-location fname line)
type
rtype)))
(loop (read-line port)
fundef
vardef
(cons met metdef)
classdef
structdef
externdef
macrodef)))))
((class ?id ?line)
(multiple-value-bind (name type)
(parse-string-id id "object")
(loop (read-line port)
fundef
vardef
metdef
(cons (new-class prgm
name
minfo
(new-location fname line)
(find-bdl-class prgm type)
'plain)
classdef)
structdef
externdef
macrodef)))
((wide-class ?id ?line)
(multiple-value-bind (name type)
(parse-string-id id "object")
(loop (read-line port)
fundef
vardef
metdef
(cons (new-class prgm
name
minfo
(new-location fname line)
(find-bdl-class prgm type)
'wide)
classdef)
structdef
externdef
macrodef)))
((final-class ?id ?line)
(multiple-value-bind (name type)
(parse-string-id id "object")
(loop (read-line port)
fundef
vardef
metdef
(cons (new-class prgm
name
minfo
(new-location fname line)
(find-bdl-class prgm type)
'final)
classdef)
structdef
externdef
macrodef)))
((define-struct ?name ?line)
(loop (read-line port)
fundef
vardef
metdef
classdef
(cons (new-structure prgm
name
minfo
(new-location fname line))
structdef)
externdef
macrodef))
((extern ?name ?line)
(loop (read-line port)
fundef
vardef
metdef
classdef
structdef
(cons (new-extern prgm
name
minfo
(new-location fname line))
externdef)
macrodef))
((define-macro (?name ?line))
(loop (read-line port)
fundef
vardef
metdef
classdef
structdef
externdef
(cons (new-macro prgm
name
minfo
(new-location fname line))
macrodef)))
((module ?name ?line)
(loop (read-line port)
fundef
vardef
metdef
classdef
structdef
externdef
macrodef))
((ignore)
(loop (read-line port)
fundef
vardef
metdef
classdef
structdef
externdef
macrodef))
(else
(bdl-error "read-etags-file-entry"
"Illegal entry format (illegal line)"
line)
(loop (read-line port)
fundef
vardef
metdef
classdef
structdef
externdef
macrodef)))))))
(define (parse-etags-entry-line line::bstring)
(let ((port (open-input-string line))
(reg (regular-grammar ((letter (in ("azAZ") (#a128 #a255)))
(special (in "!@~$%^&*></-_+\\|=?.:"))
(kspecial (in "!@~$%^&*></-_+\\|=?."))
(id (: (* digit)
(or letter special)
(* (or letter
special
digit
(in ",'`"))))))
(blank
(ignore))
("("
(list 'PAR-OPEN))
(")"
(list 'PAR-CLO))
((+ digit)
(cons 'NUMBER (the-fixnum)))
(id
(let* ((string (the-string))
(symbol (the-symbol))
(kwd (getprop symbol *keyword-key*)))
(if kwd
(cons kwd symbol)
(cons 'IDENT string))))
((: #\" (* (out #\")) #\")
(list 'STRING))
(#a127
(list 'EOI))
(#\,
(ignore))
(else
(let ((c (the-failure)))
(if (eof-object? c)
c
(bdl-error "parse-etage-entry-line"
"Illegal char"
c))))))
(lalr (lalr-grammar
(IDENT PAR-OPEN PAR-CLO EOI NUMBER
DEFINE INLINE DEFMACRO MODULE
GENERIC METHOD
TYPESEP
CLASS STRUCT EXTERN MACRO STRING INCLUDE TYPE
STATIC/EXPORT)
(line
((function)
function)
((variable)
variable)
((genericdef)
genericdef)
((methoddef)
methoddef)
((classdef)
classdef)
((structdef)
structdef)
((externdef)
externdef)
((macrodef)
macrodef)
((moduledef)
moduledef))
(function
((PAR-OPEN DEFINE PAR-OPEN IDENT EOI NUMBER@line NUMBER)
`(define (,IDENT ,line)))
((PAR-OPEN DEFINE PAR-OPEN TYPE EOI NUMBER@line NUMBER)
`(define ("TYPE" ,line)))
((PAR-OPEN INLINE PAR-OPEN IDENT EOI NUMBER@line NUMBER)
`(define (,IDENT ,line)))
((PAR-OPEN INLINE PAR-OPEN TYPE EOI NUMBER@line NUMBER)
`(define ("TYPE" ,line))))
(variable
((PAR-OPEN DEFINE IDENT EOI NUMBER@line NUMBER)
`(define ,IDENT ,line))
((PAR-OPEN DEFINE TYPE EOI NUMBER@line NUMBER)
`(define "TYPE" ,line)))
(genericdef
((PAR-OPEN GENERIC PAR-OPEN IDENT EOI NUMBER@line NUMBER)
`(define-generic (,IDENT ,line)))
((PAR-OPEN GENERIC PAR-OPEN TYPE EOI NUMBER@line NUMBER)
`(define-generic ("TYPE" ,line))))
(methoddef
((PAR-OPEN METHOD PAR-OPEN IDENT@mnane IDENT@aname dummys
EOI NUMBER@line NUMBER)
`(define-method (,mnane ,aname ,line)))
((PAR-OPEN METHOD PAR-OPEN TYPE IDENT@aname dummys
EOI NUMBER@line NUMBER)
`(define-method ("TYPE" ,aname ,line)))
((PAR-OPEN METHOD PAR-OPEN TYPE@type1 TYPE@type2 dummys
EOI NUMBER@line NUMBER)
`(define-method ("TYPE" "TYPE" ,line))))
(dummys
(()
'dummy)
((PAR-CLO dummys)
'dummy)
((PAR-OPEN dummys)
'dummy)
((IDENT dummys)
'dummy))
(classdef
((PAR-OPEN CLASS IDENT dummys
EOI NUMBER@line NUMBER)
`(,CLASS ,IDENT ,line))
((PAR-OPEN CLASS EXTERN dummys
EOI NUMBER@line NUMBER)
`(,CLASS "extern" ,line))
((PAR-OPEN CLASS TYPE dummys
EOI NUMBER@line NUMBER)
`(,CLASS "type" ,line))
((PAR-OPEN STATIC/EXPORT
PAR-OPEN CLASS TYPE dummys
EOI NUMBER@line NUMBER)
`(,CLASS "type" ,line))
((PAR-OPEN STATIC/EXPORT
PAR-OPEN CLASS IDENT dummys
EOI NUMBER@line NUMBER)
`(,CLASS ,IDENT ,line)))
(structdef
((PAR-OPEN STRUCT IDENT EOI NUMBER@line NUMBER)
`(define-struct ,IDENT ,line))
((PAR-OPEN STRUCT TYPE EOI NUMBER@line NUMBER)
`(define-struct "type" ,line))
((PAR-OPEN STRUCT EXTERN EOI NUMBER@line NUMBER)
`(define-struct "extern" ,line)))
(externdef
((PAR-OPEN EXTERN extern-sans-clause)
extern-sans-clause)
((extern-sans-clause)
extern-sans-clause))
(extern-sans-clause
((PAR-OPEN MACRO IDENT EOI NUMBER@line NUMBER)
`(extern ,IDENT ,line))
((PAR-OPEN MACRO TYPE EOI NUMBER@line NUMBER)
`(extern "TYPE" ,line))
((PAR-OPEN INCLUDE EOI NUMBER@line NUMBER)
`(ignore))
((PAR-OPEN IDENT STRING EOI NUMBER@line NUMBER)
`(extern ,IDENT ,line))
((PAR-OPEN TYPE STRING EOI NUMBER@line NUMBER)
`(extern "TYPE" ,line))
((PAR-OPEN IDENT EOI NUMBER@line NUMBER)
`(extern ,IDENT ,line))
((PAR-OPEN STATIC/EXPORT IDENT STRING
EOI NUMBER@line NUMBER)
'(ignore))
((PAR-OPEN STATIC/EXPORT TYPE STRING
EOI NUMBER@line NUMBER)
'(ignore))
((PAR-OPEN TYPE EOI NUMBER NUMBER)
'(ignore)))
(macrodef
((PAR-OPEN DEFMACRO PAR-OPEN IDENT EOI NUMBER@line NUMBER)
`(define-macro (,IDENT ,line)))
((PAR-OPEN DEFMACRO PAR-OPEN DEFINE EOI NUMBER@line NUMBER)
`(define-macro (,(symbol->string DEFINE) ,line)))
((PAR-OPEN DEFMACRO PAR-OPEN TYPE EOI NUMBER@line NUMBER)
`(define-macro ("TYPE" ,line))))
(moduledef
((PAR-OPEN MODULE IDENT EOI NUMBER@line NUMBER)
`(module ,IDENT ,line))))))
(try (read/lalrp lalr reg port)
(lambda (escape obj proc msg)
(escape #f)))))
(define (parse-etags-meta-entry-line line)
(let ((port (open-input-string line))
(reg (regular-grammar ((letter (in ("azAZ") (#a128 #a255)))
(special (in "!@~$%^&*></-_+\\|=?.:"))
(id (: (* digit)
(or letter special)
(* (or letter
special
digit
(in ",'`"))))))
(blank
(ignore))
("("
(list 'PAR-OPEN))
((+ digit)
(cons 'NUMBER (the-fixnum)))
(id
(let* ((string (the-string))
(symbol (the-symbol))
(kwd (getprop symbol *meta-key*)))
(if kwd
(cons kwd symbol)
(cons 'IDENT string))))
(#a127
(list 'EOI))
(#\,
(ignore))
(else
(let ((c (the-failure)))
(if (eof-object? c)
c
(bdl-error "parse-etage-meta-entry-line"
"Illegal char"
c))))))
(lalr (lalr-grammar
(IDENT PAR-OPEN EOI NUMBER META-DEFINE)
(metadef
((PAR-OPEN META-DEFINE IDENT@kd IDENT@id EOI NUMBER NUMBER)
`(meta-define ,kd ,id))))))
(with-exception-handler
(lambda (e)
(error-notify e)
#f)
(lambda ()
(read/lalrp lalr reg port)))))
|
12572fb557190ce67531e085a3daa2729e57ddceaf0a0e74290e9e3b9485295a | chetmurthy/typpx | debug.ml | let debug = match Sys.getenv "TYPPX_DEBUG" with
| _ -> true
| exception Not_found -> false
| null | https://raw.githubusercontent.com/chetmurthy/typpx/a740750b75739e686da49b46ded7db7d6874e108/src/debug.ml | ocaml | let debug = match Sys.getenv "TYPPX_DEBUG" with
| _ -> true
| exception Not_found -> false
| |
31d908956bcde3af77b226247ccc243b58a4d2bc48ccbdf9f8a6dfa9c154cdca | kqr/gists | markov_faster.hs | module Main where
import Prelude hiding (map)
import Data.List (foldl')
import Data.Map (Map, map, fromDistinctAscList, toAscList, insertWith, empty)
import Data.Tuple (swap)
import Control.Applicative ((<$>))
-- tiny, general utility functions that almost should
-- have been in the libraries to begin with.
enumerate :: [a] -> [(Int, a)]
enumerate = zip [0..]
unwind :: (a, [b]) -> [(a, b)]
unwind (a, b) = ((,) a) <$> b
aggregate :: (Ord k) => Map k [a] -> (k, a) -> Map k [a]
aggregate m (k, a) = insertWith (++) k [a] m
data Corpus = Corpus (Map Int String) (Map String [Int])
main = do
-- Read the corpus file and chunk it into a Corpus
corpus <- chunk <$> readFile "corpus.txt"
-- So far, only chunks up a Corpus, doesn't generate anything.
sentence <- corpus `generate` 16
putStrLn sentence
chunk :: String -> Corpus
chunk str = Corpus chunks dictionary
where
chunks = fromDistinctAscList . enumerate $ lines str
dictionary = foldl' aggregate empty $ swap <$> chunklist
chunklist = concatMap unwind . toAscList $ map words chunks
generate :: Corpus -> Int -> IO String
generate = undefined | null | https://raw.githubusercontent.com/kqr/gists/b0b5ab2a6af0f939a9e24165959bb362281ce897/algorithms/markovs/markov_faster.hs | haskell | tiny, general utility functions that almost should
have been in the libraries to begin with.
Read the corpus file and chunk it into a Corpus
So far, only chunks up a Corpus, doesn't generate anything. | module Main where
import Prelude hiding (map)
import Data.List (foldl')
import Data.Map (Map, map, fromDistinctAscList, toAscList, insertWith, empty)
import Data.Tuple (swap)
import Control.Applicative ((<$>))
enumerate :: [a] -> [(Int, a)]
enumerate = zip [0..]
unwind :: (a, [b]) -> [(a, b)]
unwind (a, b) = ((,) a) <$> b
aggregate :: (Ord k) => Map k [a] -> (k, a) -> Map k [a]
aggregate m (k, a) = insertWith (++) k [a] m
data Corpus = Corpus (Map Int String) (Map String [Int])
main = do
corpus <- chunk <$> readFile "corpus.txt"
sentence <- corpus `generate` 16
putStrLn sentence
chunk :: String -> Corpus
chunk str = Corpus chunks dictionary
where
chunks = fromDistinctAscList . enumerate $ lines str
dictionary = foldl' aggregate empty $ swap <$> chunklist
chunklist = concatMap unwind . toAscList $ map words chunks
generate :: Corpus -> Int -> IO String
generate = undefined |
ec031ee6d86cc725bf79fd68b8ea02be3650ae00894c9a72f9f1758e2dafbd8f | janestreet/hardcaml_circuits | synth.ml | open Core
open Hardcaml
let create_circuit
(type params)
scope
(module Component : Component_intf.S with type Params.t = params)
(params : params)
=
let module I_data = struct
module Pre = struct
include Component.Input
let t = Component.input_port_names_and_width params
end
include Pre
include Hardcaml.Interface.Make (Pre)
end
in
let module I = struct
type 'a t =
{ clock : 'a
; i_data : 'a I_data.t [@rtlprefix "i_data_"]
}
[@@deriving sexp_of, hardcaml]
end
in
let module O = struct
module Pre = struct
include Component.Output
let t = Component.output_port_names_and_width params
end
include Pre
include Hardcaml.Interface.Make (Pre)
end
in
let module _ = Hardcaml_xilinx_reports.Command.With_interface (I) (O) in
let create scope (input : _ I.t) =
let spec_no_clear = Reg_spec.create ~clock:input.clock () in
let reg x = Signal.reg spec_no_clear ~enable:Signal.vdd x in
Component.create ~params ~scope ~clock:input.clock (I_data.map ~f:reg input.i_data)
|> O.map ~f:reg
in
let name = Component.name ^ "__" ^ Component.Params.name params in
let module Circuit = Hardcaml.Circuit.With_interface (I) (O) in
Circuit.create_exn ~name (create scope)
;;
let name_exn signal =
match Signal.names signal with
| [ hd ] -> hd
| _ -> assert false
;;
let circuit_data_inputs circuit =
List.filter (Circuit.inputs circuit) ~f:(fun input ->
not (String.equal (name_exn input) "clock"))
;;
let create_mega_circuit scope (circuits : Circuit.t list) =
let db = Scope.circuit_database scope in
let circuit_names =
List.map circuits ~f:(fun circuit -> Circuit_database.insert db circuit)
in
let clock = Signal.input "clock" 1 in
let data_inputs =
let i = ref (-1) in
List.map circuits ~f:(fun circuit ->
List.map (circuit_data_inputs circuit) ~f:(fun inp ->
Int.incr i;
Signal.input (sprintf "data_in_%d" !i) (Signal.width inp)))
in
let outputs =
let i = ref 0 in
List.map3_exn
circuits
circuit_names
data_inputs
~f:(fun circuit circuit_name data_inputs ->
let circuit_data_input_names =
List.map ~f:name_exn (circuit_data_inputs circuit)
in
let inputs =
let clock_input = "clock", clock in
let data_inputs =
List.map2_exn circuit_data_input_names data_inputs ~f:(fun a b -> a, b)
in
clock_input :: data_inputs
in
let outputs =
List.map (Circuit.outputs circuit) ~f:(fun s -> name_exn s, Signal.width s)
in
let output_names = List.map ~f:fst outputs in
let inst = Instantiation.create ~name:circuit_name ~inputs ~outputs () in
List.map output_names ~f:(fun name ->
Int.incr i;
Signal.output (sprintf "data_out_%d" !i) (Map.find_exn inst name)))
|> List.concat
in
Circuit.create_exn ~name:"top" outputs
;;
let command_for_single =
List.map Synth_targets.targets ~f:(fun component ->
let (module Component : Component_intf.S) = component in
let command =
Async.Command.async
~summary:(Printf.sprintf "Single-component synthesis for %s" Component.name)
[%map_open.Command
let synth_flags = Hardcaml_xilinx_reports.Command.Command_flags.flags
and params = Component.Params.flags in
fun () ->
Hardcaml_xilinx_reports.Command.run_circuit
~sort_by_name:true
~flags:synth_flags
(fun scope -> create_circuit scope (module Component) params)]
~behave_nicely_in_pipeline:false
in
let name = Component.name |> String.substr_replace_all ~pattern:"_" ~with_:"-" in
name, command)
|> Command.group ~summary:"Single component synthesis report"
;;
let command_for_all =
let circuit scope =
List.concat_map Synth_targets.targets ~f:(fun component ->
let (module Component : Component_intf.S) = component in
List.map Component.params ~f:(fun param ->
create_circuit scope (module Component) param))
|> create_mega_circuit scope
in
Hardcaml_xilinx_reports.Command.command_circuit ~sort_by_name:true circuit
;;
let command_old =
Command.group
~summary:"Old-style non generic synthesis targets"
[ "arbiters", Arbiters_old.command ]
;;
let command =
Command.group
~summary:"synthesis reports commander"
[ "all", command_for_all; "old", command_old; "single", command_for_single ]
;;
| null | https://raw.githubusercontent.com/janestreet/hardcaml_circuits/4b834cfb0c42e9440ba7891b1cc2d45b0669a8dc/synthesis_reports/src/synth.ml | ocaml | open Core
open Hardcaml
let create_circuit
(type params)
scope
(module Component : Component_intf.S with type Params.t = params)
(params : params)
=
let module I_data = struct
module Pre = struct
include Component.Input
let t = Component.input_port_names_and_width params
end
include Pre
include Hardcaml.Interface.Make (Pre)
end
in
let module I = struct
type 'a t =
{ clock : 'a
; i_data : 'a I_data.t [@rtlprefix "i_data_"]
}
[@@deriving sexp_of, hardcaml]
end
in
let module O = struct
module Pre = struct
include Component.Output
let t = Component.output_port_names_and_width params
end
include Pre
include Hardcaml.Interface.Make (Pre)
end
in
let module _ = Hardcaml_xilinx_reports.Command.With_interface (I) (O) in
let create scope (input : _ I.t) =
let spec_no_clear = Reg_spec.create ~clock:input.clock () in
let reg x = Signal.reg spec_no_clear ~enable:Signal.vdd x in
Component.create ~params ~scope ~clock:input.clock (I_data.map ~f:reg input.i_data)
|> O.map ~f:reg
in
let name = Component.name ^ "__" ^ Component.Params.name params in
let module Circuit = Hardcaml.Circuit.With_interface (I) (O) in
Circuit.create_exn ~name (create scope)
;;
let name_exn signal =
match Signal.names signal with
| [ hd ] -> hd
| _ -> assert false
;;
let circuit_data_inputs circuit =
List.filter (Circuit.inputs circuit) ~f:(fun input ->
not (String.equal (name_exn input) "clock"))
;;
let create_mega_circuit scope (circuits : Circuit.t list) =
let db = Scope.circuit_database scope in
let circuit_names =
List.map circuits ~f:(fun circuit -> Circuit_database.insert db circuit)
in
let clock = Signal.input "clock" 1 in
let data_inputs =
let i = ref (-1) in
List.map circuits ~f:(fun circuit ->
List.map (circuit_data_inputs circuit) ~f:(fun inp ->
Int.incr i;
Signal.input (sprintf "data_in_%d" !i) (Signal.width inp)))
in
let outputs =
let i = ref 0 in
List.map3_exn
circuits
circuit_names
data_inputs
~f:(fun circuit circuit_name data_inputs ->
let circuit_data_input_names =
List.map ~f:name_exn (circuit_data_inputs circuit)
in
let inputs =
let clock_input = "clock", clock in
let data_inputs =
List.map2_exn circuit_data_input_names data_inputs ~f:(fun a b -> a, b)
in
clock_input :: data_inputs
in
let outputs =
List.map (Circuit.outputs circuit) ~f:(fun s -> name_exn s, Signal.width s)
in
let output_names = List.map ~f:fst outputs in
let inst = Instantiation.create ~name:circuit_name ~inputs ~outputs () in
List.map output_names ~f:(fun name ->
Int.incr i;
Signal.output (sprintf "data_out_%d" !i) (Map.find_exn inst name)))
|> List.concat
in
Circuit.create_exn ~name:"top" outputs
;;
let command_for_single =
List.map Synth_targets.targets ~f:(fun component ->
let (module Component : Component_intf.S) = component in
let command =
Async.Command.async
~summary:(Printf.sprintf "Single-component synthesis for %s" Component.name)
[%map_open.Command
let synth_flags = Hardcaml_xilinx_reports.Command.Command_flags.flags
and params = Component.Params.flags in
fun () ->
Hardcaml_xilinx_reports.Command.run_circuit
~sort_by_name:true
~flags:synth_flags
(fun scope -> create_circuit scope (module Component) params)]
~behave_nicely_in_pipeline:false
in
let name = Component.name |> String.substr_replace_all ~pattern:"_" ~with_:"-" in
name, command)
|> Command.group ~summary:"Single component synthesis report"
;;
let command_for_all =
let circuit scope =
List.concat_map Synth_targets.targets ~f:(fun component ->
let (module Component : Component_intf.S) = component in
List.map Component.params ~f:(fun param ->
create_circuit scope (module Component) param))
|> create_mega_circuit scope
in
Hardcaml_xilinx_reports.Command.command_circuit ~sort_by_name:true circuit
;;
let command_old =
Command.group
~summary:"Old-style non generic synthesis targets"
[ "arbiters", Arbiters_old.command ]
;;
let command =
Command.group
~summary:"synthesis reports commander"
[ "all", command_for_all; "old", command_old; "single", command_for_single ]
;;
| |
bf70bac0b5133fe852c75e87068b03431c77209aa19bc14bbeaace0687f085ee | exercism/common-lisp | rail-fence-cipher.lisp | (defpackage :rail-fence-cipher
(:use :cl)
(:export :encode
:decode))
(in-package :rail-fence-cipher)
(defun encode (msg rails))
(defun decode (msg rails))
| null | https://raw.githubusercontent.com/exercism/common-lisp/57bb317e68ca75f41666ce3c62066a9c13e0314a/exercises/practice/rail-fence-cipher/rail-fence-cipher.lisp | lisp | (defpackage :rail-fence-cipher
(:use :cl)
(:export :encode
:decode))
(in-package :rail-fence-cipher)
(defun encode (msg rails))
(defun decode (msg rails))
| |
5c15f64dd59ce1c1f5831164d14b68adf5a62a3efc6d5d2c3ce54a4b1baf59cb | jkrukoff/llists | test_lfiles.erl | %%%-------------------------------------------------------------------
%%% @doc
%%% Tests for src/lfiles.erl
%%% @end
%%%-------------------------------------------------------------------
-module(test_lfiles).
-include_lib("eunit/include/eunit.hrl").
%%%===================================================================
%%% Tests
%%%===================================================================
read_test() ->
{ok, File} = file:open("test/data/alpha.txt", [read]),
?assertEqual(
["A", "\n", "B", "\n", "C", "\n"],
llists:to_list(
lfiles:read(File, 1)
)
).
get_chars_test() ->
{ok, File} = file:open("test/data/alpha.txt", [read]),
?assertEqual(
["A", "\n", "B", "\n", "C", "\n"],
llists:to_list(
lfiles:get_chars(File, undefined, 1)
)
).
read_line_test() ->
{ok, File} = file:open("test/data/alpha.txt", [read]),
?assertEqual(
["A\n", "B\n", "C\n"],
llists:to_list(
lfiles:read_line(File)
)
).
get_line_test() ->
{ok, File} = file:open("test/data/alpha.txt", [read]),
?assertEqual(
["A\n", "B\n", "C\n"],
llists:to_list(
lfiles:get_line(File, undefined)
)
).
write_test() ->
?assertEqual(
"12345",
with_temp_file(fun(File) ->
lfiles:write(File, llists:from_list(["1", "2", "3", "4", "5"]))
end)
).
put_chars_test() ->
?assertEqual(
"12345",
with_temp_file(fun(File) ->
lfiles:put_chars(File, llists:from_list(["1", "2", "3", "4", "5"]))
end)
).
%%%===================================================================
%%% Internal Functions
%%%===================================================================
with_temp_file(Test) ->
Suffix = "test-lfiles-" ++ integer_to_list(binary:decode_unsigned(rand:bytes(8)), 36),
TempPath = filename:basedir(user_cache, "llists"),
TempFilename = filename:join(TempPath, Suffix),
ok = filelib:ensure_dir(TempFilename),
{ok, File} = file:open(TempFilename, [read, write]),
try
ok = file:write(File, <<>>),
?assertEqual(ok, Test(File)),
read_temp_file(File)
of
TestResult -> TestResult
after
ok = file:close(File),
ok = file:delete(TempFilename)
end.
read_temp_file(File) ->
{ok, _} = file:position(File, bof),
read_temp_file(File, []).
read_temp_file(File, Acc) ->
case io:get_chars(File, undefined, 1024) of
eof ->
unicode:characters_to_list(lists:reverse(Acc));
{error, _Reason} = Error ->
throw(Error);
Data ->
read_temp_file(File, [Data | Acc])
end.
| null | https://raw.githubusercontent.com/jkrukoff/llists/ae447e28ea2bb3ab0245f11302189be6bee76462/test/test_lfiles.erl | erlang | -------------------------------------------------------------------
@doc
Tests for src/lfiles.erl
@end
-------------------------------------------------------------------
===================================================================
Tests
===================================================================
===================================================================
Internal Functions
=================================================================== | -module(test_lfiles).
-include_lib("eunit/include/eunit.hrl").
read_test() ->
{ok, File} = file:open("test/data/alpha.txt", [read]),
?assertEqual(
["A", "\n", "B", "\n", "C", "\n"],
llists:to_list(
lfiles:read(File, 1)
)
).
get_chars_test() ->
{ok, File} = file:open("test/data/alpha.txt", [read]),
?assertEqual(
["A", "\n", "B", "\n", "C", "\n"],
llists:to_list(
lfiles:get_chars(File, undefined, 1)
)
).
read_line_test() ->
{ok, File} = file:open("test/data/alpha.txt", [read]),
?assertEqual(
["A\n", "B\n", "C\n"],
llists:to_list(
lfiles:read_line(File)
)
).
get_line_test() ->
{ok, File} = file:open("test/data/alpha.txt", [read]),
?assertEqual(
["A\n", "B\n", "C\n"],
llists:to_list(
lfiles:get_line(File, undefined)
)
).
write_test() ->
?assertEqual(
"12345",
with_temp_file(fun(File) ->
lfiles:write(File, llists:from_list(["1", "2", "3", "4", "5"]))
end)
).
put_chars_test() ->
?assertEqual(
"12345",
with_temp_file(fun(File) ->
lfiles:put_chars(File, llists:from_list(["1", "2", "3", "4", "5"]))
end)
).
with_temp_file(Test) ->
Suffix = "test-lfiles-" ++ integer_to_list(binary:decode_unsigned(rand:bytes(8)), 36),
TempPath = filename:basedir(user_cache, "llists"),
TempFilename = filename:join(TempPath, Suffix),
ok = filelib:ensure_dir(TempFilename),
{ok, File} = file:open(TempFilename, [read, write]),
try
ok = file:write(File, <<>>),
?assertEqual(ok, Test(File)),
read_temp_file(File)
of
TestResult -> TestResult
after
ok = file:close(File),
ok = file:delete(TempFilename)
end.
read_temp_file(File) ->
{ok, _} = file:position(File, bof),
read_temp_file(File, []).
read_temp_file(File, Acc) ->
case io:get_chars(File, undefined, 1024) of
eof ->
unicode:characters_to_list(lists:reverse(Acc));
{error, _Reason} = Error ->
throw(Error);
Data ->
read_temp_file(File, [Data | Acc])
end.
|
6a6d8ae94722ca7ef8cc8169837a6744b86fb21117e2327c1e69bee50d052c97 | shuieryin/wechat_mud | register_test.erl | %%%-------------------------------------------------------------------
@author shuieryin
( C ) 2015 , Shuieryin
%%% @doc
%%%
%%% @end
Created : 29 . Nov 2015 8:09 PM
%%%-------------------------------------------------------------------
-module(register_test).
-author("shuieryin").
-import(wechat_mud_SUITE, [mod_input/2, mod_input/3]).
%% API
-export([
]).
-export([
test/1,
test_id/1
]).
-include_lib("wechat_mud_test.hrl").
-include_lib("wechat_mud/src/data_type/player_profile.hrl").
%%%===================================================================
%%% API
%%%===================================================================
test(_Config) ->
RawTestUid = elib:uuid(),
TestUid = atom_to_binary(RawTestUid, utf8),
TestId = test_id(TestUid),
FsmId = register_statem:register_server_name(RawTestUid),
First time - START
mod_input(TestUid, <<"afsdf">>),
mod_input(TestUid, <<"zh">>),
normal_reg_flow(TestUid, TestId),
mod_input(TestUid, <<"event">>, <<"unsubscribe">>),
First time - END
Second time - START
mod_input(TestUid, <<"afsdf">>),
mod_input(TestUid, <<"zh">>),
normal_reg_flow(TestUid, TestId),
mod_input(TestUid, <<"n">>),
Second time - END
MonitorRef = monitor(process, FsmId),
Third time - START
normal_reg_flow(TestUid, TestId),
register_statem:current_player_profile(RawTestUid),
mod_input(TestUid, <<>>),
mod_input(TestUid, <<"y">>),
Third time - END
receive
{'DOWN', MonitorRef, process, _, _} ->
true
end.
test_id(TestUid) ->
[TestId | _] = re:split(TestUid, "-", [{return, binary}]),
TestId.
%%%===================================================================
Internal functions
%%%===================================================================
normal_reg_flow(TestUid, TestId) ->
mod_input(TestUid, <<"@!!$@#$fa">>),
mod_input(TestUid, <<"ajk2l23j4k2l3jsasaedf">>),
LoggedInUidsSet = login_server:logged_in_player_uids(),
case ?ONE_OF(gb_sets:to_list(LoggedInUidsSet)) of
undefined ->
ok;
ExistingUid ->
ExistingPlayerId = player_statem:player_id(ExistingUid),
mod_input(TestUid, ExistingPlayerId)
end,
mod_input(TestUid, TestId),
mod_input(TestUid, <<"afsdf">>),
mod_input(TestUid, <<>>),
mod_input(TestUid, ?ONE_OF([<<"m">>, <<"f">>])),
mod_input(TestUid, <<"15">>),
mod_input(TestUid, <<"asdjk">>),
mod_input(TestUid, integer_to_binary(?ONE_OF(lists:seq(1, 12)))),
mod_input(TestUid, <<"nfajsld">>). | null | https://raw.githubusercontent.com/shuieryin/wechat_mud/b2a9251a9b208fee5cd8c4213759750b95c8b8aa/test/register_test.erl | erlang | -------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
API
===================================================================
API
===================================================================
===================================================================
=================================================================== | @author shuieryin
( C ) 2015 , Shuieryin
Created : 29 . Nov 2015 8:09 PM
-module(register_test).
-author("shuieryin").
-import(wechat_mud_SUITE, [mod_input/2, mod_input/3]).
-export([
]).
-export([
test/1,
test_id/1
]).
-include_lib("wechat_mud_test.hrl").
-include_lib("wechat_mud/src/data_type/player_profile.hrl").
test(_Config) ->
RawTestUid = elib:uuid(),
TestUid = atom_to_binary(RawTestUid, utf8),
TestId = test_id(TestUid),
FsmId = register_statem:register_server_name(RawTestUid),
First time - START
mod_input(TestUid, <<"afsdf">>),
mod_input(TestUid, <<"zh">>),
normal_reg_flow(TestUid, TestId),
mod_input(TestUid, <<"event">>, <<"unsubscribe">>),
First time - END
Second time - START
mod_input(TestUid, <<"afsdf">>),
mod_input(TestUid, <<"zh">>),
normal_reg_flow(TestUid, TestId),
mod_input(TestUid, <<"n">>),
Second time - END
MonitorRef = monitor(process, FsmId),
Third time - START
normal_reg_flow(TestUid, TestId),
register_statem:current_player_profile(RawTestUid),
mod_input(TestUid, <<>>),
mod_input(TestUid, <<"y">>),
Third time - END
receive
{'DOWN', MonitorRef, process, _, _} ->
true
end.
test_id(TestUid) ->
[TestId | _] = re:split(TestUid, "-", [{return, binary}]),
TestId.
Internal functions
normal_reg_flow(TestUid, TestId) ->
mod_input(TestUid, <<"@!!$@#$fa">>),
mod_input(TestUid, <<"ajk2l23j4k2l3jsasaedf">>),
LoggedInUidsSet = login_server:logged_in_player_uids(),
case ?ONE_OF(gb_sets:to_list(LoggedInUidsSet)) of
undefined ->
ok;
ExistingUid ->
ExistingPlayerId = player_statem:player_id(ExistingUid),
mod_input(TestUid, ExistingPlayerId)
end,
mod_input(TestUid, TestId),
mod_input(TestUid, <<"afsdf">>),
mod_input(TestUid, <<>>),
mod_input(TestUid, ?ONE_OF([<<"m">>, <<"f">>])),
mod_input(TestUid, <<"15">>),
mod_input(TestUid, <<"asdjk">>),
mod_input(TestUid, integer_to_binary(?ONE_OF(lists:seq(1, 12)))),
mod_input(TestUid, <<"nfajsld">>). |
4df1da2b9174c1a37d9e1f5fcef0345a64a5a7a40355cdbd74b84f49fff77f37 | scymtym/clim.flamegraph | presentations.lisp | ;;;; presentations.lisp --- Presentation types provided by the view.timeline module.
;;;;
Copyright ( C ) 2019 , 2020 Jan Moringen
;;;;
Author : < >
(cl:in-package #:clim.flamegraph.view.timeline)
;;; `thread' presentation type
;;;
;;; Represents a thread for which samples have been collected.
(eval-when (:compile-toplevel :load-toplevel :execute)
(clim:define-presentation-type thread (&optional (selected? t))
:inherit-from '(t)))
#+later (flet ((call-with-thread-display (thunk stream thread selected?
&key
(length-limit 20))
(let* ((maybe-name (name thread))
(name (or maybe-name "unnamed"))
(text (if (< (length name) length-limit)
name
(concatenate
'string (subseq name 0 length-limit) "…"))))
(clim:with-drawing-options (stream :ink (if selected?
clim:+foreground-ink+
clim:+light-gray+)
:text-face (if maybe-name
:bold
'(:bold :italic)))
(funcall thunk stream text)))))
(clim:define-presentation-method clim:present ((object thread)
(type thread)
(stream t)
(view t)
&key)
(call-with-thread-display
(lambda (stream text)
(write-string text stream))
stream object selected?))
TODO too similar to previous
(type thread)
(stream t)
(view timeline-view)
&key)
(call-with-thread-display
(lambda (stream text)
(clim:draw-text* stream text 0 .5 :align-y :center))
stream object selected?)))
;;; `trace' presentation type
;;;
;;; Represents a "call-stack snapshot" collected in a single thread.
(clim:define-presentation-type trace ()
:inherit-from '(t))
(clim:define-presentation-method clim:present ((object t)
(type trace)
(stream t)
(view clim:textual-view)
&key)
(princ "<trace>" stream))
model::standard - trace
)
(type trace)
(stream t)
(view t)
&key)
(let ((start (- (model:time object) 0 ; *start-time*
))
(end (- (+ (model:time object) .001) 0 ; *start-time*
)))
(multiple-value-bind (dx dy) (clim:transform-distance
(clim:medium-transformation stream) 3 3)
(clim:draw-ellipse* stream start end 10 dx 0 0 dy))))
(clim:define-presentation-type traces ()
:inherit-from '(t))
(clim:define-presentation-method clim:present ((object t)
(type traces)
(stream t)
(view clim:textual-view)
&key)
(princ "<traces>" stream))
(clim:define-presentation-method clim:present ((object t)
(type traces)
(stream clim:extended-output-stream)
(view t)
&key)
(multiple-value-bind (dx dy) (clim:transform-distance
(clim:medium-transformation stream) .01 .01)
(let ((traces object)
(dt 5))
(if (< dx 3)
TODO
:for start :from (if (first head) (model:time (first head)) 0) :by dt
:for end = (+ start dt)
:for traces = (loop :for trace = (first head)
:for time = (when trace (model:time trace))
:while (and time (<= start time end))
:do (pop head)
:collect trace)
:while head
:do ; (maxf time-max end)
(clim:with-output-as-presentation (stream (first traces) 'trace)
(when traces
(clim:draw-rectangle* stream (- start (if (boundp '*start-time*) *start-time* start)) (- 20 #+later lane-height (/ (length traces) 20))
(- end (if (boundp '*start-time*) *start-time* start)) 20 #+later lane-height
:ink clim:+light-blue+))))
(loop :for i :from 0
:for trace :in traces
:do (let ((time (- (model:time trace) *start-time*)))
TODO hack
(clim:with-output-as-presentation (stream trace 'trace)
(clim:draw-ellipse* stream time (+ 4 (mod (* 4 i) 12)) .01 0 0 .01)))))
#+no (loop :for (time . trace) :in traces
:with limit = (truncate (- lane-height 8) 4)
:for i :from 0
:do (maxf time-max time)
(clim:with-output-as-presentation (pane trace 'trace)
(let ((x (* time-scale time)))
(clim:draw-circle* pane x (+ 4 (* 4 (mod i limit))) 3))))))))
;;; Event
(clim:define-presentation-type event ()
:inherit-from '(t))
(defun draw-event-info (event stream)
(clim:with-drawing-options (stream :text-size :smaller)
(princ (model:name event) stream)
(terpri stream)
(clim:formatting-table (stream)
(loop :for (name value) :on (model::properties event) :by #'cddr
:do (clim:formatting-row (stream)
(clim:formatting-cell (stream)
(format stream "~(~A~)" name))
(clim:formatting-cell (stream :align-x :right)
(format stream "~:D" value)))))))
(clim:define-presentation-method clim:highlight-presentation
((type event)
(record t)
(stream clim:extended-output-stream)
(state t))
(clim.flamegraph.view::call-as-highlighting
(lambda (type record stream state)
(declare (ignore type state))
(let ((event (clim:presentation-object record)))
(draw-event-info event stream)))
type record stream state))
(flet ((draw-info (record event stream)
(clim:with-bounding-rectangle* (x1 y1 x2 y2) record
(clim:surrounding-output-with-border (stream :shape :drop-shadow
:background clim:+background-ink+)
(clim:with-end-of-line-action (stream :allow)
( clim : draw - design stream )
(setf (clim:stream-cursor-position stream) (values x1 y1))
(clime:with-temporary-margins (stream :left `(:absolute ,x1) :top `(:absolute ,y1))
(clim:with-drawing-options (stream :text-size :smaller)
(princ (model:name event) stream)
(terpri stream)
(clim:formatting-table (stream)
(loop :for (name value) :on (model::properties event) :by #'cddr
:do (clim:formatting-row (stream)
(clim:formatting-cell (stream)
(format stream "~(~A~)" name))
(clim:formatting-cell (stream :align-x :right)
(format stream "~:D" value))))))))))))
(clim:define-presentation-method clim:highlight-presentation
((type event)
(record t)
(stream clim:extended-output-stream)
(state (eql :highlight)))
(call-next-method)
#+no (clim:with-output-recording-options (stream :draw t :record nil)
(draw-info record (clim:presentation-object record) stream)))
(clim:define-presentation-method clim:highlight-presentation
((type event)
(record t)
(stream clim:extended-output-stream)
(state (eql :unhighlight)))
(call-next-method)
#+no (let ((record (clim:with-output-recording-options (stream :draw nil :record nil)
(clim:with-output-to-output-record (stream)
(draw-info record (clim:presentation-object record) stream)))))
(clim:repaint-sheet stream record))))
| null | https://raw.githubusercontent.com/scymtym/clim.flamegraph/03b5e4f08b53af86a98afa975a8e7a29d0ddd3a7/src/view/timeline/presentations.lisp | lisp | presentations.lisp --- Presentation types provided by the view.timeline module.
`thread' presentation type
Represents a thread for which samples have been collected.
`trace' presentation type
Represents a "call-stack snapshot" collected in a single thread.
*start-time*
*start-time*
(maxf time-max end)
Event | Copyright ( C ) 2019 , 2020 Jan Moringen
Author : < >
(cl:in-package #:clim.flamegraph.view.timeline)
(eval-when (:compile-toplevel :load-toplevel :execute)
(clim:define-presentation-type thread (&optional (selected? t))
:inherit-from '(t)))
#+later (flet ((call-with-thread-display (thunk stream thread selected?
&key
(length-limit 20))
(let* ((maybe-name (name thread))
(name (or maybe-name "unnamed"))
(text (if (< (length name) length-limit)
name
(concatenate
'string (subseq name 0 length-limit) "…"))))
(clim:with-drawing-options (stream :ink (if selected?
clim:+foreground-ink+
clim:+light-gray+)
:text-face (if maybe-name
:bold
'(:bold :italic)))
(funcall thunk stream text)))))
(clim:define-presentation-method clim:present ((object thread)
(type thread)
(stream t)
(view t)
&key)
(call-with-thread-display
(lambda (stream text)
(write-string text stream))
stream object selected?))
TODO too similar to previous
(type thread)
(stream t)
(view timeline-view)
&key)
(call-with-thread-display
(lambda (stream text)
(clim:draw-text* stream text 0 .5 :align-y :center))
stream object selected?)))
(clim:define-presentation-type trace ()
:inherit-from '(t))
(clim:define-presentation-method clim:present ((object t)
(type trace)
(stream t)
(view clim:textual-view)
&key)
(princ "<trace>" stream))
model::standard - trace
)
(type trace)
(stream t)
(view t)
&key)
))
)))
(multiple-value-bind (dx dy) (clim:transform-distance
(clim:medium-transformation stream) 3 3)
(clim:draw-ellipse* stream start end 10 dx 0 0 dy))))
(clim:define-presentation-type traces ()
:inherit-from '(t))
(clim:define-presentation-method clim:present ((object t)
(type traces)
(stream t)
(view clim:textual-view)
&key)
(princ "<traces>" stream))
(clim:define-presentation-method clim:present ((object t)
(type traces)
(stream clim:extended-output-stream)
(view t)
&key)
(multiple-value-bind (dx dy) (clim:transform-distance
(clim:medium-transformation stream) .01 .01)
(let ((traces object)
(dt 5))
(if (< dx 3)
TODO
:for start :from (if (first head) (model:time (first head)) 0) :by dt
:for end = (+ start dt)
:for traces = (loop :for trace = (first head)
:for time = (when trace (model:time trace))
:while (and time (<= start time end))
:do (pop head)
:collect trace)
:while head
(clim:with-output-as-presentation (stream (first traces) 'trace)
(when traces
(clim:draw-rectangle* stream (- start (if (boundp '*start-time*) *start-time* start)) (- 20 #+later lane-height (/ (length traces) 20))
(- end (if (boundp '*start-time*) *start-time* start)) 20 #+later lane-height
:ink clim:+light-blue+))))
(loop :for i :from 0
:for trace :in traces
:do (let ((time (- (model:time trace) *start-time*)))
TODO hack
(clim:with-output-as-presentation (stream trace 'trace)
(clim:draw-ellipse* stream time (+ 4 (mod (* 4 i) 12)) .01 0 0 .01)))))
#+no (loop :for (time . trace) :in traces
:with limit = (truncate (- lane-height 8) 4)
:for i :from 0
:do (maxf time-max time)
(clim:with-output-as-presentation (pane trace 'trace)
(let ((x (* time-scale time)))
(clim:draw-circle* pane x (+ 4 (* 4 (mod i limit))) 3))))))))
(clim:define-presentation-type event ()
:inherit-from '(t))
(defun draw-event-info (event stream)
(clim:with-drawing-options (stream :text-size :smaller)
(princ (model:name event) stream)
(terpri stream)
(clim:formatting-table (stream)
(loop :for (name value) :on (model::properties event) :by #'cddr
:do (clim:formatting-row (stream)
(clim:formatting-cell (stream)
(format stream "~(~A~)" name))
(clim:formatting-cell (stream :align-x :right)
(format stream "~:D" value)))))))
(clim:define-presentation-method clim:highlight-presentation
((type event)
(record t)
(stream clim:extended-output-stream)
(state t))
(clim.flamegraph.view::call-as-highlighting
(lambda (type record stream state)
(declare (ignore type state))
(let ((event (clim:presentation-object record)))
(draw-event-info event stream)))
type record stream state))
(flet ((draw-info (record event stream)
(clim:with-bounding-rectangle* (x1 y1 x2 y2) record
(clim:surrounding-output-with-border (stream :shape :drop-shadow
:background clim:+background-ink+)
(clim:with-end-of-line-action (stream :allow)
( clim : draw - design stream )
(setf (clim:stream-cursor-position stream) (values x1 y1))
(clime:with-temporary-margins (stream :left `(:absolute ,x1) :top `(:absolute ,y1))
(clim:with-drawing-options (stream :text-size :smaller)
(princ (model:name event) stream)
(terpri stream)
(clim:formatting-table (stream)
(loop :for (name value) :on (model::properties event) :by #'cddr
:do (clim:formatting-row (stream)
(clim:formatting-cell (stream)
(format stream "~(~A~)" name))
(clim:formatting-cell (stream :align-x :right)
(format stream "~:D" value))))))))))))
(clim:define-presentation-method clim:highlight-presentation
((type event)
(record t)
(stream clim:extended-output-stream)
(state (eql :highlight)))
(call-next-method)
#+no (clim:with-output-recording-options (stream :draw t :record nil)
(draw-info record (clim:presentation-object record) stream)))
(clim:define-presentation-method clim:highlight-presentation
((type event)
(record t)
(stream clim:extended-output-stream)
(state (eql :unhighlight)))
(call-next-method)
#+no (let ((record (clim:with-output-recording-options (stream :draw nil :record nil)
(clim:with-output-to-output-record (stream)
(draw-info record (clim:presentation-object record) stream)))))
(clim:repaint-sheet stream record))))
|
4cd70488243ee5a7f45f8ff6d1cf3b4e5f1804bc1d13a7c8279007203308a976 | SamB/coq | genarg.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
$ Id$
open Pp
open Util
open Names
open Nameops
open Nametab
open Rawterm
open Topconstr
open Term
open Evd
type argument_type =
(* Basic types *)
| BoolArgType
| IntArgType
| IntOrVarArgType
| StringArgType
| PreIdentArgType
| IntroPatternArgType
| IdentArgType
| VarArgType
| RefArgType
(* Specific types *)
| SortArgType
| ConstrArgType
| ConstrMayEvalArgType
| QuantHypArgType
| OpenConstrArgType of bool
| ConstrWithBindingsArgType
| BindingsArgType
| RedExprArgType
| List0ArgType of argument_type
| List1ArgType of argument_type
| OptArgType of argument_type
| PairArgType of argument_type * argument_type
| ExtraArgType of string
type 'a and_short_name = 'a * identifier located option
type 'a or_by_notation = AN of 'a | ByNotation of loc * string
type rawconstr_and_expr = rawconstr * constr_expr option
type open_constr_expr = unit * constr_expr
type open_rawconstr = unit * rawconstr_and_expr
type 'a with_ebindings = 'a * open_constr bindings
(* Dynamics but tagged by a type expression *)
type 'a generic_argument = argument_type * Obj.t
let dyntab = ref ([] : string list)
type rlevel = constr_expr
type glevel = rawconstr_and_expr
type tlevel = open_constr
type ('a,'b) abstract_argument_type = argument_type
let create_arg s =
if List.mem s !dyntab then
anomaly ("Genarg.create: already declared generic argument " ^ s);
dyntab := s :: !dyntab;
let t = ExtraArgType s in
(t,t,t)
let exists_argtype s = List.mem s !dyntab
type intro_pattern_expr =
| IntroOrAndPattern of case_intro_pattern_expr
| IntroWildcard
| IntroIdentifier of identifier
| IntroAnonymous
| IntroRewrite of bool
| IntroFresh of identifier
and case_intro_pattern_expr = intro_pattern_expr list list
let rec pr_intro_pattern = function
| IntroOrAndPattern pll -> pr_case_intro_pattern pll
| IntroWildcard -> str "_"
| IntroIdentifier id -> pr_id id
| IntroAnonymous -> str "?"
| IntroRewrite true -> str "->"
| IntroRewrite false -> str "<-"
| IntroFresh id -> str "?" ++ pr_id id
and pr_case_intro_pattern = function
| [pl] ->
str "(" ++ hv 0 (prlist_with_sep pr_coma pr_intro_pattern pl) ++ str ")"
| pll ->
str "[" ++
hv 0 (prlist_with_sep pr_bar (prlist_with_sep spc pr_intro_pattern) pll)
++ str "]"
let rawwit_bool = BoolArgType
let globwit_bool = BoolArgType
let wit_bool = BoolArgType
let rawwit_int = IntArgType
let globwit_int = IntArgType
let wit_int = IntArgType
let rawwit_int_or_var = IntOrVarArgType
let globwit_int_or_var = IntOrVarArgType
let wit_int_or_var = IntOrVarArgType
let rawwit_string = StringArgType
let globwit_string = StringArgType
let wit_string = StringArgType
let rawwit_pre_ident = PreIdentArgType
let globwit_pre_ident = PreIdentArgType
let wit_pre_ident = PreIdentArgType
let rawwit_intro_pattern = IntroPatternArgType
let globwit_intro_pattern = IntroPatternArgType
let wit_intro_pattern = IntroPatternArgType
let rawwit_ident = IdentArgType
let globwit_ident = IdentArgType
let wit_ident = IdentArgType
let rawwit_var = VarArgType
let globwit_var = VarArgType
let wit_var = VarArgType
let rawwit_ref = RefArgType
let globwit_ref = RefArgType
let wit_ref = RefArgType
let rawwit_quant_hyp = QuantHypArgType
let globwit_quant_hyp = QuantHypArgType
let wit_quant_hyp = QuantHypArgType
let rawwit_sort = SortArgType
let globwit_sort = SortArgType
let wit_sort = SortArgType
let rawwit_constr = ConstrArgType
let globwit_constr = ConstrArgType
let wit_constr = ConstrArgType
let rawwit_constr_may_eval = ConstrMayEvalArgType
let globwit_constr_may_eval = ConstrMayEvalArgType
let wit_constr_may_eval = ConstrMayEvalArgType
let rawwit_open_constr_gen b = OpenConstrArgType b
let globwit_open_constr_gen b = OpenConstrArgType b
let wit_open_constr_gen b = OpenConstrArgType b
let rawwit_open_constr = rawwit_open_constr_gen false
let globwit_open_constr = globwit_open_constr_gen false
let wit_open_constr = wit_open_constr_gen false
let rawwit_casted_open_constr = rawwit_open_constr_gen true
let globwit_casted_open_constr = globwit_open_constr_gen true
let wit_casted_open_constr = wit_open_constr_gen true
let rawwit_constr_with_bindings = ConstrWithBindingsArgType
let globwit_constr_with_bindings = ConstrWithBindingsArgType
let wit_constr_with_bindings = ConstrWithBindingsArgType
let rawwit_bindings = BindingsArgType
let globwit_bindings = BindingsArgType
let wit_bindings = BindingsArgType
let rawwit_red_expr = RedExprArgType
let globwit_red_expr = RedExprArgType
let wit_red_expr = RedExprArgType
let wit_list0 t = List0ArgType t
let wit_list1 t = List1ArgType t
let wit_opt t = OptArgType t
let wit_pair t1 t2 = PairArgType (t1,t2)
let in_gen t o = (t,Obj.repr o)
let out_gen t (t',o) = if t = t' then Obj.magic o else failwith "out_gen"
let genarg_tag (s,_) = s
let fold_list0 f = function
| (List0ArgType t, l) ->
List.fold_right (fun x -> f (in_gen t x)) (Obj.magic l)
| _ -> failwith "Genarg: not a list0"
let fold_list1 f = function
| (List1ArgType t, l) ->
List.fold_right (fun x -> f (in_gen t x)) (Obj.magic l)
| _ -> failwith "Genarg: not a list1"
let fold_opt f a = function
| (OptArgType t, l) ->
(match Obj.magic l with
| None -> a
| Some x -> f (in_gen t x))
| _ -> failwith "Genarg: not a opt"
let fold_pair f = function
| (PairArgType (t1,t2), l) ->
let (x1,x2) = Obj.magic l in
f (in_gen t1 x1) (in_gen t2 x2)
| _ -> failwith "Genarg: not a pair"
let app_list0 f = function
| (List0ArgType t as u, l) ->
let o = Obj.magic l in
(u, Obj.repr (List.map (fun x -> out_gen t (f (in_gen t x))) o))
| _ -> failwith "Genarg: not a list0"
let app_list1 f = function
| (List1ArgType t as u, l) ->
let o = Obj.magic l in
(u, Obj.repr (List.map (fun x -> out_gen t (f (in_gen t x))) o))
| _ -> failwith "Genarg: not a list1"
let app_opt f = function
| (OptArgType t as u, l) ->
let o = Obj.magic l in
(u, Obj.repr (Option.map (fun x -> out_gen t (f (in_gen t x))) o))
| _ -> failwith "Genarg: not an opt"
let app_pair f1 f2 = function
| (PairArgType (t1,t2) as u, l) ->
let (o1,o2) = Obj.magic l in
let o1 = out_gen t1 (f1 (in_gen t1 o1)) in
let o2 = out_gen t2 (f2 (in_gen t2 o2)) in
(u, Obj.repr (o1,o2))
| _ -> failwith "Genarg: not a pair"
let unquote x = x
type an_arg_of_this_type = Obj.t
let in_generic t x = (t, Obj.repr x)
| null | https://raw.githubusercontent.com/SamB/coq/8f84aba9ae83a4dc43ea6e804227ae8cae8086b1/interp/genarg.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
Basic types
Specific types
Dynamics but tagged by a type expression | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
$ Id$
open Pp
open Util
open Names
open Nameops
open Nametab
open Rawterm
open Topconstr
open Term
open Evd
type argument_type =
| BoolArgType
| IntArgType
| IntOrVarArgType
| StringArgType
| PreIdentArgType
| IntroPatternArgType
| IdentArgType
| VarArgType
| RefArgType
| SortArgType
| ConstrArgType
| ConstrMayEvalArgType
| QuantHypArgType
| OpenConstrArgType of bool
| ConstrWithBindingsArgType
| BindingsArgType
| RedExprArgType
| List0ArgType of argument_type
| List1ArgType of argument_type
| OptArgType of argument_type
| PairArgType of argument_type * argument_type
| ExtraArgType of string
type 'a and_short_name = 'a * identifier located option
type 'a or_by_notation = AN of 'a | ByNotation of loc * string
type rawconstr_and_expr = rawconstr * constr_expr option
type open_constr_expr = unit * constr_expr
type open_rawconstr = unit * rawconstr_and_expr
type 'a with_ebindings = 'a * open_constr bindings
type 'a generic_argument = argument_type * Obj.t
let dyntab = ref ([] : string list)
type rlevel = constr_expr
type glevel = rawconstr_and_expr
type tlevel = open_constr
type ('a,'b) abstract_argument_type = argument_type
let create_arg s =
if List.mem s !dyntab then
anomaly ("Genarg.create: already declared generic argument " ^ s);
dyntab := s :: !dyntab;
let t = ExtraArgType s in
(t,t,t)
let exists_argtype s = List.mem s !dyntab
type intro_pattern_expr =
| IntroOrAndPattern of case_intro_pattern_expr
| IntroWildcard
| IntroIdentifier of identifier
| IntroAnonymous
| IntroRewrite of bool
| IntroFresh of identifier
and case_intro_pattern_expr = intro_pattern_expr list list
let rec pr_intro_pattern = function
| IntroOrAndPattern pll -> pr_case_intro_pattern pll
| IntroWildcard -> str "_"
| IntroIdentifier id -> pr_id id
| IntroAnonymous -> str "?"
| IntroRewrite true -> str "->"
| IntroRewrite false -> str "<-"
| IntroFresh id -> str "?" ++ pr_id id
and pr_case_intro_pattern = function
| [pl] ->
str "(" ++ hv 0 (prlist_with_sep pr_coma pr_intro_pattern pl) ++ str ")"
| pll ->
str "[" ++
hv 0 (prlist_with_sep pr_bar (prlist_with_sep spc pr_intro_pattern) pll)
++ str "]"
let rawwit_bool = BoolArgType
let globwit_bool = BoolArgType
let wit_bool = BoolArgType
let rawwit_int = IntArgType
let globwit_int = IntArgType
let wit_int = IntArgType
let rawwit_int_or_var = IntOrVarArgType
let globwit_int_or_var = IntOrVarArgType
let wit_int_or_var = IntOrVarArgType
let rawwit_string = StringArgType
let globwit_string = StringArgType
let wit_string = StringArgType
let rawwit_pre_ident = PreIdentArgType
let globwit_pre_ident = PreIdentArgType
let wit_pre_ident = PreIdentArgType
let rawwit_intro_pattern = IntroPatternArgType
let globwit_intro_pattern = IntroPatternArgType
let wit_intro_pattern = IntroPatternArgType
let rawwit_ident = IdentArgType
let globwit_ident = IdentArgType
let wit_ident = IdentArgType
let rawwit_var = VarArgType
let globwit_var = VarArgType
let wit_var = VarArgType
let rawwit_ref = RefArgType
let globwit_ref = RefArgType
let wit_ref = RefArgType
let rawwit_quant_hyp = QuantHypArgType
let globwit_quant_hyp = QuantHypArgType
let wit_quant_hyp = QuantHypArgType
let rawwit_sort = SortArgType
let globwit_sort = SortArgType
let wit_sort = SortArgType
let rawwit_constr = ConstrArgType
let globwit_constr = ConstrArgType
let wit_constr = ConstrArgType
let rawwit_constr_may_eval = ConstrMayEvalArgType
let globwit_constr_may_eval = ConstrMayEvalArgType
let wit_constr_may_eval = ConstrMayEvalArgType
let rawwit_open_constr_gen b = OpenConstrArgType b
let globwit_open_constr_gen b = OpenConstrArgType b
let wit_open_constr_gen b = OpenConstrArgType b
let rawwit_open_constr = rawwit_open_constr_gen false
let globwit_open_constr = globwit_open_constr_gen false
let wit_open_constr = wit_open_constr_gen false
let rawwit_casted_open_constr = rawwit_open_constr_gen true
let globwit_casted_open_constr = globwit_open_constr_gen true
let wit_casted_open_constr = wit_open_constr_gen true
let rawwit_constr_with_bindings = ConstrWithBindingsArgType
let globwit_constr_with_bindings = ConstrWithBindingsArgType
let wit_constr_with_bindings = ConstrWithBindingsArgType
let rawwit_bindings = BindingsArgType
let globwit_bindings = BindingsArgType
let wit_bindings = BindingsArgType
let rawwit_red_expr = RedExprArgType
let globwit_red_expr = RedExprArgType
let wit_red_expr = RedExprArgType
let wit_list0 t = List0ArgType t
let wit_list1 t = List1ArgType t
let wit_opt t = OptArgType t
let wit_pair t1 t2 = PairArgType (t1,t2)
let in_gen t o = (t,Obj.repr o)
let out_gen t (t',o) = if t = t' then Obj.magic o else failwith "out_gen"
let genarg_tag (s,_) = s
let fold_list0 f = function
| (List0ArgType t, l) ->
List.fold_right (fun x -> f (in_gen t x)) (Obj.magic l)
| _ -> failwith "Genarg: not a list0"
let fold_list1 f = function
| (List1ArgType t, l) ->
List.fold_right (fun x -> f (in_gen t x)) (Obj.magic l)
| _ -> failwith "Genarg: not a list1"
let fold_opt f a = function
| (OptArgType t, l) ->
(match Obj.magic l with
| None -> a
| Some x -> f (in_gen t x))
| _ -> failwith "Genarg: not a opt"
let fold_pair f = function
| (PairArgType (t1,t2), l) ->
let (x1,x2) = Obj.magic l in
f (in_gen t1 x1) (in_gen t2 x2)
| _ -> failwith "Genarg: not a pair"
let app_list0 f = function
| (List0ArgType t as u, l) ->
let o = Obj.magic l in
(u, Obj.repr (List.map (fun x -> out_gen t (f (in_gen t x))) o))
| _ -> failwith "Genarg: not a list0"
let app_list1 f = function
| (List1ArgType t as u, l) ->
let o = Obj.magic l in
(u, Obj.repr (List.map (fun x -> out_gen t (f (in_gen t x))) o))
| _ -> failwith "Genarg: not a list1"
let app_opt f = function
| (OptArgType t as u, l) ->
let o = Obj.magic l in
(u, Obj.repr (Option.map (fun x -> out_gen t (f (in_gen t x))) o))
| _ -> failwith "Genarg: not an opt"
let app_pair f1 f2 = function
| (PairArgType (t1,t2) as u, l) ->
let (o1,o2) = Obj.magic l in
let o1 = out_gen t1 (f1 (in_gen t1 o1)) in
let o2 = out_gen t2 (f2 (in_gen t2 o2)) in
(u, Obj.repr (o1,o2))
| _ -> failwith "Genarg: not a pair"
let unquote x = x
type an_arg_of_this_type = Obj.t
let in_generic t x = (t, Obj.repr x)
|
dd8e26c37297f49e90b4ec5dd9e946263fad834e5b1d307153a244b5a11b606e | roburio/ocaml-openpgp | literal_data_packet.mli | * Literal Data Packet ( Tag 11 )
open Rresult
type data_format =
| Literal_binary
| Literal_text_with_crlf
(** - Text data is stored with <CR><LF> text endings (i.e., network-
normal line endings). These should be converted to native line
endings by the receiving software.*)
val pp_data_format : Format.formatter -> data_format -> unit
type streaming
type in_memory
type 'kind parser
type final_state = private { format : data_format (** text or binary*);
filename : string (* peer's suggested filename**);
time : string (** The unspecified time field.*); }
type 'kind t = private
| Streaming_t : final_state -> streaming t
(** doesn't store the actual packet data: *)
| In_memory_t : final_state * string list -> in_memory t
(** accumulates data as a list of strings inside [t]: *)
val pp : Format.formatter -> _ t -> unit
(** [pp fmt t] is [t] pretty-printed on [fmt].*)
val in_memory_parser : total_len:int64 -> (in_memory parser, [> R.msg] )result
(** [in_memory_parser ~total_len] is a parser that will read up to [total_len]
bytes. It can be used with [parse_streaming].
The parser stores the accumulated packet in its state, which is useful for
small files when you don't want to bother with buffer management.*)
val streaming_parser : total_len:int64 -> (streaming parser, [> R.msg] )result
* [ ] is a parser that will read up to [ total_len ]
bytes . It can be used with [ parse_streaming ] .
The parser will cause [ parse_streaming ] to return each block of packet body
directly , which is useful for reading large files that do not fit in memory .
bytes. It can be used with [parse_streaming].
The parser will cause [parse_streaming] to return each block of packet body
directly, which is useful for reading large files that do not fit in memory.
*)
val parse_streaming : 'kind parser -> ([> R.msg ] as 'err) Cs.R.rt ->
('kind parser * string option, 'err)result
* [ parse_streaming parser src ] is a tuple of
[ ( next_parser_state * packet_body ) ] , reading from the [ src ] .
Different [ src ] can be used across repeated calls to [ parse_streaming ] ,
enabling you to page out the memory occupied by a [ src ] once it has been
depleted .
[(next_parser_state * packet_body)], reading from the [src].
Different [src] can be used across repeated calls to [parse_streaming],
enabling you to page out the memory occupied by a [src] once it has been
depleted.
*)
val parse : ?offset:int -> Cs.t -> (in_memory t, [> R.msg ]) result
(** [parse ?offset src] is an [in_memory t] starting at optional
[?offset] (default: 0) of [src].*)
val serialize : 'kind t -> Cs.t
(** [serialize t] is the serialized header for the Literal Data Packet [t].
If [t] is an [in_memory t], the stored body will also be serialized.
If [t] is a [streaming t], you must use [serialize] to obtain the header
yourself, and fill in the body yourself.
*)
val create_binary : string -> string list -> in_memory t
| null | https://raw.githubusercontent.com/roburio/ocaml-openpgp/55459ad98a69f80789c79219c6d3be19ef6ef521/lib/literal_data_packet.mli | ocaml | * - Text data is stored with <CR><LF> text endings (i.e., network-
normal line endings). These should be converted to native line
endings by the receiving software.
* text or binary
peer's suggested filename*
* The unspecified time field.
* doesn't store the actual packet data:
* accumulates data as a list of strings inside [t]:
* [pp fmt t] is [t] pretty-printed on [fmt].
* [in_memory_parser ~total_len] is a parser that will read up to [total_len]
bytes. It can be used with [parse_streaming].
The parser stores the accumulated packet in its state, which is useful for
small files when you don't want to bother with buffer management.
* [parse ?offset src] is an [in_memory t] starting at optional
[?offset] (default: 0) of [src].
* [serialize t] is the serialized header for the Literal Data Packet [t].
If [t] is an [in_memory t], the stored body will also be serialized.
If [t] is a [streaming t], you must use [serialize] to obtain the header
yourself, and fill in the body yourself.
| * Literal Data Packet ( Tag 11 )
open Rresult
type data_format =
| Literal_binary
| Literal_text_with_crlf
val pp_data_format : Format.formatter -> data_format -> unit
type streaming
type in_memory
type 'kind parser
type 'kind t = private
| Streaming_t : final_state -> streaming t
| In_memory_t : final_state * string list -> in_memory t
val pp : Format.formatter -> _ t -> unit
val in_memory_parser : total_len:int64 -> (in_memory parser, [> R.msg] )result
val streaming_parser : total_len:int64 -> (streaming parser, [> R.msg] )result
* [ ] is a parser that will read up to [ total_len ]
bytes . It can be used with [ parse_streaming ] .
The parser will cause [ parse_streaming ] to return each block of packet body
directly , which is useful for reading large files that do not fit in memory .
bytes. It can be used with [parse_streaming].
The parser will cause [parse_streaming] to return each block of packet body
directly, which is useful for reading large files that do not fit in memory.
*)
val parse_streaming : 'kind parser -> ([> R.msg ] as 'err) Cs.R.rt ->
('kind parser * string option, 'err)result
* [ parse_streaming parser src ] is a tuple of
[ ( next_parser_state * packet_body ) ] , reading from the [ src ] .
Different [ src ] can be used across repeated calls to [ parse_streaming ] ,
enabling you to page out the memory occupied by a [ src ] once it has been
depleted .
[(next_parser_state * packet_body)], reading from the [src].
Different [src] can be used across repeated calls to [parse_streaming],
enabling you to page out the memory occupied by a [src] once it has been
depleted.
*)
val parse : ?offset:int -> Cs.t -> (in_memory t, [> R.msg ]) result
val serialize : 'kind t -> Cs.t
val create_binary : string -> string list -> in_memory t
|
73e0b16db49bbe248440ed5f3aa39f0e38bb6784a64e264cd92f35f4e145a44d | Apress/common-lisp-recipes | deliver.lisp | (load (compile-file "code.lisp"))
(lw:deliver nil "my_lib" 0 :dll-exports '("toLispTime"))
| null | https://raw.githubusercontent.com/Apress/common-lisp-recipes/211a8b6eabc48ac906010e8c5a185f03504b3867/code/chapter-22/deliver.lisp | lisp | (load (compile-file "code.lisp"))
(lw:deliver nil "my_lib" 0 :dll-exports '("toLispTime"))
| |
d012275517cfd56ab1e5fa360536a4db2fb824d7dbfdde79837baf237bccf2f0 | IBM-Watson/kale | main.clj | ;;
( C ) Copyright IBM Corp. 2016 All Rights Reserved .
;;
(ns kale.main
(:require [kale.aliases :refer [commands] :as aliases]
[kale.getter :refer [user-selection]]
[kale.common :refer [fail try-function get-command-msg
set-trace set-language]]
[kale.assemble]
[kale.dry-run]
[kale.create]
[kale.delete]
[kale.persistence]
[kale.get-command]
[kale.help]
[kale.list]
[kale.login]
[kale.refresh]
[kale.search]
[kale.select])
(:gen-class))
(defn get-msg
"Return the corresponding main message"
[msg-key & args]
(apply get-command-msg :main-messages msg-key args))
(defn isFlag? [x] (-> (re-find #"^-" x) nil? not))
(def global-options {:trace aliases/trace-option
:help aliases/help-option})
(defn extract-global-options
"Pull out global options from CLI flags"
[flags]
(if (empty? flags)
{:options {}
:cmd-flags []}
(let [flag (first flags)
match-flag (fn [info] (contains? (second info) flag))
match (first (filter match-flag global-options))
{:keys [options cmd-flags]} (extract-global-options (next flags))]
{:options (merge (when match {(first match) true}) options)
:cmd-flags (if (nil? match)
(merge cmd-flags flag)
cmd-flags)})))
(defn read-flags
"Parse CLI arguments and pull out any flags and global options"
[arguments]
(let [args (remove isFlag? arguments)
flags (filter isFlag? arguments)
{:keys [options cmd-flags]} (extract-global-options flags)]
{:args args
:flags cmd-flags
:options options}))
(defn not-yet-implemented
[state args]
(fail (get-msg :not-implemented (first args))))
(def verbs
"Our supported verbs and the functions implementing each"
{:assemble kale.assemble/assemble
:dry-run kale.dry-run/dry-run
:create kale.create/create
:delete kale.delete/delete
:get-command kale.get-command/get-command
:help kale.help/help
:list-info kale.list/list-info
:login kale.login/login
:logout kale.login/logout
:refresh kale.refresh/refresh
:search kale.search/search
:select kale.select/select})
(defn get-cmd-name
"Determine the command name to output"
[cmd-key]
(if-let [cmd-name ({:list-info "list"
:get-command "get"}
cmd-key)]
cmd-name
(name cmd-key)))
(defn error-exit
"Exit with an error code.
This function is separated out to allow tests to redefine it."
([] (error-exit 1))
([exit-status] (System/exit exit-status)))
(defn main
[& arguments]
(let [{:keys [args flags options]} (read-flags arguments)
command (commands (first args))
state (kale.persistence/read-state)
language (keyword (user-selection state :language))]
(when (some? (options :trace))
(set-trace true))
(when (some? language)
(set-language language))
(if (or (some? (options :help))
(some? (aliases/help (second args))))
(println (kale.help/help {} (concat ["help"] args) []))
(if (nil? command)
(println (kale.help/help {} (concat ["help"] args) flags))
(do (when-not (or (#{:help :login} command) (:services state))
(fail (get-msg :please-login (get-cmd-name command))))
(println ((verbs command) state args flags)))))))
(defn -main
"The command line entry point."
[& arguments]
(try-function main arguments error-exit))
| null | https://raw.githubusercontent.com/IBM-Watson/kale/f1c5e312e5db0e3fc01c47dfb965f175b5b0a5b6/src/kale/main.clj | clojure | ( C ) Copyright IBM Corp. 2016 All Rights Reserved .
(ns kale.main
(:require [kale.aliases :refer [commands] :as aliases]
[kale.getter :refer [user-selection]]
[kale.common :refer [fail try-function get-command-msg
set-trace set-language]]
[kale.assemble]
[kale.dry-run]
[kale.create]
[kale.delete]
[kale.persistence]
[kale.get-command]
[kale.help]
[kale.list]
[kale.login]
[kale.refresh]
[kale.search]
[kale.select])
(:gen-class))
(defn get-msg
"Return the corresponding main message"
[msg-key & args]
(apply get-command-msg :main-messages msg-key args))
(defn isFlag? [x] (-> (re-find #"^-" x) nil? not))
(def global-options {:trace aliases/trace-option
:help aliases/help-option})
(defn extract-global-options
"Pull out global options from CLI flags"
[flags]
(if (empty? flags)
{:options {}
:cmd-flags []}
(let [flag (first flags)
match-flag (fn [info] (contains? (second info) flag))
match (first (filter match-flag global-options))
{:keys [options cmd-flags]} (extract-global-options (next flags))]
{:options (merge (when match {(first match) true}) options)
:cmd-flags (if (nil? match)
(merge cmd-flags flag)
cmd-flags)})))
(defn read-flags
"Parse CLI arguments and pull out any flags and global options"
[arguments]
(let [args (remove isFlag? arguments)
flags (filter isFlag? arguments)
{:keys [options cmd-flags]} (extract-global-options flags)]
{:args args
:flags cmd-flags
:options options}))
(defn not-yet-implemented
[state args]
(fail (get-msg :not-implemented (first args))))
(def verbs
"Our supported verbs and the functions implementing each"
{:assemble kale.assemble/assemble
:dry-run kale.dry-run/dry-run
:create kale.create/create
:delete kale.delete/delete
:get-command kale.get-command/get-command
:help kale.help/help
:list-info kale.list/list-info
:login kale.login/login
:logout kale.login/logout
:refresh kale.refresh/refresh
:search kale.search/search
:select kale.select/select})
(defn get-cmd-name
"Determine the command name to output"
[cmd-key]
(if-let [cmd-name ({:list-info "list"
:get-command "get"}
cmd-key)]
cmd-name
(name cmd-key)))
(defn error-exit
"Exit with an error code.
This function is separated out to allow tests to redefine it."
([] (error-exit 1))
([exit-status] (System/exit exit-status)))
(defn main
[& arguments]
(let [{:keys [args flags options]} (read-flags arguments)
command (commands (first args))
state (kale.persistence/read-state)
language (keyword (user-selection state :language))]
(when (some? (options :trace))
(set-trace true))
(when (some? language)
(set-language language))
(if (or (some? (options :help))
(some? (aliases/help (second args))))
(println (kale.help/help {} (concat ["help"] args) []))
(if (nil? command)
(println (kale.help/help {} (concat ["help"] args) flags))
(do (when-not (or (#{:help :login} command) (:services state))
(fail (get-msg :please-login (get-cmd-name command))))
(println ((verbs command) state args flags)))))))
(defn -main
"The command line entry point."
[& arguments]
(try-function main arguments error-exit))
| |
979bd6b33ea2f985eaf219e2238cee626c1a37cb83ed434a85f275e04292b6cf | mars0i/free | random.cljc | This software is copyright 2016 by , and is distributed
under the Gnu General Public License version 3.0 as specified in the
;; the file LICENSE.
(ns free.random
clj or cljs , depending
(def random-seed (ran/make-long-seed))
Do n't ever use a print statement in Clojurescript without the following :
#?(:cljs (enable-console-print!))
(println "random-seed:" random-seed)
(def rng$ (atom (ran/make-rng random-seed)))
(defn set-new-rng!
([] (reset! rng$ (ran/make-rng)))
([seed] (reset! rng$ (ran/make-rng seed))))
(defn next-gaussian
([] (ran/next-gaussian @rng$))
([mean sd] (ran/next-gaussian @rng$ mean sd)))
(defn next-double
[]
(ran/next-double @rng$))
;; Incanter versions:
;; (:require [incanter.stats :as istat]))
;(def pdf-normal istat/pdf-normal)
;(def sample-normal istat/sample-normal)
;(def sample-uniform istat/sample-uniform)
| null | https://raw.githubusercontent.com/mars0i/free/fe0fdc1c0bf1866cb07b4558a009a829f8d6ba23/src/cljc/general/free/random.cljc | clojure | the file LICENSE.
Incanter versions:
(:require [incanter.stats :as istat]))
(def pdf-normal istat/pdf-normal)
(def sample-normal istat/sample-normal)
(def sample-uniform istat/sample-uniform) | This software is copyright 2016 by , and is distributed
under the Gnu General Public License version 3.0 as specified in the
(ns free.random
clj or cljs , depending
(def random-seed (ran/make-long-seed))
Do n't ever use a print statement in Clojurescript without the following :
#?(:cljs (enable-console-print!))
(println "random-seed:" random-seed)
(def rng$ (atom (ran/make-rng random-seed)))
(defn set-new-rng!
([] (reset! rng$ (ran/make-rng)))
([seed] (reset! rng$ (ran/make-rng seed))))
(defn next-gaussian
([] (ran/next-gaussian @rng$))
([mean sd] (ran/next-gaussian @rng$ mean sd)))
(defn next-double
[]
(ran/next-double @rng$))
|
5bd1e9c777c52ea5388c222d0053b3ac272fed00c092b73d44c17f9ffef3bc7d | janestreet/memtrace_viewer_with_deps | container_intf.ml | (** This module extends {!Base.Container}. *)
open! Import
open Perms.Export
open Base.Container
module Continue_or_stop = Continue_or_stop
module type S1_permissions = sig
type ('a, -'permissions) t
(** Checks whether the provided element is there, using polymorphic compare if [equal]
is not provided. *)
val mem : ('a, [> read ]) t -> 'a -> equal:('a -> 'a -> bool) -> bool
val length : (_, [> read ]) t -> int
val is_empty : (_, [> read ]) t -> bool
(** [iter t ~f] calls [f] on each element of [t]. *)
val iter : ('a, [> read ]) t -> f:('a -> unit) -> unit
(** [fold t ~init ~f] returns [f (... f (f (f init e1) e2) e3 ...) en], where [e1..en]
are the elements of [t] *)
val fold : ('a, [> read ]) t -> init:'accum -> f:('accum -> 'a -> 'accum) -> 'accum
(** [fold_result t ~init ~f] is a short-circuiting version of [fold] that runs in the
[Result] monad. If [f] returns an [Error _], that value is returned without any
additional invocations of [f]. *)
val fold_result
: ('a, [> read ]) t
-> init:'accum
-> f:('accum -> 'a -> ('accum, 'e) Result.t)
-> ('accum, 'e) Result.t
(** [fold_until t ~init ~f ~finish] is a short-circuiting version of [fold]. If [f]
returns [Stop _] the computation ceases and results in that value. If [f] returns
[Continue _], the fold will proceed. If [f] never returns [Stop _], the final result
is computed by [finish]. *)
val fold_until
: ('a, [> read ]) t
-> init:'accum
-> f:('accum -> 'a -> ('accum, 'final) Continue_or_stop.t)
-> finish:('accum -> 'final)
-> 'final
(** Returns [true] if and only if there exists an element for which the provided
function evaluates to [true]. This is a short-circuiting operation. *)
val exists : ('a, [> read ]) t -> f:('a -> bool) -> bool
(** Returns [true] if and only if the provided function evaluates to [true] for all
elements. This is a short-circuiting operation. *)
val for_all : ('a, [> read ]) t -> f:('a -> bool) -> bool
(** Returns the number of elements for which the provided function evaluates to true. *)
val count : ('a, [> read ]) t -> f:('a -> bool) -> int
(** Returns the sum of [f i] for i in the container *)
val sum
: (module Summable with type t = 'sum)
-> ('a, [> read ]) t
-> f:('a -> 'sum)
-> 'sum
* Returns as an [ option ] the first element for which [ f ] evaluates to true .
val find : ('a, [> read ]) t -> f:('a -> bool) -> 'a option
* Returns the first evaluation of [ f ] that returns [ Some ] , and returns [ None ] if there
is no such element .
is no such element. *)
val find_map : ('a, [> read ]) t -> f:('a -> 'b option) -> 'b option
val to_list : ('a, [> read ]) t -> 'a list
val to_array : ('a, [> read ]) t -> 'a array
* Returns a min ( resp ) element from the collection using the provided [ compare ]
function . In case of a tie , the first element encountered while traversing the
collection is returned . The implementation uses [ fold ] so it has the same complexity
as [ fold ] . Returns [ None ] iff the collection is empty .
function. In case of a tie, the first element encountered while traversing the
collection is returned. The implementation uses [fold] so it has the same complexity
as [fold]. Returns [None] iff the collection is empty. *)
val min_elt : ('a, [> read ]) t -> compare:('a -> 'a -> int) -> 'a option
val max_elt : ('a, [> read ]) t -> compare:('a -> 'a -> int) -> 'a option
end
module type Container = sig
(** @open *)
include module type of struct
include Base.Container
end
module type S1_permissions = S1_permissions
end
| null | https://raw.githubusercontent.com/janestreet/memtrace_viewer_with_deps/5a9e1f927f5f8333e2d71c8d3ca03a45587422c4/vendor/core_kernel/src/container_intf.ml | ocaml | * This module extends {!Base.Container}.
* Checks whether the provided element is there, using polymorphic compare if [equal]
is not provided.
* [iter t ~f] calls [f] on each element of [t].
* [fold t ~init ~f] returns [f (... f (f (f init e1) e2) e3 ...) en], where [e1..en]
are the elements of [t]
* [fold_result t ~init ~f] is a short-circuiting version of [fold] that runs in the
[Result] monad. If [f] returns an [Error _], that value is returned without any
additional invocations of [f].
* [fold_until t ~init ~f ~finish] is a short-circuiting version of [fold]. If [f]
returns [Stop _] the computation ceases and results in that value. If [f] returns
[Continue _], the fold will proceed. If [f] never returns [Stop _], the final result
is computed by [finish].
* Returns [true] if and only if there exists an element for which the provided
function evaluates to [true]. This is a short-circuiting operation.
* Returns [true] if and only if the provided function evaluates to [true] for all
elements. This is a short-circuiting operation.
* Returns the number of elements for which the provided function evaluates to true.
* Returns the sum of [f i] for i in the container
* @open |
open! Import
open Perms.Export
open Base.Container
module Continue_or_stop = Continue_or_stop
module type S1_permissions = sig
type ('a, -'permissions) t
val mem : ('a, [> read ]) t -> 'a -> equal:('a -> 'a -> bool) -> bool
val length : (_, [> read ]) t -> int
val is_empty : (_, [> read ]) t -> bool
val iter : ('a, [> read ]) t -> f:('a -> unit) -> unit
val fold : ('a, [> read ]) t -> init:'accum -> f:('accum -> 'a -> 'accum) -> 'accum
val fold_result
: ('a, [> read ]) t
-> init:'accum
-> f:('accum -> 'a -> ('accum, 'e) Result.t)
-> ('accum, 'e) Result.t
val fold_until
: ('a, [> read ]) t
-> init:'accum
-> f:('accum -> 'a -> ('accum, 'final) Continue_or_stop.t)
-> finish:('accum -> 'final)
-> 'final
val exists : ('a, [> read ]) t -> f:('a -> bool) -> bool
val for_all : ('a, [> read ]) t -> f:('a -> bool) -> bool
val count : ('a, [> read ]) t -> f:('a -> bool) -> int
val sum
: (module Summable with type t = 'sum)
-> ('a, [> read ]) t
-> f:('a -> 'sum)
-> 'sum
* Returns as an [ option ] the first element for which [ f ] evaluates to true .
val find : ('a, [> read ]) t -> f:('a -> bool) -> 'a option
* Returns the first evaluation of [ f ] that returns [ Some ] , and returns [ None ] if there
is no such element .
is no such element. *)
val find_map : ('a, [> read ]) t -> f:('a -> 'b option) -> 'b option
val to_list : ('a, [> read ]) t -> 'a list
val to_array : ('a, [> read ]) t -> 'a array
* Returns a min ( resp ) element from the collection using the provided [ compare ]
function . In case of a tie , the first element encountered while traversing the
collection is returned . The implementation uses [ fold ] so it has the same complexity
as [ fold ] . Returns [ None ] iff the collection is empty .
function. In case of a tie, the first element encountered while traversing the
collection is returned. The implementation uses [fold] so it has the same complexity
as [fold]. Returns [None] iff the collection is empty. *)
val min_elt : ('a, [> read ]) t -> compare:('a -> 'a -> int) -> 'a option
val max_elt : ('a, [> read ]) t -> compare:('a -> 'a -> int) -> 'a option
end
module type Container = sig
include module type of struct
include Base.Container
end
module type S1_permissions = S1_permissions
end
|
e7dd4b6718d4f032416980fd047bfb12a2bdbf1f2b15f323f38caa6fc5ea7ca3 | hidaris/thinking-dumps | 4-8.rkt | ;; new-ref, due to append function
;; deref, due to list-ref
;; setref!, due to setref-inner
| null | https://raw.githubusercontent.com/hidaris/thinking-dumps/3fceaf9e6195ab99c8315749814a7377ef8baf86/eopl-solutions/chap4/4-8.rkt | racket | new-ref, due to append function
deref, due to list-ref
setref!, due to setref-inner | |
f8f46d6ba2aa09c8aa3dbd4e00bcd0d24b5f906caad2f9a71a4c8a581cb0dc47 | walmartlabs/lacinia | lists_tests.clj | Copyright ( c ) 2018 - present Walmart , Inc.
;
Licensed under the Apache License , Version 2.0 ( the " License " )
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; -2.0
;
; Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
(ns com.walmartlabs.lacinia.lists-tests
"Tests related to list types."
(:require
[clojure.test :refer [deftest is]]
[com.walmartlabs.test-utils :refer [compile-schema execute]]))
(deftest nil-lists-stay-nil
(let [schema (compile-schema "lists-schema.edn"
{:query/container
(constantly {:empty_list []
:non_empty_list ["Peekaboo"]
:null_list nil})})]
(is (= {:data {:container {:empty_list []
:non_empty_list ["Peekaboo"]
:null_list nil}}}
(execute schema
"{ container { empty_list non_empty_list null_list }}")))))
(deftest non-null-list-field-check
(let [schema (compile-schema "lists-schema.edn"
{:query/container
(constantly {:empty_list []
:non_empty_list ["Peekaboo"]
:null_list nil})})]
(is (= {:data {:container nil}
:errors [{:locations [{:column 15
:line 1}]
:message "Non-nullable field was null."
:path [:container
:non_null_list]}]}
(execute schema
"{ container { non_null_list }}")))))
(deftest promotion-of-nils-to-empty-lists
(let [schema (compile-schema "lists-schema.edn"
{:query/container
(constantly {:empty_list []
:non_empty_list ["Peekaboo"]
:null_list nil})}
{:promote-nils-to-empty-list? true})]
(is (= {:data {:container {:empty_list []
:non_empty_list ["Peekaboo"]
:null_list []}}}
(execute schema
"{ container { empty_list non_empty_list null_list }}")))))
(deftest nil-collapase
(let [schema (compile-schema "nullability.edn"
{:query/user (constantly {:id "1"
:employer {:id "10"}})})]
;; Because Employer/name was nil, the employer field collapses to nil (because
;; User/employer is nullable).
(is (= {:data {:user {:employer nil
:id "1"}}
:errors [{:locations [{:column 30
:line 4}]
:message "Non-nullable field was null."
:path [:user
:employer
:name]}]}
(execute schema "
{ user(id: \"1\") {
id
employer { id name }
}
}")))))
| null | https://raw.githubusercontent.com/walmartlabs/lacinia/88bf46f197bfed645d7767fcfe2bfa39e8b00b27/test/com/walmartlabs/lacinia/lists_tests.clj | clojure |
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.
Because Employer/name was nil, the employer field collapses to nil (because
User/employer is nullable). | Copyright ( c ) 2018 - present Walmart , Inc.
Licensed under the Apache License , Version 2.0 ( the " License " )
distributed under the License is distributed on an " AS IS " BASIS ,
(ns com.walmartlabs.lacinia.lists-tests
"Tests related to list types."
(:require
[clojure.test :refer [deftest is]]
[com.walmartlabs.test-utils :refer [compile-schema execute]]))
(deftest nil-lists-stay-nil
(let [schema (compile-schema "lists-schema.edn"
{:query/container
(constantly {:empty_list []
:non_empty_list ["Peekaboo"]
:null_list nil})})]
(is (= {:data {:container {:empty_list []
:non_empty_list ["Peekaboo"]
:null_list nil}}}
(execute schema
"{ container { empty_list non_empty_list null_list }}")))))
(deftest non-null-list-field-check
(let [schema (compile-schema "lists-schema.edn"
{:query/container
(constantly {:empty_list []
:non_empty_list ["Peekaboo"]
:null_list nil})})]
(is (= {:data {:container nil}
:errors [{:locations [{:column 15
:line 1}]
:message "Non-nullable field was null."
:path [:container
:non_null_list]}]}
(execute schema
"{ container { non_null_list }}")))))
(deftest promotion-of-nils-to-empty-lists
(let [schema (compile-schema "lists-schema.edn"
{:query/container
(constantly {:empty_list []
:non_empty_list ["Peekaboo"]
:null_list nil})}
{:promote-nils-to-empty-list? true})]
(is (= {:data {:container {:empty_list []
:non_empty_list ["Peekaboo"]
:null_list []}}}
(execute schema
"{ container { empty_list non_empty_list null_list }}")))))
(deftest nil-collapase
(let [schema (compile-schema "nullability.edn"
{:query/user (constantly {:id "1"
:employer {:id "10"}})})]
(is (= {:data {:user {:employer nil
:id "1"}}
:errors [{:locations [{:column 30
:line 4}]
:message "Non-nullable field was null."
:path [:user
:employer
:name]}]}
(execute schema "
{ user(id: \"1\") {
id
employer { id name }
}
}")))))
|
45190929ca9eab424039fa59193f5a3a097cb2274e8d611794e37dc4b096783a | coq/coq | genarg.mli | (************************************************************************)
(* * The Coq Proof Assistant / The Coq Development Team *)
v * Copyright INRIA , CNRS and contributors
< O _ _ _ , , * ( see version control and CREDITS file for authors & dates )
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
* GNU Lesser General Public License Version 2.1
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
* Generic arguments used by the extension mechanisms of several Coq ASTs .
* The route of a generic argument , from parsing to evaluation .
In the following diagram , " object " can be ltac_expr , , tactic_value , etc .
{ % \begin{verbatim } % }
parsing in_raw out_raw
char stream --- > raw_object --- > raw_object generic_argument -------+
encapsulation decaps|
|
V
raw_object
|
globalization |
V
glob_object
|
encaps |
in_glob |
V
glob_object generic_argument
|
out in out_glob |
object < --- object generic_argument < --- object < --- glob_object < ---+
| decaps encaps interp decaps
|
V
effective use
{ % \end{verbatim } % }
To distinguish between the uninterpreted , globalized and
interpreted worlds , we annotate the type [ generic_argument ] by a
phantom argument .
In the following diagram, "object" can be ltac_expr, constr, tactic_value, etc.
{% \begin{verbatim} %}
parsing in_raw out_raw
char stream ---> raw_object ---> raw_object generic_argument -------+
encapsulation decaps|
|
V
raw_object
|
globalization |
V
glob_object
|
encaps |
in_glob |
V
glob_object generic_argument
|
out in out_glob |
object <--- object generic_argument <--- object <--- glob_object <---+
| decaps encaps interp decaps
|
V
effective use
{% \end{verbatim} %}
To distinguish between the uninterpreted, globalized and
interpreted worlds, we annotate the type [generic_argument] by a
phantom argument.
*)
* { 5 Generic types }
module ArgT :
sig
type ('a, 'b, 'c) tag
val eq : ('a1, 'b1, 'c1) tag -> ('a2, 'b2, 'c2) tag -> ('a1 * 'b1 * 'c1, 'a2 * 'b2 * 'c2) CSig.eq option
val repr : ('a, 'b, 'c) tag -> string
type any = Any : ('a, 'b, 'c) tag -> any
val name : string -> any option
end
* Generic types . The first parameter is the OCaml lowest level , the second one
is the globalized level , and third one the internalized level .
is the globalized level, and third one the internalized level. *)
type (_, _, _) genarg_type =
| ExtraArg : ('a, 'b, 'c) ArgT.tag -> ('a, 'b, 'c) genarg_type
| ListArg : ('a, 'b, 'c) genarg_type -> ('a list, 'b list, 'c list) genarg_type
| OptArg : ('a, 'b, 'c) genarg_type -> ('a option, 'b option, 'c option) genarg_type
| PairArg : ('a1, 'b1, 'c1) genarg_type * ('a2, 'b2, 'c2) genarg_type ->
('a1 * 'a2, 'b1 * 'b2, 'c1 * 'c2) genarg_type
type 'a uniform_genarg_type = ('a, 'a, 'a) genarg_type
* for concision when the three types agree .
val make0 : string -> ('raw, 'glob, 'top) genarg_type
* Create a new generic type of argument : force to associate
unique ML types at each of the three levels .
unique ML types at each of the three levels. *)
val create_arg : string -> ('raw, 'glob, 'top) genarg_type
* for [ make0 ] .
* { 5 Specialized types }
* All of [ rlevel ] , [ glevel ] and [ tlevel ] must be non convertible
to ensure the injectivity of the GADT type inference .
to ensure the injectivity of the GADT type inference. *)
type rlevel = [ `rlevel ]
type glevel = [ `glevel ]
type tlevel = [ `tlevel ]
* Generic types at a fixed level . The first parameter embeds the OCaml type
and the second one the level .
and the second one the level. *)
type (_, _) abstract_argument_type =
| Rawwit : ('a, 'b, 'c) genarg_type -> ('a, rlevel) abstract_argument_type
| Glbwit : ('a, 'b, 'c) genarg_type -> ('b, glevel) abstract_argument_type
| Topwit : ('a, 'b, 'c) genarg_type -> ('c, tlevel) abstract_argument_type
type 'a raw_abstract_argument_type = ('a, rlevel) abstract_argument_type
(** Specialized type at raw level. *)
type 'a glob_abstract_argument_type = ('a, glevel) abstract_argument_type
(** Specialized type at globalized level. *)
type 'a typed_abstract_argument_type = ('a, tlevel) abstract_argument_type
(** Specialized type at internalized level. *)
* { 6 Projections }
val rawwit : ('a, 'b, 'c) genarg_type -> ('a, rlevel) abstract_argument_type
(** Projection on the raw type constructor. *)
val glbwit : ('a, 'b, 'c) genarg_type -> ('b, glevel) abstract_argument_type
(** Projection on the globalized type constructor. *)
val topwit : ('a, 'b, 'c) genarg_type -> ('c, tlevel) abstract_argument_type
(** Projection on the internalized type constructor. *)
* { 5 Generic arguments }
type 'l generic_argument = GenArg : ('a, 'l) abstract_argument_type * 'a -> 'l generic_argument
(** A inhabitant of ['level generic_argument] is a inhabitant of some type at
level ['level], together with the representation of this type. *)
type raw_generic_argument = rlevel generic_argument
type glob_generic_argument = glevel generic_argument
type typed_generic_argument = tlevel generic_argument
* { 6 Constructors }
val in_gen : ('a, 'co) abstract_argument_type -> 'a -> 'co generic_argument
(** [in_gen t x] embeds an argument of type [t] into a generic argument. *)
val out_gen : ('a, 'co) abstract_argument_type -> 'co generic_argument -> 'a
(** [out_gen t x] recovers an argument of type [t] from a generic argument. It
fails if [x] has not the right dynamic type. *)
val has_type : 'co generic_argument -> ('a, 'co) abstract_argument_type -> bool
* [ v t ] tells whether [ v ] has type [ t ] . If true , it ensures that
[ out_gen t v ] will not raise a dynamic type exception .
[out_gen t v] will not raise a dynamic type exception. *)
* { 6 Type reification }
type argument_type = ArgumentType : ('a, 'b, 'c) genarg_type -> argument_type
* { 6 Equalities }
val argument_type_eq : argument_type -> argument_type -> bool
val genarg_type_eq :
('a1, 'b1, 'c1) genarg_type ->
('a2, 'b2, 'c2) genarg_type ->
('a1 * 'b1 * 'c1, 'a2 * 'b2 * 'c2) CSig.eq option
val abstract_argument_type_eq :
('a, 'l) abstract_argument_type -> ('b, 'l) abstract_argument_type ->
('a, 'b) CSig.eq option
val pr_argument_type : argument_type -> Pp.t
(** Print a human-readable representation for a given type. *)
val genarg_tag : 'a generic_argument -> argument_type
val unquote : ('a, 'co) abstract_argument_type -> argument_type
* { 6 Registering genarg - manipulating functions }
This is boilerplate code used here and there in the code of Coq .
This is boilerplate code used here and there in the code of Coq. *)
val get_arg_tag : ('a, 'b, 'c) genarg_type -> ('a, 'b, 'c) ArgT.tag
* Works only on base objects ( ExtraArg ) , otherwise fails badly .
module type GenObj =
sig
type ('raw, 'glb, 'top) obj
(** An object manipulating generic arguments. *)
val name : string
(** A name for such kind of manipulation, e.g. [interp]. *)
val default : ('raw, 'glb, 'top) genarg_type -> ('raw, 'glb, 'top) obj option
(** A generic object when there is no registered object for this type. *)
end
module Register (M : GenObj) :
sig
val register0 : ('raw, 'glb, 'top) genarg_type ->
('raw, 'glb, 'top) M.obj -> unit
(** Register a ground type manipulation function. *)
val obj : ('raw, 'glb, 'top) genarg_type -> ('raw, 'glb, 'top) M.obj
(** Recover a manipulation function at a given type. *)
end
* { 5 Compatibility layer }
The functions below are aliases for generic_type constructors .
The functions below are aliases for generic_type constructors.
*)
val wit_list : ('a, 'b, 'c) genarg_type -> ('a list, 'b list, 'c list) genarg_type
val wit_opt : ('a, 'b, 'c) genarg_type -> ('a option, 'b option, 'c option) genarg_type
val wit_pair : ('a1, 'b1, 'c1) genarg_type -> ('a2, 'b2, 'c2) genarg_type ->
('a1 * 'a2, 'b1 * 'b2, 'c1 * 'c2) genarg_type
| null | https://raw.githubusercontent.com/coq/coq/110921a449fcb830ec2a1cd07e3acc32319feae6/lib/genarg.mli | ocaml | **********************************************************************
* The Coq Proof Assistant / The Coq Development Team
// * This file is distributed under the terms of the
* (see LICENSE file for the text of the license)
**********************************************************************
* Specialized type at raw level.
* Specialized type at globalized level.
* Specialized type at internalized level.
* Projection on the raw type constructor.
* Projection on the globalized type constructor.
* Projection on the internalized type constructor.
* A inhabitant of ['level generic_argument] is a inhabitant of some type at
level ['level], together with the representation of this type.
* [in_gen t x] embeds an argument of type [t] into a generic argument.
* [out_gen t x] recovers an argument of type [t] from a generic argument. It
fails if [x] has not the right dynamic type.
* Print a human-readable representation for a given type.
* An object manipulating generic arguments.
* A name for such kind of manipulation, e.g. [interp].
* A generic object when there is no registered object for this type.
* Register a ground type manipulation function.
* Recover a manipulation function at a given type. | v * Copyright INRIA , CNRS and contributors
< O _ _ _ , , * ( see version control and CREDITS file for authors & dates )
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* GNU Lesser General Public License Version 2.1
* Generic arguments used by the extension mechanisms of several Coq ASTs .
* The route of a generic argument , from parsing to evaluation .
In the following diagram , " object " can be ltac_expr , , tactic_value , etc .
{ % \begin{verbatim } % }
parsing in_raw out_raw
char stream --- > raw_object --- > raw_object generic_argument -------+
encapsulation decaps|
|
V
raw_object
|
globalization |
V
glob_object
|
encaps |
in_glob |
V
glob_object generic_argument
|
out in out_glob |
object < --- object generic_argument < --- object < --- glob_object < ---+
| decaps encaps interp decaps
|
V
effective use
{ % \end{verbatim } % }
To distinguish between the uninterpreted , globalized and
interpreted worlds , we annotate the type [ generic_argument ] by a
phantom argument .
In the following diagram, "object" can be ltac_expr, constr, tactic_value, etc.
{% \begin{verbatim} %}
parsing in_raw out_raw
char stream ---> raw_object ---> raw_object generic_argument -------+
encapsulation decaps|
|
V
raw_object
|
globalization |
V
glob_object
|
encaps |
in_glob |
V
glob_object generic_argument
|
out in out_glob |
object <--- object generic_argument <--- object <--- glob_object <---+
| decaps encaps interp decaps
|
V
effective use
{% \end{verbatim} %}
To distinguish between the uninterpreted, globalized and
interpreted worlds, we annotate the type [generic_argument] by a
phantom argument.
*)
* { 5 Generic types }
module ArgT :
sig
type ('a, 'b, 'c) tag
val eq : ('a1, 'b1, 'c1) tag -> ('a2, 'b2, 'c2) tag -> ('a1 * 'b1 * 'c1, 'a2 * 'b2 * 'c2) CSig.eq option
val repr : ('a, 'b, 'c) tag -> string
type any = Any : ('a, 'b, 'c) tag -> any
val name : string -> any option
end
* Generic types . The first parameter is the OCaml lowest level , the second one
is the globalized level , and third one the internalized level .
is the globalized level, and third one the internalized level. *)
type (_, _, _) genarg_type =
| ExtraArg : ('a, 'b, 'c) ArgT.tag -> ('a, 'b, 'c) genarg_type
| ListArg : ('a, 'b, 'c) genarg_type -> ('a list, 'b list, 'c list) genarg_type
| OptArg : ('a, 'b, 'c) genarg_type -> ('a option, 'b option, 'c option) genarg_type
| PairArg : ('a1, 'b1, 'c1) genarg_type * ('a2, 'b2, 'c2) genarg_type ->
('a1 * 'a2, 'b1 * 'b2, 'c1 * 'c2) genarg_type
type 'a uniform_genarg_type = ('a, 'a, 'a) genarg_type
* for concision when the three types agree .
val make0 : string -> ('raw, 'glob, 'top) genarg_type
* Create a new generic type of argument : force to associate
unique ML types at each of the three levels .
unique ML types at each of the three levels. *)
val create_arg : string -> ('raw, 'glob, 'top) genarg_type
* for [ make0 ] .
* { 5 Specialized types }
* All of [ rlevel ] , [ glevel ] and [ tlevel ] must be non convertible
to ensure the injectivity of the GADT type inference .
to ensure the injectivity of the GADT type inference. *)
type rlevel = [ `rlevel ]
type glevel = [ `glevel ]
type tlevel = [ `tlevel ]
* Generic types at a fixed level . The first parameter embeds the OCaml type
and the second one the level .
and the second one the level. *)
type (_, _) abstract_argument_type =
| Rawwit : ('a, 'b, 'c) genarg_type -> ('a, rlevel) abstract_argument_type
| Glbwit : ('a, 'b, 'c) genarg_type -> ('b, glevel) abstract_argument_type
| Topwit : ('a, 'b, 'c) genarg_type -> ('c, tlevel) abstract_argument_type
type 'a raw_abstract_argument_type = ('a, rlevel) abstract_argument_type
type 'a glob_abstract_argument_type = ('a, glevel) abstract_argument_type
type 'a typed_abstract_argument_type = ('a, tlevel) abstract_argument_type
* { 6 Projections }
val rawwit : ('a, 'b, 'c) genarg_type -> ('a, rlevel) abstract_argument_type
val glbwit : ('a, 'b, 'c) genarg_type -> ('b, glevel) abstract_argument_type
val topwit : ('a, 'b, 'c) genarg_type -> ('c, tlevel) abstract_argument_type
* { 5 Generic arguments }
type 'l generic_argument = GenArg : ('a, 'l) abstract_argument_type * 'a -> 'l generic_argument
type raw_generic_argument = rlevel generic_argument
type glob_generic_argument = glevel generic_argument
type typed_generic_argument = tlevel generic_argument
* { 6 Constructors }
val in_gen : ('a, 'co) abstract_argument_type -> 'a -> 'co generic_argument
val out_gen : ('a, 'co) abstract_argument_type -> 'co generic_argument -> 'a
val has_type : 'co generic_argument -> ('a, 'co) abstract_argument_type -> bool
* [ v t ] tells whether [ v ] has type [ t ] . If true , it ensures that
[ out_gen t v ] will not raise a dynamic type exception .
[out_gen t v] will not raise a dynamic type exception. *)
* { 6 Type reification }
type argument_type = ArgumentType : ('a, 'b, 'c) genarg_type -> argument_type
* { 6 Equalities }
val argument_type_eq : argument_type -> argument_type -> bool
val genarg_type_eq :
('a1, 'b1, 'c1) genarg_type ->
('a2, 'b2, 'c2) genarg_type ->
('a1 * 'b1 * 'c1, 'a2 * 'b2 * 'c2) CSig.eq option
val abstract_argument_type_eq :
('a, 'l) abstract_argument_type -> ('b, 'l) abstract_argument_type ->
('a, 'b) CSig.eq option
val pr_argument_type : argument_type -> Pp.t
val genarg_tag : 'a generic_argument -> argument_type
val unquote : ('a, 'co) abstract_argument_type -> argument_type
* { 6 Registering genarg - manipulating functions }
This is boilerplate code used here and there in the code of Coq .
This is boilerplate code used here and there in the code of Coq. *)
val get_arg_tag : ('a, 'b, 'c) genarg_type -> ('a, 'b, 'c) ArgT.tag
* Works only on base objects ( ExtraArg ) , otherwise fails badly .
module type GenObj =
sig
type ('raw, 'glb, 'top) obj
val name : string
val default : ('raw, 'glb, 'top) genarg_type -> ('raw, 'glb, 'top) obj option
end
module Register (M : GenObj) :
sig
val register0 : ('raw, 'glb, 'top) genarg_type ->
('raw, 'glb, 'top) M.obj -> unit
val obj : ('raw, 'glb, 'top) genarg_type -> ('raw, 'glb, 'top) M.obj
end
* { 5 Compatibility layer }
The functions below are aliases for generic_type constructors .
The functions below are aliases for generic_type constructors.
*)
val wit_list : ('a, 'b, 'c) genarg_type -> ('a list, 'b list, 'c list) genarg_type
val wit_opt : ('a, 'b, 'c) genarg_type -> ('a option, 'b option, 'c option) genarg_type
val wit_pair : ('a1, 'b1, 'c1) genarg_type -> ('a2, 'b2, 'c2) genarg_type ->
('a1 * 'a2, 'b1 * 'b2, 'c1 * 'c2) genarg_type
|
bc1f00c39515f700b2a8ce3e765eef2f4221542c3a19c0f5ce868e84bda23c54 | bazurbat/chicken-scheme | compiler-syntax.scm | ;;;; compiler-syntax.scm - compiler syntax used internally
;
Copyright ( c ) 2009 - 2016 , The CHICKEN Team
; 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 the author nor the names of its contributors may be used to endorse or promote
; products derived from this software without specific prior written permission.
;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS
; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
; AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR
; OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
; POSSIBILITY OF SUCH DAMAGE.
(declare
(unit compiler-syntax) )
(include "compiler-namespace")
(include "tweaks.scm")
Compiler macros ( that operate in the expansion phase )
(define compiler-syntax-statistics '())
(set! ##sys#compiler-syntax-hook
(lambda (name result)
(let ((a (alist-ref name compiler-syntax-statistics eq? 0)))
(set! compiler-syntax-statistics
(alist-update! name (add1 a) compiler-syntax-statistics)))))
(define (r-c-s names transformer #!optional (se '()))
(let ((t (cons (##sys#ensure-transformer
(##sys#er-transformer transformer)
(car names))
(append se ##sys#default-macro-environment))))
(for-each
(lambda (name)
(##sys#put! name '##compiler#compiler-syntax t) )
names) ) )
(define-syntax define-internal-compiler-syntax
(syntax-rules ()
((_ (names . llist) (se ...) . body)
(r-c-s
'names (lambda llist . body)
`((se . ,(##sys#primitive-alias 'se)) ...)))))
(define-internal-compiler-syntax ((for-each ##sys#for-each #%for-each) x r c)
(pair?)
(let ((%let (r 'let))
(%if (r 'if))
(%loop (r 'for-each-loop))
(%proc (gensym))
(%begin (r 'begin))
(%quote (r 'quote))
(%and (r 'and))
(%pair? (r 'pair?))
(%lambda (r 'lambda))
(lsts (cddr x)))
(if (and (memq 'for-each standard-bindings) ; we have to check this because the db (and thus
(> (length+ x) 2)) ; intrinsic marks) isn't set up yet
(let ((vars (map (lambda _ (gensym)) lsts)))
`(,%let ((,%proc ,(cadr x))
,@(map list vars lsts))
,@(map (lambda (var)
`(##core#check (##sys#check-list ,var (,%quote for-each))))
vars)
(,%let ,%loop ,(map list vars vars)
(,%if (,%and ,@(map (lambda (v) `(,%pair? ,v)) vars))
(,%begin
(,%proc
,@(map (lambda (v) `(##sys#slot ,v 0)) vars))
(##core#app
,%loop
,@(map (lambda (v) `(##sys#slot ,v 1)) vars) ) )))))
x)))
(define-internal-compiler-syntax ((map ##sys#map #%map) x r c)
(pair? cons)
(let ((%let (r 'let))
(%if (r 'if))
(%loop (r 'map-loop))
(%res (gensym))
(%cons (r 'cons))
(%set! (r 'set!))
(%result (gensym))
(%node (gensym))
(%proc (gensym))
(%quote (r 'quote))
(%begin (r 'begin))
(%lambda (r 'lambda))
(%and (r 'and))
(%pair? (r 'pair?))
(lsts (cddr x)))
(if (and (memq 'map standard-bindings) ; s.a.
(> (length+ x) 2))
(let ((vars (map (lambda _ (gensym)) lsts)))
`(,%let ((,%node (,%cons (##core#undefined) (,%quote ()))))
(,%let ((,%result ,%node)
(,%proc ,(cadr x))
,@(map list vars lsts))
,@(map (lambda (var)
`(##core#check (##sys#check-list ,var (,%quote map))))
vars)
(,%let ,%loop ,(map list vars vars)
(,%if (,%and ,@(map (lambda (v) `(,%pair? ,v)) vars))
(,%let ((,%res
(,%cons
(,%proc
,@(map (lambda (v) `(##sys#slot ,v 0)) vars))
(,%quote ()))))
(##sys#setslot ,%node 1 ,%res)
(,%set! ,%node ,%res)
(##core#app
,%loop
,@(map (lambda (v) `(##sys#slot ,v 1)) vars)))
(##sys#slot ,%result 1))))))
x)))
(define-internal-compiler-syntax ((o #%o) x r c) ()
(if (and (fx> (length x) 1)
(memq 'o extended-bindings) ) ; s.a.
(let ((%tmp (r 'tmp)))
`(,(r 'lambda) (,%tmp) ,(fold-right list %tmp (cdr x)))) ;XXX use foldr
x))
(define-internal-compiler-syntax ((sprintf #%sprintf format #%format) x r c)
(display write fprintf number->string write-char open-output-string get-output-string)
(let* ((out (gensym 'out))
(code (compile-format-string
(if (memq (car x) '(sprintf #%sprintf))
'sprintf
'format)
out
x
(cdr x)
r c)))
(if code
`(,(r 'let) ((,out (,(r 'open-output-string))))
,code
(,(r 'get-output-string) ,out))
x)))
(define-internal-compiler-syntax ((fprintf #%fprintf) x r c)
(display write fprintf number->string write-char open-output-string get-output-string)
(if (>= (length x) 3)
(let ((code (compile-format-string
'fprintf (cadr x)
x (cddr x)
r c)))
(or code x))
x))
(define-internal-compiler-syntax ((printf #%printf) x r c)
(display write fprintf number->string write-char open-output-string get-output-string)
(let ((code (compile-format-string
'printf '##sys#standard-output
x (cdr x)
r c)))
(or code x)))
(define (compile-format-string func out x args r c)
(call/cc
(lambda (return)
(and (>= (length args) 1)
(memq func extended-bindings) ; s.a.
(or (string? (car args))
(and (list? (car args))
(c (r 'quote) (caar args))
(string? (cadar args))))
(let ((fstr (if (string? (car args)) (car args) (cadar args)))
(args (cdr args)))
(define (fail ret? msg . args)
(let ((ln (get-line x)))
(warning
(sprintf "~a`~a', in format string ~s, ~?"
(if ln (sprintf "(~a) " ln) "")
func fstr
msg args) ))
(when ret? (return #f)))
(let ((code '())
(index 0)
(len (string-length fstr))
(%out (r 'out))
(%fprintf (r 'fprintf))
(%let (r 'let))
(%number->string (r 'number->string)))
(define (fetch)
(let ((c (string-ref fstr index)))
(set! index (fx+ index 1))
c) )
(define (next)
(if (null? args)
(fail #t "too few arguments to formatted output procedure")
(let ((x (car args)))
(set! args (cdr args))
x) ) )
(define (endchunk chunk)
(when (pair? chunk)
(push
(if (= 1 (length chunk))
`(##sys#write-char-0 ,(car chunk) ,%out)
`(##sys#print ,(reverse-list->string chunk) #f ,%out)))))
(define (push exp)
(set! code (cons exp code)))
(let loop ((chunk '()))
(cond ((>= index len)
(unless (null? args)
(fail #f "too many arguments to formatted output procedure"))
(endchunk chunk)
`(,%let ((,%out ,out))
(##sys#check-output-port ,%out #t ',func)
,@(reverse code)))
(else
(let ((c (fetch)))
(if (eq? c #\~)
(let ((dchar (fetch)))
(endchunk chunk)
(case (char-upcase dchar)
((#\S) (push `(##sys#print ,(next) #t ,%out)))
((#\A) (push `(##sys#print ,(next) #f ,%out)))
((#\C) (push `(##sys#write-char-0 ,(next) ,%out)))
((#\B)
(push
`(##sys#print (,%number->string ,(next) 2)
#f ,%out)))
((#\O)
(push
`(##sys#print (,%number->string ,(next) 8)
#f ,%out)))
((#\X)
(push
`(##sys#print (,%number->string ,(next) 16)
#f ,%out)))
((#\!) (push `(##sys#flush-output ,%out)))
((#\?)
(let* ([fstr (next)]
[lst (next)] )
(push `(##sys#apply ,%fprintf ,%out ,fstr ,lst))))
((#\~) (push `(##sys#write-char-0 #\~ ,%out)))
((#\% #\N) (push `(##sys#write-char-0 #\newline ,%out)))
(else
(if (char-whitespace? dchar)
(let skip ((c (fetch)))
(if (char-whitespace? c)
(skip (fetch))
(set! index (sub1 index))))
(fail #t "illegal format-string character `~c'" dchar) ) ) )
(loop '()) )
(loop (cons c chunk)))))))))))))
(define-internal-compiler-syntax ((foldr #%foldr) x r c)
(pair?)
(if (and (fx= (length x) 4)
(memq 'foldr extended-bindings) ) ; s.a.
(let ((f (cadr x))
(z (caddr x))
(lst (cadddr x))
(%let* (r 'let*))
(%let (r 'let))
(%pair? (r 'pair?))
(%if (r 'if))
(loopvar (gensym "foldr"))
(lstvar (gensym)))
`(,%let* ((,lstvar ,lst))
(##core#check (##sys#check-list ,lstvar (##core#quote foldr)))
(,%let ,loopvar ((,lstvar ,lstvar))
(,%if (,%pair? ,lstvar)
(,f (##sys#slot ,lstvar 0)
(##core#app ,loopvar (##sys#slot ,lstvar 1)))
,z))))
x))
(define-internal-compiler-syntax ((foldl #%foldl) x r c)
(pair?)
(if (and (fx= (length x) 4)
(memq 'foldl extended-bindings) ) ; s.a.
(let ((f (cadr x))
(z (caddr x))
(lst (cadddr x))
(%let* (r 'let*))
(%let (r 'let))
(%if (r 'if))
(%pair? (r 'pair?))
(zvar (gensym))
(loopvar (gensym "foldl"))
(lstvar (gensym)))
`(,%let* ((,zvar ,z)
(,lstvar ,lst))
(##core#check (##sys#check-list ,lstvar (##core#quote foldl)))
(,%let ,loopvar ((,lstvar ,lstvar) (,zvar ,zvar))
(,%if (,%pair? ,lstvar)
(##core#app
,loopvar
(##sys#slot ,lstvar 1)
(,f ,zvar (##sys#slot ,lstvar 0)))
,zvar))))
x))
| null | https://raw.githubusercontent.com/bazurbat/chicken-scheme/f0c9d1fd8b68eb322e320e65ec40b0bf7d1b41dc/compiler-syntax.scm | scheme | compiler-syntax.scm - compiler syntax used internally
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 the author nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
we have to check this because the db (and thus
intrinsic marks) isn't set up yet
s.a.
s.a.
XXX use foldr
s.a.
s.a.
s.a. | Copyright ( c ) 2009 - 2016 , The CHICKEN Team
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS
CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR
(declare
(unit compiler-syntax) )
(include "compiler-namespace")
(include "tweaks.scm")
Compiler macros ( that operate in the expansion phase )
(define compiler-syntax-statistics '())
(set! ##sys#compiler-syntax-hook
(lambda (name result)
(let ((a (alist-ref name compiler-syntax-statistics eq? 0)))
(set! compiler-syntax-statistics
(alist-update! name (add1 a) compiler-syntax-statistics)))))
(define (r-c-s names transformer #!optional (se '()))
(let ((t (cons (##sys#ensure-transformer
(##sys#er-transformer transformer)
(car names))
(append se ##sys#default-macro-environment))))
(for-each
(lambda (name)
(##sys#put! name '##compiler#compiler-syntax t) )
names) ) )
(define-syntax define-internal-compiler-syntax
(syntax-rules ()
((_ (names . llist) (se ...) . body)
(r-c-s
'names (lambda llist . body)
`((se . ,(##sys#primitive-alias 'se)) ...)))))
(define-internal-compiler-syntax ((for-each ##sys#for-each #%for-each) x r c)
(pair?)
(let ((%let (r 'let))
(%if (r 'if))
(%loop (r 'for-each-loop))
(%proc (gensym))
(%begin (r 'begin))
(%quote (r 'quote))
(%and (r 'and))
(%pair? (r 'pair?))
(%lambda (r 'lambda))
(lsts (cddr x)))
(let ((vars (map (lambda _ (gensym)) lsts)))
`(,%let ((,%proc ,(cadr x))
,@(map list vars lsts))
,@(map (lambda (var)
`(##core#check (##sys#check-list ,var (,%quote for-each))))
vars)
(,%let ,%loop ,(map list vars vars)
(,%if (,%and ,@(map (lambda (v) `(,%pair? ,v)) vars))
(,%begin
(,%proc
,@(map (lambda (v) `(##sys#slot ,v 0)) vars))
(##core#app
,%loop
,@(map (lambda (v) `(##sys#slot ,v 1)) vars) ) )))))
x)))
(define-internal-compiler-syntax ((map ##sys#map #%map) x r c)
(pair? cons)
(let ((%let (r 'let))
(%if (r 'if))
(%loop (r 'map-loop))
(%res (gensym))
(%cons (r 'cons))
(%set! (r 'set!))
(%result (gensym))
(%node (gensym))
(%proc (gensym))
(%quote (r 'quote))
(%begin (r 'begin))
(%lambda (r 'lambda))
(%and (r 'and))
(%pair? (r 'pair?))
(lsts (cddr x)))
(> (length+ x) 2))
(let ((vars (map (lambda _ (gensym)) lsts)))
`(,%let ((,%node (,%cons (##core#undefined) (,%quote ()))))
(,%let ((,%result ,%node)
(,%proc ,(cadr x))
,@(map list vars lsts))
,@(map (lambda (var)
`(##core#check (##sys#check-list ,var (,%quote map))))
vars)
(,%let ,%loop ,(map list vars vars)
(,%if (,%and ,@(map (lambda (v) `(,%pair? ,v)) vars))
(,%let ((,%res
(,%cons
(,%proc
,@(map (lambda (v) `(##sys#slot ,v 0)) vars))
(,%quote ()))))
(##sys#setslot ,%node 1 ,%res)
(,%set! ,%node ,%res)
(##core#app
,%loop
,@(map (lambda (v) `(##sys#slot ,v 1)) vars)))
(##sys#slot ,%result 1))))))
x)))
(define-internal-compiler-syntax ((o #%o) x r c) ()
(if (and (fx> (length x) 1)
(let ((%tmp (r 'tmp)))
x))
(define-internal-compiler-syntax ((sprintf #%sprintf format #%format) x r c)
(display write fprintf number->string write-char open-output-string get-output-string)
(let* ((out (gensym 'out))
(code (compile-format-string
(if (memq (car x) '(sprintf #%sprintf))
'sprintf
'format)
out
x
(cdr x)
r c)))
(if code
`(,(r 'let) ((,out (,(r 'open-output-string))))
,code
(,(r 'get-output-string) ,out))
x)))
(define-internal-compiler-syntax ((fprintf #%fprintf) x r c)
(display write fprintf number->string write-char open-output-string get-output-string)
(if (>= (length x) 3)
(let ((code (compile-format-string
'fprintf (cadr x)
x (cddr x)
r c)))
(or code x))
x))
(define-internal-compiler-syntax ((printf #%printf) x r c)
(display write fprintf number->string write-char open-output-string get-output-string)
(let ((code (compile-format-string
'printf '##sys#standard-output
x (cdr x)
r c)))
(or code x)))
(define (compile-format-string func out x args r c)
(call/cc
(lambda (return)
(and (>= (length args) 1)
(or (string? (car args))
(and (list? (car args))
(c (r 'quote) (caar args))
(string? (cadar args))))
(let ((fstr (if (string? (car args)) (car args) (cadar args)))
(args (cdr args)))
(define (fail ret? msg . args)
(let ((ln (get-line x)))
(warning
(sprintf "~a`~a', in format string ~s, ~?"
(if ln (sprintf "(~a) " ln) "")
func fstr
msg args) ))
(when ret? (return #f)))
(let ((code '())
(index 0)
(len (string-length fstr))
(%out (r 'out))
(%fprintf (r 'fprintf))
(%let (r 'let))
(%number->string (r 'number->string)))
(define (fetch)
(let ((c (string-ref fstr index)))
(set! index (fx+ index 1))
c) )
(define (next)
(if (null? args)
(fail #t "too few arguments to formatted output procedure")
(let ((x (car args)))
(set! args (cdr args))
x) ) )
(define (endchunk chunk)
(when (pair? chunk)
(push
(if (= 1 (length chunk))
`(##sys#write-char-0 ,(car chunk) ,%out)
`(##sys#print ,(reverse-list->string chunk) #f ,%out)))))
(define (push exp)
(set! code (cons exp code)))
(let loop ((chunk '()))
(cond ((>= index len)
(unless (null? args)
(fail #f "too many arguments to formatted output procedure"))
(endchunk chunk)
`(,%let ((,%out ,out))
(##sys#check-output-port ,%out #t ',func)
,@(reverse code)))
(else
(let ((c (fetch)))
(if (eq? c #\~)
(let ((dchar (fetch)))
(endchunk chunk)
(case (char-upcase dchar)
((#\S) (push `(##sys#print ,(next) #t ,%out)))
((#\A) (push `(##sys#print ,(next) #f ,%out)))
((#\C) (push `(##sys#write-char-0 ,(next) ,%out)))
((#\B)
(push
`(##sys#print (,%number->string ,(next) 2)
#f ,%out)))
((#\O)
(push
`(##sys#print (,%number->string ,(next) 8)
#f ,%out)))
((#\X)
(push
`(##sys#print (,%number->string ,(next) 16)
#f ,%out)))
((#\!) (push `(##sys#flush-output ,%out)))
((#\?)
(let* ([fstr (next)]
[lst (next)] )
(push `(##sys#apply ,%fprintf ,%out ,fstr ,lst))))
((#\~) (push `(##sys#write-char-0 #\~ ,%out)))
((#\% #\N) (push `(##sys#write-char-0 #\newline ,%out)))
(else
(if (char-whitespace? dchar)
(let skip ((c (fetch)))
(if (char-whitespace? c)
(skip (fetch))
(set! index (sub1 index))))
(fail #t "illegal format-string character `~c'" dchar) ) ) )
(loop '()) )
(loop (cons c chunk)))))))))))))
(define-internal-compiler-syntax ((foldr #%foldr) x r c)
(pair?)
(if (and (fx= (length x) 4)
(let ((f (cadr x))
(z (caddr x))
(lst (cadddr x))
(%let* (r 'let*))
(%let (r 'let))
(%pair? (r 'pair?))
(%if (r 'if))
(loopvar (gensym "foldr"))
(lstvar (gensym)))
`(,%let* ((,lstvar ,lst))
(##core#check (##sys#check-list ,lstvar (##core#quote foldr)))
(,%let ,loopvar ((,lstvar ,lstvar))
(,%if (,%pair? ,lstvar)
(,f (##sys#slot ,lstvar 0)
(##core#app ,loopvar (##sys#slot ,lstvar 1)))
,z))))
x))
(define-internal-compiler-syntax ((foldl #%foldl) x r c)
(pair?)
(if (and (fx= (length x) 4)
(let ((f (cadr x))
(z (caddr x))
(lst (cadddr x))
(%let* (r 'let*))
(%let (r 'let))
(%if (r 'if))
(%pair? (r 'pair?))
(zvar (gensym))
(loopvar (gensym "foldl"))
(lstvar (gensym)))
`(,%let* ((,zvar ,z)
(,lstvar ,lst))
(##core#check (##sys#check-list ,lstvar (##core#quote foldl)))
(,%let ,loopvar ((,lstvar ,lstvar) (,zvar ,zvar))
(,%if (,%pair? ,lstvar)
(##core#app
,loopvar
(##sys#slot ,lstvar 1)
(,f ,zvar (##sys#slot ,lstvar 0)))
,zvar))))
x))
|
67ad4f187a2c6c3e21bf23813454d2bbd766b1b3cfacb7e4cd58afc4a87a84a3 | Clojure2D/clojure2d-examples | ray.clj | (ns rt4.the-next-week.ch04c.ray
(:require [fastmath.vector :as v]
[fastmath.core :as m]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(defprotocol RayProto
(at [ray t]))
(defrecord Ray [origin direction ^double time]
RayProto
(at [_ t] (v/add origin (v/mult direction t))))
(defn ray
([m] (map->Ray (merge {:time 0.0} m)))
([origin direction] (->Ray origin direction 0.0))
([origin direction time] (->Ray origin direction time)))
| null | https://raw.githubusercontent.com/Clojure2D/clojure2d-examples/ead92d6f17744b91070e6308157364ad4eab8a1b/src/rt4/the_next_week/ch04c/ray.clj | clojure | (ns rt4.the-next-week.ch04c.ray
(:require [fastmath.vector :as v]
[fastmath.core :as m]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(defprotocol RayProto
(at [ray t]))
(defrecord Ray [origin direction ^double time]
RayProto
(at [_ t] (v/add origin (v/mult direction t))))
(defn ray
([m] (map->Ray (merge {:time 0.0} m)))
([origin direction] (->Ray origin direction 0.0))
([origin direction time] (->Ray origin direction time)))
| |
8fe893441ab876833b16898361ad30321fcd473ecffb4f75cc918996dbb6bb6e | jyh/metaprl | itt_atom_bool.mli |
* Theorems about atoms .
*
* ----------------------------------------------------------------
*
* This file is part of MetaPRL , a modular , higher order
* logical framework that provides a logical programming
* environment for OCaml and other languages .
*
* See the file doc / htmlman / default.html or visit /
* for more information .
*
* Copyright ( C ) 1998 , Cornell University
*
* This program is free software ; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation ; either version 2
* of the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 675 Mass Ave , Cambridge , , USA .
*
* Author :
*
* Theorems about atoms.
*
* ----------------------------------------------------------------
*
* This file is part of MetaPRL, a modular, higher order
* logical framework that provides a logical programming
* environment for OCaml and other languages.
*
* See the file doc/htmlman/default.html or visit /
* for more information.
*
* Copyright (C) 1998 Jason Hickey, Cornell University
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Author: Jason Hickey
*
*)
extends Itt_atom
extends Itt_bool
open Tactic_type.Tactic
prec prec_eq_atom
declare eq_atom{'x; 'y}
topval reduce_eq_atom : conv
* -*-
* Local Variables :
* Caml - master : " nl "
* End :
* -*-
* -*-
* Local Variables:
* Caml-master: "nl"
* End:
* -*-
*)
| null | https://raw.githubusercontent.com/jyh/metaprl/51ba0bbbf409ecb7f96f5abbeb91902fdec47a19/theories/itt/core/itt_atom_bool.mli | ocaml |
* Theorems about atoms .
*
* ----------------------------------------------------------------
*
* This file is part of MetaPRL , a modular , higher order
* logical framework that provides a logical programming
* environment for OCaml and other languages .
*
* See the file doc / htmlman / default.html or visit /
* for more information .
*
* Copyright ( C ) 1998 , Cornell University
*
* This program is free software ; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation ; either version 2
* of the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 675 Mass Ave , Cambridge , , USA .
*
* Author :
*
* Theorems about atoms.
*
* ----------------------------------------------------------------
*
* This file is part of MetaPRL, a modular, higher order
* logical framework that provides a logical programming
* environment for OCaml and other languages.
*
* See the file doc/htmlman/default.html or visit /
* for more information.
*
* Copyright (C) 1998 Jason Hickey, Cornell University
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Author: Jason Hickey
*
*)
extends Itt_atom
extends Itt_bool
open Tactic_type.Tactic
prec prec_eq_atom
declare eq_atom{'x; 'y}
topval reduce_eq_atom : conv
* -*-
* Local Variables :
* Caml - master : " nl "
* End :
* -*-
* -*-
* Local Variables:
* Caml-master: "nl"
* End:
* -*-
*)
| |
ba022ee1bf788d6884b10dcfc6fb88914f424ed82b88944f375dbcb9e1dc06f4 | input-output-hk/cardano-sl | Timer.hs | # LANGUAGE RecordWildCards #
| Restartable , STM - based dynamic timer build on top of ` Pos . Util . Timer . Timer ` .
module Pos.Util.Timer
( Timer
, newTimer
, waitTimer
, startTimer
) where
import Control.Concurrent.STM (readTVar, registerDelay, retry)
import Data.Time.Units (TimeUnit, toMicroseconds)
import Universum
newtype Timer = Timer { timerSemaphore :: TVar (TVar Bool) }
-- | Construct new `Timer`.
newTimer :: MonadIO m => m Timer
newTimer = Timer <$> (newTVarIO True >>= newTVarIO)
| Wait for the duration associated with the Timer that passed since the last
-- time `startTimer` was called.
waitTimer :: Timer -> STM ()
waitTimer Timer{..} = do
done <- readTVar =<< readTVar timerSemaphore
unless done retry
-- | Set the time duration of the underlying timer and start the underlying
-- timer.
startTimer :: (MonadIO m, TimeUnit t) => t -> Timer -> m ()
startTimer time Timer{..} =
(liftIO . registerDelay . fromIntegral . toMicroseconds $ time)
>>= atomically . writeTVar timerSemaphore
| null | https://raw.githubusercontent.com/input-output-hk/cardano-sl/1499214d93767b703b9599369a431e67d83f10a2/util/src/Pos/Util/Timer.hs | haskell | | Construct new `Timer`.
time `startTimer` was called.
| Set the time duration of the underlying timer and start the underlying
timer. | # LANGUAGE RecordWildCards #
| Restartable , STM - based dynamic timer build on top of ` Pos . Util . Timer . Timer ` .
module Pos.Util.Timer
( Timer
, newTimer
, waitTimer
, startTimer
) where
import Control.Concurrent.STM (readTVar, registerDelay, retry)
import Data.Time.Units (TimeUnit, toMicroseconds)
import Universum
newtype Timer = Timer { timerSemaphore :: TVar (TVar Bool) }
newTimer :: MonadIO m => m Timer
newTimer = Timer <$> (newTVarIO True >>= newTVarIO)
| Wait for the duration associated with the Timer that passed since the last
waitTimer :: Timer -> STM ()
waitTimer Timer{..} = do
done <- readTVar =<< readTVar timerSemaphore
unless done retry
startTimer :: (MonadIO m, TimeUnit t) => t -> Timer -> m ()
startTimer time Timer{..} =
(liftIO . registerDelay . fromIntegral . toMicroseconds $ time)
>>= atomically . writeTVar timerSemaphore
|
20430597a348e3bf1eb7c916e70c64c53a5d7e2ac5ae442b7c51a067378a9c31 | 0xYUANTI/eon | test_rec.erl | -module(test_rec).
-behaviour(eon_type_rec).
-include_lib("stdlib2/include/prelude.hrl").
-export([name/0, parameters/0, decl/2]).
name() -> some_obj.
parameters() -> [foo].
decl(_Obj, Params) ->
Min = ?unlift(eon:get(Params, foo)),
[ foo, {test_prim, [min,Min, max,Min]}
, bar, {test_list, [min,0, max,1]}
].
| null | https://raw.githubusercontent.com/0xYUANTI/eon/528a23513921e2be99486210dda60e8c8e069c2d/test/test_rec.erl | erlang | -module(test_rec).
-behaviour(eon_type_rec).
-include_lib("stdlib2/include/prelude.hrl").
-export([name/0, parameters/0, decl/2]).
name() -> some_obj.
parameters() -> [foo].
decl(_Obj, Params) ->
Min = ?unlift(eon:get(Params, foo)),
[ foo, {test_prim, [min,Min, max,Min]}
, bar, {test_list, [min,0, max,1]}
].
| |
29167f3a2c188272e573b4e0995411d5333fb1479cc40c3acf3bc4c7a507c38f | VictorNicollet/Ohm | action_Endpoint.ml | Ohm is © 2012
open Util
open BatPervasives
open Action_Common
module Server = Action_Server
module Args = Action_Args
type ('server,'args) endpoint = 'server -> 'args -> string
let url endpoint s a = endpoint s a
let endpoint_of_controller (server,prefix,parse) =
let prefix = path_clean (BatString.lowercase prefix) in
fun s a ->
String.concat "/"
( Server.server_root server s :: prefix ::
List.map (Netencoding.Url.encode ~plus:false) (Args.generate parse a))
let rewrite f str sub s a =
let url = f s a in
let _, url = BatString.replace url str sub in
url
let setargs f a s () =
f s a
| null | https://raw.githubusercontent.com/VictorNicollet/Ohm/ca90c162f6c49927c893114491f29d44aaf71feb/src/action_Endpoint.ml | ocaml | Ohm is © 2012
open Util
open BatPervasives
open Action_Common
module Server = Action_Server
module Args = Action_Args
type ('server,'args) endpoint = 'server -> 'args -> string
let url endpoint s a = endpoint s a
let endpoint_of_controller (server,prefix,parse) =
let prefix = path_clean (BatString.lowercase prefix) in
fun s a ->
String.concat "/"
( Server.server_root server s :: prefix ::
List.map (Netencoding.Url.encode ~plus:false) (Args.generate parse a))
let rewrite f str sub s a =
let url = f s a in
let _, url = BatString.replace url str sub in
url
let setargs f a s () =
f s a
| |
e9e0f171d7e32512d88e1af4280e0cb3aa0888a3b70ceb73023be1856c875d08 | AccelerationNet/arnesi | csv.lisp | ;; -*- lisp -*-
(in-package :it.bese.arnesi)
* Reading and Writing files in Comma - Seperated - Values format
;;;; Generating CSV files from lisp data
(defun princ-csv (items csv-stream
&key (quote #\")
(separator #\,)
(ignore-nulls t)
(newline +CR-LF+)
(princ #'princ-to-string))
"Write the list ITEMS to csv-stream."
(flet ((write-word (word)
(write-char quote csv-stream)
(loop
for char across (funcall princ word)
if (char= quote char) do
(progn
(write-char quote csv-stream)
(write-char quote csv-stream))
else do
(write-char char csv-stream))
(write-char quote csv-stream)))
(when items
(write-word (car items))
(dolist (i (cdr items))
(write-char separator csv-stream)
(if ignore-nulls
(when (not (null i))
(write-word i))
(write-word i)))
(write-sequence newline csv-stream))))
(defun princ-csv-to-string (items &key (quote #\")
(separator #\,)
(ignore-nulls t)
(newline +CR-LF+)
(princ #'princ-to-string))
(with-output-to-string (csv)
(princ-csv items csv
:quote quote
:separator separator
:ignore-nulls ignore-nulls
:newline newline
:princ princ
)))
;;;; Reading in CSV files
(defun parse-csv-string (line &key (separator #\,) (quote #\"))
"Parse a csv line into a list of strings using seperator as the
column seperator and quote as the string quoting character."
(let ((items '())
(offset 0)
(current-word (make-array 20
:element-type 'character
:adjustable t
:fill-pointer 0))
(state :read-word))
(loop
(when (= offset (length line))
;; all done
(ecase state
(:in-string
(error "Unterminated string."))
(:read-word
(return-from parse-csv-string
(nreverse (cons current-word items))))))
(cond
((char= separator (aref line offset))
(ecase state
(:in-string
(vector-push-extend (aref line offset) current-word))
(:read-word
(push current-word items)
(setf current-word (make-array 20
:element-type 'character
:adjustable t
:fill-pointer 0)))))
((char= quote (aref line offset))
(ecase state
(:in-string
(let ((offset+1 (1+ offset)))
(cond
((and (/= offset+1 (length line))
(char= quote (aref line offset+1)))
(vector-push-extend quote current-word)
(incf offset))
(t (setf state :read-word)))))
(:read-word
(setf state :in-string))))
(t
(vector-push-extend (aref line offset) current-word)))
(incf offset))))
Copyright ( c ) 2002 - 2006 ,
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are
;; met:
;;
;; - Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;;
;; - Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;;
- Neither the name of , nor , nor the names
;; of its contributors may be used to endorse or promote products
;; derived from this software without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| null | https://raw.githubusercontent.com/AccelerationNet/arnesi/1e7dc4cb2cad8599113c7492c78f4925e839522e/src/csv.lisp | lisp | -*- lisp -*-
Generating CSV files from lisp data
Reading in CSV files
all done
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.
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
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
LOSS OF USE ,
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. |
(in-package :it.bese.arnesi)
* Reading and Writing files in Comma - Seperated - Values format
(defun princ-csv (items csv-stream
&key (quote #\")
(separator #\,)
(ignore-nulls t)
(newline +CR-LF+)
(princ #'princ-to-string))
"Write the list ITEMS to csv-stream."
(flet ((write-word (word)
(write-char quote csv-stream)
(loop
for char across (funcall princ word)
if (char= quote char) do
(progn
(write-char quote csv-stream)
(write-char quote csv-stream))
else do
(write-char char csv-stream))
(write-char quote csv-stream)))
(when items
(write-word (car items))
(dolist (i (cdr items))
(write-char separator csv-stream)
(if ignore-nulls
(when (not (null i))
(write-word i))
(write-word i)))
(write-sequence newline csv-stream))))
(defun princ-csv-to-string (items &key (quote #\")
(separator #\,)
(ignore-nulls t)
(newline +CR-LF+)
(princ #'princ-to-string))
(with-output-to-string (csv)
(princ-csv items csv
:quote quote
:separator separator
:ignore-nulls ignore-nulls
:newline newline
:princ princ
)))
(defun parse-csv-string (line &key (separator #\,) (quote #\"))
"Parse a csv line into a list of strings using seperator as the
column seperator and quote as the string quoting character."
(let ((items '())
(offset 0)
(current-word (make-array 20
:element-type 'character
:adjustable t
:fill-pointer 0))
(state :read-word))
(loop
(when (= offset (length line))
(ecase state
(:in-string
(error "Unterminated string."))
(:read-word
(return-from parse-csv-string
(nreverse (cons current-word items))))))
(cond
((char= separator (aref line offset))
(ecase state
(:in-string
(vector-push-extend (aref line offset) current-word))
(:read-word
(push current-word items)
(setf current-word (make-array 20
:element-type 'character
:adjustable t
:fill-pointer 0)))))
((char= quote (aref line offset))
(ecase state
(:in-string
(let ((offset+1 (1+ offset)))
(cond
((and (/= offset+1 (length line))
(char= quote (aref line offset+1)))
(vector-push-extend quote current-word)
(incf offset))
(t (setf state :read-word)))))
(:read-word
(setf state :in-string))))
(t
(vector-push-extend (aref line offset) current-word)))
(incf offset))))
Copyright ( c ) 2002 - 2006 ,
- Neither the name of , nor , nor the names
" 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
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
|
b2380fa7a9eb6afab6576b6ba85cc8b95d806099e78c039f69855e7d41be7575 | ocaml/ocaml | afl-showmap-test.ml | (* TEST (* Just a test-driver *)
* native-compiler
** script
script = "sh ${test_source_directory}/has-afl-showmap.sh"
readonly_files = "harness.ml test.ml"
*** setup-ocamlopt.byte-build-env
**** ocamlopt.byte
module = "test.ml"
flags = "-afl-instrument"
***** ocamlopt.byte
module = ""
program = "${test_build_directory}/test"
flags = "-afl-inst-ratio 0"
all_modules = "test.cmx harness.ml"
****** run
*)
| null | https://raw.githubusercontent.com/ocaml/ocaml/58f12bcd918446c3ebf397669bda0c3b09205c76/testsuite/tests/afl-instrumentation/afl-showmap-test.ml | ocaml | TEST (* Just a test-driver | * native-compiler
** script
script = "sh ${test_source_directory}/has-afl-showmap.sh"
readonly_files = "harness.ml test.ml"
*** setup-ocamlopt.byte-build-env
**** ocamlopt.byte
module = "test.ml"
flags = "-afl-instrument"
***** ocamlopt.byte
module = ""
program = "${test_build_directory}/test"
flags = "-afl-inst-ratio 0"
all_modules = "test.cmx harness.ml"
****** run
*)
|
5f712603a78f828c75f81e87363faf9f7e5dbe7bc9634caa646e729578813792 | mbj/stratosphere | CaptchaConfigProperty.hs | module Stratosphere.WAFv2.RuleGroup.CaptchaConfigProperty (
module Exports, CaptchaConfigProperty(..), mkCaptchaConfigProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import {-# SOURCE #-} Stratosphere.WAFv2.RuleGroup.ImmunityTimePropertyProperty as Exports
import Stratosphere.ResourceProperties
data CaptchaConfigProperty
= CaptchaConfigProperty {immunityTimeProperty :: (Prelude.Maybe ImmunityTimePropertyProperty)}
mkCaptchaConfigProperty :: CaptchaConfigProperty
mkCaptchaConfigProperty
= CaptchaConfigProperty {immunityTimeProperty = Prelude.Nothing}
instance ToResourceProperties CaptchaConfigProperty where
toResourceProperties CaptchaConfigProperty {..}
= ResourceProperties
{awsType = "AWS::WAFv2::RuleGroup.CaptchaConfig",
supportsTags = Prelude.False,
properties = Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "ImmunityTimeProperty"
Prelude.<$> immunityTimeProperty])}
instance JSON.ToJSON CaptchaConfigProperty where
toJSON CaptchaConfigProperty {..}
= JSON.object
(Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "ImmunityTimeProperty"
Prelude.<$> immunityTimeProperty]))
instance Property "ImmunityTimeProperty" CaptchaConfigProperty where
type PropertyType "ImmunityTimeProperty" CaptchaConfigProperty = ImmunityTimePropertyProperty
set newValue CaptchaConfigProperty {}
= CaptchaConfigProperty
{immunityTimeProperty = Prelude.pure newValue, ..} | null | https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/wafv2/gen/Stratosphere/WAFv2/RuleGroup/CaptchaConfigProperty.hs | haskell | # SOURCE # | module Stratosphere.WAFv2.RuleGroup.CaptchaConfigProperty (
module Exports, CaptchaConfigProperty(..), mkCaptchaConfigProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
data CaptchaConfigProperty
= CaptchaConfigProperty {immunityTimeProperty :: (Prelude.Maybe ImmunityTimePropertyProperty)}
mkCaptchaConfigProperty :: CaptchaConfigProperty
mkCaptchaConfigProperty
= CaptchaConfigProperty {immunityTimeProperty = Prelude.Nothing}
instance ToResourceProperties CaptchaConfigProperty where
toResourceProperties CaptchaConfigProperty {..}
= ResourceProperties
{awsType = "AWS::WAFv2::RuleGroup.CaptchaConfig",
supportsTags = Prelude.False,
properties = Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "ImmunityTimeProperty"
Prelude.<$> immunityTimeProperty])}
instance JSON.ToJSON CaptchaConfigProperty where
toJSON CaptchaConfigProperty {..}
= JSON.object
(Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "ImmunityTimeProperty"
Prelude.<$> immunityTimeProperty]))
instance Property "ImmunityTimeProperty" CaptchaConfigProperty where
type PropertyType "ImmunityTimeProperty" CaptchaConfigProperty = ImmunityTimePropertyProperty
set newValue CaptchaConfigProperty {}
= CaptchaConfigProperty
{immunityTimeProperty = Prelude.pure newValue, ..} |
e42d247dd531fb0c57303c43403051ddf3f3a5e83deae855e5a025ba9580a6e9 | kmi/irs | new.lisp | Mode : Lisp ; Package :
File created in WebOnto
(in-package "OCML")
(in-ontology monitoring-events)
(def-class event ( )
((has-process-instance-id :type string)
(has-timestamp :type list-date-and-time)
(generated-by :type string))
)
| null | https://raw.githubusercontent.com/kmi/irs/e1b8d696f61c6b6878c0e92d993ed549fee6e7dd/ontologies/domains/monitoring-events/new.lisp | lisp | Package : |
File created in WebOnto
(in-package "OCML")
(in-ontology monitoring-events)
(def-class event ( )
((has-process-instance-id :type string)
(has-timestamp :type list-date-and-time)
(generated-by :type string))
)
|
161df0c5161971befeaf9e0dc8b0334e4eb804ee6e4a2755cac8902d392f14a0 | GaloisInc/daedalus | Types.hs | # LANGUAGE LambdaCase #
module Types where
-- system:
import System.Exit
---- types, constants --------------------------------------------------------
data Tool =
T { t_name :: String
, t_cmd_exec :: FilePath
, t_cmd_mkArgs :: FilePath -> [String]
, t_timeoutInSecs :: Int
, t_proj :: IO String -- get stdout
-> IO String -- get stderr
-> IO MetaData -- get metadata
-> IO String -- the result of tool (as string)
-- FIXME: this may add unnecessary 'needs'
, t_cmp :: FilePath -> FilePath -> IO Compared
}
-- FIXME: name things as an 'isvalid' (not 'result') projection
and abstract over projections ( e.g. , have multiple , named projs )
data ErrorType = EQ_Variance
| NE_NoVariance
deriving (Eq, Read, Show)
data MetaData = MetaData { exitCode :: ExitCode
in msecs
}
deriving (Eq,Show,Read)
---- Compared ... ------------------------------------------------------------
data Compared = Equivalent
| NotEquivalent String
deriving (Eq, Read, Show)
isEquivalent :: Compared -> Bool
isEquivalent Equivalent = True
isEquivalent _ = False
boolToCompared b = if b then
Equivalent
else
NotEquivalent ""
ppCompared = \case
Equivalent -> "Equivalent"
NotEquivalent s -> "NotEquivalent\n" ++ s
isPPEquivalent :: String -> Bool
isPPEquivalent s =
case lines s of
"Equivalent":_ -> True
"NotEquivalent":_ -> False
_ -> error "malformed pretty-print of Compared"
| null | https://raw.githubusercontent.com/GaloisInc/daedalus/016da6b2de23747e48642f6ece79c07b436ef5d1/formats/pdf/old/driver/test/src/run-testset/Types.hs | haskell | system:
-- types, constants --------------------------------------------------------
get stdout
get stderr
get metadata
the result of tool (as string)
FIXME: this may add unnecessary 'needs'
FIXME: name things as an 'isvalid' (not 'result') projection
-- Compared ... ------------------------------------------------------------ | # LANGUAGE LambdaCase #
module Types where
import System.Exit
data Tool =
T { t_name :: String
, t_cmd_exec :: FilePath
, t_cmd_mkArgs :: FilePath -> [String]
, t_timeoutInSecs :: Int
, t_cmp :: FilePath -> FilePath -> IO Compared
}
and abstract over projections ( e.g. , have multiple , named projs )
data ErrorType = EQ_Variance
| NE_NoVariance
deriving (Eq, Read, Show)
data MetaData = MetaData { exitCode :: ExitCode
in msecs
}
deriving (Eq,Show,Read)
data Compared = Equivalent
| NotEquivalent String
deriving (Eq, Read, Show)
isEquivalent :: Compared -> Bool
isEquivalent Equivalent = True
isEquivalent _ = False
boolToCompared b = if b then
Equivalent
else
NotEquivalent ""
ppCompared = \case
Equivalent -> "Equivalent"
NotEquivalent s -> "NotEquivalent\n" ++ s
isPPEquivalent :: String -> Bool
isPPEquivalent s =
case lines s of
"Equivalent":_ -> True
"NotEquivalent":_ -> False
_ -> error "malformed pretty-print of Compared"
|
a633d0faa4dec3346ca85bfecb8eadd4ff141f9db1052a52d0de553cac37eb13 | spechub/Hets | HTkProofDetails.hs | |
Module : ./GUI / HTkProofDetails.hs
Description : GUI for showing and saving proof details .
Copyright : ( c ) 2006
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : needs POSIX
Additional window used by for displaying proof details .
Module : ./GUI/HTkProofDetails.hs
Description : GUI for showing and saving proof details.
Copyright : (c) Rainer Grabbe 2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : needs POSIX
Additional window used by 'GUI.ProofManagement' for displaying proof details.
-}
module GUI.HTkProofDetails (doShowProofDetails) where
import qualified Common.Doc as Pretty
import qualified Common.OrderedMap as OMap
import Common.AS_Annotation
import qualified Data.Map as Map
import Data.Maybe
import Data.List
import Data.IORef
import GUI.Utils (fileSaveDialog)
import System.Directory
import GUI.HTkUtils
import Proofs.AbstractState
import Logic.Comorphism
import Logic.Prover
import Static.GTheory
-- * record structures and basic functions for handling
{- |
Record structure containing proof details for a single proof.
-}
data GoalDescription = GoalDescription {
proverInfo :: String, -- ^ standard proof details
tacticScriptText :: OpenText, -- ^ more details for tactic script
proofTreeText :: OpenText -- ^ more details for proof tree
}
{- |
Current state of a text tag providing additional information. The text can be
folded or unfolded.
-}
data OpenText = OpenText {
additionalText :: String, -- ^ additional information
textShown :: Bool, -- ^ if true, text is unfolded (default: false)
textStartPosition :: Position -- ^ start position in editor widget
}
|
Creates an initial ' GoalDescription ' filled with just the standard prover
info .
Creates an initial 'GoalDescription' filled with just the standard prover
info.
-}
emptyGoalDescription :: String -- ^ information about the used prover
^ initiated GoalDescription
emptyGoalDescription st =
GoalDescription {
proverInfo = st,
tacticScriptText = emptyOpenText,
proofTreeText = emptyOpenText }
|
Creates an empty ' OpenText ' with start position ( 0,0 ) .
Creates an empty 'OpenText' with start position (0,0).
-}
emptyOpenText :: OpenText
emptyOpenText = OpenText {
additionalText = "",
textShown = False,
textStartPosition = (Distance 0, Distance 0) }
| Determines the kind of content of a ' HTk . TextTag ' .
data Content = TacticScriptText | ProofTreeText deriving Eq
-- * GUI for show proof details
-- ** help functions
-- | Return number of new lines in a string.
numberOfLines :: String
-> Int
numberOfLines =
foldr (\ ch -> if ch == '\n' then (+ 1) else id) 0
{- |
Change the x-value of a 'Position' by a given arithmetical function and value.
-}
changePosition :: (Int -> Int -> Int) -- ^ mostly add or subtract values
-> Int -- ^ (difference) value
-> Position -- ^ old position
-> Position -- ^ changed position with new x-value
changePosition f diff (Distance posX, Distance posY) =
(Distance $ f posX diff, Distance posY)
{- |
Indentation of a 'String' (also multiple lines) by a number of spaces.
-}
indent :: Int -- ^ number of spaces
^ input
-> Pretty.Doc -- ^ output document
indent numSp st =
Pretty.text (replicate numSp ' ') <>
(Pretty.vcat . map Pretty.text . lines) st
{- |
Standard indent width.
-}
stdIndent :: Int
stdIndent = 4
|
An item of thmStatus will be put into ' GoalDescription ' structure .
Pretty printing of proof details , adding additional information
for text tags .
An item of thmStatus will be put into 'GoalDescription' structure.
Pretty printing of proof details, adding additional information
for text tags.
-}
fillGoalDescription :: (AnyComorphism, BasicProof)
-> GoalDescription -- ^ contents in pretty format
fillGoalDescription (cmo, basicProof) =
let gd = indent stdIndent $ show $ printCmWStat (cmo, basicProof)
stat str = Pretty.text "Status:" Pretty.<+> Pretty.text str
printCmWStat (c, bp) =
Pretty.text "Com:" Pretty.<+> Pretty.text (show c)
Pretty.$+$ indent stdIndent (show $ printBP bp)
printBP bp = case bp of
BasicProof _ ps ->
stat (show $ goalStatus ps) Pretty.$+$
(case goalStatus ps of
Proved _ -> Pretty.text "Used axioms:" Pretty.<+>
Pretty.fsep (Pretty.punctuate Pretty.comma
$ map (Pretty.text . show) $ usedAxioms ps)
Pretty.$+$ Pretty.text "Used time:" Pretty.<+>
Pretty.text (show $ usedTime ps)
_ -> Pretty.empty)
Pretty.$+$ Pretty.text "Prover:" Pretty.<+>
Pretty.text (usedProver ps)
otherProof -> stat (show otherProof)
printTS bp = case bp of
BasicProof _ ps ->
indent (2 * stdIndent) $ (\ (TacticScript xs) -> xs) $
tacticScript ps
_ -> Pretty.empty
printPT bp = case bp of
BasicProof _ ps ->
indent (2 * stdIndent) $ show $ proofTree ps
_ -> Pretty.empty
in (emptyGoalDescription $ show gd) {
tacticScriptText = emptyOpenText {
additionalText = show $ printTS basicProof },
proofTreeText = emptyOpenText {
additionalText = show $ printPT basicProof } }
|
Gets real ' EndOfText ' index at the char position after ( in x - direction )
the last written text . This is because ' EndOfText ' only gives a value where a
text would be after an imaginary newline .
Gets real 'EndOfText' index at the char position after (in x-direction)
the last written text. This is because 'EndOfText' only gives a value where a
text would be after an imaginary newline.
-}
getRealEndOfTextIndex :: Editor -- ^ the editor whose end index is determined
-> IO Position -- ^ position behind last char in widget
getRealEndOfTextIndex ed = do
(Distance eotX, _) <- getIndexPosition ed EndOfText
lineBefore <- getTextLine ed $ IndexPos (Distance (eotX - 1), 0)
return (Distance eotX - 1, Distance $ length lineBefore)
{- |
For a given Ordered Map containing all proof values, this function adapts the
text positions lying behind after a given reference position. This is called
when a position in the text is moved after clicking a text tag button.
-}
adaptTextPositions :: (Int -> Int -> Int) -- ^ mostly add or subtract values
-> Int -- ^ (difference) value
-> Position -- ^ reference Position
-> OMap.OMap (String, Int) GoalDescription
-- ^ Map for all proofs
-> OMap.OMap (String, Int) GoalDescription -- ^ adapted Map
adaptTextPositions f diff pos =
OMap.map $ \ gDesc ->
let tst = tacticScriptText gDesc
ptt = proofTreeText gDesc
in gDesc {
tacticScriptText = if textStartPosition tst > pos
then tst { textStartPosition = changePosition f diff $
textStartPosition tst }
else tst,
proofTreeText = if textStartPosition ptt > pos
then ptt { textStartPosition = changePosition f diff $
textStartPosition ptt }
else ptt }
-- ** main GUI
{- |
Called whenever the button /Show proof details/ is clicked.
-}
doShowProofDetails :: ProofState -> IO ()
doShowProofDetails prGUISt =
do
let thName = theoryName prGUISt
winTitleStr = "Proof Details of Selected Goals from Theory " ++ thName
win <- createToplevel [text winTitleStr]
bFrame <- newFrame win [relief Groove, borderwidth (cm 0.05)]
winTitle <- newLabel bFrame [text winTitleStr,
font (Helvetica, Roman, 18 :: Int)]
btnBox <- newHBox bFrame []
tsBut <- newButton btnBox [text expand_tacticScripts, width 18]
ptBut <- newButton btnBox [text expand_proofTrees, width 18]
sBut <- newButton btnBox [text "Save", width 12]
qBut <- newButton btnBox [text "Close", width 12]
pack winTitle [Side AtTop, Expand Off, PadY 10]
(sb, ed) <- newScrollBox bFrame
(`newEditor` [state Normal, size (80, 40)]) []
ed # state Disabled
pack bFrame [Side AtTop, Expand On, Fill Both]
pack sb [Side AtTop, Expand On, Fill Both]
pack ed [Side AtTop, Expand On, Fill Both]
pack btnBox [Side AtTop, Expand On, Fill X]
pack tsBut [PadX 5, PadY 5]
pack ptBut [PadX 5, PadY 5]
pack sBut [PadX 5, PadY 5]
pack qBut [PadX 8, PadY 5]
G_theory _ _ _ _ sSens _ <- return $ selectedTheory prGUISt
let sttDesc = "Tactic script"
sptDesc = "Proof tree"
sens = OMap.filter (not . isAxiom) sSens
elementMap = foldr insertSenSt Map.empty (reverse $ OMap.toList sens)
insertSenSt (gN, st) resOMap =
foldl (flip $ \ (s2, ind) -> OMap.insert (gN, ind) $
fillGoalDescription s2)
resOMap $
zip (sortBy (\ (_, a) (_, b) -> compare a b) $ thmStatus st)
[(0 :: Int) ..]
stateRef <- newIORef elementMap
ed # state Normal
mapM_ (\ ((gName, ind), goalDesc) -> do
when (ind == 0) $
appendText ed $ replicate 75 '-' ++ "\n" ++ gName ++ "\n"
appendText ed $ proverInfo goalDesc ++ "\n"
opTextTS <- addTextTagButton sttDesc (tacticScriptText goalDesc)
TacticScriptText ed (gName, ind) stateRef
opTextPT <- addTextTagButton sptDesc (proofTreeText goalDesc)
ProofTreeText ed (gName, ind) stateRef
appendText ed "\n"
let goalDesc' = goalDesc { tacticScriptText = opTextTS,
proofTreeText = opTextPT }
modifyIORef stateRef (OMap.update (\ _ -> Just goalDesc') (gName, ind))
) $ OMap.toList elementMap
ed # state Disabled
(editClicked, _) <- bindSimple ed (ButtonPress (Just 1))
quit <- clicked qBut
save <- clicked sBut
toggleTacticScript <- clicked tsBut
toggleProofTree <- clicked ptBut
btnState <- newIORef (False, False)
_ <- spawnEvent $ forever
$ quit >>> destroy win
+> save >>> do
disable qBut
disable sBut
curDir <- getCurrentDirectory
let f = curDir ++ '/' : thName ++ "-proof-details.txt"
mfile <- fileSaveDialog f [ ("Text", ["*.txt"])
, ("All Files", ["*"])] Nothing
maybe done (writeTextToFile ed) mfile
enable qBut
enable sBut
done
+> toggleTacticScript >>> do
(expTS, expPT) <- readIORef btnState
tsBut # text (if expTS then expand_tacticScripts
else hide_tacticScripts)
toggleMultipleTags TacticScriptText expTS ed stateRef
writeIORef btnState (not expTS, expPT)
+> toggleProofTree >>> do
(expTS, expPT) <- readIORef btnState
ptBut # text (if expPT then expand_proofTrees
else hide_proofTrees)
toggleMultipleTags ProofTreeText expPT ed stateRef
writeIORef btnState (expTS, not expPT)
+> editClicked >>> forceFocus ed
return ()
where
expand_tacticScripts = "Expand tactic scripts"
expand_proofTrees = "Expand proof trees"
hide_tacticScripts = "Hide tactic scripts"
hide_proofTrees = "Hide proof trees"
|
Toggle all ' TextTag 's of one kind to the same state ( visible or invisible ) ,
either tactic script or proof tree .
Toggle all 'TextTag's of one kind to the same state (visible or invisible),
either tactic script or proof tree.
-}
toggleMultipleTags :: Content -- ^ kind of text tag to toggle
-> Bool -- ^ current visibility state
-> Editor
-- ^ editor window to which button will be attached
-> IORef (OMap.OMap (String, Int) GoalDescription)
-- ^ current state of all proof descriptions
-> IO ()
toggleMultipleTags content expanded ed stateRef = do
s <- readIORef stateRef
mapM_ (\ (dKey, goalDesc) -> do
let openText = if content == TacticScriptText
then tacticScriptText goalDesc
else proofTreeText goalDesc
when (textShown openText == expanded)
(toggleTextTag content ed dKey stateRef)
) $ OMap.toList s
done
|
This functions toggles the state from a given TextTag from visible to
invisible or vice versa . This depends on the current state in the ordered map
of goal descriptions . First parameter indicates whether the tactic script
or the proof tree text from a goal description will be toggled .
This functions toggles the state from a given TextTag from visible to
invisible or vice versa. This depends on the current state in the ordered map
of goal descriptions. First parameter indicates whether the tactic script
or the proof tree text from a goal description will be toggled.
-}
toggleTextTag :: Content -- ^ kind of text tag to toggle
-> Editor -- ^ editor window to which button will be attached
-> (String, Int) {- ^ key in single proof descriptions
(goal name and index) -}
-> IORef (OMap.OMap (String, Int) GoalDescription)
-- ^ current state of all proof descriptions
-> IO ()
toggleTextTag content ed (gName, ind) stateRef = do
s <- readIORef stateRef
let gd = fromMaybe (emptyGoalDescription gName)
$ OMap.lookup (gName, ind) s
openText = if content == TacticScriptText then tacticScriptText gd
else proofTreeText gd
tsp = textStartPosition openText
nol = numberOfLines (additionalText openText)
if not $ textShown openText then do
ed # state Normal
insertText ed tsp $ additionalText openText
ed # state Disabled
done
else do
ed # state Normal
deleteTextRange ed tsp $ changePosition (+) nol tsp
ed # state Disabled
done
let openText' = openText { textShown = not $ textShown openText }
s' = OMap.update
(\ _ -> Just $ if content == TacticScriptText
then gd { tacticScriptText = openText' }
else gd { proofTreeText = openText' } )
(gName, ind) s
writeIORef stateRef $ adaptTextPositions
(if textShown openText then (-) else (+))
nol tsp s'
|
A button in form of a text tag will be added to the specified editor window .
The events for clicking on a button are set up : adding or removing
additional text lines by alternately clicking . All positions of text lying
behind have to be adapted .
The current state of text tags is stored and modified in ' IORef ' .
Initial call of this function returns an ' OpenText ' containing the status of
the added text tag button .
A button in form of a text tag will be added to the specified editor window.
The events for clicking on a button are set up: adding or removing
additional text lines by alternately clicking. All positions of text lying
behind have to be adapted.
The current state of text tags is stored and modified in 'IORef'.
Initial call of this function returns an 'OpenText' containing the status of
the added text tag button.
-}
addTextTagButton :: String -- ^ caption for button
-> OpenText -- ^ conatins text to be outfolded if clicked
^ either text from or proofTree
-> Editor -- ^ editor window to which button will be attached
-> (String, Int) {- ^ key in single proof descriptions
(goal name and index) -}
-> IORef (OMap.OMap (String, Int) GoalDescription)
-- ^ current state of all proof descriptions
^ information about OpenText status
addTextTagButton cap addText content ed dKey stateRef = do
appendText ed $ replicate (2 * stdIndent) ' '
curPosStart <- getRealEndOfTextIndex ed
appendText ed cap
curPosEnd <- getRealEndOfTextIndex ed
insertNewline ed
ttag <- createTextTag ed curPosStart curPosEnd [underlined On]
(selectTextTag, _) <- bindSimple ttag (ButtonPress (Just 1))
(enterTT, _) <- bindSimple ttag Enter
(leaveTT, _) <- bindSimple ttag Leave
_ <- spawnEvent $ forever
$ selectTextTag >>> toggleTextTag content ed dKey stateRef
+> enterTT >>> do
ed # cursor hand2
done
+> leaveTT >>> do
ed # cursor xterm
done
return OpenText {additionalText = "\n" ++ additionalText addText ++ "\n",
textShown = False,
textStartPosition = curPosEnd}
| null | https://raw.githubusercontent.com/spechub/Hets/bbaa9dd2d2e5eb1f2fd3ec6c799a6dde7dee6da2/GUI/HTkProofDetails.hs | haskell | * record structures and basic functions for handling
|
Record structure containing proof details for a single proof.
^ standard proof details
^ more details for tactic script
^ more details for proof tree
|
Current state of a text tag providing additional information. The text can be
folded or unfolded.
^ additional information
^ if true, text is unfolded (default: false)
^ start position in editor widget
^ information about the used prover
* GUI for show proof details
** help functions
| Return number of new lines in a string.
|
Change the x-value of a 'Position' by a given arithmetical function and value.
^ mostly add or subtract values
^ (difference) value
^ old position
^ changed position with new x-value
|
Indentation of a 'String' (also multiple lines) by a number of spaces.
^ number of spaces
^ output document
|
Standard indent width.
^ contents in pretty format
^ the editor whose end index is determined
^ position behind last char in widget
|
For a given Ordered Map containing all proof values, this function adapts the
text positions lying behind after a given reference position. This is called
when a position in the text is moved after clicking a text tag button.
^ mostly add or subtract values
^ (difference) value
^ reference Position
^ Map for all proofs
^ adapted Map
** main GUI
|
Called whenever the button /Show proof details/ is clicked.
^ kind of text tag to toggle
^ current visibility state
^ editor window to which button will be attached
^ current state of all proof descriptions
^ kind of text tag to toggle
^ editor window to which button will be attached
^ key in single proof descriptions
(goal name and index)
^ current state of all proof descriptions
^ caption for button
^ conatins text to be outfolded if clicked
^ editor window to which button will be attached
^ key in single proof descriptions
(goal name and index)
^ current state of all proof descriptions | |
Module : ./GUI / HTkProofDetails.hs
Description : GUI for showing and saving proof details .
Copyright : ( c ) 2006
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : needs POSIX
Additional window used by for displaying proof details .
Module : ./GUI/HTkProofDetails.hs
Description : GUI for showing and saving proof details.
Copyright : (c) Rainer Grabbe 2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : needs POSIX
Additional window used by 'GUI.ProofManagement' for displaying proof details.
-}
module GUI.HTkProofDetails (doShowProofDetails) where
import qualified Common.Doc as Pretty
import qualified Common.OrderedMap as OMap
import Common.AS_Annotation
import qualified Data.Map as Map
import Data.Maybe
import Data.List
import Data.IORef
import GUI.Utils (fileSaveDialog)
import System.Directory
import GUI.HTkUtils
import Proofs.AbstractState
import Logic.Comorphism
import Logic.Prover
import Static.GTheory
data GoalDescription = GoalDescription {
}
data OpenText = OpenText {
}
|
Creates an initial ' GoalDescription ' filled with just the standard prover
info .
Creates an initial 'GoalDescription' filled with just the standard prover
info.
-}
^ initiated GoalDescription
emptyGoalDescription st =
GoalDescription {
proverInfo = st,
tacticScriptText = emptyOpenText,
proofTreeText = emptyOpenText }
|
Creates an empty ' OpenText ' with start position ( 0,0 ) .
Creates an empty 'OpenText' with start position (0,0).
-}
emptyOpenText :: OpenText
emptyOpenText = OpenText {
additionalText = "",
textShown = False,
textStartPosition = (Distance 0, Distance 0) }
| Determines the kind of content of a ' HTk . TextTag ' .
data Content = TacticScriptText | ProofTreeText deriving Eq
numberOfLines :: String
-> Int
numberOfLines =
foldr (\ ch -> if ch == '\n' then (+ 1) else id) 0
changePosition f diff (Distance posX, Distance posY) =
(Distance $ f posX diff, Distance posY)
^ input
indent numSp st =
Pretty.text (replicate numSp ' ') <>
(Pretty.vcat . map Pretty.text . lines) st
stdIndent :: Int
stdIndent = 4
|
An item of thmStatus will be put into ' GoalDescription ' structure .
Pretty printing of proof details , adding additional information
for text tags .
An item of thmStatus will be put into 'GoalDescription' structure.
Pretty printing of proof details, adding additional information
for text tags.
-}
fillGoalDescription :: (AnyComorphism, BasicProof)
fillGoalDescription (cmo, basicProof) =
let gd = indent stdIndent $ show $ printCmWStat (cmo, basicProof)
stat str = Pretty.text "Status:" Pretty.<+> Pretty.text str
printCmWStat (c, bp) =
Pretty.text "Com:" Pretty.<+> Pretty.text (show c)
Pretty.$+$ indent stdIndent (show $ printBP bp)
printBP bp = case bp of
BasicProof _ ps ->
stat (show $ goalStatus ps) Pretty.$+$
(case goalStatus ps of
Proved _ -> Pretty.text "Used axioms:" Pretty.<+>
Pretty.fsep (Pretty.punctuate Pretty.comma
$ map (Pretty.text . show) $ usedAxioms ps)
Pretty.$+$ Pretty.text "Used time:" Pretty.<+>
Pretty.text (show $ usedTime ps)
_ -> Pretty.empty)
Pretty.$+$ Pretty.text "Prover:" Pretty.<+>
Pretty.text (usedProver ps)
otherProof -> stat (show otherProof)
printTS bp = case bp of
BasicProof _ ps ->
indent (2 * stdIndent) $ (\ (TacticScript xs) -> xs) $
tacticScript ps
_ -> Pretty.empty
printPT bp = case bp of
BasicProof _ ps ->
indent (2 * stdIndent) $ show $ proofTree ps
_ -> Pretty.empty
in (emptyGoalDescription $ show gd) {
tacticScriptText = emptyOpenText {
additionalText = show $ printTS basicProof },
proofTreeText = emptyOpenText {
additionalText = show $ printPT basicProof } }
|
Gets real ' EndOfText ' index at the char position after ( in x - direction )
the last written text . This is because ' EndOfText ' only gives a value where a
text would be after an imaginary newline .
Gets real 'EndOfText' index at the char position after (in x-direction)
the last written text. This is because 'EndOfText' only gives a value where a
text would be after an imaginary newline.
-}
getRealEndOfTextIndex ed = do
(Distance eotX, _) <- getIndexPosition ed EndOfText
lineBefore <- getTextLine ed $ IndexPos (Distance (eotX - 1), 0)
return (Distance eotX - 1, Distance $ length lineBefore)
-> OMap.OMap (String, Int) GoalDescription
adaptTextPositions f diff pos =
OMap.map $ \ gDesc ->
let tst = tacticScriptText gDesc
ptt = proofTreeText gDesc
in gDesc {
tacticScriptText = if textStartPosition tst > pos
then tst { textStartPosition = changePosition f diff $
textStartPosition tst }
else tst,
proofTreeText = if textStartPosition ptt > pos
then ptt { textStartPosition = changePosition f diff $
textStartPosition ptt }
else ptt }
doShowProofDetails :: ProofState -> IO ()
doShowProofDetails prGUISt =
do
let thName = theoryName prGUISt
winTitleStr = "Proof Details of Selected Goals from Theory " ++ thName
win <- createToplevel [text winTitleStr]
bFrame <- newFrame win [relief Groove, borderwidth (cm 0.05)]
winTitle <- newLabel bFrame [text winTitleStr,
font (Helvetica, Roman, 18 :: Int)]
btnBox <- newHBox bFrame []
tsBut <- newButton btnBox [text expand_tacticScripts, width 18]
ptBut <- newButton btnBox [text expand_proofTrees, width 18]
sBut <- newButton btnBox [text "Save", width 12]
qBut <- newButton btnBox [text "Close", width 12]
pack winTitle [Side AtTop, Expand Off, PadY 10]
(sb, ed) <- newScrollBox bFrame
(`newEditor` [state Normal, size (80, 40)]) []
ed # state Disabled
pack bFrame [Side AtTop, Expand On, Fill Both]
pack sb [Side AtTop, Expand On, Fill Both]
pack ed [Side AtTop, Expand On, Fill Both]
pack btnBox [Side AtTop, Expand On, Fill X]
pack tsBut [PadX 5, PadY 5]
pack ptBut [PadX 5, PadY 5]
pack sBut [PadX 5, PadY 5]
pack qBut [PadX 8, PadY 5]
G_theory _ _ _ _ sSens _ <- return $ selectedTheory prGUISt
let sttDesc = "Tactic script"
sptDesc = "Proof tree"
sens = OMap.filter (not . isAxiom) sSens
elementMap = foldr insertSenSt Map.empty (reverse $ OMap.toList sens)
insertSenSt (gN, st) resOMap =
foldl (flip $ \ (s2, ind) -> OMap.insert (gN, ind) $
fillGoalDescription s2)
resOMap $
zip (sortBy (\ (_, a) (_, b) -> compare a b) $ thmStatus st)
[(0 :: Int) ..]
stateRef <- newIORef elementMap
ed # state Normal
mapM_ (\ ((gName, ind), goalDesc) -> do
when (ind == 0) $
appendText ed $ replicate 75 '-' ++ "\n" ++ gName ++ "\n"
appendText ed $ proverInfo goalDesc ++ "\n"
opTextTS <- addTextTagButton sttDesc (tacticScriptText goalDesc)
TacticScriptText ed (gName, ind) stateRef
opTextPT <- addTextTagButton sptDesc (proofTreeText goalDesc)
ProofTreeText ed (gName, ind) stateRef
appendText ed "\n"
let goalDesc' = goalDesc { tacticScriptText = opTextTS,
proofTreeText = opTextPT }
modifyIORef stateRef (OMap.update (\ _ -> Just goalDesc') (gName, ind))
) $ OMap.toList elementMap
ed # state Disabled
(editClicked, _) <- bindSimple ed (ButtonPress (Just 1))
quit <- clicked qBut
save <- clicked sBut
toggleTacticScript <- clicked tsBut
toggleProofTree <- clicked ptBut
btnState <- newIORef (False, False)
_ <- spawnEvent $ forever
$ quit >>> destroy win
+> save >>> do
disable qBut
disable sBut
curDir <- getCurrentDirectory
let f = curDir ++ '/' : thName ++ "-proof-details.txt"
mfile <- fileSaveDialog f [ ("Text", ["*.txt"])
, ("All Files", ["*"])] Nothing
maybe done (writeTextToFile ed) mfile
enable qBut
enable sBut
done
+> toggleTacticScript >>> do
(expTS, expPT) <- readIORef btnState
tsBut # text (if expTS then expand_tacticScripts
else hide_tacticScripts)
toggleMultipleTags TacticScriptText expTS ed stateRef
writeIORef btnState (not expTS, expPT)
+> toggleProofTree >>> do
(expTS, expPT) <- readIORef btnState
ptBut # text (if expPT then expand_proofTrees
else hide_proofTrees)
toggleMultipleTags ProofTreeText expPT ed stateRef
writeIORef btnState (expTS, not expPT)
+> editClicked >>> forceFocus ed
return ()
where
expand_tacticScripts = "Expand tactic scripts"
expand_proofTrees = "Expand proof trees"
hide_tacticScripts = "Hide tactic scripts"
hide_proofTrees = "Hide proof trees"
|
Toggle all ' TextTag 's of one kind to the same state ( visible or invisible ) ,
either tactic script or proof tree .
Toggle all 'TextTag's of one kind to the same state (visible or invisible),
either tactic script or proof tree.
-}
-> Editor
-> IORef (OMap.OMap (String, Int) GoalDescription)
-> IO ()
toggleMultipleTags content expanded ed stateRef = do
s <- readIORef stateRef
mapM_ (\ (dKey, goalDesc) -> do
let openText = if content == TacticScriptText
then tacticScriptText goalDesc
else proofTreeText goalDesc
when (textShown openText == expanded)
(toggleTextTag content ed dKey stateRef)
) $ OMap.toList s
done
|
This functions toggles the state from a given TextTag from visible to
invisible or vice versa . This depends on the current state in the ordered map
of goal descriptions . First parameter indicates whether the tactic script
or the proof tree text from a goal description will be toggled .
This functions toggles the state from a given TextTag from visible to
invisible or vice versa. This depends on the current state in the ordered map
of goal descriptions. First parameter indicates whether the tactic script
or the proof tree text from a goal description will be toggled.
-}
-> IORef (OMap.OMap (String, Int) GoalDescription)
-> IO ()
toggleTextTag content ed (gName, ind) stateRef = do
s <- readIORef stateRef
let gd = fromMaybe (emptyGoalDescription gName)
$ OMap.lookup (gName, ind) s
openText = if content == TacticScriptText then tacticScriptText gd
else proofTreeText gd
tsp = textStartPosition openText
nol = numberOfLines (additionalText openText)
if not $ textShown openText then do
ed # state Normal
insertText ed tsp $ additionalText openText
ed # state Disabled
done
else do
ed # state Normal
deleteTextRange ed tsp $ changePosition (+) nol tsp
ed # state Disabled
done
let openText' = openText { textShown = not $ textShown openText }
s' = OMap.update
(\ _ -> Just $ if content == TacticScriptText
then gd { tacticScriptText = openText' }
else gd { proofTreeText = openText' } )
(gName, ind) s
writeIORef stateRef $ adaptTextPositions
(if textShown openText then (-) else (+))
nol tsp s'
|
A button in form of a text tag will be added to the specified editor window .
The events for clicking on a button are set up : adding or removing
additional text lines by alternately clicking . All positions of text lying
behind have to be adapted .
The current state of text tags is stored and modified in ' IORef ' .
Initial call of this function returns an ' OpenText ' containing the status of
the added text tag button .
A button in form of a text tag will be added to the specified editor window.
The events for clicking on a button are set up: adding or removing
additional text lines by alternately clicking. All positions of text lying
behind have to be adapted.
The current state of text tags is stored and modified in 'IORef'.
Initial call of this function returns an 'OpenText' containing the status of
the added text tag button.
-}
^ either text from or proofTree
-> IORef (OMap.OMap (String, Int) GoalDescription)
^ information about OpenText status
addTextTagButton cap addText content ed dKey stateRef = do
appendText ed $ replicate (2 * stdIndent) ' '
curPosStart <- getRealEndOfTextIndex ed
appendText ed cap
curPosEnd <- getRealEndOfTextIndex ed
insertNewline ed
ttag <- createTextTag ed curPosStart curPosEnd [underlined On]
(selectTextTag, _) <- bindSimple ttag (ButtonPress (Just 1))
(enterTT, _) <- bindSimple ttag Enter
(leaveTT, _) <- bindSimple ttag Leave
_ <- spawnEvent $ forever
$ selectTextTag >>> toggleTextTag content ed dKey stateRef
+> enterTT >>> do
ed # cursor hand2
done
+> leaveTT >>> do
ed # cursor xterm
done
return OpenText {additionalText = "\n" ++ additionalText addText ++ "\n",
textShown = False,
textStartPosition = curPosEnd}
|
e3e7768c5a336b14c1f9318daade4b954e164bab23f32b236e165657e7944c24 | phimuemue/lambdainterpreter_haskell | PrettyPrinter.hs | module PrettyPrinter where
import Expression
import Data.Maybe
import System.Console.ANSI
setSGRAbbrev :: IO ()
setSGRAbbrev = setSGR [SetColor Foreground Vivid Green]
setSGRFunCall :: IO ()
setSGRFunCall = setSGR [SetColor Foreground Vivid Red]
setSGRFunArg :: IO ()
setSGRFunArg = setSGR [SetColor Foreground Vivid Blue]
setSGREta :: IO ()
setSGREta = setSGR [SetColor Foreground Vivid Yellow]
prettyPrint :: Expression -> IO ()
prettyPrint term = do aux False term
setSGR []
putStrLn ""
where aux plbd t = case t of
Variable abb s -> do (if isJust abb then setSGRAbbrev else return ())
putStr s
setSGR []
Abstraction eta x f -> do (if eta then setSGREta else return ())
case (x, f) of
(_, Abstraction _ _ _) -> do putStr (if plbd then " " else "\\")
putStr x
aux True f
(_, _) -> do putStr (if plbd then " " else "\\")
putStr x
putStr ". "
aux True f
setSGR []
Application beta f x -> if beta
then do (case (f, x) of
(Abstraction _ _ _, Application _ _ _) -> do putStr "("
setSGRFunCall
putStr $ show f
setSGR []
putStr ") ("
setSGRFunArg
putStr $ show x
setSGR []
putStr ")"
(Abstraction _ _ _, Abstraction _ _ _) -> do putStr "("
setSGRFunCall
putStr $ show f
setSGR []
putStr ") ("
setSGRFunArg
putStr $ show x
setSGR []
putStr ")"
(Abstraction _ _ _, _) -> do putStr "("
setSGRFunCall
putStr $ show f
setSGR []
putStr ") "
setSGRFunArg
putStr $ show x
setSGR []
(_, Variable _ _) -> do putStr $ show f
putStr " "
putStr $ show x
(_, _) -> do putStr $ show f
putStr " ("
putStr $ show x
putStr ")")
setSGR []
else case (f, x) of
(Abstraction _ _ _, Application _ _ _) -> do putStr "("
aux False f
putStr ") ("
aux False x
putStr ")"
(Abstraction _ _ _, Abstraction _ _ _) -> do putStr "("
aux False f
putStr ") ("
aux False x
putStr ")"
(Abstraction _ _ _, _) -> do putStr "("
aux False f
putStr ") "
aux False x
(_, Variable _ _) -> do aux False f
putStr " "
aux False x
(_, _) -> do aux False f
putStr " ("
aux False x
putStr ")"
| null | https://raw.githubusercontent.com/phimuemue/lambdainterpreter_haskell/1b56487f0bce422cc2a2e448dfef800a4e0a08a4/PrettyPrinter.hs | haskell | module PrettyPrinter where
import Expression
import Data.Maybe
import System.Console.ANSI
setSGRAbbrev :: IO ()
setSGRAbbrev = setSGR [SetColor Foreground Vivid Green]
setSGRFunCall :: IO ()
setSGRFunCall = setSGR [SetColor Foreground Vivid Red]
setSGRFunArg :: IO ()
setSGRFunArg = setSGR [SetColor Foreground Vivid Blue]
setSGREta :: IO ()
setSGREta = setSGR [SetColor Foreground Vivid Yellow]
prettyPrint :: Expression -> IO ()
prettyPrint term = do aux False term
setSGR []
putStrLn ""
where aux plbd t = case t of
Variable abb s -> do (if isJust abb then setSGRAbbrev else return ())
putStr s
setSGR []
Abstraction eta x f -> do (if eta then setSGREta else return ())
case (x, f) of
(_, Abstraction _ _ _) -> do putStr (if plbd then " " else "\\")
putStr x
aux True f
(_, _) -> do putStr (if plbd then " " else "\\")
putStr x
putStr ". "
aux True f
setSGR []
Application beta f x -> if beta
then do (case (f, x) of
(Abstraction _ _ _, Application _ _ _) -> do putStr "("
setSGRFunCall
putStr $ show f
setSGR []
putStr ") ("
setSGRFunArg
putStr $ show x
setSGR []
putStr ")"
(Abstraction _ _ _, Abstraction _ _ _) -> do putStr "("
setSGRFunCall
putStr $ show f
setSGR []
putStr ") ("
setSGRFunArg
putStr $ show x
setSGR []
putStr ")"
(Abstraction _ _ _, _) -> do putStr "("
setSGRFunCall
putStr $ show f
setSGR []
putStr ") "
setSGRFunArg
putStr $ show x
setSGR []
(_, Variable _ _) -> do putStr $ show f
putStr " "
putStr $ show x
(_, _) -> do putStr $ show f
putStr " ("
putStr $ show x
putStr ")")
setSGR []
else case (f, x) of
(Abstraction _ _ _, Application _ _ _) -> do putStr "("
aux False f
putStr ") ("
aux False x
putStr ")"
(Abstraction _ _ _, Abstraction _ _ _) -> do putStr "("
aux False f
putStr ") ("
aux False x
putStr ")"
(Abstraction _ _ _, _) -> do putStr "("
aux False f
putStr ") "
aux False x
(_, Variable _ _) -> do aux False f
putStr " "
aux False x
(_, _) -> do aux False f
putStr " ("
aux False x
putStr ")"
| |
1d4558b01669667defb75a41271710c1f56dfb0132557fd02136700385bdf87c | haslab/HAAP | BotNuno.hs | # LANGUAGE PatternGuards #
module BotNuno where
import LI11718
import OracleT4
import OracleT3
import OracleT2
import OracleT1
--import Test.QuickCheck.Gen
import Data.List
import Data.Maybe
--import Safe
--import Debug.Trace
bot :: Double -> Jogo -> Int -> Acao
bot t e i | p' == Nothing = Acao False True (trg>0) (trg<0) nit
| otherwise = Acao (v<vt) (v-vt>0.2) (trg>0) (trg<0) Nothing
where p = (carros e!!i)
vt = 1.6/(lookahead/3.5)
lookahead = 1.2*(7 - k_atrito (pista e))
p' = colide m (lookahead*t) (carros (e)!!i)
Mapa ((pi,pj),pe) m = mapa (e)
Peca tp _ = (m!!pj!!pi)
prc = percorre [] m (pi,pj) pe
whereAmI = dropWhile (\(_,i,_) -> i /= ponto2Pos (posicao p)) (prc++prc)
whereAmI' = dropWhile (\(_,i,_) -> i /= ponto2Pos (posicao p)) (tail whereAmI)
dr0 = dir (posicao p) (whereAmI!!1)
dr' = if length whereAmI' > 0 then dir (posicao p) (whereAmI'!!1) else dr0
trg0 = distRad (round $ direcao p) (round dr0)
trg1 = distRad (round $ direcao p) (round dr')
trg = if abs trg0 < abs trg1 then trg0 else trg1
(v,_) = componentsToArrow (velocidade p)
ntc = (round (direcao p)) `mod` 4
nit | ntc /= i = Just ntc
| otherwise = Nothing
dir :: Ponto -> (Peca,Posicao,Orientacao) -> Double
dir p0 (Peca t _,p,_) = snd $ componentsToArrow (p'.-.p0)
where p' = centroPeca t p
distRad :: Int -> Int -> Int
distRad r1 r2 = ((r2-r1) + 180) `mod` 360 - 180 | null | https://raw.githubusercontent.com/haslab/HAAP/5acf9efaf0e5f6cba1c2482e51bda703f405a86f/examples/plab/svn/2017li1g186/src/BotNuno.hs | haskell | import Test.QuickCheck.Gen
import Safe
import Debug.Trace | # LANGUAGE PatternGuards #
module BotNuno where
import LI11718
import OracleT4
import OracleT3
import OracleT2
import OracleT1
import Data.List
import Data.Maybe
bot :: Double -> Jogo -> Int -> Acao
bot t e i | p' == Nothing = Acao False True (trg>0) (trg<0) nit
| otherwise = Acao (v<vt) (v-vt>0.2) (trg>0) (trg<0) Nothing
where p = (carros e!!i)
vt = 1.6/(lookahead/3.5)
lookahead = 1.2*(7 - k_atrito (pista e))
p' = colide m (lookahead*t) (carros (e)!!i)
Mapa ((pi,pj),pe) m = mapa (e)
Peca tp _ = (m!!pj!!pi)
prc = percorre [] m (pi,pj) pe
whereAmI = dropWhile (\(_,i,_) -> i /= ponto2Pos (posicao p)) (prc++prc)
whereAmI' = dropWhile (\(_,i,_) -> i /= ponto2Pos (posicao p)) (tail whereAmI)
dr0 = dir (posicao p) (whereAmI!!1)
dr' = if length whereAmI' > 0 then dir (posicao p) (whereAmI'!!1) else dr0
trg0 = distRad (round $ direcao p) (round dr0)
trg1 = distRad (round $ direcao p) (round dr')
trg = if abs trg0 < abs trg1 then trg0 else trg1
(v,_) = componentsToArrow (velocidade p)
ntc = (round (direcao p)) `mod` 4
nit | ntc /= i = Just ntc
| otherwise = Nothing
dir :: Ponto -> (Peca,Posicao,Orientacao) -> Double
dir p0 (Peca t _,p,_) = snd $ componentsToArrow (p'.-.p0)
where p' = centroPeca t p
distRad :: Int -> Int -> Int
distRad r1 r2 = ((r2-r1) + 180) `mod` 360 - 180 |
2b54bd89b866a7dc3e662f349cf6b7291fc1094692325c2c0d55224eacb555eb | brendanhay/gogol | List.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
{-# LANGUAGE StrictData #-}
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
-- |
Module : . ShoppingContent . Content . Repricingrules . List
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
Lists the repricing rules in your Merchant Center account .
--
/See:/ < API for Shopping Reference > for @content.repricingrules.list@.
module Gogol.ShoppingContent.Content.Repricingrules.List
( -- * Resource
ContentRepricingrulesListResource,
-- ** Constructing a Request
ContentRepricingrulesList (..),
newContentRepricingrulesList,
)
where
import qualified Gogol.Prelude as Core
import Gogol.ShoppingContent.Types
-- | A resource alias for @content.repricingrules.list@ method which the
-- 'ContentRepricingrulesList' request conforms to.
type ContentRepricingrulesListResource =
"content"
Core.:> "v2.1"
Core.:> Core.Capture "merchantId" Core.Int64
Core.:> "repricingrules"
Core.:> Core.QueryParam "$.xgafv" Xgafv
Core.:> Core.QueryParam "access_token" Core.Text
Core.:> Core.QueryParam "callback" Core.Text
Core.:> Core.QueryParam "countryCode" Core.Text
Core.:> Core.QueryParam "languageCode" Core.Text
Core.:> Core.QueryParam "pageSize" Core.Int32
Core.:> Core.QueryParam "pageToken" Core.Text
Core.:> Core.QueryParam "uploadType" Core.Text
Core.:> Core.QueryParam "upload_protocol" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.Get
'[Core.JSON]
ListRepricingRulesResponse
| Lists the repricing rules in your Merchant Center account .
--
-- /See:/ 'newContentRepricingrulesList' smart constructor.
data ContentRepricingrulesList = ContentRepricingrulesList
{ -- | V1 error format.
xgafv :: (Core.Maybe Xgafv),
-- | OAuth access token.
accessToken :: (Core.Maybe Core.Text),
| JSONP
callback :: (Core.Maybe Core.Text),
-- | < CLDR country code> (e.g. \"US\"), used as a filter on repricing rules.
countryCode :: (Core.Maybe Core.Text),
| The two - letter ISO 639 - 1 language code associated with the repricing rule , used as a filter .
languageCode :: (Core.Maybe Core.Text),
-- | Required. The id of the merchant who owns the repricing rule.
merchantId :: Core.Int64,
| The maximum number of repricing rules to return . The service may return fewer than this value . If unspecified , at most 50 rules will be returned . The maximum value is 1000 ; values above 1000 will be coerced to 1000 .
pageSize :: (Core.Maybe Core.Int32),
-- | A page token, received from a previous @ListRepricingRules@ call. Provide this to retrieve the subsequent page. When paginating, all other parameters provided to @ListRepricingRules@ must match the call that provided the page token.
pageToken :: (Core.Maybe Core.Text),
| Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) .
uploadType :: (Core.Maybe Core.Text),
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
uploadProtocol :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'ContentRepricingrulesList' with the minimum fields required to make a request.
newContentRepricingrulesList ::
-- | Required. The id of the merchant who owns the repricing rule. See 'merchantId'.
Core.Int64 ->
ContentRepricingrulesList
newContentRepricingrulesList merchantId =
ContentRepricingrulesList
{ xgafv = Core.Nothing,
accessToken = Core.Nothing,
callback = Core.Nothing,
countryCode = Core.Nothing,
languageCode = Core.Nothing,
merchantId = merchantId,
pageSize = Core.Nothing,
pageToken = Core.Nothing,
uploadType = Core.Nothing,
uploadProtocol = Core.Nothing
}
instance Core.GoogleRequest ContentRepricingrulesList where
type
Rs ContentRepricingrulesList =
ListRepricingRulesResponse
type
Scopes ContentRepricingrulesList =
'[Content'FullControl]
requestClient ContentRepricingrulesList {..} =
go
merchantId
xgafv
accessToken
callback
countryCode
languageCode
pageSize
pageToken
uploadType
uploadProtocol
(Core.Just Core.AltJSON)
shoppingContentService
where
go =
Core.buildClient
( Core.Proxy ::
Core.Proxy ContentRepricingrulesListResource
)
Core.mempty
| null | https://raw.githubusercontent.com/brendanhay/gogol/fffd4d98a1996d0ffd4cf64545c5e8af9c976cda/lib/services/gogol-shopping-content/gen/Gogol/ShoppingContent/Content/Repricingrules/List.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Stability : auto-generated
* Resource
** Constructing a Request
| A resource alias for @content.repricingrules.list@ method which the
'ContentRepricingrulesList' request conforms to.
/See:/ 'newContentRepricingrulesList' smart constructor.
| V1 error format.
| OAuth access token.
| < CLDR country code> (e.g. \"US\"), used as a filter on repricing rules.
| Required. The id of the merchant who owns the repricing rule.
| A page token, received from a previous @ListRepricingRules@ call. Provide this to retrieve the subsequent page. When paginating, all other parameters provided to @ListRepricingRules@ must match the call that provided the page token.
| Upload protocol for media (e.g. \"raw\", \"multipart\").
| Creates a value of 'ContentRepricingrulesList' with the minimum fields required to make a request.
| Required. The id of the merchant who owns the repricing rule. See 'merchantId'. | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Module : . ShoppingContent . Content . Repricingrules . List
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
Lists the repricing rules in your Merchant Center account .
/See:/ < API for Shopping Reference > for @content.repricingrules.list@.
module Gogol.ShoppingContent.Content.Repricingrules.List
ContentRepricingrulesListResource,
ContentRepricingrulesList (..),
newContentRepricingrulesList,
)
where
import qualified Gogol.Prelude as Core
import Gogol.ShoppingContent.Types
type ContentRepricingrulesListResource =
"content"
Core.:> "v2.1"
Core.:> Core.Capture "merchantId" Core.Int64
Core.:> "repricingrules"
Core.:> Core.QueryParam "$.xgafv" Xgafv
Core.:> Core.QueryParam "access_token" Core.Text
Core.:> Core.QueryParam "callback" Core.Text
Core.:> Core.QueryParam "countryCode" Core.Text
Core.:> Core.QueryParam "languageCode" Core.Text
Core.:> Core.QueryParam "pageSize" Core.Int32
Core.:> Core.QueryParam "pageToken" Core.Text
Core.:> Core.QueryParam "uploadType" Core.Text
Core.:> Core.QueryParam "upload_protocol" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.Get
'[Core.JSON]
ListRepricingRulesResponse
| Lists the repricing rules in your Merchant Center account .
data ContentRepricingrulesList = ContentRepricingrulesList
xgafv :: (Core.Maybe Xgafv),
accessToken :: (Core.Maybe Core.Text),
| JSONP
callback :: (Core.Maybe Core.Text),
countryCode :: (Core.Maybe Core.Text),
| The two - letter ISO 639 - 1 language code associated with the repricing rule , used as a filter .
languageCode :: (Core.Maybe Core.Text),
merchantId :: Core.Int64,
| The maximum number of repricing rules to return . The service may return fewer than this value . If unspecified , at most 50 rules will be returned . The maximum value is 1000 ; values above 1000 will be coerced to 1000 .
pageSize :: (Core.Maybe Core.Int32),
pageToken :: (Core.Maybe Core.Text),
| Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) .
uploadType :: (Core.Maybe Core.Text),
uploadProtocol :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newContentRepricingrulesList ::
Core.Int64 ->
ContentRepricingrulesList
newContentRepricingrulesList merchantId =
ContentRepricingrulesList
{ xgafv = Core.Nothing,
accessToken = Core.Nothing,
callback = Core.Nothing,
countryCode = Core.Nothing,
languageCode = Core.Nothing,
merchantId = merchantId,
pageSize = Core.Nothing,
pageToken = Core.Nothing,
uploadType = Core.Nothing,
uploadProtocol = Core.Nothing
}
instance Core.GoogleRequest ContentRepricingrulesList where
type
Rs ContentRepricingrulesList =
ListRepricingRulesResponse
type
Scopes ContentRepricingrulesList =
'[Content'FullControl]
requestClient ContentRepricingrulesList {..} =
go
merchantId
xgafv
accessToken
callback
countryCode
languageCode
pageSize
pageToken
uploadType
uploadProtocol
(Core.Just Core.AltJSON)
shoppingContentService
where
go =
Core.buildClient
( Core.Proxy ::
Core.Proxy ContentRepricingrulesListResource
)
Core.mempty
|
3dd03da59f203ac492ef33c3ba17e74b5a4a64938ac29dc54b9388c46dbd4aeb | potocpav/vSLAM | InternalMath.hs | |
Module : InternalMath
License : WTFPL
Maintainer : < >
This module contains some useful functions used here and there in this package .
It also exports a convenient debugging routine .
Module : InternalMath
License : WTFPL
Maintainer : Pavel Potocek <>
This module contains some useful functions used here and there in this package.
It also exports a convenient debugging routine.
-}
module InternalMath where
import Numeric.LinearAlgebra
import Control.Exception
-- for debugging
import System.IO.Unsafe (unsafePerformIO)
-- | Show a value into the STDOUT via the 'seq' function.
debug :: Show a => String -> a -> a
debug s a = a `seq` unsafePerformIO (print $ s ++ ": " ++ show a) `seq` a
infixr 1 `debug`
| A gaussian pdf . It is not used for ' GaussianCamera ' representation , because
-- some type safety would be lost. Instead, it is used to describe the feature
-- matching regions.
data Gauss = Gauss {gmu :: Vector Double, gcov :: Matrix Double} deriving (Show)
| Compute the pdf of a multivariate gaussian distribution at a given point .
normalDensity :: Gauss -> Vector Double -> Double
normalDensity (Gauss mu cov) m = norm * exp e where
norm = (2*pi)**(-(fromIntegral$dim mu)/2) * (det cov)**(-0.5)
e = (-0.5) * unpack (asRow(m-mu) <> inv cov <> asColumn(m-mu))
unpack m = assert (rows m == 1 && cols m == 1) $ m @@> (0,0)
| Mahalanobis distance squared
mahalDist_sq :: Gauss -> Vector Double -> Double
mahalDist_sq (Gauss mu cov) x = (asRow (x-mu) <> inv cov <> asColumn(x-mu)) @@> (0,0)
-- | Un-normalized 3D-vec parametrization to an azimuth-elevation pair
vec2euler :: Vector Double -> (Double, Double)
vec2euler v = (atan2 x z, atan2 (-y) (sqrt(x*x + z*z))) where
[x,y,z] = toList v
| Azimuth - elevation parametrization to a normalized 3D - vec
euler2vec :: (Double, Double) -> Vector Double
euler2vec (theta, phi) = 3 |> [cos phi * sin theta, -sin phi, cos phi * cos theta]
-- | Construct a rotation matrix along the y axis
rotateYmat :: Double -> Matrix Double
rotateYmat a = (3><3) [ cos a, 0, sin a
, 0, 1, 0
, -sin a, 0, cos a ]
-- | Inverse depth to euclidean parametrization conversion.
-- Works only with values, not with covariance matrices.
toXYZ :: Vector Double -> Vector Double
toXYZ i = (3|> [x,y,z]) + scale (1/rho) (euler2vec (theta,phi)) where
[x,y,z,theta,phi,rho] = toList i
| The difference of two values on an unit circle . The one difference that is
-- the smallest in its absolute value is returned.
cyclicDiff :: Double -> Double -> Double
cyclicDiff a b = a - b - (fromIntegral . round $ (a-b) / (2*pi)) * (2*pi)
| null | https://raw.githubusercontent.com/potocpav/vSLAM/183415d0cbd4d938d17494a15cdffa24c29142ea/InternalMath.hs | haskell | for debugging
| Show a value into the STDOUT via the 'seq' function.
some type safety would be lost. Instead, it is used to describe the feature
matching regions.
| Un-normalized 3D-vec parametrization to an azimuth-elevation pair
| Construct a rotation matrix along the y axis
| Inverse depth to euclidean parametrization conversion.
Works only with values, not with covariance matrices.
the smallest in its absolute value is returned. | |
Module : InternalMath
License : WTFPL
Maintainer : < >
This module contains some useful functions used here and there in this package .
It also exports a convenient debugging routine .
Module : InternalMath
License : WTFPL
Maintainer : Pavel Potocek <>
This module contains some useful functions used here and there in this package.
It also exports a convenient debugging routine.
-}
module InternalMath where
import Numeric.LinearAlgebra
import Control.Exception
import System.IO.Unsafe (unsafePerformIO)
debug :: Show a => String -> a -> a
debug s a = a `seq` unsafePerformIO (print $ s ++ ": " ++ show a) `seq` a
infixr 1 `debug`
| A gaussian pdf . It is not used for ' GaussianCamera ' representation , because
data Gauss = Gauss {gmu :: Vector Double, gcov :: Matrix Double} deriving (Show)
| Compute the pdf of a multivariate gaussian distribution at a given point .
normalDensity :: Gauss -> Vector Double -> Double
normalDensity (Gauss mu cov) m = norm * exp e where
norm = (2*pi)**(-(fromIntegral$dim mu)/2) * (det cov)**(-0.5)
e = (-0.5) * unpack (asRow(m-mu) <> inv cov <> asColumn(m-mu))
unpack m = assert (rows m == 1 && cols m == 1) $ m @@> (0,0)
| Mahalanobis distance squared
mahalDist_sq :: Gauss -> Vector Double -> Double
mahalDist_sq (Gauss mu cov) x = (asRow (x-mu) <> inv cov <> asColumn(x-mu)) @@> (0,0)
vec2euler :: Vector Double -> (Double, Double)
vec2euler v = (atan2 x z, atan2 (-y) (sqrt(x*x + z*z))) where
[x,y,z] = toList v
| Azimuth - elevation parametrization to a normalized 3D - vec
euler2vec :: (Double, Double) -> Vector Double
euler2vec (theta, phi) = 3 |> [cos phi * sin theta, -sin phi, cos phi * cos theta]
rotateYmat :: Double -> Matrix Double
rotateYmat a = (3><3) [ cos a, 0, sin a
, 0, 1, 0
, -sin a, 0, cos a ]
toXYZ :: Vector Double -> Vector Double
toXYZ i = (3|> [x,y,z]) + scale (1/rho) (euler2vec (theta,phi)) where
[x,y,z,theta,phi,rho] = toList i
| The difference of two values on an unit circle . The one difference that is
cyclicDiff :: Double -> Double -> Double
cyclicDiff a b = a - b - (fromIntegral . round $ (a-b) / (2*pi)) * (2*pi)
|
e199e439618080b56c79118588ca6cae9d5c5d1efe266a35ba75fd79d3537aea | imeckler/stationary | attribute.ml | open Core.Std
type t = string * string
[@@deriving sexp]
let to_string (k, v) = sprintf "%s=\"%s\"" k (String.escaped v)
let create k v = (k, v)
let class_ c = create "class" c
let href url = create "href" url
let src url = create "src" url
| null | https://raw.githubusercontent.com/imeckler/stationary/d2d6c1c1ec7d6bea63736226a7e511c0e426c5e5/src/attribute.ml | ocaml | open Core.Std
type t = string * string
[@@deriving sexp]
let to_string (k, v) = sprintf "%s=\"%s\"" k (String.escaped v)
let create k v = (k, v)
let class_ c = create "class" c
let href url = create "href" url
let src url = create "src" url
| |
72d2bd5de7eb73362af6c46479c2ff1f127e67fd707212ae6e8987cc296ddaeb | austinhaas/goalie | project.clj | (defproject com.pettomato/goalie "0.1.0"
:description "A library for unobtrusively instrumenting core.logic goals."
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.5.1"]
[org.clojure/core.logic "0.8.3"]]
:source-paths ["src/com"])
| null | https://raw.githubusercontent.com/austinhaas/goalie/6166dd05c27f5abdf5c760687d6efc110846abf1/project.clj | clojure | (defproject com.pettomato/goalie "0.1.0"
:description "A library for unobtrusively instrumenting core.logic goals."
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.5.1"]
[org.clojure/core.logic "0.8.3"]]
:source-paths ["src/com"])
| |
2260bee33f5fd283a6d954eb315c6fe2ca848f2f01a874b8e53fe62785c40450 | esl/MongooseIM | graphql_muc_SUITE.erl | -module(graphql_muc_SUITE).
-compile([export_all, nowarn_export_all]).
-import(common_helper, [unprep/1]).
-import(distributed_helper, [mim/0, require_rpc_nodes/1, rpc/4, subhost_pattern/1]).
-import(graphql_helper, [execute_command/4, execute_user_command/5, get_ok_value/2, get_err_msg/1,
get_coercion_err_msg/1, user_to_bin/1, user_to_full_bin/1, user_to_jid/1,
get_unauthorized/1, get_not_loaded/1]).
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
-include_lib("exml/include/exml.hrl").
-include_lib("jid/include/jid.hrl").
suite() ->
require_rpc_nodes([mim]) ++ escalus:suite().
all() ->
[{group, user},
{group, admin_http},
{group, admin_cli},
{group, domain_admin_muc}].
groups() ->
[{user, [], user_groups()},
{admin_http, [], admin_groups()},
{admin_cli, [], admin_groups()},
{admin_muc_configured, [], admin_muc_tests()},
{admin_muc_and_mam_configured, [], admin_muc_with_mam_tests()},
{admin_muc_not_configured, [], admin_muc_not_configured_tests()},
{user_muc_configured, [parallel], user_muc_tests()},
{user_muc_and_mam_configured, [parallel], user_muc_with_mam_tests()},
{user_muc_not_configured, [parallel], user_muc_not_configured_tests()},
{domain_admin_muc, [], domain_admin_muc_tests()}].
user_groups() ->
[{group, user_muc_configured},
{group, user_muc_and_mam_configured},
{group, user_muc_not_configured}].
admin_groups() ->
[{group, admin_muc_configured},
{group, admin_muc_and_mam_configured},
{group, admin_muc_not_configured}].
user_muc_tests() ->
[user_create_and_delete_room,
user_create_room_with_unprepped_name,
user_try_delete_nonexistent_room,
user_try_delete_room_by_not_owner,
user_try_create_instant_room_with_nonexistent_domain,
user_try_create_instant_room_with_invalid_args,
user_list_rooms,
user_try_list_rooms_for_nonexistent_domain,
user_list_room_users,
user_list_room_users_without_anonymous_mode,
user_try_list_room_users_without_permission,
user_try_list_nonexistent_room_users,
user_change_room_config,
user_try_change_nonexistent_room_config,
user_get_room_config,
user_try_get_nonexistent_room_config,
user_invite_user,
user_kick_user,
user_try_kick_user_from_nonexistent_room,
user_try_kick_user_without_moderator_resource,
user_send_message_to_room,
user_send_message_to_room_with_specified_res,
user_send_private_message,
user_without_session_send_message_to_room,
user_owner_set_user_affiliation,
user_admin_set_user_affiliation,
user_member_set_user_affiliation,
user_try_set_nonexistent_room_affiliation,
user_moderator_set_user_role,
user_participant_set_user_role,
user_try_set_nonexistent_room_role,
user_can_enter_room,
user_cannot_enter_room_with_invalid_resource,
user_can_enter_room_with_password,
user_can_exit_room,
user_list_room_affiliations,
user_try_list_room_affiliations_without_permission,
user_try_list_nonexistent_room_affiliations,
user_get_room_messages_muc_or_mam_not_configured
].
user_muc_with_mam_tests() ->
[user_get_room_messages,
user_shouldnt_store_messages_in_muc_light,
user_try_get_nonexistent_room_messages,
user_try_get_room_messages_without_permission].
user_muc_not_configured_tests() ->
[user_delete_room_muc_not_configured,
user_list_room_users_muc_not_configured,
user_change_room_config_muc_not_configured,
user_get_room_config_muc_not_configured,
user_invite_user_muc_not_configured,
user_kick_user_muc_not_configured,
user_send_message_to_room_muc_not_configured,
user_send_private_message_muc_not_configured,
user_get_room_messages_muc_or_mam_not_configured,
user_owner_set_user_affiliation_muc_not_configured,
user_moderator_set_user_role_muc_not_configured,
user_can_enter_room_muc_not_configured,
user_can_exit_room_muc_not_configured,
user_list_room_affiliations_muc_not_configured].
admin_muc_tests() ->
[admin_list_rooms,
admin_list_rooms_with_invalid_args,
admin_create_and_delete_room,
admin_create_room_with_unprepped_name,
admin_try_create_instant_room_with_nonexistent_domain,
admin_try_create_instant_room_with_nonexistent_user,
admin_try_create_instant_room_with_invalid_args,
admin_try_delete_nonexistent_room,
admin_try_delete_room_with_nonexistent_domain,
admin_try_list_rooms_for_nonexistent_domain,
admin_list_room_users,
admin_try_list_users_from_nonexistent_room,
admin_change_room_config,
admin_try_change_nonexistent_room_config,
admin_get_room_config,
admin_try_get_nonexistent_room_config,
admin_invite_user,
admin_invite_user_with_password,
admin_try_invite_user_to_nonexistent_room,
admin_kick_user,
admin_try_kick_user_from_nonexistent_room,
admin_try_kick_user_from_room_without_moderators,
admin_send_message_to_room,
admin_send_private_message,
admin_set_user_affiliation,
admin_try_set_nonexistent_room_user_affiliation,
admin_set_user_role,
admin_try_set_nonexistent_room_user_role,
admin_try_set_nonexistent_nick_role,
admin_try_set_user_role_in_room_without_moderators,
admin_make_user_enter_room,
admin_make_user_enter_room_with_password,
admin_make_user_enter_room_bare_jid,
admin_make_user_exit_room,
admin_make_user_exit_room_bare_jid,
admin_list_room_affiliations,
admin_try_list_nonexistent_room_affiliations,
admin_get_room_messages_muc_or_mam_not_configured
].
admin_muc_with_mam_tests() ->
[admin_get_room_messages,
admin_try_get_nonexistent_room_messages].
admin_muc_not_configured_tests() ->
[admin_delete_room_muc_not_configured,
admin_list_room_users_muc_not_configured,
admin_change_room_config_muc_not_configured,
admin_get_room_config_muc_not_configured,
admin_invite_user_muc_not_configured,
admin_kick_user_muc_not_configured,
admin_send_message_to_room_muc_not_configured,
admin_send_private_message_muc_not_configured,
admin_get_room_messages_muc_or_mam_not_configured,
admin_set_user_affiliation_muc_not_configured,
admin_set_user_role_muc_not_configured,
admin_make_user_enter_room_muc_not_configured,
admin_make_user_exit_room_muc_not_configured,
admin_list_room_affiliations_muc_not_configured].
domain_admin_muc_tests() ->
[admin_list_rooms,
admin_create_and_delete_room,
admin_create_room_with_unprepped_name,
admin_try_create_instant_room_with_nonexistent_domain,
admin_try_delete_nonexistent_room,
domain_admin_create_and_delete_room_no_permission,
domain_admin_list_rooms_no_permission,
admin_list_room_users,
domain_admin_list_room_users_no_permission,
admin_change_room_config,
domain_admin_change_room_config_no_permission,
admin_get_room_config,
domain_admin_get_room_config_no_permission,
admin_invite_user,
admin_invite_user_with_password,
admin_try_invite_user_to_nonexistent_room,
domain_admin_invite_user_no_permission,
admin_kick_user,
admin_try_kick_user_from_room_without_moderators,
domain_admin_kick_user_no_permission,
admin_send_message_to_room,
domain_admin_send_message_to_room_no_permission,
admin_send_private_message,
domain_admin_send_private_message_no_permission,
admin_get_room_messages,
domain_admin_get_room_messages_no_permission,
admin_set_user_affiliation,
domain_admin_set_user_affiliation_no_permission,
admin_set_user_role,
admin_try_set_nonexistent_nick_role,
admin_try_set_user_role_in_room_without_moderators,
domain_admin_set_user_role_no_permission,
admin_make_user_enter_room,
admin_make_user_enter_room_with_password,
admin_make_user_enter_room_bare_jid,
domain_admin_make_user_enter_room_no_permission,
admin_make_user_exit_room,
admin_make_user_exit_room_bare_jid,
domain_admin_make_user_exit_room_no_permission,
admin_list_room_affiliations,
domain_admin_list_room_affiliations_no_permission
].
init_per_suite(Config) ->
HostType = domain_helper:host_type(),
SecondaryHostType = domain_helper:secondary_host_type(),
Config2 = escalus:init_per_suite(Config),
Config3 = dynamic_modules:save_modules(HostType, Config2),
Config4 = dynamic_modules:save_modules(SecondaryHostType, Config3),
Config5 = ejabberd_node_utils:init(mim(), Config4),
dynamic_modules:restart(HostType, mod_disco,
config_parser_helper:default_mod_config(mod_disco)),
Config5.
end_per_suite(Config) ->
escalus_fresh:clean(),
mongoose_helper:ensure_muc_clean(),
muc_helper:unload_muc(),
dynamic_modules:restore_modules(Config),
escalus:end_per_suite(Config).
init_per_group(admin_http, Config) ->
graphql_helper:init_admin_handler(Config);
init_per_group(admin_cli, Config) ->
graphql_helper:init_admin_cli(Config);
init_per_group(domain_admin_muc, Config) ->
maybe_enable_mam(),
ensure_muc_started(),
graphql_helper:init_domain_admin_handler(Config);
init_per_group(user, Config) ->
graphql_helper:init_user(Config);
init_per_group(Group, Config) when Group =:= admin_muc_configured;
Group =:= user_muc_configured ->
disable_mam(),
ensure_muc_started(),
Config;
init_per_group(Group, Config) when Group =:= admin_muc_and_mam_configured;
Group =:= user_muc_and_mam_configured ->
case maybe_enable_mam() of
true ->
ensure_muc_started(),
ensure_muc_light_started(Config);
false ->
{skip, "No MAM backend available"}
end;
init_per_group(Group, Config) when Group =:= admin_muc_not_configured;
Group =:= user_muc_not_configured ->
maybe_enable_mam(),
ensure_muc_stopped(),
Config.
disable_mam() ->
dynamic_modules:ensure_modules(domain_helper:host_type(), [{mod_mam, stopped}]).
maybe_enable_mam() ->
case mam_helper:backend() of
disabled ->
false;
Backend ->
MAMOpts = mam_helper:config_opts(
#{backend => Backend,
muc => #{host => subhost_pattern(muc_helper:muc_host_pattern())},
async_writer => #{enabled => false}}),
dynamic_modules:ensure_modules(domain_helper:host_type(), [{mod_mam, MAMOpts}]),
true
end.
ensure_muc_started() ->
SecondaryHostType = domain_helper:secondary_host_type(),
muc_helper:load_muc(),
muc_helper:load_muc(SecondaryHostType),
mongoose_helper:ensure_muc_clean().
ensure_muc_stopped() ->
SecondaryHostType = domain_helper:secondary_host_type(),
muc_helper:unload_muc(),
muc_helper:unload_muc(SecondaryHostType).
ensure_muc_light_started(Config) ->
MucLightOpts = config_parser_helper:mod_config(mod_muc_light,
#{rooms_in_rosters => true, config_schema => custom_schema()}),
HostType = domain_helper:host_type(),
dynamic_modules:ensure_modules(HostType, [{mod_muc_light, MucLightOpts}]),
[{muc_light_host, muc_light_helper:muc_host()} | Config].
ensure_muc_light_stopped() ->
HostType = domain_helper:host_type(),
dynamic_modules:ensure_modules(HostType, [{mod_muc_light, stopped}]).
custom_schema() ->
%% Should be sorted
[{<<"background">>, <<>>, background, binary},
{<<"music">>, <<>>, music, binary},
%% Default fields
{<<"roomname">>, <<>>, roomname, binary},
{<<"subject">>, <<"Test">>, subject, binary}].
end_per_group(Group, _Config) when Group =:= user;
Group =:= admin_http;
Group =:= domain_admin_muc;
Group =:= admin_cli ->
graphql_helper:clean();
end_per_group(Group, _Config) when Group =:= admin_muc_and_mam_configured;
Group =:= user_muc_and_mam_configured ->
ensure_muc_light_stopped(),
escalus_fresh:clean();
end_per_group(_Group, _Config) ->
escalus_fresh:clean().
init_per_testcase(TC, Config) ->
escalus:init_per_testcase(TC, Config).
end_per_testcase(TC, Config) ->
escalus:end_per_testcase(TC, Config).
-define(CREATE_INSTANT_ROOM_PATH, [data, muc, createInstantRoom]).
-define(LIST_ROOMS_PATH, [data, muc, listRooms]).
-define(INVITE_USER_PATH, [data, muc, inviteUser]).
-define(KICK_USER_PATH, [data, muc, kickUser]).
-define(DELETE_ROOM_PATH, [data, muc, deleteRoom]).
-define(SEND_MESSAGE_PATH, [data, muc, sendMessageToRoom]).
-define(SEND_PRIV_MESG_PATH, [data, muc, sendPrivateMessage]).
-define(GET_MESSAGES_PATH, [data, muc, getRoomMessages]).
-define(LIST_ROOM_USERS_PATH, [data, muc, listRoomUsers]).
-define(LIST_ROOM_AFFILIATIONS_PATH, [data, muc, listRoomAffiliations]).
-define(CHANGE_ROOM_CONFIG_PATH, [data, muc, changeRoomConfiguration]).
-define(GET_ROOM_CONFIG_PATH, [data, muc, getRoomConfig]).
-define(SET_AFFILIATION_PATH, [data, muc, setUserAffiliation]).
-define(SET_ROLE_PATH, [data, muc, setUserRole]).
-define(ENTER_ROOM_PATH, [data, muc, enterRoom]).
-define(EXIT_ROOM_PATH, [data, muc, exitRoom]).
-define(NONEXISTENT_ROOM, <<"room@room">>).
-define(NONEXISTENT_ROOM2, <<"room@", (muc_helper:muc_host())/binary>>).
-define(EXTERNAL_DOMAIN_ROOM, <<"external_room@muc.", (domain_helper:secondary_domain())/binary>>).
-define(PASSWORD, <<"pa5sw0rd">>).
admin_list_rooms(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}, {bob, 1}], fun admin_list_rooms_story/3).
admin_list_rooms_story(Config, Alice, Bob) ->
Res0 = list_rooms(muc_helper:muc_host(), Alice, null, null, Config),
?assertEqual([], extract_rooms(get_ok_value(?LIST_ROOMS_PATH, Res0))),
AliceJID = jid:from_binary(escalus_client:short_jid(Alice)),
BobJID = jid:from_binary(escalus_client:short_jid(Bob)),
AliceRoom = rand_name(),
BobRoom = rand_name(),
muc_helper:create_instant_room(AliceRoom, AliceJID, <<"Ali">>, []),
muc_helper:create_instant_room(BobRoom, BobJID, <<"Bob">>, [{public_list, false}]),
Res1 = list_rooms(muc_helper:muc_host(), Alice, null, null, Config),
Rooms1 = [_, RoomB] = extract_rooms(get_ok_value(?LIST_ROOMS_PATH, Res1)),
?assertEqual(lists:sort([AliceRoom, BobRoom]), lists:sort(Rooms1)),
Res2 = list_rooms(unprep(muc_helper:muc_host()), Alice, null, null, Config),
?assertEqual(Rooms1, extract_rooms(get_ok_value(?LIST_ROOMS_PATH, Res2))),
Res3 = list_rooms(muc_helper:muc_host(), Alice, 1, 1, Config),
?assertEqual([RoomB], extract_rooms(get_ok_value(?LIST_ROOMS_PATH, Res3))).
admin_list_rooms_with_invalid_args(Config) ->
Config1 = escalus_fresh:create_users(Config, [{alice, 1}]),
AliceJid = escalus_users:get_jid(Config1, alice),
AliceDomain = escalus_users:get_host(Config1, alice),
Res1 = list_rooms(muc_helper:muc_host(), AliceDomain, null, null, Config1),
assert_coercion_err(Res1, <<"jid_without_local_part">>),
Res2 = list_rooms(muc_helper:muc_host(), AliceJid, 0, null, Config1),
assert_coercion_err(Res2, <<"Value is not a positive integer">>),
Res3 = list_rooms(muc_helper:muc_host(), AliceJid, null, -1, Config1),
assert_coercion_err(Res3, <<"Value is not a non-negative integer">>).
admin_try_list_rooms_for_nonexistent_domain(Config) ->
Config1 = escalus_fresh:create_users(Config, [{alice, 1}]),
AliceJID = escalus_users:get_jid(Config1, alice),
Res1 = list_rooms(<<"baddomain">>, AliceJID, null, null, Config1),
?assertMatch({_, _}, binary:match(get_err_msg(Res1), <<"not found">>)),
Domain instead of the MUC subdomain
Res2 = list_rooms(domain_helper:domain(), AliceJID, null, null, Config1),
?assertMatch({_, _}, binary:match(get_err_msg(Res2), <<"not found">>)).
admin_create_and_delete_room(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}], fun admin_create_and_delete_room_story/2).
admin_create_and_delete_room_story(Config, Alice) ->
Name = <<"first-alice-room">>,
MUCServer = muc_helper:muc_host(),
RoomJID = jid:make_bare(Name, MUCServer),
% Create instant room
Res = create_instant_room(RoomJID, Alice, <<"Ali">>, Config),
?assertMatch(#{<<"title">> := Name, <<"private">> := false, <<"usersNumber">> := 0},
get_ok_value(?CREATE_INSTANT_ROOM_PATH, Res)),
Res2 = list_rooms(MUCServer, Alice, null, null, Config),
?assert(contain_room(Name, get_ok_value(?LIST_ROOMS_PATH, Res2))),
% Delete room
Res3 = delete_room(RoomJID, null, Config),
?assertNotEqual(nomatch, binary:match(get_ok_value(?DELETE_ROOM_PATH, Res3),
<<"successfully">>)),
Res4 = list_rooms(MUCServer, Alice, null, null, Config),
?assertNot(contain_room(Name, get_ok_value(?LIST_ROOMS_PATH, Res4))).
admin_create_room_with_unprepped_name(Config) ->
FreshConfig = escalus_fresh:create_users(Config, [{alice, 1}]),
AliceJid = escalus_users:get_jid(FreshConfig, alice),
Name = <<$a, (rand_name())/binary>>, % make it start with a letter
MUCServer = muc_helper:muc_host(),
RoomJID = jid:make_noprep(unprep(Name), unprep(MUCServer), <<>>),
Res = create_instant_room(RoomJID, AliceJid, <<"Ali">>, FreshConfig),
?assertMatch(#{<<"title">> := Name, <<"private">> := false, <<"usersNumber">> := 0},
get_ok_value(?CREATE_INSTANT_ROOM_PATH, Res)),
Res2 = list_rooms(MUCServer, AliceJid, null, null, Config),
?assert(contain_room(Name, get_ok_value(?LIST_ROOMS_PATH, Res2))).
admin_try_create_instant_room_with_nonexistent_domain(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun admin_try_create_instant_room_with_nonexistent_domain_story/2).
admin_try_create_instant_room_with_nonexistent_domain_story(Config, Alice) ->
Res = create_instant_room(jid:make_bare(rand_name(), <<"unknown">>), Alice, <<"Ali">>, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_try_create_instant_room_with_nonexistent_user(Config) ->
RoomJID = jid:make_bare(rand_name(), muc_helper:muc_host()),
JID = <<(rand_name())/binary, "@localhost">>,
Res = create_instant_room(RoomJID, JID, <<"Ali">>, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_try_create_instant_room_with_invalid_args(Config) ->
Config1 = escalus_fresh:create_users(Config, [{alice, 1}]),
AliceJid = escalus_users:get_jid(Config1, alice),
AliceDomain = escalus_users:get_host(Config1, alice),
Domain = muc_helper:muc_host(),
Res1 = create_instant_room(<<"test room@", Domain/binary>>, AliceJid, <<"Ali">>, Config1),
assert_coercion_err(Res1, <<"failed_to_parse_jid">>),
Res2 = create_instant_room(<<"testroom@", Domain/binary, "/res1">>, AliceJid, <<"Ali">>, Config1),
assert_coercion_err(Res2, <<"jid_with_resource">>),
Res3 = create_instant_room(Domain, AliceJid, <<"Ali">>, Config1),
assert_coercion_err(Res3, <<"jid_without_local_part">>),
Res4 = create_instant_room(<<"testroom@", Domain/binary>>, AliceDomain, <<"Ali">>, Config1),
assert_coercion_err(Res4, <<"jid_without_local_part">>),
Res5 = create_instant_room(<<"testroom@", Domain/binary>>, AliceJid, <<>>, Config1),
assert_coercion_err(Res5, <<"empty_resource_name">>).
admin_try_delete_nonexistent_room(Config) ->
RoomJID = jid:make_bare(<<"unknown">>, muc_helper:muc_host()),
Res = delete_room(RoomJID, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"non-existent">>)).
admin_try_delete_room_with_nonexistent_domain(Config) ->
RoomJID = jid:make_bare(<<"unknown">>, <<"unknown">>),
Res = delete_room(RoomJID, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"non-existent">>)).
admin_invite_user(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}], fun admin_invite_user_story/3).
admin_invite_user_story(Config, Alice, Bob) ->
RoomJIDBin = ?config(room_jid, Config),
RoomJID = jid:from_binary(RoomJIDBin),
Res = invite_user(RoomJID, Alice, Bob, null, Config),
?assertNotEqual(nomatch, binary:match(get_ok_value(?INVITE_USER_PATH, Res),
<<"successfully">>)),
Stanza = escalus:wait_for_stanza(Bob),
escalus:assert(is_message, Stanza),
?assertEqual(RoomJIDBin,
exml_query:path(Stanza, [{element, <<"x">>}, {attr, <<"jid">>}])),
?assertEqual(undefined, exml_query:path(Stanza, [{element, <<"x">>}, {attr, <<"password">>}])).
admin_invite_user_with_password(Config) ->
muc_helper:story_with_room(Config, [{password_protected, true}, {password, ?PASSWORD}],
[{alice, 1}, {bob, 1}], fun admin_invite_user_with_password/3).
admin_invite_user_with_password(Config, Alice, Bob) ->
RoomJIDBin = ?config(room_jid, Config),
RoomJID = jid:from_binary(RoomJIDBin),
Res = invite_user(RoomJID, Alice, Bob, null, Config),
assert_success(?INVITE_USER_PATH, Res),
Stanza = escalus:wait_for_stanza(Bob),
escalus:assert(is_message, Stanza),
?assertEqual(RoomJIDBin,
exml_query:path(Stanza, [{element, <<"x">>}, {attr, <<"jid">>}])),
?assertEqual(?PASSWORD, exml_query:path(Stanza, [{element, <<"x">>}, {attr, <<"password">>}])).
admin_try_invite_user_to_nonexistent_room(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}, {bob, 1}],
fun admin_try_invite_user_to_nonexistent_room_story/3).
admin_try_invite_user_to_nonexistent_room_story(Config, Alice, Bob) ->
Res = invite_user(?NONEXISTENT_ROOM, Alice, Bob, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_kick_user(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}], fun admin_kick_user_story/3).
admin_kick_user_story(Config, Alice, Bob) ->
RoomJIDBin = ?config(room_jid, Config),
RoomJID = jid:from_binary(RoomJIDBin),
BobNick = <<"Bobek">>,
Reason = <<"You are too laud">>,
enter_room(RoomJID, Alice, <<"ali">>),
enter_room(RoomJID, Bob, BobNick),
Res = kick_user(RoomJID, BobNick, Reason, Config),
?assertNotEqual(nomatch, binary:match(get_ok_value(?KICK_USER_PATH, Res),
<<"successfully">>)),
escalus:wait_for_stanzas(Bob, 2),
KickStanza = escalus:wait_for_stanza(Bob),
escalus:assert(is_presence_with_type, [<<"unavailable">>], KickStanza),
?assertEqual(Reason,
exml_query:path(KickStanza, [{element, <<"x">>}, {element, <<"item">>},
{element, <<"reason">>}, cdata])).
admin_try_kick_user_from_room_without_moderators(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun admin_try_kick_user_from_room_without_moderators/3).
admin_try_kick_user_from_room_without_moderators(Config, _Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
BobNick = <<"Bobek">>,
enter_room(RoomJID, Bob, BobNick),
Res = kick_user(RoomJID, BobNick, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_try_kick_user_from_nonexistent_room(Config) ->
Res = kick_user(?NONEXISTENT_ROOM, <<"ali">>, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_send_message_to_room(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun admin_send_message_to_room_story/3).
admin_send_message_to_room_story(Config, _Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Message = <<"Hello All!">>,
BobNick = <<"Bobek">>,
enter_room(RoomJID, Bob, BobNick),
escalus:wait_for_stanza(Bob),
Try send message from bare JID ,
BareBob = escalus_client:short_jid(Bob),
Res = send_message_to_room(RoomJID, BareBob, Message, Config),
assert_no_full_jid(Res),
% Send message
Res1 = send_message_to_room(RoomJID, Bob, Message, Config),
?assertNotEqual(nomatch, binary:match(get_ok_value(?SEND_MESSAGE_PATH, Res1),
<<"successfully">>)),
assert_is_message_correct(RoomJID, BobNick, <<"groupchat">>, Message,
escalus:wait_for_stanza(Bob)).
admin_send_private_message(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun admin_send_private_message/3).
admin_send_private_message(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Message = <<"Hello Bob!">>,
BobNick = <<"Bobek">>,
AliceNick = <<"Ali">>,
enter_room(RoomJID, Alice, AliceNick),
enter_room(RoomJID, Bob, BobNick),
escalus:wait_for_stanzas(Bob, 2),
Try send private message from bare JID ,
BareAlice = escalus_client:short_jid(Alice),
Res = send_private_message(RoomJID, BareAlice, BobNick, Message, Config),
assert_no_full_jid(Res),
Try send private message to empty nick
Res1 = send_private_message(RoomJID, Alice, <<>>, Message, Config),
assert_coercion_err(Res1, <<"empty_resource_name">>),
% Send message
Res2 = send_private_message(RoomJID, Alice, BobNick, Message, Config),
assert_success(?SEND_PRIV_MESG_PATH, Res2),
assert_is_message_correct(RoomJID, AliceNick, <<"chat">>, Message,
escalus:wait_for_stanza(Bob)).
admin_get_room_config(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}], fun admin_get_room_config_story/2).
admin_get_room_config_story(Config, _Alice) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Res = get_room_config(RoomJID, Config),
assert_default_room_config(Res).
admin_try_get_nonexistent_room_config(Config) ->
Res = get_room_config(?NONEXISTENT_ROOM, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_change_room_config(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}], fun admin_change_room_config_story/2).
admin_change_room_config_story(Config, _Alice) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Title = <<"aloes">>,
Description = <<"The chat about aloes">>,
Public = false,
RoomConfig = #{title => Title, description => Description, public => Public},
Res = change_room_config(RoomJID, RoomConfig, Config),
?assertMatch(#{<<"title">> := Title,
<<"description">> := Description,
<<"public">> := Public}, get_ok_value(?CHANGE_ROOM_CONFIG_PATH, Res)).
admin_try_change_nonexistent_room_config(Config) ->
RoomConfig = #{title => <<"NewTitle">>},
Res = change_room_config(?NONEXISTENT_ROOM, RoomConfig, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_list_room_users(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun admin_list_room_users_story/3).
admin_list_room_users_story(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
BobNick = <<"Bobek">>,
AliceNick = <<"Ali">>,
enter_room(RoomJID, Bob, BobNick),
enter_room(RoomJID, Alice, AliceNick),
Res = list_room_users(RoomJID, Config),
ExpectedUsers = [{escalus_client:full_jid(Bob), BobNick, <<"PARTICIPANT">>},
{escalus_client:full_jid(Alice), AliceNick, <<"MODERATOR">>}],
assert_room_users(ExpectedUsers, get_ok_value(?LIST_ROOM_USERS_PATH, Res)).
admin_try_list_users_from_nonexistent_room(Config) ->
Res = list_room_users(?NONEXISTENT_ROOM, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_get_room_messages(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun admin_get_room_messages_story/3).
admin_get_room_messages_story(Config, Alice, Bob) ->
RoomJID = #jid{luser = RoomName, lserver = MUCDomain} =
jid:from_binary(?config(room_jid, Config)),
enter_room(RoomJID, Bob, <<"Bobek">>),
enter_room(RoomJID, Alice, <<"Ali">>),
escalus:wait_for_stanzas(Bob, 2),
send_message_to_room(RoomJID, Bob, <<"Hi!">>, Config),
escalus:wait_for_stanzas(Bob, 1),
mam_helper:wait_for_room_archive_size(MUCDomain, RoomName, 1),
Res = get_room_messages(RoomJID, 50, null, Config),
#{<<"stanzas">> := [#{<<"stanza">> := StanzaXML}], <<"limit">> := 50} =
get_ok_value(?GET_MESSAGES_PATH, Res),
?assertMatch({ok, #xmlel{name = <<"message">>}}, exml:parse(StanzaXML)).
admin_try_get_nonexistent_room_messages(Config) ->
Res = get_room_messages(?NONEXISTENT_ROOM, null, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_set_user_affiliation(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun admin_set_user_affiliation/3).
admin_set_user_affiliation(Config, _Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
% Grant member affiliation
Res = set_user_affiliation(RoomJID, Bob, member, Config),
assert_success(?SET_AFFILIATION_PATH, Res),
assert_user_affiliation(RoomJID, Bob, member),
% Grant admin affiliation
Res1 = set_user_affiliation(RoomJID, Bob, admin, Config),
assert_success(?SET_AFFILIATION_PATH, Res1),
assert_user_affiliation(RoomJID, Bob, admin),
Grant owner affiliation
Res2 = set_user_affiliation(RoomJID, Bob, owner, Config),
assert_success(?SET_AFFILIATION_PATH, Res2),
assert_user_affiliation(RoomJID, Bob, owner),
% Revoke affiliation
Res3 = set_user_affiliation(RoomJID, Bob, none, Config),
assert_success(?SET_AFFILIATION_PATH, Res3),
assert_user_affiliation(RoomJID, Bob, none),
% Ban user
Res4 = set_user_affiliation(RoomJID, Bob, outcast, Config),
assert_success(?SET_AFFILIATION_PATH, Res4),
assert_user_affiliation(RoomJID, Bob, outcast).
admin_try_set_nonexistent_room_user_affiliation(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun admin_try_set_nonexistent_room_user_affiliation/2).
admin_try_set_nonexistent_room_user_affiliation(Config, Alice) ->
Res = set_user_affiliation(?NONEXISTENT_ROOM, Alice, admin, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_set_user_role(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}], fun admin_set_user_role/3).
admin_set_user_role(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
BobNick = <<"Boobek">>,
enter_room(RoomJID, Alice, escalus_client:username(Alice)),
enter_room(RoomJID, Bob, BobNick),
% Change from participant to visitor
Res = set_user_role(RoomJID, BobNick, visitor, Config),
assert_success(?SET_ROLE_PATH, Res),
assert_user_role(RoomJID, Bob, visitor),
% Change from visitor to participant
Res1 = set_user_role(RoomJID, BobNick, participant, Config),
assert_success(?SET_ROLE_PATH, Res1),
assert_user_role(RoomJID, Bob, participant),
% Change from participant to moderator
Res2 = set_user_role(RoomJID, BobNick, moderator, Config),
assert_success(?SET_ROLE_PATH, Res2),
assert_user_role(RoomJID, Bob, moderator).
admin_try_set_nonexistent_nick_role(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}], fun admin_try_set_nonexistent_nick_role/2).
admin_try_set_nonexistent_nick_role(Config, Alice) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
enter_room(RoomJID, Alice, escalus_client:username(Alice)),
Res = set_user_role(RoomJID, <<"kik">>, visitor, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"does not exist">>)).
admin_try_set_user_role_in_room_without_moderators(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun admin_try_set_user_role_in_room_without_moderators/3).
admin_try_set_user_role_in_room_without_moderators(Config, _Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
BobNick = <<"Boobek">>,
enter_room(RoomJID, Bob, BobNick),
Res = set_user_role(RoomJID, BobNick, visitor, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_try_set_nonexistent_room_user_role(Config) ->
Res = set_user_role(?NONEXISTENT_ROOM, <<"Alice">>, moderator, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_make_user_enter_room(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}], fun admin_make_user_enter_room/2).
admin_make_user_enter_room(Config, Alice) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Nick = <<"ali">>,
JID = jid:from_binary(escalus_client:full_jid(Alice)),
enter room with password
Res = enter_room(RoomJID, Alice, Nick, null, Config),
assert_success(?ENTER_ROOM_PATH, Res),
?assertMatch([#{nick := Nick, jid := JID}], get_room_users(RoomJID)).
admin_make_user_enter_room_with_password(Config) ->
muc_helper:story_with_room(Config, [{password_protected, true}, {password, ?PASSWORD}],
[{alice, 1}, {bob, 1}],
fun admin_make_user_enter_room_with_password/3).
admin_make_user_enter_room_with_password(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Nick = <<"ali">>,
JID = jid:from_binary(escalus_client:full_jid(Alice)),
enter room with password
Res = enter_room(RoomJID, Alice, Nick, ?PASSWORD, Config),
assert_success(?ENTER_ROOM_PATH, Res),
?assertMatch([#{nick := Nick, jid := JID}], get_room_users(RoomJID)),
try enter room without password
Res1 = enter_room(RoomJID, Bob, <<"Bobek">>, null, Config),
assert_success(?ENTER_ROOM_PATH, Res1),
?assertMatch([_], get_room_users(RoomJID)),
enter room with password
Res2 = enter_room(RoomJID, Bob, <<"Bobek">>, ?PASSWORD, Config),
assert_success(?ENTER_ROOM_PATH, Res2),
?assertMatch([_, _], get_room_users(RoomJID)).
admin_make_user_enter_room_bare_jid(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}], fun admin_make_user_enter_room_bare_jid/2).
admin_make_user_enter_room_bare_jid(Config, Alice) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
BareAlice = escalus_client:short_jid(Alice),
Res = enter_room(RoomJID, BareAlice, <<"Ali">>, null, Config),
assert_no_full_jid(Res).
admin_make_user_exit_room(Config) ->
muc_helper:story_with_room(Config, [{persistent, true}], [{alice, 1}],
fun admin_make_user_exit_room/2).
admin_make_user_exit_room(Config, Alice) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Nick = <<"ali">>,
enter_room(RoomJID, Alice, Nick),
?assertMatch([_], get_room_users(RoomJID)),
Res = exit_room(RoomJID, Alice, Nick, Config),
assert_success(?EXIT_ROOM_PATH, Res),
?assertMatch([], get_room_users(RoomJID)).
admin_make_user_exit_room_bare_jid(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}], fun admin_make_user_exit_room_bare_jid/2).
admin_make_user_exit_room_bare_jid(Config, Alice) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
BareAlice = escalus_client:short_jid(Alice),
Nick = <<"ali">>,
enter_room(RoomJID, Alice, Nick),
Res = exit_room(RoomJID, BareAlice, Nick, Config),
assert_no_full_jid(Res).
admin_list_room_affiliations(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun admin_list_room_affiliations/3).
admin_list_room_affiliations(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
BobNick = <<"Bobek">>,
AliceNick = <<"Ali">>,
enter_room(RoomJID, Bob, BobNick),
enter_room(RoomJID, Alice, AliceNick),
AliceJID = escalus_utils:jid_to_lower(escalus_client:short_jid(Alice)),
BobJID = escalus_utils:jid_to_lower(escalus_client:short_jid(Bob)),
% List all owners
Res = list_room_affiliations(RoomJID, owner, Config),
?assertMatch([#{<<"jid">> := AliceJID, <<"affiliation">> := <<"OWNER">>}],
get_ok_value(?LIST_ROOM_AFFILIATIONS_PATH, Res)),
% List all members
set_user_affiliation(RoomJID, Bob, member, Config),
Res1 = list_room_affiliations(RoomJID, member, Config),
?assertMatch([#{<<"jid">> := BobJID, <<"affiliation">> := <<"MEMBER">>}],
get_ok_value(?LIST_ROOM_AFFILIATIONS_PATH, Res1)),
% List all
Res2 = list_room_affiliations(RoomJID, null, Config),
?assertMatch([_, _], get_ok_value(?LIST_ROOM_AFFILIATIONS_PATH, Res2)).
admin_try_list_nonexistent_room_affiliations(Config) ->
Res = list_room_affiliations(?NONEXISTENT_ROOM, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
%% Admin MUC not configured test cases
admin_delete_room_muc_not_configured(Config) ->
Res = delete_room(get_room_name(), null, Config),
get_not_loaded(Res).
admin_list_room_users_muc_not_configured(Config) ->
Res = list_room_users(get_room_name(), Config),
get_not_loaded(Res).
admin_change_room_config_muc_not_configured(Config) ->
RoomConfig = #{title => <<"NewTitle">>},
Res = change_room_config(get_room_name(), RoomConfig, Config),
get_not_loaded(Res).
admin_get_room_config_muc_not_configured(Config) ->
Res = get_room_config(get_room_name(), Config),
get_not_loaded(Res).
admin_invite_user_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}, {bob, 1}],
fun admin_invite_user_muc_not_configured_story/3).
admin_invite_user_muc_not_configured_story(Config, Alice, Bob) ->
Res = invite_user(get_room_name(), Alice, Bob, null, Config),
get_not_loaded(Res).
admin_kick_user_muc_not_configured(Config) ->
Res = kick_user(get_room_name(), <<"nick">>, <<"reason">>, Config),
get_not_loaded(Res).
admin_send_message_to_room_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun admin_send_message_to_room_muc_not_configured_story/2).
admin_send_message_to_room_muc_not_configured_story(Config, Alice) ->
Res = send_message_to_room(get_room_name(), Alice, <<"body">>, Config),
get_not_loaded(Res).
admin_send_private_message_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun admin_send_private_message_muc_not_configured_story/2).
admin_send_private_message_muc_not_configured_story(Config, Alice) ->
Nick = <<"ali">>,
Res = send_private_message(get_room_name(), Alice, Nick, <<"body">>, Config),
get_not_loaded(Res).
admin_get_room_messages_muc_or_mam_not_configured(Config) ->
Res = get_room_messages(get_room_name(), 4, null, Config),
get_not_loaded(Res).
admin_set_user_affiliation_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun admin_set_user_affiliation_muc_not_configured_story/2).
admin_set_user_affiliation_muc_not_configured_story(Config, Alice) ->
Res = set_user_affiliation(get_room_name(), Alice, member, Config),
get_not_loaded(Res).
admin_set_user_role_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun admin_set_user_role_muc_not_configured_story/2).
admin_set_user_role_muc_not_configured_story(Config, Alice) ->
Res = set_user_role(get_room_name(), Alice, moderator, Config),
get_not_loaded(Res).
admin_make_user_enter_room_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun admin_make_user_enter_room_muc_light_not_configured_story/2).
admin_make_user_enter_room_muc_light_not_configured_story(Config, Alice) ->
Nick = <<"ali">>,
Res = enter_room(get_room_name(), Alice, Nick, null, Config),
get_not_loaded(Res).
admin_make_user_exit_room_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun admin_make_user_exit_room_muc_not_configured_story/2).
admin_make_user_exit_room_muc_not_configured_story(Config, Alice) ->
Nick = <<"ali">>,
Res = exit_room(get_room_name(), Alice, Nick, Config),
get_not_loaded(Res).
admin_list_room_affiliations_muc_not_configured(Config) ->
Res = list_room_affiliations(get_room_name(), member, Config),
get_not_loaded(Res).
%% Domain admin test cases
domain_admin_try_delete_room_with_nonexistent_domain(Config) ->
RoomJID = jid:make_bare(<<"unknown">>, <<"unknown">>),
get_unauthorized(delete_room(RoomJID, null, Config)).
domain_admin_create_and_delete_room_no_permission(Config) ->
escalus:fresh_story_with_config(Config, [{alice_bis, 1}],
fun domain_admin_create_and_delete_room_no_permission_story/2).
domain_admin_create_and_delete_room_no_permission_story(Config, AliceBis) ->
ExternalDomain = domain_helper:secondary_domain(),
UnknownDomain = <<"unknown">>,
RoomJid = jid:make_bare(rand_name(), muc_helper:muc_host()),
ExternalServer = <<"muc.", ExternalDomain/binary>>,
% Create instant room with a non-existent domain
UnknownJID = <<(rand_name())/binary, "@", UnknownDomain/binary>>,
Res = create_instant_room(RoomJid, UnknownJID, <<"Ali">>, Config),
get_unauthorized(Res),
% Create instant room with an external domain
Res2 = create_instant_room(RoomJid, AliceBis, <<"Ali">>, Config),
get_unauthorized(Res2),
% Delete instant room with a non-existent domain
UnknownRoomJID = jid:make_bare(<<"unknown_room">>, UnknownDomain),
Res3 = delete_room(UnknownRoomJID, null, Config),
get_unauthorized(Res3),
% Delete instant room with an external domain
ExternalRoomJID = jid:make_bare(<<"external_room">>, ExternalServer),
Res4 = delete_room(ExternalRoomJID, null, Config),
get_unauthorized(Res4).
domain_admin_list_rooms_no_permission(Config) ->
escalus:fresh_story_with_config(Config, [{alice_bis, 1}],
fun domain_admin_list_rooms_no_permission_story/2).
domain_admin_list_rooms_no_permission_story(Config, AliceBis) ->
AliceBisJID = jid:from_binary(escalus_client:short_jid(AliceBis)),
AliceBisRoom = rand_name(),
muc_helper:create_instant_room(AliceBisRoom, AliceBisJID, <<"Ali">>, []),
Res = list_rooms(muc_helper:muc_host(), AliceBis, null, null, Config),
get_unauthorized(Res).
domain_admin_list_room_users_no_permission(Config) ->
get_unauthorized(list_room_users(?NONEXISTENT_ROOM, Config)),
get_unauthorized(list_room_users(?EXTERNAL_DOMAIN_ROOM, Config)).
domain_admin_change_room_config_no_permission(Config) ->
RoomConfig = #{title => <<"NewTitle">>},
get_unauthorized(change_room_config(?NONEXISTENT_ROOM, RoomConfig, Config)),
get_unauthorized(change_room_config(?EXTERNAL_DOMAIN_ROOM, RoomConfig, Config)).
domain_admin_get_room_config_no_permission(Config) ->
get_unauthorized(get_room_config(?NONEXISTENT_ROOM, Config)),
get_unauthorized(get_room_config(?EXTERNAL_DOMAIN_ROOM, Config)).
domain_admin_invite_user_no_permission(Config) ->
muc_helper:story_with_room(Config, [], [{alice_bis, 1}, {bob, 1}],
fun domain_admin_invite_user_no_permission_story/3).
domain_admin_invite_user_no_permission_story(Config, Alice, Bob) ->
RoomJIDBin = ?config(room_jid, Config),
RoomJID = jid:from_binary(RoomJIDBin),
Res = invite_user(RoomJID, Alice, Bob, null, Config),
get_unauthorized(Res).
domain_admin_kick_user_no_permission(Config) ->
get_unauthorized(kick_user(?NONEXISTENT_ROOM, <<"ali">>, null, Config)),
get_unauthorized(kick_user(?EXTERNAL_DOMAIN_ROOM, <<"ali">>, null, Config)).
domain_admin_send_message_to_room_no_permission(Config) ->
muc_helper:story_with_room(Config, [], [{alice_bis, 1}],
fun domain_admin_send_message_to_room_no_permission_story/2).
domain_admin_send_message_to_room_no_permission_story(Config, AliceBis) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Message = <<"Hello All!">>,
AliceNick = <<"Bobek">>,
enter_room(RoomJID, AliceBis, AliceNick),
escalus:wait_for_stanza(AliceBis),
% Send message
Res = send_message_to_room(RoomJID, AliceBis, Message, Config),
get_unauthorized(Res).
domain_admin_send_private_message_no_permission(Config) ->
muc_helper:story_with_room(Config, [], [{alice_bis, 1}, {bob, 1}],
fun domain_admin_send_private_message_no_permission_story/3).
domain_admin_send_private_message_no_permission_story(Config, AliceBis, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Message = <<"Hello Bob!">>,
BobNick = <<"Bobek">>,
AliceBisNick = <<"Ali">>,
enter_room(RoomJID, AliceBis, AliceBisNick),
enter_room(RoomJID, Bob, BobNick),
escalus:wait_for_stanzas(Bob, 2),
% Send message
Res = send_private_message(RoomJID, AliceBis, BobNick, Message, Config),
get_unauthorized(Res).
domain_admin_get_room_messages_no_permission(Config) ->
get_unauthorized(get_room_messages(?NONEXISTENT_ROOM, null, null, Config)),
get_unauthorized(get_room_messages(?EXTERNAL_DOMAIN_ROOM, null, null, Config)).
domain_admin_set_user_affiliation_no_permission(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun domain_admin_set_user_affiliation_no_permission_story/2).
domain_admin_set_user_affiliation_no_permission_story(Config, Alice) ->
get_unauthorized(set_user_affiliation(?NONEXISTENT_ROOM, Alice, admin, Config)),
get_unauthorized(set_user_affiliation(?EXTERNAL_DOMAIN_ROOM, Alice, admin, Config)).
domain_admin_set_user_role_no_permission(Config) ->
get_unauthorized(set_user_role(?NONEXISTENT_ROOM, <<"Alice">>, moderator, Config)),
get_unauthorized(set_user_role(?EXTERNAL_DOMAIN_ROOM, <<"Alice">>, moderator, Config)).
domain_admin_list_room_affiliations_no_permission(Config) ->
get_unauthorized(list_room_affiliations(?NONEXISTENT_ROOM, null, Config)),
get_unauthorized(list_room_affiliations(?EXTERNAL_DOMAIN_ROOM, null, Config)).
domain_admin_make_user_enter_room_no_permission(Config) ->
muc_helper:story_with_room(Config, [], [{alice_bis, 1}],
fun domain_admin_make_user_enter_room_no_permission_story/2).
domain_admin_make_user_enter_room_no_permission_story(Config, AliceBis) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Nick = <<"ali">>,
% Enter room without password
Res = enter_room(RoomJID, AliceBis, Nick, null, Config),
get_unauthorized(Res),
% Enter room with password
Res2 = enter_room(RoomJID, AliceBis, Nick, ?PASSWORD, Config),
get_unauthorized(Res2).
domain_admin_make_user_exit_room_no_permission(Config) ->
muc_helper:story_with_room(Config, [{persistent, true}], [{alice_bis, 1}],
fun domain_admin_make_user_exit_room_no_permission_story/2).
domain_admin_make_user_exit_room_no_permission_story(Config, AliceBis) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Nick = <<"ali">>,
enter_room(RoomJID, AliceBis, Nick),
?assertMatch([_], get_room_users(RoomJID)),
Res = exit_room(RoomJID, AliceBis, Nick, Config),
get_unauthorized(Res).
%% User test cases
user_list_rooms(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}, {bob, 1}], fun user_list_rooms_story/3).
user_list_rooms_story(Config, Alice, Bob) ->
AliceJID = jid:from_binary(escalus_client:short_jid(Alice)),
BobJID = jid:from_binary(escalus_client:short_jid(Bob)),
AliceRoom = rand_name(),
BobRoom = rand_name(),
muc_helper:create_instant_room(AliceRoom, AliceJID, <<"Ali">>, []),
muc_helper:create_instant_room(BobRoom, BobJID, <<"Bob">>, []),
Res = user_list_rooms(Alice, muc_helper:muc_host(), null, null, Config),
#{<<"rooms">> := Rooms } = get_ok_value(?LIST_ROOMS_PATH, Res),
?assert(contain_room(AliceRoom, Rooms)),
?assert(contain_room(BobRoom, Rooms)).
user_try_list_rooms_for_nonexistent_domain(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_try_list_rooms_for_nonexistent_domain_story/2).
user_try_list_rooms_for_nonexistent_domain_story(Config, Alice) ->
Res1 = user_list_rooms(Alice, <<"baddomain">>, null, null, Config),
?assertMatch({_, _}, binary:match(get_err_msg(Res1), <<"not found">>)),
Domain instead of the MUC subdomain
Res2 = user_list_rooms(Alice, domain_helper:domain(), null, null, Config),
?assertMatch({_, _}, binary:match(get_err_msg(Res2), <<"not found">>)).
user_create_and_delete_room(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}], fun user_create_and_delete_room_story/2).
user_create_and_delete_room_story(Config, Alice) ->
Name = rand_name(),
MUCServer = muc_helper:muc_host(),
RoomJID = jid:make_bare(Name, MUCServer),
% Create instant room
Res = user_create_instant_room(Alice, RoomJID, <<"Ali">>, Config),
?assertMatch(#{<<"title">> := Name, <<"private">> := false, <<"usersNumber">> := 0},
get_ok_value(?CREATE_INSTANT_ROOM_PATH, Res)),
Res2 = user_list_rooms(Alice, MUCServer, null, null, Config),
?assert(contain_room(Name, get_ok_value(?LIST_ROOMS_PATH, Res2))),
% Delete room
Res3 = user_delete_room(Alice, RoomJID, null, Config),
?assertNotEqual(nomatch, binary:match(get_ok_value(?DELETE_ROOM_PATH, Res3),
<<"successfully">>)),
Res4 = user_list_rooms(Alice, MUCServer, null, null, Config),
?assertNot(contain_room(Name, get_ok_value(?LIST_ROOMS_PATH, Res4))).
user_create_room_with_unprepped_name(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_create_room_with_unprepped_name_story/2).
user_create_room_with_unprepped_name_story(Config, Alice) ->
Name = <<$a, (rand_name())/binary>>, % make it start with a letter
MUCServer = muc_helper:muc_host(),
RoomJid = jid:make_noprep(unprep(Name), unprep(MUCServer), <<>>),
Res = user_create_instant_room(Alice, RoomJid, <<"Ali">>, Config),
?assertMatch(#{<<"title">> := Name, <<"private">> := false, <<"usersNumber">> := 0},
get_ok_value(?CREATE_INSTANT_ROOM_PATH, Res)).
user_try_create_instant_room_with_nonexistent_domain(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_try_create_instant_room_with_nonexistent_domain_story/2).
user_try_create_instant_room_with_nonexistent_domain_story(Config, Alice) ->
RoomJID = jid:make_bare(rand_name(), <<"unknown">>),
Res = user_create_instant_room(Alice, RoomJID, <<"Ali">>, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
user_try_create_instant_room_with_invalid_args(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_try_create_instant_room_with_invalid_args_story/2).
user_try_create_instant_room_with_invalid_args_story(Config, Alice) ->
Domain = muc_helper:muc_host(),
Res1 = user_create_instant_room(Alice, <<"test room@", Domain/binary>>, <<"Ali">>, Config),
assert_coercion_err(Res1, <<"failed_to_parse_jid">>),
Res2 = user_create_instant_room(Alice, <<"testroom@", Domain/binary, "/res1">>, <<"Ali">>, Config),
assert_coercion_err(Res2, <<"jid_with_resource">>),
Res3 = user_create_instant_room(Alice, <<"testroom@", Domain/binary>>, <<>>, Config),
assert_coercion_err(Res3, <<"empty_resource_name">>).
user_try_delete_nonexistent_room(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_try_delete_nonexistent_room_story/2).
user_try_delete_nonexistent_room_story(Config, Alice) ->
RoomJID = jid:make_bare(<<"unknown">>, muc_helper:muc_host()),
Res = user_delete_room(Alice, RoomJID, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"non-existent">>)).
user_try_delete_room_by_not_owner(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun user_try_delete_room_by_not_owner_story/3).
user_try_delete_room_by_not_owner_story(Config, _Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Res = user_delete_room(Bob, RoomJID, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"does not have permission">>)).
user_invite_user(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}], fun user_invite_user_story/3).
user_invite_user_story(Config, Alice, Bob) ->
RoomJIDBin = ?config(room_jid, Config),
RoomJID = jid:from_binary(RoomJIDBin),
Res = user_invite_user(Alice, RoomJID, Bob, null, Config),
?assertNotEqual(nomatch, binary:match(get_ok_value(?INVITE_USER_PATH, Res),
<<"successfully">>)),
Stanza = escalus:wait_for_stanza(Bob),
escalus:assert(is_message, Stanza),
?assertEqual(RoomJIDBin,
exml_query:path(Stanza, [{element, <<"x">>}, {attr, <<"jid">>}])).
user_kick_user(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}], fun user_kick_user_story/3).
user_kick_user_story(Config, Alice, Bob) ->
RoomJIDBin = ?config(room_jid, Config),
RoomJID = jid:from_binary(RoomJIDBin),
BobNick = <<"Bobek">>,
Reason = <<"You are too loud">>,
enter_room(RoomJID, Alice, <<"ali">>),
enter_room(RoomJID, Bob, BobNick),
Res = user_kick_user(Alice, RoomJID, BobNick, Reason, Config),
?assertNotEqual(nomatch, binary:match(get_ok_value(?KICK_USER_PATH, Res),
<<"successfully">>)),
escalus:wait_for_stanzas(Bob, 2),
KickStanza = escalus:wait_for_stanza(Bob),
escalus:assert(is_presence_with_type, [<<"unavailable">>], KickStanza),
?assertEqual(Reason,
exml_query:path(KickStanza, [{element, <<"x">>}, {element, <<"item">>},
{element, <<"reason">>}, cdata])).
user_try_kick_user_without_moderator_resource(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun user_try_kick_user_without_moderator_resource/3).
user_try_kick_user_without_moderator_resource(Config, Alice, Bob) ->
RoomJIDBin = ?config(room_jid, Config),
RoomJID = jid:from_binary(RoomJIDBin),
BobNick = <<"Bobek">>,
enter_room(RoomJID, Bob, BobNick),
Res = user_kick_user(Alice, RoomJID, BobNick, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
user_try_kick_user_from_nonexistent_room(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_try_kick_user_from_nonexistent_room/2).
user_try_kick_user_from_nonexistent_room(Config, Alice) ->
Res = user_kick_user(Alice, ?NONEXISTENT_ROOM, <<"bobi">>, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
user_send_message_to_room(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun user_send_message_to_room_story/3).
user_send_message_to_room_story(Config, _Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Message = <<"Hello All!">>,
BobNick = <<"Bobek">>,
enter_room(RoomJID, Bob, BobNick),
escalus:wait_for_stanza(Bob),
% Send message
Res = user_send_message_to_room(Bob, RoomJID, Message, null, Config),
?assertNotEqual(nomatch, binary:match(get_ok_value(?SEND_MESSAGE_PATH, Res),
<<"successfully">>)),
assert_is_message_correct(RoomJID, BobNick, <<"groupchat">>, Message,
escalus:wait_for_stanza(Bob)).
user_send_message_to_room_with_specified_res(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 2}],
fun user_send_message_to_room_with_specified_res_story/4).
user_send_message_to_room_with_specified_res_story(Config, _Alice, Bob, Bob2) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Message = <<"Hello All!">>,
BobNick = <<"Bobek">>,
enter_room(RoomJID, Bob2, BobNick),
escalus:wait_for_stanza(Bob2),
% Send message, the resource should be normalized to "res2"
Res = user_send_message_to_room(Bob, RoomJID, Message, <<"res₂"/utf8>>, Config),
?assertNotEqual(nomatch, binary:match(get_ok_value(?SEND_MESSAGE_PATH, Res),
<<"successfully">>)),
assert_is_message_correct(RoomJID, BobNick, <<"groupchat">>, Message,
escalus:wait_for_stanza(Bob2)).
user_send_private_message(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun user_send_private_message/3).
user_send_private_message(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Message = <<"Hello Bob!">>,
BobNick = <<"Bobek">>,
AliceNick = <<"Ali">>,
enter_room(RoomJID, Bob, BobNick),
enter_room(RoomJID, Alice, AliceNick),
escalus:wait_for_stanzas(Bob, 2),
% Send message
Res = user_send_private_message(Alice, RoomJID, Message, BobNick, null, Config),
assert_success(?SEND_PRIV_MESG_PATH, Res),
assert_is_message_correct(RoomJID, AliceNick, <<"chat">>, Message,
escalus:wait_for_stanza(Bob)).
user_send_private_message_with_specified_res(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 2}, {bob, 1}],
fun user_send_private_message/3).
user_send_private_message_with_specified_res(Config, Alice, Alice2, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Message = <<"Hello Bob!">>,
BobNick = <<"Bobek">>,
AliceNick = <<"Ali">>,
enter_room(RoomJID, Bob, BobNick),
enter_room(RoomJID, Alice2, AliceNick),
escalus:wait_for_stanzas(Bob, 2),
% Send message, the resource should be normalized to "res2"
Res = user_send_private_message(Alice, RoomJID, Message, BobNick, <<"res₂"/utf8>>, Config),
assert_success(?SEND_PRIV_MESG_PATH, Res),
assert_is_message_correct(RoomJID, AliceNick, <<"chat">>, Message,
escalus:wait_for_stanza(Bob)).
user_without_session_send_message_to_room(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}],
fun user_without_session_send_message_to_room_story/2).
user_without_session_send_message_to_room_story(Config, Alice) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
JID = jid:from_binary(escalus_client:full_jid(Alice)),
terminate_user_session(JID),
% Send message
Res = user_send_message_to_room(Alice, RoomJID, <<"Hello!">>, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"does not have any session">>)).
terminate_user_session(Jid) ->
?assertEqual(ok, rpc(mim(), ejabberd_sm, terminate_session, [Jid, <<"Kicked">>])),
F = fun() -> rpc(mim(), ejabberd_sm, get_user_resources, [Jid]) end,
mongoose_helper:wait_until(F, [], #{time_left => timer:seconds(5)}).
user_get_room_config(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun user_get_room_config_story/3).
user_get_room_config_story(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Res = user_get_room_config(Alice, RoomJID, Config),
assert_default_room_config(Res),
% Not an owner tries to get room config
Res2 = user_get_room_config(Bob, RoomJID, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res2), <<"does not have permission">>)).
user_try_get_nonexistent_room_config(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_try_get_nonexistent_room_config_story/2).
user_try_get_nonexistent_room_config_story(Config, Alice) ->
Res = user_get_room_config(Alice, ?NONEXISTENT_ROOM, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
user_change_room_config(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun user_change_room_config_story/3).
user_change_room_config_story(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Title = <<"aloes">>,
Description = <<"The chat about aloes">>,
Public = false,
RoomConfig = #{title => Title, description => Description, public => Public},
Res = user_change_room_config(Alice, RoomJID, RoomConfig, Config),
?assertMatch(#{<<"title">> := Title,
<<"description">> := Description,
<<"public">> := Public}, get_ok_value(?CHANGE_ROOM_CONFIG_PATH, Res)),
% Not an owner tries to change the room config
Res2 = user_change_room_config(Bob, RoomJID, RoomConfig, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res2), <<"does not have permission">>)).
user_try_change_nonexistent_room_config(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_try_change_nonexistent_room_config_story/2).
user_try_change_nonexistent_room_config_story(Config, Alice) ->
RoomConfig = #{title => <<"NewTitle">>},
Res = user_change_room_config(Alice, ?NONEXISTENT_ROOM, RoomConfig, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
user_list_room_users(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun user_list_room_users_story/3).
user_list_room_users_story(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
BobNick = <<"Bobek">>,
AliceNick = <<"Ali">>,
enter_room(RoomJID, Bob, BobNick),
enter_room(RoomJID, Alice, AliceNick),
Res = user_list_room_users(Alice, RoomJID, Config),
ExpectedUsers = [{null, BobNick, <<"PARTICIPANT">>},
{null, AliceNick, <<"MODERATOR">>}],
assert_room_users(ExpectedUsers, get_ok_value(?LIST_ROOM_USERS_PATH, Res)).
user_list_room_users_without_anonymous_mode(Config) ->
muc_helper:story_with_room(Config, [{anonymous, false}], [{alice, 1}, {bob, 1}],
fun user_list_room_users_without_anonymous_mode_story/3).
user_list_room_users_without_anonymous_mode_story(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
BobNick = <<"Bobek">>,
AliceNick = <<"Ali">>,
enter_room(RoomJID, Bob, BobNick),
enter_room(RoomJID, Alice, AliceNick),
Res = user_list_room_users(Alice, RoomJID, Config),
ExpectedUsers = [{escalus_client:full_jid(Bob), BobNick, <<"PARTICIPANT">>},
{escalus_client:full_jid(Alice), AliceNick, <<"MODERATOR">>}],
assert_room_users(ExpectedUsers, get_ok_value(?LIST_ROOM_USERS_PATH, Res)).
user_try_list_nonexistent_room_users(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_try_list_nonexistent_room_users_story/2).
user_try_list_nonexistent_room_users_story(Config, Alice) ->
Res = user_list_room_users(Alice, ?NONEXISTENT_ROOM, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
user_try_list_room_users_without_permission(Config) ->
muc_helper:story_with_room(Config, [{members_only, true}], [{alice, 1}, {bob, 1}],
fun user_try_list_room_users_without_permission_story/3).
user_try_list_room_users_without_permission_story(Config, _Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Res = user_list_room_users(Bob, RoomJID, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"does not have permission">>)).
user_get_room_messages(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun user_get_room_messages_story/3).
user_get_room_messages_story(Config, Alice, Bob) ->
RoomJID = #jid{luser = RoomName, lserver = MUCDomain} =
jid:from_binary(?config(room_jid, Config)),
enter_room(RoomJID, Bob, <<"Bobek">>),
enter_room(RoomJID, Alice, <<"Ali">>),
escalus:wait_for_stanzas(Bob, 2),
user_send_message_to_room(Bob, RoomJID, <<"Hi!">>, null, Config),
escalus:wait_for_stanzas(Bob, 1),
mam_helper:wait_for_room_archive_size(MUCDomain, RoomName, 1),
Res = user_get_room_messages(Alice, RoomJID, 50, null, Config),
#{<<"stanzas">> := [#{<<"stanza">> := StanzaXML}], <<"limit">> := 50} =
get_ok_value(?GET_MESSAGES_PATH, Res),
?assertMatch({ok, #xmlel{name = <<"message">>}}, exml:parse(StanzaXML)).
user_shouldnt_store_messages_in_muc_light(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_shouldnt_store_messages_in_muc_light_story/2).
user_shouldnt_store_messages_in_muc_light_story(Config, Alice) ->
%% Create a MUC Light room
MUCServer = ?config(muc_light_host, Config),
AliceBin = escalus_client:short_jid(Alice),
{ok, #{jid := RoomJID}} =
create_muc_light_room(MUCServer, <<"first room">>, <<"subject">>, AliceBin),
%% Send a message
Message = <<"Hello friends">>,
send_message_to_muc_light_room(RoomJID, jid:from_binary(AliceBin), Message),
escalus:wait_for_stanza(Alice),
%% Try to get a MUC Light message
Limit = 1,
Res = user_get_muc_light_room_messages(Alice, jid:to_binary(RoomJID), Limit, null, Config),
#{<<"stanzas">> := [], <<"limit">> := Limit} =
get_ok_value([data, muc_light, getRoomMessages], Res).
user_try_get_nonexistent_room_messages(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_try_get_nonexistent_room_messages_story/2).
user_try_get_nonexistent_room_messages_story(Config, Alice) ->
% Non-existent room with non-existent domain
Res = user_get_room_messages(Alice, ?NONEXISTENT_ROOM, null, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)),
% Non-existent room with existent domain
Res2 = user_get_room_messages(Alice, ?NONEXISTENT_ROOM2, null, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res2), <<"not found">>)).
user_try_get_room_messages_without_permission(Config) ->
muc_helper:story_with_room(Config, [{members_only, true}], [{alice, 1}, {bob, 1}],
fun user_try_get_room_messages_without_permission/3).
user_try_get_room_messages_without_permission(Config, _Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Res = user_get_room_messages(Bob, RoomJID, null, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"does not have permission">>)).
user_owner_set_user_affiliation(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun user_owner_set_user_affiliation/3).
user_owner_set_user_affiliation(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
% Grant a member affiliation
Res = user_set_user_affiliation(Alice, RoomJID, Bob, member, Config),
assert_success(?SET_AFFILIATION_PATH, Res),
assert_user_affiliation(RoomJID, Bob, member),
% Grant a member affiliation
Res1 = user_set_user_affiliation(Alice, RoomJID, Bob, admin, Config),
assert_success(?SET_AFFILIATION_PATH, Res1),
assert_user_affiliation(RoomJID, Bob, admin),
% Grant a owner affiliation
Res2 = user_set_user_affiliation(Alice, RoomJID, Bob, owner, Config),
assert_success(?SET_AFFILIATION_PATH, Res2),
assert_user_affiliation(RoomJID, Bob, owner),
% Revoke affiliation
Res3 = user_set_user_affiliation(Alice, RoomJID, Bob, none, Config),
assert_success(?SET_AFFILIATION_PATH, Res3),
assert_user_affiliation(RoomJID, Bob, none),
% Ban user
Res4 = user_set_user_affiliation(Alice, RoomJID, Bob, outcast, Config),
assert_success(?SET_AFFILIATION_PATH, Res4),
assert_user_affiliation(RoomJID, Bob, outcast).
user_admin_set_user_affiliation(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}, {kate, 1}],
fun user_admin_set_user_affiliation/4).
user_admin_set_user_affiliation(Config, Alice, Bob, Kate) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
user_set_user_affiliation(Alice, RoomJID, Bob, admin, Config),
% Grant member affiliation
Res = user_set_user_affiliation(Bob, RoomJID, Kate, member, Config),
assert_success(?SET_AFFILIATION_PATH, Res),
assert_user_affiliation(RoomJID, Kate, member),
% Revoke affiliation
Res1 = user_set_user_affiliation(Bob, RoomJID, Kate, none, Config),
assert_success(?SET_AFFILIATION_PATH, Res1),
assert_user_affiliation(RoomJID, Kate, none),
% Admin cannot grant admin affiliation
Res2 = user_set_user_affiliation(Bob, RoomJID, Kate, admin, Config),
assert_no_permission(Res2),
% Admin cannot grant owner affiliation
Res3 = user_set_user_affiliation(Bob, RoomJID, Kate, owner, Config),
assert_no_permission(Res3),
% Admin can ban member
Res4 = user_set_user_affiliation(Bob, RoomJID, Kate, outcast, Config),
assert_success(?SET_AFFILIATION_PATH, Res4),
assert_user_affiliation(RoomJID, Kate, outcast),
% Admin cannot ban owner
Res5 = user_set_user_affiliation(Bob, RoomJID, Alice, outcast, Config),
assert_no_permission(Res5).
user_member_set_user_affiliation(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}, {kate, 1}],
fun user_member_set_user_affiliation/4).
user_member_set_user_affiliation(Config, Alice, Bob, Kate) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
user_set_user_affiliation(Alice, RoomJID, Bob, member, Config),
% Member cannot grant member affiliation
Res = user_set_user_affiliation(Bob, RoomJID, Kate, member, Config),
assert_no_permission(Res),
% Member cannot grant member admin affiliation
Res1 = user_set_user_affiliation(Bob, RoomJID, Kate, admin, Config),
assert_no_permission(Res1),
% Member cannot grant member owner affiliation
Res2 = user_set_user_affiliation(Bob, RoomJID, Kate, owner, Config),
assert_no_permission(Res2),
% Member cannot revoke member affiliation
user_set_user_affiliation(Alice, RoomJID, Kate, member, Config),
Res3 = user_set_user_affiliation(Bob, RoomJID, Kate, none, Config),
assert_no_permission(Res3).
user_try_set_nonexistent_room_affiliation(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_try_set_nonexistent_room_affiliation/2).
user_try_set_nonexistent_room_affiliation(Config, Alice) ->
Res = user_set_user_affiliation(Alice, ?NONEXISTENT_ROOM, Alice, none, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
user_moderator_set_user_role(Config) ->
muc_helper:story_with_room(Config, [{anonymous, false}, {persistent, true}],
[{alice, 1}, {bob, 1}],
fun user_moderator_set_user_role/3).
user_moderator_set_user_role(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
BobNick = <<"Boobek">>,
enter_room(RoomJID, Alice, escalus_client:username(Alice)),
enter_room(RoomJID, Bob, BobNick),
% Change from participant to visitor
Res = user_set_user_role(Alice, RoomJID, BobNick, visitor, Config),
assert_success(?SET_ROLE_PATH, Res),
assert_user_role(RoomJID, Bob, visitor),
% Change from visitor to participant
Res1 = user_set_user_role(Alice, RoomJID, BobNick, participant, Config),
assert_success(?SET_ROLE_PATH, Res1),
assert_user_role(RoomJID, Bob, participant),
% Change from participant to moderator
Res2 = user_set_user_role(Alice, RoomJID, BobNick, moderator, Config),
assert_success(?SET_ROLE_PATH, Res2),
assert_user_role(RoomJID, Bob, moderator).
user_participant_set_user_role(Config) ->
muc_helper:story_with_room(Config, [{anonymous, false}, {persistent, true}],
[{alice, 1}, {bob, 1}, {kate, 1}],
fun user_participant_set_user_role/4).
user_participant_set_user_role(Config, _Alice, Bob, Kate) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
BobNick = <<"Boobek">>,
KateNick = <<"Katek">>,
enter_room(RoomJID, Bob, BobNick),
enter_room(RoomJID, Kate, KateNick),
% Try change from participant to visitor
Res = user_set_user_role(Bob, RoomJID, KateNick, visitor, Config),
assert_no_permission(Res),
% Change from participant to participant with success response
Res1 = user_set_user_role(Bob, RoomJID, KateNick, participant, Config),
assert_success(?SET_ROLE_PATH, Res1),
assert_user_role(RoomJID, Bob, participant),
% Try change from participant to moderator
Res2 = user_set_user_role(Bob, RoomJID, KateNick, moderator, Config),
assert_no_permission(Res2).
user_try_set_nonexistent_room_role(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_try_set_nonexistent_room_role/2).
user_try_set_nonexistent_room_role(Config, Alice) ->
Res = user_set_user_role(Alice, ?NONEXISTENT_ROOM, <<"Ali">>, participant, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
user_can_enter_room(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}], fun user_can_enter_room/2).
user_can_enter_room(Config, Alice) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Nick = <<"ali">>,
JID = jid:from_binary(escalus_utils:jid_to_lower(escalus_client:full_jid(Alice))),
Resource should be normalized to " res1 " , which is 's connected resource
Res = user_enter_room(Alice, RoomJID, Nick, <<"res₁"/utf8>>, null, Config),
assert_success(?ENTER_ROOM_PATH, Res),
?assertMatch([#{nick := Nick, jid := JID}], get_room_users(RoomJID)).
user_cannot_enter_room_with_invalid_resource(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}],
fun user_cannot_enter_room_with_invalid_resource/2).
user_cannot_enter_room_with_invalid_resource(Config, Alice) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Nick = <<"ali">>,
Res1 = user_enter_room(Alice, RoomJID, Nick, <<"\n">>, null, Config),
assert_coercion_err(Res1, <<"failed_to_parse_resource_name">>),
Res2 = user_enter_room(Alice, RoomJID, Nick, <<>>, null, Config),
assert_coercion_err(Res2, <<"empty_resource_name">>).
user_can_enter_room_with_password(Config) ->
muc_helper:story_with_room(Config, [{password_protected, true}, {password, ?PASSWORD}],
[{alice, 1}, {bob, 1}],
fun user_can_enter_room_with_password/3).
user_can_enter_room_with_password(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Nick = <<"ali">>,
JID = jid:from_binary(escalus_utils:jid_to_lower(escalus_client:full_jid(Alice))),
Resource = escalus_client:resource(Alice),
enter room with password
Res = user_enter_room(Alice, RoomJID, Nick, Resource, ?PASSWORD, Config),
assert_success(?ENTER_ROOM_PATH, Res),
?assertMatch([#{nick := Nick, jid := JID}], get_room_users(RoomJID)),
try enter room without password
Res1 = user_enter_room(Bob, RoomJID, <<"Bobek">>, Resource, null, Config),
assert_success(?ENTER_ROOM_PATH, Res1),
?assertMatch([_], get_room_users(RoomJID)),
enter room with password
Res2 = user_enter_room(Bob, RoomJID, <<"Bobek">>, Resource, ?PASSWORD, Config),
assert_success(?ENTER_ROOM_PATH, Res2),
?assertMatch([_, _], get_room_users(RoomJID)).
user_can_exit_room(Config) ->
muc_helper:story_with_room(Config, [{persistent, true}], [{alice, 1}],
fun user_can_exit_room/2).
user_can_exit_room(Config, Alice) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Nick = <<"ali">>,
enter_room(RoomJID, Alice, Nick),
?assertMatch([_], get_room_users(RoomJID)),
Resource should be normalized to " res1 " , which is 's connected resource
Res = user_exit_room(Alice, RoomJID, Nick, <<"res₁"/utf8>>, Config),
assert_success(?EXIT_ROOM_PATH, Res),
?assertMatch([], get_room_users(RoomJID)).
user_list_room_affiliations(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun user_list_room_affiliations/3).
user_list_room_affiliations(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
BobNick = <<"Bobek">>,
AliceNick = <<"Ali">>,
enter_room(RoomJID, Bob, BobNick),
enter_room(RoomJID, Alice, AliceNick),
AliceJID = escalus_utils:jid_to_lower(escalus_client:short_jid(Alice)),
BobJID = escalus_utils:jid_to_lower(escalus_client:short_jid(Bob)),
% List all owners
Res = user_list_room_affiliations(Alice, RoomJID, owner, Config),
?assertMatch([#{<<"jid">> := AliceJID, <<"affiliation">> := <<"OWNER">>}],
get_ok_value(?LIST_ROOM_AFFILIATIONS_PATH, Res)),
% List all members
user_set_user_affiliation(Alice, RoomJID, Bob, member, Config),
Res1 = user_list_room_affiliations(Alice, RoomJID, member, Config),
?assertMatch([#{<<"jid">> := BobJID, <<"affiliation">> := <<"MEMBER">>}],
get_ok_value(?LIST_ROOM_AFFILIATIONS_PATH, Res1)),
% List all
Res2 = user_list_room_affiliations(Alice, RoomJID, null, Config),
?assertMatch([_, _], get_ok_value(?LIST_ROOM_AFFILIATIONS_PATH, Res2)).
user_try_list_room_affiliations_without_permission(Config) ->
muc_helper:story_with_room(Config, [{members_only, true}], [{alice, 1}, {bob, 1}],
fun user_try_list_room_affiliations_without_permission/3).
user_try_list_room_affiliations_without_permission(Config, _Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Res = user_list_room_affiliations(Bob, RoomJID, null, Config),
assert_no_permission(Res).
user_try_list_nonexistent_room_affiliations(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_try_list_nonexistent_room_affiliations/2).
user_try_list_nonexistent_room_affiliations(Config, Alice) ->
Res = user_list_room_affiliations(Alice, ?NONEXISTENT_ROOM, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
%% User MUC not configured test cases
user_delete_room_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_delete_room_muc_not_configured_story/2).
user_delete_room_muc_not_configured_story(Config, Alice) ->
Res = user_delete_room(Alice, get_room_name(), null, Config),
get_not_loaded(Res).
user_list_room_users_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_list_room_users_muc_not_configured_story/2).
user_list_room_users_muc_not_configured_story(Config, Alice) ->
Res = user_list_room_users(Alice, get_room_name(), Config),
get_not_loaded(Res).
user_change_room_config_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_change_room_config_muc_not_configured_story/2).
user_change_room_config_muc_not_configured_story(Config, Alice) ->
RoomConfig = #{title => <<"NewTitle">>},
Res = user_change_room_config(Alice, get_room_name(), RoomConfig, Config),
get_not_loaded(Res).
user_get_room_config_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_get_room_config_muc_not_configured_story/2).
user_get_room_config_muc_not_configured_story(Config, Alice) ->
Res = user_get_room_config(Alice, get_room_name(), Config),
get_not_loaded(Res).
user_invite_user_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}, {bob, 1}],
fun user_invite_user_muc_not_configured_story/3).
user_invite_user_muc_not_configured_story(Config, Alice, Bob) ->
Res = user_invite_user(Alice, get_room_name(), Bob, null, Config),
get_not_loaded(Res).
user_kick_user_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_kick_user_muc_not_configured_story/2).
user_kick_user_muc_not_configured_story(Config, Alice) ->
Res = user_kick_user(Alice, get_room_name(), <<"nick">>, <<"reason">>, Config),
get_not_loaded(Res).
user_send_message_to_room_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_send_message_to_room_muc_not_configured_story/2).
user_send_message_to_room_muc_not_configured_story(Config, Alice) ->
Res = user_send_message_to_room(Alice, get_room_name(), <<"Body">>, null, Config),
get_not_loaded(Res).
user_send_private_message_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_send_private_message_muc_not_configured_story/2).
user_send_private_message_muc_not_configured_story(Config, Alice) ->
Message = <<"Hello Bob!">>,
BobNick = <<"Bobek">>,
Res = user_send_private_message(Alice, get_room_name(), Message, BobNick, null, Config),
get_not_loaded(Res).
user_get_room_messages_muc_or_mam_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_get_room_messages_muc_or_mam_not_configured_story/2).
user_get_room_messages_muc_or_mam_not_configured_story(Config, Alice) ->
Res = user_get_room_messages(Alice, get_room_name(), 10, null, Config),
get_not_loaded(Res).
user_owner_set_user_affiliation_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_owner_set_user_affiliation_muc_not_configured_story/2).
user_owner_set_user_affiliation_muc_not_configured_story(Config, Alice) ->
Res = user_set_user_affiliation(Alice, get_room_name(), Alice, member, Config),
get_not_loaded(Res).
user_moderator_set_user_role_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_moderator_set_user_role_muc_not_configured_story/2).
user_moderator_set_user_role_muc_not_configured_story(Config, Alice) ->
Res = user_set_user_role(Alice, get_room_name(), Alice, moderator, Config),
get_not_loaded(Res).
user_can_enter_room_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_can_enter_room_muc_not_configured_story/2).
user_can_enter_room_muc_not_configured_story(Config, Alice) ->
Nick = <<"ali">>,
Resource = escalus_client:resource(Alice),
Res = user_enter_room(Alice, get_room_name(), Nick, Resource, null, Config),
get_not_loaded(Res).
user_can_exit_room_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_can_exit_room_muc_not_configured_story/2).
user_can_exit_room_muc_not_configured_story(Config, Alice) ->
Resource = escalus_client:resource(Alice),
Res = user_exit_room(Alice, get_room_name(), <<"ali">>, Resource, Config),
get_not_loaded(Res).
user_list_room_affiliations_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_list_room_affiliations_muc_not_configured_story/2).
user_list_room_affiliations_muc_not_configured_story(Config, Alice) ->
Res = user_list_room_affiliations(Alice, get_room_name(), owner, Config),
get_not_loaded(Res).
%% Helpers
assert_coercion_err(Res, Code) ->
?assertNotEqual(nomatch, binary:match(get_coercion_err_msg(Res), Code)).
assert_no_full_jid(Res) ->
assert_coercion_err(Res, <<"jid_without_resource">>).
assert_no_permission(Res) ->
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"does not have permission">>)).
assert_success(Path, Res) ->
?assertNotEqual(nomatch, binary:match(get_ok_value(Path, Res), <<"successfully">>)).
get_room_affiliation(RoomJID, Aff) ->
{ok, Affs} = rpc(mim(), mod_muc_api, get_room_affiliations, [RoomJID, Aff]),
Affs.
get_room_users(RoomJID) ->
{ok, Users} = rpc(mim(), mod_muc_api, get_room_users, [RoomJID]),
Users.
assert_user_role(RoomJID, User, Role) ->
UserJID = jid:from_binary(escalus_client:full_jid(User)),
?assert(lists:any(fun(#{jid := JID, role := Role2}) ->
Role =:= Role2 andalso jid:are_bare_equal(JID, UserJID) end,
get_room_users(RoomJID))).
assert_user_affiliation(RoomJID, User, none) ->
Affs = get_room_affiliation(RoomJID, undefined),
UserSimpleJID = jid:to_lower(user_to_jid(User)),
?assertNot(lists:any(fun({U, _}) -> U == UserSimpleJID end, Affs));
assert_user_affiliation(RoomJID, User, Aff) ->
Affs = get_room_affiliation(RoomJID, Aff),
Elem = {jid:to_lower(user_to_jid(User)), Aff},
?assert(lists:member(Elem, Affs)).
rand_name() ->
rpc(mim(), mongoose_bin, gen_from_crypto, []).
-spec assert_room_users([{jid:jid(), binary(), binary()}], [map()]) -> ok.
assert_room_users(Expected, Actual) ->
ActualTuples = [{JID, Nick, Role} || #{<<"jid">> := JID, <<"role">> := Role, <<"nick">> := Nick} <- Actual],
?assertEqual(lists:sort(Expected), lists:sort(ActualTuples)).
assert_is_message_correct(RoomJID, SenderNick, Type, Text, ReceivedMessage) ->
escalus_pred:is_message(ReceivedMessage),
From = jid:to_binary(jid:replace_resource(RoomJID, SenderNick)),
From = exml_query:attr(ReceivedMessage, <<"from">>),
Type = exml_query:attr(ReceivedMessage, <<"type">>),
Body = #xmlel{name = <<"body">>, children = [#xmlcdata{content=Text}]},
Body = exml_query:subelement(ReceivedMessage, <<"body">>).
enter_room(RoomJID, User, Nick) ->
JID = jid:to_binary(jid:replace_resource(RoomJID, Nick)),
Pres = escalus_stanza:to(escalus_stanza:presence(<<"available">>, []), JID),
escalus:send(User, Pres),
escalus:wait_for_stanza(User).
contain_room(Name, #{<<"rooms">> := Rooms}) ->
contain_room(Name, Rooms);
contain_room(Name, Rooms) when is_list(Rooms) ->
lists:any(fun(#{<<"title">> := T}) -> T =:= Name end, Rooms).
extract_rooms(#{<<"rooms">> := [], <<"index">> := null, <<"count">> := 0,
<<"first">> := null, <<"last">> := null}) ->
[];
extract_rooms(#{<<"rooms">> := Rooms, <<"index">> := Index, <<"count">> := Count,
<<"first">> := First, <<"last">> := Last}) ->
Titles = lists:map(fun(#{<<"title">> := Title}) -> Title end, Rooms),
?assertEqual(hd(Titles), First),
?assertEqual(lists:last(Titles), Last),
?assert(is_integer(Count) andalso Count >= length(Titles)),
?assert(is_integer(Index) andalso Index >= 0),
Titles.
returned_rooms(#{<<"rooms">> := Rooms}) ->
[Title || #{<<"title">> := Title} <- Rooms].
assert_default_room_config(Response) ->
?assertMatch(#{<<"title">> := <<>>,
<<"description">> := <<>>,
<<"allowChangeSubject">> := true,
<<"allowQueryUsers">> := true,
<<"allowPrivateMessages">> := true,
<<"allowVisitorStatus">> := true,
<<"allowVisitorNickchange">> := true,
<<"public">> := true,
<<"publicList">> := true,
<<"persistent">> := false,
<<"moderated">> := true,
<<"membersByDefault">> := true,
<<"membersOnly">> := false,
<<"allowUserInvites">> := false,
<<"allowMultipleSession">> := false,
<<"passwordProtected">> := false,
<<"password">> := <<>>,
<<"anonymous">> := true,
<<"mayGetMemberList">> := [],
<<"maxUsers">> := 200,
<<"logging">> := false}, get_ok_value(?GET_ROOM_CONFIG_PATH, Response)).
atom_to_enum_item(null) -> null;
atom_to_enum_item(Atom) -> list_to_binary(string:to_upper(atom_to_list(Atom))).
get_room_name() ->
Domain = domain_helper:domain(),
<<"NON_EXISTING@", Domain/binary>>.
%% Commands
create_muc_light_room(Domain, Name, Subject, CreatorBin) ->
CreatorJID = jid:from_binary(CreatorBin),
Config = #{<<"roomname">> => Name, <<"subject">> => Subject},
rpc(mim(), mod_muc_light_api, create_room, [Domain, CreatorJID, Config]).
create_instant_room(Room, Owner, Nick, Config) ->
Vars = #{room => room_to_bin(Room), owner => user_to_bin(Owner), nick => Nick},
execute_command(<<"muc">>, <<"createInstantRoom">>, Vars, Config).
invite_user(Room, Sender, Recipient, Reason, Config) ->
Vars = #{room => jid:to_binary(Room), sender => user_to_bin(Sender),
recipient => user_to_bin(Recipient), reason => Reason},
execute_command(<<"muc">>, <<"inviteUser">>, Vars, Config).
kick_user(Room, Nick, Reason, Config) ->
Vars = #{room => jid:to_binary(Room), nick => Nick, reason => Reason},
execute_command(<<"muc">>, <<"kickUser">>, Vars, Config).
send_message_to_room(Room, From, Body, Config) ->
Vars = #{room => jid:to_binary(Room), from => user_to_full_bin(From), body => Body},
execute_command(<<"muc">>, <<"sendMessageToRoom">>, Vars, Config).
send_private_message(Room, From, ToNick, Body, Config) ->
Vars = #{room => jid:to_binary(Room), from => user_to_full_bin(From),
toNick => ToNick, body => Body},
execute_command(<<"muc">>, <<"sendPrivateMessage">>, Vars, Config).
send_message_to_muc_light_room(RoomJID, SenderJID, Message) ->
rpc(mim(), mod_muc_light_api, send_message, [RoomJID, SenderJID, Message]).
enter_room(Room, User, Nick, Password, Config) ->
Vars = #{room => jid:to_binary(Room), user => user_to_full_bin(User),
nick => Nick, password => Password},
execute_command(<<"muc">>, <<"enterRoom">>, Vars, Config).
delete_room(Room, Reason, Config) ->
Vars = #{room => jid:to_binary(Room), reason => Reason},
execute_command(<<"muc">>, <<"deleteRoom">>, Vars, Config).
change_room_config(Room, RoomConfig, Config) ->
Vars = #{room => jid:to_binary(Room), config => RoomConfig},
execute_command(<<"muc">>, <<"changeRoomConfiguration">>, Vars, Config).
list_rooms(MUCDomain, From, Limit, Index, Config) ->
Vars = #{mucDomain => MUCDomain, from => user_to_bin(From), limit => Limit, index => Index},
execute_command(<<"muc">>, <<"listRooms">>, Vars, Config).
get_room_config(Room, Config) ->
Vars = #{room => jid:to_binary(Room)},
execute_command(<<"muc">>, <<"getRoomConfig">>, Vars, Config).
list_room_users(RoomJID, Config) ->
Vars = #{room => jid:to_binary(RoomJID)},
execute_command(<<"muc">>, <<"listRoomUsers">>, Vars, Config).
get_room_messages(RoomJID, PageSize, Before, Config) ->
Vars = #{<<"room">> => jid:to_binary(RoomJID), <<"pageSize">> => PageSize,
<<"before">> => Before},
execute_command(<<"muc">>, <<"getRoomMessages">>, Vars, Config).
set_user_affiliation(Room, User, Aff, Config) ->
Vars = #{room => jid:to_binary(Room), user => user_to_bin(User),
affiliation => atom_to_enum_item(Aff)},
execute_command(<<"muc">>, <<"setUserAffiliation">>, Vars, Config).
set_user_role(Room, User, Role, Config) ->
Vars = #{room => jid:to_binary(Room), nick => user_to_bin(User),
role => atom_to_enum_item(Role)},
execute_command(<<"muc">>, <<"setUserRole">>, Vars, Config).
exit_room(Room, User, Nick, Config) ->
Vars = #{room => jid:to_binary(Room), user => user_to_full_bin(User), nick => Nick},
execute_command(<<"muc">>, <<"exitRoom">>, Vars, Config).
list_room_affiliations(Room, Aff, Config) ->
Vars = #{room => jid:to_binary(Room), affiliation => atom_to_enum_item(Aff)},
execute_command(<<"muc">>, <<"listRoomAffiliations">>, Vars, Config).
user_kick_user(User, Room, Nick, Reason, Config) ->
Vars = #{room => jid:to_binary(Room), nick => Nick, reason => Reason},
execute_user_command(<<"muc">>, <<"kickUser">>, User, Vars, Config).
user_enter_room(User, Room, Nick, Resource, Password, Config) ->
Vars = #{room => jid:to_binary(Room), nick => Nick, resource => Resource, password => Password},
execute_user_command(<<"muc">>, <<"enterRoom">>, User, Vars, Config).
user_get_room_messages(User, RoomJID, PageSize, Before, Config) ->
Vars = #{<<"room">> => jid:to_binary(RoomJID), <<"pageSize">> => PageSize,
<<"before">> => Before},
execute_user_command(<<"muc">>, <<"getRoomMessages">>, User, Vars, Config).
user_get_muc_light_room_messages(User, RoomJID, PageSize, Before, Config) ->
Vars = #{<<"room">> => RoomJID, <<"pageSize">> => PageSize, <<"before">> => Before},
execute_user_command(<<"muc_light">>, <<"getRoomMessages">>, User, Vars, Config).
user_delete_room(User, Room, Reason, Config) ->
Vars = #{room => jid:to_binary(Room), reason => Reason},
execute_user_command(<<"muc">>, <<"deleteRoom">>, User, Vars, Config).
user_change_room_config(User, Room, RoomConfig, Config) ->
Vars = #{room => jid:to_binary(Room), config => RoomConfig},
execute_user_command(<<"muc">>, <<"changeRoomConfiguration">>, User, Vars, Config).
user_list_rooms(User, MUCDomain, Limit, Index, Config) ->
Vars = #{mucDomain => MUCDomain, limit => Limit, index => Index},
execute_user_command(<<"muc">>, <<"listRooms">>, User, Vars, Config).
user_get_room_config(User, Room, Config) ->
Vars = #{room => jid:to_binary(Room)},
execute_user_command(<<"muc">>, <<"getRoomConfig">>, User, Vars, Config).
user_list_room_users(User, RoomJID, Config) ->
Vars = #{room => jid:to_binary(RoomJID)},
execute_user_command(<<"muc">>, <<"listRoomUsers">>, User, Vars, Config).
user_send_message_to_room(User, Room, Body, Resource, Config) ->
Vars = #{room => jid:to_binary(Room), body => Body, resource => Resource},
execute_user_command(<<"muc">>, <<"sendMessageToRoom">>, User, Vars, Config).
user_send_private_message(User, Room, Body, ToNick, Resource, Config) ->
Vars = #{room => jid:to_binary(Room), body => Body, toNick => ToNick, resource => Resource},
execute_user_command(<<"muc">>, <<"sendPrivateMessage">>, User, Vars, Config).
user_create_instant_room(User, Room, Nick, Config) ->
Vars = #{room => room_to_bin(Room), nick => Nick},
execute_user_command(<<"muc">>, <<"createInstantRoom">>, User, Vars, Config).
user_invite_user(User, Room, Recipient, Reason, Config) ->
Vars = #{room => jid:to_binary(Room), recipient => user_to_bin(Recipient), reason => Reason},
execute_user_command(<<"muc">>, <<"inviteUser">>, User, Vars, Config).
user_set_user_affiliation(User, Room, QueriedUser, Aff, Config) ->
Vars = #{room => jid:to_binary(Room), user => user_to_bin(QueriedUser),
affiliation => atom_to_enum_item(Aff)},
execute_user_command(<<"muc">>, <<"setUserAffiliation">>, User, Vars, Config).
user_set_user_role(User, Room, QueriedUser, Role, Config) ->
Vars = #{room => jid:to_binary(Room), nick => user_to_bin(QueriedUser),
role => atom_to_enum_item(Role)},
execute_user_command(<<"muc">>, <<"setUserRole">>, User, Vars, Config).
user_exit_room(User, Room, Nick, Resource, Config) ->
Vars = #{room => jid:to_binary(Room), resource => Resource, nick => Nick},
execute_user_command(<<"muc">>, <<"exitRoom">>, User, Vars, Config).
user_list_room_affiliations(User, Room, Aff, Config) ->
Vars = #{room => jid:to_binary(Room), affiliation => atom_to_enum_item(Aff)},
execute_user_command(<<"muc">>, <<"listRoomAffiliations">>, User, Vars, Config).
room_to_bin(RoomJIDBin) when is_binary(RoomJIDBin) ->RoomJIDBin;
room_to_bin(RoomJID) -> jid:to_binary(RoomJID).
| null | https://raw.githubusercontent.com/esl/MongooseIM/997ce8cc01dacf8bf1f1f4e3a984ee10f0ce5dd6/big_tests/tests/graphql_muc_SUITE.erl | erlang | Should be sorted
Default fields
Create instant room
Delete room
make it start with a letter
Send message
Send message
Grant member affiliation
Grant admin affiliation
Revoke affiliation
Ban user
Change from participant to visitor
Change from visitor to participant
Change from participant to moderator
List all owners
List all members
List all
Admin MUC not configured test cases
Domain admin test cases
Create instant room with a non-existent domain
Create instant room with an external domain
Delete instant room with a non-existent domain
Delete instant room with an external domain
Send message
Send message
Enter room without password
Enter room with password
User test cases
Create instant room
Delete room
make it start with a letter
Send message
Send message, the resource should be normalized to "res2"
Send message
Send message, the resource should be normalized to "res2"
Send message
Not an owner tries to get room config
Not an owner tries to change the room config
Create a MUC Light room
Send a message
Try to get a MUC Light message
Non-existent room with non-existent domain
Non-existent room with existent domain
Grant a member affiliation
Grant a member affiliation
Grant a owner affiliation
Revoke affiliation
Ban user
Grant member affiliation
Revoke affiliation
Admin cannot grant admin affiliation
Admin cannot grant owner affiliation
Admin can ban member
Admin cannot ban owner
Member cannot grant member affiliation
Member cannot grant member admin affiliation
Member cannot grant member owner affiliation
Member cannot revoke member affiliation
Change from participant to visitor
Change from visitor to participant
Change from participant to moderator
Try change from participant to visitor
Change from participant to participant with success response
Try change from participant to moderator
List all owners
List all members
List all
User MUC not configured test cases
Helpers
Commands | -module(graphql_muc_SUITE).
-compile([export_all, nowarn_export_all]).
-import(common_helper, [unprep/1]).
-import(distributed_helper, [mim/0, require_rpc_nodes/1, rpc/4, subhost_pattern/1]).
-import(graphql_helper, [execute_command/4, execute_user_command/5, get_ok_value/2, get_err_msg/1,
get_coercion_err_msg/1, user_to_bin/1, user_to_full_bin/1, user_to_jid/1,
get_unauthorized/1, get_not_loaded/1]).
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
-include_lib("exml/include/exml.hrl").
-include_lib("jid/include/jid.hrl").
suite() ->
require_rpc_nodes([mim]) ++ escalus:suite().
all() ->
[{group, user},
{group, admin_http},
{group, admin_cli},
{group, domain_admin_muc}].
groups() ->
[{user, [], user_groups()},
{admin_http, [], admin_groups()},
{admin_cli, [], admin_groups()},
{admin_muc_configured, [], admin_muc_tests()},
{admin_muc_and_mam_configured, [], admin_muc_with_mam_tests()},
{admin_muc_not_configured, [], admin_muc_not_configured_tests()},
{user_muc_configured, [parallel], user_muc_tests()},
{user_muc_and_mam_configured, [parallel], user_muc_with_mam_tests()},
{user_muc_not_configured, [parallel], user_muc_not_configured_tests()},
{domain_admin_muc, [], domain_admin_muc_tests()}].
user_groups() ->
[{group, user_muc_configured},
{group, user_muc_and_mam_configured},
{group, user_muc_not_configured}].
admin_groups() ->
[{group, admin_muc_configured},
{group, admin_muc_and_mam_configured},
{group, admin_muc_not_configured}].
user_muc_tests() ->
[user_create_and_delete_room,
user_create_room_with_unprepped_name,
user_try_delete_nonexistent_room,
user_try_delete_room_by_not_owner,
user_try_create_instant_room_with_nonexistent_domain,
user_try_create_instant_room_with_invalid_args,
user_list_rooms,
user_try_list_rooms_for_nonexistent_domain,
user_list_room_users,
user_list_room_users_without_anonymous_mode,
user_try_list_room_users_without_permission,
user_try_list_nonexistent_room_users,
user_change_room_config,
user_try_change_nonexistent_room_config,
user_get_room_config,
user_try_get_nonexistent_room_config,
user_invite_user,
user_kick_user,
user_try_kick_user_from_nonexistent_room,
user_try_kick_user_without_moderator_resource,
user_send_message_to_room,
user_send_message_to_room_with_specified_res,
user_send_private_message,
user_without_session_send_message_to_room,
user_owner_set_user_affiliation,
user_admin_set_user_affiliation,
user_member_set_user_affiliation,
user_try_set_nonexistent_room_affiliation,
user_moderator_set_user_role,
user_participant_set_user_role,
user_try_set_nonexistent_room_role,
user_can_enter_room,
user_cannot_enter_room_with_invalid_resource,
user_can_enter_room_with_password,
user_can_exit_room,
user_list_room_affiliations,
user_try_list_room_affiliations_without_permission,
user_try_list_nonexistent_room_affiliations,
user_get_room_messages_muc_or_mam_not_configured
].
user_muc_with_mam_tests() ->
[user_get_room_messages,
user_shouldnt_store_messages_in_muc_light,
user_try_get_nonexistent_room_messages,
user_try_get_room_messages_without_permission].
user_muc_not_configured_tests() ->
[user_delete_room_muc_not_configured,
user_list_room_users_muc_not_configured,
user_change_room_config_muc_not_configured,
user_get_room_config_muc_not_configured,
user_invite_user_muc_not_configured,
user_kick_user_muc_not_configured,
user_send_message_to_room_muc_not_configured,
user_send_private_message_muc_not_configured,
user_get_room_messages_muc_or_mam_not_configured,
user_owner_set_user_affiliation_muc_not_configured,
user_moderator_set_user_role_muc_not_configured,
user_can_enter_room_muc_not_configured,
user_can_exit_room_muc_not_configured,
user_list_room_affiliations_muc_not_configured].
admin_muc_tests() ->
[admin_list_rooms,
admin_list_rooms_with_invalid_args,
admin_create_and_delete_room,
admin_create_room_with_unprepped_name,
admin_try_create_instant_room_with_nonexistent_domain,
admin_try_create_instant_room_with_nonexistent_user,
admin_try_create_instant_room_with_invalid_args,
admin_try_delete_nonexistent_room,
admin_try_delete_room_with_nonexistent_domain,
admin_try_list_rooms_for_nonexistent_domain,
admin_list_room_users,
admin_try_list_users_from_nonexistent_room,
admin_change_room_config,
admin_try_change_nonexistent_room_config,
admin_get_room_config,
admin_try_get_nonexistent_room_config,
admin_invite_user,
admin_invite_user_with_password,
admin_try_invite_user_to_nonexistent_room,
admin_kick_user,
admin_try_kick_user_from_nonexistent_room,
admin_try_kick_user_from_room_without_moderators,
admin_send_message_to_room,
admin_send_private_message,
admin_set_user_affiliation,
admin_try_set_nonexistent_room_user_affiliation,
admin_set_user_role,
admin_try_set_nonexistent_room_user_role,
admin_try_set_nonexistent_nick_role,
admin_try_set_user_role_in_room_without_moderators,
admin_make_user_enter_room,
admin_make_user_enter_room_with_password,
admin_make_user_enter_room_bare_jid,
admin_make_user_exit_room,
admin_make_user_exit_room_bare_jid,
admin_list_room_affiliations,
admin_try_list_nonexistent_room_affiliations,
admin_get_room_messages_muc_or_mam_not_configured
].
admin_muc_with_mam_tests() ->
[admin_get_room_messages,
admin_try_get_nonexistent_room_messages].
admin_muc_not_configured_tests() ->
[admin_delete_room_muc_not_configured,
admin_list_room_users_muc_not_configured,
admin_change_room_config_muc_not_configured,
admin_get_room_config_muc_not_configured,
admin_invite_user_muc_not_configured,
admin_kick_user_muc_not_configured,
admin_send_message_to_room_muc_not_configured,
admin_send_private_message_muc_not_configured,
admin_get_room_messages_muc_or_mam_not_configured,
admin_set_user_affiliation_muc_not_configured,
admin_set_user_role_muc_not_configured,
admin_make_user_enter_room_muc_not_configured,
admin_make_user_exit_room_muc_not_configured,
admin_list_room_affiliations_muc_not_configured].
domain_admin_muc_tests() ->
[admin_list_rooms,
admin_create_and_delete_room,
admin_create_room_with_unprepped_name,
admin_try_create_instant_room_with_nonexistent_domain,
admin_try_delete_nonexistent_room,
domain_admin_create_and_delete_room_no_permission,
domain_admin_list_rooms_no_permission,
admin_list_room_users,
domain_admin_list_room_users_no_permission,
admin_change_room_config,
domain_admin_change_room_config_no_permission,
admin_get_room_config,
domain_admin_get_room_config_no_permission,
admin_invite_user,
admin_invite_user_with_password,
admin_try_invite_user_to_nonexistent_room,
domain_admin_invite_user_no_permission,
admin_kick_user,
admin_try_kick_user_from_room_without_moderators,
domain_admin_kick_user_no_permission,
admin_send_message_to_room,
domain_admin_send_message_to_room_no_permission,
admin_send_private_message,
domain_admin_send_private_message_no_permission,
admin_get_room_messages,
domain_admin_get_room_messages_no_permission,
admin_set_user_affiliation,
domain_admin_set_user_affiliation_no_permission,
admin_set_user_role,
admin_try_set_nonexistent_nick_role,
admin_try_set_user_role_in_room_without_moderators,
domain_admin_set_user_role_no_permission,
admin_make_user_enter_room,
admin_make_user_enter_room_with_password,
admin_make_user_enter_room_bare_jid,
domain_admin_make_user_enter_room_no_permission,
admin_make_user_exit_room,
admin_make_user_exit_room_bare_jid,
domain_admin_make_user_exit_room_no_permission,
admin_list_room_affiliations,
domain_admin_list_room_affiliations_no_permission
].
init_per_suite(Config) ->
HostType = domain_helper:host_type(),
SecondaryHostType = domain_helper:secondary_host_type(),
Config2 = escalus:init_per_suite(Config),
Config3 = dynamic_modules:save_modules(HostType, Config2),
Config4 = dynamic_modules:save_modules(SecondaryHostType, Config3),
Config5 = ejabberd_node_utils:init(mim(), Config4),
dynamic_modules:restart(HostType, mod_disco,
config_parser_helper:default_mod_config(mod_disco)),
Config5.
end_per_suite(Config) ->
escalus_fresh:clean(),
mongoose_helper:ensure_muc_clean(),
muc_helper:unload_muc(),
dynamic_modules:restore_modules(Config),
escalus:end_per_suite(Config).
init_per_group(admin_http, Config) ->
graphql_helper:init_admin_handler(Config);
init_per_group(admin_cli, Config) ->
graphql_helper:init_admin_cli(Config);
init_per_group(domain_admin_muc, Config) ->
maybe_enable_mam(),
ensure_muc_started(),
graphql_helper:init_domain_admin_handler(Config);
init_per_group(user, Config) ->
graphql_helper:init_user(Config);
init_per_group(Group, Config) when Group =:= admin_muc_configured;
Group =:= user_muc_configured ->
disable_mam(),
ensure_muc_started(),
Config;
init_per_group(Group, Config) when Group =:= admin_muc_and_mam_configured;
Group =:= user_muc_and_mam_configured ->
case maybe_enable_mam() of
true ->
ensure_muc_started(),
ensure_muc_light_started(Config);
false ->
{skip, "No MAM backend available"}
end;
init_per_group(Group, Config) when Group =:= admin_muc_not_configured;
Group =:= user_muc_not_configured ->
maybe_enable_mam(),
ensure_muc_stopped(),
Config.
disable_mam() ->
dynamic_modules:ensure_modules(domain_helper:host_type(), [{mod_mam, stopped}]).
maybe_enable_mam() ->
case mam_helper:backend() of
disabled ->
false;
Backend ->
MAMOpts = mam_helper:config_opts(
#{backend => Backend,
muc => #{host => subhost_pattern(muc_helper:muc_host_pattern())},
async_writer => #{enabled => false}}),
dynamic_modules:ensure_modules(domain_helper:host_type(), [{mod_mam, MAMOpts}]),
true
end.
ensure_muc_started() ->
SecondaryHostType = domain_helper:secondary_host_type(),
muc_helper:load_muc(),
muc_helper:load_muc(SecondaryHostType),
mongoose_helper:ensure_muc_clean().
ensure_muc_stopped() ->
SecondaryHostType = domain_helper:secondary_host_type(),
muc_helper:unload_muc(),
muc_helper:unload_muc(SecondaryHostType).
ensure_muc_light_started(Config) ->
MucLightOpts = config_parser_helper:mod_config(mod_muc_light,
#{rooms_in_rosters => true, config_schema => custom_schema()}),
HostType = domain_helper:host_type(),
dynamic_modules:ensure_modules(HostType, [{mod_muc_light, MucLightOpts}]),
[{muc_light_host, muc_light_helper:muc_host()} | Config].
ensure_muc_light_stopped() ->
HostType = domain_helper:host_type(),
dynamic_modules:ensure_modules(HostType, [{mod_muc_light, stopped}]).
custom_schema() ->
[{<<"background">>, <<>>, background, binary},
{<<"music">>, <<>>, music, binary},
{<<"roomname">>, <<>>, roomname, binary},
{<<"subject">>, <<"Test">>, subject, binary}].
end_per_group(Group, _Config) when Group =:= user;
Group =:= admin_http;
Group =:= domain_admin_muc;
Group =:= admin_cli ->
graphql_helper:clean();
end_per_group(Group, _Config) when Group =:= admin_muc_and_mam_configured;
Group =:= user_muc_and_mam_configured ->
ensure_muc_light_stopped(),
escalus_fresh:clean();
end_per_group(_Group, _Config) ->
escalus_fresh:clean().
init_per_testcase(TC, Config) ->
escalus:init_per_testcase(TC, Config).
end_per_testcase(TC, Config) ->
escalus:end_per_testcase(TC, Config).
-define(CREATE_INSTANT_ROOM_PATH, [data, muc, createInstantRoom]).
-define(LIST_ROOMS_PATH, [data, muc, listRooms]).
-define(INVITE_USER_PATH, [data, muc, inviteUser]).
-define(KICK_USER_PATH, [data, muc, kickUser]).
-define(DELETE_ROOM_PATH, [data, muc, deleteRoom]).
-define(SEND_MESSAGE_PATH, [data, muc, sendMessageToRoom]).
-define(SEND_PRIV_MESG_PATH, [data, muc, sendPrivateMessage]).
-define(GET_MESSAGES_PATH, [data, muc, getRoomMessages]).
-define(LIST_ROOM_USERS_PATH, [data, muc, listRoomUsers]).
-define(LIST_ROOM_AFFILIATIONS_PATH, [data, muc, listRoomAffiliations]).
-define(CHANGE_ROOM_CONFIG_PATH, [data, muc, changeRoomConfiguration]).
-define(GET_ROOM_CONFIG_PATH, [data, muc, getRoomConfig]).
-define(SET_AFFILIATION_PATH, [data, muc, setUserAffiliation]).
-define(SET_ROLE_PATH, [data, muc, setUserRole]).
-define(ENTER_ROOM_PATH, [data, muc, enterRoom]).
-define(EXIT_ROOM_PATH, [data, muc, exitRoom]).
-define(NONEXISTENT_ROOM, <<"room@room">>).
-define(NONEXISTENT_ROOM2, <<"room@", (muc_helper:muc_host())/binary>>).
-define(EXTERNAL_DOMAIN_ROOM, <<"external_room@muc.", (domain_helper:secondary_domain())/binary>>).
-define(PASSWORD, <<"pa5sw0rd">>).
admin_list_rooms(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}, {bob, 1}], fun admin_list_rooms_story/3).
admin_list_rooms_story(Config, Alice, Bob) ->
Res0 = list_rooms(muc_helper:muc_host(), Alice, null, null, Config),
?assertEqual([], extract_rooms(get_ok_value(?LIST_ROOMS_PATH, Res0))),
AliceJID = jid:from_binary(escalus_client:short_jid(Alice)),
BobJID = jid:from_binary(escalus_client:short_jid(Bob)),
AliceRoom = rand_name(),
BobRoom = rand_name(),
muc_helper:create_instant_room(AliceRoom, AliceJID, <<"Ali">>, []),
muc_helper:create_instant_room(BobRoom, BobJID, <<"Bob">>, [{public_list, false}]),
Res1 = list_rooms(muc_helper:muc_host(), Alice, null, null, Config),
Rooms1 = [_, RoomB] = extract_rooms(get_ok_value(?LIST_ROOMS_PATH, Res1)),
?assertEqual(lists:sort([AliceRoom, BobRoom]), lists:sort(Rooms1)),
Res2 = list_rooms(unprep(muc_helper:muc_host()), Alice, null, null, Config),
?assertEqual(Rooms1, extract_rooms(get_ok_value(?LIST_ROOMS_PATH, Res2))),
Res3 = list_rooms(muc_helper:muc_host(), Alice, 1, 1, Config),
?assertEqual([RoomB], extract_rooms(get_ok_value(?LIST_ROOMS_PATH, Res3))).
admin_list_rooms_with_invalid_args(Config) ->
Config1 = escalus_fresh:create_users(Config, [{alice, 1}]),
AliceJid = escalus_users:get_jid(Config1, alice),
AliceDomain = escalus_users:get_host(Config1, alice),
Res1 = list_rooms(muc_helper:muc_host(), AliceDomain, null, null, Config1),
assert_coercion_err(Res1, <<"jid_without_local_part">>),
Res2 = list_rooms(muc_helper:muc_host(), AliceJid, 0, null, Config1),
assert_coercion_err(Res2, <<"Value is not a positive integer">>),
Res3 = list_rooms(muc_helper:muc_host(), AliceJid, null, -1, Config1),
assert_coercion_err(Res3, <<"Value is not a non-negative integer">>).
admin_try_list_rooms_for_nonexistent_domain(Config) ->
Config1 = escalus_fresh:create_users(Config, [{alice, 1}]),
AliceJID = escalus_users:get_jid(Config1, alice),
Res1 = list_rooms(<<"baddomain">>, AliceJID, null, null, Config1),
?assertMatch({_, _}, binary:match(get_err_msg(Res1), <<"not found">>)),
Domain instead of the MUC subdomain
Res2 = list_rooms(domain_helper:domain(), AliceJID, null, null, Config1),
?assertMatch({_, _}, binary:match(get_err_msg(Res2), <<"not found">>)).
admin_create_and_delete_room(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}], fun admin_create_and_delete_room_story/2).
admin_create_and_delete_room_story(Config, Alice) ->
Name = <<"first-alice-room">>,
MUCServer = muc_helper:muc_host(),
RoomJID = jid:make_bare(Name, MUCServer),
Res = create_instant_room(RoomJID, Alice, <<"Ali">>, Config),
?assertMatch(#{<<"title">> := Name, <<"private">> := false, <<"usersNumber">> := 0},
get_ok_value(?CREATE_INSTANT_ROOM_PATH, Res)),
Res2 = list_rooms(MUCServer, Alice, null, null, Config),
?assert(contain_room(Name, get_ok_value(?LIST_ROOMS_PATH, Res2))),
Res3 = delete_room(RoomJID, null, Config),
?assertNotEqual(nomatch, binary:match(get_ok_value(?DELETE_ROOM_PATH, Res3),
<<"successfully">>)),
Res4 = list_rooms(MUCServer, Alice, null, null, Config),
?assertNot(contain_room(Name, get_ok_value(?LIST_ROOMS_PATH, Res4))).
admin_create_room_with_unprepped_name(Config) ->
FreshConfig = escalus_fresh:create_users(Config, [{alice, 1}]),
AliceJid = escalus_users:get_jid(FreshConfig, alice),
MUCServer = muc_helper:muc_host(),
RoomJID = jid:make_noprep(unprep(Name), unprep(MUCServer), <<>>),
Res = create_instant_room(RoomJID, AliceJid, <<"Ali">>, FreshConfig),
?assertMatch(#{<<"title">> := Name, <<"private">> := false, <<"usersNumber">> := 0},
get_ok_value(?CREATE_INSTANT_ROOM_PATH, Res)),
Res2 = list_rooms(MUCServer, AliceJid, null, null, Config),
?assert(contain_room(Name, get_ok_value(?LIST_ROOMS_PATH, Res2))).
admin_try_create_instant_room_with_nonexistent_domain(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun admin_try_create_instant_room_with_nonexistent_domain_story/2).
admin_try_create_instant_room_with_nonexistent_domain_story(Config, Alice) ->
Res = create_instant_room(jid:make_bare(rand_name(), <<"unknown">>), Alice, <<"Ali">>, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_try_create_instant_room_with_nonexistent_user(Config) ->
RoomJID = jid:make_bare(rand_name(), muc_helper:muc_host()),
JID = <<(rand_name())/binary, "@localhost">>,
Res = create_instant_room(RoomJID, JID, <<"Ali">>, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_try_create_instant_room_with_invalid_args(Config) ->
Config1 = escalus_fresh:create_users(Config, [{alice, 1}]),
AliceJid = escalus_users:get_jid(Config1, alice),
AliceDomain = escalus_users:get_host(Config1, alice),
Domain = muc_helper:muc_host(),
Res1 = create_instant_room(<<"test room@", Domain/binary>>, AliceJid, <<"Ali">>, Config1),
assert_coercion_err(Res1, <<"failed_to_parse_jid">>),
Res2 = create_instant_room(<<"testroom@", Domain/binary, "/res1">>, AliceJid, <<"Ali">>, Config1),
assert_coercion_err(Res2, <<"jid_with_resource">>),
Res3 = create_instant_room(Domain, AliceJid, <<"Ali">>, Config1),
assert_coercion_err(Res3, <<"jid_without_local_part">>),
Res4 = create_instant_room(<<"testroom@", Domain/binary>>, AliceDomain, <<"Ali">>, Config1),
assert_coercion_err(Res4, <<"jid_without_local_part">>),
Res5 = create_instant_room(<<"testroom@", Domain/binary>>, AliceJid, <<>>, Config1),
assert_coercion_err(Res5, <<"empty_resource_name">>).
admin_try_delete_nonexistent_room(Config) ->
RoomJID = jid:make_bare(<<"unknown">>, muc_helper:muc_host()),
Res = delete_room(RoomJID, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"non-existent">>)).
admin_try_delete_room_with_nonexistent_domain(Config) ->
RoomJID = jid:make_bare(<<"unknown">>, <<"unknown">>),
Res = delete_room(RoomJID, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"non-existent">>)).
admin_invite_user(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}], fun admin_invite_user_story/3).
admin_invite_user_story(Config, Alice, Bob) ->
RoomJIDBin = ?config(room_jid, Config),
RoomJID = jid:from_binary(RoomJIDBin),
Res = invite_user(RoomJID, Alice, Bob, null, Config),
?assertNotEqual(nomatch, binary:match(get_ok_value(?INVITE_USER_PATH, Res),
<<"successfully">>)),
Stanza = escalus:wait_for_stanza(Bob),
escalus:assert(is_message, Stanza),
?assertEqual(RoomJIDBin,
exml_query:path(Stanza, [{element, <<"x">>}, {attr, <<"jid">>}])),
?assertEqual(undefined, exml_query:path(Stanza, [{element, <<"x">>}, {attr, <<"password">>}])).
admin_invite_user_with_password(Config) ->
muc_helper:story_with_room(Config, [{password_protected, true}, {password, ?PASSWORD}],
[{alice, 1}, {bob, 1}], fun admin_invite_user_with_password/3).
admin_invite_user_with_password(Config, Alice, Bob) ->
RoomJIDBin = ?config(room_jid, Config),
RoomJID = jid:from_binary(RoomJIDBin),
Res = invite_user(RoomJID, Alice, Bob, null, Config),
assert_success(?INVITE_USER_PATH, Res),
Stanza = escalus:wait_for_stanza(Bob),
escalus:assert(is_message, Stanza),
?assertEqual(RoomJIDBin,
exml_query:path(Stanza, [{element, <<"x">>}, {attr, <<"jid">>}])),
?assertEqual(?PASSWORD, exml_query:path(Stanza, [{element, <<"x">>}, {attr, <<"password">>}])).
admin_try_invite_user_to_nonexistent_room(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}, {bob, 1}],
fun admin_try_invite_user_to_nonexistent_room_story/3).
admin_try_invite_user_to_nonexistent_room_story(Config, Alice, Bob) ->
Res = invite_user(?NONEXISTENT_ROOM, Alice, Bob, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_kick_user(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}], fun admin_kick_user_story/3).
admin_kick_user_story(Config, Alice, Bob) ->
RoomJIDBin = ?config(room_jid, Config),
RoomJID = jid:from_binary(RoomJIDBin),
BobNick = <<"Bobek">>,
Reason = <<"You are too laud">>,
enter_room(RoomJID, Alice, <<"ali">>),
enter_room(RoomJID, Bob, BobNick),
Res = kick_user(RoomJID, BobNick, Reason, Config),
?assertNotEqual(nomatch, binary:match(get_ok_value(?KICK_USER_PATH, Res),
<<"successfully">>)),
escalus:wait_for_stanzas(Bob, 2),
KickStanza = escalus:wait_for_stanza(Bob),
escalus:assert(is_presence_with_type, [<<"unavailable">>], KickStanza),
?assertEqual(Reason,
exml_query:path(KickStanza, [{element, <<"x">>}, {element, <<"item">>},
{element, <<"reason">>}, cdata])).
admin_try_kick_user_from_room_without_moderators(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun admin_try_kick_user_from_room_without_moderators/3).
admin_try_kick_user_from_room_without_moderators(Config, _Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
BobNick = <<"Bobek">>,
enter_room(RoomJID, Bob, BobNick),
Res = kick_user(RoomJID, BobNick, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_try_kick_user_from_nonexistent_room(Config) ->
Res = kick_user(?NONEXISTENT_ROOM, <<"ali">>, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_send_message_to_room(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun admin_send_message_to_room_story/3).
admin_send_message_to_room_story(Config, _Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Message = <<"Hello All!">>,
BobNick = <<"Bobek">>,
enter_room(RoomJID, Bob, BobNick),
escalus:wait_for_stanza(Bob),
Try send message from bare JID ,
BareBob = escalus_client:short_jid(Bob),
Res = send_message_to_room(RoomJID, BareBob, Message, Config),
assert_no_full_jid(Res),
Res1 = send_message_to_room(RoomJID, Bob, Message, Config),
?assertNotEqual(nomatch, binary:match(get_ok_value(?SEND_MESSAGE_PATH, Res1),
<<"successfully">>)),
assert_is_message_correct(RoomJID, BobNick, <<"groupchat">>, Message,
escalus:wait_for_stanza(Bob)).
admin_send_private_message(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun admin_send_private_message/3).
admin_send_private_message(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Message = <<"Hello Bob!">>,
BobNick = <<"Bobek">>,
AliceNick = <<"Ali">>,
enter_room(RoomJID, Alice, AliceNick),
enter_room(RoomJID, Bob, BobNick),
escalus:wait_for_stanzas(Bob, 2),
Try send private message from bare JID ,
BareAlice = escalus_client:short_jid(Alice),
Res = send_private_message(RoomJID, BareAlice, BobNick, Message, Config),
assert_no_full_jid(Res),
Try send private message to empty nick
Res1 = send_private_message(RoomJID, Alice, <<>>, Message, Config),
assert_coercion_err(Res1, <<"empty_resource_name">>),
Res2 = send_private_message(RoomJID, Alice, BobNick, Message, Config),
assert_success(?SEND_PRIV_MESG_PATH, Res2),
assert_is_message_correct(RoomJID, AliceNick, <<"chat">>, Message,
escalus:wait_for_stanza(Bob)).
admin_get_room_config(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}], fun admin_get_room_config_story/2).
admin_get_room_config_story(Config, _Alice) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Res = get_room_config(RoomJID, Config),
assert_default_room_config(Res).
admin_try_get_nonexistent_room_config(Config) ->
Res = get_room_config(?NONEXISTENT_ROOM, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_change_room_config(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}], fun admin_change_room_config_story/2).
admin_change_room_config_story(Config, _Alice) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Title = <<"aloes">>,
Description = <<"The chat about aloes">>,
Public = false,
RoomConfig = #{title => Title, description => Description, public => Public},
Res = change_room_config(RoomJID, RoomConfig, Config),
?assertMatch(#{<<"title">> := Title,
<<"description">> := Description,
<<"public">> := Public}, get_ok_value(?CHANGE_ROOM_CONFIG_PATH, Res)).
admin_try_change_nonexistent_room_config(Config) ->
RoomConfig = #{title => <<"NewTitle">>},
Res = change_room_config(?NONEXISTENT_ROOM, RoomConfig, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_list_room_users(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun admin_list_room_users_story/3).
admin_list_room_users_story(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
BobNick = <<"Bobek">>,
AliceNick = <<"Ali">>,
enter_room(RoomJID, Bob, BobNick),
enter_room(RoomJID, Alice, AliceNick),
Res = list_room_users(RoomJID, Config),
ExpectedUsers = [{escalus_client:full_jid(Bob), BobNick, <<"PARTICIPANT">>},
{escalus_client:full_jid(Alice), AliceNick, <<"MODERATOR">>}],
assert_room_users(ExpectedUsers, get_ok_value(?LIST_ROOM_USERS_PATH, Res)).
admin_try_list_users_from_nonexistent_room(Config) ->
Res = list_room_users(?NONEXISTENT_ROOM, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_get_room_messages(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun admin_get_room_messages_story/3).
admin_get_room_messages_story(Config, Alice, Bob) ->
RoomJID = #jid{luser = RoomName, lserver = MUCDomain} =
jid:from_binary(?config(room_jid, Config)),
enter_room(RoomJID, Bob, <<"Bobek">>),
enter_room(RoomJID, Alice, <<"Ali">>),
escalus:wait_for_stanzas(Bob, 2),
send_message_to_room(RoomJID, Bob, <<"Hi!">>, Config),
escalus:wait_for_stanzas(Bob, 1),
mam_helper:wait_for_room_archive_size(MUCDomain, RoomName, 1),
Res = get_room_messages(RoomJID, 50, null, Config),
#{<<"stanzas">> := [#{<<"stanza">> := StanzaXML}], <<"limit">> := 50} =
get_ok_value(?GET_MESSAGES_PATH, Res),
?assertMatch({ok, #xmlel{name = <<"message">>}}, exml:parse(StanzaXML)).
admin_try_get_nonexistent_room_messages(Config) ->
Res = get_room_messages(?NONEXISTENT_ROOM, null, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_set_user_affiliation(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun admin_set_user_affiliation/3).
admin_set_user_affiliation(Config, _Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Res = set_user_affiliation(RoomJID, Bob, member, Config),
assert_success(?SET_AFFILIATION_PATH, Res),
assert_user_affiliation(RoomJID, Bob, member),
Res1 = set_user_affiliation(RoomJID, Bob, admin, Config),
assert_success(?SET_AFFILIATION_PATH, Res1),
assert_user_affiliation(RoomJID, Bob, admin),
Grant owner affiliation
Res2 = set_user_affiliation(RoomJID, Bob, owner, Config),
assert_success(?SET_AFFILIATION_PATH, Res2),
assert_user_affiliation(RoomJID, Bob, owner),
Res3 = set_user_affiliation(RoomJID, Bob, none, Config),
assert_success(?SET_AFFILIATION_PATH, Res3),
assert_user_affiliation(RoomJID, Bob, none),
Res4 = set_user_affiliation(RoomJID, Bob, outcast, Config),
assert_success(?SET_AFFILIATION_PATH, Res4),
assert_user_affiliation(RoomJID, Bob, outcast).
admin_try_set_nonexistent_room_user_affiliation(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun admin_try_set_nonexistent_room_user_affiliation/2).
admin_try_set_nonexistent_room_user_affiliation(Config, Alice) ->
Res = set_user_affiliation(?NONEXISTENT_ROOM, Alice, admin, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_set_user_role(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}], fun admin_set_user_role/3).
admin_set_user_role(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
BobNick = <<"Boobek">>,
enter_room(RoomJID, Alice, escalus_client:username(Alice)),
enter_room(RoomJID, Bob, BobNick),
Res = set_user_role(RoomJID, BobNick, visitor, Config),
assert_success(?SET_ROLE_PATH, Res),
assert_user_role(RoomJID, Bob, visitor),
Res1 = set_user_role(RoomJID, BobNick, participant, Config),
assert_success(?SET_ROLE_PATH, Res1),
assert_user_role(RoomJID, Bob, participant),
Res2 = set_user_role(RoomJID, BobNick, moderator, Config),
assert_success(?SET_ROLE_PATH, Res2),
assert_user_role(RoomJID, Bob, moderator).
admin_try_set_nonexistent_nick_role(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}], fun admin_try_set_nonexistent_nick_role/2).
admin_try_set_nonexistent_nick_role(Config, Alice) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
enter_room(RoomJID, Alice, escalus_client:username(Alice)),
Res = set_user_role(RoomJID, <<"kik">>, visitor, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"does not exist">>)).
admin_try_set_user_role_in_room_without_moderators(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun admin_try_set_user_role_in_room_without_moderators/3).
admin_try_set_user_role_in_room_without_moderators(Config, _Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
BobNick = <<"Boobek">>,
enter_room(RoomJID, Bob, BobNick),
Res = set_user_role(RoomJID, BobNick, visitor, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_try_set_nonexistent_room_user_role(Config) ->
Res = set_user_role(?NONEXISTENT_ROOM, <<"Alice">>, moderator, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_make_user_enter_room(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}], fun admin_make_user_enter_room/2).
admin_make_user_enter_room(Config, Alice) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Nick = <<"ali">>,
JID = jid:from_binary(escalus_client:full_jid(Alice)),
enter room with password
Res = enter_room(RoomJID, Alice, Nick, null, Config),
assert_success(?ENTER_ROOM_PATH, Res),
?assertMatch([#{nick := Nick, jid := JID}], get_room_users(RoomJID)).
admin_make_user_enter_room_with_password(Config) ->
muc_helper:story_with_room(Config, [{password_protected, true}, {password, ?PASSWORD}],
[{alice, 1}, {bob, 1}],
fun admin_make_user_enter_room_with_password/3).
admin_make_user_enter_room_with_password(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Nick = <<"ali">>,
JID = jid:from_binary(escalus_client:full_jid(Alice)),
enter room with password
Res = enter_room(RoomJID, Alice, Nick, ?PASSWORD, Config),
assert_success(?ENTER_ROOM_PATH, Res),
?assertMatch([#{nick := Nick, jid := JID}], get_room_users(RoomJID)),
try enter room without password
Res1 = enter_room(RoomJID, Bob, <<"Bobek">>, null, Config),
assert_success(?ENTER_ROOM_PATH, Res1),
?assertMatch([_], get_room_users(RoomJID)),
enter room with password
Res2 = enter_room(RoomJID, Bob, <<"Bobek">>, ?PASSWORD, Config),
assert_success(?ENTER_ROOM_PATH, Res2),
?assertMatch([_, _], get_room_users(RoomJID)).
admin_make_user_enter_room_bare_jid(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}], fun admin_make_user_enter_room_bare_jid/2).
admin_make_user_enter_room_bare_jid(Config, Alice) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
BareAlice = escalus_client:short_jid(Alice),
Res = enter_room(RoomJID, BareAlice, <<"Ali">>, null, Config),
assert_no_full_jid(Res).
admin_make_user_exit_room(Config) ->
muc_helper:story_with_room(Config, [{persistent, true}], [{alice, 1}],
fun admin_make_user_exit_room/2).
admin_make_user_exit_room(Config, Alice) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Nick = <<"ali">>,
enter_room(RoomJID, Alice, Nick),
?assertMatch([_], get_room_users(RoomJID)),
Res = exit_room(RoomJID, Alice, Nick, Config),
assert_success(?EXIT_ROOM_PATH, Res),
?assertMatch([], get_room_users(RoomJID)).
admin_make_user_exit_room_bare_jid(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}], fun admin_make_user_exit_room_bare_jid/2).
admin_make_user_exit_room_bare_jid(Config, Alice) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
BareAlice = escalus_client:short_jid(Alice),
Nick = <<"ali">>,
enter_room(RoomJID, Alice, Nick),
Res = exit_room(RoomJID, BareAlice, Nick, Config),
assert_no_full_jid(Res).
admin_list_room_affiliations(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun admin_list_room_affiliations/3).
admin_list_room_affiliations(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
BobNick = <<"Bobek">>,
AliceNick = <<"Ali">>,
enter_room(RoomJID, Bob, BobNick),
enter_room(RoomJID, Alice, AliceNick),
AliceJID = escalus_utils:jid_to_lower(escalus_client:short_jid(Alice)),
BobJID = escalus_utils:jid_to_lower(escalus_client:short_jid(Bob)),
Res = list_room_affiliations(RoomJID, owner, Config),
?assertMatch([#{<<"jid">> := AliceJID, <<"affiliation">> := <<"OWNER">>}],
get_ok_value(?LIST_ROOM_AFFILIATIONS_PATH, Res)),
set_user_affiliation(RoomJID, Bob, member, Config),
Res1 = list_room_affiliations(RoomJID, member, Config),
?assertMatch([#{<<"jid">> := BobJID, <<"affiliation">> := <<"MEMBER">>}],
get_ok_value(?LIST_ROOM_AFFILIATIONS_PATH, Res1)),
Res2 = list_room_affiliations(RoomJID, null, Config),
?assertMatch([_, _], get_ok_value(?LIST_ROOM_AFFILIATIONS_PATH, Res2)).
admin_try_list_nonexistent_room_affiliations(Config) ->
Res = list_room_affiliations(?NONEXISTENT_ROOM, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
admin_delete_room_muc_not_configured(Config) ->
Res = delete_room(get_room_name(), null, Config),
get_not_loaded(Res).
admin_list_room_users_muc_not_configured(Config) ->
Res = list_room_users(get_room_name(), Config),
get_not_loaded(Res).
admin_change_room_config_muc_not_configured(Config) ->
RoomConfig = #{title => <<"NewTitle">>},
Res = change_room_config(get_room_name(), RoomConfig, Config),
get_not_loaded(Res).
admin_get_room_config_muc_not_configured(Config) ->
Res = get_room_config(get_room_name(), Config),
get_not_loaded(Res).
admin_invite_user_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}, {bob, 1}],
fun admin_invite_user_muc_not_configured_story/3).
admin_invite_user_muc_not_configured_story(Config, Alice, Bob) ->
Res = invite_user(get_room_name(), Alice, Bob, null, Config),
get_not_loaded(Res).
admin_kick_user_muc_not_configured(Config) ->
Res = kick_user(get_room_name(), <<"nick">>, <<"reason">>, Config),
get_not_loaded(Res).
admin_send_message_to_room_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun admin_send_message_to_room_muc_not_configured_story/2).
admin_send_message_to_room_muc_not_configured_story(Config, Alice) ->
Res = send_message_to_room(get_room_name(), Alice, <<"body">>, Config),
get_not_loaded(Res).
admin_send_private_message_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun admin_send_private_message_muc_not_configured_story/2).
admin_send_private_message_muc_not_configured_story(Config, Alice) ->
Nick = <<"ali">>,
Res = send_private_message(get_room_name(), Alice, Nick, <<"body">>, Config),
get_not_loaded(Res).
admin_get_room_messages_muc_or_mam_not_configured(Config) ->
Res = get_room_messages(get_room_name(), 4, null, Config),
get_not_loaded(Res).
admin_set_user_affiliation_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun admin_set_user_affiliation_muc_not_configured_story/2).
admin_set_user_affiliation_muc_not_configured_story(Config, Alice) ->
Res = set_user_affiliation(get_room_name(), Alice, member, Config),
get_not_loaded(Res).
admin_set_user_role_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun admin_set_user_role_muc_not_configured_story/2).
admin_set_user_role_muc_not_configured_story(Config, Alice) ->
Res = set_user_role(get_room_name(), Alice, moderator, Config),
get_not_loaded(Res).
admin_make_user_enter_room_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun admin_make_user_enter_room_muc_light_not_configured_story/2).
admin_make_user_enter_room_muc_light_not_configured_story(Config, Alice) ->
Nick = <<"ali">>,
Res = enter_room(get_room_name(), Alice, Nick, null, Config),
get_not_loaded(Res).
admin_make_user_exit_room_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun admin_make_user_exit_room_muc_not_configured_story/2).
admin_make_user_exit_room_muc_not_configured_story(Config, Alice) ->
Nick = <<"ali">>,
Res = exit_room(get_room_name(), Alice, Nick, Config),
get_not_loaded(Res).
admin_list_room_affiliations_muc_not_configured(Config) ->
Res = list_room_affiliations(get_room_name(), member, Config),
get_not_loaded(Res).
domain_admin_try_delete_room_with_nonexistent_domain(Config) ->
RoomJID = jid:make_bare(<<"unknown">>, <<"unknown">>),
get_unauthorized(delete_room(RoomJID, null, Config)).
domain_admin_create_and_delete_room_no_permission(Config) ->
escalus:fresh_story_with_config(Config, [{alice_bis, 1}],
fun domain_admin_create_and_delete_room_no_permission_story/2).
domain_admin_create_and_delete_room_no_permission_story(Config, AliceBis) ->
ExternalDomain = domain_helper:secondary_domain(),
UnknownDomain = <<"unknown">>,
RoomJid = jid:make_bare(rand_name(), muc_helper:muc_host()),
ExternalServer = <<"muc.", ExternalDomain/binary>>,
UnknownJID = <<(rand_name())/binary, "@", UnknownDomain/binary>>,
Res = create_instant_room(RoomJid, UnknownJID, <<"Ali">>, Config),
get_unauthorized(Res),
Res2 = create_instant_room(RoomJid, AliceBis, <<"Ali">>, Config),
get_unauthorized(Res2),
UnknownRoomJID = jid:make_bare(<<"unknown_room">>, UnknownDomain),
Res3 = delete_room(UnknownRoomJID, null, Config),
get_unauthorized(Res3),
ExternalRoomJID = jid:make_bare(<<"external_room">>, ExternalServer),
Res4 = delete_room(ExternalRoomJID, null, Config),
get_unauthorized(Res4).
domain_admin_list_rooms_no_permission(Config) ->
escalus:fresh_story_with_config(Config, [{alice_bis, 1}],
fun domain_admin_list_rooms_no_permission_story/2).
domain_admin_list_rooms_no_permission_story(Config, AliceBis) ->
AliceBisJID = jid:from_binary(escalus_client:short_jid(AliceBis)),
AliceBisRoom = rand_name(),
muc_helper:create_instant_room(AliceBisRoom, AliceBisJID, <<"Ali">>, []),
Res = list_rooms(muc_helper:muc_host(), AliceBis, null, null, Config),
get_unauthorized(Res).
domain_admin_list_room_users_no_permission(Config) ->
get_unauthorized(list_room_users(?NONEXISTENT_ROOM, Config)),
get_unauthorized(list_room_users(?EXTERNAL_DOMAIN_ROOM, Config)).
domain_admin_change_room_config_no_permission(Config) ->
RoomConfig = #{title => <<"NewTitle">>},
get_unauthorized(change_room_config(?NONEXISTENT_ROOM, RoomConfig, Config)),
get_unauthorized(change_room_config(?EXTERNAL_DOMAIN_ROOM, RoomConfig, Config)).
domain_admin_get_room_config_no_permission(Config) ->
get_unauthorized(get_room_config(?NONEXISTENT_ROOM, Config)),
get_unauthorized(get_room_config(?EXTERNAL_DOMAIN_ROOM, Config)).
domain_admin_invite_user_no_permission(Config) ->
muc_helper:story_with_room(Config, [], [{alice_bis, 1}, {bob, 1}],
fun domain_admin_invite_user_no_permission_story/3).
domain_admin_invite_user_no_permission_story(Config, Alice, Bob) ->
RoomJIDBin = ?config(room_jid, Config),
RoomJID = jid:from_binary(RoomJIDBin),
Res = invite_user(RoomJID, Alice, Bob, null, Config),
get_unauthorized(Res).
domain_admin_kick_user_no_permission(Config) ->
get_unauthorized(kick_user(?NONEXISTENT_ROOM, <<"ali">>, null, Config)),
get_unauthorized(kick_user(?EXTERNAL_DOMAIN_ROOM, <<"ali">>, null, Config)).
domain_admin_send_message_to_room_no_permission(Config) ->
muc_helper:story_with_room(Config, [], [{alice_bis, 1}],
fun domain_admin_send_message_to_room_no_permission_story/2).
domain_admin_send_message_to_room_no_permission_story(Config, AliceBis) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Message = <<"Hello All!">>,
AliceNick = <<"Bobek">>,
enter_room(RoomJID, AliceBis, AliceNick),
escalus:wait_for_stanza(AliceBis),
Res = send_message_to_room(RoomJID, AliceBis, Message, Config),
get_unauthorized(Res).
domain_admin_send_private_message_no_permission(Config) ->
muc_helper:story_with_room(Config, [], [{alice_bis, 1}, {bob, 1}],
fun domain_admin_send_private_message_no_permission_story/3).
domain_admin_send_private_message_no_permission_story(Config, AliceBis, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Message = <<"Hello Bob!">>,
BobNick = <<"Bobek">>,
AliceBisNick = <<"Ali">>,
enter_room(RoomJID, AliceBis, AliceBisNick),
enter_room(RoomJID, Bob, BobNick),
escalus:wait_for_stanzas(Bob, 2),
Res = send_private_message(RoomJID, AliceBis, BobNick, Message, Config),
get_unauthorized(Res).
domain_admin_get_room_messages_no_permission(Config) ->
get_unauthorized(get_room_messages(?NONEXISTENT_ROOM, null, null, Config)),
get_unauthorized(get_room_messages(?EXTERNAL_DOMAIN_ROOM, null, null, Config)).
domain_admin_set_user_affiliation_no_permission(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun domain_admin_set_user_affiliation_no_permission_story/2).
domain_admin_set_user_affiliation_no_permission_story(Config, Alice) ->
get_unauthorized(set_user_affiliation(?NONEXISTENT_ROOM, Alice, admin, Config)),
get_unauthorized(set_user_affiliation(?EXTERNAL_DOMAIN_ROOM, Alice, admin, Config)).
domain_admin_set_user_role_no_permission(Config) ->
get_unauthorized(set_user_role(?NONEXISTENT_ROOM, <<"Alice">>, moderator, Config)),
get_unauthorized(set_user_role(?EXTERNAL_DOMAIN_ROOM, <<"Alice">>, moderator, Config)).
domain_admin_list_room_affiliations_no_permission(Config) ->
get_unauthorized(list_room_affiliations(?NONEXISTENT_ROOM, null, Config)),
get_unauthorized(list_room_affiliations(?EXTERNAL_DOMAIN_ROOM, null, Config)).
domain_admin_make_user_enter_room_no_permission(Config) ->
muc_helper:story_with_room(Config, [], [{alice_bis, 1}],
fun domain_admin_make_user_enter_room_no_permission_story/2).
domain_admin_make_user_enter_room_no_permission_story(Config, AliceBis) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Nick = <<"ali">>,
Res = enter_room(RoomJID, AliceBis, Nick, null, Config),
get_unauthorized(Res),
Res2 = enter_room(RoomJID, AliceBis, Nick, ?PASSWORD, Config),
get_unauthorized(Res2).
domain_admin_make_user_exit_room_no_permission(Config) ->
muc_helper:story_with_room(Config, [{persistent, true}], [{alice_bis, 1}],
fun domain_admin_make_user_exit_room_no_permission_story/2).
domain_admin_make_user_exit_room_no_permission_story(Config, AliceBis) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Nick = <<"ali">>,
enter_room(RoomJID, AliceBis, Nick),
?assertMatch([_], get_room_users(RoomJID)),
Res = exit_room(RoomJID, AliceBis, Nick, Config),
get_unauthorized(Res).
user_list_rooms(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}, {bob, 1}], fun user_list_rooms_story/3).
user_list_rooms_story(Config, Alice, Bob) ->
AliceJID = jid:from_binary(escalus_client:short_jid(Alice)),
BobJID = jid:from_binary(escalus_client:short_jid(Bob)),
AliceRoom = rand_name(),
BobRoom = rand_name(),
muc_helper:create_instant_room(AliceRoom, AliceJID, <<"Ali">>, []),
muc_helper:create_instant_room(BobRoom, BobJID, <<"Bob">>, []),
Res = user_list_rooms(Alice, muc_helper:muc_host(), null, null, Config),
#{<<"rooms">> := Rooms } = get_ok_value(?LIST_ROOMS_PATH, Res),
?assert(contain_room(AliceRoom, Rooms)),
?assert(contain_room(BobRoom, Rooms)).
user_try_list_rooms_for_nonexistent_domain(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_try_list_rooms_for_nonexistent_domain_story/2).
user_try_list_rooms_for_nonexistent_domain_story(Config, Alice) ->
Res1 = user_list_rooms(Alice, <<"baddomain">>, null, null, Config),
?assertMatch({_, _}, binary:match(get_err_msg(Res1), <<"not found">>)),
Domain instead of the MUC subdomain
Res2 = user_list_rooms(Alice, domain_helper:domain(), null, null, Config),
?assertMatch({_, _}, binary:match(get_err_msg(Res2), <<"not found">>)).
user_create_and_delete_room(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}], fun user_create_and_delete_room_story/2).
user_create_and_delete_room_story(Config, Alice) ->
Name = rand_name(),
MUCServer = muc_helper:muc_host(),
RoomJID = jid:make_bare(Name, MUCServer),
Res = user_create_instant_room(Alice, RoomJID, <<"Ali">>, Config),
?assertMatch(#{<<"title">> := Name, <<"private">> := false, <<"usersNumber">> := 0},
get_ok_value(?CREATE_INSTANT_ROOM_PATH, Res)),
Res2 = user_list_rooms(Alice, MUCServer, null, null, Config),
?assert(contain_room(Name, get_ok_value(?LIST_ROOMS_PATH, Res2))),
Res3 = user_delete_room(Alice, RoomJID, null, Config),
?assertNotEqual(nomatch, binary:match(get_ok_value(?DELETE_ROOM_PATH, Res3),
<<"successfully">>)),
Res4 = user_list_rooms(Alice, MUCServer, null, null, Config),
?assertNot(contain_room(Name, get_ok_value(?LIST_ROOMS_PATH, Res4))).
user_create_room_with_unprepped_name(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_create_room_with_unprepped_name_story/2).
user_create_room_with_unprepped_name_story(Config, Alice) ->
MUCServer = muc_helper:muc_host(),
RoomJid = jid:make_noprep(unprep(Name), unprep(MUCServer), <<>>),
Res = user_create_instant_room(Alice, RoomJid, <<"Ali">>, Config),
?assertMatch(#{<<"title">> := Name, <<"private">> := false, <<"usersNumber">> := 0},
get_ok_value(?CREATE_INSTANT_ROOM_PATH, Res)).
user_try_create_instant_room_with_nonexistent_domain(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_try_create_instant_room_with_nonexistent_domain_story/2).
user_try_create_instant_room_with_nonexistent_domain_story(Config, Alice) ->
RoomJID = jid:make_bare(rand_name(), <<"unknown">>),
Res = user_create_instant_room(Alice, RoomJID, <<"Ali">>, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
user_try_create_instant_room_with_invalid_args(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_try_create_instant_room_with_invalid_args_story/2).
user_try_create_instant_room_with_invalid_args_story(Config, Alice) ->
Domain = muc_helper:muc_host(),
Res1 = user_create_instant_room(Alice, <<"test room@", Domain/binary>>, <<"Ali">>, Config),
assert_coercion_err(Res1, <<"failed_to_parse_jid">>),
Res2 = user_create_instant_room(Alice, <<"testroom@", Domain/binary, "/res1">>, <<"Ali">>, Config),
assert_coercion_err(Res2, <<"jid_with_resource">>),
Res3 = user_create_instant_room(Alice, <<"testroom@", Domain/binary>>, <<>>, Config),
assert_coercion_err(Res3, <<"empty_resource_name">>).
user_try_delete_nonexistent_room(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_try_delete_nonexistent_room_story/2).
user_try_delete_nonexistent_room_story(Config, Alice) ->
RoomJID = jid:make_bare(<<"unknown">>, muc_helper:muc_host()),
Res = user_delete_room(Alice, RoomJID, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"non-existent">>)).
user_try_delete_room_by_not_owner(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun user_try_delete_room_by_not_owner_story/3).
user_try_delete_room_by_not_owner_story(Config, _Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Res = user_delete_room(Bob, RoomJID, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"does not have permission">>)).
user_invite_user(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}], fun user_invite_user_story/3).
user_invite_user_story(Config, Alice, Bob) ->
RoomJIDBin = ?config(room_jid, Config),
RoomJID = jid:from_binary(RoomJIDBin),
Res = user_invite_user(Alice, RoomJID, Bob, null, Config),
?assertNotEqual(nomatch, binary:match(get_ok_value(?INVITE_USER_PATH, Res),
<<"successfully">>)),
Stanza = escalus:wait_for_stanza(Bob),
escalus:assert(is_message, Stanza),
?assertEqual(RoomJIDBin,
exml_query:path(Stanza, [{element, <<"x">>}, {attr, <<"jid">>}])).
user_kick_user(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}], fun user_kick_user_story/3).
user_kick_user_story(Config, Alice, Bob) ->
RoomJIDBin = ?config(room_jid, Config),
RoomJID = jid:from_binary(RoomJIDBin),
BobNick = <<"Bobek">>,
Reason = <<"You are too loud">>,
enter_room(RoomJID, Alice, <<"ali">>),
enter_room(RoomJID, Bob, BobNick),
Res = user_kick_user(Alice, RoomJID, BobNick, Reason, Config),
?assertNotEqual(nomatch, binary:match(get_ok_value(?KICK_USER_PATH, Res),
<<"successfully">>)),
escalus:wait_for_stanzas(Bob, 2),
KickStanza = escalus:wait_for_stanza(Bob),
escalus:assert(is_presence_with_type, [<<"unavailable">>], KickStanza),
?assertEqual(Reason,
exml_query:path(KickStanza, [{element, <<"x">>}, {element, <<"item">>},
{element, <<"reason">>}, cdata])).
user_try_kick_user_without_moderator_resource(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun user_try_kick_user_without_moderator_resource/3).
user_try_kick_user_without_moderator_resource(Config, Alice, Bob) ->
RoomJIDBin = ?config(room_jid, Config),
RoomJID = jid:from_binary(RoomJIDBin),
BobNick = <<"Bobek">>,
enter_room(RoomJID, Bob, BobNick),
Res = user_kick_user(Alice, RoomJID, BobNick, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
user_try_kick_user_from_nonexistent_room(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_try_kick_user_from_nonexistent_room/2).
user_try_kick_user_from_nonexistent_room(Config, Alice) ->
Res = user_kick_user(Alice, ?NONEXISTENT_ROOM, <<"bobi">>, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
user_send_message_to_room(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun user_send_message_to_room_story/3).
user_send_message_to_room_story(Config, _Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Message = <<"Hello All!">>,
BobNick = <<"Bobek">>,
enter_room(RoomJID, Bob, BobNick),
escalus:wait_for_stanza(Bob),
Res = user_send_message_to_room(Bob, RoomJID, Message, null, Config),
?assertNotEqual(nomatch, binary:match(get_ok_value(?SEND_MESSAGE_PATH, Res),
<<"successfully">>)),
assert_is_message_correct(RoomJID, BobNick, <<"groupchat">>, Message,
escalus:wait_for_stanza(Bob)).
user_send_message_to_room_with_specified_res(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 2}],
fun user_send_message_to_room_with_specified_res_story/4).
user_send_message_to_room_with_specified_res_story(Config, _Alice, Bob, Bob2) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Message = <<"Hello All!">>,
BobNick = <<"Bobek">>,
enter_room(RoomJID, Bob2, BobNick),
escalus:wait_for_stanza(Bob2),
Res = user_send_message_to_room(Bob, RoomJID, Message, <<"res₂"/utf8>>, Config),
?assertNotEqual(nomatch, binary:match(get_ok_value(?SEND_MESSAGE_PATH, Res),
<<"successfully">>)),
assert_is_message_correct(RoomJID, BobNick, <<"groupchat">>, Message,
escalus:wait_for_stanza(Bob2)).
user_send_private_message(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun user_send_private_message/3).
user_send_private_message(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Message = <<"Hello Bob!">>,
BobNick = <<"Bobek">>,
AliceNick = <<"Ali">>,
enter_room(RoomJID, Bob, BobNick),
enter_room(RoomJID, Alice, AliceNick),
escalus:wait_for_stanzas(Bob, 2),
Res = user_send_private_message(Alice, RoomJID, Message, BobNick, null, Config),
assert_success(?SEND_PRIV_MESG_PATH, Res),
assert_is_message_correct(RoomJID, AliceNick, <<"chat">>, Message,
escalus:wait_for_stanza(Bob)).
user_send_private_message_with_specified_res(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 2}, {bob, 1}],
fun user_send_private_message/3).
user_send_private_message_with_specified_res(Config, Alice, Alice2, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Message = <<"Hello Bob!">>,
BobNick = <<"Bobek">>,
AliceNick = <<"Ali">>,
enter_room(RoomJID, Bob, BobNick),
enter_room(RoomJID, Alice2, AliceNick),
escalus:wait_for_stanzas(Bob, 2),
Res = user_send_private_message(Alice, RoomJID, Message, BobNick, <<"res₂"/utf8>>, Config),
assert_success(?SEND_PRIV_MESG_PATH, Res),
assert_is_message_correct(RoomJID, AliceNick, <<"chat">>, Message,
escalus:wait_for_stanza(Bob)).
user_without_session_send_message_to_room(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}],
fun user_without_session_send_message_to_room_story/2).
user_without_session_send_message_to_room_story(Config, Alice) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
JID = jid:from_binary(escalus_client:full_jid(Alice)),
terminate_user_session(JID),
Res = user_send_message_to_room(Alice, RoomJID, <<"Hello!">>, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"does not have any session">>)).
terminate_user_session(Jid) ->
?assertEqual(ok, rpc(mim(), ejabberd_sm, terminate_session, [Jid, <<"Kicked">>])),
F = fun() -> rpc(mim(), ejabberd_sm, get_user_resources, [Jid]) end,
mongoose_helper:wait_until(F, [], #{time_left => timer:seconds(5)}).
user_get_room_config(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun user_get_room_config_story/3).
user_get_room_config_story(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Res = user_get_room_config(Alice, RoomJID, Config),
assert_default_room_config(Res),
Res2 = user_get_room_config(Bob, RoomJID, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res2), <<"does not have permission">>)).
user_try_get_nonexistent_room_config(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_try_get_nonexistent_room_config_story/2).
user_try_get_nonexistent_room_config_story(Config, Alice) ->
Res = user_get_room_config(Alice, ?NONEXISTENT_ROOM, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
user_change_room_config(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun user_change_room_config_story/3).
user_change_room_config_story(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Title = <<"aloes">>,
Description = <<"The chat about aloes">>,
Public = false,
RoomConfig = #{title => Title, description => Description, public => Public},
Res = user_change_room_config(Alice, RoomJID, RoomConfig, Config),
?assertMatch(#{<<"title">> := Title,
<<"description">> := Description,
<<"public">> := Public}, get_ok_value(?CHANGE_ROOM_CONFIG_PATH, Res)),
Res2 = user_change_room_config(Bob, RoomJID, RoomConfig, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res2), <<"does not have permission">>)).
user_try_change_nonexistent_room_config(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_try_change_nonexistent_room_config_story/2).
user_try_change_nonexistent_room_config_story(Config, Alice) ->
RoomConfig = #{title => <<"NewTitle">>},
Res = user_change_room_config(Alice, ?NONEXISTENT_ROOM, RoomConfig, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
user_list_room_users(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun user_list_room_users_story/3).
user_list_room_users_story(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
BobNick = <<"Bobek">>,
AliceNick = <<"Ali">>,
enter_room(RoomJID, Bob, BobNick),
enter_room(RoomJID, Alice, AliceNick),
Res = user_list_room_users(Alice, RoomJID, Config),
ExpectedUsers = [{null, BobNick, <<"PARTICIPANT">>},
{null, AliceNick, <<"MODERATOR">>}],
assert_room_users(ExpectedUsers, get_ok_value(?LIST_ROOM_USERS_PATH, Res)).
user_list_room_users_without_anonymous_mode(Config) ->
muc_helper:story_with_room(Config, [{anonymous, false}], [{alice, 1}, {bob, 1}],
fun user_list_room_users_without_anonymous_mode_story/3).
user_list_room_users_without_anonymous_mode_story(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
BobNick = <<"Bobek">>,
AliceNick = <<"Ali">>,
enter_room(RoomJID, Bob, BobNick),
enter_room(RoomJID, Alice, AliceNick),
Res = user_list_room_users(Alice, RoomJID, Config),
ExpectedUsers = [{escalus_client:full_jid(Bob), BobNick, <<"PARTICIPANT">>},
{escalus_client:full_jid(Alice), AliceNick, <<"MODERATOR">>}],
assert_room_users(ExpectedUsers, get_ok_value(?LIST_ROOM_USERS_PATH, Res)).
user_try_list_nonexistent_room_users(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_try_list_nonexistent_room_users_story/2).
user_try_list_nonexistent_room_users_story(Config, Alice) ->
Res = user_list_room_users(Alice, ?NONEXISTENT_ROOM, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
user_try_list_room_users_without_permission(Config) ->
muc_helper:story_with_room(Config, [{members_only, true}], [{alice, 1}, {bob, 1}],
fun user_try_list_room_users_without_permission_story/3).
user_try_list_room_users_without_permission_story(Config, _Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Res = user_list_room_users(Bob, RoomJID, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"does not have permission">>)).
user_get_room_messages(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun user_get_room_messages_story/3).
user_get_room_messages_story(Config, Alice, Bob) ->
RoomJID = #jid{luser = RoomName, lserver = MUCDomain} =
jid:from_binary(?config(room_jid, Config)),
enter_room(RoomJID, Bob, <<"Bobek">>),
enter_room(RoomJID, Alice, <<"Ali">>),
escalus:wait_for_stanzas(Bob, 2),
user_send_message_to_room(Bob, RoomJID, <<"Hi!">>, null, Config),
escalus:wait_for_stanzas(Bob, 1),
mam_helper:wait_for_room_archive_size(MUCDomain, RoomName, 1),
Res = user_get_room_messages(Alice, RoomJID, 50, null, Config),
#{<<"stanzas">> := [#{<<"stanza">> := StanzaXML}], <<"limit">> := 50} =
get_ok_value(?GET_MESSAGES_PATH, Res),
?assertMatch({ok, #xmlel{name = <<"message">>}}, exml:parse(StanzaXML)).
user_shouldnt_store_messages_in_muc_light(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_shouldnt_store_messages_in_muc_light_story/2).
user_shouldnt_store_messages_in_muc_light_story(Config, Alice) ->
MUCServer = ?config(muc_light_host, Config),
AliceBin = escalus_client:short_jid(Alice),
{ok, #{jid := RoomJID}} =
create_muc_light_room(MUCServer, <<"first room">>, <<"subject">>, AliceBin),
Message = <<"Hello friends">>,
send_message_to_muc_light_room(RoomJID, jid:from_binary(AliceBin), Message),
escalus:wait_for_stanza(Alice),
Limit = 1,
Res = user_get_muc_light_room_messages(Alice, jid:to_binary(RoomJID), Limit, null, Config),
#{<<"stanzas">> := [], <<"limit">> := Limit} =
get_ok_value([data, muc_light, getRoomMessages], Res).
user_try_get_nonexistent_room_messages(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_try_get_nonexistent_room_messages_story/2).
user_try_get_nonexistent_room_messages_story(Config, Alice) ->
Res = user_get_room_messages(Alice, ?NONEXISTENT_ROOM, null, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)),
Res2 = user_get_room_messages(Alice, ?NONEXISTENT_ROOM2, null, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res2), <<"not found">>)).
user_try_get_room_messages_without_permission(Config) ->
muc_helper:story_with_room(Config, [{members_only, true}], [{alice, 1}, {bob, 1}],
fun user_try_get_room_messages_without_permission/3).
user_try_get_room_messages_without_permission(Config, _Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Res = user_get_room_messages(Bob, RoomJID, null, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"does not have permission">>)).
user_owner_set_user_affiliation(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun user_owner_set_user_affiliation/3).
user_owner_set_user_affiliation(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Res = user_set_user_affiliation(Alice, RoomJID, Bob, member, Config),
assert_success(?SET_AFFILIATION_PATH, Res),
assert_user_affiliation(RoomJID, Bob, member),
Res1 = user_set_user_affiliation(Alice, RoomJID, Bob, admin, Config),
assert_success(?SET_AFFILIATION_PATH, Res1),
assert_user_affiliation(RoomJID, Bob, admin),
Res2 = user_set_user_affiliation(Alice, RoomJID, Bob, owner, Config),
assert_success(?SET_AFFILIATION_PATH, Res2),
assert_user_affiliation(RoomJID, Bob, owner),
Res3 = user_set_user_affiliation(Alice, RoomJID, Bob, none, Config),
assert_success(?SET_AFFILIATION_PATH, Res3),
assert_user_affiliation(RoomJID, Bob, none),
Res4 = user_set_user_affiliation(Alice, RoomJID, Bob, outcast, Config),
assert_success(?SET_AFFILIATION_PATH, Res4),
assert_user_affiliation(RoomJID, Bob, outcast).
user_admin_set_user_affiliation(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}, {kate, 1}],
fun user_admin_set_user_affiliation/4).
user_admin_set_user_affiliation(Config, Alice, Bob, Kate) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
user_set_user_affiliation(Alice, RoomJID, Bob, admin, Config),
Res = user_set_user_affiliation(Bob, RoomJID, Kate, member, Config),
assert_success(?SET_AFFILIATION_PATH, Res),
assert_user_affiliation(RoomJID, Kate, member),
Res1 = user_set_user_affiliation(Bob, RoomJID, Kate, none, Config),
assert_success(?SET_AFFILIATION_PATH, Res1),
assert_user_affiliation(RoomJID, Kate, none),
Res2 = user_set_user_affiliation(Bob, RoomJID, Kate, admin, Config),
assert_no_permission(Res2),
Res3 = user_set_user_affiliation(Bob, RoomJID, Kate, owner, Config),
assert_no_permission(Res3),
Res4 = user_set_user_affiliation(Bob, RoomJID, Kate, outcast, Config),
assert_success(?SET_AFFILIATION_PATH, Res4),
assert_user_affiliation(RoomJID, Kate, outcast),
Res5 = user_set_user_affiliation(Bob, RoomJID, Alice, outcast, Config),
assert_no_permission(Res5).
user_member_set_user_affiliation(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}, {kate, 1}],
fun user_member_set_user_affiliation/4).
user_member_set_user_affiliation(Config, Alice, Bob, Kate) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
user_set_user_affiliation(Alice, RoomJID, Bob, member, Config),
Res = user_set_user_affiliation(Bob, RoomJID, Kate, member, Config),
assert_no_permission(Res),
Res1 = user_set_user_affiliation(Bob, RoomJID, Kate, admin, Config),
assert_no_permission(Res1),
Res2 = user_set_user_affiliation(Bob, RoomJID, Kate, owner, Config),
assert_no_permission(Res2),
user_set_user_affiliation(Alice, RoomJID, Kate, member, Config),
Res3 = user_set_user_affiliation(Bob, RoomJID, Kate, none, Config),
assert_no_permission(Res3).
user_try_set_nonexistent_room_affiliation(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_try_set_nonexistent_room_affiliation/2).
user_try_set_nonexistent_room_affiliation(Config, Alice) ->
Res = user_set_user_affiliation(Alice, ?NONEXISTENT_ROOM, Alice, none, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
user_moderator_set_user_role(Config) ->
muc_helper:story_with_room(Config, [{anonymous, false}, {persistent, true}],
[{alice, 1}, {bob, 1}],
fun user_moderator_set_user_role/3).
user_moderator_set_user_role(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
BobNick = <<"Boobek">>,
enter_room(RoomJID, Alice, escalus_client:username(Alice)),
enter_room(RoomJID, Bob, BobNick),
Res = user_set_user_role(Alice, RoomJID, BobNick, visitor, Config),
assert_success(?SET_ROLE_PATH, Res),
assert_user_role(RoomJID, Bob, visitor),
Res1 = user_set_user_role(Alice, RoomJID, BobNick, participant, Config),
assert_success(?SET_ROLE_PATH, Res1),
assert_user_role(RoomJID, Bob, participant),
Res2 = user_set_user_role(Alice, RoomJID, BobNick, moderator, Config),
assert_success(?SET_ROLE_PATH, Res2),
assert_user_role(RoomJID, Bob, moderator).
user_participant_set_user_role(Config) ->
muc_helper:story_with_room(Config, [{anonymous, false}, {persistent, true}],
[{alice, 1}, {bob, 1}, {kate, 1}],
fun user_participant_set_user_role/4).
user_participant_set_user_role(Config, _Alice, Bob, Kate) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
BobNick = <<"Boobek">>,
KateNick = <<"Katek">>,
enter_room(RoomJID, Bob, BobNick),
enter_room(RoomJID, Kate, KateNick),
Res = user_set_user_role(Bob, RoomJID, KateNick, visitor, Config),
assert_no_permission(Res),
Res1 = user_set_user_role(Bob, RoomJID, KateNick, participant, Config),
assert_success(?SET_ROLE_PATH, Res1),
assert_user_role(RoomJID, Bob, participant),
Res2 = user_set_user_role(Bob, RoomJID, KateNick, moderator, Config),
assert_no_permission(Res2).
user_try_set_nonexistent_room_role(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_try_set_nonexistent_room_role/2).
user_try_set_nonexistent_room_role(Config, Alice) ->
Res = user_set_user_role(Alice, ?NONEXISTENT_ROOM, <<"Ali">>, participant, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
user_can_enter_room(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}], fun user_can_enter_room/2).
user_can_enter_room(Config, Alice) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Nick = <<"ali">>,
JID = jid:from_binary(escalus_utils:jid_to_lower(escalus_client:full_jid(Alice))),
Resource should be normalized to " res1 " , which is 's connected resource
Res = user_enter_room(Alice, RoomJID, Nick, <<"res₁"/utf8>>, null, Config),
assert_success(?ENTER_ROOM_PATH, Res),
?assertMatch([#{nick := Nick, jid := JID}], get_room_users(RoomJID)).
user_cannot_enter_room_with_invalid_resource(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}],
fun user_cannot_enter_room_with_invalid_resource/2).
user_cannot_enter_room_with_invalid_resource(Config, Alice) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Nick = <<"ali">>,
Res1 = user_enter_room(Alice, RoomJID, Nick, <<"\n">>, null, Config),
assert_coercion_err(Res1, <<"failed_to_parse_resource_name">>),
Res2 = user_enter_room(Alice, RoomJID, Nick, <<>>, null, Config),
assert_coercion_err(Res2, <<"empty_resource_name">>).
user_can_enter_room_with_password(Config) ->
muc_helper:story_with_room(Config, [{password_protected, true}, {password, ?PASSWORD}],
[{alice, 1}, {bob, 1}],
fun user_can_enter_room_with_password/3).
user_can_enter_room_with_password(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Nick = <<"ali">>,
JID = jid:from_binary(escalus_utils:jid_to_lower(escalus_client:full_jid(Alice))),
Resource = escalus_client:resource(Alice),
enter room with password
Res = user_enter_room(Alice, RoomJID, Nick, Resource, ?PASSWORD, Config),
assert_success(?ENTER_ROOM_PATH, Res),
?assertMatch([#{nick := Nick, jid := JID}], get_room_users(RoomJID)),
try enter room without password
Res1 = user_enter_room(Bob, RoomJID, <<"Bobek">>, Resource, null, Config),
assert_success(?ENTER_ROOM_PATH, Res1),
?assertMatch([_], get_room_users(RoomJID)),
enter room with password
Res2 = user_enter_room(Bob, RoomJID, <<"Bobek">>, Resource, ?PASSWORD, Config),
assert_success(?ENTER_ROOM_PATH, Res2),
?assertMatch([_, _], get_room_users(RoomJID)).
user_can_exit_room(Config) ->
muc_helper:story_with_room(Config, [{persistent, true}], [{alice, 1}],
fun user_can_exit_room/2).
user_can_exit_room(Config, Alice) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Nick = <<"ali">>,
enter_room(RoomJID, Alice, Nick),
?assertMatch([_], get_room_users(RoomJID)),
Resource should be normalized to " res1 " , which is 's connected resource
Res = user_exit_room(Alice, RoomJID, Nick, <<"res₁"/utf8>>, Config),
assert_success(?EXIT_ROOM_PATH, Res),
?assertMatch([], get_room_users(RoomJID)).
user_list_room_affiliations(Config) ->
muc_helper:story_with_room(Config, [], [{alice, 1}, {bob, 1}],
fun user_list_room_affiliations/3).
user_list_room_affiliations(Config, Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
BobNick = <<"Bobek">>,
AliceNick = <<"Ali">>,
enter_room(RoomJID, Bob, BobNick),
enter_room(RoomJID, Alice, AliceNick),
AliceJID = escalus_utils:jid_to_lower(escalus_client:short_jid(Alice)),
BobJID = escalus_utils:jid_to_lower(escalus_client:short_jid(Bob)),
Res = user_list_room_affiliations(Alice, RoomJID, owner, Config),
?assertMatch([#{<<"jid">> := AliceJID, <<"affiliation">> := <<"OWNER">>}],
get_ok_value(?LIST_ROOM_AFFILIATIONS_PATH, Res)),
user_set_user_affiliation(Alice, RoomJID, Bob, member, Config),
Res1 = user_list_room_affiliations(Alice, RoomJID, member, Config),
?assertMatch([#{<<"jid">> := BobJID, <<"affiliation">> := <<"MEMBER">>}],
get_ok_value(?LIST_ROOM_AFFILIATIONS_PATH, Res1)),
Res2 = user_list_room_affiliations(Alice, RoomJID, null, Config),
?assertMatch([_, _], get_ok_value(?LIST_ROOM_AFFILIATIONS_PATH, Res2)).
user_try_list_room_affiliations_without_permission(Config) ->
muc_helper:story_with_room(Config, [{members_only, true}], [{alice, 1}, {bob, 1}],
fun user_try_list_room_affiliations_without_permission/3).
user_try_list_room_affiliations_without_permission(Config, _Alice, Bob) ->
RoomJID = jid:from_binary(?config(room_jid, Config)),
Res = user_list_room_affiliations(Bob, RoomJID, null, Config),
assert_no_permission(Res).
user_try_list_nonexistent_room_affiliations(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_try_list_nonexistent_room_affiliations/2).
user_try_list_nonexistent_room_affiliations(Config, Alice) ->
Res = user_list_room_affiliations(Alice, ?NONEXISTENT_ROOM, null, Config),
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"not found">>)).
user_delete_room_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_delete_room_muc_not_configured_story/2).
user_delete_room_muc_not_configured_story(Config, Alice) ->
Res = user_delete_room(Alice, get_room_name(), null, Config),
get_not_loaded(Res).
user_list_room_users_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_list_room_users_muc_not_configured_story/2).
user_list_room_users_muc_not_configured_story(Config, Alice) ->
Res = user_list_room_users(Alice, get_room_name(), Config),
get_not_loaded(Res).
user_change_room_config_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_change_room_config_muc_not_configured_story/2).
user_change_room_config_muc_not_configured_story(Config, Alice) ->
RoomConfig = #{title => <<"NewTitle">>},
Res = user_change_room_config(Alice, get_room_name(), RoomConfig, Config),
get_not_loaded(Res).
user_get_room_config_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_get_room_config_muc_not_configured_story/2).
user_get_room_config_muc_not_configured_story(Config, Alice) ->
Res = user_get_room_config(Alice, get_room_name(), Config),
get_not_loaded(Res).
user_invite_user_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}, {bob, 1}],
fun user_invite_user_muc_not_configured_story/3).
user_invite_user_muc_not_configured_story(Config, Alice, Bob) ->
Res = user_invite_user(Alice, get_room_name(), Bob, null, Config),
get_not_loaded(Res).
user_kick_user_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_kick_user_muc_not_configured_story/2).
user_kick_user_muc_not_configured_story(Config, Alice) ->
Res = user_kick_user(Alice, get_room_name(), <<"nick">>, <<"reason">>, Config),
get_not_loaded(Res).
user_send_message_to_room_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_send_message_to_room_muc_not_configured_story/2).
user_send_message_to_room_muc_not_configured_story(Config, Alice) ->
Res = user_send_message_to_room(Alice, get_room_name(), <<"Body">>, null, Config),
get_not_loaded(Res).
user_send_private_message_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_send_private_message_muc_not_configured_story/2).
user_send_private_message_muc_not_configured_story(Config, Alice) ->
Message = <<"Hello Bob!">>,
BobNick = <<"Bobek">>,
Res = user_send_private_message(Alice, get_room_name(), Message, BobNick, null, Config),
get_not_loaded(Res).
user_get_room_messages_muc_or_mam_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_get_room_messages_muc_or_mam_not_configured_story/2).
user_get_room_messages_muc_or_mam_not_configured_story(Config, Alice) ->
Res = user_get_room_messages(Alice, get_room_name(), 10, null, Config),
get_not_loaded(Res).
user_owner_set_user_affiliation_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_owner_set_user_affiliation_muc_not_configured_story/2).
user_owner_set_user_affiliation_muc_not_configured_story(Config, Alice) ->
Res = user_set_user_affiliation(Alice, get_room_name(), Alice, member, Config),
get_not_loaded(Res).
user_moderator_set_user_role_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_moderator_set_user_role_muc_not_configured_story/2).
user_moderator_set_user_role_muc_not_configured_story(Config, Alice) ->
Res = user_set_user_role(Alice, get_room_name(), Alice, moderator, Config),
get_not_loaded(Res).
user_can_enter_room_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_can_enter_room_muc_not_configured_story/2).
user_can_enter_room_muc_not_configured_story(Config, Alice) ->
Nick = <<"ali">>,
Resource = escalus_client:resource(Alice),
Res = user_enter_room(Alice, get_room_name(), Nick, Resource, null, Config),
get_not_loaded(Res).
user_can_exit_room_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_can_exit_room_muc_not_configured_story/2).
user_can_exit_room_muc_not_configured_story(Config, Alice) ->
Resource = escalus_client:resource(Alice),
Res = user_exit_room(Alice, get_room_name(), <<"ali">>, Resource, Config),
get_not_loaded(Res).
user_list_room_affiliations_muc_not_configured(Config) ->
escalus:fresh_story_with_config(Config, [{alice, 1}],
fun user_list_room_affiliations_muc_not_configured_story/2).
user_list_room_affiliations_muc_not_configured_story(Config, Alice) ->
Res = user_list_room_affiliations(Alice, get_room_name(), owner, Config),
get_not_loaded(Res).
assert_coercion_err(Res, Code) ->
?assertNotEqual(nomatch, binary:match(get_coercion_err_msg(Res), Code)).
assert_no_full_jid(Res) ->
assert_coercion_err(Res, <<"jid_without_resource">>).
assert_no_permission(Res) ->
?assertNotEqual(nomatch, binary:match(get_err_msg(Res), <<"does not have permission">>)).
assert_success(Path, Res) ->
?assertNotEqual(nomatch, binary:match(get_ok_value(Path, Res), <<"successfully">>)).
get_room_affiliation(RoomJID, Aff) ->
{ok, Affs} = rpc(mim(), mod_muc_api, get_room_affiliations, [RoomJID, Aff]),
Affs.
get_room_users(RoomJID) ->
{ok, Users} = rpc(mim(), mod_muc_api, get_room_users, [RoomJID]),
Users.
assert_user_role(RoomJID, User, Role) ->
UserJID = jid:from_binary(escalus_client:full_jid(User)),
?assert(lists:any(fun(#{jid := JID, role := Role2}) ->
Role =:= Role2 andalso jid:are_bare_equal(JID, UserJID) end,
get_room_users(RoomJID))).
assert_user_affiliation(RoomJID, User, none) ->
Affs = get_room_affiliation(RoomJID, undefined),
UserSimpleJID = jid:to_lower(user_to_jid(User)),
?assertNot(lists:any(fun({U, _}) -> U == UserSimpleJID end, Affs));
assert_user_affiliation(RoomJID, User, Aff) ->
Affs = get_room_affiliation(RoomJID, Aff),
Elem = {jid:to_lower(user_to_jid(User)), Aff},
?assert(lists:member(Elem, Affs)).
rand_name() ->
rpc(mim(), mongoose_bin, gen_from_crypto, []).
-spec assert_room_users([{jid:jid(), binary(), binary()}], [map()]) -> ok.
assert_room_users(Expected, Actual) ->
ActualTuples = [{JID, Nick, Role} || #{<<"jid">> := JID, <<"role">> := Role, <<"nick">> := Nick} <- Actual],
?assertEqual(lists:sort(Expected), lists:sort(ActualTuples)).
assert_is_message_correct(RoomJID, SenderNick, Type, Text, ReceivedMessage) ->
escalus_pred:is_message(ReceivedMessage),
From = jid:to_binary(jid:replace_resource(RoomJID, SenderNick)),
From = exml_query:attr(ReceivedMessage, <<"from">>),
Type = exml_query:attr(ReceivedMessage, <<"type">>),
Body = #xmlel{name = <<"body">>, children = [#xmlcdata{content=Text}]},
Body = exml_query:subelement(ReceivedMessage, <<"body">>).
enter_room(RoomJID, User, Nick) ->
JID = jid:to_binary(jid:replace_resource(RoomJID, Nick)),
Pres = escalus_stanza:to(escalus_stanza:presence(<<"available">>, []), JID),
escalus:send(User, Pres),
escalus:wait_for_stanza(User).
contain_room(Name, #{<<"rooms">> := Rooms}) ->
contain_room(Name, Rooms);
contain_room(Name, Rooms) when is_list(Rooms) ->
lists:any(fun(#{<<"title">> := T}) -> T =:= Name end, Rooms).
extract_rooms(#{<<"rooms">> := [], <<"index">> := null, <<"count">> := 0,
<<"first">> := null, <<"last">> := null}) ->
[];
extract_rooms(#{<<"rooms">> := Rooms, <<"index">> := Index, <<"count">> := Count,
<<"first">> := First, <<"last">> := Last}) ->
Titles = lists:map(fun(#{<<"title">> := Title}) -> Title end, Rooms),
?assertEqual(hd(Titles), First),
?assertEqual(lists:last(Titles), Last),
?assert(is_integer(Count) andalso Count >= length(Titles)),
?assert(is_integer(Index) andalso Index >= 0),
Titles.
returned_rooms(#{<<"rooms">> := Rooms}) ->
[Title || #{<<"title">> := Title} <- Rooms].
assert_default_room_config(Response) ->
?assertMatch(#{<<"title">> := <<>>,
<<"description">> := <<>>,
<<"allowChangeSubject">> := true,
<<"allowQueryUsers">> := true,
<<"allowPrivateMessages">> := true,
<<"allowVisitorStatus">> := true,
<<"allowVisitorNickchange">> := true,
<<"public">> := true,
<<"publicList">> := true,
<<"persistent">> := false,
<<"moderated">> := true,
<<"membersByDefault">> := true,
<<"membersOnly">> := false,
<<"allowUserInvites">> := false,
<<"allowMultipleSession">> := false,
<<"passwordProtected">> := false,
<<"password">> := <<>>,
<<"anonymous">> := true,
<<"mayGetMemberList">> := [],
<<"maxUsers">> := 200,
<<"logging">> := false}, get_ok_value(?GET_ROOM_CONFIG_PATH, Response)).
atom_to_enum_item(null) -> null;
atom_to_enum_item(Atom) -> list_to_binary(string:to_upper(atom_to_list(Atom))).
get_room_name() ->
Domain = domain_helper:domain(),
<<"NON_EXISTING@", Domain/binary>>.
create_muc_light_room(Domain, Name, Subject, CreatorBin) ->
CreatorJID = jid:from_binary(CreatorBin),
Config = #{<<"roomname">> => Name, <<"subject">> => Subject},
rpc(mim(), mod_muc_light_api, create_room, [Domain, CreatorJID, Config]).
create_instant_room(Room, Owner, Nick, Config) ->
Vars = #{room => room_to_bin(Room), owner => user_to_bin(Owner), nick => Nick},
execute_command(<<"muc">>, <<"createInstantRoom">>, Vars, Config).
invite_user(Room, Sender, Recipient, Reason, Config) ->
Vars = #{room => jid:to_binary(Room), sender => user_to_bin(Sender),
recipient => user_to_bin(Recipient), reason => Reason},
execute_command(<<"muc">>, <<"inviteUser">>, Vars, Config).
kick_user(Room, Nick, Reason, Config) ->
Vars = #{room => jid:to_binary(Room), nick => Nick, reason => Reason},
execute_command(<<"muc">>, <<"kickUser">>, Vars, Config).
send_message_to_room(Room, From, Body, Config) ->
Vars = #{room => jid:to_binary(Room), from => user_to_full_bin(From), body => Body},
execute_command(<<"muc">>, <<"sendMessageToRoom">>, Vars, Config).
send_private_message(Room, From, ToNick, Body, Config) ->
Vars = #{room => jid:to_binary(Room), from => user_to_full_bin(From),
toNick => ToNick, body => Body},
execute_command(<<"muc">>, <<"sendPrivateMessage">>, Vars, Config).
send_message_to_muc_light_room(RoomJID, SenderJID, Message) ->
rpc(mim(), mod_muc_light_api, send_message, [RoomJID, SenderJID, Message]).
enter_room(Room, User, Nick, Password, Config) ->
Vars = #{room => jid:to_binary(Room), user => user_to_full_bin(User),
nick => Nick, password => Password},
execute_command(<<"muc">>, <<"enterRoom">>, Vars, Config).
delete_room(Room, Reason, Config) ->
Vars = #{room => jid:to_binary(Room), reason => Reason},
execute_command(<<"muc">>, <<"deleteRoom">>, Vars, Config).
change_room_config(Room, RoomConfig, Config) ->
Vars = #{room => jid:to_binary(Room), config => RoomConfig},
execute_command(<<"muc">>, <<"changeRoomConfiguration">>, Vars, Config).
list_rooms(MUCDomain, From, Limit, Index, Config) ->
Vars = #{mucDomain => MUCDomain, from => user_to_bin(From), limit => Limit, index => Index},
execute_command(<<"muc">>, <<"listRooms">>, Vars, Config).
get_room_config(Room, Config) ->
Vars = #{room => jid:to_binary(Room)},
execute_command(<<"muc">>, <<"getRoomConfig">>, Vars, Config).
list_room_users(RoomJID, Config) ->
Vars = #{room => jid:to_binary(RoomJID)},
execute_command(<<"muc">>, <<"listRoomUsers">>, Vars, Config).
get_room_messages(RoomJID, PageSize, Before, Config) ->
Vars = #{<<"room">> => jid:to_binary(RoomJID), <<"pageSize">> => PageSize,
<<"before">> => Before},
execute_command(<<"muc">>, <<"getRoomMessages">>, Vars, Config).
set_user_affiliation(Room, User, Aff, Config) ->
Vars = #{room => jid:to_binary(Room), user => user_to_bin(User),
affiliation => atom_to_enum_item(Aff)},
execute_command(<<"muc">>, <<"setUserAffiliation">>, Vars, Config).
set_user_role(Room, User, Role, Config) ->
Vars = #{room => jid:to_binary(Room), nick => user_to_bin(User),
role => atom_to_enum_item(Role)},
execute_command(<<"muc">>, <<"setUserRole">>, Vars, Config).
exit_room(Room, User, Nick, Config) ->
Vars = #{room => jid:to_binary(Room), user => user_to_full_bin(User), nick => Nick},
execute_command(<<"muc">>, <<"exitRoom">>, Vars, Config).
list_room_affiliations(Room, Aff, Config) ->
Vars = #{room => jid:to_binary(Room), affiliation => atom_to_enum_item(Aff)},
execute_command(<<"muc">>, <<"listRoomAffiliations">>, Vars, Config).
user_kick_user(User, Room, Nick, Reason, Config) ->
Vars = #{room => jid:to_binary(Room), nick => Nick, reason => Reason},
execute_user_command(<<"muc">>, <<"kickUser">>, User, Vars, Config).
user_enter_room(User, Room, Nick, Resource, Password, Config) ->
Vars = #{room => jid:to_binary(Room), nick => Nick, resource => Resource, password => Password},
execute_user_command(<<"muc">>, <<"enterRoom">>, User, Vars, Config).
user_get_room_messages(User, RoomJID, PageSize, Before, Config) ->
Vars = #{<<"room">> => jid:to_binary(RoomJID), <<"pageSize">> => PageSize,
<<"before">> => Before},
execute_user_command(<<"muc">>, <<"getRoomMessages">>, User, Vars, Config).
user_get_muc_light_room_messages(User, RoomJID, PageSize, Before, Config) ->
Vars = #{<<"room">> => RoomJID, <<"pageSize">> => PageSize, <<"before">> => Before},
execute_user_command(<<"muc_light">>, <<"getRoomMessages">>, User, Vars, Config).
user_delete_room(User, Room, Reason, Config) ->
Vars = #{room => jid:to_binary(Room), reason => Reason},
execute_user_command(<<"muc">>, <<"deleteRoom">>, User, Vars, Config).
user_change_room_config(User, Room, RoomConfig, Config) ->
Vars = #{room => jid:to_binary(Room), config => RoomConfig},
execute_user_command(<<"muc">>, <<"changeRoomConfiguration">>, User, Vars, Config).
user_list_rooms(User, MUCDomain, Limit, Index, Config) ->
Vars = #{mucDomain => MUCDomain, limit => Limit, index => Index},
execute_user_command(<<"muc">>, <<"listRooms">>, User, Vars, Config).
user_get_room_config(User, Room, Config) ->
Vars = #{room => jid:to_binary(Room)},
execute_user_command(<<"muc">>, <<"getRoomConfig">>, User, Vars, Config).
user_list_room_users(User, RoomJID, Config) ->
Vars = #{room => jid:to_binary(RoomJID)},
execute_user_command(<<"muc">>, <<"listRoomUsers">>, User, Vars, Config).
user_send_message_to_room(User, Room, Body, Resource, Config) ->
Vars = #{room => jid:to_binary(Room), body => Body, resource => Resource},
execute_user_command(<<"muc">>, <<"sendMessageToRoom">>, User, Vars, Config).
user_send_private_message(User, Room, Body, ToNick, Resource, Config) ->
Vars = #{room => jid:to_binary(Room), body => Body, toNick => ToNick, resource => Resource},
execute_user_command(<<"muc">>, <<"sendPrivateMessage">>, User, Vars, Config).
user_create_instant_room(User, Room, Nick, Config) ->
Vars = #{room => room_to_bin(Room), nick => Nick},
execute_user_command(<<"muc">>, <<"createInstantRoom">>, User, Vars, Config).
user_invite_user(User, Room, Recipient, Reason, Config) ->
Vars = #{room => jid:to_binary(Room), recipient => user_to_bin(Recipient), reason => Reason},
execute_user_command(<<"muc">>, <<"inviteUser">>, User, Vars, Config).
user_set_user_affiliation(User, Room, QueriedUser, Aff, Config) ->
Vars = #{room => jid:to_binary(Room), user => user_to_bin(QueriedUser),
affiliation => atom_to_enum_item(Aff)},
execute_user_command(<<"muc">>, <<"setUserAffiliation">>, User, Vars, Config).
user_set_user_role(User, Room, QueriedUser, Role, Config) ->
Vars = #{room => jid:to_binary(Room), nick => user_to_bin(QueriedUser),
role => atom_to_enum_item(Role)},
execute_user_command(<<"muc">>, <<"setUserRole">>, User, Vars, Config).
user_exit_room(User, Room, Nick, Resource, Config) ->
Vars = #{room => jid:to_binary(Room), resource => Resource, nick => Nick},
execute_user_command(<<"muc">>, <<"exitRoom">>, User, Vars, Config).
user_list_room_affiliations(User, Room, Aff, Config) ->
Vars = #{room => jid:to_binary(Room), affiliation => atom_to_enum_item(Aff)},
execute_user_command(<<"muc">>, <<"listRoomAffiliations">>, User, Vars, Config).
room_to_bin(RoomJIDBin) when is_binary(RoomJIDBin) ->RoomJIDBin;
room_to_bin(RoomJID) -> jid:to_binary(RoomJID).
|
b393944b0afc433167e66a3b2bf5639e0460492fd4c609b012c7b676e63ab7cb | rajasegar/cl-djula-tailwind | main.lisp | (defpackage cl-djula-tailwind
(:use :cl
:cl-djula-tailwind.layout
:cl-djula-tailwind.spacing
:cl-djula-tailwind.typography
:cl-djula-tailwind.backgrounds
:cl-djula-tailwind.sizing
:cl-djula-tailwind.borders
:cl-djula-tailwind.effects
:cl-djula-tailwind.flexbox-grid
:cl-djula-tailwind.accessibility
:cl-djula-tailwind.svg
:cl-djula-tailwind.transforms
:cl-djula-tailwind.tables)
(:import-from :cl-ppcre
:all-matches
:do-register-groups
:all-matches-as-strings
:regex-replace-all)
(:export :get-stylesheet
:get-plain-class
:get-pseudo-class
:get-responsive-class
:get-darkmode-class
:get-peer-class
:get-form-state-class
:get-child-modifier-class))
(in-package :cl-djula-tailwind)
(defvar *util-prop-hash* '(
("p" . :padding)
("pt" . :padding-top)
("pr" . :padding-right)
("pb" . :padding-bottom)
("pl" . :padding-left)
("m" . :margin)
("mt" . :margin-top)
("mr" . :margin-right)
("mb" . :margin-bottom)
("ml" . :margin-left)
("h" . :height)
("min-h" . :min-height)
("max-h" . :max-height)
("w" . :width)
("min-w" . :min-width)
("max-w" . :max-width)
))
(defun parse-template-string (path dir)
"Parse Djula template from the given path"
(djula::parse-template-string (uiop::read-file-string (merge-pathnames path dir))))
(defun get-markup (template)
"Get the HTML markup from the template content"
(let ((markup '()))
(dolist (l template)
(let ((x (first l))
(y (second l)))
(when (eq x :string)
(push y markup))))
(remove-duplicates (reverse markup) :test #'string=)))
(defun find-class-attrs (html)
"Find the class attribute values"
(loop for l in html
for x = (all-matches-as-strings "class=\"([^\"]*)\"" l)
when x
collect x))
(defun replace-class-keyword (props)
"Remove the class keywords and extra quotes"
(let ((classnames '()))
(dolist (line props)
(dolist (word line)
(let* ((x (regex-replace-all "class=" word ""))
(y (regex-replace-all "\\\"" x "")))
(push y classnames))))
(reverse classnames)))
(defun join-string-list (string-list)
"Concatenates a list of strings and puts spaces between the elements."
(format nil "~{~A~^ ~}" string-list))
(defun split-by-one-space (string)
"Returns a list of substrings of string
divided by ONE space each.
Note: Two consecutive spaces will be seen as
if there were an empty string between them."
(remove-duplicates
(loop for i = 0 then (1+ j)
as j = (position #\Space string :start i)
collect (subseq string i j)
while j) :test #'string=))
(defun get-classnames (markup)
"Get the list of Tailwind class names as a list"
(split-by-one-space
(join-string-list
(replace-class-keyword
(find-class-attrs markup)))))
(defvar *tailwind* (append
*layout*
*spacing*
*typography*
*backgrounds*
*sizing*
*borders*
*effects*
*flexbox-grid*
*accessibility*
*svg*
*transforms*
*tables*
))
(defun is-plain-util (c)
(assoc c *tailwind* :test #'string=))
(defun is-pseudo-util (str)
(all-matches "(hover|focus|active|disabled):([a-z0-9-]*)" str))
(defun is-darkmode-util (str)
(all-matches "dark:([a-z0-9-]*)" str))
(defun is-responsive-util (str)
(all-matches "(sm|md|lg|xl|2xl):([a-z0-9-]*)" str))
(defun is-peer-util (str)
(all-matches "peer-(checked|hover|focus|active|disabled):([a-z0-9-]*)" str))
(defvar *form-state-util-regex* "(required|invalid|disabled):([a-z0-9-]*)")
(defun form-state-utilp (str)
"Is this a form state modifier util"
(all-matches *form-state-util-regex* str))
(defun get-form-state-class (str)
"Generate class definitions for required: invalid: and other form states"
(let (result)
(do-register-groups
(state class)
(*form-state-util-regex* str)
(let ((classname (concatenate 'string "." state "\\:" class ":" state))
(props (cdr (cadr (assoc class *tailwind* :test #'string=)))))
(push (concatenate 'string classname " { " (cl-css:inline-css props) " }") result)))
(car result)))
(defvar *arbitrary-value-regex* "([a-z]*)-\\[([a-z0-9-]*)\\]")
(defun arbitrary-value-utilp (str)
"Is this an arbitrary value util"
(all-matches *arbitrary-value-regex* str))
(defun get-arbitrary-value-class (str)
"Generate class definitions for arbitrary values"
(let (result)
(do-register-groups
(class value)
(*arbitrary-value-regex* str)
(let ((classname (concatenate 'string "." class "-\\[" value "\\] " ))
(props (cdr (assoc class *util-prop-hash* :test #'string=))))
(push (concatenate 'string classname " { " (cl-css:inline-css `(,props ,value)) " }") result)))
(car result)))
(defvar *child-modifier-regex* "(first|last|odd|even):([a-z0-9-]*)")
(defun child-modifier-utilp (str)
"Is this a child modifier util"
(all-matches *child-modifier-regex* str))
(defun get-child-modifier-class (str)
"Generate class definitions for first: last: and other child modifiers"
(let (result)
(do-register-groups
(state class)
(*child-modifier-regex* str)
(let ((classname (concatenate 'string "." state "\\:" class ":" state))
(props (cdr (cadr (assoc class *tailwind* :test #'string=)))))
(push (concatenate 'string classname " { " (cl-css:inline-css props) " }") result)))
(car result)))
(defun get-plain-class (str)
"Generate class definitions for simple plain utilities"
(cl-css:css (cdr (assoc str *tailwind* :test #'string=))))
(defun get-pseudo-class (str)
"Generate class definitions for hover: focus: and other states"
(let (result)
(do-register-groups
(state class)
("(hover|focus|active|disabled|focus-within|focus-visible):([a-z0-9-]*)" str)
(let ((classname (concatenate 'string "." state "\\:" class ":" state))
(props (cdr (cadr (assoc class *tailwind* :test #'string=)))))
(push (concatenate 'string classname " { " (cl-css:inline-css props) " }") result)))
(car result)))
(defun get-darkmode-class (str)
"Generate class definitions for darkmode"
(let (result)
(do-register-groups
(state class)
("(dark):([a-z0-9-]*)" str)
(let ((classname (concatenate 'string "." state "\\:" class))
(props (cdr (cadr (assoc class *tailwind* :test #'string=)))))
(push (concatenate 'string "@media (prefers-color-scheme: dark) { " classname " { " (cl-css:inline-css props) " } }") result)))
(car result)))
(defvar *media-query* '(("sm" . "@media (min-width: 640px)")
("md" . "@media (min-width: 768px)")
("lg" . "@media (min-width: 1024px)")
("xl" . "@media (min-width: 1280px)")
("2xl" . "@media (min-width: 1536px)")))
(defun get-media-query (breakpoint)
(cdr (assoc breakpoint *media-query* :test #'string=)))
(defun get-responsive-class (str)
"Generate class definitions for responsive utility variants sm: md: lg: etc.,"
(let (result)
(do-register-groups
(breakpoint class)
("(sm|md|lg|xl|2xl):([a-z0-9-]*)" str)
(let ((classname (concatenate 'string "." breakpoint "\\:" class ))
(props (cdr (cadr (assoc class *tailwind* :test #'string=)))))
(push (concatenate 'string
(get-media-query breakpoint) " { " classname " { " (cl-css:inline-css props) " } }") result)))
(car result)))
(defun get-peer-class (str)
"Generate class definitions for peer:{{modifier}} states"
(let (result)
(do-register-groups
(state class)
("peer-(checked|invalid|required|hover|focus|active|disabled|focus-within|focus-visible):([a-z0-9-]*)" str)
(let ((classname (concatenate 'string ".peer:" state " ~ .peer-" state "\\:" class))
(props (cdr (cadr (assoc class *tailwind* :test #'string=)))))
(push (concatenate 'string classname " { " (cl-css:inline-css props) " }") result)))
(car result)))
(defvar *group-regex* "group-(hover|focus|active):([a-z0-9-]*)")
(defun group-utilp (str)
"Is this a group modifier util"
(all-matches *group-regex* str))
(defun get-group-class (str)
"Generate class definitions for group-*:{{modifier}} states"
(let (result)
(do-register-groups
(state class)
(*group-regex* str)
(let ((classname (concatenate 'string ".group:" state " ~ .group-" state "\\:" class))
(props (cdr (cadr (assoc class *tailwind* :test #'string=)))))
(push (concatenate 'string classname " { " (cl-css:inline-css props) " }") result)))
(car result)))
(defun get-templates (root-template)
"Get the list of templates - extends and includes from the root-template"
(let ((templates '()))
(dolist (l root-template)
(let ((x (first l))
(y (second l)))
(when (eq x :unparsed-tag)
(do-register-groups
(tag template-name)
("(extends|include) \"([_a-z\/\.]*)\"" y)
(push template-name templates)))
))
(reverse templates)))
(defun get-stylesheet (file dir)
"Generate the stylesheet based on tailwind class definitions"
(let* ((root-template (parse-template-string file dir))
(templates (get-templates root-template))
(markup '()))
Let get the list of templates first
;; Then process each template and collect the markup
;; in a single list
(dolist (tmplt templates)
(let ((template-content (parse-template-string tmplt dir)))
;; (print tmplt)
;; (print (join-string-list (get-markup template-content)))
(push (join-string-list (get-markup template-content)) markup)))
;; finally push the markup of the root-template (current route template)
(push (join-string-list (get-markup root-template)) markup)
(let ((styles '()))
(dolist (c (get-classnames markup))
(cond
((is-plain-util c) (push (get-plain-class c) styles))
((is-pseudo-util c) (push (get-pseudo-class c) styles))
((is-responsive-util c) (push (get-responsive-class c) styles))
((is-darkmode-util c) (push (get-darkmode-class c) styles))
((is-peer-util c) (push (get-peer-class c) styles))
((form-state-utilp c) (push (get-form-state-class c) styles))
((child-modifier-utilp c) (push (get-child-modifier-class c) styles))
((group-utilp c) (push (get-group-class c) styles))
((arbitrary-value-utilp c) (push (get-arbitrary-value-class c) styles))
(t (print c))))
(cl-minify-css:minify-css (join-string-list (reverse styles))))))
;; (defparameter *template-directory* (asdf:system-relative-pathname "cl-djula-tailwind" "tests/templates/"))
;; (defparameter *tests-directory* (asdf:system-relative-pathname "cl-djula-tailwind" "tests/"))
;; (print (get-stylesheet #P"index.html" *template-directory*))
| null | https://raw.githubusercontent.com/rajasegar/cl-djula-tailwind/26cf98609b2fb42660a8d72ade2f1135d41dfec1/src/main.lisp | lisp | Then process each template and collect the markup
in a single list
(print tmplt)
(print (join-string-list (get-markup template-content)))
finally push the markup of the root-template (current route template)
(defparameter *template-directory* (asdf:system-relative-pathname "cl-djula-tailwind" "tests/templates/"))
(defparameter *tests-directory* (asdf:system-relative-pathname "cl-djula-tailwind" "tests/"))
(print (get-stylesheet #P"index.html" *template-directory*)) | (defpackage cl-djula-tailwind
(:use :cl
:cl-djula-tailwind.layout
:cl-djula-tailwind.spacing
:cl-djula-tailwind.typography
:cl-djula-tailwind.backgrounds
:cl-djula-tailwind.sizing
:cl-djula-tailwind.borders
:cl-djula-tailwind.effects
:cl-djula-tailwind.flexbox-grid
:cl-djula-tailwind.accessibility
:cl-djula-tailwind.svg
:cl-djula-tailwind.transforms
:cl-djula-tailwind.tables)
(:import-from :cl-ppcre
:all-matches
:do-register-groups
:all-matches-as-strings
:regex-replace-all)
(:export :get-stylesheet
:get-plain-class
:get-pseudo-class
:get-responsive-class
:get-darkmode-class
:get-peer-class
:get-form-state-class
:get-child-modifier-class))
(in-package :cl-djula-tailwind)
(defvar *util-prop-hash* '(
("p" . :padding)
("pt" . :padding-top)
("pr" . :padding-right)
("pb" . :padding-bottom)
("pl" . :padding-left)
("m" . :margin)
("mt" . :margin-top)
("mr" . :margin-right)
("mb" . :margin-bottom)
("ml" . :margin-left)
("h" . :height)
("min-h" . :min-height)
("max-h" . :max-height)
("w" . :width)
("min-w" . :min-width)
("max-w" . :max-width)
))
(defun parse-template-string (path dir)
"Parse Djula template from the given path"
(djula::parse-template-string (uiop::read-file-string (merge-pathnames path dir))))
(defun get-markup (template)
"Get the HTML markup from the template content"
(let ((markup '()))
(dolist (l template)
(let ((x (first l))
(y (second l)))
(when (eq x :string)
(push y markup))))
(remove-duplicates (reverse markup) :test #'string=)))
(defun find-class-attrs (html)
"Find the class attribute values"
(loop for l in html
for x = (all-matches-as-strings "class=\"([^\"]*)\"" l)
when x
collect x))
(defun replace-class-keyword (props)
"Remove the class keywords and extra quotes"
(let ((classnames '()))
(dolist (line props)
(dolist (word line)
(let* ((x (regex-replace-all "class=" word ""))
(y (regex-replace-all "\\\"" x "")))
(push y classnames))))
(reverse classnames)))
(defun join-string-list (string-list)
"Concatenates a list of strings and puts spaces between the elements."
(format nil "~{~A~^ ~}" string-list))
(defun split-by-one-space (string)
"Returns a list of substrings of string
divided by ONE space each.
Note: Two consecutive spaces will be seen as
if there were an empty string between them."
(remove-duplicates
(loop for i = 0 then (1+ j)
as j = (position #\Space string :start i)
collect (subseq string i j)
while j) :test #'string=))
(defun get-classnames (markup)
"Get the list of Tailwind class names as a list"
(split-by-one-space
(join-string-list
(replace-class-keyword
(find-class-attrs markup)))))
(defvar *tailwind* (append
*layout*
*spacing*
*typography*
*backgrounds*
*sizing*
*borders*
*effects*
*flexbox-grid*
*accessibility*
*svg*
*transforms*
*tables*
))
(defun is-plain-util (c)
(assoc c *tailwind* :test #'string=))
(defun is-pseudo-util (str)
(all-matches "(hover|focus|active|disabled):([a-z0-9-]*)" str))
(defun is-darkmode-util (str)
(all-matches "dark:([a-z0-9-]*)" str))
(defun is-responsive-util (str)
(all-matches "(sm|md|lg|xl|2xl):([a-z0-9-]*)" str))
(defun is-peer-util (str)
(all-matches "peer-(checked|hover|focus|active|disabled):([a-z0-9-]*)" str))
(defvar *form-state-util-regex* "(required|invalid|disabled):([a-z0-9-]*)")
(defun form-state-utilp (str)
"Is this a form state modifier util"
(all-matches *form-state-util-regex* str))
(defun get-form-state-class (str)
"Generate class definitions for required: invalid: and other form states"
(let (result)
(do-register-groups
(state class)
(*form-state-util-regex* str)
(let ((classname (concatenate 'string "." state "\\:" class ":" state))
(props (cdr (cadr (assoc class *tailwind* :test #'string=)))))
(push (concatenate 'string classname " { " (cl-css:inline-css props) " }") result)))
(car result)))
(defvar *arbitrary-value-regex* "([a-z]*)-\\[([a-z0-9-]*)\\]")
(defun arbitrary-value-utilp (str)
"Is this an arbitrary value util"
(all-matches *arbitrary-value-regex* str))
(defun get-arbitrary-value-class (str)
"Generate class definitions for arbitrary values"
(let (result)
(do-register-groups
(class value)
(*arbitrary-value-regex* str)
(let ((classname (concatenate 'string "." class "-\\[" value "\\] " ))
(props (cdr (assoc class *util-prop-hash* :test #'string=))))
(push (concatenate 'string classname " { " (cl-css:inline-css `(,props ,value)) " }") result)))
(car result)))
(defvar *child-modifier-regex* "(first|last|odd|even):([a-z0-9-]*)")
(defun child-modifier-utilp (str)
"Is this a child modifier util"
(all-matches *child-modifier-regex* str))
(defun get-child-modifier-class (str)
"Generate class definitions for first: last: and other child modifiers"
(let (result)
(do-register-groups
(state class)
(*child-modifier-regex* str)
(let ((classname (concatenate 'string "." state "\\:" class ":" state))
(props (cdr (cadr (assoc class *tailwind* :test #'string=)))))
(push (concatenate 'string classname " { " (cl-css:inline-css props) " }") result)))
(car result)))
(defun get-plain-class (str)
"Generate class definitions for simple plain utilities"
(cl-css:css (cdr (assoc str *tailwind* :test #'string=))))
(defun get-pseudo-class (str)
"Generate class definitions for hover: focus: and other states"
(let (result)
(do-register-groups
(state class)
("(hover|focus|active|disabled|focus-within|focus-visible):([a-z0-9-]*)" str)
(let ((classname (concatenate 'string "." state "\\:" class ":" state))
(props (cdr (cadr (assoc class *tailwind* :test #'string=)))))
(push (concatenate 'string classname " { " (cl-css:inline-css props) " }") result)))
(car result)))
(defun get-darkmode-class (str)
"Generate class definitions for darkmode"
(let (result)
(do-register-groups
(state class)
("(dark):([a-z0-9-]*)" str)
(let ((classname (concatenate 'string "." state "\\:" class))
(props (cdr (cadr (assoc class *tailwind* :test #'string=)))))
(push (concatenate 'string "@media (prefers-color-scheme: dark) { " classname " { " (cl-css:inline-css props) " } }") result)))
(car result)))
(defvar *media-query* '(("sm" . "@media (min-width: 640px)")
("md" . "@media (min-width: 768px)")
("lg" . "@media (min-width: 1024px)")
("xl" . "@media (min-width: 1280px)")
("2xl" . "@media (min-width: 1536px)")))
(defun get-media-query (breakpoint)
(cdr (assoc breakpoint *media-query* :test #'string=)))
(defun get-responsive-class (str)
"Generate class definitions for responsive utility variants sm: md: lg: etc.,"
(let (result)
(do-register-groups
(breakpoint class)
("(sm|md|lg|xl|2xl):([a-z0-9-]*)" str)
(let ((classname (concatenate 'string "." breakpoint "\\:" class ))
(props (cdr (cadr (assoc class *tailwind* :test #'string=)))))
(push (concatenate 'string
(get-media-query breakpoint) " { " classname " { " (cl-css:inline-css props) " } }") result)))
(car result)))
(defun get-peer-class (str)
"Generate class definitions for peer:{{modifier}} states"
(let (result)
(do-register-groups
(state class)
("peer-(checked|invalid|required|hover|focus|active|disabled|focus-within|focus-visible):([a-z0-9-]*)" str)
(let ((classname (concatenate 'string ".peer:" state " ~ .peer-" state "\\:" class))
(props (cdr (cadr (assoc class *tailwind* :test #'string=)))))
(push (concatenate 'string classname " { " (cl-css:inline-css props) " }") result)))
(car result)))
(defvar *group-regex* "group-(hover|focus|active):([a-z0-9-]*)")
(defun group-utilp (str)
"Is this a group modifier util"
(all-matches *group-regex* str))
(defun get-group-class (str)
"Generate class definitions for group-*:{{modifier}} states"
(let (result)
(do-register-groups
(state class)
(*group-regex* str)
(let ((classname (concatenate 'string ".group:" state " ~ .group-" state "\\:" class))
(props (cdr (cadr (assoc class *tailwind* :test #'string=)))))
(push (concatenate 'string classname " { " (cl-css:inline-css props) " }") result)))
(car result)))
(defun get-templates (root-template)
"Get the list of templates - extends and includes from the root-template"
(let ((templates '()))
(dolist (l root-template)
(let ((x (first l))
(y (second l)))
(when (eq x :unparsed-tag)
(do-register-groups
(tag template-name)
("(extends|include) \"([_a-z\/\.]*)\"" y)
(push template-name templates)))
))
(reverse templates)))
(defun get-stylesheet (file dir)
"Generate the stylesheet based on tailwind class definitions"
(let* ((root-template (parse-template-string file dir))
(templates (get-templates root-template))
(markup '()))
Let get the list of templates first
(dolist (tmplt templates)
(let ((template-content (parse-template-string tmplt dir)))
(push (join-string-list (get-markup template-content)) markup)))
(push (join-string-list (get-markup root-template)) markup)
(let ((styles '()))
(dolist (c (get-classnames markup))
(cond
((is-plain-util c) (push (get-plain-class c) styles))
((is-pseudo-util c) (push (get-pseudo-class c) styles))
((is-responsive-util c) (push (get-responsive-class c) styles))
((is-darkmode-util c) (push (get-darkmode-class c) styles))
((is-peer-util c) (push (get-peer-class c) styles))
((form-state-utilp c) (push (get-form-state-class c) styles))
((child-modifier-utilp c) (push (get-child-modifier-class c) styles))
((group-utilp c) (push (get-group-class c) styles))
((arbitrary-value-utilp c) (push (get-arbitrary-value-class c) styles))
(t (print c))))
(cl-minify-css:minify-css (join-string-list (reverse styles))))))
|
3156eaed8100ea924267bd5846c088ff356826d3f1a1f161b812bcaa6f5edc9e | 2600hz/kazoo | kazoo_tts.erl | %%%-----------------------------------------------------------------------------
( C ) 2010 - 2020 , 2600Hz
%%% @doc
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%%
%%% @end
%%%-----------------------------------------------------------------------------
-module(kazoo_tts).
-export([create/1
,create/2
,create/3
,create/4
,create/5
]).
-export([decode/4]).
-export([cache_time_ms/0
,default_provider/0, default_provider/1, set_default_provider/1
,default_language/0, set_default_language/1
,default_voice/0, set_default_voice/1
,provider_module/1
]).
-include("kazoo_speech.hrl").
-spec create(kz_term:ne_binary()) -> create_resp().
create(Text) ->
create(Text, <<"female/en-us">>).
-spec create(kz_term:ne_binary(), kz_term:ne_binary()) -> create_resp().
create(Text, Voice) ->
create(Text, Voice, <<"wav">>).
-spec create(kz_term:ne_binary(), kz_term:ne_binary(), kz_term:ne_binary()) -> create_resp().
create(Text, Voice, Format) ->
create(Text, Voice, Format, []).
-spec create(kz_term:ne_binary(), kz_term:ne_binary(), kz_term:ne_binary(), kz_term:proplist()) -> create_resp().
create(Text, Voice, Format, Options) ->
create(default_provider(), Text, Voice, Format, Options).
-spec create(kz_term:api_binary(), kz_term:ne_binary(), kz_term:ne_binary(), kz_term:ne_binary(), kz_term:proplist()) -> create_resp().
create('undefined', Text, Voice, Format, Options) ->
create(Text, Voice, Format, Options);
create(<<"flite">>, _Text, _Voice, _Format, _Options) ->
{'error', 'tts_provider_failure', <<"flite is not available to create TTS media">>};
create(Provider, Text, Voice, Format, Options) ->
lager:debug("using provider ~s to create tts", [Provider]),
Module = provider_module(Provider),
Module:create(Text, Voice, Format, Options).
-spec decode(kz_term:ne_binary(), kz_term:ne_binary(), kz_json:object(), any()) -> decode_resp().
decode(Provider, Contents, Metadata, ProviderData) ->
lager:debug("using provider ~s to decode response", [Provider]),
Module = provider_module(Provider),
case kz_module:is_exported(Module, 'decode', 3) of
'true' -> Module:decode(Contents, Metadata, ProviderData);
'false' -> {Contents, Metadata}
end.
-spec provider_module(kz_term:ne_binary()) -> atom().
provider_module(Provider) ->
kz_term:to_atom(<<"kazoo_tts_", Provider/binary>>, 'true').
-spec cache_time_ms() -> pos_integer().
cache_time_ms() ->
kapps_config:get_integer(?MOD_CONFIG_CAT, <<"tts_cache">>, ?MILLISECONDS_IN_HOUR).
-spec default_provider() -> kz_term:ne_binary().
default_provider() ->
kapps_config:get_binary(?MOD_CONFIG_CAT, <<"tts_provider">>, <<"flite">>).
-spec default_provider(kapps_call:call()) -> kz_term:ne_binary().
default_provider(Call) ->
Default = default_provider(),
kapps_account_config:get_global(kapps_call:account_id(Call)
,?MOD_CONFIG_CAT
,<<"tts_provider">>
,Default
).
-spec set_default_provider(kz_term:ne_binary()) -> 'ok'.
set_default_provider(Provider) ->
{'ok', _} = kapps_config:set_default(?MOD_CONFIG_CAT, <<"tts_provider">>, Provider),
'ok'.
-spec default_language() -> kz_term:ne_binary().
default_language() ->
kapps_config:get_binary(?MOD_CONFIG_CAT, <<"tts_language">>, <<"en-us">>).
-spec set_default_language(kz_term:ne_binary()) -> 'ok'.
set_default_language(Language) ->
{'ok', _} = kapps_config:set_default(?MOD_CONFIG_CAT, <<"tts_language">>, Language),
'ok'.
-spec default_voice() -> kz_term:ne_binary().
default_voice() ->
kapps_config:get_binary(?MOD_CONFIG_CAT, <<"tts_voice">>, <<"male">>).
-spec set_default_voice(kz_term:ne_binary()) -> 'ok'.
set_default_voice(Voice) ->
{'ok', _} = kapps_config:set_default(?MOD_CONFIG_CAT, <<"tts_voice">>, Voice),
'ok'.
| null | https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/core/kazoo_speech/src/kazoo_tts.erl | erlang | -----------------------------------------------------------------------------
@doc
@end
----------------------------------------------------------------------------- | ( C ) 2010 - 2020 , 2600Hz
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
-module(kazoo_tts).
-export([create/1
,create/2
,create/3
,create/4
,create/5
]).
-export([decode/4]).
-export([cache_time_ms/0
,default_provider/0, default_provider/1, set_default_provider/1
,default_language/0, set_default_language/1
,default_voice/0, set_default_voice/1
,provider_module/1
]).
-include("kazoo_speech.hrl").
-spec create(kz_term:ne_binary()) -> create_resp().
create(Text) ->
create(Text, <<"female/en-us">>).
-spec create(kz_term:ne_binary(), kz_term:ne_binary()) -> create_resp().
create(Text, Voice) ->
create(Text, Voice, <<"wav">>).
-spec create(kz_term:ne_binary(), kz_term:ne_binary(), kz_term:ne_binary()) -> create_resp().
create(Text, Voice, Format) ->
create(Text, Voice, Format, []).
-spec create(kz_term:ne_binary(), kz_term:ne_binary(), kz_term:ne_binary(), kz_term:proplist()) -> create_resp().
create(Text, Voice, Format, Options) ->
create(default_provider(), Text, Voice, Format, Options).
-spec create(kz_term:api_binary(), kz_term:ne_binary(), kz_term:ne_binary(), kz_term:ne_binary(), kz_term:proplist()) -> create_resp().
create('undefined', Text, Voice, Format, Options) ->
create(Text, Voice, Format, Options);
create(<<"flite">>, _Text, _Voice, _Format, _Options) ->
{'error', 'tts_provider_failure', <<"flite is not available to create TTS media">>};
create(Provider, Text, Voice, Format, Options) ->
lager:debug("using provider ~s to create tts", [Provider]),
Module = provider_module(Provider),
Module:create(Text, Voice, Format, Options).
-spec decode(kz_term:ne_binary(), kz_term:ne_binary(), kz_json:object(), any()) -> decode_resp().
decode(Provider, Contents, Metadata, ProviderData) ->
lager:debug("using provider ~s to decode response", [Provider]),
Module = provider_module(Provider),
case kz_module:is_exported(Module, 'decode', 3) of
'true' -> Module:decode(Contents, Metadata, ProviderData);
'false' -> {Contents, Metadata}
end.
-spec provider_module(kz_term:ne_binary()) -> atom().
provider_module(Provider) ->
kz_term:to_atom(<<"kazoo_tts_", Provider/binary>>, 'true').
-spec cache_time_ms() -> pos_integer().
cache_time_ms() ->
kapps_config:get_integer(?MOD_CONFIG_CAT, <<"tts_cache">>, ?MILLISECONDS_IN_HOUR).
-spec default_provider() -> kz_term:ne_binary().
default_provider() ->
kapps_config:get_binary(?MOD_CONFIG_CAT, <<"tts_provider">>, <<"flite">>).
-spec default_provider(kapps_call:call()) -> kz_term:ne_binary().
default_provider(Call) ->
Default = default_provider(),
kapps_account_config:get_global(kapps_call:account_id(Call)
,?MOD_CONFIG_CAT
,<<"tts_provider">>
,Default
).
-spec set_default_provider(kz_term:ne_binary()) -> 'ok'.
set_default_provider(Provider) ->
{'ok', _} = kapps_config:set_default(?MOD_CONFIG_CAT, <<"tts_provider">>, Provider),
'ok'.
-spec default_language() -> kz_term:ne_binary().
default_language() ->
kapps_config:get_binary(?MOD_CONFIG_CAT, <<"tts_language">>, <<"en-us">>).
-spec set_default_language(kz_term:ne_binary()) -> 'ok'.
set_default_language(Language) ->
{'ok', _} = kapps_config:set_default(?MOD_CONFIG_CAT, <<"tts_language">>, Language),
'ok'.
-spec default_voice() -> kz_term:ne_binary().
default_voice() ->
kapps_config:get_binary(?MOD_CONFIG_CAT, <<"tts_voice">>, <<"male">>).
-spec set_default_voice(kz_term:ne_binary()) -> 'ok'.
set_default_voice(Voice) ->
{'ok', _} = kapps_config:set_default(?MOD_CONFIG_CAT, <<"tts_voice">>, Voice),
'ok'.
|
12320eb6b9cee003709ed596c66ba1144a903f27d1c6daf458332f925fdee19f | ucsd-progsys/nate | odoc_search.mli | (***********************************************************************)
(* OCamldoc *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 2001 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ I d : odoc_search.mli , v 1.4 2003/11/24 10:43:12 starynke Exp $
(** Research of elements through modules. *)
(** The type for an element of the result of a research. *)
type result_element =
Res_module of Odoc_module.t_module
| Res_module_type of Odoc_module.t_module_type
| Res_class of Odoc_class.t_class
| Res_class_type of Odoc_class.t_class_type
| Res_value of Odoc_value.t_value
| Res_type of Odoc_type.t_type
| Res_exception of Odoc_exception.t_exception
| Res_attribute of Odoc_value.t_attribute
| Res_method of Odoc_value.t_method
| Res_section of string * Odoc_types.text
(** The type representing a research result.*)
type result = result_element list
* The type of modules which contain the predicates used during the research .
Some functions return a couple of booleans ; the first indicates if we
must go deeper in the analysed element , the second if the element satisfies
the predicate .
Some functions return a couple of booleans ; the first indicates if we
must go deeper in the analysed element, the second if the element satisfies
the predicate.
*)
module type Predicates =
sig
type t
val p_module : Odoc_module.t_module -> t -> bool * bool
val p_module_type : Odoc_module.t_module_type -> t -> bool * bool
val p_class : Odoc_class.t_class -> t -> bool * bool
val p_class_type : Odoc_class.t_class_type -> t -> bool * bool
val p_value : Odoc_value.t_value -> t -> bool
val p_type : Odoc_type.t_type -> t -> bool
val p_exception : Odoc_exception.t_exception -> t -> bool
val p_attribute : Odoc_value.t_attribute -> t -> bool
val p_method : Odoc_value.t_method -> t -> bool
val p_section : string -> t -> bool
end
(** Search for elements verifying the predicates in the module in parameter.*)
module Search :
functor (P : Predicates) ->
sig
(** search in a section title *)
val search_section : Odoc_types.text -> string -> P.t -> result_element list
(** search in a value *)
val search_value : Odoc_value.t_value -> P.t -> result_element list
(** search in a type *)
val search_type : Odoc_type.t_type -> P.t -> result_element list
(** search in an exception *)
val search_exception :
Odoc_exception.t_exception -> P.t -> result_element list
(** search in an attribute *)
val search_attribute :
Odoc_value.t_attribute -> P.t -> result_element list
(** search in a method *)
val search_method : Odoc_value.t_method -> P.t -> result_element list
(** search in a class *)
val search_class : Odoc_class.t_class -> P.t -> result_element list
(** search in a class type *)
val search_class_type :
Odoc_class.t_class_type -> P.t -> result_element list
(** search in a module type *)
val search_module_type :
Odoc_module.t_module_type -> P.t -> result_element list
(** search in a module *)
val search_module : Odoc_module.t_module -> P.t -> result_element list
(** search in a list of modules *)
val search : Odoc_module.t_module list -> P.t -> result_element list
end
(** A module of predicates to search elements by name (and accepting regexps).*)
module P_name :
sig
type t = Str.regexp
val ( =~ ) : string -> Str.regexp -> bool
val p_module : Odoc_module.t_module -> Str.regexp -> bool * bool
val p_module_type :
Odoc_module.t_module_type -> Str.regexp -> bool * bool
val p_class : Odoc_class.t_class -> Str.regexp -> bool * bool
val p_class_type : Odoc_class.t_class_type -> Str.regexp -> bool * bool
val p_value : Odoc_value.t_value -> Str.regexp -> bool
val p_type : Odoc_type.t_type -> Str.regexp -> bool
val p_exception : Odoc_exception.t_exception -> Str.regexp -> bool
val p_attribute : Odoc_value.t_attribute -> Str.regexp -> bool
val p_method : Odoc_value.t_method -> Str.regexp -> bool
end
(** A module to search elements by name. *)
module Search_by_name :
sig
val search_section : Odoc_types.text -> string -> P_name.t -> result_element list
val search_value : Odoc_value.t_value -> P_name.t -> result_element list
val search_type : Odoc_type.t_type -> P_name.t -> result_element list
val search_exception :
Odoc_exception.t_exception -> P_name.t -> result_element list
val search_attribute :
Odoc_value.t_attribute -> P_name.t -> result_element list
val search_method :
Odoc_value.t_method -> P_name.t -> result_element list
val search_class : Odoc_class.t_class -> P_name.t -> result_element list
val search_class_type :
Odoc_class.t_class_type -> P_name.t -> result_element list
val search_module_type :
Odoc_module.t_module_type -> P_name.t -> result_element list
val search_module :
Odoc_module.t_module -> P_name.t -> result_element list
val search : Odoc_module.t_module list -> P_name.t -> result_element list
end
(** A function to search all the values in a list of modules. *)
val values : Odoc_module.t_module list -> Odoc_value.t_value list
(** A function to search all the exceptions in a list of modules. *)
val exceptions : Odoc_module.t_module list -> Odoc_exception.t_exception list
(** A function to search all the types in a list of modules. *)
val types : Odoc_module.t_module list -> Odoc_type.t_type list
(** A function to search all the class attributes in a list of modules. *)
val attributes : Odoc_module.t_module list -> Odoc_value.t_attribute list
(** A function to search all the class methods in a list of modules. *)
val methods : Odoc_module.t_module list -> Odoc_value.t_method list
(** A function to search all the classes in a list of modules. *)
val classes : Odoc_module.t_module list -> Odoc_class.t_class list
(** A function to search all the class types in a list of modules. *)
val class_types : Odoc_module.t_module list -> Odoc_class.t_class_type list
(** A function to search all the modules in a list of modules. *)
val modules : Odoc_module.t_module list -> Odoc_module.t_module list
(** A function to search all the module types in a list of modules. *)
val module_types : Odoc_module.t_module list -> Odoc_module.t_module_type list
(** Return [true] if a type with the given complete name (regexp) exists
in the given module list.*)
val type_exists : Odoc_module.t_module list -> Str.regexp -> bool
(** Return [true] if a value with the given complete name (regexp) exists
in the given module list.*)
val value_exists : Odoc_module.t_module list -> Str.regexp -> bool
(** Return [true] if a module with the given complete name (regexp) exists
in the given module list.*)
val module_exists : Odoc_module.t_module list -> Str.regexp -> bool
(** Return [true] if a module type with the given complete name (regexp) exists
in the given module list.*)
val module_type_exists : Odoc_module.t_module list -> Str.regexp -> bool
(** Return [true] if a class with the given complete name (regexp) exists
in the given module list.*)
val class_exists : Odoc_module.t_module list -> Str.regexp -> bool
(** Return [true] if a class type with the given complete name (regexp) exists
in the given module list.*)
val class_type_exists : Odoc_module.t_module list -> Str.regexp -> bool
(** Return [true] if a exception with the given complete name (regexp) exists
in the given module list.*)
val exception_exists : Odoc_module.t_module list -> Str.regexp -> bool
(** Return [true] if an attribute with the given complete name (regexp) exists
in the given module list.*)
val attribute_exists : Odoc_module.t_module list -> Str.regexp -> bool
(** Return [true] if a method with the given complete name (regexp) exists
in the given module list.*)
val method_exists : Odoc_module.t_module list -> Str.regexp -> bool
(** Return the [text] of the section with the given complete name (regexp)
in the given module list.
@raise Not_found if the section was not found.*)
val find_section : Odoc_module.t_module list -> Str.regexp -> Odoc_types.text
| null | https://raw.githubusercontent.com/ucsd-progsys/nate/8b1267cd8b10283d8bc239d16a28c654a4cb8942/eval/sherrloc/easyocaml%2B%2B/ocamldoc/odoc_search.mli | ocaml | *********************************************************************
OCamldoc
*********************************************************************
* Research of elements through modules.
* The type for an element of the result of a research.
* The type representing a research result.
* Search for elements verifying the predicates in the module in parameter.
* search in a section title
* search in a value
* search in a type
* search in an exception
* search in an attribute
* search in a method
* search in a class
* search in a class type
* search in a module type
* search in a module
* search in a list of modules
* A module of predicates to search elements by name (and accepting regexps).
* A module to search elements by name.
* A function to search all the values in a list of modules.
* A function to search all the exceptions in a list of modules.
* A function to search all the types in a list of modules.
* A function to search all the class attributes in a list of modules.
* A function to search all the class methods in a list of modules.
* A function to search all the classes in a list of modules.
* A function to search all the class types in a list of modules.
* A function to search all the modules in a list of modules.
* A function to search all the module types in a list of modules.
* Return [true] if a type with the given complete name (regexp) exists
in the given module list.
* Return [true] if a value with the given complete name (regexp) exists
in the given module list.
* Return [true] if a module with the given complete name (regexp) exists
in the given module list.
* Return [true] if a module type with the given complete name (regexp) exists
in the given module list.
* Return [true] if a class with the given complete name (regexp) exists
in the given module list.
* Return [true] if a class type with the given complete name (regexp) exists
in the given module list.
* Return [true] if a exception with the given complete name (regexp) exists
in the given module list.
* Return [true] if an attribute with the given complete name (regexp) exists
in the given module list.
* Return [true] if a method with the given complete name (regexp) exists
in the given module list.
* Return the [text] of the section with the given complete name (regexp)
in the given module list.
@raise Not_found if the section was not found. | , projet Cristal , INRIA Rocquencourt
Copyright 2001 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ I d : odoc_search.mli , v 1.4 2003/11/24 10:43:12 starynke Exp $
type result_element =
Res_module of Odoc_module.t_module
| Res_module_type of Odoc_module.t_module_type
| Res_class of Odoc_class.t_class
| Res_class_type of Odoc_class.t_class_type
| Res_value of Odoc_value.t_value
| Res_type of Odoc_type.t_type
| Res_exception of Odoc_exception.t_exception
| Res_attribute of Odoc_value.t_attribute
| Res_method of Odoc_value.t_method
| Res_section of string * Odoc_types.text
type result = result_element list
* The type of modules which contain the predicates used during the research .
Some functions return a couple of booleans ; the first indicates if we
must go deeper in the analysed element , the second if the element satisfies
the predicate .
Some functions return a couple of booleans ; the first indicates if we
must go deeper in the analysed element, the second if the element satisfies
the predicate.
*)
module type Predicates =
sig
type t
val p_module : Odoc_module.t_module -> t -> bool * bool
val p_module_type : Odoc_module.t_module_type -> t -> bool * bool
val p_class : Odoc_class.t_class -> t -> bool * bool
val p_class_type : Odoc_class.t_class_type -> t -> bool * bool
val p_value : Odoc_value.t_value -> t -> bool
val p_type : Odoc_type.t_type -> t -> bool
val p_exception : Odoc_exception.t_exception -> t -> bool
val p_attribute : Odoc_value.t_attribute -> t -> bool
val p_method : Odoc_value.t_method -> t -> bool
val p_section : string -> t -> bool
end
module Search :
functor (P : Predicates) ->
sig
val search_section : Odoc_types.text -> string -> P.t -> result_element list
val search_value : Odoc_value.t_value -> P.t -> result_element list
val search_type : Odoc_type.t_type -> P.t -> result_element list
val search_exception :
Odoc_exception.t_exception -> P.t -> result_element list
val search_attribute :
Odoc_value.t_attribute -> P.t -> result_element list
val search_method : Odoc_value.t_method -> P.t -> result_element list
val search_class : Odoc_class.t_class -> P.t -> result_element list
val search_class_type :
Odoc_class.t_class_type -> P.t -> result_element list
val search_module_type :
Odoc_module.t_module_type -> P.t -> result_element list
val search_module : Odoc_module.t_module -> P.t -> result_element list
val search : Odoc_module.t_module list -> P.t -> result_element list
end
module P_name :
sig
type t = Str.regexp
val ( =~ ) : string -> Str.regexp -> bool
val p_module : Odoc_module.t_module -> Str.regexp -> bool * bool
val p_module_type :
Odoc_module.t_module_type -> Str.regexp -> bool * bool
val p_class : Odoc_class.t_class -> Str.regexp -> bool * bool
val p_class_type : Odoc_class.t_class_type -> Str.regexp -> bool * bool
val p_value : Odoc_value.t_value -> Str.regexp -> bool
val p_type : Odoc_type.t_type -> Str.regexp -> bool
val p_exception : Odoc_exception.t_exception -> Str.regexp -> bool
val p_attribute : Odoc_value.t_attribute -> Str.regexp -> bool
val p_method : Odoc_value.t_method -> Str.regexp -> bool
end
module Search_by_name :
sig
val search_section : Odoc_types.text -> string -> P_name.t -> result_element list
val search_value : Odoc_value.t_value -> P_name.t -> result_element list
val search_type : Odoc_type.t_type -> P_name.t -> result_element list
val search_exception :
Odoc_exception.t_exception -> P_name.t -> result_element list
val search_attribute :
Odoc_value.t_attribute -> P_name.t -> result_element list
val search_method :
Odoc_value.t_method -> P_name.t -> result_element list
val search_class : Odoc_class.t_class -> P_name.t -> result_element list
val search_class_type :
Odoc_class.t_class_type -> P_name.t -> result_element list
val search_module_type :
Odoc_module.t_module_type -> P_name.t -> result_element list
val search_module :
Odoc_module.t_module -> P_name.t -> result_element list
val search : Odoc_module.t_module list -> P_name.t -> result_element list
end
val values : Odoc_module.t_module list -> Odoc_value.t_value list
val exceptions : Odoc_module.t_module list -> Odoc_exception.t_exception list
val types : Odoc_module.t_module list -> Odoc_type.t_type list
val attributes : Odoc_module.t_module list -> Odoc_value.t_attribute list
val methods : Odoc_module.t_module list -> Odoc_value.t_method list
val classes : Odoc_module.t_module list -> Odoc_class.t_class list
val class_types : Odoc_module.t_module list -> Odoc_class.t_class_type list
val modules : Odoc_module.t_module list -> Odoc_module.t_module list
val module_types : Odoc_module.t_module list -> Odoc_module.t_module_type list
val type_exists : Odoc_module.t_module list -> Str.regexp -> bool
val value_exists : Odoc_module.t_module list -> Str.regexp -> bool
val module_exists : Odoc_module.t_module list -> Str.regexp -> bool
val module_type_exists : Odoc_module.t_module list -> Str.regexp -> bool
val class_exists : Odoc_module.t_module list -> Str.regexp -> bool
val class_type_exists : Odoc_module.t_module list -> Str.regexp -> bool
val exception_exists : Odoc_module.t_module list -> Str.regexp -> bool
val attribute_exists : Odoc_module.t_module list -> Str.regexp -> bool
val method_exists : Odoc_module.t_module list -> Str.regexp -> bool
val find_section : Odoc_module.t_module list -> Str.regexp -> Odoc_types.text
|
ec1e1c3d3398308f794c7baeb1fa1e86014d7cd2f965db463fbf3f6762dabd49 | gedge-platform/gedge-platform | rabbit_event.erl | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%
Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved .
%%
-module(rabbit_event).
-include("rabbit.hrl").
-export([start_link/0]).
-export([init_stats_timer/2, init_disabled_stats_timer/2,
ensure_stats_timer/3, stop_stats_timer/2, reset_stats_timer/2]).
-export([stats_level/2, if_enabled/3]).
-export([notify/2, notify/3, notify_if/3]).
-export([sync_notify/2, sync_notify/3]).
-ignore_xref([{gen_event, start_link, 2}]).
-dialyzer([{no_missing_calls, start_link/0}]).
%%----------------------------------------------------------------------------
-record(state, {level, interval, timer}).
%%----------------------------------------------------------------------------
-export_type([event_type/0, event_props/0, event_timestamp/0, event/0]).
-type event_type() :: atom().
-type event_props() :: term().
-type event_timestamp() :: non_neg_integer().
-type event() :: #event { type :: event_type(),
props :: event_props(),
reference :: 'none' | reference(),
timestamp :: event_timestamp() }.
-type level() :: 'none' | 'coarse' | 'fine'.
-type timer_fun() :: fun (() -> 'ok').
-type container() :: tuple().
-type pos() :: non_neg_integer().
-spec start_link() -> rabbit_types:ok_pid_or_error().
-spec init_stats_timer(container(), pos()) -> container().
-spec init_disabled_stats_timer(container(), pos()) -> container().
-spec ensure_stats_timer(container(), pos(), term()) -> container().
-spec stop_stats_timer(container(), pos()) -> container().
-spec reset_stats_timer(container(), pos()) -> container().
-spec stats_level(container(), pos()) -> level().
-spec if_enabled(container(), pos(), timer_fun()) -> 'ok'.
-spec notify(event_type(), event_props()) -> 'ok'.
-spec notify(event_type(), event_props(), reference() | 'none') -> 'ok'.
-spec notify_if(boolean(), event_type(), event_props()) -> 'ok'.
-spec sync_notify(event_type(), event_props()) -> 'ok'.
-spec sync_notify(event_type(), event_props(), reference() | 'none') -> 'ok'.
%%----------------------------------------------------------------------------
start_link() ->
gen_event : start_link/2 is not available before OTP 20
RabbitMQ 3.7 supports OTP > = 19.3
case erlang:function_exported(gen_event, start_link, 2) of
true ->
gen_event:start_link(
{local, ?MODULE},
[{spawn_opt, [{fullsweep_after, 0}]}]
);
false ->
gen_event:start_link({local, ?MODULE})
end.
%% The idea is, for each stat-emitting object:
%%
%% On startup:
%% init_stats_timer(State)
%% notify(created event)
if_enabled(internal_emit_stats ) - so we immediately send something
%%
%% On wakeup:
%% ensure_stats_timer(State, emit_stats)
( Note we ca n't emit stats immediately , the timer may have fired 1ms ago . )
%%
%% emit_stats:
if_enabled(internal_emit_stats )
%% reset_stats_timer(State) - just bookkeeping
%%
%% Pre-hibernation:
if_enabled(internal_emit_stats )
%% stop_stats_timer(State)
%%
%% internal_emit_stats:
%% notify(stats)
init_stats_timer(C, P) ->
If the rabbit app is not loaded - use default none:5000
StatsLevel = application:get_env(rabbit, collect_statistics, none),
Interval = application:get_env(rabbit, collect_statistics_interval, 5000),
setelement(P, C, #state{level = StatsLevel, interval = Interval,
timer = undefined}).
init_disabled_stats_timer(C, P) ->
setelement(P, C, #state{level = none, interval = 0, timer = undefined}).
ensure_stats_timer(C, P, Msg) ->
case element(P, C) of
#state{level = Level, interval = Interval, timer = undefined} = State
when Level =/= none ->
TRef = erlang:send_after(Interval, self(), Msg),
setelement(P, C, State#state{timer = TRef});
#state{} ->
C
end.
stop_stats_timer(C, P) ->
case element(P, C) of
#state{timer = TRef} = State when TRef =/= undefined ->
case erlang:cancel_timer(TRef) of
false -> C;
_ -> setelement(P, C, State#state{timer = undefined})
end;
#state{} ->
C
end.
reset_stats_timer(C, P) ->
case element(P, C) of
#state{timer = TRef} = State when TRef =/= undefined ->
setelement(P, C, State#state{timer = undefined});
#state{} ->
C
end.
stats_level(C, P) ->
#state{level = Level} = element(P, C),
Level.
if_enabled(C, P, Fun) ->
case element(P, C) of
#state{level = none} -> ok;
#state{} -> Fun(), ok
end.
notify_if(true, Type, Props) -> notify(Type, Props);
notify_if(false, _Type, _Props) -> ok.
notify(Type, Props) -> notify(Type, rabbit_data_coercion:to_proplist(Props), none).
notify(Type, Props, Ref) ->
%% Using {Name, node()} here to not fail if the event handler is not started
gen_event:notify({?MODULE, node()}, event_cons(Type, rabbit_data_coercion:to_proplist(Props), Ref)).
sync_notify(Type, Props) -> sync_notify(Type, Props, none).
sync_notify(Type, Props, Ref) ->
gen_event:sync_notify(?MODULE, event_cons(Type, Props, Ref)).
event_cons(Type, Props, Ref) ->
#event{type = Type,
props = Props,
reference = Ref,
timestamp = os:system_time(milli_seconds)}.
| null | https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/rabbit_common/src/rabbit_event.erl | erlang |
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
The idea is, for each stat-emitting object:
On startup:
init_stats_timer(State)
notify(created event)
On wakeup:
ensure_stats_timer(State, emit_stats)
emit_stats:
reset_stats_timer(State) - just bookkeeping
Pre-hibernation:
stop_stats_timer(State)
internal_emit_stats:
notify(stats)
Using {Name, node()} here to not fail if the event handler is not started | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved .
-module(rabbit_event).
-include("rabbit.hrl").
-export([start_link/0]).
-export([init_stats_timer/2, init_disabled_stats_timer/2,
ensure_stats_timer/3, stop_stats_timer/2, reset_stats_timer/2]).
-export([stats_level/2, if_enabled/3]).
-export([notify/2, notify/3, notify_if/3]).
-export([sync_notify/2, sync_notify/3]).
-ignore_xref([{gen_event, start_link, 2}]).
-dialyzer([{no_missing_calls, start_link/0}]).
-record(state, {level, interval, timer}).
-export_type([event_type/0, event_props/0, event_timestamp/0, event/0]).
-type event_type() :: atom().
-type event_props() :: term().
-type event_timestamp() :: non_neg_integer().
-type event() :: #event { type :: event_type(),
props :: event_props(),
reference :: 'none' | reference(),
timestamp :: event_timestamp() }.
-type level() :: 'none' | 'coarse' | 'fine'.
-type timer_fun() :: fun (() -> 'ok').
-type container() :: tuple().
-type pos() :: non_neg_integer().
-spec start_link() -> rabbit_types:ok_pid_or_error().
-spec init_stats_timer(container(), pos()) -> container().
-spec init_disabled_stats_timer(container(), pos()) -> container().
-spec ensure_stats_timer(container(), pos(), term()) -> container().
-spec stop_stats_timer(container(), pos()) -> container().
-spec reset_stats_timer(container(), pos()) -> container().
-spec stats_level(container(), pos()) -> level().
-spec if_enabled(container(), pos(), timer_fun()) -> 'ok'.
-spec notify(event_type(), event_props()) -> 'ok'.
-spec notify(event_type(), event_props(), reference() | 'none') -> 'ok'.
-spec notify_if(boolean(), event_type(), event_props()) -> 'ok'.
-spec sync_notify(event_type(), event_props()) -> 'ok'.
-spec sync_notify(event_type(), event_props(), reference() | 'none') -> 'ok'.
start_link() ->
gen_event : start_link/2 is not available before OTP 20
RabbitMQ 3.7 supports OTP > = 19.3
case erlang:function_exported(gen_event, start_link, 2) of
true ->
gen_event:start_link(
{local, ?MODULE},
[{spawn_opt, [{fullsweep_after, 0}]}]
);
false ->
gen_event:start_link({local, ?MODULE})
end.
if_enabled(internal_emit_stats ) - so we immediately send something
( Note we ca n't emit stats immediately , the timer may have fired 1ms ago . )
if_enabled(internal_emit_stats )
if_enabled(internal_emit_stats )
init_stats_timer(C, P) ->
If the rabbit app is not loaded - use default none:5000
StatsLevel = application:get_env(rabbit, collect_statistics, none),
Interval = application:get_env(rabbit, collect_statistics_interval, 5000),
setelement(P, C, #state{level = StatsLevel, interval = Interval,
timer = undefined}).
init_disabled_stats_timer(C, P) ->
setelement(P, C, #state{level = none, interval = 0, timer = undefined}).
ensure_stats_timer(C, P, Msg) ->
case element(P, C) of
#state{level = Level, interval = Interval, timer = undefined} = State
when Level =/= none ->
TRef = erlang:send_after(Interval, self(), Msg),
setelement(P, C, State#state{timer = TRef});
#state{} ->
C
end.
stop_stats_timer(C, P) ->
case element(P, C) of
#state{timer = TRef} = State when TRef =/= undefined ->
case erlang:cancel_timer(TRef) of
false -> C;
_ -> setelement(P, C, State#state{timer = undefined})
end;
#state{} ->
C
end.
reset_stats_timer(C, P) ->
case element(P, C) of
#state{timer = TRef} = State when TRef =/= undefined ->
setelement(P, C, State#state{timer = undefined});
#state{} ->
C
end.
stats_level(C, P) ->
#state{level = Level} = element(P, C),
Level.
if_enabled(C, P, Fun) ->
case element(P, C) of
#state{level = none} -> ok;
#state{} -> Fun(), ok
end.
notify_if(true, Type, Props) -> notify(Type, Props);
notify_if(false, _Type, _Props) -> ok.
notify(Type, Props) -> notify(Type, rabbit_data_coercion:to_proplist(Props), none).
notify(Type, Props, Ref) ->
gen_event:notify({?MODULE, node()}, event_cons(Type, rabbit_data_coercion:to_proplist(Props), Ref)).
sync_notify(Type, Props) -> sync_notify(Type, Props, none).
sync_notify(Type, Props, Ref) ->
gen_event:sync_notify(?MODULE, event_cons(Type, Props, Ref)).
event_cons(Type, Props, Ref) ->
#event{type = Type,
props = Props,
reference = Ref,
timestamp = os:system_time(milli_seconds)}.
|
2c0d37b7b576bcba5e5d87e8f94cce84faad3ac8eb0bec9c0caacbfeddee7fa7 | mtesseract/nakadi-client | Test.hs | # LANGUAGE DuplicateRecordFields #
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Network.Nakadi.EventTypes.ShiftedCursors.Test where
import ClassyPrelude
import Data.UUID ()
import Network.Nakadi
import Network.Nakadi.Tests.Common
import System.Random
import Test.Tasty
import Test.Tasty.HUnit
testEventTypesShiftedCursors :: Config App -> TestTree
testEventTypesShiftedCursors conf = testGroup "ShiftedCursors"
[ testCase "ShiftedCursorsZero" (testShiftedCursorsZero conf)
, testCase "ShiftedCursorsN" (testShiftedCursorsN conf 10)
]
testShiftedCursorsZero :: Config App -> Assertion
testShiftedCursorsZero conf = runApp . runNakadiT conf $ do
recreateEvent myEventType
partitions <- eventTypePartitions myEventTypeName
let cursors = map extractCursor partitions
cursors' <- cursorsShift myEventTypeName cursors 0
liftIO $ cursors @=? cursors'
testShiftedCursorsN :: Config App -> Int64 -> Assertion
testShiftedCursorsN conf n = runApp . runNakadiT conf $ do
now <- liftIO getCurrentTime
eid <- EventId <$> liftIO randomIO
recreateEvent myEventType
partitions <- eventTypePartitions myEventTypeName
let cursors = map extractCursor partitions
liftIO $ length cursors > 0 @=? True
forM_ [1..n] $ \_ ->
eventsPublish myEventTypeName [myDataChangeEvent eid now]
cursors' <- cursorsShift myEventTypeName cursors n
liftIO $ length cursors' @=? length cursors
forM_ (zip cursors cursors') $ \(c, c') -> do
distance <- cursorDistance myEventTypeName c c'
liftIO $ distance @=? n
| null | https://raw.githubusercontent.com/mtesseract/nakadi-client/f8eef3ac215459081b01b0b48f0b430ae7701f52/tests/Network/Nakadi/EventTypes/ShiftedCursors/Test.hs | haskell | # LANGUAGE FlexibleContexts #
# LANGUAGE ScopedTypeVariables # | # LANGUAGE DuplicateRecordFields #
module Network.Nakadi.EventTypes.ShiftedCursors.Test where
import ClassyPrelude
import Data.UUID ()
import Network.Nakadi
import Network.Nakadi.Tests.Common
import System.Random
import Test.Tasty
import Test.Tasty.HUnit
testEventTypesShiftedCursors :: Config App -> TestTree
testEventTypesShiftedCursors conf = testGroup "ShiftedCursors"
[ testCase "ShiftedCursorsZero" (testShiftedCursorsZero conf)
, testCase "ShiftedCursorsN" (testShiftedCursorsN conf 10)
]
testShiftedCursorsZero :: Config App -> Assertion
testShiftedCursorsZero conf = runApp . runNakadiT conf $ do
recreateEvent myEventType
partitions <- eventTypePartitions myEventTypeName
let cursors = map extractCursor partitions
cursors' <- cursorsShift myEventTypeName cursors 0
liftIO $ cursors @=? cursors'
testShiftedCursorsN :: Config App -> Int64 -> Assertion
testShiftedCursorsN conf n = runApp . runNakadiT conf $ do
now <- liftIO getCurrentTime
eid <- EventId <$> liftIO randomIO
recreateEvent myEventType
partitions <- eventTypePartitions myEventTypeName
let cursors = map extractCursor partitions
liftIO $ length cursors > 0 @=? True
forM_ [1..n] $ \_ ->
eventsPublish myEventTypeName [myDataChangeEvent eid now]
cursors' <- cursorsShift myEventTypeName cursors n
liftIO $ length cursors' @=? length cursors
forM_ (zip cursors cursors') $ \(c, c') -> do
distance <- cursorDistance myEventTypeName c c'
liftIO $ distance @=? n
|
fa9ae9811ce98988ae91a967b43eafab83d69459474dec72e9e1288da4dd42ce | witheve/eve-experiments | avl.clj | (ns server.avl
"An implementation of persistent sorted maps and sets based on AVL
trees which can be used as drop-in replacements for Clojure's
built-in sorted maps and sets based on red-black trees. Apart from
the standard sorted collection API, the provided map and set types
support the transients API and several additional logarithmic time
operations: rank queries via clojure.core/nth (select element by
rank) and clojure.data.avl/rank-of (discover rank of element),
\"nearest key\" lookups via clojure.data.avl/nearest, splits by key
and index via clojure.data.avl/split-key and
clojure.data.avl/split-at, respectively, and subsets/submaps using
clojure.data.avl/subrange."
{:author "Michał Marczyk"}
(:refer-clojure :exclude [sorted-map sorted-map-by sorted-set sorted-set-by
range split-at])
(:import (clojure.lang RT Util APersistentMap APersistentSet
IPersistentMap IPersistentSet IPersistentStack
Box MapEntry SeqIterator)
(java.util Comparator Collections ArrayList)
(java.util.concurrent.atomic AtomicReference)))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(defn ^:private throw-unsupported []
(throw (UnsupportedOperationException.)))
(defmacro ^:private caching-hash [coll hash-fn hash-key]
`(let [h# ~hash-key]
(if-not (== h# (int -1))
h#
(let [h# (~hash-fn ~coll)]
(set! ~hash-key (int h#))
h#))))
(defmacro ^:private compile-if [test then else]
(if (eval test)
then
else))
(def ^:private ^:const empty-set-hashcode (.hashCode #{}))
(def ^:private ^:const empty-set-hasheq (hash #{}))
(def ^:private ^:const empty-map-hashcode (.hashCode {}))
(def ^:private ^:const empty-map-hasheq (hash {}))
(defn ^:private hash-imap
[^IPersistentMap m]
(APersistentMap/mapHash m))
(defn ^:private hasheq-imap
[^IPersistentMap m]
(compile-if (resolve 'clojure.core/hash-unordered-coll)
(hash-unordered-coll m)
(APersistentMap/mapHasheq m)))
(defn ^:private hash-iset [^IPersistentSet s]
;; a la clojure.lang.APersistentSet
(loop [h (int 0) s (seq s)]
(if s
(let [e (first s)]
(recur (unchecked-add-int h (if (nil? e) 0 (.hashCode ^Object e)))
(next s)))
h)))
(defn ^:private hasheq-iset [^IPersistentSet s]
(compile-if (resolve 'clojure.core/hash-unordered-coll)
(hash-unordered-coll s)
(loop [h (int 0) s (seq s)]
(if s
(recur (unchecked-add-int h (Util/hasheq (first s)))
(next s))
h))))
(defn ^:private hash-seq
[s]
(loop [h (int 1) s (seq s)]
(if s
(recur (unchecked-add-int (unchecked-multiply-int (int 31) h)
(if (nil? (first s))
(int 0)
(.hashCode ^Object (first s))))
(next s))
h)))
(defn ^:private hasheq-seq
[s]
(compile-if (resolve 'clojure.core/hash-ordered-coll)
(hash-ordered-coll s)
(loop [h (int 1) s (seq s)]
(if s
(recur (unchecked-add-int (unchecked-multiply-int (int 31) h)
(Util/hasheq (first s)))
(next s))
h))))
(defn ^:private equiv-sequential
"Assumes x is sequential. Returns true if x equals y, otherwise
returns false."
[x y]
(boolean
(when (sequential? y)
(loop [xs (seq x) ys (seq y)]
(cond (nil? xs) (nil? ys)
(nil? ys) false
(= (first xs) (first ys)) (recur (next xs) (next ys))
:else false)))))
(def ^:private never-equiv (Object.))
(defn ^:private equiv-map
"Assumes x is a map. Returns true if y equals x, otherwise returns
false."
[^clojure.lang.IPersistentMap x y]
(if-not (instance? java.util.Map y)
false
(if (and (instance? clojure.lang.IPersistentMap y)
(not (instance? clojure.lang.MapEquivalence y)))
false
(let [m ^java.util.Map y]
(if-not (== (.size ^java.util.Map x) (.size m))
false
(reduce-kv (fn [t k v]
(if-not (.containsKey m k)
(reduced false)
(if-not (Util/equiv v (.get m k))
(reduced false)
t)))
true
x))))))
(gen-interface
:name clojure.data.avl.IAVLNode
:methods
[[getKey [] Object]
[setKey [Object] clojure.data.avl.IAVLNode]
[getVal [] Object]
[setVal [Object] clojure.data.avl.IAVLNode]
[getLeft [] clojure.data.avl.IAVLNode]
[setLeft [clojure.data.avl.IAVLNode] clojure.data.avl.IAVLNode]
[getRight [] clojure.data.avl.IAVLNode]
[setRight [clojure.data.avl.IAVLNode] clojure.data.avl.IAVLNode]
[getHeight [] int]
[setHeight [int] clojure.data.avl.IAVLNode]
[getRank [] int]
[setRank [int] clojure.data.avl.IAVLNode]])
(gen-interface
:name clojure.data.avl.IAVLTree
:methods [[getTree [] clojure.data.avl.IAVLNode]])
(import (clojure.data.avl IAVLNode IAVLTree))
(definterface INavigableTree
(nearest [test k]))
(deftype AVLNode [^AtomicReference edit
^:unsynchronized-mutable key
^:unsynchronized-mutable val
^:unsynchronized-mutable ^IAVLNode left
^:unsynchronized-mutable ^IAVLNode right
^:unsynchronized-mutable ^int height
^:unsynchronized-mutable ^int rank]
IAVLNode
(getKey [this]
key)
(setKey [this k]
(set! key k)
this)
(getVal [this]
val)
(setVal [this v]
(set! val v)
this)
(getLeft [this]
left)
(setLeft [this l]
(set! left l)
this)
(getRight [this]
right)
(setRight [this r]
(set! right r)
this)
(getHeight [this]
height)
(setHeight [this h]
(set! height h)
this)
(getRank [this]
rank)
(setRank [this r]
(set! rank r)
this)
Object
(equals [this that]
(cond
(identical? this that) true
(or (instance? clojure.lang.IPersistentVector that)
(instance? java.util.RandomAccess that))
(and (== 2 (count that))
(.equals key (nth that 0))
(.equals val (nth that 1)))
(or (instance? clojure.lang.Sequential that)
(instance? java.util.List that))
(and (== 2 (count that))
(.equals key (first that))
(.equals val (second that)))
:else false))
(hashCode [this]
(-> (int 31)
(unchecked-add-int (Util/hash key))
(unchecked-multiply-int (int 31))
(unchecked-add-int (Util/hash val))))
(toString [this]
(pr-str this))
clojure.lang.IHashEq
(hasheq [this]
(compile-if (resolve 'clojure.core/hash-ordered-coll)
(hash-ordered-coll this)
(-> (int 31)
(unchecked-add-int (Util/hasheq key))
(unchecked-multiply-int (int 31))
(unchecked-add-int (Util/hasheq val)))))
clojure.lang.Indexed
(nth [this n]
(case n
0 key
1 val
(throw
(IndexOutOfBoundsException. "nth index out of bounds in AVLNode"))))
(nth [this n not-found]
(case n
0 key
1 val
not-found))
clojure.lang.Counted
(count [this]
2)
clojure.lang.IMeta
(meta [this]
nil)
clojure.lang.IObj
(withMeta [this m]
(with-meta [key val] m))
clojure.lang.IPersistentCollection
(cons [this x]
[key val x])
(empty [this]
[])
(equiv [this that]
(cond
(or (instance? clojure.lang.IPersistentVector that)
(instance? java.util.RandomAccess that))
(and (== 2 (count that))
(= key (nth that 0))
(= val (nth that 1)))
(or (instance? clojure.lang.Sequential that)
(instance? java.util.List that))
(and (== 2 (count that))
(= key (first that))
(= val (second that)))
:else false))
clojure.lang.IPersistentStack
(peek [this]
val)
(pop [this]
[key])
clojure.lang.IPersistentVector
(assocN [this i x]
(case i
0 [x val]
1 [key x]
(throw
(IndexOutOfBoundsException. "assocN index out of bounds in AVLNode"))))
(length [this]
2)
clojure.lang.Reversible
(rseq [this]
(list val key))
clojure.lang.Associative
(assoc [this k v]
(if (Util/isInteger k)
(.assocN this k v)
(throw (IllegalArgumentException. "key must be integer"))))
(containsKey [this k]
(if (Util/isInteger k)
(case (int k)
0 true
1 true
false)
false))
(entryAt [this k]
(if (Util/isInteger k)
(case (int k)
0 (MapEntry. 0 key)
1 (MapEntry. 1 val)
nil)))
clojure.lang.ILookup
(valAt [this k not-found]
(if (Util/isInteger k)
(case (int k)
0 key
1 val
not-found)
not-found))
(valAt [this k]
(.valAt this k nil))
clojure.lang.IFn
(invoke [this k]
(if (Util/isInteger k)
(case (int k)
0 key
1 val
(throw
(IndexOutOfBoundsException.
"invoke index out of bounds in AVLNode")))
(throw (IllegalArgumentException. "key must be integer"))))
(applyTo [this args]
(let [n (RT/boundedLength args 1)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.Seqable
(seq [this]
(list key val))
clojure.lang.Sequential
clojure.lang.IEditableCollection
(asTransient [this]
(transient [key val]))
clojure.lang.IMapEntry
(key [this]
key)
(val [this]
val)
java.util.Map$Entry
(getValue [this]
val)
(setValue [this x]
(throw-unsupported))
java.io.Serializable
java.lang.Comparable
(compareTo [this that]
(if (identical? this that)
0
(let [^clojure.lang.IPersistentVector v
(cast clojure.lang.IPersistentVector that)
vcnt (.count v)]
(cond
(< 2 vcnt) -1
(> 2 vcnt) 1
:else
(let [comp (Util/compare key (.nth v 0))]
(if (zero? comp)
(Util/compare val (.nth v 1))
comp))))))
java.lang.Iterable
(iterator [this]
(.iterator ^java.lang.Iterable (list key val)))
java.util.RandomAccess
java.util.List
(get [this i]
(.nth this i))
(indexOf [this x]
(condp = x
key 0
val 1
-1))
(lastIndexOf [this x]
(condp = x
val 1
key 0
-1))
(listIterator [this]
(.listIterator this 0))
(listIterator [this i]
(.listIterator (doto (java.util.ArrayList.)
(.add key)
(.add val))
i))
(subList [this a z]
(if (<= 0 a z 2)
(cond
(== a z) []
(and (== a 0) (== z 2)) this
:else (case a
0 [key]
1 [val]))
(throw
(IndexOutOfBoundsException. "subList index out of bounds in AVLNode"))))
java.util.Collection
(contains [this x]
(or (= key x) (= val x)))
(containsAll [this c]
(every? #(.contains this %) c))
(isEmpty [this]
false)
(toArray [this]
(into-array Object this))
(toArray [this arr]
(if (>= (count arr) 2)
(doto arr
(aset 0 key)
(aset 1 val))
(into-array Object this)))
(size [this]
2)
(add [this x] (throw-unsupported))
(^boolean remove [this x] (throw-unsupported))
(addAll [this c] (throw-unsupported))
(clear [this] (throw-unsupported))
(retainAll [this c] (throw-unsupported))
(removeAll [this c] (throw-unsupported))
(set [this i e] (throw-unsupported))
(remove [this ^int i] (throw-unsupported))
(add [this i e] (throw-unsupported)))
(defn ^:private ensure-editable
(^IAVLNode [^AtomicReference edit]
(let [owner (.get edit)]
(cond
(identical? owner (Thread/currentThread))
true
(nil? owner)
(throw (IllegalAccessError. "Transient used after persistent! call"))
:else
(throw (IllegalAccessError. "Transient used by non-owner thread")))))
(^IAVLNode [^AtomicReference edit ^AVLNode node]
(if (identical? edit (.-edit node))
node
(AVLNode. edit
(.getKey node) (.getVal node)
(.getLeft node)
(.getRight node)
(.getHeight node)
(.getRank node)))))
(defn ^:private height ^long [^IAVLNode node]
(if (nil? node)
0
(long (.getHeight node))))
(defn ^:private rotate-left ^IAVLNode [^IAVLNode node]
(let [l (.getLeft node)
r (.getRight node)
rl (.getLeft r)
rr (.getRight r)
lh (height l)
rlh (height rl)
rrh (height rr)
rnk (.getRank node)
rnkr (.getRank r)]
(AVLNode. nil
(.getKey r) (.getVal r)
(AVLNode. nil
(.getKey node) (.getVal node)
l
rl
(inc (max lh rlh))
rnk)
rr
(max (+ lh 2)
(+ rlh 2)
(inc rrh))
(inc (+ rnk rnkr)))))
(defn ^:private rotate-left! ^IAVLNode [edit ^IAVLNode node]
(let [node (ensure-editable edit node)
l (.getLeft node)
r (ensure-editable edit (.getRight node))
rl (.getLeft r)
rr (.getRight r)
lh (height l)
rlh (height rl)
rrh (height rr)
rnk (.getRank node)
rnkr (.getRank r)]
(.setLeft r node)
(.setHeight r (max (+ lh 2) (+ rlh 2) (inc rrh)))
(.setRank r (inc (+ rnk rnkr)))
(.setRight node rl)
(.setHeight node (inc (max lh rlh)))
r))
(defn ^:private rotate-right ^IAVLNode [^IAVLNode node]
(let [r (.getRight node)
l (.getLeft node)
lr (.getRight l)
ll (.getLeft l)
rh (height r)
lrh (height lr)
llh (height ll)
rnk (.getRank node)
rnkl (.getRank l)]
(AVLNode. nil
(.getKey l) (.getVal l)
ll
(AVLNode. nil
(.getKey node) (.getVal node)
lr
r
(inc (max rh lrh))
(dec (- rnk rnkl)))
(max (+ rh 2)
(+ lrh 2)
(inc llh))
rnkl)))
(defn ^:private rotate-right! ^IAVLNode [edit ^IAVLNode node]
(let [node (ensure-editable edit node)
r (.getRight node)
l (ensure-editable edit (.getLeft node))
lr (.getRight l)
ll (.getLeft l)
rh (height r)
lrh (height lr)
llh (height ll)
rnk (.getRank node)
rnkl (.getRank l)]
(.setRight l node)
(.setHeight l (max (+ rh 2) (+ lrh 2) (inc llh)))
(.setLeft node lr)
(.setHeight node (inc (max rh lrh)))
(.setRank node (dec (- rnk rnkl)))
l))
(defn ^:private lookup ^IAVLNode [^Comparator comp ^IAVLNode node k]
(if (nil? node)
nil
(let [c (.compare comp k (.getKey node))]
(cond
(zero? c) node
(neg? c) (recur comp (.getLeft node) k)
:else (recur comp (.getRight node) k)))))
(defn ^:private lookup-nearest
^IAVLNode [^Comparator comp ^IAVLNode node test k]
(let [below? (or (identical? < test) (identical? <= test))
equal? (or (identical? <= test) (identical? >= test))
back? (if below? neg? pos?)
backward (if below?
#(.getLeft ^IAVLNode %)
#(.getRight ^IAVLNode %))
forward (if below?
#(.getRight ^IAVLNode %)
#(.getLeft ^IAVLNode %))]
(loop [prev nil
node node]
(if (nil? node)
prev
(let [c (.compare comp k (.getKey node))]
(cond
(zero? c) (if equal?
node
(recur prev (backward node)))
(back? c) (recur prev (backward node))
:else (recur node (forward node))))))))
(defn ^:private select [^IAVLNode node ^long rank]
(if (nil? node)
nil
(let [node-rank (.getRank node)]
(cond
(== node-rank rank) node
(< node-rank rank) (recur (.getRight node) (dec (- rank node-rank)))
:else (recur (.getLeft node) rank)))))
(defn ^:private rank ^long [^Comparator comp ^IAVLNode node k]
(if (nil? node)
-1
(let [c (.compare comp k (.getKey node))]
(cond
(zero? c) (.getRank node)
(neg? c) (recur comp (.getLeft node) k)
:else (let [r (rank comp (.getRight node) k)]
(if (== -1 r)
-1
(inc (+ (.getRank node) r))))))))
(defn ^:private maybe-rebalance ^IAVLNode [^IAVLNode node]
(let [l (.getLeft node)
r (.getRight node)
lh (height l)
rh (height r)
b (- lh rh)]
(cond
;; right-heavy
(< b -1)
(let [rl (.getLeft r)
rr (.getRight r)
rlh (height rl)
rrh (height rr)]
(if (== (- rlh rrh) 1)
;; left-heavy
(let [new-right (rotate-right r)]
(rotate-left (AVLNode. nil
(.getKey node) (.getVal node)
(.getLeft node)
new-right
(inc (max lh (height new-right)))
(.getRank node))))
(rotate-left node)))
;; left-heavy
(> b 1)
(let [ll (.getLeft l)
lr (.getRight l)
llh (height ll)
lrh (height lr)]
;; right-heavy
(if (== (- lrh llh) 1)
(let [new-left (rotate-left l)]
(rotate-right (AVLNode. nil
(.getKey node) (.getVal node)
new-left
(.getRight node)
(inc (max rh (height new-left)))
(.getRank node))))
(rotate-right node)))
:else
node)))
(defn ^:private maybe-rebalance! ^IAVLNode [edit ^IAVLNode node]
(let [l (.getLeft node)
r (.getRight node)
lh (height l)
rh (height r)
b (- lh rh)]
(cond
;; right-heavy
(< b -1)
(let [node (ensure-editable edit node)
rl (.getLeft r)
rr (.getRight r)
rlh (height rl)
rrh (height rr)]
(if (== (- rlh rrh) 1)
;; left-heavy
(let [new-right (rotate-right! edit r)]
(.setRight node new-right)
(.setHeight node (inc (max lh (height new-right))))
(rotate-left! edit node))
(rotate-left! edit node)))
;; left-heavy
(> b 1)
(let [node (ensure-editable edit node)
ll (.getLeft l)
lr (.getRight l)
llh (height ll)
lrh (height lr)]
;; right-heavy
(if (== (- lrh llh) 1)
(let [new-left (rotate-left! edit l)]
(.setLeft node new-left)
(.setHeight node (inc (max rh (height new-left))))
(rotate-right! edit node))
(rotate-right! edit node)))
:else
node)))
(defn ^:private insert
^IAVLNode [^Comparator comp ^IAVLNode node k v ^Box found?]
(if (nil? node)
(AVLNode. nil k v nil nil 1 0)
(let [nk (.getKey node)
c (.compare comp k nk)]
(cond
(zero? c)
(do
(set! (.-val found?) true)
(AVLNode. nil
k v
(.getLeft node)
(.getRight node)
(.getHeight node)
(.getRank node)))
(neg? c)
(let [new-child (insert comp (.getLeft node) k v found?)]
(maybe-rebalance
(AVLNode. nil
nk (.getVal node)
new-child
(.getRight node)
(inc (max (.getHeight new-child)
(height (.getRight node))))
(if (.-val found?)
(.getRank node)
(unchecked-inc-int (.getRank node))))))
:else
(let [new-child (insert comp (.getRight node) k v found?)]
(maybe-rebalance
(AVLNode. nil
nk (.getVal node)
(.getLeft node)
new-child
(inc (max (.getHeight new-child)
(height (.getLeft node))))
(.getRank node))))))))
(defn ^:private insert!
^IAVLNode [edit ^Comparator comp ^IAVLNode node k v ^Box found?]
(if (nil? node)
(AVLNode. edit k v nil nil 1 0)
(let [node (ensure-editable edit node)
nk (.getKey node)
c (.compare comp k nk)]
(cond
(zero? c)
(do
(set! (.-val found?) true)
(.setKey node k)
(.setVal node v)
node)
(neg? c)
(let [new-child (insert! edit comp (.getLeft node) k v found?)]
(.setLeft node new-child)
(.setHeight node
(inc (max (.getHeight new-child)
(height (.getRight node)))))
(if-not (.-val found?)
(.setRank node (unchecked-inc-int (.getRank node))))
(maybe-rebalance! edit node))
:else
(let [new-child (insert! edit comp (.getRight node) k v found?)]
(.setRight node new-child)
(.setHeight node
(inc (max (.getHeight new-child)
(height (.getLeft node)))))
(maybe-rebalance! edit node))))))
(defn ^:private get-rightmost ^IAVLNode [^IAVLNode node]
(if-let [r (.getRight node)]
(recur r)
node))
(defn ^:private delete-rightmost ^IAVLNode [^IAVLNode node]
(if-let [r (.getRight node)]
(let [l (.getLeft node)
new-right (delete-rightmost r)]
(AVLNode. nil
(.getKey node) (.getVal node)
l
new-right
(inc (max (height l) (height new-right)))
(.getRank node)))
(.getLeft node)))
(defn ^:private delete-rightmost! ^IAVLNode [edit ^IAVLNode node]
(if-not (nil? node)
(let [node (ensure-editable edit node)
r ^IAVLNode (.getRight node)]
(cond
(nil? r)
(if-let [l (.getLeft node)]
(ensure-editable edit l))
(nil? (.getRight r))
(do
(.setRight node (.getLeft r))
(.setHeight node
(inc (max (height (.getLeft node))
(height (.getLeft r)))))
node)
:else
(let [new-right (delete-rightmost! edit r)]
(.setRight node new-right)
(.setHeight node
(inc (max (height (.getLeft node))
(height new-right))))
node)))))
(defn ^:private delete
^IAVLNode [^Comparator comp ^IAVLNode node k ^Box found?]
(if (nil? node)
nil
(let [nk (.getKey node)
c (.compare comp k nk)]
(cond
(zero? c)
(let [l (.getLeft node)
r (.getRight node)]
(set! (.-val found?) true)
(if (and l r)
(let [p (get-rightmost l)
l' (delete-rightmost l)]
(AVLNode. nil
(.getKey p) (.getVal p)
l'
r
(inc (max (height l') (height r)))
(unchecked-dec-int (.getRank node))))
(or l r)))
(neg? c)
(let [new-child (delete comp (.getLeft node) k found?)]
(if (identical? new-child (.getLeft node))
node
(maybe-rebalance
(AVLNode. nil
nk (.getVal node)
new-child
(.getRight node)
(inc (max (height new-child)
(height (.getRight node))))
(if (.-val found?)
(unchecked-dec-int (.getRank node))
(.getRank node))))))
:else
(let [new-child (delete comp (.getRight node) k found?)]
(if (identical? new-child (.getRight node))
node
(maybe-rebalance
(AVLNode. nil
nk (.getVal node)
(.getLeft node)
new-child
(inc (max (height new-child)
(height (.getLeft node))))
(.getRank node)))))))))
(defn ^:private delete!
^IAVLNode [edit ^Comparator comp ^IAVLNode node k ^Box found?]
(if (nil? node)
nil
(let [nk (.getKey node)
c (.compare comp k nk)]
(cond
(zero? c)
(let [l (.getLeft node)
r (.getRight node)]
(set! (.-val found?) true)
(cond
(and l r)
(let [node (ensure-editable edit node)
p (get-rightmost l)
l' (delete-rightmost! edit l)]
(.setKey node (.getKey p))
(.setVal node (.getVal p))
(.setLeft node l')
(.setHeight node (inc (max (height l') (height r))))
(.setRank node (unchecked-dec-int (.getRank node)))
node)
l l
r r
:else nil))
(neg? c)
(let [new-child (delete! edit comp (.getLeft node) k found?)]
(if (identical? new-child (.getLeft node))
node
(let [node (ensure-editable edit node)]
(.setLeft node new-child)
(.setHeight node
(inc (max (height new-child)
(height (.getRight node)))))
(if (.-val found?)
(.setRank node (unchecked-dec-int (.getRank node))))
(maybe-rebalance! edit node))))
:else
(let [new-child (delete! edit comp (.getRight node) k found?)]
(if (identical? new-child (.getRight node))
node
(let [node (ensure-editable edit node)]
(.setRight node new-child)
(.setHeight node
(inc (max (height new-child)
(height (.getLeft node)))))
(maybe-rebalance! edit node))))))))
(defn ^:private join
[^Comparator comp ^long left-count ^IAVLNode left ^IAVLNode right]
(cond
(nil? left) right
(nil? right) left
:else
(let [lh (.getHeight left)
rh (.getHeight right)]
(cond
(== lh rh)
(let [left-min (get-rightmost left)
new-left (delete comp left (.getKey left-min) (Box. false))]
(AVLNode. nil
(.getKey left-min) (.getVal left-min)
new-left
right
(unchecked-inc-int rh)
(unchecked-dec-int left-count)))
(< lh rh)
(letfn [(step [^IAVLNode current ^long lvl]
(cond
(zero? lvl)
(join comp left-count left current)
(nil? (.getLeft current))
(AVLNode. nil
(.getKey current) (.getVal current)
left
(.getRight current)
2
left-count)
:else
(let [new-child (step (.getLeft current) (dec lvl))
current-r (.getRight current)]
(maybe-rebalance
(AVLNode. nil
(.getKey current) (.getVal current)
new-child
current-r
(inc (max (.getHeight ^IAVLNode new-child)
(height current-r)
#_
(if current-r
(.getHeight current-r)
0)))
(+ left-count (.getRank current)))))))]
(step right (- rh lh)))
:else
(letfn [(step [^IAVLNode current ^long cnt ^long lvl]
(cond
(zero? lvl)
(join comp cnt current right)
(nil? (.getRight current))
(AVLNode. nil
(.getKey current) (.getVal current)
(.getLeft current)
right
2
(.getRank current))
:else
(let [new-child (step (.getRight current)
(dec (- cnt (.getRank current)))
(dec lvl))
current-l (.getLeft current)]
(maybe-rebalance
(AVLNode. nil
(.getKey current) (.getVal current)
current-l
new-child
(inc (max (.getHeight ^IAVLNode new-child)
(height current-l)
#_
(if current-l
(.getHeight current-l)
0)))
(.getRank current))))))]
(step left left-count (- lh rh)))))))
(defn ^:private split [^Comparator comp ^IAVLNode node k]
(letfn [(step [^IAVLNode node]
(if (nil? node)
[nil nil nil]
(let [c (.compare comp k (.getKey node))]
(cond
(zero? c)
[(.getLeft node)
(MapEntry. (.getKey node) (.getVal node))
(.getRight node)]
(neg? c)
(let [[l e r] (step (.getLeft node))
r' (insert comp
(.getRight node)
(.getKey node)
(.getVal node)
(Box. false))]
[l
e
(cond
e (join comp
(- (.getRank node)
(inc (rank comp
(.getLeft node)
(.key ^MapEntry e))))
r
r')
r (join comp
(- (.getRank node)
(inc (rank comp
(.getLeft node)
(.getKey (get-rightmost r)))))
r
r')
:else (join comp 0 r r'))
#_
(join comp
(- (.getRank node)
(cond
e
(inc (rank comp
(.getLeft node)
(.key ^MapEntry e)))
r
(inc (rank comp
(.getLeft node)
(.getKey (get-rightmost r))))
:else
(.getRank node)))
r
(insert comp
(.getRight node)
(.getKey node)
(.getVal node)
(Box. false)))])
:else
(let [[l e r] (step (.getRight node))]
[(join comp
(unchecked-inc-int (.getRank node))
(insert comp
(.getLeft node)
(.getKey node)
(.getVal node)
(Box. false))
l)
e
r])))))]
(step node)))
(defn ^:private range ^IAVLNode [^Comparator comp ^IAVLNode node low high]
(let [[_ ^MapEntry low-e r] (split comp node low)
[l ^MapEntry high-e _] (split comp r high)]
(cond-> l
low-e (as-> node
(insert comp node
(.key low-e) (.val low-e)
(Box. false)))
high-e (as-> node
(insert comp node
(.key high-e) (.val high-e)
(Box. false))))))
(defn ^:private seq-push [^IAVLNode node stack ascending?]
(loop [node node stack stack]
(if (nil? node)
stack
(recur (if ascending? (.getLeft node) (.getRight node))
(conj stack node)))))
(defn ^:private avl-map-kv-reduce [^IAVLNode node f init]
(let [init (if (nil? (.getLeft node))
init
(avl-map-kv-reduce (.getLeft node) f init))]
(if (reduced? init)
init
(let [init (f init (.getKey node) (.getVal node))]
(if (reduced? init)
init
(if (nil? (.getRight node))
init
(recur (.getRight node) f init)))))))
(deftype AVLMapSeq [^IPersistentMap _meta
^IPersistentStack stack
^boolean ascending?
^int cnt
^:unsynchronized-mutable ^int _hash
^:unsynchronized-mutable ^int _hasheq]
:no-print true
Object
(toString [this]
(RT/printString this))
(hashCode [this]
(caching-hash this hash-seq _hash))
clojure.lang.IHashEq
(hasheq [this]
(caching-hash this hasheq-seq _hasheq))
clojure.lang.Seqable
(seq [this]
this)
clojure.lang.Sequential
clojure.lang.ISeq
(first [this]
(peek stack)
#_
(let [node ^IAVLNode (peek stack)]
(MapEntry. (.getKey node) (.getVal node))))
(more [this]
(let [node ^IAVLNode (first stack)
next-stack (seq-push (if ascending? (.getRight node) (.getLeft node))
(next stack)
ascending?)]
(if (nil? next-stack)
()
(AVLMapSeq. nil next-stack ascending? (unchecked-dec-int cnt) -1 -1))))
(next [this]
(.seq (.more this)))
clojure.lang.Counted
(count [this]
(if (neg? cnt)
(unchecked-inc-int (count (next this)))
cnt))
clojure.lang.IPersistentCollection
(cons [this x]
(cons x this))
(equiv [this that]
(equiv-sequential this that))
(empty [this]
(with-meta () _meta))
clojure.lang.IMeta
(meta [this]
_meta)
clojure.lang.IObj
(withMeta [this meta]
(AVLMapSeq. meta stack ascending? cnt _hash _hasheq))
java.io.Serializable
java.util.List
(toArray [this]
(RT/seqToArray (seq this)))
(toArray [this arr]
(RT/seqToPassedArray (seq this) arr))
(containsAll [this c]
(every? #(.contains this %) (iterator-seq (.iterator c))))
(size [this]
(count this))
(isEmpty [this]
(zero? cnt))
(contains [this x]
(or (some #(Util/equiv % x) this) false))
(iterator [this]
(SeqIterator. this))
(subList [this from to]
(.subList (Collections/unmodifiableList (ArrayList. this)) from to))
(indexOf [this x]
(loop [i (int 0) s (seq this)]
(if s
(if (Util/equiv (first s) x)
i
(recur (unchecked-inc-int i) (next s)))
(int -1))))
(lastIndexOf [this x]
(.lastIndexOf (ArrayList. this) x))
(listIterator [this]
(.listIterator (Collections/unmodifiableList (ArrayList. this))))
(listIterator [this i]
(.listIterator (Collections/unmodifiableList (ArrayList. this)) i))
(get [this i]
(RT/nth this i))
(add [this x] (throw-unsupported))
(^boolean remove [this x] (throw-unsupported))
(addAll [this c] (throw-unsupported))
(clear [this] (throw-unsupported))
(retainAll [this c] (throw-unsupported))
(removeAll [this c] (throw-unsupported))
(set [this i e] (throw-unsupported))
(remove [this ^int i] (throw-unsupported))
(add [this i e] (throw-unsupported)))
(defn ^:private create-seq [node ascending? cnt]
(AVLMapSeq. nil (seq-push node nil ascending?) ascending? cnt -1 -1))
(declare ->AVLTransientMap)
(deftype AVLMap [^Comparator comp
^IAVLNode tree
^int cnt
^IPersistentMap _meta
^:unsynchronized-mutable ^int _hash
^:unsynchronized-mutable ^int _hasheq]
Object
(toString [this]
(RT/printString this))
(hashCode [this]
(caching-hash this hash-imap _hash))
(equals [this that]
(APersistentMap/mapEquals this that))
IAVLTree
(getTree [this]
tree)
INavigableTree
(nearest [this test k]
(if-let [node (lookup-nearest comp tree test k)]
(MapEntry. (.getKey node) (.getVal node))))
clojure.lang.IHashEq
(hasheq [this]
(caching-hash this hasheq-imap _hasheq))
clojure.lang.IMeta
(meta [this]
_meta)
clojure.lang.IObj
(withMeta [this meta]
(AVLMap. comp tree cnt meta _hash _hasheq))
clojure.lang.Counted
(count [this]
cnt)
clojure.lang.Indexed
(nth [this i]
(if-let [n (select tree i)]
(MapEntry. (.getKey ^IAVLNode n) (.getVal ^IAVLNode n))
(throw
(IndexOutOfBoundsException. "nth index out of bounds in AVL tree"))))
(nth [this i not-found]
(if-let [n (select tree i)]
(MapEntry. (.getKey ^IAVLNode n) (.getVal ^IAVLNode n))
not-found))
clojure.lang.IPersistentCollection
(cons [this entry]
(if (vector? entry)
(assoc this (nth entry 0) (nth entry 1))
(reduce conj this entry)))
(empty [this]
(AVLMap. comp nil 0 _meta empty-map-hashcode empty-map-hasheq))
(equiv [this that]
(equiv-map this that))
clojure.lang.IFn
(invoke [this k]
(.valAt this k))
(invoke [this k not-found]
(.valAt this k not-found))
(applyTo [this args]
(let [n (RT/boundedLength args 2)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (.invoke this (first args) (second args))
3 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.Seqable
(seq [this]
(if (pos? cnt)
(create-seq tree true cnt)))
clojure.lang.Reversible
(rseq [this]
(if (pos? cnt)
(create-seq tree false cnt)))
clojure.lang.ILookup
(valAt [this k]
(.valAt this k nil))
(valAt [this k not-found]
(let [n ^IAVLNode (lookup comp tree k)]
(if-not (nil? n)
(.getVal n)
not-found)))
clojure.lang.Associative
(assoc [this k v]
(let [found? (Box. false)
new-tree (insert comp tree k v found?)]
(AVLMap. comp
new-tree
(if (.-val found?) cnt (unchecked-inc-int cnt))
_meta -1 -1)))
(containsKey [this k]
(not (nil? (.entryAt this k))))
(entryAt [this k]
(if-let [node (lookup comp tree k)]
(MapEntry. (.getKey node) (.getVal node))))
clojure.lang.MapEquivalence
clojure.lang.IPersistentMap
(without [this k]
(let [found? (Box. false)
new-tree (delete comp tree k found?)]
(if (.-val found?)
(AVLMap. comp
new-tree
(unchecked-dec-int cnt)
_meta -1 -1)
this)))
(assocEx [this k v]
(let [found? (Box. false)
new-tree (insert comp tree k v found?)]
(if (.-val found?)
(throw (ex-info "key already present" {}))
(AVLMap. comp
new-tree
(unchecked-inc-int cnt)
_meta -1 -1))))
clojure.lang.Sorted
(seq [this ascending?]
(if (pos? cnt)
(create-seq tree ascending? cnt)))
(seqFrom [this k ascending?]
(if (pos? cnt)
(loop [stack nil t tree]
(if-not (nil? t)
(let [c (.compare comp k (.getKey t))]
(cond
(zero? c) (AVLMapSeq. nil (conj stack t) ascending? -1 -1 -1)
ascending? (if (neg? c)
(recur (conj stack t) (.getLeft t))
(recur stack (.getRight t)))
:else (if (pos? c)
(recur (conj stack t) (.getRight t))
(recur stack (.getLeft t)))))
(if-not (nil? stack)
(AVLMapSeq. nil stack ascending? -1 -1 -1))))))
(entryKey [this entry]
(key entry))
(comparator [this]
comp)
clojure.lang.IEditableCollection
(asTransient [this]
(->AVLTransientMap
(AtomicReference. (Thread/currentThread)) comp tree cnt))
clojure.core.protocols/IKVReduce
(kv-reduce [this f init]
(if (nil? tree)
init
(let [init (avl-map-kv-reduce tree f init)]
(if (reduced? init)
@init
init))))
java.io.Serializable
Iterable
(iterator [this]
(SeqIterator. (seq this)))
java.util.Map
(get [this k]
(.valAt this k))
(clear [this]
(throw-unsupported))
(containsValue [this v]
(.. this values (contains v)))
(entrySet [this]
(set (seq this)))
(put [this k v]
(throw-unsupported))
(putAll [this m]
(throw-unsupported))
(remove [this k]
(throw-unsupported))
(size [this]
cnt)
(values [this]
(vals this)))
(deftype AVLTransientMap [^AtomicReference edit
^Comparator comp
^:unsynchronized-mutable ^IAVLNode tree
^:unsynchronized-mutable ^int cnt]
clojure.lang.Counted
(count [this]
cnt)
clojure.lang.ILookup
(valAt [this k]
(.valAt this k nil))
(valAt [this k not-found]
(let [n ^IAVLNode (lookup comp tree k)]
(if-not (nil? n)
(.getVal n)
not-found)))
clojure.lang.IFn
(invoke [this k]
(.valAt this k))
(invoke [this k not-found]
(.valAt this k not-found))
(applyTo [this args]
(let [n (RT/boundedLength args 2)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (.invoke this (first args) (second args))
3 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.ITransientCollection
(conj [this entry]
(ensure-editable edit)
(if (vector? entry)
(assoc! this (nth entry 0) (nth entry 1))
(reduce conj! this entry)))
(persistent [this]
(ensure-editable edit)
(.set edit nil)
(AVLMap. comp tree cnt nil -1 -1))
clojure.lang.ITransientAssociative
(assoc [this k v]
(ensure-editable edit)
(let [found? (Box. false)
new-tree (insert! edit comp tree k v found?)]
(set! tree new-tree)
(if-not (.-val found?)
(set! cnt (unchecked-inc-int cnt)))
this))
clojure.lang.ITransientMap
(without [this k]
(ensure-editable edit)
(let [found? (Box. false)
new-tree (delete! edit comp tree k found?)]
(when (.-val found?)
(set! tree new-tree)
(set! cnt (unchecked-dec-int cnt)))
this)))
(declare ->AVLTransientSet)
(deftype AVLSet [^IPersistentMap _meta
^AVLMap avl-map
^:unsynchronized-mutable ^int _hash
^:unsynchronized-mutable ^int _hasheq]
Object
(toString [this]
(RT/printString this))
(hashCode [this]
(caching-hash this hash-iset _hash))
(equals [this that]
(APersistentSet/setEquals this that))
IAVLTree
(getTree [this]
(.getTree avl-map))
INavigableTree
(nearest [this test k]
(if-let [node (lookup-nearest (.comparator avl-map)
(.getTree avl-map)
test
k)]
(.getKey node)))
clojure.lang.IHashEq
(hasheq [this]
(caching-hash this hasheq-iset _hasheq))
clojure.lang.IMeta
(meta [this]
_meta)
clojure.lang.IObj
(withMeta [this meta]
(AVLSet. meta avl-map _hash _hasheq))
clojure.lang.Counted
(count [this]
(count avl-map))
clojure.lang.Indexed
(nth [this i]
(if-let [n (select (.-tree avl-map) i)]
(.getVal ^IAVLNode n)
(throw
(IndexOutOfBoundsException. "nth index out of bounds in AVL tree"))))
(nth [this i not-found]
(if-let [n (select (.-tree avl-map) i)]
(.getVal ^IAVLNode n)
not-found))
clojure.lang.IPersistentCollection
(cons [this x]
(AVLSet. _meta (assoc avl-map x x) -1 -1))
(empty [this]
(AVLSet. _meta (empty avl-map) empty-set-hashcode empty-set-hasheq))
(equiv [this that]
(and
(set? that)
(== (count this) (count that))
(every? #(contains? this %) that)))
clojure.lang.Seqable
(seq [this]
(keys avl-map))
clojure.lang.Sorted
(seq [this ascending?]
(RT/keys (.seq avl-map ascending?)))
(seqFrom [this k ascending?]
(RT/keys (.seqFrom avl-map k ascending?)))
(entryKey [this entry]
entry)
(comparator [this]
(.comparator avl-map))
clojure.lang.Reversible
(rseq [this]
(map key (rseq avl-map)))
clojure.lang.ILookup
(valAt [this v]
(.valAt this v nil))
(valAt [this v not-found]
(let [n (.entryAt avl-map v)]
(if-not (nil? n)
(.getKey n)
not-found)))
clojure.lang.IPersistentSet
(disjoin [this v]
(AVLSet. _meta (dissoc avl-map v) -1 -1))
(contains [this k]
(contains? avl-map k))
(get [this k]
(.valAt this k nil))
clojure.lang.IFn
(invoke [this k]
(.valAt this k))
(applyTo [this args]
(let [n (RT/boundedLength args 1)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.IEditableCollection
(asTransient [this]
(->AVLTransientSet (.asTransient avl-map)))
java.io.Serializable
java.util.Set
(add [this o] (throw-unsupported))
(remove [this o] (throw-unsupported))
(addAll [this c] (throw-unsupported))
(clear [this] (throw-unsupported))
(retainAll [this c] (throw-unsupported))
(removeAll [this c] (throw-unsupported))
(containsAll [this c]
(every? #(.contains this %) (iterator-seq (.iterator c))))
(size [this]
(count this))
(isEmpty [this]
(zero? (count this)))
(iterator [this]
(SeqIterator. (seq this)))
(toArray [this]
(RT/seqToArray (seq this)))
(toArray [this a]
(RT/seqToPassedArray (seq this) a)))
(deftype AVLTransientSet
[^:unsynchronized-mutable ^AVLTransientMap transient-avl-map]
clojure.lang.ITransientCollection
(conj [this k]
(set! transient-avl-map (.assoc transient-avl-map k k))
this)
(persistent [this]
(AVLSet. nil (.persistent transient-avl-map) -1 -1))
clojure.lang.ITransientSet
(disjoin [this k]
(set! transient-avl-map (.without transient-avl-map k))
this)
(contains [this k]
(not (identical? this (.valAt transient-avl-map k this))))
(get [this k]
(.valAt transient-avl-map k))
clojure.lang.IFn
(invoke [this k]
(.valAt transient-avl-map k))
(invoke [this k not-found]
(.valAt transient-avl-map k not-found))
(applyTo [this args]
(let [n (RT/boundedLength args 2)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (.invoke this (first args) (second args))
3 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.Counted
(count [this]
(.count transient-avl-map)))
(def ^:private empty-map
(AVLMap. RT/DEFAULT_COMPARATOR nil 0 nil
empty-map-hashcode empty-map-hasheq))
(def ^:private empty-set
(AVLSet. nil empty-map empty-set-hashcode empty-set-hasheq))
(doseq [v [#'->AVLMapSeq
#'->AVLNode
#'->AVLMap
#'->AVLSet
#'->AVLTransientMap
#'->AVLTransientSet]]
(alter-meta! v assoc :private true))
(defn sorted-map
"keyval => key val
Returns a new AVL map with supplied mappings."
{:added "0.0.1"}
[& keyvals]
(loop [in (seq keyvals) out (transient empty-map)]
(if in
(if-let [nin (next in)]
(recur (next nin) (assoc! out (first in) (first nin)))
(throw (IllegalArgumentException.
(format
"sorted-map: no value supplied for key: %s"
(first in)))))
(persistent! out))))
(defn sorted-map-by
"keyval => key val
Returns a new sorted map with supplied mappings, using the supplied
comparator."
{:added "0.0.1"}
[^Comparator comparator & keyvals]
(loop [in (seq keyvals)
out (AVLTransientMap.
(AtomicReference. (Thread/currentThread)) comparator nil 0)]
(if in
(if-let [nin (next in)]
(recur (next nin) (assoc! out (first in) (first nin)))
(throw (IllegalArgumentException.
(format
"sorted-map-by: no value supplied for key: %s"
(first in)))))
(persistent! out))))
(defn sorted-set
"Returns a new sorted set with supplied keys."
{:added "0.0.1"}
[& keys]
(persistent! (reduce conj! (transient empty-set) keys)))
(defn sorted-set-by
"Returns a new sorted set with supplied keys, using the supplied comparator."
{:added "0.0.1"}
[^Comparator comparator & keys]
(persistent!
(reduce conj!
(AVLTransientSet. (transient (sorted-map-by comparator)))
keys)))
(defn rank-of
"Returns the rank of x in coll or -1 if not present."
{:added "0.0.6"}
^long [coll x]
(rank (.comparator ^clojure.lang.Sorted coll) (.getTree ^IAVLTree coll) x))
(defn nearest
"(alpha)
Equivalent to, but more efficient than, (first (subseq* coll test x)),
where subseq* is clojure.core/subseq for test in #{>, >=} and
clojure.core/rsubseq for test in #{<, <=}."
{:added "0.0.12"}
[coll test x]
(.nearest ^INavigableTree coll test x))
(defn split-key
"(alpha)
Returns [left e? right], where left and right are collections of
the same type as coll and containing, respectively, the keys below
and above k in the ordering determined by coll's comparator, while
e? is the entry at key k for maps, the stored copy of the key k for
sets, nil if coll does not contain k."
{:added "0.0.12"}
[k coll]
(let [comp (.comparator ^clojure.lang.Sorted coll)
[left e? right] (split comp (.getTree ^IAVLTree coll) k)
keyfn (if (map? coll) key identity)
wrap (if (map? coll)
(fn wrap-map [tree cnt]
(AVLMap. comp tree cnt nil -1 -1))
(fn wrap-set [tree cnt]
(AVLSet. nil (AVLMap. comp tree cnt nil -1 -1) -1 -1)))]
[(wrap left
(if (or e? right)
(rank-of coll (keyfn (nearest coll >= k)))
(count coll)))
(if (and e? (set? coll))
(.getKey ^MapEntry e?)
e?)
(wrap right
(if right
(- (count coll) (rank-of coll (keyfn (nearest coll > k))))
0))]))
(defn split-at
"(alpha)
Equivalent to, but more efficient than,
[(into (empty coll) (take n coll))
(into (empty coll) (drop n coll))]."
{:added "0.0.12"}
[^long n coll]
(if (>= n (count coll))
[coll (empty coll)]
(let [k (nth coll n)
k (if (map? coll) (key k) k)
[l e r] (split-key k coll)]
[l (conj r e)])))
(defn subrange
"(alpha)
Returns an AVL collection comprising the entries of coll between
start and end (in the sense determined by coll's comparator) in
logarithmic time. Whether the endpoints are themselves included in
the returned collection depends on the provided tests; start-test
must be either > or >=, end-test must be either < or <=.
When passed a single test and limit, subrange infers the other end
of the range from the test: > / >= mean to include items up to the
end of coll, < / <= mean to include items taken from the beginning
of coll.
(subrange >= start <= end) is equivalent to, but more efficient
than, (into (empty coll) (subseq coll >= start <= end)."
{:added "0.0.12"}
([coll test limit]
(cond
(zero? (count coll))
coll
(#{> >=} test)
(let [n (select (.getTree ^IAVLTree coll)
(dec (count coll)))]
(subrange coll
test limit
<= (.getKey ^IAVLNode n)))
:else
(let [n (select (.getTree ^IAVLTree coll) 0)]
(subrange coll
>= (.getKey ^IAVLNode n)
test limit))))
([coll start-test start end-test end]
(if (zero? (count coll))
coll
(let [comp (.comparator ^clojure.lang.Sorted coll)]
(if (pos? (.compare comp start end))
(throw
(IndexOutOfBoundsException. "start greater than end in subrange"))
(let [keyfn (if (map? coll) key identity)
l (nearest coll start-test start)
h (nearest coll end-test end)]
(if (and l h)
(let [tree (range comp (.getTree ^IAVLTree coll)
(keyfn l)
(keyfn h))
cnt (inc (- (rank-of coll (keyfn h))
(rank-of coll (keyfn l))))
m (AVLMap. comp tree cnt nil -1 -1)]
(if (map? coll)
m
(AVLSet. nil m -1 -1)))
(empty coll))))))))
| null | https://raw.githubusercontent.com/witheve/eve-experiments/8a1cdb353b3e728bc768b315e5b9a9f9dc785ae1/server/src/server/avl.clj | clojure | a la clojure.lang.APersistentSet
right-heavy
left-heavy
left-heavy
right-heavy
right-heavy
left-heavy
left-heavy
right-heavy
start-test | (ns server.avl
"An implementation of persistent sorted maps and sets based on AVL
trees which can be used as drop-in replacements for Clojure's
built-in sorted maps and sets based on red-black trees. Apart from
the standard sorted collection API, the provided map and set types
support the transients API and several additional logarithmic time
operations: rank queries via clojure.core/nth (select element by
rank) and clojure.data.avl/rank-of (discover rank of element),
\"nearest key\" lookups via clojure.data.avl/nearest, splits by key
and index via clojure.data.avl/split-key and
clojure.data.avl/split-at, respectively, and subsets/submaps using
clojure.data.avl/subrange."
{:author "Michał Marczyk"}
(:refer-clojure :exclude [sorted-map sorted-map-by sorted-set sorted-set-by
range split-at])
(:import (clojure.lang RT Util APersistentMap APersistentSet
IPersistentMap IPersistentSet IPersistentStack
Box MapEntry SeqIterator)
(java.util Comparator Collections ArrayList)
(java.util.concurrent.atomic AtomicReference)))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(defn ^:private throw-unsupported []
(throw (UnsupportedOperationException.)))
(defmacro ^:private caching-hash [coll hash-fn hash-key]
`(let [h# ~hash-key]
(if-not (== h# (int -1))
h#
(let [h# (~hash-fn ~coll)]
(set! ~hash-key (int h#))
h#))))
(defmacro ^:private compile-if [test then else]
(if (eval test)
then
else))
(def ^:private ^:const empty-set-hashcode (.hashCode #{}))
(def ^:private ^:const empty-set-hasheq (hash #{}))
(def ^:private ^:const empty-map-hashcode (.hashCode {}))
(def ^:private ^:const empty-map-hasheq (hash {}))
(defn ^:private hash-imap
[^IPersistentMap m]
(APersistentMap/mapHash m))
(defn ^:private hasheq-imap
[^IPersistentMap m]
(compile-if (resolve 'clojure.core/hash-unordered-coll)
(hash-unordered-coll m)
(APersistentMap/mapHasheq m)))
(defn ^:private hash-iset [^IPersistentSet s]
(loop [h (int 0) s (seq s)]
(if s
(let [e (first s)]
(recur (unchecked-add-int h (if (nil? e) 0 (.hashCode ^Object e)))
(next s)))
h)))
(defn ^:private hasheq-iset [^IPersistentSet s]
(compile-if (resolve 'clojure.core/hash-unordered-coll)
(hash-unordered-coll s)
(loop [h (int 0) s (seq s)]
(if s
(recur (unchecked-add-int h (Util/hasheq (first s)))
(next s))
h))))
(defn ^:private hash-seq
[s]
(loop [h (int 1) s (seq s)]
(if s
(recur (unchecked-add-int (unchecked-multiply-int (int 31) h)
(if (nil? (first s))
(int 0)
(.hashCode ^Object (first s))))
(next s))
h)))
(defn ^:private hasheq-seq
[s]
(compile-if (resolve 'clojure.core/hash-ordered-coll)
(hash-ordered-coll s)
(loop [h (int 1) s (seq s)]
(if s
(recur (unchecked-add-int (unchecked-multiply-int (int 31) h)
(Util/hasheq (first s)))
(next s))
h))))
(defn ^:private equiv-sequential
"Assumes x is sequential. Returns true if x equals y, otherwise
returns false."
[x y]
(boolean
(when (sequential? y)
(loop [xs (seq x) ys (seq y)]
(cond (nil? xs) (nil? ys)
(nil? ys) false
(= (first xs) (first ys)) (recur (next xs) (next ys))
:else false)))))
(def ^:private never-equiv (Object.))
(defn ^:private equiv-map
"Assumes x is a map. Returns true if y equals x, otherwise returns
false."
[^clojure.lang.IPersistentMap x y]
(if-not (instance? java.util.Map y)
false
(if (and (instance? clojure.lang.IPersistentMap y)
(not (instance? clojure.lang.MapEquivalence y)))
false
(let [m ^java.util.Map y]
(if-not (== (.size ^java.util.Map x) (.size m))
false
(reduce-kv (fn [t k v]
(if-not (.containsKey m k)
(reduced false)
(if-not (Util/equiv v (.get m k))
(reduced false)
t)))
true
x))))))
(gen-interface
:name clojure.data.avl.IAVLNode
:methods
[[getKey [] Object]
[setKey [Object] clojure.data.avl.IAVLNode]
[getVal [] Object]
[setVal [Object] clojure.data.avl.IAVLNode]
[getLeft [] clojure.data.avl.IAVLNode]
[setLeft [clojure.data.avl.IAVLNode] clojure.data.avl.IAVLNode]
[getRight [] clojure.data.avl.IAVLNode]
[setRight [clojure.data.avl.IAVLNode] clojure.data.avl.IAVLNode]
[getHeight [] int]
[setHeight [int] clojure.data.avl.IAVLNode]
[getRank [] int]
[setRank [int] clojure.data.avl.IAVLNode]])
(gen-interface
:name clojure.data.avl.IAVLTree
:methods [[getTree [] clojure.data.avl.IAVLNode]])
(import (clojure.data.avl IAVLNode IAVLTree))
(definterface INavigableTree
(nearest [test k]))
(deftype AVLNode [^AtomicReference edit
^:unsynchronized-mutable key
^:unsynchronized-mutable val
^:unsynchronized-mutable ^IAVLNode left
^:unsynchronized-mutable ^IAVLNode right
^:unsynchronized-mutable ^int height
^:unsynchronized-mutable ^int rank]
IAVLNode
(getKey [this]
key)
(setKey [this k]
(set! key k)
this)
(getVal [this]
val)
(setVal [this v]
(set! val v)
this)
(getLeft [this]
left)
(setLeft [this l]
(set! left l)
this)
(getRight [this]
right)
(setRight [this r]
(set! right r)
this)
(getHeight [this]
height)
(setHeight [this h]
(set! height h)
this)
(getRank [this]
rank)
(setRank [this r]
(set! rank r)
this)
Object
(equals [this that]
(cond
(identical? this that) true
(or (instance? clojure.lang.IPersistentVector that)
(instance? java.util.RandomAccess that))
(and (== 2 (count that))
(.equals key (nth that 0))
(.equals val (nth that 1)))
(or (instance? clojure.lang.Sequential that)
(instance? java.util.List that))
(and (== 2 (count that))
(.equals key (first that))
(.equals val (second that)))
:else false))
(hashCode [this]
(-> (int 31)
(unchecked-add-int (Util/hash key))
(unchecked-multiply-int (int 31))
(unchecked-add-int (Util/hash val))))
(toString [this]
(pr-str this))
clojure.lang.IHashEq
(hasheq [this]
(compile-if (resolve 'clojure.core/hash-ordered-coll)
(hash-ordered-coll this)
(-> (int 31)
(unchecked-add-int (Util/hasheq key))
(unchecked-multiply-int (int 31))
(unchecked-add-int (Util/hasheq val)))))
clojure.lang.Indexed
(nth [this n]
(case n
0 key
1 val
(throw
(IndexOutOfBoundsException. "nth index out of bounds in AVLNode"))))
(nth [this n not-found]
(case n
0 key
1 val
not-found))
clojure.lang.Counted
(count [this]
2)
clojure.lang.IMeta
(meta [this]
nil)
clojure.lang.IObj
(withMeta [this m]
(with-meta [key val] m))
clojure.lang.IPersistentCollection
(cons [this x]
[key val x])
(empty [this]
[])
(equiv [this that]
(cond
(or (instance? clojure.lang.IPersistentVector that)
(instance? java.util.RandomAccess that))
(and (== 2 (count that))
(= key (nth that 0))
(= val (nth that 1)))
(or (instance? clojure.lang.Sequential that)
(instance? java.util.List that))
(and (== 2 (count that))
(= key (first that))
(= val (second that)))
:else false))
clojure.lang.IPersistentStack
(peek [this]
val)
(pop [this]
[key])
clojure.lang.IPersistentVector
(assocN [this i x]
(case i
0 [x val]
1 [key x]
(throw
(IndexOutOfBoundsException. "assocN index out of bounds in AVLNode"))))
(length [this]
2)
clojure.lang.Reversible
(rseq [this]
(list val key))
clojure.lang.Associative
(assoc [this k v]
(if (Util/isInteger k)
(.assocN this k v)
(throw (IllegalArgumentException. "key must be integer"))))
(containsKey [this k]
(if (Util/isInteger k)
(case (int k)
0 true
1 true
false)
false))
(entryAt [this k]
(if (Util/isInteger k)
(case (int k)
0 (MapEntry. 0 key)
1 (MapEntry. 1 val)
nil)))
clojure.lang.ILookup
(valAt [this k not-found]
(if (Util/isInteger k)
(case (int k)
0 key
1 val
not-found)
not-found))
(valAt [this k]
(.valAt this k nil))
clojure.lang.IFn
(invoke [this k]
(if (Util/isInteger k)
(case (int k)
0 key
1 val
(throw
(IndexOutOfBoundsException.
"invoke index out of bounds in AVLNode")))
(throw (IllegalArgumentException. "key must be integer"))))
(applyTo [this args]
(let [n (RT/boundedLength args 1)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.Seqable
(seq [this]
(list key val))
clojure.lang.Sequential
clojure.lang.IEditableCollection
(asTransient [this]
(transient [key val]))
clojure.lang.IMapEntry
(key [this]
key)
(val [this]
val)
java.util.Map$Entry
(getValue [this]
val)
(setValue [this x]
(throw-unsupported))
java.io.Serializable
java.lang.Comparable
(compareTo [this that]
(if (identical? this that)
0
(let [^clojure.lang.IPersistentVector v
(cast clojure.lang.IPersistentVector that)
vcnt (.count v)]
(cond
(< 2 vcnt) -1
(> 2 vcnt) 1
:else
(let [comp (Util/compare key (.nth v 0))]
(if (zero? comp)
(Util/compare val (.nth v 1))
comp))))))
java.lang.Iterable
(iterator [this]
(.iterator ^java.lang.Iterable (list key val)))
java.util.RandomAccess
java.util.List
(get [this i]
(.nth this i))
(indexOf [this x]
(condp = x
key 0
val 1
-1))
(lastIndexOf [this x]
(condp = x
val 1
key 0
-1))
(listIterator [this]
(.listIterator this 0))
(listIterator [this i]
(.listIterator (doto (java.util.ArrayList.)
(.add key)
(.add val))
i))
(subList [this a z]
(if (<= 0 a z 2)
(cond
(== a z) []
(and (== a 0) (== z 2)) this
:else (case a
0 [key]
1 [val]))
(throw
(IndexOutOfBoundsException. "subList index out of bounds in AVLNode"))))
java.util.Collection
(contains [this x]
(or (= key x) (= val x)))
(containsAll [this c]
(every? #(.contains this %) c))
(isEmpty [this]
false)
(toArray [this]
(into-array Object this))
(toArray [this arr]
(if (>= (count arr) 2)
(doto arr
(aset 0 key)
(aset 1 val))
(into-array Object this)))
(size [this]
2)
(add [this x] (throw-unsupported))
(^boolean remove [this x] (throw-unsupported))
(addAll [this c] (throw-unsupported))
(clear [this] (throw-unsupported))
(retainAll [this c] (throw-unsupported))
(removeAll [this c] (throw-unsupported))
(set [this i e] (throw-unsupported))
(remove [this ^int i] (throw-unsupported))
(add [this i e] (throw-unsupported)))
(defn ^:private ensure-editable
(^IAVLNode [^AtomicReference edit]
(let [owner (.get edit)]
(cond
(identical? owner (Thread/currentThread))
true
(nil? owner)
(throw (IllegalAccessError. "Transient used after persistent! call"))
:else
(throw (IllegalAccessError. "Transient used by non-owner thread")))))
(^IAVLNode [^AtomicReference edit ^AVLNode node]
(if (identical? edit (.-edit node))
node
(AVLNode. edit
(.getKey node) (.getVal node)
(.getLeft node)
(.getRight node)
(.getHeight node)
(.getRank node)))))
(defn ^:private height ^long [^IAVLNode node]
(if (nil? node)
0
(long (.getHeight node))))
(defn ^:private rotate-left ^IAVLNode [^IAVLNode node]
(let [l (.getLeft node)
r (.getRight node)
rl (.getLeft r)
rr (.getRight r)
lh (height l)
rlh (height rl)
rrh (height rr)
rnk (.getRank node)
rnkr (.getRank r)]
(AVLNode. nil
(.getKey r) (.getVal r)
(AVLNode. nil
(.getKey node) (.getVal node)
l
rl
(inc (max lh rlh))
rnk)
rr
(max (+ lh 2)
(+ rlh 2)
(inc rrh))
(inc (+ rnk rnkr)))))
(defn ^:private rotate-left! ^IAVLNode [edit ^IAVLNode node]
(let [node (ensure-editable edit node)
l (.getLeft node)
r (ensure-editable edit (.getRight node))
rl (.getLeft r)
rr (.getRight r)
lh (height l)
rlh (height rl)
rrh (height rr)
rnk (.getRank node)
rnkr (.getRank r)]
(.setLeft r node)
(.setHeight r (max (+ lh 2) (+ rlh 2) (inc rrh)))
(.setRank r (inc (+ rnk rnkr)))
(.setRight node rl)
(.setHeight node (inc (max lh rlh)))
r))
(defn ^:private rotate-right ^IAVLNode [^IAVLNode node]
(let [r (.getRight node)
l (.getLeft node)
lr (.getRight l)
ll (.getLeft l)
rh (height r)
lrh (height lr)
llh (height ll)
rnk (.getRank node)
rnkl (.getRank l)]
(AVLNode. nil
(.getKey l) (.getVal l)
ll
(AVLNode. nil
(.getKey node) (.getVal node)
lr
r
(inc (max rh lrh))
(dec (- rnk rnkl)))
(max (+ rh 2)
(+ lrh 2)
(inc llh))
rnkl)))
(defn ^:private rotate-right! ^IAVLNode [edit ^IAVLNode node]
(let [node (ensure-editable edit node)
r (.getRight node)
l (ensure-editable edit (.getLeft node))
lr (.getRight l)
ll (.getLeft l)
rh (height r)
lrh (height lr)
llh (height ll)
rnk (.getRank node)
rnkl (.getRank l)]
(.setRight l node)
(.setHeight l (max (+ rh 2) (+ lrh 2) (inc llh)))
(.setLeft node lr)
(.setHeight node (inc (max rh lrh)))
(.setRank node (dec (- rnk rnkl)))
l))
(defn ^:private lookup ^IAVLNode [^Comparator comp ^IAVLNode node k]
(if (nil? node)
nil
(let [c (.compare comp k (.getKey node))]
(cond
(zero? c) node
(neg? c) (recur comp (.getLeft node) k)
:else (recur comp (.getRight node) k)))))
(defn ^:private lookup-nearest
^IAVLNode [^Comparator comp ^IAVLNode node test k]
(let [below? (or (identical? < test) (identical? <= test))
equal? (or (identical? <= test) (identical? >= test))
back? (if below? neg? pos?)
backward (if below?
#(.getLeft ^IAVLNode %)
#(.getRight ^IAVLNode %))
forward (if below?
#(.getRight ^IAVLNode %)
#(.getLeft ^IAVLNode %))]
(loop [prev nil
node node]
(if (nil? node)
prev
(let [c (.compare comp k (.getKey node))]
(cond
(zero? c) (if equal?
node
(recur prev (backward node)))
(back? c) (recur prev (backward node))
:else (recur node (forward node))))))))
(defn ^:private select [^IAVLNode node ^long rank]
(if (nil? node)
nil
(let [node-rank (.getRank node)]
(cond
(== node-rank rank) node
(< node-rank rank) (recur (.getRight node) (dec (- rank node-rank)))
:else (recur (.getLeft node) rank)))))
(defn ^:private rank ^long [^Comparator comp ^IAVLNode node k]
(if (nil? node)
-1
(let [c (.compare comp k (.getKey node))]
(cond
(zero? c) (.getRank node)
(neg? c) (recur comp (.getLeft node) k)
:else (let [r (rank comp (.getRight node) k)]
(if (== -1 r)
-1
(inc (+ (.getRank node) r))))))))
(defn ^:private maybe-rebalance ^IAVLNode [^IAVLNode node]
(let [l (.getLeft node)
r (.getRight node)
lh (height l)
rh (height r)
b (- lh rh)]
(cond
(< b -1)
(let [rl (.getLeft r)
rr (.getRight r)
rlh (height rl)
rrh (height rr)]
(if (== (- rlh rrh) 1)
(let [new-right (rotate-right r)]
(rotate-left (AVLNode. nil
(.getKey node) (.getVal node)
(.getLeft node)
new-right
(inc (max lh (height new-right)))
(.getRank node))))
(rotate-left node)))
(> b 1)
(let [ll (.getLeft l)
lr (.getRight l)
llh (height ll)
lrh (height lr)]
(if (== (- lrh llh) 1)
(let [new-left (rotate-left l)]
(rotate-right (AVLNode. nil
(.getKey node) (.getVal node)
new-left
(.getRight node)
(inc (max rh (height new-left)))
(.getRank node))))
(rotate-right node)))
:else
node)))
(defn ^:private maybe-rebalance! ^IAVLNode [edit ^IAVLNode node]
(let [l (.getLeft node)
r (.getRight node)
lh (height l)
rh (height r)
b (- lh rh)]
(cond
(< b -1)
(let [node (ensure-editable edit node)
rl (.getLeft r)
rr (.getRight r)
rlh (height rl)
rrh (height rr)]
(if (== (- rlh rrh) 1)
(let [new-right (rotate-right! edit r)]
(.setRight node new-right)
(.setHeight node (inc (max lh (height new-right))))
(rotate-left! edit node))
(rotate-left! edit node)))
(> b 1)
(let [node (ensure-editable edit node)
ll (.getLeft l)
lr (.getRight l)
llh (height ll)
lrh (height lr)]
(if (== (- lrh llh) 1)
(let [new-left (rotate-left! edit l)]
(.setLeft node new-left)
(.setHeight node (inc (max rh (height new-left))))
(rotate-right! edit node))
(rotate-right! edit node)))
:else
node)))
(defn ^:private insert
^IAVLNode [^Comparator comp ^IAVLNode node k v ^Box found?]
(if (nil? node)
(AVLNode. nil k v nil nil 1 0)
(let [nk (.getKey node)
c (.compare comp k nk)]
(cond
(zero? c)
(do
(set! (.-val found?) true)
(AVLNode. nil
k v
(.getLeft node)
(.getRight node)
(.getHeight node)
(.getRank node)))
(neg? c)
(let [new-child (insert comp (.getLeft node) k v found?)]
(maybe-rebalance
(AVLNode. nil
nk (.getVal node)
new-child
(.getRight node)
(inc (max (.getHeight new-child)
(height (.getRight node))))
(if (.-val found?)
(.getRank node)
(unchecked-inc-int (.getRank node))))))
:else
(let [new-child (insert comp (.getRight node) k v found?)]
(maybe-rebalance
(AVLNode. nil
nk (.getVal node)
(.getLeft node)
new-child
(inc (max (.getHeight new-child)
(height (.getLeft node))))
(.getRank node))))))))
(defn ^:private insert!
^IAVLNode [edit ^Comparator comp ^IAVLNode node k v ^Box found?]
(if (nil? node)
(AVLNode. edit k v nil nil 1 0)
(let [node (ensure-editable edit node)
nk (.getKey node)
c (.compare comp k nk)]
(cond
(zero? c)
(do
(set! (.-val found?) true)
(.setKey node k)
(.setVal node v)
node)
(neg? c)
(let [new-child (insert! edit comp (.getLeft node) k v found?)]
(.setLeft node new-child)
(.setHeight node
(inc (max (.getHeight new-child)
(height (.getRight node)))))
(if-not (.-val found?)
(.setRank node (unchecked-inc-int (.getRank node))))
(maybe-rebalance! edit node))
:else
(let [new-child (insert! edit comp (.getRight node) k v found?)]
(.setRight node new-child)
(.setHeight node
(inc (max (.getHeight new-child)
(height (.getLeft node)))))
(maybe-rebalance! edit node))))))
(defn ^:private get-rightmost ^IAVLNode [^IAVLNode node]
(if-let [r (.getRight node)]
(recur r)
node))
(defn ^:private delete-rightmost ^IAVLNode [^IAVLNode node]
(if-let [r (.getRight node)]
(let [l (.getLeft node)
new-right (delete-rightmost r)]
(AVLNode. nil
(.getKey node) (.getVal node)
l
new-right
(inc (max (height l) (height new-right)))
(.getRank node)))
(.getLeft node)))
(defn ^:private delete-rightmost! ^IAVLNode [edit ^IAVLNode node]
(if-not (nil? node)
(let [node (ensure-editable edit node)
r ^IAVLNode (.getRight node)]
(cond
(nil? r)
(if-let [l (.getLeft node)]
(ensure-editable edit l))
(nil? (.getRight r))
(do
(.setRight node (.getLeft r))
(.setHeight node
(inc (max (height (.getLeft node))
(height (.getLeft r)))))
node)
:else
(let [new-right (delete-rightmost! edit r)]
(.setRight node new-right)
(.setHeight node
(inc (max (height (.getLeft node))
(height new-right))))
node)))))
(defn ^:private delete
^IAVLNode [^Comparator comp ^IAVLNode node k ^Box found?]
(if (nil? node)
nil
(let [nk (.getKey node)
c (.compare comp k nk)]
(cond
(zero? c)
(let [l (.getLeft node)
r (.getRight node)]
(set! (.-val found?) true)
(if (and l r)
(let [p (get-rightmost l)
l' (delete-rightmost l)]
(AVLNode. nil
(.getKey p) (.getVal p)
l'
r
(inc (max (height l') (height r)))
(unchecked-dec-int (.getRank node))))
(or l r)))
(neg? c)
(let [new-child (delete comp (.getLeft node) k found?)]
(if (identical? new-child (.getLeft node))
node
(maybe-rebalance
(AVLNode. nil
nk (.getVal node)
new-child
(.getRight node)
(inc (max (height new-child)
(height (.getRight node))))
(if (.-val found?)
(unchecked-dec-int (.getRank node))
(.getRank node))))))
:else
(let [new-child (delete comp (.getRight node) k found?)]
(if (identical? new-child (.getRight node))
node
(maybe-rebalance
(AVLNode. nil
nk (.getVal node)
(.getLeft node)
new-child
(inc (max (height new-child)
(height (.getLeft node))))
(.getRank node)))))))))
(defn ^:private delete!
^IAVLNode [edit ^Comparator comp ^IAVLNode node k ^Box found?]
(if (nil? node)
nil
(let [nk (.getKey node)
c (.compare comp k nk)]
(cond
(zero? c)
(let [l (.getLeft node)
r (.getRight node)]
(set! (.-val found?) true)
(cond
(and l r)
(let [node (ensure-editable edit node)
p (get-rightmost l)
l' (delete-rightmost! edit l)]
(.setKey node (.getKey p))
(.setVal node (.getVal p))
(.setLeft node l')
(.setHeight node (inc (max (height l') (height r))))
(.setRank node (unchecked-dec-int (.getRank node)))
node)
l l
r r
:else nil))
(neg? c)
(let [new-child (delete! edit comp (.getLeft node) k found?)]
(if (identical? new-child (.getLeft node))
node
(let [node (ensure-editable edit node)]
(.setLeft node new-child)
(.setHeight node
(inc (max (height new-child)
(height (.getRight node)))))
(if (.-val found?)
(.setRank node (unchecked-dec-int (.getRank node))))
(maybe-rebalance! edit node))))
:else
(let [new-child (delete! edit comp (.getRight node) k found?)]
(if (identical? new-child (.getRight node))
node
(let [node (ensure-editable edit node)]
(.setRight node new-child)
(.setHeight node
(inc (max (height new-child)
(height (.getLeft node)))))
(maybe-rebalance! edit node))))))))
(defn ^:private join
[^Comparator comp ^long left-count ^IAVLNode left ^IAVLNode right]
(cond
(nil? left) right
(nil? right) left
:else
(let [lh (.getHeight left)
rh (.getHeight right)]
(cond
(== lh rh)
(let [left-min (get-rightmost left)
new-left (delete comp left (.getKey left-min) (Box. false))]
(AVLNode. nil
(.getKey left-min) (.getVal left-min)
new-left
right
(unchecked-inc-int rh)
(unchecked-dec-int left-count)))
(< lh rh)
(letfn [(step [^IAVLNode current ^long lvl]
(cond
(zero? lvl)
(join comp left-count left current)
(nil? (.getLeft current))
(AVLNode. nil
(.getKey current) (.getVal current)
left
(.getRight current)
2
left-count)
:else
(let [new-child (step (.getLeft current) (dec lvl))
current-r (.getRight current)]
(maybe-rebalance
(AVLNode. nil
(.getKey current) (.getVal current)
new-child
current-r
(inc (max (.getHeight ^IAVLNode new-child)
(height current-r)
#_
(if current-r
(.getHeight current-r)
0)))
(+ left-count (.getRank current)))))))]
(step right (- rh lh)))
:else
(letfn [(step [^IAVLNode current ^long cnt ^long lvl]
(cond
(zero? lvl)
(join comp cnt current right)
(nil? (.getRight current))
(AVLNode. nil
(.getKey current) (.getVal current)
(.getLeft current)
right
2
(.getRank current))
:else
(let [new-child (step (.getRight current)
(dec (- cnt (.getRank current)))
(dec lvl))
current-l (.getLeft current)]
(maybe-rebalance
(AVLNode. nil
(.getKey current) (.getVal current)
current-l
new-child
(inc (max (.getHeight ^IAVLNode new-child)
(height current-l)
#_
(if current-l
(.getHeight current-l)
0)))
(.getRank current))))))]
(step left left-count (- lh rh)))))))
(defn ^:private split [^Comparator comp ^IAVLNode node k]
(letfn [(step [^IAVLNode node]
(if (nil? node)
[nil nil nil]
(let [c (.compare comp k (.getKey node))]
(cond
(zero? c)
[(.getLeft node)
(MapEntry. (.getKey node) (.getVal node))
(.getRight node)]
(neg? c)
(let [[l e r] (step (.getLeft node))
r' (insert comp
(.getRight node)
(.getKey node)
(.getVal node)
(Box. false))]
[l
e
(cond
e (join comp
(- (.getRank node)
(inc (rank comp
(.getLeft node)
(.key ^MapEntry e))))
r
r')
r (join comp
(- (.getRank node)
(inc (rank comp
(.getLeft node)
(.getKey (get-rightmost r)))))
r
r')
:else (join comp 0 r r'))
#_
(join comp
(- (.getRank node)
(cond
e
(inc (rank comp
(.getLeft node)
(.key ^MapEntry e)))
r
(inc (rank comp
(.getLeft node)
(.getKey (get-rightmost r))))
:else
(.getRank node)))
r
(insert comp
(.getRight node)
(.getKey node)
(.getVal node)
(Box. false)))])
:else
(let [[l e r] (step (.getRight node))]
[(join comp
(unchecked-inc-int (.getRank node))
(insert comp
(.getLeft node)
(.getKey node)
(.getVal node)
(Box. false))
l)
e
r])))))]
(step node)))
(defn ^:private range ^IAVLNode [^Comparator comp ^IAVLNode node low high]
(let [[_ ^MapEntry low-e r] (split comp node low)
[l ^MapEntry high-e _] (split comp r high)]
(cond-> l
low-e (as-> node
(insert comp node
(.key low-e) (.val low-e)
(Box. false)))
high-e (as-> node
(insert comp node
(.key high-e) (.val high-e)
(Box. false))))))
(defn ^:private seq-push [^IAVLNode node stack ascending?]
(loop [node node stack stack]
(if (nil? node)
stack
(recur (if ascending? (.getLeft node) (.getRight node))
(conj stack node)))))
(defn ^:private avl-map-kv-reduce [^IAVLNode node f init]
(let [init (if (nil? (.getLeft node))
init
(avl-map-kv-reduce (.getLeft node) f init))]
(if (reduced? init)
init
(let [init (f init (.getKey node) (.getVal node))]
(if (reduced? init)
init
(if (nil? (.getRight node))
init
(recur (.getRight node) f init)))))))
(deftype AVLMapSeq [^IPersistentMap _meta
^IPersistentStack stack
^boolean ascending?
^int cnt
^:unsynchronized-mutable ^int _hash
^:unsynchronized-mutable ^int _hasheq]
:no-print true
Object
(toString [this]
(RT/printString this))
(hashCode [this]
(caching-hash this hash-seq _hash))
clojure.lang.IHashEq
(hasheq [this]
(caching-hash this hasheq-seq _hasheq))
clojure.lang.Seqable
(seq [this]
this)
clojure.lang.Sequential
clojure.lang.ISeq
(first [this]
(peek stack)
#_
(let [node ^IAVLNode (peek stack)]
(MapEntry. (.getKey node) (.getVal node))))
(more [this]
(let [node ^IAVLNode (first stack)
next-stack (seq-push (if ascending? (.getRight node) (.getLeft node))
(next stack)
ascending?)]
(if (nil? next-stack)
()
(AVLMapSeq. nil next-stack ascending? (unchecked-dec-int cnt) -1 -1))))
(next [this]
(.seq (.more this)))
clojure.lang.Counted
(count [this]
(if (neg? cnt)
(unchecked-inc-int (count (next this)))
cnt))
clojure.lang.IPersistentCollection
(cons [this x]
(cons x this))
(equiv [this that]
(equiv-sequential this that))
(empty [this]
(with-meta () _meta))
clojure.lang.IMeta
(meta [this]
_meta)
clojure.lang.IObj
(withMeta [this meta]
(AVLMapSeq. meta stack ascending? cnt _hash _hasheq))
java.io.Serializable
java.util.List
(toArray [this]
(RT/seqToArray (seq this)))
(toArray [this arr]
(RT/seqToPassedArray (seq this) arr))
(containsAll [this c]
(every? #(.contains this %) (iterator-seq (.iterator c))))
(size [this]
(count this))
(isEmpty [this]
(zero? cnt))
(contains [this x]
(or (some #(Util/equiv % x) this) false))
(iterator [this]
(SeqIterator. this))
(subList [this from to]
(.subList (Collections/unmodifiableList (ArrayList. this)) from to))
(indexOf [this x]
(loop [i (int 0) s (seq this)]
(if s
(if (Util/equiv (first s) x)
i
(recur (unchecked-inc-int i) (next s)))
(int -1))))
(lastIndexOf [this x]
(.lastIndexOf (ArrayList. this) x))
(listIterator [this]
(.listIterator (Collections/unmodifiableList (ArrayList. this))))
(listIterator [this i]
(.listIterator (Collections/unmodifiableList (ArrayList. this)) i))
(get [this i]
(RT/nth this i))
(add [this x] (throw-unsupported))
(^boolean remove [this x] (throw-unsupported))
(addAll [this c] (throw-unsupported))
(clear [this] (throw-unsupported))
(retainAll [this c] (throw-unsupported))
(removeAll [this c] (throw-unsupported))
(set [this i e] (throw-unsupported))
(remove [this ^int i] (throw-unsupported))
(add [this i e] (throw-unsupported)))
(defn ^:private create-seq [node ascending? cnt]
(AVLMapSeq. nil (seq-push node nil ascending?) ascending? cnt -1 -1))
(declare ->AVLTransientMap)
(deftype AVLMap [^Comparator comp
^IAVLNode tree
^int cnt
^IPersistentMap _meta
^:unsynchronized-mutable ^int _hash
^:unsynchronized-mutable ^int _hasheq]
Object
(toString [this]
(RT/printString this))
(hashCode [this]
(caching-hash this hash-imap _hash))
(equals [this that]
(APersistentMap/mapEquals this that))
IAVLTree
(getTree [this]
tree)
INavigableTree
(nearest [this test k]
(if-let [node (lookup-nearest comp tree test k)]
(MapEntry. (.getKey node) (.getVal node))))
clojure.lang.IHashEq
(hasheq [this]
(caching-hash this hasheq-imap _hasheq))
clojure.lang.IMeta
(meta [this]
_meta)
clojure.lang.IObj
(withMeta [this meta]
(AVLMap. comp tree cnt meta _hash _hasheq))
clojure.lang.Counted
(count [this]
cnt)
clojure.lang.Indexed
(nth [this i]
(if-let [n (select tree i)]
(MapEntry. (.getKey ^IAVLNode n) (.getVal ^IAVLNode n))
(throw
(IndexOutOfBoundsException. "nth index out of bounds in AVL tree"))))
(nth [this i not-found]
(if-let [n (select tree i)]
(MapEntry. (.getKey ^IAVLNode n) (.getVal ^IAVLNode n))
not-found))
clojure.lang.IPersistentCollection
(cons [this entry]
(if (vector? entry)
(assoc this (nth entry 0) (nth entry 1))
(reduce conj this entry)))
(empty [this]
(AVLMap. comp nil 0 _meta empty-map-hashcode empty-map-hasheq))
(equiv [this that]
(equiv-map this that))
clojure.lang.IFn
(invoke [this k]
(.valAt this k))
(invoke [this k not-found]
(.valAt this k not-found))
(applyTo [this args]
(let [n (RT/boundedLength args 2)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (.invoke this (first args) (second args))
3 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.Seqable
(seq [this]
(if (pos? cnt)
(create-seq tree true cnt)))
clojure.lang.Reversible
(rseq [this]
(if (pos? cnt)
(create-seq tree false cnt)))
clojure.lang.ILookup
(valAt [this k]
(.valAt this k nil))
(valAt [this k not-found]
(let [n ^IAVLNode (lookup comp tree k)]
(if-not (nil? n)
(.getVal n)
not-found)))
clojure.lang.Associative
(assoc [this k v]
(let [found? (Box. false)
new-tree (insert comp tree k v found?)]
(AVLMap. comp
new-tree
(if (.-val found?) cnt (unchecked-inc-int cnt))
_meta -1 -1)))
(containsKey [this k]
(not (nil? (.entryAt this k))))
(entryAt [this k]
(if-let [node (lookup comp tree k)]
(MapEntry. (.getKey node) (.getVal node))))
clojure.lang.MapEquivalence
clojure.lang.IPersistentMap
(without [this k]
(let [found? (Box. false)
new-tree (delete comp tree k found?)]
(if (.-val found?)
(AVLMap. comp
new-tree
(unchecked-dec-int cnt)
_meta -1 -1)
this)))
(assocEx [this k v]
(let [found? (Box. false)
new-tree (insert comp tree k v found?)]
(if (.-val found?)
(throw (ex-info "key already present" {}))
(AVLMap. comp
new-tree
(unchecked-inc-int cnt)
_meta -1 -1))))
clojure.lang.Sorted
(seq [this ascending?]
(if (pos? cnt)
(create-seq tree ascending? cnt)))
(seqFrom [this k ascending?]
(if (pos? cnt)
(loop [stack nil t tree]
(if-not (nil? t)
(let [c (.compare comp k (.getKey t))]
(cond
(zero? c) (AVLMapSeq. nil (conj stack t) ascending? -1 -1 -1)
ascending? (if (neg? c)
(recur (conj stack t) (.getLeft t))
(recur stack (.getRight t)))
:else (if (pos? c)
(recur (conj stack t) (.getRight t))
(recur stack (.getLeft t)))))
(if-not (nil? stack)
(AVLMapSeq. nil stack ascending? -1 -1 -1))))))
(entryKey [this entry]
(key entry))
(comparator [this]
comp)
clojure.lang.IEditableCollection
(asTransient [this]
(->AVLTransientMap
(AtomicReference. (Thread/currentThread)) comp tree cnt))
clojure.core.protocols/IKVReduce
(kv-reduce [this f init]
(if (nil? tree)
init
(let [init (avl-map-kv-reduce tree f init)]
(if (reduced? init)
@init
init))))
java.io.Serializable
Iterable
(iterator [this]
(SeqIterator. (seq this)))
java.util.Map
(get [this k]
(.valAt this k))
(clear [this]
(throw-unsupported))
(containsValue [this v]
(.. this values (contains v)))
(entrySet [this]
(set (seq this)))
(put [this k v]
(throw-unsupported))
(putAll [this m]
(throw-unsupported))
(remove [this k]
(throw-unsupported))
(size [this]
cnt)
(values [this]
(vals this)))
(deftype AVLTransientMap [^AtomicReference edit
^Comparator comp
^:unsynchronized-mutable ^IAVLNode tree
^:unsynchronized-mutable ^int cnt]
clojure.lang.Counted
(count [this]
cnt)
clojure.lang.ILookup
(valAt [this k]
(.valAt this k nil))
(valAt [this k not-found]
(let [n ^IAVLNode (lookup comp tree k)]
(if-not (nil? n)
(.getVal n)
not-found)))
clojure.lang.IFn
(invoke [this k]
(.valAt this k))
(invoke [this k not-found]
(.valAt this k not-found))
(applyTo [this args]
(let [n (RT/boundedLength args 2)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (.invoke this (first args) (second args))
3 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.ITransientCollection
(conj [this entry]
(ensure-editable edit)
(if (vector? entry)
(assoc! this (nth entry 0) (nth entry 1))
(reduce conj! this entry)))
(persistent [this]
(ensure-editable edit)
(.set edit nil)
(AVLMap. comp tree cnt nil -1 -1))
clojure.lang.ITransientAssociative
(assoc [this k v]
(ensure-editable edit)
(let [found? (Box. false)
new-tree (insert! edit comp tree k v found?)]
(set! tree new-tree)
(if-not (.-val found?)
(set! cnt (unchecked-inc-int cnt)))
this))
clojure.lang.ITransientMap
(without [this k]
(ensure-editable edit)
(let [found? (Box. false)
new-tree (delete! edit comp tree k found?)]
(when (.-val found?)
(set! tree new-tree)
(set! cnt (unchecked-dec-int cnt)))
this)))
(declare ->AVLTransientSet)
(deftype AVLSet [^IPersistentMap _meta
^AVLMap avl-map
^:unsynchronized-mutable ^int _hash
^:unsynchronized-mutable ^int _hasheq]
Object
(toString [this]
(RT/printString this))
(hashCode [this]
(caching-hash this hash-iset _hash))
(equals [this that]
(APersistentSet/setEquals this that))
IAVLTree
(getTree [this]
(.getTree avl-map))
INavigableTree
(nearest [this test k]
(if-let [node (lookup-nearest (.comparator avl-map)
(.getTree avl-map)
test
k)]
(.getKey node)))
clojure.lang.IHashEq
(hasheq [this]
(caching-hash this hasheq-iset _hasheq))
clojure.lang.IMeta
(meta [this]
_meta)
clojure.lang.IObj
(withMeta [this meta]
(AVLSet. meta avl-map _hash _hasheq))
clojure.lang.Counted
(count [this]
(count avl-map))
clojure.lang.Indexed
(nth [this i]
(if-let [n (select (.-tree avl-map) i)]
(.getVal ^IAVLNode n)
(throw
(IndexOutOfBoundsException. "nth index out of bounds in AVL tree"))))
(nth [this i not-found]
(if-let [n (select (.-tree avl-map) i)]
(.getVal ^IAVLNode n)
not-found))
clojure.lang.IPersistentCollection
(cons [this x]
(AVLSet. _meta (assoc avl-map x x) -1 -1))
(empty [this]
(AVLSet. _meta (empty avl-map) empty-set-hashcode empty-set-hasheq))
(equiv [this that]
(and
(set? that)
(== (count this) (count that))
(every? #(contains? this %) that)))
clojure.lang.Seqable
(seq [this]
(keys avl-map))
clojure.lang.Sorted
(seq [this ascending?]
(RT/keys (.seq avl-map ascending?)))
(seqFrom [this k ascending?]
(RT/keys (.seqFrom avl-map k ascending?)))
(entryKey [this entry]
entry)
(comparator [this]
(.comparator avl-map))
clojure.lang.Reversible
(rseq [this]
(map key (rseq avl-map)))
clojure.lang.ILookup
(valAt [this v]
(.valAt this v nil))
(valAt [this v not-found]
(let [n (.entryAt avl-map v)]
(if-not (nil? n)
(.getKey n)
not-found)))
clojure.lang.IPersistentSet
(disjoin [this v]
(AVLSet. _meta (dissoc avl-map v) -1 -1))
(contains [this k]
(contains? avl-map k))
(get [this k]
(.valAt this k nil))
clojure.lang.IFn
(invoke [this k]
(.valAt this k))
(applyTo [this args]
(let [n (RT/boundedLength args 1)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.IEditableCollection
(asTransient [this]
(->AVLTransientSet (.asTransient avl-map)))
java.io.Serializable
java.util.Set
(add [this o] (throw-unsupported))
(remove [this o] (throw-unsupported))
(addAll [this c] (throw-unsupported))
(clear [this] (throw-unsupported))
(retainAll [this c] (throw-unsupported))
(removeAll [this c] (throw-unsupported))
(containsAll [this c]
(every? #(.contains this %) (iterator-seq (.iterator c))))
(size [this]
(count this))
(isEmpty [this]
(zero? (count this)))
(iterator [this]
(SeqIterator. (seq this)))
(toArray [this]
(RT/seqToArray (seq this)))
(toArray [this a]
(RT/seqToPassedArray (seq this) a)))
(deftype AVLTransientSet
[^:unsynchronized-mutable ^AVLTransientMap transient-avl-map]
clojure.lang.ITransientCollection
(conj [this k]
(set! transient-avl-map (.assoc transient-avl-map k k))
this)
(persistent [this]
(AVLSet. nil (.persistent transient-avl-map) -1 -1))
clojure.lang.ITransientSet
(disjoin [this k]
(set! transient-avl-map (.without transient-avl-map k))
this)
(contains [this k]
(not (identical? this (.valAt transient-avl-map k this))))
(get [this k]
(.valAt transient-avl-map k))
clojure.lang.IFn
(invoke [this k]
(.valAt transient-avl-map k))
(invoke [this k not-found]
(.valAt transient-avl-map k not-found))
(applyTo [this args]
(let [n (RT/boundedLength args 2)]
(case n
0 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName))))
1 (.invoke this (first args))
2 (.invoke this (first args) (second args))
3 (throw (clojure.lang.ArityException.
n (.. this (getClass) (getSimpleName)))))))
clojure.lang.Counted
(count [this]
(.count transient-avl-map)))
(def ^:private empty-map
(AVLMap. RT/DEFAULT_COMPARATOR nil 0 nil
empty-map-hashcode empty-map-hasheq))
(def ^:private empty-set
(AVLSet. nil empty-map empty-set-hashcode empty-set-hasheq))
(doseq [v [#'->AVLMapSeq
#'->AVLNode
#'->AVLMap
#'->AVLSet
#'->AVLTransientMap
#'->AVLTransientSet]]
(alter-meta! v assoc :private true))
(defn sorted-map
"keyval => key val
Returns a new AVL map with supplied mappings."
{:added "0.0.1"}
[& keyvals]
(loop [in (seq keyvals) out (transient empty-map)]
(if in
(if-let [nin (next in)]
(recur (next nin) (assoc! out (first in) (first nin)))
(throw (IllegalArgumentException.
(format
"sorted-map: no value supplied for key: %s"
(first in)))))
(persistent! out))))
(defn sorted-map-by
"keyval => key val
Returns a new sorted map with supplied mappings, using the supplied
comparator."
{:added "0.0.1"}
[^Comparator comparator & keyvals]
(loop [in (seq keyvals)
out (AVLTransientMap.
(AtomicReference. (Thread/currentThread)) comparator nil 0)]
(if in
(if-let [nin (next in)]
(recur (next nin) (assoc! out (first in) (first nin)))
(throw (IllegalArgumentException.
(format
"sorted-map-by: no value supplied for key: %s"
(first in)))))
(persistent! out))))
(defn sorted-set
"Returns a new sorted set with supplied keys."
{:added "0.0.1"}
[& keys]
(persistent! (reduce conj! (transient empty-set) keys)))
(defn sorted-set-by
"Returns a new sorted set with supplied keys, using the supplied comparator."
{:added "0.0.1"}
[^Comparator comparator & keys]
(persistent!
(reduce conj!
(AVLTransientSet. (transient (sorted-map-by comparator)))
keys)))
(defn rank-of
"Returns the rank of x in coll or -1 if not present."
{:added "0.0.6"}
^long [coll x]
(rank (.comparator ^clojure.lang.Sorted coll) (.getTree ^IAVLTree coll) x))
(defn nearest
"(alpha)
Equivalent to, but more efficient than, (first (subseq* coll test x)),
where subseq* is clojure.core/subseq for test in #{>, >=} and
clojure.core/rsubseq for test in #{<, <=}."
{:added "0.0.12"}
[coll test x]
(.nearest ^INavigableTree coll test x))
(defn split-key
"(alpha)
Returns [left e? right], where left and right are collections of
the same type as coll and containing, respectively, the keys below
and above k in the ordering determined by coll's comparator, while
e? is the entry at key k for maps, the stored copy of the key k for
sets, nil if coll does not contain k."
{:added "0.0.12"}
[k coll]
(let [comp (.comparator ^clojure.lang.Sorted coll)
[left e? right] (split comp (.getTree ^IAVLTree coll) k)
keyfn (if (map? coll) key identity)
wrap (if (map? coll)
(fn wrap-map [tree cnt]
(AVLMap. comp tree cnt nil -1 -1))
(fn wrap-set [tree cnt]
(AVLSet. nil (AVLMap. comp tree cnt nil -1 -1) -1 -1)))]
[(wrap left
(if (or e? right)
(rank-of coll (keyfn (nearest coll >= k)))
(count coll)))
(if (and e? (set? coll))
(.getKey ^MapEntry e?)
e?)
(wrap right
(if right
(- (count coll) (rank-of coll (keyfn (nearest coll > k))))
0))]))
(defn split-at
"(alpha)
Equivalent to, but more efficient than,
[(into (empty coll) (take n coll))
(into (empty coll) (drop n coll))]."
{:added "0.0.12"}
[^long n coll]
(if (>= n (count coll))
[coll (empty coll)]
(let [k (nth coll n)
k (if (map? coll) (key k) k)
[l e r] (split-key k coll)]
[l (conj r e)])))
(defn subrange
"(alpha)
Returns an AVL collection comprising the entries of coll between
start and end (in the sense determined by coll's comparator) in
logarithmic time. Whether the endpoints are themselves included in
must be either > or >=, end-test must be either < or <=.
When passed a single test and limit, subrange infers the other end
of the range from the test: > / >= mean to include items up to the
end of coll, < / <= mean to include items taken from the beginning
of coll.
(subrange >= start <= end) is equivalent to, but more efficient
than, (into (empty coll) (subseq coll >= start <= end)."
{:added "0.0.12"}
([coll test limit]
(cond
(zero? (count coll))
coll
(#{> >=} test)
(let [n (select (.getTree ^IAVLTree coll)
(dec (count coll)))]
(subrange coll
test limit
<= (.getKey ^IAVLNode n)))
:else
(let [n (select (.getTree ^IAVLTree coll) 0)]
(subrange coll
>= (.getKey ^IAVLNode n)
test limit))))
([coll start-test start end-test end]
(if (zero? (count coll))
coll
(let [comp (.comparator ^clojure.lang.Sorted coll)]
(if (pos? (.compare comp start end))
(throw
(IndexOutOfBoundsException. "start greater than end in subrange"))
(let [keyfn (if (map? coll) key identity)
l (nearest coll start-test start)
h (nearest coll end-test end)]
(if (and l h)
(let [tree (range comp (.getTree ^IAVLTree coll)
(keyfn l)
(keyfn h))
cnt (inc (- (rank-of coll (keyfn h))
(rank-of coll (keyfn l))))
m (AVLMap. comp tree cnt nil -1 -1)]
(if (map? coll)
m
(AVLSet. nil m -1 -1)))
(empty coll))))))))
|
1c9caef94632555fe2f76ff6c13562f9e97376d096fb83a82fffb0ce1ece579d | RefactoringTools/HaRe | HsModuleMaps.hs | module HsModuleMaps where
import HsModule
import MUtils
import HsIdent(seqHsIdent)
instance Functor (HsImportDeclI m) where
fmap f (HsImportDecl s m q as optspec) =
HsImportDecl s m q as (fmap (apSnd (map (fmap f))) optspec)
instance Functor (HsExportSpecI m) where
fmap f e =
case e of
EntE espec -> EntE (fmap f espec)
ModuleE mn -> ModuleE mn
instance Functor EntSpec where
fmap f e =
case e of
Var i -> Var (f i)
Abs i -> Abs (f i)
AllSubs i -> AllSubs (f i)
ListSubs i is -> ListSubs (f i) (map (fmap f) is)
--------------------------------------------------------------------------------
mapDecls f (HsModule loc name exps imps ds) = HsModule loc name exps imps (f ds)
seqDecls (HsModule loc name exps imps ds) = HsModule loc name exps imps # ds
seqImportDecl (HsImportDecl s m q as optspec) =
HsImportDecl s m q as # seqMaybe (fmap (apSndM (mapM seqEntSpec)) optspec)
seqExportSpec e =
case e of
EntE espec -> EntE # seqEntSpec espec
ModuleE mn -> return (ModuleE mn)
seqEntSpec e =
case e of
Var i -> Var # i
Abs i -> Abs # i
AllSubs i -> AllSubs # i
ListSubs i is -> ListSubs # i <# mapM seqHsIdent is
--------------------------------------------------------------------------------
mapModMN f (HsModule loc name exps imps ds) =
HsModule loc (f name) (mapExpsMN f exps) (mapImpsMN f imps) ds
mapExpsMN f = fmap . map . mapExpMN $ f
mapExpMN f (EntE e) = EntE e
mapExpMN f (ModuleE m) = ModuleE (f m)
mapImpsMN f = map . mapImpMN $ f
mapImpMN f (HsImportDecl loc m q as spec) =
HsImportDecl loc (f m) q (fmap f as) spec
| null | https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/old/tools/base/AST/HsModuleMaps.hs | haskell | ------------------------------------------------------------------------------
------------------------------------------------------------------------------ | module HsModuleMaps where
import HsModule
import MUtils
import HsIdent(seqHsIdent)
instance Functor (HsImportDeclI m) where
fmap f (HsImportDecl s m q as optspec) =
HsImportDecl s m q as (fmap (apSnd (map (fmap f))) optspec)
instance Functor (HsExportSpecI m) where
fmap f e =
case e of
EntE espec -> EntE (fmap f espec)
ModuleE mn -> ModuleE mn
instance Functor EntSpec where
fmap f e =
case e of
Var i -> Var (f i)
Abs i -> Abs (f i)
AllSubs i -> AllSubs (f i)
ListSubs i is -> ListSubs (f i) (map (fmap f) is)
mapDecls f (HsModule loc name exps imps ds) = HsModule loc name exps imps (f ds)
seqDecls (HsModule loc name exps imps ds) = HsModule loc name exps imps # ds
seqImportDecl (HsImportDecl s m q as optspec) =
HsImportDecl s m q as # seqMaybe (fmap (apSndM (mapM seqEntSpec)) optspec)
seqExportSpec e =
case e of
EntE espec -> EntE # seqEntSpec espec
ModuleE mn -> return (ModuleE mn)
seqEntSpec e =
case e of
Var i -> Var # i
Abs i -> Abs # i
AllSubs i -> AllSubs # i
ListSubs i is -> ListSubs # i <# mapM seqHsIdent is
mapModMN f (HsModule loc name exps imps ds) =
HsModule loc (f name) (mapExpsMN f exps) (mapImpsMN f imps) ds
mapExpsMN f = fmap . map . mapExpMN $ f
mapExpMN f (EntE e) = EntE e
mapExpMN f (ModuleE m) = ModuleE (f m)
mapImpsMN f = map . mapImpMN $ f
mapImpMN f (HsImportDecl loc m q as spec) =
HsImportDecl loc (f m) q (fmap f as) spec
|
143eb55ee73edb710a0ce5e06df5bfa7037709e86ccccbd9842488520ca66894 | input-output-hk/cardano-wallet-legacy | Response.hs | {-# LANGUAGE DeriveFunctor #-}
# LANGUAGE DeriveGeneric #
{-# LANGUAGE LambdaCase #-}
# LANGUAGE OverloadedLists #
module Cardano.Wallet.API.Response (
Metadata (..)
, ResponseStatus(..)
, APIResponse(..)
, JSONValidationError(..)
, UnsupportedMimeTypeError(..)
-- * Generating responses for collections
, respondWith
, fromSlice
-- * Generating responses for single resources
, single
-- * A slice of a collection
, SliceOf(..)
, ValidJSON
) where
import Prelude
import Universum (Buildable, Exception, Text)
import Data.Aeson (FromJSON (..), ToJSON (..))
import Formatting (bprint, build)
import qualified Formatting.Buildable
import Generics.SOP.TH (deriveGeneric)
import GHC.Generics (Generic)
import Servant (err400, err415)
import Test.QuickCheck
import Cardano.Wallet.API.Indices (Indexable, IxSet)
import Cardano.Wallet.API.Request (RequestParams (..))
import Cardano.Wallet.API.Request.Filter (FilterOperations (..))
import Cardano.Wallet.API.Request.Pagination (Page (..),
PaginationMetadata (..), PaginationParams (..),
PerPage (..))
import Cardano.Wallet.API.Request.Sort (SortOperations (..))
import Cardano.Wallet.API.Response.Filter.IxSet as FilterBackend
import Cardano.Wallet.API.Response.JSend (HasDiagnostic (..),
ResponseStatus (..))
import Cardano.Wallet.API.Response.Sort.IxSet as SortBackend
import Cardano.Wallet.API.V1.Errors (ToServantError (..))
import Cardano.Wallet.API.V1.Generic (jsendErrorGenericParseJSON,
jsendErrorGenericToJSON)
import Pos.Util.Servant as ServantUtil
data SliceOf a = SliceOf {
paginatedSlice :: [a]
-- ^ A paginated fraction of the resource
, paginatedTotal :: Int
-- ^ The total number of entries
}
instance Arbitrary a => Arbitrary (SliceOf a) where
arbitrary = SliceOf <$> arbitrary <*> arbitrary
-- | Inefficient function to build a response out of a @generator@ function. When the data layer will
-- be rewritten the obvious solution is to slice & dice the data as soon as possible (aka out of the DB), in this order:
--
1 . Query / Filtering operations ( affects the number of total entries for pagination ) ;
2 . Sorting operations
3 . Pagination
--
-- See also <-wg/guidelines/pagination_filter_sort.html this document>, which
-- states:
" Paginating responses should be done after applying the filters in a query , because it ’s possible for there
to be no matches in the first page of results , and returning an empty page is a poor API when the user explicitly
-- requested a number of results."
--
-- NOTE: We have chosen have an approach such that we are sorting the whole dataset after filtering and using
-- lazyness to avoid work. This might not be optimal in terms of performances and we might need to swap sorting
-- and pagination.
--
respondWith :: (Monad m, Indexable a)
=> RequestParams
-> FilterOperations ixs a
-- ^ Filtering operations to perform on the data.
-> SortOperations a
-- ^ Sorting operations to perform on the data.
-> m (IxSet a)
-- ^ The monadic action which produces the results.
-> m (APIResponse [a])
respondWith RequestParams{..} fops sorts generator = do
(theData, paginationMetadata) <- paginate rpPaginationParams . sortData sorts . applyFilters fops <$> generator
return APIResponse {
wrData = theData
, wrStatus = SuccessStatus
, wrMeta = Metadata paginationMetadata
}
paginate :: PaginationParams -> [a] -> ([a], PaginationMetadata)
paginate params@PaginationParams{..} rawResultSet =
let totalEntries = length rawResultSet
(PerPage pp) = ppPerPage
(Page cp) = ppPage
metadata = paginationParamsToMeta params totalEntries
slice = take pp . drop ((cp - 1) * pp)
in (slice rawResultSet, metadata)
paginationParamsToMeta :: PaginationParams -> Int -> PaginationMetadata
paginationParamsToMeta PaginationParams{..} totalEntries =
let perPage@(PerPage pp) = ppPerPage
currentPage = ppPage
totalPages = max 1 $ ceiling (fromIntegral totalEntries / (fromIntegral pp :: Double))
in PaginationMetadata {
metaTotalPages = totalPages
, metaPage = currentPage
, metaPerPage = perPage
, metaTotalEntries = totalEntries
}
fromSlice :: PaginationParams -> SliceOf a -> APIResponse [a]
fromSlice params (SliceOf theData totalEntries) = APIResponse {
wrData = theData
, wrStatus = SuccessStatus
, wrMeta = Metadata (paginationParamsToMeta params totalEntries)
}
--
-- Creating a better user experience when it comes to errors.
--
--
-- Error from parsing / validating JSON inputs
--
newtype JSONValidationError
= JSONValidationFailed Text
deriving (Eq, Show, Generic)
deriveGeneric ''JSONValidationError
instance ToJSON JSONValidationError where
toJSON =
jsendErrorGenericToJSON
instance FromJSON JSONValidationError where
parseJSON =
jsendErrorGenericParseJSON
instance Exception JSONValidationError
instance Arbitrary JSONValidationError where
arbitrary =
pure (JSONValidationFailed "JSON validation failed.")
instance Buildable JSONValidationError where
build _ =
bprint "Couldn't decode a JSON input."
instance HasDiagnostic JSONValidationError where
getDiagnosticKey _ =
"validationError"
instance ToServantError JSONValidationError where
declareServantError _ =
err400
newtype UnsupportedMimeTypeError
= UnsupportedMimeTypePresent Text
deriving (Eq, Show, Generic)
deriveGeneric ''UnsupportedMimeTypeError
instance ToJSON UnsupportedMimeTypeError where
toJSON =
jsendErrorGenericToJSON
instance FromJSON UnsupportedMimeTypeError where
parseJSON =
jsendErrorGenericParseJSON
instance Exception UnsupportedMimeTypeError
instance Arbitrary UnsupportedMimeTypeError where
arbitrary =
pure (UnsupportedMimeTypePresent "Delivered MIME-type is not supported.")
instance Buildable UnsupportedMimeTypeError where
build (UnsupportedMimeTypePresent txt) =
bprint build txt
instance HasDiagnostic UnsupportedMimeTypeError where
getDiagnosticKey _ =
"mimeContentTypeError"
instance ToServantError UnsupportedMimeTypeError where
declareServantError _ =
err415
| null | https://raw.githubusercontent.com/input-output-hk/cardano-wallet-legacy/143e6d0dac0b28b3274600c6c49ec87e42ec9f37/src/Cardano/Wallet/API/Response.hs | haskell | # LANGUAGE DeriveFunctor #
# LANGUAGE LambdaCase #
* Generating responses for collections
* Generating responses for single resources
* A slice of a collection
^ A paginated fraction of the resource
^ The total number of entries
| Inefficient function to build a response out of a @generator@ function. When the data layer will
be rewritten the obvious solution is to slice & dice the data as soon as possible (aka out of the DB), in this order:
See also <-wg/guidelines/pagination_filter_sort.html this document>, which
states:
requested a number of results."
NOTE: We have chosen have an approach such that we are sorting the whole dataset after filtering and using
lazyness to avoid work. This might not be optimal in terms of performances and we might need to swap sorting
and pagination.
^ Filtering operations to perform on the data.
^ Sorting operations to perform on the data.
^ The monadic action which produces the results.
Creating a better user experience when it comes to errors.
Error from parsing / validating JSON inputs
| # LANGUAGE DeriveGeneric #
# LANGUAGE OverloadedLists #
module Cardano.Wallet.API.Response (
Metadata (..)
, ResponseStatus(..)
, APIResponse(..)
, JSONValidationError(..)
, UnsupportedMimeTypeError(..)
, respondWith
, fromSlice
, single
, SliceOf(..)
, ValidJSON
) where
import Prelude
import Universum (Buildable, Exception, Text)
import Data.Aeson (FromJSON (..), ToJSON (..))
import Formatting (bprint, build)
import qualified Formatting.Buildable
import Generics.SOP.TH (deriveGeneric)
import GHC.Generics (Generic)
import Servant (err400, err415)
import Test.QuickCheck
import Cardano.Wallet.API.Indices (Indexable, IxSet)
import Cardano.Wallet.API.Request (RequestParams (..))
import Cardano.Wallet.API.Request.Filter (FilterOperations (..))
import Cardano.Wallet.API.Request.Pagination (Page (..),
PaginationMetadata (..), PaginationParams (..),
PerPage (..))
import Cardano.Wallet.API.Request.Sort (SortOperations (..))
import Cardano.Wallet.API.Response.Filter.IxSet as FilterBackend
import Cardano.Wallet.API.Response.JSend (HasDiagnostic (..),
ResponseStatus (..))
import Cardano.Wallet.API.Response.Sort.IxSet as SortBackend
import Cardano.Wallet.API.V1.Errors (ToServantError (..))
import Cardano.Wallet.API.V1.Generic (jsendErrorGenericParseJSON,
jsendErrorGenericToJSON)
import Pos.Util.Servant as ServantUtil
data SliceOf a = SliceOf {
paginatedSlice :: [a]
, paginatedTotal :: Int
}
instance Arbitrary a => Arbitrary (SliceOf a) where
arbitrary = SliceOf <$> arbitrary <*> arbitrary
1 . Query / Filtering operations ( affects the number of total entries for pagination ) ;
2 . Sorting operations
3 . Pagination
" Paginating responses should be done after applying the filters in a query , because it ’s possible for there
to be no matches in the first page of results , and returning an empty page is a poor API when the user explicitly
respondWith :: (Monad m, Indexable a)
=> RequestParams
-> FilterOperations ixs a
-> SortOperations a
-> m (IxSet a)
-> m (APIResponse [a])
respondWith RequestParams{..} fops sorts generator = do
(theData, paginationMetadata) <- paginate rpPaginationParams . sortData sorts . applyFilters fops <$> generator
return APIResponse {
wrData = theData
, wrStatus = SuccessStatus
, wrMeta = Metadata paginationMetadata
}
paginate :: PaginationParams -> [a] -> ([a], PaginationMetadata)
paginate params@PaginationParams{..} rawResultSet =
let totalEntries = length rawResultSet
(PerPage pp) = ppPerPage
(Page cp) = ppPage
metadata = paginationParamsToMeta params totalEntries
slice = take pp . drop ((cp - 1) * pp)
in (slice rawResultSet, metadata)
paginationParamsToMeta :: PaginationParams -> Int -> PaginationMetadata
paginationParamsToMeta PaginationParams{..} totalEntries =
let perPage@(PerPage pp) = ppPerPage
currentPage = ppPage
totalPages = max 1 $ ceiling (fromIntegral totalEntries / (fromIntegral pp :: Double))
in PaginationMetadata {
metaTotalPages = totalPages
, metaPage = currentPage
, metaPerPage = perPage
, metaTotalEntries = totalEntries
}
fromSlice :: PaginationParams -> SliceOf a -> APIResponse [a]
fromSlice params (SliceOf theData totalEntries) = APIResponse {
wrData = theData
, wrStatus = SuccessStatus
, wrMeta = Metadata (paginationParamsToMeta params totalEntries)
}
newtype JSONValidationError
= JSONValidationFailed Text
deriving (Eq, Show, Generic)
deriveGeneric ''JSONValidationError
instance ToJSON JSONValidationError where
toJSON =
jsendErrorGenericToJSON
instance FromJSON JSONValidationError where
parseJSON =
jsendErrorGenericParseJSON
instance Exception JSONValidationError
instance Arbitrary JSONValidationError where
arbitrary =
pure (JSONValidationFailed "JSON validation failed.")
instance Buildable JSONValidationError where
build _ =
bprint "Couldn't decode a JSON input."
instance HasDiagnostic JSONValidationError where
getDiagnosticKey _ =
"validationError"
instance ToServantError JSONValidationError where
declareServantError _ =
err400
newtype UnsupportedMimeTypeError
= UnsupportedMimeTypePresent Text
deriving (Eq, Show, Generic)
deriveGeneric ''UnsupportedMimeTypeError
instance ToJSON UnsupportedMimeTypeError where
toJSON =
jsendErrorGenericToJSON
instance FromJSON UnsupportedMimeTypeError where
parseJSON =
jsendErrorGenericParseJSON
instance Exception UnsupportedMimeTypeError
instance Arbitrary UnsupportedMimeTypeError where
arbitrary =
pure (UnsupportedMimeTypePresent "Delivered MIME-type is not supported.")
instance Buildable UnsupportedMimeTypeError where
build (UnsupportedMimeTypePresent txt) =
bprint build txt
instance HasDiagnostic UnsupportedMimeTypeError where
getDiagnosticKey _ =
"mimeContentTypeError"
instance ToServantError UnsupportedMimeTypeError where
declareServantError _ =
err415
|
f4f3a313f9419b1b4b5bcdf4c8eb1fe67f119f6e151441a85076ae3ff07a5acd | ekmett/distributive | Store.hs | {-# Language DerivingStrategies #-}
{-# Language Safe #-}
-- |
Copyright : ( c ) 2011 - 2021
( c ) 2011
License : BSD-2 - Clause OR Apache-2.0
-- Maintainer :
-- Stability : experimental
--
-- This is a generalized 'Store' 'Comonad', parameterized by a 'Representable' 'Functor'.
-- The representation of that 'Functor' serves as the index of the store.
--
-- This can be useful if the representable functor serves to memoize its
-- contents and will be inspected often.
module Control.Comonad.Rep.Store
( Store
, pattern Store
, runStore
, StoreT(StoreT, ..)
, runStoreT
, ComonadStore(..)
) where
import Control.Comonad
import Control.Comonad.Env.Class
import Control.Comonad.Hoist.Class
import Control.Comonad.Store.Class
import Control.Comonad.Traced.Class
import Control.Comonad.Trans.Class
import Control.Monad.Identity
import Data.Rep
import Data.Data
import Data.Foldable.WithIndex
import Data.Functor.WithIndex
import Data.Traversable.WithIndex
import GHC.Generics
| A memoized store comonad parameterized by a representable functor , where
the representatation of @g@ , @Log g@ is the index of the store .
--
type Store g = StoreT g Identity
-- | Construct a store comonad computation from a function and a current index.
-- (The inverse of 'runStore'.)
pattern Store :: Representable g => (Log g -> a) -> Log g -> Store g a
pattern Store f l = StoreDist (Tabulate f) l
pattern StoreDist :: g a -> Log g -> Store g a
pattern StoreDist f l = StoreDistT (Identity f) l
-- | Unwrap a store comonad computation as a function and a current index.
-- (The inverse of 'store'.)
runStore :: Representable g
=> Store g a -- ^ a store to access
-> (Log g -> a, Log g) -- ^ initial state
runStore (StoreDistT (Identity ga) k) = (index ga, k)
# inline runStore #
-- ---------------------------------------------------------------------------
-- | A store transformer comonad parameterized by:
--
-- * @g@ - A representable functor used to memoize results for an index @Log g@
--
-- * @w@ - The inner comonad.
data StoreT g w a = StoreDistT (w (g a)) (Log g)
deriving stock (Generic, Generic1, Functor, Foldable, Traversable)
deriving ( FunctorWithIndex ( Log w , Log g ) )
pattern StoreT :: (Functor w, Representable g) => w (Log g -> a) -> Log g -> StoreT g w a
pattern StoreT w s <- StoreDistT (fmap index -> w) s where
StoreT w s = StoreDistT (fmap tabulate w) s
runStoreT :: (Functor w, Indexable g) => StoreT g w a -> (w (Log g -> a), Log g)
runStoreT (StoreDistT w s) = (index <$> w, s)
# inline runStoreT #
deriving stock instance
( Typeable g
, Typeable w
, Typeable a
, Data (w (g a))
, Data (Log g)
) => Data (StoreT g w a)
instance
( FunctorWithIndex i w
, FunctorWithIndex j g
) => FunctorWithIndex (i, j) (StoreT g w) where
imap f (StoreDistT wg lg) = StoreDistT (imap (\i -> imap \j -> f (i,j)) wg) lg
instance
( FoldableWithIndex i w
, FoldableWithIndex j g
) => FoldableWithIndex (i, j) (StoreT g w) where
ifoldMap f (StoreDistT wg _) = ifoldMap (\i -> ifoldMap \j -> f (i,j)) wg
instance
( TraversableWithIndex i w
, TraversableWithIndex j g
) => TraversableWithIndex (i, j) (StoreT g w) where
itraverse f (StoreDistT wg lg) = (`StoreDistT` lg) <$> itraverse (\i -> itraverse \j -> f (i,j)) wg
instance (Comonad w, Representable g, Log g ~ s) => ComonadStore s (StoreT g w) where
pos (StoreDistT _ s) = s
# inline pos #
peek s (StoreDistT w _) = extract w `index` s
# inline peek #
peeks f (StoreDistT w s) = extract w `index` f s
# inline peeks #
seek s (StoreDistT w _) = StoreDistT w s
{-# inline seek #-}
seeks f (StoreDistT w s) = StoreDistT w (f s)
{-# inline seeks #-}
instance (ComonadApply w, Semigroup (Log g), Representable g) => ComonadApply (StoreT g w) where
StoreDistT ff m <@> StoreDistT fa n = StoreDistT (apRep <$> ff <@> fa) (m <> n)
{-# inline (<@>) #-}
instance (Applicative w, Monoid (Log g), Representable g) => Applicative (StoreT g w) where
pure a = StoreDistT (pure (pureRep a)) mempty
{-# inline pure #-}
StoreDistT ff m <*> StoreDistT fa n = StoreDistT (apRep <$> ff <*> fa) (m `mappend` n)
{-# inline (<*>) #-}
instance (Comonad w, Representable g) => Comonad (StoreT g w) where
duplicate (StoreDistT wf s) = StoreDistT (extend (tabulate . StoreDistT) wf) s
{-# inline duplicate #-}
extract (StoreDistT wf s) = index (extract wf) s
{-# inline extract #-}
instance Representable g => ComonadTrans (StoreT g) where
lower (StoreDistT w s) = fmap (`index` s) w
# inline lower #
instance ComonadHoist (StoreT g) where
cohoist f (StoreDistT w s) = StoreDistT (f w) s
# inline cohoist #
instance (ComonadTraced m w, Representable g) => ComonadTraced m (StoreT g w) where
trace m = trace m . lower
{-# inline trace #-}
instance (ComonadEnv m w, Representable g) => ComonadEnv m (StoreT g w) where
ask = ask . lower
{-# inline ask #-}
instance ( , ComonadCofree f w ) = > ComonadCofree f ( w ) where
unwrap ( StoreDistT w s ) = fmap ( ` StoreDistT ` s ) ( unwrap w )
{ - # inline unwrap # - }
| null | https://raw.githubusercontent.com/ekmett/distributive/df1cd53a1c9befdeec8e0890c6b5a52159c3e852/src/Control/Comonad/Rep/Store.hs | haskell | # Language DerivingStrategies #
# Language Safe #
|
Maintainer :
Stability : experimental
This is a generalized 'Store' 'Comonad', parameterized by a 'Representable' 'Functor'.
The representation of that 'Functor' serves as the index of the store.
This can be useful if the representable functor serves to memoize its
contents and will be inspected often.
| Construct a store comonad computation from a function and a current index.
(The inverse of 'runStore'.)
| Unwrap a store comonad computation as a function and a current index.
(The inverse of 'store'.)
^ a store to access
^ initial state
---------------------------------------------------------------------------
| A store transformer comonad parameterized by:
* @g@ - A representable functor used to memoize results for an index @Log g@
* @w@ - The inner comonad.
# inline seek #
# inline seeks #
# inline (<@>) #
# inline pure #
# inline (<*>) #
# inline duplicate #
# inline extract #
# inline trace #
# inline ask # |
Copyright : ( c ) 2011 - 2021
( c ) 2011
License : BSD-2 - Clause OR Apache-2.0
module Control.Comonad.Rep.Store
( Store
, pattern Store
, runStore
, StoreT(StoreT, ..)
, runStoreT
, ComonadStore(..)
) where
import Control.Comonad
import Control.Comonad.Env.Class
import Control.Comonad.Hoist.Class
import Control.Comonad.Store.Class
import Control.Comonad.Traced.Class
import Control.Comonad.Trans.Class
import Control.Monad.Identity
import Data.Rep
import Data.Data
import Data.Foldable.WithIndex
import Data.Functor.WithIndex
import Data.Traversable.WithIndex
import GHC.Generics
| A memoized store comonad parameterized by a representable functor , where
the representatation of @g@ , @Log g@ is the index of the store .
type Store g = StoreT g Identity
pattern Store :: Representable g => (Log g -> a) -> Log g -> Store g a
pattern Store f l = StoreDist (Tabulate f) l
pattern StoreDist :: g a -> Log g -> Store g a
pattern StoreDist f l = StoreDistT (Identity f) l
runStore :: Representable g
runStore (StoreDistT (Identity ga) k) = (index ga, k)
# inline runStore #
data StoreT g w a = StoreDistT (w (g a)) (Log g)
deriving stock (Generic, Generic1, Functor, Foldable, Traversable)
deriving ( FunctorWithIndex ( Log w , Log g ) )
pattern StoreT :: (Functor w, Representable g) => w (Log g -> a) -> Log g -> StoreT g w a
pattern StoreT w s <- StoreDistT (fmap index -> w) s where
StoreT w s = StoreDistT (fmap tabulate w) s
runStoreT :: (Functor w, Indexable g) => StoreT g w a -> (w (Log g -> a), Log g)
runStoreT (StoreDistT w s) = (index <$> w, s)
# inline runStoreT #
deriving stock instance
( Typeable g
, Typeable w
, Typeable a
, Data (w (g a))
, Data (Log g)
) => Data (StoreT g w a)
instance
( FunctorWithIndex i w
, FunctorWithIndex j g
) => FunctorWithIndex (i, j) (StoreT g w) where
imap f (StoreDistT wg lg) = StoreDistT (imap (\i -> imap \j -> f (i,j)) wg) lg
instance
( FoldableWithIndex i w
, FoldableWithIndex j g
) => FoldableWithIndex (i, j) (StoreT g w) where
ifoldMap f (StoreDistT wg _) = ifoldMap (\i -> ifoldMap \j -> f (i,j)) wg
instance
( TraversableWithIndex i w
, TraversableWithIndex j g
) => TraversableWithIndex (i, j) (StoreT g w) where
itraverse f (StoreDistT wg lg) = (`StoreDistT` lg) <$> itraverse (\i -> itraverse \j -> f (i,j)) wg
instance (Comonad w, Representable g, Log g ~ s) => ComonadStore s (StoreT g w) where
pos (StoreDistT _ s) = s
# inline pos #
peek s (StoreDistT w _) = extract w `index` s
# inline peek #
peeks f (StoreDistT w s) = extract w `index` f s
# inline peeks #
seek s (StoreDistT w _) = StoreDistT w s
seeks f (StoreDistT w s) = StoreDistT w (f s)
instance (ComonadApply w, Semigroup (Log g), Representable g) => ComonadApply (StoreT g w) where
StoreDistT ff m <@> StoreDistT fa n = StoreDistT (apRep <$> ff <@> fa) (m <> n)
instance (Applicative w, Monoid (Log g), Representable g) => Applicative (StoreT g w) where
pure a = StoreDistT (pure (pureRep a)) mempty
StoreDistT ff m <*> StoreDistT fa n = StoreDistT (apRep <$> ff <*> fa) (m `mappend` n)
instance (Comonad w, Representable g) => Comonad (StoreT g w) where
duplicate (StoreDistT wf s) = StoreDistT (extend (tabulate . StoreDistT) wf) s
extract (StoreDistT wf s) = index (extract wf) s
instance Representable g => ComonadTrans (StoreT g) where
lower (StoreDistT w s) = fmap (`index` s) w
# inline lower #
instance ComonadHoist (StoreT g) where
cohoist f (StoreDistT w s) = StoreDistT (f w) s
# inline cohoist #
instance (ComonadTraced m w, Representable g) => ComonadTraced m (StoreT g w) where
trace m = trace m . lower
instance (ComonadEnv m w, Representable g) => ComonadEnv m (StoreT g w) where
ask = ask . lower
instance ( , ComonadCofree f w ) = > ComonadCofree f ( w ) where
unwrap ( StoreDistT w s ) = fmap ( ` StoreDistT ` s ) ( unwrap w )
{ - # inline unwrap # - }
|
637f7368c1fb90e086ba744c4faa251390bd40c86de3cc5d34b96e5be9aefe02 | spurious/snd-mirror | selection.scm | ;;; selection.scm -- selection-related functions
;;;
;;; swap-selection-channels
;;; replace-with-selection
;;; selection-members
;;; make-selection
;;; filter-selection-and-smooth
;;; with-temporary-selection
(provide 'snd-selection.scm)
(if (not (defined? 'all-chans))
(define (all-chans)
(let ((sndlist ())
(chnlist ()))
(for-each (lambda (snd)
(do ((i (- (channels snd) 1) (- i 1)))
((< i 0))
(set! sndlist (cons snd sndlist))
(set! chnlist (cons i chnlist))))
(sounds))
(list sndlist chnlist))))
-------- swap selection chans
(define swap-selection-channels
(let ((+documentation+ "(swap-selection-channels) swaps the currently selected data's channels")
(find-selection-sound
(lambda (not-this)
(let ((scs (all-chans)))
(call-with-exit
(lambda (return)
(map
(lambda (snd chn)
(if (and (selection-member? snd chn)
(or (null? not-this)
(not (equal? snd (car not-this)))
(not (= chn (cadr not-this)))))
(return (list snd chn))))
(car scs)
(cadr scs))))))))
(lambda ()
(if (not (selection?))
(error 'no-active-selection "swap-selection-channels needs a selection")
(if (not (= (selection-chans) 2))
(error 'wrong-number-of-channels "swap-selection-channels needs a stereo selection")
(let* ((snd-chn0 (find-selection-sound ()))
(snd-chn1 (find-selection-sound snd-chn0)))
(if snd-chn1
(swap-channels (car snd-chn0) (cadr snd-chn0)
(car snd-chn1) (cadr snd-chn1)
(selection-position)
(selection-framples))
(error 'wrong-number-of-channels "swap-selection-channels needs two channels to swap"))))))))
;;; -------- replace-with-selection
(define replace-with-selection
(let ((+documentation+ "(replace-with-selection) replaces the samples from the cursor with the current selection"))
(lambda ()
(let ((beg (cursor))
(len (selection-framples)))
(insert-selection beg) ; put in the selection before deletion, since delete-samples can deactivate the selection
(delete-samples (+ beg len) len)))))
;;; -------- selection-members
;;;
returns a list of lists of ( snd chn ): channels in current selection
(define selection-members
(let ((+documentation+ "(selection-members) -> list of lists of (snd chn) indicating the channels participating in the current selection."))
(lambda ()
(let ((sndlist ()))
(if (selection?)
(for-each (lambda (snd)
(do ((i (- (channels snd) 1) (- i 1)))
((< i 0))
(if (selection-member? snd i)
(set! sndlist (cons (list snd i) sndlist)))))
(sounds)))
sndlist))))
;;; -------- make-selection
the regularized form of this would use not end
(define make-selection
(let ((+documentation+ "(make-selection beg end snd chn) makes a selection like make-region but without creating a region.
make-selection follows snd's sync field, and applies to all snd's channels if chn is not specified. end defaults
to end of channel, beg defaults to 0, snd defaults to the currently selected sound.")
(add-chan-to-selection
(lambda (s0 s1 s c)
(set! (selection-member? s c) #t)
(set! (selection-position s c) (or s0 0))
(set! (selection-framples s c) (- (or (and (number? s1) (+ 1 s1)) (framples s c)) (or s0 0))))))
(lambda* (beg end snd chn)
(let ((current-sound (or snd (selected-sound) (car (sounds)))))
(if (not (sound? current-sound))
(error 'no-such-sound "make-selection can't find sound"))
(let ((current-sync (sync current-sound)))
(unselect-all)
(if (number? chn)
(add-chan-to-selection beg end snd chn)
(for-each
(lambda (s)
(if (or (eq? snd #t)
(equal? s current-sound)
(and (not (= current-sync 0))
(= current-sync (sync s))))
(do ((i 0 (+ 1 i)))
((= i (channels s)))
(add-chan-to-selection beg end s i))))
(sounds))))))))
;;; -------- with-temporary-selection
(define with-temporary-selection
(let ((+documentation+ "(with-temporary-selection thunk beg dur snd chn) saves the current selection placement, makes a new selection \
of the data from sample beg to beg + dur in the given channel. It then calls thunk, and
restores the previous selection (if any). It returns whatever 'thunk' returned."))
(lambda (thunk beg dur snd chn)
(let ((seldata (and (selection?)
(car (selection-members)))))
(if (selection?)
(set! seldata (append seldata (list (selection-position) (selection-framples)))))
(make-selection beg (- (+ beg dur) 1) snd chn)
(let ((result (thunk)))
(if (not seldata)
(unselect-all)
(make-selection (caddr seldata)
(- (+ (caddr seldata) (cadddr seldata)) 1)
(car seldata)
(cadr seldata)))
result)))))
;;; -------- filter-selection-and-smooth
(define filter-selection-and-smooth
(let ((+documentation+ "(filter-selection-and-smooth ramp-dur flt order) applies 'flt' (via filter-sound) to \
the selection, the smooths the edges with a ramp whose duration is 'ramp-dur' (in seconds)"))
(lambda* (ramp-dur flt order)
(let ((temp-file (snd-tempnam)))
(save-selection temp-file)
(let ((selsnd (open-sound temp-file)))
(filter-sound flt (or order (length flt)) selsnd)
(let ((tmp-dur (samples->seconds (framples selsnd))))
make sure env - sound hits all chans
(env-sound (list 0 0 ramp-dur 1 (- tmp-dur ramp-dur) 1 tmp-dur 0) 0 #f 1.0 selsnd)
(save-sound selsnd)
(close-sound selsnd)
(env-selection (list 0 1 ramp-dur 0 (- tmp-dur ramp-dur) 0 tmp-dur 1))))
(mix temp-file (selection-position) #t #f #f #f #f)))))
( filter - selection - and - smooth .01 ( float - vector .25 .5 .5 .5 .25 ) )
| null | https://raw.githubusercontent.com/spurious/snd-mirror/8e7a643c840592797c29384ffe07c87ba5c0a3eb/selection.scm | scheme | selection.scm -- selection-related functions
swap-selection-channels
replace-with-selection
selection-members
make-selection
filter-selection-and-smooth
with-temporary-selection
-------- replace-with-selection
put in the selection before deletion, since delete-samples can deactivate the selection
-------- selection-members
-------- make-selection
-------- with-temporary-selection
-------- filter-selection-and-smooth |
(provide 'snd-selection.scm)
(if (not (defined? 'all-chans))
(define (all-chans)
(let ((sndlist ())
(chnlist ()))
(for-each (lambda (snd)
(do ((i (- (channels snd) 1) (- i 1)))
((< i 0))
(set! sndlist (cons snd sndlist))
(set! chnlist (cons i chnlist))))
(sounds))
(list sndlist chnlist))))
-------- swap selection chans
(define swap-selection-channels
(let ((+documentation+ "(swap-selection-channels) swaps the currently selected data's channels")
(find-selection-sound
(lambda (not-this)
(let ((scs (all-chans)))
(call-with-exit
(lambda (return)
(map
(lambda (snd chn)
(if (and (selection-member? snd chn)
(or (null? not-this)
(not (equal? snd (car not-this)))
(not (= chn (cadr not-this)))))
(return (list snd chn))))
(car scs)
(cadr scs))))))))
(lambda ()
(if (not (selection?))
(error 'no-active-selection "swap-selection-channels needs a selection")
(if (not (= (selection-chans) 2))
(error 'wrong-number-of-channels "swap-selection-channels needs a stereo selection")
(let* ((snd-chn0 (find-selection-sound ()))
(snd-chn1 (find-selection-sound snd-chn0)))
(if snd-chn1
(swap-channels (car snd-chn0) (cadr snd-chn0)
(car snd-chn1) (cadr snd-chn1)
(selection-position)
(selection-framples))
(error 'wrong-number-of-channels "swap-selection-channels needs two channels to swap"))))))))
(define replace-with-selection
(let ((+documentation+ "(replace-with-selection) replaces the samples from the cursor with the current selection"))
(lambda ()
(let ((beg (cursor))
(len (selection-framples)))
(delete-samples (+ beg len) len)))))
returns a list of lists of ( snd chn ): channels in current selection
(define selection-members
(let ((+documentation+ "(selection-members) -> list of lists of (snd chn) indicating the channels participating in the current selection."))
(lambda ()
(let ((sndlist ()))
(if (selection?)
(for-each (lambda (snd)
(do ((i (- (channels snd) 1) (- i 1)))
((< i 0))
(if (selection-member? snd i)
(set! sndlist (cons (list snd i) sndlist)))))
(sounds)))
sndlist))))
the regularized form of this would use not end
(define make-selection
(let ((+documentation+ "(make-selection beg end snd chn) makes a selection like make-region but without creating a region.
make-selection follows snd's sync field, and applies to all snd's channels if chn is not specified. end defaults
to end of channel, beg defaults to 0, snd defaults to the currently selected sound.")
(add-chan-to-selection
(lambda (s0 s1 s c)
(set! (selection-member? s c) #t)
(set! (selection-position s c) (or s0 0))
(set! (selection-framples s c) (- (or (and (number? s1) (+ 1 s1)) (framples s c)) (or s0 0))))))
(lambda* (beg end snd chn)
(let ((current-sound (or snd (selected-sound) (car (sounds)))))
(if (not (sound? current-sound))
(error 'no-such-sound "make-selection can't find sound"))
(let ((current-sync (sync current-sound)))
(unselect-all)
(if (number? chn)
(add-chan-to-selection beg end snd chn)
(for-each
(lambda (s)
(if (or (eq? snd #t)
(equal? s current-sound)
(and (not (= current-sync 0))
(= current-sync (sync s))))
(do ((i 0 (+ 1 i)))
((= i (channels s)))
(add-chan-to-selection beg end s i))))
(sounds))))))))
(define with-temporary-selection
(let ((+documentation+ "(with-temporary-selection thunk beg dur snd chn) saves the current selection placement, makes a new selection \
of the data from sample beg to beg + dur in the given channel. It then calls thunk, and
restores the previous selection (if any). It returns whatever 'thunk' returned."))
(lambda (thunk beg dur snd chn)
(let ((seldata (and (selection?)
(car (selection-members)))))
(if (selection?)
(set! seldata (append seldata (list (selection-position) (selection-framples)))))
(make-selection beg (- (+ beg dur) 1) snd chn)
(let ((result (thunk)))
(if (not seldata)
(unselect-all)
(make-selection (caddr seldata)
(- (+ (caddr seldata) (cadddr seldata)) 1)
(car seldata)
(cadr seldata)))
result)))))
(define filter-selection-and-smooth
(let ((+documentation+ "(filter-selection-and-smooth ramp-dur flt order) applies 'flt' (via filter-sound) to \
the selection, the smooths the edges with a ramp whose duration is 'ramp-dur' (in seconds)"))
(lambda* (ramp-dur flt order)
(let ((temp-file (snd-tempnam)))
(save-selection temp-file)
(let ((selsnd (open-sound temp-file)))
(filter-sound flt (or order (length flt)) selsnd)
(let ((tmp-dur (samples->seconds (framples selsnd))))
make sure env - sound hits all chans
(env-sound (list 0 0 ramp-dur 1 (- tmp-dur ramp-dur) 1 tmp-dur 0) 0 #f 1.0 selsnd)
(save-sound selsnd)
(close-sound selsnd)
(env-selection (list 0 1 ramp-dur 0 (- tmp-dur ramp-dur) 0 tmp-dur 1))))
(mix temp-file (selection-position) #t #f #f #f #f)))))
( filter - selection - and - smooth .01 ( float - vector .25 .5 .5 .5 .25 ) )
|
3d1725e8bbd4fc1f98971210535a2f43514172c9dd4537b23714b80e3c0299e5 | kappamodeler/kappa | git_commit_info.ml | let git_commit_version,git_commit_release,git_commit_tag,git_commit_date = 4,329,10578,"2013-02-03 19:29:20" | null | https://raw.githubusercontent.com/kappamodeler/kappa/de63d1857898b1fc3b7f112f1027768b851ce14d/complx_rep/automatically_generated/git_commit_info.ml | ocaml | let git_commit_version,git_commit_release,git_commit_tag,git_commit_date = 4,329,10578,"2013-02-03 19:29:20" | |
62b2320366b00c40d78444824632b8d88e93f58c814face74260cae4d11b669c | hyperthunk/annotations | conditional.erl | %% -----------------------------------------------------------------------------
Copyright ( c ) 2002 - 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.
%% -----------------------------------------------------------------------------
-module(conditional).
-annotation('function').
-include_lib("annotations/include/types.hrl").
-compile(export_all).
%% examples
around_advice(#annotation{data={PropName, 'gt', Val}}, M, F, Inputs) ->
io:format("Checking for ~p in ~p~n", [PropName, Inputs]),
case lists:keyfind(PropName, 1, erlang:hd(Inputs)) of
false ->
false;
{PropName, GivenValue} ->
case GivenValue > Val of
false ->
false;
true ->
annotation:call_advised(M, F, Inputs)
end
end.
| null | https://raw.githubusercontent.com/hyperthunk/annotations/ac34bf92a7b369aae3a763dd6ff7c0e463230404/examples/around/src/conditional.erl | erlang | -----------------------------------------------------------------------------
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
examples | Copyright ( c ) 2002 - 2012 ( )
in the Software without restriction , including without limitation the rights
copies of the Software , and to permit persons to whom the Software is
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
-module(conditional).
-annotation('function').
-include_lib("annotations/include/types.hrl").
-compile(export_all).
around_advice(#annotation{data={PropName, 'gt', Val}}, M, F, Inputs) ->
io:format("Checking for ~p in ~p~n", [PropName, Inputs]),
case lists:keyfind(PropName, 1, erlang:hd(Inputs)) of
false ->
false;
{PropName, GivenValue} ->
case GivenValue > Val of
false ->
false;
true ->
annotation:call_advised(M, F, Inputs)
end
end.
|
875cf3732b3d6dd7b5133b1b0984d2d98eeb67015c24df95b867385b1c0057c7 | PrecursorApp/precursor | template.clj | (ns pc.views.blog.template)
;; To make a new post, copy this template to a new file, rename the
;; template fn below to something like your-post-name, then add
;; "your-post-name" to the end of slugs in pc.views.blog.
;; Whatever you set as your-post-name will be the slug after /blog/ in the url.
(defn template []
{:title nil ;; replace the nil with a string like "This is a title"
:blurb nil ;; replace the nil with a short string about this post
should be " " or " " , ask to add you to the list if you want to blog
:body (list
[:article
[:p "opening paragraph"]]
[:h3 "Heading"]
[:article
[:p "New paragraph"]]
[:figure [:img {:src "/some-image.png"}]])})
| null | https://raw.githubusercontent.com/PrecursorApp/precursor/30202e40365f6883c4767e423d6299f0d13dc528/src/pc/views/blog/template.clj | clojure | To make a new post, copy this template to a new file, rename the
template fn below to something like your-post-name, then add
"your-post-name" to the end of slugs in pc.views.blog.
Whatever you set as your-post-name will be the slug after /blog/ in the url.
replace the nil with a string like "This is a title"
replace the nil with a short string about this post | (ns pc.views.blog.template)
(defn template []
should be " " or " " , ask to add you to the list if you want to blog
:body (list
[:article
[:p "opening paragraph"]]
[:h3 "Heading"]
[:article
[:p "New paragraph"]]
[:figure [:img {:src "/some-image.png"}]])})
|
a5f953f0ad4568582693048df7c6d4b278e05e50cd15a64394815f29fd0fdff5 | kappelmann/eidi2_repetitorium_tum | ha1.ml | (* generate .mli with `ocamlc -i` *)
exception Invalid_input
let hello name = "Hello "^name^"!"
let rec fac n =
if n<0 then raise Invalid_input
else if n<=1 then n
else n * fac (n-1)
let rec fib n =
if n<0 then raise Invalid_input
else if n<=1 then n
else fib (n-1) + fib (n-2)
let rec even_sum n =
if n<0 then raise Invalid_input
else if n=0 then 0
else (if n mod 2 = 0 then n else 0) + even_sum (n-1);;
let is_empty xs = xs = []
let rec length = function [] -> 0 | _::xs -> 1 + length xs
let rec sum = function [] -> 0 | x::xs -> x + sum xs
| null | https://raw.githubusercontent.com/kappelmann/eidi2_repetitorium_tum/1d16bbc498487a85960e0d83152249eb13944611/2017/ocaml/basics/solutions/ha1.ml | ocaml | generate .mli with `ocamlc -i` |
exception Invalid_input
let hello name = "Hello "^name^"!"
let rec fac n =
if n<0 then raise Invalid_input
else if n<=1 then n
else n * fac (n-1)
let rec fib n =
if n<0 then raise Invalid_input
else if n<=1 then n
else fib (n-1) + fib (n-2)
let rec even_sum n =
if n<0 then raise Invalid_input
else if n=0 then 0
else (if n mod 2 = 0 then n else 0) + even_sum (n-1);;
let is_empty xs = xs = []
let rec length = function [] -> 0 | _::xs -> 1 + length xs
let rec sum = function [] -> 0 | x::xs -> x + sum xs
|
b6c629b7e729cdb401fc27affcb47ca25311b726f70990a0a1fd07bd62eb4b5f | wfnuser/sicp-solutions | e2-54.scm | (define (equal? a b)
(if (pair? a)
(if (pair? b)
(and (equal? (car a) (car b)) (equal? (cdr a) (cdr b)))
#f
)
(eq? a b)
)
)
(equal? '(1 2 3) '(1 2 3)) | null | https://raw.githubusercontent.com/wfnuser/sicp-solutions/2c94b28d8ee004dcbfe7311f866e5a346ee01d12/ch2/e2-54.scm | scheme | (define (equal? a b)
(if (pair? a)
(if (pair? b)
(and (equal? (car a) (car b)) (equal? (cdr a) (cdr b)))
#f
)
(eq? a b)
)
)
(equal? '(1 2 3) '(1 2 3)) | |
e02783e82184de5ed4fb87b12828a93571061622b92a5df92c5fae4a75e3c55b | hoytech/antiweb | convert.lisp | -*- Mode : LISP ; Syntax : COMMON - LISP ; Package : CL - PPCRE ; Base : 10 -*-
$ Header : /usr / cvs / hcsw / antiweb / bundled / cl - ppcre / convert.lisp , v 1.1 2008/04/26 02:40:56
;;; Here the parse tree is converted into its internal representation
;;; using REGEX objects. At the same time some optimizations are
;;; already applied.
Copyright ( c ) 2002 - 2007 , Dr. . 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 #:cl-ppcre)
;;; The flags that represent the "ism" modifiers are always kept
together in a three - element list . We use the following macros to
;;; access individual elements.
(defmacro case-insensitive-mode-p (flags)
"Accessor macro to extract the first flag out of a three-element flag list."
`(first ,flags))
(defmacro multi-line-mode-p (flags)
"Accessor macro to extract the second flag out of a three-element flag list."
`(second ,flags))
(defmacro single-line-mode-p (flags)
"Accessor macro to extract the third flag out of a three-element flag list."
`(third ,flags))
(defun set-flag (token)
(declare #.*standard-optimize-settings*)
(declare (special flags))
"Reads a flag token and sets or unsets the corresponding entry in
the special FLAGS list."
(case token
((:case-insensitive-p)
(setf (case-insensitive-mode-p flags) t))
((:case-sensitive-p)
(setf (case-insensitive-mode-p flags) nil))
((:multi-line-mode-p)
(setf (multi-line-mode-p flags) t))
((:not-multi-line-mode-p)
(setf (multi-line-mode-p flags) nil))
((:single-line-mode-p)
(setf (single-line-mode-p flags) t))
((:not-single-line-mode-p)
(setf (single-line-mode-p flags) nil))
(otherwise
(signal-ppcre-syntax-error "Unknown flag token ~A" token))))
(defun add-range-to-hash (hash from to)
(declare #.*standard-optimize-settings*)
(declare (special flags))
"Adds all characters from character FROM to character TO (inclusive)
to the char class hash HASH. Does the right thing with respect to
case-(in)sensitivity as specified by the special variable FLAGS."
(let ((from-code (char-code from))
(to-code (char-code to)))
(when (> from-code to-code)
(signal-ppcre-syntax-error "Invalid range from ~A to ~A in char-class"
from to))
(cond ((case-insensitive-mode-p flags)
(loop for code from from-code to to-code
for chr = (code-char code)
do (setf (gethash (char-upcase chr) hash) t
(gethash (char-downcase chr) hash) t)))
(t
(loop for code from from-code to to-code
do (setf (gethash (code-char code) hash) t))))
hash))
(defun convert-char-class-to-hash (list)
(declare #.*standard-optimize-settings*)
"Combines all items in LIST into one char class hash and returns it.
Items can be single characters, character ranges like \(:RANGE #\\A
#\\E), or special character classes like :DIGIT-CLASS. Does the right
thing with respect to case-\(in)sensitivity as specified by the
special variable FLAGS."
(loop with hash = (make-hash-table :size (ceiling (expt *regex-char-code-limit* (/ 1 4)))
:rehash-size (float (expt *regex-char-code-limit* (/ 1 4)))
:rehash-threshold #-genera 1.0 #+genera 0.99)
for item in list
if (characterp item)
;; treat a single character C like a range (:RANGE C C)
do (add-range-to-hash hash item item)
else if (symbolp item)
;; special character classes
do (setq hash
(case item
((:digit-class)
(merge-hash hash +digit-hash+))
((:non-digit-class)
(merge-inverted-hash hash +digit-hash+))
((:whitespace-char-class)
(merge-hash hash +whitespace-char-hash+))
((:non-whitespace-char-class)
(merge-inverted-hash hash +whitespace-char-hash+))
((:word-char-class)
(merge-hash hash +word-char-hash+))
((:non-word-char-class)
(merge-inverted-hash hash +word-char-hash+))
(otherwise
(signal-ppcre-syntax-error
"Unknown symbol ~A in character class"
item))))
else if (and (consp item)
(eq (car item) :range))
;; proper ranges
do (add-range-to-hash hash
(second item)
(third item))
else do (signal-ppcre-syntax-error "Unknown item ~A in char-class list"
item)
finally (return hash)))
(defun maybe-split-repetition (regex
greedyp
minimum
maximum
min-len
length
reg-seen)
(declare #.*standard-optimize-settings*)
(declare (type fixnum minimum)
(type (or fixnum null) maximum))
"Splits a REPETITION object into a constant and a varying part if
applicable, i.e. something like
a{3,} -> a{3}a*
The arguments to this function correspond to the REPETITION slots of
the same name."
;; note the usage of COPY-REGEX here; we can't use the same REGEX
;; object in both REPETITIONS because they will have different
;; offsets
(when maximum
(when (zerop maximum)
;; trivial case: don't repeat at all
(return-from maybe-split-repetition
(make-instance 'void)))
(when (= 1 minimum maximum)
;; another trivial case: "repeat" exactly once
(return-from maybe-split-repetition
regex)))
first set up the constant part of the repetition
;; maybe that's all we need
(let ((constant-repetition (if (plusp minimum)
(make-instance 'repetition
:regex (copy-regex regex)
:greedyp greedyp
:minimum minimum
:maximum minimum
:min-len min-len
:len length
:contains-register-p reg-seen)
;; don't create garbage if minimum is 0
nil)))
(when (and maximum
(= maximum minimum))
(return-from maybe-split-repetition
no varying part needed because min =
constant-repetition))
;; now construct the varying part
(let ((varying-repetition
(make-instance 'repetition
:regex regex
:greedyp greedyp
:minimum 0
:maximum (if maximum (- maximum minimum) nil)
:min-len min-len
:len length
:contains-register-p reg-seen)))
(cond ((zerop minimum)
;; min = 0, no constant part needed
varying-repetition)
((= 1 minimum)
min = 1 , constant part needs no REPETITION wrapped around
(make-instance 'seq
:elements (list (copy-regex regex)
varying-repetition)))
(t
;; general case
(make-instance 'seq
:elements (list constant-repetition
varying-repetition)))))))
;; During the conversion of the parse tree we keep track of the start
;; of the parse tree in the special variable STARTS-WITH which'll
;; either hold a STR object or an EVERYTHING object. The latter is the
;; case if the regex starts with ".*" which implicitly anchors the
;; regex at the start (perhaps modulo #\Newline).
(defun maybe-accumulate (str)
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p starts-with))
(declare (ftype (function (t) fixnum) len))
"Accumulate STR into the special variable STARTS-WITH if
ACCUMULATE-START-P (also special) is true and STARTS-WITH is either
NIL or a STR object of the same case mode. Always returns NIL."
(when accumulate-start-p
(etypecase starts-with
(str
STARTS - WITH already holds a STR , so we check if we can
;; concatenate
(cond ((eq (case-insensitive-p starts-with)
(case-insensitive-p str))
;; we modify STARTS-WITH in place
(setf (len starts-with)
(+ (len starts-with) (len str)))
note that we use SLOT - VALUE because the accessor
STR has a declared FTYPE which does n't fit here
(adjust-array (slot-value starts-with 'str)
(len starts-with)
:fill-pointer t)
(setf (subseq (slot-value starts-with 'str)
(- (len starts-with) (len str)))
(str str)
STR objects that are parts of STARTS - WITH
;; always have their SKIP slot set to true
;; because the SCAN function will take care of
;; them, i.e. the matcher can ignore them
(skip str) t))
(t (setq accumulate-start-p nil))))
(null
STARTS - WITH is still empty , so we create a new STR object
(setf starts-with
(make-instance 'str
:str ""
:case-insensitive-p (case-insensitive-p str))
INITIALIZE - INSTANCE will coerce the STR to a simple
;; string, so we have to fill it afterwards
(slot-value starts-with 'str)
(make-array (len str)
:initial-contents (str str)
:element-type 'character
:fill-pointer t
:adjustable t)
(len starts-with)
(len str)
;; see remark about SKIP above
(skip str) t))
(everything
;; STARTS-WITH already holds an EVERYTHING object - we can't
;; concatenate
(setq accumulate-start-p nil))))
nil)
(defun convert-aux (parse-tree)
(declare #.*standard-optimize-settings*)
(declare (special flags reg-num reg-names accumulate-start-p starts-with max-back-ref))
"Converts the parse tree PARSE-TREE into a REGEX object and returns it.
Will also
- split and optimize repetitions,
- accumulate strings or EVERYTHING objects into the special variable
STARTS-WITH,
- keep track of all registers seen in the special variable REG-NUM,
- keep track of all named registers seen in the special variable REG-NAMES
- keep track of the highest backreference seen in the special
variable MAX-BACK-REF,
- maintain and adher to the currently applicable modifiers in the special
variable FLAGS, and
- maybe even wash your car..."
(cond ((consp parse-tree)
(case (first parse-tree)
(: { < regex > } * )
((:sequence)
(cond ((cddr parse-tree)
;; this is essentially like
( MAPCAR ' CONVERT - AUX ( REST PARSE - TREE ) )
;; but we don't cons a new list
(loop for parse-tree-rest on (rest parse-tree)
while parse-tree-rest
do (setf (car parse-tree-rest)
(convert-aux (car parse-tree-rest))))
(make-instance 'seq
:elements (rest parse-tree)))
(t (convert-aux (second parse-tree)))))
;; (:GROUP {<regex>}*)
;; this is a syntactical construct equivalent to :SEQUENCE
;; intended to keep the effect of modifiers local
((:group)
make a local copy of FLAGS and shadow the global
;; value while we descend into the enclosed regexes
(let ((flags (copy-list flags)))
(declare (special flags))
(cond ((cddr parse-tree)
(loop for parse-tree-rest on (rest parse-tree)
while parse-tree-rest
do (setf (car parse-tree-rest)
(convert-aux (car parse-tree-rest))))
(make-instance 'seq
:elements (rest parse-tree)))
(t (convert-aux (second parse-tree))))))
(: { < regex > } * )
((:alternation)
;; we must stop accumulating objects into STARTS-WITH
;; once we reach an alternation
(setq accumulate-start-p nil)
(loop for parse-tree-rest on (rest parse-tree)
while parse-tree-rest
do (setf (car parse-tree-rest)
(convert-aux (car parse-tree-rest))))
(make-instance 'alternation
:choices (rest parse-tree)))
(: BRANCH < test > < regex > )
;; <test> must be look-ahead, look-behind or number;
if < regex > is an alternation it must have one or two
;; choices
((:branch)
(setq accumulate-start-p nil)
(let* ((test-candidate (second parse-tree))
(test (cond ((numberp test-candidate)
(when (zerop (the fixnum test-candidate))
(signal-ppcre-syntax-error
"Register 0 doesn't exist: ~S"
parse-tree))
(1- (the fixnum test-candidate)))
(t (convert-aux test-candidate))))
(alternations (convert-aux (third parse-tree))))
(when (and (not (numberp test))
(not (typep test 'lookahead))
(not (typep test 'lookbehind)))
(signal-ppcre-syntax-error
"Branch test must be look-ahead, look-behind or number: ~S"
parse-tree))
(typecase alternations
(alternation
(case (length (choices alternations))
((0)
(signal-ppcre-syntax-error "No choices in branch: ~S"
parse-tree))
((1)
(make-instance 'branch
:test test
:then-regex (first
(choices alternations))))
((2)
(make-instance 'branch
:test test
:then-regex (first
(choices alternations))
:else-regex (second
(choices alternations))))
(otherwise
(signal-ppcre-syntax-error
"Too much choices in branch: ~S"
parse-tree))))
(t
(make-instance 'branch
:test test
:then-regex alternations)))))
;; (:POSITIVE-LOOKAHEAD|:NEGATIVE-LOOKAHEAD <regex>)
((:positive-lookahead :negative-lookahead)
;; keep the effect of modifiers local to the enclosed
;; regex and stop accumulating into STARTS-WITH
(setq accumulate-start-p nil)
(let ((flags (copy-list flags)))
(declare (special flags))
(make-instance 'lookahead
:regex (convert-aux (second parse-tree))
:positivep (eq (first parse-tree)
:positive-lookahead))))
;; (:POSITIVE-LOOKBEHIND|:NEGATIVE-LOOKBEHIND <regex>)
((:positive-lookbehind :negative-lookbehind)
;; keep the effect of modifiers local to the enclosed
;; regex and stop accumulating into STARTS-WITH
(setq accumulate-start-p nil)
(let* ((flags (copy-list flags))
(regex (convert-aux (second parse-tree)))
(len (regex-length regex)))
(declare (special flags))
;; lookbehind assertions must be of fixed length
(unless len
(signal-ppcre-syntax-error
"Variable length look-behind not implemented (yet): ~S"
parse-tree))
(make-instance 'lookbehind
:regex regex
:positivep (eq (first parse-tree)
:positive-lookbehind)
:len len)))
;; (:GREEDY-REPETITION|:NON-GREEDY-REPETITION <min> <max> <regex>)
((:greedy-repetition :non-greedy-repetition)
;; remember the value of ACCUMULATE-START-P upon entering
(let ((local-accumulate-start-p accumulate-start-p))
(let ((minimum (second parse-tree))
(maximum (third parse-tree)))
(declare (type fixnum minimum))
(declare (type (or null fixnum) maximum))
(unless (and maximum
(= 1 minimum maximum))
;; set ACCUMULATE-START-P to NIL for the rest of
;; the conversion because we can't continue to
;; accumulate inside as well as after a proper
;; repetition
(setq accumulate-start-p nil))
(let* (reg-seen
(regex (convert-aux (fourth parse-tree)))
(min-len (regex-min-length regex))
(greedyp (eq (first parse-tree) :greedy-repetition))
(length (regex-length regex)))
;; note that this declaration already applies to
the call to CONVERT - AUX above
(declare (special reg-seen))
(when (and local-accumulate-start-p
(not starts-with)
(zerop minimum)
(not maximum))
;; if this repetition is (equivalent to) ".*"
;; and if we're at the start of the regex we
remember it for ADVANCE - FN ( see the SCAN
;; function)
(setq starts-with (everythingp regex)))
(if (or (not reg-seen)
(not greedyp)
(not length)
(zerop length)
(and maximum (= minimum maximum)))
;; the repetition doesn't enclose a register, or
;; it's not greedy, or we can't determine it's
( inner ) length , or the length is zero , or the
;; number of repetitions is fixed; in all of
;; these cases we don't bother to optimize
(maybe-split-repetition regex
greedyp
minimum
maximum
min-len
length
reg-seen)
;; otherwise we make a transformation that looks
;; roughly like one of
;; <regex>* -> (?:<regex'>*<regex>)?
;; <regex>+ -> <regex'>*<regex>
;; where the trick is that as much as possible
;; registers from <regex> are removed in
;; <regex'>
(let* (reg-seen ; new instance for REMOVE-REGISTERS
(remove-registers-p t)
(inner-regex (remove-registers regex))
(inner-repetition
;; this is the "<regex'>" part
(maybe-split-repetition inner-regex
;; always greedy
t
reduce minimum by 1
;; unless it's already 0
(if (zerop minimum)
0
(1- minimum))
reduce maximum by 1
;; unless it's NIL
(and maximum
(1- maximum))
min-len
length
reg-seen))
(inner-seq
;; this is the "<regex'>*<regex>" part
(make-instance 'seq
:elements (list inner-repetition
regex))))
;; note that this declaration already applies
;; to the call to REMOVE-REGISTERS above
(declare (special remove-registers-p reg-seen))
wrap INNER - SEQ with a greedy
;; {0,1}-repetition (i.e. "?") if necessary
(if (plusp minimum)
inner-seq
(maybe-split-repetition inner-seq
t
0
1
min-len
nil
t))))))))
;; (:REGISTER <regex>)
;; (:NAMED-REGISTER <name> <regex>)
((:register :named-register)
;; keep the effect of modifiers local to the enclosed
regex ; also , assign the current value of REG - NUM to
the corresponding slot of the REGISTER object and
;; increase this counter afterwards; for named register
update REG - NAMES and set the corresponding name slot
of the REGISTER object too
(let ((flags (copy-list flags))
(stored-reg-num reg-num)
(reg-name (when (eq (first parse-tree) :named-register)
(copy-seq (second parse-tree)))))
(declare (special flags reg-seen named-reg-seen))
(setq reg-seen t)
(when reg-name
(setq named-reg-seen t))
(incf (the fixnum reg-num))
(push reg-name
reg-names)
(make-instance 'register
:regex (convert-aux (if (eq (first parse-tree) :named-register)
(third parse-tree)
(second parse-tree)))
:num stored-reg-num
:name reg-name)))
;; (:FILTER <function> &optional <length>)
((:filter)
;; stop accumulating into STARTS-WITH
(setq accumulate-start-p nil)
(make-instance 'filter
:fn (second parse-tree)
:len (third parse-tree)))
(: STANDALONE < regex > )
((:standalone)
;; stop accumulating into STARTS-WITH
(setq accumulate-start-p nil)
;; keep the effect of modifiers local to the enclosed
;; regex
(let ((flags (copy-list flags)))
(declare (special flags))
(make-instance 'standalone
:regex (convert-aux (second parse-tree)))))
;; (:BACK-REFERENCE <number>)
;; (:BACK-REFERENCE <name>)
((:back-reference)
(locally (declare (special reg-names reg-num))
(let* ((backref-name (and (stringp (second parse-tree))
(second parse-tree)))
(referred-regs
(when backref-name
;; find which register corresponds to the given name
;; we have to deal with case where several registers share
;; the same name and collect their respective numbers
(loop
for name in reg-names
for reg-index from 0
when (string= name backref-name)
;; NOTE: REG-NAMES stores register names in reversed order
REG - NUM contains number of ( any ) registers seen so far
;; 1- will be done later
collect (- reg-num reg-index))))
;; store the register number for the simple case
(backref-number (or (first referred-regs)
(second parse-tree))))
(declare (type (or fixnum null) backref-number))
(when (or (not (typep backref-number 'fixnum))
(<= backref-number 0))
(signal-ppcre-syntax-error
"Illegal back-reference: ~S"
parse-tree))
;; stop accumulating into STARTS-WITH and increase
MAX - BACK - REF if necessary
(setq accumulate-start-p nil
max-back-ref (max (the fixnum max-back-ref)
backref-number))
(flet ((make-back-ref (backref-number)
(make-instance 'back-reference
;; we start counting from 0 internally
:num (1- backref-number)
:case-insensitive-p (case-insensitive-mode-p flags)
backref - name is NIL or string , safe to copy
:name (copy-seq backref-name))))
(cond
((cdr referred-regs)
;; several registers share the same name
;; we will try to match any of them, starting
with the most recent first
;; alternation is used to accomplish matching
(make-instance 'alternation
:choices (loop
for reg-index in referred-regs
collect (make-back-ref reg-index))))
simple case - backref corresponds to only one register
(t
(make-back-ref backref-number)))))))
;; (:REGEX <string>)
((:regex)
(let ((regex (second parse-tree)))
(convert-aux (parse-string regex))))
(: - CHAR - CLASS { < item > } * )
where item is one of
;; - a character
;; - a character range: (:RANGE <char1> <char2>)
;; - a special char class symbol like :DIGIT-CHAR-CLASS
((:char-class :inverted-char-class)
;; first create the hash-table and some auxiliary values
(let* (hash
hash-keys
(count most-positive-fixnum)
(item-list (rest parse-tree))
(invertedp (eq (first parse-tree) :inverted-char-class))
word-char-class-p)
(cond ((every (lambda (item) (eq item :word-char-class))
item-list)
treat " [ \\w ] " like " \\w "
(setq word-char-class-p t))
((every (lambda (item) (eq item :non-word-char-class))
item-list)
treat " [ \\W ] " like " \\W "
(setq word-char-class-p t)
(setq invertedp (not invertedp)))
(t
(setq hash (convert-char-class-to-hash item-list)
count (hash-table-count hash))
(when (<= count 2)
;; collect the hash-table keys into a list if
COUNT is smaller than 3
(setq hash-keys
(loop for chr being the hash-keys of hash
collect chr)))))
(cond ((and (not invertedp)
(= count 1))
convert one - element hash table into a STR
;; object and try to accumulate into
;; STARTS-WITH
(let ((str (make-instance 'str
:str (string
(first hash-keys))
:case-insensitive-p nil)))
(maybe-accumulate str)
str))
((and (not invertedp)
(= count 2)
(char-equal (first hash-keys) (second hash-keys)))
convert two - element hash table into a
;; case-insensitive STR object and try to
accumulate into STARTS - WITH if the two
;; characters are CHAR-EQUAL
(let ((str (make-instance 'str
:str (string
(first hash-keys))
:case-insensitive-p t)))
(maybe-accumulate str)
str))
(t
;; the general case; stop accumulating into STARTS-WITH
(setq accumulate-start-p nil)
(make-instance 'char-class
:hash hash
:case-insensitive-p
(case-insensitive-mode-p flags)
:invertedp invertedp
:word-char-class-p word-char-class-p)))))
(: { < flag > } * )
;; where flag is a modifier symbol like :CASE-INSENSITIVE-P
((:flags)
;; set/unset the flags corresponding to the symbols
following :
(mapc #'set-flag (rest parse-tree))
;; we're only interested in the side effect of
;; setting/unsetting the flags and turn this syntactical
;; construct into a VOID object which'll be optimized
;; away when creating the matcher
(make-instance 'void))
(otherwise
(signal-ppcre-syntax-error
"Unknown token ~A in parse-tree"
(first parse-tree)))))
((or (characterp parse-tree) (stringp parse-tree))
turn characters or strings into STR objects and try to
;; accumulate into STARTS-WITH
(let ((str (make-instance 'str
:str (string parse-tree)
:case-insensitive-p
(case-insensitive-mode-p flags))))
(maybe-accumulate str)
str))
(t
;; and now for the tokens which are symbols
(case parse-tree
((:void)
(make-instance 'void))
((:word-boundary)
(make-instance 'word-boundary :negatedp nil))
((:non-word-boundary)
(make-instance 'word-boundary :negatedp t))
;; the special character classes
((:digit-class
:non-digit-class
:word-char-class
:non-word-char-class
:whitespace-char-class
:non-whitespace-char-class)
;; stop accumulating into STARTS-WITH
(setq accumulate-start-p nil)
(make-instance 'char-class
use the constants defined in util.lisp
:hash (case parse-tree
((:digit-class
:non-digit-class)
+digit-hash+)
((:word-char-class
:non-word-char-class)
nil)
((:whitespace-char-class
:non-whitespace-char-class)
+whitespace-char-hash+))
;; this value doesn't really matter but
NIL should result in slightly faster
;; matchers
:case-insensitive-p nil
:invertedp (member parse-tree
'(:non-digit-class
:non-word-char-class
:non-whitespace-char-class)
:test #'eq)
:word-char-class-p (member parse-tree
'(:word-char-class
:non-word-char-class)
:test #'eq)))
((:start-anchor ; Perl's "^"
:end-anchor ; Perl's "$"
:modeless-end-anchor-no-newline
; Perl's "\z"
:modeless-start-anchor ; Perl's "\A"
:modeless-end-anchor) ; Perl's "\Z"
(make-instance 'anchor
:startp (member parse-tree
'(:start-anchor
:modeless-start-anchor)
:test #'eq)
;; set this value according to the
current settings of ( unless it 's
;; a modeless anchor)
:multi-line-p
(and (multi-line-mode-p flags)
(not (member parse-tree
'(:modeless-start-anchor
:modeless-end-anchor
:modeless-end-anchor-no-newline)
:test #'eq)))
:no-newline-p
(eq parse-tree
:modeless-end-anchor-no-newline)))
((:everything)
stop accumulating into STARTS - WITHS
(setq accumulate-start-p nil)
(make-instance 'everything
:single-line-p (single-line-mode-p flags)))
special tokens corresponding to 's " ism " modifiers
((:case-insensitive-p
:case-sensitive-p
:multi-line-mode-p
:not-multi-line-mode-p
:single-line-mode-p
:not-single-line-mode-p)
;; we're only interested in the side effect of
;; setting/unsetting the flags and turn these tokens
;; into VOID objects which'll be optimized away when
;; creating the matcher
(set-flag parse-tree)
(make-instance 'void))
(otherwise
(let ((translation (and (symbolp parse-tree)
(parse-tree-synonym parse-tree))))
(if translation
(convert-aux (copy-tree translation))
(signal-ppcre-syntax-error "Unknown token ~A in parse-tree"
parse-tree))))))))
(defun convert (parse-tree)
(declare #.*standard-optimize-settings*)
"Converts the parse tree PARSE-TREE into an equivalent REGEX object
and returns three values: the REGEX object, the number of registers
seen and an object the regex starts with which is either a STR object
or an EVERYTHING object (if the regex starts with something like
\".*\") or NIL."
;; this function basically just initializes the special variables
and then calls CONVERT - AUX to do all the work
(let* ((flags (list nil nil nil))
(reg-num 0)
reg-names
named-reg-seen
(accumulate-start-p t)
starts-with
(max-back-ref 0)
(converted-parse-tree (convert-aux parse-tree)))
(declare (special flags reg-num reg-names named-reg-seen
accumulate-start-p starts-with max-back-ref))
;; make sure we don't reference registers which aren't there
(when (> (the fixnum max-back-ref)
(the fixnum reg-num))
(signal-ppcre-syntax-error
"Backreference to register ~A which has not been defined"
max-back-ref))
(when (typep starts-with 'str)
(setf (slot-value starts-with 'str)
(coerce (slot-value starts-with 'str) 'simple-string)))
(values converted-parse-tree reg-num starts-with
;; we can't simply use *ALLOW-NAMED-REGISTERS*
;; since parse-tree syntax ignores it
(when named-reg-seen
(nreverse reg-names)))))
| null | https://raw.githubusercontent.com/hoytech/antiweb/53c38f78ea01f04f6d1a1ecdca5c012e7a9ae4bb/bundled/cl-ppcre/convert.lisp | lisp | Syntax : COMMON - LISP ; Package : CL - PPCRE ; Base : 10 -*-
Here the parse tree is converted into its internal representation
using REGEX objects. At the same time some optimizations are
already applied.
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.
The flags that represent the "ism" modifiers are always kept
access individual elements.
treat a single character C like a range (:RANGE C C)
special character classes
proper ranges
note the usage of COPY-REGEX here; we can't use the same REGEX
object in both REPETITIONS because they will have different
offsets
trivial case: don't repeat at all
another trivial case: "repeat" exactly once
maybe that's all we need
don't create garbage if minimum is 0
now construct the varying part
min = 0, no constant part needed
general case
During the conversion of the parse tree we keep track of the start
of the parse tree in the special variable STARTS-WITH which'll
either hold a STR object or an EVERYTHING object. The latter is the
case if the regex starts with ".*" which implicitly anchors the
regex at the start (perhaps modulo #\Newline).
concatenate
we modify STARTS-WITH in place
always have their SKIP slot set to true
because the SCAN function will take care of
them, i.e. the matcher can ignore them
string, so we have to fill it afterwards
see remark about SKIP above
STARTS-WITH already holds an EVERYTHING object - we can't
concatenate
this is essentially like
but we don't cons a new list
(:GROUP {<regex>}*)
this is a syntactical construct equivalent to :SEQUENCE
intended to keep the effect of modifiers local
value while we descend into the enclosed regexes
we must stop accumulating objects into STARTS-WITH
once we reach an alternation
<test> must be look-ahead, look-behind or number;
choices
(:POSITIVE-LOOKAHEAD|:NEGATIVE-LOOKAHEAD <regex>)
keep the effect of modifiers local to the enclosed
regex and stop accumulating into STARTS-WITH
(:POSITIVE-LOOKBEHIND|:NEGATIVE-LOOKBEHIND <regex>)
keep the effect of modifiers local to the enclosed
regex and stop accumulating into STARTS-WITH
lookbehind assertions must be of fixed length
(:GREEDY-REPETITION|:NON-GREEDY-REPETITION <min> <max> <regex>)
remember the value of ACCUMULATE-START-P upon entering
set ACCUMULATE-START-P to NIL for the rest of
the conversion because we can't continue to
accumulate inside as well as after a proper
repetition
note that this declaration already applies to
if this repetition is (equivalent to) ".*"
and if we're at the start of the regex we
function)
the repetition doesn't enclose a register, or
it's not greedy, or we can't determine it's
number of repetitions is fixed; in all of
these cases we don't bother to optimize
otherwise we make a transformation that looks
roughly like one of
<regex>* -> (?:<regex'>*<regex>)?
<regex>+ -> <regex'>*<regex>
where the trick is that as much as possible
registers from <regex> are removed in
<regex'>
new instance for REMOVE-REGISTERS
this is the "<regex'>" part
always greedy
unless it's already 0
unless it's NIL
this is the "<regex'>*<regex>" part
note that this declaration already applies
to the call to REMOVE-REGISTERS above
{0,1}-repetition (i.e. "?") if necessary
(:REGISTER <regex>)
(:NAMED-REGISTER <name> <regex>)
keep the effect of modifiers local to the enclosed
also , assign the current value of REG - NUM to
increase this counter afterwards; for named register
(:FILTER <function> &optional <length>)
stop accumulating into STARTS-WITH
stop accumulating into STARTS-WITH
keep the effect of modifiers local to the enclosed
regex
(:BACK-REFERENCE <number>)
(:BACK-REFERENCE <name>)
find which register corresponds to the given name
we have to deal with case where several registers share
the same name and collect their respective numbers
NOTE: REG-NAMES stores register names in reversed order
1- will be done later
store the register number for the simple case
stop accumulating into STARTS-WITH and increase
we start counting from 0 internally
several registers share the same name
we will try to match any of them, starting
alternation is used to accomplish matching
(:REGEX <string>)
- a character
- a character range: (:RANGE <char1> <char2>)
- a special char class symbol like :DIGIT-CHAR-CLASS
first create the hash-table and some auxiliary values
collect the hash-table keys into a list if
object and try to accumulate into
STARTS-WITH
case-insensitive STR object and try to
characters are CHAR-EQUAL
the general case; stop accumulating into STARTS-WITH
where flag is a modifier symbol like :CASE-INSENSITIVE-P
set/unset the flags corresponding to the symbols
we're only interested in the side effect of
setting/unsetting the flags and turn this syntactical
construct into a VOID object which'll be optimized
away when creating the matcher
accumulate into STARTS-WITH
and now for the tokens which are symbols
the special character classes
stop accumulating into STARTS-WITH
this value doesn't really matter but
matchers
Perl's "^"
Perl's "$"
Perl's "\z"
Perl's "\A"
Perl's "\Z"
set this value according to the
a modeless anchor)
we're only interested in the side effect of
setting/unsetting the flags and turn these tokens
into VOID objects which'll be optimized away when
creating the matcher
this function basically just initializes the special variables
make sure we don't reference registers which aren't there
we can't simply use *ALLOW-NAMED-REGISTERS*
since parse-tree syntax ignores it | $ Header : /usr / cvs / hcsw / antiweb / bundled / cl - ppcre / convert.lisp , v 1.1 2008/04/26 02:40:56
Copyright ( c ) 2002 - 2007 , Dr. . All rights reserved .
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
(in-package #:cl-ppcre)
together in a three - element list . We use the following macros to
(defmacro case-insensitive-mode-p (flags)
"Accessor macro to extract the first flag out of a three-element flag list."
`(first ,flags))
(defmacro multi-line-mode-p (flags)
"Accessor macro to extract the second flag out of a three-element flag list."
`(second ,flags))
(defmacro single-line-mode-p (flags)
"Accessor macro to extract the third flag out of a three-element flag list."
`(third ,flags))
(defun set-flag (token)
(declare #.*standard-optimize-settings*)
(declare (special flags))
"Reads a flag token and sets or unsets the corresponding entry in
the special FLAGS list."
(case token
((:case-insensitive-p)
(setf (case-insensitive-mode-p flags) t))
((:case-sensitive-p)
(setf (case-insensitive-mode-p flags) nil))
((:multi-line-mode-p)
(setf (multi-line-mode-p flags) t))
((:not-multi-line-mode-p)
(setf (multi-line-mode-p flags) nil))
((:single-line-mode-p)
(setf (single-line-mode-p flags) t))
((:not-single-line-mode-p)
(setf (single-line-mode-p flags) nil))
(otherwise
(signal-ppcre-syntax-error "Unknown flag token ~A" token))))
(defun add-range-to-hash (hash from to)
(declare #.*standard-optimize-settings*)
(declare (special flags))
"Adds all characters from character FROM to character TO (inclusive)
to the char class hash HASH. Does the right thing with respect to
case-(in)sensitivity as specified by the special variable FLAGS."
(let ((from-code (char-code from))
(to-code (char-code to)))
(when (> from-code to-code)
(signal-ppcre-syntax-error "Invalid range from ~A to ~A in char-class"
from to))
(cond ((case-insensitive-mode-p flags)
(loop for code from from-code to to-code
for chr = (code-char code)
do (setf (gethash (char-upcase chr) hash) t
(gethash (char-downcase chr) hash) t)))
(t
(loop for code from from-code to to-code
do (setf (gethash (code-char code) hash) t))))
hash))
(defun convert-char-class-to-hash (list)
(declare #.*standard-optimize-settings*)
"Combines all items in LIST into one char class hash and returns it.
Items can be single characters, character ranges like \(:RANGE #\\A
#\\E), or special character classes like :DIGIT-CLASS. Does the right
thing with respect to case-\(in)sensitivity as specified by the
special variable FLAGS."
(loop with hash = (make-hash-table :size (ceiling (expt *regex-char-code-limit* (/ 1 4)))
:rehash-size (float (expt *regex-char-code-limit* (/ 1 4)))
:rehash-threshold #-genera 1.0 #+genera 0.99)
for item in list
if (characterp item)
do (add-range-to-hash hash item item)
else if (symbolp item)
do (setq hash
(case item
((:digit-class)
(merge-hash hash +digit-hash+))
((:non-digit-class)
(merge-inverted-hash hash +digit-hash+))
((:whitespace-char-class)
(merge-hash hash +whitespace-char-hash+))
((:non-whitespace-char-class)
(merge-inverted-hash hash +whitespace-char-hash+))
((:word-char-class)
(merge-hash hash +word-char-hash+))
((:non-word-char-class)
(merge-inverted-hash hash +word-char-hash+))
(otherwise
(signal-ppcre-syntax-error
"Unknown symbol ~A in character class"
item))))
else if (and (consp item)
(eq (car item) :range))
do (add-range-to-hash hash
(second item)
(third item))
else do (signal-ppcre-syntax-error "Unknown item ~A in char-class list"
item)
finally (return hash)))
(defun maybe-split-repetition (regex
greedyp
minimum
maximum
min-len
length
reg-seen)
(declare #.*standard-optimize-settings*)
(declare (type fixnum minimum)
(type (or fixnum null) maximum))
"Splits a REPETITION object into a constant and a varying part if
applicable, i.e. something like
a{3,} -> a{3}a*
The arguments to this function correspond to the REPETITION slots of
the same name."
(when maximum
(when (zerop maximum)
(return-from maybe-split-repetition
(make-instance 'void)))
(when (= 1 minimum maximum)
(return-from maybe-split-repetition
regex)))
first set up the constant part of the repetition
(let ((constant-repetition (if (plusp minimum)
(make-instance 'repetition
:regex (copy-regex regex)
:greedyp greedyp
:minimum minimum
:maximum minimum
:min-len min-len
:len length
:contains-register-p reg-seen)
nil)))
(when (and maximum
(= maximum minimum))
(return-from maybe-split-repetition
no varying part needed because min =
constant-repetition))
(let ((varying-repetition
(make-instance 'repetition
:regex regex
:greedyp greedyp
:minimum 0
:maximum (if maximum (- maximum minimum) nil)
:min-len min-len
:len length
:contains-register-p reg-seen)))
(cond ((zerop minimum)
varying-repetition)
((= 1 minimum)
min = 1 , constant part needs no REPETITION wrapped around
(make-instance 'seq
:elements (list (copy-regex regex)
varying-repetition)))
(t
(make-instance 'seq
:elements (list constant-repetition
varying-repetition)))))))
(defun maybe-accumulate (str)
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p starts-with))
(declare (ftype (function (t) fixnum) len))
"Accumulate STR into the special variable STARTS-WITH if
ACCUMULATE-START-P (also special) is true and STARTS-WITH is either
NIL or a STR object of the same case mode. Always returns NIL."
(when accumulate-start-p
(etypecase starts-with
(str
STARTS - WITH already holds a STR , so we check if we can
(cond ((eq (case-insensitive-p starts-with)
(case-insensitive-p str))
(setf (len starts-with)
(+ (len starts-with) (len str)))
note that we use SLOT - VALUE because the accessor
STR has a declared FTYPE which does n't fit here
(adjust-array (slot-value starts-with 'str)
(len starts-with)
:fill-pointer t)
(setf (subseq (slot-value starts-with 'str)
(- (len starts-with) (len str)))
(str str)
STR objects that are parts of STARTS - WITH
(skip str) t))
(t (setq accumulate-start-p nil))))
(null
STARTS - WITH is still empty , so we create a new STR object
(setf starts-with
(make-instance 'str
:str ""
:case-insensitive-p (case-insensitive-p str))
INITIALIZE - INSTANCE will coerce the STR to a simple
(slot-value starts-with 'str)
(make-array (len str)
:initial-contents (str str)
:element-type 'character
:fill-pointer t
:adjustable t)
(len starts-with)
(len str)
(skip str) t))
(everything
(setq accumulate-start-p nil))))
nil)
(defun convert-aux (parse-tree)
(declare #.*standard-optimize-settings*)
(declare (special flags reg-num reg-names accumulate-start-p starts-with max-back-ref))
"Converts the parse tree PARSE-TREE into a REGEX object and returns it.
Will also
- split and optimize repetitions,
- accumulate strings or EVERYTHING objects into the special variable
STARTS-WITH,
- keep track of all registers seen in the special variable REG-NUM,
- keep track of all named registers seen in the special variable REG-NAMES
- keep track of the highest backreference seen in the special
variable MAX-BACK-REF,
- maintain and adher to the currently applicable modifiers in the special
variable FLAGS, and
- maybe even wash your car..."
(cond ((consp parse-tree)
(case (first parse-tree)
(: { < regex > } * )
((:sequence)
(cond ((cddr parse-tree)
( MAPCAR ' CONVERT - AUX ( REST PARSE - TREE ) )
(loop for parse-tree-rest on (rest parse-tree)
while parse-tree-rest
do (setf (car parse-tree-rest)
(convert-aux (car parse-tree-rest))))
(make-instance 'seq
:elements (rest parse-tree)))
(t (convert-aux (second parse-tree)))))
((:group)
make a local copy of FLAGS and shadow the global
(let ((flags (copy-list flags)))
(declare (special flags))
(cond ((cddr parse-tree)
(loop for parse-tree-rest on (rest parse-tree)
while parse-tree-rest
do (setf (car parse-tree-rest)
(convert-aux (car parse-tree-rest))))
(make-instance 'seq
:elements (rest parse-tree)))
(t (convert-aux (second parse-tree))))))
(: { < regex > } * )
((:alternation)
(setq accumulate-start-p nil)
(loop for parse-tree-rest on (rest parse-tree)
while parse-tree-rest
do (setf (car parse-tree-rest)
(convert-aux (car parse-tree-rest))))
(make-instance 'alternation
:choices (rest parse-tree)))
(: BRANCH < test > < regex > )
if < regex > is an alternation it must have one or two
((:branch)
(setq accumulate-start-p nil)
(let* ((test-candidate (second parse-tree))
(test (cond ((numberp test-candidate)
(when (zerop (the fixnum test-candidate))
(signal-ppcre-syntax-error
"Register 0 doesn't exist: ~S"
parse-tree))
(1- (the fixnum test-candidate)))
(t (convert-aux test-candidate))))
(alternations (convert-aux (third parse-tree))))
(when (and (not (numberp test))
(not (typep test 'lookahead))
(not (typep test 'lookbehind)))
(signal-ppcre-syntax-error
"Branch test must be look-ahead, look-behind or number: ~S"
parse-tree))
(typecase alternations
(alternation
(case (length (choices alternations))
((0)
(signal-ppcre-syntax-error "No choices in branch: ~S"
parse-tree))
((1)
(make-instance 'branch
:test test
:then-regex (first
(choices alternations))))
((2)
(make-instance 'branch
:test test
:then-regex (first
(choices alternations))
:else-regex (second
(choices alternations))))
(otherwise
(signal-ppcre-syntax-error
"Too much choices in branch: ~S"
parse-tree))))
(t
(make-instance 'branch
:test test
:then-regex alternations)))))
((:positive-lookahead :negative-lookahead)
(setq accumulate-start-p nil)
(let ((flags (copy-list flags)))
(declare (special flags))
(make-instance 'lookahead
:regex (convert-aux (second parse-tree))
:positivep (eq (first parse-tree)
:positive-lookahead))))
((:positive-lookbehind :negative-lookbehind)
(setq accumulate-start-p nil)
(let* ((flags (copy-list flags))
(regex (convert-aux (second parse-tree)))
(len (regex-length regex)))
(declare (special flags))
(unless len
(signal-ppcre-syntax-error
"Variable length look-behind not implemented (yet): ~S"
parse-tree))
(make-instance 'lookbehind
:regex regex
:positivep (eq (first parse-tree)
:positive-lookbehind)
:len len)))
((:greedy-repetition :non-greedy-repetition)
(let ((local-accumulate-start-p accumulate-start-p))
(let ((minimum (second parse-tree))
(maximum (third parse-tree)))
(declare (type fixnum minimum))
(declare (type (or null fixnum) maximum))
(unless (and maximum
(= 1 minimum maximum))
(setq accumulate-start-p nil))
(let* (reg-seen
(regex (convert-aux (fourth parse-tree)))
(min-len (regex-min-length regex))
(greedyp (eq (first parse-tree) :greedy-repetition))
(length (regex-length regex)))
the call to CONVERT - AUX above
(declare (special reg-seen))
(when (and local-accumulate-start-p
(not starts-with)
(zerop minimum)
(not maximum))
remember it for ADVANCE - FN ( see the SCAN
(setq starts-with (everythingp regex)))
(if (or (not reg-seen)
(not greedyp)
(not length)
(zerop length)
(and maximum (= minimum maximum)))
( inner ) length , or the length is zero , or the
(maybe-split-repetition regex
greedyp
minimum
maximum
min-len
length
reg-seen)
(remove-registers-p t)
(inner-regex (remove-registers regex))
(inner-repetition
(maybe-split-repetition inner-regex
t
reduce minimum by 1
(if (zerop minimum)
0
(1- minimum))
reduce maximum by 1
(and maximum
(1- maximum))
min-len
length
reg-seen))
(inner-seq
(make-instance 'seq
:elements (list inner-repetition
regex))))
(declare (special remove-registers-p reg-seen))
wrap INNER - SEQ with a greedy
(if (plusp minimum)
inner-seq
(maybe-split-repetition inner-seq
t
0
1
min-len
nil
t))))))))
((:register :named-register)
the corresponding slot of the REGISTER object and
update REG - NAMES and set the corresponding name slot
of the REGISTER object too
(let ((flags (copy-list flags))
(stored-reg-num reg-num)
(reg-name (when (eq (first parse-tree) :named-register)
(copy-seq (second parse-tree)))))
(declare (special flags reg-seen named-reg-seen))
(setq reg-seen t)
(when reg-name
(setq named-reg-seen t))
(incf (the fixnum reg-num))
(push reg-name
reg-names)
(make-instance 'register
:regex (convert-aux (if (eq (first parse-tree) :named-register)
(third parse-tree)
(second parse-tree)))
:num stored-reg-num
:name reg-name)))
((:filter)
(setq accumulate-start-p nil)
(make-instance 'filter
:fn (second parse-tree)
:len (third parse-tree)))
(: STANDALONE < regex > )
((:standalone)
(setq accumulate-start-p nil)
(let ((flags (copy-list flags)))
(declare (special flags))
(make-instance 'standalone
:regex (convert-aux (second parse-tree)))))
((:back-reference)
(locally (declare (special reg-names reg-num))
(let* ((backref-name (and (stringp (second parse-tree))
(second parse-tree)))
(referred-regs
(when backref-name
(loop
for name in reg-names
for reg-index from 0
when (string= name backref-name)
REG - NUM contains number of ( any ) registers seen so far
collect (- reg-num reg-index))))
(backref-number (or (first referred-regs)
(second parse-tree))))
(declare (type (or fixnum null) backref-number))
(when (or (not (typep backref-number 'fixnum))
(<= backref-number 0))
(signal-ppcre-syntax-error
"Illegal back-reference: ~S"
parse-tree))
MAX - BACK - REF if necessary
(setq accumulate-start-p nil
max-back-ref (max (the fixnum max-back-ref)
backref-number))
(flet ((make-back-ref (backref-number)
(make-instance 'back-reference
:num (1- backref-number)
:case-insensitive-p (case-insensitive-mode-p flags)
backref - name is NIL or string , safe to copy
:name (copy-seq backref-name))))
(cond
((cdr referred-regs)
with the most recent first
(make-instance 'alternation
:choices (loop
for reg-index in referred-regs
collect (make-back-ref reg-index))))
simple case - backref corresponds to only one register
(t
(make-back-ref backref-number)))))))
((:regex)
(let ((regex (second parse-tree)))
(convert-aux (parse-string regex))))
(: - CHAR - CLASS { < item > } * )
where item is one of
((:char-class :inverted-char-class)
(let* (hash
hash-keys
(count most-positive-fixnum)
(item-list (rest parse-tree))
(invertedp (eq (first parse-tree) :inverted-char-class))
word-char-class-p)
(cond ((every (lambda (item) (eq item :word-char-class))
item-list)
treat " [ \\w ] " like " \\w "
(setq word-char-class-p t))
((every (lambda (item) (eq item :non-word-char-class))
item-list)
treat " [ \\W ] " like " \\W "
(setq word-char-class-p t)
(setq invertedp (not invertedp)))
(t
(setq hash (convert-char-class-to-hash item-list)
count (hash-table-count hash))
(when (<= count 2)
COUNT is smaller than 3
(setq hash-keys
(loop for chr being the hash-keys of hash
collect chr)))))
(cond ((and (not invertedp)
(= count 1))
convert one - element hash table into a STR
(let ((str (make-instance 'str
:str (string
(first hash-keys))
:case-insensitive-p nil)))
(maybe-accumulate str)
str))
((and (not invertedp)
(= count 2)
(char-equal (first hash-keys) (second hash-keys)))
convert two - element hash table into a
accumulate into STARTS - WITH if the two
(let ((str (make-instance 'str
:str (string
(first hash-keys))
:case-insensitive-p t)))
(maybe-accumulate str)
str))
(t
(setq accumulate-start-p nil)
(make-instance 'char-class
:hash hash
:case-insensitive-p
(case-insensitive-mode-p flags)
:invertedp invertedp
:word-char-class-p word-char-class-p)))))
(: { < flag > } * )
((:flags)
following :
(mapc #'set-flag (rest parse-tree))
(make-instance 'void))
(otherwise
(signal-ppcre-syntax-error
"Unknown token ~A in parse-tree"
(first parse-tree)))))
((or (characterp parse-tree) (stringp parse-tree))
turn characters or strings into STR objects and try to
(let ((str (make-instance 'str
:str (string parse-tree)
:case-insensitive-p
(case-insensitive-mode-p flags))))
(maybe-accumulate str)
str))
(t
(case parse-tree
((:void)
(make-instance 'void))
((:word-boundary)
(make-instance 'word-boundary :negatedp nil))
((:non-word-boundary)
(make-instance 'word-boundary :negatedp t))
((:digit-class
:non-digit-class
:word-char-class
:non-word-char-class
:whitespace-char-class
:non-whitespace-char-class)
(setq accumulate-start-p nil)
(make-instance 'char-class
use the constants defined in util.lisp
:hash (case parse-tree
((:digit-class
:non-digit-class)
+digit-hash+)
((:word-char-class
:non-word-char-class)
nil)
((:whitespace-char-class
:non-whitespace-char-class)
+whitespace-char-hash+))
NIL should result in slightly faster
:case-insensitive-p nil
:invertedp (member parse-tree
'(:non-digit-class
:non-word-char-class
:non-whitespace-char-class)
:test #'eq)
:word-char-class-p (member parse-tree
'(:word-char-class
:non-word-char-class)
:test #'eq)))
:modeless-end-anchor-no-newline
(make-instance 'anchor
:startp (member parse-tree
'(:start-anchor
:modeless-start-anchor)
:test #'eq)
current settings of ( unless it 's
:multi-line-p
(and (multi-line-mode-p flags)
(not (member parse-tree
'(:modeless-start-anchor
:modeless-end-anchor
:modeless-end-anchor-no-newline)
:test #'eq)))
:no-newline-p
(eq parse-tree
:modeless-end-anchor-no-newline)))
((:everything)
stop accumulating into STARTS - WITHS
(setq accumulate-start-p nil)
(make-instance 'everything
:single-line-p (single-line-mode-p flags)))
special tokens corresponding to 's " ism " modifiers
((:case-insensitive-p
:case-sensitive-p
:multi-line-mode-p
:not-multi-line-mode-p
:single-line-mode-p
:not-single-line-mode-p)
(set-flag parse-tree)
(make-instance 'void))
(otherwise
(let ((translation (and (symbolp parse-tree)
(parse-tree-synonym parse-tree))))
(if translation
(convert-aux (copy-tree translation))
(signal-ppcre-syntax-error "Unknown token ~A in parse-tree"
parse-tree))))))))
(defun convert (parse-tree)
(declare #.*standard-optimize-settings*)
"Converts the parse tree PARSE-TREE into an equivalent REGEX object
and returns three values: the REGEX object, the number of registers
seen and an object the regex starts with which is either a STR object
or an EVERYTHING object (if the regex starts with something like
\".*\") or NIL."
and then calls CONVERT - AUX to do all the work
(let* ((flags (list nil nil nil))
(reg-num 0)
reg-names
named-reg-seen
(accumulate-start-p t)
starts-with
(max-back-ref 0)
(converted-parse-tree (convert-aux parse-tree)))
(declare (special flags reg-num reg-names named-reg-seen
accumulate-start-p starts-with max-back-ref))
(when (> (the fixnum max-back-ref)
(the fixnum reg-num))
(signal-ppcre-syntax-error
"Backreference to register ~A which has not been defined"
max-back-ref))
(when (typep starts-with 'str)
(setf (slot-value starts-with 'str)
(coerce (slot-value starts-with 'str) 'simple-string)))
(values converted-parse-tree reg-num starts-with
(when named-reg-seen
(nreverse reg-names)))))
|
8cf5ab47d1780d025cbca60c0a18236696b4cb87352bfb67503d68b8bda01057 | ocaml-flambda/ocaml-jst | iarray_comprehensions_require_immutable_arrays.ml | TEST
flags = " -extension comprehensions_experimental "
ocamlc_byte_exit_status = " 2 "
* setup - ocamlc.byte - build - env
* * ocamlc.byte
* * * check - ocamlc.byte - output
flags = "-extension comprehensions_experimental"
ocamlc_byte_exit_status = "2"
* setup-ocamlc.byte-build-env
** ocamlc.byte
*** check-ocamlc.byte-output
*)
[:x for x = 1 to 10:];;
| null | https://raw.githubusercontent.com/ocaml-flambda/ocaml-jst/b0a649516b33b83b7290c6fa5d7cb4c8c343df8c/testsuite/tests/comprehensions/iarray_comprehensions_require_immutable_arrays.ml | ocaml | TEST
flags = " -extension comprehensions_experimental "
ocamlc_byte_exit_status = " 2 "
* setup - ocamlc.byte - build - env
* * ocamlc.byte
* * * check - ocamlc.byte - output
flags = "-extension comprehensions_experimental"
ocamlc_byte_exit_status = "2"
* setup-ocamlc.byte-build-env
** ocamlc.byte
*** check-ocamlc.byte-output
*)
[:x for x = 1 to 10:];;
| |
112ff000c89cee09d2ec349e9422604bdcc5a619ade4c304c409cc4ff9f63605 | daveyarwood/ezzmq | context.clj | (ns ezzmq.context
(:require [clojure.set :as set]
[wall.hack])
(:import [org.zeromq ZMQ ZMQ$Context ZContext]))
(def ^:dynamic *context* nil)
(def ^:dynamic *context-type* :zcontext)
(defn context
"Returns a new ZMQ context."
[]
(case *context-type*
:zcontext (ZContext. 1)
:zmq.context (ZMQ/context 1)
(throw (Exception. (format "Invalid context type: %s" *context-type*)))))
(defprotocol Destructible
(destroy-context! [ctx]))
(extend-protocol Destructible
ZContext
(destroy-context! [ctx] (.destroy ctx))
ZMQ$Context
(destroy-context! [context]
; ZMQ$Contexts don't automatically close their sockets when you terminate
; them; they block until you do it manually.
;
The array of sockets is hidden inside of an inner instance , and both
of these fields are private , so we have to use wallhaxx to get to them .
(let [ctx (wall.hack/field org.zeromq.ZMQ$Context :ctx context)
sockets (wall.hack/field zmq.Ctx :sockets ctx)]
(doseq [socket sockets]
(doto socket
(.setSocketOpt zmq.ZMQ/ZMQ_LINGER (int 0))
(.close))))
(.term context)))
(def ^:dynamic *before-shutdown-fns* {})
(def ^:dynamic *after-shutdown-fns* {})
(def ^:dynamic *shutting-down* #{})
(defmacro before-shutdown
[& body]
`(alter-var-root #'*before-shutdown-fns*
update *context* conj (fn [] ~@body)))
(defmacro after-shutdown
[& body]
`(alter-var-root #'*after-shutdown-fns*
update *context* conj (fn [] ~@body)))
(defn init-context!
[ctx]
(alter-var-root #'*before-shutdown-fns* assoc ctx [])
(alter-var-root #'*after-shutdown-fns* assoc ctx []))
(defn shut-down-context!
[ctx]
(when-not (*shutting-down* ctx)
(do
(alter-var-root #'*shutting-down* conj ctx)
(let [before-fns (get *before-shutdown-fns* ctx [])
after-fns (get *after-shutdown-fns* ctx [])]
(doseq [f before-fns] (f))
(destroy-context! ctx)
(doseq [f after-fns] (f)))
(alter-var-root #'*before-shutdown-fns* dissoc ctx)
(alter-var-root #'*after-shutdown-fns* dissoc ctx)
(alter-var-root #'*shutting-down* disj ctx))))
; Ensures that on shutdown, any "active" contexts are shut down, and their
; before- and after-shutdown hooks are called.
(.addShutdownHook (Runtime/getRuntime)
(Thread.
(fn []
(doseq [ctx (set/union (set (keys *before-shutdown-fns*))
(set (keys *after-shutdown-fns*)))]
(shut-down-context! ctx)))))
(defmacro with-context
"Executes `body` given an existing ZMQ context `ctx`.
When done, closes all sockets and destroys the context."
[ctx & body]
`(binding [*context* ~ctx]
(init-context! *context*)
(let [result# (do ~@body)]
(shut-down-context! *context*)
result#)))
(defmacro with-new-context
"Executes `body` using a one-off ZMQ context.
When done, closes all sockets and destroys the context."
[& body]
`(with-context (context) ~@body))
| null | https://raw.githubusercontent.com/daveyarwood/ezzmq/7ad3c234bb39c7425fec4cc93228a80268dc1902/src/ezzmq/context.clj | clojure | ZMQ$Contexts don't automatically close their sockets when you terminate
them; they block until you do it manually.
Ensures that on shutdown, any "active" contexts are shut down, and their
before- and after-shutdown hooks are called. | (ns ezzmq.context
(:require [clojure.set :as set]
[wall.hack])
(:import [org.zeromq ZMQ ZMQ$Context ZContext]))
(def ^:dynamic *context* nil)
(def ^:dynamic *context-type* :zcontext)
(defn context
"Returns a new ZMQ context."
[]
(case *context-type*
:zcontext (ZContext. 1)
:zmq.context (ZMQ/context 1)
(throw (Exception. (format "Invalid context type: %s" *context-type*)))))
(defprotocol Destructible
(destroy-context! [ctx]))
(extend-protocol Destructible
ZContext
(destroy-context! [ctx] (.destroy ctx))
ZMQ$Context
(destroy-context! [context]
The array of sockets is hidden inside of an inner instance , and both
of these fields are private , so we have to use wallhaxx to get to them .
(let [ctx (wall.hack/field org.zeromq.ZMQ$Context :ctx context)
sockets (wall.hack/field zmq.Ctx :sockets ctx)]
(doseq [socket sockets]
(doto socket
(.setSocketOpt zmq.ZMQ/ZMQ_LINGER (int 0))
(.close))))
(.term context)))
(def ^:dynamic *before-shutdown-fns* {})
(def ^:dynamic *after-shutdown-fns* {})
(def ^:dynamic *shutting-down* #{})
(defmacro before-shutdown
[& body]
`(alter-var-root #'*before-shutdown-fns*
update *context* conj (fn [] ~@body)))
(defmacro after-shutdown
[& body]
`(alter-var-root #'*after-shutdown-fns*
update *context* conj (fn [] ~@body)))
(defn init-context!
[ctx]
(alter-var-root #'*before-shutdown-fns* assoc ctx [])
(alter-var-root #'*after-shutdown-fns* assoc ctx []))
(defn shut-down-context!
[ctx]
(when-not (*shutting-down* ctx)
(do
(alter-var-root #'*shutting-down* conj ctx)
(let [before-fns (get *before-shutdown-fns* ctx [])
after-fns (get *after-shutdown-fns* ctx [])]
(doseq [f before-fns] (f))
(destroy-context! ctx)
(doseq [f after-fns] (f)))
(alter-var-root #'*before-shutdown-fns* dissoc ctx)
(alter-var-root #'*after-shutdown-fns* dissoc ctx)
(alter-var-root #'*shutting-down* disj ctx))))
(.addShutdownHook (Runtime/getRuntime)
(Thread.
(fn []
(doseq [ctx (set/union (set (keys *before-shutdown-fns*))
(set (keys *after-shutdown-fns*)))]
(shut-down-context! ctx)))))
(defmacro with-context
"Executes `body` given an existing ZMQ context `ctx`.
When done, closes all sockets and destroys the context."
[ctx & body]
`(binding [*context* ~ctx]
(init-context! *context*)
(let [result# (do ~@body)]
(shut-down-context! *context*)
result#)))
(defmacro with-new-context
"Executes `body` using a one-off ZMQ context.
When done, closes all sockets and destroys the context."
[& body]
`(with-context (context) ~@body))
|
b387d15f55d327234a8e872d56ba823aa55fb46f48a8d9d2617777eac20a67ca | cabol/dberl | dberl_json.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2015 , Inc. All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
%%%-------------------------------------------------------------------
@author < >
( C ) 2015 , < > , All Rights Reserved .
%%% @doc
JSON Utilities .
%%% @end
%%%-------------------------------------------------------------------
-module(dberl_json).
%% API
-export([encode/1, decode/1]).
-export([ejson_to_proplist/1, proplist_to_ejson/1, ejson_to_map/1]).
%% Types
-type json() :: #{} | [#{}] | binary() | number() | boolean() | null.
-type proplist() :: [{atom() | iolist() | string(), any()}].
-type json_term() :: [json_term()] | {[json_term()]} |
[{binary() | atom() | integer(), json_term()}] |
integer() | float() | binary() | atom().
-export_type([json/0]).
%%%===================================================================
%%% API
%%%===================================================================
-spec encode(json()) -> iodata().
encode(Json) -> jiffy:encode(Json, [uescape]).
-spec decode(iodata()) -> json().
decode(Data) ->
try jiffy:decode(Data, [return_maps])
catch
_:{error, _} ->
lager:warning("Bad Json: ~p", [Data]),
throw(bad_json)
end.
-spec ejson_to_proplist(json_term()) -> proplist().
ejson_to_proplist({TupleList}) ->
ejson_to_proplist(TupleList, []);
ejson_to_proplist(TupleList) ->
ejson_to_proplist(TupleList, []).
-spec proplist_to_ejson(proplist()) -> json_term().
proplist_to_ejson(TupleList) ->
proplist_to_ejson(TupleList, []).
-spec ejson_to_map(json_term()) -> map().
ejson_to_map({TupleList}) ->
ejson_to_map(TupleList, #{});
ejson_to_map(TupleList) ->
ejson_to_map(TupleList, #{}).
%%%===================================================================
Internal functions
%%%===================================================================
@private
ejson_to_proplist([], Acc) ->
Acc;
ejson_to_proplist([{K, []} | T], Acc) ->
ejson_to_proplist(T, [{K, [], []} | Acc]);
ejson_to_proplist([{K, {V = [{_, _} | _T0]}} | T], Acc) ->
ejson_to_proplist(T, [{K, ejson_to_proplist(V, [])} | Acc]);
ejson_to_proplist([{K, V} | T], Acc) ->
ejson_to_proplist(T, [{K, V} | Acc]).
@private
proplist_to_ejson([], Acc) ->
{Acc};
proplist_to_ejson([{K, []} | T], Acc) ->
proplist_to_ejson(T, [{K, <<>>} | Acc]);
proplist_to_ejson([{K, V = [{_, _} | _T0]} | T], Acc) ->
proplist_to_ejson(T, [{K, proplist_to_ejson(V, [])} | Acc]);
proplist_to_ejson([{K, V} | T], Acc) ->
proplist_to_ejson(T, [{K, V} | Acc]).
@private
ejson_to_map([], Acc) ->
Acc;
ejson_to_map([{K, []} | T], Acc) ->
ejson_to_map(T, maps:put(K, [], Acc));
ejson_to_map([{K, {V = [{_, _} | _T0]}} | T], Acc) ->
ejson_to_map(T, maps:put(K, ejson_to_map(V, #{}), Acc));
ejson_to_map([{K, V} | T], Acc) ->
ejson_to_map(T, maps:put(K, V, Acc)).
| null | https://raw.githubusercontent.com/cabol/dberl/8de9a9ee81a8fa5454fe961237b619563c91bf5d/src/dberl_json.erl | erlang | -------------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
-------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
API
Types
===================================================================
API
===================================================================
===================================================================
=================================================================== | Copyright ( c ) 2015 , Inc. All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
@author < >
( C ) 2015 , < > , All Rights Reserved .
JSON Utilities .
-module(dberl_json).
-export([encode/1, decode/1]).
-export([ejson_to_proplist/1, proplist_to_ejson/1, ejson_to_map/1]).
-type json() :: #{} | [#{}] | binary() | number() | boolean() | null.
-type proplist() :: [{atom() | iolist() | string(), any()}].
-type json_term() :: [json_term()] | {[json_term()]} |
[{binary() | atom() | integer(), json_term()}] |
integer() | float() | binary() | atom().
-export_type([json/0]).
-spec encode(json()) -> iodata().
encode(Json) -> jiffy:encode(Json, [uescape]).
-spec decode(iodata()) -> json().
decode(Data) ->
try jiffy:decode(Data, [return_maps])
catch
_:{error, _} ->
lager:warning("Bad Json: ~p", [Data]),
throw(bad_json)
end.
-spec ejson_to_proplist(json_term()) -> proplist().
ejson_to_proplist({TupleList}) ->
ejson_to_proplist(TupleList, []);
ejson_to_proplist(TupleList) ->
ejson_to_proplist(TupleList, []).
-spec proplist_to_ejson(proplist()) -> json_term().
proplist_to_ejson(TupleList) ->
proplist_to_ejson(TupleList, []).
-spec ejson_to_map(json_term()) -> map().
ejson_to_map({TupleList}) ->
ejson_to_map(TupleList, #{});
ejson_to_map(TupleList) ->
ejson_to_map(TupleList, #{}).
Internal functions
@private
ejson_to_proplist([], Acc) ->
Acc;
ejson_to_proplist([{K, []} | T], Acc) ->
ejson_to_proplist(T, [{K, [], []} | Acc]);
ejson_to_proplist([{K, {V = [{_, _} | _T0]}} | T], Acc) ->
ejson_to_proplist(T, [{K, ejson_to_proplist(V, [])} | Acc]);
ejson_to_proplist([{K, V} | T], Acc) ->
ejson_to_proplist(T, [{K, V} | Acc]).
@private
proplist_to_ejson([], Acc) ->
{Acc};
proplist_to_ejson([{K, []} | T], Acc) ->
proplist_to_ejson(T, [{K, <<>>} | Acc]);
proplist_to_ejson([{K, V = [{_, _} | _T0]} | T], Acc) ->
proplist_to_ejson(T, [{K, proplist_to_ejson(V, [])} | Acc]);
proplist_to_ejson([{K, V} | T], Acc) ->
proplist_to_ejson(T, [{K, V} | Acc]).
@private
ejson_to_map([], Acc) ->
Acc;
ejson_to_map([{K, []} | T], Acc) ->
ejson_to_map(T, maps:put(K, [], Acc));
ejson_to_map([{K, {V = [{_, _} | _T0]}} | T], Acc) ->
ejson_to_map(T, maps:put(K, ejson_to_map(V, #{}), Acc));
ejson_to_map([{K, V} | T], Acc) ->
ejson_to_map(T, maps:put(K, V, Acc)).
|
3352857d5a6da2430b44a492111f367368b34f4449d7b90236805cbfea2febd2 | travitch/datalog | Rules.hs | {-# LANGUAGE BangPatterns #-}
# LANGUAGE FlexibleContexts #
-- | FIXME: Change the adornment/query building process such that
-- conditional clauses are always processed last. This is necessary
-- so that all variables are bound.
--
FIXME : Add an assertion to say that ConditionalClauses can not have
-- Free variables.
module Database.Datalog.Rules (
Adornment(..),
Term(..),
Clause(..),
AdornedClause(..),
Rule(..),
Literal(..),
Query(..),
QueryBuilder,
PartialTuple(..),
(|-),
assertRule,
relationPredicateFromName,
inferencePredicate,
ruleRelations,
issueQuery,
runQuery,
queryToPartialTuple,
queryPredicate,
lit,
negLit,
cond1,
cond2,
cond3,
cond4,
cond5,
bindQuery,
partitionRules
) where
import qualified Control.Monad.Catch as E
import Control.Monad.Trans.Class
import Control.Monad.Trans.State.Strict
import Data.Function ( on )
import Data.Hashable
import Data.HashMap.Strict ( HashMap )
import qualified Data.HashMap.Strict as HM
import Data.List ( intercalate, groupBy, sortBy )
import Data.Maybe ( mapMaybe )
import Data.Monoid
import Data.Text ( Text )
import qualified Data.Text as T
import Text.Printf ( printf )
import Prelude
import Database.Datalog.Adornment
import Database.Datalog.Relation
import Database.Datalog.Errors
import Database.Datalog.Database
-- import Debug.Trace
-- debug = flip trace
data QueryState a = QueryState { intensionalDatabase :: Database a
, conditionalIdSource :: Int
, queryRules :: [(Clause a, [Literal Clause a])]
}
| The Monad in which queries are constructed and rules are declared
type QueryBuilder m a = StateT (QueryState a) m
nextConditionalId :: (E.MonadThrow m) => QueryBuilder m a Int
nextConditionalId = do
s <- get
let cid = conditionalIdSource s
put s { conditionalIdSource = cid + 1 }
return cid
data Term a = LogicVar !Text
^ A basic logic variable . Equality is based on the
-- variable name.
| BindVar !Text
-- ^ A special variable available in queries that can be
-- bound at query execution time
| Anything
-- ^ A term that is allowed to take any value (this is
-- sugar for a fresh logic variable)
| Atom a
-- ^ A user-provided literal from the domain a
| FreshVar !Int
-- ^ A fresh logic variable, generated internally for
-- each Anything occurrence. Not exposed to the user
instance (Show a) => Show (Term a) where
show (LogicVar t) = T.unpack t
show (BindVar t) = "??" ++ T.unpack t
show (Atom a) = show a
show Anything = "*"
show (FreshVar _) = "*"
instance (Hashable a) => Hashable (Term a) where
hashWithSalt s (LogicVar t) =
s `hashWithSalt` t `hashWithSalt` (1 :: Int)
hashWithSalt s (BindVar t) =
s `hashWithSalt` t `hashWithSalt` (2 :: Int)
hashWithSalt s (Atom a) = s `hashWithSalt` a
hashWithSalt s Anything = s `hashWithSalt` (99 :: Int)
hashWithSalt s (FreshVar i) =
s `hashWithSalt` i `hashWithSalt` (22 :: Int)
instance (Eq a) => Eq (Term a) where
(LogicVar t1) == (LogicVar t2) = t1 == t2
(BindVar t1) == (BindVar t2) = t1 == t2
(Atom a1) == (Atom a2) = a1 == a2
Anything == Anything = True
FreshVar i1 == FreshVar i2 = i1 == i2
_ == _ = False
data Clause a = Clause { clauseRelation :: Relation
, clauseTerms :: [Term a]
}
instance (Eq a) => Eq (Clause a) where
(Clause r1 ts1) == (Clause r2 ts2) = r1 == r2 && ts1 == ts2
instance (Show a) => Show (Clause a) where
show (Clause p ts) =
printf "%s(%s)" (show p) (intercalate ", " (map show ts))
data AdornedClause a = AdornedClause { adornedClauseRelation :: Relation
, adornedClauseTerms :: [(Term a, Adornment)]
}
instance (Eq a) => Eq (AdornedClause a) where
(AdornedClause r1 cs1) == (AdornedClause r2 cs2) = r1 == r2 && cs1 == cs2
instance (Hashable a) => Hashable (AdornedClause a) where
hashWithSalt s (AdornedClause r ts) =
s `hashWithSalt` r `hashWithSalt` ts
instance (Show a) => Show (AdornedClause a) where
show (AdornedClause p ats) =
printf "%s(%s)" (show p) (intercalate ", " (map showAT ats))
where
showAT (t, a) = printf "%s[%s]" (show t) (show a)
-- | Body clauses can be normal clauses, negated clauses, or
-- conditionals. Conditionals are arbitrary-arity (via a list)
-- functions over literals and logic variables.
data Literal ctype a = Literal (ctype a)
| NegatedLiteral (ctype a)
| ConditionalClause Int ([a] -> Bool) [Term a] (HashMap (Term a) Int)
-- | This equality instance is complicated because conditional clauses
-- contain functions. We assign a unique id at conditional clause
-- creation time so they have identity and we can compare on that.
-- Rules from different queries cannot be compared safely, but that
-- shouldn't be a problem because there isn't really a way to sneak a
-- rule reference out of a query. If there is a shady way to do so,
-- don't because it will be bad.
instance (Eq a, Eq (ctype a)) => Eq (Literal ctype a) where
(Literal c1) == (Literal c2) = c1 == c2
(NegatedLiteral c1) == (NegatedLiteral c2) = c1 == c2
(ConditionalClause cid1 _ _ _) == (ConditionalClause cid2 _ _ _) = cid1 == cid2
_ == _ = False
instance (Hashable a, Hashable (ctype a)) => Hashable (Literal ctype a) where
hashWithSalt s (Literal c) =
s `hashWithSalt` c `hashWithSalt` (1 :: Int)
hashWithSalt s (NegatedLiteral c) =
s `hashWithSalt` c `hashWithSalt` (2 :: Int)
hashWithSalt s (ConditionalClause cid _ ts vm) =
s `hashWithSalt` cid `hashWithSalt` ts `hashWithSalt` HM.size vm
lit :: (E.MonadThrow m) => Relation -> [Term a] -> QueryBuilder m a (Literal Clause a)
lit p ts = return $ Literal $ Clause p ts
negLit :: (E.MonadThrow m) => Relation -> [Term a] -> QueryBuilder m a (Literal Clause a)
negLit p ts = return $ NegatedLiteral $ Clause p ts
cond1 :: (E.MonadThrow m, Eq a, Hashable a)
=> (a -> Bool)
-> Term a
-> QueryBuilder m a (Literal Clause a)
cond1 p t = do
cid <- nextConditionalId
return $ ConditionalClause cid (\[x] -> p x) [t] mempty
cond2 :: (E.MonadThrow m, Eq a, Hashable a)
=> (a -> a -> Bool)
-> (Term a, Term a)
-> QueryBuilder m a (Literal Clause a)
cond2 p (t1, t2) = do
cid <- nextConditionalId
return $ ConditionalClause cid (\[x1, x2] -> p x1 x2) [t1, t2] mempty
cond3 :: (E.MonadThrow m, Eq a, Hashable a)
=> (a -> a -> a -> Bool)
-> (Term a, Term a, Term a)
-> QueryBuilder m a (Literal Clause a)
cond3 p (t1, t2, t3) = do
cid <- nextConditionalId
return $ ConditionalClause cid (\[x1, x2, x3] -> p x1 x2 x3) [t1, t2, t3] mempty
cond4 :: (E.MonadThrow m, Eq a, Hashable a)
=> (a -> a -> a -> a -> Bool)
-> (Term a, Term a, Term a, Term a)
-> QueryBuilder m a (Literal Clause a)
cond4 p (t1, t2, t3, t4) = do
cid <- nextConditionalId
return $ ConditionalClause cid (\[x1, x2, x3, x4] -> p x1 x2 x3 x4) [t1, t2, t3, t4] mempty
cond5 :: (E.MonadThrow m, Eq a, Hashable a)
=> (a -> a -> a -> a -> a -> Bool)
-> (Term a, Term a, Term a, Term a, Term a)
-> QueryBuilder m a (Literal Clause a)
cond5 p (t1, t2, t3, t4, t5) = do
cid <- nextConditionalId
return $ ConditionalClause cid (\[x1, x2, x3, x4, x5] -> p x1 x2 x3 x4 x5) [t1, t2, t3, t4, t5] mempty
instance (Show a, Show (ctype a)) => Show (Literal ctype a) where
show (Literal c) = show c
show (NegatedLiteral c) = '~' : show c
show (ConditionalClause _ _ ts _) = printf "f(%s)" (show ts)
-- | A rule has a head and body clauses. Body clauses can be normal
-- clauses, negated clauses, or conditionals.
data Rule a = Rule { ruleHead :: AdornedClause a
, ruleBody :: [Literal AdornedClause a]
, ruleVariableMap :: HashMap (Term a) Int
}
instance (Show a) => Show (Rule a) where
show (Rule h b _) = printf "%s |- %s" (show h) (intercalate ", " (map show b))
instance (Eq a) => Eq (Rule a) where
(Rule h1 b1 vms1) == (Rule h2 b2 vms2) =
h1 == h2 && b1 == b2 && vms1 == vms2
instance (Hashable a) => Hashable (Rule a) where
hashWithSalt s (Rule h b vms) =
s `hashWithSalt` h `hashWithSalt` b `hashWithSalt` HM.size vms
newtype Query a = Query { unQuery :: Clause a }
deriving (Show)
infixr 0 |-
-- | Assert a rule
--
-- FIXME: Check to make sure that clause arities match their declared
-- schema.
(|-), assertRule :: (E.MonadThrow m)
=> (Relation, [Term a]) -- ^ The rule head
-> [QueryBuilder m a (Literal Clause a)] -- ^ Body literals
-> QueryBuilder m a ()
(|-) = assertRule
assertRule (p, ts) b = do
-- FIXME: Assert that Anything does not appear in the head terms
-- (that is a range restriction violation). Also check the range
-- restriction here.
b' <- sequence b
let h = Clause p ts
b'' = fst $ foldr freshenVars ([], [0..]) b'
s <- get
put s { queryRules = (h, b'') : queryRules s }
| Replace all instances of Anything with a FreshVar with a unique
-- (to the rule) index. This lets later evaluation stages ignore
these and just deal with clean FreshVars .
freshenVars :: Literal Clause a
-> ([Literal Clause a], [Int])
-> ([Literal Clause a], [Int])
freshenVars l (cs, ixSrc) =
case l of
ConditionalClause _ _ _ _ -> (l : cs, ixSrc)
Literal (Clause h ts) ->
let (ts', ixRest) = foldr freshen ([], ixSrc) ts
in (Literal (Clause h ts') : cs, ixRest)
NegatedLiteral (Clause h ts) ->
let (ts', ixRest) = foldr freshen ([], ixSrc) ts
in (NegatedLiteral (Clause h ts') : cs, ixRest)
where
freshen t (ts, src) =
case t of
Anything -> (FreshVar (head src) : ts, tail src)
_ -> (t : ts, src)
-- FIXME: Unify these and require inferred relations to be declared in
-- the schema at db construction time. That also gives an opportunity
-- to name the columns
| Retrieve a Relation handle from the IDB . If the Relation does
-- not exist, an error will be raised.
relationPredicateFromName :: (E.MonadThrow m)
=> Text
-> QueryBuilder m a Relation
relationPredicateFromName name = do
let rel = Relation name
idb <- gets intensionalDatabase
case rel `elem` databaseRelations idb of
False -> lift $ E.throwM (NoRelationError rel)
True -> return rel
-- | Create a new predicate that will be referenced by an EDB rule
inferencePredicate :: (E.MonadThrow m)
=> Text
-> QueryBuilder m a Relation
inferencePredicate = return . Relation
-- | A partial tuple records the atoms in a tuple (with their indices
-- in the tuple). These are primarily used in database queries.
newtype PartialTuple a = PartialTuple [Maybe a]
instance (Show a) => Show (PartialTuple a) where
show (PartialTuple vs) = show $ map show vs
| Convert a ' Query ' into a ' PartialTuple ' that can be used in a
' select ' of the IDB
queryToPartialTuple :: Query a -> PartialTuple a
queryToPartialTuple (Query c) =
PartialTuple $! map takeAtom ts
where
ts = clauseTerms c
takeAtom t =
case t of
Atom a -> Just a
_ -> Nothing
literalClauseRelation :: Literal AdornedClause a -> Maybe Relation
literalClauseRelation bc =
case bc of
Literal c -> Just $ adornedClauseRelation c
NegatedLiteral c -> Just $ adornedClauseRelation c
_ -> Nothing
ruleRelations :: Rule a -> [Relation]
ruleRelations (Rule h bcs _) = adornedClauseRelation h : mapMaybe literalClauseRelation bcs
-- | Turn a Clause into a Query. This is meant to be the last
-- statement in a QueryBuilder monad.
issueQuery :: (E.MonadThrow m) => Relation -> [Term a] -> QueryBuilder m a (Query a)
issueQuery r ts = return $ Query $ Clause r ts
-- | Run the QueryBuilder action to build a query and initial rule
-- database
--
-- Rules are adorned (marking each variable as Free or Bound as they
-- appear) before being returned.
runQuery :: (E.MonadThrow m, Eq a, Hashable a)
=> QueryBuilder m a (Query a) -> Database a -> m (Query a, [(Clause a, [Literal Clause a])])
runQuery qm idb = do
(q, QueryState _ _ rs) <- runStateT qm (QueryState idb 0 [])
return (q, rs)
-- | Group rules by their head relations. This is needed to perform
-- semi-naive evaluation easily.
partitionRules :: [Rule a] -> [[Rule a]]
partitionRules = groupBy gcmp . sortBy scmp
where
scmp = compare `on` (adornedClauseRelation . ruleHead)
gcmp = (==) `on` (adornedClauseRelation . ruleHead)
queryPredicate :: Query a -> Relation
queryPredicate = clauseRelation . unQuery
-- | Apply bindings to a query
bindQuery :: Query a -> [(Text, a)] -> Query a
bindQuery (Query (Clause r ts)) bs =
Query $ Clause r $ foldr applyBinding [] ts
where
applyBinding t acc =
case t of
LogicVar _ -> t : acc
BindVar name ->
case lookup name bs of
Nothing -> error ("No binding provided for BindVar " ++ show name)
Just b -> Atom b : acc
Anything -> t : acc
Atom _ -> t : acc
FreshVar _ -> error "Users cannot provide FreshVars"
| null | https://raw.githubusercontent.com/travitch/datalog/8b3c37f1887c42d28a158285b8570e27480a0a56/src/Database/Datalog/Rules.hs | haskell | # LANGUAGE BangPatterns #
| FIXME: Change the adornment/query building process such that
conditional clauses are always processed last. This is necessary
so that all variables are bound.
Free variables.
import Debug.Trace
debug = flip trace
variable name.
^ A special variable available in queries that can be
bound at query execution time
^ A term that is allowed to take any value (this is
sugar for a fresh logic variable)
^ A user-provided literal from the domain a
^ A fresh logic variable, generated internally for
each Anything occurrence. Not exposed to the user
| Body clauses can be normal clauses, negated clauses, or
conditionals. Conditionals are arbitrary-arity (via a list)
functions over literals and logic variables.
| This equality instance is complicated because conditional clauses
contain functions. We assign a unique id at conditional clause
creation time so they have identity and we can compare on that.
Rules from different queries cannot be compared safely, but that
shouldn't be a problem because there isn't really a way to sneak a
rule reference out of a query. If there is a shady way to do so,
don't because it will be bad.
| A rule has a head and body clauses. Body clauses can be normal
clauses, negated clauses, or conditionals.
| Assert a rule
FIXME: Check to make sure that clause arities match their declared
schema.
^ The rule head
^ Body literals
FIXME: Assert that Anything does not appear in the head terms
(that is a range restriction violation). Also check the range
restriction here.
(to the rule) index. This lets later evaluation stages ignore
FIXME: Unify these and require inferred relations to be declared in
the schema at db construction time. That also gives an opportunity
to name the columns
not exist, an error will be raised.
| Create a new predicate that will be referenced by an EDB rule
| A partial tuple records the atoms in a tuple (with their indices
in the tuple). These are primarily used in database queries.
| Turn a Clause into a Query. This is meant to be the last
statement in a QueryBuilder monad.
| Run the QueryBuilder action to build a query and initial rule
database
Rules are adorned (marking each variable as Free or Bound as they
appear) before being returned.
| Group rules by their head relations. This is needed to perform
semi-naive evaluation easily.
| Apply bindings to a query | # LANGUAGE FlexibleContexts #
FIXME : Add an assertion to say that ConditionalClauses can not have
module Database.Datalog.Rules (
Adornment(..),
Term(..),
Clause(..),
AdornedClause(..),
Rule(..),
Literal(..),
Query(..),
QueryBuilder,
PartialTuple(..),
(|-),
assertRule,
relationPredicateFromName,
inferencePredicate,
ruleRelations,
issueQuery,
runQuery,
queryToPartialTuple,
queryPredicate,
lit,
negLit,
cond1,
cond2,
cond3,
cond4,
cond5,
bindQuery,
partitionRules
) where
import qualified Control.Monad.Catch as E
import Control.Monad.Trans.Class
import Control.Monad.Trans.State.Strict
import Data.Function ( on )
import Data.Hashable
import Data.HashMap.Strict ( HashMap )
import qualified Data.HashMap.Strict as HM
import Data.List ( intercalate, groupBy, sortBy )
import Data.Maybe ( mapMaybe )
import Data.Monoid
import Data.Text ( Text )
import qualified Data.Text as T
import Text.Printf ( printf )
import Prelude
import Database.Datalog.Adornment
import Database.Datalog.Relation
import Database.Datalog.Errors
import Database.Datalog.Database
data QueryState a = QueryState { intensionalDatabase :: Database a
, conditionalIdSource :: Int
, queryRules :: [(Clause a, [Literal Clause a])]
}
| The Monad in which queries are constructed and rules are declared
type QueryBuilder m a = StateT (QueryState a) m
nextConditionalId :: (E.MonadThrow m) => QueryBuilder m a Int
nextConditionalId = do
s <- get
let cid = conditionalIdSource s
put s { conditionalIdSource = cid + 1 }
return cid
data Term a = LogicVar !Text
^ A basic logic variable . Equality is based on the
| BindVar !Text
| Anything
| Atom a
| FreshVar !Int
instance (Show a) => Show (Term a) where
show (LogicVar t) = T.unpack t
show (BindVar t) = "??" ++ T.unpack t
show (Atom a) = show a
show Anything = "*"
show (FreshVar _) = "*"
instance (Hashable a) => Hashable (Term a) where
hashWithSalt s (LogicVar t) =
s `hashWithSalt` t `hashWithSalt` (1 :: Int)
hashWithSalt s (BindVar t) =
s `hashWithSalt` t `hashWithSalt` (2 :: Int)
hashWithSalt s (Atom a) = s `hashWithSalt` a
hashWithSalt s Anything = s `hashWithSalt` (99 :: Int)
hashWithSalt s (FreshVar i) =
s `hashWithSalt` i `hashWithSalt` (22 :: Int)
instance (Eq a) => Eq (Term a) where
(LogicVar t1) == (LogicVar t2) = t1 == t2
(BindVar t1) == (BindVar t2) = t1 == t2
(Atom a1) == (Atom a2) = a1 == a2
Anything == Anything = True
FreshVar i1 == FreshVar i2 = i1 == i2
_ == _ = False
data Clause a = Clause { clauseRelation :: Relation
, clauseTerms :: [Term a]
}
instance (Eq a) => Eq (Clause a) where
(Clause r1 ts1) == (Clause r2 ts2) = r1 == r2 && ts1 == ts2
instance (Show a) => Show (Clause a) where
show (Clause p ts) =
printf "%s(%s)" (show p) (intercalate ", " (map show ts))
data AdornedClause a = AdornedClause { adornedClauseRelation :: Relation
, adornedClauseTerms :: [(Term a, Adornment)]
}
instance (Eq a) => Eq (AdornedClause a) where
(AdornedClause r1 cs1) == (AdornedClause r2 cs2) = r1 == r2 && cs1 == cs2
instance (Hashable a) => Hashable (AdornedClause a) where
hashWithSalt s (AdornedClause r ts) =
s `hashWithSalt` r `hashWithSalt` ts
instance (Show a) => Show (AdornedClause a) where
show (AdornedClause p ats) =
printf "%s(%s)" (show p) (intercalate ", " (map showAT ats))
where
showAT (t, a) = printf "%s[%s]" (show t) (show a)
data Literal ctype a = Literal (ctype a)
| NegatedLiteral (ctype a)
| ConditionalClause Int ([a] -> Bool) [Term a] (HashMap (Term a) Int)
instance (Eq a, Eq (ctype a)) => Eq (Literal ctype a) where
(Literal c1) == (Literal c2) = c1 == c2
(NegatedLiteral c1) == (NegatedLiteral c2) = c1 == c2
(ConditionalClause cid1 _ _ _) == (ConditionalClause cid2 _ _ _) = cid1 == cid2
_ == _ = False
instance (Hashable a, Hashable (ctype a)) => Hashable (Literal ctype a) where
hashWithSalt s (Literal c) =
s `hashWithSalt` c `hashWithSalt` (1 :: Int)
hashWithSalt s (NegatedLiteral c) =
s `hashWithSalt` c `hashWithSalt` (2 :: Int)
hashWithSalt s (ConditionalClause cid _ ts vm) =
s `hashWithSalt` cid `hashWithSalt` ts `hashWithSalt` HM.size vm
lit :: (E.MonadThrow m) => Relation -> [Term a] -> QueryBuilder m a (Literal Clause a)
lit p ts = return $ Literal $ Clause p ts
negLit :: (E.MonadThrow m) => Relation -> [Term a] -> QueryBuilder m a (Literal Clause a)
negLit p ts = return $ NegatedLiteral $ Clause p ts
cond1 :: (E.MonadThrow m, Eq a, Hashable a)
=> (a -> Bool)
-> Term a
-> QueryBuilder m a (Literal Clause a)
cond1 p t = do
cid <- nextConditionalId
return $ ConditionalClause cid (\[x] -> p x) [t] mempty
cond2 :: (E.MonadThrow m, Eq a, Hashable a)
=> (a -> a -> Bool)
-> (Term a, Term a)
-> QueryBuilder m a (Literal Clause a)
cond2 p (t1, t2) = do
cid <- nextConditionalId
return $ ConditionalClause cid (\[x1, x2] -> p x1 x2) [t1, t2] mempty
cond3 :: (E.MonadThrow m, Eq a, Hashable a)
=> (a -> a -> a -> Bool)
-> (Term a, Term a, Term a)
-> QueryBuilder m a (Literal Clause a)
cond3 p (t1, t2, t3) = do
cid <- nextConditionalId
return $ ConditionalClause cid (\[x1, x2, x3] -> p x1 x2 x3) [t1, t2, t3] mempty
cond4 :: (E.MonadThrow m, Eq a, Hashable a)
=> (a -> a -> a -> a -> Bool)
-> (Term a, Term a, Term a, Term a)
-> QueryBuilder m a (Literal Clause a)
cond4 p (t1, t2, t3, t4) = do
cid <- nextConditionalId
return $ ConditionalClause cid (\[x1, x2, x3, x4] -> p x1 x2 x3 x4) [t1, t2, t3, t4] mempty
cond5 :: (E.MonadThrow m, Eq a, Hashable a)
=> (a -> a -> a -> a -> a -> Bool)
-> (Term a, Term a, Term a, Term a, Term a)
-> QueryBuilder m a (Literal Clause a)
cond5 p (t1, t2, t3, t4, t5) = do
cid <- nextConditionalId
return $ ConditionalClause cid (\[x1, x2, x3, x4, x5] -> p x1 x2 x3 x4 x5) [t1, t2, t3, t4, t5] mempty
instance (Show a, Show (ctype a)) => Show (Literal ctype a) where
show (Literal c) = show c
show (NegatedLiteral c) = '~' : show c
show (ConditionalClause _ _ ts _) = printf "f(%s)" (show ts)
data Rule a = Rule { ruleHead :: AdornedClause a
, ruleBody :: [Literal AdornedClause a]
, ruleVariableMap :: HashMap (Term a) Int
}
instance (Show a) => Show (Rule a) where
show (Rule h b _) = printf "%s |- %s" (show h) (intercalate ", " (map show b))
instance (Eq a) => Eq (Rule a) where
(Rule h1 b1 vms1) == (Rule h2 b2 vms2) =
h1 == h2 && b1 == b2 && vms1 == vms2
instance (Hashable a) => Hashable (Rule a) where
hashWithSalt s (Rule h b vms) =
s `hashWithSalt` h `hashWithSalt` b `hashWithSalt` HM.size vms
newtype Query a = Query { unQuery :: Clause a }
deriving (Show)
infixr 0 |-
(|-), assertRule :: (E.MonadThrow m)
-> QueryBuilder m a ()
(|-) = assertRule
assertRule (p, ts) b = do
b' <- sequence b
let h = Clause p ts
b'' = fst $ foldr freshenVars ([], [0..]) b'
s <- get
put s { queryRules = (h, b'') : queryRules s }
| Replace all instances of Anything with a FreshVar with a unique
these and just deal with clean FreshVars .
freshenVars :: Literal Clause a
-> ([Literal Clause a], [Int])
-> ([Literal Clause a], [Int])
freshenVars l (cs, ixSrc) =
case l of
ConditionalClause _ _ _ _ -> (l : cs, ixSrc)
Literal (Clause h ts) ->
let (ts', ixRest) = foldr freshen ([], ixSrc) ts
in (Literal (Clause h ts') : cs, ixRest)
NegatedLiteral (Clause h ts) ->
let (ts', ixRest) = foldr freshen ([], ixSrc) ts
in (NegatedLiteral (Clause h ts') : cs, ixRest)
where
freshen t (ts, src) =
case t of
Anything -> (FreshVar (head src) : ts, tail src)
_ -> (t : ts, src)
| Retrieve a Relation handle from the IDB . If the Relation does
relationPredicateFromName :: (E.MonadThrow m)
=> Text
-> QueryBuilder m a Relation
relationPredicateFromName name = do
let rel = Relation name
idb <- gets intensionalDatabase
case rel `elem` databaseRelations idb of
False -> lift $ E.throwM (NoRelationError rel)
True -> return rel
inferencePredicate :: (E.MonadThrow m)
=> Text
-> QueryBuilder m a Relation
inferencePredicate = return . Relation
newtype PartialTuple a = PartialTuple [Maybe a]
instance (Show a) => Show (PartialTuple a) where
show (PartialTuple vs) = show $ map show vs
| Convert a ' Query ' into a ' PartialTuple ' that can be used in a
' select ' of the IDB
queryToPartialTuple :: Query a -> PartialTuple a
queryToPartialTuple (Query c) =
PartialTuple $! map takeAtom ts
where
ts = clauseTerms c
takeAtom t =
case t of
Atom a -> Just a
_ -> Nothing
literalClauseRelation :: Literal AdornedClause a -> Maybe Relation
literalClauseRelation bc =
case bc of
Literal c -> Just $ adornedClauseRelation c
NegatedLiteral c -> Just $ adornedClauseRelation c
_ -> Nothing
ruleRelations :: Rule a -> [Relation]
ruleRelations (Rule h bcs _) = adornedClauseRelation h : mapMaybe literalClauseRelation bcs
issueQuery :: (E.MonadThrow m) => Relation -> [Term a] -> QueryBuilder m a (Query a)
issueQuery r ts = return $ Query $ Clause r ts
runQuery :: (E.MonadThrow m, Eq a, Hashable a)
=> QueryBuilder m a (Query a) -> Database a -> m (Query a, [(Clause a, [Literal Clause a])])
runQuery qm idb = do
(q, QueryState _ _ rs) <- runStateT qm (QueryState idb 0 [])
return (q, rs)
partitionRules :: [Rule a] -> [[Rule a]]
partitionRules = groupBy gcmp . sortBy scmp
where
scmp = compare `on` (adornedClauseRelation . ruleHead)
gcmp = (==) `on` (adornedClauseRelation . ruleHead)
queryPredicate :: Query a -> Relation
queryPredicate = clauseRelation . unQuery
bindQuery :: Query a -> [(Text, a)] -> Query a
bindQuery (Query (Clause r ts)) bs =
Query $ Clause r $ foldr applyBinding [] ts
where
applyBinding t acc =
case t of
LogicVar _ -> t : acc
BindVar name ->
case lookup name bs of
Nothing -> error ("No binding provided for BindVar " ++ show name)
Just b -> Atom b : acc
Anything -> t : acc
Atom _ -> t : acc
FreshVar _ -> error "Users cannot provide FreshVars"
|
c1758bb7f04ec88068be725df7f4158230e671d911ab0a905ec81b4b3db02ccd | bmeurer/ocaml-experimental | builtinf_bind.ml | ##ifdef CAMLTK
(* type *)
type bindAction =
| BindSet of eventField list * (eventInfo -> unit)
| BindSetBreakable of eventField list * (eventInfo -> unit)
| BindRemove
| BindExtend of eventField list * (eventInfo -> unit)
/type
(*
FUNCTION
val bind:
widget -> (modifier list * xEvent) list -> bindAction -> unit
/FUNCTION
*)
let bind widget eventsequence action =
tkCommand [| TkToken "bind";
TkToken (Widget.name widget);
cCAMLtoTKeventSequence eventsequence;
begin match action with
BindRemove -> TkToken ""
| BindSet (what, f) ->
let cbId = register_callback widget (wrapeventInfo f what)
in
TkToken ("camlcb " ^ cbId ^ (writeeventField what))
| BindSetBreakable (what, f) ->
let cbId = register_callback widget (wrapeventInfo f what)
in
TkToken ("camlcb " ^ cbId ^ (writeeventField what) ^
" ; if { $BreakBindingsSequence == 1 } then { break ;} ; set BreakBindingsSequence 0")
| BindExtend (what, f) ->
let cbId = register_callback widget (wrapeventInfo f what)
in
TkToken ("+camlcb " ^ cbId ^ (writeeventField what))
end |]
;;
(* FUNCTION
(* unsafe *)
val bind_class :
string -> (modifier list * xEvent) list -> bindAction -> unit
(* /unsafe *)
/FUNCTION class arg is not constrained *)
let bind_class clas eventsequence action =
tkCommand [| TkToken "bind";
TkToken clas;
cCAMLtoTKeventSequence eventsequence;
begin match action with
BindRemove -> TkToken ""
| BindSet (what, f) ->
let cbId = register_callback Widget.dummy
(wrapeventInfo f what) in
TkToken ("camlcb " ^ cbId ^ (writeeventField what))
| BindSetBreakable (what, f) ->
let cbId = register_callback Widget.dummy
(wrapeventInfo f what) in
TkToken ("camlcb " ^ cbId ^ (writeeventField what)^
" ; if { $BreakBindingsSequence == 1 } then { break ;} ; set BreakBindingsSequence 0" )
| BindExtend (what, f) ->
let cbId = register_callback Widget.dummy
(wrapeventInfo f what) in
TkToken ("+camlcb " ^ cbId ^ (writeeventField what))
end |]
;;
(* FUNCTION
(* unsafe *)
val bind_tag :
string -> (modifier list * xEvent) list -> bindAction -> unit
(* /unsafe *)
/FUNCTION *)
let bind_tag = bind_class
;;
(*
FUNCTION
val break : unit -> unit
/FUNCTION
*)
let break = function () ->
Textvariable.set (Textvariable.coerce "BreakBindingsSequence") "1"
;;
(* Legacy functions *)
let tag_bind = bind_tag;;
let class_bind = bind_class;;
##else
let bind_class ~events ?(extend = false) ?(breakable = false) ?(fields = [])
?action ?on:widget name =
let widget = match widget with None -> Widget.dummy | Some w -> coe w in
tkCommand
[| TkToken "bind";
TkToken name;
cCAMLtoTKeventSequence events;
begin match action with None -> TkToken ""
| Some f ->
let cbId =
register_callback widget ~callback: (wrapeventInfo f fields) in
let cb = if extend then "+camlcb " else "camlcb " in
let cb = cb ^ cbId ^ writeeventField fields in
let cb =
if breakable then
cb ^ " ; if { $BreakBindingsSequence == 1 } then { break ;}"
^ " ; set BreakBindingsSequence 0"
else cb in
TkToken cb
end
|]
;;
let bind ~events ?extend ?breakable ?fields ?action widget =
bind_class ~events ?extend ?breakable ?fields ?action ~on:widget
(Widget.name widget)
;;
let bind_tag = bind_class
;;
(*
FUNCTION
val break : unit -> unit
/FUNCTION
*)
let break = function () ->
tkCommand [| TkToken "set" ; TkToken "BreakBindingsSequence" ; TkToken "1" |]
;;
##endif
| null | https://raw.githubusercontent.com/bmeurer/ocaml-experimental/fe5c10cdb0499e43af4b08f35a3248e5c1a8b541/otherlibs/labltk/builtin/builtinf_bind.ml | ocaml | type
FUNCTION
val bind:
widget -> (modifier list * xEvent) list -> bindAction -> unit
/FUNCTION
FUNCTION
(* unsafe
/unsafe
FUNCTION
(* unsafe
/unsafe
FUNCTION
val break : unit -> unit
/FUNCTION
Legacy functions
FUNCTION
val break : unit -> unit
/FUNCTION
| ##ifdef CAMLTK
type bindAction =
| BindSet of eventField list * (eventInfo -> unit)
| BindSetBreakable of eventField list * (eventInfo -> unit)
| BindRemove
| BindExtend of eventField list * (eventInfo -> unit)
/type
let bind widget eventsequence action =
tkCommand [| TkToken "bind";
TkToken (Widget.name widget);
cCAMLtoTKeventSequence eventsequence;
begin match action with
BindRemove -> TkToken ""
| BindSet (what, f) ->
let cbId = register_callback widget (wrapeventInfo f what)
in
TkToken ("camlcb " ^ cbId ^ (writeeventField what))
| BindSetBreakable (what, f) ->
let cbId = register_callback widget (wrapeventInfo f what)
in
TkToken ("camlcb " ^ cbId ^ (writeeventField what) ^
" ; if { $BreakBindingsSequence == 1 } then { break ;} ; set BreakBindingsSequence 0")
| BindExtend (what, f) ->
let cbId = register_callback widget (wrapeventInfo f what)
in
TkToken ("+camlcb " ^ cbId ^ (writeeventField what))
end |]
;;
val bind_class :
string -> (modifier list * xEvent) list -> bindAction -> unit
/FUNCTION class arg is not constrained *)
let bind_class clas eventsequence action =
tkCommand [| TkToken "bind";
TkToken clas;
cCAMLtoTKeventSequence eventsequence;
begin match action with
BindRemove -> TkToken ""
| BindSet (what, f) ->
let cbId = register_callback Widget.dummy
(wrapeventInfo f what) in
TkToken ("camlcb " ^ cbId ^ (writeeventField what))
| BindSetBreakable (what, f) ->
let cbId = register_callback Widget.dummy
(wrapeventInfo f what) in
TkToken ("camlcb " ^ cbId ^ (writeeventField what)^
" ; if { $BreakBindingsSequence == 1 } then { break ;} ; set BreakBindingsSequence 0" )
| BindExtend (what, f) ->
let cbId = register_callback Widget.dummy
(wrapeventInfo f what) in
TkToken ("+camlcb " ^ cbId ^ (writeeventField what))
end |]
;;
val bind_tag :
string -> (modifier list * xEvent) list -> bindAction -> unit
/FUNCTION *)
let bind_tag = bind_class
;;
let break = function () ->
Textvariable.set (Textvariable.coerce "BreakBindingsSequence") "1"
;;
let tag_bind = bind_tag;;
let class_bind = bind_class;;
##else
let bind_class ~events ?(extend = false) ?(breakable = false) ?(fields = [])
?action ?on:widget name =
let widget = match widget with None -> Widget.dummy | Some w -> coe w in
tkCommand
[| TkToken "bind";
TkToken name;
cCAMLtoTKeventSequence events;
begin match action with None -> TkToken ""
| Some f ->
let cbId =
register_callback widget ~callback: (wrapeventInfo f fields) in
let cb = if extend then "+camlcb " else "camlcb " in
let cb = cb ^ cbId ^ writeeventField fields in
let cb =
if breakable then
cb ^ " ; if { $BreakBindingsSequence == 1 } then { break ;}"
^ " ; set BreakBindingsSequence 0"
else cb in
TkToken cb
end
|]
;;
let bind ~events ?extend ?breakable ?fields ?action widget =
bind_class ~events ?extend ?breakable ?fields ?action ~on:widget
(Widget.name widget)
;;
let bind_tag = bind_class
;;
let break = function () ->
tkCommand [| TkToken "set" ; TkToken "BreakBindingsSequence" ; TkToken "1" |]
;;
##endif
|
eab99798d25dd709663a2c63da84828633b0815b35c7c94a8ce1ae1bac362ec2 | jrm-code-project/LISP-Machine | k-user.lisp | -*- Mode : LISP ; Package : USER ; : CL ; -*-
(eval-when (compile)
(in-package 'k-user
:use '(defstruct lisp-io)))
| null | https://raw.githubusercontent.com/jrm-code-project/LISP-Machine/0a448d27f40761fafabe5775ffc550637be537b2/lambda/rauen/k-user.lisp | lisp | Package : USER ; : CL ; -*- |
(eval-when (compile)
(in-package 'k-user
:use '(defstruct lisp-io)))
|
4bf2fd1f778c5b80ebaa33fb4ae86a2f1a483171c5e8c752cb6e3191beee90a1 | tarides/dune-release | opam.mli | ---------------------------------------------------------------------------
Copyright ( c ) 2016 . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
% % NAME%% % % ---------------------------------------------------------------------------
Copyright (c) 2016 Daniel C. Bünzli. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
%%NAME%% %%VERSION%%
---------------------------------------------------------------------------*)
(** Entrypoints for the [distro] command. *)
val get_pkgs :
?build_dir:Fpath.t ->
?opam:Fpath.t ->
?distrib_file:Fpath.t ->
?readme:Fpath.t ->
?change_log:Fpath.t ->
?publish_msg:string ->
?pkg_descr:Fpath.t ->
dry_run:bool ->
keep_v:bool Dune_release.Config.Cli.t ->
tag:Dune_release.Vcs.Tag.t option ->
pkg_names:string list ->
version:Dune_release.Version.t option ->
unit ->
(Dune_release.Pkg.t list, Bos_setup.R.msg) result
* [ get_pkgs ~build_dir ~opam ~distrib_uri ~change_log
~publish_msg ~pkg_descr ~dry_run ~keep_v ~tag ~name ~pkg_names ~version ( ) ]
returns the list of packages built from the [ distrib_file ] or the associated
error messages .
~publish_msg ~pkg_descr ~dry_run ~keep_v ~tag ~name ~pkg_names ~version ()]
returns the list of packages built from the [distrib_file] or the associated
error messages. *)
val descr : pkgs:Dune_release.Pkg.t list -> (int, Bos_setup.R.msg) result
* [ descr ~pkgs ] prints the opam description of packages [ pkgs ] . Returns the
exit code ( 0 for success , 1 for failure ) or error messages .
exit code (0 for success, 1 for failure) or error messages. *)
val pkg :
?distrib_uri:string ->
dry_run:bool ->
pkgs:Dune_release.Pkg.t list ->
unit ->
(int, Bos_setup.R.msg) result
* [ pkg ~dry_run ~pkgs ] creates the opam package descriptions for packages
[ pkgs ] and upgrades them to opam 2.0 if necessary . Returns the exit code ( 0
for success , 1 for failure ) or error messages .
[pkgs] and upgrades them to opam 2.0 if necessary. Returns the exit code (0
for success, 1 for failure) or error messages. *)
val submit :
?local_repo:Fpath.t Dune_release.Config.Cli.t ->
?remote_repo:string Dune_release.Config.Cli.t ->
?opam_repo:string * string ->
?user:string ->
?token:string Dune_release.Config.Cli.t ->
dry_run:bool ->
pkgs:Dune_release.Pkg.t list ->
pkg_names:string list ->
no_auto_open:bool Dune_release.Config.Cli.t ->
yes:bool ->
draft:bool ->
unit ->
(int, Bos_setup.R.msg) result
* [ submit ? distrib_uri ? local_repo ? remote_repo ? opam_repo ? user ~dry_run
~pkgs ~pkg_names ~no_auto_open ( ) ]
opens a pull request on the opam repository for the packages [ pkgs ] . Returns
the exit code ( 0 for success , 1 for failure ) or error messages .
~pkgs ~pkg_names ~no_auto_open ~yes ~draft ()]
opens a pull request on the opam repository for the packages [pkgs]. Returns
the exit code (0 for success, 1 for failure) or error messages. *)
val field :
pkgs:Dune_release.Pkg.t list ->
field_name:string option ->
(int, Bos_setup.R.msg) result
* [ field ~pkgs ~field_name ] prints the value of the field [ field_name ] in the
opam file of packages [ pkgs ] . Returns the exit code ( 0 for success , 1 for
failure ) or error messages .
opam file of packages [pkgs]. Returns the exit code (0 for success, 1 for
failure) or error messages. *)
(** The [opam] command. *)
val cmd : int Cmdliner.Cmd.t
---------------------------------------------------------------------------
Copyright ( c ) 2016
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) 2016 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/tarides/dune-release/6bfed0f299b82c0931c78d4e216fd0efedff0673/bin/opam.mli | ocaml | * Entrypoints for the [distro] command.
* The [opam] command. | ---------------------------------------------------------------------------
Copyright ( c ) 2016 . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
% % NAME%% % % ---------------------------------------------------------------------------
Copyright (c) 2016 Daniel C. Bünzli. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
%%NAME%% %%VERSION%%
---------------------------------------------------------------------------*)
val get_pkgs :
?build_dir:Fpath.t ->
?opam:Fpath.t ->
?distrib_file:Fpath.t ->
?readme:Fpath.t ->
?change_log:Fpath.t ->
?publish_msg:string ->
?pkg_descr:Fpath.t ->
dry_run:bool ->
keep_v:bool Dune_release.Config.Cli.t ->
tag:Dune_release.Vcs.Tag.t option ->
pkg_names:string list ->
version:Dune_release.Version.t option ->
unit ->
(Dune_release.Pkg.t list, Bos_setup.R.msg) result
* [ get_pkgs ~build_dir ~opam ~distrib_uri ~change_log
~publish_msg ~pkg_descr ~dry_run ~keep_v ~tag ~name ~pkg_names ~version ( ) ]
returns the list of packages built from the [ distrib_file ] or the associated
error messages .
~publish_msg ~pkg_descr ~dry_run ~keep_v ~tag ~name ~pkg_names ~version ()]
returns the list of packages built from the [distrib_file] or the associated
error messages. *)
val descr : pkgs:Dune_release.Pkg.t list -> (int, Bos_setup.R.msg) result
* [ descr ~pkgs ] prints the opam description of packages [ pkgs ] . Returns the
exit code ( 0 for success , 1 for failure ) or error messages .
exit code (0 for success, 1 for failure) or error messages. *)
val pkg :
?distrib_uri:string ->
dry_run:bool ->
pkgs:Dune_release.Pkg.t list ->
unit ->
(int, Bos_setup.R.msg) result
* [ pkg ~dry_run ~pkgs ] creates the opam package descriptions for packages
[ pkgs ] and upgrades them to opam 2.0 if necessary . Returns the exit code ( 0
for success , 1 for failure ) or error messages .
[pkgs] and upgrades them to opam 2.0 if necessary. Returns the exit code (0
for success, 1 for failure) or error messages. *)
val submit :
?local_repo:Fpath.t Dune_release.Config.Cli.t ->
?remote_repo:string Dune_release.Config.Cli.t ->
?opam_repo:string * string ->
?user:string ->
?token:string Dune_release.Config.Cli.t ->
dry_run:bool ->
pkgs:Dune_release.Pkg.t list ->
pkg_names:string list ->
no_auto_open:bool Dune_release.Config.Cli.t ->
yes:bool ->
draft:bool ->
unit ->
(int, Bos_setup.R.msg) result
* [ submit ? distrib_uri ? local_repo ? remote_repo ? opam_repo ? user ~dry_run
~pkgs ~pkg_names ~no_auto_open ( ) ]
opens a pull request on the opam repository for the packages [ pkgs ] . Returns
the exit code ( 0 for success , 1 for failure ) or error messages .
~pkgs ~pkg_names ~no_auto_open ~yes ~draft ()]
opens a pull request on the opam repository for the packages [pkgs]. Returns
the exit code (0 for success, 1 for failure) or error messages. *)
val field :
pkgs:Dune_release.Pkg.t list ->
field_name:string option ->
(int, Bos_setup.R.msg) result
* [ field ~pkgs ~field_name ] prints the value of the field [ field_name ] in the
opam file of packages [ pkgs ] . Returns the exit code ( 0 for success , 1 for
failure ) or error messages .
opam file of packages [pkgs]. Returns the exit code (0 for success, 1 for
failure) or error messages. *)
val cmd : int Cmdliner.Cmd.t
---------------------------------------------------------------------------
Copyright ( c ) 2016
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) 2016 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.
---------------------------------------------------------------------------*)
|
e7cc68d4d59230f2e767c1f55e0e3489181299518aa72e4276284950dced12ce | sunshineclt/Racket-Helper | 04.rkt | #lang racket
(define (accumulate op init seq)
(if (null? seq)
init
(op (car seq) (accumulate op init (cdr seq)))))
(define (accumulate-n op init seqs)
(if (null? seqs)
'()
(cons (accumulate op init (map first seqs))
(accumulate-n op init (cond [(empty? (list-ref (map rest seqs) 0)) null]
[else (map rest seqs)])))))
(define s (list (list 1 2 3) (list 4 5 6) (list 7 8 9) (list 10 11 12)))
(display (accumulate-n + 10 s)) (newline)
(display (accumulate-n * 1 s)) (newline)
(display (accumulate-n cons '() s)) (newline)
(display "******") (newline)
(define (myloop)
(let ((lst (read)))
(if (eq? lst eof)
(void)
(begin (display (accumulate-n + 0 lst)) (newline)
(display (accumulate-n cons '(a) lst)) (newline)
(myloop)))))
(myloop) | null | https://raw.githubusercontent.com/sunshineclt/Racket-Helper/bf85f38dd8d084db68265bb98d8c38bada6494ec/%E9%AA%86%E6%A2%81%E5%AE%B8/Assignment/3/04.rkt | racket | #lang racket
(define (accumulate op init seq)
(if (null? seq)
init
(op (car seq) (accumulate op init (cdr seq)))))
(define (accumulate-n op init seqs)
(if (null? seqs)
'()
(cons (accumulate op init (map first seqs))
(accumulate-n op init (cond [(empty? (list-ref (map rest seqs) 0)) null]
[else (map rest seqs)])))))
(define s (list (list 1 2 3) (list 4 5 6) (list 7 8 9) (list 10 11 12)))
(display (accumulate-n + 10 s)) (newline)
(display (accumulate-n * 1 s)) (newline)
(display (accumulate-n cons '() s)) (newline)
(display "******") (newline)
(define (myloop)
(let ((lst (read)))
(if (eq? lst eof)
(void)
(begin (display (accumulate-n + 0 lst)) (newline)
(display (accumulate-n cons '(a) lst)) (newline)
(myloop)))))
(myloop) | |
4f9ccd5f5f7060c69a6fe2e7862c5410c354e7a7917bbdbcad26fd10de0ea1fd | jlouis/safetyvalve | sv_codel.erl | @doc This is a loose translation of the following link from ACM :
%%%
%%%
%%%
%%% The document you want to read is
" Controlling queue Delay " , ,
But also note that some of the other papers are interesting . Especially notes are of
%%% interest.
%%%
%%% @end
-module(sv_codel).
%% Public API
-export([new/0, new/2, in/3, out/2, len/1, remove/3]).
-export([init/2, enqueue/3, dequeue/2, delete/1]).
Scrutiny
-export([qstate/1]).
-type task() :: term().
-define(Q, sv_queue_ets).
%% Internal state
-record(state, {
%% The underlying queue to use. For now, since we are mainly in a test phase, we just use a standard
%% functional queue. But later the plan is to use a module here and then call the right kind of queue
%% functions for that module.
queue = ?Q:new(),
The ` dropping ' field tracks if the CoDel system is in a dropping state or not .
dropping = false,
%% If we are dropping, this value tracks the point in time where the next packet should
%% be dropped from the queue.
drop_next = 0,
First above time tracks when we first began seeing too much delay imposed by the queue .
%% This value may be 0 in which case it means we have not seen such a delay.
first_above_time = 0,
%% This variable tracks how many packets/jobs were recently dropped from the queue.
%% The value decays over time if no packets are dropped and is used to manipulate the control
%% law of the queue.
count = 0,
The ` interval ' and ` target ' are configurable parameters , described in @see init/2 .
interval = 100, % ms
target = 5 %ms
}).
%% @doc Look at the queue state as a proplist
%% @end
-spec qstate(#state{}) -> [{atom(), term()}].
qstate(#state {
queue = Q,
dropping = Drop,
drop_next = DN,
interval = I,
target = T,
first_above_time = FAT,
count = C
}) ->
[{queue, Q},
{dropping, Drop},
{drop_next, DN},
{interval, I},
{target, T},
{first_above_time, FAT},
{count, C}].
%% Queue API
%% -----------------------------
new() -> new(5, 100).
new(Target, Interval) ->
init(Target*1000, Interval*1000).
len(#state { queue = Q }) -> ?Q:len(Q).
in(Item, Ts, CoDelState) ->
enqueue(Item, Ts, CoDelState).
out(Ts, CoDelState) ->
dequeue(Ts, CoDelState).
remove(Item, TS, CoDelState) ->
queue_remove(Item, TS, CoDelState).
@doc Initialize the CoDel state
< p > The value ` Target ' defines the delay target in ms . If the queue has a sojourn - time through the queue
%% which is above this value, then the queue begins to consider dropping packets.</p>
< p > The value ` Interval ' is the window we have to be above ` Target ' before we consider that there may be
%% problems. As such, it provides a hysteresis on the queue as well and small increases in latency does
%% not affect the queue.</p>
%% <p>Note that the interval makes sure we can use the queue as "good queue". If we get a sudden small
%% spike in jobs, then the queue will make sure they get smoothed out and processed with no loss of jobs.
%% But it also protects against "bad queue" where a standing queue won't dissipate due to consistent
overload of the >
%% @end
-spec init(pos_integer(), pos_integer()) -> #state{}.
init(Target, Interval) when Target > Interval -> exit(misconfiguration);
init(Target, Interval) -> #state{ target = Target, interval = Interval }.
delete(#state { queue = Q }) -> ?Q:delete(Q).
%% @doc Enqueue a packet
%% <p>Enqueue packet `Pkt' at time `TS' into the queue.</p>
%% @end
-spec enqueue(task(), term(), #state{}) -> #state{}.
enqueue(Pkt, TS, #state { queue = Q } = State) ->
State#state { queue = ?Q:in({Pkt, TS}, TS, Q) }.
%% @doc queue_remove/3 removes a packet from the queue
%% @end
queue_remove(Item, TS, #state { queue = Q } = State) ->
State#state { queue = ?Q:remove(Item, TS, Q) }.
@doc Dequeue a packet from the CoDel system
Given a point in time , ` Now ' and a CoDel ` State ' , extract the next task from it .
%% @end
-spec dequeue(Now, InState) ->
{empty, [Pkt], OutState} | {drop, [Pkt], OutState} | {Pkt, [Pkt], OutState}
when
Now :: term(),
Pkt :: task(),
InState :: #state{},
OutState :: #state{}.
dequeue(Now, State) ->
dequeue_(Now, dodequeue(Now, State)).
Internal functions
%% ---------------------------------------------------------
%% The control law defines the packet drop rate. Given a time T we drop the next packet at T+I, where
%% I is the interval. Now, if we need to drop yet another packet, we drop it at I/math:sqrt(C) where C
%% is the number of packets we have dropped so far in this round.
control_law(T, I, C) ->
T + I / math:sqrt(C).
This is a helper function . It dequeues from the underlying queue and then analyzes the Sojourn
%% time together with the next function, dodequeue_.
dodequeue({TS, _Uniq} = Now, #state { queue = Q } = State) ->
case ?Q:out(Now, Q) of
{empty, [], NQ} ->
sv:report(TS div 1000, {dodequeue, 0, 0}),
{nodrop, empty, State#state { first_above_time = 0, queue = NQ }};
{{Pkt, {InT, _}}, [], NQ} ->
Sojourn = TS - InT,
sv:report(TS div 1000, {dodequeue, ?Q:len(NQ), Sojourn div 1000}),
dodequeue_(Now, Pkt, Sojourn, State#state { queue = NQ })
end.
%% Case split:
%% The sojourn time through the queue is less than our target value.
Thus , we should not drop , and we reset when we were first above .
dodequeue_(_Now, Pkt, Sojourn, #state { target = T } = State)
when Sojourn < T ->
{nodrop, Pkt, State#state { first_above_time = 0 }};
We are above target , but this is the first time we are above target .
%% We set up the point in time when we went above the target to start
%% tracking this.
dodequeue_({TS, _}, Pkt, _Sojourn, #state { first_above_time = FAT, interval = I } = State)
when FAT == 0 ->
{nodrop, Pkt, State#state { first_above_time = TS + I }};
We have been above target for more than one interval . This is when we need to start dropping .
dodequeue_({TS, _}, Pkt, _Sojourn, #state { first_above_time = FAT } = State)
when TS >= FAT ->
{drop, Pkt, State};
%% We are above target, but we have not yet been above target for a complete interval. Wait and see
%% what happens, but don't begin dropping packets just yet.
dodequeue_(_Now, Pkt, _Sojourn, State) ->
{nodrop, Pkt, State}.
Dequeue worker . This drives the meat of the dequeue steps .
%% Case split:
%% We are in the dropping state, but are transitioning to not dropping.
dequeue_(Now, {nodrop, Pkt, #state { dropping = true } = State}) ->
dequeue_drop_next(Now, Pkt, State#state { dropping = false }, []);
%% We are in the dropping state and are to continue dropping.
dequeue_(Now, {drop, Pkt, #state { dropping = true } = State}) ->
dequeue_drop_next(Now, Pkt, State, []);
%% We are not in the dropping state, but should start dropping.
dequeue_(Now, {drop, Pkt, #state { dropping = false } = State}) ->
dequeue_start_drop(Now, Pkt, State);
%% Default case for normal operation.
dequeue_(_Now, {nodrop, Pkt, #state { dropping = false } = State}) ->
{Pkt, [], State}.
%% Consider dropping the next packet from the queue.
%% This function drives a loop until the next timepoint
%% where we should drop is in the future. The helper
%% dequeue_drop_next_/3 carries out the book-keeping
dequeue_drop_next({TS, _} = Now, Pkt, #state { drop_next = DN, dropping = true } = State, Dropped)
when TS >= DN ->
dequeue_drop_next_(Now, dodequeue(Now, State), [Pkt | Dropped]);
dequeue_drop_next(_Now, Pkt, State, Dropped) ->
{Pkt, Dropped, State}.
%% If the Sojourn time improves, we leave the dropping state.
dequeue_drop_next_(Now, {nodrop, Pkt, State}, Dropped) ->
dequeue_drop_next(Now, Pkt, State#state { dropping = false }, Dropped);
%% We are still to drop packets, so update the count and the
%% control law for the next loop round.
dequeue_drop_next_(
Now,
{drop, Pkt,
#state {
count = C,
interval = I,
drop_next = DN } = State},
Dropped) ->
NewState = State#state { count = C + 1, drop_next = control_law(DN, I, C+1) },
dequeue_drop_next(Now, Pkt, NewState, Dropped).
%% Function for setting up the dropping state. When we start dropping, we evaluate a bit on
%% how long ago we last dropped. If we did this recently, we do not start off from the bottom of
%% the control law, but rather pick a point a bit up the function. On the other hand, if it is a long time
ago , we just pick the usual starting point of 1 .
dequeue_start_drop({TS, _}, Pkt, #state { drop_next = DN, interval = Interval, count = Count } = State)
when TS - DN < Interval, Count > 2 ->
{drop, [Pkt], State#state {
dropping = true,
count = Count - 2,
drop_next = control_law(TS, Interval, Count - 2) }};
dequeue_start_drop({TS, _}, Pkt, #state { interval = I } = State) ->
{drop, [Pkt], State#state {
dropping = true,
count = 1,
drop_next = control_law(TS, I, 1) }}.
| null | https://raw.githubusercontent.com/jlouis/safetyvalve/c8235c6ca1deffeccdbba9dd74263408ed56594a/src/sv_codel.erl | erlang |
The document you want to read is
interest.
@end
Public API
Internal state
The underlying queue to use. For now, since we are mainly in a test phase, we just use a standard
functional queue. But later the plan is to use a module here and then call the right kind of queue
functions for that module.
If we are dropping, this value tracks the point in time where the next packet should
be dropped from the queue.
This value may be 0 in which case it means we have not seen such a delay.
This variable tracks how many packets/jobs were recently dropped from the queue.
The value decays over time if no packets are dropped and is used to manipulate the control
law of the queue.
ms
ms
@doc Look at the queue state as a proplist
@end
Queue API
-----------------------------
which is above this value, then the queue begins to consider dropping packets.</p>
problems. As such, it provides a hysteresis on the queue as well and small increases in latency does
not affect the queue.</p>
<p>Note that the interval makes sure we can use the queue as "good queue". If we get a sudden small
spike in jobs, then the queue will make sure they get smoothed out and processed with no loss of jobs.
But it also protects against "bad queue" where a standing queue won't dissipate due to consistent
@end
@doc Enqueue a packet
<p>Enqueue packet `Pkt' at time `TS' into the queue.</p>
@end
@doc queue_remove/3 removes a packet from the queue
@end
@end
---------------------------------------------------------
The control law defines the packet drop rate. Given a time T we drop the next packet at T+I, where
I is the interval. Now, if we need to drop yet another packet, we drop it at I/math:sqrt(C) where C
is the number of packets we have dropped so far in this round.
time together with the next function, dodequeue_.
Case split:
The sojourn time through the queue is less than our target value.
We set up the point in time when we went above the target to start
tracking this.
We are above target, but we have not yet been above target for a complete interval. Wait and see
what happens, but don't begin dropping packets just yet.
Case split:
We are in the dropping state, but are transitioning to not dropping.
We are in the dropping state and are to continue dropping.
We are not in the dropping state, but should start dropping.
Default case for normal operation.
Consider dropping the next packet from the queue.
This function drives a loop until the next timepoint
where we should drop is in the future. The helper
dequeue_drop_next_/3 carries out the book-keeping
If the Sojourn time improves, we leave the dropping state.
We are still to drop packets, so update the count and the
control law for the next loop round.
Function for setting up the dropping state. When we start dropping, we evaluate a bit on
how long ago we last dropped. If we did this recently, we do not start off from the bottom of
the control law, but rather pick a point a bit up the function. On the other hand, if it is a long time | @doc This is a loose translation of the following link from ACM :
" Controlling queue Delay " , ,
But also note that some of the other papers are interesting . Especially notes are of
-module(sv_codel).
-export([new/0, new/2, in/3, out/2, len/1, remove/3]).
-export([init/2, enqueue/3, dequeue/2, delete/1]).
Scrutiny
-export([qstate/1]).
-type task() :: term().
-define(Q, sv_queue_ets).
-record(state, {
queue = ?Q:new(),
The ` dropping ' field tracks if the CoDel system is in a dropping state or not .
dropping = false,
drop_next = 0,
First above time tracks when we first began seeing too much delay imposed by the queue .
first_above_time = 0,
count = 0,
The ` interval ' and ` target ' are configurable parameters , described in @see init/2 .
}).
-spec qstate(#state{}) -> [{atom(), term()}].
qstate(#state {
queue = Q,
dropping = Drop,
drop_next = DN,
interval = I,
target = T,
first_above_time = FAT,
count = C
}) ->
[{queue, Q},
{dropping, Drop},
{drop_next, DN},
{interval, I},
{target, T},
{first_above_time, FAT},
{count, C}].
new() -> new(5, 100).
new(Target, Interval) ->
init(Target*1000, Interval*1000).
len(#state { queue = Q }) -> ?Q:len(Q).
in(Item, Ts, CoDelState) ->
enqueue(Item, Ts, CoDelState).
out(Ts, CoDelState) ->
dequeue(Ts, CoDelState).
remove(Item, TS, CoDelState) ->
queue_remove(Item, TS, CoDelState).
@doc Initialize the CoDel state
< p > The value ` Target ' defines the delay target in ms . If the queue has a sojourn - time through the queue
< p > The value ` Interval ' is the window we have to be above ` Target ' before we consider that there may be
overload of the >
-spec init(pos_integer(), pos_integer()) -> #state{}.
init(Target, Interval) when Target > Interval -> exit(misconfiguration);
init(Target, Interval) -> #state{ target = Target, interval = Interval }.
delete(#state { queue = Q }) -> ?Q:delete(Q).
-spec enqueue(task(), term(), #state{}) -> #state{}.
enqueue(Pkt, TS, #state { queue = Q } = State) ->
State#state { queue = ?Q:in({Pkt, TS}, TS, Q) }.
queue_remove(Item, TS, #state { queue = Q } = State) ->
State#state { queue = ?Q:remove(Item, TS, Q) }.
@doc Dequeue a packet from the CoDel system
Given a point in time , ` Now ' and a CoDel ` State ' , extract the next task from it .
-spec dequeue(Now, InState) ->
{empty, [Pkt], OutState} | {drop, [Pkt], OutState} | {Pkt, [Pkt], OutState}
when
Now :: term(),
Pkt :: task(),
InState :: #state{},
OutState :: #state{}.
dequeue(Now, State) ->
dequeue_(Now, dodequeue(Now, State)).
Internal functions
control_law(T, I, C) ->
T + I / math:sqrt(C).
This is a helper function . It dequeues from the underlying queue and then analyzes the Sojourn
dodequeue({TS, _Uniq} = Now, #state { queue = Q } = State) ->
case ?Q:out(Now, Q) of
{empty, [], NQ} ->
sv:report(TS div 1000, {dodequeue, 0, 0}),
{nodrop, empty, State#state { first_above_time = 0, queue = NQ }};
{{Pkt, {InT, _}}, [], NQ} ->
Sojourn = TS - InT,
sv:report(TS div 1000, {dodequeue, ?Q:len(NQ), Sojourn div 1000}),
dodequeue_(Now, Pkt, Sojourn, State#state { queue = NQ })
end.
Thus , we should not drop , and we reset when we were first above .
dodequeue_(_Now, Pkt, Sojourn, #state { target = T } = State)
when Sojourn < T ->
{nodrop, Pkt, State#state { first_above_time = 0 }};
We are above target , but this is the first time we are above target .
dodequeue_({TS, _}, Pkt, _Sojourn, #state { first_above_time = FAT, interval = I } = State)
when FAT == 0 ->
{nodrop, Pkt, State#state { first_above_time = TS + I }};
We have been above target for more than one interval . This is when we need to start dropping .
dodequeue_({TS, _}, Pkt, _Sojourn, #state { first_above_time = FAT } = State)
when TS >= FAT ->
{drop, Pkt, State};
dodequeue_(_Now, Pkt, _Sojourn, State) ->
{nodrop, Pkt, State}.
Dequeue worker . This drives the meat of the dequeue steps .
dequeue_(Now, {nodrop, Pkt, #state { dropping = true } = State}) ->
dequeue_drop_next(Now, Pkt, State#state { dropping = false }, []);
dequeue_(Now, {drop, Pkt, #state { dropping = true } = State}) ->
dequeue_drop_next(Now, Pkt, State, []);
dequeue_(Now, {drop, Pkt, #state { dropping = false } = State}) ->
dequeue_start_drop(Now, Pkt, State);
dequeue_(_Now, {nodrop, Pkt, #state { dropping = false } = State}) ->
{Pkt, [], State}.
dequeue_drop_next({TS, _} = Now, Pkt, #state { drop_next = DN, dropping = true } = State, Dropped)
when TS >= DN ->
dequeue_drop_next_(Now, dodequeue(Now, State), [Pkt | Dropped]);
dequeue_drop_next(_Now, Pkt, State, Dropped) ->
{Pkt, Dropped, State}.
dequeue_drop_next_(Now, {nodrop, Pkt, State}, Dropped) ->
dequeue_drop_next(Now, Pkt, State#state { dropping = false }, Dropped);
dequeue_drop_next_(
Now,
{drop, Pkt,
#state {
count = C,
interval = I,
drop_next = DN } = State},
Dropped) ->
NewState = State#state { count = C + 1, drop_next = control_law(DN, I, C+1) },
dequeue_drop_next(Now, Pkt, NewState, Dropped).
ago , we just pick the usual starting point of 1 .
dequeue_start_drop({TS, _}, Pkt, #state { drop_next = DN, interval = Interval, count = Count } = State)
when TS - DN < Interval, Count > 2 ->
{drop, [Pkt], State#state {
dropping = true,
count = Count - 2,
drop_next = control_law(TS, Interval, Count - 2) }};
dequeue_start_drop({TS, _}, Pkt, #state { interval = I } = State) ->
{drop, [Pkt], State#state {
dropping = true,
count = 1,
drop_next = control_law(TS, I, 1) }}.
|
1e4b1a3075bfab041e10aebf609ab462cb4a0782d8831995c7596c8e78725425 | thomaseding/hearthshroud | GameEvent.hs | # LANGUAGE DataKinds #
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GADTs #-}
# LANGUAGE KindSignatures #
# LANGUAGE StandaloneDeriving #
module Hearth.Model.Runtime.GameEvent where
--------------------------------------------------------------------------------
import Data.Data
import Hearth.Model.Authoring
import Hearth.Model.Runtime
--------------------------------------------------------------------------------
data GameEvent :: * where
GameBegins :: GameEvent
GameEnds :: GameResult -> GameEvent
PhaseEvent :: Scoped Phase -> GameEvent
DeckShuffled :: Handle 'Player' -> Deck -> GameEvent
CardDrawn :: Handle 'Player' -> Either DeckCard HandCard -> Deck -> GameEvent
UsedHeroPower :: Handle 'Player' -> HeroPower -> GameEvent
PlayedMinion :: Handle 'Player' -> Handle 'Minion' -> GameEvent
PlayedSpell :: Handle 'Player' -> Handle 'Spell' -> GameEvent
PlayedWeapon :: Handle 'Player' -> Handle 'Weapon' -> GameEvent
DealtDamage :: Handle 'Character' -> Damage -> DamageSource -> GameEvent
HealthRestored :: Handle 'Character' -> Health -> GameEvent
GainedArmor :: Handle 'Player' -> Armor -> GameEvent
MinionDestroyed :: Handle 'Minion' -> GameEvent
MinionDied :: Handle 'Minion' -> GameEvent
EnactAttack :: Handle 'Character' -> Handle 'Character' -> GameEvent
GainsManaCrystal :: Handle 'Player' -> Maybe CrystalState -> GameEvent
ManaCrystalsRefill :: Handle 'Player' -> Int -> GameEvent
ManaCrystalsEmpty :: Handle 'Player' -> Int -> GameEvent
LostDivineShield :: Handle 'Minion' -> GameEvent
Silenced :: Handle 'Minion' -> GameEvent
AttackFailed :: AttackFailedReason -> GameEvent
Transformed :: Handle 'Minion' -> MinionCard -> GameEvent
deriving (Typeable)
data AttackFailedReason :: * where
AttackWithEnemy :: AttackFailedReason
DefendWithFriendly :: AttackFailedReason
ZeroAttack :: AttackFailedReason
DoesNotHaveCharge :: AttackFailedReason
OutOfAttacks :: AttackFailedReason
TauntsExist :: AttackFailedReason
AttackerIsFrozen :: AttackFailedReason
AttackerCan'tAttack :: AttackFailedReason
deriving (Show, Typeable)
| null | https://raw.githubusercontent.com/thomaseding/hearthshroud/b21e2f69f394c94a106a3b57b95aa1a76b8d4003/src/Hearth/Model/Runtime/GameEvent.hs | haskell | # LANGUAGE DeriveDataTypeable #
# LANGUAGE GADTs #
------------------------------------------------------------------------------
------------------------------------------------------------------------------ | # LANGUAGE DataKinds #
# LANGUAGE KindSignatures #
# LANGUAGE StandaloneDeriving #
module Hearth.Model.Runtime.GameEvent where
import Data.Data
import Hearth.Model.Authoring
import Hearth.Model.Runtime
data GameEvent :: * where
GameBegins :: GameEvent
GameEnds :: GameResult -> GameEvent
PhaseEvent :: Scoped Phase -> GameEvent
DeckShuffled :: Handle 'Player' -> Deck -> GameEvent
CardDrawn :: Handle 'Player' -> Either DeckCard HandCard -> Deck -> GameEvent
UsedHeroPower :: Handle 'Player' -> HeroPower -> GameEvent
PlayedMinion :: Handle 'Player' -> Handle 'Minion' -> GameEvent
PlayedSpell :: Handle 'Player' -> Handle 'Spell' -> GameEvent
PlayedWeapon :: Handle 'Player' -> Handle 'Weapon' -> GameEvent
DealtDamage :: Handle 'Character' -> Damage -> DamageSource -> GameEvent
HealthRestored :: Handle 'Character' -> Health -> GameEvent
GainedArmor :: Handle 'Player' -> Armor -> GameEvent
MinionDestroyed :: Handle 'Minion' -> GameEvent
MinionDied :: Handle 'Minion' -> GameEvent
EnactAttack :: Handle 'Character' -> Handle 'Character' -> GameEvent
GainsManaCrystal :: Handle 'Player' -> Maybe CrystalState -> GameEvent
ManaCrystalsRefill :: Handle 'Player' -> Int -> GameEvent
ManaCrystalsEmpty :: Handle 'Player' -> Int -> GameEvent
LostDivineShield :: Handle 'Minion' -> GameEvent
Silenced :: Handle 'Minion' -> GameEvent
AttackFailed :: AttackFailedReason -> GameEvent
Transformed :: Handle 'Minion' -> MinionCard -> GameEvent
deriving (Typeable)
data AttackFailedReason :: * where
AttackWithEnemy :: AttackFailedReason
DefendWithFriendly :: AttackFailedReason
ZeroAttack :: AttackFailedReason
DoesNotHaveCharge :: AttackFailedReason
OutOfAttacks :: AttackFailedReason
TauntsExist :: AttackFailedReason
AttackerIsFrozen :: AttackFailedReason
AttackerCan'tAttack :: AttackFailedReason
deriving (Show, Typeable)
|
13514d4a6897d198c75005a2b29ef9eea2f7b78a266e237fc04a50894507de0c | day8/re-frame-10x | core.cljc | (ns day8.re-frame-10x.inlined-deps.garden.v1v3v10.garden.core
"Convert Clojure data structures to CSS."
(:require [day8.re-frame-10x.inlined-deps.garden.v1v3v10.garden.compiler :as compiler]))
(defn ^String css
"Convert a variable number of Clojure data structure to a string of
CSS. The first argument may be a list of flags for the compiler."
{:arglists '([rules] [flags? rules])}
[& rules]
(apply compiler/compile-css rules))
(defn ^String style
"Convert a variable number of maps into a string of CSS for use with
the HTML `style` attribute."
[& maps]
(compiler/compile-style maps))
| null | https://raw.githubusercontent.com/day8/re-frame-10x/d8dcb17e217449aba2cf64b9f843b0e9f86cfcb6/gen-src/day8/re_frame_10x/inlined_deps/garden/v1v3v10/garden/core.cljc | clojure | (ns day8.re-frame-10x.inlined-deps.garden.v1v3v10.garden.core
"Convert Clojure data structures to CSS."
(:require [day8.re-frame-10x.inlined-deps.garden.v1v3v10.garden.compiler :as compiler]))
(defn ^String css
"Convert a variable number of Clojure data structure to a string of
CSS. The first argument may be a list of flags for the compiler."
{:arglists '([rules] [flags? rules])}
[& rules]
(apply compiler/compile-css rules))
(defn ^String style
"Convert a variable number of maps into a string of CSS for use with
the HTML `style` attribute."
[& maps]
(compiler/compile-style maps))
| |
dc0949f1e53fd9923062a182d7c4dbcc7a371009257f843211757a8ef667d5f9 | smabie/xs | xs.ml | (* xs.ml *)
* This file is public domain as declared by
* This file is public domain as declared by Sturm Mabie
*)
open Core
let filename_param =
let open Command.Param in
anon ("filename" %: string)
let command =
Random.self_init ();
Command.basic
~summary:"Public domain xs interpreter"
~readme:(fun () ->
{|This is the main binary for the xs language. For more information information
check out the project's github page at |}
)
Command.Let_syntax.(
let%map_open fname = anon (maybe ("filename" %: string)) in
fun () ->
match fname with
| Some f -> Xslib.Top.load f
| None ->
print_endline
{|Public domain interpreter for the xs language. Created by Sturm Mabie
(). For more information check out the project's github at
|};
Xslib.Top.repl ())
let () =
Command.run ~version:"0.1" ~build_info:"" command
| null | https://raw.githubusercontent.com/smabie/xs/9757b10c05ead985e12bb9b301428181a4db07ed/xs.ml | ocaml | xs.ml |
* This file is public domain as declared by
* This file is public domain as declared by Sturm Mabie
*)
open Core
let filename_param =
let open Command.Param in
anon ("filename" %: string)
let command =
Random.self_init ();
Command.basic
~summary:"Public domain xs interpreter"
~readme:(fun () ->
{|This is the main binary for the xs language. For more information information
check out the project's github page at |}
)
Command.Let_syntax.(
let%map_open fname = anon (maybe ("filename" %: string)) in
fun () ->
match fname with
| Some f -> Xslib.Top.load f
| None ->
print_endline
{|Public domain interpreter for the xs language. Created by Sturm Mabie
(). For more information check out the project's github at
|};
Xslib.Top.repl ())
let () =
Command.run ~version:"0.1" ~build_info:"" command
|
469311f13a8ccc0000d3291fed9cf780b52095a8e19f4b8e44a15dad4ff71a37 | may-liu/qtalk | ejabberd_sm_v2.erl | %%----------------------------------------------------------------------
File :
Author : < >
%%% Purpose : Session manager
Created : 24 Nov 2002 by < >
%%%
%%%
ejabberd , Copyright ( C ) 2002 - 2014 ProcessOne
%%%
%%% This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
%%% General Public License for more details.
%%%
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
%%%
%%%----------------------------------------------------------------------
-module(ejabberd_sm_v2).
-author('').
-behaviour(gen_server).
%% API
-export([start_link/0,
route/3,
open_session/5,
open_session/6,
close_session/4,
check_in_subscription/6,
bounce_offline_message/3,
disconnect_removed_user/2,
get_user_resources/2,
get_user_present_resources/2,
set_presence/7,
unset_presence/6,
close_session_unset_presence/5,
dirty_get_sessions_list/0,
dirty_get_my_sessions_list/0,
get_vh_session_list/1,
get_vh_session_number/1,
register_iq_handler/4,
register_iq_handler/5,
unregister_iq_handler/2,
force_update_presence/1,
connected_users/0,
connected_users_number/0,
user_resources/2,
kick_user/2,
get_session_pid/3,
get_user_info/3,
get_user_ip/3,
get_max_user_sessions/2,
get_all_pids/0,
is_existing_resource/3,
insert_chat_msg/9,
record_show/4,
get_user_away_rescources/2,
get_user_session/2,
judge_away_flag/2,
add_datetime_to_packet/3,
add_msectime_to_packet/4,
timestamp_to_xml/1
]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2,
handle_info/2, terminate/2, code_change/3]).
-export([get_user_present_resources_and_pid/2]).
-include("ejabberd.hrl").
-include("logger.hrl").
-include("jlib.hrl").
-include("ejabberd_commands.hrl").
-include_lib("stdlib/include/ms_transform.hrl").
-include("mod_privacy.hrl").
-record(session, {sid, usr, us, priority, info, show}).
-record(session_counter, {vhost, count}).
-record(state, {}).
-record(muc_online_room,
{name_host = {<<"">>, <<"">>} :: {binary(), binary()} | '$1' |
{'_', binary()} | '_',
pid = self() :: pid() | '$2' | '_' | '$1'}).
%% default value for the maximum number of user connections
-define(MAX_USER_SESSIONS, infinity).
-define(DIRECTION, <<"recv">>).
-define(CN, <<"qchat">>).
-define(USRTYPE, <<"common">>).
%%====================================================================
%% API
%%====================================================================
%%--------------------------------------------------------------------
Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error }
%% Description: Starts the server
%%--------------------------------------------------------------------
-type sid() :: {erlang:timestamp(), pid()}.
-type ip() :: {inet:ip_address(), inet:port_number()} | undefined.
-type info() :: [{conn, atom()} | {ip, ip()} | {node, atom()}
| {oor, boolean()} | {auth_module, atom()}].
-type prio() :: undefined | integer().
-export_type([sid/0]).
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [],
[]).
-spec route(jid(), jid(), xmlel() | broadcast()) -> ok.
route(From, To, Packet) ->
case catch do_route(From, To, Packet) of
{'EXIT', Reason} ->
?ERROR_MSG("~p~nwhen processing: ~p",
[Reason, {From, To, Packet}]);
_ -> ok
end.
-spec open_session(sid(), binary(), binary(), binary(), prio(), info()) -> ok.
open_session(SID, User, Server, Resource, Priority, Info) ->
set_session(SID, User, Server, Resource, Priority, Info),
mnesia:dirty_update_counter(session_counter,
jlib:nameprep(Server), 1),
check_for_sessions_to_replace(User, Server, Resource),
JID = jlib:make_jid(User, Server, Resource),
ejabberd_hooks:run(sm_register_connection_hook,
JID#jid.lserver, [SID, JID, Info]).
-spec open_session(sid(), binary(), binary(), binary(), info()) -> ok.
open_session(SID, User, Server, Resource, Info) ->
open_session(SID, User, Server, Resource, undefined, Info).
-spec close_session(sid(), binary(), binary(), binary()) -> ok.
close_session(SID, User, Server, Resource) ->
Info = case mnesia:dirty_read({session, SID}) of
[] -> [];
[#session{info=I}] -> I
end,
F = fun() ->
mnesia:delete({session, SID}),
mnesia:dirty_update_counter(session_counter,
jlib:nameprep(Server), -1)
end,
mnesia:sync_dirty(F),
JID = jlib:make_jid(User, Server, Resource),
%% catch mod_monitor:count_user_login_out(Server,User,0),
% case catch redis_link:hash_get(Server,1,binary_to_list(User),binary_to_list(Resource)) of
% {ok,undefined} ->
% ok;
% {ok,Key} ->
%% catch redis_link:hash_del(Server,1,binary_to_list(User),binary_to_list(Resource)),
% catch redis_link:hash_del(Server,2,binary_to_list(User),binary_to_list(Key));
% _ ->
% ok
% end,
ejabberd_hooks:run(sm_remove_connection_hook,
JID#jid.lserver, [SID, JID, Info]).
check_in_subscription(Acc, User, Server, _JID, _Type, _Reason) ->
case ejabberd_auth:is_user_exists(User, Server) of
true -> Acc;
false -> {stop, false}
end.
-spec bounce_offline_message(jid(), jid(), xmlel()) -> stop.
bounce_offline_message(From, To, Packet) ->
Err = jlib:make_error_reply(Packet,
?ERR_SERVICE_UNAVAILABLE),
ejabberd_router:route(To, From, Err),
stop.
-spec disconnect_removed_user(binary(), binary()) -> ok.
disconnect_removed_user(User, Server) ->
ejabberd_sm:route(jlib:make_jid(<<"">>, <<"">>, <<"">>),
jlib:make_jid(User, Server, <<"">>),
{broadcast, {exit, <<"User removed">>}}).
get_user_resources(User, Server) ->
LUser = jlib:nodeprep(User),
LServer = jlib:nameprep(Server),
US = {LUser, LServer},
case catch mnesia:dirty_index_read(session, US, #session.us) of
{'EXIT', _Reason} ->
[];
Ss ->
[element(3, S#session.usr) || S <- clean_session_list(Ss)]
end.
-spec get_user_present_resources(binary(), binary()) -> [tuple()].
get_user_present_resources(LUser, LServer) ->
US = {LUser, LServer},
case catch mnesia:dirty_index_read(session, US,
#session.us)
of
{'EXIT', _Reason} -> [];
Ss ->
[{S#session.priority, element(3, S#session.usr)}
|| S <- clean_session_list(Ss),
is_integer(S#session.priority)]
end.
get_user_present_resources_and_pid(LUser, LServer) ->
US = {LUser, LServer},
case catch mnesia:dirty_index_read(session, US,
#session.us)
of
{'EXIT', _Reason} -> [];
Ss ->
[{S#session.priority, element(3, S#session.usr),element(2, S#session.sid)}
|| S <- clean_session_list(Ss),
is_integer(S#session.priority)]
end.
get_user_session(LUser, LServer) ->
US = {LUser, LServer},
case catch mnesia:dirty_index_read(session, US,
#session.us)
of
{'EXIT', _Reason} -> [];
Ss ->
[S || S <- clean_session_list(Ss), is_integer(S#session.priority)]
end.
-spec get_user_ip(binary(), binary(), binary()) -> ip().
get_user_ip(User, Server, Resource) ->
LUser = jlib:nodeprep(User),
LServer = jlib:nameprep(Server),
LResource = jlib:resourceprep(Resource),
USR = {LUser, LServer, LResource},
case mnesia:dirty_index_read(session, USR, #session.usr) of
[] ->
undefined;
Ss ->
Session = lists:max(Ss),
proplists:get_value(ip, Session#session.info)
end.
-spec get_user_info(binary(), binary(), binary()) -> info() | offline.
get_user_info(User, Server, Resource) ->
LUser = jlib:nodeprep(User),
LServer = jlib:nameprep(Server),
LResource = jlib:resourceprep(Resource),
USR = {LUser, LServer, LResource},
case mnesia:dirty_index_read(session, USR, #session.usr) of
[] ->
offline;
Ss ->
Session = lists:max(Ss),
Node = node(element(2, Session#session.sid)),
Conn = proplists:get_value(conn, Session#session.info),
IP = proplists:get_value(ip, Session#session.info),
[{node, Node}, {conn, Conn}, {ip, IP}]
end.
-spec set_presence(sid(), binary(), binary(), binary(),
prio(), xmlel(), info()) -> ok.
set_presence(SID, User, Server, Resource, Priority,
Presence, Info) ->
set_session(SID, User, Server, Resource, Priority,
Info),
ejabberd_hooks:run(set_presence_hook,
jlib:nameprep(Server),
[User, Server, Resource, Presence]).
-spec unset_presence(sid(), binary(), binary(),
binary(), binary(), info()) -> ok.
unset_presence(SID, User, Server, Resource, Status,
Info) ->
set_session(SID, User, Server, Resource, undefined,
Info),
ejabberd_hooks:run(unset_presence_hook,
jlib:nameprep(Server),
[User, Server, Resource, Status]).
-spec close_session_unset_presence(sid(), binary(), binary(),
binary(), binary()) -> ok.
close_session_unset_presence(SID, User, Server,
Resource, Status) ->
close_session(SID, User, Server, Resource),
ejabberd_hooks:run(unset_presence_hook,
jlib:nameprep(Server),
[User, Server, Resource, Status]).
-spec get_session_pid(binary(), binary(), binary()) -> none | pid().
get_session_pid(User, Server, Resource) ->
LUser = jlib:nodeprep(User),
LServer = jlib:nameprep(Server),
LResource = jlib:resourceprep(Resource),
USR = {LUser, LServer, LResource},
case catch mnesia:dirty_index_read(session, USR, #session.usr) of
[#session{sid = {_, Pid}}] -> Pid;
_ -> none
end.
-spec dirty_get_sessions_list() -> [ljid()].
dirty_get_sessions_list() ->
mnesia:dirty_select(
session,
[{#session{usr = '$1', _ = '_'},
[],
['$1']}]).
dirty_get_my_sessions_list() ->
mnesia:dirty_select(
session,
[{#session{sid = {'_', '$1'}, _ = '_'},
[{'==', {node, '$1'}, node()}],
['$_']}]).
-spec get_vh_session_list(binary()) -> [ljid()].
get_vh_session_list(Server) ->
LServer = jlib:nameprep(Server),
mnesia:dirty_select(session,
[{#session{usr = '$1', _ = '_'},
[{'==', {element, 2, '$1'}, LServer}], ['$1']}]).
-spec get_all_pids() -> [pid()].
get_all_pids() ->
mnesia:dirty_select(
session,
ets:fun2ms(
fun(#session{sid = {_, Pid}}) ->
Pid
end)).
get_vh_session_number(Server) ->
LServer = jlib:nameprep(Server),
Query = mnesia:dirty_select(
session_counter,
[{#session_counter{vhost = LServer, count = '$1'},
[],
['$1']}]),
case Query of
[Count] ->
Count;
_ -> 0
end.
register_iq_handler(Host, XMLNS, Module, Fun) ->
ejabberd_sm !
{register_iq_handler, Host, XMLNS, Module, Fun}.
-spec register_iq_handler(binary(), binary(), atom(), atom(), list()) -> any().
register_iq_handler(Host, XMLNS, Module, Fun, Opts) ->
ejabberd_sm !
{register_iq_handler, Host, XMLNS, Module, Fun, Opts}.
-spec unregister_iq_handler(binary(), binary()) -> any().
unregister_iq_handler(Host, XMLNS) ->
ejabberd_sm ! {unregister_iq_handler, Host, XMLNS}.
%%====================================================================
%% gen_server callbacks
%%====================================================================
%%--------------------------------------------------------------------
%% Function: init(Args) -> {ok, State} |
{ ok , State , Timeout } |
%% ignore |
%% {stop, Reason}
%% Description: Initiates the server
%%--------------------------------------------------------------------
init([]) ->
update_tables(),
mnesia:create_table(session,
[{ram_copies, [node()]},
{attributes, record_info(fields, session)}]),
mnesia:create_table(session_counter,
[{ram_copies, [node()]},
{attributes, record_info(fields, session_counter)}]),
mnesia:add_table_index(session, usr),
mnesia:add_table_index(session, us),
mnesia:add_table_index(session, show),
mnesia:add_table_copy(session, node(), ram_copies),
mnesia:add_table_copy(session_counter, node(), ram_copies),
mnesia:subscribe(system),
ets:new(sm_iqtable, [named_table]),
lists:foreach(
fun(Host) ->
ejabberd_hooks:add(roster_in_subscription, Host,
ejabberd_sm, check_in_subscription, 20),
ejabberd_hooks:add(offline_message_hook, Host,
ejabberd_sm, bounce_offline_message, 100),
ejabberd_hooks:add(remove_user, Host,
ejabberd_sm, disconnect_removed_user, 100)
end, ?MYHOSTS),
ejabberd_commands:register_commands(commands()),
{ok, #state{}}.
%%--------------------------------------------------------------------
Function : % % handle_call(Request , From , State ) - > { reply , Reply , State } |
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, Reply, State} |
%% {stop, Reason, State}
%% Description: Handling call messages
%%--------------------------------------------------------------------
handle_call(_Request, _From, State) ->
Reply = ok, {reply, Reply, State}.
%%--------------------------------------------------------------------
Function : handle_cast(Msg , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State}
%% Description: Handling cast messages
%%--------------------------------------------------------------------
handle_cast(_Msg, State) -> {noreply, State}.
%%--------------------------------------------------------------------
Function : handle_info(Info , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State}
%% Description: Handling all non call/cast messages
%%--------------------------------------------------------------------
handle_info({route, From, To, Packet}, State) ->
case catch do_route(From, To, Packet) of
{'EXIT', Reason} ->
?ERROR_MSG("~p~nwhen processing: ~p",
[Reason, {From, To, Packet}]);
_ ->
ok
end,
{noreply, State};
handle_info({mnesia_system_event, {mnesia_down, Node}}, State) ->
recount_session_table(Node),
{noreply, State};
handle_info({register_iq_handler, Host, XMLNS, Module, Function}, State) ->
ets:insert(sm_iqtable, {{XMLNS, Host}, Module, Function}),
{noreply, State};
handle_info({register_iq_handler, Host, XMLNS, Module,
Function, Opts},
State) ->
ets:insert(sm_iqtable,
{{XMLNS, Host}, Module, Function, Opts}),
{noreply, State};
handle_info({unregister_iq_handler, Host, XMLNS},
State) ->
case ets:lookup(sm_iqtable, {XMLNS, Host}) of
[{_, Module, Function, Opts}] ->
gen_iq_handler:stop_iq_handler(Module, Function, Opts);
_ -> ok
end,
ets:delete(sm_iqtable, {XMLNS, Host}),
{noreply, State};
handle_info(_Info, State) -> {noreply, State}.
%%--------------------------------------------------------------------
%% Function: terminate(Reason, State) -> void()
%% Description: This function is called by a gen_server when it is about to
%% terminate. It should be the opposite of Module:init/1 and do any necessary
%% cleaning up. When it returns, the gen_server terminates with Reason.
%% The return value is ignored.
%%--------------------------------------------------------------------
terminate(_Reason, _State) ->
ejabberd_commands:unregister_commands(commands()),
ok.
%%--------------------------------------------------------------------
Func : code_change(OldVsn , State , Extra ) - > { ok , NewState }
%% Description: Convert process state when code is changed
%%--------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) -> {ok, State}.
%%--------------------------------------------------------------------
Internal functions
%%--------------------------------------------------------------------
set_session(SID, User, Server, Resource, Priority, Info) ->
LUser = jlib:nodeprep(User),
LServer = jlib:nameprep(Server),
LResource = jlib:resourceprep(Resource),
US = {LUser, LServer},
USR = {LUser, LServer, LResource},
F = fun () ->
mnesia:write(#session{sid = SID, usr = USR, us = US,
priority = Priority, info = Info, show = <<"normal">>})
end,
mnesia:sync_dirty(F).
Recalculates alive sessions when goes down
and updates session and session_counter tables
recount_session_table(Node) ->
F = fun() ->
Es = mnesia:select(
session,
[{#session{sid = {'_', '$1'}, _ = '_'},
[{'==', {node, '$1'}, Node}],
['$_']}]),
lists:foreach(fun(E) ->
mnesia:delete({session, E#session.sid})
end, Es),
%% reset session_counter table with active sessions
mnesia:clear_table(session_counter),
lists:foreach(fun(Server) ->
LServer = jlib:nameprep(Server),
Hs = mnesia:select(session,
[{#session{usr = '$1', _ = '_'},
[{'==', {element, 2, '$1'}, LServer}],
['$1']}]),
mnesia:write(
#session_counter{vhost = LServer,
count = length(Hs)})
end, ?MYHOSTS)
end,
mnesia:async_dirty(F).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
do_route(From, To, {broadcast, _} = Packet) ->
case To#jid.lresource of
<<"">> ->
lists:foreach(fun(R) ->
do_route(From,
jlib:jid_replace_resource(To, R),
Packet)
end,
get_user_resources(To#jid.user, To#jid.server));
_ ->
USR = jlib:jid_tolower(To),
case mnesia:dirty_index_read(session, USR, #session.usr) of
[] ->
?DEBUG("packet dropped~n", []);
Ss ->
Session = lists:max(Ss),
Pid = element(2, Session#session.sid),
?DEBUG("sending to process ~p~n", [Pid]),
Pid ! {route, From, To, Packet}
end
end;
do_route(From, To, #xmlel{} = Packet) ->
% ?DEBUG("session manager~n\tfrom ~p~n\tto ~p~n\tpacket "
% "~P~n",
[ From , To , Packet , 8 ] ) ,
#jid{user = User, server = Server,
luser = LUser, lserver = LServer, lresource = LResource} = To,
#xmlel{name = Name, attrs = Attrs, children = Els} = Packet,
case LResource of
<<"">> ->
case Name of
<<"presence">> ->
{Pass, _Subsc} = case xml:get_attr_s(<<"type">>, Attrs)
of
<<"subscribe">> ->
Reason = xml:get_path_s(Packet,
[{elem,
<<"status">>},
cdata]),
{is_privacy_allow(From, To, Packet)
andalso
ejabberd_hooks:run_fold(roster_in_subscription,
LServer,
false,
[User, Server,
From,
subscribe,
Reason]),
true};
<<"subscribed">> ->
{is_privacy_allow(From, To, Packet)
andalso
ejabberd_hooks:run_fold(roster_in_subscription,
LServer,
false,
[User, Server,
From,
subscribed,
<<"">>]),
true};
<<"unsubscribe">> ->
{is_privacy_allow(From, To, Packet)
andalso
ejabberd_hooks:run_fold(roster_in_subscription,
LServer,
false,
[User, Server,
From,
unsubscribe,
<<"">>]),
true};
<<"unsubscribed">> ->
{is_privacy_allow(From, To, Packet)
andalso
ejabberd_hooks:run_fold(roster_in_subscription,
LServer,
false,
[User, Server,
From,
unsubscribed,
<<"">>]),
true};
_ -> {true, false}
end,
if Pass ->
handle_presence(LServer,From,To,Packet,Attrs);
true -> ok
end;
<<"message">> ->
route_message(From, To, Packet);
<<"iq">> -> process_iq(From, To, Packet);
_ -> ok
end;
_ ->
USR = {LUser, LServer, LResource},
case mnesia:dirty_index_read(session, USR, #session.usr)
of
[] ->
case Name of
<<"message">> -> route_message(From, To, Packet);
<<"iq">> ->
case xml:get_attr_s(<<"type">>, Attrs) of
<<"error">> -> ok;
<<"result">> -> ok;
_ ->
Err = jlib:make_error_reply(Packet,
?ERR_SERVICE_UNAVAILABLE),
ejabberd_router:route(To, From, Err)
end;
_ -> ?DEBUG("packet droped~n", [])
end;
Ss ->
Session = lists:max(Ss),
Pid = element(2, Session#session.sid),
NewPacket =
case Name of
<<"message">> ->
make_new_packet(From,To,Packet,Name,Attrs,Els);
<<"iq">> ->
insert_user_mucs(From,To,Packet),
Packet;
_ ->
Packet
end,
Pid ! {route, From, To, NewPacket}
end
end.
%% The default list applies to the user as a whole,
%% and is processed if there is no active list set
%% for the target session/resource to which a stanza is addressed,
%% or if there are no current sessions for the user.
is_privacy_allow(From, To, Packet) ->
User = To#jid.user,
Server = To#jid.server,
PrivacyList =
ejabberd_hooks:run_fold(privacy_get_user_list, Server,
#userlist{}, [User, Server]),
is_privacy_allow(From, To, Packet, PrivacyList).
%% Check if privacy rules allow this delivery
%% Function copied from ejabberd_c2s.erl
is_privacy_allow(From, To, Packet, PrivacyList) ->
User = To#jid.user,
Server = To#jid.server,
allow ==
ejabberd_hooks:run_fold(privacy_check_packet, Server,
allow,
[User, Server, PrivacyList, {From, To, Packet},
in]).
route_message(From, To, Packet) ->
LUser = To#jid.luser,
LServer = To#jid.lserver,
case xml:get_tag_attr_s(<<"type">>, Packet) of
<<"readmark">> ->
readmark:readmark_message(From,To,Packet);
<<"revoke">> ->
revoke:revoke_message(From,To,Packet);
_ ->
PrioRes = get_user_present_resources(LUser, LServer),
#xmlel{name = Name, attrs = Attrs, children = Els} = Packet,
NewPacket = make_new_packet(From,To,Packet,Name,Attrs,Els),
case catch lists:max(PrioRes) of
{Priority, _R}
when is_integer(Priority), Priority >= 0 ->
catch send_max_priority_msg(LUser,LServer,Priority,From,To,NewPacket,PrioRes);
_ ->
case xml:get_tag_attr_s(<<"type">>, Packet) of
<<"error">> -> ok;
<<"groupchat">> -> ok;
<<"subscription">>->
subscription:subscription_message(From,To,Packet);
<<"readmark">> ->
readmark:readmark_message(From,To,Packet);
<<"consult">> ->
consult_message(From,To,Packet);
_ ->
case ejabberd_auth:is_user_exists(LUser, LServer) of
true ->
case is_privacy_allow(From, To, Packet) of
true ->
case catch check_carbon_msg(Packet) of
true ->
ok;
_ ->
ejabberd_hooks:run(offline_message_hook, LServer,
[From, To, Packet])
end;
_ ->
ok
end;
_ ->
Err = jlib:make_error_reply(Packet,
?ERR_SERVICE_UNAVAILABLE),
ejabberd_router:route(To, From, Err)
end
end
end
end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clean_session_list(Ss) ->
clean_session_list(lists:keysort(#session.usr, Ss), []).
clean_session_list([], Res) -> Res;
clean_session_list([S], Res) -> [S | Res];
clean_session_list([S1, S2 | Rest], Res) ->
if S1#session.usr == S2#session.usr ->
if S1#session.sid > S2#session.sid ->
clean_session_list([S1 | Rest], Res);
true -> clean_session_list([S2 | Rest], Res)
end;
true -> clean_session_list([S2 | Rest], [S1 | Res])
end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% On new session, check if some existing connections need to be replace
check_for_sessions_to_replace(User, Server, Resource) ->
LUser = jlib:nodeprep(User),
LServer = jlib:nameprep(Server),
LResource = jlib:resourceprep(Resource),
check_existing_resources(LUser, LServer, LResource),
check_max_sessions(LUser, LServer).
check_existing_resources(LUser, LServer, LResource) ->
SIDs = get_resource_sessions(LUser, LServer, LResource),
if SIDs == [] -> ok;
true ->
MaxSID = lists:max(SIDs),
lists:foreach(fun ({_, Pid} = S) when S /= MaxSID ->
Pid ! replaced;
(_) -> ok
end,
SIDs)
end.
-spec is_existing_resource(binary(), binary(), binary()) -> boolean().
is_existing_resource(LUser, LServer, LResource) ->
[] /= get_resource_sessions(LUser, LServer, LResource).
get_resource_sessions(User, Server, Resource) ->
USR = {jlib:nodeprep(User), jlib:nameprep(Server),
jlib:resourceprep(Resource)},
mnesia:dirty_select(session,
[{#session{sid = '$1', usr = USR, _ = '_'}, [],
['$1']}]).
check_max_sessions(LUser, LServer) ->
SIDs = mnesia:dirty_select(session,
[{#session{sid = '$1', us = {LUser, LServer},
_ = '_'},
[], ['$1']}]),
MaxSessions = get_max_user_sessions(LUser, LServer),
if length(SIDs) =< MaxSessions -> ok;
true -> {_, Pid} = lists:min(SIDs), Pid ! replaced
end.
%% Get the user_max_session setting
This option defines the number of time a given users are allowed to
%% log in
%% Defaults to infinity
get_max_user_sessions(LUser, Host) ->
case acl:match_rule(Host, max_user_sessions,
jlib:make_jid(LUser, Host, <<"">>))
of
Max when is_integer(Max) -> Max;
infinity -> infinity;
_ -> ?MAX_USER_SESSIONS
end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
process_iq(From, To, Packet) ->
IQ = jlib:iq_query_info(Packet),
case IQ of
#iq{xmlns = XMLNS} ->
Host = To#jid.lserver,
case ets:lookup(sm_iqtable, {XMLNS, Host}) of
[{_, Module, Function}] ->
ResIQ = Module:Function(From, To, IQ),
if ResIQ /= ignore ->
ejabberd_router:route(To, From, jlib:iq_to_xml(ResIQ));
true -> ok
end;
[{_, Module, Function, Opts}] ->
gen_iq_handler:handle(Host, Module, Function, Opts,
From, To, IQ);
[] ->
Err = jlib:make_error_reply(Packet,
?ERR_SERVICE_UNAVAILABLE),
ejabberd_router:route(To, From, Err)
end;
reply -> insert_user_mucs(From,To,Packet), ok;
_ ->
Err = jlib:make_error_reply(Packet, ?ERR_BAD_REQUEST),
ejabberd_router:route(To, From, Err),
ok
end.
-spec force_update_presence({binary(), binary()}) -> any().
force_update_presence({LUser, _LServer} = US) ->
case catch mnesia:dirty_index_read(session, US,
#session.us)
of
{'EXIT', _Reason} -> ok;
Ss ->
lists:foreach(fun (#session{sid = {_, Pid}}) ->
Pid ! {force_update_presence, LUser}
end,
Ss)
end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% ejabberd commands
commands() ->
[#ejabberd_commands{name = connected_users,
tags = [session],
desc = "List all established sessions",
module = ?MODULE, function = connected_users, args = [],
result = {connected_users, {list, {sessions, string}}}},
#ejabberd_commands{name = connected_users_number,
tags = [session, stats],
desc = "Get the number of established sessions",
module = ?MODULE, function = connected_users_number,
args = [], result = {num_sessions, integer}},
#ejabberd_commands{name = user_resources,
tags = [session],
desc = "List user's connected resources",
module = ?MODULE, function = user_resources,
args = [{user, binary}, {host, binary}],
result = {resources, {list, {resource, string}}}},
#ejabberd_commands{name = kick_user,
tags = [session],
desc = "Disconnect user's active sessions",
module = ?MODULE, function = kick_user,
args = [{user, binary}, {host, binary}],
result = {num_resources, integer}}].
-spec connected_users() -> [binary()].
connected_users() ->
USRs = dirty_get_sessions_list(),
SUSRs = lists:sort(USRs),
lists:map(fun ({U, S, R}) -> <<U/binary, $@, S/binary, $/, R/binary>> end,
SUSRs).
connected_users_number() ->
length(dirty_get_sessions_list()).
user_resources(User, Server) ->
Resources = get_user_resources(User, Server),
lists:sort(Resources).
kick_user(User, Server) ->
Resources = get_user_resources(User, Server),
lists:foreach(
fun(Resource) ->
PID = get_session_pid(User, Server, Resource),
PID ! disconnect
end, Resources),
length(Resources).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Update Mnesia tables
update_tables() ->
case catch mnesia:table_info(session, attributes) of
[ur, user, node] -> mnesia:delete_table(session);
[ur, user, pid] -> mnesia:delete_table(session);
[usr, us, pid] -> mnesia:delete_table(session);
[usr, us, sid, priority, info] -> mnesia:delete_table(session);
[usr, us, sid, priority, info, show] -> mnesia:delete_table(session);
[sid, usr, us, priority] ->
mnesia:delete_table(session);
%% [sid, usr, us, priority, info] -> ok;
[sid, usr, us, priority, info] ->
mnesia:delete_table(session);
[sid, usr, us, priority, info,show] -> ok;
{'EXIT', _} -> ok
end,
case lists:member(presence, mnesia:system_info(tables))
of
true -> mnesia:delete_table(presence);
false -> ok
end,
case lists:member(local_session, mnesia:system_info(tables)) of
true ->
mnesia:delete_table(local_session);
false ->
ok
end.
insert_chat_msg(Server,From, To,From_host,To_host, Msg,_Body,ID,InsertTime) ->
case jlib:nodeprep(From) of
error -> {error, invalid_jid};
LUser ->
LFrom = ejabberd_odbc:escape(LUser),
LTo = ejabberd_odbc:escape(To),
LBody = ejabberd_odbc:escape(Msg),
LID = ejabberd_odbc:escape(ID),
LServer = get_server(From_host,To_host),
Time = ejabberd_public:pg2timestamp(InsertTime),
case str:str(LID,<<"http">>) of
0 ->
case catch odbc_queries:insert_msg6(LServer, LFrom,LTo,From_host,To_host,LBody,LID,Time) of
{updated, 1} -> {atomic, ok};
A ->
?INFO_MSG("Insert Msg error Body: ~p ,~p ~n",[A,LBody]),
{atomic, exists}
end;
_ ->
case ejabberd_public:judge_spec_jid(LFrom,LTo) of
true ->
case catch odbc_queries:insert_msg4(LServer, LFrom,LTo,From_host,To_host,LBody,LID,Time) of
{updated, 1} -> {atomic, ok};
_ ->
?INFO_MSG("Insert Msg error Body: ~p ~n",[LBody]),
{atomic, exists}
end;
_ ->
case catch odbc_queries:insert_msg5(LServer, LFrom,LTo,From_host,To_host,LBody,LID,Time) of
{updated, 1} -> {atomic, ok};
_ ->
?INFO_MSG("Insert Msg error Body: ~p ~n",[LBody]),
{atomic, exists}
end
end
end
end.
timestamp_to_xml({{Year, Month, Day},
{Hour, Minute, Second}}) ->
#xmlel{name = <<"stime">>,
attrs =
[{<<"xmlns">>, ?NS_TIME91},
{<<"stamp">>,iolist_to_binary(
io_lib:format("~4..0w~2..0w~2..0wT~2..0w:~2..0w:~2..0w",[Year, Month, Day, Hour, Minute,Second]))}],children = []}.
record_show(User,Server,Resource,Show) ->
LUser = jlib:nodeprep(User),
LServer = jlib:nameprep(Server),
LResource = jlib:resourceprep(Resource),
US = {LUser, LServer},
USR = {LUser, LServer, LResource},
case mnesia:dirty_index_read(session, USR, #session.usr) of
[] ->
ok;
Ss ->
Session = lists:max(Ss),
F = fun () ->
mnesia:write(Session#session{usr = USR,us = US, show = Show}) end,
mnesia:sync_dirty(F)
end.
判读特殊情况,聊天室用户非正常退出,导致存在于聊天室中的#state.users表中 ,
judge_to_user_available(_FServer,<<"">>,_R)->
true;
judge_to_user_available(FServer,Rescource,R) ->
case str:str(FServer,<<"conference">>) of
0 ->
true;
_ ->
if Rescource == R ->
true;
true ->
false
end
end.
send_muc_room_remove_unavailable_user(From,To) ->
case mnesia:dirty_read(muc_online_room, {From#jid.user, From#jid.server}) of
[] ->
ok;
[Muc] ->
Muc_Pid = Muc#muc_online_room.pid,
Muc_Pid ! {delete_unavailable_user,To}
end.
get_user_away_rescources(User, Server) ->
LUser = jlib:nodeprep(User),
LServer = jlib:nameprep(Server),
US = {LUser, LServer},
case catch mnesia:dirty_index_read(session, US, #session.us) of
{'EXIT', _Reason} ->
[];
[] ->
[<<"none">>];
Ss ->
lists:flatmap(fun(S) ->
case S#session.show of
<<"away">> ->
[element(3, S#session.usr)];
_ ->
[]
end
end,clean_session_list(Ss))
end.
insert_away_spool(From,To,LServer,Packet) ->
FromUsername = ejabberd_odbc:escape(From#jid.luser),
Username = ejabberd_odbc:escape(To#jid.luser),
#xmlel{name = Name,attrs = Attrs, children = Els} = Packet,
TimeStamp = os:timestamp(),
NewPacket = #xmlel{name = Name,attrs = Attrs,
children =
Els ++ [jlib:timestamp_to_xml(calendar:now_to_universal_time(TimeStamp),
utc, jlib:make_jid(<<"">>,From#jid.lserver ,<<"">>),
<<"Offline Storage">>),
jlib:timestamp_to_xml(calendar:now_to_universal_time(TimeStamp))]},
case catch ets:lookup(mac_push_notice,{Username,FromUsername}) of
[] ->
catch odbc_queries:add_spool_away(LServer,FromUsername,Username,
ejabberd_odbc:escape(xml:element_to_binary(NewPacket)),<<"0">>);
_ ->
catch odbc_queries:add_spool_away(LServer,FromUsername,Username,
ejabberd_odbc:escape(xml:element_to_binary(NewPacket)),<<"1">>)
end.
try_insert_msg(From,To,Packet,Mbody) ->
#xmlel{name = Name, attrs = Attrs, children = Els} = Packet,
LServer = To#jid.lserver,
case ejabberd_public:is_conference_server(From#jid.lserver) of
false ->
insert_user_chat_msg(From,To,Packet,Attrs,Els,Mbody,LServer);
_ ->
insert_muc_chat_msg(From,To,Packet,Name,Attrs,Els,Mbody,LServer)
end.
insert_user_chat_msg(From,To,Packet,Attrs,Els,Mbody,LServer) ->
catch mod_monitor:monitor_count(LServer,<<"chat_message">>,1),
Carbon = xml:get_attr_s(<<"carbon_message">>, Attrs),
Now = mod_time:get_exact_timestamp(),
case Carbon =/= <<"true">> andalso (not mod_muc_room:is_invitation(Els)) of
true ->
Msg_id = xml:get_tag_attr_s(<<"id">>,xml:get_subtag(Packet,<<"body">>)),
insert_chat_msg(LServer,From#jid.user,To#jid.user,From#jid.lserver,To#jid.lserver, xml:element_to_binary(
Packet),Mbody,Msg_id,Now);
_ ->
ok
end.
insert_muc_chat_msg(From,To,_Packet,Name,Attrs,Els,Mbody,LServer)->
case mnesia:dirty_read(muc_online_room, {From#jid.user, From#jid.server}) of
[] ->
add_datetime_to_packet(Name,Attrs,Els);
[Muc] ->
Now = mod_time:get_exact_timestamp(),
Time = trunc(Now/1000),
NewPacket = add_datetime_to_packet(Name,[{<<"msec_times">>,integer_to_binary(Now )}] ++ Attrs,
Els,timestamp_to_xml(mod_time:timestamp_to_datetime_utc1(Time))),
Muc_Pid = Muc#muc_online_room.pid,
Muc_Pid ! {insert_chat_msg,LServer,From,To,From#jid.lserver,To#jid.lserver,NewPacket,Mbody,Time},
NewPacket
end.
send_max_priority_msg(LUser,LServer,Priority,From,To,NewPacket,PrioRes) ->
Status_and_Resources = send_msg_and_get_resources(LUser,LServer,Priority,From,To,NewPacket,PrioRes),
case judge_away_flag(Status_and_Resources,false) of
false ->
ok;
_ ->
#xmlel{attrs = Attrs, children = Els} = NewPacket,
Mtype = xml:get_attr_s(<<"type">>, Attrs),Mbody = xml:get_subtag_cdata(NewPacket, <<"body">>),
Delay = xml:get_subtag_cdata(NewPacket,<<"delay">>),
Carbon_message = xml:get_attr_s(<<"carbon_message">>, Attrs),
case (Mtype == <<"normal">> orelse Mtype == <<"chat">>)
andalso Mbody /= <<>> andalso Delay /= <<"Offline Storage">>
andalso Carbon_message /= <<"true">> of
true ->
case (not mod_muc_room:is_invitation(Els)) andalso
xml:get_tag_attr_s(<<"msgType">>,xml:get_subtag(NewPacket,<<"body">>)) =/= <<"1024">> of
true -> insert_away_spool(From,To,LServer,NewPacket);
_ -> ok
end;
_ ->
ok
end
end.
send_msg_and_get_resources(LUser,LServer,Priority,From,To,NewPacket,PrioRes) ->
lists:flatmap(fun ({P, R}) when P == Priority ->
LResource = jlib:resourceprep(R),
USR = {LUser, LServer, LResource},
case mnesia:dirty_index_read(session, USR, #session.usr) of
[] ->
[]; % Race condition
Ss ->
case judge_to_user_available(From#jid.server,To#jid.lresource,LResource) of
true ->
Session = lists:max(Ss),
Pid = element(2, Session#session.sid),
?DEBUG("sending to process ~p~n", [Pid]),
Pid ! {route, From, To, NewPacket},
[{Session#session.show,LResource}];
_ ->
?INFO_MSG("Rescoure not match ~p : ~p ~n",[R,To#jid.lresource]),
send_muc_room_remove_unavailable_user(From,To),
[]
end
end;
%% Ignore other priority:
({_Prio, _Res}) -> []
end,PrioRes).
judge_away_flag(Resources,Offline_send_flag) ->
{Away_lan_num,Normal_lan_num,Away_wlan_num,Normal_wlan_num} = get_resources_num(Resources,0,0,0,0),
case Resources of
[] ->
case Offline_send_flag of
true ->
true;
_ ->
false
end;
_ ->
case Away_wlan_num + Away_lan_num =:= 0 of
true ->
false;
_ ->
case Away_lan_num > 0 of
true ->
true;
_ ->
case Away_wlan_num =/= 0 andalso Normal_lan_num =:= 0 of
true ->
true;
_ ->
false
end
end
end
end.
get_resources_num([],A_lan_num,N_lan_num,A_wlan_num,N_wlan_num) ->
{A_lan_num,N_lan_num,A_wlan_num,N_wlan_num};
get_resources_num(Rs,A_lan_num,N_lan_num,A_wlan_num,N_wlan_num) ->
[{S,R} | L ] = Rs,
if S =:= <<"away">> ->
case str:str(R,<<"iPhone">>) =/= 0 orelse str:str(R,<<"Android">>) =/= 0 orelse str:str(R,<<"IOS">>) =/= 0 of
true ->
get_resources_num(L, A_lan_num,N_lan_num,A_wlan_num + 1,N_wlan_num);
_ ->
get_resources_num(L, A_lan_num+1,N_lan_num,A_wlan_num,N_wlan_num)
end;
true ->
case str:str(R,<<"iPhone">>) =/= 0 orelse str:str(R,<<"Android">>) =/= 0 orelse str:str(R,<<"IOS">>) =/= 0 of
true ->
get_resources_num(L, A_lan_num,N_lan_num,A_wlan_num,N_wlan_num+1);
_ ->
get_resources_num(L, A_lan_num,N_lan_num+1,A_wlan_num,N_wlan_num)
end
end.
make_new_packet(From,To,Packet,Name,Attrs,Els) ->
Mtype = xml:get_attr_s(<<"type">>, Attrs),
case Mtype == <<"normal">> orelse Mtype == <<"chat">> orelse Mtype == <<"consult">> of
true ->
Reply = xml:get_attr_s(<<"auto_reply">>, Attrs),
Reply1 = xml:get_attr_s(<<"atuo_reply">>, Attrs),
Mbody = xml:get_subtag_cdata(Packet, <<"body">>),
Delay = xml:get_subtag_cdata(Packet,<<"delay">>),
case Mbody =/= <<>> andalso Delay =/= <<"Offline Storage">> andalso Reply =/= <<"true">>
andalso Reply1 =/= <<"true">> of
true ->
case xml:get_attr_s(<<"msec_times">>, Attrs) of
<<"">> ->
NewPacket = add_datetime_to_packet(Name,Attrs,Els),
try_insert_msg(From,To,NewPacket,Mbody),
NewPacket;
_ ->
?INFO_MSG("Packet ~p ~n",[Packet]),
Packet
end;
_ ->
Packet
end;
_ ->
Packet
end.
add_datetime_to_packet(Name,Attrs,Els) ->
Now = mod_time:get_exact_timestamp(),
add_datetime_to_packet(Name,
[{<<"msec_times">>,integer_to_binary(Now )}] ++ Attrs,Els,
timestamp_to_xml(mod_time:timestamp_to_datetime_utc1(trunc(Now/1000)))).
add_datetime_to_packet(Name,Attrs,Els,Time) ->
#xmlel{name = Name, attrs = Attrs, children = Els ++ [Time]}.
add_msectime_to_packet(Name,Attrs,Els,Time) ->
#xmlel{name = Name, attrs = [{<<"msec_times">>,integer_to_binary(Time)}] ++ Attrs,
children = Els ++ [timestamp_to_xml(mod_time:timestamp_to_datetime_utc1(trunc(Time/1000)))]}.
make_verify_friend_packet(Num,Rslt,From,To,Packet,Attrs) ->
Num1 = case proplists:get_value(<<"num">>,Rslt) of
undefined ->
0;
V ->
V
end,
case Num < 300 andalso Num1 < 300 of
true ->
case proplists:get_value(<<"mode">>,Rslt) of
<<"0">> ->
do_make_verify_friend_packet(?NS_VER_FRI,<<"refused">>,<<"all_refuse">>,2);
<<"1">> ->
{Packet,1};
<<"2">> ->
case xml:get_attr_s(<<"answer">>, Attrs) == proplists:get_value(<<"answer">>,Rslt) of
true ->
do_make_verify_friend_packet(?NS_VER_FRI,<<"success">>,<<"answer_right">>,2) ;
_ ->
do_make_verify_friend_packet(?NS_VER_FRI,<<"refused">>,<<"answer_errror">>,2)
end;
<<"3">> ->
do_make_verify_friend_packet(?NS_VER_FRI,<<"success">>,<<"all_accpet">>,2);
_ ->
do_make_verify_friend_packet(?NS_VER_FRI,<<"success">>,<<"default_config">>,2)
end;
false ->
do_make_verify_friend_packet(?NS_VER_FRI,<<"refused">>,<<"out of max friend num">>,2)
end.
do_make_verify_friend_packet(XMLNS,Rslt,Reason,Two_ways) ->
{#xmlel{name = <<"presence">>,
attrs = [{<<"xmlns">>,XMLNS},{<<"type">>,<<"handle_friend_result">>},{<<"result">>,Rslt},{<<"reason">>,Reason}],
children = []},Two_ways}.
do_make_verify_friend_packet1(XMLNS,Rslt,Reason,Two_ways) ->
{#xmlel{name = <<"presence">>,
attrs = [{<<"xmlns">>,XMLNS},{<<"body">>,Reason}],
children = []},Two_ways}.
send_presence_packet(From,To,Packet) ->
PResources = get_user_present_resources(To#jid.luser, To#jid.lserver),
lists:foreach(fun ({_, R}) ->
do_route(From,
jlib:jid_replace_resource(To,
R),
Packet)
end,
PResources).
send_presence_packet1(From,To,Packet,Attrs) ->
PResources = get_user_present_resources(To#jid.luser, To#jid.lserver),
case PResources of
[] ->
Body = xml:get_attr_s(<<"body">>, Attrs),
catch insert_presence_spool(From#jid.server,From#jid.luser,To#jid.luser,Body);
_ ->
lists:foreach(fun ({_, R}) ->
do_route(From,
jlib:jid_replace_resource(To,
R),
Packet)
end,
PResources)
end.
insert_presence_spool(Server,From,To,Body) ->
Timestamp = integer_to_binary(mod_time:get_timestamp()),
case catch ejabberd_odbc:sql_query(Server,
[<<"udpate invite_spool set timestamp = ">>,Timestamp,<<",Body = '">>,Body,<<"' where username = '">>,To,<<"' and inviter = '">>,
From,<<"';">>]) of
{updated,1} ->
ok;
_ ->
case catch ejabberd_odbc:sql_query(Server,
[<<"insert into invite_spool(username,inviter,body,timestamp) values ('">>,
To,<<"','">>,From,<<"','">>,ejabberd_odbc:escape(Body),<<"',">>,Timestamp,<<")">>]) of
{updated,1} ->
ok;
_ ->
ok
end
end.
delete_presence_spool(Server,From,To) ->
case catch ejabberd_odbc:sql_query(Server,
[<<"delete from invite_spool where username = '">>,From,<<"' and inviter = '">>,To,<<"';">>]) of
{updated,1} ->
ok;
_ ->
ok
end.
handle_presence(LServer,From,To,Packet,Attrs) ->
User = To#jid.luser,
case xml:get_attr_s(<<"type">>, Attrs) of
<<"verify_friend">> ->
Rslt = mod_user_relation:do_verify_friend(LServer,User),
Num =
case xml:get_attr_s(<<"friend_num">>,Attrs) of
<<>> ->
0;
N when is_binary(N) ->
binary_to_integer(N);
_ ->
0
end,
{NewPacket,Two_way} = make_verify_friend_packet(Num,Rslt,From,To,Packet,Attrs),
case Two_way of
1 ->
send_presence_packet1(From,To,NewPacket,Attrs);
_ ->
ejabberd_router:route(From,jlib:jid_replace_resource(To,<<"">>),NewPacket),
ejabberd_router:route(To,jlib:jid_replace_resource(From,<<"">>),xml:replace_tag_attr(<<"direction">>, <<"2">>, NewPacket))
end;
<<"manual_authentication_confirm">> ->
case xml:get_attr_s(<<"result">>, Attrs) of
<<"allow">> ->
Num1 = mod_user_relation:get_users_friend_num(LServer,User),
Num = binary_to_integer(xml:get_attr_s(<<"friend_num">>,Attrs)),
case Num1 < 300 andalso Num < 300 of
true ->
{NewPacket,_} = do_make_verify_friend_packet(?NS_VER_FRI,<<"success">>,<<"manual_authentication_confirm_success">>,1),
ejabberd_router:route(From,jlib:jid_replace_resource(To,<<"">>),NewPacket),
ejabberd_router:route(To,jlib:jid_replace_resource(From,<<"">>),xml:replace_tag_attr(<<"direction">>, <<"2">>, NewPacket));
_ ->
{NewPacket,_} = do_make_verify_friend_packet(?NS_VER_FRI,<<"refused">>,<<"out of max friend num">>,1),
ejabberd_router:route(From,jlib:jid_replace_resource(To,<<"">>),NewPacket),
ejabberd_router:route(To,jlib:jid_replace_resource(From,<<"">>),xml:replace_tag_attr(<<"direction">>, <<"2">>, NewPacket))
end;
_ ->
ok
end;
<<"handle_friend_result">> ->
case xml:get_attr_s(<<"result">>, Attrs) of
<<"success">> ->
mod_hash_user:add_user_friend(LServer,To,From,<<"1">>),
send_presence_packet(From,To,Packet);
_ ->
send_presence_packet(From,To,Packet)
end;
<<"two_way_del">> ->
case xml:get_attr_s(<<"result">>, Attrs) of
<<"success">> ->
Del_user = xml:get_attr_s(<<"jid">>, Attrs),
Domain = xml:get_attr_s(<<"domain">>, Attrs),
catch mod_hash_user:handle_del_friend(To#jid.lserver,To#jid.luser,Del_user,Domain,<<"1">>),
send_presence_packet(From,To,Packet);
_ ->
ok
end;
_ ->
send_presence_packet(From,To,Packet)
end.
insert_user_mucs(From,To, #xmlel{attrs = PAttrs,children = Els}) ->
case Els of
[#xmlel{name = <<"del_user">>,attrs = Attrs}] ->
case xml:get_attr_s(<<"xmlns">>, Attrs) of
?NS_MUC_DEL_USER ->
catch odbc_queries:update_register_mucs(To#jid.lserver,To#jid.luser,From#jid.luser,From#jid.lserver,<<"0">>);
_ ->
ok
end;
[#xmlel{name = <<"add_user">>,attrs = Attrs}] ->
case xml:get_attr_s(<<"xmlns">>, Attrs) of
?NS_MUC_ADD_USER ->
catch odbc_queries:insert_user_register_mucs(To#jid.lserver,To#jid.luser,From#jid.luser,From#jid.lserver);
_ ->
ok
end;
[#xmlel{name = <<"query">>,attrs = Attrs,children = [{xmlel,<<"set_register">>,[],[]}]}] ->
case xml:get_attr_s(<<"xmlns">>, Attrs) of
?NS_MUC_REGISTER ->
case xml:get_attr_s(<<"type">>,PAttrs) of
<<"result">> ->
catch odbc_queries:insert_user_register_mucs(To#jid.lserver,To#jid.luser,From#jid.luser,From#jid.lserver);
_ ->
ok
end;
_ ->
ok
end;
_ ->
ok
end.
get_server(From_host,To_host) ->
if From_host =:= To_host ->
From_host;
true ->
lists:nth(1,ejabberd_config:get_myhosts())
end.
check_carbon_msg(Packet) ->
case catch xml:get_tag_attr_s(<<"carbon_message">>, Packet) of
<<"true">> ->
true;
_ ->
false
end.
consult_message(From,To,Packet) ->
{ThirdDirection, _CN, UsrType} = case xml:get_tag_attr_s(<<"channelid">>, Packet) of
<<"">> ->
{?DIRECTION, ?CN, ?USRTYPE};
ChannelId ->
{ok, {obj, ChannelIdJson}, []} = rfc4627:decode(ChannelId),
{proplists:get_value("d", ChannelIdJson, ?DIRECTION),
proplists:get_value("cn", ChannelIdJson, ?CN),
proplists:get_value("usrType", ChannelIdJson, ?USRTYPE)}
end,
case ThirdDirection of
<<"send">> ->
make_new_consult_message(From,To,Packet,UsrType);
?DIRECTION ->
ok
end.
make_new_consult_message(From,To,Packet,UsrType) ->
Message1 = jlib:remove_attr(<<"channelid">>, Packet),
Channelid = rfc4627:encode({obj, [{"d", <<"recv">>}, {"cn", <<"consult">>}, {"usrType", UsrType}]}),
RToStr = xml:get_tag_attr_s(<<"realto">>, Message1),
RTo = jlib:string_to_jid(RToStr),
Body = xml:get_subtag(Message1, <<"body">>),
Bid = list_to_binary("http_" ++ integer_to_list(random:uniform(65536)) ++ integer_to_list(mod_time:get_exact_timestamp())),
NewBody = xml:replace_tag_attr(<<"id">>, Bid, Body),
#xmlel{name = Name, attrs = Attrs, children = Children} = xml:replace_subtag(NewBody, Message1),
Attrs2 = jlib:replace_from_to_attrs(To, RToStr, Attrs),
NewPacket = #xmlel{name = Name, attrs = [{<<"channelid">>, Channelid}|Attrs2], children = Children},
ejabberd_router:route(jlib:string_to_jid(To), RTo, NewPacket),
Msg_id = xml:get_tag_attr_s(<<"id">>,xml:get_subtag(Packet,<<"body">>)),
Now = mod_time:get_exact_timestamp(),
insert_chat_msg(To#jid.lserver,From#jid.user,To#jid.user,From#jid.lserver,To#jid.lserver, xml:element_to_binary(
Packet),body,Msg_id,Now).
| null | https://raw.githubusercontent.com/may-liu/qtalk/f5431e5a7123975e9656e7ab239e674ce33713cd/qtalk_opensource/src/ejabberd_sm_v2.erl | erlang | ----------------------------------------------------------------------
Purpose : Session manager
This program is free software; you can redistribute it and/or
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
----------------------------------------------------------------------
API
gen_server callbacks
default value for the maximum number of user connections
====================================================================
API
====================================================================
--------------------------------------------------------------------
Description: Starts the server
--------------------------------------------------------------------
catch mod_monitor:count_user_login_out(Server,User,0),
case catch redis_link:hash_get(Server,1,binary_to_list(User),binary_to_list(Resource)) of
{ok,undefined} ->
ok;
{ok,Key} ->
catch redis_link:hash_del(Server,1,binary_to_list(User),binary_to_list(Resource)),
catch redis_link:hash_del(Server,2,binary_to_list(User),binary_to_list(Key));
_ ->
ok
end,
====================================================================
gen_server callbacks
====================================================================
--------------------------------------------------------------------
Function: init(Args) -> {ok, State} |
ignore |
{stop, Reason}
Description: Initiates the server
--------------------------------------------------------------------
--------------------------------------------------------------------
% handle_call(Request , From , State ) - > { reply , Reply , State } |
{stop, Reason, Reply, State} |
{stop, Reason, State}
Description: Handling call messages
--------------------------------------------------------------------
--------------------------------------------------------------------
{stop, Reason, State}
Description: Handling cast messages
--------------------------------------------------------------------
--------------------------------------------------------------------
{stop, Reason, State}
Description: Handling all non call/cast messages
--------------------------------------------------------------------
--------------------------------------------------------------------
Function: terminate(Reason, State) -> void()
Description: This function is called by a gen_server when it is about to
terminate. It should be the opposite of Module:init/1 and do any necessary
cleaning up. When it returns, the gen_server terminates with Reason.
The return value is ignored.
--------------------------------------------------------------------
--------------------------------------------------------------------
Description: Convert process state when code is changed
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
reset session_counter table with active sessions
?DEBUG("session manager~n\tfrom ~p~n\tto ~p~n\tpacket "
"~P~n",
The default list applies to the user as a whole,
and is processed if there is no active list set
for the target session/resource to which a stanza is addressed,
or if there are no current sessions for the user.
Check if privacy rules allow this delivery
Function copied from ejabberd_c2s.erl
On new session, check if some existing connections need to be replace
Get the user_max_session setting
log in
Defaults to infinity
ejabberd commands
Update Mnesia tables
[sid, usr, us, priority, info] -> ok;
Race condition
Ignore other priority: | File :
Author : < >
Created : 24 Nov 2002 by < >
ejabberd , Copyright ( C ) 2002 - 2014 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
-module(ejabberd_sm_v2).
-author('').
-behaviour(gen_server).
-export([start_link/0,
route/3,
open_session/5,
open_session/6,
close_session/4,
check_in_subscription/6,
bounce_offline_message/3,
disconnect_removed_user/2,
get_user_resources/2,
get_user_present_resources/2,
set_presence/7,
unset_presence/6,
close_session_unset_presence/5,
dirty_get_sessions_list/0,
dirty_get_my_sessions_list/0,
get_vh_session_list/1,
get_vh_session_number/1,
register_iq_handler/4,
register_iq_handler/5,
unregister_iq_handler/2,
force_update_presence/1,
connected_users/0,
connected_users_number/0,
user_resources/2,
kick_user/2,
get_session_pid/3,
get_user_info/3,
get_user_ip/3,
get_max_user_sessions/2,
get_all_pids/0,
is_existing_resource/3,
insert_chat_msg/9,
record_show/4,
get_user_away_rescources/2,
get_user_session/2,
judge_away_flag/2,
add_datetime_to_packet/3,
add_msectime_to_packet/4,
timestamp_to_xml/1
]).
-export([init/1, handle_call/3, handle_cast/2,
handle_info/2, terminate/2, code_change/3]).
-export([get_user_present_resources_and_pid/2]).
-include("ejabberd.hrl").
-include("logger.hrl").
-include("jlib.hrl").
-include("ejabberd_commands.hrl").
-include_lib("stdlib/include/ms_transform.hrl").
-include("mod_privacy.hrl").
-record(session, {sid, usr, us, priority, info, show}).
-record(session_counter, {vhost, count}).
-record(state, {}).
-record(muc_online_room,
{name_host = {<<"">>, <<"">>} :: {binary(), binary()} | '$1' |
{'_', binary()} | '_',
pid = self() :: pid() | '$2' | '_' | '$1'}).
-define(MAX_USER_SESSIONS, infinity).
-define(DIRECTION, <<"recv">>).
-define(CN, <<"qchat">>).
-define(USRTYPE, <<"common">>).
Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error }
-type sid() :: {erlang:timestamp(), pid()}.
-type ip() :: {inet:ip_address(), inet:port_number()} | undefined.
-type info() :: [{conn, atom()} | {ip, ip()} | {node, atom()}
| {oor, boolean()} | {auth_module, atom()}].
-type prio() :: undefined | integer().
-export_type([sid/0]).
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [],
[]).
-spec route(jid(), jid(), xmlel() | broadcast()) -> ok.
route(From, To, Packet) ->
case catch do_route(From, To, Packet) of
{'EXIT', Reason} ->
?ERROR_MSG("~p~nwhen processing: ~p",
[Reason, {From, To, Packet}]);
_ -> ok
end.
-spec open_session(sid(), binary(), binary(), binary(), prio(), info()) -> ok.
open_session(SID, User, Server, Resource, Priority, Info) ->
set_session(SID, User, Server, Resource, Priority, Info),
mnesia:dirty_update_counter(session_counter,
jlib:nameprep(Server), 1),
check_for_sessions_to_replace(User, Server, Resource),
JID = jlib:make_jid(User, Server, Resource),
ejabberd_hooks:run(sm_register_connection_hook,
JID#jid.lserver, [SID, JID, Info]).
-spec open_session(sid(), binary(), binary(), binary(), info()) -> ok.
open_session(SID, User, Server, Resource, Info) ->
open_session(SID, User, Server, Resource, undefined, Info).
-spec close_session(sid(), binary(), binary(), binary()) -> ok.
close_session(SID, User, Server, Resource) ->
Info = case mnesia:dirty_read({session, SID}) of
[] -> [];
[#session{info=I}] -> I
end,
F = fun() ->
mnesia:delete({session, SID}),
mnesia:dirty_update_counter(session_counter,
jlib:nameprep(Server), -1)
end,
mnesia:sync_dirty(F),
JID = jlib:make_jid(User, Server, Resource),
ejabberd_hooks:run(sm_remove_connection_hook,
JID#jid.lserver, [SID, JID, Info]).
check_in_subscription(Acc, User, Server, _JID, _Type, _Reason) ->
case ejabberd_auth:is_user_exists(User, Server) of
true -> Acc;
false -> {stop, false}
end.
-spec bounce_offline_message(jid(), jid(), xmlel()) -> stop.
bounce_offline_message(From, To, Packet) ->
Err = jlib:make_error_reply(Packet,
?ERR_SERVICE_UNAVAILABLE),
ejabberd_router:route(To, From, Err),
stop.
-spec disconnect_removed_user(binary(), binary()) -> ok.
disconnect_removed_user(User, Server) ->
ejabberd_sm:route(jlib:make_jid(<<"">>, <<"">>, <<"">>),
jlib:make_jid(User, Server, <<"">>),
{broadcast, {exit, <<"User removed">>}}).
get_user_resources(User, Server) ->
LUser = jlib:nodeprep(User),
LServer = jlib:nameprep(Server),
US = {LUser, LServer},
case catch mnesia:dirty_index_read(session, US, #session.us) of
{'EXIT', _Reason} ->
[];
Ss ->
[element(3, S#session.usr) || S <- clean_session_list(Ss)]
end.
-spec get_user_present_resources(binary(), binary()) -> [tuple()].
get_user_present_resources(LUser, LServer) ->
US = {LUser, LServer},
case catch mnesia:dirty_index_read(session, US,
#session.us)
of
{'EXIT', _Reason} -> [];
Ss ->
[{S#session.priority, element(3, S#session.usr)}
|| S <- clean_session_list(Ss),
is_integer(S#session.priority)]
end.
get_user_present_resources_and_pid(LUser, LServer) ->
US = {LUser, LServer},
case catch mnesia:dirty_index_read(session, US,
#session.us)
of
{'EXIT', _Reason} -> [];
Ss ->
[{S#session.priority, element(3, S#session.usr),element(2, S#session.sid)}
|| S <- clean_session_list(Ss),
is_integer(S#session.priority)]
end.
get_user_session(LUser, LServer) ->
US = {LUser, LServer},
case catch mnesia:dirty_index_read(session, US,
#session.us)
of
{'EXIT', _Reason} -> [];
Ss ->
[S || S <- clean_session_list(Ss), is_integer(S#session.priority)]
end.
-spec get_user_ip(binary(), binary(), binary()) -> ip().
get_user_ip(User, Server, Resource) ->
LUser = jlib:nodeprep(User),
LServer = jlib:nameprep(Server),
LResource = jlib:resourceprep(Resource),
USR = {LUser, LServer, LResource},
case mnesia:dirty_index_read(session, USR, #session.usr) of
[] ->
undefined;
Ss ->
Session = lists:max(Ss),
proplists:get_value(ip, Session#session.info)
end.
-spec get_user_info(binary(), binary(), binary()) -> info() | offline.
get_user_info(User, Server, Resource) ->
LUser = jlib:nodeprep(User),
LServer = jlib:nameprep(Server),
LResource = jlib:resourceprep(Resource),
USR = {LUser, LServer, LResource},
case mnesia:dirty_index_read(session, USR, #session.usr) of
[] ->
offline;
Ss ->
Session = lists:max(Ss),
Node = node(element(2, Session#session.sid)),
Conn = proplists:get_value(conn, Session#session.info),
IP = proplists:get_value(ip, Session#session.info),
[{node, Node}, {conn, Conn}, {ip, IP}]
end.
-spec set_presence(sid(), binary(), binary(), binary(),
prio(), xmlel(), info()) -> ok.
set_presence(SID, User, Server, Resource, Priority,
Presence, Info) ->
set_session(SID, User, Server, Resource, Priority,
Info),
ejabberd_hooks:run(set_presence_hook,
jlib:nameprep(Server),
[User, Server, Resource, Presence]).
-spec unset_presence(sid(), binary(), binary(),
binary(), binary(), info()) -> ok.
unset_presence(SID, User, Server, Resource, Status,
Info) ->
set_session(SID, User, Server, Resource, undefined,
Info),
ejabberd_hooks:run(unset_presence_hook,
jlib:nameprep(Server),
[User, Server, Resource, Status]).
-spec close_session_unset_presence(sid(), binary(), binary(),
binary(), binary()) -> ok.
close_session_unset_presence(SID, User, Server,
Resource, Status) ->
close_session(SID, User, Server, Resource),
ejabberd_hooks:run(unset_presence_hook,
jlib:nameprep(Server),
[User, Server, Resource, Status]).
-spec get_session_pid(binary(), binary(), binary()) -> none | pid().
get_session_pid(User, Server, Resource) ->
LUser = jlib:nodeprep(User),
LServer = jlib:nameprep(Server),
LResource = jlib:resourceprep(Resource),
USR = {LUser, LServer, LResource},
case catch mnesia:dirty_index_read(session, USR, #session.usr) of
[#session{sid = {_, Pid}}] -> Pid;
_ -> none
end.
-spec dirty_get_sessions_list() -> [ljid()].
dirty_get_sessions_list() ->
mnesia:dirty_select(
session,
[{#session{usr = '$1', _ = '_'},
[],
['$1']}]).
dirty_get_my_sessions_list() ->
mnesia:dirty_select(
session,
[{#session{sid = {'_', '$1'}, _ = '_'},
[{'==', {node, '$1'}, node()}],
['$_']}]).
-spec get_vh_session_list(binary()) -> [ljid()].
get_vh_session_list(Server) ->
LServer = jlib:nameprep(Server),
mnesia:dirty_select(session,
[{#session{usr = '$1', _ = '_'},
[{'==', {element, 2, '$1'}, LServer}], ['$1']}]).
-spec get_all_pids() -> [pid()].
get_all_pids() ->
mnesia:dirty_select(
session,
ets:fun2ms(
fun(#session{sid = {_, Pid}}) ->
Pid
end)).
get_vh_session_number(Server) ->
LServer = jlib:nameprep(Server),
Query = mnesia:dirty_select(
session_counter,
[{#session_counter{vhost = LServer, count = '$1'},
[],
['$1']}]),
case Query of
[Count] ->
Count;
_ -> 0
end.
register_iq_handler(Host, XMLNS, Module, Fun) ->
ejabberd_sm !
{register_iq_handler, Host, XMLNS, Module, Fun}.
-spec register_iq_handler(binary(), binary(), atom(), atom(), list()) -> any().
register_iq_handler(Host, XMLNS, Module, Fun, Opts) ->
ejabberd_sm !
{register_iq_handler, Host, XMLNS, Module, Fun, Opts}.
-spec unregister_iq_handler(binary(), binary()) -> any().
unregister_iq_handler(Host, XMLNS) ->
ejabberd_sm ! {unregister_iq_handler, Host, XMLNS}.
{ ok , State , Timeout } |
init([]) ->
update_tables(),
mnesia:create_table(session,
[{ram_copies, [node()]},
{attributes, record_info(fields, session)}]),
mnesia:create_table(session_counter,
[{ram_copies, [node()]},
{attributes, record_info(fields, session_counter)}]),
mnesia:add_table_index(session, usr),
mnesia:add_table_index(session, us),
mnesia:add_table_index(session, show),
mnesia:add_table_copy(session, node(), ram_copies),
mnesia:add_table_copy(session_counter, node(), ram_copies),
mnesia:subscribe(system),
ets:new(sm_iqtable, [named_table]),
lists:foreach(
fun(Host) ->
ejabberd_hooks:add(roster_in_subscription, Host,
ejabberd_sm, check_in_subscription, 20),
ejabberd_hooks:add(offline_message_hook, Host,
ejabberd_sm, bounce_offline_message, 100),
ejabberd_hooks:add(remove_user, Host,
ejabberd_sm, disconnect_removed_user, 100)
end, ?MYHOSTS),
ejabberd_commands:register_commands(commands()),
{ok, #state{}}.
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
handle_call(_Request, _From, State) ->
Reply = ok, {reply, Reply, State}.
Function : handle_cast(Msg , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
handle_cast(_Msg, State) -> {noreply, State}.
Function : handle_info(Info , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
handle_info({route, From, To, Packet}, State) ->
case catch do_route(From, To, Packet) of
{'EXIT', Reason} ->
?ERROR_MSG("~p~nwhen processing: ~p",
[Reason, {From, To, Packet}]);
_ ->
ok
end,
{noreply, State};
handle_info({mnesia_system_event, {mnesia_down, Node}}, State) ->
recount_session_table(Node),
{noreply, State};
handle_info({register_iq_handler, Host, XMLNS, Module, Function}, State) ->
ets:insert(sm_iqtable, {{XMLNS, Host}, Module, Function}),
{noreply, State};
handle_info({register_iq_handler, Host, XMLNS, Module,
Function, Opts},
State) ->
ets:insert(sm_iqtable,
{{XMLNS, Host}, Module, Function, Opts}),
{noreply, State};
handle_info({unregister_iq_handler, Host, XMLNS},
State) ->
case ets:lookup(sm_iqtable, {XMLNS, Host}) of
[{_, Module, Function, Opts}] ->
gen_iq_handler:stop_iq_handler(Module, Function, Opts);
_ -> ok
end,
ets:delete(sm_iqtable, {XMLNS, Host}),
{noreply, State};
handle_info(_Info, State) -> {noreply, State}.
terminate(_Reason, _State) ->
ejabberd_commands:unregister_commands(commands()),
ok.
Func : code_change(OldVsn , State , Extra ) - > { ok , NewState }
code_change(_OldVsn, State, _Extra) -> {ok, State}.
Internal functions
set_session(SID, User, Server, Resource, Priority, Info) ->
LUser = jlib:nodeprep(User),
LServer = jlib:nameprep(Server),
LResource = jlib:resourceprep(Resource),
US = {LUser, LServer},
USR = {LUser, LServer, LResource},
F = fun () ->
mnesia:write(#session{sid = SID, usr = USR, us = US,
priority = Priority, info = Info, show = <<"normal">>})
end,
mnesia:sync_dirty(F).
Recalculates alive sessions when goes down
and updates session and session_counter tables
recount_session_table(Node) ->
F = fun() ->
Es = mnesia:select(
session,
[{#session{sid = {'_', '$1'}, _ = '_'},
[{'==', {node, '$1'}, Node}],
['$_']}]),
lists:foreach(fun(E) ->
mnesia:delete({session, E#session.sid})
end, Es),
mnesia:clear_table(session_counter),
lists:foreach(fun(Server) ->
LServer = jlib:nameprep(Server),
Hs = mnesia:select(session,
[{#session{usr = '$1', _ = '_'},
[{'==', {element, 2, '$1'}, LServer}],
['$1']}]),
mnesia:write(
#session_counter{vhost = LServer,
count = length(Hs)})
end, ?MYHOSTS)
end,
mnesia:async_dirty(F).
do_route(From, To, {broadcast, _} = Packet) ->
case To#jid.lresource of
<<"">> ->
lists:foreach(fun(R) ->
do_route(From,
jlib:jid_replace_resource(To, R),
Packet)
end,
get_user_resources(To#jid.user, To#jid.server));
_ ->
USR = jlib:jid_tolower(To),
case mnesia:dirty_index_read(session, USR, #session.usr) of
[] ->
?DEBUG("packet dropped~n", []);
Ss ->
Session = lists:max(Ss),
Pid = element(2, Session#session.sid),
?DEBUG("sending to process ~p~n", [Pid]),
Pid ! {route, From, To, Packet}
end
end;
do_route(From, To, #xmlel{} = Packet) ->
[ From , To , Packet , 8 ] ) ,
#jid{user = User, server = Server,
luser = LUser, lserver = LServer, lresource = LResource} = To,
#xmlel{name = Name, attrs = Attrs, children = Els} = Packet,
case LResource of
<<"">> ->
case Name of
<<"presence">> ->
{Pass, _Subsc} = case xml:get_attr_s(<<"type">>, Attrs)
of
<<"subscribe">> ->
Reason = xml:get_path_s(Packet,
[{elem,
<<"status">>},
cdata]),
{is_privacy_allow(From, To, Packet)
andalso
ejabberd_hooks:run_fold(roster_in_subscription,
LServer,
false,
[User, Server,
From,
subscribe,
Reason]),
true};
<<"subscribed">> ->
{is_privacy_allow(From, To, Packet)
andalso
ejabberd_hooks:run_fold(roster_in_subscription,
LServer,
false,
[User, Server,
From,
subscribed,
<<"">>]),
true};
<<"unsubscribe">> ->
{is_privacy_allow(From, To, Packet)
andalso
ejabberd_hooks:run_fold(roster_in_subscription,
LServer,
false,
[User, Server,
From,
unsubscribe,
<<"">>]),
true};
<<"unsubscribed">> ->
{is_privacy_allow(From, To, Packet)
andalso
ejabberd_hooks:run_fold(roster_in_subscription,
LServer,
false,
[User, Server,
From,
unsubscribed,
<<"">>]),
true};
_ -> {true, false}
end,
if Pass ->
handle_presence(LServer,From,To,Packet,Attrs);
true -> ok
end;
<<"message">> ->
route_message(From, To, Packet);
<<"iq">> -> process_iq(From, To, Packet);
_ -> ok
end;
_ ->
USR = {LUser, LServer, LResource},
case mnesia:dirty_index_read(session, USR, #session.usr)
of
[] ->
case Name of
<<"message">> -> route_message(From, To, Packet);
<<"iq">> ->
case xml:get_attr_s(<<"type">>, Attrs) of
<<"error">> -> ok;
<<"result">> -> ok;
_ ->
Err = jlib:make_error_reply(Packet,
?ERR_SERVICE_UNAVAILABLE),
ejabberd_router:route(To, From, Err)
end;
_ -> ?DEBUG("packet droped~n", [])
end;
Ss ->
Session = lists:max(Ss),
Pid = element(2, Session#session.sid),
NewPacket =
case Name of
<<"message">> ->
make_new_packet(From,To,Packet,Name,Attrs,Els);
<<"iq">> ->
insert_user_mucs(From,To,Packet),
Packet;
_ ->
Packet
end,
Pid ! {route, From, To, NewPacket}
end
end.
is_privacy_allow(From, To, Packet) ->
User = To#jid.user,
Server = To#jid.server,
PrivacyList =
ejabberd_hooks:run_fold(privacy_get_user_list, Server,
#userlist{}, [User, Server]),
is_privacy_allow(From, To, Packet, PrivacyList).
is_privacy_allow(From, To, Packet, PrivacyList) ->
User = To#jid.user,
Server = To#jid.server,
allow ==
ejabberd_hooks:run_fold(privacy_check_packet, Server,
allow,
[User, Server, PrivacyList, {From, To, Packet},
in]).
route_message(From, To, Packet) ->
LUser = To#jid.luser,
LServer = To#jid.lserver,
case xml:get_tag_attr_s(<<"type">>, Packet) of
<<"readmark">> ->
readmark:readmark_message(From,To,Packet);
<<"revoke">> ->
revoke:revoke_message(From,To,Packet);
_ ->
PrioRes = get_user_present_resources(LUser, LServer),
#xmlel{name = Name, attrs = Attrs, children = Els} = Packet,
NewPacket = make_new_packet(From,To,Packet,Name,Attrs,Els),
case catch lists:max(PrioRes) of
{Priority, _R}
when is_integer(Priority), Priority >= 0 ->
catch send_max_priority_msg(LUser,LServer,Priority,From,To,NewPacket,PrioRes);
_ ->
case xml:get_tag_attr_s(<<"type">>, Packet) of
<<"error">> -> ok;
<<"groupchat">> -> ok;
<<"subscription">>->
subscription:subscription_message(From,To,Packet);
<<"readmark">> ->
readmark:readmark_message(From,To,Packet);
<<"consult">> ->
consult_message(From,To,Packet);
_ ->
case ejabberd_auth:is_user_exists(LUser, LServer) of
true ->
case is_privacy_allow(From, To, Packet) of
true ->
case catch check_carbon_msg(Packet) of
true ->
ok;
_ ->
ejabberd_hooks:run(offline_message_hook, LServer,
[From, To, Packet])
end;
_ ->
ok
end;
_ ->
Err = jlib:make_error_reply(Packet,
?ERR_SERVICE_UNAVAILABLE),
ejabberd_router:route(To, From, Err)
end
end
end
end.
clean_session_list(Ss) ->
clean_session_list(lists:keysort(#session.usr, Ss), []).
clean_session_list([], Res) -> Res;
clean_session_list([S], Res) -> [S | Res];
clean_session_list([S1, S2 | Rest], Res) ->
if S1#session.usr == S2#session.usr ->
if S1#session.sid > S2#session.sid ->
clean_session_list([S1 | Rest], Res);
true -> clean_session_list([S2 | Rest], Res)
end;
true -> clean_session_list([S2 | Rest], [S1 | Res])
end.
check_for_sessions_to_replace(User, Server, Resource) ->
LUser = jlib:nodeprep(User),
LServer = jlib:nameprep(Server),
LResource = jlib:resourceprep(Resource),
check_existing_resources(LUser, LServer, LResource),
check_max_sessions(LUser, LServer).
check_existing_resources(LUser, LServer, LResource) ->
SIDs = get_resource_sessions(LUser, LServer, LResource),
if SIDs == [] -> ok;
true ->
MaxSID = lists:max(SIDs),
lists:foreach(fun ({_, Pid} = S) when S /= MaxSID ->
Pid ! replaced;
(_) -> ok
end,
SIDs)
end.
-spec is_existing_resource(binary(), binary(), binary()) -> boolean().
is_existing_resource(LUser, LServer, LResource) ->
[] /= get_resource_sessions(LUser, LServer, LResource).
get_resource_sessions(User, Server, Resource) ->
USR = {jlib:nodeprep(User), jlib:nameprep(Server),
jlib:resourceprep(Resource)},
mnesia:dirty_select(session,
[{#session{sid = '$1', usr = USR, _ = '_'}, [],
['$1']}]).
check_max_sessions(LUser, LServer) ->
SIDs = mnesia:dirty_select(session,
[{#session{sid = '$1', us = {LUser, LServer},
_ = '_'},
[], ['$1']}]),
MaxSessions = get_max_user_sessions(LUser, LServer),
if length(SIDs) =< MaxSessions -> ok;
true -> {_, Pid} = lists:min(SIDs), Pid ! replaced
end.
This option defines the number of time a given users are allowed to
get_max_user_sessions(LUser, Host) ->
case acl:match_rule(Host, max_user_sessions,
jlib:make_jid(LUser, Host, <<"">>))
of
Max when is_integer(Max) -> Max;
infinity -> infinity;
_ -> ?MAX_USER_SESSIONS
end.
process_iq(From, To, Packet) ->
IQ = jlib:iq_query_info(Packet),
case IQ of
#iq{xmlns = XMLNS} ->
Host = To#jid.lserver,
case ets:lookup(sm_iqtable, {XMLNS, Host}) of
[{_, Module, Function}] ->
ResIQ = Module:Function(From, To, IQ),
if ResIQ /= ignore ->
ejabberd_router:route(To, From, jlib:iq_to_xml(ResIQ));
true -> ok
end;
[{_, Module, Function, Opts}] ->
gen_iq_handler:handle(Host, Module, Function, Opts,
From, To, IQ);
[] ->
Err = jlib:make_error_reply(Packet,
?ERR_SERVICE_UNAVAILABLE),
ejabberd_router:route(To, From, Err)
end;
reply -> insert_user_mucs(From,To,Packet), ok;
_ ->
Err = jlib:make_error_reply(Packet, ?ERR_BAD_REQUEST),
ejabberd_router:route(To, From, Err),
ok
end.
-spec force_update_presence({binary(), binary()}) -> any().
force_update_presence({LUser, _LServer} = US) ->
case catch mnesia:dirty_index_read(session, US,
#session.us)
of
{'EXIT', _Reason} -> ok;
Ss ->
lists:foreach(fun (#session{sid = {_, Pid}}) ->
Pid ! {force_update_presence, LUser}
end,
Ss)
end.
commands() ->
[#ejabberd_commands{name = connected_users,
tags = [session],
desc = "List all established sessions",
module = ?MODULE, function = connected_users, args = [],
result = {connected_users, {list, {sessions, string}}}},
#ejabberd_commands{name = connected_users_number,
tags = [session, stats],
desc = "Get the number of established sessions",
module = ?MODULE, function = connected_users_number,
args = [], result = {num_sessions, integer}},
#ejabberd_commands{name = user_resources,
tags = [session],
desc = "List user's connected resources",
module = ?MODULE, function = user_resources,
args = [{user, binary}, {host, binary}],
result = {resources, {list, {resource, string}}}},
#ejabberd_commands{name = kick_user,
tags = [session],
desc = "Disconnect user's active sessions",
module = ?MODULE, function = kick_user,
args = [{user, binary}, {host, binary}],
result = {num_resources, integer}}].
-spec connected_users() -> [binary()].
connected_users() ->
USRs = dirty_get_sessions_list(),
SUSRs = lists:sort(USRs),
lists:map(fun ({U, S, R}) -> <<U/binary, $@, S/binary, $/, R/binary>> end,
SUSRs).
connected_users_number() ->
length(dirty_get_sessions_list()).
user_resources(User, Server) ->
Resources = get_user_resources(User, Server),
lists:sort(Resources).
kick_user(User, Server) ->
Resources = get_user_resources(User, Server),
lists:foreach(
fun(Resource) ->
PID = get_session_pid(User, Server, Resource),
PID ! disconnect
end, Resources),
length(Resources).
update_tables() ->
case catch mnesia:table_info(session, attributes) of
[ur, user, node] -> mnesia:delete_table(session);
[ur, user, pid] -> mnesia:delete_table(session);
[usr, us, pid] -> mnesia:delete_table(session);
[usr, us, sid, priority, info] -> mnesia:delete_table(session);
[usr, us, sid, priority, info, show] -> mnesia:delete_table(session);
[sid, usr, us, priority] ->
mnesia:delete_table(session);
[sid, usr, us, priority, info] ->
mnesia:delete_table(session);
[sid, usr, us, priority, info,show] -> ok;
{'EXIT', _} -> ok
end,
case lists:member(presence, mnesia:system_info(tables))
of
true -> mnesia:delete_table(presence);
false -> ok
end,
case lists:member(local_session, mnesia:system_info(tables)) of
true ->
mnesia:delete_table(local_session);
false ->
ok
end.
insert_chat_msg(Server,From, To,From_host,To_host, Msg,_Body,ID,InsertTime) ->
case jlib:nodeprep(From) of
error -> {error, invalid_jid};
LUser ->
LFrom = ejabberd_odbc:escape(LUser),
LTo = ejabberd_odbc:escape(To),
LBody = ejabberd_odbc:escape(Msg),
LID = ejabberd_odbc:escape(ID),
LServer = get_server(From_host,To_host),
Time = ejabberd_public:pg2timestamp(InsertTime),
case str:str(LID,<<"http">>) of
0 ->
case catch odbc_queries:insert_msg6(LServer, LFrom,LTo,From_host,To_host,LBody,LID,Time) of
{updated, 1} -> {atomic, ok};
A ->
?INFO_MSG("Insert Msg error Body: ~p ,~p ~n",[A,LBody]),
{atomic, exists}
end;
_ ->
case ejabberd_public:judge_spec_jid(LFrom,LTo) of
true ->
case catch odbc_queries:insert_msg4(LServer, LFrom,LTo,From_host,To_host,LBody,LID,Time) of
{updated, 1} -> {atomic, ok};
_ ->
?INFO_MSG("Insert Msg error Body: ~p ~n",[LBody]),
{atomic, exists}
end;
_ ->
case catch odbc_queries:insert_msg5(LServer, LFrom,LTo,From_host,To_host,LBody,LID,Time) of
{updated, 1} -> {atomic, ok};
_ ->
?INFO_MSG("Insert Msg error Body: ~p ~n",[LBody]),
{atomic, exists}
end
end
end
end.
timestamp_to_xml({{Year, Month, Day},
{Hour, Minute, Second}}) ->
#xmlel{name = <<"stime">>,
attrs =
[{<<"xmlns">>, ?NS_TIME91},
{<<"stamp">>,iolist_to_binary(
io_lib:format("~4..0w~2..0w~2..0wT~2..0w:~2..0w:~2..0w",[Year, Month, Day, Hour, Minute,Second]))}],children = []}.
record_show(User,Server,Resource,Show) ->
LUser = jlib:nodeprep(User),
LServer = jlib:nameprep(Server),
LResource = jlib:resourceprep(Resource),
US = {LUser, LServer},
USR = {LUser, LServer, LResource},
case mnesia:dirty_index_read(session, USR, #session.usr) of
[] ->
ok;
Ss ->
Session = lists:max(Ss),
F = fun () ->
mnesia:write(Session#session{usr = USR,us = US, show = Show}) end,
mnesia:sync_dirty(F)
end.
判读特殊情况,聊天室用户非正常退出,导致存在于聊天室中的#state.users表中 ,
judge_to_user_available(_FServer,<<"">>,_R)->
true;
judge_to_user_available(FServer,Rescource,R) ->
case str:str(FServer,<<"conference">>) of
0 ->
true;
_ ->
if Rescource == R ->
true;
true ->
false
end
end.
send_muc_room_remove_unavailable_user(From,To) ->
case mnesia:dirty_read(muc_online_room, {From#jid.user, From#jid.server}) of
[] ->
ok;
[Muc] ->
Muc_Pid = Muc#muc_online_room.pid,
Muc_Pid ! {delete_unavailable_user,To}
end.
get_user_away_rescources(User, Server) ->
LUser = jlib:nodeprep(User),
LServer = jlib:nameprep(Server),
US = {LUser, LServer},
case catch mnesia:dirty_index_read(session, US, #session.us) of
{'EXIT', _Reason} ->
[];
[] ->
[<<"none">>];
Ss ->
lists:flatmap(fun(S) ->
case S#session.show of
<<"away">> ->
[element(3, S#session.usr)];
_ ->
[]
end
end,clean_session_list(Ss))
end.
insert_away_spool(From,To,LServer,Packet) ->
FromUsername = ejabberd_odbc:escape(From#jid.luser),
Username = ejabberd_odbc:escape(To#jid.luser),
#xmlel{name = Name,attrs = Attrs, children = Els} = Packet,
TimeStamp = os:timestamp(),
NewPacket = #xmlel{name = Name,attrs = Attrs,
children =
Els ++ [jlib:timestamp_to_xml(calendar:now_to_universal_time(TimeStamp),
utc, jlib:make_jid(<<"">>,From#jid.lserver ,<<"">>),
<<"Offline Storage">>),
jlib:timestamp_to_xml(calendar:now_to_universal_time(TimeStamp))]},
case catch ets:lookup(mac_push_notice,{Username,FromUsername}) of
[] ->
catch odbc_queries:add_spool_away(LServer,FromUsername,Username,
ejabberd_odbc:escape(xml:element_to_binary(NewPacket)),<<"0">>);
_ ->
catch odbc_queries:add_spool_away(LServer,FromUsername,Username,
ejabberd_odbc:escape(xml:element_to_binary(NewPacket)),<<"1">>)
end.
try_insert_msg(From,To,Packet,Mbody) ->
#xmlel{name = Name, attrs = Attrs, children = Els} = Packet,
LServer = To#jid.lserver,
case ejabberd_public:is_conference_server(From#jid.lserver) of
false ->
insert_user_chat_msg(From,To,Packet,Attrs,Els,Mbody,LServer);
_ ->
insert_muc_chat_msg(From,To,Packet,Name,Attrs,Els,Mbody,LServer)
end.
insert_user_chat_msg(From,To,Packet,Attrs,Els,Mbody,LServer) ->
catch mod_monitor:monitor_count(LServer,<<"chat_message">>,1),
Carbon = xml:get_attr_s(<<"carbon_message">>, Attrs),
Now = mod_time:get_exact_timestamp(),
case Carbon =/= <<"true">> andalso (not mod_muc_room:is_invitation(Els)) of
true ->
Msg_id = xml:get_tag_attr_s(<<"id">>,xml:get_subtag(Packet,<<"body">>)),
insert_chat_msg(LServer,From#jid.user,To#jid.user,From#jid.lserver,To#jid.lserver, xml:element_to_binary(
Packet),Mbody,Msg_id,Now);
_ ->
ok
end.
insert_muc_chat_msg(From,To,_Packet,Name,Attrs,Els,Mbody,LServer)->
case mnesia:dirty_read(muc_online_room, {From#jid.user, From#jid.server}) of
[] ->
add_datetime_to_packet(Name,Attrs,Els);
[Muc] ->
Now = mod_time:get_exact_timestamp(),
Time = trunc(Now/1000),
NewPacket = add_datetime_to_packet(Name,[{<<"msec_times">>,integer_to_binary(Now )}] ++ Attrs,
Els,timestamp_to_xml(mod_time:timestamp_to_datetime_utc1(Time))),
Muc_Pid = Muc#muc_online_room.pid,
Muc_Pid ! {insert_chat_msg,LServer,From,To,From#jid.lserver,To#jid.lserver,NewPacket,Mbody,Time},
NewPacket
end.
send_max_priority_msg(LUser,LServer,Priority,From,To,NewPacket,PrioRes) ->
Status_and_Resources = send_msg_and_get_resources(LUser,LServer,Priority,From,To,NewPacket,PrioRes),
case judge_away_flag(Status_and_Resources,false) of
false ->
ok;
_ ->
#xmlel{attrs = Attrs, children = Els} = NewPacket,
Mtype = xml:get_attr_s(<<"type">>, Attrs),Mbody = xml:get_subtag_cdata(NewPacket, <<"body">>),
Delay = xml:get_subtag_cdata(NewPacket,<<"delay">>),
Carbon_message = xml:get_attr_s(<<"carbon_message">>, Attrs),
case (Mtype == <<"normal">> orelse Mtype == <<"chat">>)
andalso Mbody /= <<>> andalso Delay /= <<"Offline Storage">>
andalso Carbon_message /= <<"true">> of
true ->
case (not mod_muc_room:is_invitation(Els)) andalso
xml:get_tag_attr_s(<<"msgType">>,xml:get_subtag(NewPacket,<<"body">>)) =/= <<"1024">> of
true -> insert_away_spool(From,To,LServer,NewPacket);
_ -> ok
end;
_ ->
ok
end
end.
send_msg_and_get_resources(LUser,LServer,Priority,From,To,NewPacket,PrioRes) ->
lists:flatmap(fun ({P, R}) when P == Priority ->
LResource = jlib:resourceprep(R),
USR = {LUser, LServer, LResource},
case mnesia:dirty_index_read(session, USR, #session.usr) of
[] ->
Ss ->
case judge_to_user_available(From#jid.server,To#jid.lresource,LResource) of
true ->
Session = lists:max(Ss),
Pid = element(2, Session#session.sid),
?DEBUG("sending to process ~p~n", [Pid]),
Pid ! {route, From, To, NewPacket},
[{Session#session.show,LResource}];
_ ->
?INFO_MSG("Rescoure not match ~p : ~p ~n",[R,To#jid.lresource]),
send_muc_room_remove_unavailable_user(From,To),
[]
end
end;
({_Prio, _Res}) -> []
end,PrioRes).
judge_away_flag(Resources,Offline_send_flag) ->
{Away_lan_num,Normal_lan_num,Away_wlan_num,Normal_wlan_num} = get_resources_num(Resources,0,0,0,0),
case Resources of
[] ->
case Offline_send_flag of
true ->
true;
_ ->
false
end;
_ ->
case Away_wlan_num + Away_lan_num =:= 0 of
true ->
false;
_ ->
case Away_lan_num > 0 of
true ->
true;
_ ->
case Away_wlan_num =/= 0 andalso Normal_lan_num =:= 0 of
true ->
true;
_ ->
false
end
end
end
end.
get_resources_num([],A_lan_num,N_lan_num,A_wlan_num,N_wlan_num) ->
{A_lan_num,N_lan_num,A_wlan_num,N_wlan_num};
get_resources_num(Rs,A_lan_num,N_lan_num,A_wlan_num,N_wlan_num) ->
[{S,R} | L ] = Rs,
if S =:= <<"away">> ->
case str:str(R,<<"iPhone">>) =/= 0 orelse str:str(R,<<"Android">>) =/= 0 orelse str:str(R,<<"IOS">>) =/= 0 of
true ->
get_resources_num(L, A_lan_num,N_lan_num,A_wlan_num + 1,N_wlan_num);
_ ->
get_resources_num(L, A_lan_num+1,N_lan_num,A_wlan_num,N_wlan_num)
end;
true ->
case str:str(R,<<"iPhone">>) =/= 0 orelse str:str(R,<<"Android">>) =/= 0 orelse str:str(R,<<"IOS">>) =/= 0 of
true ->
get_resources_num(L, A_lan_num,N_lan_num,A_wlan_num,N_wlan_num+1);
_ ->
get_resources_num(L, A_lan_num,N_lan_num+1,A_wlan_num,N_wlan_num)
end
end.
make_new_packet(From,To,Packet,Name,Attrs,Els) ->
Mtype = xml:get_attr_s(<<"type">>, Attrs),
case Mtype == <<"normal">> orelse Mtype == <<"chat">> orelse Mtype == <<"consult">> of
true ->
Reply = xml:get_attr_s(<<"auto_reply">>, Attrs),
Reply1 = xml:get_attr_s(<<"atuo_reply">>, Attrs),
Mbody = xml:get_subtag_cdata(Packet, <<"body">>),
Delay = xml:get_subtag_cdata(Packet,<<"delay">>),
case Mbody =/= <<>> andalso Delay =/= <<"Offline Storage">> andalso Reply =/= <<"true">>
andalso Reply1 =/= <<"true">> of
true ->
case xml:get_attr_s(<<"msec_times">>, Attrs) of
<<"">> ->
NewPacket = add_datetime_to_packet(Name,Attrs,Els),
try_insert_msg(From,To,NewPacket,Mbody),
NewPacket;
_ ->
?INFO_MSG("Packet ~p ~n",[Packet]),
Packet
end;
_ ->
Packet
end;
_ ->
Packet
end.
add_datetime_to_packet(Name,Attrs,Els) ->
Now = mod_time:get_exact_timestamp(),
add_datetime_to_packet(Name,
[{<<"msec_times">>,integer_to_binary(Now )}] ++ Attrs,Els,
timestamp_to_xml(mod_time:timestamp_to_datetime_utc1(trunc(Now/1000)))).
add_datetime_to_packet(Name,Attrs,Els,Time) ->
#xmlel{name = Name, attrs = Attrs, children = Els ++ [Time]}.
add_msectime_to_packet(Name,Attrs,Els,Time) ->
#xmlel{name = Name, attrs = [{<<"msec_times">>,integer_to_binary(Time)}] ++ Attrs,
children = Els ++ [timestamp_to_xml(mod_time:timestamp_to_datetime_utc1(trunc(Time/1000)))]}.
make_verify_friend_packet(Num,Rslt,From,To,Packet,Attrs) ->
Num1 = case proplists:get_value(<<"num">>,Rslt) of
undefined ->
0;
V ->
V
end,
case Num < 300 andalso Num1 < 300 of
true ->
case proplists:get_value(<<"mode">>,Rslt) of
<<"0">> ->
do_make_verify_friend_packet(?NS_VER_FRI,<<"refused">>,<<"all_refuse">>,2);
<<"1">> ->
{Packet,1};
<<"2">> ->
case xml:get_attr_s(<<"answer">>, Attrs) == proplists:get_value(<<"answer">>,Rslt) of
true ->
do_make_verify_friend_packet(?NS_VER_FRI,<<"success">>,<<"answer_right">>,2) ;
_ ->
do_make_verify_friend_packet(?NS_VER_FRI,<<"refused">>,<<"answer_errror">>,2)
end;
<<"3">> ->
do_make_verify_friend_packet(?NS_VER_FRI,<<"success">>,<<"all_accpet">>,2);
_ ->
do_make_verify_friend_packet(?NS_VER_FRI,<<"success">>,<<"default_config">>,2)
end;
false ->
do_make_verify_friend_packet(?NS_VER_FRI,<<"refused">>,<<"out of max friend num">>,2)
end.
do_make_verify_friend_packet(XMLNS,Rslt,Reason,Two_ways) ->
{#xmlel{name = <<"presence">>,
attrs = [{<<"xmlns">>,XMLNS},{<<"type">>,<<"handle_friend_result">>},{<<"result">>,Rslt},{<<"reason">>,Reason}],
children = []},Two_ways}.
do_make_verify_friend_packet1(XMLNS,Rslt,Reason,Two_ways) ->
{#xmlel{name = <<"presence">>,
attrs = [{<<"xmlns">>,XMLNS},{<<"body">>,Reason}],
children = []},Two_ways}.
send_presence_packet(From,To,Packet) ->
PResources = get_user_present_resources(To#jid.luser, To#jid.lserver),
lists:foreach(fun ({_, R}) ->
do_route(From,
jlib:jid_replace_resource(To,
R),
Packet)
end,
PResources).
send_presence_packet1(From,To,Packet,Attrs) ->
PResources = get_user_present_resources(To#jid.luser, To#jid.lserver),
case PResources of
[] ->
Body = xml:get_attr_s(<<"body">>, Attrs),
catch insert_presence_spool(From#jid.server,From#jid.luser,To#jid.luser,Body);
_ ->
lists:foreach(fun ({_, R}) ->
do_route(From,
jlib:jid_replace_resource(To,
R),
Packet)
end,
PResources)
end.
insert_presence_spool(Server,From,To,Body) ->
Timestamp = integer_to_binary(mod_time:get_timestamp()),
case catch ejabberd_odbc:sql_query(Server,
[<<"udpate invite_spool set timestamp = ">>,Timestamp,<<",Body = '">>,Body,<<"' where username = '">>,To,<<"' and inviter = '">>,
From,<<"';">>]) of
{updated,1} ->
ok;
_ ->
case catch ejabberd_odbc:sql_query(Server,
[<<"insert into invite_spool(username,inviter,body,timestamp) values ('">>,
To,<<"','">>,From,<<"','">>,ejabberd_odbc:escape(Body),<<"',">>,Timestamp,<<")">>]) of
{updated,1} ->
ok;
_ ->
ok
end
end.
delete_presence_spool(Server,From,To) ->
case catch ejabberd_odbc:sql_query(Server,
[<<"delete from invite_spool where username = '">>,From,<<"' and inviter = '">>,To,<<"';">>]) of
{updated,1} ->
ok;
_ ->
ok
end.
handle_presence(LServer,From,To,Packet,Attrs) ->
User = To#jid.luser,
case xml:get_attr_s(<<"type">>, Attrs) of
<<"verify_friend">> ->
Rslt = mod_user_relation:do_verify_friend(LServer,User),
Num =
case xml:get_attr_s(<<"friend_num">>,Attrs) of
<<>> ->
0;
N when is_binary(N) ->
binary_to_integer(N);
_ ->
0
end,
{NewPacket,Two_way} = make_verify_friend_packet(Num,Rslt,From,To,Packet,Attrs),
case Two_way of
1 ->
send_presence_packet1(From,To,NewPacket,Attrs);
_ ->
ejabberd_router:route(From,jlib:jid_replace_resource(To,<<"">>),NewPacket),
ejabberd_router:route(To,jlib:jid_replace_resource(From,<<"">>),xml:replace_tag_attr(<<"direction">>, <<"2">>, NewPacket))
end;
<<"manual_authentication_confirm">> ->
case xml:get_attr_s(<<"result">>, Attrs) of
<<"allow">> ->
Num1 = mod_user_relation:get_users_friend_num(LServer,User),
Num = binary_to_integer(xml:get_attr_s(<<"friend_num">>,Attrs)),
case Num1 < 300 andalso Num < 300 of
true ->
{NewPacket,_} = do_make_verify_friend_packet(?NS_VER_FRI,<<"success">>,<<"manual_authentication_confirm_success">>,1),
ejabberd_router:route(From,jlib:jid_replace_resource(To,<<"">>),NewPacket),
ejabberd_router:route(To,jlib:jid_replace_resource(From,<<"">>),xml:replace_tag_attr(<<"direction">>, <<"2">>, NewPacket));
_ ->
{NewPacket,_} = do_make_verify_friend_packet(?NS_VER_FRI,<<"refused">>,<<"out of max friend num">>,1),
ejabberd_router:route(From,jlib:jid_replace_resource(To,<<"">>),NewPacket),
ejabberd_router:route(To,jlib:jid_replace_resource(From,<<"">>),xml:replace_tag_attr(<<"direction">>, <<"2">>, NewPacket))
end;
_ ->
ok
end;
<<"handle_friend_result">> ->
case xml:get_attr_s(<<"result">>, Attrs) of
<<"success">> ->
mod_hash_user:add_user_friend(LServer,To,From,<<"1">>),
send_presence_packet(From,To,Packet);
_ ->
send_presence_packet(From,To,Packet)
end;
<<"two_way_del">> ->
case xml:get_attr_s(<<"result">>, Attrs) of
<<"success">> ->
Del_user = xml:get_attr_s(<<"jid">>, Attrs),
Domain = xml:get_attr_s(<<"domain">>, Attrs),
catch mod_hash_user:handle_del_friend(To#jid.lserver,To#jid.luser,Del_user,Domain,<<"1">>),
send_presence_packet(From,To,Packet);
_ ->
ok
end;
_ ->
send_presence_packet(From,To,Packet)
end.
insert_user_mucs(From,To, #xmlel{attrs = PAttrs,children = Els}) ->
case Els of
[#xmlel{name = <<"del_user">>,attrs = Attrs}] ->
case xml:get_attr_s(<<"xmlns">>, Attrs) of
?NS_MUC_DEL_USER ->
catch odbc_queries:update_register_mucs(To#jid.lserver,To#jid.luser,From#jid.luser,From#jid.lserver,<<"0">>);
_ ->
ok
end;
[#xmlel{name = <<"add_user">>,attrs = Attrs}] ->
case xml:get_attr_s(<<"xmlns">>, Attrs) of
?NS_MUC_ADD_USER ->
catch odbc_queries:insert_user_register_mucs(To#jid.lserver,To#jid.luser,From#jid.luser,From#jid.lserver);
_ ->
ok
end;
[#xmlel{name = <<"query">>,attrs = Attrs,children = [{xmlel,<<"set_register">>,[],[]}]}] ->
case xml:get_attr_s(<<"xmlns">>, Attrs) of
?NS_MUC_REGISTER ->
case xml:get_attr_s(<<"type">>,PAttrs) of
<<"result">> ->
catch odbc_queries:insert_user_register_mucs(To#jid.lserver,To#jid.luser,From#jid.luser,From#jid.lserver);
_ ->
ok
end;
_ ->
ok
end;
_ ->
ok
end.
get_server(From_host,To_host) ->
if From_host =:= To_host ->
From_host;
true ->
lists:nth(1,ejabberd_config:get_myhosts())
end.
check_carbon_msg(Packet) ->
case catch xml:get_tag_attr_s(<<"carbon_message">>, Packet) of
<<"true">> ->
true;
_ ->
false
end.
consult_message(From,To,Packet) ->
{ThirdDirection, _CN, UsrType} = case xml:get_tag_attr_s(<<"channelid">>, Packet) of
<<"">> ->
{?DIRECTION, ?CN, ?USRTYPE};
ChannelId ->
{ok, {obj, ChannelIdJson}, []} = rfc4627:decode(ChannelId),
{proplists:get_value("d", ChannelIdJson, ?DIRECTION),
proplists:get_value("cn", ChannelIdJson, ?CN),
proplists:get_value("usrType", ChannelIdJson, ?USRTYPE)}
end,
case ThirdDirection of
<<"send">> ->
make_new_consult_message(From,To,Packet,UsrType);
?DIRECTION ->
ok
end.
make_new_consult_message(From,To,Packet,UsrType) ->
Message1 = jlib:remove_attr(<<"channelid">>, Packet),
Channelid = rfc4627:encode({obj, [{"d", <<"recv">>}, {"cn", <<"consult">>}, {"usrType", UsrType}]}),
RToStr = xml:get_tag_attr_s(<<"realto">>, Message1),
RTo = jlib:string_to_jid(RToStr),
Body = xml:get_subtag(Message1, <<"body">>),
Bid = list_to_binary("http_" ++ integer_to_list(random:uniform(65536)) ++ integer_to_list(mod_time:get_exact_timestamp())),
NewBody = xml:replace_tag_attr(<<"id">>, Bid, Body),
#xmlel{name = Name, attrs = Attrs, children = Children} = xml:replace_subtag(NewBody, Message1),
Attrs2 = jlib:replace_from_to_attrs(To, RToStr, Attrs),
NewPacket = #xmlel{name = Name, attrs = [{<<"channelid">>, Channelid}|Attrs2], children = Children},
ejabberd_router:route(jlib:string_to_jid(To), RTo, NewPacket),
Msg_id = xml:get_tag_attr_s(<<"id">>,xml:get_subtag(Packet,<<"body">>)),
Now = mod_time:get_exact_timestamp(),
insert_chat_msg(To#jid.lserver,From#jid.user,To#jid.user,From#jid.lserver,To#jid.lserver, xml:element_to_binary(
Packet),body,Msg_id,Now).
|
295ca5f0c6d2f9c552025d6a78318c9a1117895973c2afd8be80ca7ce6dee159 | brendanhay/gogol | Watch.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
{-# LANGUAGE StrictData #-}
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
-- |
Module : . AppsCalendar . Calendar . Events . Watch
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
-- Watch for changes to Events resources.
--
-- /See:/ <-apps/calendar/firstapp Calendar API Reference> for @calendar.events.watch@.
module Gogol.AppsCalendar.Calendar.Events.Watch
( -- * Resource
CalendarEventsWatchResource,
-- ** Constructing a Request
CalendarEventsWatch (..),
newCalendarEventsWatch,
)
where
import Gogol.AppsCalendar.Types
import qualified Gogol.Prelude as Core
| A resource alias for @calendar.events.watch@ method which the
' CalendarEventsWatch ' request conforms to .
type CalendarEventsWatchResource =
"calendar"
Core.:> "v3"
Core.:> "calendars"
Core.:> Core.Capture "calendarId" Core.Text
Core.:> "events"
Core.:> "watch"
Core.:> Core.QueryParam "alwaysIncludeEmail" Core.Bool
Core.:> Core.QueryParam "iCalUID" Core.Text
Core.:> Core.QueryParam "maxAttendees" Core.Int32
Core.:> Core.QueryParam "maxResults" Core.Int32
Core.:> Core.QueryParam "orderBy" EventsWatchOrderBy
Core.:> Core.QueryParam "pageToken" Core.Text
Core.:> Core.QueryParams
"privateExtendedProperty"
Core.Text
Core.:> Core.QueryParam "q" Core.Text
Core.:> Core.QueryParams
"sharedExtendedProperty"
Core.Text
Core.:> Core.QueryParam "showDeleted" Core.Bool
Core.:> Core.QueryParam
"showHiddenInvitations"
Core.Bool
Core.:> Core.QueryParam "singleEvents" Core.Bool
Core.:> Core.QueryParam "syncToken" Core.Text
Core.:> Core.QueryParam
"timeMax"
Core.DateTime
Core.:> Core.QueryParam
"timeMin"
Core.DateTime
Core.:> Core.QueryParam
"timeZone"
Core.Text
Core.:> Core.QueryParam
"updatedMin"
Core.DateTime
Core.:> Core.QueryParam
"alt"
Core.AltJSON
Core.:> Core.ReqBody
'[Core.JSON]
Channel
Core.:> Core.Post
'[Core.JSON]
Channel
-- | Watch for changes to Events resources.
--
-- /See:/ 'newCalendarEventsWatch' smart constructor.
data CalendarEventsWatch = CalendarEventsWatch
{ -- | Deprecated and ignored. A value will always be returned in the email field for the organizer, creator and attendees, even if no real email address is available (i.e. a generated, non-working value will be provided).
alwaysIncludeEmail :: (Core.Maybe Core.Bool),
| Calendar identifier . To retrieve calendar IDs call the calendarList.list method . If you want to access the primary calendar of the currently logged in user , use the \"primary\ " keyword .
calendarId :: Core.Text,
-- | Specifies event ID in the iCalendar format to be included in the response. Optional.
iCalUID :: (Core.Maybe Core.Text),
-- | The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. Optional.
maxAttendees :: (Core.Maybe Core.Int32),
| Maximum number of events returned on one result page . The number of events in the resulting page may be less than this value , or none at all , even if there are more events matching the query . Incomplete pages can be detected by a non - empty nextPageToken field in the response . By default the value is 250 events . The page size can never be larger than 2500 events . Optional .
maxResults :: Core.Int32,
-- | The order of the events returned in the result. Optional. The default is an unspecified, stable order.
orderBy :: (Core.Maybe EventsWatchOrderBy),
-- | Token specifying which result page to return. Optional.
pageToken :: (Core.Maybe Core.Text),
-- | Multipart request metadata.
payload :: Channel,
-- | Extended properties constraint specified as propertyName=value. Matches only private properties. This parameter might be repeated multiple times to return events that match all given constraints.
privateExtendedProperty :: (Core.Maybe [Core.Text]),
-- | Free text search terms to find events that match these terms in any field, except for extended properties. Optional.
q :: (Core.Maybe Core.Text),
-- | Extended properties constraint specified as propertyName=value. Matches only shared properties. This parameter might be repeated multiple times to return events that match all given constraints.
sharedExtendedProperty :: (Core.Maybe [Core.Text]),
| Whether to include deleted events ( with status equals \"cancelled\ " ) in the result . Cancelled instances of recurring events ( but not the underlying recurring event ) will still be included if showDeleted and are both False . If showDeleted and are both True , only single instances of deleted events ( but not the underlying recurring events ) are returned . Optional . The default is False .
showDeleted :: (Core.Maybe Core.Bool),
-- | Whether to include hidden invitations in the result. Optional. The default is False.
showHiddenInvitations :: (Core.Maybe Core.Bool),
| Whether to expand recurring events into instances and only return single one - off events and instances of recurring events , but not the underlying recurring events themselves . Optional . The default is False .
singleEvents :: (Core.Maybe Core.Bool),
| Token obtained from the nextSyncToken field returned on the last page of results from the previous list request . It makes the result of this list request contain only entries that have changed since then . All events deleted since the previous list request will always be in the result set and it is not allowed to set showDeleted to False . There are several query parameters that can not be specified together with nextSyncToken to ensure consistency of the client state .
--
These are : - iCalUID - orderBy - privateExtendedProperty - q - sharedExtendedProperty - timeMin - timeMax - updatedMin If the syncToken expires , the server will respond with a 410 GONE response code and the client should clear its storage and perform a full synchronization without any syncToken . Learn more about incremental synchronization . Optional . The default is to return all entries .
syncToken :: (Core.Maybe Core.Text),
| Upper bound ( exclusive ) for an event\ 's start time to filter by . Optional . The default is not to filter by start time . Must be an RFC3339 timestamp with mandatory time zone offset , for example , 2011 - 06 - 03T10:00:00 - 07:00 , 2011 - 06 - 03T10:00:00Z. Milliseconds may be provided but are ignored . If is set , must be greater than timeMin .
timeMax :: (Core.Maybe Core.DateTime),
| Lower bound ( exclusive ) for an event\ 's end time to filter by . Optional . The default is not to filter by end time . Must be an RFC3339 timestamp with mandatory time zone offset , for example , 2011 - 06 - 03T10:00:00 - 07:00 , 2011 - 06 - 03T10:00:00Z. Milliseconds may be provided but are ignored . If is set , timeMin must be smaller than timeMax .
timeMin :: (Core.Maybe Core.DateTime),
-- | Time zone used in the response. Optional. The default is the time zone of the calendar.
timeZone :: (Core.Maybe Core.Text),
-- | Lower bound for an event\'s last modification time (as a RFC3339 timestamp) to filter by. When specified, entries deleted since this time will always be included regardless of showDeleted. Optional. The default is not to filter by last modification time.
updatedMin :: (Core.Maybe Core.DateTime)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' CalendarEventsWatch ' with the minimum fields required to make a request .
newCalendarEventsWatch ::
| Calendar identifier . To retrieve calendar IDs call the calendarList.list method . If you want to access the primary calendar of the currently logged in user , use the \"primary\ " keyword . See ' calendarId ' .
Core.Text ->
-- | Multipart request metadata. See 'payload'.
Channel ->
CalendarEventsWatch
newCalendarEventsWatch calendarId payload =
CalendarEventsWatch
{ alwaysIncludeEmail = Core.Nothing,
calendarId = calendarId,
iCalUID = Core.Nothing,
maxAttendees = Core.Nothing,
maxResults = 250,
orderBy = Core.Nothing,
pageToken = Core.Nothing,
payload = payload,
privateExtendedProperty = Core.Nothing,
q = Core.Nothing,
sharedExtendedProperty = Core.Nothing,
showDeleted = Core.Nothing,
showHiddenInvitations = Core.Nothing,
singleEvents = Core.Nothing,
syncToken = Core.Nothing,
timeMax = Core.Nothing,
timeMin = Core.Nothing,
timeZone = Core.Nothing,
updatedMin = Core.Nothing
}
instance Core.GoogleRequest CalendarEventsWatch where
type Rs CalendarEventsWatch = Channel
type
Scopes CalendarEventsWatch =
'[ Calendar'FullControl,
Calendar'Events,
Calendar'Events'Readonly,
Calendar'Readonly
]
requestClient CalendarEventsWatch {..} =
go
calendarId
alwaysIncludeEmail
iCalUID
maxAttendees
(Core.Just maxResults)
orderBy
pageToken
(privateExtendedProperty Core.^. Core._Default)
q
(sharedExtendedProperty Core.^. Core._Default)
showDeleted
showHiddenInvitations
singleEvents
syncToken
timeMax
timeMin
timeZone
updatedMin
(Core.Just Core.AltJSON)
payload
appsCalendarService
where
go =
Core.buildClient
( Core.Proxy ::
Core.Proxy CalendarEventsWatchResource
)
Core.mempty
| null | https://raw.githubusercontent.com/brendanhay/gogol/77394c4e0f5bd729e6fe27119701c45f9d5e1e9a/lib/services/gogol-apps-calendar/gen/Gogol/AppsCalendar/Calendar/Events/Watch.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Stability : auto-generated
Watch for changes to Events resources.
/See:/ <-apps/calendar/firstapp Calendar API Reference> for @calendar.events.watch@.
* Resource
** Constructing a Request
| Watch for changes to Events resources.
/See:/ 'newCalendarEventsWatch' smart constructor.
| Deprecated and ignored. A value will always be returned in the email field for the organizer, creator and attendees, even if no real email address is available (i.e. a generated, non-working value will be provided).
| Specifies event ID in the iCalendar format to be included in the response. Optional.
| The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. Optional.
| The order of the events returned in the result. Optional. The default is an unspecified, stable order.
| Token specifying which result page to return. Optional.
| Multipart request metadata.
| Extended properties constraint specified as propertyName=value. Matches only private properties. This parameter might be repeated multiple times to return events that match all given constraints.
| Free text search terms to find events that match these terms in any field, except for extended properties. Optional.
| Extended properties constraint specified as propertyName=value. Matches only shared properties. This parameter might be repeated multiple times to return events that match all given constraints.
| Whether to include hidden invitations in the result. Optional. The default is False.
| Time zone used in the response. Optional. The default is the time zone of the calendar.
| Lower bound for an event\'s last modification time (as a RFC3339 timestamp) to filter by. When specified, entries deleted since this time will always be included regardless of showDeleted. Optional. The default is not to filter by last modification time.
| Multipart request metadata. See 'payload'. | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Module : . AppsCalendar . Calendar . Events . Watch
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
module Gogol.AppsCalendar.Calendar.Events.Watch
CalendarEventsWatchResource,
CalendarEventsWatch (..),
newCalendarEventsWatch,
)
where
import Gogol.AppsCalendar.Types
import qualified Gogol.Prelude as Core
| A resource alias for @calendar.events.watch@ method which the
' CalendarEventsWatch ' request conforms to .
type CalendarEventsWatchResource =
"calendar"
Core.:> "v3"
Core.:> "calendars"
Core.:> Core.Capture "calendarId" Core.Text
Core.:> "events"
Core.:> "watch"
Core.:> Core.QueryParam "alwaysIncludeEmail" Core.Bool
Core.:> Core.QueryParam "iCalUID" Core.Text
Core.:> Core.QueryParam "maxAttendees" Core.Int32
Core.:> Core.QueryParam "maxResults" Core.Int32
Core.:> Core.QueryParam "orderBy" EventsWatchOrderBy
Core.:> Core.QueryParam "pageToken" Core.Text
Core.:> Core.QueryParams
"privateExtendedProperty"
Core.Text
Core.:> Core.QueryParam "q" Core.Text
Core.:> Core.QueryParams
"sharedExtendedProperty"
Core.Text
Core.:> Core.QueryParam "showDeleted" Core.Bool
Core.:> Core.QueryParam
"showHiddenInvitations"
Core.Bool
Core.:> Core.QueryParam "singleEvents" Core.Bool
Core.:> Core.QueryParam "syncToken" Core.Text
Core.:> Core.QueryParam
"timeMax"
Core.DateTime
Core.:> Core.QueryParam
"timeMin"
Core.DateTime
Core.:> Core.QueryParam
"timeZone"
Core.Text
Core.:> Core.QueryParam
"updatedMin"
Core.DateTime
Core.:> Core.QueryParam
"alt"
Core.AltJSON
Core.:> Core.ReqBody
'[Core.JSON]
Channel
Core.:> Core.Post
'[Core.JSON]
Channel
data CalendarEventsWatch = CalendarEventsWatch
alwaysIncludeEmail :: (Core.Maybe Core.Bool),
| Calendar identifier . To retrieve calendar IDs call the calendarList.list method . If you want to access the primary calendar of the currently logged in user , use the \"primary\ " keyword .
calendarId :: Core.Text,
iCalUID :: (Core.Maybe Core.Text),
maxAttendees :: (Core.Maybe Core.Int32),
| Maximum number of events returned on one result page . The number of events in the resulting page may be less than this value , or none at all , even if there are more events matching the query . Incomplete pages can be detected by a non - empty nextPageToken field in the response . By default the value is 250 events . The page size can never be larger than 2500 events . Optional .
maxResults :: Core.Int32,
orderBy :: (Core.Maybe EventsWatchOrderBy),
pageToken :: (Core.Maybe Core.Text),
payload :: Channel,
privateExtendedProperty :: (Core.Maybe [Core.Text]),
q :: (Core.Maybe Core.Text),
sharedExtendedProperty :: (Core.Maybe [Core.Text]),
| Whether to include deleted events ( with status equals \"cancelled\ " ) in the result . Cancelled instances of recurring events ( but not the underlying recurring event ) will still be included if showDeleted and are both False . If showDeleted and are both True , only single instances of deleted events ( but not the underlying recurring events ) are returned . Optional . The default is False .
showDeleted :: (Core.Maybe Core.Bool),
showHiddenInvitations :: (Core.Maybe Core.Bool),
| Whether to expand recurring events into instances and only return single one - off events and instances of recurring events , but not the underlying recurring events themselves . Optional . The default is False .
singleEvents :: (Core.Maybe Core.Bool),
| Token obtained from the nextSyncToken field returned on the last page of results from the previous list request . It makes the result of this list request contain only entries that have changed since then . All events deleted since the previous list request will always be in the result set and it is not allowed to set showDeleted to False . There are several query parameters that can not be specified together with nextSyncToken to ensure consistency of the client state .
These are : - iCalUID - orderBy - privateExtendedProperty - q - sharedExtendedProperty - timeMin - timeMax - updatedMin If the syncToken expires , the server will respond with a 410 GONE response code and the client should clear its storage and perform a full synchronization without any syncToken . Learn more about incremental synchronization . Optional . The default is to return all entries .
syncToken :: (Core.Maybe Core.Text),
| Upper bound ( exclusive ) for an event\ 's start time to filter by . Optional . The default is not to filter by start time . Must be an RFC3339 timestamp with mandatory time zone offset , for example , 2011 - 06 - 03T10:00:00 - 07:00 , 2011 - 06 - 03T10:00:00Z. Milliseconds may be provided but are ignored . If is set , must be greater than timeMin .
timeMax :: (Core.Maybe Core.DateTime),
| Lower bound ( exclusive ) for an event\ 's end time to filter by . Optional . The default is not to filter by end time . Must be an RFC3339 timestamp with mandatory time zone offset , for example , 2011 - 06 - 03T10:00:00 - 07:00 , 2011 - 06 - 03T10:00:00Z. Milliseconds may be provided but are ignored . If is set , timeMin must be smaller than timeMax .
timeMin :: (Core.Maybe Core.DateTime),
timeZone :: (Core.Maybe Core.Text),
updatedMin :: (Core.Maybe Core.DateTime)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' CalendarEventsWatch ' with the minimum fields required to make a request .
newCalendarEventsWatch ::
| Calendar identifier . To retrieve calendar IDs call the calendarList.list method . If you want to access the primary calendar of the currently logged in user , use the \"primary\ " keyword . See ' calendarId ' .
Core.Text ->
Channel ->
CalendarEventsWatch
newCalendarEventsWatch calendarId payload =
CalendarEventsWatch
{ alwaysIncludeEmail = Core.Nothing,
calendarId = calendarId,
iCalUID = Core.Nothing,
maxAttendees = Core.Nothing,
maxResults = 250,
orderBy = Core.Nothing,
pageToken = Core.Nothing,
payload = payload,
privateExtendedProperty = Core.Nothing,
q = Core.Nothing,
sharedExtendedProperty = Core.Nothing,
showDeleted = Core.Nothing,
showHiddenInvitations = Core.Nothing,
singleEvents = Core.Nothing,
syncToken = Core.Nothing,
timeMax = Core.Nothing,
timeMin = Core.Nothing,
timeZone = Core.Nothing,
updatedMin = Core.Nothing
}
instance Core.GoogleRequest CalendarEventsWatch where
type Rs CalendarEventsWatch = Channel
type
Scopes CalendarEventsWatch =
'[ Calendar'FullControl,
Calendar'Events,
Calendar'Events'Readonly,
Calendar'Readonly
]
requestClient CalendarEventsWatch {..} =
go
calendarId
alwaysIncludeEmail
iCalUID
maxAttendees
(Core.Just maxResults)
orderBy
pageToken
(privateExtendedProperty Core.^. Core._Default)
q
(sharedExtendedProperty Core.^. Core._Default)
showDeleted
showHiddenInvitations
singleEvents
syncToken
timeMax
timeMin
timeZone
updatedMin
(Core.Just Core.AltJSON)
payload
appsCalendarService
where
go =
Core.buildClient
( Core.Proxy ::
Core.Proxy CalendarEventsWatchResource
)
Core.mempty
|
b3425258c80c54908cec4577c4dde2ac65c21eeef40f5ab217103b5776511944 | skynet-gh/skylobby | battle_chat_test.clj | (ns skylobby.fx.battle-chat-test
(:require
[cljfx.api :as fx]
[clojure.test :refer [deftest is]]
[skylobby.fx.battle-chat :as fx.battle-chat]))
(set! *warn-on-reflection* true)
(deftest battle-chat-window-impl
(is (map?
(fx.battle-chat/battle-chat-window-impl
{:fx/context (fx/create-context {})}))))
| null | https://raw.githubusercontent.com/skynet-gh/skylobby/7895ad30d992b790ffbffcd2d7be2cf17f8df794/test/clj/skylobby/fx/battle_chat_test.clj | clojure | (ns skylobby.fx.battle-chat-test
(:require
[cljfx.api :as fx]
[clojure.test :refer [deftest is]]
[skylobby.fx.battle-chat :as fx.battle-chat]))
(set! *warn-on-reflection* true)
(deftest battle-chat-window-impl
(is (map?
(fx.battle-chat/battle-chat-window-impl
{:fx/context (fx/create-context {})}))))
| |
30623d4b915c47900d4997b38b5be32521be5aaa61c1a3ff689136a299202023 | AkronCodeClub/edX-FP101x-Oct-2014 | A.hs | import Control.Parallel
main = a `par` b `par` c `pseq` print (a+b+c)
where
a = ack 3 10
b = fac 42
c = fib 34
fac 0 = 1
fac n = n * fac (n-1)
ack 0 n = n+1
ack m 0 = ack (m-1) 1
ack m n = ack (m-1) (ack m (n-1))
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)
| null | https://raw.githubusercontent.com/AkronCodeClub/edX-FP101x-Oct-2014/7db691d795126ad912256fec29b5aa1817beb8c0/chris_f/5steps/A.hs | haskell | import Control.Parallel
main = a `par` b `par` c `pseq` print (a+b+c)
where
a = ack 3 10
b = fac 42
c = fib 34
fac 0 = 1
fac n = n * fac (n-1)
ack 0 n = n+1
ack m 0 = ack (m-1) 1
ack m n = ack (m-1) (ack m (n-1))
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)
| |
3a66121281fec61528bfe9ad5b27930caaa47afb6137cfec2a2a16f6d9dd528a | c-cube/ocaml-containers | CCIntMap.mli | * Map specialized for Int keys
{ b status : stable }
@since 0.10
{b status: stable}
@since 0.10 *)
type +'a t
val empty : 'a t
val is_empty : _ t -> bool
* Is the map empty ?
@since 2.3
@since 2.3 *)
val singleton : int -> 'a -> 'a t
val doubleton : int -> 'a -> int -> 'a -> 'a t
val mem : int -> _ t -> bool
val find : int -> 'a t -> 'a option
val find_exn : int -> 'a t -> 'a
(** Same as {!find} but unsafe.
@raise Not_found if key is not present. *)
val add : int -> 'a -> 'a t -> 'a t
val remove : int -> 'a t -> 'a t
val equal : eq:('a -> 'a -> bool) -> 'a t -> 'a t -> bool
* [ equal ~eq a b ] checks whether [ a ] and [ b ] have the same set of pairs
( key , value ) , comparing values with [ eq ] .
@since 0.13
(key, value), comparing values with [eq].
@since 0.13 *)
val compare : cmp:('a -> 'a -> int) -> 'a t -> 'a t -> int
* Total order between maps ; the precise order is unspecified .
@since 0.13
@since 0.13 *)
val update : int -> ('a option -> 'a option) -> 'a t -> 'a t
val filter : (int -> 'a -> bool) -> 'a t -> 'a t
* Filter values using the given predicate
@since 2.3
@since 2.3 *)
val filter_map : (int -> 'a -> 'b option) -> 'a t -> 'b t
* Filter - map values using the given function
@since 2.3
@since 2.3 *)
val cardinal : _ t -> int
(** Number of bindings in the map. Linear time. *)
val iter : (int -> 'a -> unit) -> 'a t -> unit
val fold : (int -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
val mapi : (int -> 'a -> 'b) -> 'a t -> 'b t
* @since 0.17
val map : ('a -> 'b) -> 'a t -> 'b t
* @since 0.17
val choose : 'a t -> (int * 'a) option
val choose_exn : 'a t -> int * 'a
(** @raise Not_found if not pair was found. *)
val union : (int -> 'a -> 'a -> 'a) -> 'a t -> 'a t -> 'a t
val inter : (int -> 'a -> 'a -> 'a) -> 'a t -> 'a t -> 'a t
val merge :
f:(int -> [ `Left of 'a | `Right of 'b | `Both of 'a * 'b ] -> 'c option) ->
'a t ->
'b t ->
'c t
* [ merge ~f ] merges [ m1 ] and [ m2 ] together , calling [ f ] once on every
key that occurs in at least one of [ m1 ] and [ m2 ] .
if [ f k binding = Some c ] then [ k - > c ] is part of the result ,
else [ k ] is not part of the result .
@since 2.3
key that occurs in at least one of [m1] and [m2].
if [f k binding = Some c] then [k -> c] is part of the result,
else [k] is not part of the result.
@since 2.3 *)
* { 2 Whole - collection operations }
type 'a iter = ('a -> unit) -> unit
type 'a gen = unit -> 'a option
val add_list : 'a t -> (int * 'a) list -> 'a t
val of_list : (int * 'a) list -> 'a t
val to_list : 'a t -> (int * 'a) list
val add_iter : 'a t -> (int * 'a) iter -> 'a t
val of_iter : (int * 'a) iter -> 'a t
val to_iter : 'a t -> (int * 'a) iter
val keys : _ t -> int iter
val values : 'a t -> 'a iter
val add_gen : 'a t -> (int * 'a) gen -> 'a t
* @since 0.13
val of_gen : (int * 'a) gen -> 'a t
* @since 0.13
val to_gen : 'a t -> (int * 'a) gen
* @since 0.13
val add_seq : 'a t -> (int * 'a) Seq.t -> 'a t
* @since 3.0
val of_seq : (int * 'a) Seq.t -> 'a t
* @since 3.0
val to_seq : 'a t -> (int * 'a) Seq.t
* @since 3.0
type 'a tree = unit -> [ `Nil | `Node of 'a * 'a tree list ]
val as_tree : 'a t -> [ `Node of int * int | `Leaf of int * 'a ] tree
* { 2 IO }
type 'a printer = Format.formatter -> 'a -> unit
val pp : 'a printer -> 'a t printer
* @since 0.13
(** Helpers *)
(**/**)
module Bit : sig
type t = private int
val min_int : t
val highest : int -> t
val equal_int : int -> t -> bool
end
val check_invariants : _ t -> bool
(**/**)
| null | https://raw.githubusercontent.com/c-cube/ocaml-containers/69f2805f1073c4ebd1063bbd58380d17e62f6324/src/data/CCIntMap.mli | ocaml | * Same as {!find} but unsafe.
@raise Not_found if key is not present.
* Number of bindings in the map. Linear time.
* @raise Not_found if not pair was found.
* Helpers
*/*
*/* | * Map specialized for Int keys
{ b status : stable }
@since 0.10
{b status: stable}
@since 0.10 *)
type +'a t
val empty : 'a t
val is_empty : _ t -> bool
* Is the map empty ?
@since 2.3
@since 2.3 *)
val singleton : int -> 'a -> 'a t
val doubleton : int -> 'a -> int -> 'a -> 'a t
val mem : int -> _ t -> bool
val find : int -> 'a t -> 'a option
val find_exn : int -> 'a t -> 'a
val add : int -> 'a -> 'a t -> 'a t
val remove : int -> 'a t -> 'a t
val equal : eq:('a -> 'a -> bool) -> 'a t -> 'a t -> bool
* [ equal ~eq a b ] checks whether [ a ] and [ b ] have the same set of pairs
( key , value ) , comparing values with [ eq ] .
@since 0.13
(key, value), comparing values with [eq].
@since 0.13 *)
val compare : cmp:('a -> 'a -> int) -> 'a t -> 'a t -> int
* Total order between maps ; the precise order is unspecified .
@since 0.13
@since 0.13 *)
val update : int -> ('a option -> 'a option) -> 'a t -> 'a t
val filter : (int -> 'a -> bool) -> 'a t -> 'a t
* Filter values using the given predicate
@since 2.3
@since 2.3 *)
val filter_map : (int -> 'a -> 'b option) -> 'a t -> 'b t
* Filter - map values using the given function
@since 2.3
@since 2.3 *)
val cardinal : _ t -> int
val iter : (int -> 'a -> unit) -> 'a t -> unit
val fold : (int -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
val mapi : (int -> 'a -> 'b) -> 'a t -> 'b t
* @since 0.17
val map : ('a -> 'b) -> 'a t -> 'b t
* @since 0.17
val choose : 'a t -> (int * 'a) option
val choose_exn : 'a t -> int * 'a
val union : (int -> 'a -> 'a -> 'a) -> 'a t -> 'a t -> 'a t
val inter : (int -> 'a -> 'a -> 'a) -> 'a t -> 'a t -> 'a t
val merge :
f:(int -> [ `Left of 'a | `Right of 'b | `Both of 'a * 'b ] -> 'c option) ->
'a t ->
'b t ->
'c t
* [ merge ~f ] merges [ m1 ] and [ m2 ] together , calling [ f ] once on every
key that occurs in at least one of [ m1 ] and [ m2 ] .
if [ f k binding = Some c ] then [ k - > c ] is part of the result ,
else [ k ] is not part of the result .
@since 2.3
key that occurs in at least one of [m1] and [m2].
if [f k binding = Some c] then [k -> c] is part of the result,
else [k] is not part of the result.
@since 2.3 *)
* { 2 Whole - collection operations }
type 'a iter = ('a -> unit) -> unit
type 'a gen = unit -> 'a option
val add_list : 'a t -> (int * 'a) list -> 'a t
val of_list : (int * 'a) list -> 'a t
val to_list : 'a t -> (int * 'a) list
val add_iter : 'a t -> (int * 'a) iter -> 'a t
val of_iter : (int * 'a) iter -> 'a t
val to_iter : 'a t -> (int * 'a) iter
val keys : _ t -> int iter
val values : 'a t -> 'a iter
val add_gen : 'a t -> (int * 'a) gen -> 'a t
* @since 0.13
val of_gen : (int * 'a) gen -> 'a t
* @since 0.13
val to_gen : 'a t -> (int * 'a) gen
* @since 0.13
val add_seq : 'a t -> (int * 'a) Seq.t -> 'a t
* @since 3.0
val of_seq : (int * 'a) Seq.t -> 'a t
* @since 3.0
val to_seq : 'a t -> (int * 'a) Seq.t
* @since 3.0
type 'a tree = unit -> [ `Nil | `Node of 'a * 'a tree list ]
val as_tree : 'a t -> [ `Node of int * int | `Leaf of int * 'a ] tree
* { 2 IO }
type 'a printer = Format.formatter -> 'a -> unit
val pp : 'a printer -> 'a t printer
* @since 0.13
module Bit : sig
type t = private int
val min_int : t
val highest : int -> t
val equal_int : int -> t -> bool
end
val check_invariants : _ t -> bool
|
48a96864406d6657a0b4d1eafb9feeee04f7789b958c75a9417c46004d6f8b9d | typedb-osi/typedb-client-haskell | TypeQLParser.hs | # LANGUAGE QuasiQuotes #
# LANGUAGE TemplateHaskell #
module TypeQLParser where
[ g4|
atom
: STRING - > Str
| SYMBOL - > Symb
| NUMBER - > Number
;
STRING : ( ( ' \\ ' . ) | ~ [ \\ ] ) * - > String ;
WHITESPACE : [ \n\t\r]+ - > String ;
NUMBER : ( ' + ' | ' - ' ) ? ( ' . ' ) ? - > Double ;
SYMBOL : SYMBOL_START ( SYMBOL_START | DIGIT ) * - > String ;
fragment SYMBOL_START : [ a - zA - Z+\-*/ ] ;
fragment DIGIT : [ 0 - 9 ] ;
| ]
[g4|
atom
: STRING -> Str
| SYMBOL -> Symb
| NUMBER -> Number
;
STRING : ( ('\\' .) | ~ [\\] )* -> String;
WHITESPACE : [ \n\t\r]+ -> String;
NUMBER : ('+' | '-')? DIGIT+ ('.' DIGIT+)? -> Double;
SYMBOL : SYMBOL_START (SYMBOL_START | DIGIT)* -> String;
fragment SYMBOL_START : [a-zA-Z+\-*/] ;
fragment DIGIT : [0-9] ;
|]
-}
| null | https://raw.githubusercontent.com/typedb-osi/typedb-client-haskell/051a4c93ff255c6df58ac0676ba3b0f306862cdd/lib/TypeQLParser.hs | haskell | # LANGUAGE QuasiQuotes #
# LANGUAGE TemplateHaskell #
module TypeQLParser where
[ g4|
atom
: STRING - > Str
| SYMBOL - > Symb
| NUMBER - > Number
;
STRING : ( ( ' \\ ' . ) | ~ [ \\ ] ) * - > String ;
WHITESPACE : [ \n\t\r]+ - > String ;
NUMBER : ( ' + ' | ' - ' ) ? ( ' . ' ) ? - > Double ;
SYMBOL : SYMBOL_START ( SYMBOL_START | DIGIT ) * - > String ;
fragment SYMBOL_START : [ a - zA - Z+\-*/ ] ;
fragment DIGIT : [ 0 - 9 ] ;
| ]
[g4|
atom
: STRING -> Str
| SYMBOL -> Symb
| NUMBER -> Number
;
STRING : ( ('\\' .) | ~ [\\] )* -> String;
WHITESPACE : [ \n\t\r]+ -> String;
NUMBER : ('+' | '-')? DIGIT+ ('.' DIGIT+)? -> Double;
SYMBOL : SYMBOL_START (SYMBOL_START | DIGIT)* -> String;
fragment SYMBOL_START : [a-zA-Z+\-*/] ;
fragment DIGIT : [0-9] ;
|]
-}
| |
ad6f4712ad9adc157e335b72086cace470a8e0949a566d5a4a7cd5dc893850a8 | Helium4Haskell/helium | Information.hs | module Helium.StaticAnalysis.Messages.Information where
import Top.Types
import Helium.Main.CompileUtils
import Helium.Parser.OperatorTable
import Helium.StaticAnalysis.Messages.Messages hiding (Constructor)
import Helium.Syntax.UHA_Syntax hiding (Fixity)
import Helium.Syntax.UHA_Utils
import Helium.Syntax.UHA_Range
import qualified Data.Map as M
type Fixity = (Int, Assoc)
data InfoItem
= Function Name TpScheme (Maybe Fixity)
| ValueConstructor Name TpScheme (Maybe Fixity)
| TypeSynonym Name Int (Tps -> Tp)
| DataTypeConstructor Name Int [(Name, TpScheme)]
| TypeClass String Class
| NotDefined String
showInformation :: Bool -> [Option] -> ImportEnvironment -> IO ()
showInformation reportNotFound options importEnv =
let items = concat [ makeInfoItem name | Information name <- options ]
in showMessages items
where
makeInfoItem :: String -> [InfoItem]
makeInfoItem string =
let
notFound items = if null items && reportNotFound then [ NotDefined string ] else items
function =
case lookupWithKey (nameFromString string) (typeEnvironment importEnv) of
Just (name, scheme) ->
[Function name scheme (M.lookup name (operatorTable importEnv))]
Nothing -> []
constructor =
case lookupWithKey (nameFromString string) (valueConstructors importEnv) of
Just (name, (_, scheme)) ->
[ValueConstructor name scheme (M.lookup name (operatorTable importEnv))]
Nothing -> []
synonyms =
case lookupWithKey (nameFromString string) (typeSynonyms importEnv) of
Just (name, (i, f)) ->
[TypeSynonym name i f]
Nothing -> []
datatypeconstructor =
case lookupWithKey (nameFromString string) (typeConstructors importEnv) of
Just (name, (i,_)) | not (M.member name (typeSynonyms importEnv))
-> [DataTypeConstructor name i (findValueConstructors name importEnv)]
_ -> []
typeclass =
case M.lookup string (classEnvironment importEnv) of
Just cl -> [TypeClass string cl]
Nothing -> []
in
notFound (function ++ constructor ++ synonyms ++ datatypeconstructor ++ typeclass)
itemDescription :: InfoItem -> [String]
itemDescription infoItem =
case infoItem of
Function name ts _ ->
let tp = unqualify (unquantify ts)
start | isOperatorName name = "operator"
| isFunctionType tp = "function"
| otherwise = "value"
in [ "-- " ++ start ++ " " ++ show name ++ ", " ++ definedOrImported (getNameRange name) ]
ValueConstructor name _ _ ->
[ "-- value constructor " ++ show name ++ ", " ++ definedOrImported (getNameRange name) ]
TypeSynonym name _ _ ->
[ "-- type synonym " ++ show name ++ ", " ++ definedOrImported (getNameRange name) ]
DataTypeConstructor name _ _ ->
[ "-- type constructor " ++ show name ++ ", " ++ definedOrImported (getNameRange name) ]
TypeClass s _ ->
[ " -- type class " ++ s ]
NotDefined _ ->
[ ]
definedOrImported :: Range -> String
definedOrImported range
| isImportRange range = "imported from " ++ show range
| otherwise = "defined at " ++ show range
showMaybeFixity :: Name -> Maybe Fixity -> MessageBlocks
showMaybeFixity name =
let f (prio', associativity) = show associativity ++ " " ++ show prio' ++ " " ++ showNameAsOperator name
in maybe [] ((:[]) . MessageString . f)
instance HasMessage InfoItem where
getMessage infoItem =
map (MessageOneLiner . MessageString) (itemDescription infoItem)
++
case infoItem of
Function name ts mFixity ->
map MessageOneLiner
( MessageString (showNameAsVariable name ++ " :: " ++ show ts)
: showMaybeFixity name mFixity
)
ValueConstructor name ts mFixity ->
map MessageOneLiner
( MessageString (showNameAsVariable name ++ " :: " ++ show ts)
: showMaybeFixity name mFixity
)
TypeSynonym name i f ->
let tps = take i [ TCon [c] | c <- ['a'..] ]
text = unwords ("type" : show name : map show tps ++ ["=", show (f tps)])
in [ MessageOneLiner (MessageString text) ]
DataTypeConstructor name i cons ->
let tps = take i [ TCon [c] | c <- ['a'..] ]
text = unwords ("data" : show name : map show tps)
related = let f (name', ts) = " " ++ showNameAsVariable name' ++ " :: " ++ show ts
in if null cons then [] else " -- value constructors" : map f cons
in map MessageOneLiner
( MessageString text
: map MessageString related
)
TypeClass name (supers, theInstances) ->
let f s = s ++ " a"
text = "class " ++ showContextSimple (map f supers) ++ f name
related = let ef (p, ps) = " instance " ++ show (generalizeAll (ps .=>. p))
in if null theInstances then [] else " -- instances" : map ef theInstances
in map MessageOneLiner
( MessageString text
: map MessageString related
)
NotDefined name ->
map MessageOneLiner
[ MessageString (show name ++ " not defined") ]
findValueConstructors :: Name -> ImportEnvironment -> [(Name, TpScheme)]
findValueConstructors name =
let test = isName . fst . leftSpine . snd . functionSpine . unqualify . unquantify
isName (TCon s) = s == show name
isName _ = False
toSchemeMap = M.map (\(_, scheme) -> scheme)
in M.assocs . M.filter test . toSchemeMap . valueConstructors
lookupWithKey :: Ord key => key -> M.Map key a -> Maybe (key, a)
lookupWithKey key = M.lookup key . M.mapWithKey (,) | null | https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/src/Helium/StaticAnalysis/Messages/Information.hs | haskell | module Helium.StaticAnalysis.Messages.Information where
import Top.Types
import Helium.Main.CompileUtils
import Helium.Parser.OperatorTable
import Helium.StaticAnalysis.Messages.Messages hiding (Constructor)
import Helium.Syntax.UHA_Syntax hiding (Fixity)
import Helium.Syntax.UHA_Utils
import Helium.Syntax.UHA_Range
import qualified Data.Map as M
type Fixity = (Int, Assoc)
data InfoItem
= Function Name TpScheme (Maybe Fixity)
| ValueConstructor Name TpScheme (Maybe Fixity)
| TypeSynonym Name Int (Tps -> Tp)
| DataTypeConstructor Name Int [(Name, TpScheme)]
| TypeClass String Class
| NotDefined String
showInformation :: Bool -> [Option] -> ImportEnvironment -> IO ()
showInformation reportNotFound options importEnv =
let items = concat [ makeInfoItem name | Information name <- options ]
in showMessages items
where
makeInfoItem :: String -> [InfoItem]
makeInfoItem string =
let
notFound items = if null items && reportNotFound then [ NotDefined string ] else items
function =
case lookupWithKey (nameFromString string) (typeEnvironment importEnv) of
Just (name, scheme) ->
[Function name scheme (M.lookup name (operatorTable importEnv))]
Nothing -> []
constructor =
case lookupWithKey (nameFromString string) (valueConstructors importEnv) of
Just (name, (_, scheme)) ->
[ValueConstructor name scheme (M.lookup name (operatorTable importEnv))]
Nothing -> []
synonyms =
case lookupWithKey (nameFromString string) (typeSynonyms importEnv) of
Just (name, (i, f)) ->
[TypeSynonym name i f]
Nothing -> []
datatypeconstructor =
case lookupWithKey (nameFromString string) (typeConstructors importEnv) of
Just (name, (i,_)) | not (M.member name (typeSynonyms importEnv))
-> [DataTypeConstructor name i (findValueConstructors name importEnv)]
_ -> []
typeclass =
case M.lookup string (classEnvironment importEnv) of
Just cl -> [TypeClass string cl]
Nothing -> []
in
notFound (function ++ constructor ++ synonyms ++ datatypeconstructor ++ typeclass)
itemDescription :: InfoItem -> [String]
itemDescription infoItem =
case infoItem of
Function name ts _ ->
let tp = unqualify (unquantify ts)
start | isOperatorName name = "operator"
| isFunctionType tp = "function"
| otherwise = "value"
in [ "-- " ++ start ++ " " ++ show name ++ ", " ++ definedOrImported (getNameRange name) ]
ValueConstructor name _ _ ->
[ "-- value constructor " ++ show name ++ ", " ++ definedOrImported (getNameRange name) ]
TypeSynonym name _ _ ->
[ "-- type synonym " ++ show name ++ ", " ++ definedOrImported (getNameRange name) ]
DataTypeConstructor name _ _ ->
[ "-- type constructor " ++ show name ++ ", " ++ definedOrImported (getNameRange name) ]
TypeClass s _ ->
[ " -- type class " ++ s ]
NotDefined _ ->
[ ]
definedOrImported :: Range -> String
definedOrImported range
| isImportRange range = "imported from " ++ show range
| otherwise = "defined at " ++ show range
showMaybeFixity :: Name -> Maybe Fixity -> MessageBlocks
showMaybeFixity name =
let f (prio', associativity) = show associativity ++ " " ++ show prio' ++ " " ++ showNameAsOperator name
in maybe [] ((:[]) . MessageString . f)
instance HasMessage InfoItem where
getMessage infoItem =
map (MessageOneLiner . MessageString) (itemDescription infoItem)
++
case infoItem of
Function name ts mFixity ->
map MessageOneLiner
( MessageString (showNameAsVariable name ++ " :: " ++ show ts)
: showMaybeFixity name mFixity
)
ValueConstructor name ts mFixity ->
map MessageOneLiner
( MessageString (showNameAsVariable name ++ " :: " ++ show ts)
: showMaybeFixity name mFixity
)
TypeSynonym name i f ->
let tps = take i [ TCon [c] | c <- ['a'..] ]
text = unwords ("type" : show name : map show tps ++ ["=", show (f tps)])
in [ MessageOneLiner (MessageString text) ]
DataTypeConstructor name i cons ->
let tps = take i [ TCon [c] | c <- ['a'..] ]
text = unwords ("data" : show name : map show tps)
related = let f (name', ts) = " " ++ showNameAsVariable name' ++ " :: " ++ show ts
in if null cons then [] else " -- value constructors" : map f cons
in map MessageOneLiner
( MessageString text
: map MessageString related
)
TypeClass name (supers, theInstances) ->
let f s = s ++ " a"
text = "class " ++ showContextSimple (map f supers) ++ f name
related = let ef (p, ps) = " instance " ++ show (generalizeAll (ps .=>. p))
in if null theInstances then [] else " -- instances" : map ef theInstances
in map MessageOneLiner
( MessageString text
: map MessageString related
)
NotDefined name ->
map MessageOneLiner
[ MessageString (show name ++ " not defined") ]
findValueConstructors :: Name -> ImportEnvironment -> [(Name, TpScheme)]
findValueConstructors name =
let test = isName . fst . leftSpine . snd . functionSpine . unqualify . unquantify
isName (TCon s) = s == show name
isName _ = False
toSchemeMap = M.map (\(_, scheme) -> scheme)
in M.assocs . M.filter test . toSchemeMap . valueConstructors
lookupWithKey :: Ord key => key -> M.Map key a -> Maybe (key, a)
lookupWithKey key = M.lookup key . M.mapWithKey (,) | |
92ae870f16cc538198672544eb29579be1bbc93c0135c82ec047f00826057b88 | hasktorch/hasktorch | Autograd.hs | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE PolyKinds #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
# LANGUAGE NoStarIsType #
module Torch.Typed.Autograd
( Torch.Typed.Autograd.HasGrad,
Torch.Typed.Autograd.grad,
)
where
import Data.Kind
import GHC.TypeLits
import System.IO.Unsafe
import qualified Torch.DType as D
import qualified Torch.Device as D
import Torch.HList
import qualified Torch.Internal.Cast as ATen
import qualified Torch.Internal.Class as ATen
import qualified Torch.Internal.Managed.Autograd as LibTorch
import qualified Torch.Tensor as D
import Torch.Typed.Parameter
import Torch.Typed.Tensor
class HasGrad a b | a -> b where
| calculate gradients of a zero - dimensional tensor with respect to a list of parameters
grad :: forall dtype device. Tensor device dtype '[] -> a -> b
toDependent :: a -> b
instance ( Tensor device dtype shape ) ( Tensor device dtype shape ) where
grad loss input = head . $ ATen.cast2
Torch.Managed.Autograd.grad
-- loss
[ Torch . Typed . Autograd.toDependent input ]
-- toDependent = id
instance HasGrad (Parameter device dtype shape) (Tensor device dtype shape) where
grad loss input =
head . unsafePerformIO $
ATen.cast2
LibTorch.grad
loss
[Torch.Typed.Autograd.toDependent input]
toDependent = Torch.Typed.Parameter.toDependent
instance HasGrad (HList ('[] :: [Type])) (HList ('[] :: [Type])) where
grad _ = id
toDependent = id
instance
( HasGrad a b,
HasGrad (HList as) (HList bs),
ATen.Castable (HList (b ': bs)) [D.ATenTensor]
) =>
HasGrad (HList (a ': as)) (HList (b ': bs))
where
grad loss inputs =
unsafePerformIO $
ATen.cast2
LibTorch.grad
loss
(Torch.Typed.Autograd.toDependent inputs)
toDependent (a :. as) =
Torch.Typed.Autograd.toDependent a :. Torch.Typed.Autograd.toDependent as
| null | https://raw.githubusercontent.com/hasktorch/hasktorch/4e846fdcd89df5c7c6991cb9d6142007a6bb0a58/hasktorch/src/Torch/Typed/Autograd.hs | haskell | # LANGUAGE RankNTypes #
loss
toDependent = id | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE PolyKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
# LANGUAGE NoStarIsType #
module Torch.Typed.Autograd
( Torch.Typed.Autograd.HasGrad,
Torch.Typed.Autograd.grad,
)
where
import Data.Kind
import GHC.TypeLits
import System.IO.Unsafe
import qualified Torch.DType as D
import qualified Torch.Device as D
import Torch.HList
import qualified Torch.Internal.Cast as ATen
import qualified Torch.Internal.Class as ATen
import qualified Torch.Internal.Managed.Autograd as LibTorch
import qualified Torch.Tensor as D
import Torch.Typed.Parameter
import Torch.Typed.Tensor
class HasGrad a b | a -> b where
| calculate gradients of a zero - dimensional tensor with respect to a list of parameters
grad :: forall dtype device. Tensor device dtype '[] -> a -> b
toDependent :: a -> b
instance ( Tensor device dtype shape ) ( Tensor device dtype shape ) where
grad loss input = head . $ ATen.cast2
Torch.Managed.Autograd.grad
[ Torch . Typed . Autograd.toDependent input ]
instance HasGrad (Parameter device dtype shape) (Tensor device dtype shape) where
grad loss input =
head . unsafePerformIO $
ATen.cast2
LibTorch.grad
loss
[Torch.Typed.Autograd.toDependent input]
toDependent = Torch.Typed.Parameter.toDependent
instance HasGrad (HList ('[] :: [Type])) (HList ('[] :: [Type])) where
grad _ = id
toDependent = id
instance
( HasGrad a b,
HasGrad (HList as) (HList bs),
ATen.Castable (HList (b ': bs)) [D.ATenTensor]
) =>
HasGrad (HList (a ': as)) (HList (b ': bs))
where
grad loss inputs =
unsafePerformIO $
ATen.cast2
LibTorch.grad
loss
(Torch.Typed.Autograd.toDependent inputs)
toDependent (a :. as) =
Torch.Typed.Autograd.toDependent a :. Torch.Typed.Autograd.toDependent as
|
a98d929878d3b5733d3c76ff7b7ed66000aeaac4924352a54de01411cf7b7951 | reborg/clojure-essential-reference | 16.clj | < 1 >
( ( 0 ) ( 1 2 3 4 5 6 7 8 9 ) )
< 2 >
;; (0)
(first (sequence (partition-by pos?) (range))) ; <3>
;; WARNING: hangs | null | https://raw.githubusercontent.com/reborg/clojure-essential-reference/c37fa19d45dd52b2995a191e3e96f0ebdc3f6d69/SequentialProcessing/partition%2Cpartition-allandpartition-by/16.clj | clojure | (0)
<3>
WARNING: hangs | < 1 >
( ( 0 ) ( 1 2 3 4 5 6 7 8 9 ) )
< 2 >
|
a1bf13493d123573ab4a64678bc3c95046ed05cd91f4631819e30660303452a2 | svenvc/s-http-server | test.lisp | ;;;; -*- mode: lisp -*-
;;;;
;;;; Test and example code for S-HTTP[S]-SERVER
;;;;
Copyright ( C ) 2006 - 2009 , Beta Nine BVBA .
;;;;
;;;; You are granted the rights to distribute and use this software
as governed by the terms of the Lisp Lesser General Public License
;;;; (), also known as the LLGPL.
(in-package :s-http-server)
;; some convenience globals
(defvar test-server)
(defun start-test-server ()
(start-server test-server))
(defun stop-test-server ()
(stop-server test-server))
;; a quick example on setting up a server on a directory
(defun make-test-server (&key (port 1701)
(www "/Library/WebServer/Documents/"))
(setf test-server (make-s-http-server :port port))
(configure-default-handlers test-server)
(register-context-handler test-server "/www" 'static-resource-handler :arguments (list www))
test-server)
after starting the above server , you can access :1701 / s - http - server
;; by disabling debug mode and logging to *standard-output*, you get a faster server
(defun make-fast-server ()
(setf test-server (make-s-http-server :log-stream nil :access-log-stream nil))
(configure-default-handlers test-server)
(setf (get-debug-mode test-server) nil)
test-server)
;; the files in the rsrc directory are provided as examples to configure an https server
(defun make-secure-server (&key (rsrc-dir "/Users/sven/darcs/s-http-server/rsrc/"))
(setf test-server
(make-s-https-server :certificate (merge-pathnames "test-server.crt" rsrc-dir)
:private-key (merge-pathnames "test-server.key" rsrc-dir)
:dhparam (merge-pathnames "dhparam.pem" rsrc-dir)
:password "123456"))
(configure-default-handlers test-server)
test-server)
;; please consult the readme.txt file in the rsrc directory for more information.
;; after starting the above server, you can access :1701/s-http-server
eof
| null | https://raw.githubusercontent.com/svenvc/s-http-server/552973ab051a2e0478807153402a347be5943a4d/src/test.lisp | lisp | -*- mode: lisp -*-
Test and example code for S-HTTP[S]-SERVER
You are granted the rights to distribute and use this software
(), also known as the LLGPL.
some convenience globals
a quick example on setting up a server on a directory
by disabling debug mode and logging to *standard-output*, you get a faster server
the files in the rsrc directory are provided as examples to configure an https server
please consult the readme.txt file in the rsrc directory for more information.
after starting the above server, you can access :1701/s-http-server | Copyright ( C ) 2006 - 2009 , Beta Nine BVBA .
as governed by the terms of the Lisp Lesser General Public License
(in-package :s-http-server)
(defvar test-server)
(defun start-test-server ()
(start-server test-server))
(defun stop-test-server ()
(stop-server test-server))
(defun make-test-server (&key (port 1701)
(www "/Library/WebServer/Documents/"))
(setf test-server (make-s-http-server :port port))
(configure-default-handlers test-server)
(register-context-handler test-server "/www" 'static-resource-handler :arguments (list www))
test-server)
after starting the above server , you can access :1701 / s - http - server
(defun make-fast-server ()
(setf test-server (make-s-http-server :log-stream nil :access-log-stream nil))
(configure-default-handlers test-server)
(setf (get-debug-mode test-server) nil)
test-server)
(defun make-secure-server (&key (rsrc-dir "/Users/sven/darcs/s-http-server/rsrc/"))
(setf test-server
(make-s-https-server :certificate (merge-pathnames "test-server.crt" rsrc-dir)
:private-key (merge-pathnames "test-server.key" rsrc-dir)
:dhparam (merge-pathnames "dhparam.pem" rsrc-dir)
:password "123456"))
(configure-default-handlers test-server)
test-server)
eof
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.