_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 |
|---|---|---|---|---|---|---|---|---|
27afbbd3546dfb6ca1d00ce763ea7934e9a416766dcd77f08eed0fb2b0b7be98 | kiranlak/austin-sbst | branchtrace.ml | Copyright : , University College London , 2011
open Cil
open Printf
open Cfginfo
open Utils
open TraceManager
module Log = LogManager
let prototypeFundecs = ref []
let branchInfos : (int,exp) Hashtbl.t = Hashtbl.create Options.hashtblInitSize
let reset () =
prototypeFundecs := [];
Hashtbl.clear branchInfos
let addPrototype (f:fundec) =
let namesMatch (f':fundec) = (compare f'.svar.vname f.svar.vname) = 0 in
if not(List.exists namesMatch (!prototypeFundecs)) then
prototypeFundecs := (f::(!prototypeFundecs));
;;
let ikindStrAndCast (kind : ikind) =
match kind with
| IChar -> ("Char", TInt(IChar,[]))
| ISChar -> ("SChar", TInt(ISChar,[]))
| IUChar -> ("UChar", TInt(IUChar,[]))
| IBool -> ("Bool", TInt(IBool,[]))
| IInt -> ("Int", TInt(IInt,[]))
| IUInt -> ("UInt", TInt(IUInt,[]))
| IShort -> ("Short", TInt(IShort,[]))
| IUShort -> ("UShort", TInt(IUShort,[]))
| ILong -> ("Long", TInt(ILong,[]))
| IULong -> ("ULong", TInt(IULong,[]))
| ILongLong -> ("LongLong", TInt(ILongLong,[]))
| IULongLong -> ("ULongLong", TInt(IULongLong,[]))
let fkindStrAndCast (kind : fkind) =
match kind with
| FFloat -> ("Float", TFloat(FFloat,[]))
| FDouble -> ("Double", TFloat(FDouble,[]))
| FLongDouble -> ("LongDouble", TFloat(FLongDouble,[]))
let rec typeToString (t:typ) =
match (unrollType t) with
| TVoid _ -> ("Void", voidPtrType)
| TInt(kind, _) -> ikindStrAndCast kind
| TFloat(kind, _) -> fkindStrAndCast kind
| TNamed(ti, _) -> typeToString ti.ttype
| TPtr(pt, _) -> ("Void", voidPtrType)(*typeToString pt*)
| TEnum(ei,_) -> ikindStrAndCast ei.ekind
| _ -> Log.error (Printf.sprintf "invalid distance type: %s\r\n" (Pretty.sprint 255 (Cil.d_type () t)))
let getBinOpFuncName (b:binop) (orig:exp) (lhs:exp) (rhs:exp) =
match b with
| Lt -> ("Austin__EvalLessThan__", lhs, rhs)
| Gt -> ("Austin__EvalGreaterThan__", lhs, rhs)
| Le -> ("Austin__EvalLessThanEq__", lhs, rhs)
| Ge -> ("Austin__EvalGreaterThanEq__", lhs, rhs)
| Eq -> ("Austin__EvalEquals__", lhs, rhs)
| Ne -> ("Austin__EvalNotEqual__", lhs, rhs)
| _ -> ("Austin__EvalNotEqual__", orig, zero)
let getUnOpoFuncName (u:unop) (orig : exp) =
match u with
| Neg -> ("Austin__EvalNotEqual__", orig, zero)
| BNot -> ("Austin__EvalNotEqual__", orig, zero)
| LNot -> ("Austin__EvalEquals__", orig, zero)
let invertExpression (e:exp) =
let strippedEx, strippedCasts = stripCastsEx e [] in
match strippedEx with
| UnOp(u, e', t) ->
(
match u with
| LNot -> reapplyCasts e' strippedCasts
| _ -> UnOp(LNot, e, t)
)
| BinOp(b, lhs, rhs, t) ->
(
match b with
| Lt -> reapplyCasts (BinOp(Ge, lhs, rhs, t)) strippedCasts
| Gt -> reapplyCasts (BinOp(Le, lhs, rhs, t)) strippedCasts
| Le -> reapplyCasts (BinOp(Gt, lhs, rhs, t)) strippedCasts
| Ge -> reapplyCasts (BinOp(Lt, lhs, rhs, t)) strippedCasts
| Eq -> reapplyCasts (BinOp(Ne, lhs, rhs, t)) strippedCasts
| Ne -> reapplyCasts (BinOp(Eq, lhs, rhs, t)) strippedCasts
| _ -> UnOp(LNot, e, t)
)
| _ -> UnOp(LNot, e, (typeOf e))
let uint (value : int) =
Const(CInt64((Int64.of_int value), IUInt, None))
class branchDistanceVisitor (fut:fundec) = object(this)
inherit nopCilVisitor
method private mkSendDistValuesCall (args:exp list) =
let f = emptyFunction "Austin__SendBranchDistances" in
f.svar.vtype <- TFun(voidType, Some[
("fid", uintType, []);
("sid", uintType, []);
("index", uintType, []);
("values", uintType, [])
], true, []);
addPrototype f;
Call(None, Lval((var f.svar)), args, locUnknown)
method private constructIfFunctionCall (distance:varinfo) (sid:int) (index : int) (e:exp) =
let (prefix, lhs, rhs), t =
match (stripCasts e) with
| UnOp(u, e', t') -> ((getUnOpoFuncName u e'), (typeOf e'))
| BinOp(b, lhs', rhs', t') ->
((getBinOpFuncName b e lhs' rhs'), (typeOf lhs'))
| _ -> (("Austin__EvalNotEqual__", e, zero), (typeOf e))
in
let name,argType = typeToString t in
let distFunc = emptyFunction (prefix^name) in
distFunc.svar.vtype <-
TFun(TFloat(FLongDouble,[]), Some[("lhs", argType, []); ("rhs", argType, [])], false, []);
addPrototype distFunc;
let i1 = Call(Some((var distance)), Lval((var distFunc.svar)), [mkCast lhs argType;mkCast rhs argType], locUnknown) in
let i2 = this#mkSendDistValuesCall
[
(uint fut.svar.vid);
(uint sid);
(uint index);
(uint 1); (* number of values *)
(Lval((var distance)))
] in
[i1;i2]
method private instrumentIfStatement (sid:int) (e:exp) (thn:block) (els:block) =
(* invert expression, because we want to know how far away execution was from avoiding this branch*)
if sid = (-1) then
Log.error (Printf.sprintf "sid = -1 for e=%s\n" (Pretty.sprint 255 (Cil.d_exp()e)));
let distance = makeLocalVar fut
("__AUSTIN__distance__"^(string_of_int fut.svar.vid)^"__"^(string_of_int sid)) (TFloat(FLongDouble,[])) in
let inverseExp = invertExpression e in
addInstrsToBlock thn (this#constructIfFunctionCall distance sid 0 inverseExp);
addInstrsToBlock els (this#constructIfFunctionCall distance sid 1 e)
method private callAustinMin (args:exp list) =
let f = emptyFunction "Austin__Min" in
f.svar.vtype <- TFun(TFloat(FLongDouble,[]), Some["arg1", (TFloat(FLongDouble,[])), [];"arg2", (TFloat(FLongDouble,[])),[]], false, []);
let v = makeTempVar fut (TFloat(FLongDouble,[])) in
addPrototype f;
(v, (Call(Some((var v)), Lval((var f.svar)), args, locUnknown)))
method private instrumentSwitchStatement (currentStmt:stmt) (sid:int) (e:exp) (cases:stmt list) =
if sid = (-1) then
Log.error (Printf.sprintf "sid = -1 for e=%s\n" (Pretty.sprint 255 (Cil.d_exp()e)));
let caseswodef = removeDefaultCase cases in
let name,argType = typeToString (unrollTypeDeep(typeOf e)) in
let distFunc = emptyFunction ("Austin__EvalEquals__"^name) in
distFunc.svar.vtype <- TFun(TFloat(FLongDouble,[]), Some[("lhs", argType, []); ("rhs", argType, [])], false, []);
addPrototype distFunc;
let makeDistanceVar (name : string) =
makeLocalVar fut name (TFloat(FLongDouble,[]))
in
let htCases : (int, (bool * varinfo list)) Hashtbl.t = Hashtbl.create (List.length caseswodef) in
let counter = ref 0 in
let caseDistances =
List.fold_left (
fun ilist s ->
let caseExpressions = getSwitchCaseExpressions s in
assert((List.length caseExpressions) > 0);
let distanceVars = List.map(
fun case ->
let v = makeDistanceVar
("__AUSTIN__distance__"^(string_of_int fut.svar.vid)^"__"^(string_of_int sid)^"__"^(string_of_int (!counter)))
in
incr counter;
v
) caseExpressions
in
Hashtbl.add htCases s.sid (false, distanceVars);
let dcalls =
List.map2(
fun v case ->
Call(Some((var v)), Lval((var distFunc.svar)), [mkCast e argType;mkCast case argType], locUnknown)
)distanceVars caseExpressions
in
(dcalls @ ilist)
) [] caseswodef
in
let computeDefaultDistance = []
(**TODO: default distance should be negation for each case, and then minimum of all the other cases vs default case *)
match(tryGetDefaultCase cases)with
| None - > [ ]
| Some(s ) - >
(
let defVar = makeDistanceVar
( " _ _ AUSTIN__distance__"^(string_of_int fut.svar.vid)^"__"^(string_of_int sid)^"__def " )
in
( * iter through hashtable and find minimum
| None -> []
| Some(s) ->
(
let defVar = makeDistanceVar
("__AUSTIN__distance__"^(string_of_int fut.svar.vid)^"__"^(string_of_int sid)^"__def")
in
(* iter through hashtable and find minimum *)
let arglist = Hashtbl.fold(
fun id (_,vars) elist ->
((List.map(fun v -> Lval((var v)))vars)@elist)
) htCases [] in
Hashtbl.add htCases s.sid (true, [defVar]);
if (List.length arglist) = 1 then (
[Set((var defVar), (List.hd arglist), locUnknown)]
) else (
let rec stackCalls (ilist) (twoarg:exp list) (arglist:exp list) =
match arglist with
| [] -> (ilist, (List.hd twoarg))
| a::rem ->
(
match twoarg with
| [] -> (* add it*)stackCalls ilist [a] rem
| e::r ->
let v, i = this#callAustinMin [e;a] in
stackCalls (i::ilist) [Lval((var v))] rem
)
in
let ilist,finalResult = stackCalls [] [] arglist in
(List.rev (Set((var defVar), finalResult, locUnknown)::ilist))
)
)*)
in
(* insert send distance calls *)
counter := 0;
List.iter(
fun s ->
let args = ref [] in
Hashtbl.iter(
fun id (_,vars) ->
if id <> s.sid then (
args := ((List.map(fun v -> Lval((var v)))vars) @ (!args))
)
)htCases;
let i =
let l1 = [
uint fut.svar.vid;
uint sid;
uint (!counter);
uint (List.length (!args)); ] in
let distargs = (l1 @ (!args)) in
this#mkSendDistValuesCall distargs
in
incr counter;
pushInstrBeforeStmt s [i]
) cases;
pushInstrBeforeStmt currentStmt (caseDistances@computeDefaultDistance)
method vstmt (s:stmt) =
match s.skind with
| If(e, thn, els, loc) ->
let e' = propagateNegation e in
(* use the original condition (e) rather than the one with negations removed (e.g. e') *)
Hashtbl.replace branchInfos s.sid e;
this#instrumentIfStatement s.sid e' thn els;
DoChildren
| Switch(e, _,cases,_) ->
(**START LOGGING**)
let printE =
let rec searchLabels (labelExpr:exp list) (labels : label list) =
match labels with
| [] -> labelExpr
| l::rem ->
(
match l with
| Case(e', _) -> searchLabels (e'::labelExpr) rem
| Default _ -> searchLabels ((mkString "default")::labelExpr) rem
| _ -> searchLabels labelExpr rem
)
in
let res = List.fold_left(
fun e' s' ->
let l = List.fold_left(
fun bexp lexp ->
if (List.length bexp) = 0 then
[lexp]
else (
[BinOp(LOr, (List.hd bexp), lexp, intType)]
)
)[] (List.rev (searchLabels [] s'.labels)) in
if (List.length l) = 0 then
e'
else (
if (List.length e') = 0 then
[BinOp(Eq, e, (List.hd l), intType)]
else (
let b1 = BinOp(Eq, e, (List.hd l), intType) in
[BinOp(LOr, (List.hd e'), b1, intType)]
)
)
) [] cases in
if (List.length res) = 0 then e else (List.hd res)
in
Hashtbl.replace branchInfos s.sid printE;
(**END LOGGING**)
this#instrumentSwitchStatement s s.sid e cases;
DoChildren
| _ -> DoChildren
end
let saveBranchIDInfo () =
let outchan = open_out (ConfigFile.find Options.keyBranchIds) in
Hashtbl.iter(
fun id e ->
let str =
(string_of_int id)^":"^(Pretty.sprint 255 (Cil.d_exp () e))^"\r\n"
in
output_string outchan str
)branchInfos;
close_out outchan
let main (source : file) (fut : fundec) (ignoreList:string list) =
computeControlDependencies source fut;
assert((List.length fut.sallstmts) > 0);
let vis = new branchDistanceVisitor fut in
ignore(visitCilFunction vis fut);
saveControlDependencies (ConfigFile.find Options.keyCfgInfo);
saveBranchIDInfo ();
(!prototypeFundecs,[]) | null | https://raw.githubusercontent.com/kiranlak/austin-sbst/9c8aac72692dca952302e0e4fdb9ff381bba58ae/AustinOcaml/instrumentation/branchtrace.ml | ocaml | typeToString pt
number of values
invert expression, because we want to know how far away execution was from avoiding this branch
*TODO: default distance should be negation for each case, and then minimum of all the other cases vs default case
iter through hashtable and find minimum
add it
insert send distance calls
use the original condition (e) rather than the one with negations removed (e.g. e')
*START LOGGING*
*END LOGGING* | Copyright : , University College London , 2011
open Cil
open Printf
open Cfginfo
open Utils
open TraceManager
module Log = LogManager
let prototypeFundecs = ref []
let branchInfos : (int,exp) Hashtbl.t = Hashtbl.create Options.hashtblInitSize
let reset () =
prototypeFundecs := [];
Hashtbl.clear branchInfos
let addPrototype (f:fundec) =
let namesMatch (f':fundec) = (compare f'.svar.vname f.svar.vname) = 0 in
if not(List.exists namesMatch (!prototypeFundecs)) then
prototypeFundecs := (f::(!prototypeFundecs));
;;
let ikindStrAndCast (kind : ikind) =
match kind with
| IChar -> ("Char", TInt(IChar,[]))
| ISChar -> ("SChar", TInt(ISChar,[]))
| IUChar -> ("UChar", TInt(IUChar,[]))
| IBool -> ("Bool", TInt(IBool,[]))
| IInt -> ("Int", TInt(IInt,[]))
| IUInt -> ("UInt", TInt(IUInt,[]))
| IShort -> ("Short", TInt(IShort,[]))
| IUShort -> ("UShort", TInt(IUShort,[]))
| ILong -> ("Long", TInt(ILong,[]))
| IULong -> ("ULong", TInt(IULong,[]))
| ILongLong -> ("LongLong", TInt(ILongLong,[]))
| IULongLong -> ("ULongLong", TInt(IULongLong,[]))
let fkindStrAndCast (kind : fkind) =
match kind with
| FFloat -> ("Float", TFloat(FFloat,[]))
| FDouble -> ("Double", TFloat(FDouble,[]))
| FLongDouble -> ("LongDouble", TFloat(FLongDouble,[]))
let rec typeToString (t:typ) =
match (unrollType t) with
| TVoid _ -> ("Void", voidPtrType)
| TInt(kind, _) -> ikindStrAndCast kind
| TFloat(kind, _) -> fkindStrAndCast kind
| TNamed(ti, _) -> typeToString ti.ttype
| TEnum(ei,_) -> ikindStrAndCast ei.ekind
| _ -> Log.error (Printf.sprintf "invalid distance type: %s\r\n" (Pretty.sprint 255 (Cil.d_type () t)))
let getBinOpFuncName (b:binop) (orig:exp) (lhs:exp) (rhs:exp) =
match b with
| Lt -> ("Austin__EvalLessThan__", lhs, rhs)
| Gt -> ("Austin__EvalGreaterThan__", lhs, rhs)
| Le -> ("Austin__EvalLessThanEq__", lhs, rhs)
| Ge -> ("Austin__EvalGreaterThanEq__", lhs, rhs)
| Eq -> ("Austin__EvalEquals__", lhs, rhs)
| Ne -> ("Austin__EvalNotEqual__", lhs, rhs)
| _ -> ("Austin__EvalNotEqual__", orig, zero)
let getUnOpoFuncName (u:unop) (orig : exp) =
match u with
| Neg -> ("Austin__EvalNotEqual__", orig, zero)
| BNot -> ("Austin__EvalNotEqual__", orig, zero)
| LNot -> ("Austin__EvalEquals__", orig, zero)
let invertExpression (e:exp) =
let strippedEx, strippedCasts = stripCastsEx e [] in
match strippedEx with
| UnOp(u, e', t) ->
(
match u with
| LNot -> reapplyCasts e' strippedCasts
| _ -> UnOp(LNot, e, t)
)
| BinOp(b, lhs, rhs, t) ->
(
match b with
| Lt -> reapplyCasts (BinOp(Ge, lhs, rhs, t)) strippedCasts
| Gt -> reapplyCasts (BinOp(Le, lhs, rhs, t)) strippedCasts
| Le -> reapplyCasts (BinOp(Gt, lhs, rhs, t)) strippedCasts
| Ge -> reapplyCasts (BinOp(Lt, lhs, rhs, t)) strippedCasts
| Eq -> reapplyCasts (BinOp(Ne, lhs, rhs, t)) strippedCasts
| Ne -> reapplyCasts (BinOp(Eq, lhs, rhs, t)) strippedCasts
| _ -> UnOp(LNot, e, t)
)
| _ -> UnOp(LNot, e, (typeOf e))
let uint (value : int) =
Const(CInt64((Int64.of_int value), IUInt, None))
class branchDistanceVisitor (fut:fundec) = object(this)
inherit nopCilVisitor
method private mkSendDistValuesCall (args:exp list) =
let f = emptyFunction "Austin__SendBranchDistances" in
f.svar.vtype <- TFun(voidType, Some[
("fid", uintType, []);
("sid", uintType, []);
("index", uintType, []);
("values", uintType, [])
], true, []);
addPrototype f;
Call(None, Lval((var f.svar)), args, locUnknown)
method private constructIfFunctionCall (distance:varinfo) (sid:int) (index : int) (e:exp) =
let (prefix, lhs, rhs), t =
match (stripCasts e) with
| UnOp(u, e', t') -> ((getUnOpoFuncName u e'), (typeOf e'))
| BinOp(b, lhs', rhs', t') ->
((getBinOpFuncName b e lhs' rhs'), (typeOf lhs'))
| _ -> (("Austin__EvalNotEqual__", e, zero), (typeOf e))
in
let name,argType = typeToString t in
let distFunc = emptyFunction (prefix^name) in
distFunc.svar.vtype <-
TFun(TFloat(FLongDouble,[]), Some[("lhs", argType, []); ("rhs", argType, [])], false, []);
addPrototype distFunc;
let i1 = Call(Some((var distance)), Lval((var distFunc.svar)), [mkCast lhs argType;mkCast rhs argType], locUnknown) in
let i2 = this#mkSendDistValuesCall
[
(uint fut.svar.vid);
(uint sid);
(uint index);
(Lval((var distance)))
] in
[i1;i2]
method private instrumentIfStatement (sid:int) (e:exp) (thn:block) (els:block) =
if sid = (-1) then
Log.error (Printf.sprintf "sid = -1 for e=%s\n" (Pretty.sprint 255 (Cil.d_exp()e)));
let distance = makeLocalVar fut
("__AUSTIN__distance__"^(string_of_int fut.svar.vid)^"__"^(string_of_int sid)) (TFloat(FLongDouble,[])) in
let inverseExp = invertExpression e in
addInstrsToBlock thn (this#constructIfFunctionCall distance sid 0 inverseExp);
addInstrsToBlock els (this#constructIfFunctionCall distance sid 1 e)
method private callAustinMin (args:exp list) =
let f = emptyFunction "Austin__Min" in
f.svar.vtype <- TFun(TFloat(FLongDouble,[]), Some["arg1", (TFloat(FLongDouble,[])), [];"arg2", (TFloat(FLongDouble,[])),[]], false, []);
let v = makeTempVar fut (TFloat(FLongDouble,[])) in
addPrototype f;
(v, (Call(Some((var v)), Lval((var f.svar)), args, locUnknown)))
method private instrumentSwitchStatement (currentStmt:stmt) (sid:int) (e:exp) (cases:stmt list) =
if sid = (-1) then
Log.error (Printf.sprintf "sid = -1 for e=%s\n" (Pretty.sprint 255 (Cil.d_exp()e)));
let caseswodef = removeDefaultCase cases in
let name,argType = typeToString (unrollTypeDeep(typeOf e)) in
let distFunc = emptyFunction ("Austin__EvalEquals__"^name) in
distFunc.svar.vtype <- TFun(TFloat(FLongDouble,[]), Some[("lhs", argType, []); ("rhs", argType, [])], false, []);
addPrototype distFunc;
let makeDistanceVar (name : string) =
makeLocalVar fut name (TFloat(FLongDouble,[]))
in
let htCases : (int, (bool * varinfo list)) Hashtbl.t = Hashtbl.create (List.length caseswodef) in
let counter = ref 0 in
let caseDistances =
List.fold_left (
fun ilist s ->
let caseExpressions = getSwitchCaseExpressions s in
assert((List.length caseExpressions) > 0);
let distanceVars = List.map(
fun case ->
let v = makeDistanceVar
("__AUSTIN__distance__"^(string_of_int fut.svar.vid)^"__"^(string_of_int sid)^"__"^(string_of_int (!counter)))
in
incr counter;
v
) caseExpressions
in
Hashtbl.add htCases s.sid (false, distanceVars);
let dcalls =
List.map2(
fun v case ->
Call(Some((var v)), Lval((var distFunc.svar)), [mkCast e argType;mkCast case argType], locUnknown)
)distanceVars caseExpressions
in
(dcalls @ ilist)
) [] caseswodef
in
let computeDefaultDistance = []
match(tryGetDefaultCase cases)with
| None - > [ ]
| Some(s ) - >
(
let defVar = makeDistanceVar
( " _ _ AUSTIN__distance__"^(string_of_int fut.svar.vid)^"__"^(string_of_int sid)^"__def " )
in
( * iter through hashtable and find minimum
| None -> []
| Some(s) ->
(
let defVar = makeDistanceVar
("__AUSTIN__distance__"^(string_of_int fut.svar.vid)^"__"^(string_of_int sid)^"__def")
in
let arglist = Hashtbl.fold(
fun id (_,vars) elist ->
((List.map(fun v -> Lval((var v)))vars)@elist)
) htCases [] in
Hashtbl.add htCases s.sid (true, [defVar]);
if (List.length arglist) = 1 then (
[Set((var defVar), (List.hd arglist), locUnknown)]
) else (
let rec stackCalls (ilist) (twoarg:exp list) (arglist:exp list) =
match arglist with
| [] -> (ilist, (List.hd twoarg))
| a::rem ->
(
match twoarg with
| e::r ->
let v, i = this#callAustinMin [e;a] in
stackCalls (i::ilist) [Lval((var v))] rem
)
in
let ilist,finalResult = stackCalls [] [] arglist in
(List.rev (Set((var defVar), finalResult, locUnknown)::ilist))
)
)*)
in
counter := 0;
List.iter(
fun s ->
let args = ref [] in
Hashtbl.iter(
fun id (_,vars) ->
if id <> s.sid then (
args := ((List.map(fun v -> Lval((var v)))vars) @ (!args))
)
)htCases;
let i =
let l1 = [
uint fut.svar.vid;
uint sid;
uint (!counter);
uint (List.length (!args)); ] in
let distargs = (l1 @ (!args)) in
this#mkSendDistValuesCall distargs
in
incr counter;
pushInstrBeforeStmt s [i]
) cases;
pushInstrBeforeStmt currentStmt (caseDistances@computeDefaultDistance)
method vstmt (s:stmt) =
match s.skind with
| If(e, thn, els, loc) ->
let e' = propagateNegation e in
Hashtbl.replace branchInfos s.sid e;
this#instrumentIfStatement s.sid e' thn els;
DoChildren
| Switch(e, _,cases,_) ->
let printE =
let rec searchLabels (labelExpr:exp list) (labels : label list) =
match labels with
| [] -> labelExpr
| l::rem ->
(
match l with
| Case(e', _) -> searchLabels (e'::labelExpr) rem
| Default _ -> searchLabels ((mkString "default")::labelExpr) rem
| _ -> searchLabels labelExpr rem
)
in
let res = List.fold_left(
fun e' s' ->
let l = List.fold_left(
fun bexp lexp ->
if (List.length bexp) = 0 then
[lexp]
else (
[BinOp(LOr, (List.hd bexp), lexp, intType)]
)
)[] (List.rev (searchLabels [] s'.labels)) in
if (List.length l) = 0 then
e'
else (
if (List.length e') = 0 then
[BinOp(Eq, e, (List.hd l), intType)]
else (
let b1 = BinOp(Eq, e, (List.hd l), intType) in
[BinOp(LOr, (List.hd e'), b1, intType)]
)
)
) [] cases in
if (List.length res) = 0 then e else (List.hd res)
in
Hashtbl.replace branchInfos s.sid printE;
this#instrumentSwitchStatement s s.sid e cases;
DoChildren
| _ -> DoChildren
end
let saveBranchIDInfo () =
let outchan = open_out (ConfigFile.find Options.keyBranchIds) in
Hashtbl.iter(
fun id e ->
let str =
(string_of_int id)^":"^(Pretty.sprint 255 (Cil.d_exp () e))^"\r\n"
in
output_string outchan str
)branchInfos;
close_out outchan
let main (source : file) (fut : fundec) (ignoreList:string list) =
computeControlDependencies source fut;
assert((List.length fut.sallstmts) > 0);
let vis = new branchDistanceVisitor fut in
ignore(visitCilFunction vis fut);
saveControlDependencies (ConfigFile.find Options.keyCfgInfo);
saveBranchIDInfo ();
(!prototypeFundecs,[]) |
3fe4e02129596c8a916b75dc21d003633cb8cd427dbb3426f5148f4b7d76216e | s-expressionists/Cleavir | defaults.lisp | (in-package #:cleavir-graph)
(defun depth-first-preorder-thunk (start-node map-successors-fun)
(declare (type node-mapper map-successors-fun))
(lambda (function)
(declare (type (function (t)) function))
(let ((table (make-hash-table :test #'eq)))
(labels ((traverse (node)
(unless (gethash node table)
(setf (gethash node table) t)
(funcall function node)
(funcall map-successors-fun #'traverse node))))
(traverse start-node)))
(values)))
(defun depth-first-reverse-postorder-thunk (start-node map-successors-fun)
(declare (type node-mapper map-successors-fun))
(lambda (function)
(declare (type (function (t)) function))
(let ((table (make-hash-table :test #'eq)))
(labels ((traverse (node)
(unless (gethash node table)
(setf (gethash node table) t)
(funcall map-successors-fun #'traverse node)
(funcall function node))))
(traverse start-node)))
(values)))
Construct a predecessors mapping from a graph that does n't have it built in
;;; by exhaustively iterating through with the successor function, filling a
;;; table of predecessor relationships, to use for future reference.
(defun map-predecessors-thunk (start-node map-successors-fun)
(declare (type node-mapper map-successors-fun))
(let ((pred-table (make-hash-table :test #'eq))
(traversal-table (make-hash-table :test #'eq)))
(labels ((predecessors (node) (gethash node pred-table))
((setf predecessors) (preds node)
(setf (gethash node pred-table) preds))
(traverse (node)
(unless (gethash node traversal-table)
(setf (gethash node traversal-table) t)
(funcall map-successors-fun
(lambda (succ) (push node (predecessors succ)))
node)
(funcall map-successors-fun #'traverse node))))
(traverse start-node))
(lambda (function node)
(mapc function (gethash node pred-table))
(values))))
(defun size-thunk (start-node map-successors-fun)
(declare (type node-mapper map-successors-fun))
(lambda ()
(let ((table (make-hash-table :test #'eq))
(size 0))
(labels ((traverse (node)
(unless (gethash node table)
(setf (gethash node table) t)
(incf size)
(funcall map-successors-fun #'traverse node))))
(traverse start-node))
size)))
| null | https://raw.githubusercontent.com/s-expressionists/Cleavir/e0293780d356a9d563af9abf9317019f608b4e1d/Graph/defaults.lisp | lisp | by exhaustively iterating through with the successor function, filling a
table of predecessor relationships, to use for future reference. | (in-package #:cleavir-graph)
(defun depth-first-preorder-thunk (start-node map-successors-fun)
(declare (type node-mapper map-successors-fun))
(lambda (function)
(declare (type (function (t)) function))
(let ((table (make-hash-table :test #'eq)))
(labels ((traverse (node)
(unless (gethash node table)
(setf (gethash node table) t)
(funcall function node)
(funcall map-successors-fun #'traverse node))))
(traverse start-node)))
(values)))
(defun depth-first-reverse-postorder-thunk (start-node map-successors-fun)
(declare (type node-mapper map-successors-fun))
(lambda (function)
(declare (type (function (t)) function))
(let ((table (make-hash-table :test #'eq)))
(labels ((traverse (node)
(unless (gethash node table)
(setf (gethash node table) t)
(funcall map-successors-fun #'traverse node)
(funcall function node))))
(traverse start-node)))
(values)))
Construct a predecessors mapping from a graph that does n't have it built in
(defun map-predecessors-thunk (start-node map-successors-fun)
(declare (type node-mapper map-successors-fun))
(let ((pred-table (make-hash-table :test #'eq))
(traversal-table (make-hash-table :test #'eq)))
(labels ((predecessors (node) (gethash node pred-table))
((setf predecessors) (preds node)
(setf (gethash node pred-table) preds))
(traverse (node)
(unless (gethash node traversal-table)
(setf (gethash node traversal-table) t)
(funcall map-successors-fun
(lambda (succ) (push node (predecessors succ)))
node)
(funcall map-successors-fun #'traverse node))))
(traverse start-node))
(lambda (function node)
(mapc function (gethash node pred-table))
(values))))
(defun size-thunk (start-node map-successors-fun)
(declare (type node-mapper map-successors-fun))
(lambda ()
(let ((table (make-hash-table :test #'eq))
(size 0))
(labels ((traverse (node)
(unless (gethash node table)
(setf (gethash node table) t)
(incf size)
(funcall map-successors-fun #'traverse node))))
(traverse start-node))
size)))
|
7e30425a09e1f4e35182537b117aca9b82237ece4389320bcfb8a18a764422c8 | lspitzner/brittany | Test88.hs | func x | x = simple expression
| otherwise = 0
| null | https://raw.githubusercontent.com/lspitzner/brittany/a15eed5f3608bf1fa7084fcf008c6ecb79542562/data/Test88.hs | haskell | func x | x = simple expression
| otherwise = 0
| |
dc2ebd3d3fe9e392e989c75037e6f739c3f7f7511111b6ada3ddf423cdc08ec3 | mejgun/haskell-tdlib | StickerSetInfo.hs | {-# LANGUAGE OverloadedStrings #-}
-- |
module TD.Data.StickerSetInfo where
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as T
import qualified TD.Data.ClosedVectorPath as ClosedVectorPath
import qualified TD.Data.Sticker as Sticker
import qualified TD.Data.StickerFormat as StickerFormat
import qualified TD.Data.StickerType as StickerType
import qualified TD.Data.Thumbnail as Thumbnail
import qualified Utils as U
-- |
data StickerSetInfo = -- | Represents short information about a sticker set
StickerSetInfo
| Up to the first 5 stickers from the set , depending on the context . If the application needs more stickers the full sticker set needs to be requested
covers :: Maybe [Sticker.Sticker],
-- | Total number of stickers in the set
size :: Maybe Int,
-- | True for already viewed trending sticker sets
is_viewed :: Maybe Bool,
-- | Type of the stickers in the set
sticker_type :: Maybe StickerType.StickerType,
-- | Format of the stickers in the set
sticker_format :: Maybe StickerFormat.StickerFormat,
-- | True, if the sticker set is official
is_official :: Maybe Bool,
-- | True, if the sticker set has been archived. A sticker set can't be installed and archived simultaneously
is_archived :: Maybe Bool,
-- | True, if the sticker set has been installed by the current user
is_installed :: Maybe Bool,
-- | Sticker set thumbnail's outline represented as a list of closed vector paths; may be empty. The coordinate system origin is in the upper-left corner
thumbnail_outline :: Maybe [ClosedVectorPath.ClosedVectorPath],
| Sticker set thumbnail in WEBP , TGS , or WEBM format with width and height 100 ; may be null
thumbnail :: Maybe Thumbnail.Thumbnail,
-- | Name of the sticker set
name :: Maybe String,
-- | Title of the sticker set
title :: Maybe String,
-- | Identifier of the sticker set
_id :: Maybe Int
}
deriving (Eq)
instance Show StickerSetInfo where
show
StickerSetInfo
{ covers = covers_,
size = size_,
is_viewed = is_viewed_,
sticker_type = sticker_type_,
sticker_format = sticker_format_,
is_official = is_official_,
is_archived = is_archived_,
is_installed = is_installed_,
thumbnail_outline = thumbnail_outline_,
thumbnail = thumbnail_,
name = name_,
title = title_,
_id = _id_
} =
"StickerSetInfo"
++ U.cc
[ U.p "covers" covers_,
U.p "size" size_,
U.p "is_viewed" is_viewed_,
U.p "sticker_type" sticker_type_,
U.p "sticker_format" sticker_format_,
U.p "is_official" is_official_,
U.p "is_archived" is_archived_,
U.p "is_installed" is_installed_,
U.p "thumbnail_outline" thumbnail_outline_,
U.p "thumbnail" thumbnail_,
U.p "name" name_,
U.p "title" title_,
U.p "_id" _id_
]
instance T.FromJSON StickerSetInfo where
parseJSON v@(T.Object obj) = do
t <- obj A..: "@type" :: T.Parser String
case t of
"stickerSetInfo" -> parseStickerSetInfo v
_ -> mempty
where
parseStickerSetInfo :: A.Value -> T.Parser StickerSetInfo
parseStickerSetInfo = A.withObject "StickerSetInfo" $ \o -> do
covers_ <- o A..:? "covers"
size_ <- o A..:? "size"
is_viewed_ <- o A..:? "is_viewed"
sticker_type_ <- o A..:? "sticker_type"
sticker_format_ <- o A..:? "sticker_format"
is_official_ <- o A..:? "is_official"
is_archived_ <- o A..:? "is_archived"
is_installed_ <- o A..:? "is_installed"
thumbnail_outline_ <- o A..:? "thumbnail_outline"
thumbnail_ <- o A..:? "thumbnail"
name_ <- o A..:? "name"
title_ <- o A..:? "title"
_id_ <- U.rm <$> (o A..:? "id" :: T.Parser (Maybe String)) :: T.Parser (Maybe Int)
return $ StickerSetInfo {covers = covers_, size = size_, is_viewed = is_viewed_, sticker_type = sticker_type_, sticker_format = sticker_format_, is_official = is_official_, is_archived = is_archived_, is_installed = is_installed_, thumbnail_outline = thumbnail_outline_, thumbnail = thumbnail_, name = name_, title = title_, _id = _id_}
parseJSON _ = mempty
instance T.ToJSON StickerSetInfo where
toJSON
StickerSetInfo
{ covers = covers_,
size = size_,
is_viewed = is_viewed_,
sticker_type = sticker_type_,
sticker_format = sticker_format_,
is_official = is_official_,
is_archived = is_archived_,
is_installed = is_installed_,
thumbnail_outline = thumbnail_outline_,
thumbnail = thumbnail_,
name = name_,
title = title_,
_id = _id_
} =
A.object
[ "@type" A..= T.String "stickerSetInfo",
"covers" A..= covers_,
"size" A..= size_,
"is_viewed" A..= is_viewed_,
"sticker_type" A..= sticker_type_,
"sticker_format" A..= sticker_format_,
"is_official" A..= is_official_,
"is_archived" A..= is_archived_,
"is_installed" A..= is_installed_,
"thumbnail_outline" A..= thumbnail_outline_,
"thumbnail" A..= thumbnail_,
"name" A..= name_,
"title" A..= title_,
"id" A..= U.toS _id_
]
| null | https://raw.githubusercontent.com/mejgun/haskell-tdlib/dc380d18d49eaadc386a81dc98af2ce00f8797c2/src/TD/Data/StickerSetInfo.hs | haskell | # LANGUAGE OverloadedStrings #
|
|
| Represents short information about a sticker set
| Total number of stickers in the set
| True for already viewed trending sticker sets
| Type of the stickers in the set
| Format of the stickers in the set
| True, if the sticker set is official
| True, if the sticker set has been archived. A sticker set can't be installed and archived simultaneously
| True, if the sticker set has been installed by the current user
| Sticker set thumbnail's outline represented as a list of closed vector paths; may be empty. The coordinate system origin is in the upper-left corner
| Name of the sticker set
| Title of the sticker set
| Identifier of the sticker set |
module TD.Data.StickerSetInfo where
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as T
import qualified TD.Data.ClosedVectorPath as ClosedVectorPath
import qualified TD.Data.Sticker as Sticker
import qualified TD.Data.StickerFormat as StickerFormat
import qualified TD.Data.StickerType as StickerType
import qualified TD.Data.Thumbnail as Thumbnail
import qualified Utils as U
StickerSetInfo
| Up to the first 5 stickers from the set , depending on the context . If the application needs more stickers the full sticker set needs to be requested
covers :: Maybe [Sticker.Sticker],
size :: Maybe Int,
is_viewed :: Maybe Bool,
sticker_type :: Maybe StickerType.StickerType,
sticker_format :: Maybe StickerFormat.StickerFormat,
is_official :: Maybe Bool,
is_archived :: Maybe Bool,
is_installed :: Maybe Bool,
thumbnail_outline :: Maybe [ClosedVectorPath.ClosedVectorPath],
| Sticker set thumbnail in WEBP , TGS , or WEBM format with width and height 100 ; may be null
thumbnail :: Maybe Thumbnail.Thumbnail,
name :: Maybe String,
title :: Maybe String,
_id :: Maybe Int
}
deriving (Eq)
instance Show StickerSetInfo where
show
StickerSetInfo
{ covers = covers_,
size = size_,
is_viewed = is_viewed_,
sticker_type = sticker_type_,
sticker_format = sticker_format_,
is_official = is_official_,
is_archived = is_archived_,
is_installed = is_installed_,
thumbnail_outline = thumbnail_outline_,
thumbnail = thumbnail_,
name = name_,
title = title_,
_id = _id_
} =
"StickerSetInfo"
++ U.cc
[ U.p "covers" covers_,
U.p "size" size_,
U.p "is_viewed" is_viewed_,
U.p "sticker_type" sticker_type_,
U.p "sticker_format" sticker_format_,
U.p "is_official" is_official_,
U.p "is_archived" is_archived_,
U.p "is_installed" is_installed_,
U.p "thumbnail_outline" thumbnail_outline_,
U.p "thumbnail" thumbnail_,
U.p "name" name_,
U.p "title" title_,
U.p "_id" _id_
]
instance T.FromJSON StickerSetInfo where
parseJSON v@(T.Object obj) = do
t <- obj A..: "@type" :: T.Parser String
case t of
"stickerSetInfo" -> parseStickerSetInfo v
_ -> mempty
where
parseStickerSetInfo :: A.Value -> T.Parser StickerSetInfo
parseStickerSetInfo = A.withObject "StickerSetInfo" $ \o -> do
covers_ <- o A..:? "covers"
size_ <- o A..:? "size"
is_viewed_ <- o A..:? "is_viewed"
sticker_type_ <- o A..:? "sticker_type"
sticker_format_ <- o A..:? "sticker_format"
is_official_ <- o A..:? "is_official"
is_archived_ <- o A..:? "is_archived"
is_installed_ <- o A..:? "is_installed"
thumbnail_outline_ <- o A..:? "thumbnail_outline"
thumbnail_ <- o A..:? "thumbnail"
name_ <- o A..:? "name"
title_ <- o A..:? "title"
_id_ <- U.rm <$> (o A..:? "id" :: T.Parser (Maybe String)) :: T.Parser (Maybe Int)
return $ StickerSetInfo {covers = covers_, size = size_, is_viewed = is_viewed_, sticker_type = sticker_type_, sticker_format = sticker_format_, is_official = is_official_, is_archived = is_archived_, is_installed = is_installed_, thumbnail_outline = thumbnail_outline_, thumbnail = thumbnail_, name = name_, title = title_, _id = _id_}
parseJSON _ = mempty
instance T.ToJSON StickerSetInfo where
toJSON
StickerSetInfo
{ covers = covers_,
size = size_,
is_viewed = is_viewed_,
sticker_type = sticker_type_,
sticker_format = sticker_format_,
is_official = is_official_,
is_archived = is_archived_,
is_installed = is_installed_,
thumbnail_outline = thumbnail_outline_,
thumbnail = thumbnail_,
name = name_,
title = title_,
_id = _id_
} =
A.object
[ "@type" A..= T.String "stickerSetInfo",
"covers" A..= covers_,
"size" A..= size_,
"is_viewed" A..= is_viewed_,
"sticker_type" A..= sticker_type_,
"sticker_format" A..= sticker_format_,
"is_official" A..= is_official_,
"is_archived" A..= is_archived_,
"is_installed" A..= is_installed_,
"thumbnail_outline" A..= thumbnail_outline_,
"thumbnail" A..= thumbnail_,
"name" A..= name_,
"title" A..= title_,
"id" A..= U.toS _id_
]
|
39d34064132b452021692f695201ec5e8ccd7f75687998c8aa994d0f91860a20 | bmeurer/ocaml-experimental | odoc_comments.ml | (***********************************************************************)
(* 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 .
(* *)
(***********************************************************************)
$ Id$
(** Analysis of comments. *)
open Odoc_types
let print_DEBUG s = print_string s ; print_newline ();;
(** This variable contains the regular expression representing a blank but not a '\n'.*)
let simple_blank = "[ \013\009\012]"
module type Texter =
sig
(** Return a text structure from a string. *)
val text_of_string : string -> text
end
module Info_retriever =
functor (MyTexter : Texter) ->
struct
let create_see s =
try
let lexbuf = Lexing.from_string s in
let (see_ref, s) = Odoc_parser.see_info Odoc_see_lexer.main lexbuf in
(see_ref, MyTexter.text_of_string s)
with
| Odoc_text.Text_syntax (l, c, s) ->
raise (Failure (Odoc_messages.text_parse_error l c s))
| _ ->
raise (Failure ("Erreur inconnue lors du parse de see : "^s))
let retrieve_info fun_lex file (s : string) =
try
let _ = Odoc_comments_global.init () in
Odoc_lexer.comments_level := 0;
let lexbuf = Lexing.from_string s in
match Odoc_parser.main fun_lex lexbuf with
None ->
(0, None)
| Some (desc, remain_opt) ->
let mem_nb_chars = !Odoc_comments_global.nb_chars in
let _ =
match remain_opt with
None ->
()
| Some s ->
(*DEBUG*)print_string ("remain: "^s); print_newline();
let lexbuf2 = Lexing.from_string s in
Odoc_parser.info_part2 Odoc_lexer.elements lexbuf2
in
(mem_nb_chars,
Some
{
i_desc = (match desc with "" -> None | _ -> Some (MyTexter.text_of_string desc));
i_authors = !Odoc_comments_global.authors;
i_version = !Odoc_comments_global.version;
i_sees = (List.map create_see !Odoc_comments_global.sees) ;
i_since = !Odoc_comments_global.since;
i_before = Odoc_merge.merge_before_tags
(List.map (fun (n, s) ->
(n, MyTexter.text_of_string s)) !Odoc_comments_global.before)
;
i_deprecated =
(match !Odoc_comments_global.deprecated with
None -> None | Some s -> Some (MyTexter.text_of_string s));
i_params =
(List.map (fun (n, s) ->
(n, MyTexter.text_of_string s)) !Odoc_comments_global.params);
i_raised_exceptions =
(List.map (fun (n, s) ->
(n, MyTexter.text_of_string s)) !Odoc_comments_global.raised_exceptions);
i_return_value =
(match !Odoc_comments_global.return_value with
None -> None | Some s -> Some (MyTexter.text_of_string s)) ;
i_custom = (List.map
(fun (tag, s) -> (tag, MyTexter.text_of_string s))
!Odoc_comments_global.customs)
}
)
with
Failure s ->
incr Odoc_global.errors ;
prerr_endline (file^" : "^s^"\n");
(0, None)
| Odoc_text.Text_syntax (l, c, s) ->
incr Odoc_global.errors ;
prerr_endline (file^" : "^(Odoc_messages.text_parse_error l c s));
(0, None)
| _ ->
incr Odoc_global.errors ;
prerr_endline (file^" : "^Odoc_messages.parse_error^"\n");
(0, None)
* This function takes a string where a simple comment may has been found . It returns
false if there is a blank line or the first comment is a special one , or if there is
no comment if the string .
false if there is a blank line or the first comment is a special one, or if there is
no comment if the string.*)
let nothing_before_simple_comment s =
get the position of the first " ( * "
try
print_DEBUG ("comment_is_attached: "^s);
let pos = Str.search_forward (Str.regexp "(\\*") s 0 in
let next_char = if (String.length s) >= (pos + 1) then s.[pos + 2] else '_' in
(next_char <> '*') &&
(
(* there is no special comment between the constructor and the coment we got *)
let s2 = String.sub s 0 pos in
print_DEBUG ("s2="^s2);
try
let _ = Str.search_forward (Str.regexp ("['\n']"^simple_blank^"*['\n']")) s2 0 in
(* a blank line was before the comment *)
false
with
Not_found ->
true
)
with
Not_found ->
false
(** Return true if the given string contains a blank line. *)
let blank_line s =
try
let _ = Str.search_forward (Str.regexp ("['\n']"^simple_blank^"*['\n']")) s 0 in
(* a blank line was before the comment *)
true
with
Not_found ->
false
let retrieve_info_special file (s : string) =
retrieve_info Odoc_lexer.main file s
let retrieve_info_simple file (s : string) =
let _ = Odoc_comments_global.init () in
Odoc_lexer.comments_level := 0;
let lexbuf = Lexing.from_string s in
match Odoc_parser.main Odoc_lexer.simple lexbuf with
None ->
(0, None)
| Some (desc, remain_opt) ->
(!Odoc_comments_global.nb_chars, Some Odoc_types.dummy_info)
(** Return true if the given string contains a blank line outside a simple comment. *)
let blank_line_outside_simple file s =
let rec iter s2 =
match retrieve_info_simple file s2 with
(_, None) ->
blank_line s2
| (len, Some _) ->
try
let pos = Str.search_forward (Str.regexp_string "(*") s2 0 in
let s_before = String.sub s2 0 pos in
let s_after = String.sub s2 len ((String.length s2) - len) in
(blank_line s_before) || (iter s_after)
with
Not_found ->
(* we shouldn't get here *)
false
in
iter s
* This function returns the first simple comment in
the given string . If strict is [ true ] then no
comment is returned if a blank line or a special
comment is found before the simple comment .
the given string. If strict is [true] then no
comment is returned if a blank line or a special
comment is found before the simple comment. *)
let retrieve_first_info_simple ?(strict=true) file (s : string) =
match retrieve_info_simple file s with
(_, None) ->
(0, None)
| (len, Some d) ->
(* we check if the comment we got was really attached to the constructor,
i.e. that there was no blank line or any special comment "(**" before *)
if (not strict) or (nothing_before_simple_comment s) then
(* ok, we attach the comment to the constructor *)
(len, Some d)
else
(* a blank line or special comment was before the comment,
so we must not attach this comment to the constructor. *)
(0, None)
let retrieve_last_info_simple file (s : string) =
print_DEBUG ("retrieve_last_info_simple:"^s);
let rec f cur_len cur_d =
try
let s2 = String.sub s cur_len ((String.length s) - cur_len) in
print_DEBUG ("retrieve_last_info_simple.f:"^s2);
match retrieve_info_simple file s2 with
(len, None) ->
print_DEBUG "retrieve_last_info_simple: None";
(cur_len + len, cur_d)
| (len, Some d) ->
print_DEBUG "retrieve_last_info_simple: Some";
f (len + cur_len) (Some d)
with
_ ->
print_DEBUG "retrieve_last_info_simple : Erreur String.sub";
(cur_len, cur_d)
in
f 0 None
let retrieve_last_special_no_blank_after file (s : string) =
print_DEBUG ("retrieve_last_special_no_blank_after:"^s);
let rec f cur_len cur_d =
try
let s2 = String.sub s cur_len ((String.length s) - cur_len) in
print_DEBUG ("retrieve_last_special_no_blank_after.f:"^s2);
match retrieve_info_special file s2 with
(len, None) ->
print_DEBUG "retrieve_last_special_no_blank_after: None";
(cur_len + len, cur_d)
| (len, Some d) ->
print_DEBUG "retrieve_last_special_no_blank_after: Some";
f (len + cur_len) (Some d)
with
_ ->
print_DEBUG "retrieve_last_special_no_blank_after : Erreur String.sub";
(cur_len, cur_d)
in
f 0 None
let all_special file s =
print_DEBUG ("all_special: "^s);
let rec iter acc n s2 =
match retrieve_info_special file s2 with
(_, None) ->
(n, acc)
| (n2, Some i) ->
print_DEBUG ("all_special: avant String.sub new_s="^s2);
print_DEBUG ("n2="^(string_of_int n2)) ;
print_DEBUG ("len(s2)="^(string_of_int (String.length s2))) ;
let new_s = String.sub s2 n2 ((String.length s2) - n2) in
print_DEBUG ("all_special: apres String.sub new_s="^new_s);
iter (acc @ [i]) (n + n2) new_s
in
let res = iter [] 0 s in
print_DEBUG ("all_special: end");
res
let just_after_special file s =
print_DEBUG ("just_after_special: "^s);
let res = match retrieve_info_special file s with
(_, None) ->
(0, None)
| (len, Some d) ->
(* we must not have a simple comment or a blank line before. *)
match retrieve_info_simple file (String.sub s 0 len) with
(_, None) ->
(
try
(* if the special comment is the stop comment (**/**),
then we must not associate it. *)
let pos = Str.search_forward (Str.regexp_string "(**") s 0 in
if blank_line (String.sub s 0 pos) or
d.Odoc_types.i_desc = Some [Odoc_types.Raw "/*"]
then
(0, None)
else
(len, Some d)
with
Not_found ->
(* should not occur *)
(0, None)
)
| (len2, Some d2) ->
(0, None)
in
print_DEBUG ("just_after_special:end");
res
let first_special file s =
retrieve_info_special file s
let get_comments f_create_ele file s =
let (assoc_com, ele_coms) =
(* get the comments *)
let (len, special_coms) = all_special file s in
(* if there is no blank line after the special comments, and
if the last special comment is not the stop special comment, then the
last special comments must be associated to the element. *)
match List.rev special_coms with
[] ->
(None, [])
| h :: q ->
if (blank_line_outside_simple file
(String.sub s len ((String.length s) - len)) )
or h.Odoc_types.i_desc = Some [Odoc_types.Raw "/*"]
then
(None, special_coms)
else
(Some h, List.rev q)
in
let ele_comments =
List.fold_left
(fun acc -> fun sc ->
match sc.Odoc_types.i_desc with
None ->
acc
| Some t ->
acc @ [f_create_ele t])
[]
ele_coms
in
(assoc_com, ele_comments)
end
module Basic_info_retriever = Info_retriever (Odoc_text.Texter)
let info_of_string s =
let dummy =
{
i_desc = None ;
i_authors = [] ;
i_version = None ;
i_sees = [] ;
i_since = None ;
i_before = [] ;
i_deprecated = None ;
i_params = [] ;
i_raised_exceptions = [] ;
i_return_value = None ;
i_custom = [] ;
}
in
let s2 = Printf.sprintf "(** %s *)" s in
let (_, i_opt) = Basic_info_retriever.first_special "-" s2 in
match i_opt with
None -> dummy
| Some i -> i
let info_of_comment_file modlist f =
try
let s = Odoc_misc.input_file_as_string f in
let i = info_of_string s in
Odoc_cross.assoc_comments_info "" modlist i
with
Sys_error s ->
failwith s
| null | https://raw.githubusercontent.com/bmeurer/ocaml-experimental/fe5c10cdb0499e43af4b08f35a3248e5c1a8b541/ocamldoc/odoc_comments.ml | ocaml | *********************************************************************
OCamldoc
*********************************************************************
* Analysis of comments.
* This variable contains the regular expression representing a blank but not a '\n'.
* Return a text structure from a string.
DEBUG
there is no special comment between the constructor and the coment we got
a blank line was before the comment
* Return true if the given string contains a blank line.
a blank line was before the comment
* Return true if the given string contains a blank line outside a simple comment.
we shouldn't get here
we check if the comment we got was really attached to the constructor,
i.e. that there was no blank line or any special comment "(**" before
ok, we attach the comment to the constructor
a blank line or special comment was before the comment,
so we must not attach this comment to the constructor.
we must not have a simple comment or a blank line before.
if the special comment is the stop comment (**/*
should not occur
get the comments
if there is no blank line after the special comments, and
if the last special comment is not the stop special comment, then the
last special comments must be associated to the element. | , 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 .
$ Id$
open Odoc_types
let print_DEBUG s = print_string s ; print_newline ();;
let simple_blank = "[ \013\009\012]"
module type Texter =
sig
val text_of_string : string -> text
end
module Info_retriever =
functor (MyTexter : Texter) ->
struct
let create_see s =
try
let lexbuf = Lexing.from_string s in
let (see_ref, s) = Odoc_parser.see_info Odoc_see_lexer.main lexbuf in
(see_ref, MyTexter.text_of_string s)
with
| Odoc_text.Text_syntax (l, c, s) ->
raise (Failure (Odoc_messages.text_parse_error l c s))
| _ ->
raise (Failure ("Erreur inconnue lors du parse de see : "^s))
let retrieve_info fun_lex file (s : string) =
try
let _ = Odoc_comments_global.init () in
Odoc_lexer.comments_level := 0;
let lexbuf = Lexing.from_string s in
match Odoc_parser.main fun_lex lexbuf with
None ->
(0, None)
| Some (desc, remain_opt) ->
let mem_nb_chars = !Odoc_comments_global.nb_chars in
let _ =
match remain_opt with
None ->
()
| Some s ->
let lexbuf2 = Lexing.from_string s in
Odoc_parser.info_part2 Odoc_lexer.elements lexbuf2
in
(mem_nb_chars,
Some
{
i_desc = (match desc with "" -> None | _ -> Some (MyTexter.text_of_string desc));
i_authors = !Odoc_comments_global.authors;
i_version = !Odoc_comments_global.version;
i_sees = (List.map create_see !Odoc_comments_global.sees) ;
i_since = !Odoc_comments_global.since;
i_before = Odoc_merge.merge_before_tags
(List.map (fun (n, s) ->
(n, MyTexter.text_of_string s)) !Odoc_comments_global.before)
;
i_deprecated =
(match !Odoc_comments_global.deprecated with
None -> None | Some s -> Some (MyTexter.text_of_string s));
i_params =
(List.map (fun (n, s) ->
(n, MyTexter.text_of_string s)) !Odoc_comments_global.params);
i_raised_exceptions =
(List.map (fun (n, s) ->
(n, MyTexter.text_of_string s)) !Odoc_comments_global.raised_exceptions);
i_return_value =
(match !Odoc_comments_global.return_value with
None -> None | Some s -> Some (MyTexter.text_of_string s)) ;
i_custom = (List.map
(fun (tag, s) -> (tag, MyTexter.text_of_string s))
!Odoc_comments_global.customs)
}
)
with
Failure s ->
incr Odoc_global.errors ;
prerr_endline (file^" : "^s^"\n");
(0, None)
| Odoc_text.Text_syntax (l, c, s) ->
incr Odoc_global.errors ;
prerr_endline (file^" : "^(Odoc_messages.text_parse_error l c s));
(0, None)
| _ ->
incr Odoc_global.errors ;
prerr_endline (file^" : "^Odoc_messages.parse_error^"\n");
(0, None)
* This function takes a string where a simple comment may has been found . It returns
false if there is a blank line or the first comment is a special one , or if there is
no comment if the string .
false if there is a blank line or the first comment is a special one, or if there is
no comment if the string.*)
let nothing_before_simple_comment s =
get the position of the first " ( * "
try
print_DEBUG ("comment_is_attached: "^s);
let pos = Str.search_forward (Str.regexp "(\\*") s 0 in
let next_char = if (String.length s) >= (pos + 1) then s.[pos + 2] else '_' in
(next_char <> '*') &&
(
let s2 = String.sub s 0 pos in
print_DEBUG ("s2="^s2);
try
let _ = Str.search_forward (Str.regexp ("['\n']"^simple_blank^"*['\n']")) s2 0 in
false
with
Not_found ->
true
)
with
Not_found ->
false
let blank_line s =
try
let _ = Str.search_forward (Str.regexp ("['\n']"^simple_blank^"*['\n']")) s 0 in
true
with
Not_found ->
false
let retrieve_info_special file (s : string) =
retrieve_info Odoc_lexer.main file s
let retrieve_info_simple file (s : string) =
let _ = Odoc_comments_global.init () in
Odoc_lexer.comments_level := 0;
let lexbuf = Lexing.from_string s in
match Odoc_parser.main Odoc_lexer.simple lexbuf with
None ->
(0, None)
| Some (desc, remain_opt) ->
(!Odoc_comments_global.nb_chars, Some Odoc_types.dummy_info)
let blank_line_outside_simple file s =
let rec iter s2 =
match retrieve_info_simple file s2 with
(_, None) ->
blank_line s2
| (len, Some _) ->
try
let pos = Str.search_forward (Str.regexp_string "(*") s2 0 in
let s_before = String.sub s2 0 pos in
let s_after = String.sub s2 len ((String.length s2) - len) in
(blank_line s_before) || (iter s_after)
with
Not_found ->
false
in
iter s
* This function returns the first simple comment in
the given string . If strict is [ true ] then no
comment is returned if a blank line or a special
comment is found before the simple comment .
the given string. If strict is [true] then no
comment is returned if a blank line or a special
comment is found before the simple comment. *)
let retrieve_first_info_simple ?(strict=true) file (s : string) =
match retrieve_info_simple file s with
(_, None) ->
(0, None)
| (len, Some d) ->
if (not strict) or (nothing_before_simple_comment s) then
(len, Some d)
else
(0, None)
let retrieve_last_info_simple file (s : string) =
print_DEBUG ("retrieve_last_info_simple:"^s);
let rec f cur_len cur_d =
try
let s2 = String.sub s cur_len ((String.length s) - cur_len) in
print_DEBUG ("retrieve_last_info_simple.f:"^s2);
match retrieve_info_simple file s2 with
(len, None) ->
print_DEBUG "retrieve_last_info_simple: None";
(cur_len + len, cur_d)
| (len, Some d) ->
print_DEBUG "retrieve_last_info_simple: Some";
f (len + cur_len) (Some d)
with
_ ->
print_DEBUG "retrieve_last_info_simple : Erreur String.sub";
(cur_len, cur_d)
in
f 0 None
let retrieve_last_special_no_blank_after file (s : string) =
print_DEBUG ("retrieve_last_special_no_blank_after:"^s);
let rec f cur_len cur_d =
try
let s2 = String.sub s cur_len ((String.length s) - cur_len) in
print_DEBUG ("retrieve_last_special_no_blank_after.f:"^s2);
match retrieve_info_special file s2 with
(len, None) ->
print_DEBUG "retrieve_last_special_no_blank_after: None";
(cur_len + len, cur_d)
| (len, Some d) ->
print_DEBUG "retrieve_last_special_no_blank_after: Some";
f (len + cur_len) (Some d)
with
_ ->
print_DEBUG "retrieve_last_special_no_blank_after : Erreur String.sub";
(cur_len, cur_d)
in
f 0 None
let all_special file s =
print_DEBUG ("all_special: "^s);
let rec iter acc n s2 =
match retrieve_info_special file s2 with
(_, None) ->
(n, acc)
| (n2, Some i) ->
print_DEBUG ("all_special: avant String.sub new_s="^s2);
print_DEBUG ("n2="^(string_of_int n2)) ;
print_DEBUG ("len(s2)="^(string_of_int (String.length s2))) ;
let new_s = String.sub s2 n2 ((String.length s2) - n2) in
print_DEBUG ("all_special: apres String.sub new_s="^new_s);
iter (acc @ [i]) (n + n2) new_s
in
let res = iter [] 0 s in
print_DEBUG ("all_special: end");
res
let just_after_special file s =
print_DEBUG ("just_after_special: "^s);
let res = match retrieve_info_special file s with
(_, None) ->
(0, None)
| (len, Some d) ->
match retrieve_info_simple file (String.sub s 0 len) with
(_, None) ->
(
try
then we must not associate it. *)
let pos = Str.search_forward (Str.regexp_string "(**") s 0 in
if blank_line (String.sub s 0 pos) or
d.Odoc_types.i_desc = Some [Odoc_types.Raw "/*"]
then
(0, None)
else
(len, Some d)
with
Not_found ->
(0, None)
)
| (len2, Some d2) ->
(0, None)
in
print_DEBUG ("just_after_special:end");
res
let first_special file s =
retrieve_info_special file s
let get_comments f_create_ele file s =
let (assoc_com, ele_coms) =
let (len, special_coms) = all_special file s in
match List.rev special_coms with
[] ->
(None, [])
| h :: q ->
if (blank_line_outside_simple file
(String.sub s len ((String.length s) - len)) )
or h.Odoc_types.i_desc = Some [Odoc_types.Raw "/*"]
then
(None, special_coms)
else
(Some h, List.rev q)
in
let ele_comments =
List.fold_left
(fun acc -> fun sc ->
match sc.Odoc_types.i_desc with
None ->
acc
| Some t ->
acc @ [f_create_ele t])
[]
ele_coms
in
(assoc_com, ele_comments)
end
module Basic_info_retriever = Info_retriever (Odoc_text.Texter)
let info_of_string s =
let dummy =
{
i_desc = None ;
i_authors = [] ;
i_version = None ;
i_sees = [] ;
i_since = None ;
i_before = [] ;
i_deprecated = None ;
i_params = [] ;
i_raised_exceptions = [] ;
i_return_value = None ;
i_custom = [] ;
}
in
let s2 = Printf.sprintf "(** %s *)" s in
let (_, i_opt) = Basic_info_retriever.first_special "-" s2 in
match i_opt with
None -> dummy
| Some i -> i
let info_of_comment_file modlist f =
try
let s = Odoc_misc.input_file_as_string f in
let i = info_of_string s in
Odoc_cross.assoc_comments_info "" modlist i
with
Sys_error s ->
failwith s
|
e7ff05a6679216c3d2523c9d2da90c17a88fffcaaf3acfb0e08cd22dfa9d8088 | GaloisInc/ivory | Overflow.hs | # LANGUAGE DataKinds #
# LANGUAGE TypeOperators #
module Overflow where
import Ivory.Language
import Ivory.Compile.C.CmdlineFrontend
ovf1 :: Def ('[Sint8] ':-> Sint8)
ovf1 = proc "ovf1" $ \ n -> body $
ifte_ (n <? maxBound - 20)
(ret (n + 15))
(ret (n .% 2))
ovf2 :: Def ('[Sint8] ':-> Sint8)
ovf2 = proc "ovf2" $ \ n -> requires (n <? 1)
$ body
$ ret (n + 15)
ovf3 :: Def ('[IFloat, IFloat, IBool] ':-> IFloat)
ovf3 = proc "ovf3" $ \ n m o -> body $ do
-- x <- assign (n / m / o)
ret $ (o ? (n / m, m / n))
cmodule :: Module
cmodule = package "Overflow" $ --incl ovf1 >> incl ovf2 >>
incl ovf3
writeOverflow :: Opts -> IO ()
writeOverflow opts = runCompiler [cmodule] []
opts { constFold = False, overflow = False, divZero = True, outDir = Nothing }
| null | https://raw.githubusercontent.com/GaloisInc/ivory/53a0795b4fbeb0b7da0f6cdaccdde18849a78cd6/ivory-examples/examples/Overflow.hs | haskell | x <- assign (n / m / o)
incl ovf1 >> incl ovf2 >> | # LANGUAGE DataKinds #
# LANGUAGE TypeOperators #
module Overflow where
import Ivory.Language
import Ivory.Compile.C.CmdlineFrontend
ovf1 :: Def ('[Sint8] ':-> Sint8)
ovf1 = proc "ovf1" $ \ n -> body $
ifte_ (n <? maxBound - 20)
(ret (n + 15))
(ret (n .% 2))
ovf2 :: Def ('[Sint8] ':-> Sint8)
ovf2 = proc "ovf2" $ \ n -> requires (n <? 1)
$ body
$ ret (n + 15)
ovf3 :: Def ('[IFloat, IFloat, IBool] ':-> IFloat)
ovf3 = proc "ovf3" $ \ n m o -> body $ do
ret $ (o ? (n / m, m / n))
cmodule :: Module
incl ovf3
writeOverflow :: Opts -> IO ()
writeOverflow opts = runCompiler [cmodule] []
opts { constFold = False, overflow = False, divZero = True, outDir = Nothing }
|
2b291600e0e94131841af0a9c6b3c46aacdb46b305dfbcfd5fe2ed10349b9f2a | den1k/vimsical | style.clj | (ns vimsical.frontend.vcr.style
(:require [vimsical.frontend.timeline.style :refer [timeline]]
[vimsical.frontend.code-editor.style :refer [code-editor]]
[vimsical.frontend.vcr.libs.style :refer [libs]]
[vimsical.frontend.styles.color :as color :refer [colors]]
[vimsical.frontend.styles.media :as media]))
(def play-pause
[:&.play-pause
[:.icon
[:&.play {:height :23px
:width :23px}]
[:&.pause {:height :21px
:width :21px}]]])
(def speed-control
[:&.speed
{:display :flex
:justify-content :space-between
:align-items :center}
[:.speed-triangle
{:width :11px
:height :11px}]])
(def playback
[:.playback {:display :flex
:flex-direction :row
:justify-content :center
:align-items :center
:padding "13px 24px"}
[:.control {:margin "10px"
:display :flex
:justify-content :center
:align-items :center
:height :24px
:width :85px
:color (:grey colors)}
play-pause
speed-control
[:.icon {:fill (:grey colors)
:stroke (:grey colors)
:cursor :pointer}
[:&:hover
[:* {:fill :black
:stroke :black}]]]]
timeline])
(def editor-tab
[:.editor-tab
{:width :24px
:height :24px
:box-sizing :border-box
:padding :5px
:margin-top :6.4px
:margin-bottom :6.4px
:border-radius :2.3px
:background :white
:cursor :pointer
:box-shadow "inset 0 2px 3px 0 rgba(171,165,165,0.5)"}
[:.tab-checkbox
{:width :14px
:height :14px
:border-radius :1.6px
:background :#f0805f
:box-shadow "0 2px 3px 0 rgba(107,94,94,0.5)"}]
(mapv #(color/type-style (first %)
:.tab-checkbox.
:background
(second %))
color/type->colors-editors)
[:&.disabled
{:background-color "rgba(219, 216, 217, 0.9)"}
[:.tab-checkbox {:background :white}]]])
(def editor-tabs
[:.editor-tabs {:width :24px
:display :flex
:flex-direction :column
:justify-content :center}
editor-tab])
(def editor-header
[:.editor-header
{:display :flex
:flex-shrink 0
:flex-direction :row
:align-items :center
;; height set on component due requirement of precise height by
;; split component
: padding " 6px 16px "
:text-align :center
:background :#ffffff
:border-bottom "solid 2px #eceff3"}
[:.title {:flex-grow :1
:font-size :20.7px
:letter-spacing :0}]
(mapv #(color/type-child-style (first %)
:&.
:.title
:color
(second %))
color/type->colors-editors)])
(def live-preview-and-editors
[:.live-preview-and-editors
{:border-top "solid 2px #eceff3"}
[:.rc-n-v-split
[:.split-panel
[:&:first-child
{:z-index :inherit
:border :none
:box-shadow :none}]
{:z-index :1
:border-top "solid 2px #eceff3"
:box-shadow "0 -4px 6px 0 rgba(143, 144, 150, 0.2)"}]]
[:.rc-n-h-split-splitter
{:display :flex
:flex "1"
:flex-direction :column
:justify-content :space-around
:align-items :center
:box-sizing :border-box
:padding :4px
;; width set on component due requirement of precise height by
;; split component
:background :white
:border-left "solid 2px #eceff3"
:border-right "solid 2px #eceff3"
:cursor :col-resize}
editor-tabs]
editor-header
code-editor])
(def vcr-footer
[:.vcr-footer
{:white-space :nowrap
:padding "2px 10px"
:font-size :12px
:letter-spacing :0.3px
:background (:mediumgrey colors)}
[:.section
{:width :150px}]
[:.options
[:.option
{:cursor :pointer}]]
[:.sync-status-wrapper
[:.sync-status
[:.status-circle
{:width :6px
:height :6px
:background :orange
:border-radius :50%
:flex-shrink 0}]
[:&.saved
[:.status-circle
{:background :limegreen}]]]]
[:.author-credit
{:letter-spacing :0.5px
:font-weight 500}]])
(def vcr
(media/not-on-mobile
[:.route-vims
{:min-width :700px
:user-select :none}]
[:.vcr
;; Styles to prevent code-editor from overflowing beyond VCR's boundaries
;; Set here instead of on code-editor to allow widget overflow
{:position :relative
:overflow "hidden"}
playback
live-preview-and-editors
vcr-footer]))
| null | https://raw.githubusercontent.com/den1k/vimsical/1e4a1f1297849b1121baf24bdb7a0c6ba3558954/src/frontend/vimsical/frontend/vcr/style.clj | clojure | height set on component due requirement of precise height by
split component
width set on component due requirement of precise height by
split component
Styles to prevent code-editor from overflowing beyond VCR's boundaries
Set here instead of on code-editor to allow widget overflow | (ns vimsical.frontend.vcr.style
(:require [vimsical.frontend.timeline.style :refer [timeline]]
[vimsical.frontend.code-editor.style :refer [code-editor]]
[vimsical.frontend.vcr.libs.style :refer [libs]]
[vimsical.frontend.styles.color :as color :refer [colors]]
[vimsical.frontend.styles.media :as media]))
(def play-pause
[:&.play-pause
[:.icon
[:&.play {:height :23px
:width :23px}]
[:&.pause {:height :21px
:width :21px}]]])
(def speed-control
[:&.speed
{:display :flex
:justify-content :space-between
:align-items :center}
[:.speed-triangle
{:width :11px
:height :11px}]])
(def playback
[:.playback {:display :flex
:flex-direction :row
:justify-content :center
:align-items :center
:padding "13px 24px"}
[:.control {:margin "10px"
:display :flex
:justify-content :center
:align-items :center
:height :24px
:width :85px
:color (:grey colors)}
play-pause
speed-control
[:.icon {:fill (:grey colors)
:stroke (:grey colors)
:cursor :pointer}
[:&:hover
[:* {:fill :black
:stroke :black}]]]]
timeline])
(def editor-tab
[:.editor-tab
{:width :24px
:height :24px
:box-sizing :border-box
:padding :5px
:margin-top :6.4px
:margin-bottom :6.4px
:border-radius :2.3px
:background :white
:cursor :pointer
:box-shadow "inset 0 2px 3px 0 rgba(171,165,165,0.5)"}
[:.tab-checkbox
{:width :14px
:height :14px
:border-radius :1.6px
:background :#f0805f
:box-shadow "0 2px 3px 0 rgba(107,94,94,0.5)"}]
(mapv #(color/type-style (first %)
:.tab-checkbox.
:background
(second %))
color/type->colors-editors)
[:&.disabled
{:background-color "rgba(219, 216, 217, 0.9)"}
[:.tab-checkbox {:background :white}]]])
(def editor-tabs
[:.editor-tabs {:width :24px
:display :flex
:flex-direction :column
:justify-content :center}
editor-tab])
(def editor-header
[:.editor-header
{:display :flex
:flex-shrink 0
:flex-direction :row
:align-items :center
: padding " 6px 16px "
:text-align :center
:background :#ffffff
:border-bottom "solid 2px #eceff3"}
[:.title {:flex-grow :1
:font-size :20.7px
:letter-spacing :0}]
(mapv #(color/type-child-style (first %)
:&.
:.title
:color
(second %))
color/type->colors-editors)])
(def live-preview-and-editors
[:.live-preview-and-editors
{:border-top "solid 2px #eceff3"}
[:.rc-n-v-split
[:.split-panel
[:&:first-child
{:z-index :inherit
:border :none
:box-shadow :none}]
{:z-index :1
:border-top "solid 2px #eceff3"
:box-shadow "0 -4px 6px 0 rgba(143, 144, 150, 0.2)"}]]
[:.rc-n-h-split-splitter
{:display :flex
:flex "1"
:flex-direction :column
:justify-content :space-around
:align-items :center
:box-sizing :border-box
:padding :4px
:background :white
:border-left "solid 2px #eceff3"
:border-right "solid 2px #eceff3"
:cursor :col-resize}
editor-tabs]
editor-header
code-editor])
(def vcr-footer
[:.vcr-footer
{:white-space :nowrap
:padding "2px 10px"
:font-size :12px
:letter-spacing :0.3px
:background (:mediumgrey colors)}
[:.section
{:width :150px}]
[:.options
[:.option
{:cursor :pointer}]]
[:.sync-status-wrapper
[:.sync-status
[:.status-circle
{:width :6px
:height :6px
:background :orange
:border-radius :50%
:flex-shrink 0}]
[:&.saved
[:.status-circle
{:background :limegreen}]]]]
[:.author-credit
{:letter-spacing :0.5px
:font-weight 500}]])
(def vcr
(media/not-on-mobile
[:.route-vims
{:min-width :700px
:user-select :none}]
[:.vcr
{:position :relative
:overflow "hidden"}
playback
live-preview-and-editors
vcr-footer]))
|
650422dd01ba24148468f01bac6f587d92670fca3efdc86b805fb7658157f5e0 | rd--/hsc3 | Types.hs | | Composite module of all Ugen related types .
module Sound.Sc3.Ugen.Types (module M) where
import Sound.Sc3.Ugen.Brackets as M
import Sound.Sc3.Ugen.Control as M
import Sound.Sc3.Ugen.Constant as M
import Sound.Sc3.Ugen.Label as M
import Sound.Sc3.Ugen.Mrg as M
import Sound.Sc3.Ugen.Primitive as M
import Sound.Sc3.Ugen.Proxy as M
import Sound.Sc3.Ugen.Ugen as M
| null | https://raw.githubusercontent.com/rd--/hsc3/65b0ae5422dfd9c6458c5a97dfb416ab80bd7a72/Sound/Sc3/Ugen/Types.hs | haskell | | Composite module of all Ugen related types .
module Sound.Sc3.Ugen.Types (module M) where
import Sound.Sc3.Ugen.Brackets as M
import Sound.Sc3.Ugen.Control as M
import Sound.Sc3.Ugen.Constant as M
import Sound.Sc3.Ugen.Label as M
import Sound.Sc3.Ugen.Mrg as M
import Sound.Sc3.Ugen.Primitive as M
import Sound.Sc3.Ugen.Proxy as M
import Sound.Sc3.Ugen.Ugen as M
| |
046b73069113914c3a6a16518949dba8c752b53f6919a809b509cccf2da77035 | ocamllabs/ocaml-modular-implicits | t250-closurerec-1.ml | open Lib;;
let rec f _ = 0;;
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7
9 BRANCH 14
11 CONST0
12 RETURN 1
14 CLOSUREREC 0 , 11
18 ACC0
19 MAKEBLOCK1 0
21 POP 1
23 SETGLOBAL T250 - closurerec-1
25 STOP
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7 SETGLOBAL Lib
9 BRANCH 14
11 CONST0
12 RETURN 1
14 CLOSUREREC 0, 11
18 ACC0
19 MAKEBLOCK1 0
21 POP 1
23 SETGLOBAL T250-closurerec-1
25 STOP
**)
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/testsuite/tests/tool-ocaml/t250-closurerec-1.ml | ocaml | open Lib;;
let rec f _ = 0;;
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7
9 BRANCH 14
11 CONST0
12 RETURN 1
14 CLOSUREREC 0 , 11
18 ACC0
19 MAKEBLOCK1 0
21 POP 1
23 SETGLOBAL T250 - closurerec-1
25 STOP
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7 SETGLOBAL Lib
9 BRANCH 14
11 CONST0
12 RETURN 1
14 CLOSUREREC 0, 11
18 ACC0
19 MAKEBLOCK1 0
21 POP 1
23 SETGLOBAL T250-closurerec-1
25 STOP
**)
| |
2cc3e9812439ee2faecd53f05199a1ec57d3a96e42208bf25a37ea1a3b0bd7ae | Cipherwraith/hblog | GenerateArchives.hs | module GenerateArchives where
import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.IO as T
import System.FilePath
import Types
import Templates
import Data.Monoid
import Config
import ArchivedPosts
writeArchives :: [Publish] -> T.Text -> IO ()
writeArchives publish recent = do
htmlHead <- headerRaw
htmlFoot <- footerRaw
let content = archivedPosts publish
let writeOut = mconcat [htmlHead, recent, archivedPosts publish, htmlFoot]
let writePath = localStaticDirectory </> "archives" <.> "html"
T.writeFile writePath writeOut
| null | https://raw.githubusercontent.com/Cipherwraith/hblog/f92d96a60e301302c8a0e46fd68ee1e1810eb031/GenerateArchives.hs | haskell | module GenerateArchives where
import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.IO as T
import System.FilePath
import Types
import Templates
import Data.Monoid
import Config
import ArchivedPosts
writeArchives :: [Publish] -> T.Text -> IO ()
writeArchives publish recent = do
htmlHead <- headerRaw
htmlFoot <- footerRaw
let content = archivedPosts publish
let writeOut = mconcat [htmlHead, recent, archivedPosts publish, htmlFoot]
let writePath = localStaticDirectory </> "archives" <.> "html"
T.writeFile writePath writeOut
| |
29acc2b1a460a096f86388f307b49f4b74311110550e60ee1fd8aaaf5ab26ad1 | racket/racket7 | windows.rkt | #lang racket/base
(require "sep.rkt")
(provide special-filename?
drive-letter?
letter-drive-start?
backslash-backslash-questionmark?
backslash-backslash-questionmark-kind
parse-backslash-backslash-questionmark
parse-unc
backslash-backslash-questionmark-dot-ups-end
split-drive
strip-trailing-spaces)
(define special-filenames
and " CLOCK$ " on NT --- but not traditionally detected by Racket
'("NUL" "CON" "PRN" "AUX"
"COM1" "COM2" "COM3" "COM4" "COM5"
"COM6" "COM7" "COM8" "COM9"
"LPT1" "LPT2" "LPT3" "LPT4" "LPT5"
"LPT6" "LPT7" "LPT8" "LPT9"))
(define (special-filename? in-bstr #:immediate? [immediate? #t])
(define bstr (cond
[immediate? in-bstr]
[(backslash-backslash-questionmark? in-bstr) #""]
[else
Extract bytes after last sep or after drive letter :
(define len (bytes-length in-bstr))
(let loop ([i+1 len])
(cond
[(zero? i+1)
(if (letter-drive-start? bstr len)
(subbytes in-bstr 2)
in-bstr)]
[else
(define i (sub1 i+1))
(if (is-sep? (bytes-ref in-bstr i) 'windows)
(subbytes in-bstr i+1)
(loop i))]))]))
(define len (bytes-length bstr))
(cond
[(zero? len) #f]
[(backslash-backslash-questionmark? bstr) #f]
[else
(for/or ([fn (in-list special-filenames)])
;; check for case-insensitive `fn` match followed by
;; '.' or ':' or (whitespace|'.')*
(define fn-len (string-length fn))
(and (len . >= . fn-len)
(for/and ([c (in-string fn)]
[b (in-bytes bstr)])
(or (eqv? (char->integer c) b)
(eqv? (char->integer (char-downcase c)) b)))
(or (= len fn-len)
(eqv? (bytes-ref bstr fn-len) (char->integer #\.))
(eqv? (bytes-ref bstr fn-len) (char->integer #\:))
(for/and ([b (in-bytes bstr len)])
(or (eqv? b (char->integer #\space))
(eqv? b (char->integer #\.)))))))]))
(define (drive-letter? c)
(or (<= (char->integer #\a) c (char->integer #\z))
(<= (char->integer #\A) c (char->integer #\Z))))
(define (letter-drive-start? bstr len)
(and (len . >= . 2)
(drive-letter? (bytes-ref bstr 0))
(eqv? (bytes-ref bstr 1) (char->integer #\:))))
(define (backslash-backslash-questionmark? bstr)
(define len (bytes-length bstr))
(and (len . >= . 4)
(eqv? (bytes-ref bstr 0) (char->integer #\\))
(eqv? (bytes-ref bstr 1) (char->integer #\\))
(eqv? (bytes-ref bstr 2) (char->integer #\?))
(eqv? (bytes-ref bstr 3) (char->integer #\\))))
;; Returns #f, 'rel, 'red, or 'abs
(define (backslash-backslash-questionmark-kind bstr)
(define-values (kind drive-end-pos orig-drive-end-pos clean-start-pos add-sep-pos)
(parse-backslash-backslash-questionmark bstr))
kind)
;; Returns (values kind drive-len orig-drive-len clean-start-pos sep-bstr)
;; where `kind` is #f, 'rel, 'red, or 'abs
;;
;; For 'abs, then `drive-len` is set to the length of the root
;; specification. For example, if the drive is terminated by \\\ (a
weird " root " ) , then ` drive - len ` is after the third \. If the drive
;; is \\?\C:\, then `drive-len` is after the last slash. In the case
of \\?\UNC\ ... , ` drive - len ` is after the UNC part as in
;; `parse-unc` (so it doesn't include a slash after the volume name).
;;
;; The `orig-drive-len` result is almost the same as `drive-len`,
;; but maybe longer. It preserves an artifact of the given specification:
;; a backslash after a \\?\UNC\<mahine>\<volume> drive.
;;
;; For 'abs, `clean-start-pos` is the position where it's ok to start
;; removing extra slashes. It's usually the same as `drive-len`. In
the case of a \\?\UNC\ path , ` clean - start ` is 7 ( i.e. , just after
that prefix ) . In the case of a \\?\REL\ or \\?\RED\ path ,
;; `clean-start-pos` is the end of the string.
;;
For ' abs , the sep - bstr result is a byte string to insert after
;; the root to add further elements.
(define (parse-backslash-backslash-questionmark bstr)
(cond
[(not (backslash-backslash-questionmark? bstr))
(values #f #f #f #f #f)]
[else
(define len (bytes-length bstr))
;; Allow one extra "\":
(define base
(if (and (len . >= . 5)
(eqv? (bytes-ref bstr 4) (char->integer #\\)))
5
4))
If there are two backslashes in a row at the end , count everything
as the drive ; there are two exceptions : two backslashes are ok
at the end in the form \\?\C:\\ , and \\?\\\ is \\?\
(define two-backslashes?
(and (len . > . 5)
(eqv? (bytes-ref bstr (sub1 len)) (char->integer #\\))
(eqv? (bytes-ref bstr (- len 2)) (char->integer #\\))))
(cond
[(and two-backslashes?
(= len 6))
\\?\ is the root
(values 'abs 4 4 3 #"\\\\")]
[(and two-backslashes?
(or (not (= len (+ base 4)))
(not (and (len . > . base)
(drive-letter? (bytes-ref bstr base))))
(not (and (len . > . (add1 base))
(eqv? (bytes-ref bstr (add1 base)) (char->integer #\:))))))
;; Not the special case \\?\C:\\
(values 'abs len len len
If not already three \s , preserve this root when
;; adding more:
(if (not (eqv? (bytes-ref bstr (- len 3)) (char->integer #\\)))
#"\\"
#""))]
If there are three backslashes in a row , count everything
;; up to the slashes as the drive
[(and (len . > . 6)
(let loop ([i+1 len])
(cond
[(= i+1 6) #f]
[else
(define i (sub1 i+1))
(if (and (eqv? (bytes-ref bstr i) (char->integer #\\))
(eqv? (bytes-ref bstr (- i 1)) (char->integer #\\))
(eqv? (bytes-ref bstr (- i 2)) (char->integer #\\)))
i
(loop i))])))
=> (lambda (i)
(define i+1 (add1 i))
(values 'abs i+1 i+1 i+1 #""))]
;; Check for drive-letter case
[(and (len . > . 6)
(drive-letter? (bytes-ref bstr base))
(eqv? (bytes-ref bstr (add1 base)) (char->integer #\:))
(len . > . (+ 2 base))
(eqv? (bytes-ref bstr (+ 2 base)) (char->integer #\\)))
(define drive-len (if (and (len . > . (+ 3 base))
(eqv? (bytes-ref bstr (+ 3 base)) (char->integer #\\)))
(+ base 4)
(+ base 3)))
(values 'abs drive-len drive-len (+ base 2) #"")]
Check for UNC
[(and (len . > . (+ base 3))
(let ([b (bytes-ref bstr base)])
(or (eqv? b (char->integer #\U)) (eqv? b (char->integer #\u))))
(let ([b (bytes-ref bstr (add1 base))])
(or (eqv? b (char->integer #\N)) (eqv? b (char->integer #\n))))
(let ([b (bytes-ref bstr (+ base 2))])
(or (eqv? b (char->integer #\C)) (eqv? b (char->integer #\c))))
(eqv? (bytes-ref bstr (+ 3 base)) (char->integer #\\))
(parse-unc bstr #:no-forward-slash? #t
(if (and (len . > . (+ base 4))
(eqv? (bytes-ref bstr (+ 4 base)) (char->integer #\\)))
(+ base 5)
(+ base 4))))
=> (lambda (drive-len)
(define orig-drive-len
(if (and (len . > . drive-len)
(eqv? (bytes-ref bstr drive-len) (char->integer #\\)))
(add1 drive-len)
drive-len))
(values 'abs drive-len orig-drive-len (+ base 3) #"\\"))]
;; Check for REL and RED
[(and (= base 4)
(len . > . 8)
(eqv? (bytes-ref bstr 4) (char->integer #\R))
(eqv? (bytes-ref bstr 5) (char->integer #\E))
(let ([b (bytes-ref bstr 6)])
(or (eqv? b (char->integer #\L))
(eqv? b (char->integer #\D))))
(eqv? (bytes-ref bstr 7) (char->integer #\\))
(or (not (eqv? (bytes-ref bstr 8) (char->integer #\\)))
(len . > . 9)))
(values (if (eqv? (bytes-ref bstr 6) (char->integer #\L))
'rel
'red)
#f
#f
#f
#f)]
Otherwise , \\?\ is the ( non - existent ) drive
[else
(define clean-start-pos
(if (or (and (= len 5)
(eqv? (bytes-ref bstr 4) (char->integer #\\)))
(and (= len 6)
(eqv? (bytes-ref bstr 4) (char->integer #\\))
(eqv? (bytes-ref bstr 5) (char->integer #\\))))
3
4))
(values 'abs 4 4 clean-start-pos #"\\\\")])]))
Returns an integer if this path is a UNC path , # f otherwise .
;; If `delta` is non-0, then `delta` is after a leading \\.
;; (It starts by checking for \\?\ paths, so they won't be
treated as UNC . Unless delta is non-0 , in which case the
;; check isn't necessary, presumably because the original
;; `next' already started with \\?\UNC\.)
;; An integer result is set to the length (including offset) of
;; the \\server\vol part; which means that it's either the length of
;; the given byte string or a position that has a separator.
;; If `exact?`, then an integer is returned only if `bstr' is just the
;; drive; that is, only if only slashes are
;; in `bstr' starting with the result integer.
;; If `no-forward-slash?', then only backslashes are recognized.
(define (parse-unc bstr delta
#:exact? [exact? #f]
#:no-forward-slash? [no-forward-slash? #f])
(cond
[(and (zero? delta)
(backslash-backslash-questionmark? bstr))
#f]
;; Bail out fast on an easy non-match:
[(and (zero? delta)
(not
(and ((bytes-length bstr) . > . 2)
(is-sep? (bytes-ref bstr 0) 'windows)
(is-sep? (bytes-ref bstr 1) 'windows))))
#f]
[else
;; Check for a drive form: //x/y
(define (is-a-sep? c) (if no-forward-slash?
(eqv? c (char->integer #\\))
(is-sep? c 'windows)))
(define len (bytes-length bstr))
(define j (if (zero? delta) 2 delta))
(and
(not (and (len . > . j)
(is-a-sep? (bytes-ref bstr j))))
;; Found non-sep; skip over more
(let loop ([j j])
(cond
[(= j len)
;; Didn't find a sep, so not //x/
#f]
[(not (is-a-sep? (bytes-ref bstr j)))
(cond
[(and no-forward-slash?
(eqv? (bytes-ref bstr j) (char->integer #\/)))
;; Found / when only \ is allowed as separator
#f]
[else
;; Keep looking
(loop (add1 j))])]
[else
;; Found sep again, so we have //x/:
(let* ([j (add1 j)]
[j (if (and no-forward-slash?
(j . < . len)
(is-a-sep? (bytes-ref bstr j)))
two backslashes ok in \\?\UNC mode
(add1 j)
j)])
(cond
[(and (= j (if (zero? delta) 4 (+ delta 2)))
(eqv? (bytes-ref bstr (- j 2)) (char->integer #\?)))
We have //?/ , with up to 2 backslashes .
This does n't count as UNC , to avoid confusion with \\?\.
#f]
[else
(let loop ([j j])
(cond
[(= j len)
Did n't find a non - sep , so not UNC
#f]
[(is-a-sep? (bytes-ref bstr j))
Keep looking for non - sep
(loop (add1 j))]
[else
Found non - sep again ; this is UNC
(let loop ([j j])
(cond
[(= j len)
;; Whole string is drive
len]
[(is-a-sep? (bytes-ref bstr j))
Found sep that ends UNC drive
(and (or (not exact?)
;; Make sure there are no more separators:
(for/and ([b (in-bytes bstr (add1 j))])
(not (is-a-sep? b))))
j)]
[else (loop (add1 j))]))]))]))])))]))
;; Assumes `bstr` is of the form \\?\REL or \\?\RED and returns
;; (values dots-end literal-start)
;; If `bstr` is \\?\REL\..\..\.., the `dots-end` result is the index just
past the last " \ .. " . This might be the first " \ " of a " \\ "
;; separator, the "\" before a non-".." element, or the end of the
string . For a \\?\RED\ path , it 's as if there are no " .. " s
;; (because ".." is not special in "RED" paths). Otherwise, `dots-end`
is # f.
;; The `literal-start` result is the starting index of the literal part of
the path ( i.e. , after one or two slashes , possibly after dots ) .
(define (backslash-backslash-questionmark-dot-ups-end bstr len)
(define pos
(and (eqv? (bytes-ref bstr 6) (char->integer #\L))
(let loop ([pos #f]
[j 7]) ;; \\?\REL\
(cond
[((+ j 3) . > . len)
pos]
[(and (eqv? (bytes-ref bstr j) (char->integer #\\))
(eqv? (bytes-ref bstr (+ j 1)) (char->integer #\.))
(eqv? (bytes-ref bstr (+ j 2)) (char->integer #\.))
(or (= len (+ j 3))
(eqv? (bytes-ref bstr (+ j 3)) (char->integer #\\))))
(define j+3 (+ j 3))
(loop j+3 j+3)]
[else pos]))))
(cond
[pos
(cond
[(= pos len)
(values pos len)]
[(and ((+ pos 2) . < . len)
(eqv? (bytes-ref bstr (add1 pos)) (char->integer #\\)))
(values pos (+ pos 2))]
[else
(values pos (+ pos 1))])]
[(len . > . 8)
(cond
[(eqv? (bytes-ref bstr 8) (char->integer #\\))
(values #f 9)]
[else
(values #f 8)])]
[else
(values #f 8)]))
(define (split-drive bstr)
(cond
[(backslash-backslash-questionmark? bstr)
(define-values (kind drive-len orig-drive-len clean-start-pos add-sep-pos)
(parse-backslash-backslash-questionmark bstr))
(subbytes bstr 0 drive-len)]
[(parse-unc bstr 0)
=> (lambda (pos) (subbytes bstr 0 pos))]
[else
(subbytes bstr 0 (min 3 (bytes-length bstr)))]))
(define (strip-trailing-spaces bstr)
(cond
[(backslash-backslash-questionmark? bstr)
;; all spaces are significant, so don't strip them
bstr]
[else
(define len (bytes-length bstr))
;; ignore/keep trailing separators
(define len-before-seps
(let loop ([i+1 len])
(define i (sub1 i+1))
(cond
[(is-sep? (bytes-ref bstr i) 'windows)
(loop i)]
[else i+1])))
(let loop ([i+1 len-before-seps])
(cond
[(zero? i+1)
;; A path element that's all spaces; don't trim
bstr]
[else
(define i (sub1 i+1))
(define b (bytes-ref bstr i))
(cond
[(is-sep? b 'windows)
;; A path element that's all spaces; don't trim
bstr]
[(or (eqv? b (char->integer #\.))
(eqv? b (char->integer #\space)))
(loop i)]
[(= i+1 len-before-seps)
;; Nothing to trim
bstr]
[else
;; Trim
(bytes-append (subbytes bstr 0 i+1)
(subbytes bstr len-before-seps len))])]))]))
| null | https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/racket/src/io/path/windows.rkt | racket | check for case-insensitive `fn` match followed by
'.' or ':' or (whitespace|'.')*
Returns #f, 'rel, 'red, or 'abs
Returns (values kind drive-len orig-drive-len clean-start-pos sep-bstr)
where `kind` is #f, 'rel, 'red, or 'abs
For 'abs, then `drive-len` is set to the length of the root
specification. For example, if the drive is terminated by \\\ (a
is \\?\C:\, then `drive-len` is after the last slash. In the case
`parse-unc` (so it doesn't include a slash after the volume name).
The `orig-drive-len` result is almost the same as `drive-len`,
but maybe longer. It preserves an artifact of the given specification:
a backslash after a \\?\UNC\<mahine>\<volume> drive.
For 'abs, `clean-start-pos` is the position where it's ok to start
removing extra slashes. It's usually the same as `drive-len`. In
`clean-start-pos` is the end of the string.
the root to add further elements.
Allow one extra "\":
there are two exceptions : two backslashes are ok
Not the special case \\?\C:\\
adding more:
up to the slashes as the drive
Check for drive-letter case
Check for REL and RED
If `delta` is non-0, then `delta` is after a leading \\.
(It starts by checking for \\?\ paths, so they won't be
check isn't necessary, presumably because the original
`next' already started with \\?\UNC\.)
An integer result is set to the length (including offset) of
the \\server\vol part; which means that it's either the length of
the given byte string or a position that has a separator.
If `exact?`, then an integer is returned only if `bstr' is just the
drive; that is, only if only slashes are
in `bstr' starting with the result integer.
If `no-forward-slash?', then only backslashes are recognized.
Bail out fast on an easy non-match:
Check for a drive form: //x/y
Found non-sep; skip over more
Didn't find a sep, so not //x/
Found / when only \ is allowed as separator
Keep looking
Found sep again, so we have //x/:
this is UNC
Whole string is drive
Make sure there are no more separators:
Assumes `bstr` is of the form \\?\REL or \\?\RED and returns
(values dots-end literal-start)
If `bstr` is \\?\REL\..\..\.., the `dots-end` result is the index just
separator, the "\" before a non-".." element, or the end of the
(because ".." is not special in "RED" paths). Otherwise, `dots-end`
The `literal-start` result is the starting index of the literal part of
\\?\REL\
all spaces are significant, so don't strip them
ignore/keep trailing separators
A path element that's all spaces; don't trim
A path element that's all spaces; don't trim
Nothing to trim
Trim | #lang racket/base
(require "sep.rkt")
(provide special-filename?
drive-letter?
letter-drive-start?
backslash-backslash-questionmark?
backslash-backslash-questionmark-kind
parse-backslash-backslash-questionmark
parse-unc
backslash-backslash-questionmark-dot-ups-end
split-drive
strip-trailing-spaces)
(define special-filenames
and " CLOCK$ " on NT --- but not traditionally detected by Racket
'("NUL" "CON" "PRN" "AUX"
"COM1" "COM2" "COM3" "COM4" "COM5"
"COM6" "COM7" "COM8" "COM9"
"LPT1" "LPT2" "LPT3" "LPT4" "LPT5"
"LPT6" "LPT7" "LPT8" "LPT9"))
(define (special-filename? in-bstr #:immediate? [immediate? #t])
(define bstr (cond
[immediate? in-bstr]
[(backslash-backslash-questionmark? in-bstr) #""]
[else
Extract bytes after last sep or after drive letter :
(define len (bytes-length in-bstr))
(let loop ([i+1 len])
(cond
[(zero? i+1)
(if (letter-drive-start? bstr len)
(subbytes in-bstr 2)
in-bstr)]
[else
(define i (sub1 i+1))
(if (is-sep? (bytes-ref in-bstr i) 'windows)
(subbytes in-bstr i+1)
(loop i))]))]))
(define len (bytes-length bstr))
(cond
[(zero? len) #f]
[(backslash-backslash-questionmark? bstr) #f]
[else
(for/or ([fn (in-list special-filenames)])
(define fn-len (string-length fn))
(and (len . >= . fn-len)
(for/and ([c (in-string fn)]
[b (in-bytes bstr)])
(or (eqv? (char->integer c) b)
(eqv? (char->integer (char-downcase c)) b)))
(or (= len fn-len)
(eqv? (bytes-ref bstr fn-len) (char->integer #\.))
(eqv? (bytes-ref bstr fn-len) (char->integer #\:))
(for/and ([b (in-bytes bstr len)])
(or (eqv? b (char->integer #\space))
(eqv? b (char->integer #\.)))))))]))
(define (drive-letter? c)
(or (<= (char->integer #\a) c (char->integer #\z))
(<= (char->integer #\A) c (char->integer #\Z))))
(define (letter-drive-start? bstr len)
(and (len . >= . 2)
(drive-letter? (bytes-ref bstr 0))
(eqv? (bytes-ref bstr 1) (char->integer #\:))))
(define (backslash-backslash-questionmark? bstr)
(define len (bytes-length bstr))
(and (len . >= . 4)
(eqv? (bytes-ref bstr 0) (char->integer #\\))
(eqv? (bytes-ref bstr 1) (char->integer #\\))
(eqv? (bytes-ref bstr 2) (char->integer #\?))
(eqv? (bytes-ref bstr 3) (char->integer #\\))))
(define (backslash-backslash-questionmark-kind bstr)
(define-values (kind drive-end-pos orig-drive-end-pos clean-start-pos add-sep-pos)
(parse-backslash-backslash-questionmark bstr))
kind)
weird " root " ) , then ` drive - len ` is after the third \. If the drive
of \\?\UNC\ ... , ` drive - len ` is after the UNC part as in
the case of a \\?\UNC\ path , ` clean - start ` is 7 ( i.e. , just after
that prefix ) . In the case of a \\?\REL\ or \\?\RED\ path ,
For ' abs , the sep - bstr result is a byte string to insert after
(define (parse-backslash-backslash-questionmark bstr)
(cond
[(not (backslash-backslash-questionmark? bstr))
(values #f #f #f #f #f)]
[else
(define len (bytes-length bstr))
(define base
(if (and (len . >= . 5)
(eqv? (bytes-ref bstr 4) (char->integer #\\)))
5
4))
If there are two backslashes in a row at the end , count everything
at the end in the form \\?\C:\\ , and \\?\\\ is \\?\
(define two-backslashes?
(and (len . > . 5)
(eqv? (bytes-ref bstr (sub1 len)) (char->integer #\\))
(eqv? (bytes-ref bstr (- len 2)) (char->integer #\\))))
(cond
[(and two-backslashes?
(= len 6))
\\?\ is the root
(values 'abs 4 4 3 #"\\\\")]
[(and two-backslashes?
(or (not (= len (+ base 4)))
(not (and (len . > . base)
(drive-letter? (bytes-ref bstr base))))
(not (and (len . > . (add1 base))
(eqv? (bytes-ref bstr (add1 base)) (char->integer #\:))))))
(values 'abs len len len
If not already three \s , preserve this root when
(if (not (eqv? (bytes-ref bstr (- len 3)) (char->integer #\\)))
#"\\"
#""))]
If there are three backslashes in a row , count everything
[(and (len . > . 6)
(let loop ([i+1 len])
(cond
[(= i+1 6) #f]
[else
(define i (sub1 i+1))
(if (and (eqv? (bytes-ref bstr i) (char->integer #\\))
(eqv? (bytes-ref bstr (- i 1)) (char->integer #\\))
(eqv? (bytes-ref bstr (- i 2)) (char->integer #\\)))
i
(loop i))])))
=> (lambda (i)
(define i+1 (add1 i))
(values 'abs i+1 i+1 i+1 #""))]
[(and (len . > . 6)
(drive-letter? (bytes-ref bstr base))
(eqv? (bytes-ref bstr (add1 base)) (char->integer #\:))
(len . > . (+ 2 base))
(eqv? (bytes-ref bstr (+ 2 base)) (char->integer #\\)))
(define drive-len (if (and (len . > . (+ 3 base))
(eqv? (bytes-ref bstr (+ 3 base)) (char->integer #\\)))
(+ base 4)
(+ base 3)))
(values 'abs drive-len drive-len (+ base 2) #"")]
Check for UNC
[(and (len . > . (+ base 3))
(let ([b (bytes-ref bstr base)])
(or (eqv? b (char->integer #\U)) (eqv? b (char->integer #\u))))
(let ([b (bytes-ref bstr (add1 base))])
(or (eqv? b (char->integer #\N)) (eqv? b (char->integer #\n))))
(let ([b (bytes-ref bstr (+ base 2))])
(or (eqv? b (char->integer #\C)) (eqv? b (char->integer #\c))))
(eqv? (bytes-ref bstr (+ 3 base)) (char->integer #\\))
(parse-unc bstr #:no-forward-slash? #t
(if (and (len . > . (+ base 4))
(eqv? (bytes-ref bstr (+ 4 base)) (char->integer #\\)))
(+ base 5)
(+ base 4))))
=> (lambda (drive-len)
(define orig-drive-len
(if (and (len . > . drive-len)
(eqv? (bytes-ref bstr drive-len) (char->integer #\\)))
(add1 drive-len)
drive-len))
(values 'abs drive-len orig-drive-len (+ base 3) #"\\"))]
[(and (= base 4)
(len . > . 8)
(eqv? (bytes-ref bstr 4) (char->integer #\R))
(eqv? (bytes-ref bstr 5) (char->integer #\E))
(let ([b (bytes-ref bstr 6)])
(or (eqv? b (char->integer #\L))
(eqv? b (char->integer #\D))))
(eqv? (bytes-ref bstr 7) (char->integer #\\))
(or (not (eqv? (bytes-ref bstr 8) (char->integer #\\)))
(len . > . 9)))
(values (if (eqv? (bytes-ref bstr 6) (char->integer #\L))
'rel
'red)
#f
#f
#f
#f)]
Otherwise , \\?\ is the ( non - existent ) drive
[else
(define clean-start-pos
(if (or (and (= len 5)
(eqv? (bytes-ref bstr 4) (char->integer #\\)))
(and (= len 6)
(eqv? (bytes-ref bstr 4) (char->integer #\\))
(eqv? (bytes-ref bstr 5) (char->integer #\\))))
3
4))
(values 'abs 4 4 clean-start-pos #"\\\\")])]))
Returns an integer if this path is a UNC path , # f otherwise .
treated as UNC . Unless delta is non-0 , in which case the
(define (parse-unc bstr delta
#:exact? [exact? #f]
#:no-forward-slash? [no-forward-slash? #f])
(cond
[(and (zero? delta)
(backslash-backslash-questionmark? bstr))
#f]
[(and (zero? delta)
(not
(and ((bytes-length bstr) . > . 2)
(is-sep? (bytes-ref bstr 0) 'windows)
(is-sep? (bytes-ref bstr 1) 'windows))))
#f]
[else
(define (is-a-sep? c) (if no-forward-slash?
(eqv? c (char->integer #\\))
(is-sep? c 'windows)))
(define len (bytes-length bstr))
(define j (if (zero? delta) 2 delta))
(and
(not (and (len . > . j)
(is-a-sep? (bytes-ref bstr j))))
(let loop ([j j])
(cond
[(= j len)
#f]
[(not (is-a-sep? (bytes-ref bstr j)))
(cond
[(and no-forward-slash?
(eqv? (bytes-ref bstr j) (char->integer #\/)))
#f]
[else
(loop (add1 j))])]
[else
(let* ([j (add1 j)]
[j (if (and no-forward-slash?
(j . < . len)
(is-a-sep? (bytes-ref bstr j)))
two backslashes ok in \\?\UNC mode
(add1 j)
j)])
(cond
[(and (= j (if (zero? delta) 4 (+ delta 2)))
(eqv? (bytes-ref bstr (- j 2)) (char->integer #\?)))
We have //?/ , with up to 2 backslashes .
This does n't count as UNC , to avoid confusion with \\?\.
#f]
[else
(let loop ([j j])
(cond
[(= j len)
Did n't find a non - sep , so not UNC
#f]
[(is-a-sep? (bytes-ref bstr j))
Keep looking for non - sep
(loop (add1 j))]
[else
(let loop ([j j])
(cond
[(= j len)
len]
[(is-a-sep? (bytes-ref bstr j))
Found sep that ends UNC drive
(and (or (not exact?)
(for/and ([b (in-bytes bstr (add1 j))])
(not (is-a-sep? b))))
j)]
[else (loop (add1 j))]))]))]))])))]))
past the last " \ .. " . This might be the first " \ " of a " \\ "
string . For a \\?\RED\ path , it 's as if there are no " .. " s
is # f.
the path ( i.e. , after one or two slashes , possibly after dots ) .
(define (backslash-backslash-questionmark-dot-ups-end bstr len)
(define pos
(and (eqv? (bytes-ref bstr 6) (char->integer #\L))
(let loop ([pos #f]
(cond
[((+ j 3) . > . len)
pos]
[(and (eqv? (bytes-ref bstr j) (char->integer #\\))
(eqv? (bytes-ref bstr (+ j 1)) (char->integer #\.))
(eqv? (bytes-ref bstr (+ j 2)) (char->integer #\.))
(or (= len (+ j 3))
(eqv? (bytes-ref bstr (+ j 3)) (char->integer #\\))))
(define j+3 (+ j 3))
(loop j+3 j+3)]
[else pos]))))
(cond
[pos
(cond
[(= pos len)
(values pos len)]
[(and ((+ pos 2) . < . len)
(eqv? (bytes-ref bstr (add1 pos)) (char->integer #\\)))
(values pos (+ pos 2))]
[else
(values pos (+ pos 1))])]
[(len . > . 8)
(cond
[(eqv? (bytes-ref bstr 8) (char->integer #\\))
(values #f 9)]
[else
(values #f 8)])]
[else
(values #f 8)]))
(define (split-drive bstr)
(cond
[(backslash-backslash-questionmark? bstr)
(define-values (kind drive-len orig-drive-len clean-start-pos add-sep-pos)
(parse-backslash-backslash-questionmark bstr))
(subbytes bstr 0 drive-len)]
[(parse-unc bstr 0)
=> (lambda (pos) (subbytes bstr 0 pos))]
[else
(subbytes bstr 0 (min 3 (bytes-length bstr)))]))
(define (strip-trailing-spaces bstr)
(cond
[(backslash-backslash-questionmark? bstr)
bstr]
[else
(define len (bytes-length bstr))
(define len-before-seps
(let loop ([i+1 len])
(define i (sub1 i+1))
(cond
[(is-sep? (bytes-ref bstr i) 'windows)
(loop i)]
[else i+1])))
(let loop ([i+1 len-before-seps])
(cond
[(zero? i+1)
bstr]
[else
(define i (sub1 i+1))
(define b (bytes-ref bstr i))
(cond
[(is-sep? b 'windows)
bstr]
[(or (eqv? b (char->integer #\.))
(eqv? b (char->integer #\space)))
(loop i)]
[(= i+1 len-before-seps)
bstr]
[else
(bytes-append (subbytes bstr 0 i+1)
(subbytes bstr len-before-seps len))])]))]))
|
4fa52c7951c31d431b7694bf927c0b5cb63d6aaf9998260db92d60a9d369aced | ericfinster/opetopictt | opetopictt.ml | (*****************************************************************************)
(* *)
(* Main module *)
(* *)
(*****************************************************************************)
(* open Base
* open Fmt *)
open Format
open Opetopictt.Io
open Opetopictt.Typecheck
(*****************************************************************************)
(* Options *)
(*****************************************************************************)
let usage = "opetopictt [options] [file]"
let spec_list = []
(*****************************************************************************)
(* Main Entry Point *)
(*****************************************************************************)
let () =
let file_in = ref [] in
set_margin 80;
open_vbox 0; (* initialize the pretty printer *)
Arg.parse spec_list (fun s -> file_in := s::!file_in) usage;
let files = List.rev (!file_in) in
let _ = check_files empty_ctx [] files in
()
let rec repl_loop _ =
* print_string " # > " ;
* let str = read_line ( ) in
* if ( String.equal str " quit " ) then
* exit 0
* else
* let _ = Printf.printf " You said : % s\n " str in
* repl_loop ( )
*
* let ( ) = repl_loop ( )
* print_string "#> " ;
* let str = read_line () in
* if (String.equal str "quit") then
* exit 0
* else
* let _ = Printf.printf "You said: %s\n" str in
* repl_loop ()
*
* let () = repl_loop () *)
| null | https://raw.githubusercontent.com/ericfinster/opetopictt/766a547b59280b4016657318d9fb486940b863da/bin/opetopictt.ml | ocaml | ***************************************************************************
Main module
***************************************************************************
open Base
* open Fmt
***************************************************************************
Options
***************************************************************************
***************************************************************************
Main Entry Point
***************************************************************************
initialize the pretty printer |
open Format
open Opetopictt.Io
open Opetopictt.Typecheck
let usage = "opetopictt [options] [file]"
let spec_list = []
let () =
let file_in = ref [] in
set_margin 80;
Arg.parse spec_list (fun s -> file_in := s::!file_in) usage;
let files = List.rev (!file_in) in
let _ = check_files empty_ctx [] files in
()
let rec repl_loop _ =
* print_string " # > " ;
* let str = read_line ( ) in
* if ( String.equal str " quit " ) then
* exit 0
* else
* let _ = Printf.printf " You said : % s\n " str in
* repl_loop ( )
*
* let ( ) = repl_loop ( )
* print_string "#> " ;
* let str = read_line () in
* if (String.equal str "quit") then
* exit 0
* else
* let _ = Printf.printf "You said: %s\n" str in
* repl_loop ()
*
* let () = repl_loop () *)
|
1435bf6b72518f1ec751a2d74b92dc70b1f0680d9bc5a73b60f6ef83cef98d4e | alonsodomin/haskell-schema | Schema.hs | {-# LANGUAGE RankNTypes #-}
module Data.Schema
( Field
, Fields
, field
, optional
, alt
, Schema
, HasSchema (..)
, prim
, const
, record
, asList
, toList
, oneOf
, alias
) where
import Control.Functor.HigherOrder
import Control.Lens
import Data.Functor.Invariant
import Data.HashMap.Strict (HashMap)
import Data.Hashable (Hashable)
import qualified Data.List.NonEmpty as NEL
import Data.Schema.Internal.Types
import Data.Text (Text)
import Data.Vector (Vector)
import qualified Data.Vector as Vector
import Prelude hiding (const, seq)
-- | Define an alternative
alt :: Text -> s b -> Prism' a b -> AltDef s a
alt = AltDef
-- | Define an annotated schema for primitives of type `p`
prim :: p a -> Schema p a
prim primAlg = Schema (HFix $ PrimitiveSchema primAlg)
-- | Define a schema for a type that is always constant
const :: a -> Schema p a
const a = Schema (HFix (RecordSchema $ pure a))
-- | Define the schema of record using the given fields
record :: Fields (Schema p) a -> Schema p a
record ps = Schema (HFix (RecordSchema $ hoistField unwrapSchema ps))
-- | Define the schema of a list based on the element type
asList :: Iso' (Vector a) [a]
asList = iso Vector.toList Vector.fromList
toList :: Schema p (Vector a) -> Schema p [a]
toList = invmap Vector.toList Vector.fromList
-- | Define the schema of an union (coproduct) type based on the given alternatives
oneOf :: [AltDef (Schema p) a] -> Schema p a
oneOf alts = Schema (HFix (UnionSchema $ hfmap unwrapSchema <$> NEL.fromList alts))
-- | Define an schema alias that is isomorphic to another one using the given ISO transformation
alias :: Iso' a b -> Schema p a -> Schema p b
alias i = invmap (view i) (view . from $ i)
| null | https://raw.githubusercontent.com/alonsodomin/haskell-schema/4f12bda9550e83000b9f886c1c12a8becb6ad7d7/hschema/src/Data/Schema.hs | haskell | # LANGUAGE RankNTypes #
| Define an alternative
| Define an annotated schema for primitives of type `p`
| Define a schema for a type that is always constant
| Define the schema of record using the given fields
| Define the schema of a list based on the element type
| Define the schema of an union (coproduct) type based on the given alternatives
| Define an schema alias that is isomorphic to another one using the given ISO transformation |
module Data.Schema
( Field
, Fields
, field
, optional
, alt
, Schema
, HasSchema (..)
, prim
, const
, record
, asList
, toList
, oneOf
, alias
) where
import Control.Functor.HigherOrder
import Control.Lens
import Data.Functor.Invariant
import Data.HashMap.Strict (HashMap)
import Data.Hashable (Hashable)
import qualified Data.List.NonEmpty as NEL
import Data.Schema.Internal.Types
import Data.Text (Text)
import Data.Vector (Vector)
import qualified Data.Vector as Vector
import Prelude hiding (const, seq)
alt :: Text -> s b -> Prism' a b -> AltDef s a
alt = AltDef
prim :: p a -> Schema p a
prim primAlg = Schema (HFix $ PrimitiveSchema primAlg)
const :: a -> Schema p a
const a = Schema (HFix (RecordSchema $ pure a))
record :: Fields (Schema p) a -> Schema p a
record ps = Schema (HFix (RecordSchema $ hoistField unwrapSchema ps))
asList :: Iso' (Vector a) [a]
asList = iso Vector.toList Vector.fromList
toList :: Schema p (Vector a) -> Schema p [a]
toList = invmap Vector.toList Vector.fromList
oneOf :: [AltDef (Schema p) a] -> Schema p a
oneOf alts = Schema (HFix (UnionSchema $ hfmap unwrapSchema <$> NEL.fromList alts))
alias :: Iso' a b -> Schema p a -> Schema p b
alias i = invmap (view i) (view . from $ i)
|
7b11ebffb9c4cdb25b945961d2251ab805869799c0004bcf8cb73946ac2b9101 | mejgun/haskell-tdlib | Updates.hs | {-# LANGUAGE OverloadedStrings #-}
-- |
module TD.Data.Updates where
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as T
import qualified TD.Data.Update as Update
import qualified Utils as U
-- |
data Updates = -- | Contains a list of updates @updates List of updates
Updates
{ -- |
updates :: Maybe [Update.Update]
}
deriving (Eq)
instance Show Updates where
show
Updates
{ updates = updates_
} =
"Updates"
++ U.cc
[ U.p "updates" updates_
]
instance T.FromJSON Updates where
parseJSON v@(T.Object obj) = do
t <- obj A..: "@type" :: T.Parser String
case t of
"updates" -> parseUpdates v
_ -> mempty
where
parseUpdates :: A.Value -> T.Parser Updates
parseUpdates = A.withObject "Updates" $ \o -> do
updates_ <- o A..:? "updates"
return $ Updates {updates = updates_}
parseJSON _ = mempty
instance T.ToJSON Updates where
toJSON
Updates
{ updates = updates_
} =
A.object
[ "@type" A..= T.String "updates",
"updates" A..= updates_
]
| null | https://raw.githubusercontent.com/mejgun/haskell-tdlib/beb6635177d7626b70fd909b1d89f2156a992cd2/src/TD/Data/Updates.hs | haskell | # LANGUAGE OverloadedStrings #
|
|
| Contains a list of updates @updates List of updates
| |
module TD.Data.Updates where
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as T
import qualified TD.Data.Update as Update
import qualified Utils as U
Updates
updates :: Maybe [Update.Update]
}
deriving (Eq)
instance Show Updates where
show
Updates
{ updates = updates_
} =
"Updates"
++ U.cc
[ U.p "updates" updates_
]
instance T.FromJSON Updates where
parseJSON v@(T.Object obj) = do
t <- obj A..: "@type" :: T.Parser String
case t of
"updates" -> parseUpdates v
_ -> mempty
where
parseUpdates :: A.Value -> T.Parser Updates
parseUpdates = A.withObject "Updates" $ \o -> do
updates_ <- o A..:? "updates"
return $ Updates {updates = updates_}
parseJSON _ = mempty
instance T.ToJSON Updates where
toJSON
Updates
{ updates = updates_
} =
A.object
[ "@type" A..= T.String "updates",
"updates" A..= updates_
]
|
ec8fbba7a5a11b4f7f362a5266ae261e97bc698254514e20087db14174b8aadd | jlouis/erlang-utp | gen_utp_worker.erl | %%%-------------------------------------------------------------------
@author < >
( C ) 2011 ,
%%% @doc
%%%
%%% @end
Created : 19 Feb 2011 by < >
%%%-------------------------------------------------------------------
-module(gen_utp_worker).
-include("log.hrl").
-include("utp.hrl").
-behaviour(gen_fsm).
%% API
-export([start_link/4]).
Operations
-export([connect/1,
accept/2,
close/1,
recv/2,
send/2
]).
%% Internal API
-export([
incoming/3,
reply/2
]).
%% gen_fsm callbacks
-export([init/1, handle_event/3,
handle_sync_event/4, handle_info/3, terminate/3, code_change/4]).
%% gen_fsm callback states
-export([idle/2, idle/3,
syn_sent/2,
connected/2, connected/3,
got_fin/2, got_fin/3,
destroy_delay/2,
fin_sent/2, fin_sent/3,
reset/2, reset/3,
destroy/2]).
-type conn_state() :: idle | syn_sent | connected | got_fin
| destroy_delay | fin_sent | reset | destroy.
-type error_type() :: econnreset | econnrefused | etiemedout | emsgsize.
-type ret_value() :: ok | {ok, binary()} | {error, error_type()}.
-export_type([conn_state/0,
error_type/0,
ret_value/0]).
-define(SERVER, ?MODULE).
Default extensions to use when SYN / SYNACK'ing
-define(SYN_EXTS, [{ext_bits, <<0:64/integer>>}]).
%% Default SYN packet timeout
-define(SYN_TIMEOUT, 3000).
-define(DEFAULT_RETRANSMIT_TIMEOUT, 3000).
-define(SYN_TIMEOUT_THRESHOLD, ?SYN_TIMEOUT*2).
-define(RTT_VAR, 800). % Round trip time variance
-define(PACKET_SIZE, 350). % @todo Probably dead!
-define(MAX_WINDOW_USER, 255 * ?PACKET_SIZE). % Likewise!
-define(DEFAULT_ACK_TIME, 16#70000000). % Default add to the future when an Ack is expected
-define(DELAYED_ACK_BYTE_THRESHOLD, 2400). % bytes
-define(DELAYED_ACK_TIME_THRESHOLD, 100). % milliseconds
-define(KEEPALIVE_INTERVAL, 29000). % ms
Number of bytes to increase max window size by , per RTT . This is
%% scaled down linearly proportional to off_target. i.e. if all packets
in one window have 0 delay , window size will increase by this number .
Typically it 's less . TCP increases one MSS per RTT , which is 1500
-define(MAX_CWND_INCREASE_BYTES_PER_RTT, 3000).
-define(CUR_DELAY_SIZE, 3).
%% Default timeout value for sockets where we will destroy them!
-define(RTO_DESTROY_VALUE, 30*1000).
The delay to set on Zero Windows . It is awfully high , but that is what it has
%% to be it seems.
-define(ZERO_WINDOW_DELAY, 15*1000).
Experiments suggest that a clock skew of 10 ms per 325 seconds
is not impossible . Reset delay_base every 13 minutes . The clock
%% skew is dealt with by observing the delay base in the other
%% direction, and adjusting our own upwards if the opposite direction
%% delay base keeps going down
-define(DELAY_BASE_HISTORY, 13).
-define(MAX_WINDOW_DECAY, 100). % ms
-define(DEFAULT_OPT_RECV_SZ, 8192). %% @todo Fix this
, arbitrary at the moment
-define(DEFAULT_FSM_TIMEOUT, 10*60*1000).
%% STATE RECORDS
%% ----------------------------------------------------------------------
-record(state, { network :: utp_network:t(),
buffer :: utp_buffer:t(),
process :: utp_process:t(),
connector :: {{reference(), pid()}, [{pkt, #packet{}, term()}]},
zerowindow_timeout :: undefined | {set, reference()},
retransmit_timeout :: undefined | {set, reference()},
delayed_ack_timeout :: undefined | {set, integer(), reference()},
options = [] :: [{atom(), term()}]
}).
%%%===================================================================
%% @doc Create a worker for a peer endpoint
%% @end
start_link(Socket, Addr, Port, Options) ->
gen_fsm:start_link(?MODULE, [Socket, Addr, Port, Options], []).
%% @doc Send a connect event
%% @end
connect(Pid) ->
utp:report_event(60, client, us, connect, []),
sync_send_event(Pid, connect).
%% @doc Send an accept event
%% @end
accept(Pid, SynPacket) ->
utp:report_event(60, client, us, accept, [SynPacket]),
sync_send_event(Pid, {accept, SynPacket}).
%% @doc Receive some bytes from the socket. Blocks until the said amount of
%% bytes have been read.
%% @end
recv(Pid, Amount) ->
utp:report_event(60, client, us, {recv, Amount}, []),
try
gen_fsm:sync_send_event(Pid, {recv, Amount}, infinity)
catch
exit:{noproc, _} ->
{error, enoconn}
end.
%% @doc Send some bytes from the socket. Blocks until the said amount of
%% bytes have been sent and has been accepted by the underlying layer.
%% @end
send(Pid, Data) ->
utp:report_event(60, client, us, {send, size(Data)}, [Data]),
try
gen_fsm:sync_send_event(Pid, {send, Data}, infinity)
catch
exit:{noproc, _} ->
{error, enoconn}
end.
%% @doc Send a close event
%% @end
close(Pid) ->
utp:report_event(60, client, us, close, []),
%% Consider making it sync, but the de-facto implementation isn't
gen_fsm:send_event(Pid, close).
%% ----------------------------------------------------------------------
incoming(Pid, Packet, Timing) ->
utp:report_event(50, peer, us, utp_proto:succinct_format_packet(Packet), [{packet, Packet}]),
gen_fsm:send_event(Pid, {pkt, Packet, Timing}).
reply(To, Msg) ->
utp:report_event(60, us, client, reply, [Msg]),
gen_fsm:reply(To, Msg).
sync_send_event(Pid, Event) ->
gen_fsm:sync_send_event(Pid, Event, ?DEFAULT_FSM_TIMEOUT).
%%%===================================================================
%%% gen_fsm callbacks
%%%===================================================================
@private
init([Socket, Addr, Port, Options]) ->
case validate_options(Options) of
ok ->
PktBuf = utp_buffer:mk(?DEFAULT_OPT_RECV_SZ),
ProcInfo = utp_process:mk(),
CanonAddr = utp_util:canonicalize_address(Addr),
SockInfo = utp_socket:mk(CanonAddr, Options, Port, Socket),
Network = utp_network:mk(?DEFAULT_PACKET_SIZE, SockInfo),
{ok, report(idle), #state{ network = Network,
buffer = PktBuf,
process = ProcInfo,
options= Options }};
badarg ->
{report(stop), badarg}
end.
@private
idle(close, S) ->
{next_state, report(destroy), S, 0};
idle(_Msg, S) ->
%% Ignore messages
?ERR([node(), async_message, idle, _Msg]),
{next_state, idle, S}.
@private
syn_sent({pkt, #packet { ty = st_reset }, _},
#state { process = PRI,
connector = {From, _} } = State) ->
%% We received a reset packet in the connected state. This means an abrupt
%% disconnect, so move to the RESET state right away after telling people
%% we can't fulfill their requests.
N_PRI = utp_process:error_all(PRI, econnrefused),
%% Also handle the guy making the connection
reply(From, econnrefused),
{next_state, report(destroy), State#state { process = N_PRI }, 0};
syn_sent({pkt, #packet { ty = st_state,
win_sz = WindowSize,
seq_no = PktSeqNo },
{TS, TSDiff, RecvTime}},
#state { network = Network,
buffer = PktBuf,
connector = {From, Packets},
retransmit_timeout = RTimeout
} = State) ->
reply(From, ok),
%% Empty the queue of packets for the new state
%% We reverse the list so they are in the order we got them originally
[incoming(self(), P, T) || {pkt, P, T} <- lists:reverse(Packets)],
@todo Consider LEDBAT here
ReplyMicro = utp_util:bit32(TS - RecvTime),
set_ledbat_timer(),
N2 = utp_network:handle_advertised_window(Network, WindowSize),
N_Network = utp_network:update_our_ledbat(N2, TSDiff),
{next_state, report(connected),
State#state { network = utp_network:update_reply_micro(N_Network, ReplyMicro),
retransmit_timeout = clear_retransmit_timer(RTimeout),
buffer = utp_buffer:init_ackno(PktBuf, utp_util:bit16(PktSeqNo + 1))}};
syn_sent({pkt, _Packet, _Timing} = Pkt,
#state { connector = {From, Packets}} = State) ->
{next_state, syn_sent,
State#state {
connector = {From, [Pkt | Packets]}}};
syn_sent(close, #state {
network = Network,
retransmit_timeout = RTimeout
} = State) ->
clear_retransmit_timer(RTimeout),
Gracetime = lists:min([60, utp_network:rto(Network) * 2]),
Timer = set_retransmit_timer(Gracetime, undefined),
{next_state, syn_sent, State#state {
retransmit_timeout = Timer }};
syn_sent({timeout, TRef, {retransmit_timeout, N}},
#state { retransmit_timeout = {set, TRef},
network = Network,
connector = {From, _},
buffer = PktBuf
} = State) ->
report_timer_trigger(retransmit),
case N > ?SYN_TIMEOUT_THRESHOLD of
true ->
reply(From, {error, etimedout}),
{next_state, report(reset), State#state {retransmit_timeout = undefined}};
false ->
% Resend packet
SynPacket = utp_proto:mk_syn(),
Win = utp_buffer:advertised_window(PktBuf),
{ok, _} = utp_network:send_pkt(Win, Network, SynPacket, conn_id_recv),
{next_state, syn_sent,
State#state {
retransmit_timeout = set_retransmit_timer(N*2, undefined)
}}
end;
syn_sent(_Msg, S) ->
%% Ignore messages
?ERR([node(), async_message, syn_sent, _Msg]),
{next_state, syn_sent, S}.
@private
connected({pkt, #packet { ty = st_reset }, _},
#state { process = PRI } = State) ->
%% We received a reset packet in the connected state. This means an abrupt
%% disconnect, so move to the RESET state right away after telling people
%% we can't fulfill their requests.
N_PRI = utp_process:error_all(PRI, econnreset),
{next_state, report(reset), State#state { process = N_PRI }};
connected({pkt, #packet { ty = st_syn }, _}, State) ->
?INFO([duplicate_syn_packet, ignoring]),
{next_state, connected, State};
connected({pkt, Pkt, {TS, TSDiff, RecvTime}}, State) ->
{ok, Messages, N_Network, N_PB, N_PRI, ZWinTimeout, N_DelayAck, N_RetransTimer} =
handle_packet_incoming(connected,
Pkt, utp_util:bit32(TS - RecvTime), RecvTime, TSDiff, State),
{NextState,
N_ProcessInfo } = case proplists:get_value(got_fin, Messages) of
true ->
%% We need to tell all processes that had data to send that
%% it is now in limbo. In particular we don't know if it will
%% ever complete
utp_process:apply_senders(N_PRI,
fun(From) ->
reply(From, {error, eclosed})
end),
{report(got_fin), utp_process:clear_senders(N_PRI)};
undefined ->
{connected, N_PRI}
end,
{next_state, NextState,
State#state { buffer = N_PB,
network = N_Network,
retransmit_timeout = N_RetransTimer,
zerowindow_timeout = ZWinTimeout,
delayed_ack_timeout = N_DelayAck,
process = N_ProcessInfo }};
connected(close, #state { network = Network,
buffer = PktBuf } = State) ->
NPBuf = utp_buffer:send_fin(Network, PktBuf),
{next_state, report(fin_sent), State#state { buffer = NPBuf } };
connected({timeout, _, ledbat_timeout}, State) ->
{next_state, connected, bump_ledbat(State)};
connected({timeout, Ref, send_delayed_ack}, State) ->
{next_state, connected, trigger_delayed_ack(Ref, State)};
connected({timeout, Ref, {zerowindow_timeout, _N}},
#state {
buffer = PktBuf,
process = ProcessInfo,
network = Network,
zerowindow_timeout = {set, Ref}} = State) ->
report_timer_trigger(zerowin),
N_Network = utp_network:bump_window(Network),
{_FillMessages, ZWinTimer, N_PktBuf, N_ProcessInfo} =
fill_window(N_Network, ProcessInfo, PktBuf, undefined),
{next_state, connected,
State#state {
zerowindow_timeout = ZWinTimer,
buffer = N_PktBuf,
process = N_ProcessInfo}};
connected({timeout, Ref, {retransmit_timeout, N}},
#state {
buffer = PacketBuf,
network = Network,
retransmit_timeout = {set, Ref} = Timer} = State) ->
report_timer_trigger(retransmit),
case handle_timeout(Ref, N, PacketBuf, Network, Timer) of
stray ->
{next_state, connected, State};
gave_up ->
{next_state, report(reset), State};
{reinstalled, N_Timer, N_PB, N_Network} ->
{next_state, connected, State#state { retransmit_timeout = N_Timer,
network = N_Network,
buffer = N_PB }}
end;
connected(_Msg, State) ->
%% Ignore messages
?ERR([node(), async_message, connected, _Msg]),
{next_state, connected, State}.
@private
got_fin(close, #state {
retransmit_timeout = Timer,
network = Network } = State) ->
N_Timer = set_retransmit_timer(utp_network:rto(Network), Timer),
{next_state, report(destroy_delay), State#state { retransmit_timeout = N_Timer } };
got_fin({timeout, Ref, {retransmit_timeout, N}},
#state {
buffer = PacketBuf,
network = Network,
retransmit_timeout = Timer} = State) ->
report_timer_trigger(retransmit),
case handle_timeout(Ref, N, PacketBuf, Network, Timer) of
stray ->
{next_state, got_fin, State};
gave_up ->
{next_state, report(reset), State};
{reinstalled, N_Timer, N_PB, N_Network} ->
{next_state, got_fin, State#state { retransmit_timeout = N_Timer,
network = N_Network,
buffer = N_PB }}
end;
got_fin({timeout, Ref, send_delayed_ack}, State) ->
{next_state, got_fin, trigger_delayed_ack(Ref, State)};
got_fin({pkt, #packet { ty = st_state }, _}, State) ->
State packets incoming can be ignored . Why ? Because state packets from the other
%% end doesn't matter at this point: We got the FIN completed, so we can't send or receive
%% anymore. And all who were waiting are expunged from the receive buffer. No new can enter.
Our Timeout will move us on ( or a close ) . The other end is in the FIN_SENT state , so
%% he will only send state packets when he needs to ack some of our stuff, which he wont.
{next_state, got_fin, State};
got_fin({pkt, #packet {ty = st_reset}, _}, #state {process = Process} = State) ->
%% The other end requests that we close down the socket? Ok, lets just comply:
N_Process = utp_process:error_all(Process, econnreset),
{next_state, report(destroy), State#state { process = N_Process }, 0};
got_fin({pkt, #packet { ty = st_fin }, _}, State) ->
%% @todo We should probably send out an ACK for the FIN here since it is a retransmit
{next_state, got_fin, State};
got_fin(_Msg, State) ->
%% Ignore messages
?ERR([node(), async_message, got_fin, _Msg]),
{next_state, got_fin, State}.
@private
destroy_delay({timeout, Ref, {retransmit_timeout, _N}},
#state { retransmit_timeout = {set, Ref} } = State) ->
report_timer_trigger(retransmit),
{next_state, report(destroy), State#state { retransmit_timeout = undefined }, 0};
destroy_delay({timeout, Ref, send_delayed_ack}, State) ->
{next_state, destroy_delay, trigger_delayed_ack(Ref, State)};
destroy_delay({pkt, #packet { ty = st_fin }, _}, State) ->
{next_state, destroy_delay, State};
destroy_delay(close, State) ->
{next_state, report(destroy), State, 0};
destroy_delay(_Msg, State) ->
%% Ignore messages
?ERR([node(), async_message, destroy_delay, _Msg]),
{next_state, destroy_delay, State}.
@private
%% Die deliberately on close for now
fin_sent({pkt, #packet { ty = st_syn }, _},
State) ->
%% Quaff SYN packets if they arrive in this state. They are stray.
%% I have seen it happen in tests, however unlikely that it happens in real life.
{next_state, fin_sent, State};
fin_sent({pkt, #packet { ty = st_reset }, _},
#state { process = PRI } = State) ->
%% We received a reset packet in the connected state. This means an abrupt
%% disconnect, so move to the RESET state right away after telling people
%% we can't fulfill their requests.
N_PRI = utp_process:error_all(PRI, econnreset),
{next_state, report(destroy), State#state { process = N_PRI }, 0};
fin_sent({pkt, Pkt, {TS, TSDiff, RecvTime}}, State) ->
{ok, Messages, N_Network, N_PB, N_PRI, ZWinTimeout, N_DelayAck, N_RetransTimer} =
handle_packet_incoming(fin_sent,
Pkt, utp_util:bit32(TS - RecvTime), RecvTime, TSDiff, State),
%% Calculate the next state
N_State = State#state {
buffer = N_PB,
network = N_Network,
retransmit_timeout = N_RetransTimer,
zerowindow_timeout = ZWinTimeout,
delayed_ack_timeout = N_DelayAck,
process = N_PRI },
case proplists:get_value(fin_sent_acked, Messages) of
true ->
{next_state, report(destroy), N_State, 0};
undefined ->
{next_state, fin_sent, N_State}
end;
fin_sent({timeout, _, ledbat_timeout}, State) ->
{next_state, fin_sent, bump_ledbat(State)};
fin_sent({timeout, Ref, send_delayed_ack}, State) ->
{next_state, fin_sent, trigger_delayed_ack(Ref, State)};
fin_sent({timeout, Ref, {retransmit_timeout, N}},
#state { buffer = PacketBuf,
network = Network,
retransmit_timeout = Timer} = State) ->
report_timer_trigger(retransmit),
case handle_timeout(Ref, N, PacketBuf, Network, Timer) of
stray ->
{next_state, fin_sent, State};
gave_up ->
{next_state, report(destroy), State, 0};
{reinstalled, N_Timer, N_PB, N_Network} ->
{next_state, fin_sent, State#state { retransmit_timeout = N_Timer,
network = N_Network,
buffer = N_PB }}
end;
fin_sent(_Msg, State) ->
%% Ignore messages
?ERR([node(), async_message, fin_sent, _Msg]),
{next_state, fin_sent, State}.
@private
reset(close, State) ->
{next_state, report(destroy), State, 0};
reset(_Msg, State) ->
%% Ignore messages
?ERR([node(), async_message, reset, _Msg]),
{next_state, reset, State}.
@private
%% Die deliberately on close for now
destroy(timeout, #state { process = ProcessInfo } = State) ->
N_ProcessInfo = utp_process:error_all(ProcessInfo, econnreset),
{report(stop), normal, State#state { process = N_ProcessInfo }};
destroy(_Msg, State) ->
%% Ignore messages
?ERR([node(), async_message, destroy, _Msg]),
{next_state, destroy, State, 0}.
@private
idle(connect,
From, State = #state { network = Network,
buffer = PktBuf}) ->
{Address, Port} = utp_network:hostname_port(Network),
Conn_id_recv = utp_proto:mk_connection_id(),
gen_utp:register_process(self(), {Conn_id_recv, Address, Port}),
N_Network = utp_network:set_conn_id(Conn_id_recv + 1, Network),
SynPacket = utp_proto:mk_syn(),
send_pkt(PktBuf, N_Network, SynPacket),
{next_state, report(syn_sent),
State#state { network = N_Network,
retransmit_timeout = set_retransmit_timer(?SYN_TIMEOUT, undefined),
buffer = utp_buffer:init_seqno(PktBuf, 2),
connector = {From, []}}};
idle({accept, SYN}, _From, #state { network = Network,
options = Options,
buffer = PktBuf } = State) ->
utp:report_event(50, peer, us, utp_proto:succinct_format_packet(SYN), [{packet, SYN}]),
1 = SYN#packet.seq_no,
Conn_id_send = SYN#packet.conn_id,
N_Network = utp_network:set_conn_id(Conn_id_send, Network),
SeqNo = init_seq_no(Options),
AckPacket = utp_proto:mk_ack(SeqNo, SYN#packet.seq_no),
Win = utp_buffer:advertised_window(PktBuf),
{ok, _} = utp_network:send_pkt(Win, N_Network, AckPacket),
@todo retransmit timer here ?
set_ledbat_timer(),
utp:report_event(60, us, client, ok, []),
{reply, ok, report(connected),
State#state { network = utp_network:handle_advertised_window(N_Network, SYN),
buffer = utp_buffer:init_counters(PktBuf,
utp_util:bit16(SeqNo + 1),
utp_util:bit16(SYN#packet.seq_no + 1))}};
idle(_Msg, _From, State) ->
{reply, idle, {error, enotconn}, State}.
init_seq_no(Options) ->
case proplists:get_value(force_seq_no, Options) of
undefined -> utp_buffer:mk_random_seq_no();
K -> K
end.
send_pkt(PktBuf, N_Network, SynPacket) ->
Win = utp_buffer:advertised_window(PktBuf),
{ok, _} = utp_network:send_pkt(Win, N_Network, SynPacket, conn_id_recv).
@private
connected({recv, Length}, From, #state { process = PI,
network = Network,
delayed_ack_timeout = DelayAckT,
buffer = PKB } = State) ->
PI1 = utp_process:enqueue_receiver(From, Length, PI),
case satisfy_recvs(PI1, PKB) of
{_, N_PRI, N_PKB} ->
N_Delay = case utp_buffer:view_zerowindow_reopen(PKB, N_PKB) of
true ->
handle_send_ack(Network, N_PKB, DelayAckT,
[send_ack, no_piggyback], 0);
false ->
DelayAckT
end,
{next_state, connected, State#state { process = N_PRI,
delayed_ack_timeout = N_Delay,
buffer = N_PKB } }
end;
connected({send, Data}, From, #state {
network = Network,
process = PI,
retransmit_timeout = RTimer,
zerowindow_timeout = ZWinTimer,
buffer = PKB } = State) ->
ProcInfo = utp_process:enqueue_sender(From, Data, PI),
{FillMessages, N_ZWinTimer, PKB1, ProcInfo1} =
fill_window(Network,
ProcInfo,
PKB,
ZWinTimer),
N_RTimer = handle_send_retransmit_timer(FillMessages, Network, RTimer),
{next_state, connected, State#state {
zerowindow_timeout = N_ZWinTimer,
retransmit_timeout = N_RTimer,
process = ProcInfo1,
buffer = PKB1 }};
connected(_Msg, _From, State) ->
?ERR([sync_message, connected, _Msg, _From]),
{next_state, connected, State}.
@private
got_fin({recv, L}, _From,State) ->
{ok, Reply, NewProcessState} = drain_buffer(L, State),
{reply, Reply, got_fin, NewProcessState};
got_fin({send, _Data}, _From, State) ->
utp:report_event(60, us, client, {error, econnreset}, []),
{reply, {error, econnreset}, got_fin, State}.
@private
fin_sent({recv, L}, _From, State) ->
{ok, Reply, NewProcessState} = drain_buffer(L, State),
{reply, Reply, fin_sent, NewProcessState};
fin_sent({send, _Data}, _From, State) ->
utp:report_event(60, us, client, {error, econnreset}),
{reply, {error, econnreset}, fin_sent, State}.
@private
reset({recv, _L}, _From, State) ->
utp:report_event(60, us, client, {error, econnreset}),
{reply, {error, econnreset}, reset, State};
reset({send, _Data}, _From, State) ->
utp:report_event(60, us, client, {error, econnreset}),
{reply, {error, econnreset}, reset, State}.
@private
handle_event(_Event, StateName, State) ->
?ERR([unknown_handle_event, _Event, StateName, State]),
{next_state, StateName, State}.
@private
handle_sync_event(_Event, _From, StateName, State) ->
Reply = ok,
{reply, Reply, StateName, State}.
@private
handle_info(_Info, StateName, State) ->
{next_state, StateName, State}.
@private
terminate(_Reason, _StateName, _State) ->
ok.
@private
code_change(_OldVsn, StateName, State, _Extra) ->
{ok, StateName, State}.
%%%===================================================================
satisfy_buffer(From, 0, Res, Buffer) ->
reply(From, {ok, Res}),
{ok, Buffer};
satisfy_buffer(From, Length, Res, Buffer) ->
case utp_buffer:buffer_dequeue(Buffer) of
{ok, Bin, N_Buffer} when byte_size(Bin) =< Length ->
satisfy_buffer(From, Length - byte_size(Bin), <<Res/binary, Bin/binary>>, N_Buffer);
{ok, Bin, N_Buffer} when byte_size(Bin) > Length ->
<<Cut:Length/binary, Rest/binary>> = Bin,
satisfy_buffer(From, 0, <<Res/binary, Cut/binary>>,
utp_buffer:buffer_putback(Rest, N_Buffer));
empty ->
{rb_drained, From, Length, Res, Buffer}
end.
satisfy_recvs(Processes, Buffer) ->
case utp_process:dequeue_receiver(Processes) of
{ok, {receiver, From, Length, Res}, N_Processes} ->
case satisfy_buffer(From, Length, Res, Buffer) of
{ok, N_Buffer} ->
satisfy_recvs(N_Processes, N_Buffer);
{rb_drained, F, L, R, N_Buffer} ->
{rb_drained, utp_process:putback_receiver(F, L, R, N_Processes), N_Buffer}
end;
empty ->
{ok, Processes, Buffer}
end.
set_retransmit_timer(N, Timer) ->
set_retransmit_timer(N, N, Timer).
set_retransmit_timer(N, K, undefined) ->
report_timer_set(retransmit),
Ref = gen_fsm:start_timer(N, {retransmit_timeout, K}),
{set, Ref};
set_retransmit_timer(N, K, {set, Ref}) ->
report_timer_bump(retransmit),
gen_fsm:cancel_timer(Ref),
N_Ref = gen_fsm:start_timer(N, {retransmit_timeout, K}),
{set, N_Ref}.
clear_retransmit_timer(undefined) ->
undefined;
clear_retransmit_timer({set, Ref}) ->
report_timer_clear(retransmit),
gen_fsm:cancel_timer(Ref),
undefined.
%% @doc Handle the retransmit timer in the send direction
handle_send_retransmit_timer(Messages, Network, RetransTimer) ->
case proplists:get_value(sent_data, Messages) of
true ->
set_retransmit_timer(utp_network:rto(Network), RetransTimer);
undefined ->
%% We sent nothing out, just use the current timer
RetransTimer
end.
handle_recv_retransmit_timer(Messages, Network, RetransTimer) ->
Analyzer = fun(L) -> lists:foldl(is_set(Messages), false, L) end,
case Analyzer([data_inflight, fin_sent, sent_data]) of
true ->
set_retransmit_timer(utp_network:rto(Network), RetransTimer);
false ->
case Analyzer([all_acked]) of
true ->
clear_retransmit_timer(RetransTimer);
false ->
RetransTimer % Just pass it along with no update
end
end.
is_set(Messages) ->
fun(E, Acc) ->
case proplists:get_value(E, Messages) of
true ->
true;
undefined ->
Acc
end
end.
fill_window(Network, ProcessInfo, PktBuffer, ZWinTimer) ->
{Messages, N_PktBuffer, N_ProcessInfo} =
utp_buffer:fill_window(Network,
ProcessInfo,
PktBuffer),
%% Capture and handle the case where the other end has given up in
%% the space department of its receive buffer.
case utp_network:view_zero_window(Network) of
ok ->
{Messages, cancel_zerowin_timer(ZWinTimer), N_PktBuffer, N_ProcessInfo};
zero ->
{Messages, set_zerowin_timer(ZWinTimer), N_PktBuffer, N_ProcessInfo}
end.
cancel_zerowin_timer(undefined) -> undefined;
cancel_zerowin_timer({set, Ref}) ->
report_timer_clear(zerowin),
gen_fsm:cancel_timer(Ref),
undefined.
set_zerowin_timer(undefined) ->
report_timer_set(zerowin),
Ref = gen_fsm:start_timer(?ZERO_WINDOW_DELAY,
{zerowindow_timeout, ?ZERO_WINDOW_DELAY}),
{set, Ref};
set_zerowin_timer({set, Ref}) -> {set, Ref}. % Already set, do nothing
handle_packet_incoming(FSMState, Pkt, ReplyMicro, TimeAcked, TSDiff,
#state { buffer = PB,
process = PRI,
network = Network,
zerowindow_timeout = ZWin,
retransmit_timeout = RetransTimer,
delayed_ack_timeout = DelayAckT
}) ->
%% Handle the incoming packet
try
utp_buffer:handle_packet(FSMState, Pkt, Network, PB)
of
{ok, N_PB1, N_Network3, RecvMessages} ->
N_Network2 = utp_network:update_window(N_Network3, ReplyMicro, TimeAcked, RecvMessages, TSDiff, Pkt),
%% The packet may bump the advertised window from the peer, update
%% The incoming datagram may have payload we can deliver to an application
{_Drainage, N_PRI, N_PB} = satisfy_recvs(PRI, N_PB1),
%% Fill up the send window again with the new information
{FillMessages, ZWinTimeout, N_PB2, N_PRI2} =
fill_window(N_Network2, N_PRI, N_PB, ZWin),
Messages = RecvMessages ++ FillMessages,
N_Network = utp_network:handle_maxed_out_window(Messages, N_Network2),
%% @todo This ACK may be cancelled if we manage to push something out
%% the window, etc., but the code is currently ready for it!
%% The trick is to clear the message.
%% Send out an ACK if needed
AckedBytes = acked_bytes(Messages),
N_DelayAckT = handle_send_ack(N_Network, N_PB2,
DelayAckT,
Messages,
AckedBytes),
N_RetransTimer = handle_recv_retransmit_timer(Messages, N_Network, RetransTimer),
{ok, Messages, N_Network, N_PB2, N_PRI2, ZWinTimeout, N_DelayAckT, N_RetransTimer}
catch
throw:{error, is_far_in_future} ->
utp:report_event(90, us, is_far_in_future, [Pkt]),
{ok, [], Network, PB, PRI, ZWin, DelayAckT, RetransTimer}
end.
acked_bytes(Messages) ->
case proplists:get_value(acked, Messages) of
undefined ->
0;
Acked when is_list(Acked) ->
utp_buffer:extract_payload_size(Acked)
end.
handle_timeout(Ref, N, PacketBuf, Network, {set, Ref} = Timer) ->
case N > ?RTO_DESTROY_VALUE of
true ->
gave_up;
false ->
N_Timer = set_retransmit_timer(N*2, Timer),
N_PB = utp_buffer:retransmit_packet(PacketBuf, Network),
N_Network = utp_network:reset_window(Network),
{reinstalled, N_Timer, N_PB, N_Network}
end;
handle_timeout(_Ref, _N, _PacketBuf, _Network, _Timer) ->
?ERR([stray_retransmit_timer, _Ref, _N, _Timer]),
stray.
-spec validate_options([term()]) -> ok | badarg.
validate_options([{backlog, N} | R]) ->
case is_integer(N) of
true ->
validate_options(R);
false ->
badarg
end;
validate_options([{trace_counters, TF} | R]) when is_boolean(TF) ->
validate_options(R);
validate_options([{trace_counters, _} | _]) ->
badarg;
validate_options([{force_seq_no, N} | R]) ->
case is_integer(N) of
true when N >= 0,
N =< 16#FFFF ->
validate_options(R);
true ->
badarg;
false ->
badarg
end;
validate_options([]) ->
ok;
validate_options([_Unknown | R]) ->
%% @todo Skip unknown options silently for now.
validate_options(R).
set_ledbat_timer() ->
report_timer_set(ledbat),
gen_fsm:start_timer(timer:seconds(60), ledbat_timeout).
bump_ledbat(#state { network = Network } = State) ->
report_timer_trigger(ledbat),
N_Network = utp_network:bump_ledbat(Network),
set_ledbat_timer(),
State#state { network = N_Network }.
trigger_delayed_ack(Ref, #state {
buffer = PktBuf,
network = Network,
delayed_ack_timeout = {set, _, Ref}
} = State) ->
report_timer_trigger(delayed_ack),
utp_buffer:send_ack(Network, PktBuf),
State#state { delayed_ack_timeout = undefined }.
cancel_delayed_ack(undefined) ->
undefined; %% It was never there, ignore it
cancel_delayed_ack({set, _Count, Ref}) ->
report_timer_clear(delayed_ack),
gen_fsm:cancel_timer(Ref),
undefined.
handle_delayed_ack(undefined, AckedBytes, Network, PktBuf)
when AckedBytes >= ?DELAYED_ACK_BYTE_THRESHOLD ->
utp_buffer:send_ack(Network, PktBuf),
undefined;
handle_delayed_ack(undefined, AckedBytes, _Network, _PktBuf) ->
report_timer_set(delay_ack),
Ref = gen_fsm:start_timer(?DELAYED_ACK_TIME_THRESHOLD, send_delayed_ack),
{set, AckedBytes, Ref};
handle_delayed_ack({set, ByteCount, _Ref} = DelayAck, AckedBytes, Network, PktBuf)
when ByteCount+AckedBytes >= ?DELAYED_ACK_BYTE_THRESHOLD ->
utp_buffer:send_ack(Network, PktBuf),
cancel_delayed_ack(DelayAck);
handle_delayed_ack({set, ByteCount, Ref}, AckedBytes, _Network, _PktBuf) ->
{set, ByteCount+AckedBytes, Ref}.
%% @doc Consider if we should send out an ACK and do it if so
%% @end
handle_send_ack(Network, PktBuf, DelayAck, Messages, AckedBytes) ->
case view_ack_messages(Messages) of
nothing ->
DelayAck;
got_fin ->
utp_buffer:send_ack(Network, PktBuf),
cancel_delayed_ack(DelayAck);
no_piggyback ->
handle_delayed_ack(DelayAck, AckedBytes, Network, PktBuf);
piggybacked ->
The requested ACK is already sent as a piggyback on
%% top of a data message. There is no reason to resend it.
cancel_delayed_ack(DelayAck)
end.
view_ack_messages(Messages) ->
case proplists:get_value(send_ack, Messages) of
undefined ->
nothing;
true ->
ack_analyze_further(Messages)
end.
ack_analyze_further(Messages) ->
case proplists:get_value(got_fin, Messages) of
true ->
got_fin;
undefined ->
case proplists:get_value(no_piggyback, Messages) of
true ->
no_piggyback;
undefined ->
piggybacked
end
end.
drain_buffer(L, #state { buffer = PktBuf,
process = ProcInfo } = State) ->
true = utp_process:recv_buffer_empty(ProcInfo),
case utp_buffer:draining_receive(L, PktBuf) of
{ok, Bin, N_PktBuf} ->
utp:report_event(60, us, client, {ok, size(Bin)}, [Bin]),
{ok, {ok, Bin}, State#state { buffer = N_PktBuf}};
empty ->
utp:report_event(60, us, client, {error, eof}, []),
{ok, {error, eof}, State};
{partial_read, Bin, N_PktBuf} ->
utp:report_event(60, us, client, {error, {partial, size(Bin)}}, [Bin]),
{ok, {error, {partial, Bin}}, State#state { buffer = N_PktBuf}}
end.
report_timer_clear(Type) ->
utp:report_event(80, us, timer, {clear, Type}, []).
report_timer_trigger(Type) ->
utp:report_event(85, timer, us, {trigger, Type}, []).
report_timer_set(Type) ->
utp:report_event(80, us, timer, {set, Type}, []).
report_timer_bump(Type) ->
utp:report_event(80, us, timer, {bump, Type}, []).
report(NewState) ->
utp:report_event(55, us, NewState, []),
NewState.
| null | https://raw.githubusercontent.com/jlouis/erlang-utp/fa6cbb8831b06e7f507779dcd7a0e2e94bdbff1a/src/gen_utp_worker.erl | erlang | -------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
API
Internal API
gen_fsm callbacks
gen_fsm callback states
Default SYN packet timeout
Round trip time variance
@todo Probably dead!
Likewise!
Default add to the future when an Ack is expected
bytes
milliseconds
ms
scaled down linearly proportional to off_target. i.e. if all packets
Default timeout value for sockets where we will destroy them!
to be it seems.
skew is dealt with by observing the delay base in the other
direction, and adjusting our own upwards if the opposite direction
delay base keeps going down
ms
@todo Fix this
STATE RECORDS
----------------------------------------------------------------------
===================================================================
@doc Create a worker for a peer endpoint
@end
@doc Send a connect event
@end
@doc Send an accept event
@end
@doc Receive some bytes from the socket. Blocks until the said amount of
bytes have been read.
@end
@doc Send some bytes from the socket. Blocks until the said amount of
bytes have been sent and has been accepted by the underlying layer.
@end
@doc Send a close event
@end
Consider making it sync, but the de-facto implementation isn't
----------------------------------------------------------------------
===================================================================
gen_fsm callbacks
===================================================================
Ignore messages
We received a reset packet in the connected state. This means an abrupt
disconnect, so move to the RESET state right away after telling people
we can't fulfill their requests.
Also handle the guy making the connection
Empty the queue of packets for the new state
We reverse the list so they are in the order we got them originally
Resend packet
Ignore messages
We received a reset packet in the connected state. This means an abrupt
disconnect, so move to the RESET state right away after telling people
we can't fulfill their requests.
We need to tell all processes that had data to send that
it is now in limbo. In particular we don't know if it will
ever complete
Ignore messages
end doesn't matter at this point: We got the FIN completed, so we can't send or receive
anymore. And all who were waiting are expunged from the receive buffer. No new can enter.
he will only send state packets when he needs to ack some of our stuff, which he wont.
The other end requests that we close down the socket? Ok, lets just comply:
@todo We should probably send out an ACK for the FIN here since it is a retransmit
Ignore messages
Ignore messages
Die deliberately on close for now
Quaff SYN packets if they arrive in this state. They are stray.
I have seen it happen in tests, however unlikely that it happens in real life.
We received a reset packet in the connected state. This means an abrupt
disconnect, so move to the RESET state right away after telling people
we can't fulfill their requests.
Calculate the next state
Ignore messages
Ignore messages
Die deliberately on close for now
Ignore messages
===================================================================
@doc Handle the retransmit timer in the send direction
We sent nothing out, just use the current timer
Just pass it along with no update
Capture and handle the case where the other end has given up in
the space department of its receive buffer.
Already set, do nothing
Handle the incoming packet
The packet may bump the advertised window from the peer, update
The incoming datagram may have payload we can deliver to an application
Fill up the send window again with the new information
@todo This ACK may be cancelled if we manage to push something out
the window, etc., but the code is currently ready for it!
The trick is to clear the message.
Send out an ACK if needed
@todo Skip unknown options silently for now.
It was never there, ignore it
@doc Consider if we should send out an ACK and do it if so
@end
top of a data message. There is no reason to resend it. | @author < >
( C ) 2011 ,
Created : 19 Feb 2011 by < >
-module(gen_utp_worker).
-include("log.hrl").
-include("utp.hrl").
-behaviour(gen_fsm).
-export([start_link/4]).
Operations
-export([connect/1,
accept/2,
close/1,
recv/2,
send/2
]).
-export([
incoming/3,
reply/2
]).
-export([init/1, handle_event/3,
handle_sync_event/4, handle_info/3, terminate/3, code_change/4]).
-export([idle/2, idle/3,
syn_sent/2,
connected/2, connected/3,
got_fin/2, got_fin/3,
destroy_delay/2,
fin_sent/2, fin_sent/3,
reset/2, reset/3,
destroy/2]).
-type conn_state() :: idle | syn_sent | connected | got_fin
| destroy_delay | fin_sent | reset | destroy.
-type error_type() :: econnreset | econnrefused | etiemedout | emsgsize.
-type ret_value() :: ok | {ok, binary()} | {error, error_type()}.
-export_type([conn_state/0,
error_type/0,
ret_value/0]).
-define(SERVER, ?MODULE).
Default extensions to use when SYN / SYNACK'ing
-define(SYN_EXTS, [{ext_bits, <<0:64/integer>>}]).
-define(SYN_TIMEOUT, 3000).
-define(DEFAULT_RETRANSMIT_TIMEOUT, 3000).
-define(SYN_TIMEOUT_THRESHOLD, ?SYN_TIMEOUT*2).
Number of bytes to increase max window size by , per RTT . This is
in one window have 0 delay , window size will increase by this number .
Typically it 's less . TCP increases one MSS per RTT , which is 1500
-define(MAX_CWND_INCREASE_BYTES_PER_RTT, 3000).
-define(CUR_DELAY_SIZE, 3).
-define(RTO_DESTROY_VALUE, 30*1000).
The delay to set on Zero Windows . It is awfully high , but that is what it has
-define(ZERO_WINDOW_DELAY, 15*1000).
Experiments suggest that a clock skew of 10 ms per 325 seconds
is not impossible . Reset delay_base every 13 minutes . The clock
-define(DELAY_BASE_HISTORY, 13).
, arbitrary at the moment
-define(DEFAULT_FSM_TIMEOUT, 10*60*1000).
-record(state, { network :: utp_network:t(),
buffer :: utp_buffer:t(),
process :: utp_process:t(),
connector :: {{reference(), pid()}, [{pkt, #packet{}, term()}]},
zerowindow_timeout :: undefined | {set, reference()},
retransmit_timeout :: undefined | {set, reference()},
delayed_ack_timeout :: undefined | {set, integer(), reference()},
options = [] :: [{atom(), term()}]
}).
start_link(Socket, Addr, Port, Options) ->
gen_fsm:start_link(?MODULE, [Socket, Addr, Port, Options], []).
connect(Pid) ->
utp:report_event(60, client, us, connect, []),
sync_send_event(Pid, connect).
accept(Pid, SynPacket) ->
utp:report_event(60, client, us, accept, [SynPacket]),
sync_send_event(Pid, {accept, SynPacket}).
recv(Pid, Amount) ->
utp:report_event(60, client, us, {recv, Amount}, []),
try
gen_fsm:sync_send_event(Pid, {recv, Amount}, infinity)
catch
exit:{noproc, _} ->
{error, enoconn}
end.
send(Pid, Data) ->
utp:report_event(60, client, us, {send, size(Data)}, [Data]),
try
gen_fsm:sync_send_event(Pid, {send, Data}, infinity)
catch
exit:{noproc, _} ->
{error, enoconn}
end.
close(Pid) ->
utp:report_event(60, client, us, close, []),
gen_fsm:send_event(Pid, close).
incoming(Pid, Packet, Timing) ->
utp:report_event(50, peer, us, utp_proto:succinct_format_packet(Packet), [{packet, Packet}]),
gen_fsm:send_event(Pid, {pkt, Packet, Timing}).
reply(To, Msg) ->
utp:report_event(60, us, client, reply, [Msg]),
gen_fsm:reply(To, Msg).
sync_send_event(Pid, Event) ->
gen_fsm:sync_send_event(Pid, Event, ?DEFAULT_FSM_TIMEOUT).
@private
init([Socket, Addr, Port, Options]) ->
case validate_options(Options) of
ok ->
PktBuf = utp_buffer:mk(?DEFAULT_OPT_RECV_SZ),
ProcInfo = utp_process:mk(),
CanonAddr = utp_util:canonicalize_address(Addr),
SockInfo = utp_socket:mk(CanonAddr, Options, Port, Socket),
Network = utp_network:mk(?DEFAULT_PACKET_SIZE, SockInfo),
{ok, report(idle), #state{ network = Network,
buffer = PktBuf,
process = ProcInfo,
options= Options }};
badarg ->
{report(stop), badarg}
end.
@private
idle(close, S) ->
{next_state, report(destroy), S, 0};
idle(_Msg, S) ->
?ERR([node(), async_message, idle, _Msg]),
{next_state, idle, S}.
@private
syn_sent({pkt, #packet { ty = st_reset }, _},
#state { process = PRI,
connector = {From, _} } = State) ->
N_PRI = utp_process:error_all(PRI, econnrefused),
reply(From, econnrefused),
{next_state, report(destroy), State#state { process = N_PRI }, 0};
syn_sent({pkt, #packet { ty = st_state,
win_sz = WindowSize,
seq_no = PktSeqNo },
{TS, TSDiff, RecvTime}},
#state { network = Network,
buffer = PktBuf,
connector = {From, Packets},
retransmit_timeout = RTimeout
} = State) ->
reply(From, ok),
[incoming(self(), P, T) || {pkt, P, T} <- lists:reverse(Packets)],
@todo Consider LEDBAT here
ReplyMicro = utp_util:bit32(TS - RecvTime),
set_ledbat_timer(),
N2 = utp_network:handle_advertised_window(Network, WindowSize),
N_Network = utp_network:update_our_ledbat(N2, TSDiff),
{next_state, report(connected),
State#state { network = utp_network:update_reply_micro(N_Network, ReplyMicro),
retransmit_timeout = clear_retransmit_timer(RTimeout),
buffer = utp_buffer:init_ackno(PktBuf, utp_util:bit16(PktSeqNo + 1))}};
syn_sent({pkt, _Packet, _Timing} = Pkt,
#state { connector = {From, Packets}} = State) ->
{next_state, syn_sent,
State#state {
connector = {From, [Pkt | Packets]}}};
syn_sent(close, #state {
network = Network,
retransmit_timeout = RTimeout
} = State) ->
clear_retransmit_timer(RTimeout),
Gracetime = lists:min([60, utp_network:rto(Network) * 2]),
Timer = set_retransmit_timer(Gracetime, undefined),
{next_state, syn_sent, State#state {
retransmit_timeout = Timer }};
syn_sent({timeout, TRef, {retransmit_timeout, N}},
#state { retransmit_timeout = {set, TRef},
network = Network,
connector = {From, _},
buffer = PktBuf
} = State) ->
report_timer_trigger(retransmit),
case N > ?SYN_TIMEOUT_THRESHOLD of
true ->
reply(From, {error, etimedout}),
{next_state, report(reset), State#state {retransmit_timeout = undefined}};
false ->
SynPacket = utp_proto:mk_syn(),
Win = utp_buffer:advertised_window(PktBuf),
{ok, _} = utp_network:send_pkt(Win, Network, SynPacket, conn_id_recv),
{next_state, syn_sent,
State#state {
retransmit_timeout = set_retransmit_timer(N*2, undefined)
}}
end;
syn_sent(_Msg, S) ->
?ERR([node(), async_message, syn_sent, _Msg]),
{next_state, syn_sent, S}.
@private
connected({pkt, #packet { ty = st_reset }, _},
#state { process = PRI } = State) ->
N_PRI = utp_process:error_all(PRI, econnreset),
{next_state, report(reset), State#state { process = N_PRI }};
connected({pkt, #packet { ty = st_syn }, _}, State) ->
?INFO([duplicate_syn_packet, ignoring]),
{next_state, connected, State};
connected({pkt, Pkt, {TS, TSDiff, RecvTime}}, State) ->
{ok, Messages, N_Network, N_PB, N_PRI, ZWinTimeout, N_DelayAck, N_RetransTimer} =
handle_packet_incoming(connected,
Pkt, utp_util:bit32(TS - RecvTime), RecvTime, TSDiff, State),
{NextState,
N_ProcessInfo } = case proplists:get_value(got_fin, Messages) of
true ->
utp_process:apply_senders(N_PRI,
fun(From) ->
reply(From, {error, eclosed})
end),
{report(got_fin), utp_process:clear_senders(N_PRI)};
undefined ->
{connected, N_PRI}
end,
{next_state, NextState,
State#state { buffer = N_PB,
network = N_Network,
retransmit_timeout = N_RetransTimer,
zerowindow_timeout = ZWinTimeout,
delayed_ack_timeout = N_DelayAck,
process = N_ProcessInfo }};
connected(close, #state { network = Network,
buffer = PktBuf } = State) ->
NPBuf = utp_buffer:send_fin(Network, PktBuf),
{next_state, report(fin_sent), State#state { buffer = NPBuf } };
connected({timeout, _, ledbat_timeout}, State) ->
{next_state, connected, bump_ledbat(State)};
connected({timeout, Ref, send_delayed_ack}, State) ->
{next_state, connected, trigger_delayed_ack(Ref, State)};
connected({timeout, Ref, {zerowindow_timeout, _N}},
#state {
buffer = PktBuf,
process = ProcessInfo,
network = Network,
zerowindow_timeout = {set, Ref}} = State) ->
report_timer_trigger(zerowin),
N_Network = utp_network:bump_window(Network),
{_FillMessages, ZWinTimer, N_PktBuf, N_ProcessInfo} =
fill_window(N_Network, ProcessInfo, PktBuf, undefined),
{next_state, connected,
State#state {
zerowindow_timeout = ZWinTimer,
buffer = N_PktBuf,
process = N_ProcessInfo}};
connected({timeout, Ref, {retransmit_timeout, N}},
#state {
buffer = PacketBuf,
network = Network,
retransmit_timeout = {set, Ref} = Timer} = State) ->
report_timer_trigger(retransmit),
case handle_timeout(Ref, N, PacketBuf, Network, Timer) of
stray ->
{next_state, connected, State};
gave_up ->
{next_state, report(reset), State};
{reinstalled, N_Timer, N_PB, N_Network} ->
{next_state, connected, State#state { retransmit_timeout = N_Timer,
network = N_Network,
buffer = N_PB }}
end;
connected(_Msg, State) ->
?ERR([node(), async_message, connected, _Msg]),
{next_state, connected, State}.
@private
got_fin(close, #state {
retransmit_timeout = Timer,
network = Network } = State) ->
N_Timer = set_retransmit_timer(utp_network:rto(Network), Timer),
{next_state, report(destroy_delay), State#state { retransmit_timeout = N_Timer } };
got_fin({timeout, Ref, {retransmit_timeout, N}},
#state {
buffer = PacketBuf,
network = Network,
retransmit_timeout = Timer} = State) ->
report_timer_trigger(retransmit),
case handle_timeout(Ref, N, PacketBuf, Network, Timer) of
stray ->
{next_state, got_fin, State};
gave_up ->
{next_state, report(reset), State};
{reinstalled, N_Timer, N_PB, N_Network} ->
{next_state, got_fin, State#state { retransmit_timeout = N_Timer,
network = N_Network,
buffer = N_PB }}
end;
got_fin({timeout, Ref, send_delayed_ack}, State) ->
{next_state, got_fin, trigger_delayed_ack(Ref, State)};
got_fin({pkt, #packet { ty = st_state }, _}, State) ->
State packets incoming can be ignored . Why ? Because state packets from the other
Our Timeout will move us on ( or a close ) . The other end is in the FIN_SENT state , so
{next_state, got_fin, State};
got_fin({pkt, #packet {ty = st_reset}, _}, #state {process = Process} = State) ->
N_Process = utp_process:error_all(Process, econnreset),
{next_state, report(destroy), State#state { process = N_Process }, 0};
got_fin({pkt, #packet { ty = st_fin }, _}, State) ->
{next_state, got_fin, State};
got_fin(_Msg, State) ->
?ERR([node(), async_message, got_fin, _Msg]),
{next_state, got_fin, State}.
@private
destroy_delay({timeout, Ref, {retransmit_timeout, _N}},
#state { retransmit_timeout = {set, Ref} } = State) ->
report_timer_trigger(retransmit),
{next_state, report(destroy), State#state { retransmit_timeout = undefined }, 0};
destroy_delay({timeout, Ref, send_delayed_ack}, State) ->
{next_state, destroy_delay, trigger_delayed_ack(Ref, State)};
destroy_delay({pkt, #packet { ty = st_fin }, _}, State) ->
{next_state, destroy_delay, State};
destroy_delay(close, State) ->
{next_state, report(destroy), State, 0};
destroy_delay(_Msg, State) ->
?ERR([node(), async_message, destroy_delay, _Msg]),
{next_state, destroy_delay, State}.
@private
fin_sent({pkt, #packet { ty = st_syn }, _},
State) ->
{next_state, fin_sent, State};
fin_sent({pkt, #packet { ty = st_reset }, _},
#state { process = PRI } = State) ->
N_PRI = utp_process:error_all(PRI, econnreset),
{next_state, report(destroy), State#state { process = N_PRI }, 0};
fin_sent({pkt, Pkt, {TS, TSDiff, RecvTime}}, State) ->
{ok, Messages, N_Network, N_PB, N_PRI, ZWinTimeout, N_DelayAck, N_RetransTimer} =
handle_packet_incoming(fin_sent,
Pkt, utp_util:bit32(TS - RecvTime), RecvTime, TSDiff, State),
N_State = State#state {
buffer = N_PB,
network = N_Network,
retransmit_timeout = N_RetransTimer,
zerowindow_timeout = ZWinTimeout,
delayed_ack_timeout = N_DelayAck,
process = N_PRI },
case proplists:get_value(fin_sent_acked, Messages) of
true ->
{next_state, report(destroy), N_State, 0};
undefined ->
{next_state, fin_sent, N_State}
end;
fin_sent({timeout, _, ledbat_timeout}, State) ->
{next_state, fin_sent, bump_ledbat(State)};
fin_sent({timeout, Ref, send_delayed_ack}, State) ->
{next_state, fin_sent, trigger_delayed_ack(Ref, State)};
fin_sent({timeout, Ref, {retransmit_timeout, N}},
#state { buffer = PacketBuf,
network = Network,
retransmit_timeout = Timer} = State) ->
report_timer_trigger(retransmit),
case handle_timeout(Ref, N, PacketBuf, Network, Timer) of
stray ->
{next_state, fin_sent, State};
gave_up ->
{next_state, report(destroy), State, 0};
{reinstalled, N_Timer, N_PB, N_Network} ->
{next_state, fin_sent, State#state { retransmit_timeout = N_Timer,
network = N_Network,
buffer = N_PB }}
end;
fin_sent(_Msg, State) ->
?ERR([node(), async_message, fin_sent, _Msg]),
{next_state, fin_sent, State}.
@private
reset(close, State) ->
{next_state, report(destroy), State, 0};
reset(_Msg, State) ->
?ERR([node(), async_message, reset, _Msg]),
{next_state, reset, State}.
@private
destroy(timeout, #state { process = ProcessInfo } = State) ->
N_ProcessInfo = utp_process:error_all(ProcessInfo, econnreset),
{report(stop), normal, State#state { process = N_ProcessInfo }};
destroy(_Msg, State) ->
?ERR([node(), async_message, destroy, _Msg]),
{next_state, destroy, State, 0}.
@private
idle(connect,
From, State = #state { network = Network,
buffer = PktBuf}) ->
{Address, Port} = utp_network:hostname_port(Network),
Conn_id_recv = utp_proto:mk_connection_id(),
gen_utp:register_process(self(), {Conn_id_recv, Address, Port}),
N_Network = utp_network:set_conn_id(Conn_id_recv + 1, Network),
SynPacket = utp_proto:mk_syn(),
send_pkt(PktBuf, N_Network, SynPacket),
{next_state, report(syn_sent),
State#state { network = N_Network,
retransmit_timeout = set_retransmit_timer(?SYN_TIMEOUT, undefined),
buffer = utp_buffer:init_seqno(PktBuf, 2),
connector = {From, []}}};
idle({accept, SYN}, _From, #state { network = Network,
options = Options,
buffer = PktBuf } = State) ->
utp:report_event(50, peer, us, utp_proto:succinct_format_packet(SYN), [{packet, SYN}]),
1 = SYN#packet.seq_no,
Conn_id_send = SYN#packet.conn_id,
N_Network = utp_network:set_conn_id(Conn_id_send, Network),
SeqNo = init_seq_no(Options),
AckPacket = utp_proto:mk_ack(SeqNo, SYN#packet.seq_no),
Win = utp_buffer:advertised_window(PktBuf),
{ok, _} = utp_network:send_pkt(Win, N_Network, AckPacket),
@todo retransmit timer here ?
set_ledbat_timer(),
utp:report_event(60, us, client, ok, []),
{reply, ok, report(connected),
State#state { network = utp_network:handle_advertised_window(N_Network, SYN),
buffer = utp_buffer:init_counters(PktBuf,
utp_util:bit16(SeqNo + 1),
utp_util:bit16(SYN#packet.seq_no + 1))}};
idle(_Msg, _From, State) ->
{reply, idle, {error, enotconn}, State}.
init_seq_no(Options) ->
case proplists:get_value(force_seq_no, Options) of
undefined -> utp_buffer:mk_random_seq_no();
K -> K
end.
send_pkt(PktBuf, N_Network, SynPacket) ->
Win = utp_buffer:advertised_window(PktBuf),
{ok, _} = utp_network:send_pkt(Win, N_Network, SynPacket, conn_id_recv).
@private
connected({recv, Length}, From, #state { process = PI,
network = Network,
delayed_ack_timeout = DelayAckT,
buffer = PKB } = State) ->
PI1 = utp_process:enqueue_receiver(From, Length, PI),
case satisfy_recvs(PI1, PKB) of
{_, N_PRI, N_PKB} ->
N_Delay = case utp_buffer:view_zerowindow_reopen(PKB, N_PKB) of
true ->
handle_send_ack(Network, N_PKB, DelayAckT,
[send_ack, no_piggyback], 0);
false ->
DelayAckT
end,
{next_state, connected, State#state { process = N_PRI,
delayed_ack_timeout = N_Delay,
buffer = N_PKB } }
end;
connected({send, Data}, From, #state {
network = Network,
process = PI,
retransmit_timeout = RTimer,
zerowindow_timeout = ZWinTimer,
buffer = PKB } = State) ->
ProcInfo = utp_process:enqueue_sender(From, Data, PI),
{FillMessages, N_ZWinTimer, PKB1, ProcInfo1} =
fill_window(Network,
ProcInfo,
PKB,
ZWinTimer),
N_RTimer = handle_send_retransmit_timer(FillMessages, Network, RTimer),
{next_state, connected, State#state {
zerowindow_timeout = N_ZWinTimer,
retransmit_timeout = N_RTimer,
process = ProcInfo1,
buffer = PKB1 }};
connected(_Msg, _From, State) ->
?ERR([sync_message, connected, _Msg, _From]),
{next_state, connected, State}.
@private
got_fin({recv, L}, _From,State) ->
{ok, Reply, NewProcessState} = drain_buffer(L, State),
{reply, Reply, got_fin, NewProcessState};
got_fin({send, _Data}, _From, State) ->
utp:report_event(60, us, client, {error, econnreset}, []),
{reply, {error, econnreset}, got_fin, State}.
@private
fin_sent({recv, L}, _From, State) ->
{ok, Reply, NewProcessState} = drain_buffer(L, State),
{reply, Reply, fin_sent, NewProcessState};
fin_sent({send, _Data}, _From, State) ->
utp:report_event(60, us, client, {error, econnreset}),
{reply, {error, econnreset}, fin_sent, State}.
@private
reset({recv, _L}, _From, State) ->
utp:report_event(60, us, client, {error, econnreset}),
{reply, {error, econnreset}, reset, State};
reset({send, _Data}, _From, State) ->
utp:report_event(60, us, client, {error, econnreset}),
{reply, {error, econnreset}, reset, State}.
@private
handle_event(_Event, StateName, State) ->
?ERR([unknown_handle_event, _Event, StateName, State]),
{next_state, StateName, State}.
@private
handle_sync_event(_Event, _From, StateName, State) ->
Reply = ok,
{reply, Reply, StateName, State}.
@private
handle_info(_Info, StateName, State) ->
{next_state, StateName, State}.
@private
terminate(_Reason, _StateName, _State) ->
ok.
@private
code_change(_OldVsn, StateName, State, _Extra) ->
{ok, StateName, State}.
satisfy_buffer(From, 0, Res, Buffer) ->
reply(From, {ok, Res}),
{ok, Buffer};
satisfy_buffer(From, Length, Res, Buffer) ->
case utp_buffer:buffer_dequeue(Buffer) of
{ok, Bin, N_Buffer} when byte_size(Bin) =< Length ->
satisfy_buffer(From, Length - byte_size(Bin), <<Res/binary, Bin/binary>>, N_Buffer);
{ok, Bin, N_Buffer} when byte_size(Bin) > Length ->
<<Cut:Length/binary, Rest/binary>> = Bin,
satisfy_buffer(From, 0, <<Res/binary, Cut/binary>>,
utp_buffer:buffer_putback(Rest, N_Buffer));
empty ->
{rb_drained, From, Length, Res, Buffer}
end.
satisfy_recvs(Processes, Buffer) ->
case utp_process:dequeue_receiver(Processes) of
{ok, {receiver, From, Length, Res}, N_Processes} ->
case satisfy_buffer(From, Length, Res, Buffer) of
{ok, N_Buffer} ->
satisfy_recvs(N_Processes, N_Buffer);
{rb_drained, F, L, R, N_Buffer} ->
{rb_drained, utp_process:putback_receiver(F, L, R, N_Processes), N_Buffer}
end;
empty ->
{ok, Processes, Buffer}
end.
set_retransmit_timer(N, Timer) ->
set_retransmit_timer(N, N, Timer).
set_retransmit_timer(N, K, undefined) ->
report_timer_set(retransmit),
Ref = gen_fsm:start_timer(N, {retransmit_timeout, K}),
{set, Ref};
set_retransmit_timer(N, K, {set, Ref}) ->
report_timer_bump(retransmit),
gen_fsm:cancel_timer(Ref),
N_Ref = gen_fsm:start_timer(N, {retransmit_timeout, K}),
{set, N_Ref}.
clear_retransmit_timer(undefined) ->
undefined;
clear_retransmit_timer({set, Ref}) ->
report_timer_clear(retransmit),
gen_fsm:cancel_timer(Ref),
undefined.
handle_send_retransmit_timer(Messages, Network, RetransTimer) ->
case proplists:get_value(sent_data, Messages) of
true ->
set_retransmit_timer(utp_network:rto(Network), RetransTimer);
undefined ->
RetransTimer
end.
handle_recv_retransmit_timer(Messages, Network, RetransTimer) ->
Analyzer = fun(L) -> lists:foldl(is_set(Messages), false, L) end,
case Analyzer([data_inflight, fin_sent, sent_data]) of
true ->
set_retransmit_timer(utp_network:rto(Network), RetransTimer);
false ->
case Analyzer([all_acked]) of
true ->
clear_retransmit_timer(RetransTimer);
false ->
end
end.
is_set(Messages) ->
fun(E, Acc) ->
case proplists:get_value(E, Messages) of
true ->
true;
undefined ->
Acc
end
end.
fill_window(Network, ProcessInfo, PktBuffer, ZWinTimer) ->
{Messages, N_PktBuffer, N_ProcessInfo} =
utp_buffer:fill_window(Network,
ProcessInfo,
PktBuffer),
case utp_network:view_zero_window(Network) of
ok ->
{Messages, cancel_zerowin_timer(ZWinTimer), N_PktBuffer, N_ProcessInfo};
zero ->
{Messages, set_zerowin_timer(ZWinTimer), N_PktBuffer, N_ProcessInfo}
end.
cancel_zerowin_timer(undefined) -> undefined;
cancel_zerowin_timer({set, Ref}) ->
report_timer_clear(zerowin),
gen_fsm:cancel_timer(Ref),
undefined.
set_zerowin_timer(undefined) ->
report_timer_set(zerowin),
Ref = gen_fsm:start_timer(?ZERO_WINDOW_DELAY,
{zerowindow_timeout, ?ZERO_WINDOW_DELAY}),
{set, Ref};
handle_packet_incoming(FSMState, Pkt, ReplyMicro, TimeAcked, TSDiff,
#state { buffer = PB,
process = PRI,
network = Network,
zerowindow_timeout = ZWin,
retransmit_timeout = RetransTimer,
delayed_ack_timeout = DelayAckT
}) ->
try
utp_buffer:handle_packet(FSMState, Pkt, Network, PB)
of
{ok, N_PB1, N_Network3, RecvMessages} ->
N_Network2 = utp_network:update_window(N_Network3, ReplyMicro, TimeAcked, RecvMessages, TSDiff, Pkt),
{_Drainage, N_PRI, N_PB} = satisfy_recvs(PRI, N_PB1),
{FillMessages, ZWinTimeout, N_PB2, N_PRI2} =
fill_window(N_Network2, N_PRI, N_PB, ZWin),
Messages = RecvMessages ++ FillMessages,
N_Network = utp_network:handle_maxed_out_window(Messages, N_Network2),
AckedBytes = acked_bytes(Messages),
N_DelayAckT = handle_send_ack(N_Network, N_PB2,
DelayAckT,
Messages,
AckedBytes),
N_RetransTimer = handle_recv_retransmit_timer(Messages, N_Network, RetransTimer),
{ok, Messages, N_Network, N_PB2, N_PRI2, ZWinTimeout, N_DelayAckT, N_RetransTimer}
catch
throw:{error, is_far_in_future} ->
utp:report_event(90, us, is_far_in_future, [Pkt]),
{ok, [], Network, PB, PRI, ZWin, DelayAckT, RetransTimer}
end.
acked_bytes(Messages) ->
case proplists:get_value(acked, Messages) of
undefined ->
0;
Acked when is_list(Acked) ->
utp_buffer:extract_payload_size(Acked)
end.
handle_timeout(Ref, N, PacketBuf, Network, {set, Ref} = Timer) ->
case N > ?RTO_DESTROY_VALUE of
true ->
gave_up;
false ->
N_Timer = set_retransmit_timer(N*2, Timer),
N_PB = utp_buffer:retransmit_packet(PacketBuf, Network),
N_Network = utp_network:reset_window(Network),
{reinstalled, N_Timer, N_PB, N_Network}
end;
handle_timeout(_Ref, _N, _PacketBuf, _Network, _Timer) ->
?ERR([stray_retransmit_timer, _Ref, _N, _Timer]),
stray.
-spec validate_options([term()]) -> ok | badarg.
validate_options([{backlog, N} | R]) ->
case is_integer(N) of
true ->
validate_options(R);
false ->
badarg
end;
validate_options([{trace_counters, TF} | R]) when is_boolean(TF) ->
validate_options(R);
validate_options([{trace_counters, _} | _]) ->
badarg;
validate_options([{force_seq_no, N} | R]) ->
case is_integer(N) of
true when N >= 0,
N =< 16#FFFF ->
validate_options(R);
true ->
badarg;
false ->
badarg
end;
validate_options([]) ->
ok;
validate_options([_Unknown | R]) ->
validate_options(R).
set_ledbat_timer() ->
report_timer_set(ledbat),
gen_fsm:start_timer(timer:seconds(60), ledbat_timeout).
bump_ledbat(#state { network = Network } = State) ->
report_timer_trigger(ledbat),
N_Network = utp_network:bump_ledbat(Network),
set_ledbat_timer(),
State#state { network = N_Network }.
trigger_delayed_ack(Ref, #state {
buffer = PktBuf,
network = Network,
delayed_ack_timeout = {set, _, Ref}
} = State) ->
report_timer_trigger(delayed_ack),
utp_buffer:send_ack(Network, PktBuf),
State#state { delayed_ack_timeout = undefined }.
cancel_delayed_ack(undefined) ->
cancel_delayed_ack({set, _Count, Ref}) ->
report_timer_clear(delayed_ack),
gen_fsm:cancel_timer(Ref),
undefined.
handle_delayed_ack(undefined, AckedBytes, Network, PktBuf)
when AckedBytes >= ?DELAYED_ACK_BYTE_THRESHOLD ->
utp_buffer:send_ack(Network, PktBuf),
undefined;
handle_delayed_ack(undefined, AckedBytes, _Network, _PktBuf) ->
report_timer_set(delay_ack),
Ref = gen_fsm:start_timer(?DELAYED_ACK_TIME_THRESHOLD, send_delayed_ack),
{set, AckedBytes, Ref};
handle_delayed_ack({set, ByteCount, _Ref} = DelayAck, AckedBytes, Network, PktBuf)
when ByteCount+AckedBytes >= ?DELAYED_ACK_BYTE_THRESHOLD ->
utp_buffer:send_ack(Network, PktBuf),
cancel_delayed_ack(DelayAck);
handle_delayed_ack({set, ByteCount, Ref}, AckedBytes, _Network, _PktBuf) ->
{set, ByteCount+AckedBytes, Ref}.
handle_send_ack(Network, PktBuf, DelayAck, Messages, AckedBytes) ->
case view_ack_messages(Messages) of
nothing ->
DelayAck;
got_fin ->
utp_buffer:send_ack(Network, PktBuf),
cancel_delayed_ack(DelayAck);
no_piggyback ->
handle_delayed_ack(DelayAck, AckedBytes, Network, PktBuf);
piggybacked ->
The requested ACK is already sent as a piggyback on
cancel_delayed_ack(DelayAck)
end.
view_ack_messages(Messages) ->
case proplists:get_value(send_ack, Messages) of
undefined ->
nothing;
true ->
ack_analyze_further(Messages)
end.
ack_analyze_further(Messages) ->
case proplists:get_value(got_fin, Messages) of
true ->
got_fin;
undefined ->
case proplists:get_value(no_piggyback, Messages) of
true ->
no_piggyback;
undefined ->
piggybacked
end
end.
drain_buffer(L, #state { buffer = PktBuf,
process = ProcInfo } = State) ->
true = utp_process:recv_buffer_empty(ProcInfo),
case utp_buffer:draining_receive(L, PktBuf) of
{ok, Bin, N_PktBuf} ->
utp:report_event(60, us, client, {ok, size(Bin)}, [Bin]),
{ok, {ok, Bin}, State#state { buffer = N_PktBuf}};
empty ->
utp:report_event(60, us, client, {error, eof}, []),
{ok, {error, eof}, State};
{partial_read, Bin, N_PktBuf} ->
utp:report_event(60, us, client, {error, {partial, size(Bin)}}, [Bin]),
{ok, {error, {partial, Bin}}, State#state { buffer = N_PktBuf}}
end.
report_timer_clear(Type) ->
utp:report_event(80, us, timer, {clear, Type}, []).
report_timer_trigger(Type) ->
utp:report_event(85, timer, us, {trigger, Type}, []).
report_timer_set(Type) ->
utp:report_event(80, us, timer, {set, Type}, []).
report_timer_bump(Type) ->
utp:report_event(80, us, timer, {bump, Type}, []).
report(NewState) ->
utp:report_event(55, us, NewState, []),
NewState.
|
7d85d4a61fce7c5f7079a370db4cba869d4ecf0bdd6cbf2fe9ea78b261114117 | pfdietz/ansi-test | bit-andc1.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Sun Jan 26 18:56:39 2003
;;;; Contains: Tests of BIT-ANDC1
(deftest bit-andc1.1
(let* ((s1 (make-array nil :initial-element 0 :element-type 'bit))
(s2 (make-array nil :initial-element 0 :element-type 'bit)))
(values (bit-andc1 s1 s2) s1 s2))
#0a0
#0a0
#0a0)
(deftest bit-andc1.2
(let* ((s1 (make-array nil :initial-element 1 :element-type 'bit))
(s2 (make-array nil :initial-element 0 :element-type 'bit)))
(values (bit-andc1 s1 s2) s1 s2))
#0a0
#0a1
#0a0)
(deftest bit-andc1.3
(let* ((s1 (make-array nil :initial-element 0 :element-type 'bit))
(s2 (make-array nil :initial-element 1 :element-type 'bit)))
(values (bit-andc1 s1 s2) s1 s2))
#0a1
#0a0
#0a1)
(deftest bit-andc1.4
(let* ((s1 (make-array nil :initial-element 1 :element-type 'bit))
(s2 (make-array nil :initial-element 1 :element-type 'bit)))
(values (bit-andc1 s1 s2) s1 s2))
#0a0
#0a1
#0a1)
(deftest bit-andc1.5
(let* ((s1 (make-array nil :initial-element 0 :element-type 'bit))
(s2 (make-array nil :initial-element 0 :element-type 'bit))
(s3 (make-array nil :initial-element 1 :element-type 'bit))
(result (bit-andc1 s1 s2 s3)))
(values s1 s2 s3 result (eqt s3 result)))
#0a0
#0a0
#0a0
#0a0
t)
(deftest bit-andc1.6
(let* ((s1 (make-array nil :initial-element 0 :element-type 'bit))
(s2 (make-array nil :initial-element 1 :element-type 'bit))
(s3 (make-array nil :initial-element 0 :element-type 'bit))
(result (bit-andc1 s1 s2 s3)))
(values s1 s2 s3 result (eqt s3 result)))
#0a0
#0a1
#0a1
#0a1
t)
(deftest bit-andc1.7
(let* ((s1 (make-array nil :initial-element 1 :element-type 'bit))
(s2 (make-array nil :initial-element 0 :element-type 'bit))
(result (bit-andc1 s1 s2 t)))
(values s1 s2 result (eqt s1 result)))
#0a0
#0a0
#0a0
t)
;;; Tests on bit vectors
(deftest bit-andc1.8
(let ((a1 (copy-seq #*0011))
(a2 (copy-seq #*0101)))
(values (check-values (bit-andc1 a1 a2)) a1 a2))
#*0100 #*0011 #*0101)
(deftest bit-andc1.9
(let* ((a1 (copy-seq #*0011))
(a2 (copy-seq #*0101))
(result (check-values (bit-andc1 a1 a2 t))))
(values result a1 a2 (eqt result a1)))
#*0100 #*0100 #*0101 t)
(deftest bit-andc1.10
(let* ((a1 (copy-seq #*0011))
(a2 (copy-seq #*0101))
(a3 (copy-seq #*0000))
(result (check-values (bit-andc1 a1 a2 a3))))
(values result a1 a2 a3 (eqt result a3)))
#*0100 #*0011 #*0101 #*0100 t)
(deftest bit-andc1.11
(let ((a1 (copy-seq #*0011))
(a2 (copy-seq #*0101)))
(values (check-values (bit-andc1 a1 a2 nil)) a1 a2))
#*0100 #*0011 #*0101)
;;; Tests on bit arrays
(deftest bit-andc1.12
(let* ((a1 (make-array '(2 2) :element-type 'bit
:initial-contents '((0 1)(0 1))))
(a2 (make-array '(2 2) :element-type 'bit
:initial-contents '((0 0)(1 1))))
(result (bit-andc1 a1 a2)))
(values a1 a2 result))
#2a((0 1)(0 1))
#2a((0 0)(1 1))
#2a((0 0)(1 0)))
(deftest bit-andc1.13
(let* ((a1 (make-array '(2 2) :element-type 'bit
:initial-contents '((0 1)(0 1))))
(a2 (make-array '(2 2) :element-type 'bit
:initial-contents '((0 0)(1 1))))
(result (bit-andc1 a1 a2 t)))
(values a1 a2 result))
#2a((0 0)(1 0))
#2a((0 0)(1 1))
#2a((0 0)(1 0)))
(deftest bit-andc1.14
(let* ((a1 (make-array '(2 2) :element-type 'bit
:initial-contents '((0 1)(0 1))))
(a2 (make-array '(2 2) :element-type 'bit
:initial-contents '((0 0)(1 1))))
(result (bit-andc1 a1 a2 nil)))
(values a1 a2 result))
#2a((0 1)(0 1))
#2a((0 0)(1 1))
#2a((0 0)(1 0)))
(deftest bit-andc1.15
(let* ((a1 (make-array '(2 2) :element-type 'bit
:initial-contents '((0 1)(0 1))))
(a2 (make-array '(2 2) :element-type 'bit
:initial-contents '((0 0)(1 1))))
(a3 (make-array '(2 2) :element-type 'bit
:initial-contents '((0 0)(0 0))))
(result (bit-andc1 a1 a2 a3)))
(values a1 a2 a3 result))
#2a((0 1)(0 1))
#2a((0 0)(1 1))
#2a((0 0)(1 0))
#2a((0 0)(1 0)))
;;; Adjustable arrays
(deftest bit-andc1.16
(let* ((a1 (make-array '(2 2) :element-type 'bit
:initial-contents '((0 1)(0 1))
:adjustable t))
(a2 (make-array '(2 2) :element-type 'bit
:initial-contents '((0 0)(1 1))
:adjustable t))
(result (bit-andc1 a1 a2)))
(values a1 a2 result))
#2a((0 1)(0 1))
#2a((0 0)(1 1))
#2a((0 0)(1 0)))
;;; Displaced arrays
(deftest bit-andc1.17
(let* ((a0 (make-array '(8) :element-type 'bit
:initial-contents '(0 1 0 1 0 0 1 1)))
(a1 (make-array '(2 2) :element-type 'bit
:displaced-to a0
:displaced-index-offset 0))
(a2 (make-array '(2 2) :element-type 'bit
:displaced-to a0
:displaced-index-offset 4))
(result (bit-andc1 a1 a2)))
(values a0 a1 a2 result))
#*01010011
#2a((0 1)(0 1))
#2a((0 0)(1 1))
#2a((0 0)(1 0)))
(deftest bit-andc1.18
(let* ((a0 (make-array '(8) :element-type 'bit
:initial-contents '(0 1 0 1 0 0 1 1)))
(a1 (make-array '(2 2) :element-type 'bit
:displaced-to a0
:displaced-index-offset 0))
(a2 (make-array '(2 2) :element-type 'bit
:displaced-to a0
:displaced-index-offset 4))
(result (bit-andc1 a1 a2 t)))
(values a0 a1 a2 result))
#*00100011
#2a((0 0)(1 0))
#2a((0 0)(1 1))
#2a((0 0)(1 0)))
(deftest bit-andc1.19
(let* ((a0 (make-array '(12) :element-type 'bit
:initial-contents '(0 1 0 1 0 0 1 1 1 1 1 0)))
(a1 (make-array '(2 2) :element-type 'bit
:displaced-to a0
:displaced-index-offset 0))
(a2 (make-array '(2 2) :element-type 'bit
:displaced-to a0
:displaced-index-offset 4))
(a3 (make-array '(2 2) :element-type 'bit
:displaced-to a0
:displaced-index-offset 8))
(result (bit-andc1 a1 a2 a3)))
(values a0 a1 a2 result))
#*010100110010
#2a((0 1)(0 1))
#2a((0 0)(1 1))
#2a((0 0)(1 0)))
(deftest bit-andc1.20
(macrolet ((%m (z) z)) (bit-andc1 (expand-in-current-env (%m #*0011)) #*0101))
#*0100)
(deftest bit-andc1.21
(macrolet ((%m (z) z)) (bit-andc1 #*1010 (expand-in-current-env (%m #*1100))))
#*0100)
(deftest bit-andc1.22
(macrolet ((%m (z) z)) (bit-andc1 #*10100011 #*01101010
(expand-in-current-env (%m nil))))
#*01001000)
(deftest bit-andc1.order.1
(let* ((s1 (make-array 1 :initial-element 0 :element-type 'bit))
(s2 (make-array 1 :initial-element 0 :element-type 'bit))
(x 0) y z)
(values
(bit-andc1 (progn (setf y (incf x)) s1)
(progn (setf z (incf x)) s2))
x y z))
#*0 2 1 2)
(def-fold-test bit-andc1.fold.1 (bit-andc1 #*10010 #*01011))
;;; Random tests
(deftest bit-andc1.random.1
(bit-random-test-fn #'bit-andc1 #'logandc1)
nil)
;;; Error tests
(deftest bit-andc1.error.1
(signals-error (bit-andc1) program-error)
t)
(deftest bit-andc1.error.2
(signals-error (bit-andc1 #*000) program-error)
t)
(deftest bit-andc1.error.3
(signals-error (bit-andc1 #*000 #*0100 nil nil)
program-error)
t)
| null | https://raw.githubusercontent.com/pfdietz/ansi-test/3f4b9d31c3408114f0467eaeca4fd13b28e2ce31/arrays/bit-andc1.lsp | lisp | -*- Mode: Lisp -*-
Contains: Tests of BIT-ANDC1
Tests on bit vectors
Tests on bit arrays
Adjustable arrays
Displaced arrays
Random tests
Error tests | Author :
Created : Sun Jan 26 18:56:39 2003
(deftest bit-andc1.1
(let* ((s1 (make-array nil :initial-element 0 :element-type 'bit))
(s2 (make-array nil :initial-element 0 :element-type 'bit)))
(values (bit-andc1 s1 s2) s1 s2))
#0a0
#0a0
#0a0)
(deftest bit-andc1.2
(let* ((s1 (make-array nil :initial-element 1 :element-type 'bit))
(s2 (make-array nil :initial-element 0 :element-type 'bit)))
(values (bit-andc1 s1 s2) s1 s2))
#0a0
#0a1
#0a0)
(deftest bit-andc1.3
(let* ((s1 (make-array nil :initial-element 0 :element-type 'bit))
(s2 (make-array nil :initial-element 1 :element-type 'bit)))
(values (bit-andc1 s1 s2) s1 s2))
#0a1
#0a0
#0a1)
(deftest bit-andc1.4
(let* ((s1 (make-array nil :initial-element 1 :element-type 'bit))
(s2 (make-array nil :initial-element 1 :element-type 'bit)))
(values (bit-andc1 s1 s2) s1 s2))
#0a0
#0a1
#0a1)
(deftest bit-andc1.5
(let* ((s1 (make-array nil :initial-element 0 :element-type 'bit))
(s2 (make-array nil :initial-element 0 :element-type 'bit))
(s3 (make-array nil :initial-element 1 :element-type 'bit))
(result (bit-andc1 s1 s2 s3)))
(values s1 s2 s3 result (eqt s3 result)))
#0a0
#0a0
#0a0
#0a0
t)
(deftest bit-andc1.6
(let* ((s1 (make-array nil :initial-element 0 :element-type 'bit))
(s2 (make-array nil :initial-element 1 :element-type 'bit))
(s3 (make-array nil :initial-element 0 :element-type 'bit))
(result (bit-andc1 s1 s2 s3)))
(values s1 s2 s3 result (eqt s3 result)))
#0a0
#0a1
#0a1
#0a1
t)
(deftest bit-andc1.7
(let* ((s1 (make-array nil :initial-element 1 :element-type 'bit))
(s2 (make-array nil :initial-element 0 :element-type 'bit))
(result (bit-andc1 s1 s2 t)))
(values s1 s2 result (eqt s1 result)))
#0a0
#0a0
#0a0
t)
(deftest bit-andc1.8
(let ((a1 (copy-seq #*0011))
(a2 (copy-seq #*0101)))
(values (check-values (bit-andc1 a1 a2)) a1 a2))
#*0100 #*0011 #*0101)
(deftest bit-andc1.9
(let* ((a1 (copy-seq #*0011))
(a2 (copy-seq #*0101))
(result (check-values (bit-andc1 a1 a2 t))))
(values result a1 a2 (eqt result a1)))
#*0100 #*0100 #*0101 t)
(deftest bit-andc1.10
(let* ((a1 (copy-seq #*0011))
(a2 (copy-seq #*0101))
(a3 (copy-seq #*0000))
(result (check-values (bit-andc1 a1 a2 a3))))
(values result a1 a2 a3 (eqt result a3)))
#*0100 #*0011 #*0101 #*0100 t)
(deftest bit-andc1.11
(let ((a1 (copy-seq #*0011))
(a2 (copy-seq #*0101)))
(values (check-values (bit-andc1 a1 a2 nil)) a1 a2))
#*0100 #*0011 #*0101)
(deftest bit-andc1.12
(let* ((a1 (make-array '(2 2) :element-type 'bit
:initial-contents '((0 1)(0 1))))
(a2 (make-array '(2 2) :element-type 'bit
:initial-contents '((0 0)(1 1))))
(result (bit-andc1 a1 a2)))
(values a1 a2 result))
#2a((0 1)(0 1))
#2a((0 0)(1 1))
#2a((0 0)(1 0)))
(deftest bit-andc1.13
(let* ((a1 (make-array '(2 2) :element-type 'bit
:initial-contents '((0 1)(0 1))))
(a2 (make-array '(2 2) :element-type 'bit
:initial-contents '((0 0)(1 1))))
(result (bit-andc1 a1 a2 t)))
(values a1 a2 result))
#2a((0 0)(1 0))
#2a((0 0)(1 1))
#2a((0 0)(1 0)))
(deftest bit-andc1.14
(let* ((a1 (make-array '(2 2) :element-type 'bit
:initial-contents '((0 1)(0 1))))
(a2 (make-array '(2 2) :element-type 'bit
:initial-contents '((0 0)(1 1))))
(result (bit-andc1 a1 a2 nil)))
(values a1 a2 result))
#2a((0 1)(0 1))
#2a((0 0)(1 1))
#2a((0 0)(1 0)))
(deftest bit-andc1.15
(let* ((a1 (make-array '(2 2) :element-type 'bit
:initial-contents '((0 1)(0 1))))
(a2 (make-array '(2 2) :element-type 'bit
:initial-contents '((0 0)(1 1))))
(a3 (make-array '(2 2) :element-type 'bit
:initial-contents '((0 0)(0 0))))
(result (bit-andc1 a1 a2 a3)))
(values a1 a2 a3 result))
#2a((0 1)(0 1))
#2a((0 0)(1 1))
#2a((0 0)(1 0))
#2a((0 0)(1 0)))
(deftest bit-andc1.16
(let* ((a1 (make-array '(2 2) :element-type 'bit
:initial-contents '((0 1)(0 1))
:adjustable t))
(a2 (make-array '(2 2) :element-type 'bit
:initial-contents '((0 0)(1 1))
:adjustable t))
(result (bit-andc1 a1 a2)))
(values a1 a2 result))
#2a((0 1)(0 1))
#2a((0 0)(1 1))
#2a((0 0)(1 0)))
(deftest bit-andc1.17
(let* ((a0 (make-array '(8) :element-type 'bit
:initial-contents '(0 1 0 1 0 0 1 1)))
(a1 (make-array '(2 2) :element-type 'bit
:displaced-to a0
:displaced-index-offset 0))
(a2 (make-array '(2 2) :element-type 'bit
:displaced-to a0
:displaced-index-offset 4))
(result (bit-andc1 a1 a2)))
(values a0 a1 a2 result))
#*01010011
#2a((0 1)(0 1))
#2a((0 0)(1 1))
#2a((0 0)(1 0)))
(deftest bit-andc1.18
(let* ((a0 (make-array '(8) :element-type 'bit
:initial-contents '(0 1 0 1 0 0 1 1)))
(a1 (make-array '(2 2) :element-type 'bit
:displaced-to a0
:displaced-index-offset 0))
(a2 (make-array '(2 2) :element-type 'bit
:displaced-to a0
:displaced-index-offset 4))
(result (bit-andc1 a1 a2 t)))
(values a0 a1 a2 result))
#*00100011
#2a((0 0)(1 0))
#2a((0 0)(1 1))
#2a((0 0)(1 0)))
(deftest bit-andc1.19
(let* ((a0 (make-array '(12) :element-type 'bit
:initial-contents '(0 1 0 1 0 0 1 1 1 1 1 0)))
(a1 (make-array '(2 2) :element-type 'bit
:displaced-to a0
:displaced-index-offset 0))
(a2 (make-array '(2 2) :element-type 'bit
:displaced-to a0
:displaced-index-offset 4))
(a3 (make-array '(2 2) :element-type 'bit
:displaced-to a0
:displaced-index-offset 8))
(result (bit-andc1 a1 a2 a3)))
(values a0 a1 a2 result))
#*010100110010
#2a((0 1)(0 1))
#2a((0 0)(1 1))
#2a((0 0)(1 0)))
(deftest bit-andc1.20
(macrolet ((%m (z) z)) (bit-andc1 (expand-in-current-env (%m #*0011)) #*0101))
#*0100)
(deftest bit-andc1.21
(macrolet ((%m (z) z)) (bit-andc1 #*1010 (expand-in-current-env (%m #*1100))))
#*0100)
(deftest bit-andc1.22
(macrolet ((%m (z) z)) (bit-andc1 #*10100011 #*01101010
(expand-in-current-env (%m nil))))
#*01001000)
(deftest bit-andc1.order.1
(let* ((s1 (make-array 1 :initial-element 0 :element-type 'bit))
(s2 (make-array 1 :initial-element 0 :element-type 'bit))
(x 0) y z)
(values
(bit-andc1 (progn (setf y (incf x)) s1)
(progn (setf z (incf x)) s2))
x y z))
#*0 2 1 2)
(def-fold-test bit-andc1.fold.1 (bit-andc1 #*10010 #*01011))
(deftest bit-andc1.random.1
(bit-random-test-fn #'bit-andc1 #'logandc1)
nil)
(deftest bit-andc1.error.1
(signals-error (bit-andc1) program-error)
t)
(deftest bit-andc1.error.2
(signals-error (bit-andc1 #*000) program-error)
t)
(deftest bit-andc1.error.3
(signals-error (bit-andc1 #*000 #*0100 nil nil)
program-error)
t)
|
7e19b31789190a795211ce0cf56f41364ac182e73c06ad03807735fe193019fc | input-output-hk/marlowe-cardano | Spec.hs | module Main
( main
) where
import Spec.Actus.Examples
import Test.Tasty
main :: IO ()
main =
defaultMain $
testGroup
"ACTUS test cases"
[ testGroup
"ACTUS examples"
[ Spec.Actus.Examples.tests
]
]
| null | https://raw.githubusercontent.com/input-output-hk/marlowe-cardano/78a3dbb1cd692146b7d1a32e1e66faed884f2432/marlowe-actus/test/Spec.hs | haskell | module Main
( main
) where
import Spec.Actus.Examples
import Test.Tasty
main :: IO ()
main =
defaultMain $
testGroup
"ACTUS test cases"
[ testGroup
"ACTUS examples"
[ Spec.Actus.Examples.tests
]
]
| |
12f044815ffb086493ab90e97e108d725d3d65c7b0ba54e7ca0927c3dbdf5241 | aeternity/aeternity | aemon_config.erl | -module(aemon_config).
%% API
-export([ privkey/0
, pubkey/0
, is_active/0
, amount/0
, autostart/0
, interval/0
, ttl/0
]).
%% ==================================================================
%% API
pubkey() ->
raw_key(<<"pubkey">>, publisher_pubkey, <<>>).
privkey() ->
raw_key(<<"privkey">>, publisher_privkey, <<>>).
is_active() ->
case pubkey() of
<<>> ->
false;
_ ->
env([<<"active">>], active, false)
end.
autostart() ->
case privkey() of
<<>> ->
false;
_ ->
env(<<"autostart">>, publisher_autostart, false)
end.
amount() ->
env(<<"amount">>, publisher_spend_amount, 20000).
interval() ->
env(<<"interval">>, publisher_interval, 10000).
ttl() ->
env(<<"ttl">>, publisher_spend_ttl, 10).
%% ==================================================================
%% internal functions
raw_key(YKey, SKey, Default) ->
Value = env(YKey, SKey, Default),
raw_key(Value).
raw_key(<<>>) ->
<<>>;
raw_key(Raw) ->
{_, Key} = aeser_api_encoder:decode(Raw),
Key.
env(YamlKey, Key, Default) when is_binary(YamlKey) ->
env([<<"publisher">>, YamlKey], Key, Default);
env(YamlKey, Key, Default) ->
aeu_env:user_config_or_env([<<"monitoring">> | YamlKey], aemon, Key, Default).
| null | https://raw.githubusercontent.com/aeternity/aeternity/b7ce6ae15dab7fa22287c2da3d4405c29bb4edd7/apps/aemon/src/aemon_config.erl | erlang | API
==================================================================
API
==================================================================
internal functions | -module(aemon_config).
-export([ privkey/0
, pubkey/0
, is_active/0
, amount/0
, autostart/0
, interval/0
, ttl/0
]).
pubkey() ->
raw_key(<<"pubkey">>, publisher_pubkey, <<>>).
privkey() ->
raw_key(<<"privkey">>, publisher_privkey, <<>>).
is_active() ->
case pubkey() of
<<>> ->
false;
_ ->
env([<<"active">>], active, false)
end.
autostart() ->
case privkey() of
<<>> ->
false;
_ ->
env(<<"autostart">>, publisher_autostart, false)
end.
amount() ->
env(<<"amount">>, publisher_spend_amount, 20000).
interval() ->
env(<<"interval">>, publisher_interval, 10000).
ttl() ->
env(<<"ttl">>, publisher_spend_ttl, 10).
raw_key(YKey, SKey, Default) ->
Value = env(YKey, SKey, Default),
raw_key(Value).
raw_key(<<>>) ->
<<>>;
raw_key(Raw) ->
{_, Key} = aeser_api_encoder:decode(Raw),
Key.
env(YamlKey, Key, Default) when is_binary(YamlKey) ->
env([<<"publisher">>, YamlKey], Key, Default);
env(YamlKey, Key, Default) ->
aeu_env:user_config_or_env([<<"monitoring">> | YamlKey], aemon, Key, Default).
|
c69d9bcfabeba5f05eaa2412e4c12773be9628bcc706977e3fcc7b96b0b4cf57 | Mayvenn/storefront | blog.cljc | (ns homepage.ui.blog
(:require [clojure.string :refer [join split]]
[storefront.component :as c]
[storefront.components.ui :as ui]
[storefront.platform.component-utils :as utils]))
(c/defcomponent organism
[{:blog/keys [id target heading ucare-id date read-time beginning author] } _ _]
(when heading
[:div.mx-auto.flex-on-tb-dt.max-1080
{:key (str "blog-" id)}
[:a
{:href target
:data-test (str "to-" id)
:aria-label heading}
(ui/defer-ucare-img {:class "block col-12"
:smart-crop "600x400"
:alt ""}
ucare-id)]
[:div.p3.col-9-on-tb-dt
[:h2.canela.title-1.mb2
[:a.inherit-color {:href target} heading]]
[:div.flex.mt2.content-3.shout
[:div.mr2 author]
[:div.dark-dark-gray date " • " read-time]]
[:div.pt4 beginning]
[:div.shout.col-8.pt3 (ui/button-medium-primary
{:href target
:data-test (str "go-to-" id)}
"Read More")]]]))
| null | https://raw.githubusercontent.com/Mayvenn/storefront/e3fdf346cea341e9dc9a6e2c8c5c48529f966b22/src-cljc/homepage/ui/blog.cljc | clojure | (ns homepage.ui.blog
(:require [clojure.string :refer [join split]]
[storefront.component :as c]
[storefront.components.ui :as ui]
[storefront.platform.component-utils :as utils]))
(c/defcomponent organism
[{:blog/keys [id target heading ucare-id date read-time beginning author] } _ _]
(when heading
[:div.mx-auto.flex-on-tb-dt.max-1080
{:key (str "blog-" id)}
[:a
{:href target
:data-test (str "to-" id)
:aria-label heading}
(ui/defer-ucare-img {:class "block col-12"
:smart-crop "600x400"
:alt ""}
ucare-id)]
[:div.p3.col-9-on-tb-dt
[:h2.canela.title-1.mb2
[:a.inherit-color {:href target} heading]]
[:div.flex.mt2.content-3.shout
[:div.mr2 author]
[:div.dark-dark-gray date " • " read-time]]
[:div.pt4 beginning]
[:div.shout.col-8.pt3 (ui/button-medium-primary
{:href target
:data-test (str "go-to-" id)}
"Read More")]]]))
| |
dd2a63a5d2bc5eacf1cd64967119f6c82e572634c3b3e4128cb6226391fe245d | clojure-emacs/refactor-nrepl | four.clj | (ns com.example.four
(:require [clojure.string :refer [split join]]
[com.example.three :refer [fn-with-println thre]]
[com.example.twenty-four :refer [stuff more-stuff]]))
(defn some-fn-with-split []
(split "foo:bar:baz" #":"))
(def registry
{:fn-with-println #'fn-with-println})
(thre)
(stuff)
(more-stuff)
| null | https://raw.githubusercontent.com/clojure-emacs/refactor-nrepl/8457b0341fdb220d4cba577ed150565e4d103364/testproject/src/com/example/four.clj | clojure | (ns com.example.four
(:require [clojure.string :refer [split join]]
[com.example.three :refer [fn-with-println thre]]
[com.example.twenty-four :refer [stuff more-stuff]]))
(defn some-fn-with-split []
(split "foo:bar:baz" #":"))
(def registry
{:fn-with-println #'fn-with-println})
(thre)
(stuff)
(more-stuff)
| |
8920febb46f5bf6aae25a34b688ae315ddcc334acee7823faf938ecd75357f06 | orbitz/scow | scow_server_msg.mli | open Core.Std
open Async.Std
module Make :
functor (Statem : Scow_statem.S) ->
functor (Log : Scow_log.S) ->
functor (Transport : Scow_transport.S) ->
sig
type append_entries = (Statem.ret, [ `Not_master | `Append_failed | `Invalid_log ]) Result.t
type rpc = (Transport.Node.t, Transport.elt) Scow_transport.Msg.t * Transport.ctx
type append_entries_resp =
(Transport.Node.t * Scow_log_index.t * ((Scow_term.t * bool), [ `Transport_error ]) Result.t)
type op =
| Election_timeout
| Heartbeat
| Rpc of rpc
| Append_entry of (append_entries Ivar.t * Statem.op)
| Received_vote of (Transport.Node.t * Scow_term.t * bool)
| Append_entries_resp of append_entries_resp
type getter =
| Get_me of Transport.Node.t Ivar.t
| Get_nodes of Transport.Node.t list Ivar.t
| Get_current_term of Scow_term.t Ivar.t
| Get_voted_for of Transport.Node.t option Ivar.t
| Get_leader of Transport.Node.t option Ivar.t
type t =
| Op of op
| Get of getter
end
| null | https://raw.githubusercontent.com/orbitz/scow/feb633ef94824f44f0ffc679a548f97288c8ae48/lib/scow/scow_server_msg.mli | ocaml | open Core.Std
open Async.Std
module Make :
functor (Statem : Scow_statem.S) ->
functor (Log : Scow_log.S) ->
functor (Transport : Scow_transport.S) ->
sig
type append_entries = (Statem.ret, [ `Not_master | `Append_failed | `Invalid_log ]) Result.t
type rpc = (Transport.Node.t, Transport.elt) Scow_transport.Msg.t * Transport.ctx
type append_entries_resp =
(Transport.Node.t * Scow_log_index.t * ((Scow_term.t * bool), [ `Transport_error ]) Result.t)
type op =
| Election_timeout
| Heartbeat
| Rpc of rpc
| Append_entry of (append_entries Ivar.t * Statem.op)
| Received_vote of (Transport.Node.t * Scow_term.t * bool)
| Append_entries_resp of append_entries_resp
type getter =
| Get_me of Transport.Node.t Ivar.t
| Get_nodes of Transport.Node.t list Ivar.t
| Get_current_term of Scow_term.t Ivar.t
| Get_voted_for of Transport.Node.t option Ivar.t
| Get_leader of Transport.Node.t option Ivar.t
type t =
| Op of op
| Get of getter
end
| |
877cf31aa32ee4d9dcbe503f69b08d3020a2f723c251779c11a063ef2804d28c | cfcs/PongOS | command.ml | open Lwt
module Flow = Qubes.RExec.Flow
let src = Logs.Src.create "command" ~doc:"qrexec command handler"
module Log = (val Logs.src_log src : Logs.LOG)
let echo ~user flow =
Flow.writef flow "Hi %s! Please enter a string:" user >>= fun () ->
Flow.read_line flow >>= function
| `Eof -> return 1
| `Ok input ->
Flow.writef flow "You wrote %S. Bye." input >|= fun () -> 0
let download flow =
(* adapted from do_unpack in qubes-linux-utils/qrexec-lib/unpack.c*)
step 1 : read struct file_header " untrusted_hdr "
- if namelen = = 0 :
reply with send_status_and_crc(errno , last filename )
step 2 : process_one_file(&untrusted_hdr )
- read_all_with_crc(filename , untrusted_hdr->namelen )
step 3 : match hdr.mode with ( * S_ISREG / S_ISLNK / S_ISDIR
- if namelen == 0:
reply with send_status_and_crc(errno, last filename)
step 2: process_one_file(&untrusted_hdr)
- read_all_with_crc(filename, untrusted_hdr->namelen)
step 3: match hdr.mode with (* S_ISREG/S_ISLNK/S_ISDIR *)
| -> process_one_file_reg(hdr, name)
| process_one_file_link(hdr, name)
| process_one_file_dir(hdr, name)
step 4: goto 1
*)
let open Qubes.Formats.Rpc_filecopy in
Flow.read flow >>= function
| `Eof -> return 1
| `Ok hdr when Cstruct.len hdr < sizeof_file_header -> return 1
| `Ok hdr_much ->
let hdr, filename, first_filedata =
Cstruct.split hdr_much sizeof_file_header
|> fun (hdr, extra) ->
Cstruct.split extra (get_file_header_namelen hdr |> Int32.to_int)
|> fun (filename, filedata) ->
hdr, Cstruct.to_string filename, filedata
in
Log.warn (fun m -> m "filename: %S" filename) ;
let rec loop acc =
Flow.read flow >>= function
| `Eof -> return 1
| `Ok input ->
Log.warn (fun m -> m "read: @[<v>%a@]"
Cstruct.hexdump_pp input) ;
loop (input::acc)
in
loop [first_filedata]
let handler ~user cmd flow =
Write a message to the client and return an exit status of 1 .
let error fmt =
fmt |> Printf.ksprintf @@ fun s ->
Log.warn (fun f -> f "<< %s" s);
Flow.ewritef flow "%s [while processing %S]" s cmd >|= fun () -> 1 in
match cmd with
| "echo" -> echo ~user flow
| "QUBESRPC qubes.Filecopy dom0" -> download flow
| cmd -> error "Unknown command %S" cmd
| null | https://raw.githubusercontent.com/cfcs/PongOS/45e1b64f00f6c06bee819770f2ed803c7e645f96/command.ml | ocaml | adapted from do_unpack in qubes-linux-utils/qrexec-lib/unpack.c
S_ISREG/S_ISLNK/S_ISDIR | open Lwt
module Flow = Qubes.RExec.Flow
let src = Logs.Src.create "command" ~doc:"qrexec command handler"
module Log = (val Logs.src_log src : Logs.LOG)
let echo ~user flow =
Flow.writef flow "Hi %s! Please enter a string:" user >>= fun () ->
Flow.read_line flow >>= function
| `Eof -> return 1
| `Ok input ->
Flow.writef flow "You wrote %S. Bye." input >|= fun () -> 0
let download flow =
step 1 : read struct file_header " untrusted_hdr "
- if namelen = = 0 :
reply with send_status_and_crc(errno , last filename )
step 2 : process_one_file(&untrusted_hdr )
- read_all_with_crc(filename , untrusted_hdr->namelen )
step 3 : match hdr.mode with ( * S_ISREG / S_ISLNK / S_ISDIR
- if namelen == 0:
reply with send_status_and_crc(errno, last filename)
step 2: process_one_file(&untrusted_hdr)
- read_all_with_crc(filename, untrusted_hdr->namelen)
| -> process_one_file_reg(hdr, name)
| process_one_file_link(hdr, name)
| process_one_file_dir(hdr, name)
step 4: goto 1
*)
let open Qubes.Formats.Rpc_filecopy in
Flow.read flow >>= function
| `Eof -> return 1
| `Ok hdr when Cstruct.len hdr < sizeof_file_header -> return 1
| `Ok hdr_much ->
let hdr, filename, first_filedata =
Cstruct.split hdr_much sizeof_file_header
|> fun (hdr, extra) ->
Cstruct.split extra (get_file_header_namelen hdr |> Int32.to_int)
|> fun (filename, filedata) ->
hdr, Cstruct.to_string filename, filedata
in
Log.warn (fun m -> m "filename: %S" filename) ;
let rec loop acc =
Flow.read flow >>= function
| `Eof -> return 1
| `Ok input ->
Log.warn (fun m -> m "read: @[<v>%a@]"
Cstruct.hexdump_pp input) ;
loop (input::acc)
in
loop [first_filedata]
let handler ~user cmd flow =
Write a message to the client and return an exit status of 1 .
let error fmt =
fmt |> Printf.ksprintf @@ fun s ->
Log.warn (fun f -> f "<< %s" s);
Flow.ewritef flow "%s [while processing %S]" s cmd >|= fun () -> 1 in
match cmd with
| "echo" -> echo ~user flow
| "QUBESRPC qubes.Filecopy dom0" -> download flow
| cmd -> error "Unknown command %S" cmd
|
8935faa4cdeba91d567571c1fbbc9b8150b80a4e72c979fe53f1164ea2fade73 | bennn/dissertation | lightbulb.rkt | #lang racket/base
;; License: Apache-2.0
By
;; <>
(require racket/draw
pict
racket/class
racket/math
racket/list
racket/contract)
(module+ main
(inset (lightbulb) 10))
(provide (contract-out
[lightbulb
(->* []
[#:color (or/c string? (is-a?/c color%) (is-a?/c brush%))
#:base-color (or/c string? (is-a?/c color%))
#:border-color (or/c string? (is-a?/c color%))
#:tip-color (or/c string? (is-a?/c color%))
#:border-width (real-in 0 255)
#:bulb-radius (and/c rational? (not/c negative?))
#:stem-width-radians (and/c rational? (not/c negative?))
#:stem-height (and/c rational? (not/c negative?))
#:base-segments natural-number/c
#:base-segment-height (and/c rational? (not/c negative?))
#:base-segment-corner-radius real?
#:tip-ratio (and/c rational? (not/c negative?))]
pict?)]
))
(define (lightbulb #:color [bulb-color "yellow"]
#:base-color [base-color (make-color 200 200 200)]
#:border-color [border-color (make-color 0 0 0)]
#:tip-color [tip-color border-color]
#:border-width [border-width 2.5]
#:bulb-radius [bulb-radius 50]
#:stem-width-radians [stem-width-radians (/ pi 4)]
#:stem-height [stem-height 15]
#:base-segments [base-segments 3]
#:base-segment-height [base-segment-height 9]
#:base-segment-corner-radius [base-segment-corner-radius 3]
#:tip-ratio [tip-ratio 5/12])
(define-values [stem-width bulb-part]
(stem-width+bulb-part-pict #:color bulb-color
#:border-color border-color
#:border-width border-width
#:bulb-radius bulb-radius
#:stem-width-radians stem-width-radians
#:stem-height stem-height))
(define base
(base-pict #:base-color base-color
#:border-color border-color
#:tip-color tip-color
#:border-width border-width
#:stem-width stem-width
#:base-segments base-segments
#:base-segment-height base-segment-height
#:base-segment-corner-radius base-segment-corner-radius
#:tip-ratio tip-ratio))
(vc-append bulb-part
base))
(define (stem-width+bulb-part-pict
#:color [bulb-color "yellow"]
#:border-color [border-color (make-color 0 0 0)]
#:border-width [border-width 2.5]
#:bulb-radius [bulb-radius 50]
#:stem-width-radians [stem-width-radians (/ pi 4)]
#:stem-height [stem-height 15])
(define-syntax-rule (with-methods obj #:methods [m ...] body ...)
(let ([this obj])
(with-method ([m (this m)] ...)
body ... this)))
(let*-values ([{left-θ right-θ}
(let ([6pm (* 3/2 pi)]
[half-gap (/ stem-width-radians 2)])
(values (- 6pm half-gap)
(+ 6pm half-gap)))]
[{left-x right-x}
(let ([θ->x (λ (θ)
(+ bulb-radius (* bulb-radius (cos θ))))])
(values (θ->x left-θ)
(θ->x right-θ)))]
[{stem-width}
(- right-x left-x)]
[{diameter} (* 2 bulb-radius)]
[{bottom-y} (+ diameter stem-height)]
[{pth}
(with-methods
(new dc-path%) #:methods [arc line-to]
(arc 0 0 diameter diameter right-θ left-θ)
(line-to left-x bottom-y)
(line-to right-x bottom-y)
(line-to right-x (+ bulb-radius (- (* bulb-radius (sin right-θ))))))]
[{lightbulb-pen} (make-pen #:width border-width
#:color border-color)]
[{lightbulb-brush} (if (is-a? bulb-color brush%)
bulb-color
(make-brush #:color bulb-color
#:style 'solid))])
(values
stem-width
(dc (λ (dc dx dy)
(with-methods
dc #:methods [draw-path
get-brush get-pen set-brush set-pen]
(define old-brush (get-brush))
(define old-pen (get-pen))
(set-brush lightbulb-brush)
(set-pen lightbulb-pen)
;;;;;;;;
(draw-path pth dx dy)
;;;;;;;;
(set-brush old-brush)
(set-pen old-pen)))
diameter
bottom-y))))
(define (base-pict #:base-color [base-color (make-color 200 200 200)]
#:border-color [border-color (make-color 0 0 0)]
#:tip-color [tip-color border-color]
#:border-width [border-width 2.5]
#:stem-width [stem-width (let-values ([{w _} (stem-width+bulb-part-pict)])
w)]
#:base-segments [base-segments 3]
#:base-segment-height [base-segment-height 9]
#:base-segment-corner-radius [base-segment-corner-radius 3]
#:tip-ratio [tip-ratio 5/12])
(define base-rect
(filled-rounded-rectangle
(+ stem-width
base-segment-corner-radius)
base-segment-height
base-segment-corner-radius
#:color base-color
#:border-color border-color
#:border-width border-width))
(define tip-diameter
(* tip-ratio stem-width))
(define tip
(disk tip-diameter
#:color tip-color
#:border-color border-color
#:border-width border-width))
(define base-rect-stack
(apply vc-append
(make-list base-segments base-rect)))
(define tip-radius
(/ tip-diameter 2))
(panorama
(pin-under base-rect-stack
(- (/ (pict-width base-rect-stack) 2)
tip-radius)
(- (pict-height base-rect-stack)
tip-radius)
tip)))
| null | https://raw.githubusercontent.com/bennn/dissertation/779bfe6f8fee19092849b7e2cfc476df33e9357b/proposal/talk/lightbulb.rkt | racket | License: Apache-2.0
<>
| #lang racket/base
By
(require racket/draw
pict
racket/class
racket/math
racket/list
racket/contract)
(module+ main
(inset (lightbulb) 10))
(provide (contract-out
[lightbulb
(->* []
[#:color (or/c string? (is-a?/c color%) (is-a?/c brush%))
#:base-color (or/c string? (is-a?/c color%))
#:border-color (or/c string? (is-a?/c color%))
#:tip-color (or/c string? (is-a?/c color%))
#:border-width (real-in 0 255)
#:bulb-radius (and/c rational? (not/c negative?))
#:stem-width-radians (and/c rational? (not/c negative?))
#:stem-height (and/c rational? (not/c negative?))
#:base-segments natural-number/c
#:base-segment-height (and/c rational? (not/c negative?))
#:base-segment-corner-radius real?
#:tip-ratio (and/c rational? (not/c negative?))]
pict?)]
))
(define (lightbulb #:color [bulb-color "yellow"]
#:base-color [base-color (make-color 200 200 200)]
#:border-color [border-color (make-color 0 0 0)]
#:tip-color [tip-color border-color]
#:border-width [border-width 2.5]
#:bulb-radius [bulb-radius 50]
#:stem-width-radians [stem-width-radians (/ pi 4)]
#:stem-height [stem-height 15]
#:base-segments [base-segments 3]
#:base-segment-height [base-segment-height 9]
#:base-segment-corner-radius [base-segment-corner-radius 3]
#:tip-ratio [tip-ratio 5/12])
(define-values [stem-width bulb-part]
(stem-width+bulb-part-pict #:color bulb-color
#:border-color border-color
#:border-width border-width
#:bulb-radius bulb-radius
#:stem-width-radians stem-width-radians
#:stem-height stem-height))
(define base
(base-pict #:base-color base-color
#:border-color border-color
#:tip-color tip-color
#:border-width border-width
#:stem-width stem-width
#:base-segments base-segments
#:base-segment-height base-segment-height
#:base-segment-corner-radius base-segment-corner-radius
#:tip-ratio tip-ratio))
(vc-append bulb-part
base))
(define (stem-width+bulb-part-pict
#:color [bulb-color "yellow"]
#:border-color [border-color (make-color 0 0 0)]
#:border-width [border-width 2.5]
#:bulb-radius [bulb-radius 50]
#:stem-width-radians [stem-width-radians (/ pi 4)]
#:stem-height [stem-height 15])
(define-syntax-rule (with-methods obj #:methods [m ...] body ...)
(let ([this obj])
(with-method ([m (this m)] ...)
body ... this)))
(let*-values ([{left-θ right-θ}
(let ([6pm (* 3/2 pi)]
[half-gap (/ stem-width-radians 2)])
(values (- 6pm half-gap)
(+ 6pm half-gap)))]
[{left-x right-x}
(let ([θ->x (λ (θ)
(+ bulb-radius (* bulb-radius (cos θ))))])
(values (θ->x left-θ)
(θ->x right-θ)))]
[{stem-width}
(- right-x left-x)]
[{diameter} (* 2 bulb-radius)]
[{bottom-y} (+ diameter stem-height)]
[{pth}
(with-methods
(new dc-path%) #:methods [arc line-to]
(arc 0 0 diameter diameter right-θ left-θ)
(line-to left-x bottom-y)
(line-to right-x bottom-y)
(line-to right-x (+ bulb-radius (- (* bulb-radius (sin right-θ))))))]
[{lightbulb-pen} (make-pen #:width border-width
#:color border-color)]
[{lightbulb-brush} (if (is-a? bulb-color brush%)
bulb-color
(make-brush #:color bulb-color
#:style 'solid))])
(values
stem-width
(dc (λ (dc dx dy)
(with-methods
dc #:methods [draw-path
get-brush get-pen set-brush set-pen]
(define old-brush (get-brush))
(define old-pen (get-pen))
(set-brush lightbulb-brush)
(set-pen lightbulb-pen)
(draw-path pth dx dy)
(set-brush old-brush)
(set-pen old-pen)))
diameter
bottom-y))))
(define (base-pict #:base-color [base-color (make-color 200 200 200)]
#:border-color [border-color (make-color 0 0 0)]
#:tip-color [tip-color border-color]
#:border-width [border-width 2.5]
#:stem-width [stem-width (let-values ([{w _} (stem-width+bulb-part-pict)])
w)]
#:base-segments [base-segments 3]
#:base-segment-height [base-segment-height 9]
#:base-segment-corner-radius [base-segment-corner-radius 3]
#:tip-ratio [tip-ratio 5/12])
(define base-rect
(filled-rounded-rectangle
(+ stem-width
base-segment-corner-radius)
base-segment-height
base-segment-corner-radius
#:color base-color
#:border-color border-color
#:border-width border-width))
(define tip-diameter
(* tip-ratio stem-width))
(define tip
(disk tip-diameter
#:color tip-color
#:border-color border-color
#:border-width border-width))
(define base-rect-stack
(apply vc-append
(make-list base-segments base-rect)))
(define tip-radius
(/ tip-diameter 2))
(panorama
(pin-under base-rect-stack
(- (/ (pict-width base-rect-stack) 2)
tip-radius)
(- (pict-height base-rect-stack)
tip-radius)
tip)))
|
2d396588dc24520c2b762bbefae22e9ddc5dc34f63b266cc5fd961f901a45916 | mirage/ocaml-cstruct | bounds.ml |
* Copyright ( c ) 2014 Anil Madhavapeddy < >
* Copyright ( c ) 2013 Citrix Systems Inc
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2014 Anil Madhavapeddy <>
* Copyright (c) 2013 Citrix Systems Inc
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
let to_string { Cstruct.buffer; off; len } =
Printf.sprintf "buffer length = %d; off=%d; len=%d" (Bigarray.Array1.dim buffer) off len
(* Check we can create and use an empty cstruct *)
let test_empty_cstruct () =
let x = Cstruct.create 0 in
Alcotest.(check int) "empty len" 0 (Cstruct.length x);
let y = Cstruct.to_string x in
Alcotest.(check string) "empty" "" y
(* Check that we can't create a cstruct with a negative length *)
let test_anti_cstruct () =
try
let x = Cstruct.create (-1) in
failwith (Printf.sprintf "test_anti_cstruct: %s" (to_string x))
with Invalid_argument _ ->
()
(* Check we can shift in the +ve direction *)
let test_positive_shift () =
let x = Cstruct.create 1 in
let y = Cstruct.shift x 1 in
Alcotest.(check int) "positive shift" 0 (Cstruct.length y)
(* Check that negative shifts are forbidden. *)
let test_negative_shift () =
let x = Cstruct.create 2 in
let y = Cstruct.sub x 1 1 in
try
let z = Cstruct.shift x (-1) in
failwith (Printf.sprintf "test_negative_shift/outer: %s" (to_string z))
with Invalid_argument _ ->
try
let z = Cstruct.shift y (-1) in
failwith (Printf.sprintf "test_negative_shift/inner: %s" (to_string z))
with Invalid_argument _ ->
()
(* Check that an attempt to shift beyond the end of the buffer fails *)
let test_bad_positive_shift () =
let x = Cstruct.create 10 in
try
let y = Cstruct.shift x 11 in
failwith (Printf.sprintf "test_bad_positive_shift: %s" (to_string y))
with Invalid_argument _ -> ()
(* Check that 'sub' works *)
let test_sub () =
let x = Cstruct.create 100 in
let y = Cstruct.sub x 10 80 in
Alcotest.(check int) "sub 1" 10 y.Cstruct.off;
Alcotest.(check int) "sub 2" 80 y.Cstruct.len;
let z = Cstruct.sub y 10 60 in
Alcotest.(check int) "sub 3" 20 z.Cstruct.off;
Alcotest.(check int) "sub 4" 60 z.Cstruct.len
let test_sub_copy () =
let x = Cstruct.create 100 in
let y = Cstruct.sub_copy x 10 80 in
Alcotest.(check int) "sub_copy 1" 0 y.Cstruct.off;
Alcotest.(check int) "sub_copy 2" 80 y.Cstruct.len;
let z = Cstruct.sub_copy y 10 60 in
Alcotest.(check int) "sub_copy 3" 0 z.Cstruct.off;
Alcotest.(check int) "sub_copy 4" 60 z.Cstruct.len;
Cstruct.set_uint8 x 50 42;
Alcotest.(check int) "x changed" 42 (Cstruct.get_uint8 x 50);
Alcotest.(check int) "y unchanged" 0 (Cstruct.get_uint8 y 50);
()
let test_negative_sub () =
let x = Cstruct.create 2 in
let y = Cstruct.sub x 1 1 in
try
let z = Cstruct.sub x (-1) 0 in
failwith (Printf.sprintf "test_negative_sub/outer: %s" (to_string z))
with Invalid_argument _ ->
try
let z = Cstruct.sub y (-1) 0 in
failwith (Printf.sprintf "test_negative_sub/inner: %s" (to_string z))
with Invalid_argument _ ->
()
(* Check that 'sub' can't set 'len' too big *)
let test_sub_len_too_big () =
let x = Cstruct.create 0 in
try
let y = Cstruct.sub x 0 1 in
failwith (Printf.sprintf "test_sub_len_too_big: %s" (to_string y))
with Invalid_argument _ -> ()
let test_sub_len_too_small () =
let x = Cstruct.create 0 in
try
let y = Cstruct.sub x 0 (-1) in
failwith (Printf.sprintf "test_sub_len_too_small: %s" (to_string y))
with Invalid_argument _ -> ()
let test_sub_offset_too_big () =
let x = Cstruct.create 10 in
begin
try
let y = Cstruct.sub x 11 0 in
failwith (Printf.sprintf "test_sub_offset_too_big: %s" (to_string y))
with Invalid_argument _ -> ()
end;
let y = Cstruct.sub x 1 9 in
begin
try
let z = Cstruct.sub y 10 0 in
failwith (Printf.sprintf "test_sub_offset_too_big: %s" (to_string z))
with Invalid_argument _ -> ()
end
let test_of_bigarray_negative_params () =
let ba = Bigarray.(Array1.create char c_layout 1) in
try
let x = Cstruct.of_bigarray ~off:(-1) ba in
failwith (Printf.sprintf "test_of_bigarray_negative_params: negative ~off: %s" (to_string x))
with Invalid_argument _ ->
try
let x = Cstruct.of_bigarray ~len:(-1) ba in
failwith (Printf.sprintf "test_of_bigarray_negative_params: negative ~len: %s" (to_string x))
with Invalid_argument _ ->
()
let test_of_bigarray_large_offset () =
let ba = Bigarray.(Array1.create char c_layout 1) in
let _ = Cstruct.of_bigarray ~off:1 ~len:0 ba
and _ = Cstruct.of_bigarray ~off:1 ba in
try
let x = Cstruct.of_bigarray ~off:2 ~len:0 ba in
failwith (Printf.sprintf "test_of_bigarray_large_offset: %s" (to_string x))
with Invalid_argument _ ->
try
let x = Cstruct.of_bigarray ~off:2 ba in
failwith (Printf.sprintf "test_of_bigarray_large_offset: large ~off: %s" (to_string x))
with Invalid_argument _ ->
()
let test_of_bigarray_large_length () =
let ba = Bigarray.(Array1.create char c_layout 1) in
try
let x = Cstruct.of_bigarray ~off:0 ~len:2 ba in
failwith (Printf.sprintf "test_of_bigarray_large_length: %s" (to_string x))
with Invalid_argument _ ->
try
let x = Cstruct.of_bigarray ~off:1 ~len:1 ba in
failwith (Printf.sprintf "test_of_bigarray_large_length: %s" (to_string x))
with Invalid_argument _ ->
try
let x = Cstruct.of_bigarray ~off:2 ~len:0 ba in
failwith (Printf.sprintf "test_of_bigarray_large_length: %s" (to_string x))
with Invalid_argument _ ->
try
let x = Cstruct.of_bigarray ~off:2 ba in
failwith (Printf.sprintf "test_of_bigarray_large_length: %s" (to_string x))
with Invalid_argument _ ->
()
let test_blit_offset_too_big () =
let x = Cstruct.create 1 in
let y = Cstruct.create 1 in
try
Cstruct.blit x 2 y 1 1;
failwith "test_blit_offset_too_big"
with Invalid_argument _ -> ()
let test_blit_offset_too_small () =
let x = Cstruct.create 1 in
let y = Cstruct.create 1 in
try
Cstruct.blit x (-1) y 1 1;
failwith "test_blit_offset_too_small"
with Invalid_argument _ -> ()
let test_blit_dst_offset_too_big () =
let x = Cstruct.create 1 in
let y = Cstruct.create 1 in
try
Cstruct.blit x 1 y 2 1;
failwith "test_blit_dst_offset_too_big"
with Invalid_argument _ -> ()
let test_blit_dst_offset_too_small () =
let x = Cstruct.create 1 in
let y = Cstruct.create 1 in
try
Cstruct.blit x 1 y (-1) 1;
failwith "test_blit_dst_offset_too_small"
with Invalid_argument _ -> ()
let test_blit_dst_offset_negative () =
let x = Cstruct.create 1 in
let y = Cstruct.create 1 in
try
Cstruct.blit x 0 y (-1) 1;
failwith "test_blit_dst_offset_negative"
with Invalid_argument _ -> ()
let test_blit_len_too_big () =
let x = Cstruct.create 1 in
let y = Cstruct.create 2 in
try
Cstruct.blit x 0 y 0 2;
failwith "test_blit_len_too_big"
with Invalid_argument _ -> ()
let test_blit_len_too_big2 () =
let x = Cstruct.create 2 in
let y = Cstruct.create 1 in
try
Cstruct.blit x 0 y 0 2;
failwith "test_blit_len_too_big2"
with Invalid_argument _ -> ()
let test_blit_len_too_small () =
let x = Cstruct.create 1 in
let y = Cstruct.create 1 in
try
Cstruct.blit x 0 y 0 (-1);
failwith "test_blit_len_too_small"
with Invalid_argument _ -> ()
let test_view_bounds_too_small () =
let src = Cstruct.create 4 in
let dst = Cstruct.create 4 in
let dst_small = Cstruct.sub dst 0 2 in
try
Cstruct.blit src 0 dst_small 0 3;
failwith "test_view_bounds_too_small"
with
Invalid_argument _ -> ()
let test_view_bounds_too_small_get_u8 () =
let x = Cstruct.create 2 in
let x' = Cstruct.sub x 0 1 in
try
let _ = Cstruct.get_uint8 x' 1 in
failwith "test_view_bounds_too_small_get_u8"
with
Invalid_argument _ -> ()
let test_view_bounds_too_small_get_char () =
let x = Cstruct.create 2 in
let x' = Cstruct.sub x 0 1 in
try
let _ = Cstruct.get_char x' 1 in
failwith "test_view_bounds_too_small_get_char"
with
Invalid_argument _ -> ()
let test_view_bounds_too_small_get_be16 () =
let x = Cstruct.create 4 in
let x' = Cstruct.sub x 0 1 in
try
let _ = Cstruct.BE.get_uint16 x' 0 in
failwith "test_view_bounds_too_small_get_be16"
with
Invalid_argument _ -> ()
let test_view_bounds_too_small_get_be32 () =
let x = Cstruct.create 8 in
let x' = Cstruct.sub x 2 5 in
try
let _ = Cstruct.BE.get_uint32 x' 2 in
failwith "test_view_bounds_too_small_get_be32"
with
Invalid_argument _ -> ()
let test_view_bounds_too_small_get_be64 () =
let x = Cstruct.create 9 in
let x' = Cstruct.sub x 1 5 in
try
let _ = Cstruct.BE.get_uint64 x' 0 in
failwith "test_view_bounds_too_small_get_be64"
with
Invalid_argument _ -> ()
let test_view_bounds_too_small_get_le16 () =
let x = Cstruct.create 4 in
let x' = Cstruct.sub x 0 1 in
try
let _ = Cstruct.LE.get_uint16 x' 0 in
failwith "test_view_bounds_too_small_get_le16"
with
Invalid_argument _ -> ()
let test_view_bounds_too_small_get_le32 () =
let x = Cstruct.create 8 in
let x' = Cstruct.sub x 2 5 in
try
let _ = Cstruct.LE.get_uint32 x' 2 in
failwith "test_view_bounds_too_small_get_le32"
with
Invalid_argument _ -> ()
let test_view_bounds_too_small_get_le64 () =
let x = Cstruct.create 9 in
let x' = Cstruct.sub x 1 5 in
try
let _ = Cstruct.LE.get_uint64 x' 0 in
failwith "test_view_bounds_too_small_get_le64"
with
Invalid_argument _ -> ()
let test_view_bounds_too_small_get_he16 () =
let x = Cstruct.create 4 in
let x' = Cstruct.sub x 0 1 in
try
let _ = Cstruct.HE.get_uint16 x' 0 in
failwith "test_view_bounds_too_small_get_he16"
with
Invalid_argument _ -> ()
let test_view_bounds_too_small_get_he32 () =
let x = Cstruct.create 8 in
let x' = Cstruct.sub x 2 5 in
try
let _ = Cstruct.HE.get_uint32 x' 2 in
failwith "test_view_bounds_too_small_get_he32"
with
Invalid_argument _ -> ()
let test_view_bounds_too_small_get_he64 () =
let x = Cstruct.create 9 in
let x' = Cstruct.sub x 1 5 in
try
let _ = Cstruct.HE.get_uint64 x' 0 in
failwith "test_view_bounds_too_small_get_he64"
with
Invalid_argument _ -> ()
let test_lenv_overflow () =
if Sys.word_size = 32 then (
(* free-up some space *)
Gc.major ();
let b = Cstruct.create max_int and c = Cstruct.create 3 in
try
let _ = Cstruct.lenv [b; b; c] in
failwith "test_lenv_overflow"
with
Invalid_argument _ -> ())
let test_copyv_overflow () =
if Sys.word_size = 32 then (
(* free-up some space *)
Gc.major ();
let b = Cstruct.create max_int and c = Cstruct.create 3 in
try
let _ = Cstruct.copyv [b; b; c] in
failwith "test_copyv_overflow"
with
Invalid_argument _ -> ())
Steamroll over a buffer and a contained subview , checking that only the
* contents of the subview is visible .
* contents of the subview is visible. *)
let test_subview_containment_get_char,
test_subview_containment_get_8,
test_subview_containment_get_be16,
test_subview_containment_get_be32,
test_subview_containment_get_be64,
test_subview_containment_get_le16,
test_subview_containment_get_le32,
test_subview_containment_get_le64,
test_subview_containment_get_he16,
test_subview_containment_get_he32,
test_subview_containment_get_he64
=
let open Cstruct in
let test get zero () =
let x = create 24 in
let x' = sub x 8 8 in
for i = 0 to length x - 1 do set_uint8 x i 0xff done ;
for i = 0 to length x' - 1 do set_uint8 x' i 0x00 done ;
for i = -8 to 8 do
try
let v = get x' i in
if v <> zero then
failwith "test_subview_containment_get"
with Invalid_argument _ -> ()
done
in
test get_char '\000',
test get_uint8 0,
test BE.get_uint16 0,
test BE.get_uint32 0l,
test BE.get_uint64 0L,
test LE.get_uint16 0,
test LE.get_uint32 0l,
test LE.get_uint64 0L,
test HE.get_uint16 0,
test HE.get_uint32 0l,
test HE.get_uint64 0L
Steamroll over a buffer and a contained subview , checking that only the
* contents of the subview is writable .
* contents of the subview is writable. *)
let test_subview_containment_set_char,
test_subview_containment_set_8,
test_subview_containment_set_be16,
test_subview_containment_set_be32,
test_subview_containment_set_be64,
test_subview_containment_set_le16,
test_subview_containment_set_le32,
test_subview_containment_set_le64,
test_subview_containment_set_he16,
test_subview_containment_set_he32,
test_subview_containment_set_he64
=
let open Cstruct in
let test set ff () =
let x = create 24 in
let x' = sub x 8 8 in
for i = 0 to length x - 1 do set_uint8 x i 0x00 done ;
for i = -8 to 8 do
try set x' i ff with Invalid_argument _ -> ()
done;
let acc = ref 0 in
for i = 0 to length x - 1 do
acc := !acc + get_uint8 x i
done ;
if !acc <> (length x' * 0xff) then
failwith "test_subview_containment_set"
in
test set_char '\255',
test set_uint8 0xff,
test BE.set_uint16 0xffff,
test BE.set_uint32 0xffffffffl,
test BE.set_uint64 0xffffffffffffffffL,
test LE.set_uint16 0xffff,
test LE.set_uint32 0xffffffffl,
test LE.set_uint64 0xffffffffffffffffL,
test HE.set_uint16 0xffff,
test HE.set_uint32 0xffffffffl,
test HE.set_uint64 0xffffffffffffffffL
let regression_244 () =
let whole = Cstruct.create 44943 in
let empty = Cstruct.sub whole 0 0 in
try
let _big = Cstruct.sub empty 0 204 in
Alcotest.fail "could get a bigger buffer via sub"
with Invalid_argument _ -> ()
let suite = [
"test empty cstruct", `Quick, test_empty_cstruct;
"test anti cstruct", `Quick, test_anti_cstruct;
"test positive shift", `Quick, test_positive_shift;
"test negative shift", `Quick, test_negative_shift;
"test bad positive shift", `Quick, test_bad_positive_shift;
"test sub", `Quick, test_sub;
"test sub_copy", `Quick, test_sub_copy;
"test negative sub", `Quick, test_negative_sub;
"test sub len too big", `Quick, test_sub_len_too_big;
"test sub len too small", `Quick, test_sub_len_too_small;
"test sub offset too big", `Quick, test_sub_offset_too_big;
"test of_bigarray negative params", `Quick, test_of_bigarray_negative_params;
"test of_bigarray large offset", `Quick, test_of_bigarray_large_offset;
"test of_bigarray large length", `Quick, test_of_bigarray_large_length;
"test blit offset too big", `Quick, test_blit_offset_too_big;
"test blit offset too small", `Quick, test_blit_offset_too_small;
"test blit dst offset too big", `Quick, test_blit_dst_offset_too_big;
"test blit dst offset too small", `Quick, test_blit_dst_offset_too_small;
"test blit dst offset negative", `Quick, test_blit_dst_offset_negative;
"test blit len too big", `Quick, test_blit_len_too_big;
"test blit len too big2", `Quick, test_blit_len_too_big2;
"test blit len too small", `Quick, test_blit_len_too_small;
"test view bounds too small", `Quick, test_view_bounds_too_small;
"test_view_bounds_too_small_get_u8" , `Quick, test_view_bounds_too_small_get_u8;
"test_view_bounds_too_small_get_char" , `Quick, test_view_bounds_too_small_get_char;
"test_view_bounds_too_small_get_be16" , `Quick, test_view_bounds_too_small_get_be16;
"test_view_bounds_too_small_get_be32" , `Quick, test_view_bounds_too_small_get_be32;
"test_view_bounds_too_small_get_be64" , `Quick, test_view_bounds_too_small_get_be64;
"test_view_bounds_too_small_get_le16" , `Quick, test_view_bounds_too_small_get_le16;
"test_view_bounds_too_small_get_le32" , `Quick, test_view_bounds_too_small_get_le32;
"test_view_bounds_too_small_get_le64" , `Quick, test_view_bounds_too_small_get_le64;
"test_view_bounds_too_small_get_he16" , `Quick, test_view_bounds_too_small_get_he16;
"test_view_bounds_too_small_get_he32" , `Quick, test_view_bounds_too_small_get_he32;
"test_view_bounds_too_small_get_he64" , `Quick, test_view_bounds_too_small_get_he64;
"test_lenv_overflow", `Quick, test_lenv_overflow;
"test_copyv_overflow", `Quick, test_copyv_overflow;
"test_subview_containment_get_char", `Quick, test_subview_containment_get_char;
"test_subview_containment_get_8" , `Quick, test_subview_containment_get_8;
"test_subview_containment_get_be16", `Quick, test_subview_containment_get_be16;
"test_subview_containment_get_be32", `Quick, test_subview_containment_get_be32;
"test_subview_containment_get_be64", `Quick, test_subview_containment_get_be64;
"test_subview_containment_get_le16", `Quick, test_subview_containment_get_le16;
"test_subview_containment_get_le32", `Quick, test_subview_containment_get_le32;
"test_subview_containment_get_le64", `Quick, test_subview_containment_get_le64;
"test_subview_containment_get_le16", `Quick, test_subview_containment_get_he16;
"test_subview_containment_get_le32", `Quick, test_subview_containment_get_he32;
"test_subview_containment_get_le64", `Quick, test_subview_containment_get_he64;
"test_subview_containment_set_char", `Quick, test_subview_containment_set_char;
"test_subview_containment_set_8" , `Quick, test_subview_containment_set_8;
"test_subview_containment_set_be16", `Quick, test_subview_containment_set_be16;
"test_subview_containment_set_be32", `Quick, test_subview_containment_set_be32;
"test_subview_containment_set_be64", `Quick, test_subview_containment_set_be64;
"test_subview_containment_set_le16", `Quick, test_subview_containment_set_le16;
"test_subview_containment_set_le32", `Quick, test_subview_containment_set_le32;
"test_subview_containment_set_le64", `Quick, test_subview_containment_set_le64;
"test_subview_containment_set_le16", `Quick, test_subview_containment_set_he16;
"test_subview_containment_set_le32", `Quick, test_subview_containment_set_he32;
"test_subview_containment_set_le64", `Quick, test_subview_containment_set_he64;
"regression 244", `Quick, regression_244;
]
| null | https://raw.githubusercontent.com/mirage/ocaml-cstruct/63ca7ccaf7cf4ad68bda1449027ac22b8af59745/lib_test/bounds.ml | ocaml | Check we can create and use an empty cstruct
Check that we can't create a cstruct with a negative length
Check we can shift in the +ve direction
Check that negative shifts are forbidden.
Check that an attempt to shift beyond the end of the buffer fails
Check that 'sub' works
Check that 'sub' can't set 'len' too big
free-up some space
free-up some space |
* Copyright ( c ) 2014 Anil Madhavapeddy < >
* Copyright ( c ) 2013 Citrix Systems Inc
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2014 Anil Madhavapeddy <>
* Copyright (c) 2013 Citrix Systems Inc
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
let to_string { Cstruct.buffer; off; len } =
Printf.sprintf "buffer length = %d; off=%d; len=%d" (Bigarray.Array1.dim buffer) off len
let test_empty_cstruct () =
let x = Cstruct.create 0 in
Alcotest.(check int) "empty len" 0 (Cstruct.length x);
let y = Cstruct.to_string x in
Alcotest.(check string) "empty" "" y
let test_anti_cstruct () =
try
let x = Cstruct.create (-1) in
failwith (Printf.sprintf "test_anti_cstruct: %s" (to_string x))
with Invalid_argument _ ->
()
let test_positive_shift () =
let x = Cstruct.create 1 in
let y = Cstruct.shift x 1 in
Alcotest.(check int) "positive shift" 0 (Cstruct.length y)
let test_negative_shift () =
let x = Cstruct.create 2 in
let y = Cstruct.sub x 1 1 in
try
let z = Cstruct.shift x (-1) in
failwith (Printf.sprintf "test_negative_shift/outer: %s" (to_string z))
with Invalid_argument _ ->
try
let z = Cstruct.shift y (-1) in
failwith (Printf.sprintf "test_negative_shift/inner: %s" (to_string z))
with Invalid_argument _ ->
()
let test_bad_positive_shift () =
let x = Cstruct.create 10 in
try
let y = Cstruct.shift x 11 in
failwith (Printf.sprintf "test_bad_positive_shift: %s" (to_string y))
with Invalid_argument _ -> ()
let test_sub () =
let x = Cstruct.create 100 in
let y = Cstruct.sub x 10 80 in
Alcotest.(check int) "sub 1" 10 y.Cstruct.off;
Alcotest.(check int) "sub 2" 80 y.Cstruct.len;
let z = Cstruct.sub y 10 60 in
Alcotest.(check int) "sub 3" 20 z.Cstruct.off;
Alcotest.(check int) "sub 4" 60 z.Cstruct.len
let test_sub_copy () =
let x = Cstruct.create 100 in
let y = Cstruct.sub_copy x 10 80 in
Alcotest.(check int) "sub_copy 1" 0 y.Cstruct.off;
Alcotest.(check int) "sub_copy 2" 80 y.Cstruct.len;
let z = Cstruct.sub_copy y 10 60 in
Alcotest.(check int) "sub_copy 3" 0 z.Cstruct.off;
Alcotest.(check int) "sub_copy 4" 60 z.Cstruct.len;
Cstruct.set_uint8 x 50 42;
Alcotest.(check int) "x changed" 42 (Cstruct.get_uint8 x 50);
Alcotest.(check int) "y unchanged" 0 (Cstruct.get_uint8 y 50);
()
let test_negative_sub () =
let x = Cstruct.create 2 in
let y = Cstruct.sub x 1 1 in
try
let z = Cstruct.sub x (-1) 0 in
failwith (Printf.sprintf "test_negative_sub/outer: %s" (to_string z))
with Invalid_argument _ ->
try
let z = Cstruct.sub y (-1) 0 in
failwith (Printf.sprintf "test_negative_sub/inner: %s" (to_string z))
with Invalid_argument _ ->
()
let test_sub_len_too_big () =
let x = Cstruct.create 0 in
try
let y = Cstruct.sub x 0 1 in
failwith (Printf.sprintf "test_sub_len_too_big: %s" (to_string y))
with Invalid_argument _ -> ()
let test_sub_len_too_small () =
let x = Cstruct.create 0 in
try
let y = Cstruct.sub x 0 (-1) in
failwith (Printf.sprintf "test_sub_len_too_small: %s" (to_string y))
with Invalid_argument _ -> ()
let test_sub_offset_too_big () =
let x = Cstruct.create 10 in
begin
try
let y = Cstruct.sub x 11 0 in
failwith (Printf.sprintf "test_sub_offset_too_big: %s" (to_string y))
with Invalid_argument _ -> ()
end;
let y = Cstruct.sub x 1 9 in
begin
try
let z = Cstruct.sub y 10 0 in
failwith (Printf.sprintf "test_sub_offset_too_big: %s" (to_string z))
with Invalid_argument _ -> ()
end
let test_of_bigarray_negative_params () =
let ba = Bigarray.(Array1.create char c_layout 1) in
try
let x = Cstruct.of_bigarray ~off:(-1) ba in
failwith (Printf.sprintf "test_of_bigarray_negative_params: negative ~off: %s" (to_string x))
with Invalid_argument _ ->
try
let x = Cstruct.of_bigarray ~len:(-1) ba in
failwith (Printf.sprintf "test_of_bigarray_negative_params: negative ~len: %s" (to_string x))
with Invalid_argument _ ->
()
let test_of_bigarray_large_offset () =
let ba = Bigarray.(Array1.create char c_layout 1) in
let _ = Cstruct.of_bigarray ~off:1 ~len:0 ba
and _ = Cstruct.of_bigarray ~off:1 ba in
try
let x = Cstruct.of_bigarray ~off:2 ~len:0 ba in
failwith (Printf.sprintf "test_of_bigarray_large_offset: %s" (to_string x))
with Invalid_argument _ ->
try
let x = Cstruct.of_bigarray ~off:2 ba in
failwith (Printf.sprintf "test_of_bigarray_large_offset: large ~off: %s" (to_string x))
with Invalid_argument _ ->
()
let test_of_bigarray_large_length () =
let ba = Bigarray.(Array1.create char c_layout 1) in
try
let x = Cstruct.of_bigarray ~off:0 ~len:2 ba in
failwith (Printf.sprintf "test_of_bigarray_large_length: %s" (to_string x))
with Invalid_argument _ ->
try
let x = Cstruct.of_bigarray ~off:1 ~len:1 ba in
failwith (Printf.sprintf "test_of_bigarray_large_length: %s" (to_string x))
with Invalid_argument _ ->
try
let x = Cstruct.of_bigarray ~off:2 ~len:0 ba in
failwith (Printf.sprintf "test_of_bigarray_large_length: %s" (to_string x))
with Invalid_argument _ ->
try
let x = Cstruct.of_bigarray ~off:2 ba in
failwith (Printf.sprintf "test_of_bigarray_large_length: %s" (to_string x))
with Invalid_argument _ ->
()
let test_blit_offset_too_big () =
let x = Cstruct.create 1 in
let y = Cstruct.create 1 in
try
Cstruct.blit x 2 y 1 1;
failwith "test_blit_offset_too_big"
with Invalid_argument _ -> ()
let test_blit_offset_too_small () =
let x = Cstruct.create 1 in
let y = Cstruct.create 1 in
try
Cstruct.blit x (-1) y 1 1;
failwith "test_blit_offset_too_small"
with Invalid_argument _ -> ()
let test_blit_dst_offset_too_big () =
let x = Cstruct.create 1 in
let y = Cstruct.create 1 in
try
Cstruct.blit x 1 y 2 1;
failwith "test_blit_dst_offset_too_big"
with Invalid_argument _ -> ()
let test_blit_dst_offset_too_small () =
let x = Cstruct.create 1 in
let y = Cstruct.create 1 in
try
Cstruct.blit x 1 y (-1) 1;
failwith "test_blit_dst_offset_too_small"
with Invalid_argument _ -> ()
let test_blit_dst_offset_negative () =
let x = Cstruct.create 1 in
let y = Cstruct.create 1 in
try
Cstruct.blit x 0 y (-1) 1;
failwith "test_blit_dst_offset_negative"
with Invalid_argument _ -> ()
let test_blit_len_too_big () =
let x = Cstruct.create 1 in
let y = Cstruct.create 2 in
try
Cstruct.blit x 0 y 0 2;
failwith "test_blit_len_too_big"
with Invalid_argument _ -> ()
let test_blit_len_too_big2 () =
let x = Cstruct.create 2 in
let y = Cstruct.create 1 in
try
Cstruct.blit x 0 y 0 2;
failwith "test_blit_len_too_big2"
with Invalid_argument _ -> ()
let test_blit_len_too_small () =
let x = Cstruct.create 1 in
let y = Cstruct.create 1 in
try
Cstruct.blit x 0 y 0 (-1);
failwith "test_blit_len_too_small"
with Invalid_argument _ -> ()
let test_view_bounds_too_small () =
let src = Cstruct.create 4 in
let dst = Cstruct.create 4 in
let dst_small = Cstruct.sub dst 0 2 in
try
Cstruct.blit src 0 dst_small 0 3;
failwith "test_view_bounds_too_small"
with
Invalid_argument _ -> ()
let test_view_bounds_too_small_get_u8 () =
let x = Cstruct.create 2 in
let x' = Cstruct.sub x 0 1 in
try
let _ = Cstruct.get_uint8 x' 1 in
failwith "test_view_bounds_too_small_get_u8"
with
Invalid_argument _ -> ()
let test_view_bounds_too_small_get_char () =
let x = Cstruct.create 2 in
let x' = Cstruct.sub x 0 1 in
try
let _ = Cstruct.get_char x' 1 in
failwith "test_view_bounds_too_small_get_char"
with
Invalid_argument _ -> ()
let test_view_bounds_too_small_get_be16 () =
let x = Cstruct.create 4 in
let x' = Cstruct.sub x 0 1 in
try
let _ = Cstruct.BE.get_uint16 x' 0 in
failwith "test_view_bounds_too_small_get_be16"
with
Invalid_argument _ -> ()
let test_view_bounds_too_small_get_be32 () =
let x = Cstruct.create 8 in
let x' = Cstruct.sub x 2 5 in
try
let _ = Cstruct.BE.get_uint32 x' 2 in
failwith "test_view_bounds_too_small_get_be32"
with
Invalid_argument _ -> ()
let test_view_bounds_too_small_get_be64 () =
let x = Cstruct.create 9 in
let x' = Cstruct.sub x 1 5 in
try
let _ = Cstruct.BE.get_uint64 x' 0 in
failwith "test_view_bounds_too_small_get_be64"
with
Invalid_argument _ -> ()
let test_view_bounds_too_small_get_le16 () =
let x = Cstruct.create 4 in
let x' = Cstruct.sub x 0 1 in
try
let _ = Cstruct.LE.get_uint16 x' 0 in
failwith "test_view_bounds_too_small_get_le16"
with
Invalid_argument _ -> ()
let test_view_bounds_too_small_get_le32 () =
let x = Cstruct.create 8 in
let x' = Cstruct.sub x 2 5 in
try
let _ = Cstruct.LE.get_uint32 x' 2 in
failwith "test_view_bounds_too_small_get_le32"
with
Invalid_argument _ -> ()
let test_view_bounds_too_small_get_le64 () =
let x = Cstruct.create 9 in
let x' = Cstruct.sub x 1 5 in
try
let _ = Cstruct.LE.get_uint64 x' 0 in
failwith "test_view_bounds_too_small_get_le64"
with
Invalid_argument _ -> ()
let test_view_bounds_too_small_get_he16 () =
let x = Cstruct.create 4 in
let x' = Cstruct.sub x 0 1 in
try
let _ = Cstruct.HE.get_uint16 x' 0 in
failwith "test_view_bounds_too_small_get_he16"
with
Invalid_argument _ -> ()
let test_view_bounds_too_small_get_he32 () =
let x = Cstruct.create 8 in
let x' = Cstruct.sub x 2 5 in
try
let _ = Cstruct.HE.get_uint32 x' 2 in
failwith "test_view_bounds_too_small_get_he32"
with
Invalid_argument _ -> ()
let test_view_bounds_too_small_get_he64 () =
let x = Cstruct.create 9 in
let x' = Cstruct.sub x 1 5 in
try
let _ = Cstruct.HE.get_uint64 x' 0 in
failwith "test_view_bounds_too_small_get_he64"
with
Invalid_argument _ -> ()
let test_lenv_overflow () =
if Sys.word_size = 32 then (
Gc.major ();
let b = Cstruct.create max_int and c = Cstruct.create 3 in
try
let _ = Cstruct.lenv [b; b; c] in
failwith "test_lenv_overflow"
with
Invalid_argument _ -> ())
let test_copyv_overflow () =
if Sys.word_size = 32 then (
Gc.major ();
let b = Cstruct.create max_int and c = Cstruct.create 3 in
try
let _ = Cstruct.copyv [b; b; c] in
failwith "test_copyv_overflow"
with
Invalid_argument _ -> ())
Steamroll over a buffer and a contained subview , checking that only the
* contents of the subview is visible .
* contents of the subview is visible. *)
let test_subview_containment_get_char,
test_subview_containment_get_8,
test_subview_containment_get_be16,
test_subview_containment_get_be32,
test_subview_containment_get_be64,
test_subview_containment_get_le16,
test_subview_containment_get_le32,
test_subview_containment_get_le64,
test_subview_containment_get_he16,
test_subview_containment_get_he32,
test_subview_containment_get_he64
=
let open Cstruct in
let test get zero () =
let x = create 24 in
let x' = sub x 8 8 in
for i = 0 to length x - 1 do set_uint8 x i 0xff done ;
for i = 0 to length x' - 1 do set_uint8 x' i 0x00 done ;
for i = -8 to 8 do
try
let v = get x' i in
if v <> zero then
failwith "test_subview_containment_get"
with Invalid_argument _ -> ()
done
in
test get_char '\000',
test get_uint8 0,
test BE.get_uint16 0,
test BE.get_uint32 0l,
test BE.get_uint64 0L,
test LE.get_uint16 0,
test LE.get_uint32 0l,
test LE.get_uint64 0L,
test HE.get_uint16 0,
test HE.get_uint32 0l,
test HE.get_uint64 0L
Steamroll over a buffer and a contained subview , checking that only the
* contents of the subview is writable .
* contents of the subview is writable. *)
let test_subview_containment_set_char,
test_subview_containment_set_8,
test_subview_containment_set_be16,
test_subview_containment_set_be32,
test_subview_containment_set_be64,
test_subview_containment_set_le16,
test_subview_containment_set_le32,
test_subview_containment_set_le64,
test_subview_containment_set_he16,
test_subview_containment_set_he32,
test_subview_containment_set_he64
=
let open Cstruct in
let test set ff () =
let x = create 24 in
let x' = sub x 8 8 in
for i = 0 to length x - 1 do set_uint8 x i 0x00 done ;
for i = -8 to 8 do
try set x' i ff with Invalid_argument _ -> ()
done;
let acc = ref 0 in
for i = 0 to length x - 1 do
acc := !acc + get_uint8 x i
done ;
if !acc <> (length x' * 0xff) then
failwith "test_subview_containment_set"
in
test set_char '\255',
test set_uint8 0xff,
test BE.set_uint16 0xffff,
test BE.set_uint32 0xffffffffl,
test BE.set_uint64 0xffffffffffffffffL,
test LE.set_uint16 0xffff,
test LE.set_uint32 0xffffffffl,
test LE.set_uint64 0xffffffffffffffffL,
test HE.set_uint16 0xffff,
test HE.set_uint32 0xffffffffl,
test HE.set_uint64 0xffffffffffffffffL
let regression_244 () =
let whole = Cstruct.create 44943 in
let empty = Cstruct.sub whole 0 0 in
try
let _big = Cstruct.sub empty 0 204 in
Alcotest.fail "could get a bigger buffer via sub"
with Invalid_argument _ -> ()
let suite = [
"test empty cstruct", `Quick, test_empty_cstruct;
"test anti cstruct", `Quick, test_anti_cstruct;
"test positive shift", `Quick, test_positive_shift;
"test negative shift", `Quick, test_negative_shift;
"test bad positive shift", `Quick, test_bad_positive_shift;
"test sub", `Quick, test_sub;
"test sub_copy", `Quick, test_sub_copy;
"test negative sub", `Quick, test_negative_sub;
"test sub len too big", `Quick, test_sub_len_too_big;
"test sub len too small", `Quick, test_sub_len_too_small;
"test sub offset too big", `Quick, test_sub_offset_too_big;
"test of_bigarray negative params", `Quick, test_of_bigarray_negative_params;
"test of_bigarray large offset", `Quick, test_of_bigarray_large_offset;
"test of_bigarray large length", `Quick, test_of_bigarray_large_length;
"test blit offset too big", `Quick, test_blit_offset_too_big;
"test blit offset too small", `Quick, test_blit_offset_too_small;
"test blit dst offset too big", `Quick, test_blit_dst_offset_too_big;
"test blit dst offset too small", `Quick, test_blit_dst_offset_too_small;
"test blit dst offset negative", `Quick, test_blit_dst_offset_negative;
"test blit len too big", `Quick, test_blit_len_too_big;
"test blit len too big2", `Quick, test_blit_len_too_big2;
"test blit len too small", `Quick, test_blit_len_too_small;
"test view bounds too small", `Quick, test_view_bounds_too_small;
"test_view_bounds_too_small_get_u8" , `Quick, test_view_bounds_too_small_get_u8;
"test_view_bounds_too_small_get_char" , `Quick, test_view_bounds_too_small_get_char;
"test_view_bounds_too_small_get_be16" , `Quick, test_view_bounds_too_small_get_be16;
"test_view_bounds_too_small_get_be32" , `Quick, test_view_bounds_too_small_get_be32;
"test_view_bounds_too_small_get_be64" , `Quick, test_view_bounds_too_small_get_be64;
"test_view_bounds_too_small_get_le16" , `Quick, test_view_bounds_too_small_get_le16;
"test_view_bounds_too_small_get_le32" , `Quick, test_view_bounds_too_small_get_le32;
"test_view_bounds_too_small_get_le64" , `Quick, test_view_bounds_too_small_get_le64;
"test_view_bounds_too_small_get_he16" , `Quick, test_view_bounds_too_small_get_he16;
"test_view_bounds_too_small_get_he32" , `Quick, test_view_bounds_too_small_get_he32;
"test_view_bounds_too_small_get_he64" , `Quick, test_view_bounds_too_small_get_he64;
"test_lenv_overflow", `Quick, test_lenv_overflow;
"test_copyv_overflow", `Quick, test_copyv_overflow;
"test_subview_containment_get_char", `Quick, test_subview_containment_get_char;
"test_subview_containment_get_8" , `Quick, test_subview_containment_get_8;
"test_subview_containment_get_be16", `Quick, test_subview_containment_get_be16;
"test_subview_containment_get_be32", `Quick, test_subview_containment_get_be32;
"test_subview_containment_get_be64", `Quick, test_subview_containment_get_be64;
"test_subview_containment_get_le16", `Quick, test_subview_containment_get_le16;
"test_subview_containment_get_le32", `Quick, test_subview_containment_get_le32;
"test_subview_containment_get_le64", `Quick, test_subview_containment_get_le64;
"test_subview_containment_get_le16", `Quick, test_subview_containment_get_he16;
"test_subview_containment_get_le32", `Quick, test_subview_containment_get_he32;
"test_subview_containment_get_le64", `Quick, test_subview_containment_get_he64;
"test_subview_containment_set_char", `Quick, test_subview_containment_set_char;
"test_subview_containment_set_8" , `Quick, test_subview_containment_set_8;
"test_subview_containment_set_be16", `Quick, test_subview_containment_set_be16;
"test_subview_containment_set_be32", `Quick, test_subview_containment_set_be32;
"test_subview_containment_set_be64", `Quick, test_subview_containment_set_be64;
"test_subview_containment_set_le16", `Quick, test_subview_containment_set_le16;
"test_subview_containment_set_le32", `Quick, test_subview_containment_set_le32;
"test_subview_containment_set_le64", `Quick, test_subview_containment_set_le64;
"test_subview_containment_set_le16", `Quick, test_subview_containment_set_he16;
"test_subview_containment_set_le32", `Quick, test_subview_containment_set_he32;
"test_subview_containment_set_le64", `Quick, test_subview_containment_set_he64;
"regression 244", `Quick, regression_244;
]
|
1920ba000466988d81b5ea0db04f554d064e45b06980d1ac4157002050492c31 | lojic/LearningRacket | day01-min.rkt | #lang racket
(require "../../advent/advent.rkt")
(define input (file->list "day01.txt"))
(define (count-increases lst)
(car (foldl (match-lambda* [ (list n (cons count last)) (cons (+ count (if (> n last) 1 0)) n) ])
(cons 0 (car lst))
(cdr lst))))
(define (windows-3 lst) (zipn lst (cdr lst) (cddr lst)))
(define (part1) (count-increases input))
(define (part2) (count-increases (map sum (windows-3 input))))
| null | https://raw.githubusercontent.com/lojic/LearningRacket/00951818e2d160989e1b56cf00dfa38b55b6f4a9/advent-of-code-2021/solutions/day01/day01-min.rkt | racket | #lang racket
(require "../../advent/advent.rkt")
(define input (file->list "day01.txt"))
(define (count-increases lst)
(car (foldl (match-lambda* [ (list n (cons count last)) (cons (+ count (if (> n last) 1 0)) n) ])
(cons 0 (car lst))
(cdr lst))))
(define (windows-3 lst) (zipn lst (cdr lst) (cddr lst)))
(define (part1) (count-increases input))
(define (part2) (count-increases (map sum (windows-3 input))))
| |
879d7e62796916f635c0367395f7f6b902eb06f7578395a8a2cd380b09fe2cf4 | spawnfest/eep49ers | wxBitmap.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2008 - 2020 . All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%% This file is generated DO NOT EDIT
-module(wxBitmap).
-include("wxe.hrl").
-export([convertToImage/1,copyFromIcon/2,create/2,create/3,create/4,destroy/1,
getDepth/1,getHeight/1,getMask/1,getPalette/1,getSubBitmap/2,getWidth/1,
isOk/1,loadFile/2,loadFile/3,new/0,new/1,new/2,new/3,new/4,ok/1,saveFile/3,
saveFile/4,setDepth/2,setHeight/2,setMask/2,setPalette/2,setWidth/2]).
%% inherited exports
-export([parent_class/1]).
-type wxBitmap() :: wx:wx_object().
-export_type([wxBitmap/0]).
%% @hidden
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
%% @doc See <a href="#wxbitmapwxbitmap">external documentation</a>.
-spec new() -> wxBitmap().
new() ->
wxe_util:queue_cmd(?get_env(), ?wxBitmap_new_0),
wxe_util:rec(?wxBitmap_new_0).
%% @doc See <a href="#wxbitmapwxbitmap">external documentation</a>.
%% <br /> Also:<br />
%% new(Sz) -> wxBitmap() when<br />
Sz::{W::integer ( ) , H::integer()};<br / >
( ) - > wxBitmap ( ) when < br / >
%% Img::wxImage:wxImage() | wxBitmap:wxBitmap().<br />
%%
< br / > Type = ? wxBITMAP_TYPE_INVALID | ? wxBITMAP_TYPE_BMP | ? wxBITMAP_TYPE_BMP_RESOURCE | ? wxBITMAP_TYPE_RESOURCE | ? wxBITMAP_TYPE_ICO | ? | ? wxBITMAP_TYPE_CUR | ? | ? wxBITMAP_TYPE_XBM | ? wxBITMAP_TYPE_XBM_DATA | ? wxBITMAP_TYPE_XPM | ? wxBITMAP_TYPE_XPM_DATA | ? wxBITMAP_TYPE_TIFF | ? wxBITMAP_TYPE_TIF | ? wxBITMAP_TYPE_TIFF_RESOURCE | ? wxBITMAP_TYPE_TIF_RESOURCE | ? wxBITMAP_TYPE_GIF | ? wxBITMAP_TYPE_GIF_RESOURCE | ? wxBITMAP_TYPE_PNG | ? wxBITMAP_TYPE_PNG_RESOURCE | ? wxBITMAP_TYPE_JPEG | ? wxBITMAP_TYPE_JPEG_RESOURCE | ? wxBITMAP_TYPE_PNM | ? wxBITMAP_TYPE_PNM_RESOURCE | ? | ? ? wxBITMAP_TYPE_PICT | ? wxBITMAP_TYPE_PICT_RESOURCE | ? wxBITMAP_TYPE_ICON | ? | ? wxBITMAP_TYPE_ANI | ? wxBITMAP_TYPE_IFF | ? wxBITMAP_TYPE_TGA | ? wxBITMAP_TYPE_MACCURSOR | ? wxBITMAP_TYPE_MACCURSOR_RESOURCE | ? wxBITMAP_TYPE_ANY
-spec new(Name) -> wxBitmap() when
Name::unicode:chardata();
(Sz) -> wxBitmap() when
Sz::{W::integer(), H::integer()};
(Img) -> wxBitmap() when
Img::wxImage:wxImage() | wxBitmap:wxBitmap().
new(Name)
when ?is_chardata(Name) ->
new(Name, []);
new({SzW,SzH} = Sz)
when is_integer(SzW),is_integer(SzH) ->
new(Sz, []);
new(#wx_ref{type=ImgT}=Img) ->
IswxImage = ?CLASS_T(ImgT,wxImage),
IswxBitmap = ?CLASS_T(ImgT,wxBitmap),
ImgType = if
IswxImage -> wxImage;
IswxBitmap -> wxBitmap;
true -> error({badarg, ImgT})
end,
wxe_util:queue_cmd(wx:typeCast(Img, ImgType),?get_env(),?wxBitmap_new_2_3),
wxe_util:rec(?wxBitmap_new_2_3).
%% @doc See <a href="#wxbitmapwxbitmap">external documentation</a>.
%% <br /> Also:<br />
%% new(Name, [Option]) -> wxBitmap() when<br />
Name::unicode : chardata(),<br / >
%% Option :: {'type', wx:wx_enum()};<br />
%% (Sz, [Option]) -> wxBitmap() when<br />
Sz::{W::integer ( ) , H::integer()},<br / >
%% Option :: {'depth', integer()};<br />
( , [ Option ] ) - > wxBitmap ( ) when < br / >
%% Img::wxImage:wxImage(),<br />
%% Option :: {'depth', integer()}.<br />
%%
< br / > Type = ? wxBITMAP_TYPE_INVALID | ? wxBITMAP_TYPE_BMP | ? wxBITMAP_TYPE_BMP_RESOURCE | ? wxBITMAP_TYPE_RESOURCE | ? wxBITMAP_TYPE_ICO | ? | ? wxBITMAP_TYPE_CUR | ? | ? wxBITMAP_TYPE_XBM | ? wxBITMAP_TYPE_XBM_DATA | ? wxBITMAP_TYPE_XPM | ? wxBITMAP_TYPE_XPM_DATA | ? wxBITMAP_TYPE_TIFF | ? wxBITMAP_TYPE_TIF | ? wxBITMAP_TYPE_TIFF_RESOURCE | ? wxBITMAP_TYPE_TIF_RESOURCE | ? wxBITMAP_TYPE_GIF | ? wxBITMAP_TYPE_GIF_RESOURCE | ? wxBITMAP_TYPE_PNG | ? wxBITMAP_TYPE_PNG_RESOURCE | ? wxBITMAP_TYPE_JPEG | ? wxBITMAP_TYPE_JPEG_RESOURCE | ? wxBITMAP_TYPE_PNM | ? wxBITMAP_TYPE_PNM_RESOURCE | ? | ? ? wxBITMAP_TYPE_PICT | ? wxBITMAP_TYPE_PICT_RESOURCE | ? wxBITMAP_TYPE_ICON | ? | ? wxBITMAP_TYPE_ANI | ? wxBITMAP_TYPE_IFF | ? wxBITMAP_TYPE_TGA | ? wxBITMAP_TYPE_MACCURSOR | ? wxBITMAP_TYPE_MACCURSOR_RESOURCE | ? wxBITMAP_TYPE_ANY
-spec new(Width, Height) -> wxBitmap() when
Width::integer(), Height::integer();
(Name, [Option]) -> wxBitmap() when
Name::unicode:chardata(),
Option :: {'type', wx:wx_enum()};
(Sz, [Option]) -> wxBitmap() when
Sz::{W::integer(), H::integer()},
Option :: {'depth', integer()};
(Img, [Option]) -> wxBitmap() when
Img::wxImage:wxImage(),
Option :: {'depth', integer()}.
new(Width,Height)
when is_integer(Width),is_integer(Height) ->
new(Width,Height, []);
new(Name, Options)
when ?is_chardata(Name),is_list(Options) ->
Name_UC = unicode:characters_to_binary(Name),
MOpts = fun({type, _type} = Arg) -> Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(Name_UC, Opts,?get_env(),?wxBitmap_new_2_0),
wxe_util:rec(?wxBitmap_new_2_0);
new({SzW,SzH} = Sz, Options)
when is_integer(SzW),is_integer(SzH),is_list(Options) ->
MOpts = fun({depth, _depth} = Arg) -> Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(Sz, Opts,?get_env(),?wxBitmap_new_2_1),
wxe_util:rec(?wxBitmap_new_2_1);
new(#wx_ref{type=ImgT}=Img, Options)
when is_list(Options) ->
?CLASS(ImgT,wxImage),
MOpts = fun({depth, _depth} = Arg) -> Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(Img, Opts,?get_env(),?wxBitmap_new_2_2),
wxe_util:rec(?wxBitmap_new_2_2).
%% @doc See <a href="#wxbitmapwxbitmap">external documentation</a>.
%% <br /> Also:<br />
new(Width , , [ Option ] ) - > wxBitmap ( ) when < br / >
%% Width::integer(), Height::integer(),<br />
%% Option :: {'depth', integer()}.<br />
%%
-spec new(Bits, Width, Height) -> wxBitmap() when
Bits::binary(), Width::integer(), Height::integer();
(Width, Height, [Option]) -> wxBitmap() when
Width::integer(), Height::integer(),
Option :: {'depth', integer()}.
new(Bits,Width,Height)
when is_binary(Bits),is_integer(Width),is_integer(Height) ->
new(Bits,Width,Height, []);
new(Width,Height, Options)
when is_integer(Width),is_integer(Height),is_list(Options) ->
MOpts = fun({depth, _depth} = Arg) -> Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(Width,Height, Opts,?get_env(),?wxBitmap_new_3),
wxe_util:rec(?wxBitmap_new_3).
%% @doc See <a href="#wxbitmapwxbitmap">external documentation</a>.
-spec new(Bits, Width, Height, [Option]) -> wxBitmap() when
Bits::binary(), Width::integer(), Height::integer(),
Option :: {'depth', integer()}.
new(Bits,Width,Height, Options)
when is_binary(Bits),is_integer(Width),is_integer(Height),is_list(Options) ->
MOpts = fun({depth, _depth} = Arg) -> Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(Bits,Width,Height, Opts,?get_env(),?wxBitmap_new_4),
wxe_util:rec(?wxBitmap_new_4).
%% @doc See <a href="#wxbitmapconverttoimage">external documentation</a>.
-spec convertToImage(This) -> wxImage:wxImage() when
This::wxBitmap().
convertToImage(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxBitmap),
wxe_util:queue_cmd(This,?get_env(),?wxBitmap_ConvertToImage),
wxe_util:rec(?wxBitmap_ConvertToImage).
%% @doc See <a href="#wxbitmapcopyfromicon">external documentation</a>.
-spec copyFromIcon(This, Icon) -> boolean() when
This::wxBitmap(), Icon::wxIcon:wxIcon().
copyFromIcon(#wx_ref{type=ThisT}=This,#wx_ref{type=IconT}=Icon) ->
?CLASS(ThisT,wxBitmap),
?CLASS(IconT,wxIcon),
wxe_util:queue_cmd(This,Icon,?get_env(),?wxBitmap_CopyFromIcon),
wxe_util:rec(?wxBitmap_CopyFromIcon).
%% @equiv create(This,Sz, [])
-spec create(This, Sz) -> boolean() when
This::wxBitmap(), Sz::{W::integer(), H::integer()}.
create(This,{SzW,SzH} = Sz)
when is_record(This, wx_ref),is_integer(SzW),is_integer(SzH) ->
create(This,Sz, []).
@doc See < a href=" / manuals/2.8.12 / wx_wxbitmap.html#wxbitmapcreate">external documentation</a > .
%% <br /> Also:<br />
create(This , , [ Option ] ) - > boolean ( ) when < br / >
This::wxBitmap ( ) , Sz::{W::integer ( ) , H::integer()},<br / >
%% Option :: {'depth', integer()}.<br />
%%
-spec create(This, Width, Height) -> boolean() when
This::wxBitmap(), Width::integer(), Height::integer();
(This, Sz, [Option]) -> boolean() when
This::wxBitmap(), Sz::{W::integer(), H::integer()},
Option :: {'depth', integer()}.
create(This,Width,Height)
when is_record(This, wx_ref),is_integer(Width),is_integer(Height) ->
create(This,Width,Height, []);
create(#wx_ref{type=ThisT}=This,{SzW,SzH} = Sz, Options)
when is_integer(SzW),is_integer(SzH),is_list(Options) ->
?CLASS(ThisT,wxBitmap),
MOpts = fun({depth, _depth} = Arg) -> Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(This,Sz, Opts,?get_env(),?wxBitmap_Create_2),
wxe_util:rec(?wxBitmap_Create_2).
@doc See < a href=" / manuals/2.8.12 / wx_wxbitmap.html#wxbitmapcreate">external documentation</a > .
%% <br /> Also:<br />
create(This , , Height , Dc ) - > boolean ( ) when < br / >
%% This::wxBitmap(), Width::integer(), Height::integer(), Dc::wxDC:wxDC().<br />
%%
-spec create(This, Width, Height, [Option]) -> boolean() when
This::wxBitmap(), Width::integer(), Height::integer(),
Option :: {'depth', integer()};
(This, Width, Height, Dc) -> boolean() when
This::wxBitmap(), Width::integer(), Height::integer(), Dc::wxDC:wxDC().
create(#wx_ref{type=ThisT}=This,Width,Height, Options)
when is_integer(Width),is_integer(Height),is_list(Options) ->
?CLASS(ThisT,wxBitmap),
MOpts = fun({depth, _depth} = Arg) -> Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(This,Width,Height, Opts,?get_env(),?wxBitmap_Create_3_0),
wxe_util:rec(?wxBitmap_Create_3_0);
create(#wx_ref{type=ThisT}=This,Width,Height,#wx_ref{type=DcT}=Dc)
when is_integer(Width),is_integer(Height) ->
?CLASS(ThisT,wxBitmap),
?CLASS(DcT,wxDC),
wxe_util:queue_cmd(This,Width,Height,Dc,?get_env(),?wxBitmap_Create_3_1),
wxe_util:rec(?wxBitmap_Create_3_1).
%% @doc See <a href="#wxbitmapgetdepth">external documentation</a>.
-spec getDepth(This) -> integer() when
This::wxBitmap().
getDepth(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxBitmap),
wxe_util:queue_cmd(This,?get_env(),?wxBitmap_GetDepth),
wxe_util:rec(?wxBitmap_GetDepth).
%% @doc See <a href="#wxbitmapgetheight">external documentation</a>.
-spec getHeight(This) -> integer() when
This::wxBitmap().
getHeight(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxBitmap),
wxe_util:queue_cmd(This,?get_env(),?wxBitmap_GetHeight),
wxe_util:rec(?wxBitmap_GetHeight).
%% @doc See <a href="#wxbitmapgetpalette">external documentation</a>.
-spec getPalette(This) -> wxPalette:wxPalette() when
This::wxBitmap().
getPalette(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxBitmap),
wxe_util:queue_cmd(This,?get_env(),?wxBitmap_GetPalette),
wxe_util:rec(?wxBitmap_GetPalette).
%% @doc See <a href="#wxbitmapgetmask">external documentation</a>.
-spec getMask(This) -> wxMask:wxMask() when
This::wxBitmap().
getMask(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxBitmap),
wxe_util:queue_cmd(This,?get_env(),?wxBitmap_GetMask),
wxe_util:rec(?wxBitmap_GetMask).
%% @doc See <a href="#wxbitmapgetwidth">external documentation</a>.
-spec getWidth(This) -> integer() when
This::wxBitmap().
getWidth(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxBitmap),
wxe_util:queue_cmd(This,?get_env(),?wxBitmap_GetWidth),
wxe_util:rec(?wxBitmap_GetWidth).
%% @doc See <a href="#wxbitmapgetsubbitmap">external documentation</a>.
-spec getSubBitmap(This, Rect) -> wxBitmap() when
This::wxBitmap(), Rect::{X::integer(), Y::integer(), W::integer(), H::integer()}.
getSubBitmap(#wx_ref{type=ThisT}=This,{RectX,RectY,RectW,RectH} = Rect)
when is_integer(RectX),is_integer(RectY),is_integer(RectW),is_integer(RectH) ->
?CLASS(ThisT,wxBitmap),
wxe_util:queue_cmd(This,Rect,?get_env(),?wxBitmap_GetSubBitmap),
wxe_util:rec(?wxBitmap_GetSubBitmap).
%% @equiv loadFile(This,Name, [])
-spec loadFile(This, Name) -> boolean() when
This::wxBitmap(), Name::unicode:chardata().
loadFile(This,Name)
when is_record(This, wx_ref),?is_chardata(Name) ->
loadFile(This,Name, []).
%% @doc See <a href="#wxbitmaploadfile">external documentation</a>.
< br / > Type = ? wxBITMAP_TYPE_INVALID | ? wxBITMAP_TYPE_BMP | ? wxBITMAP_TYPE_BMP_RESOURCE | ? wxBITMAP_TYPE_RESOURCE | ? wxBITMAP_TYPE_ICO | ? | ? wxBITMAP_TYPE_CUR | ? | ? wxBITMAP_TYPE_XBM | ? wxBITMAP_TYPE_XBM_DATA | ? wxBITMAP_TYPE_XPM | ? wxBITMAP_TYPE_XPM_DATA | ? wxBITMAP_TYPE_TIFF | ? wxBITMAP_TYPE_TIF | ? wxBITMAP_TYPE_TIFF_RESOURCE | ? wxBITMAP_TYPE_TIF_RESOURCE | ? wxBITMAP_TYPE_GIF | ? wxBITMAP_TYPE_GIF_RESOURCE | ? wxBITMAP_TYPE_PNG | ? wxBITMAP_TYPE_PNG_RESOURCE | ? wxBITMAP_TYPE_JPEG | ? wxBITMAP_TYPE_JPEG_RESOURCE | ? wxBITMAP_TYPE_PNM | ? wxBITMAP_TYPE_PNM_RESOURCE | ? | ? ? wxBITMAP_TYPE_PICT | ? wxBITMAP_TYPE_PICT_RESOURCE | ? wxBITMAP_TYPE_ICON | ? | ? wxBITMAP_TYPE_ANI | ? wxBITMAP_TYPE_IFF | ? wxBITMAP_TYPE_TGA | ? wxBITMAP_TYPE_MACCURSOR | ? wxBITMAP_TYPE_MACCURSOR_RESOURCE | ? wxBITMAP_TYPE_ANY
-spec loadFile(This, Name, [Option]) -> boolean() when
This::wxBitmap(), Name::unicode:chardata(),
Option :: {'type', wx:wx_enum()}.
loadFile(#wx_ref{type=ThisT}=This,Name, Options)
when ?is_chardata(Name),is_list(Options) ->
?CLASS(ThisT,wxBitmap),
Name_UC = unicode:characters_to_binary(Name),
MOpts = fun({type, _type} = Arg) -> Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(This,Name_UC, Opts,?get_env(),?wxBitmap_LoadFile),
wxe_util:rec(?wxBitmap_LoadFile).
%% @doc See <a href="#wxbitmapisok">external documentation</a>.
-spec ok(This) -> boolean() when
This::wxBitmap().
ok(This)
when is_record(This, wx_ref) ->
isOk(This).
%% @doc See <a href="#wxbitmapisok">external documentation</a>.
-spec isOk(This) -> boolean() when
This::wxBitmap().
isOk(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxBitmap),
wxe_util:queue_cmd(This,?get_env(),?wxBitmap_IsOk),
wxe_util:rec(?wxBitmap_IsOk).
%% @equiv saveFile(This,Name,Type, [])
-spec saveFile(This, Name, Type) -> boolean() when
This::wxBitmap(), Name::unicode:chardata(), Type::wx:wx_enum().
saveFile(This,Name,Type)
when is_record(This, wx_ref),?is_chardata(Name),is_integer(Type) ->
saveFile(This,Name,Type, []).
%% @doc See <a href="#wxbitmapsavefile">external documentation</a>.
< br / > Type = ? wxBITMAP_TYPE_INVALID | ? wxBITMAP_TYPE_BMP | ? wxBITMAP_TYPE_BMP_RESOURCE | ? wxBITMAP_TYPE_RESOURCE | ? wxBITMAP_TYPE_ICO | ? | ? wxBITMAP_TYPE_CUR | ? | ? wxBITMAP_TYPE_XBM | ? wxBITMAP_TYPE_XBM_DATA | ? wxBITMAP_TYPE_XPM | ? wxBITMAP_TYPE_XPM_DATA | ? wxBITMAP_TYPE_TIFF | ? wxBITMAP_TYPE_TIF | ? wxBITMAP_TYPE_TIFF_RESOURCE | ? wxBITMAP_TYPE_TIF_RESOURCE | ? wxBITMAP_TYPE_GIF | ? wxBITMAP_TYPE_GIF_RESOURCE | ? wxBITMAP_TYPE_PNG | ? wxBITMAP_TYPE_PNG_RESOURCE | ? wxBITMAP_TYPE_JPEG | ? wxBITMAP_TYPE_JPEG_RESOURCE | ? wxBITMAP_TYPE_PNM | ? wxBITMAP_TYPE_PNM_RESOURCE | ? | ? ? wxBITMAP_TYPE_PICT | ? wxBITMAP_TYPE_PICT_RESOURCE | ? wxBITMAP_TYPE_ICON | ? | ? wxBITMAP_TYPE_ANI | ? wxBITMAP_TYPE_IFF | ? wxBITMAP_TYPE_TGA | ? wxBITMAP_TYPE_MACCURSOR | ? wxBITMAP_TYPE_MACCURSOR_RESOURCE | ? wxBITMAP_TYPE_ANY
-spec saveFile(This, Name, Type, [Option]) -> boolean() when
This::wxBitmap(), Name::unicode:chardata(), Type::wx:wx_enum(),
Option :: {'palette', wxPalette:wxPalette()}.
saveFile(#wx_ref{type=ThisT}=This,Name,Type, Options)
when ?is_chardata(Name),is_integer(Type),is_list(Options) ->
?CLASS(ThisT,wxBitmap),
Name_UC = unicode:characters_to_binary(Name),
MOpts = fun({palette, #wx_ref{type=PaletteT}} = Arg) -> ?CLASS(PaletteT,wxPalette),Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(This,Name_UC,Type, Opts,?get_env(),?wxBitmap_SaveFile),
wxe_util:rec(?wxBitmap_SaveFile).
@doc See < a href=" / manuals/2.8.12 / wx_wxbitmap.html#wxbitmapsetdepth">external documentation</a > .
-spec setDepth(This, Depth) -> 'ok' when
This::wxBitmap(), Depth::integer().
setDepth(#wx_ref{type=ThisT}=This,Depth)
when is_integer(Depth) ->
?CLASS(ThisT,wxBitmap),
wxe_util:queue_cmd(This,Depth,?get_env(),?wxBitmap_SetDepth).
%% @doc See <a href="#wxbitmapsetheight">external documentation</a>.
-spec setHeight(This, Height) -> 'ok' when
This::wxBitmap(), Height::integer().
setHeight(#wx_ref{type=ThisT}=This,Height)
when is_integer(Height) ->
?CLASS(ThisT,wxBitmap),
wxe_util:queue_cmd(This,Height,?get_env(),?wxBitmap_SetHeight).
%% @doc See <a href="#wxbitmapsetmask">external documentation</a>.
-spec setMask(This, Mask) -> 'ok' when
This::wxBitmap(), Mask::wxMask:wxMask().
setMask(#wx_ref{type=ThisT}=This,#wx_ref{type=MaskT}=Mask) ->
?CLASS(ThisT,wxBitmap),
?CLASS(MaskT,wxMask),
wxe_util:queue_cmd(This,Mask,?get_env(),?wxBitmap_SetMask).
%% @doc See <a href="#wxbitmapsetpalette">external documentation</a>.
-spec setPalette(This, Palette) -> 'ok' when
This::wxBitmap(), Palette::wxPalette:wxPalette().
setPalette(#wx_ref{type=ThisT}=This,#wx_ref{type=PaletteT}=Palette) ->
?CLASS(ThisT,wxBitmap),
?CLASS(PaletteT,wxPalette),
wxe_util:queue_cmd(This,Palette,?get_env(),?wxBitmap_SetPalette).
@doc See < a href=" / manuals/2.8.12 / wx_wxbitmap.html#wxbitmapsetwidth">external documentation</a > .
-spec setWidth(This, Width) -> 'ok' when
This::wxBitmap(), Width::integer().
setWidth(#wx_ref{type=ThisT}=This,Width)
when is_integer(Width) ->
?CLASS(ThisT,wxBitmap),
wxe_util:queue_cmd(This,Width,?get_env(),?wxBitmap_SetWidth).
%% @doc Destroys this object, do not use object again
-spec destroy(This::wxBitmap()) -> 'ok'.
destroy(Obj=#wx_ref{type=Type}) ->
?CLASS(Type,wxBitmap),
wxe_util:queue_cmd(Obj, ?get_env(), ?DESTROY_OBJECT),
ok.
| null | https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/wx/src/gen/wxBitmap.erl | erlang |
%CopyrightBegin%
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
%CopyrightEnd%
This file is generated DO NOT EDIT
inherited exports
@hidden
@doc See <a href="#wxbitmapwxbitmap">external documentation</a>.
@doc See <a href="#wxbitmapwxbitmap">external documentation</a>.
<br /> Also:<br />
new(Sz) -> wxBitmap() when<br />
Img::wxImage:wxImage() | wxBitmap:wxBitmap().<br />
@doc See <a href="#wxbitmapwxbitmap">external documentation</a>.
<br /> Also:<br />
new(Name, [Option]) -> wxBitmap() when<br />
Option :: {'type', wx:wx_enum()};<br />
(Sz, [Option]) -> wxBitmap() when<br />
Option :: {'depth', integer()};<br />
Img::wxImage:wxImage(),<br />
Option :: {'depth', integer()}.<br />
@doc See <a href="#wxbitmapwxbitmap">external documentation</a>.
<br /> Also:<br />
Width::integer(), Height::integer(),<br />
Option :: {'depth', integer()}.<br />
@doc See <a href="#wxbitmapwxbitmap">external documentation</a>.
@doc See <a href="#wxbitmapconverttoimage">external documentation</a>.
@doc See <a href="#wxbitmapcopyfromicon">external documentation</a>.
@equiv create(This,Sz, [])
<br /> Also:<br />
Option :: {'depth', integer()}.<br />
<br /> Also:<br />
This::wxBitmap(), Width::integer(), Height::integer(), Dc::wxDC:wxDC().<br />
@doc See <a href="#wxbitmapgetdepth">external documentation</a>.
@doc See <a href="#wxbitmapgetheight">external documentation</a>.
@doc See <a href="#wxbitmapgetpalette">external documentation</a>.
@doc See <a href="#wxbitmapgetmask">external documentation</a>.
@doc See <a href="#wxbitmapgetwidth">external documentation</a>.
@doc See <a href="#wxbitmapgetsubbitmap">external documentation</a>.
@equiv loadFile(This,Name, [])
@doc See <a href="#wxbitmaploadfile">external documentation</a>.
@doc See <a href="#wxbitmapisok">external documentation</a>.
@doc See <a href="#wxbitmapisok">external documentation</a>.
@equiv saveFile(This,Name,Type, [])
@doc See <a href="#wxbitmapsavefile">external documentation</a>.
@doc See <a href="#wxbitmapsetheight">external documentation</a>.
@doc See <a href="#wxbitmapsetmask">external documentation</a>.
@doc See <a href="#wxbitmapsetpalette">external documentation</a>.
@doc Destroys this object, do not use object again | Copyright Ericsson AB 2008 - 2020 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(wxBitmap).
-include("wxe.hrl").
-export([convertToImage/1,copyFromIcon/2,create/2,create/3,create/4,destroy/1,
getDepth/1,getHeight/1,getMask/1,getPalette/1,getSubBitmap/2,getWidth/1,
isOk/1,loadFile/2,loadFile/3,new/0,new/1,new/2,new/3,new/4,ok/1,saveFile/3,
saveFile/4,setDepth/2,setHeight/2,setMask/2,setPalette/2,setWidth/2]).
-export([parent_class/1]).
-type wxBitmap() :: wx:wx_object().
-export_type([wxBitmap/0]).
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
-spec new() -> wxBitmap().
new() ->
wxe_util:queue_cmd(?get_env(), ?wxBitmap_new_0),
wxe_util:rec(?wxBitmap_new_0).
Sz::{W::integer ( ) , H::integer()};<br / >
( ) - > wxBitmap ( ) when < br / >
< br / > Type = ? wxBITMAP_TYPE_INVALID | ? wxBITMAP_TYPE_BMP | ? wxBITMAP_TYPE_BMP_RESOURCE | ? wxBITMAP_TYPE_RESOURCE | ? wxBITMAP_TYPE_ICO | ? | ? wxBITMAP_TYPE_CUR | ? | ? wxBITMAP_TYPE_XBM | ? wxBITMAP_TYPE_XBM_DATA | ? wxBITMAP_TYPE_XPM | ? wxBITMAP_TYPE_XPM_DATA | ? wxBITMAP_TYPE_TIFF | ? wxBITMAP_TYPE_TIF | ? wxBITMAP_TYPE_TIFF_RESOURCE | ? wxBITMAP_TYPE_TIF_RESOURCE | ? wxBITMAP_TYPE_GIF | ? wxBITMAP_TYPE_GIF_RESOURCE | ? wxBITMAP_TYPE_PNG | ? wxBITMAP_TYPE_PNG_RESOURCE | ? wxBITMAP_TYPE_JPEG | ? wxBITMAP_TYPE_JPEG_RESOURCE | ? wxBITMAP_TYPE_PNM | ? wxBITMAP_TYPE_PNM_RESOURCE | ? | ? ? wxBITMAP_TYPE_PICT | ? wxBITMAP_TYPE_PICT_RESOURCE | ? wxBITMAP_TYPE_ICON | ? | ? wxBITMAP_TYPE_ANI | ? wxBITMAP_TYPE_IFF | ? wxBITMAP_TYPE_TGA | ? wxBITMAP_TYPE_MACCURSOR | ? wxBITMAP_TYPE_MACCURSOR_RESOURCE | ? wxBITMAP_TYPE_ANY
-spec new(Name) -> wxBitmap() when
Name::unicode:chardata();
(Sz) -> wxBitmap() when
Sz::{W::integer(), H::integer()};
(Img) -> wxBitmap() when
Img::wxImage:wxImage() | wxBitmap:wxBitmap().
new(Name)
when ?is_chardata(Name) ->
new(Name, []);
new({SzW,SzH} = Sz)
when is_integer(SzW),is_integer(SzH) ->
new(Sz, []);
new(#wx_ref{type=ImgT}=Img) ->
IswxImage = ?CLASS_T(ImgT,wxImage),
IswxBitmap = ?CLASS_T(ImgT,wxBitmap),
ImgType = if
IswxImage -> wxImage;
IswxBitmap -> wxBitmap;
true -> error({badarg, ImgT})
end,
wxe_util:queue_cmd(wx:typeCast(Img, ImgType),?get_env(),?wxBitmap_new_2_3),
wxe_util:rec(?wxBitmap_new_2_3).
Name::unicode : chardata(),<br / >
Sz::{W::integer ( ) , H::integer()},<br / >
( , [ Option ] ) - > wxBitmap ( ) when < br / >
< br / > Type = ? wxBITMAP_TYPE_INVALID | ? wxBITMAP_TYPE_BMP | ? wxBITMAP_TYPE_BMP_RESOURCE | ? wxBITMAP_TYPE_RESOURCE | ? wxBITMAP_TYPE_ICO | ? | ? wxBITMAP_TYPE_CUR | ? | ? wxBITMAP_TYPE_XBM | ? wxBITMAP_TYPE_XBM_DATA | ? wxBITMAP_TYPE_XPM | ? wxBITMAP_TYPE_XPM_DATA | ? wxBITMAP_TYPE_TIFF | ? wxBITMAP_TYPE_TIF | ? wxBITMAP_TYPE_TIFF_RESOURCE | ? wxBITMAP_TYPE_TIF_RESOURCE | ? wxBITMAP_TYPE_GIF | ? wxBITMAP_TYPE_GIF_RESOURCE | ? wxBITMAP_TYPE_PNG | ? wxBITMAP_TYPE_PNG_RESOURCE | ? wxBITMAP_TYPE_JPEG | ? wxBITMAP_TYPE_JPEG_RESOURCE | ? wxBITMAP_TYPE_PNM | ? wxBITMAP_TYPE_PNM_RESOURCE | ? | ? ? wxBITMAP_TYPE_PICT | ? wxBITMAP_TYPE_PICT_RESOURCE | ? wxBITMAP_TYPE_ICON | ? | ? wxBITMAP_TYPE_ANI | ? wxBITMAP_TYPE_IFF | ? wxBITMAP_TYPE_TGA | ? wxBITMAP_TYPE_MACCURSOR | ? wxBITMAP_TYPE_MACCURSOR_RESOURCE | ? wxBITMAP_TYPE_ANY
-spec new(Width, Height) -> wxBitmap() when
Width::integer(), Height::integer();
(Name, [Option]) -> wxBitmap() when
Name::unicode:chardata(),
Option :: {'type', wx:wx_enum()};
(Sz, [Option]) -> wxBitmap() when
Sz::{W::integer(), H::integer()},
Option :: {'depth', integer()};
(Img, [Option]) -> wxBitmap() when
Img::wxImage:wxImage(),
Option :: {'depth', integer()}.
new(Width,Height)
when is_integer(Width),is_integer(Height) ->
new(Width,Height, []);
new(Name, Options)
when ?is_chardata(Name),is_list(Options) ->
Name_UC = unicode:characters_to_binary(Name),
MOpts = fun({type, _type} = Arg) -> Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(Name_UC, Opts,?get_env(),?wxBitmap_new_2_0),
wxe_util:rec(?wxBitmap_new_2_0);
new({SzW,SzH} = Sz, Options)
when is_integer(SzW),is_integer(SzH),is_list(Options) ->
MOpts = fun({depth, _depth} = Arg) -> Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(Sz, Opts,?get_env(),?wxBitmap_new_2_1),
wxe_util:rec(?wxBitmap_new_2_1);
new(#wx_ref{type=ImgT}=Img, Options)
when is_list(Options) ->
?CLASS(ImgT,wxImage),
MOpts = fun({depth, _depth} = Arg) -> Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(Img, Opts,?get_env(),?wxBitmap_new_2_2),
wxe_util:rec(?wxBitmap_new_2_2).
new(Width , , [ Option ] ) - > wxBitmap ( ) when < br / >
-spec new(Bits, Width, Height) -> wxBitmap() when
Bits::binary(), Width::integer(), Height::integer();
(Width, Height, [Option]) -> wxBitmap() when
Width::integer(), Height::integer(),
Option :: {'depth', integer()}.
new(Bits,Width,Height)
when is_binary(Bits),is_integer(Width),is_integer(Height) ->
new(Bits,Width,Height, []);
new(Width,Height, Options)
when is_integer(Width),is_integer(Height),is_list(Options) ->
MOpts = fun({depth, _depth} = Arg) -> Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(Width,Height, Opts,?get_env(),?wxBitmap_new_3),
wxe_util:rec(?wxBitmap_new_3).
-spec new(Bits, Width, Height, [Option]) -> wxBitmap() when
Bits::binary(), Width::integer(), Height::integer(),
Option :: {'depth', integer()}.
new(Bits,Width,Height, Options)
when is_binary(Bits),is_integer(Width),is_integer(Height),is_list(Options) ->
MOpts = fun({depth, _depth} = Arg) -> Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(Bits,Width,Height, Opts,?get_env(),?wxBitmap_new_4),
wxe_util:rec(?wxBitmap_new_4).
-spec convertToImage(This) -> wxImage:wxImage() when
This::wxBitmap().
convertToImage(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxBitmap),
wxe_util:queue_cmd(This,?get_env(),?wxBitmap_ConvertToImage),
wxe_util:rec(?wxBitmap_ConvertToImage).
-spec copyFromIcon(This, Icon) -> boolean() when
This::wxBitmap(), Icon::wxIcon:wxIcon().
copyFromIcon(#wx_ref{type=ThisT}=This,#wx_ref{type=IconT}=Icon) ->
?CLASS(ThisT,wxBitmap),
?CLASS(IconT,wxIcon),
wxe_util:queue_cmd(This,Icon,?get_env(),?wxBitmap_CopyFromIcon),
wxe_util:rec(?wxBitmap_CopyFromIcon).
-spec create(This, Sz) -> boolean() when
This::wxBitmap(), Sz::{W::integer(), H::integer()}.
create(This,{SzW,SzH} = Sz)
when is_record(This, wx_ref),is_integer(SzW),is_integer(SzH) ->
create(This,Sz, []).
@doc See < a href=" / manuals/2.8.12 / wx_wxbitmap.html#wxbitmapcreate">external documentation</a > .
create(This , , [ Option ] ) - > boolean ( ) when < br / >
This::wxBitmap ( ) , Sz::{W::integer ( ) , H::integer()},<br / >
-spec create(This, Width, Height) -> boolean() when
This::wxBitmap(), Width::integer(), Height::integer();
(This, Sz, [Option]) -> boolean() when
This::wxBitmap(), Sz::{W::integer(), H::integer()},
Option :: {'depth', integer()}.
create(This,Width,Height)
when is_record(This, wx_ref),is_integer(Width),is_integer(Height) ->
create(This,Width,Height, []);
create(#wx_ref{type=ThisT}=This,{SzW,SzH} = Sz, Options)
when is_integer(SzW),is_integer(SzH),is_list(Options) ->
?CLASS(ThisT,wxBitmap),
MOpts = fun({depth, _depth} = Arg) -> Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(This,Sz, Opts,?get_env(),?wxBitmap_Create_2),
wxe_util:rec(?wxBitmap_Create_2).
@doc See < a href=" / manuals/2.8.12 / wx_wxbitmap.html#wxbitmapcreate">external documentation</a > .
create(This , , Height , Dc ) - > boolean ( ) when < br / >
-spec create(This, Width, Height, [Option]) -> boolean() when
This::wxBitmap(), Width::integer(), Height::integer(),
Option :: {'depth', integer()};
(This, Width, Height, Dc) -> boolean() when
This::wxBitmap(), Width::integer(), Height::integer(), Dc::wxDC:wxDC().
create(#wx_ref{type=ThisT}=This,Width,Height, Options)
when is_integer(Width),is_integer(Height),is_list(Options) ->
?CLASS(ThisT,wxBitmap),
MOpts = fun({depth, _depth} = Arg) -> Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(This,Width,Height, Opts,?get_env(),?wxBitmap_Create_3_0),
wxe_util:rec(?wxBitmap_Create_3_0);
create(#wx_ref{type=ThisT}=This,Width,Height,#wx_ref{type=DcT}=Dc)
when is_integer(Width),is_integer(Height) ->
?CLASS(ThisT,wxBitmap),
?CLASS(DcT,wxDC),
wxe_util:queue_cmd(This,Width,Height,Dc,?get_env(),?wxBitmap_Create_3_1),
wxe_util:rec(?wxBitmap_Create_3_1).
-spec getDepth(This) -> integer() when
This::wxBitmap().
getDepth(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxBitmap),
wxe_util:queue_cmd(This,?get_env(),?wxBitmap_GetDepth),
wxe_util:rec(?wxBitmap_GetDepth).
-spec getHeight(This) -> integer() when
This::wxBitmap().
getHeight(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxBitmap),
wxe_util:queue_cmd(This,?get_env(),?wxBitmap_GetHeight),
wxe_util:rec(?wxBitmap_GetHeight).
-spec getPalette(This) -> wxPalette:wxPalette() when
This::wxBitmap().
getPalette(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxBitmap),
wxe_util:queue_cmd(This,?get_env(),?wxBitmap_GetPalette),
wxe_util:rec(?wxBitmap_GetPalette).
-spec getMask(This) -> wxMask:wxMask() when
This::wxBitmap().
getMask(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxBitmap),
wxe_util:queue_cmd(This,?get_env(),?wxBitmap_GetMask),
wxe_util:rec(?wxBitmap_GetMask).
-spec getWidth(This) -> integer() when
This::wxBitmap().
getWidth(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxBitmap),
wxe_util:queue_cmd(This,?get_env(),?wxBitmap_GetWidth),
wxe_util:rec(?wxBitmap_GetWidth).
-spec getSubBitmap(This, Rect) -> wxBitmap() when
This::wxBitmap(), Rect::{X::integer(), Y::integer(), W::integer(), H::integer()}.
getSubBitmap(#wx_ref{type=ThisT}=This,{RectX,RectY,RectW,RectH} = Rect)
when is_integer(RectX),is_integer(RectY),is_integer(RectW),is_integer(RectH) ->
?CLASS(ThisT,wxBitmap),
wxe_util:queue_cmd(This,Rect,?get_env(),?wxBitmap_GetSubBitmap),
wxe_util:rec(?wxBitmap_GetSubBitmap).
-spec loadFile(This, Name) -> boolean() when
This::wxBitmap(), Name::unicode:chardata().
loadFile(This,Name)
when is_record(This, wx_ref),?is_chardata(Name) ->
loadFile(This,Name, []).
< br / > Type = ? wxBITMAP_TYPE_INVALID | ? wxBITMAP_TYPE_BMP | ? wxBITMAP_TYPE_BMP_RESOURCE | ? wxBITMAP_TYPE_RESOURCE | ? wxBITMAP_TYPE_ICO | ? | ? wxBITMAP_TYPE_CUR | ? | ? wxBITMAP_TYPE_XBM | ? wxBITMAP_TYPE_XBM_DATA | ? wxBITMAP_TYPE_XPM | ? wxBITMAP_TYPE_XPM_DATA | ? wxBITMAP_TYPE_TIFF | ? wxBITMAP_TYPE_TIF | ? wxBITMAP_TYPE_TIFF_RESOURCE | ? wxBITMAP_TYPE_TIF_RESOURCE | ? wxBITMAP_TYPE_GIF | ? wxBITMAP_TYPE_GIF_RESOURCE | ? wxBITMAP_TYPE_PNG | ? wxBITMAP_TYPE_PNG_RESOURCE | ? wxBITMAP_TYPE_JPEG | ? wxBITMAP_TYPE_JPEG_RESOURCE | ? wxBITMAP_TYPE_PNM | ? wxBITMAP_TYPE_PNM_RESOURCE | ? | ? ? wxBITMAP_TYPE_PICT | ? wxBITMAP_TYPE_PICT_RESOURCE | ? wxBITMAP_TYPE_ICON | ? | ? wxBITMAP_TYPE_ANI | ? wxBITMAP_TYPE_IFF | ? wxBITMAP_TYPE_TGA | ? wxBITMAP_TYPE_MACCURSOR | ? wxBITMAP_TYPE_MACCURSOR_RESOURCE | ? wxBITMAP_TYPE_ANY
-spec loadFile(This, Name, [Option]) -> boolean() when
This::wxBitmap(), Name::unicode:chardata(),
Option :: {'type', wx:wx_enum()}.
loadFile(#wx_ref{type=ThisT}=This,Name, Options)
when ?is_chardata(Name),is_list(Options) ->
?CLASS(ThisT,wxBitmap),
Name_UC = unicode:characters_to_binary(Name),
MOpts = fun({type, _type} = Arg) -> Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(This,Name_UC, Opts,?get_env(),?wxBitmap_LoadFile),
wxe_util:rec(?wxBitmap_LoadFile).
-spec ok(This) -> boolean() when
This::wxBitmap().
ok(This)
when is_record(This, wx_ref) ->
isOk(This).
-spec isOk(This) -> boolean() when
This::wxBitmap().
isOk(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxBitmap),
wxe_util:queue_cmd(This,?get_env(),?wxBitmap_IsOk),
wxe_util:rec(?wxBitmap_IsOk).
-spec saveFile(This, Name, Type) -> boolean() when
This::wxBitmap(), Name::unicode:chardata(), Type::wx:wx_enum().
saveFile(This,Name,Type)
when is_record(This, wx_ref),?is_chardata(Name),is_integer(Type) ->
saveFile(This,Name,Type, []).
< br / > Type = ? wxBITMAP_TYPE_INVALID | ? wxBITMAP_TYPE_BMP | ? wxBITMAP_TYPE_BMP_RESOURCE | ? wxBITMAP_TYPE_RESOURCE | ? wxBITMAP_TYPE_ICO | ? | ? wxBITMAP_TYPE_CUR | ? | ? wxBITMAP_TYPE_XBM | ? wxBITMAP_TYPE_XBM_DATA | ? wxBITMAP_TYPE_XPM | ? wxBITMAP_TYPE_XPM_DATA | ? wxBITMAP_TYPE_TIFF | ? wxBITMAP_TYPE_TIF | ? wxBITMAP_TYPE_TIFF_RESOURCE | ? wxBITMAP_TYPE_TIF_RESOURCE | ? wxBITMAP_TYPE_GIF | ? wxBITMAP_TYPE_GIF_RESOURCE | ? wxBITMAP_TYPE_PNG | ? wxBITMAP_TYPE_PNG_RESOURCE | ? wxBITMAP_TYPE_JPEG | ? wxBITMAP_TYPE_JPEG_RESOURCE | ? wxBITMAP_TYPE_PNM | ? wxBITMAP_TYPE_PNM_RESOURCE | ? | ? ? wxBITMAP_TYPE_PICT | ? wxBITMAP_TYPE_PICT_RESOURCE | ? wxBITMAP_TYPE_ICON | ? | ? wxBITMAP_TYPE_ANI | ? wxBITMAP_TYPE_IFF | ? wxBITMAP_TYPE_TGA | ? wxBITMAP_TYPE_MACCURSOR | ? wxBITMAP_TYPE_MACCURSOR_RESOURCE | ? wxBITMAP_TYPE_ANY
-spec saveFile(This, Name, Type, [Option]) -> boolean() when
This::wxBitmap(), Name::unicode:chardata(), Type::wx:wx_enum(),
Option :: {'palette', wxPalette:wxPalette()}.
saveFile(#wx_ref{type=ThisT}=This,Name,Type, Options)
when ?is_chardata(Name),is_integer(Type),is_list(Options) ->
?CLASS(ThisT,wxBitmap),
Name_UC = unicode:characters_to_binary(Name),
MOpts = fun({palette, #wx_ref{type=PaletteT}} = Arg) -> ?CLASS(PaletteT,wxPalette),Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(This,Name_UC,Type, Opts,?get_env(),?wxBitmap_SaveFile),
wxe_util:rec(?wxBitmap_SaveFile).
@doc See < a href=" / manuals/2.8.12 / wx_wxbitmap.html#wxbitmapsetdepth">external documentation</a > .
-spec setDepth(This, Depth) -> 'ok' when
This::wxBitmap(), Depth::integer().
setDepth(#wx_ref{type=ThisT}=This,Depth)
when is_integer(Depth) ->
?CLASS(ThisT,wxBitmap),
wxe_util:queue_cmd(This,Depth,?get_env(),?wxBitmap_SetDepth).
-spec setHeight(This, Height) -> 'ok' when
This::wxBitmap(), Height::integer().
setHeight(#wx_ref{type=ThisT}=This,Height)
when is_integer(Height) ->
?CLASS(ThisT,wxBitmap),
wxe_util:queue_cmd(This,Height,?get_env(),?wxBitmap_SetHeight).
-spec setMask(This, Mask) -> 'ok' when
This::wxBitmap(), Mask::wxMask:wxMask().
setMask(#wx_ref{type=ThisT}=This,#wx_ref{type=MaskT}=Mask) ->
?CLASS(ThisT,wxBitmap),
?CLASS(MaskT,wxMask),
wxe_util:queue_cmd(This,Mask,?get_env(),?wxBitmap_SetMask).
-spec setPalette(This, Palette) -> 'ok' when
This::wxBitmap(), Palette::wxPalette:wxPalette().
setPalette(#wx_ref{type=ThisT}=This,#wx_ref{type=PaletteT}=Palette) ->
?CLASS(ThisT,wxBitmap),
?CLASS(PaletteT,wxPalette),
wxe_util:queue_cmd(This,Palette,?get_env(),?wxBitmap_SetPalette).
@doc See < a href=" / manuals/2.8.12 / wx_wxbitmap.html#wxbitmapsetwidth">external documentation</a > .
-spec setWidth(This, Width) -> 'ok' when
This::wxBitmap(), Width::integer().
setWidth(#wx_ref{type=ThisT}=This,Width)
when is_integer(Width) ->
?CLASS(ThisT,wxBitmap),
wxe_util:queue_cmd(This,Width,?get_env(),?wxBitmap_SetWidth).
-spec destroy(This::wxBitmap()) -> 'ok'.
destroy(Obj=#wx_ref{type=Type}) ->
?CLASS(Type,wxBitmap),
wxe_util:queue_cmd(Obj, ?get_env(), ?DESTROY_OBJECT),
ok.
|
babfb665e7b839db0dd5a1bffe5776ad895a47c1e3e6b2c4c96e7c87d100d27f | tweag/ormolu | forall-1.hs | {-# RULES "rd_tyvs" forall a. forall (x :: a). id x = x #-}
{-# RULES "rd_tyvs'" forall f a. forall (x :: f a). id x = x #-}
{-# RULES "rd_tyvs''" forall (a :: *). forall (x :: a). id x = x #-}
{-# RULES "rd_tyvs_multiline1"
forall (a :: *).
forall (x :: a).
id x = x #-}
{-# RULES "rd_tyvs_multiline2"
forall (a ::
*).
forall (x ::
a).
id x = x #-}
| null | https://raw.githubusercontent.com/tweag/ormolu/34bdf62429768f24b70d0f8ba7730fc4d8ae73ba/data/examples/declaration/rewrite-rule/forall-1.hs | haskell | # RULES "rd_tyvs" forall a. forall (x :: a). id x = x #
# RULES "rd_tyvs'" forall f a. forall (x :: f a). id x = x #
# RULES "rd_tyvs''" forall (a :: *). forall (x :: a). id x = x #
# RULES "rd_tyvs_multiline1"
forall (a :: *).
forall (x :: a).
id x = x #
# RULES "rd_tyvs_multiline2"
forall (a ::
*).
forall (x ::
a).
id x = x # | |
6d27645be64ec54ff3a724072bc681b8bebe3129def0cb20987a6e5be6db7c06 | saleyn/etran | listcomp_test.erl | %% vim:ts=2:sw=2:et
-module(listcomp_test).
-compile({parse_transform, listcomp}).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
%%%-----------------------------------------------------------------------------
%%% Unit Tests
%%%-----------------------------------------------------------------------------
-ifdef(EUNIT).
fold_test() ->
?assertEqual(6, [S+I || S = 0, I <- [1,2,3]]),
?assertEqual(6, [S+I || S = 0, {I,_} <- [{1,a},{2,b},{3,c}]]),
?assertEqual(4, [S+I || S = 0, I <- [1,2,3], I /= 2]),
?assertEqual(9, [S+I+J || S = 0, I <- [1,2], J <- [3,4], I /= 2]),
ok.
indexed_fold_test() ->
?assertEqual([{1,10},{2,20},{3,30}], [{Idx, I} || Idx, I <- [10,20,30]]),
?assertEqual(140, [do1(Idx, I, S) || Idx, S=0, I <- [10,20,30]]),
ok.
index_test() ->
?assertEqual([{1,10},{2,20},{3,30}], [{Idx,I} || Idx, {req, FF} <- [{req, [10,20,30]}], I <- FF]),
ok.
do1(Idx, I, S) ->
S + Idx*I.
foldlr_test() ->
?assertEqual([3,1], listcomp:foldl(fun(V, I, S) ->
if (I rem 2 == 0) -> S;
true -> [V|S]
end
end, [], [1,2,3,4])),
?assertEqual([1,3], listcomp:foldr(fun(V, I, S) ->
if (I rem 2 == 0) -> S;
true -> [V|S]
end
end, [], [1,2,3,4])),
ok.
-endif.
| null | https://raw.githubusercontent.com/saleyn/etran/d77bbc26b886656b5717dae51b2b8ff701c56c60/test/listcomp_test.erl | erlang | vim:ts=2:sw=2:et
-----------------------------------------------------------------------------
Unit Tests
----------------------------------------------------------------------------- | -module(listcomp_test).
-compile({parse_transform, listcomp}).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-ifdef(EUNIT).
fold_test() ->
?assertEqual(6, [S+I || S = 0, I <- [1,2,3]]),
?assertEqual(6, [S+I || S = 0, {I,_} <- [{1,a},{2,b},{3,c}]]),
?assertEqual(4, [S+I || S = 0, I <- [1,2,3], I /= 2]),
?assertEqual(9, [S+I+J || S = 0, I <- [1,2], J <- [3,4], I /= 2]),
ok.
indexed_fold_test() ->
?assertEqual([{1,10},{2,20},{3,30}], [{Idx, I} || Idx, I <- [10,20,30]]),
?assertEqual(140, [do1(Idx, I, S) || Idx, S=0, I <- [10,20,30]]),
ok.
index_test() ->
?assertEqual([{1,10},{2,20},{3,30}], [{Idx,I} || Idx, {req, FF} <- [{req, [10,20,30]}], I <- FF]),
ok.
do1(Idx, I, S) ->
S + Idx*I.
foldlr_test() ->
?assertEqual([3,1], listcomp:foldl(fun(V, I, S) ->
if (I rem 2 == 0) -> S;
true -> [V|S]
end
end, [], [1,2,3,4])),
?assertEqual([1,3], listcomp:foldr(fun(V, I, S) ->
if (I rem 2 == 0) -> S;
true -> [V|S]
end
end, [], [1,2,3,4])),
ok.
-endif.
|
d1804c1c309d79ee67053d482b3c60730f74894617a85c26e6d4f960717ebceb | CatalaLang/catala | errors.ml | This file is part of the Catala compiler , a specification language for tax
and social benefits computation rules . Copyright ( C ) 2020 , contributor :
< >
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 .
and social benefits computation rules. Copyright (C) 2020 Inria, contributor:
Denis Merigoux <>
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. *)
(** Error formatting and helper functions *)
* { 1 Error exception and printing }
exception StructuredError of (string * (string option * Pos.t) list)
(** The payload of the expression is a main error message, with a list of
secondary positions related to the error, each carrying an optional
secondary message to describe what is pointed by the position. *)
let print_structured_error (msg : string) (pos : (string option * Pos.t) list) :
string =
Printf.sprintf "%s%s%s" msg
(if pos = [] then "" else "\n\n")
(String.concat "\n\n"
(List.map
(fun (msg, pos) ->
Printf.sprintf "%s%s"
(match msg with None -> "" | Some msg -> msg ^ "\n")
(Pos.retrieve_loc_text pos))
pos))
* { 1 Error exception and printing }
let raise_spanned_error ?(span_msg : string option) (span : Pos.t) format =
Format.kasprintf
(fun msg -> raise (StructuredError (msg, [span_msg, span])))
format
let raise_multispanned_error (spans : (string option * Pos.t) list) format =
Format.kasprintf (fun msg -> raise (StructuredError (msg, spans))) format
let raise_error format =
Format.kasprintf (fun msg -> raise (StructuredError (msg, []))) format
(** {1 Warning printing}*)
let format_multispanned_warning (pos : (string option * Pos.t) list) format =
Format.kasprintf
(fun msg -> Cli.warning_print "%s" (print_structured_error msg pos))
format
let format_spanned_warning ?(span_msg : string option) (span : Pos.t) format =
format_multispanned_warning [span_msg, span] format
let format_warning format = format_multispanned_warning [] format
| null | https://raw.githubusercontent.com/CatalaLang/catala/07edff2cd2371581ba0e5664aa32bcf06650bd0e/compiler/catala_utils/errors.ml | ocaml | * Error formatting and helper functions
* The payload of the expression is a main error message, with a list of
secondary positions related to the error, each carrying an optional
secondary message to describe what is pointed by the position.
* {1 Warning printing} | This file is part of the Catala compiler , a specification language for tax
and social benefits computation rules . Copyright ( C ) 2020 , contributor :
< >
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 .
and social benefits computation rules. Copyright (C) 2020 Inria, contributor:
Denis Merigoux <>
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. *)
* { 1 Error exception and printing }
exception StructuredError of (string * (string option * Pos.t) list)
let print_structured_error (msg : string) (pos : (string option * Pos.t) list) :
string =
Printf.sprintf "%s%s%s" msg
(if pos = [] then "" else "\n\n")
(String.concat "\n\n"
(List.map
(fun (msg, pos) ->
Printf.sprintf "%s%s"
(match msg with None -> "" | Some msg -> msg ^ "\n")
(Pos.retrieve_loc_text pos))
pos))
* { 1 Error exception and printing }
let raise_spanned_error ?(span_msg : string option) (span : Pos.t) format =
Format.kasprintf
(fun msg -> raise (StructuredError (msg, [span_msg, span])))
format
let raise_multispanned_error (spans : (string option * Pos.t) list) format =
Format.kasprintf (fun msg -> raise (StructuredError (msg, spans))) format
let raise_error format =
Format.kasprintf (fun msg -> raise (StructuredError (msg, []))) format
let format_multispanned_warning (pos : (string option * Pos.t) list) format =
Format.kasprintf
(fun msg -> Cli.warning_print "%s" (print_structured_error msg pos))
format
let format_spanned_warning ?(span_msg : string option) (span : Pos.t) format =
format_multispanned_warning [span_msg, span] format
let format_warning format = format_multispanned_warning [] format
|
0561485a9237fe5f7f108d480dad614f70cd4c04e0dfbe13db2ba70fffc0b900 | ghcjs/ghcjs | t7797.hs | # LANGUAGE ExistentialQuantification #
module Main where
import T7797a
data Box = forall a. (Size a) => Box a a
box = Box (go 10000000) (go 10000000) where
go :: Int -> [Int]
go 0 = []
go n = 1 : go (n - 1)
# NOINLINE box #
main = print $ case box of
Box l r -> size l r
| null | https://raw.githubusercontent.com/ghcjs/ghcjs/e4cd4232a31f6371c761acd93853702f4c7ca74c/test/ghc/perf/t7797.hs | haskell | # LANGUAGE ExistentialQuantification #
module Main where
import T7797a
data Box = forall a. (Size a) => Box a a
box = Box (go 10000000) (go 10000000) where
go :: Int -> [Int]
go 0 = []
go n = 1 : go (n - 1)
# NOINLINE box #
main = print $ case box of
Box l r -> size l r
| |
f88580ba307656c4413b7db6263675b988faa88260d92990b5a886339ef0bd53 | eugmes/imp | SourceLoc.hs | # LANGUAGE DeriveFunctor #
-- | Utilities for working with source locations.
module IMP.SourceLoc ( Located(..)
, WithLoc(..)
, SourcePos(..)
, initialPos
, withLoc
) where
import Text.Megaparsec.Pos
-- | Type @'Located' a@ represents values of type @a@ with source location
-- attached to them.
data Located a = Located
{ getLoc :: SourcePos
, unLoc :: a
} deriving (Eq, Ord, Show, Functor)
-- | @'WithLoc' m@ represents computations with associated source location.
--
Instances of ' WithLoc ' should satisfy the following laws :
--
-- * @'withNewLoc' p 'currentLoc' == 'pure' p@
--
class Applicative f => WithLoc f where
| The expression ( @'withNewLoc ' p f@ ) returns computation @f@ with location
-- @p@ set as context.
withNewLoc :: SourcePos -> f a -> f a
-- | Pure value containing current location.
currentLoc :: f SourcePos
| The expression ( @'withLoc ' f ) passes the value from @x@ to the
function @f@ and returns computation with location from @x@.
withLoc :: WithLoc f => (t -> f a) -> Located t -> f a
withLoc f (Located p a) = withNewLoc p (f a)
| null | https://raw.githubusercontent.com/eugmes/imp/7bee4dcff146e041b0242b9e7054dfec4c04c84f/lib/IMP/SourceLoc.hs | haskell | | Utilities for working with source locations.
| Type @'Located' a@ represents values of type @a@ with source location
attached to them.
| @'WithLoc' m@ represents computations with associated source location.
* @'withNewLoc' p 'currentLoc' == 'pure' p@
@p@ set as context.
| Pure value containing current location. | # LANGUAGE DeriveFunctor #
module IMP.SourceLoc ( Located(..)
, WithLoc(..)
, SourcePos(..)
, initialPos
, withLoc
) where
import Text.Megaparsec.Pos
data Located a = Located
{ getLoc :: SourcePos
, unLoc :: a
} deriving (Eq, Ord, Show, Functor)
Instances of ' WithLoc ' should satisfy the following laws :
class Applicative f => WithLoc f where
| The expression ( @'withNewLoc ' p f@ ) returns computation @f@ with location
withNewLoc :: SourcePos -> f a -> f a
currentLoc :: f SourcePos
| The expression ( @'withLoc ' f ) passes the value from @x@ to the
function @f@ and returns computation with location from @x@.
withLoc :: WithLoc f => (t -> f a) -> Located t -> f a
withLoc f (Located p a) = withNewLoc p (f a)
|
521fc83390f49bd2f53b9df52a997d19d5581b6591e5b995db7069a8146f50e9 | input-output-hk/hydra | HeadLogic.hs | # LANGUAGE DuplicateRecordFields #
# LANGUAGE TypeApplications #
# LANGUAGE UndecidableInstances #
-- | Implements the Head Protocol's /state machine/ as a /pure function/.
--
The protocol is described in two parts in the [ Hydra paper]( / en / research / library / papers / hydrafast - isomorphic - state - channels/ )
--
* One part detailing how the Head deals with /client input/.
-- * Another part describing how the Head reacts to /network messages/ from peers.
* A third part detailing the /On - Chain Verification ( OCV)/ protocol , i.e. the abstract " smart contracts " that are need to provide on - chain security .
--
This module is about the first two parts , while the " Hydra . Contract . Head " module in ' hydra - plutus ' covers the third part .
module Hydra.HeadLogic where
import Hydra.Prelude
import Data.List (elemIndex)
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import GHC.Records (getField)
import Hydra.API.ClientInput (ClientInput (..))
import Hydra.API.ServerOutput (ServerOutput (..))
import Hydra.Chain (
ChainEvent (..),
ChainSlot,
ChainStateType,
HeadId,
HeadParameters (..),
IsChainState (chainStateSlot),
OnChainTx (..),
PostChainTx (..),
PostTxError,
)
import Hydra.ContestationPeriod
import Hydra.Crypto (
HydraKey,
Signature,
SigningKey,
aggregateInOrder,
sign,
verifyMultiSignature,
)
import Hydra.Ledger (
IsTx,
Ledger (..),
UTxOType,
ValidationError,
applyTransactions,
)
import Hydra.Network.Message (Message (..))
import Hydra.Party (Party (vkey))
import Hydra.Snapshot (ConfirmedSnapshot (..), Snapshot (..), SnapshotNumber, getSnapshot)
import Test.QuickCheck (oneof)
-- * Types
-- TODO: Move logic up and types down or re-organize using explicit exports
-- | The different events which are processed by the head logic (the "core").
-- Corresponding to each of the "shell" layers, we distinguish between events
-- from the client, the network and the chain.
data Event tx
= -- | Event received from clients via the "Hydra.API".
ClientEvent {clientInput :: ClientInput tx}
| -- | Event received from peers via a "Hydra.Network".
--
* ` ` is a simple counter that 's decreased every time the event is
-- reenqueued due to a wait. It's default value is `defaultTTL`
NetworkEvent {ttl :: TTL, message :: Message tx}
| Event received from the chain via a " Hydra . Chain " .
OnChainEvent {chainEvent :: ChainEvent tx}
| -- | Event to re-ingest errors from 'postTx' for further processing.
PostTxError {postChainTx :: PostChainTx tx, postTxError :: PostTxError tx}
deriving stock (Generic)
deriving instance (IsTx tx, IsChainState tx) => Eq (Event tx)
deriving instance (IsTx tx, IsChainState tx) => Show (Event tx)
deriving instance (IsTx tx, IsChainState tx) => ToJSON (Event tx)
deriving instance (IsTx tx, IsChainState tx) => FromJSON (Event tx)
instance
( IsTx tx
, Arbitrary (ChainStateType tx)
) =>
Arbitrary (Event tx)
where
arbitrary = genericArbitrary
-- | Analogous to events, the pure head logic "core" can have effects emited to
-- the "shell" layers and we distinguish the same: effects onto the client, the
-- network and the chain.
data Effect tx
| Effect to be handled by the " Hydra . API " , results in sending this ' ServerOutput ' .
ClientEffect {serverOutput :: ServerOutput tx}
| Effect to be handled by a " Hydra . Network " , results in a ' Hydra.Network.broadcast ' .
NetworkEffect {message :: Message tx}
| -- | Effect to be handled by a "Hydra.Chain", results in a 'Hydra.Chain.postTx'.
OnChainEffect {chainState :: ChainStateType tx, postChainTx :: PostChainTx tx}
deriving stock (Generic)
deriving instance (IsTx tx, IsChainState tx) => Eq (Effect tx)
deriving instance (IsTx tx, IsChainState tx) => Show (Effect tx)
deriving instance (IsTx tx, IsChainState tx) => ToJSON (Effect tx)
deriving instance (IsTx tx, IsChainState tx) => FromJSON (Effect tx)
instance
( IsTx tx
, Arbitrary (ChainStateType tx)
) =>
Arbitrary (Effect tx)
where
arbitrary = genericArbitrary
| The main state of the Hydra protocol state machine . It holds both , the
-- overall protocol state, but also the off-chain 'CoordinatedHeadState'.
--
-- It is a recursive data structure, where 'previousRecoverableState' fields
-- record the state before the latest 'OnChainEvent' that has been observed.
-- On-Chain events are indeed only __eventually__ immutable and the application
-- state may be rolled back at any time (with a decreasing probability as the
-- time pass).
--
-- Thus, leverage functional immutable data-structure, we build a recursive
-- structure of states which we can easily navigate backwards when needed (see
-- 'Rollback' and 'rollback').
--
-- Note that currently, rolling back to a previous recoverable state eliminates
-- any off-chain events (e.g. transactions) that happened after that state. This
-- is particularly important for anything following the transition to
' OpenState ' since this is where clients may start submitting transactions . In
-- practice, clients should not send transactions right way but wait for a
-- certain grace period to minimize the risk.
data HeadState tx
= Idle (IdleState tx)
| Initial (InitialState tx)
| Open (OpenState tx)
| Closed (ClosedState tx)
deriving stock (Generic)
instance (IsTx tx, Arbitrary (ChainStateType tx)) => Arbitrary (HeadState tx) where
arbitrary = genericArbitrary
deriving instance (IsTx tx, Eq (ChainStateType tx)) => Eq (HeadState tx)
deriving instance (IsTx tx, Show (ChainStateType tx)) => Show (HeadState tx)
deriving instance (IsTx tx, ToJSON (ChainStateType tx)) => ToJSON (HeadState tx)
deriving instance (IsTx tx, FromJSON (ChainStateType tx)) => FromJSON (HeadState tx)
-- | Get the chain state in any 'HeadState'.
getChainState :: HeadState tx -> ChainStateType tx
getChainState = \case
Idle IdleState{chainState} -> chainState
Initial InitialState{chainState} -> chainState
Open OpenState{chainState} -> chainState
Closed ClosedState{chainState} -> chainState
-- | Update the chain state in any 'HeadState'.
setChainState :: ChainStateType tx -> HeadState tx -> HeadState tx
setChainState chainState = \case
Idle st -> Idle st{chainState}
Initial st -> Initial st{chainState}
Open st -> Open st{chainState}
Closed st -> Closed st{chainState}
-- ** Idle
-- | An 'Idle' head only having a chain state with things seen on chain so far.
newtype IdleState tx = IdleState {chainState :: ChainStateType tx}
deriving (Generic)
deriving instance Eq (ChainStateType tx) => Eq (IdleState tx)
deriving instance Show (ChainStateType tx) => Show (IdleState tx)
deriving anyclass instance ToJSON (ChainStateType tx) => ToJSON (IdleState tx)
deriving anyclass instance FromJSON (ChainStateType tx) => FromJSON (IdleState tx)
instance (Arbitrary (ChainStateType tx)) => Arbitrary (IdleState tx) where
arbitrary = genericArbitrary
-- ** Initial
-- | An 'Initial' head which already has an identity and is collecting commits.
data InitialState tx = InitialState
{ parameters :: HeadParameters
, pendingCommits :: PendingCommits
, committed :: Committed tx
, chainState :: ChainStateType tx
, headId :: HeadId
, previousRecoverableState :: HeadState tx
}
deriving (Generic)
deriving instance (IsTx tx, Eq (ChainStateType tx)) => Eq (InitialState tx)
deriving instance (IsTx tx, Show (ChainStateType tx)) => Show (InitialState tx)
deriving instance (IsTx tx, ToJSON (ChainStateType tx)) => ToJSON (InitialState tx)
deriving instance (IsTx tx, FromJSON (ChainStateType tx)) => FromJSON (InitialState tx)
instance (IsTx tx, Arbitrary (ChainStateType tx)) => Arbitrary (InitialState tx) where
arbitrary = do
InitialState
<$> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> oneof
[ Idle <$> arbitrary
, Initial <$> arbitrary
]
type PendingCommits = Set Party
type Committed tx = Map Party (UTxOType tx)
-- ** Open
-- | An 'Open' head with a 'CoordinatedHeadState' tracking off-chain
-- transactions.
data OpenState tx = OpenState
{ parameters :: HeadParameters
, coordinatedHeadState :: CoordinatedHeadState tx
, chainState :: ChainStateType tx
, headId :: HeadId
, previousRecoverableState :: HeadState tx
}
deriving (Generic)
deriving instance (IsTx tx, Eq (ChainStateType tx)) => Eq (OpenState tx)
deriving instance (IsTx tx, Show (ChainStateType tx)) => Show (OpenState tx)
deriving instance (IsTx tx, ToJSON (ChainStateType tx)) => ToJSON (OpenState tx)
deriving instance (IsTx tx, FromJSON (ChainStateType tx)) => FromJSON (OpenState tx)
instance (IsTx tx, Arbitrary (ChainStateType tx)) => Arbitrary (OpenState tx) where
arbitrary =
OpenState
<$> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> (Initial <$> arbitrary)
| Off - chain state of the Coordinated Head protocol .
data CoordinatedHeadState tx = CoordinatedHeadState
{ -- | The latest UTxO resulting from applying 'seenTxs' to
' confirmedSnapshot ' . Spec : L̂
seenUTxO :: UTxOType tx
, -- | List of seen transactions pending inclusion in a snapshot. Spec: T̂
seenTxs :: [tx]
, -- | The latest confirmed snapshot. Spec: U̅, s̅ and σ̅
confirmedSnapshot :: ConfirmedSnapshot tx
| Last seen snapshot and signatures accumulator . Spec : Û , ŝ and Σ̂
seenSnapshot :: SeenSnapshot tx
}
deriving stock (Generic)
deriving instance IsTx tx => Eq (CoordinatedHeadState tx)
deriving instance IsTx tx => Show (CoordinatedHeadState tx)
deriving instance IsTx tx => ToJSON (CoordinatedHeadState tx)
deriving instance IsTx tx => FromJSON (CoordinatedHeadState tx)
instance IsTx tx => Arbitrary (CoordinatedHeadState tx) where
arbitrary = genericArbitrary
-- | Data structure to help in tracking whether we have seen or requested a
ReqSn already and if seen , the signatures we collected already .
data SeenSnapshot tx
| Never saw a ReqSn .
NoSeenSnapshot
| -- | No snapshot in flight with last seen snapshot number as given.
LastSeenSnapshot {lastSeen :: SnapshotNumber}
| -- | ReqSn was sent out and it should be considered already in flight.
RequestedSnapshot
{ lastSeen :: SnapshotNumber
, requested :: SnapshotNumber
}
| -- | ReqSn for given snapshot was received.
SeenSnapshot
{ snapshot :: Snapshot tx
, -- | Collected signatures and so far.
signatories :: Map Party (Signature (Snapshot tx))
}
deriving stock (Generic)
instance IsTx tx => Arbitrary (SeenSnapshot tx) where
arbitrary = genericArbitrary
deriving instance IsTx tx => Eq (SeenSnapshot tx)
deriving instance IsTx tx => Show (SeenSnapshot tx)
deriving instance IsTx tx => ToJSON (SeenSnapshot tx)
deriving instance IsTx tx => FromJSON (SeenSnapshot tx)
| Get the last seen snapshot number given a ' SeenSnapshot ' .
seenSnapshotNumber :: SeenSnapshot tx -> SnapshotNumber
seenSnapshotNumber = \case
NoSeenSnapshot -> 0
LastSeenSnapshot{lastSeen} -> lastSeen
RequestedSnapshot{lastSeen} -> lastSeen
SeenSnapshot{snapshot = Snapshot{number}} -> number
-- ** Closed
| An ' Closed ' head with an current candidate ' ConfirmedSnapshot ' , which may
-- be contested before the 'contestationDeadline'.
data ClosedState tx = ClosedState
{ parameters :: HeadParameters
, confirmedSnapshot :: ConfirmedSnapshot tx
, contestationDeadline :: UTCTime
, -- | Tracks whether we have informed clients already about being
' ReadyToFanout ' .
readyToFanoutSent :: Bool
, chainState :: ChainStateType tx
, headId :: HeadId
, previousRecoverableState :: HeadState tx
}
deriving (Generic)
deriving instance (IsTx tx, Eq (ChainStateType tx)) => Eq (ClosedState tx)
deriving instance (IsTx tx, Show (ChainStateType tx)) => Show (ClosedState tx)
deriving instance (IsTx tx, ToJSON (ChainStateType tx)) => ToJSON (ClosedState tx)
deriving instance (IsTx tx, FromJSON (ChainStateType tx)) => FromJSON (ClosedState tx)
instance (IsTx tx, Arbitrary (ChainStateType tx)) => Arbitrary (ClosedState tx) where
arbitrary =
ClosedState
<$> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> oneof
[ Open <$> arbitrary
, Closed <$> arbitrary
]
-- ** Other types
type TTL = Natural
defaultTTL :: TTL
defaultTTL = 5
-- | Preliminary type for collecting errors occurring during 'update'.
-- TODO: Try to merge this (back) into 'Outcome'.
data LogicError tx
= InvalidEvent (Event tx) (HeadState tx)
| InvalidState (HeadState tx)
| InvalidSnapshot {expected :: SnapshotNumber, actual :: SnapshotNumber}
| LedgerError ValidationError
| RequireFailed Text
deriving stock (Generic)
instance (Typeable tx, Show (Event tx), Show (HeadState tx)) => Exception (LogicError tx)
instance (Arbitrary (Event tx), Arbitrary (HeadState tx)) => Arbitrary (LogicError tx) where
arbitrary = genericArbitrary
deriving instance (Eq (HeadState tx), Eq (Event tx)) => Eq (LogicError tx)
deriving instance (Show (HeadState tx), Show (Event tx)) => Show (LogicError tx)
deriving instance (ToJSON (Event tx), ToJSON (HeadState tx)) => ToJSON (LogicError tx)
deriving instance (FromJSON (Event tx), FromJSON (HeadState tx)) => FromJSON (LogicError tx)
data Outcome tx
= OnlyEffects {effects :: [Effect tx]}
| NewState {headState :: HeadState tx, effects :: [Effect tx]}
| Wait {reason :: WaitReason}
| Error {error :: LogicError tx}
deriving stock (Generic)
deriving instance (IsTx tx, IsChainState tx) => Eq (Outcome tx)
deriving instance (IsTx tx, IsChainState tx) => Show (Outcome tx)
deriving instance (IsTx tx, IsChainState tx) => ToJSON (Outcome tx)
deriving instance (IsTx tx, IsChainState tx) => FromJSON (Outcome tx)
instance (IsTx tx, Arbitrary (ChainStateType tx)) => Arbitrary (Outcome tx) where
arbitrary = genericArbitrary
data WaitReason
= WaitOnNotApplicableTx {validationError :: ValidationError}
| WaitOnSnapshotNumber {waitingFor :: SnapshotNumber}
| WaitOnSeenSnapshot
| WaitOnContestationDeadline
deriving stock (Generic, Eq, Show)
deriving anyclass (ToJSON, FromJSON)
instance Arbitrary WaitReason where
arbitrary = genericArbitrary
data Environment = Environment
{ -- | This is the p_i from the paper
party :: Party
NOTE(MB ): In the long run we would not want to keep the signing key in
-- memory, i.e. have an 'Effect' for signing or so.
signingKey :: SigningKey HydraKey
, otherParties :: [Party]
, contestationPeriod :: ContestationPeriod
}
-- * The Coordinated Head protocol
-- ** Opening the Head
-- | Client request to init the head. This leads to an init transaction on chain,
-- containing the head parameters.
--
_ _ Transition _ _ : ' IdleState ' → ' IdleState '
onIdleClientInit ::
Environment ->
IdleState tx ->
Outcome tx
onIdleClientInit env st =
OnlyEffects [OnChainEffect{chainState, postChainTx = InitTx parameters}]
where
parameters =
HeadParameters
{ contestationPeriod
, parties = party : otherParties
}
Environment{party, otherParties, contestationPeriod} = env
IdleState{chainState} = st
| Observe an init transaction , initialize parameters in an ' InitialState ' and
-- notify clients that they can now commit.
--
_ _ Transition _ _ : ' IdleState ' → ' InitialState '
onIdleChainInitTx ::
IdleState tx ->
-- | New chain state.
ChainStateType tx ->
[Party] ->
ContestationPeriod ->
HeadId ->
Outcome tx
onIdleChainInitTx idleState newChainState parties contestationPeriod headId =
NewState
( Initial
InitialState
{ parameters = HeadParameters{contestationPeriod, parties}
, pendingCommits = Set.fromList parties
, committed = mempty
, previousRecoverableState = Idle idleState
, chainState = newChainState
, headId
}
)
[ClientEffect $ HeadIsInitializing headId (fromList parties)]
| Client request to commit a entry to the head . Provided the client
-- hasn't committed yet, this leads to a commit transaction on-chain containing
that entry .
--
_ _ Transition _ _ : ' InitialState ' → ' InitialState '
onInitialClientCommit ::
Environment ->
InitialState tx ->
ClientInput tx ->
Outcome tx
onInitialClientCommit env st clientInput =
case clientInput of
(Commit utxo)
-- REVIEW: Is 'canCommit' something we want to handle here or have the OCV
-- deal with it?
| canCommit -> OnlyEffects [OnChainEffect{chainState, postChainTx = CommitTx party utxo}]
_ -> OnlyEffects [ClientEffect $ CommandFailed clientInput]
where
canCommit = party `Set.member` pendingCommits
InitialState{pendingCommits, chainState} = st
Environment{party} = env
-- | Observe a commit transaction and record the committed UTxO in the state.
-- Also, if this is the last commit to be observed, post a collect-com
-- transaction on-chain.
--
_ _ Transition _ _ : ' InitialState ' → ' InitialState '
onInitialChainCommitTx ::
Monoid (UTxOType tx) =>
Environment ->
InitialState tx ->
-- | New chain state
ChainStateType tx ->
-- | Comitting party
Party ->
-- | Committed UTxO
UTxOType tx ->
Outcome tx
onInitialChainCommitTx env st newChainState pt utxo =
NewState newState $
notifyClient :
[postCollectCom | canCollectCom]
where
newState =
Initial
InitialState
{ parameters
, pendingCommits = remainingParties
, committed = newCommitted
, previousRecoverableState = Initial st
, chainState = newChainState
, headId
}
newCommitted = Map.insert pt utxo committed
notifyClient = ClientEffect $ Committed headId pt utxo
postCollectCom =
OnChainEffect
{ chainState = newChainState
, postChainTx = CollectComTx $ fold newCommitted
}
canCollectCom = null remainingParties && pt == us
remainingParties = Set.delete pt pendingCommits
InitialState{parameters, pendingCommits, committed, headId} = st
Environment{party = us} = env
-- | Client request to abort the head. This leads to an abort transaction on
-- chain, reimbursing already committed UTxOs.
--
_ _ Transition _ _ : ' InitialState ' → ' InitialState '
onInitialClientAbort ::
Monoid (UTxOType tx) =>
InitialState tx ->
Outcome tx
onInitialClientAbort st =
OnlyEffects [OnChainEffect{chainState, postChainTx = AbortTx{utxo = fold committed}}]
where
InitialState{chainState, committed} = st
-- | Observe an abort transaction by switching the state and notifying clients
-- about it.
--
_ _ Transition _ _ : ' InitialState ' → ' IdleState '
onInitialChainAbortTx ::
Monoid (UTxOType tx) =>
-- | New chain state
ChainStateType tx ->
Committed tx ->
HeadId ->
Outcome tx
onInitialChainAbortTx newChainState committed headId =
NewState
(Idle IdleState{chainState = newChainState})
[ClientEffect $ HeadIsAborted{headId, utxo = fold committed}]
| Observe a collectCom transaction . We initialize the ' OpenState ' using the
head parameters from ' IdleState ' and construct an ' InitialSnapshot ' holding
@u0@ from the committed UTxOs .
--
_ _ Transition _ _ : ' InitialState ' → ' OpenState '
onInitialChainCollectTx ::
(Monoid (UTxOType tx)) =>
InitialState tx ->
-- | New chain state
ChainStateType tx ->
Outcome tx
onInitialChainCollectTx st newChainState =
NewState
( Open
OpenState
{ parameters
, coordinatedHeadState =
CoordinatedHeadState u0 mempty initialSnapshot NoSeenSnapshot
, previousRecoverableState = Initial st
, chainState = newChainState
, headId
}
)
[ClientEffect $ HeadIsOpen{headId, utxo = u0}]
where
u0 = fold committed
initialSnapshot = InitialSnapshot u0
-- TODO: Do we want to check whether this even matches our local state? For
-- example, we do expect `null remainingParties` but what happens if it's
-- untrue?
InitialState{parameters, committed, headId} = st
-- ** Off-chain protocol
-- | Client request to ingest a new transaction into the head.
--
_ _ Transition _ _ : ' OpenState ' → ' OpenState '
onOpenClientNewTx ::
Environment ->
-- | The transaction to be submitted to the head.
tx ->
Outcome tx
onOpenClientNewTx env tx =
OnlyEffects [NetworkEffect $ ReqTx party tx]
where
Environment{party} = env
| Process a transaction request ( ' ReqTx ' ) from a party .
--
-- We apply this transaction to the seen utxo (ledger state). If not applicable,
-- we wait and retry later. If it applies, this yields an updated seen ledger
-- state. Then, we check whether we are the leader for the next snapshot and
emit a snapshot request ' ReqSn ' including this transaction if needed .
--
_ _ Transition _ _ : ' OpenState ' → ' OpenState '
onOpenNetworkReqTx ::
Environment ->
Ledger tx ->
OpenState tx ->
TTL ->
-- | The transaction to be submitted to the head.
tx ->
Outcome tx
onOpenNetworkReqTx env ledger st ttl tx =
Spec : wait L̂ ◦ ⊥ combined with L̂ ← L̂ ◦ tx
case applyTransactions seenUTxO [tx] of
Left (_, err)
| ttl <= 0 ->
OnlyEffects [ClientEffect $ TxInvalid headId seenUTxO tx err]
| otherwise -> Wait $ WaitOnNotApplicableTx err
Right utxo' ->
NewState
( Open
st
{ coordinatedHeadState =
coordinatedHeadState
{ seenTxs = seenTxs <> [tx]
, -- FIXME: This is never reset otherwise. For example if
-- some other party was not up for some txs, but is up
-- again later and we would not agree with them on the
-- seen ledger.
seenUTxO = utxo'
}
}
)
[ClientEffect $ TxValid headId tx]
& emitSnapshot env
where
Ledger{applyTransactions} = ledger
CoordinatedHeadState{seenTxs, seenUTxO} = coordinatedHeadState
OpenState{coordinatedHeadState, headId} = st
-- | Process a snapshot request ('ReqSn') from party.
--
-- This checks that s is the next snapshot number and that the party is
-- responsible for leading that snapshot. Then, we potentially wait until the
-- previous snapshot is confirmed (no snapshot is in flight), before we apply
-- (or wait until applicable) the requested transactions to the last confirmed
-- snapshot. Only then, we start tracking this new "seen" snapshot, compute a
-- signature of it and send the corresponding 'AckSn' to all parties. Finally,
-- the pending transaction set gets pruned to only contain still applicable
-- transactions.
--
_ _ Transition _ _ : ' OpenState ' → ' OpenState '
onOpenNetworkReqSn ::
IsTx tx =>
Environment ->
Ledger tx ->
OpenState tx ->
| Party which sent the ReqSn .
Party ->
-- | Requested snapshot number.
SnapshotNumber ->
-- | List of transactions to snapshot.
[tx] ->
Outcome tx
onOpenNetworkReqSn env ledger st otherParty sn requestedTxs =
-- TODO: Verify the request is signed by (?) / comes from the leader
-- (Can we prove a message comes from a given peer, without signature?)
Spec : require s = ŝ + 1 and leader(s ) = j
requireReqSn $
Spec : wait s̅ = ŝ
waitNoSnapshotInFlight $
Spec : wait U̅ ◦ T ̸= ⊥ combined with Û ← Ū̅ ◦ T
waitApplyTxs $ \u -> do
-- NOTE: confSn == seenSn == sn here
let nextSnapshot = Snapshot (confSn + 1) u requestedTxs
Spec : σᵢ
let snapshotSignature = sign signingKey nextSnapshot
Spec : T̂ ← ∀tx ∈ T̂ , Û ◦ tx ≠ ⊥ } and L̂ ← Û ◦ T̂
let (seenTxs', seenUTxO') = pruneTransactions u
NewState
( Open
st
{ coordinatedHeadState =
coordinatedHeadState
{ seenSnapshot = SeenSnapshot nextSnapshot mempty
, seenTxs = seenTxs'
, seenUTxO = seenUTxO'
}
}
)
[NetworkEffect $ AckSn party snapshotSignature sn]
where
requireReqSn continue =
if sn == seenSn + 1 && isLeader parameters otherParty sn
then continue
else Error $ RequireFailed "requireReqSn"
waitNoSnapshotInFlight continue =
if confSn == seenSn
then continue
else Wait $ WaitOnSnapshotNumber seenSn
waitApplyTxs cont =
case applyTransactions ledger confirmedUTxO requestedTxs of
Left (_, err) ->
-- FIXME: this will not happen, as we are always comparing against the
confirmed snapshot utxo in NewTx ?
Wait $ WaitOnNotApplicableTx err
Right u -> cont u
pruneTransactions utxo = do
foldr go ([], utxo) seenTxs
where
go tx (txs, u) =
case applyTransactions ledger u [tx] of
Left (_, _) -> (txs, u)
Right u' -> (txs <> [tx], u')
confSn = case confirmedSnapshot of
InitialSnapshot{} -> 0
ConfirmedSnapshot{snapshot = Snapshot{number}} -> number
seenSn = seenSnapshotNumber seenSnapshot
confirmedUTxO = case confirmedSnapshot of
InitialSnapshot{initialUTxO} -> initialUTxO
ConfirmedSnapshot{snapshot = Snapshot{utxo}} -> utxo
CoordinatedHeadState{confirmedSnapshot, seenSnapshot, seenTxs} = coordinatedHeadState
OpenState{parameters, coordinatedHeadState} = st
Environment{party, signingKey} = env
-- | Process a snapshot acknowledgement ('AckSn') from a party.
--
-- We do require that the is from the last seen or next expected snapshot, and
potentially wait wait for the corresponding ' ReqSn ' before proceeding . If the
-- party hasn't sent us a signature yet, we store it. Once a signature from each
-- party has been collected, we aggregate a multi-signature and verify it is
-- correct. If everything is fine, the snapshot can be considered as the latest
confirmed one . Similar to processing a ' ReqTx ' , we check whether we are
-- leading the next snapshot and craft a corresponding 'ReqSn' if needed.
--
_ _ Transition _ _ : ' OpenState ' → ' OpenState '
onOpenNetworkAckSn ::
IsTx tx =>
Environment ->
OpenState tx ->
| Party which sent the AckSn .
Party ->
-- | Signature from other party.
Signature (Snapshot tx) ->
| Snapshot number of this AckSn .
SnapshotNumber ->
Outcome tx
onOpenNetworkAckSn env openState otherParty snapshotSignature sn =
-- TODO: verify authenticity of message and whether otherParty is part of the head
Spec : require s ∈ { ŝ , ŝ + 1 }
requireValidAckSn $ do
Spec : wait ŝ = s
waitOnSeenSnapshot $ \snapshot sigs -> do
Spec : ( j , . ) ∉ ̂Σ
requireNotSignedYet sigs $ do
let sigs' = Map.insert otherParty snapshotSignature sigs
ifAllMembersHaveSigned snapshot sigs' $ do
-- Spec: σ̃ ← MS-ASig(k_H, ̂Σ̂)
let multisig = aggregateInOrder sigs' parties
requireVerifiedMultisignature multisig snapshot $ do
NewState
( onlyUpdateCoordinatedHeadState $
coordinatedHeadState
{ confirmedSnapshot =
ConfirmedSnapshot
{ snapshot
, signatures = multisig
}
, seenSnapshot = LastSeenSnapshot (number snapshot)
}
)
[ClientEffect $ SnapshotConfirmed headId snapshot multisig]
& emitSnapshot env
where
seenSn = seenSnapshotNumber seenSnapshot
requireValidAckSn continue =
if sn `elem` [seenSn, seenSn + 1]
then continue
else Error $ RequireFailed "requireValidAckSn"
waitOnSeenSnapshot continue =
case seenSnapshot of
SeenSnapshot snapshot sigs
| seenSn == sn -> continue snapshot sigs
_ -> Wait WaitOnSeenSnapshot
requireNotSignedYet sigs continue =
if not (Map.member otherParty sigs)
then continue
else Error $ RequireFailed "requireNotSignedYet"
ifAllMembersHaveSigned snapshot sigs' cont =
if Map.keysSet sigs' == Set.fromList parties
then cont
else
NewState
( onlyUpdateCoordinatedHeadState $
coordinatedHeadState
{ seenSnapshot = SeenSnapshot snapshot sigs'
}
)
[]
requireVerifiedMultisignature multisig msg cont =
if verifyMultiSignature (vkey <$> parties) multisig msg
then cont
else Error $ RequireFailed "requireVerifiedMultisignature"
-- XXX: Data structures become unwieldy -> helper functions or lenses
onlyUpdateCoordinatedHeadState chs' =
Open openState{coordinatedHeadState = chs'}
CoordinatedHeadState{seenSnapshot} = coordinatedHeadState
OpenState
{ parameters = HeadParameters{parties}
, coordinatedHeadState
, headId
} = openState
-- ** Closing the Head
-- | Client request to close the head. This leads to a close transaction on
chain using the latest confirmed snaphshot of the ' OpenState ' .
--
_ _ Transition _ _ : ' OpenState ' → ' OpenState '
onOpenClientClose ::
OpenState tx ->
Outcome tx
onOpenClientClose st =
OnlyEffects [OnChainEffect{chainState, postChainTx = CloseTx confirmedSnapshot}]
where
CoordinatedHeadState{confirmedSnapshot} = coordinatedHeadState
OpenState{chainState, coordinatedHeadState} = st
-- | Observe a close transaction. If the closed snapshot number is smaller than
-- our last confirmed, we post a contest transaction. Also, we do schedule a
-- notification for clients to fanout at the deadline.
--
_ _ Transition _ _ : ' OpenState ' → ' ClosedState '
onOpenChainCloseTx ::
OpenState tx ->
-- | New chain state.
ChainStateType tx ->
-- | Closed snapshot number.
SnapshotNumber ->
-- | Contestation deadline.
UTCTime ->
Outcome tx
onOpenChainCloseTx openState newChainState closedSnapshotNumber contestationDeadline =
NewState closedState $
notifyClient :
[ OnChainEffect
REVIEW : Was using " old " chainState before
chainState = newChainState
, postChainTx = ContestTx{confirmedSnapshot}
}
| doContest
]
where
doContest =
number (getSnapshot confirmedSnapshot) > closedSnapshotNumber
closedState =
Closed
ClosedState
{ parameters
, confirmedSnapshot
, contestationDeadline
, readyToFanoutSent = False
, previousRecoverableState = Open openState
, chainState = newChainState
, headId
}
notifyClient =
ClientEffect $
HeadIsClosed
{ headId
, snapshotNumber = closedSnapshotNumber
, contestationDeadline
}
CoordinatedHeadState{confirmedSnapshot} = coordinatedHeadState
OpenState{parameters, headId, coordinatedHeadState} = openState
-- | Observe a contest transaction. If the contested snapshot number is smaller
-- than our last confirmed snapshot, we post a contest transaction.
--
_ _ Transition _ _ : ' ClosedState ' → ' ClosedState '
onClosedChainContestTx ::
ClosedState tx ->
SnapshotNumber ->
Outcome tx
onClosedChainContestTx closedState snapshotNumber
| snapshotNumber < number (getSnapshot confirmedSnapshot) =
OnlyEffects
[ ClientEffect HeadIsContested{snapshotNumber, headId}
, OnChainEffect{chainState, postChainTx = ContestTx{confirmedSnapshot}}
]
| snapshotNumber > number (getSnapshot confirmedSnapshot) =
-- TODO: A more recent snapshot number was succesfully contested, we will
-- not be able to fanout! We might want to communicate that to the client!
OnlyEffects [ClientEffect HeadIsContested{snapshotNumber, headId}]
| otherwise =
OnlyEffects [ClientEffect HeadIsContested{snapshotNumber, headId}]
where
ClosedState{chainState, confirmedSnapshot, headId} = closedState
-- | Client request to fanout leads to a fanout transaction on chain using the
latest confirmed snapshot from ' ClosedState ' .
--
_ _ Transition _ _ : ' ClosedState ' → ' ClosedState '
onClosedClientFanout ::
ClosedState tx ->
Outcome tx
onClosedClientFanout closedState =
OnlyEffects
[ OnChainEffect
{ chainState
, postChainTx =
FanoutTx{utxo, contestationDeadline}
}
]
where
Snapshot{utxo} = getSnapshot confirmedSnapshot
ClosedState{chainState, confirmedSnapshot, contestationDeadline} = closedState
-- | Observe a fanout transaction by finalize the head state and notifying
-- clients about it.
--
_ _ Transition _ _ : ' ClosedState ' → ' IdleState '
onClosedChainFanoutTx ::
ClosedState tx ->
-- | New chain state
ChainStateType tx ->
Outcome tx
onClosedChainFanoutTx closedState newChainState =
NewState
(Idle IdleState{chainState = newChainState})
[ ClientEffect $ HeadIsFinalized{headId, utxo}
]
where
Snapshot{utxo} = getSnapshot confirmedSnapshot
ClosedState{confirmedSnapshot, headId} = closedState
-- | Observe a chain rollback and transition to corresponding previous
-- recoverable state.
--
_ _ Transition _ _ : ' OpenState ' → ' HeadState '
onCurrentChainRollback ::
(IsChainState tx) =>
HeadState tx ->
ChainSlot ->
Outcome tx
onCurrentChainRollback currentState slot =
NewState (rollback slot currentState) [ClientEffect RolledBack]
where
rollback rollbackSlot hs
| chainStateSlot (getChainState hs) <= rollbackSlot = hs
| otherwise =
case hs of
Idle{} -> hs
Initial InitialState{previousRecoverableState} ->
rollback rollbackSlot previousRecoverableState
Open OpenState{previousRecoverableState} ->
rollback rollbackSlot previousRecoverableState
Closed ClosedState{previousRecoverableState} ->
rollback rollbackSlot previousRecoverableState
| The " pure core " of the Hydra node , which handles the ' Event ' against a
-- current 'HeadState'. Resulting new 'HeadState's are retained and 'Effect'
outcomes handled by the " Hydra . Node " .
update ::
(IsTx tx, IsChainState tx) =>
Environment ->
Ledger tx ->
HeadState tx ->
Event tx ->
Outcome tx
update env ledger st ev = case (st, ev) of
(Idle idleState, ClientEvent Init) ->
onIdleClientInit env idleState
(Idle idleState, OnChainEvent Observation{observedTx = OnInitTx{headId, contestationPeriod, parties}, newChainState}) ->
onIdleChainInitTx idleState newChainState parties contestationPeriod headId
-- Initial
(Initial idleState, ClientEvent clientInput@(Commit _)) ->
onInitialClientCommit env idleState clientInput
(Initial initialState, OnChainEvent Observation{observedTx = OnCommitTx{party = pt, committed = utxo}, newChainState}) ->
onInitialChainCommitTx env initialState newChainState pt utxo
(Initial initialState, ClientEvent Abort) ->
onInitialClientAbort initialState
(Initial initialState, OnChainEvent Observation{observedTx = OnCollectComTx{}, newChainState}) ->
onInitialChainCollectTx initialState newChainState
(Initial InitialState{headId, committed}, OnChainEvent Observation{observedTx = OnAbortTx{}, newChainState}) ->
onInitialChainAbortTx newChainState committed headId
(Initial InitialState{committed, headId}, ClientEvent GetUTxO) ->
OnlyEffects [ClientEffect . GetUTxOResponse headId $ fold committed]
-- Open
(Open openState, ClientEvent Close) ->
onOpenClientClose openState
(Open{}, ClientEvent (NewTx tx)) ->
onOpenClientNewTx env tx
(Open openState, NetworkEvent ttl (ReqTx _ tx)) ->
onOpenNetworkReqTx env ledger openState ttl tx
(Open openState, NetworkEvent _ (ReqSn otherParty sn txs)) ->
XXX : = = 0 not handled for ReqSn
onOpenNetworkReqSn env ledger openState otherParty sn txs
(Open openState, NetworkEvent _ (AckSn otherParty snapshotSignature sn)) ->
XXX : = = 0 not handled for AckSn
onOpenNetworkAckSn env openState otherParty snapshotSignature sn
( Open openState
, OnChainEvent Observation{observedTx = OnCloseTx{snapshotNumber = closedSnapshotNumber, contestationDeadline}, newChainState}
) ->
onOpenChainCloseTx openState newChainState closedSnapshotNumber contestationDeadline
(Open OpenState{coordinatedHeadState = CoordinatedHeadState{confirmedSnapshot}, headId}, ClientEvent GetUTxO) ->
-- TODO: Is it really intuitive that we respond from the confirmed ledger if
-- transactions are validated against the seen ledger?
OnlyEffects [ClientEffect . GetUTxOResponse headId $ getField @"utxo" $ getSnapshot confirmedSnapshot]
-- Closed
(Closed closedState, OnChainEvent Observation{observedTx = OnContestTx{snapshotNumber}}) ->
onClosedChainContestTx closedState snapshotNumber
(Closed cst@ClosedState{contestationDeadline, readyToFanoutSent, headId}, OnChainEvent (Tick chainTime))
| chainTime > contestationDeadline && not readyToFanoutSent ->
NewState
(Closed cst{readyToFanoutSent = True})
[ClientEffect $ ReadyToFanout headId]
(Closed closedState, ClientEvent Fanout) ->
onClosedClientFanout closedState
(Closed closedState, OnChainEvent Observation{observedTx = OnFanoutTx{}, newChainState}) ->
onClosedChainFanoutTx closedState newChainState
-- General
(currentState, OnChainEvent (Rollback slot)) ->
onCurrentChainRollback currentState slot
(_, OnChainEvent Tick{}) ->
OnlyEffects []
(_, NetworkEvent _ (Connected nodeId)) ->
OnlyEffects [ClientEffect $ PeerConnected{peer = nodeId}]
(_, NetworkEvent _ (Disconnected nodeId)) ->
OnlyEffects [ClientEffect $ PeerDisconnected{peer = nodeId}]
(_, PostTxError{postChainTx, postTxError}) ->
OnlyEffects [ClientEffect $ PostTxOnChainFailed{postChainTx, postTxError}]
(_, ClientEvent{clientInput}) ->
OnlyEffects [ClientEffect $ CommandFailed clientInput]
_ ->
Error $ InvalidEvent ev st
-- * Snapshot helper functions
data SnapshotOutcome tx
= ShouldSnapshot SnapshotNumber [tx] -- TODO(AB) : should really be a Set (TxId tx)
| ShouldNotSnapshot NoSnapshotReason
deriving (Eq, Show, Generic)
data NoSnapshotReason
= NotLeader SnapshotNumber
| SnapshotInFlight SnapshotNumber
| NoTransactionsToSnapshot
deriving (Eq, Show, Generic)
isLeader :: HeadParameters -> Party -> SnapshotNumber -> Bool
isLeader HeadParameters{parties} p sn =
case p `elemIndex` parties of
Just i -> ((fromIntegral sn - 1) `mod` length parties) == i
_ -> False
-- | Snapshot emission decider
newSn :: Environment -> HeadParameters -> CoordinatedHeadState tx -> SnapshotOutcome tx
newSn Environment{party} parameters CoordinatedHeadState{confirmedSnapshot, seenSnapshot, seenTxs} =
if
| not (isLeader parameters party nextSn) ->
ShouldNotSnapshot $ NotLeader nextSn
| -- NOTE: This is different than in the spec. If we use seenSn /=
-- confirmedSn here, we implicitly require confirmedSn <= seenSn. Which
-- may be an acceptable invariant, but we have property tests which are
-- more strict right now. Anyhow, we can be more expressive.
snapshotInFlight ->
ShouldNotSnapshot $ SnapshotInFlight nextSn
| null seenTxs ->
ShouldNotSnapshot NoTransactionsToSnapshot
| otherwise ->
ShouldSnapshot nextSn seenTxs
where
nextSn = confirmedSn + 1
snapshotInFlight = case seenSnapshot of
NoSeenSnapshot -> False
LastSeenSnapshot{} -> False
RequestedSnapshot{} -> True
SeenSnapshot{} -> True
Snapshot{number = confirmedSn} = getSnapshot confirmedSnapshot
-- | Emit a snapshot if we are the next snapshot leader. 'Outcome' modifying
-- signature so it can be chained with other 'update' functions.
emitSnapshot :: Environment -> Outcome tx -> Outcome tx
emitSnapshot env@Environment{party} outcome =
case outcome of
NewState (Open OpenState{parameters, coordinatedHeadState, previousRecoverableState, chainState, headId}) effects ->
case newSn env parameters coordinatedHeadState of
ShouldSnapshot sn txs -> do
let CoordinatedHeadState{seenSnapshot} = coordinatedHeadState
NewState
( Open
OpenState
{ parameters
, coordinatedHeadState =
coordinatedHeadState
{ seenSnapshot =
RequestedSnapshot
{ lastSeen = seenSnapshotNumber $ seenSnapshot
, requested = sn
}
}
, previousRecoverableState
, chainState
, headId
}
)
$ NetworkEffect (ReqSn party sn txs) : effects
_ -> outcome
_ -> outcome
| null | https://raw.githubusercontent.com/input-output-hk/hydra/54d6e4507fa4a67bb52a1507249e836e23e592bf/hydra-node/src/Hydra/HeadLogic.hs | haskell | | Implements the Head Protocol's /state machine/ as a /pure function/.
* Another part describing how the Head reacts to /network messages/ from peers.
* Types
TODO: Move logic up and types down or re-organize using explicit exports
| The different events which are processed by the head logic (the "core").
Corresponding to each of the "shell" layers, we distinguish between events
from the client, the network and the chain.
| Event received from clients via the "Hydra.API".
| Event received from peers via a "Hydra.Network".
reenqueued due to a wait. It's default value is `defaultTTL`
| Event to re-ingest errors from 'postTx' for further processing.
| Analogous to events, the pure head logic "core" can have effects emited to
the "shell" layers and we distinguish the same: effects onto the client, the
network and the chain.
| Effect to be handled by a "Hydra.Chain", results in a 'Hydra.Chain.postTx'.
overall protocol state, but also the off-chain 'CoordinatedHeadState'.
It is a recursive data structure, where 'previousRecoverableState' fields
record the state before the latest 'OnChainEvent' that has been observed.
On-Chain events are indeed only __eventually__ immutable and the application
state may be rolled back at any time (with a decreasing probability as the
time pass).
Thus, leverage functional immutable data-structure, we build a recursive
structure of states which we can easily navigate backwards when needed (see
'Rollback' and 'rollback').
Note that currently, rolling back to a previous recoverable state eliminates
any off-chain events (e.g. transactions) that happened after that state. This
is particularly important for anything following the transition to
practice, clients should not send transactions right way but wait for a
certain grace period to minimize the risk.
| Get the chain state in any 'HeadState'.
| Update the chain state in any 'HeadState'.
** Idle
| An 'Idle' head only having a chain state with things seen on chain so far.
** Initial
| An 'Initial' head which already has an identity and is collecting commits.
** Open
| An 'Open' head with a 'CoordinatedHeadState' tracking off-chain
transactions.
| The latest UTxO resulting from applying 'seenTxs' to
| List of seen transactions pending inclusion in a snapshot. Spec: T̂
| The latest confirmed snapshot. Spec: U̅, s̅ and σ̅
| Data structure to help in tracking whether we have seen or requested a
| No snapshot in flight with last seen snapshot number as given.
| ReqSn was sent out and it should be considered already in flight.
| ReqSn for given snapshot was received.
| Collected signatures and so far.
** Closed
be contested before the 'contestationDeadline'.
| Tracks whether we have informed clients already about being
** Other types
| Preliminary type for collecting errors occurring during 'update'.
TODO: Try to merge this (back) into 'Outcome'.
| This is the p_i from the paper
memory, i.e. have an 'Effect' for signing or so.
* The Coordinated Head protocol
** Opening the Head
| Client request to init the head. This leads to an init transaction on chain,
containing the head parameters.
notify clients that they can now commit.
| New chain state.
hasn't committed yet, this leads to a commit transaction on-chain containing
REVIEW: Is 'canCommit' something we want to handle here or have the OCV
deal with it?
| Observe a commit transaction and record the committed UTxO in the state.
Also, if this is the last commit to be observed, post a collect-com
transaction on-chain.
| New chain state
| Comitting party
| Committed UTxO
| Client request to abort the head. This leads to an abort transaction on
chain, reimbursing already committed UTxOs.
| Observe an abort transaction by switching the state and notifying clients
about it.
| New chain state
| New chain state
TODO: Do we want to check whether this even matches our local state? For
example, we do expect `null remainingParties` but what happens if it's
untrue?
** Off-chain protocol
| Client request to ingest a new transaction into the head.
| The transaction to be submitted to the head.
We apply this transaction to the seen utxo (ledger state). If not applicable,
we wait and retry later. If it applies, this yields an updated seen ledger
state. Then, we check whether we are the leader for the next snapshot and
| The transaction to be submitted to the head.
FIXME: This is never reset otherwise. For example if
some other party was not up for some txs, but is up
again later and we would not agree with them on the
seen ledger.
| Process a snapshot request ('ReqSn') from party.
This checks that s is the next snapshot number and that the party is
responsible for leading that snapshot. Then, we potentially wait until the
previous snapshot is confirmed (no snapshot is in flight), before we apply
(or wait until applicable) the requested transactions to the last confirmed
snapshot. Only then, we start tracking this new "seen" snapshot, compute a
signature of it and send the corresponding 'AckSn' to all parties. Finally,
the pending transaction set gets pruned to only contain still applicable
transactions.
| Requested snapshot number.
| List of transactions to snapshot.
TODO: Verify the request is signed by (?) / comes from the leader
(Can we prove a message comes from a given peer, without signature?)
NOTE: confSn == seenSn == sn here
FIXME: this will not happen, as we are always comparing against the
| Process a snapshot acknowledgement ('AckSn') from a party.
We do require that the is from the last seen or next expected snapshot, and
party hasn't sent us a signature yet, we store it. Once a signature from each
party has been collected, we aggregate a multi-signature and verify it is
correct. If everything is fine, the snapshot can be considered as the latest
leading the next snapshot and craft a corresponding 'ReqSn' if needed.
| Signature from other party.
TODO: verify authenticity of message and whether otherParty is part of the head
Spec: σ̃ ← MS-ASig(k_H, ̂Σ̂)
XXX: Data structures become unwieldy -> helper functions or lenses
** Closing the Head
| Client request to close the head. This leads to a close transaction on
| Observe a close transaction. If the closed snapshot number is smaller than
our last confirmed, we post a contest transaction. Also, we do schedule a
notification for clients to fanout at the deadline.
| New chain state.
| Closed snapshot number.
| Contestation deadline.
| Observe a contest transaction. If the contested snapshot number is smaller
than our last confirmed snapshot, we post a contest transaction.
TODO: A more recent snapshot number was succesfully contested, we will
not be able to fanout! We might want to communicate that to the client!
| Client request to fanout leads to a fanout transaction on chain using the
| Observe a fanout transaction by finalize the head state and notifying
clients about it.
| New chain state
| Observe a chain rollback and transition to corresponding previous
recoverable state.
current 'HeadState'. Resulting new 'HeadState's are retained and 'Effect'
Initial
Open
TODO: Is it really intuitive that we respond from the confirmed ledger if
transactions are validated against the seen ledger?
Closed
General
* Snapshot helper functions
TODO(AB) : should really be a Set (TxId tx)
| Snapshot emission decider
NOTE: This is different than in the spec. If we use seenSn /=
confirmedSn here, we implicitly require confirmedSn <= seenSn. Which
may be an acceptable invariant, but we have property tests which are
more strict right now. Anyhow, we can be more expressive.
| Emit a snapshot if we are the next snapshot leader. 'Outcome' modifying
signature so it can be chained with other 'update' functions. | # LANGUAGE DuplicateRecordFields #
# LANGUAGE TypeApplications #
# LANGUAGE UndecidableInstances #
The protocol is described in two parts in the [ Hydra paper]( / en / research / library / papers / hydrafast - isomorphic - state - channels/ )
* One part detailing how the Head deals with /client input/.
* A third part detailing the /On - Chain Verification ( OCV)/ protocol , i.e. the abstract " smart contracts " that are need to provide on - chain security .
This module is about the first two parts , while the " Hydra . Contract . Head " module in ' hydra - plutus ' covers the third part .
module Hydra.HeadLogic where
import Hydra.Prelude
import Data.List (elemIndex)
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import GHC.Records (getField)
import Hydra.API.ClientInput (ClientInput (..))
import Hydra.API.ServerOutput (ServerOutput (..))
import Hydra.Chain (
ChainEvent (..),
ChainSlot,
ChainStateType,
HeadId,
HeadParameters (..),
IsChainState (chainStateSlot),
OnChainTx (..),
PostChainTx (..),
PostTxError,
)
import Hydra.ContestationPeriod
import Hydra.Crypto (
HydraKey,
Signature,
SigningKey,
aggregateInOrder,
sign,
verifyMultiSignature,
)
import Hydra.Ledger (
IsTx,
Ledger (..),
UTxOType,
ValidationError,
applyTransactions,
)
import Hydra.Network.Message (Message (..))
import Hydra.Party (Party (vkey))
import Hydra.Snapshot (ConfirmedSnapshot (..), Snapshot (..), SnapshotNumber, getSnapshot)
import Test.QuickCheck (oneof)
data Event tx
ClientEvent {clientInput :: ClientInput tx}
* ` ` is a simple counter that 's decreased every time the event is
NetworkEvent {ttl :: TTL, message :: Message tx}
| Event received from the chain via a " Hydra . Chain " .
OnChainEvent {chainEvent :: ChainEvent tx}
PostTxError {postChainTx :: PostChainTx tx, postTxError :: PostTxError tx}
deriving stock (Generic)
deriving instance (IsTx tx, IsChainState tx) => Eq (Event tx)
deriving instance (IsTx tx, IsChainState tx) => Show (Event tx)
deriving instance (IsTx tx, IsChainState tx) => ToJSON (Event tx)
deriving instance (IsTx tx, IsChainState tx) => FromJSON (Event tx)
instance
( IsTx tx
, Arbitrary (ChainStateType tx)
) =>
Arbitrary (Event tx)
where
arbitrary = genericArbitrary
data Effect tx
| Effect to be handled by the " Hydra . API " , results in sending this ' ServerOutput ' .
ClientEffect {serverOutput :: ServerOutput tx}
| Effect to be handled by a " Hydra . Network " , results in a ' Hydra.Network.broadcast ' .
NetworkEffect {message :: Message tx}
OnChainEffect {chainState :: ChainStateType tx, postChainTx :: PostChainTx tx}
deriving stock (Generic)
deriving instance (IsTx tx, IsChainState tx) => Eq (Effect tx)
deriving instance (IsTx tx, IsChainState tx) => Show (Effect tx)
deriving instance (IsTx tx, IsChainState tx) => ToJSON (Effect tx)
deriving instance (IsTx tx, IsChainState tx) => FromJSON (Effect tx)
instance
( IsTx tx
, Arbitrary (ChainStateType tx)
) =>
Arbitrary (Effect tx)
where
arbitrary = genericArbitrary
| The main state of the Hydra protocol state machine . It holds both , the
' OpenState ' since this is where clients may start submitting transactions . In
data HeadState tx
= Idle (IdleState tx)
| Initial (InitialState tx)
| Open (OpenState tx)
| Closed (ClosedState tx)
deriving stock (Generic)
instance (IsTx tx, Arbitrary (ChainStateType tx)) => Arbitrary (HeadState tx) where
arbitrary = genericArbitrary
deriving instance (IsTx tx, Eq (ChainStateType tx)) => Eq (HeadState tx)
deriving instance (IsTx tx, Show (ChainStateType tx)) => Show (HeadState tx)
deriving instance (IsTx tx, ToJSON (ChainStateType tx)) => ToJSON (HeadState tx)
deriving instance (IsTx tx, FromJSON (ChainStateType tx)) => FromJSON (HeadState tx)
getChainState :: HeadState tx -> ChainStateType tx
getChainState = \case
Idle IdleState{chainState} -> chainState
Initial InitialState{chainState} -> chainState
Open OpenState{chainState} -> chainState
Closed ClosedState{chainState} -> chainState
setChainState :: ChainStateType tx -> HeadState tx -> HeadState tx
setChainState chainState = \case
Idle st -> Idle st{chainState}
Initial st -> Initial st{chainState}
Open st -> Open st{chainState}
Closed st -> Closed st{chainState}
newtype IdleState tx = IdleState {chainState :: ChainStateType tx}
deriving (Generic)
deriving instance Eq (ChainStateType tx) => Eq (IdleState tx)
deriving instance Show (ChainStateType tx) => Show (IdleState tx)
deriving anyclass instance ToJSON (ChainStateType tx) => ToJSON (IdleState tx)
deriving anyclass instance FromJSON (ChainStateType tx) => FromJSON (IdleState tx)
instance (Arbitrary (ChainStateType tx)) => Arbitrary (IdleState tx) where
arbitrary = genericArbitrary
data InitialState tx = InitialState
{ parameters :: HeadParameters
, pendingCommits :: PendingCommits
, committed :: Committed tx
, chainState :: ChainStateType tx
, headId :: HeadId
, previousRecoverableState :: HeadState tx
}
deriving (Generic)
deriving instance (IsTx tx, Eq (ChainStateType tx)) => Eq (InitialState tx)
deriving instance (IsTx tx, Show (ChainStateType tx)) => Show (InitialState tx)
deriving instance (IsTx tx, ToJSON (ChainStateType tx)) => ToJSON (InitialState tx)
deriving instance (IsTx tx, FromJSON (ChainStateType tx)) => FromJSON (InitialState tx)
instance (IsTx tx, Arbitrary (ChainStateType tx)) => Arbitrary (InitialState tx) where
arbitrary = do
InitialState
<$> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> oneof
[ Idle <$> arbitrary
, Initial <$> arbitrary
]
type PendingCommits = Set Party
type Committed tx = Map Party (UTxOType tx)
data OpenState tx = OpenState
{ parameters :: HeadParameters
, coordinatedHeadState :: CoordinatedHeadState tx
, chainState :: ChainStateType tx
, headId :: HeadId
, previousRecoverableState :: HeadState tx
}
deriving (Generic)
deriving instance (IsTx tx, Eq (ChainStateType tx)) => Eq (OpenState tx)
deriving instance (IsTx tx, Show (ChainStateType tx)) => Show (OpenState tx)
deriving instance (IsTx tx, ToJSON (ChainStateType tx)) => ToJSON (OpenState tx)
deriving instance (IsTx tx, FromJSON (ChainStateType tx)) => FromJSON (OpenState tx)
instance (IsTx tx, Arbitrary (ChainStateType tx)) => Arbitrary (OpenState tx) where
arbitrary =
OpenState
<$> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> (Initial <$> arbitrary)
| Off - chain state of the Coordinated Head protocol .
data CoordinatedHeadState tx = CoordinatedHeadState
' confirmedSnapshot ' . Spec : L̂
seenUTxO :: UTxOType tx
seenTxs :: [tx]
confirmedSnapshot :: ConfirmedSnapshot tx
| Last seen snapshot and signatures accumulator . Spec : Û , ŝ and Σ̂
seenSnapshot :: SeenSnapshot tx
}
deriving stock (Generic)
deriving instance IsTx tx => Eq (CoordinatedHeadState tx)
deriving instance IsTx tx => Show (CoordinatedHeadState tx)
deriving instance IsTx tx => ToJSON (CoordinatedHeadState tx)
deriving instance IsTx tx => FromJSON (CoordinatedHeadState tx)
instance IsTx tx => Arbitrary (CoordinatedHeadState tx) where
arbitrary = genericArbitrary
ReqSn already and if seen , the signatures we collected already .
data SeenSnapshot tx
| Never saw a ReqSn .
NoSeenSnapshot
LastSeenSnapshot {lastSeen :: SnapshotNumber}
RequestedSnapshot
{ lastSeen :: SnapshotNumber
, requested :: SnapshotNumber
}
SeenSnapshot
{ snapshot :: Snapshot tx
signatories :: Map Party (Signature (Snapshot tx))
}
deriving stock (Generic)
instance IsTx tx => Arbitrary (SeenSnapshot tx) where
arbitrary = genericArbitrary
deriving instance IsTx tx => Eq (SeenSnapshot tx)
deriving instance IsTx tx => Show (SeenSnapshot tx)
deriving instance IsTx tx => ToJSON (SeenSnapshot tx)
deriving instance IsTx tx => FromJSON (SeenSnapshot tx)
| Get the last seen snapshot number given a ' SeenSnapshot ' .
seenSnapshotNumber :: SeenSnapshot tx -> SnapshotNumber
seenSnapshotNumber = \case
NoSeenSnapshot -> 0
LastSeenSnapshot{lastSeen} -> lastSeen
RequestedSnapshot{lastSeen} -> lastSeen
SeenSnapshot{snapshot = Snapshot{number}} -> number
| An ' Closed ' head with an current candidate ' ConfirmedSnapshot ' , which may
data ClosedState tx = ClosedState
{ parameters :: HeadParameters
, confirmedSnapshot :: ConfirmedSnapshot tx
, contestationDeadline :: UTCTime
' ReadyToFanout ' .
readyToFanoutSent :: Bool
, chainState :: ChainStateType tx
, headId :: HeadId
, previousRecoverableState :: HeadState tx
}
deriving (Generic)
deriving instance (IsTx tx, Eq (ChainStateType tx)) => Eq (ClosedState tx)
deriving instance (IsTx tx, Show (ChainStateType tx)) => Show (ClosedState tx)
deriving instance (IsTx tx, ToJSON (ChainStateType tx)) => ToJSON (ClosedState tx)
deriving instance (IsTx tx, FromJSON (ChainStateType tx)) => FromJSON (ClosedState tx)
instance (IsTx tx, Arbitrary (ChainStateType tx)) => Arbitrary (ClosedState tx) where
arbitrary =
ClosedState
<$> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> oneof
[ Open <$> arbitrary
, Closed <$> arbitrary
]
type TTL = Natural
defaultTTL :: TTL
defaultTTL = 5
data LogicError tx
= InvalidEvent (Event tx) (HeadState tx)
| InvalidState (HeadState tx)
| InvalidSnapshot {expected :: SnapshotNumber, actual :: SnapshotNumber}
| LedgerError ValidationError
| RequireFailed Text
deriving stock (Generic)
instance (Typeable tx, Show (Event tx), Show (HeadState tx)) => Exception (LogicError tx)
instance (Arbitrary (Event tx), Arbitrary (HeadState tx)) => Arbitrary (LogicError tx) where
arbitrary = genericArbitrary
deriving instance (Eq (HeadState tx), Eq (Event tx)) => Eq (LogicError tx)
deriving instance (Show (HeadState tx), Show (Event tx)) => Show (LogicError tx)
deriving instance (ToJSON (Event tx), ToJSON (HeadState tx)) => ToJSON (LogicError tx)
deriving instance (FromJSON (Event tx), FromJSON (HeadState tx)) => FromJSON (LogicError tx)
data Outcome tx
= OnlyEffects {effects :: [Effect tx]}
| NewState {headState :: HeadState tx, effects :: [Effect tx]}
| Wait {reason :: WaitReason}
| Error {error :: LogicError tx}
deriving stock (Generic)
deriving instance (IsTx tx, IsChainState tx) => Eq (Outcome tx)
deriving instance (IsTx tx, IsChainState tx) => Show (Outcome tx)
deriving instance (IsTx tx, IsChainState tx) => ToJSON (Outcome tx)
deriving instance (IsTx tx, IsChainState tx) => FromJSON (Outcome tx)
instance (IsTx tx, Arbitrary (ChainStateType tx)) => Arbitrary (Outcome tx) where
arbitrary = genericArbitrary
data WaitReason
= WaitOnNotApplicableTx {validationError :: ValidationError}
| WaitOnSnapshotNumber {waitingFor :: SnapshotNumber}
| WaitOnSeenSnapshot
| WaitOnContestationDeadline
deriving stock (Generic, Eq, Show)
deriving anyclass (ToJSON, FromJSON)
instance Arbitrary WaitReason where
arbitrary = genericArbitrary
data Environment = Environment
party :: Party
NOTE(MB ): In the long run we would not want to keep the signing key in
signingKey :: SigningKey HydraKey
, otherParties :: [Party]
, contestationPeriod :: ContestationPeriod
}
_ _ Transition _ _ : ' IdleState ' → ' IdleState '
onIdleClientInit ::
Environment ->
IdleState tx ->
Outcome tx
onIdleClientInit env st =
OnlyEffects [OnChainEffect{chainState, postChainTx = InitTx parameters}]
where
parameters =
HeadParameters
{ contestationPeriod
, parties = party : otherParties
}
Environment{party, otherParties, contestationPeriod} = env
IdleState{chainState} = st
| Observe an init transaction , initialize parameters in an ' InitialState ' and
_ _ Transition _ _ : ' IdleState ' → ' InitialState '
onIdleChainInitTx ::
IdleState tx ->
ChainStateType tx ->
[Party] ->
ContestationPeriod ->
HeadId ->
Outcome tx
onIdleChainInitTx idleState newChainState parties contestationPeriod headId =
NewState
( Initial
InitialState
{ parameters = HeadParameters{contestationPeriod, parties}
, pendingCommits = Set.fromList parties
, committed = mempty
, previousRecoverableState = Idle idleState
, chainState = newChainState
, headId
}
)
[ClientEffect $ HeadIsInitializing headId (fromList parties)]
| Client request to commit a entry to the head . Provided the client
that entry .
_ _ Transition _ _ : ' InitialState ' → ' InitialState '
onInitialClientCommit ::
Environment ->
InitialState tx ->
ClientInput tx ->
Outcome tx
onInitialClientCommit env st clientInput =
case clientInput of
(Commit utxo)
| canCommit -> OnlyEffects [OnChainEffect{chainState, postChainTx = CommitTx party utxo}]
_ -> OnlyEffects [ClientEffect $ CommandFailed clientInput]
where
canCommit = party `Set.member` pendingCommits
InitialState{pendingCommits, chainState} = st
Environment{party} = env
_ _ Transition _ _ : ' InitialState ' → ' InitialState '
onInitialChainCommitTx ::
Monoid (UTxOType tx) =>
Environment ->
InitialState tx ->
ChainStateType tx ->
Party ->
UTxOType tx ->
Outcome tx
onInitialChainCommitTx env st newChainState pt utxo =
NewState newState $
notifyClient :
[postCollectCom | canCollectCom]
where
newState =
Initial
InitialState
{ parameters
, pendingCommits = remainingParties
, committed = newCommitted
, previousRecoverableState = Initial st
, chainState = newChainState
, headId
}
newCommitted = Map.insert pt utxo committed
notifyClient = ClientEffect $ Committed headId pt utxo
postCollectCom =
OnChainEffect
{ chainState = newChainState
, postChainTx = CollectComTx $ fold newCommitted
}
canCollectCom = null remainingParties && pt == us
remainingParties = Set.delete pt pendingCommits
InitialState{parameters, pendingCommits, committed, headId} = st
Environment{party = us} = env
_ _ Transition _ _ : ' InitialState ' → ' InitialState '
onInitialClientAbort ::
Monoid (UTxOType tx) =>
InitialState tx ->
Outcome tx
onInitialClientAbort st =
OnlyEffects [OnChainEffect{chainState, postChainTx = AbortTx{utxo = fold committed}}]
where
InitialState{chainState, committed} = st
_ _ Transition _ _ : ' InitialState ' → ' IdleState '
onInitialChainAbortTx ::
Monoid (UTxOType tx) =>
ChainStateType tx ->
Committed tx ->
HeadId ->
Outcome tx
onInitialChainAbortTx newChainState committed headId =
NewState
(Idle IdleState{chainState = newChainState})
[ClientEffect $ HeadIsAborted{headId, utxo = fold committed}]
| Observe a collectCom transaction . We initialize the ' OpenState ' using the
head parameters from ' IdleState ' and construct an ' InitialSnapshot ' holding
@u0@ from the committed UTxOs .
_ _ Transition _ _ : ' InitialState ' → ' OpenState '
onInitialChainCollectTx ::
(Monoid (UTxOType tx)) =>
InitialState tx ->
ChainStateType tx ->
Outcome tx
onInitialChainCollectTx st newChainState =
NewState
( Open
OpenState
{ parameters
, coordinatedHeadState =
CoordinatedHeadState u0 mempty initialSnapshot NoSeenSnapshot
, previousRecoverableState = Initial st
, chainState = newChainState
, headId
}
)
[ClientEffect $ HeadIsOpen{headId, utxo = u0}]
where
u0 = fold committed
initialSnapshot = InitialSnapshot u0
InitialState{parameters, committed, headId} = st
_ _ Transition _ _ : ' OpenState ' → ' OpenState '
onOpenClientNewTx ::
Environment ->
tx ->
Outcome tx
onOpenClientNewTx env tx =
OnlyEffects [NetworkEffect $ ReqTx party tx]
where
Environment{party} = env
| Process a transaction request ( ' ReqTx ' ) from a party .
emit a snapshot request ' ReqSn ' including this transaction if needed .
_ _ Transition _ _ : ' OpenState ' → ' OpenState '
onOpenNetworkReqTx ::
Environment ->
Ledger tx ->
OpenState tx ->
TTL ->
tx ->
Outcome tx
onOpenNetworkReqTx env ledger st ttl tx =
Spec : wait L̂ ◦ ⊥ combined with L̂ ← L̂ ◦ tx
case applyTransactions seenUTxO [tx] of
Left (_, err)
| ttl <= 0 ->
OnlyEffects [ClientEffect $ TxInvalid headId seenUTxO tx err]
| otherwise -> Wait $ WaitOnNotApplicableTx err
Right utxo' ->
NewState
( Open
st
{ coordinatedHeadState =
coordinatedHeadState
{ seenTxs = seenTxs <> [tx]
seenUTxO = utxo'
}
}
)
[ClientEffect $ TxValid headId tx]
& emitSnapshot env
where
Ledger{applyTransactions} = ledger
CoordinatedHeadState{seenTxs, seenUTxO} = coordinatedHeadState
OpenState{coordinatedHeadState, headId} = st
_ _ Transition _ _ : ' OpenState ' → ' OpenState '
onOpenNetworkReqSn ::
IsTx tx =>
Environment ->
Ledger tx ->
OpenState tx ->
| Party which sent the ReqSn .
Party ->
SnapshotNumber ->
[tx] ->
Outcome tx
onOpenNetworkReqSn env ledger st otherParty sn requestedTxs =
Spec : require s = ŝ + 1 and leader(s ) = j
requireReqSn $
Spec : wait s̅ = ŝ
waitNoSnapshotInFlight $
Spec : wait U̅ ◦ T ̸= ⊥ combined with Û ← Ū̅ ◦ T
waitApplyTxs $ \u -> do
let nextSnapshot = Snapshot (confSn + 1) u requestedTxs
Spec : σᵢ
let snapshotSignature = sign signingKey nextSnapshot
Spec : T̂ ← ∀tx ∈ T̂ , Û ◦ tx ≠ ⊥ } and L̂ ← Û ◦ T̂
let (seenTxs', seenUTxO') = pruneTransactions u
NewState
( Open
st
{ coordinatedHeadState =
coordinatedHeadState
{ seenSnapshot = SeenSnapshot nextSnapshot mempty
, seenTxs = seenTxs'
, seenUTxO = seenUTxO'
}
}
)
[NetworkEffect $ AckSn party snapshotSignature sn]
where
requireReqSn continue =
if sn == seenSn + 1 && isLeader parameters otherParty sn
then continue
else Error $ RequireFailed "requireReqSn"
waitNoSnapshotInFlight continue =
if confSn == seenSn
then continue
else Wait $ WaitOnSnapshotNumber seenSn
waitApplyTxs cont =
case applyTransactions ledger confirmedUTxO requestedTxs of
Left (_, err) ->
confirmed snapshot utxo in NewTx ?
Wait $ WaitOnNotApplicableTx err
Right u -> cont u
pruneTransactions utxo = do
foldr go ([], utxo) seenTxs
where
go tx (txs, u) =
case applyTransactions ledger u [tx] of
Left (_, _) -> (txs, u)
Right u' -> (txs <> [tx], u')
confSn = case confirmedSnapshot of
InitialSnapshot{} -> 0
ConfirmedSnapshot{snapshot = Snapshot{number}} -> number
seenSn = seenSnapshotNumber seenSnapshot
confirmedUTxO = case confirmedSnapshot of
InitialSnapshot{initialUTxO} -> initialUTxO
ConfirmedSnapshot{snapshot = Snapshot{utxo}} -> utxo
CoordinatedHeadState{confirmedSnapshot, seenSnapshot, seenTxs} = coordinatedHeadState
OpenState{parameters, coordinatedHeadState} = st
Environment{party, signingKey} = env
potentially wait wait for the corresponding ' ReqSn ' before proceeding . If the
confirmed one . Similar to processing a ' ReqTx ' , we check whether we are
_ _ Transition _ _ : ' OpenState ' → ' OpenState '
onOpenNetworkAckSn ::
IsTx tx =>
Environment ->
OpenState tx ->
| Party which sent the AckSn .
Party ->
Signature (Snapshot tx) ->
| Snapshot number of this AckSn .
SnapshotNumber ->
Outcome tx
onOpenNetworkAckSn env openState otherParty snapshotSignature sn =
Spec : require s ∈ { ŝ , ŝ + 1 }
requireValidAckSn $ do
Spec : wait ŝ = s
waitOnSeenSnapshot $ \snapshot sigs -> do
Spec : ( j , . ) ∉ ̂Σ
requireNotSignedYet sigs $ do
let sigs' = Map.insert otherParty snapshotSignature sigs
ifAllMembersHaveSigned snapshot sigs' $ do
let multisig = aggregateInOrder sigs' parties
requireVerifiedMultisignature multisig snapshot $ do
NewState
( onlyUpdateCoordinatedHeadState $
coordinatedHeadState
{ confirmedSnapshot =
ConfirmedSnapshot
{ snapshot
, signatures = multisig
}
, seenSnapshot = LastSeenSnapshot (number snapshot)
}
)
[ClientEffect $ SnapshotConfirmed headId snapshot multisig]
& emitSnapshot env
where
seenSn = seenSnapshotNumber seenSnapshot
requireValidAckSn continue =
if sn `elem` [seenSn, seenSn + 1]
then continue
else Error $ RequireFailed "requireValidAckSn"
waitOnSeenSnapshot continue =
case seenSnapshot of
SeenSnapshot snapshot sigs
| seenSn == sn -> continue snapshot sigs
_ -> Wait WaitOnSeenSnapshot
requireNotSignedYet sigs continue =
if not (Map.member otherParty sigs)
then continue
else Error $ RequireFailed "requireNotSignedYet"
ifAllMembersHaveSigned snapshot sigs' cont =
if Map.keysSet sigs' == Set.fromList parties
then cont
else
NewState
( onlyUpdateCoordinatedHeadState $
coordinatedHeadState
{ seenSnapshot = SeenSnapshot snapshot sigs'
}
)
[]
requireVerifiedMultisignature multisig msg cont =
if verifyMultiSignature (vkey <$> parties) multisig msg
then cont
else Error $ RequireFailed "requireVerifiedMultisignature"
onlyUpdateCoordinatedHeadState chs' =
Open openState{coordinatedHeadState = chs'}
CoordinatedHeadState{seenSnapshot} = coordinatedHeadState
OpenState
{ parameters = HeadParameters{parties}
, coordinatedHeadState
, headId
} = openState
chain using the latest confirmed snaphshot of the ' OpenState ' .
_ _ Transition _ _ : ' OpenState ' → ' OpenState '
onOpenClientClose ::
OpenState tx ->
Outcome tx
onOpenClientClose st =
OnlyEffects [OnChainEffect{chainState, postChainTx = CloseTx confirmedSnapshot}]
where
CoordinatedHeadState{confirmedSnapshot} = coordinatedHeadState
OpenState{chainState, coordinatedHeadState} = st
_ _ Transition _ _ : ' OpenState ' → ' ClosedState '
onOpenChainCloseTx ::
OpenState tx ->
ChainStateType tx ->
SnapshotNumber ->
UTCTime ->
Outcome tx
onOpenChainCloseTx openState newChainState closedSnapshotNumber contestationDeadline =
NewState closedState $
notifyClient :
[ OnChainEffect
REVIEW : Was using " old " chainState before
chainState = newChainState
, postChainTx = ContestTx{confirmedSnapshot}
}
| doContest
]
where
doContest =
number (getSnapshot confirmedSnapshot) > closedSnapshotNumber
closedState =
Closed
ClosedState
{ parameters
, confirmedSnapshot
, contestationDeadline
, readyToFanoutSent = False
, previousRecoverableState = Open openState
, chainState = newChainState
, headId
}
notifyClient =
ClientEffect $
HeadIsClosed
{ headId
, snapshotNumber = closedSnapshotNumber
, contestationDeadline
}
CoordinatedHeadState{confirmedSnapshot} = coordinatedHeadState
OpenState{parameters, headId, coordinatedHeadState} = openState
_ _ Transition _ _ : ' ClosedState ' → ' ClosedState '
onClosedChainContestTx ::
ClosedState tx ->
SnapshotNumber ->
Outcome tx
onClosedChainContestTx closedState snapshotNumber
| snapshotNumber < number (getSnapshot confirmedSnapshot) =
OnlyEffects
[ ClientEffect HeadIsContested{snapshotNumber, headId}
, OnChainEffect{chainState, postChainTx = ContestTx{confirmedSnapshot}}
]
| snapshotNumber > number (getSnapshot confirmedSnapshot) =
OnlyEffects [ClientEffect HeadIsContested{snapshotNumber, headId}]
| otherwise =
OnlyEffects [ClientEffect HeadIsContested{snapshotNumber, headId}]
where
ClosedState{chainState, confirmedSnapshot, headId} = closedState
latest confirmed snapshot from ' ClosedState ' .
_ _ Transition _ _ : ' ClosedState ' → ' ClosedState '
onClosedClientFanout ::
ClosedState tx ->
Outcome tx
onClosedClientFanout closedState =
OnlyEffects
[ OnChainEffect
{ chainState
, postChainTx =
FanoutTx{utxo, contestationDeadline}
}
]
where
Snapshot{utxo} = getSnapshot confirmedSnapshot
ClosedState{chainState, confirmedSnapshot, contestationDeadline} = closedState
_ _ Transition _ _ : ' ClosedState ' → ' IdleState '
onClosedChainFanoutTx ::
ClosedState tx ->
ChainStateType tx ->
Outcome tx
onClosedChainFanoutTx closedState newChainState =
NewState
(Idle IdleState{chainState = newChainState})
[ ClientEffect $ HeadIsFinalized{headId, utxo}
]
where
Snapshot{utxo} = getSnapshot confirmedSnapshot
ClosedState{confirmedSnapshot, headId} = closedState
_ _ Transition _ _ : ' OpenState ' → ' HeadState '
onCurrentChainRollback ::
(IsChainState tx) =>
HeadState tx ->
ChainSlot ->
Outcome tx
onCurrentChainRollback currentState slot =
NewState (rollback slot currentState) [ClientEffect RolledBack]
where
rollback rollbackSlot hs
| chainStateSlot (getChainState hs) <= rollbackSlot = hs
| otherwise =
case hs of
Idle{} -> hs
Initial InitialState{previousRecoverableState} ->
rollback rollbackSlot previousRecoverableState
Open OpenState{previousRecoverableState} ->
rollback rollbackSlot previousRecoverableState
Closed ClosedState{previousRecoverableState} ->
rollback rollbackSlot previousRecoverableState
| The " pure core " of the Hydra node , which handles the ' Event ' against a
outcomes handled by the " Hydra . Node " .
update ::
(IsTx tx, IsChainState tx) =>
Environment ->
Ledger tx ->
HeadState tx ->
Event tx ->
Outcome tx
update env ledger st ev = case (st, ev) of
(Idle idleState, ClientEvent Init) ->
onIdleClientInit env idleState
(Idle idleState, OnChainEvent Observation{observedTx = OnInitTx{headId, contestationPeriod, parties}, newChainState}) ->
onIdleChainInitTx idleState newChainState parties contestationPeriod headId
(Initial idleState, ClientEvent clientInput@(Commit _)) ->
onInitialClientCommit env idleState clientInput
(Initial initialState, OnChainEvent Observation{observedTx = OnCommitTx{party = pt, committed = utxo}, newChainState}) ->
onInitialChainCommitTx env initialState newChainState pt utxo
(Initial initialState, ClientEvent Abort) ->
onInitialClientAbort initialState
(Initial initialState, OnChainEvent Observation{observedTx = OnCollectComTx{}, newChainState}) ->
onInitialChainCollectTx initialState newChainState
(Initial InitialState{headId, committed}, OnChainEvent Observation{observedTx = OnAbortTx{}, newChainState}) ->
onInitialChainAbortTx newChainState committed headId
(Initial InitialState{committed, headId}, ClientEvent GetUTxO) ->
OnlyEffects [ClientEffect . GetUTxOResponse headId $ fold committed]
(Open openState, ClientEvent Close) ->
onOpenClientClose openState
(Open{}, ClientEvent (NewTx tx)) ->
onOpenClientNewTx env tx
(Open openState, NetworkEvent ttl (ReqTx _ tx)) ->
onOpenNetworkReqTx env ledger openState ttl tx
(Open openState, NetworkEvent _ (ReqSn otherParty sn txs)) ->
XXX : = = 0 not handled for ReqSn
onOpenNetworkReqSn env ledger openState otherParty sn txs
(Open openState, NetworkEvent _ (AckSn otherParty snapshotSignature sn)) ->
XXX : = = 0 not handled for AckSn
onOpenNetworkAckSn env openState otherParty snapshotSignature sn
( Open openState
, OnChainEvent Observation{observedTx = OnCloseTx{snapshotNumber = closedSnapshotNumber, contestationDeadline}, newChainState}
) ->
onOpenChainCloseTx openState newChainState closedSnapshotNumber contestationDeadline
(Open OpenState{coordinatedHeadState = CoordinatedHeadState{confirmedSnapshot}, headId}, ClientEvent GetUTxO) ->
OnlyEffects [ClientEffect . GetUTxOResponse headId $ getField @"utxo" $ getSnapshot confirmedSnapshot]
(Closed closedState, OnChainEvent Observation{observedTx = OnContestTx{snapshotNumber}}) ->
onClosedChainContestTx closedState snapshotNumber
(Closed cst@ClosedState{contestationDeadline, readyToFanoutSent, headId}, OnChainEvent (Tick chainTime))
| chainTime > contestationDeadline && not readyToFanoutSent ->
NewState
(Closed cst{readyToFanoutSent = True})
[ClientEffect $ ReadyToFanout headId]
(Closed closedState, ClientEvent Fanout) ->
onClosedClientFanout closedState
(Closed closedState, OnChainEvent Observation{observedTx = OnFanoutTx{}, newChainState}) ->
onClosedChainFanoutTx closedState newChainState
(currentState, OnChainEvent (Rollback slot)) ->
onCurrentChainRollback currentState slot
(_, OnChainEvent Tick{}) ->
OnlyEffects []
(_, NetworkEvent _ (Connected nodeId)) ->
OnlyEffects [ClientEffect $ PeerConnected{peer = nodeId}]
(_, NetworkEvent _ (Disconnected nodeId)) ->
OnlyEffects [ClientEffect $ PeerDisconnected{peer = nodeId}]
(_, PostTxError{postChainTx, postTxError}) ->
OnlyEffects [ClientEffect $ PostTxOnChainFailed{postChainTx, postTxError}]
(_, ClientEvent{clientInput}) ->
OnlyEffects [ClientEffect $ CommandFailed clientInput]
_ ->
Error $ InvalidEvent ev st
data SnapshotOutcome tx
| ShouldNotSnapshot NoSnapshotReason
deriving (Eq, Show, Generic)
data NoSnapshotReason
= NotLeader SnapshotNumber
| SnapshotInFlight SnapshotNumber
| NoTransactionsToSnapshot
deriving (Eq, Show, Generic)
isLeader :: HeadParameters -> Party -> SnapshotNumber -> Bool
isLeader HeadParameters{parties} p sn =
case p `elemIndex` parties of
Just i -> ((fromIntegral sn - 1) `mod` length parties) == i
_ -> False
newSn :: Environment -> HeadParameters -> CoordinatedHeadState tx -> SnapshotOutcome tx
newSn Environment{party} parameters CoordinatedHeadState{confirmedSnapshot, seenSnapshot, seenTxs} =
if
| not (isLeader parameters party nextSn) ->
ShouldNotSnapshot $ NotLeader nextSn
snapshotInFlight ->
ShouldNotSnapshot $ SnapshotInFlight nextSn
| null seenTxs ->
ShouldNotSnapshot NoTransactionsToSnapshot
| otherwise ->
ShouldSnapshot nextSn seenTxs
where
nextSn = confirmedSn + 1
snapshotInFlight = case seenSnapshot of
NoSeenSnapshot -> False
LastSeenSnapshot{} -> False
RequestedSnapshot{} -> True
SeenSnapshot{} -> True
Snapshot{number = confirmedSn} = getSnapshot confirmedSnapshot
emitSnapshot :: Environment -> Outcome tx -> Outcome tx
emitSnapshot env@Environment{party} outcome =
case outcome of
NewState (Open OpenState{parameters, coordinatedHeadState, previousRecoverableState, chainState, headId}) effects ->
case newSn env parameters coordinatedHeadState of
ShouldSnapshot sn txs -> do
let CoordinatedHeadState{seenSnapshot} = coordinatedHeadState
NewState
( Open
OpenState
{ parameters
, coordinatedHeadState =
coordinatedHeadState
{ seenSnapshot =
RequestedSnapshot
{ lastSeen = seenSnapshotNumber $ seenSnapshot
, requested = sn
}
}
, previousRecoverableState
, chainState
, headId
}
)
$ NetworkEffect (ReqSn party sn txs) : effects
_ -> outcome
_ -> outcome
|
937fd8e70bb44ef9cf12dd4ba23c58c2831b673efe938f9a245658295dc4267f | tmfg/mmtis-national-access-point | buttons.cljs | (ns ote.ui.buttons
(:require [cljs-react-material-ui.reagent :as ui]
[ote.localization :refer [tr tr-key]]
[cljs-react-material-ui.core :refer [color]]
[cljs-react-material-ui.icons :as ic]
[stylefy.core :as stylefy]
[ote.style.base :as style-base]
[ote.style.buttons :as style-buttons]
[ote.ui.common :as common]
[ote.theme.colors :as colors]))
(defn- button-container [button]
[:div (stylefy/use-style style-base/action-button-container)
button])
(defn save [opts label]
[button-container
[:button (merge opts
(if (:disabled opts)
(stylefy/use-style style-buttons/disabled-button)
(stylefy/use-style style-buttons/primary-button)))
label]])
(defn save-publish [opts label]
[button-container
[:button (merge opts
(if (:disabled opts)
(stylefy/use-style style-buttons/disabled-button)
(stylefy/use-style style-buttons/primary-button)))
[ic/editor-publish {:style {:color "#FFFFFF" :margin-right "1rem"}}] [:span label]]])
(defn save-publish-table-row [opts label]
[button-container
[:button (merge opts
(if (:disabled opts)
(stylefy/use-style style-buttons/disabled-button)
(stylefy/use-style style-buttons/save-row-button)))
[ic/editor-publish {:style {:color "#FFFFFF" :margin-left "-10px"}}] [:span label]]])
(defn save-draft [opts label]
[button-container
[:button (merge opts
(if (:disabled opts)
(stylefy/use-style style-buttons/disabled-button)
(stylefy/use-style style-buttons/primary-button)))
[ic/content-drafts {:style {:color "#FFFFFF" :margin-right "1rem"}}] [:span label]]])
(defn cancel [opts label]
[button-container
[:button (merge opts
(if (:disabled opts)
(stylefy/use-style style-buttons/disabled-button)
(stylefy/use-style style-buttons/outline-button)))
label]])
(defn cancel-with-icon [opts label]
[button-container
[:button (merge opts
(if (:disabled opts)
(stylefy/use-style style-buttons/disabled-button)
(stylefy/use-style style-buttons/outline-button)))
[ic/navigation-close {:style {:color colors/primary-button-background-color :margin-right "1rem"}}] [:span label]]])
(defn delete [opts label]
[button-container
[:button (merge opts
(if (:disabled opts)
(stylefy/use-style style-buttons/disabled-button)
(stylefy/use-style style-buttons/negative-button)))
label]])
(defn delete-with-icon [opts label]
[button-container
[:button (merge opts
(if (:disabled opts)
(stylefy/use-style style-buttons/disabled-button)
(stylefy/use-style style-buttons/negative-button)))
[ic/action-delete {:style {:color "#FFFFFF" :margin-right "1rem"}}] [:span label]]])
(defn delete-table-row [opts label]
[button-container
[:button (merge opts
(if (:disabled opts)
(stylefy/use-style style-buttons/disabled-button)
(stylefy/use-style style-buttons/delete-row-button)))
[ic/action-delete {:style {:color "#FFFFFF" :margin-left "-10px"}}] [:span label]]])
(defn delete-set [opts label]
[button-container
[:button (merge opts
(if (:disabled opts)
(stylefy/use-style style-buttons/disabled-button)
(stylefy/use-style style-buttons/delete-set-button)))
[ic/action-delete {:style {:color "#FFFFFF" :margin-left "-10px"}}] [:span label]]])
(defn open-dialog-row [opts label]
[button-container
[:button (merge opts
(if (:disabled opts)
(stylefy/use-style style-buttons/disabled-button)
(stylefy/use-style style-buttons/open-dialog-row-button)))
[ic/action-today {:style {:color "#FFFFFF" :margin-left "-10px"}}] [:span label]]])
(defn open-link
"Create button like linkify link"
[url label]
[button-container
(common/linkify url
[ui/flat-button {:label label :primary true}]
{:target "_blank"})])
(defn icon-button
[opts label]
[:button.unstyled-button (merge
(stylefy/use-style style-buttons/svg-button)
opts)
label])
(defn big-icon-button-with-label
"Give icon-element in format: (ic/action-description {:style {:width 30
:height 30
:margin-right \"0.5rem\"
:color colors/primary}})
And label-text as text.
element-tag is :button or :a depending on do you want to move the user to different page or do magic right where she/he is."
[options icon-element label-text]
[:button (merge options
{:style {:align-items "center"}}
(stylefy/use-style style-base/blue-link-with-icon)
(stylefy/use-style style-buttons/outline-button))
icon-element
[:span label-text]])
| null | https://raw.githubusercontent.com/tmfg/mmtis-national-access-point/e36f9898bce005736e36153bdc7cca3386a44daf/ote/src/cljs/ote/ui/buttons.cljs | clojure | (ns ote.ui.buttons
(:require [cljs-react-material-ui.reagent :as ui]
[ote.localization :refer [tr tr-key]]
[cljs-react-material-ui.core :refer [color]]
[cljs-react-material-ui.icons :as ic]
[stylefy.core :as stylefy]
[ote.style.base :as style-base]
[ote.style.buttons :as style-buttons]
[ote.ui.common :as common]
[ote.theme.colors :as colors]))
(defn- button-container [button]
[:div (stylefy/use-style style-base/action-button-container)
button])
(defn save [opts label]
[button-container
[:button (merge opts
(if (:disabled opts)
(stylefy/use-style style-buttons/disabled-button)
(stylefy/use-style style-buttons/primary-button)))
label]])
(defn save-publish [opts label]
[button-container
[:button (merge opts
(if (:disabled opts)
(stylefy/use-style style-buttons/disabled-button)
(stylefy/use-style style-buttons/primary-button)))
[ic/editor-publish {:style {:color "#FFFFFF" :margin-right "1rem"}}] [:span label]]])
(defn save-publish-table-row [opts label]
[button-container
[:button (merge opts
(if (:disabled opts)
(stylefy/use-style style-buttons/disabled-button)
(stylefy/use-style style-buttons/save-row-button)))
[ic/editor-publish {:style {:color "#FFFFFF" :margin-left "-10px"}}] [:span label]]])
(defn save-draft [opts label]
[button-container
[:button (merge opts
(if (:disabled opts)
(stylefy/use-style style-buttons/disabled-button)
(stylefy/use-style style-buttons/primary-button)))
[ic/content-drafts {:style {:color "#FFFFFF" :margin-right "1rem"}}] [:span label]]])
(defn cancel [opts label]
[button-container
[:button (merge opts
(if (:disabled opts)
(stylefy/use-style style-buttons/disabled-button)
(stylefy/use-style style-buttons/outline-button)))
label]])
(defn cancel-with-icon [opts label]
[button-container
[:button (merge opts
(if (:disabled opts)
(stylefy/use-style style-buttons/disabled-button)
(stylefy/use-style style-buttons/outline-button)))
[ic/navigation-close {:style {:color colors/primary-button-background-color :margin-right "1rem"}}] [:span label]]])
(defn delete [opts label]
[button-container
[:button (merge opts
(if (:disabled opts)
(stylefy/use-style style-buttons/disabled-button)
(stylefy/use-style style-buttons/negative-button)))
label]])
(defn delete-with-icon [opts label]
[button-container
[:button (merge opts
(if (:disabled opts)
(stylefy/use-style style-buttons/disabled-button)
(stylefy/use-style style-buttons/negative-button)))
[ic/action-delete {:style {:color "#FFFFFF" :margin-right "1rem"}}] [:span label]]])
(defn delete-table-row [opts label]
[button-container
[:button (merge opts
(if (:disabled opts)
(stylefy/use-style style-buttons/disabled-button)
(stylefy/use-style style-buttons/delete-row-button)))
[ic/action-delete {:style {:color "#FFFFFF" :margin-left "-10px"}}] [:span label]]])
(defn delete-set [opts label]
[button-container
[:button (merge opts
(if (:disabled opts)
(stylefy/use-style style-buttons/disabled-button)
(stylefy/use-style style-buttons/delete-set-button)))
[ic/action-delete {:style {:color "#FFFFFF" :margin-left "-10px"}}] [:span label]]])
(defn open-dialog-row [opts label]
[button-container
[:button (merge opts
(if (:disabled opts)
(stylefy/use-style style-buttons/disabled-button)
(stylefy/use-style style-buttons/open-dialog-row-button)))
[ic/action-today {:style {:color "#FFFFFF" :margin-left "-10px"}}] [:span label]]])
(defn open-link
"Create button like linkify link"
[url label]
[button-container
(common/linkify url
[ui/flat-button {:label label :primary true}]
{:target "_blank"})])
(defn icon-button
[opts label]
[:button.unstyled-button (merge
(stylefy/use-style style-buttons/svg-button)
opts)
label])
(defn big-icon-button-with-label
"Give icon-element in format: (ic/action-description {:style {:width 30
:height 30
:margin-right \"0.5rem\"
:color colors/primary}})
And label-text as text.
element-tag is :button or :a depending on do you want to move the user to different page or do magic right where she/he is."
[options icon-element label-text]
[:button (merge options
{:style {:align-items "center"}}
(stylefy/use-style style-base/blue-link-with-icon)
(stylefy/use-style style-buttons/outline-button))
icon-element
[:span label-text]])
| |
12c71da123d584ceb7060e025c94a7a1a0fe4c520878a466797e678015ecde76 | meain/evil-textobj-tree-sitter | textobjects.scm | (class_declaration
body: (declaration_list . "{" . (_) @class.inner._start @class.inner._end (_)? @class.inner._end . "}"
)) @class.outer
(struct_declaration
body: (declaration_list . "{" . (_) @class.inner._start @class.inner._end (_)? @class.inner._end . "}"
)) @class.outer
(method_declaration
body: (block . "{" . (_) @function.inner._start @function.inner._end (_)? @function.inner._end . "}"
)) @function.outer
(lambda_expression
body: (block . "{" . (_) @function.inner._start @function.inner._end (_)? @function.inner._end . "}"
)) @function.outer
;; loops
(for_statement
body: (_) @loop.inner) @loop.outer
(for_each_statement
body: (_) @loop.inner) @loop.outer
(do_statement
(block) @loop.inner) @loop.outer
(while_statement
(block) @loop.inner) @loop.outer
;; conditionals
(if_statement
consequence: (_)? @conditional.inner
alternative: (_)? @conditional.inner) @conditional.outer
(switch_statement
body: (switch_body) @conditional.inner) @conditional.outer
;; calls
(invocation_expression) @call.outer
(invocation_expression
arguments: (argument_list . "(" . (_) @call.inner._start (_)? @call.inner._end . ")"
))
;; blocks
(_ (block) @block.inner) @block.outer
;; parameters
((parameter_list
"," @parameter.outer._start . (parameter) @parameter.inner @parameter.outer._end)
)
((parameter_list
. (parameter) @parameter.inner @parameter.outer._start . ","? @parameter.outer._end)
)
((argument_list
"," @parameter.outer._start . (argument) @parameter.inner @parameter.outer._end)
)
((argument_list
. (argument) @parameter.inner @parameter.outer._start . ","? @parameter.outer._end)
)
;; comments
(comment) @comment.outer
| null | https://raw.githubusercontent.com/meain/evil-textobj-tree-sitter/866928d3ee6b4623addc2324f2eebe55e95dd778/queries/c_sharp/textobjects.scm | scheme | loops
conditionals
calls
blocks
parameters
comments | (class_declaration
body: (declaration_list . "{" . (_) @class.inner._start @class.inner._end (_)? @class.inner._end . "}"
)) @class.outer
(struct_declaration
body: (declaration_list . "{" . (_) @class.inner._start @class.inner._end (_)? @class.inner._end . "}"
)) @class.outer
(method_declaration
body: (block . "{" . (_) @function.inner._start @function.inner._end (_)? @function.inner._end . "}"
)) @function.outer
(lambda_expression
body: (block . "{" . (_) @function.inner._start @function.inner._end (_)? @function.inner._end . "}"
)) @function.outer
(for_statement
body: (_) @loop.inner) @loop.outer
(for_each_statement
body: (_) @loop.inner) @loop.outer
(do_statement
(block) @loop.inner) @loop.outer
(while_statement
(block) @loop.inner) @loop.outer
(if_statement
consequence: (_)? @conditional.inner
alternative: (_)? @conditional.inner) @conditional.outer
(switch_statement
body: (switch_body) @conditional.inner) @conditional.outer
(invocation_expression) @call.outer
(invocation_expression
arguments: (argument_list . "(" . (_) @call.inner._start (_)? @call.inner._end . ")"
))
(_ (block) @block.inner) @block.outer
((parameter_list
"," @parameter.outer._start . (parameter) @parameter.inner @parameter.outer._end)
)
((parameter_list
. (parameter) @parameter.inner @parameter.outer._start . ","? @parameter.outer._end)
)
((argument_list
"," @parameter.outer._start . (argument) @parameter.inner @parameter.outer._end)
)
((argument_list
. (argument) @parameter.inner @parameter.outer._start . ","? @parameter.outer._end)
)
(comment) @comment.outer
|
44c9cda1e4682af8e855fcf3086050befa19cd7f5bc64d90205eb1d0a33d9965 | utkarshkukreti/reaml | Reaml_Ppx_Bin.ml | open Migrate_parsetree
let _ = Driver.run_as_ppx_rewriter ()
| null | https://raw.githubusercontent.com/utkarshkukreti/reaml/5640a36293ba2a765171225deddb644f4d6c5d26/ppx/bin/Reaml_Ppx_Bin.ml | ocaml | open Migrate_parsetree
let _ = Driver.run_as_ppx_rewriter ()
| |
e08b8b1e7a58508ce7e9045c8ed112da2a4fed7c2f975fb99293fcb882035cbe | Kappa-Dev/KappaTools | fileNames.ml | (*file names*)
let input:(string list ref) = ref [] (*name of the kappa files*)
let output = ref "data.out"
| null | https://raw.githubusercontent.com/Kappa-Dev/KappaTools/eef2337e8688018eda47ccc838aea809cae68de7/core/parameters/fileNames.ml | ocaml | file names
name of the kappa files |
let output = ref "data.out"
|
0df23ae9f977203f8e7d050d944ce767fe412c23fcc0a89b5d7a9e7a41755870 | ml4tp/tcoq | indrec.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Names
open Term
open Environ
open Evd
(** Errors related to recursors building *)
type recursion_scheme_error =
:
| NotMutualInScheme of inductive * inductive
:
exception RecursionSchemeError of recursion_scheme_error
(** Eliminations *)
type dep_flag = bool
(** Build a case analysis elimination scheme in some sort family *)
val build_case_analysis_scheme : env -> 'r Sigma.t -> pinductive ->
dep_flag -> sorts_family -> (constr, 'r) Sigma.sigma
* Build a dependent case elimination predicate unless type is in Prop
or is a recursive record with primitive projections .
or is a recursive record with primitive projections. *)
val build_case_analysis_scheme_default : env -> 'r Sigma.t -> pinductive ->
sorts_family -> (constr, 'r) Sigma.sigma
* Builds a recursive induction scheme ( Peano - induction style ) in the same
sort family as the inductive family ; it is dependent if not in Prop
or a recursive record with primitive projections .
sort family as the inductive family; it is dependent if not in Prop
or a recursive record with primitive projections. *)
val build_induction_scheme : env -> evar_map -> pinductive ->
dep_flag -> sorts_family -> evar_map * constr
(** Builds mutual (recursive) induction schemes *)
val build_mutual_induction_scheme :
env -> evar_map -> (pinductive * dep_flag * sorts_family) list -> evar_map * constr list
(** Scheme combinators *)
(** [weaken_sort_scheme env sigma eq s n c t] derives by subtyping from [c:t]
whose conclusion is quantified on [Type i] at position [n] of [t] a
scheme quantified on sort [s]. [set] asks for [s] be declared equal to [i],
otherwise just less or equal to [i]. *)
val weaken_sort_scheme : env -> evar_map -> bool -> sorts -> int -> constr -> types ->
evar_map * types * constr
(** Recursor names utilities *)
val lookup_eliminator : inductive -> sorts_family -> Globnames.global_reference
val elimination_suffix : sorts_family -> string
val make_elimination_ident : Id.t -> sorts_family -> Id.t
val case_suffix : string
| null | https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/pretyping/indrec.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
* Errors related to recursors building
* Eliminations
* Build a case analysis elimination scheme in some sort family
* Builds mutual (recursive) induction schemes
* Scheme combinators
* [weaken_sort_scheme env sigma eq s n c t] derives by subtyping from [c:t]
whose conclusion is quantified on [Type i] at position [n] of [t] a
scheme quantified on sort [s]. [set] asks for [s] be declared equal to [i],
otherwise just less or equal to [i].
* Recursor names utilities | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Names
open Term
open Environ
open Evd
type recursion_scheme_error =
:
| NotMutualInScheme of inductive * inductive
:
exception RecursionSchemeError of recursion_scheme_error
type dep_flag = bool
val build_case_analysis_scheme : env -> 'r Sigma.t -> pinductive ->
dep_flag -> sorts_family -> (constr, 'r) Sigma.sigma
* Build a dependent case elimination predicate unless type is in Prop
or is a recursive record with primitive projections .
or is a recursive record with primitive projections. *)
val build_case_analysis_scheme_default : env -> 'r Sigma.t -> pinductive ->
sorts_family -> (constr, 'r) Sigma.sigma
* Builds a recursive induction scheme ( Peano - induction style ) in the same
sort family as the inductive family ; it is dependent if not in Prop
or a recursive record with primitive projections .
sort family as the inductive family; it is dependent if not in Prop
or a recursive record with primitive projections. *)
val build_induction_scheme : env -> evar_map -> pinductive ->
dep_flag -> sorts_family -> evar_map * constr
val build_mutual_induction_scheme :
env -> evar_map -> (pinductive * dep_flag * sorts_family) list -> evar_map * constr list
val weaken_sort_scheme : env -> evar_map -> bool -> sorts -> int -> constr -> types ->
evar_map * types * constr
val lookup_eliminator : inductive -> sorts_family -> Globnames.global_reference
val elimination_suffix : sorts_family -> string
val make_elimination_ident : Id.t -> sorts_family -> Id.t
val case_suffix : string
|
3a0528fc98c7948f7d6b9390edb61b0a2e6f745f1f0be8a6be0acfce4d9d2295 | themetaschemer/malt | A-autodiff.rkt | #lang racket
(require "../tensors.rkt")
;;----------------------------
;; Reverse-mode AD
;;----------------------------
(define ∇
(λ (f theta)
(let ((wrt (map* dual* theta)))
(∇-once (f wrt) wrt))))
(define ∇¹
(λ (f)
(λ xs
(let ((wrt (map* dual* xs)))
(∇-once (apply f wrt) wrt)))))
(define ∇-once
(λ (y wrt)
(let ((σ (∇σ y (hasheq))))
(map* (λ (d)
(hash-ref σ d 0.0))
wrt))))
(define ∇σ
(λ (y σ)
(cond
((scalar? y)
((κ y) y 1.0 σ))
((list? y)
(∇σ-list y σ))
((vector? y)
(∇σ-vector y (sub1 (tlen y)) σ))
(else (printf "Unknown: ~a~%" y)))))
(define ∇σ-list
(λ (y σ)
(cond
((null? y) σ)
(else
(let ((σ-hat (∇σ (ref y 0) σ)))
(∇σ-list (refr y 1) σ-hat))))))
(define ∇σ-vector
(λ (y i σ)
(let ((σ-hat (∇σ (tref y i) σ)))
(cond
((zero? i) σ-hat)
(else (∇σ-vector y (sub1 i) σ-hat))))))
;;----------------------------
;; General helpers
;;----------------------------
(define map*
(λ (f y)
(cond
((scalar? y) (f y))
((list? y)
(map (λ (lm)
(map* f lm))
y))
((vector? y)
(vector-map (λ (ve)
(map* f ve))
y))
(else
(error 'map* "Cannot map* ~a" y)))))
(define trace-print
(λ (v port)
(cond
((dual? v) (trace-print (ρ v) port))
(else (fprintf port "~a~%" v)))))
(include "test/test-A-autodiff.rkt")
(provide
dual dual? ρ κ ∇ ∇¹ ∇-once map* dual* scalar?
trace-print)
| null | https://raw.githubusercontent.com/themetaschemer/malt/78a04063a5a343f5cf4332e84da0e914cdb4d347/learner/autodiff/A-autodiff.rkt | racket | ----------------------------
Reverse-mode AD
----------------------------
----------------------------
General helpers
---------------------------- | #lang racket
(require "../tensors.rkt")
(define ∇
(λ (f theta)
(let ((wrt (map* dual* theta)))
(∇-once (f wrt) wrt))))
(define ∇¹
(λ (f)
(λ xs
(let ((wrt (map* dual* xs)))
(∇-once (apply f wrt) wrt)))))
(define ∇-once
(λ (y wrt)
(let ((σ (∇σ y (hasheq))))
(map* (λ (d)
(hash-ref σ d 0.0))
wrt))))
(define ∇σ
(λ (y σ)
(cond
((scalar? y)
((κ y) y 1.0 σ))
((list? y)
(∇σ-list y σ))
((vector? y)
(∇σ-vector y (sub1 (tlen y)) σ))
(else (printf "Unknown: ~a~%" y)))))
(define ∇σ-list
(λ (y σ)
(cond
((null? y) σ)
(else
(let ((σ-hat (∇σ (ref y 0) σ)))
(∇σ-list (refr y 1) σ-hat))))))
(define ∇σ-vector
(λ (y i σ)
(let ((σ-hat (∇σ (tref y i) σ)))
(cond
((zero? i) σ-hat)
(else (∇σ-vector y (sub1 i) σ-hat))))))
(define map*
(λ (f y)
(cond
((scalar? y) (f y))
((list? y)
(map (λ (lm)
(map* f lm))
y))
((vector? y)
(vector-map (λ (ve)
(map* f ve))
y))
(else
(error 'map* "Cannot map* ~a" y)))))
(define trace-print
(λ (v port)
(cond
((dual? v) (trace-print (ρ v) port))
(else (fprintf port "~a~%" v)))))
(include "test/test-A-autodiff.rkt")
(provide
dual dual? ρ κ ∇ ∇¹ ∇-once map* dual* scalar?
trace-print)
|
77c71d66eb46167038d5b2f9b682c9382003beab939fb70ebf76184b2466ccb3 | rpav/cl-gendoc | package.lisp | (defpackage :gendoc
(:use #:cl)
(:export #:gendoc #:define-gendoc-load-op
#:add-processor))
| null | https://raw.githubusercontent.com/rpav/cl-gendoc/c8fed7dd008a0cc34138521e45116e063aea33bd/package.lisp | lisp | (defpackage :gendoc
(:use #:cl)
(:export #:gendoc #:define-gendoc-load-op
#:add-processor))
| |
f0ae99fe2ffae0d490b26b235337ab5614cd76580b85edb1ec0c754e09b845be | deadpendency/deadpendency | Vector.hs | # OPTIONS_GHC -fno - warn - orphans #
module Common.HtmlReport.Instances.Vector
(
)
where
import Common.HtmlReport.HtmlReport
import Data.Vector qualified as V
import Data.Vector.NonEmpty qualified as NV
instance {-# OVERLAPPABLE #-} (ToHtmlReportBody a) => ToHtmlReportBody (NV.NonEmptyVector a) where
toHtmlReportBody = toHtmlReportBody . NV.toVector
instance {-# OVERLAPPABLE #-} (ToHtmlReportBody a) => ToHtmlReportBody (V.Vector a) where
toHtmlReportBody items
| V.null items = mempty
| otherwise =
foldMap' toHtmlReportBody items
| null | https://raw.githubusercontent.com/deadpendency/deadpendency/170d6689658f81842168b90aa3d9e235d416c8bd/apps/common/src/Common/HtmlReport/Instances/Vector.hs | haskell | # OVERLAPPABLE #
# OVERLAPPABLE # | # OPTIONS_GHC -fno - warn - orphans #
module Common.HtmlReport.Instances.Vector
(
)
where
import Common.HtmlReport.HtmlReport
import Data.Vector qualified as V
import Data.Vector.NonEmpty qualified as NV
toHtmlReportBody = toHtmlReportBody . NV.toVector
toHtmlReportBody items
| V.null items = mempty
| otherwise =
foldMap' toHtmlReportBody items
|
9fc56ac2de36f264d6b57ef86642321a484f9fbf24ca1c75b7f177738383523b | kkinnear/zprint | guide.cljc | (ns ^:no-doc zprint.guide
#?@(:cljs [[:require-macros
[zprint.macros :refer
[dbg dbg-s dbg-pr dbg-s-pr dbg-form dbg-print zfuture]]]])
(:require #?@(:clj [[zprint.macros :refer
[dbg-pr dbg-s-pr dbg dbg-s dbg-form dbg-print zfuture]]])
[zprint.util :refer [column-alignment cumulative-alignment]]))
;;
;; Contains functions which can be called with {:option-fn <fn>} to produce
;; a "guide", which is, roughtly, a sequence comprised of keywords
;; which describe how to format an expression. A guide must be created
;; explicitly for the expression to be formatted.
;;
;; For instance, this expression: (a b c d e f g) could be formatted
;; for this output:
;;
;; (a b c
;; d e f
;; g)
;;
;; by this guide:
;;
;; [:element :element :element :newline :element :element :element :newline
;; :element]
;;
;; There are a lot more keywords and other things which can be in a guide
;; than demonstrated above.
;;
# Guide for " rules of defn " , an alternative way to format defn expressions .
;;
(defn rodguide
"Given a structure which starts with defn, create a guide for the
'rules of defn', an alternative approach to formatting a defn."
([] "rodguide")
; If you call a guide with partial because it has its own options map,
; the "no-argument" arity must include the options map!
([rod-options] "rodguide")
; Since we have released this before, we will also allow it to be called
; without rod-options
([options len sexpr] (rodguide {} options len sexpr))
([rod-options options len sexpr]
(when (or (= (str (first sexpr)) "defn") (= (str (first sexpr)) "defn-"))
(let [multi-arity-nl? (get rod-options :multi-arity-nl? true)
docstring? (string? (nth sexpr 2))
rest (nthnext sexpr (if docstring? 3 2))
multi-arity? (not (vector? (first rest)))
rest (if multi-arity? rest (next rest))
#_#_zfn-map (:zfn-map options)
#_#_rest-count ((:zcount zfn-map) (:zloc options))
; It is not just that the count is off.
rest-guide (repeat (dec #_rest-count (count rest)) :element)
rest-guide
(into []
(if (and multi-arity? multi-arity-nl?)
(interleave rest-guide (repeat :newline) (repeat :newline))
(interleave rest-guide (repeat :newline))))
; Make interleave into interpose
rest-guide (conj rest-guide :element)
guide (cond-> [:element :element]
docstring? (conj :newline :element :newline)
(not multi-arity?) (conj :element :newline)
(and multi-arity? (not docstring?)) (conj :newline)
:rest (into rest-guide))
option-map {:guide guide, :next-inner {:list {:option-fn nil}}}]
(if multi-arity?
(assoc option-map
:next-inner {:list {:option-fn nil},
:fn-map {:vector :force-nl},
:next-inner-restore [[:fn-map :vector]]})
option-map)))))
; Use this to use the above:
;
; (czprint rod4
; {:parse-string? true
; :fn-map {"defn" [:guided {:list {:option-fn rodguide}}]}})
;;
;; # Guide to replicate the existing output for {:style :moustache}
;;
(defn constant-or-vector?
"Return true if a constant or vector."
[element]
#_(println "c-or-v?" element)
(or (number? element)
(string? element)
(vector? element)
(keyword? element)
(= element true)
(= element false)))
(defn count-constants
[[constant-count possible-constant?] element]
(if possible-constant?
(if (constant-or-vector? element)
[(inc constant-count) (not possible-constant?)]
(reduced [constant-count possible-constant?]))
[constant-count (not possible-constant?)]))
(defn moustacheguide
"Reimplement :style :moustache with guides."
([] "moustacheguide")
([options len sexpr]
First , find the pairs .
(let [rev-sexpr (reverse sexpr)
[constant-count _] (reduce count-constants [0 false] rev-sexpr)
pair-count (* constant-count 2)
pair-guide (into [] (repeat pair-count :element))
pair-guide (conj pair-guide :group-end)
pair-guide (conj pair-guide :element-pair-group)
non-pair-count (- (count sexpr) pair-count)
non-pair-guide (repeat non-pair-count :element)
non-pair-guide (into [] (interpose :newline non-pair-guide))
guide (conj non-pair-guide :newline :group-begin)
guide (concat guide pair-guide)]
(dbg-s options
:guide
"moustacheguide: sexpr" sexpr
"pair-count:" pair-count
"output:" guide)
{:guide guide,
:pair {:justify? true},
:next-inner {:pair {:justify? false}, :list {:option-fn nil}}})))
; Use this to use the above:
;
( czprint
; {:parse-string? true
; :fn-map {"m/app" [:guided {:list {:option-fn moustacheguide}}]}})
;;
;; # Guide for the "are" function
;;
(defn add-double-quotes
"Given two arguments, an s-expression and a string, if the s-expression
is actually a string, add a double quote on to the beginning and end of
the string."
[sexpr s]
(if (string? sexpr) (str "\"" s "\"") s))
(defn areguide
"Format are test functions. Call it with (partial {} areguide), where
the map can be {:justify? true} to justify the various rows. It will
use {:pair {:justify {:max-variance n}}} for the variance, but you can
give it a variance to use with {:max-variance n} in the map which is
its first argument."
([] "areguide")
; If you call a guide with partial because it has its own options map,
; the "no-argument" arity must include the options map!
([are-options] "areguide")
; Since we have released this before, we will also allow it to be called
; without are-options
([options len sexpr] (areguide {} options len sexpr))
([are-options options len sexpr]
(let [justify? (:justify? are-options)
max-variance (when justify?
(or (:max-variance are-options)
(:max-variance (:justify (:pair options)))))
caller-options ((:caller options) options)
current-indent (or (:indent-arg caller-options)
(:indent caller-options))
are-indent (:indent are-options)
table-indent (+ current-indent (or are-indent current-indent))
arg-vec-len (count (second sexpr))
test-len (- (count sexpr) 3)
rows (/ test-len arg-vec-len)
excess-tests (- test-len (* rows arg-vec-len))
alignment-vec
(when justify?
(let [; zloc-seq no comments
zfn-map (:zfn-map options)
zloc-seq-nc
((:zmap-no-comment zfn-map) identity (:zloc options))
args (drop 3 zloc-seq-nc)
; Get the lengths of the actual zloc values, not the sexpr
arg-strs (mapv (:zstring zfn-map) args)
#_(prn "early arg-strs:" arg-strs)
; This makes strings too long, but it was
presumably added for some reason ? Issue # 212
arg - strs ( mapv add - double - quotes ( drop 3 sexpr ) arg - strs )
#_(prn "later arg-strs:" arg-strs)
seq-of-seqs (partition arg-vec-len arg-vec-len [] arg-strs)
max-width-vec (column-alignment max-variance
seq-of-seqs
nil
:no-string-adj?)
alignment-vec (cumulative-alignment max-width-vec)]
#_(prn "max-width-vec:" max-width-vec
"alignment-vec:" alignment-vec)
alignment-vec))
mark-guide
(vec (flatten
(mapv vector (repeat :mark-at-indent) (range) alignment-vec)))
new-row-guide (cond-> [:element :indent table-indent]
(not (empty? alignment-vec))
(into (interleave (repeat :align)
(range (count alignment-vec))
(repeat :element)))
(empty? alignment-vec) (into (repeat (dec arg-vec-len)
:element))
true (conj :indent-reset :newline))
multi-row-guide (apply concat (repeat rows new-row-guide))
guide (cond-> (-> [:element :element :element-best :newline]
(into mark-guide)
(into multi-row-guide))
(pos? excess-tests) (conj :element-*))]
#_(prn "guide:" guide)
{:guide guide, :next-inner {:list {:option-fn nil}}})))
(defn areguide-basic
"Format are test functions, no justification."
([] "areguide")
([options len sexpr]
(let [arg-vec-len (count (second sexpr))
beginning (take 3 sexpr)
test-len (- (count sexpr) 3)
rows (/ test-len arg-vec-len)
excess-tests (- test-len (* rows arg-vec-len))
single-row (into [:newline] (repeat arg-vec-len :element))
row-guide (apply concat (repeat rows single-row))
guide (cond-> (-> [:element :element :element-best]
(into row-guide))
(pos? excess-tests) (conj :newline :element-*))]
{:guide guide, :next-inner {:list {:option-fn nil}}})))
; Do this to use the above:
;
; (czprint are3
; {:parse-string? true
; :fn-map {"are" [:guided {:list {:option-fn areguide}}]}})
;
;;
;; # Guide to justify the content of the vectors in a (:require ...)
;;
;
; A much simpler version of the require guide. This version doesn't require
use of the call - stack , and has only one option - fn instead of two . It also
; uses the new variance-based justification capabilities.
;
(defn jrequireguide
"Justify the first things in a variety of settings. The first argument
is the things to recognize, and can be :require, :require-macros, or
:import. :require and :require-macros are handled the same, and :import
is handled differently since it has the values all in the same expression.
Handles sequences with lists or vectors."
([] "jrequireguide")
If you call a guide with partial because it has its a required first
argument , ; the " no - argument " arity must include the first argument !
([keyword] "jrequireguide")
([keyword options len sexpr]
(when (= (first sexpr) keyword)
(let [vectors+lists (filter #(or (vector? %) (list? %)) sexpr)]
(when (not (empty? vectors+lists))
(let [max-width-vec (column-alignment (:max-variance
(:justify (:pair options)))
vectors+lists
only do the first column
1)
_ (dbg-s options
:guide
"jrequireguide max-width-vec:"
max-width-vec)
max-first (first max-width-vec)
element-guide :element-pair-*
vector-guide (if max-first
(if (= (first sexpr) :import)
[:mark-at 0 (inc max-first) :element :align 0
:indent-here #_(+ max-first 2) :element-*]
[:mark-at 0 (inc max-first) :element :align 0
element-guide])
; We can't justify things, fall back to this.
[:element element-guide])]
Do this for all of the first level vectors and lists below the
; :require, but no other vectors or lists more deeply nested.
{:next-inner {:vector {:option-fn (fn [_ _ _] {:guide vector-guide}),
:wrap-multi? true,
:hang? true},
:list {:option-fn (fn [_ _ _] {:guide vector-guide}),
:wrap-multi? true,
:hang? true},
:pair {:justify? true},
:next-inner-restore
[[:vector :option-fn] [:vector :wrap-multi?]
[:vector :hang?] [:list :option-fn]
[:list :wrap-multi?] [:list :hang?]
[:pair :justify?]]}}))))))
; Do this to use the above:
;
; (czprint jr1
; {:parse-string? true
; :fn-map {":require" [:none {:list {:option-fn jrequireguide}}]}})
;;
;; # Guide to replicate the output of :arg1-mixin
;;
(defn rumguide
"Assumes that this is rum/defcs or something similar. Implement :arg1-mixin
with guides using :spaces. For guide testing, do not use this as a model
for how to write a guide."
([] "rumguide")
([options len sexpr]
(let [docstring? (string? (nth sexpr 2))
[up-to-arguments args-and-after]
(split-with #(not (or (vector? %)
(and (list? %) (vector? (first %)))))
sexpr)
#_(println "rumguide: up-to-arguments:" up-to-arguments
"\nargs-and-after:" args-and-after)]
(if (empty? args-and-after)
{:list {:option-fn nil}}
(let [lt (nth sexpr (if docstring? 3 2))
lt? (= (str lt) "<")
mixin-indent (if lt? 2 1)
beginning-guide [:element :element :newline]
beginning-guide (if docstring?
(concat beginning-guide [:element :newline])
beginning-guide)
middle-element-count
(- (count up-to-arguments) 2 (if docstring? 1 0) (if lt? 1 0))
middle-guide
(if (pos? middle-element-count)
(if lt? [:element :element :newline] [:element :newline])
[])
#_(println "middle-element-count:" middle-element-count)
middle-guide (concat middle-guide
(repeat (dec middle-element-count)
[:spaces mixin-indent :element
:newline]))
end-element-count (count args-and-after)
end-guide [:element
(repeat (dec end-element-count) [:newline :element])]
guide (concat beginning-guide middle-guide end-guide)
; This could have been done so flatten wasn't necessary
; but it for testing it wasn't worth the re-work.
guide (flatten guide)
#_(println "rumguide: guide:" guide)]
{:guide guide, :next-inner {:list {:option-fn nil}}})))))
(defn rumguide-1
"Assumes that this is rum/defcs or something similar. Implement :arg1-mixin
with guides using :align. For guide testing, do not use this as a model
for how to write a guide."
([] "rumguide")
([options len sexpr]
(let [docstring? (string? (nth sexpr 2))
[up-to-arguments args-and-after]
(split-with #(not (or (vector? %)
(and (list? %) (vector? (first %)))))
sexpr)
#_(println "rumguide: up-to-arguments:" up-to-arguments
"\nargs-and-after:" args-and-after)]
(if (empty? args-and-after)
{:list {:option-fn nil}}
(let [lt (nth sexpr (if docstring? 3 2))
lt? (= (str lt) "<")
beginning-guide [:element :element :newline]
beginning-guide (if docstring?
(concat beginning-guide [:element :newline])
beginning-guide)
middle-element-count
(- (count up-to-arguments) 2 (if docstring? 1 0) (if lt? 1 0))
middle-guide (if (pos? middle-element-count)
(if lt?
[:element :mark 1 :align 1 :element :newline]
[:mark 1 :align 1 :element :newline])
[])
#_(println "middle-element-count:" middle-element-count)
middle-guide (concat middle-guide
(repeat (dec middle-element-count)
[:align 1 :element :newline]))
end-element-count (count args-and-after)
end-guide [:element
(repeat (dec end-element-count) [:newline :element])]
guide (concat beginning-guide middle-guide end-guide)
; This could have been done so flatten wasn't necessary
; but it for testing it wasn't worth the re-work.
guide (flatten guide)
#_(println "rumguide: guide:" guide)]
{:guide guide, :next-inner {:list {:option-fn nil}}})))))
(defn rumguide-2
"Assumes that this is rum/defcs or something similar. Implement :arg1-mixin
with guides using :indent. This is probably the simplest and therefore the
best of them all. For guide testing, do not use this as a model for how
to write a guide."
([] "rumguide")
([options len sexpr]
(let [docstring? (string? (nth sexpr 2))
[up-to-arguments args-and-after]
(split-with #(not (or (vector? %)
(and (list? %) (vector? (first %)))))
sexpr)
#_(println "rumguide: up-to-arguments:" up-to-arguments
"\nargs-and-after:" args-and-after)]
(if (empty? args-and-after)
{:list {:option-fn nil}}
(let [lt (nth sexpr (if docstring? 3 2))
lt? (= (str lt) "<")
beginning-guide [:element :element :newline]
beginning-guide (if docstring?
(concat beginning-guide [:element :newline])
beginning-guide)
middle-element-count
(- (count up-to-arguments) 2 (if docstring? 1 0) (if lt? 1 0))
middle-guide (if (pos? middle-element-count)
(if lt?
[:element :indent 4 :element :newline]
[:indent 4 :element :newline])
[])
#_(println "middle-element-count:" middle-element-count)
middle-guide (concat middle-guide
(repeat (dec middle-element-count)
[:element :newline]))
end-element-count (count args-and-after)
end-guide [:indent-reset :element
(repeat (dec end-element-count) [:newline :element])]
guide (concat beginning-guide middle-guide end-guide)
; This could have been done so flatten wasn't necessary
; but it for testing it wasn't worth the re-work.
guide (flatten guide)
#_(println "rumguide: guide:" guide)]
{:guide guide, :next-inner {:list {:option-fn nil}}})))))
; Do this to use the above:
;
; (czprint cz8x1
; {:parse-string? true
; :fn-map {"rum/defcs" [:guided {:list {:option-fn rumguide}}]}})
(defn odrguide
"Justify O'Doyles Rules"
([] "odrguide")
([options len sexpr]
(when (= (first sexpr) :what)
(let [[vectors beyond] (split-with vector? (next sexpr))
max-width-vec (column-alignment (:max-variance (:justify (:pair
options)))
vectors)
alignment-vec (cumulative-alignment max-width-vec)
mark-guide
(vec (flatten
(mapv vector (repeat :mark-at) (range) alignment-vec)))
alignment-guide
(mapv vector (repeat :align) (range (count alignment-vec)))
vector-guide (into mark-guide
(flatten [(interleave (repeat :element)
alignment-guide)
:element-*]))
keyword-1 (first beyond)
[keyword-1-lists beyond] (split-with list? (next beyond))
keyword-2 (first beyond)
[keyword-2-lists beyond] (split-with list? (next beyond))
_ (dbg-s options
:guide
"odrguide alignment-vec:" alignment-vec
"mark-guide:" mark-guide
"alignment-guide:" alignment-guide
"vector-guide:" vector-guide
"keyword-1:" keyword-1
"keyword-1-lists:" keyword-1-lists
"keyword-2:" keyword-2
"keyword-2-lists:" keyword-2-lists)
guide
(cond-> (->
[:element :indent 2 :options
{:guide vector-guide,
:vector {:wrap-multi? true, :hang? true}} :group-begin]
(into (repeat (count vectors) :element))
(conj :group-end
:element-newline-best-group :options-reset
:options {:vector {:wrap-multi? true, :hang? true}}
:indent 1))
keyword-1 (conj :newline :element)
(not (empty? keyword-1-lists))
(-> (conj :indent 2 :group-begin)
(into (repeat (count keyword-1-lists) :element))
(conj :group-end :element-newline-best-group :indent 1))
keyword-2 (conj :newline :element)
(not (empty? keyword-2-lists))
(-> (conj :indent 2 :group-begin)
(into (repeat (count keyword-2-lists) :element))
(conj :group-end :element-newline-best-group)))]
(dbg-s options :guide "odrguide:" guide)
{:guide guide}))))
;;
;; Guide guide
;;
(def guide-arg-count
{:element 0,
:element-* 0,
:element-best 0,
:element-best-* 0,
:element-pair-group 0,
:element-pair-* 0,
:element-newline-best-group 0,
:element-newline-best-* 0,
:element-binding-group 0,
:element-binding-* 0,
:element-guide 1,
:element-binding-vec 0,
:newline 0,
:options 1,
:options-reset 0,
:indent 1,
:indent-reset 0,
:spaces 1,
:mark-at 2,
:mark-at-indent 2,
:mark 1,
:align 1,
:group-begin 0,
:group-end 0})
(def guide-insert
{:group-begin {:after [:indent 3]}, :group-end {:before [:indent 1]}})
(defn handle-args
"Figure out the arg-count for a guide."
[[guide running-arg-count] command]
(if (zero? running-arg-count)
(let [command-arg-count (or (guide-arg-count command) 0)
before (:before (guide-insert command))
after (:after (guide-insert command))]
[(cond-> guide
before (into before)
(empty? guide) (conj :element)
(not (empty? guide)) (conj :newline :element)
after (into after)) command-arg-count])
[(conj guide :element) (dec running-arg-count)]))
(defn guideguide
"Print out a guide"
([] "guideguide")
([options len sexpr]
(when (guide-arg-count (first sexpr))
{:guide (first (reduce handle-args [[] 0] sexpr))})))
;;
;; Real guide for defprotocol
;;
(declare signatureguide1)
(defn defprotocolguide
"Handle defprotocol with options."
([] "defprotocolguide")
([options len sexpr]
(when (= (first sexpr) 'defprotocol)
(let [third (nth sexpr 2 nil)
fourth (nth sexpr 3 nil)
fifth (nth sexpr 4 nil)
[docstring option option-value]
(cond (and (string? third) (keyword? fourth)) [third fourth fifth]
(string? third) [third nil nil]
(keyword? third) [nil third fourth]
:else [nil nil nil])
guide (cond-> [:element :element-best :newline]
docstring (conj :element :newline)
option (conj :element :element :newline)
:else (conj :element-newline-best-*))]
{:guide guide, :next-inner {:list {:option-fn nil}}}))))
(defn signatureguide1
"Handle defprotocol signatures with arities and doc string on their
own lines."
([] "signatureguide1")
([options len sexpr]
(let [vectors (filter vector? sexpr)
guide [:element :group-begin]
guide (apply conj guide (repeat (count vectors) :element))
guide (conj guide
:group-end :element-newline-best-group
:newline :element-*)]
{:guide guide})))
(defn defprotocolguide-s
"Handle defprotocol with options, uses extend."
([] "defprotocolguide")
([options len sexpr]
(when (= (first sexpr) 'defprotocol)
(let [remaining (nnext sexpr)
[docstring remaining] (if (string? (first remaining))
[(first remaining) (next remaining)]
[nil remaining])
pair-count (some identity
(map-indexed (fn [idx item] (when (list? item) idx))
remaining))
pair-count (if (= pair-count 0) nil pair-count)
guide (cond-> [:element :element-best :newline]
docstring (conj :element :newline)
pair-count (conj :group-begin)
pair-count (into (repeat pair-count :element))
pair-count (conj :group-end :element-pair-group :newline)
:else (conj :element-newline-extend-*))]
{:guide guide, :next-inner {:list {:option-fn nil}}}))))
;;
Temporary place to stash semantic3 to make collaboration easier
;;
;; -alt
;;
(def semantic3
version 0.1.6
Requires zprint 1.2.5
{:style-map
{:s1.0 {:doc "Set up community indentation",
:binding {:indent 0},
:list {:indent-arg 1},
:map {:indent 0},
:pair {:indent 0}},
:s1.1 {:doc "defn and fn",
:fn-map {"defn" [:force-nl-body {:style :rod-base}],
"defn-" "defn",
"fn" "defn"}},
:s1.2
{:doc "defprotocol, defrecord, deftype, extend-type, extend-protocol",
:fn-map {"defprotocol" [:arg1-extend-body
{:extend {:nl-count 2, :nl-separator? true},
:list {:option-fn defprotocolguide-s},
:fn-type-map {:fn :flow-body}}],
"defrecord" [:arg2-extend-body {:style :s1.2-base}],
"deftype" "defrecord",
"extend-type" [:arg1-extend-body {:style :s1.2-base}],
"extend-protocol" "extend-type"}},
:s1.2-base {:doc "Common code for extend things",
:extend {:nl-count 2, :nl-separator? true, :indent 0},
:fn-force-nl #{:fn},
:fn-type-map {:fn [:force-nl-body {:style :rod-base}]},
:next-inner {:next-inner {:fn-type-map {:fn nil}}}},
:s1.3 {:doc "defmethod",
:fn-map {"defmethod" [:guided-body
{:guide [:element :element-best
:element-best-first
:element-best-first :newline
:element-newline-best-*]}]}},
:s1.4 {:doc "if, if-not, handled now in s1.5"},
:s1.5
{:doc
"Don't format on single line: case cond-> cond->> when
while when-not when-first locking let binding loop for doseq
dotimes when-let if-let when-some if-some testing go-loop",
:binding {:force-nl? true},
:fn-force-nl #{:arg1-pair-body},
:fn-map {"when" :arg1-force-nl-body,
"when-not" "when",
"while" "when",
"locking" "when",
"testing" "when"}},
:s1.6 {:doc "=, not=, or, and, <, >, <=, >=",
:fn-force-nl #{:hang},
:fn-map {"<" "=", ">" "=", "<=" "=", ">=" "="}},
:s1.7 {:doc "->, ->>", :remove {:fn-force-nl #{:noarg1-body}}},
:s1.8 {:doc "try, catch, finally",
:fn-map {"try" :flow-body,
"catch" :arg2-force-nl-body,
"finally" :flow-body}},
:s1.9 {:doc "other stuff", :fn-map {"is" :force-nl-body}},
:s1.10 {:doc "cond do delay future comment alt! alt!! go thread",
:pair-fn {:hang? false},
:fn-map {"do" :flow-body,
"delay" "do",
"future" "do",
"comment" "do",
"go" "do",
"thread" "do"}},
:sall {:doc "version 0.1.4",
:style [:s1.0 :s1.1 :s1.2 :s1.3 :s1.4 :s1.5 :s1.6 :s1.7 :s1.8 :s1.9
:s1.10]}}})
| null | https://raw.githubusercontent.com/kkinnear/zprint/c5806b5c7a7455f626a0fd26a36367da94af09a6/src/zprint/guide.cljc | clojure |
Contains functions which can be called with {:option-fn <fn>} to produce
a "guide", which is, roughtly, a sequence comprised of keywords
which describe how to format an expression. A guide must be created
explicitly for the expression to be formatted.
For instance, this expression: (a b c d e f g) could be formatted
for this output:
(a b c
d e f
g)
by this guide:
[:element :element :element :newline :element :element :element :newline
:element]
There are a lot more keywords and other things which can be in a guide
than demonstrated above.
If you call a guide with partial because it has its own options map,
the "no-argument" arity must include the options map!
Since we have released this before, we will also allow it to be called
without rod-options
It is not just that the count is off.
Make interleave into interpose
Use this to use the above:
(czprint rod4
{:parse-string? true
:fn-map {"defn" [:guided {:list {:option-fn rodguide}}]}})
# Guide to replicate the existing output for {:style :moustache}
Use this to use the above:
{:parse-string? true
:fn-map {"m/app" [:guided {:list {:option-fn moustacheguide}}]}})
# Guide for the "are" function
If you call a guide with partial because it has its own options map,
the "no-argument" arity must include the options map!
Since we have released this before, we will also allow it to be called
without are-options
zloc-seq no comments
Get the lengths of the actual zloc values, not the sexpr
This makes strings too long, but it was
Do this to use the above:
(czprint are3
{:parse-string? true
:fn-map {"are" [:guided {:list {:option-fn areguide}}]}})
# Guide to justify the content of the vectors in a (:require ...)
A much simpler version of the require guide. This version doesn't require
uses the new variance-based justification capabilities.
the " no - argument " arity must include the first argument !
We can't justify things, fall back to this.
:require, but no other vectors or lists more deeply nested.
Do this to use the above:
(czprint jr1
{:parse-string? true
:fn-map {":require" [:none {:list {:option-fn jrequireguide}}]}})
# Guide to replicate the output of :arg1-mixin
This could have been done so flatten wasn't necessary
but it for testing it wasn't worth the re-work.
This could have been done so flatten wasn't necessary
but it for testing it wasn't worth the re-work.
This could have been done so flatten wasn't necessary
but it for testing it wasn't worth the re-work.
Do this to use the above:
(czprint cz8x1
{:parse-string? true
:fn-map {"rum/defcs" [:guided {:list {:option-fn rumguide}}]}})
Guide guide
Real guide for defprotocol
-alt
| (ns ^:no-doc zprint.guide
#?@(:cljs [[:require-macros
[zprint.macros :refer
[dbg dbg-s dbg-pr dbg-s-pr dbg-form dbg-print zfuture]]]])
(:require #?@(:clj [[zprint.macros :refer
[dbg-pr dbg-s-pr dbg dbg-s dbg-form dbg-print zfuture]]])
[zprint.util :refer [column-alignment cumulative-alignment]]))
# Guide for " rules of defn " , an alternative way to format defn expressions .
(defn rodguide
"Given a structure which starts with defn, create a guide for the
'rules of defn', an alternative approach to formatting a defn."
([] "rodguide")
([rod-options] "rodguide")
([options len sexpr] (rodguide {} options len sexpr))
([rod-options options len sexpr]
(when (or (= (str (first sexpr)) "defn") (= (str (first sexpr)) "defn-"))
(let [multi-arity-nl? (get rod-options :multi-arity-nl? true)
docstring? (string? (nth sexpr 2))
rest (nthnext sexpr (if docstring? 3 2))
multi-arity? (not (vector? (first rest)))
rest (if multi-arity? rest (next rest))
#_#_zfn-map (:zfn-map options)
#_#_rest-count ((:zcount zfn-map) (:zloc options))
rest-guide (repeat (dec #_rest-count (count rest)) :element)
rest-guide
(into []
(if (and multi-arity? multi-arity-nl?)
(interleave rest-guide (repeat :newline) (repeat :newline))
(interleave rest-guide (repeat :newline))))
rest-guide (conj rest-guide :element)
guide (cond-> [:element :element]
docstring? (conj :newline :element :newline)
(not multi-arity?) (conj :element :newline)
(and multi-arity? (not docstring?)) (conj :newline)
:rest (into rest-guide))
option-map {:guide guide, :next-inner {:list {:option-fn nil}}}]
(if multi-arity?
(assoc option-map
:next-inner {:list {:option-fn nil},
:fn-map {:vector :force-nl},
:next-inner-restore [[:fn-map :vector]]})
option-map)))))
(defn constant-or-vector?
"Return true if a constant or vector."
[element]
#_(println "c-or-v?" element)
(or (number? element)
(string? element)
(vector? element)
(keyword? element)
(= element true)
(= element false)))
(defn count-constants
[[constant-count possible-constant?] element]
(if possible-constant?
(if (constant-or-vector? element)
[(inc constant-count) (not possible-constant?)]
(reduced [constant-count possible-constant?]))
[constant-count (not possible-constant?)]))
(defn moustacheguide
"Reimplement :style :moustache with guides."
([] "moustacheguide")
([options len sexpr]
First , find the pairs .
(let [rev-sexpr (reverse sexpr)
[constant-count _] (reduce count-constants [0 false] rev-sexpr)
pair-count (* constant-count 2)
pair-guide (into [] (repeat pair-count :element))
pair-guide (conj pair-guide :group-end)
pair-guide (conj pair-guide :element-pair-group)
non-pair-count (- (count sexpr) pair-count)
non-pair-guide (repeat non-pair-count :element)
non-pair-guide (into [] (interpose :newline non-pair-guide))
guide (conj non-pair-guide :newline :group-begin)
guide (concat guide pair-guide)]
(dbg-s options
:guide
"moustacheguide: sexpr" sexpr
"pair-count:" pair-count
"output:" guide)
{:guide guide,
:pair {:justify? true},
:next-inner {:pair {:justify? false}, :list {:option-fn nil}}})))
( czprint
(defn add-double-quotes
"Given two arguments, an s-expression and a string, if the s-expression
is actually a string, add a double quote on to the beginning and end of
the string."
[sexpr s]
(if (string? sexpr) (str "\"" s "\"") s))
(defn areguide
"Format are test functions. Call it with (partial {} areguide), where
the map can be {:justify? true} to justify the various rows. It will
use {:pair {:justify {:max-variance n}}} for the variance, but you can
give it a variance to use with {:max-variance n} in the map which is
its first argument."
([] "areguide")
([are-options] "areguide")
([options len sexpr] (areguide {} options len sexpr))
([are-options options len sexpr]
(let [justify? (:justify? are-options)
max-variance (when justify?
(or (:max-variance are-options)
(:max-variance (:justify (:pair options)))))
caller-options ((:caller options) options)
current-indent (or (:indent-arg caller-options)
(:indent caller-options))
are-indent (:indent are-options)
table-indent (+ current-indent (or are-indent current-indent))
arg-vec-len (count (second sexpr))
test-len (- (count sexpr) 3)
rows (/ test-len arg-vec-len)
excess-tests (- test-len (* rows arg-vec-len))
alignment-vec
(when justify?
zfn-map (:zfn-map options)
zloc-seq-nc
((:zmap-no-comment zfn-map) identity (:zloc options))
args (drop 3 zloc-seq-nc)
arg-strs (mapv (:zstring zfn-map) args)
#_(prn "early arg-strs:" arg-strs)
presumably added for some reason ? Issue # 212
arg - strs ( mapv add - double - quotes ( drop 3 sexpr ) arg - strs )
#_(prn "later arg-strs:" arg-strs)
seq-of-seqs (partition arg-vec-len arg-vec-len [] arg-strs)
max-width-vec (column-alignment max-variance
seq-of-seqs
nil
:no-string-adj?)
alignment-vec (cumulative-alignment max-width-vec)]
#_(prn "max-width-vec:" max-width-vec
"alignment-vec:" alignment-vec)
alignment-vec))
mark-guide
(vec (flatten
(mapv vector (repeat :mark-at-indent) (range) alignment-vec)))
new-row-guide (cond-> [:element :indent table-indent]
(not (empty? alignment-vec))
(into (interleave (repeat :align)
(range (count alignment-vec))
(repeat :element)))
(empty? alignment-vec) (into (repeat (dec arg-vec-len)
:element))
true (conj :indent-reset :newline))
multi-row-guide (apply concat (repeat rows new-row-guide))
guide (cond-> (-> [:element :element :element-best :newline]
(into mark-guide)
(into multi-row-guide))
(pos? excess-tests) (conj :element-*))]
#_(prn "guide:" guide)
{:guide guide, :next-inner {:list {:option-fn nil}}})))
(defn areguide-basic
"Format are test functions, no justification."
([] "areguide")
([options len sexpr]
(let [arg-vec-len (count (second sexpr))
beginning (take 3 sexpr)
test-len (- (count sexpr) 3)
rows (/ test-len arg-vec-len)
excess-tests (- test-len (* rows arg-vec-len))
single-row (into [:newline] (repeat arg-vec-len :element))
row-guide (apply concat (repeat rows single-row))
guide (cond-> (-> [:element :element :element-best]
(into row-guide))
(pos? excess-tests) (conj :newline :element-*))]
{:guide guide, :next-inner {:list {:option-fn nil}}})))
use of the call - stack , and has only one option - fn instead of two . It also
(defn jrequireguide
"Justify the first things in a variety of settings. The first argument
is the things to recognize, and can be :require, :require-macros, or
:import. :require and :require-macros are handled the same, and :import
is handled differently since it has the values all in the same expression.
Handles sequences with lists or vectors."
([] "jrequireguide")
If you call a guide with partial because it has its a required first
([keyword] "jrequireguide")
([keyword options len sexpr]
(when (= (first sexpr) keyword)
(let [vectors+lists (filter #(or (vector? %) (list? %)) sexpr)]
(when (not (empty? vectors+lists))
(let [max-width-vec (column-alignment (:max-variance
(:justify (:pair options)))
vectors+lists
only do the first column
1)
_ (dbg-s options
:guide
"jrequireguide max-width-vec:"
max-width-vec)
max-first (first max-width-vec)
element-guide :element-pair-*
vector-guide (if max-first
(if (= (first sexpr) :import)
[:mark-at 0 (inc max-first) :element :align 0
:indent-here #_(+ max-first 2) :element-*]
[:mark-at 0 (inc max-first) :element :align 0
element-guide])
[:element element-guide])]
Do this for all of the first level vectors and lists below the
{:next-inner {:vector {:option-fn (fn [_ _ _] {:guide vector-guide}),
:wrap-multi? true,
:hang? true},
:list {:option-fn (fn [_ _ _] {:guide vector-guide}),
:wrap-multi? true,
:hang? true},
:pair {:justify? true},
:next-inner-restore
[[:vector :option-fn] [:vector :wrap-multi?]
[:vector :hang?] [:list :option-fn]
[:list :wrap-multi?] [:list :hang?]
[:pair :justify?]]}}))))))
(defn rumguide
"Assumes that this is rum/defcs or something similar. Implement :arg1-mixin
with guides using :spaces. For guide testing, do not use this as a model
for how to write a guide."
([] "rumguide")
([options len sexpr]
(let [docstring? (string? (nth sexpr 2))
[up-to-arguments args-and-after]
(split-with #(not (or (vector? %)
(and (list? %) (vector? (first %)))))
sexpr)
#_(println "rumguide: up-to-arguments:" up-to-arguments
"\nargs-and-after:" args-and-after)]
(if (empty? args-and-after)
{:list {:option-fn nil}}
(let [lt (nth sexpr (if docstring? 3 2))
lt? (= (str lt) "<")
mixin-indent (if lt? 2 1)
beginning-guide [:element :element :newline]
beginning-guide (if docstring?
(concat beginning-guide [:element :newline])
beginning-guide)
middle-element-count
(- (count up-to-arguments) 2 (if docstring? 1 0) (if lt? 1 0))
middle-guide
(if (pos? middle-element-count)
(if lt? [:element :element :newline] [:element :newline])
[])
#_(println "middle-element-count:" middle-element-count)
middle-guide (concat middle-guide
(repeat (dec middle-element-count)
[:spaces mixin-indent :element
:newline]))
end-element-count (count args-and-after)
end-guide [:element
(repeat (dec end-element-count) [:newline :element])]
guide (concat beginning-guide middle-guide end-guide)
guide (flatten guide)
#_(println "rumguide: guide:" guide)]
{:guide guide, :next-inner {:list {:option-fn nil}}})))))
(defn rumguide-1
"Assumes that this is rum/defcs or something similar. Implement :arg1-mixin
with guides using :align. For guide testing, do not use this as a model
for how to write a guide."
([] "rumguide")
([options len sexpr]
(let [docstring? (string? (nth sexpr 2))
[up-to-arguments args-and-after]
(split-with #(not (or (vector? %)
(and (list? %) (vector? (first %)))))
sexpr)
#_(println "rumguide: up-to-arguments:" up-to-arguments
"\nargs-and-after:" args-and-after)]
(if (empty? args-and-after)
{:list {:option-fn nil}}
(let [lt (nth sexpr (if docstring? 3 2))
lt? (= (str lt) "<")
beginning-guide [:element :element :newline]
beginning-guide (if docstring?
(concat beginning-guide [:element :newline])
beginning-guide)
middle-element-count
(- (count up-to-arguments) 2 (if docstring? 1 0) (if lt? 1 0))
middle-guide (if (pos? middle-element-count)
(if lt?
[:element :mark 1 :align 1 :element :newline]
[:mark 1 :align 1 :element :newline])
[])
#_(println "middle-element-count:" middle-element-count)
middle-guide (concat middle-guide
(repeat (dec middle-element-count)
[:align 1 :element :newline]))
end-element-count (count args-and-after)
end-guide [:element
(repeat (dec end-element-count) [:newline :element])]
guide (concat beginning-guide middle-guide end-guide)
guide (flatten guide)
#_(println "rumguide: guide:" guide)]
{:guide guide, :next-inner {:list {:option-fn nil}}})))))
(defn rumguide-2
"Assumes that this is rum/defcs or something similar. Implement :arg1-mixin
with guides using :indent. This is probably the simplest and therefore the
best of them all. For guide testing, do not use this as a model for how
to write a guide."
([] "rumguide")
([options len sexpr]
(let [docstring? (string? (nth sexpr 2))
[up-to-arguments args-and-after]
(split-with #(not (or (vector? %)
(and (list? %) (vector? (first %)))))
sexpr)
#_(println "rumguide: up-to-arguments:" up-to-arguments
"\nargs-and-after:" args-and-after)]
(if (empty? args-and-after)
{:list {:option-fn nil}}
(let [lt (nth sexpr (if docstring? 3 2))
lt? (= (str lt) "<")
beginning-guide [:element :element :newline]
beginning-guide (if docstring?
(concat beginning-guide [:element :newline])
beginning-guide)
middle-element-count
(- (count up-to-arguments) 2 (if docstring? 1 0) (if lt? 1 0))
middle-guide (if (pos? middle-element-count)
(if lt?
[:element :indent 4 :element :newline]
[:indent 4 :element :newline])
[])
#_(println "middle-element-count:" middle-element-count)
middle-guide (concat middle-guide
(repeat (dec middle-element-count)
[:element :newline]))
end-element-count (count args-and-after)
end-guide [:indent-reset :element
(repeat (dec end-element-count) [:newline :element])]
guide (concat beginning-guide middle-guide end-guide)
guide (flatten guide)
#_(println "rumguide: guide:" guide)]
{:guide guide, :next-inner {:list {:option-fn nil}}})))))
(defn odrguide
"Justify O'Doyles Rules"
([] "odrguide")
([options len sexpr]
(when (= (first sexpr) :what)
(let [[vectors beyond] (split-with vector? (next sexpr))
max-width-vec (column-alignment (:max-variance (:justify (:pair
options)))
vectors)
alignment-vec (cumulative-alignment max-width-vec)
mark-guide
(vec (flatten
(mapv vector (repeat :mark-at) (range) alignment-vec)))
alignment-guide
(mapv vector (repeat :align) (range (count alignment-vec)))
vector-guide (into mark-guide
(flatten [(interleave (repeat :element)
alignment-guide)
:element-*]))
keyword-1 (first beyond)
[keyword-1-lists beyond] (split-with list? (next beyond))
keyword-2 (first beyond)
[keyword-2-lists beyond] (split-with list? (next beyond))
_ (dbg-s options
:guide
"odrguide alignment-vec:" alignment-vec
"mark-guide:" mark-guide
"alignment-guide:" alignment-guide
"vector-guide:" vector-guide
"keyword-1:" keyword-1
"keyword-1-lists:" keyword-1-lists
"keyword-2:" keyword-2
"keyword-2-lists:" keyword-2-lists)
guide
(cond-> (->
[:element :indent 2 :options
{:guide vector-guide,
:vector {:wrap-multi? true, :hang? true}} :group-begin]
(into (repeat (count vectors) :element))
(conj :group-end
:element-newline-best-group :options-reset
:options {:vector {:wrap-multi? true, :hang? true}}
:indent 1))
keyword-1 (conj :newline :element)
(not (empty? keyword-1-lists))
(-> (conj :indent 2 :group-begin)
(into (repeat (count keyword-1-lists) :element))
(conj :group-end :element-newline-best-group :indent 1))
keyword-2 (conj :newline :element)
(not (empty? keyword-2-lists))
(-> (conj :indent 2 :group-begin)
(into (repeat (count keyword-2-lists) :element))
(conj :group-end :element-newline-best-group)))]
(dbg-s options :guide "odrguide:" guide)
{:guide guide}))))
(def guide-arg-count
{:element 0,
:element-* 0,
:element-best 0,
:element-best-* 0,
:element-pair-group 0,
:element-pair-* 0,
:element-newline-best-group 0,
:element-newline-best-* 0,
:element-binding-group 0,
:element-binding-* 0,
:element-guide 1,
:element-binding-vec 0,
:newline 0,
:options 1,
:options-reset 0,
:indent 1,
:indent-reset 0,
:spaces 1,
:mark-at 2,
:mark-at-indent 2,
:mark 1,
:align 1,
:group-begin 0,
:group-end 0})
(def guide-insert
{:group-begin {:after [:indent 3]}, :group-end {:before [:indent 1]}})
(defn handle-args
"Figure out the arg-count for a guide."
[[guide running-arg-count] command]
(if (zero? running-arg-count)
(let [command-arg-count (or (guide-arg-count command) 0)
before (:before (guide-insert command))
after (:after (guide-insert command))]
[(cond-> guide
before (into before)
(empty? guide) (conj :element)
(not (empty? guide)) (conj :newline :element)
after (into after)) command-arg-count])
[(conj guide :element) (dec running-arg-count)]))
(defn guideguide
"Print out a guide"
([] "guideguide")
([options len sexpr]
(when (guide-arg-count (first sexpr))
{:guide (first (reduce handle-args [[] 0] sexpr))})))
(declare signatureguide1)
(defn defprotocolguide
"Handle defprotocol with options."
([] "defprotocolguide")
([options len sexpr]
(when (= (first sexpr) 'defprotocol)
(let [third (nth sexpr 2 nil)
fourth (nth sexpr 3 nil)
fifth (nth sexpr 4 nil)
[docstring option option-value]
(cond (and (string? third) (keyword? fourth)) [third fourth fifth]
(string? third) [third nil nil]
(keyword? third) [nil third fourth]
:else [nil nil nil])
guide (cond-> [:element :element-best :newline]
docstring (conj :element :newline)
option (conj :element :element :newline)
:else (conj :element-newline-best-*))]
{:guide guide, :next-inner {:list {:option-fn nil}}}))))
(defn signatureguide1
"Handle defprotocol signatures with arities and doc string on their
own lines."
([] "signatureguide1")
([options len sexpr]
(let [vectors (filter vector? sexpr)
guide [:element :group-begin]
guide (apply conj guide (repeat (count vectors) :element))
guide (conj guide
:group-end :element-newline-best-group
:newline :element-*)]
{:guide guide})))
(defn defprotocolguide-s
"Handle defprotocol with options, uses extend."
([] "defprotocolguide")
([options len sexpr]
(when (= (first sexpr) 'defprotocol)
(let [remaining (nnext sexpr)
[docstring remaining] (if (string? (first remaining))
[(first remaining) (next remaining)]
[nil remaining])
pair-count (some identity
(map-indexed (fn [idx item] (when (list? item) idx))
remaining))
pair-count (if (= pair-count 0) nil pair-count)
guide (cond-> [:element :element-best :newline]
docstring (conj :element :newline)
pair-count (conj :group-begin)
pair-count (into (repeat pair-count :element))
pair-count (conj :group-end :element-pair-group :newline)
:else (conj :element-newline-extend-*))]
{:guide guide, :next-inner {:list {:option-fn nil}}}))))
Temporary place to stash semantic3 to make collaboration easier
(def semantic3
version 0.1.6
Requires zprint 1.2.5
{:style-map
{:s1.0 {:doc "Set up community indentation",
:binding {:indent 0},
:list {:indent-arg 1},
:map {:indent 0},
:pair {:indent 0}},
:s1.1 {:doc "defn and fn",
:fn-map {"defn" [:force-nl-body {:style :rod-base}],
"defn-" "defn",
"fn" "defn"}},
:s1.2
{:doc "defprotocol, defrecord, deftype, extend-type, extend-protocol",
:fn-map {"defprotocol" [:arg1-extend-body
{:extend {:nl-count 2, :nl-separator? true},
:list {:option-fn defprotocolguide-s},
:fn-type-map {:fn :flow-body}}],
"defrecord" [:arg2-extend-body {:style :s1.2-base}],
"deftype" "defrecord",
"extend-type" [:arg1-extend-body {:style :s1.2-base}],
"extend-protocol" "extend-type"}},
:s1.2-base {:doc "Common code for extend things",
:extend {:nl-count 2, :nl-separator? true, :indent 0},
:fn-force-nl #{:fn},
:fn-type-map {:fn [:force-nl-body {:style :rod-base}]},
:next-inner {:next-inner {:fn-type-map {:fn nil}}}},
:s1.3 {:doc "defmethod",
:fn-map {"defmethod" [:guided-body
{:guide [:element :element-best
:element-best-first
:element-best-first :newline
:element-newline-best-*]}]}},
:s1.4 {:doc "if, if-not, handled now in s1.5"},
:s1.5
{:doc
"Don't format on single line: case cond-> cond->> when
while when-not when-first locking let binding loop for doseq
dotimes when-let if-let when-some if-some testing go-loop",
:binding {:force-nl? true},
:fn-force-nl #{:arg1-pair-body},
:fn-map {"when" :arg1-force-nl-body,
"when-not" "when",
"while" "when",
"locking" "when",
"testing" "when"}},
:s1.6 {:doc "=, not=, or, and, <, >, <=, >=",
:fn-force-nl #{:hang},
:fn-map {"<" "=", ">" "=", "<=" "=", ">=" "="}},
:s1.7 {:doc "->, ->>", :remove {:fn-force-nl #{:noarg1-body}}},
:s1.8 {:doc "try, catch, finally",
:fn-map {"try" :flow-body,
"catch" :arg2-force-nl-body,
"finally" :flow-body}},
:s1.9 {:doc "other stuff", :fn-map {"is" :force-nl-body}},
:s1.10 {:doc "cond do delay future comment alt! alt!! go thread",
:pair-fn {:hang? false},
:fn-map {"do" :flow-body,
"delay" "do",
"future" "do",
"comment" "do",
"go" "do",
"thread" "do"}},
:sall {:doc "version 0.1.4",
:style [:s1.0 :s1.1 :s1.2 :s1.3 :s1.4 :s1.5 :s1.6 :s1.7 :s1.8 :s1.9
:s1.10]}}})
|
4657900a8b913731e87d0280785dc1ab9e8a28b27af358ca17576ad90c1798d6 | lambdamikel/DLMAPS | edge-management.lisp | ;;; -*- Mode: LISP; Syntax: Common-Lisp; Package: PROVER -*-
(in-package :PROVER)
;;;
;;;
;;;
(timed-defmethod mark-deleted :after ((abox abox) (edge abox-edge))
t)
(timed-defmethod mark-deleted :after ((abox abox1) (edge abox-edge))
(with-slots (all-edges) abox
(if (not *use-avl-trees-for-abox1-p*)
(setf all-edges (delete edge all-edges))
(delete-from-avl-tree edge all-edges :key #'id))))
;;;
;;;
;;;
(timed-defmethod delete-edge ((abox abox) (edge abox-edge) &rest args)
(declare (ignorable args))
(call-next-method))
(timed-defmethod delete-edge ((abox abox1) (edge abox-edge) &rest args)
(declare (ignorable args))
(if (old-p edge)
(call-next-method)
(let ((from (from edge))
(to (to edge)))
wird sonst !
(setf (slot-value from 'successors) (delete to (slot-value from 'successors)))
(setf (slot-value to 'predecessors) (delete from (slot-value to 'predecessors)))
(setf (slot-value from 'outgoing) (delete edge (slot-value from 'outgoing)))
(setf (slot-value to 'incoming) (delete edge (slot-value to 'incoming))))))
(timed-defmethod delete-edge :after ((abox abox) (edge abox-edge) &rest args)
(declare (ignorable args))
(mark-deleted abox edge))
;;;
;;;
;;;
(defmethod get-state-vector ((edge abox-edge))
(with-slots (old-p
active-p
deleted-p
multiplicity
inverse-multiplicity) edge
active-p
deleted-p
multiplicity
inverse-multiplicity)))
(defmethod set-state-vector ((edge abox-edge) state &optional maintain-index-structures-p)
(declare (ignorable maintain-index-structures-p))
(with-slots (old-p
active-p
deleted-p
multiplicity
inverse-multiplicity) edge
( pop state )
active-p (pop state)
deleted-p (pop state)
multiplicity (pop state)
inverse-multiplicity (pop state))))
| null | https://raw.githubusercontent.com/lambdamikel/DLMAPS/7f8dbb9432069d41e6a7d9c13dc5b25602ad35dc/src/prover/edge-management.lisp | lisp | -*- Mode: LISP; Syntax: Common-Lisp; Package: PROVER -*-
|
(in-package :PROVER)
(timed-defmethod mark-deleted :after ((abox abox) (edge abox-edge))
t)
(timed-defmethod mark-deleted :after ((abox abox1) (edge abox-edge))
(with-slots (all-edges) abox
(if (not *use-avl-trees-for-abox1-p*)
(setf all-edges (delete edge all-edges))
(delete-from-avl-tree edge all-edges :key #'id))))
(timed-defmethod delete-edge ((abox abox) (edge abox-edge) &rest args)
(declare (ignorable args))
(call-next-method))
(timed-defmethod delete-edge ((abox abox1) (edge abox-edge) &rest args)
(declare (ignorable args))
(if (old-p edge)
(call-next-method)
(let ((from (from edge))
(to (to edge)))
wird sonst !
(setf (slot-value from 'successors) (delete to (slot-value from 'successors)))
(setf (slot-value to 'predecessors) (delete from (slot-value to 'predecessors)))
(setf (slot-value from 'outgoing) (delete edge (slot-value from 'outgoing)))
(setf (slot-value to 'incoming) (delete edge (slot-value to 'incoming))))))
(timed-defmethod delete-edge :after ((abox abox) (edge abox-edge) &rest args)
(declare (ignorable args))
(mark-deleted abox edge))
(defmethod get-state-vector ((edge abox-edge))
(with-slots (old-p
active-p
deleted-p
multiplicity
inverse-multiplicity) edge
active-p
deleted-p
multiplicity
inverse-multiplicity)))
(defmethod set-state-vector ((edge abox-edge) state &optional maintain-index-structures-p)
(declare (ignorable maintain-index-structures-p))
(with-slots (old-p
active-p
deleted-p
multiplicity
inverse-multiplicity) edge
( pop state )
active-p (pop state)
deleted-p (pop state)
multiplicity (pop state)
inverse-multiplicity (pop state))))
|
6ca2291a253593096231c17c8c6ec108ff09462972edab95738e5afa68ad6832 | input-output-hk/plutus | Substitute.hs | -- editorconfig-checker-disable-file
# LANGUAGE FlexibleContexts #
# LANGUAGE ViewPatterns #
-- | Implements naive substitution functions for replacing type and term variables.
module PlutusIR.Transform.Substitute (
substVar
, substTyVar
, typeSubstTyNames
, termSubstNames
, termSubstTyNames
, bindingSubstNames
, bindingSubstTyNames
) where
import PlutusIR
import PlutusCore.Subst (substTyVar, typeSubstTyNames)
import Control.Lens
import Data.Maybe
Needs to be different from the PLC version since we have different Terms
-- | Replace a variable using the given function.
substVar :: (name -> Maybe (Term tyname name uni fun a)) -> Term tyname name uni fun a -> Maybe (Term tyname name uni fun a)
substVar nameF (Var _ n) = nameF n
substVar _ _ = Nothing
-- | Naively substitute names using the given functions (i.e. do not substitute binders).
termSubstNames :: (name -> Maybe (Term tyname name uni fun a)) -> Term tyname name uni fun a -> Term tyname name uni fun a
termSubstNames nameF = transformOf termSubterms (\x -> fromMaybe x (substVar nameF x))
-- | Naively substitute type names using the given functions (i.e. do not substitute binders).
termSubstTyNames :: (tyname -> Maybe (Type tyname uni a)) -> Term tyname name uni fun a -> Term tyname name uni fun a
termSubstTyNames tynameF = over termSubterms (termSubstTyNames tynameF) . over termSubtypes (typeSubstTyNames tynameF)
-- | Naively substitute names using the given functions (i.e. do not substitute binders).
bindingSubstNames :: (name -> Maybe (Term tyname name uni fun a)) -> Binding tyname name uni fun a -> Binding tyname name uni fun a
bindingSubstNames nameF = over bindingSubterms (termSubstNames nameF)
-- | Naively substitute type names using the given functions (i.e. do not substitute binders).
bindingSubstTyNames :: (tyname -> Maybe (Type tyname uni a)) -> Binding tyname name uni fun a -> Binding tyname name uni fun a
bindingSubstTyNames tynameF = over bindingSubterms (termSubstTyNames tynameF) . over bindingSubtypes (typeSubstTyNames tynameF)
| null | https://raw.githubusercontent.com/input-output-hk/plutus/c8d4364d0e639fef4d5b93f7d6c0912d992b54f9/plutus-core/plutus-ir/src/PlutusIR/Transform/Substitute.hs | haskell | editorconfig-checker-disable-file
| Implements naive substitution functions for replacing type and term variables.
| Replace a variable using the given function.
| Naively substitute names using the given functions (i.e. do not substitute binders).
| Naively substitute type names using the given functions (i.e. do not substitute binders).
| Naively substitute names using the given functions (i.e. do not substitute binders).
| Naively substitute type names using the given functions (i.e. do not substitute binders). | # LANGUAGE FlexibleContexts #
# LANGUAGE ViewPatterns #
module PlutusIR.Transform.Substitute (
substVar
, substTyVar
, typeSubstTyNames
, termSubstNames
, termSubstTyNames
, bindingSubstNames
, bindingSubstTyNames
) where
import PlutusIR
import PlutusCore.Subst (substTyVar, typeSubstTyNames)
import Control.Lens
import Data.Maybe
Needs to be different from the PLC version since we have different Terms
substVar :: (name -> Maybe (Term tyname name uni fun a)) -> Term tyname name uni fun a -> Maybe (Term tyname name uni fun a)
substVar nameF (Var _ n) = nameF n
substVar _ _ = Nothing
termSubstNames :: (name -> Maybe (Term tyname name uni fun a)) -> Term tyname name uni fun a -> Term tyname name uni fun a
termSubstNames nameF = transformOf termSubterms (\x -> fromMaybe x (substVar nameF x))
termSubstTyNames :: (tyname -> Maybe (Type tyname uni a)) -> Term tyname name uni fun a -> Term tyname name uni fun a
termSubstTyNames tynameF = over termSubterms (termSubstTyNames tynameF) . over termSubtypes (typeSubstTyNames tynameF)
bindingSubstNames :: (name -> Maybe (Term tyname name uni fun a)) -> Binding tyname name uni fun a -> Binding tyname name uni fun a
bindingSubstNames nameF = over bindingSubterms (termSubstNames nameF)
bindingSubstTyNames :: (tyname -> Maybe (Type tyname uni a)) -> Binding tyname name uni fun a -> Binding tyname name uni fun a
bindingSubstTyNames tynameF = over bindingSubterms (termSubstTyNames tynameF) . over bindingSubtypes (typeSubstTyNames tynameF)
|
25ec910d650797543430541d99ec3b98d3cb0c5e9c1eba7773306d43b80bf916 | abdulapopoola/SICPBook | 5.34.scm | (load "compiler.scm")
(define code (compile
'(define (factorial n)
(define (iter product counter)
(if (> counter n)
product
(iter (* counter product)
(+ counter 1))))
(iter 1 1))
'val
'next))
(pretty-print code)
;; OUTPUT BELOW
(env)
(val)
((assign val (op make-compiled-procedure) (label entry1) (reg env))
(goto (label after-lambda2))
entry1
(assign env (op compiled-procedure-env) (reg proc))
(assign env (op extend-environment) (const (n)) (reg argl) (reg env))
(assign val (op make-compiled-procedure) (label entry3) (reg env))
(goto (label after-lambda4))
entry3
(assign env (op compiled-procedure-env) (reg proc))
(assign env (op extend-environment) (const (product counter)) (reg argl) (reg env))
(save continue)
(save env)
(assign proc (op lookup-variable-value) (const >) (reg env))
(assign val (op lookup-variable-value) (const n) (reg env))
(assign argl (op list) (reg val))
(assign val (op lookup-variable-value) (const counter) (reg env))
(assign argl (op cons) (reg val) (reg argl))
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-branch8))
compiled-branch9
(assign continue (label after-call10))
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
primitive-branch8
(assign val (op apply-primitive-procedure) (reg proc) (reg argl))
after-call10
(restore env)
(restore continue)
(test (op false?) (reg val))
(branch (label false-branch6))
true-branch5
(assign val (op lookup-variable-value) (const product) (reg env))
(goto (reg continue))
false-branch6
(assign proc (op lookup-variable-value) (const iter) (reg env))
(save continue)
(save proc)
(save env)
(assign proc (op lookup-variable-value) (const +) (reg env))
(assign val (const 1)) (assign argl (op list) (reg val))
(assign val (op lookup-variable-value) (const counter) (reg env))
(assign argl (op cons) (reg val) (reg argl))
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-branch14))
compiled-branch15
(assign continue (label after-call16))
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
primitive-branch14
(assign val (op apply-primitive-procedure) (reg proc) (reg argl))
after-call16
(assign argl (op list) (reg val))
(restore env)
(save argl)
(assign proc (op lookup-variable-value) (const *) (reg env))
(assign val (op lookup-variable-value) (const product) (reg env))
(assign argl (op list) (reg val))
(assign val (op lookup-variable-value) (const counter) (reg env))
(assign argl (op cons) (reg val) (reg argl))
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-branch11))
compiled-branch12
(assign continue (label after-call13))
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
primitive-branch11
(assign val (op apply-primitive-procedure) (reg proc) (reg argl))
after-call13
(restore argl)
(assign argl (op cons) (reg val) (reg argl))
(restore proc)
(restore continue)
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-branch17))
compiled-branch18
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
primitive-branch17
(assign val (op apply-primitive-procedure) (reg proc) (reg argl))
(goto (reg continue))
after-call19
after-if7
after-lambda4
(perform (op define-variable!) (const iter) (reg val) (reg env))
(assign val (const ok))
(assign proc (op lookup-variable-value) (const iter) (reg env))
(assign val (const 1))
(assign argl (op list) (reg val))
(assign val (const 1))
(assign argl (op cons) (reg val) (reg argl))
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-branch20))
compiled-branch21
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
primitive-branch20
(assign val (op apply-primitive-procedure) (reg proc) (reg argl))
(goto (reg continue))
after-call22
after-lambda2
(perform (op define-variable!) (const factorial) (reg val) (reg env))
(assign val (const ok))) | null | https://raw.githubusercontent.com/abdulapopoola/SICPBook/c8a0228ebf66d9c1ddc5ef1fcc1d05d8684f090a/Chapter%205/5.5/5.34.scm | scheme | OUTPUT BELOW | (load "compiler.scm")
(define code (compile
'(define (factorial n)
(define (iter product counter)
(if (> counter n)
product
(iter (* counter product)
(+ counter 1))))
(iter 1 1))
'val
'next))
(pretty-print code)
(env)
(val)
((assign val (op make-compiled-procedure) (label entry1) (reg env))
(goto (label after-lambda2))
entry1
(assign env (op compiled-procedure-env) (reg proc))
(assign env (op extend-environment) (const (n)) (reg argl) (reg env))
(assign val (op make-compiled-procedure) (label entry3) (reg env))
(goto (label after-lambda4))
entry3
(assign env (op compiled-procedure-env) (reg proc))
(assign env (op extend-environment) (const (product counter)) (reg argl) (reg env))
(save continue)
(save env)
(assign proc (op lookup-variable-value) (const >) (reg env))
(assign val (op lookup-variable-value) (const n) (reg env))
(assign argl (op list) (reg val))
(assign val (op lookup-variable-value) (const counter) (reg env))
(assign argl (op cons) (reg val) (reg argl))
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-branch8))
compiled-branch9
(assign continue (label after-call10))
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
primitive-branch8
(assign val (op apply-primitive-procedure) (reg proc) (reg argl))
after-call10
(restore env)
(restore continue)
(test (op false?) (reg val))
(branch (label false-branch6))
true-branch5
(assign val (op lookup-variable-value) (const product) (reg env))
(goto (reg continue))
false-branch6
(assign proc (op lookup-variable-value) (const iter) (reg env))
(save continue)
(save proc)
(save env)
(assign proc (op lookup-variable-value) (const +) (reg env))
(assign val (const 1)) (assign argl (op list) (reg val))
(assign val (op lookup-variable-value) (const counter) (reg env))
(assign argl (op cons) (reg val) (reg argl))
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-branch14))
compiled-branch15
(assign continue (label after-call16))
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
primitive-branch14
(assign val (op apply-primitive-procedure) (reg proc) (reg argl))
after-call16
(assign argl (op list) (reg val))
(restore env)
(save argl)
(assign proc (op lookup-variable-value) (const *) (reg env))
(assign val (op lookup-variable-value) (const product) (reg env))
(assign argl (op list) (reg val))
(assign val (op lookup-variable-value) (const counter) (reg env))
(assign argl (op cons) (reg val) (reg argl))
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-branch11))
compiled-branch12
(assign continue (label after-call13))
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
primitive-branch11
(assign val (op apply-primitive-procedure) (reg proc) (reg argl))
after-call13
(restore argl)
(assign argl (op cons) (reg val) (reg argl))
(restore proc)
(restore continue)
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-branch17))
compiled-branch18
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
primitive-branch17
(assign val (op apply-primitive-procedure) (reg proc) (reg argl))
(goto (reg continue))
after-call19
after-if7
after-lambda4
(perform (op define-variable!) (const iter) (reg val) (reg env))
(assign val (const ok))
(assign proc (op lookup-variable-value) (const iter) (reg env))
(assign val (const 1))
(assign argl (op list) (reg val))
(assign val (const 1))
(assign argl (op cons) (reg val) (reg argl))
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-branch20))
compiled-branch21
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
primitive-branch20
(assign val (op apply-primitive-procedure) (reg proc) (reg argl))
(goto (reg continue))
after-call22
after-lambda2
(perform (op define-variable!) (const factorial) (reg val) (reg env))
(assign val (const ok))) |
5a095725582b5d1d69a9b0e8599b858e6930e40e97f2afcadf8934553f216365 | pirapira/coq2rust | tacmach.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Util
open Namegen
open Termops
open Environ
open Reductionops
open Evd
open Typing
open Redexpr
open Tacred
open Proof_type
open Logic
open Refiner
let re_sig it gc = { it = it; sigma = gc; }
(**************************************************************)
(* Operations for handling terms under a local typing context *)
(**************************************************************)
type 'a sigma = 'a Evd.sigma;;
type tactic = Proof_type.tactic;;
let unpackage = Refiner.unpackage
let repackage = Refiner.repackage
let apply_sig_tac = Refiner.apply_sig_tac
let sig_it = Refiner.sig_it
let project = Refiner.project
let pf_env = Refiner.pf_env
let pf_hyps = Refiner.pf_hyps
let pf_concl gls = Goal.V82.concl (project gls) (sig_it gls)
let pf_hyps_types gls =
let sign = Environ.named_context (pf_env gls) in
List.map (fun (id,_,x) -> (id, x)) sign
let pf_nth_hyp_id gls n = let (id,c,t) = List.nth (pf_hyps gls) (n-1) in id
let pf_last_hyp gl = List.hd (pf_hyps gl)
let pf_get_hyp gls id =
try
Context.lookup_named id (pf_hyps gls)
with Not_found ->
raise (RefinerError (NoSuchHyp id))
let pf_get_hyp_typ gls id =
let (_,_,ty)= (pf_get_hyp gls id) in
ty
let pf_ids_of_hyps gls = ids_of_named_context (pf_hyps gls)
let pf_get_new_id id gls =
next_ident_away id (pf_ids_of_hyps gls)
let pf_get_new_ids ids gls =
let avoid = pf_ids_of_hyps gls in
List.fold_right
(fun id acc -> (next_ident_away id (acc@avoid))::acc)
ids []
let pf_global gls id = Constrintern.construct_reference (pf_hyps gls) id
let pf_reduction_of_red_expr gls re c =
(fst (reduction_of_red_expr (pf_env gls) re)) (pf_env gls) (project gls) c
let pf_apply f gls = f (pf_env gls) (project gls)
let pf_eapply f gls x =
on_sig gls (fun evm -> f (pf_env gls) evm x)
let pf_reduce = pf_apply
let pf_e_reduce = pf_apply
let pf_whd_betadeltaiota = pf_reduce whd_betadeltaiota
let pf_hnf_constr = pf_reduce hnf_constr
let pf_nf = pf_reduce simpl
let pf_nf_betaiota = pf_reduce (fun _ -> nf_betaiota)
let pf_compute = pf_reduce compute
let pf_unfoldn ubinds = pf_reduce (unfoldn ubinds)
let pf_type_of = pf_reduce type_of
let pf_get_type_of = pf_reduce Retyping.get_type_of
let pf_conv_x gl = pf_reduce test_conversion gl Reduction.CONV
let pf_conv_x_leq gl = pf_reduce test_conversion gl Reduction.CUMUL
let pf_const_value = pf_reduce (fun env _ -> constant_value_in env)
let pf_reduce_to_quantified_ind = pf_reduce reduce_to_quantified_ind
let pf_reduce_to_atomic_ind = pf_reduce reduce_to_atomic_ind
let pf_hnf_type_of gls = compose (pf_whd_betadeltaiota gls) (pf_get_type_of gls)
let pf_is_matching = pf_apply ConstrMatching.is_matching_conv
let pf_matches = pf_apply ConstrMatching.matches_conv
(********************************************)
(* Definition of the most primitive tactics *)
(********************************************)
let refiner = refiner
let internal_cut_no_check replace id t gl =
refiner (Cut (true,replace,id,t)) gl
let internal_cut_rev_no_check replace id t gl =
refiner (Cut (false,replace,id,t)) gl
let refine_no_check c gl =
refiner (Refine c) gl
(* This does not check dependencies *)
let thin_no_check ids gl =
if List.is_empty ids then tclIDTAC gl else refiner (Thin ids) gl
let move_hyp_no_check id1 id2 gl =
refiner (Move (id1,id2)) gl
let mutual_fix f n others j gl =
with_check (refiner (FixRule (f,n,others,j))) gl
let mutual_cofix f others j gl =
with_check (refiner (Cofix (f,others,j))) gl
(* Versions with consistency checks *)
let internal_cut b d t = with_check (internal_cut_no_check b d t)
let internal_cut_rev b d t = with_check (internal_cut_rev_no_check b d t)
let refine c = with_check (refine_no_check c)
let thin c = with_check (thin_no_check c)
let move_hyp id id' = with_check (move_hyp_no_check id id')
(* Pretty-printers *)
open Pp
let db_pr_goal sigma g =
let env = Goal.V82.env sigma g in
let penv = print_named_context env in
let pc = print_constr_env env (Goal.V82.concl sigma g) in
str" " ++ hv 0 (penv ++ fnl () ++
str "============================" ++ fnl () ++
str" " ++ pc) ++ fnl ()
let pr_gls gls =
hov 0 (pr_evar_map (Some 2) (sig_sig gls) ++ fnl () ++ db_pr_goal (project gls) (sig_it gls))
let pr_glls glls =
hov 0 (pr_evar_map (Some 2) (sig_sig glls) ++ fnl () ++
prlist_with_sep fnl (db_pr_goal (project glls)) (sig_it glls))
(* Variants of [Tacmach] functions built with the new proof engine *)
module New = struct
let pf_apply f gl =
f (Proofview.Goal.env gl) (Proofview.Goal.sigma gl)
let of_old f gl =
f { Evd.it = Proofview.Goal.goal gl ; sigma = Proofview.Goal.sigma gl }
let pf_global id gl =
* We only check for the existence of an [ i d ] in [ hyps ]
let gl = Proofview.Goal.assume gl in
let hyps = Proofview.Goal.hyps gl in
Constrintern.construct_reference hyps id
let pf_env = Proofview.Goal.env
let pf_concl = Proofview.Goal.concl
let pf_type_of gl t =
pf_apply type_of gl t
let pf_conv_x gl t1 t2 = pf_apply is_conv gl t1 t2
let pf_ids_of_hyps gl =
* We only get the identifiers in [ hyps ]
let gl = Proofview.Goal.assume gl in
let hyps = Proofview.Goal.hyps gl in
ids_of_named_context hyps
let pf_get_new_id id gl =
let ids = pf_ids_of_hyps gl in
next_ident_away id ids
let pf_get_hyp id gl =
let hyps = Proofview.Goal.hyps gl in
let sign =
try Context.lookup_named id hyps
with Not_found -> raise (RefinerError (NoSuchHyp id))
in
sign
let pf_get_hyp_typ id gl =
let (_,_,ty) = pf_get_hyp id gl in
ty
let pf_hyps_types gl =
let env = Proofview.Goal.env gl in
let sign = Environ.named_context env in
List.map (fun (id,_,x) -> (id, x)) sign
let pf_last_hyp gl =
let hyps = Proofview.Goal.hyps gl in
List.hd hyps
let pf_nf_concl (gl : [ `LZ ] Proofview.Goal.t) =
(** We normalize the conclusion just after *)
let gl = Proofview.Goal.assume gl in
let concl = Proofview.Goal.concl gl in
let sigma = Proofview.Goal.sigma gl in
nf_evar sigma concl
let pf_whd_betadeltaiota gl t = pf_apply whd_betadeltaiota gl t
let pf_get_type_of gl t = pf_apply Retyping.get_type_of gl t
let pf_reduce_to_quantified_ind gl t =
pf_apply reduce_to_quantified_ind gl t
let pf_hnf_constr gl t = pf_apply hnf_constr gl t
let pf_hnf_type_of gl t =
pf_whd_betadeltaiota gl (pf_get_type_of gl t)
let pf_matches gl pat t = pf_apply ConstrMatching.matches_conv gl pat t
let pf_whd_betadeltaiota gl t = pf_apply whd_betadeltaiota gl t
let pf_compute gl t = pf_apply compute gl t
let pf_nf_evar gl t = nf_evar (Proofview.Goal.sigma gl) t
end
| null | https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/proofs/tacmach.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
************************************************************
Operations for handling terms under a local typing context
************************************************************
******************************************
Definition of the most primitive tactics
******************************************
This does not check dependencies
Versions with consistency checks
Pretty-printers
Variants of [Tacmach] functions built with the new proof engine
* We normalize the conclusion just after | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Util
open Namegen
open Termops
open Environ
open Reductionops
open Evd
open Typing
open Redexpr
open Tacred
open Proof_type
open Logic
open Refiner
let re_sig it gc = { it = it; sigma = gc; }
type 'a sigma = 'a Evd.sigma;;
type tactic = Proof_type.tactic;;
let unpackage = Refiner.unpackage
let repackage = Refiner.repackage
let apply_sig_tac = Refiner.apply_sig_tac
let sig_it = Refiner.sig_it
let project = Refiner.project
let pf_env = Refiner.pf_env
let pf_hyps = Refiner.pf_hyps
let pf_concl gls = Goal.V82.concl (project gls) (sig_it gls)
let pf_hyps_types gls =
let sign = Environ.named_context (pf_env gls) in
List.map (fun (id,_,x) -> (id, x)) sign
let pf_nth_hyp_id gls n = let (id,c,t) = List.nth (pf_hyps gls) (n-1) in id
let pf_last_hyp gl = List.hd (pf_hyps gl)
let pf_get_hyp gls id =
try
Context.lookup_named id (pf_hyps gls)
with Not_found ->
raise (RefinerError (NoSuchHyp id))
let pf_get_hyp_typ gls id =
let (_,_,ty)= (pf_get_hyp gls id) in
ty
let pf_ids_of_hyps gls = ids_of_named_context (pf_hyps gls)
let pf_get_new_id id gls =
next_ident_away id (pf_ids_of_hyps gls)
let pf_get_new_ids ids gls =
let avoid = pf_ids_of_hyps gls in
List.fold_right
(fun id acc -> (next_ident_away id (acc@avoid))::acc)
ids []
let pf_global gls id = Constrintern.construct_reference (pf_hyps gls) id
let pf_reduction_of_red_expr gls re c =
(fst (reduction_of_red_expr (pf_env gls) re)) (pf_env gls) (project gls) c
let pf_apply f gls = f (pf_env gls) (project gls)
let pf_eapply f gls x =
on_sig gls (fun evm -> f (pf_env gls) evm x)
let pf_reduce = pf_apply
let pf_e_reduce = pf_apply
let pf_whd_betadeltaiota = pf_reduce whd_betadeltaiota
let pf_hnf_constr = pf_reduce hnf_constr
let pf_nf = pf_reduce simpl
let pf_nf_betaiota = pf_reduce (fun _ -> nf_betaiota)
let pf_compute = pf_reduce compute
let pf_unfoldn ubinds = pf_reduce (unfoldn ubinds)
let pf_type_of = pf_reduce type_of
let pf_get_type_of = pf_reduce Retyping.get_type_of
let pf_conv_x gl = pf_reduce test_conversion gl Reduction.CONV
let pf_conv_x_leq gl = pf_reduce test_conversion gl Reduction.CUMUL
let pf_const_value = pf_reduce (fun env _ -> constant_value_in env)
let pf_reduce_to_quantified_ind = pf_reduce reduce_to_quantified_ind
let pf_reduce_to_atomic_ind = pf_reduce reduce_to_atomic_ind
let pf_hnf_type_of gls = compose (pf_whd_betadeltaiota gls) (pf_get_type_of gls)
let pf_is_matching = pf_apply ConstrMatching.is_matching_conv
let pf_matches = pf_apply ConstrMatching.matches_conv
let refiner = refiner
let internal_cut_no_check replace id t gl =
refiner (Cut (true,replace,id,t)) gl
let internal_cut_rev_no_check replace id t gl =
refiner (Cut (false,replace,id,t)) gl
let refine_no_check c gl =
refiner (Refine c) gl
let thin_no_check ids gl =
if List.is_empty ids then tclIDTAC gl else refiner (Thin ids) gl
let move_hyp_no_check id1 id2 gl =
refiner (Move (id1,id2)) gl
let mutual_fix f n others j gl =
with_check (refiner (FixRule (f,n,others,j))) gl
let mutual_cofix f others j gl =
with_check (refiner (Cofix (f,others,j))) gl
let internal_cut b d t = with_check (internal_cut_no_check b d t)
let internal_cut_rev b d t = with_check (internal_cut_rev_no_check b d t)
let refine c = with_check (refine_no_check c)
let thin c = with_check (thin_no_check c)
let move_hyp id id' = with_check (move_hyp_no_check id id')
open Pp
let db_pr_goal sigma g =
let env = Goal.V82.env sigma g in
let penv = print_named_context env in
let pc = print_constr_env env (Goal.V82.concl sigma g) in
str" " ++ hv 0 (penv ++ fnl () ++
str "============================" ++ fnl () ++
str" " ++ pc) ++ fnl ()
let pr_gls gls =
hov 0 (pr_evar_map (Some 2) (sig_sig gls) ++ fnl () ++ db_pr_goal (project gls) (sig_it gls))
let pr_glls glls =
hov 0 (pr_evar_map (Some 2) (sig_sig glls) ++ fnl () ++
prlist_with_sep fnl (db_pr_goal (project glls)) (sig_it glls))
module New = struct
let pf_apply f gl =
f (Proofview.Goal.env gl) (Proofview.Goal.sigma gl)
let of_old f gl =
f { Evd.it = Proofview.Goal.goal gl ; sigma = Proofview.Goal.sigma gl }
let pf_global id gl =
* We only check for the existence of an [ i d ] in [ hyps ]
let gl = Proofview.Goal.assume gl in
let hyps = Proofview.Goal.hyps gl in
Constrintern.construct_reference hyps id
let pf_env = Proofview.Goal.env
let pf_concl = Proofview.Goal.concl
let pf_type_of gl t =
pf_apply type_of gl t
let pf_conv_x gl t1 t2 = pf_apply is_conv gl t1 t2
let pf_ids_of_hyps gl =
* We only get the identifiers in [ hyps ]
let gl = Proofview.Goal.assume gl in
let hyps = Proofview.Goal.hyps gl in
ids_of_named_context hyps
let pf_get_new_id id gl =
let ids = pf_ids_of_hyps gl in
next_ident_away id ids
let pf_get_hyp id gl =
let hyps = Proofview.Goal.hyps gl in
let sign =
try Context.lookup_named id hyps
with Not_found -> raise (RefinerError (NoSuchHyp id))
in
sign
let pf_get_hyp_typ id gl =
let (_,_,ty) = pf_get_hyp id gl in
ty
let pf_hyps_types gl =
let env = Proofview.Goal.env gl in
let sign = Environ.named_context env in
List.map (fun (id,_,x) -> (id, x)) sign
let pf_last_hyp gl =
let hyps = Proofview.Goal.hyps gl in
List.hd hyps
let pf_nf_concl (gl : [ `LZ ] Proofview.Goal.t) =
let gl = Proofview.Goal.assume gl in
let concl = Proofview.Goal.concl gl in
let sigma = Proofview.Goal.sigma gl in
nf_evar sigma concl
let pf_whd_betadeltaiota gl t = pf_apply whd_betadeltaiota gl t
let pf_get_type_of gl t = pf_apply Retyping.get_type_of gl t
let pf_reduce_to_quantified_ind gl t =
pf_apply reduce_to_quantified_ind gl t
let pf_hnf_constr gl t = pf_apply hnf_constr gl t
let pf_hnf_type_of gl t =
pf_whd_betadeltaiota gl (pf_get_type_of gl t)
let pf_matches gl pat t = pf_apply ConstrMatching.matches_conv gl pat t
let pf_whd_betadeltaiota gl t = pf_apply whd_betadeltaiota gl t
let pf_compute gl t = pf_apply compute gl t
let pf_nf_evar gl t = nf_evar (Proofview.Goal.sigma gl) t
end
|
52d3cabfe63224b58d122f340c4719441f851512b7257d7e7242a3e02da42564 | codinuum/cca | stat.ml |
Copyright 2012 - 2022 Codinuum Software Lab < >
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Copyright 2012-2022 Codinuum Software Lab <>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
(* stat.ml *)
module C = Compression
let printf = Printf.printf
let fprintf = Printf.fprintf
let sprintf = Printf.sprintf
let fact_file_name = "fact.nt"
let diff_file_name = "diff"
let info_file_name = "info"
let summary_file_name = "summary"
let map_file_name = "map"
let stat_file_name = "stat"
let sources_file_name = "sources"
let source_file_name = "source"
let changes_file_name = "changes"
let delta_file_name = Delta_base.delta_file_name
let dot_file_name1 = "old.dot"
let dot_file_name2 = "new.dot"
let parser_file_name = "parser"
exception Stat_not_found
exception Malformed_stat of string
let fscanf ic =
let ib = Scanf.Scanning.from_channel ic in
Scanf.bscanf ib
let scan ?(max_retry_count=10) scanner path =
let rec _scan n path (scanner : in_channel -> 'a) =
try
let ch = open_in path in
try
let res = scanner ch in
begin
try
close_in ch
with
Sys_error s -> WARN_MSG s
end;
res
with
| Scanf.Scan_failure _
| Failure _
| End_of_file
| Invalid_argument _ ->
(try
close_in ch;
with _ -> ());
raise (Malformed_stat path)
with
| Sys_error s -> (* WARN_MSG s; *) raise Stat_not_found
| Malformed_stat _ ->
if n > max_retry_count then
raise Stat_not_found
else begin
Xprint.warning "malformed cache \"%s\": retrying...(%d)" path n;
Unix.sleep 1;
_scan (n+1) path scanner
end
in
let x = _scan 1 path scanner in
x
let scan_paths ?(max_retry_count=10) scanner paths =
let scan_path = scan ~max_retry_count:1 scanner in
let rec doit count ps =
if count < 0 then
raise Stat_not_found
else
match ps with
| [] -> raise Stat_not_found
| [x] -> begin
try
scan_path x.Cache.sr_path
with
_ ->
Unix.sleep 1;
doit (count-1) ps
end
| x::xs -> begin
try
scan_path x.Cache.sr_path
with
_ ->
Unix.sleep 1;
doit (count-1) xs
end
in
doit max_retry_count paths
module File = struct
type diff_stat = { s_nnodes1 : int;
s_nnodes2 : int;
s_deletes : int; s_deletes_gr : int;
s_inserts : int; s_inserts_gr : int;
s_relabels : int; s_relabels_orig : int; s_relabels_gr : int;
s_movrels : int; s_movrels_orig : int;
s_moves : int; s_moves_gr : int;
s_mapping : int;
s_units : int;
s_unmodified_units : int;
s_total_changes : int;
s_similarity : string;
s_change_ratio : string;
s_unmodified_rate : string;
s_SPSM : int;
s_SPM : int;
s_MGSM : int;
s_MGM : int;
s_AHS : string;
}
let make_empty_diff_stat() = { s_nnodes1 = 0;
s_nnodes2 = 0;
s_deletes = 0; s_deletes_gr = 0;
s_inserts = 0; s_inserts_gr = 0;
s_relabels = 0; s_relabels_orig = 0; s_relabels_gr = 0;
s_movrels = 0; s_movrels_orig = 0;
s_moves = 0; s_moves_gr = 0;
s_mapping = 0;
s_units = 0;
s_unmodified_units = 0;
s_total_changes = 0;
s_similarity = "0.0";
s_change_ratio = "0.0";
s_unmodified_rate = "1.0";
s_SPSM = 0;
s_SPM = 0;
s_MGSM = 0;
s_MGM = 0;
s_AHS = "0.0";
}
let make_diff_stat
?(mapping=0)
?(units=0)
?(unmodified_units=0)
()
= { s_nnodes1 = 0;
s_nnodes2 = 0;
s_deletes = 0; s_deletes_gr = 0;
s_inserts = 0; s_inserts_gr = 0;
s_relabels = 0; s_relabels_orig = 0; s_relabels_gr = 0;
s_movrels = 0; s_movrels_orig = 0;
s_moves = 0; s_moves_gr = 0;
s_mapping = mapping;
s_units = units;
s_unmodified_units = unmodified_units;
s_total_changes = 0;
s_similarity = "0.0";
s_change_ratio = "0.0";
s_unmodified_rate = "1.0";
s_SPSM = 0;
s_SPM = 0;
s_MGSM = 0;
s_MGM = 0;
s_AHS = "0.0";
}
let diff_stat_fmt () =
"nnodes1 : %d\n" ^^
"nnodes2 : %d\n\n" ^^
"deletes(hunks) : %d(%d)\n" ^^
"inserts(hunks) : %d(%d)\n" ^^
"relabels : %d(orig:%d)(%d)\n" ^^
"mov+rels : %d(orig:%d)\n" ^^
"moves(hunks) : %d(%d)\n\n" ^^
"total changes : %d\n" ^^
"mapping size : %d\n" ^^
"similarity : %s\n" ^^
"CMR : %s\n\n" ^^
"units (old) : %d\n" ^^
"unmodified units : %d\n" ^^
"UNMODIFIED RATE : %s\n\n" ^^
"SPSM : %d\n" ^^
"SPM : %d\n" ^^
"MGSM : %d\n" ^^
"MGM : %d\n" ^^
"AHS : %s\n"
let diff_stat_short_fmt () =
"nodes : %d -> %d\n" ^^
"deletes(hunks) : %d(%d)\n" ^^
"inserts(hunks) : %d(%d)\n" ^^
"relabels : %d (orig:%d)\n" ^^
"mov+rels : %d (orig:%d)\n" ^^
"moves(hunks) : %d(%d)\n" ^^
"total changes : %d\n" ^^
"mapping size : %d\n" ^^
"similarity : %s\n"
let diff_stat_json_fmt () =
"{" ^^
"\"nnodes1\":%d,\"nnodes2\":%d," ^^
"\"deletes\":%d,\"delete_groups\":%d," ^^
"\"inserts\":%d,\"insert_groups\":%d," ^^
"\"relabels\":%d,\"orig_relabels\":%d," ^^
"\"move+relabels\":%d,\"orig_move+relabels\":%d," ^^
"\"moves\":%d,\"move_groups\":%d," ^^
"\"edit_cost\":%d," ^^
"\"nmappings\":%d," ^^
"\"similarity\":%s" ^^
"}"
let dump_diff_stat_json_ch s ch =
fprintf ch (diff_stat_json_fmt())
s.s_nnodes1 s.s_nnodes2
s.s_deletes s.s_deletes_gr
s.s_inserts s.s_inserts_gr
s.s_relabels s.s_relabels_orig
s.s_movrels s.s_movrels_orig
s.s_moves s.s_moves_gr
s.s_total_changes
s.s_mapping
s.s_similarity
let dump_diff_stat_ch ?(short=false) s ch =
if short then
fprintf ch (diff_stat_short_fmt())
s.s_nnodes1 s.s_nnodes2
s.s_deletes s.s_deletes_gr
s.s_inserts s.s_inserts_gr
s.s_relabels s.s_relabels_orig(*s.s_relabels_gr*)
s.s_movrels s.s_movrels_orig
s.s_moves s.s_moves_gr
s.s_total_changes
s.s_mapping
s.s_similarity
else
fprintf ch (diff_stat_fmt())
s.s_nnodes1 s.s_nnodes2
s.s_deletes s.s_deletes_gr
s.s_inserts s.s_inserts_gr
s.s_relabels s.s_relabels_orig s.s_relabels_gr
s.s_movrels s.s_movrels_orig
s.s_moves s.s_moves_gr
s.s_total_changes
s.s_mapping
s.s_similarity
s.s_change_ratio
s.s_units
s.s_unmodified_units
s.s_unmodified_rate
s.s_SPSM
s.s_SPM
s.s_MGSM
s.s_MGM
s.s_AHS
let dump_diff_stat_json fname s =
Xfile.dump fname (dump_diff_stat_json_ch s)
let dump_diff_stat fname s =
Xfile.dump fname (dump_diff_stat_ch s)
let dump_sim_ch s ch = fprintf ch "%s\n" s.s_similarity
type info = {
i_nodes : int;
i_units : int;
i_LOC : int;
i_missed_LOC : int;
}
let dummy_info = {
i_nodes = 0;
i_units = 0;
i_LOC = 0;
i_missed_LOC = 0;
}
let info_fmt () =
"nodes: %d\n" ^^
"units: %d\n" ^^
"LOC: %d\n" ^^
"missed LOC: %d\n"
let mkinfo n u l m =
{ i_nodes = n;
i_units = u;
i_LOC = l;
i_missed_LOC = m;
}
let dump_info_ch info ch =
let fmt = info_fmt() in
fprintf ch fmt info.i_nodes info.i_units info.i_LOC info.i_missed_LOC
let show_info info = dump_info_ch info stdout
let get_tree_info tree =
let units = tree#get_units_to_be_notified in
mkinfo tree#initial_size (List.length units) tree#total_LOC tree#misparsed_LOC
let dump_info cache_path tree =
let path = Filename.concat cache_path info_file_name in
let info = get_tree_info tree in
Xfile.dump path (dump_info_ch info)
let scan_diff_stat ?(max_retry_count=10) paths =
scan_paths ~max_retry_count
(fun ch ->
fscanf ch (diff_stat_fmt())
(fun n1 n2 d dg i ig r ro rg rm rmo m mg tc map sim cr u uu ur spsm mgsm spm mgm ahs ->
{ s_nnodes1 = n1; s_nnodes2 = n2;
s_deletes = d; s_deletes_gr = dg;
s_inserts = i; s_inserts_gr = ig;
s_relabels = r; s_relabels_orig = ro; s_relabels_gr = rg;
s_movrels = rm; s_movrels_orig = rmo;
s_moves = m; s_moves_gr = mg;
s_mapping = map;
s_units = u;
s_unmodified_units = uu;
s_total_changes = tc;
s_similarity = sim;
s_change_ratio = cr;
s_unmodified_rate = ur;
s_SPSM = spsm;
s_SPM = spm;
s_MGSM = mgsm;
s_MGM = mgm;
s_AHS = ahs;
}
)
) paths
let scan_info paths =
scan_paths
(fun ch ->
fscanf ch (info_fmt())
(fun nnodes nunits tloc mloc ->
{ i_nodes = nnodes;
i_units = nunits;
i_LOC = tloc;
i_missed_LOC = mloc;
}
)
) paths
end (* module Stat.File *)
module Dir = struct
type diff_stat = { mutable s_deletes : int; mutable s_deletes_gr : int;
mutable s_inserts : int; mutable s_inserts_gr : int;
mutable s_relabels : int; mutable s_relabels_gr : int;
mutable s_movrels : int;
mutable s_moves : int; mutable s_moves_gr : int;
mutable s_mapping : int;
mutable s_units : int;
mutable s_unmodified_units : int;
mutable s_nnodes1 : int;
mutable s_nnodes2 : int;
}
let empty_diff_stat() = { s_deletes = 0; s_deletes_gr = 0;
s_inserts = 0; s_inserts_gr = 0;
s_relabels = 0; s_relabels_gr = 0;
s_movrels = 0;
s_moves = 0; s_moves_gr = 0;
s_mapping = 0;
s_units = 0;
s_unmodified_units = 0;
s_nnodes1 = 0;
s_nnodes2 = 0;
}
let diff_stat_short_fmt () =
"nodes : %d -> %d\n" ^^
"deletes(hunks) : %d(%d)\n" ^^
"inserts(hunks) : %d(%d)\n" ^^
"relabels : %d\n" ^^
"mov+rels : %d\n" ^^
"moves(hunks) : %d(%d)\n" ^^
"total changes : %d\n" ^^
"mapping size : %d\n" ^^
"similarity : %s\n"
let dump_diff_stat_ch ?(short=false) s ch =
let total = s.s_deletes + s.s_inserts + s.s_relabels + s.s_moves_gr in
let sim =
if total = 0 then
"1.0"
else
let spm = s.s_mapping - s.s_moves - s.s_relabels + s.s_movrels in
let _sim = float (spm * 2) /. float (s.s_nnodes1 + s.s_nnodes2) in
sprintf "%.6f" _sim
in
if short then
fprintf ch (diff_stat_short_fmt())
s.s_nnodes1 s.s_nnodes2
s.s_deletes s.s_deletes_gr
s.s_inserts s.s_inserts_gr
s.s_relabels
s.s_movrels
s.s_moves s.s_moves_gr
total
s.s_mapping
sim
else begin
fprintf ch "nnodes1: %d\n" s.s_nnodes1;
fprintf ch "nnodes2: %d\n" s.s_nnodes2;
fprintf ch "deletes : %d(%d)\n" s.s_deletes s.s_deletes_gr;
fprintf ch "inserts : %d(%d)\n" s.s_inserts s.s_inserts_gr;
fprintf ch "relabels : %d(%d)\n" s.s_relabels s.s_relabels_gr;
fprintf ch "movrels : %d\n" s.s_movrels;
fprintf ch "moves : %d(%d)\n\n" s.s_moves s.s_moves_gr;
fprintf ch "total changes : %d\n" total;
fprintf ch "mapping size : %d\n" s.s_mapping;
fprintf ch "similarity : %s\n" sim;
fprintf ch "CMR : %.6f\n\n"
((float_of_int total) /. (float_of_int s.s_mapping));
fprintf ch "units (old) : %d\n" s.s_units;
fprintf ch "unmodified units : %d\n" s.s_unmodified_units;
fprintf ch "UNMODIFIED RATE : %.6f\n\n"
((float_of_int s.s_unmodified_units) /. (float_of_int s.s_units));
fprintf ch "SPSM : %d\n" (s.s_mapping - s.s_relabels - s.s_moves + s.s_movrels);
fprintf ch "SPM : %d\n" (s.s_mapping - s.s_moves);
fprintf ch "AHS : %.6f\n"
((float_of_int (s.s_deletes + s.s_inserts + s.s_moves))
/. (float_of_int (s.s_deletes_gr + s.s_inserts_gr + s.s_moves_gr)))
end
let show_diff_stat ?(short=false) stat =
dump_diff_stat_ch ~short stat stdout
let dump_diff_stat cache_dir stat =
let path = Filename.concat cache_dir stat_file_name in
Xfile.dump path (dump_diff_stat_ch stat)
let info_fmt () =
"%s\n" ^^
"nodes: %d\n" ^^
"source files: %d\n" ^^
"AST nodes: %d\n"
let dump_info_ch dtree ast_nodes ch =
let fmt = info_fmt() in
fprintf ch fmt
dtree#id
dtree#initial_size
(List.length dtree#get_whole_initial_leaves)
ast_nodes
end (* module Stat.Dir *)
let _get_vkey vkind ver =
if not (Entity.vkind_is_unknown vkind) && ver <> "" then
Entity.mkvkey vkind ver
else
""
let get_vkey tree = _get_vkey tree#vkind tree#version
let dump_source_path_ch p ch =
Printf.fprintf ch "%s\n" p
let _dump_source_path cache_path (k, v) spath =
let vkey = _get_vkey k v in
let a = if vkey = "" then "" else "."^vkey in
let path = (Filename.concat cache_path source_file_name)^a in
Xfile.dump path (dump_source_path_ch spath)
let dump_source_ch tree = dump_source_path_ch tree#source_path
let _dump_source cache_path tree =
_dump_source_path cache_path (tree#vkind, tree#version) tree#source_path
let dump_source options file tree =
let cache_path = options#get_cache_path_for_file1 file in
_dump_source cache_path tree
let dump_file_info options file tree =
let cache_path = options#get_cache_path_for_file1 file in
File.dump_info cache_path tree
let dump_parser_name_ch pname ch =
Printf.fprintf ch "%s\n" pname
let dump_parser_name file parser_name =
Xfile.dump file (dump_parser_name_ch parser_name)
let dump_parser_ch tree = dump_parser_name_ch tree#parser_name
let _dump_parser cache_path tree =
let path = Filename.concat cache_path parser_file_name in
Xfile.dump path (dump_parser_ch tree)
let dump_parser options file tree =
let cache_path = options#get_cache_path_for_file1 file in
_dump_parser cache_path tree
| null | https://raw.githubusercontent.com/codinuum/cca/3d97b64a5c23ff97c08455ac604ccb9fed471d91/src/ast/analyzing/common/stat.ml | ocaml | stat.ml
WARN_MSG s;
s.s_relabels_gr
module Stat.File
module Stat.Dir |
Copyright 2012 - 2022 Codinuum Software Lab < >
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Copyright 2012-2022 Codinuum Software Lab <>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
module C = Compression
let printf = Printf.printf
let fprintf = Printf.fprintf
let sprintf = Printf.sprintf
let fact_file_name = "fact.nt"
let diff_file_name = "diff"
let info_file_name = "info"
let summary_file_name = "summary"
let map_file_name = "map"
let stat_file_name = "stat"
let sources_file_name = "sources"
let source_file_name = "source"
let changes_file_name = "changes"
let delta_file_name = Delta_base.delta_file_name
let dot_file_name1 = "old.dot"
let dot_file_name2 = "new.dot"
let parser_file_name = "parser"
exception Stat_not_found
exception Malformed_stat of string
let fscanf ic =
let ib = Scanf.Scanning.from_channel ic in
Scanf.bscanf ib
let scan ?(max_retry_count=10) scanner path =
let rec _scan n path (scanner : in_channel -> 'a) =
try
let ch = open_in path in
try
let res = scanner ch in
begin
try
close_in ch
with
Sys_error s -> WARN_MSG s
end;
res
with
| Scanf.Scan_failure _
| Failure _
| End_of_file
| Invalid_argument _ ->
(try
close_in ch;
with _ -> ());
raise (Malformed_stat path)
with
| Malformed_stat _ ->
if n > max_retry_count then
raise Stat_not_found
else begin
Xprint.warning "malformed cache \"%s\": retrying...(%d)" path n;
Unix.sleep 1;
_scan (n+1) path scanner
end
in
let x = _scan 1 path scanner in
x
let scan_paths ?(max_retry_count=10) scanner paths =
let scan_path = scan ~max_retry_count:1 scanner in
let rec doit count ps =
if count < 0 then
raise Stat_not_found
else
match ps with
| [] -> raise Stat_not_found
| [x] -> begin
try
scan_path x.Cache.sr_path
with
_ ->
Unix.sleep 1;
doit (count-1) ps
end
| x::xs -> begin
try
scan_path x.Cache.sr_path
with
_ ->
Unix.sleep 1;
doit (count-1) xs
end
in
doit max_retry_count paths
module File = struct
type diff_stat = { s_nnodes1 : int;
s_nnodes2 : int;
s_deletes : int; s_deletes_gr : int;
s_inserts : int; s_inserts_gr : int;
s_relabels : int; s_relabels_orig : int; s_relabels_gr : int;
s_movrels : int; s_movrels_orig : int;
s_moves : int; s_moves_gr : int;
s_mapping : int;
s_units : int;
s_unmodified_units : int;
s_total_changes : int;
s_similarity : string;
s_change_ratio : string;
s_unmodified_rate : string;
s_SPSM : int;
s_SPM : int;
s_MGSM : int;
s_MGM : int;
s_AHS : string;
}
let make_empty_diff_stat() = { s_nnodes1 = 0;
s_nnodes2 = 0;
s_deletes = 0; s_deletes_gr = 0;
s_inserts = 0; s_inserts_gr = 0;
s_relabels = 0; s_relabels_orig = 0; s_relabels_gr = 0;
s_movrels = 0; s_movrels_orig = 0;
s_moves = 0; s_moves_gr = 0;
s_mapping = 0;
s_units = 0;
s_unmodified_units = 0;
s_total_changes = 0;
s_similarity = "0.0";
s_change_ratio = "0.0";
s_unmodified_rate = "1.0";
s_SPSM = 0;
s_SPM = 0;
s_MGSM = 0;
s_MGM = 0;
s_AHS = "0.0";
}
let make_diff_stat
?(mapping=0)
?(units=0)
?(unmodified_units=0)
()
= { s_nnodes1 = 0;
s_nnodes2 = 0;
s_deletes = 0; s_deletes_gr = 0;
s_inserts = 0; s_inserts_gr = 0;
s_relabels = 0; s_relabels_orig = 0; s_relabels_gr = 0;
s_movrels = 0; s_movrels_orig = 0;
s_moves = 0; s_moves_gr = 0;
s_mapping = mapping;
s_units = units;
s_unmodified_units = unmodified_units;
s_total_changes = 0;
s_similarity = "0.0";
s_change_ratio = "0.0";
s_unmodified_rate = "1.0";
s_SPSM = 0;
s_SPM = 0;
s_MGSM = 0;
s_MGM = 0;
s_AHS = "0.0";
}
let diff_stat_fmt () =
"nnodes1 : %d\n" ^^
"nnodes2 : %d\n\n" ^^
"deletes(hunks) : %d(%d)\n" ^^
"inserts(hunks) : %d(%d)\n" ^^
"relabels : %d(orig:%d)(%d)\n" ^^
"mov+rels : %d(orig:%d)\n" ^^
"moves(hunks) : %d(%d)\n\n" ^^
"total changes : %d\n" ^^
"mapping size : %d\n" ^^
"similarity : %s\n" ^^
"CMR : %s\n\n" ^^
"units (old) : %d\n" ^^
"unmodified units : %d\n" ^^
"UNMODIFIED RATE : %s\n\n" ^^
"SPSM : %d\n" ^^
"SPM : %d\n" ^^
"MGSM : %d\n" ^^
"MGM : %d\n" ^^
"AHS : %s\n"
let diff_stat_short_fmt () =
"nodes : %d -> %d\n" ^^
"deletes(hunks) : %d(%d)\n" ^^
"inserts(hunks) : %d(%d)\n" ^^
"relabels : %d (orig:%d)\n" ^^
"mov+rels : %d (orig:%d)\n" ^^
"moves(hunks) : %d(%d)\n" ^^
"total changes : %d\n" ^^
"mapping size : %d\n" ^^
"similarity : %s\n"
let diff_stat_json_fmt () =
"{" ^^
"\"nnodes1\":%d,\"nnodes2\":%d," ^^
"\"deletes\":%d,\"delete_groups\":%d," ^^
"\"inserts\":%d,\"insert_groups\":%d," ^^
"\"relabels\":%d,\"orig_relabels\":%d," ^^
"\"move+relabels\":%d,\"orig_move+relabels\":%d," ^^
"\"moves\":%d,\"move_groups\":%d," ^^
"\"edit_cost\":%d," ^^
"\"nmappings\":%d," ^^
"\"similarity\":%s" ^^
"}"
let dump_diff_stat_json_ch s ch =
fprintf ch (diff_stat_json_fmt())
s.s_nnodes1 s.s_nnodes2
s.s_deletes s.s_deletes_gr
s.s_inserts s.s_inserts_gr
s.s_relabels s.s_relabels_orig
s.s_movrels s.s_movrels_orig
s.s_moves s.s_moves_gr
s.s_total_changes
s.s_mapping
s.s_similarity
let dump_diff_stat_ch ?(short=false) s ch =
if short then
fprintf ch (diff_stat_short_fmt())
s.s_nnodes1 s.s_nnodes2
s.s_deletes s.s_deletes_gr
s.s_inserts s.s_inserts_gr
s.s_movrels s.s_movrels_orig
s.s_moves s.s_moves_gr
s.s_total_changes
s.s_mapping
s.s_similarity
else
fprintf ch (diff_stat_fmt())
s.s_nnodes1 s.s_nnodes2
s.s_deletes s.s_deletes_gr
s.s_inserts s.s_inserts_gr
s.s_relabels s.s_relabels_orig s.s_relabels_gr
s.s_movrels s.s_movrels_orig
s.s_moves s.s_moves_gr
s.s_total_changes
s.s_mapping
s.s_similarity
s.s_change_ratio
s.s_units
s.s_unmodified_units
s.s_unmodified_rate
s.s_SPSM
s.s_SPM
s.s_MGSM
s.s_MGM
s.s_AHS
let dump_diff_stat_json fname s =
Xfile.dump fname (dump_diff_stat_json_ch s)
let dump_diff_stat fname s =
Xfile.dump fname (dump_diff_stat_ch s)
let dump_sim_ch s ch = fprintf ch "%s\n" s.s_similarity
type info = {
i_nodes : int;
i_units : int;
i_LOC : int;
i_missed_LOC : int;
}
let dummy_info = {
i_nodes = 0;
i_units = 0;
i_LOC = 0;
i_missed_LOC = 0;
}
let info_fmt () =
"nodes: %d\n" ^^
"units: %d\n" ^^
"LOC: %d\n" ^^
"missed LOC: %d\n"
let mkinfo n u l m =
{ i_nodes = n;
i_units = u;
i_LOC = l;
i_missed_LOC = m;
}
let dump_info_ch info ch =
let fmt = info_fmt() in
fprintf ch fmt info.i_nodes info.i_units info.i_LOC info.i_missed_LOC
let show_info info = dump_info_ch info stdout
let get_tree_info tree =
let units = tree#get_units_to_be_notified in
mkinfo tree#initial_size (List.length units) tree#total_LOC tree#misparsed_LOC
let dump_info cache_path tree =
let path = Filename.concat cache_path info_file_name in
let info = get_tree_info tree in
Xfile.dump path (dump_info_ch info)
let scan_diff_stat ?(max_retry_count=10) paths =
scan_paths ~max_retry_count
(fun ch ->
fscanf ch (diff_stat_fmt())
(fun n1 n2 d dg i ig r ro rg rm rmo m mg tc map sim cr u uu ur spsm mgsm spm mgm ahs ->
{ s_nnodes1 = n1; s_nnodes2 = n2;
s_deletes = d; s_deletes_gr = dg;
s_inserts = i; s_inserts_gr = ig;
s_relabels = r; s_relabels_orig = ro; s_relabels_gr = rg;
s_movrels = rm; s_movrels_orig = rmo;
s_moves = m; s_moves_gr = mg;
s_mapping = map;
s_units = u;
s_unmodified_units = uu;
s_total_changes = tc;
s_similarity = sim;
s_change_ratio = cr;
s_unmodified_rate = ur;
s_SPSM = spsm;
s_SPM = spm;
s_MGSM = mgsm;
s_MGM = mgm;
s_AHS = ahs;
}
)
) paths
let scan_info paths =
scan_paths
(fun ch ->
fscanf ch (info_fmt())
(fun nnodes nunits tloc mloc ->
{ i_nodes = nnodes;
i_units = nunits;
i_LOC = tloc;
i_missed_LOC = mloc;
}
)
) paths
module Dir = struct
type diff_stat = { mutable s_deletes : int; mutable s_deletes_gr : int;
mutable s_inserts : int; mutable s_inserts_gr : int;
mutable s_relabels : int; mutable s_relabels_gr : int;
mutable s_movrels : int;
mutable s_moves : int; mutable s_moves_gr : int;
mutable s_mapping : int;
mutable s_units : int;
mutable s_unmodified_units : int;
mutable s_nnodes1 : int;
mutable s_nnodes2 : int;
}
let empty_diff_stat() = { s_deletes = 0; s_deletes_gr = 0;
s_inserts = 0; s_inserts_gr = 0;
s_relabels = 0; s_relabels_gr = 0;
s_movrels = 0;
s_moves = 0; s_moves_gr = 0;
s_mapping = 0;
s_units = 0;
s_unmodified_units = 0;
s_nnodes1 = 0;
s_nnodes2 = 0;
}
let diff_stat_short_fmt () =
"nodes : %d -> %d\n" ^^
"deletes(hunks) : %d(%d)\n" ^^
"inserts(hunks) : %d(%d)\n" ^^
"relabels : %d\n" ^^
"mov+rels : %d\n" ^^
"moves(hunks) : %d(%d)\n" ^^
"total changes : %d\n" ^^
"mapping size : %d\n" ^^
"similarity : %s\n"
let dump_diff_stat_ch ?(short=false) s ch =
let total = s.s_deletes + s.s_inserts + s.s_relabels + s.s_moves_gr in
let sim =
if total = 0 then
"1.0"
else
let spm = s.s_mapping - s.s_moves - s.s_relabels + s.s_movrels in
let _sim = float (spm * 2) /. float (s.s_nnodes1 + s.s_nnodes2) in
sprintf "%.6f" _sim
in
if short then
fprintf ch (diff_stat_short_fmt())
s.s_nnodes1 s.s_nnodes2
s.s_deletes s.s_deletes_gr
s.s_inserts s.s_inserts_gr
s.s_relabels
s.s_movrels
s.s_moves s.s_moves_gr
total
s.s_mapping
sim
else begin
fprintf ch "nnodes1: %d\n" s.s_nnodes1;
fprintf ch "nnodes2: %d\n" s.s_nnodes2;
fprintf ch "deletes : %d(%d)\n" s.s_deletes s.s_deletes_gr;
fprintf ch "inserts : %d(%d)\n" s.s_inserts s.s_inserts_gr;
fprintf ch "relabels : %d(%d)\n" s.s_relabels s.s_relabels_gr;
fprintf ch "movrels : %d\n" s.s_movrels;
fprintf ch "moves : %d(%d)\n\n" s.s_moves s.s_moves_gr;
fprintf ch "total changes : %d\n" total;
fprintf ch "mapping size : %d\n" s.s_mapping;
fprintf ch "similarity : %s\n" sim;
fprintf ch "CMR : %.6f\n\n"
((float_of_int total) /. (float_of_int s.s_mapping));
fprintf ch "units (old) : %d\n" s.s_units;
fprintf ch "unmodified units : %d\n" s.s_unmodified_units;
fprintf ch "UNMODIFIED RATE : %.6f\n\n"
((float_of_int s.s_unmodified_units) /. (float_of_int s.s_units));
fprintf ch "SPSM : %d\n" (s.s_mapping - s.s_relabels - s.s_moves + s.s_movrels);
fprintf ch "SPM : %d\n" (s.s_mapping - s.s_moves);
fprintf ch "AHS : %.6f\n"
((float_of_int (s.s_deletes + s.s_inserts + s.s_moves))
/. (float_of_int (s.s_deletes_gr + s.s_inserts_gr + s.s_moves_gr)))
end
let show_diff_stat ?(short=false) stat =
dump_diff_stat_ch ~short stat stdout
let dump_diff_stat cache_dir stat =
let path = Filename.concat cache_dir stat_file_name in
Xfile.dump path (dump_diff_stat_ch stat)
let info_fmt () =
"%s\n" ^^
"nodes: %d\n" ^^
"source files: %d\n" ^^
"AST nodes: %d\n"
let dump_info_ch dtree ast_nodes ch =
let fmt = info_fmt() in
fprintf ch fmt
dtree#id
dtree#initial_size
(List.length dtree#get_whole_initial_leaves)
ast_nodes
let _get_vkey vkind ver =
if not (Entity.vkind_is_unknown vkind) && ver <> "" then
Entity.mkvkey vkind ver
else
""
let get_vkey tree = _get_vkey tree#vkind tree#version
let dump_source_path_ch p ch =
Printf.fprintf ch "%s\n" p
let _dump_source_path cache_path (k, v) spath =
let vkey = _get_vkey k v in
let a = if vkey = "" then "" else "."^vkey in
let path = (Filename.concat cache_path source_file_name)^a in
Xfile.dump path (dump_source_path_ch spath)
let dump_source_ch tree = dump_source_path_ch tree#source_path
let _dump_source cache_path tree =
_dump_source_path cache_path (tree#vkind, tree#version) tree#source_path
let dump_source options file tree =
let cache_path = options#get_cache_path_for_file1 file in
_dump_source cache_path tree
let dump_file_info options file tree =
let cache_path = options#get_cache_path_for_file1 file in
File.dump_info cache_path tree
let dump_parser_name_ch pname ch =
Printf.fprintf ch "%s\n" pname
let dump_parser_name file parser_name =
Xfile.dump file (dump_parser_name_ch parser_name)
let dump_parser_ch tree = dump_parser_name_ch tree#parser_name
let _dump_parser cache_path tree =
let path = Filename.concat cache_path parser_file_name in
Xfile.dump path (dump_parser_ch tree)
let dump_parser options file tree =
let cache_path = options#get_cache_path_for_file1 file in
_dump_parser cache_path tree
|
8f98eb7cec2b2403d72bfa3e3a581e1480b4ba76295da4cad58febdad779d191 | alang9/dynamic-graphs | Splay.hs | {-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE MultiWayIf #-}
# LANGUAGE RecordWildCards #
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Data.Graph.Dynamic.Internal.Splay
( Tree
, singleton
, cons
, snoc
, append
, split
, connected
, root
, aggregate
, toList
-- * Debugging only
, readRoot
, freeze
, print
, assertInvariants
) where
import Control.Monad (when)
import Control.Monad.Primitive (PrimMonad (..))
import qualified Data.Graph.Dynamic.Internal.Tree as Class
#if !(MIN_VERSION_base(4,8,0))
import Data.Monoid ((<>))
#endif
import Data.Primitive.MutVar (MutVar)
import qualified Data.Primitive.MutVar as MutVar
import qualified Data.Tree as Tree
import Prelude hiding (concat, print)
import System.IO.Unsafe (unsafePerformIO)
import Unsafe.Coerce (unsafeCoerce)
data T s a v = T
{ tParent :: {-# UNPACK #-} !(Tree s a v)
, tLeft :: {-# UNPACK #-} !(Tree s a v)
, tRight :: {-# UNPACK #-} !(Tree s a v)
, tLabel :: !a
, tValue :: !v
, tAgg :: !v
}
| NOTE ( jaspervdj ): There are two ways of indicating the parent / left /
-- right is not set (we want to avoid Maybe's since they cause a lot of
-- indirections).
--
Imagine that we are considering tLeft .
--
1 . We can set of x to the MutVar that holds the tree itself ( i.e. a
-- self-loop).
2 . We can set to some nil value .
--
-- They seem to offer similar performance. We choose to use the latter since it
-- is less likely to end up in infinite loops that way, and additionally, we can
-- move easily move e.g. x's left child to y's right child, even it is an empty
-- child.
nil :: Tree s a v
nil = unsafeCoerce $ unsafePerformIO $ fmap Tree $ MutVar.newMutVar undefined
# NOINLINE nil #
newtype Tree s a v = Tree {unTree :: MutVar s (T s a v)}
deriving (Eq)
singleton :: PrimMonad m => a -> v -> m (Tree (PrimState m) a v)
singleton tLabel tValue =
fmap Tree $ MutVar.newMutVar $! T nil nil nil tLabel tValue tValue
readRoot :: PrimMonad m => Tree (PrimState m) a v -> m (Tree (PrimState m) a v)
readRoot tree = do
T {..} <- MutVar.readMutVar (unTree tree)
if tParent == nil then return tree else readRoot tParent
-- | `lv` must be a singleton tree
cons
:: (PrimMonad m, Monoid v)
=> Tree (PrimState m) a v -> Tree (PrimState m) a v
-> m (Tree (PrimState m) a v)
cons lt@(Tree lv) rt@(Tree rv) = do
r <- MutVar.readMutVar rv
MutVar.modifyMutVar' lv $ \l -> l {tRight = rt, tAgg = tAgg l <> tAgg r}
MutVar.writeMutVar rv $! r {tParent = lt}
return lt
-- | `rv` must be a singleton tree
snoc
:: (PrimMonad m, Monoid v)
=> Tree (PrimState m) a v -> Tree (PrimState m) a v
-> m (Tree (PrimState m) a v)
snoc lt@(Tree lv) rt@(Tree rv) = do
l <- MutVar.readMutVar lv
MutVar.modifyMutVar' rv $ \r -> r {tLeft = lt, tAgg = tAgg l <> tAgg r}
MutVar.writeMutVar lv $! l {tParent = rt}
return rt
| Appends two trees . Returns the root of the tree .
append
:: (PrimMonad m, Monoid v)
=> Tree (PrimState m) a v
-> Tree (PrimState m) a v
-> m (Tree (PrimState m) a v)
append xt@(Tree _xv) yt@(Tree yv) = do
rmt@(Tree rmv) <- getRightMost xt
_ <- splay rmt
y <- MutVar.readMutVar yv
MutVar.modifyMutVar rmv $ \r -> r {tRight = yt, tAgg = tAgg r <> tAgg y}
MutVar.writeMutVar yv $! y {tParent = rmt}
return rmt
where
getRightMost tt@(Tree tv) = do
t <- MutVar.readMutVar tv
if tRight t == nil then return tt else getRightMost (tRight t)
split
:: (PrimMonad m, Monoid v)
=> Tree (PrimState m) a v
-> m (Maybe (Tree (PrimState m) a v), Maybe (Tree (PrimState m) a v))
split xt@(Tree xv) = do
_ <- splay xt
T {..} <- MutVar.readMutVar xv
when (tLeft /= nil) (removeParent tLeft) -- Works even if l is x
when (tRight /= nil) (removeParent tRight)
MutVar.writeMutVar xv $ T {tAgg = tValue, ..}
removeLeft xt
removeRight xt
return
( if tLeft == nil then Nothing else Just tLeft
, if tRight == nil then Nothing else Just tRight
)
connected
:: (PrimMonad m, Monoid v)
=> Tree (PrimState m) a v
-> Tree (PrimState m) a v
-> m Bool
connected x y = do
_ <- splay x
x' <- splay y
return $ x == x'
root
:: (PrimMonad m, Monoid v)
=> Tree (PrimState m) a v
-> m (Tree (PrimState m) a v)
root x = do
_ <- splay x
return x
label
:: (PrimMonad m, Monoid v)
=> Tree (PrimState m) a v
-> m a
label (Tree xv) = tLabel <$> MutVar.readMutVar xv
aggregate
:: (PrimMonad m, Monoid v)
=> Tree (PrimState m) a v
-> m v
aggregate (Tree xv) = tAgg <$> MutVar.readMutVar xv
-- | For debugging/testing.
toList
:: PrimMonad m => Tree (PrimState m) a v -> m [a]
toList = go []
where
go acc0 (Tree tv) = do
T {..} <- MutVar.readMutVar tv
acc1 <- if tRight == nil then return acc0 else go acc0 tRight
let acc2 = tLabel : acc1
if tLeft == nil then return acc2 else go acc2 tLeft
splay
:: forall m a v. (PrimMonad m, Monoid v)
=> Tree (PrimState m) a v
-> m (Tree (PrimState m) a v) -- Returns the old root.
splay xt@(Tree xv) = do
-- Note (jaspervdj): Rather than repeatedly reading from/writing to xv we
-- read x once and thread its (continuously updated) value through the
-- entire stack of `go` calls.
--
-- The same is true for the left and right aggregates of x: they can be
-- passed upwards rather than recomputed.
x0 <- MutVar.readMutVar xv
xla <- if tLeft x0 == nil then return mempty else tAgg <$> MutVar.readMutVar (unTree $ tLeft x0)
xra <- if tRight x0 == nil then return mempty else tAgg <$> MutVar.readMutVar (unTree $ tRight x0)
go xt xla xra x0
where
go :: Tree (PrimState m) a v -> v -> v -> T (PrimState m) a v
-> m (Tree (PrimState m) a v)
go closestToRootFound xla xra !x = do
let !(pt@(Tree pv)) = tParent x
if pt == nil then do
MutVar.writeMutVar xv x
return closestToRootFound
else do
p <- MutVar.readMutVar pv
let gt@(Tree gv) = tParent p
let plt@(Tree plv) = tLeft p
let prt@(Tree prv) = tRight p
let xlt@(Tree xlv) = tLeft x
let xrt@(Tree xrv) = tRight x
if | gt == nil, plt == xt -> do
ZIG ( Right )
--
> x
-- / \
-- x p
-- \ /
xr xr
--
when (xrt /= nil) $ MutVar.modifyMutVar' xrv $ \xr ->
xr {tParent = pt}
pra <- if prt == nil then return mempty else tAgg <$> MutVar.readMutVar prv
MutVar.writeMutVar pv $! p
{ tLeft = xrt
, tParent = xt
, tAgg = xra <> tValue p <> pra
}
MutVar.writeMutVar xv $! x
{ tAgg = tAgg p
, tRight = pt
, tParent = nil
}
return pt
| gt == nil -> do
ZIG ( Left )
--
-- p => x
-- \ /
-- x p
-- / \
xl xl
--
when (xlt /= nil) $ MutVar.modifyMutVar' xlv $ \xl ->
xl {tParent = pt}
pla <- if plt == nil then return mempty else tAgg <$> MutVar.readMutVar plv
MutVar.writeMutVar pv $! p
{ tRight = xlt
, tParent = xt
, tAgg = pla <> tValue p <> xla
}
MutVar.writeMutVar xv $! x
{ tAgg = tAgg p
, tLeft = pt
, tParent = nil
}
return pt
| otherwise -> do
g <- MutVar.readMutVar gv
let ggt@(Tree ggv) = tParent g
let glt@(Tree glv) = tLeft g
let grt@(Tree grv) = tRight g
when (ggt /= nil) $ MutVar.modifyMutVar' ggv $ \gg ->
if tLeft gg == gt
then gg {tLeft = xt}
else gg {tRight = xt}
if | plt == xt && glt == pt -> do
ZIGZIG ( Right ):
--
-- gg gg
-- | |
-- g x
-- / \ / \
-- p => p
-- / \ / \
-- x pr xr g
-- / \ /
-- xr pr
--
pra <- if prt == nil then return mempty else tAgg <$> MutVar.readMutVar prv
gra <- if grt == nil then return mempty else tAgg <$> MutVar.readMutVar grv
let !ga' = pra <> tValue g <> gra
when (prt /= nil) $ MutVar.modifyMutVar' prv $ \pr ->
pr {tParent = gt}
MutVar.writeMutVar gv $! g
{ tParent = pt
, tLeft = prt
, tAgg = ga'
}
when (xrt /= nil) $ MutVar.modifyMutVar' xrv $ \xr ->
xr {tParent = pt}
let !pa' = xra <> tValue p <> ga'
MutVar.writeMutVar pv $! p
{ tParent = xt
, tLeft = xrt
, tRight = gt
, tAgg = pa'
}
go gt xla pa' $! x
{ tRight = pt
, tAgg = tAgg g
, tParent = ggt
}
| plv /= xv && glv /= pv -> do
ZIGZIG ( Left ):
--
-- gg gg
-- | |
-- g x
-- / \ / \
-- p => p
-- / \ / \
pl x g xl
-- / \ / \
xl pl
--
pla <- if plt == nil then return mempty else tAgg <$> MutVar.readMutVar plv
gla <- if glt == nil then return mempty else tAgg <$> MutVar.readMutVar glv
let !ga' = gla <> tValue g <> pla
when (plt /= nil) $ MutVar.modifyMutVar' plv $ \pl ->
pl {tParent = gt}
MutVar.writeMutVar gv $! g
{ tParent = pt
, tRight = plt
, tAgg = ga'
}
when (xlt /= nil) $ MutVar.modifyMutVar' xlv $ \xl ->
xl {tParent = pt}
let !pa' = ga' <> tValue p <> xla
MutVar.writeMutVar pv $! p
{ tParent = xt
, tLeft = gt
, tRight = xlt
, tAgg = pa'
}
go gt pa' xra $! x
{ tLeft = pt
, tAgg = tAgg g
, tParent = ggt
}
| plv == xv -> do
ZIGZIG ( Left ):
--
-- gg gg
-- | |
x
-- \ / \
p =
-- / \ /
x xl xr
-- / \
xl xr
--
when (xlt /= nil) $ MutVar.modifyMutVar' xlv $ \xl ->
xl {tParent = gt}
gla <- if glt == nil then return mempty else tAgg <$> MutVar.readMutVar glv
let !ga' = gla <> tValue g <> xla
MutVar.writeMutVar gv $! g
{ tParent = xt
, tRight = xlt
, tAgg = ga'
}
when (xrt /= nil) $ MutVar.modifyMutVar' xrv $ \xr ->
xr {tParent = pt}
pra <- if prt == nil then return mempty else tAgg <$> MutVar.readMutVar prv
let pa' = xra <> tValue p <> pra
MutVar.writeMutVar pv $! p
{ tParent = xt
, tLeft = xrt
, tAgg = pa'
}
go gt ga' pa' $! x
{ tParent = ggt
, tLeft = gt
, tRight = pt
, tAgg = tAgg g
}
| otherwise -> do
ZIGZIG ( Right ):
--
-- gg gg
-- | |
x
-- / / \
-- p => p g
-- \ \ /
x xl xr
-- / \
xl xr
--
when (xrt /= nil) $ MutVar.modifyMutVar' xrv $ \xr ->
xr {tParent = gt}
gra <- if grt == nil then return mempty else tAgg <$> MutVar.readMutVar grv
let !ga' = xra <> tValue g <> gra
MutVar.writeMutVar gv $! g
{ tParent = xt
, tLeft = xrt
, tAgg = ga'
}
when (xlt /= nil) $ MutVar.modifyMutVar' xlv $ \xl ->
xl {tParent = pt}
pla <- if plt == nil then return mempty else tAgg <$> MutVar.readMutVar plv
let !pa' = pla <> tValue p <> xla
MutVar.writeMutVar pv $! p
{ tParent = xt
, tRight = xlt
, tAgg = pa'
}
go gt pa' ga' $! x
{ tParent = ggt
, tLeft = pt
, tRight = gt
, tAgg = tAgg g
}
removeParent, removeLeft, removeRight
:: PrimMonad m
=> Tree (PrimState m) a v -- Parent
-> m ()
removeParent (Tree x) = MutVar.modifyMutVar' x $ \x' -> x' {tParent = nil}
removeLeft (Tree x) = MutVar.modifyMutVar' x $ \x' -> x' {tLeft = nil}
removeRight (Tree x) = MutVar.modifyMutVar' x $ \x' -> x' {tRight = nil}
-- | For debugging/testing.
freeze :: PrimMonad m => Tree (PrimState m) a v -> m (Tree.Tree a)
freeze (Tree tv) = do
T {..} <- MutVar.readMutVar tv
children <- sequence $
[freeze tLeft | tLeft /= nil] ++
[freeze tRight | tRight /= nil]
return $ Tree.Node tLabel children
print :: Show a => Tree (PrimState IO) a v -> IO ()
print = go 0
where
go d (Tree tv) = do
T {..} <- MutVar.readMutVar tv
when (tLeft /= nil) $ go (d + 1) tLeft
putStrLn $ replicate d ' ' ++ show tLabel
when (tRight /= nil) $ go (d + 1) tRight
assertInvariants
:: (PrimMonad m, Monoid v, Eq v, Show v) => Tree (PrimState m) a v -> m ()
assertInvariants t = do
_ <- computeAgg nil t
return ()
where
-- TODO: Check average
computeAgg pt xt@(Tree xv) = do
x' <- MutVar.readMutVar xv
let p' = tParent x'
when (pt /= p') $ error "broken parent pointer"
let l = tLeft x'
let r = tRight x'
la <- if l == nil then return mempty else computeAgg xt l
ra <- if r == nil then return mempty else computeAgg xt r
let actualAgg = la <> (tValue x') <> ra
let storedAgg = tAgg x'
when (actualAgg /= storedAgg) $ error $
"error in stored aggregates: " ++ show storedAgg ++
", actual: " ++ show actualAgg
return actualAgg
data TreeGen s = TreeGen
instance Class.Tree Tree where
type TreeGen Tree = TreeGen
newTreeGen _ = return TreeGen
singleton _ = singleton
append = append
split = split
connected = connected
root = root
readRoot = readRoot
label = label
aggregate = aggregate
toList = toList
instance Class.TestTree Tree where
print = print
assertInvariants = assertInvariants
assertSingleton = \_ -> return ()
assertRoot = \_ -> return ()
| null | https://raw.githubusercontent.com/alang9/dynamic-graphs/b88f001850c7bee8faa62099e93172a0bb0df613/src/Data/Graph/Dynamic/Internal/Splay.hs | haskell | # LANGUAGE BangPatterns #
# LANGUAGE CPP #
# LANGUAGE MultiWayIf #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeSynonymInstances #
* Debugging only
# UNPACK #
# UNPACK #
# UNPACK #
right is not set (we want to avoid Maybe's since they cause a lot of
indirections).
self-loop).
They seem to offer similar performance. We choose to use the latter since it
is less likely to end up in infinite loops that way, and additionally, we can
move easily move e.g. x's left child to y's right child, even it is an empty
child.
| `lv` must be a singleton tree
| `rv` must be a singleton tree
Works even if l is x
| For debugging/testing.
Returns the old root.
Note (jaspervdj): Rather than repeatedly reading from/writing to xv we
read x once and thread its (continuously updated) value through the
entire stack of `go` calls.
The same is true for the left and right aggregates of x: they can be
passed upwards rather than recomputed.
/ \
x p
\ /
p => x
\ /
x p
/ \
gg gg
| |
g x
/ \ / \
p => p
/ \ / \
x pr xr g
/ \ /
xr pr
gg gg
| |
g x
/ \ / \
p => p
/ \ / \
/ \ / \
gg gg
| |
\ / \
/ \ /
/ \
gg gg
| |
/ / \
p => p g
\ \ /
/ \
Parent
| For debugging/testing.
TODO: Check average | # LANGUAGE RecordWildCards #
module Data.Graph.Dynamic.Internal.Splay
( Tree
, singleton
, cons
, snoc
, append
, split
, connected
, root
, aggregate
, toList
, readRoot
, freeze
, print
, assertInvariants
) where
import Control.Monad (when)
import Control.Monad.Primitive (PrimMonad (..))
import qualified Data.Graph.Dynamic.Internal.Tree as Class
#if !(MIN_VERSION_base(4,8,0))
import Data.Monoid ((<>))
#endif
import Data.Primitive.MutVar (MutVar)
import qualified Data.Primitive.MutVar as MutVar
import qualified Data.Tree as Tree
import Prelude hiding (concat, print)
import System.IO.Unsafe (unsafePerformIO)
import Unsafe.Coerce (unsafeCoerce)
data T s a v = T
, tLabel :: !a
, tValue :: !v
, tAgg :: !v
}
| NOTE ( jaspervdj ): There are two ways of indicating the parent / left /
Imagine that we are considering tLeft .
1 . We can set of x to the MutVar that holds the tree itself ( i.e. a
2 . We can set to some nil value .
nil :: Tree s a v
nil = unsafeCoerce $ unsafePerformIO $ fmap Tree $ MutVar.newMutVar undefined
# NOINLINE nil #
newtype Tree s a v = Tree {unTree :: MutVar s (T s a v)}
deriving (Eq)
singleton :: PrimMonad m => a -> v -> m (Tree (PrimState m) a v)
singleton tLabel tValue =
fmap Tree $ MutVar.newMutVar $! T nil nil nil tLabel tValue tValue
readRoot :: PrimMonad m => Tree (PrimState m) a v -> m (Tree (PrimState m) a v)
readRoot tree = do
T {..} <- MutVar.readMutVar (unTree tree)
if tParent == nil then return tree else readRoot tParent
cons
:: (PrimMonad m, Monoid v)
=> Tree (PrimState m) a v -> Tree (PrimState m) a v
-> m (Tree (PrimState m) a v)
cons lt@(Tree lv) rt@(Tree rv) = do
r <- MutVar.readMutVar rv
MutVar.modifyMutVar' lv $ \l -> l {tRight = rt, tAgg = tAgg l <> tAgg r}
MutVar.writeMutVar rv $! r {tParent = lt}
return lt
snoc
:: (PrimMonad m, Monoid v)
=> Tree (PrimState m) a v -> Tree (PrimState m) a v
-> m (Tree (PrimState m) a v)
snoc lt@(Tree lv) rt@(Tree rv) = do
l <- MutVar.readMutVar lv
MutVar.modifyMutVar' rv $ \r -> r {tLeft = lt, tAgg = tAgg l <> tAgg r}
MutVar.writeMutVar lv $! l {tParent = rt}
return rt
| Appends two trees . Returns the root of the tree .
append
:: (PrimMonad m, Monoid v)
=> Tree (PrimState m) a v
-> Tree (PrimState m) a v
-> m (Tree (PrimState m) a v)
append xt@(Tree _xv) yt@(Tree yv) = do
rmt@(Tree rmv) <- getRightMost xt
_ <- splay rmt
y <- MutVar.readMutVar yv
MutVar.modifyMutVar rmv $ \r -> r {tRight = yt, tAgg = tAgg r <> tAgg y}
MutVar.writeMutVar yv $! y {tParent = rmt}
return rmt
where
getRightMost tt@(Tree tv) = do
t <- MutVar.readMutVar tv
if tRight t == nil then return tt else getRightMost (tRight t)
split
:: (PrimMonad m, Monoid v)
=> Tree (PrimState m) a v
-> m (Maybe (Tree (PrimState m) a v), Maybe (Tree (PrimState m) a v))
split xt@(Tree xv) = do
_ <- splay xt
T {..} <- MutVar.readMutVar xv
when (tRight /= nil) (removeParent tRight)
MutVar.writeMutVar xv $ T {tAgg = tValue, ..}
removeLeft xt
removeRight xt
return
( if tLeft == nil then Nothing else Just tLeft
, if tRight == nil then Nothing else Just tRight
)
connected
:: (PrimMonad m, Monoid v)
=> Tree (PrimState m) a v
-> Tree (PrimState m) a v
-> m Bool
connected x y = do
_ <- splay x
x' <- splay y
return $ x == x'
root
:: (PrimMonad m, Monoid v)
=> Tree (PrimState m) a v
-> m (Tree (PrimState m) a v)
root x = do
_ <- splay x
return x
label
:: (PrimMonad m, Monoid v)
=> Tree (PrimState m) a v
-> m a
label (Tree xv) = tLabel <$> MutVar.readMutVar xv
aggregate
:: (PrimMonad m, Monoid v)
=> Tree (PrimState m) a v
-> m v
aggregate (Tree xv) = tAgg <$> MutVar.readMutVar xv
toList
:: PrimMonad m => Tree (PrimState m) a v -> m [a]
toList = go []
where
go acc0 (Tree tv) = do
T {..} <- MutVar.readMutVar tv
acc1 <- if tRight == nil then return acc0 else go acc0 tRight
let acc2 = tLabel : acc1
if tLeft == nil then return acc2 else go acc2 tLeft
splay
:: forall m a v. (PrimMonad m, Monoid v)
=> Tree (PrimState m) a v
splay xt@(Tree xv) = do
x0 <- MutVar.readMutVar xv
xla <- if tLeft x0 == nil then return mempty else tAgg <$> MutVar.readMutVar (unTree $ tLeft x0)
xra <- if tRight x0 == nil then return mempty else tAgg <$> MutVar.readMutVar (unTree $ tRight x0)
go xt xla xra x0
where
go :: Tree (PrimState m) a v -> v -> v -> T (PrimState m) a v
-> m (Tree (PrimState m) a v)
go closestToRootFound xla xra !x = do
let !(pt@(Tree pv)) = tParent x
if pt == nil then do
MutVar.writeMutVar xv x
return closestToRootFound
else do
p <- MutVar.readMutVar pv
let gt@(Tree gv) = tParent p
let plt@(Tree plv) = tLeft p
let prt@(Tree prv) = tRight p
let xlt@(Tree xlv) = tLeft x
let xrt@(Tree xrv) = tRight x
if | gt == nil, plt == xt -> do
ZIG ( Right )
> x
xr xr
when (xrt /= nil) $ MutVar.modifyMutVar' xrv $ \xr ->
xr {tParent = pt}
pra <- if prt == nil then return mempty else tAgg <$> MutVar.readMutVar prv
MutVar.writeMutVar pv $! p
{ tLeft = xrt
, tParent = xt
, tAgg = xra <> tValue p <> pra
}
MutVar.writeMutVar xv $! x
{ tAgg = tAgg p
, tRight = pt
, tParent = nil
}
return pt
| gt == nil -> do
ZIG ( Left )
xl xl
when (xlt /= nil) $ MutVar.modifyMutVar' xlv $ \xl ->
xl {tParent = pt}
pla <- if plt == nil then return mempty else tAgg <$> MutVar.readMutVar plv
MutVar.writeMutVar pv $! p
{ tRight = xlt
, tParent = xt
, tAgg = pla <> tValue p <> xla
}
MutVar.writeMutVar xv $! x
{ tAgg = tAgg p
, tLeft = pt
, tParent = nil
}
return pt
| otherwise -> do
g <- MutVar.readMutVar gv
let ggt@(Tree ggv) = tParent g
let glt@(Tree glv) = tLeft g
let grt@(Tree grv) = tRight g
when (ggt /= nil) $ MutVar.modifyMutVar' ggv $ \gg ->
if tLeft gg == gt
then gg {tLeft = xt}
else gg {tRight = xt}
if | plt == xt && glt == pt -> do
ZIGZIG ( Right ):
pra <- if prt == nil then return mempty else tAgg <$> MutVar.readMutVar prv
gra <- if grt == nil then return mempty else tAgg <$> MutVar.readMutVar grv
let !ga' = pra <> tValue g <> gra
when (prt /= nil) $ MutVar.modifyMutVar' prv $ \pr ->
pr {tParent = gt}
MutVar.writeMutVar gv $! g
{ tParent = pt
, tLeft = prt
, tAgg = ga'
}
when (xrt /= nil) $ MutVar.modifyMutVar' xrv $ \xr ->
xr {tParent = pt}
let !pa' = xra <> tValue p <> ga'
MutVar.writeMutVar pv $! p
{ tParent = xt
, tLeft = xrt
, tRight = gt
, tAgg = pa'
}
go gt xla pa' $! x
{ tRight = pt
, tAgg = tAgg g
, tParent = ggt
}
| plv /= xv && glv /= pv -> do
ZIGZIG ( Left ):
pl x g xl
xl pl
pla <- if plt == nil then return mempty else tAgg <$> MutVar.readMutVar plv
gla <- if glt == nil then return mempty else tAgg <$> MutVar.readMutVar glv
let !ga' = gla <> tValue g <> pla
when (plt /= nil) $ MutVar.modifyMutVar' plv $ \pl ->
pl {tParent = gt}
MutVar.writeMutVar gv $! g
{ tParent = pt
, tRight = plt
, tAgg = ga'
}
when (xlt /= nil) $ MutVar.modifyMutVar' xlv $ \xl ->
xl {tParent = pt}
let !pa' = ga' <> tValue p <> xla
MutVar.writeMutVar pv $! p
{ tParent = xt
, tLeft = gt
, tRight = xlt
, tAgg = pa'
}
go gt pa' xra $! x
{ tLeft = pt
, tAgg = tAgg g
, tParent = ggt
}
| plv == xv -> do
ZIGZIG ( Left ):
x
p =
x xl xr
xl xr
when (xlt /= nil) $ MutVar.modifyMutVar' xlv $ \xl ->
xl {tParent = gt}
gla <- if glt == nil then return mempty else tAgg <$> MutVar.readMutVar glv
let !ga' = gla <> tValue g <> xla
MutVar.writeMutVar gv $! g
{ tParent = xt
, tRight = xlt
, tAgg = ga'
}
when (xrt /= nil) $ MutVar.modifyMutVar' xrv $ \xr ->
xr {tParent = pt}
pra <- if prt == nil then return mempty else tAgg <$> MutVar.readMutVar prv
let pa' = xra <> tValue p <> pra
MutVar.writeMutVar pv $! p
{ tParent = xt
, tLeft = xrt
, tAgg = pa'
}
go gt ga' pa' $! x
{ tParent = ggt
, tLeft = gt
, tRight = pt
, tAgg = tAgg g
}
| otherwise -> do
ZIGZIG ( Right ):
x
x xl xr
xl xr
when (xrt /= nil) $ MutVar.modifyMutVar' xrv $ \xr ->
xr {tParent = gt}
gra <- if grt == nil then return mempty else tAgg <$> MutVar.readMutVar grv
let !ga' = xra <> tValue g <> gra
MutVar.writeMutVar gv $! g
{ tParent = xt
, tLeft = xrt
, tAgg = ga'
}
when (xlt /= nil) $ MutVar.modifyMutVar' xlv $ \xl ->
xl {tParent = pt}
pla <- if plt == nil then return mempty else tAgg <$> MutVar.readMutVar plv
let !pa' = pla <> tValue p <> xla
MutVar.writeMutVar pv $! p
{ tParent = xt
, tRight = xlt
, tAgg = pa'
}
go gt pa' ga' $! x
{ tParent = ggt
, tLeft = pt
, tRight = gt
, tAgg = tAgg g
}
removeParent, removeLeft, removeRight
:: PrimMonad m
-> m ()
removeParent (Tree x) = MutVar.modifyMutVar' x $ \x' -> x' {tParent = nil}
removeLeft (Tree x) = MutVar.modifyMutVar' x $ \x' -> x' {tLeft = nil}
removeRight (Tree x) = MutVar.modifyMutVar' x $ \x' -> x' {tRight = nil}
freeze :: PrimMonad m => Tree (PrimState m) a v -> m (Tree.Tree a)
freeze (Tree tv) = do
T {..} <- MutVar.readMutVar tv
children <- sequence $
[freeze tLeft | tLeft /= nil] ++
[freeze tRight | tRight /= nil]
return $ Tree.Node tLabel children
print :: Show a => Tree (PrimState IO) a v -> IO ()
print = go 0
where
go d (Tree tv) = do
T {..} <- MutVar.readMutVar tv
when (tLeft /= nil) $ go (d + 1) tLeft
putStrLn $ replicate d ' ' ++ show tLabel
when (tRight /= nil) $ go (d + 1) tRight
assertInvariants
:: (PrimMonad m, Monoid v, Eq v, Show v) => Tree (PrimState m) a v -> m ()
assertInvariants t = do
_ <- computeAgg nil t
return ()
where
computeAgg pt xt@(Tree xv) = do
x' <- MutVar.readMutVar xv
let p' = tParent x'
when (pt /= p') $ error "broken parent pointer"
let l = tLeft x'
let r = tRight x'
la <- if l == nil then return mempty else computeAgg xt l
ra <- if r == nil then return mempty else computeAgg xt r
let actualAgg = la <> (tValue x') <> ra
let storedAgg = tAgg x'
when (actualAgg /= storedAgg) $ error $
"error in stored aggregates: " ++ show storedAgg ++
", actual: " ++ show actualAgg
return actualAgg
data TreeGen s = TreeGen
instance Class.Tree Tree where
type TreeGen Tree = TreeGen
newTreeGen _ = return TreeGen
singleton _ = singleton
append = append
split = split
connected = connected
root = root
readRoot = readRoot
label = label
aggregate = aggregate
toList = toList
instance Class.TestTree Tree where
print = print
assertInvariants = assertInvariants
assertSingleton = \_ -> return ()
assertRoot = \_ -> return ()
|
42161011265010e40e8135c579bdf306136d1959accd3e8eea5c6d942fb0824f | BinaryAnalysisPlatform/bap | arm_branch.ml | open Core_kernel[@@warning "-D"]
open Bap.Std
open Or_error
open Arm_types
open Arm_utils
module Env = Arm_env
let pc_offset = Word.(of_int 8 ~width:32) (* PC is ahead by some bytes in ARM *)
let word = Word.of_int ~width:32
let lift operand ?link ?x:_ ?cond addr =
let target =
match operand with
| `Reg r -> Bil.var (Env.of_reg r)
| `Imm offset ->
let width = Word.bitwidth offset in
let _1 = Word.one 32 in
let min_32 = Word.Int_exn.(_1 lsl Word.of_int 31 ~width) in
let offset = if Word.equal offset min_32 then Word.zero 32 else offset in
let r = Word.Int_exn.(addr + pc_offset + offset) in
Bil.int r in
TODO detect change to thumb in ` x `
let jump_instr = [Bil.jmp target] in
let link_instr =
let next_addr = Word.Int_exn.(addr + pc_offset - word 4) in
match link with
| Some true -> [Bil.move Env.lr Bil.(int next_addr)]
| _ -> [] in
let stmts = link_instr @ jump_instr in
match cond with
| Some c -> exec stmts c
| None -> stmts
| null | https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap/253afc171bbfd0fe1b34f6442795dbf4b1798348/lib/arm/arm_branch.ml | ocaml | PC is ahead by some bytes in ARM | open Core_kernel[@@warning "-D"]
open Bap.Std
open Or_error
open Arm_types
open Arm_utils
module Env = Arm_env
let word = Word.of_int ~width:32
let lift operand ?link ?x:_ ?cond addr =
let target =
match operand with
| `Reg r -> Bil.var (Env.of_reg r)
| `Imm offset ->
let width = Word.bitwidth offset in
let _1 = Word.one 32 in
let min_32 = Word.Int_exn.(_1 lsl Word.of_int 31 ~width) in
let offset = if Word.equal offset min_32 then Word.zero 32 else offset in
let r = Word.Int_exn.(addr + pc_offset + offset) in
Bil.int r in
TODO detect change to thumb in ` x `
let jump_instr = [Bil.jmp target] in
let link_instr =
let next_addr = Word.Int_exn.(addr + pc_offset - word 4) in
match link with
| Some true -> [Bil.move Env.lr Bil.(int next_addr)]
| _ -> [] in
let stmts = link_instr @ jump_instr in
match cond with
| Some c -> exec stmts c
| None -> stmts
|
ab33e77a0eff8ee0710c9d8ac417958d6c2a91c5f8ed5e8922d5af566afefad6 | juspay/atlas | Handler.hs | |
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Module : API.Parking . Booking . BookingList . Handler
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Module : API.Parking.Booking.BookingList.Handler
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module API.Parking.Booking.BookingList.Handler where
import API.Parking.Booking.BookingList.Types
import App.Types
import Beckn.Prelude
import Beckn.Types.Id
import Beckn.Utils.Common
import Domain.Booking.API as Booking
import Domain.Booking.Type
import qualified Storage.Queries.Booking as QBooking
import qualified Storage.Queries.ParkingLocation as QPLocation
import qualified Storage.Queries.PaymentTransaction as QPT
import Tools.Auth
import Tools.Error
handler :: FlowServer API
handler = bookingList
bookingList :: PersonId -> Maybe Integer -> Maybe Integer -> FlowHandler Booking.BookingListRes
bookingList personId mbLimit mbOffset = withFlowHandlerAPI $ do
let limit = fromMaybe 10 mbLimit
offset = fromMaybe 0 mbOffset
bList <- QBooking.findAllByRequestorId personId limit offset
Booking.BookingListRes <$> traverse buildBookingListRes bList
buildBookingListRes :: EsqDBFlow m r => Booking -> m Booking.BookingAPIEntity
buildBookingListRes booking = do
location <- QPLocation.findById (Id booking.parkingSpaceLocationId) >>= fromMaybeM (ParkingLocationNotFound booking.parkingSpaceLocationId)
paymentTrans <- QPT.findByBookingId booking.id
return $ Booking.makeBookingAPIEntity booking location paymentTrans
| null | https://raw.githubusercontent.com/juspay/atlas/e64b227dc17887fb01c2554db21c08284d18a806/app/parking-bap/src/API/Parking/Booking/BookingList/Handler.hs | haskell | |
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Module : API.Parking . Booking . BookingList . Handler
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Module : API.Parking.Booking.BookingList.Handler
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module API.Parking.Booking.BookingList.Handler where
import API.Parking.Booking.BookingList.Types
import App.Types
import Beckn.Prelude
import Beckn.Types.Id
import Beckn.Utils.Common
import Domain.Booking.API as Booking
import Domain.Booking.Type
import qualified Storage.Queries.Booking as QBooking
import qualified Storage.Queries.ParkingLocation as QPLocation
import qualified Storage.Queries.PaymentTransaction as QPT
import Tools.Auth
import Tools.Error
handler :: FlowServer API
handler = bookingList
bookingList :: PersonId -> Maybe Integer -> Maybe Integer -> FlowHandler Booking.BookingListRes
bookingList personId mbLimit mbOffset = withFlowHandlerAPI $ do
let limit = fromMaybe 10 mbLimit
offset = fromMaybe 0 mbOffset
bList <- QBooking.findAllByRequestorId personId limit offset
Booking.BookingListRes <$> traverse buildBookingListRes bList
buildBookingListRes :: EsqDBFlow m r => Booking -> m Booking.BookingAPIEntity
buildBookingListRes booking = do
location <- QPLocation.findById (Id booking.parkingSpaceLocationId) >>= fromMaybeM (ParkingLocationNotFound booking.parkingSpaceLocationId)
paymentTrans <- QPT.findByBookingId booking.id
return $ Booking.makeBookingAPIEntity booking location paymentTrans
| |
cf8e64109ca50d3d4a825fabc24ae26421ffc0e8dd59a69107523d797f3d6464 | simoncourtenage/quanthas | Paths_QuantHas.hs | # LANGUAGE CPP #
# OPTIONS_GHC -fno - warn - missing - import - lists #
# OPTIONS_GHC -fno - warn - implicit - prelude #
module Paths_QuantHas (
version,
getBinDir, getLibDir, getDataDir, getLibexecDir,
getDataFileName, getSysconfDir
) where
import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
import Prelude
#if defined(VERSION_base)
#if MIN_VERSION_base(4,0,0)
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
#else
catchIO :: IO a -> (Exception.Exception -> IO a) -> IO a
#endif
#else
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
#endif
catchIO = Exception.catch
version :: Version
version = Version [0,0] []
bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath
bindir = "/Users/courtes/Library/Haskell/bin"
libdir = "/Users/courtes/Library/Haskell/ghc-8.0.1-x86_64/lib/QuantHas-0.0"
datadir = "/Users/courtes/Library/Haskell/share/ghc-8.0.1-x86_64/QuantHas-0.0"
libexecdir = "/Users/courtes/Library/Haskell/libexec"
sysconfdir = "/Users/courtes/Library/Haskell/etc"
getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath
getBinDir = catchIO (getEnv "QuantHas_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "QuantHas_libdir") (\_ -> return libdir)
getDataDir = catchIO (getEnv "QuantHas_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "QuantHas_libexecdir") (\_ -> return libexecdir)
getSysconfDir = catchIO (getEnv "QuantHas_sysconfdir") (\_ -> return sysconfdir)
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "/" ++ name)
| null | https://raw.githubusercontent.com/simoncourtenage/quanthas/6e0b2cc9a60bb7d1709f98ed10d09aa6c071c8dd/dist/build/autogen/Paths_QuantHas.hs | haskell | # LANGUAGE CPP #
# OPTIONS_GHC -fno - warn - missing - import - lists #
# OPTIONS_GHC -fno - warn - implicit - prelude #
module Paths_QuantHas (
version,
getBinDir, getLibDir, getDataDir, getLibexecDir,
getDataFileName, getSysconfDir
) where
import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
import Prelude
#if defined(VERSION_base)
#if MIN_VERSION_base(4,0,0)
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
#else
catchIO :: IO a -> (Exception.Exception -> IO a) -> IO a
#endif
#else
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
#endif
catchIO = Exception.catch
version :: Version
version = Version [0,0] []
bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath
bindir = "/Users/courtes/Library/Haskell/bin"
libdir = "/Users/courtes/Library/Haskell/ghc-8.0.1-x86_64/lib/QuantHas-0.0"
datadir = "/Users/courtes/Library/Haskell/share/ghc-8.0.1-x86_64/QuantHas-0.0"
libexecdir = "/Users/courtes/Library/Haskell/libexec"
sysconfdir = "/Users/courtes/Library/Haskell/etc"
getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath
getBinDir = catchIO (getEnv "QuantHas_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "QuantHas_libdir") (\_ -> return libdir)
getDataDir = catchIO (getEnv "QuantHas_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "QuantHas_libexecdir") (\_ -> return libexecdir)
getSysconfDir = catchIO (getEnv "QuantHas_sysconfdir") (\_ -> return sysconfdir)
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "/" ++ name)
| |
5d45c73832ae2a6ca0e89234a535a4004d2e2055de3d124fba85e27b27438c40 | emaphis/HtDP2e-solutions | ex081.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-reader.ss" "lang")((modname ex081) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
Ex . 81 :
;; Design the function time->seconds, which consumes instances of time
;; structures and produces the number of seconds that have passed since
;; midnight.
For example , if you are representing 12 hours , 30 minutes , and 2 seconds
with one of these structures and if you then apply time->seconds to this
instance , the correct result is 45002 .
(define-struct time [hours minutes seconds])
; timet is a (make-time Number Number Number))
interp : a point in time having hours , minutes , seconds
10:30
Time - > ? ? ?
(define (fn-for-time t)
(... (... (time-hours t))
(... (time-minutes t))
(... (time-seconds t))))
; Time -> Number
; convert a given time to seconds
(check-expect (time->seconds (make-time 0 0 0)) 0)
(check-expect (time->seconds (make-time 12 30 2)) 45002)
(check-expect (time->seconds TIME1) 37800)
;(define (time->seconds t) 0) ; stub
(define (time->seconds t)
(+ (* 3600 (time-hours t))
(* 60 (time-minutes t))
(time-seconds t)))
| null | https://raw.githubusercontent.com/emaphis/HtDP2e-solutions/ecb60b9a7bbf9b8999c0122b6ea152a3301f0a68/1-Fixed-Size-Data/05-Adding-Structure/ex081.rkt | racket | about the language level of this file in a form that our tools can easily process.
Design the function time->seconds, which consumes instances of time
structures and produces the number of seconds that have passed since
midnight.
timet is a (make-time Number Number Number))
Time -> Number
convert a given time to seconds
(define (time->seconds t) 0) ; stub | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-beginner-reader.ss" "lang")((modname ex081) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
Ex . 81 :
For example , if you are representing 12 hours , 30 minutes , and 2 seconds
with one of these structures and if you then apply time->seconds to this
instance , the correct result is 45002 .
(define-struct time [hours minutes seconds])
interp : a point in time having hours , minutes , seconds
10:30
Time - > ? ? ?
(define (fn-for-time t)
(... (... (time-hours t))
(... (time-minutes t))
(... (time-seconds t))))
(check-expect (time->seconds (make-time 0 0 0)) 0)
(check-expect (time->seconds (make-time 12 30 2)) 45002)
(check-expect (time->seconds TIME1) 37800)
(define (time->seconds t)
(+ (* 3600 (time-hours t))
(* 60 (time-minutes t))
(time-seconds t)))
|
2d283e407b1110a62d9ec0a5fd41a0c8bad92929925921c2855304b6931787df | ghcjs/jsaddle-dom | SVGTransformList.hs | # LANGUAGE PatternSynonyms #
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.SVGTransformList
(clear, initialize, initialize_, getItem, getItem_,
insertItemBefore, insertItemBefore_, replaceItem, replaceItem_,
removeItem, removeItem_, appendItem, appendItem_,
createSVGTransformFromMatrix, createSVGTransformFromMatrix_,
consolidate, consolidate_, getNumberOfItems, SVGTransformList(..),
gTypeSVGTransformList)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
-- | <-US/docs/Web/API/SVGTransformList.clear Mozilla SVGTransformList.clear documentation>
clear :: (MonadDOM m) => SVGTransformList -> m ()
clear self = liftDOM (void (self ^. jsf "clear" ()))
| < -US/docs/Web/API/SVGTransformList.initialize Mozilla SVGTransformList.initialize documentation >
initialize ::
(MonadDOM m) => SVGTransformList -> SVGTransform -> m SVGTransform
initialize self item
= liftDOM
((self ^. jsf "initialize" [toJSVal item]) >>= fromJSValUnchecked)
| < -US/docs/Web/API/SVGTransformList.initialize Mozilla SVGTransformList.initialize documentation >
initialize_ ::
(MonadDOM m) => SVGTransformList -> SVGTransform -> m ()
initialize_ self item
= liftDOM (void (self ^. jsf "initialize" [toJSVal item]))
| < -US/docs/Web/API/SVGTransformList.getItem Mozilla SVGTransformList.getItem documentation >
getItem ::
(MonadDOM m) => SVGTransformList -> Word -> m SVGTransform
getItem self index
= liftDOM
((self ^. jsf "getItem" [toJSVal index]) >>= fromJSValUnchecked)
| < -US/docs/Web/API/SVGTransformList.getItem Mozilla SVGTransformList.getItem documentation >
getItem_ :: (MonadDOM m) => SVGTransformList -> Word -> m ()
getItem_ self index
= liftDOM (void (self ^. jsf "getItem" [toJSVal index]))
| < -US/docs/Web/API/SVGTransformList.insertItemBefore Mozilla SVGTransformList.insertItemBefore documentation >
insertItemBefore ::
(MonadDOM m) =>
SVGTransformList -> SVGTransform -> Word -> m SVGTransform
insertItemBefore self item index
= liftDOM
((self ^. jsf "insertItemBefore" [toJSVal item, toJSVal index]) >>=
fromJSValUnchecked)
| < -US/docs/Web/API/SVGTransformList.insertItemBefore Mozilla SVGTransformList.insertItemBefore documentation >
insertItemBefore_ ::
(MonadDOM m) => SVGTransformList -> SVGTransform -> Word -> m ()
insertItemBefore_ self item index
= liftDOM
(void
(self ^. jsf "insertItemBefore" [toJSVal item, toJSVal index]))
| < -US/docs/Web/API/SVGTransformList.replaceItem Mozilla SVGTransformList.replaceItem documentation >
replaceItem ::
(MonadDOM m) =>
SVGTransformList -> SVGTransform -> Word -> m SVGTransform
replaceItem self item index
= liftDOM
((self ^. jsf "replaceItem" [toJSVal item, toJSVal index]) >>=
fromJSValUnchecked)
| < -US/docs/Web/API/SVGTransformList.replaceItem Mozilla SVGTransformList.replaceItem documentation >
replaceItem_ ::
(MonadDOM m) => SVGTransformList -> SVGTransform -> Word -> m ()
replaceItem_ self item index
= liftDOM
(void (self ^. jsf "replaceItem" [toJSVal item, toJSVal index]))
| < -US/docs/Web/API/SVGTransformList.removeItem Mozilla SVGTransformList.removeItem documentation >
removeItem ::
(MonadDOM m) => SVGTransformList -> Word -> m SVGTransform
removeItem self index
= liftDOM
((self ^. jsf "removeItem" [toJSVal index]) >>= fromJSValUnchecked)
| < -US/docs/Web/API/SVGTransformList.removeItem Mozilla SVGTransformList.removeItem documentation >
removeItem_ :: (MonadDOM m) => SVGTransformList -> Word -> m ()
removeItem_ self index
= liftDOM (void (self ^. jsf "removeItem" [toJSVal index]))
| < -US/docs/Web/API/SVGTransformList.appendItem Mozilla SVGTransformList.appendItem documentation >
appendItem ::
(MonadDOM m) => SVGTransformList -> SVGTransform -> m SVGTransform
appendItem self item
= liftDOM
((self ^. jsf "appendItem" [toJSVal item]) >>= fromJSValUnchecked)
| < -US/docs/Web/API/SVGTransformList.appendItem Mozilla SVGTransformList.appendItem documentation >
appendItem_ ::
(MonadDOM m) => SVGTransformList -> SVGTransform -> m ()
appendItem_ self item
= liftDOM (void (self ^. jsf "appendItem" [toJSVal item]))
| < -US/docs/Web/API/SVGTransformList.createSVGTransformFromMatrix Mozilla SVGTransformList.createSVGTransformFromMatrix documentation >
createSVGTransformFromMatrix ::
(MonadDOM m) => SVGTransformList -> SVGMatrix -> m SVGTransform
createSVGTransformFromMatrix self matrix
= liftDOM
((self ^. jsf "createSVGTransformFromMatrix" [toJSVal matrix]) >>=
fromJSValUnchecked)
| < -US/docs/Web/API/SVGTransformList.createSVGTransformFromMatrix Mozilla SVGTransformList.createSVGTransformFromMatrix documentation >
createSVGTransformFromMatrix_ ::
(MonadDOM m) => SVGTransformList -> SVGMatrix -> m ()
createSVGTransformFromMatrix_ self matrix
= liftDOM
(void
(self ^. jsf "createSVGTransformFromMatrix" [toJSVal matrix]))
| < -US/docs/Web/API/SVGTransformList.consolidate Mozilla SVGTransformList.consolidate documentation >
consolidate :: (MonadDOM m) => SVGTransformList -> m SVGTransform
consolidate self
= liftDOM ((self ^. jsf "consolidate" ()) >>= fromJSValUnchecked)
| < -US/docs/Web/API/SVGTransformList.consolidate Mozilla SVGTransformList.consolidate documentation >
consolidate_ :: (MonadDOM m) => SVGTransformList -> m ()
consolidate_ self = liftDOM (void (self ^. jsf "consolidate" ()))
| < -US/docs/Web/API/SVGTransformList.numberOfItems Mozilla SVGTransformList.numberOfItems documentation >
getNumberOfItems :: (MonadDOM m) => SVGTransformList -> m Word
getNumberOfItems self
= liftDOM
(round <$> ((self ^. js "numberOfItems") >>= valToNumber))
| null | https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/SVGTransformList.hs | haskell | For HasCallStack compatibility
# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #
| <-US/docs/Web/API/SVGTransformList.clear Mozilla SVGTransformList.clear documentation> | # LANGUAGE PatternSynonyms #
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.SVGTransformList
(clear, initialize, initialize_, getItem, getItem_,
insertItemBefore, insertItemBefore_, replaceItem, replaceItem_,
removeItem, removeItem_, appendItem, appendItem_,
createSVGTransformFromMatrix, createSVGTransformFromMatrix_,
consolidate, consolidate_, getNumberOfItems, SVGTransformList(..),
gTypeSVGTransformList)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
clear :: (MonadDOM m) => SVGTransformList -> m ()
clear self = liftDOM (void (self ^. jsf "clear" ()))
| < -US/docs/Web/API/SVGTransformList.initialize Mozilla SVGTransformList.initialize documentation >
initialize ::
(MonadDOM m) => SVGTransformList -> SVGTransform -> m SVGTransform
initialize self item
= liftDOM
((self ^. jsf "initialize" [toJSVal item]) >>= fromJSValUnchecked)
| < -US/docs/Web/API/SVGTransformList.initialize Mozilla SVGTransformList.initialize documentation >
initialize_ ::
(MonadDOM m) => SVGTransformList -> SVGTransform -> m ()
initialize_ self item
= liftDOM (void (self ^. jsf "initialize" [toJSVal item]))
| < -US/docs/Web/API/SVGTransformList.getItem Mozilla SVGTransformList.getItem documentation >
getItem ::
(MonadDOM m) => SVGTransformList -> Word -> m SVGTransform
getItem self index
= liftDOM
((self ^. jsf "getItem" [toJSVal index]) >>= fromJSValUnchecked)
| < -US/docs/Web/API/SVGTransformList.getItem Mozilla SVGTransformList.getItem documentation >
getItem_ :: (MonadDOM m) => SVGTransformList -> Word -> m ()
getItem_ self index
= liftDOM (void (self ^. jsf "getItem" [toJSVal index]))
| < -US/docs/Web/API/SVGTransformList.insertItemBefore Mozilla SVGTransformList.insertItemBefore documentation >
insertItemBefore ::
(MonadDOM m) =>
SVGTransformList -> SVGTransform -> Word -> m SVGTransform
insertItemBefore self item index
= liftDOM
((self ^. jsf "insertItemBefore" [toJSVal item, toJSVal index]) >>=
fromJSValUnchecked)
| < -US/docs/Web/API/SVGTransformList.insertItemBefore Mozilla SVGTransformList.insertItemBefore documentation >
insertItemBefore_ ::
(MonadDOM m) => SVGTransformList -> SVGTransform -> Word -> m ()
insertItemBefore_ self item index
= liftDOM
(void
(self ^. jsf "insertItemBefore" [toJSVal item, toJSVal index]))
| < -US/docs/Web/API/SVGTransformList.replaceItem Mozilla SVGTransformList.replaceItem documentation >
replaceItem ::
(MonadDOM m) =>
SVGTransformList -> SVGTransform -> Word -> m SVGTransform
replaceItem self item index
= liftDOM
((self ^. jsf "replaceItem" [toJSVal item, toJSVal index]) >>=
fromJSValUnchecked)
| < -US/docs/Web/API/SVGTransformList.replaceItem Mozilla SVGTransformList.replaceItem documentation >
replaceItem_ ::
(MonadDOM m) => SVGTransformList -> SVGTransform -> Word -> m ()
replaceItem_ self item index
= liftDOM
(void (self ^. jsf "replaceItem" [toJSVal item, toJSVal index]))
| < -US/docs/Web/API/SVGTransformList.removeItem Mozilla SVGTransformList.removeItem documentation >
removeItem ::
(MonadDOM m) => SVGTransformList -> Word -> m SVGTransform
removeItem self index
= liftDOM
((self ^. jsf "removeItem" [toJSVal index]) >>= fromJSValUnchecked)
| < -US/docs/Web/API/SVGTransformList.removeItem Mozilla SVGTransformList.removeItem documentation >
removeItem_ :: (MonadDOM m) => SVGTransformList -> Word -> m ()
removeItem_ self index
= liftDOM (void (self ^. jsf "removeItem" [toJSVal index]))
| < -US/docs/Web/API/SVGTransformList.appendItem Mozilla SVGTransformList.appendItem documentation >
appendItem ::
(MonadDOM m) => SVGTransformList -> SVGTransform -> m SVGTransform
appendItem self item
= liftDOM
((self ^. jsf "appendItem" [toJSVal item]) >>= fromJSValUnchecked)
| < -US/docs/Web/API/SVGTransformList.appendItem Mozilla SVGTransformList.appendItem documentation >
appendItem_ ::
(MonadDOM m) => SVGTransformList -> SVGTransform -> m ()
appendItem_ self item
= liftDOM (void (self ^. jsf "appendItem" [toJSVal item]))
| < -US/docs/Web/API/SVGTransformList.createSVGTransformFromMatrix Mozilla SVGTransformList.createSVGTransformFromMatrix documentation >
createSVGTransformFromMatrix ::
(MonadDOM m) => SVGTransformList -> SVGMatrix -> m SVGTransform
createSVGTransformFromMatrix self matrix
= liftDOM
((self ^. jsf "createSVGTransformFromMatrix" [toJSVal matrix]) >>=
fromJSValUnchecked)
| < -US/docs/Web/API/SVGTransformList.createSVGTransformFromMatrix Mozilla SVGTransformList.createSVGTransformFromMatrix documentation >
createSVGTransformFromMatrix_ ::
(MonadDOM m) => SVGTransformList -> SVGMatrix -> m ()
createSVGTransformFromMatrix_ self matrix
= liftDOM
(void
(self ^. jsf "createSVGTransformFromMatrix" [toJSVal matrix]))
| < -US/docs/Web/API/SVGTransformList.consolidate Mozilla SVGTransformList.consolidate documentation >
consolidate :: (MonadDOM m) => SVGTransformList -> m SVGTransform
consolidate self
= liftDOM ((self ^. jsf "consolidate" ()) >>= fromJSValUnchecked)
| < -US/docs/Web/API/SVGTransformList.consolidate Mozilla SVGTransformList.consolidate documentation >
consolidate_ :: (MonadDOM m) => SVGTransformList -> m ()
consolidate_ self = liftDOM (void (self ^. jsf "consolidate" ()))
| < -US/docs/Web/API/SVGTransformList.numberOfItems Mozilla SVGTransformList.numberOfItems documentation >
getNumberOfItems :: (MonadDOM m) => SVGTransformList -> m Word
getNumberOfItems self
= liftDOM
(round <$> ((self ^. js "numberOfItems") >>= valToNumber))
|
07f1b3feae305363798479882282fb8791f26b0456fbc6a896df496bdad6027c | ghcjs/ghcjs-boot | hGetLine003.hs | import System.IO
main = f stdin
where f h = do p <- hIsEOF h
if p then putStrLn "done"
else do l <- hGetLine h
putStrLn l
f h
| null | https://raw.githubusercontent.com/ghcjs/ghcjs-boot/8c549931da27ba9e607f77195208ec156c840c8a/boot/base/tests/IO/hGetLine003.hs | haskell | import System.IO
main = f stdin
where f h = do p <- hIsEOF h
if p then putStrLn "done"
else do l <- hGetLine h
putStrLn l
f h
| |
8135f247db2bd4b5c63e969c5486f1c268eda7f21c12e290585748064324a623 | threatgrid/asami | encoder.clj | (ns ^{:doc "Encodes and decodes data for storage. Clojure implementation"
:author "Paula Gearon"}
asami.durable.encoder
(:require [clojure.string :as s]
[asami.graph :as graph]
[asami.durable.codec :refer [byte-mask data-mask sbytes-shift len-nybble-shift utf8
long-type-mask date-type-mask inst-type-mask
sstr-type-mask skey-type-mask node-type-mask
boolean-true-bits boolean-false-bits]])
(:import [clojure.lang Keyword BigInt ISeq
IPersistentMap IPersistentVector PersistentVector
PersistentHashMap PersistentArrayMap PersistentTreeMap]
[java.io RandomAccessFile]
[java.math BigInteger BigDecimal]
[java.net URI]
[java.time Instant]
[java.util Date UUID]
[java.nio ByteBuffer]
[java.nio.charset Charset]))
;; Refer to asami.durable.codec for a description of the encoding implemented below
;; (set! *warn-on-reflection* true)
(def ^:dynamic *entity-offsets* nil)
(def ^:dynamic *current-offset* nil)
(def empty-bytes (byte-array 0))
(def type->code
{Long (byte 0)
Double (byte 1)
String (byte 2)
URI (byte 3)
ISeq (byte 4)
IPersistentMap (byte 5)
BigInt (byte 6)
BigInteger (byte 6)
BigDecimal (byte 7)
Date (byte 8)
Instant (byte 9)
Keyword (byte 10)
UUID (byte 11)
:blob (byte 12)
:xsd (byte 13)
:pojo (byte 14)
:internal (byte 15)})
(def
registered-xsd-types
"A map of types to encoding functions"
(atom {}))
(defn str-constructor?
"Tests if a class has a constructor that takes a string"
[c]
(try
(boolean (.getConstructor ^Class c (into-array Class [String])))
(catch Throwable _ false)))
(defn type-code
"Returns a code number for an object"
[o]
(if (bytes? o)
[(type->code :blob) identity]
(if-let [encoder (get @registered-xsd-types (type o))]
[(type->code :xsd) encoder]
(if (str-constructor? (type o))
[(type->code :pojo) (fn [obj] (.getBytes (str (.getName ^Class (type o)) " " obj) ^Charset utf8))]
(throw (ex-info (str "Don't know how to encode a: " (type o)) {:object o}))))))
(defn general-header
"Takes a type number and a length, and encodes to the general header style.
Lengths 0-255 [2r1110tttt length]
Lengths 256-32k [2r1111tttt (low-byte length) (high-byte length)]
Lengths 32k-2G [2r1111tttt (byte0 length) (byte1 length) (byte2 length) (byte3 length)]"
[t len]
(cond
(<= len 0xFF)
(byte-array [(bit-or 0xE0 t) len])
(<= len 0x7FFF)
(byte-array [(bit-or 0xF0 t) (bit-shift-right len 8) (bit-and 0xFF len)])
:default
(byte-array [(bit-or 0xF0 t)
(bit-and 0xFF (bit-shift-right len 24))
(bit-and 0xFF (bit-shift-right len 16))
(bit-and 0xFF (bit-shift-right len 8))
(bit-and 0xFF len)])))
;; to-counted-bytes is required by the recursive concattenation operation
(declare to-counted-bytes)
(defn concat-bytes
"Takes multiple byte arrays and returns an array with all of the bytes concattenated"
^bytes [bas]
(let [len (apply + (map alength bas))
output (byte-array len)]
(reduce (fn [offset arr]
(let [l (alength arr)]
(System/arraycopy arr 0 output offset l)
(+ offset l)))
0 bas)
output))
(def zero-array
"A single element byte array containing 0"
(byte-array [(byte 0)]))
(defprotocol FlatFile
(header [this len] "Returns a byte array containing a header")
(body [this] "Returns a byte array containing the encoded data")
(encapsulate-id [this] "Returns an ID that encapsulates the type")
(comparable [this] "Returns a version of this data that can be compared"))
(def ^:const max-short-long 0x07FFFFFFFFFFFFFF)
(def ^:const max-short-len 7)
(def ^:const milli-nano "Number of nanoseconds in a millisecond" 1000000)
(defn encapsulate-sstr
"Encapsulates a short string. If the string cannot be encapsulated, then return nil."
[^String s type-mask]
(when (<= (.length s) max-short-len)
(let [abytes (.getBytes s ^Charset utf8)
len (alength abytes)]
(when (<= len max-short-len)
(reduce (fn [v n]
(-> (aget abytes n)
(bit-and byte-mask)
(bit-shift-left (- sbytes-shift (* Byte/SIZE n)))
(bit-or v)))
;; start with the top byte set to the type nybble and the length
(bit-or type-mask (bit-shift-left len len-nybble-shift))
(range len))))))
(defn encapsulate-long
"Encapsulates a long value. If the long is too large to be encapsulated, then return nil."
[^long l]
(when (and (< l max-short-long) (> l min-short-long))
(bit-and data-mask l)))
(def ^:dynamic *number-bytes* nil)
(def ^:dynamic *number-buffer* nil)
(defn n-byte-number
"Returns an array of n bytes representing the number x.
Must be initialized for the current thread."
[^long n ^long x]
(.putLong *number-buffer* 0 x)
(let [ret (byte-array n)]
(System/arraycopy ^bytes *number-bytes* (int (- Long/BYTES n)) ret 0 (int n))
ret))
(defn num-bytes
"Determines the number of bytes that can hold a value.
From 2-4 tests, this preferences small numbers."
[^long n]
(let [f (neg? n)
nn (if f (dec (- n)) n)]
(if (<= nn 0x7FFF)
(if (<= nn 0x7F) 1 2)
(if (<= nn 0x7FFFFFFF)
(if (<= nn 0x7FFFFF) 3 4)
(if (<= nn 0x7FFFFFFFFFFF)
(if (<= nn 0x7FFFFFFFFF) 5 6)
(if (<= nn 0x7FFFFFFFFFFFFF) 7 8))))))
(def constant-length?
"The set of types that can be encoded in a constant number of bytes. Used for homogenous sequences."
#{Long Double Date Instant UUID})
(defn type-compare
"Provides a regular comparison of objects of potentially different types"
[a b]
(let [ta (type a)
tb (type b)]
(if (= ta tb)
(compare (comparable a) (comparable b))
(let [tan (type->code ta)
tab (type->code tb)]
(if (and tan tab)
(compare tan tab)
(compare (str ta) (str tb)))))))
(defn map-header
"Common function for encoding the header of the various map types"
[this len]
(general-header (type->code IPersistentMap) len))
(defn map-body
"Common function for encoding the body of the various map types"
[this]
;; If this is an identified object, then save its location
;; only look for keyword keys if unsorted, or keys are keywords
(let [sorted-map? (sorted? this)]
(when (or (not sorted-map?) (keyword? (ffirst this)))
(doseq [id-attr [:db/id :db/ident :id]]
(when-let [id (get this id-attr)]
(vswap! *entity-offsets* assoc id @*current-offset*))))
(body (apply concat (if sorted-map?
(seq this)
(sort-by first type-compare this))))))
(defn comparable-map
"Converts a map into a vector of the equivalent data, so it may be compared"
[m]
(into [] (sort-by first type-compare m)))
(extend-protocol FlatFile
String
(header [this len]
(if (< len 0x80)
(byte-array [len])
(general-header (type->code String) len)))
(body [^String this]
(.getBytes this ^Charset utf8))
(encapsulate-id [this]
(encapsulate-sstr this sstr-type-mask))
(comparable [this] this)
Boolean
(header [this len]
(throw (ex-info "Unexpected encoding of internal node" {:node this})))
(body [this]
(throw (ex-info "Unexpected encoding of internal node" {:node this})))
(encapsulate-id [this]
(if this boolean-true-bits boolean-false-bits))
(comparable [this] this)
URI
(header [this len]
(if (< len 0x40)
(byte-array [(bit-or 0x80 len)])
(general-header (type->code URI) len)))
(body [this]
(.getBytes (str this) ^Charset utf8))
(encapsulate-id [this] nil)
(comparable [this] this)
Keyword
(header [this len]
(if (< len 0x10)
(byte-array [(bit-or 0xC0 len)])
(general-header (type->code Keyword) len)))
(body [this]
(.getBytes (subs (str this) 1) ^Charset utf8))
(encapsulate-id [this]
(encapsulate-sstr (subs (str this) 1) skey-type-mask))
(comparable [this] this)
Long
(header [this len]
(assert (<= len Long/BYTES))
(byte-array [(bit-or 0xD0 len)]))
(body [^long this]
(let [n (num-bytes this)]
(n-byte-number n this)))
(encapsulate-id [this]
(when-let [v (encapsulate-long this)]
(bit-or long-type-mask v)))
(comparable [this] this)
Double
(header [this len]
(assert (= len Double/BYTES))
(byte-array [(bit-or 0xE0 (type->code Double))]))
(body [^double this]
(let [b (byte-array Double/BYTES)
bb (ByteBuffer/wrap b)]
(.putDouble bb 0 this)
b))
(encapsulate-id [this] nil)
(comparable [this] this)
BigInt
(header [this len]
(general-header (type->code BigInt) len))
(body [this]
(.toByteArray (biginteger this)))
(encapsulate-id [this] nil)
(comparable [this] this)
BigDecimal
(header [this len]
(general-header (type->code BigDecimal) len))
(body [^BigDecimal this]
(.getBytes (str this) ^Charset utf8))
(encapsulate-id [this] nil)
(comparable [this] this)
Date
(header [this len]
(assert (= len Long/BYTES))
(byte-array [(bit-or 0xE0 (type->code Date))]))
(body [^Date this]
(n-byte-number Long/BYTES (.getTime this)))
(encapsulate-id [this]
(when-let [v (encapsulate-long (.getTime ^Date this))]
(bit-or date-type-mask v)))
(comparable [this] this)
Instant
(header [this len]
(assert (= len (+ Long/BYTES Integer/BYTES)))
(byte-array [(bit-or 0xE0 (type->code Instant))]))
(body [^Instant this]
(let [b (byte-array (+ Long/BYTES Integer/BYTES))]
(doto (ByteBuffer/wrap b)
(.putLong 0 (.getEpochSecond this))
(.putInt Long/BYTES (.getNano this)))
b))
(encapsulate-id [this]
(when-let [v (and (zero? (mod (.getNano ^Instant this) milli-nano))
(encapsulate-long (.toEpochMilli ^Instant this)))]
(bit-or inst-type-mask v)))
(comparable [this] this)
UUID
(header [this len]
(assert (= len (* 2 Long/BYTES)))
(byte-array [(bit-or 0xE0 (type->code UUID))]))
(body [^UUID this]
(let [b (byte-array (* 2 Long/BYTES))]
(doto (ByteBuffer/wrap b)
(.putLong 0 (.getLeastSignificantBits this))
(.putLong Long/BYTES (.getMostSignificantBits this)))
b))
(encapsulate-id [this] nil)
(comparable [this] this)
ISeq
(header [this len]
(general-header (type->code ISeq) len))
(body [this]
(if-not (seq this)
empty-bytes
(let [fst (first this)
t (type fst)
homogeneous (and (constant-length? t) (every? #(instance? t %) this))
[elt-fn prefix] (if homogeneous
(if (= t Long)
(let [elt-len (apply max (map num-bytes this))
0xDllll is the header byte for longs
;; integer homogenous arrays store the number in the header, with nil bodies
[#(vector (n-byte-number elt-len %)) arr-hdr])
(let [arr-hdr (byte-array [(bit-or 0xE0 (type->code t))])] ;; 0xEtttt is the header byte for typed things
;; simple homogenous arrays store everything in the object header, with nil bodies
[#(vector (body %)) arr-hdr]))
[to-counted-bytes zero-array])
;; start counting the bytes that are going into the buffer
starting-offset @*current-offset*
2 bytes for a short header + 1 byte for the prefix array
result (->> this
;; like a mapv but records the lengths of the data as it iterates through the seq
(reduce (fn [arrays x]
(let [offset @*current-offset* ;; save the start, as the embedded objects will update this
[head body] (elt-fn x)]
;; regardless of what embedded objects have update the *current-offset* to, change it to the
;; start of the current object, plus its total size
(vreset! *current-offset* (+ offset (alength head) (if body (alength body) 0)))
;; add the bytes of this object to the overall result of byte arrays
(cond-> (conj! arrays head)
only add the body if there is one
(transient [prefix]))
persistent!
concat-bytes)
update-lengths (fn [m u]
(into {} (map (fn [[k v :as kv]]
(if (> v starting-offset) [k (+ v u)] kv))
m)))
rlen (alength result)]
;; correct offsets for longer headers
(cond
total 5 after the 2 already added
total 3 after the 2 already added
result)))
(encapsulate-id [this] nil)
(comparable [this] (if (vector? this) this (into [] this)))
PersistentVector
(header [this len] (header (or (seq this) '()) len))
(body [this] (body (or (seq this) '())))
(encapsulate-id [this] nil)
(comparable [this] this)
PersistentArrayMap
(header [this len] (map-header this len))
(body [this] (map-body this))
(encapsulate-id [this] nil)
(comparable [this] (comparable-map this))
PersistentHashMap
(header [this len] (map-header this len))
(body [this] (map-body this))
(encapsulate-id [this] nil)
(comparable [this] (comparable-map this))
PersistentTreeMap
(header [this len] (map-header this len))
(body [this] (map-body this))
(encapsulate-id [this] nil)
(comparable [this] (comparable-map this))
Object
(header [this len]
(let [tc (or (type->code (type this))
(first (type-code this)))]
(general-header tc len)))
(body [this]
(if-let [tc (type->code (type this))]
(.getBytes (str this) ^Charset utf8)
(if-let [[_ encoder] (type-code this)]
(encoder this))))
(encapsulate-id [this] nil)
(comparable [this] this)
asami.graph.InternalNode
(header [this len]
(throw (ex-info "Unexpected encoding of internal node" {:node this})))
(body [this]
(throw (ex-info "Unexpected encoding of internal node" {:node this})))
(encapsulate-id [^asami.graph.InternalNode this]
(bit-or node-type-mask (bit-and data-mask (.id this))))
(comparable [this] (.id this)))
(defn to-counted-bytes
"Returns a tuple of byte arrays, representing the header and the body"
[o]
(let [^bytes b (body o)]
[(header o (alength b)) b]))
(defn to-bytes
"Returns a tuple of byte arrays, representing the header and the body"
[o]
(binding [*entity-offsets* (volatile! {})
*current-offset* (volatile! 0)
*number-bytes* (byte-array Long/BYTES)]
(binding [*number-buffer* (ByteBuffer/wrap *number-bytes*)]
(conj (to-counted-bytes o) @*entity-offsets*))))
| null | https://raw.githubusercontent.com/threatgrid/asami/d3f1741ad368e25a3100eff280d38350b98cfe70/src/asami/durable/encoder.clj | clojure | Refer to asami.durable.codec for a description of the encoding implemented below
(set! *warn-on-reflection* true)
to-counted-bytes is required by the recursive concattenation operation
start with the top byte set to the type nybble and the length
If this is an identified object, then save its location
only look for keyword keys if unsorted, or keys are keywords
integer homogenous arrays store the number in the header, with nil bodies
0xEtttt is the header byte for typed things
simple homogenous arrays store everything in the object header, with nil bodies
start counting the bytes that are going into the buffer
like a mapv but records the lengths of the data as it iterates through the seq
save the start, as the embedded objects will update this
regardless of what embedded objects have update the *current-offset* to, change it to the
start of the current object, plus its total size
add the bytes of this object to the overall result of byte arrays
correct offsets for longer headers | (ns ^{:doc "Encodes and decodes data for storage. Clojure implementation"
:author "Paula Gearon"}
asami.durable.encoder
(:require [clojure.string :as s]
[asami.graph :as graph]
[asami.durable.codec :refer [byte-mask data-mask sbytes-shift len-nybble-shift utf8
long-type-mask date-type-mask inst-type-mask
sstr-type-mask skey-type-mask node-type-mask
boolean-true-bits boolean-false-bits]])
(:import [clojure.lang Keyword BigInt ISeq
IPersistentMap IPersistentVector PersistentVector
PersistentHashMap PersistentArrayMap PersistentTreeMap]
[java.io RandomAccessFile]
[java.math BigInteger BigDecimal]
[java.net URI]
[java.time Instant]
[java.util Date UUID]
[java.nio ByteBuffer]
[java.nio.charset Charset]))
(def ^:dynamic *entity-offsets* nil)
(def ^:dynamic *current-offset* nil)
(def empty-bytes (byte-array 0))
(def type->code
{Long (byte 0)
Double (byte 1)
String (byte 2)
URI (byte 3)
ISeq (byte 4)
IPersistentMap (byte 5)
BigInt (byte 6)
BigInteger (byte 6)
BigDecimal (byte 7)
Date (byte 8)
Instant (byte 9)
Keyword (byte 10)
UUID (byte 11)
:blob (byte 12)
:xsd (byte 13)
:pojo (byte 14)
:internal (byte 15)})
(def
registered-xsd-types
"A map of types to encoding functions"
(atom {}))
(defn str-constructor?
"Tests if a class has a constructor that takes a string"
[c]
(try
(boolean (.getConstructor ^Class c (into-array Class [String])))
(catch Throwable _ false)))
(defn type-code
"Returns a code number for an object"
[o]
(if (bytes? o)
[(type->code :blob) identity]
(if-let [encoder (get @registered-xsd-types (type o))]
[(type->code :xsd) encoder]
(if (str-constructor? (type o))
[(type->code :pojo) (fn [obj] (.getBytes (str (.getName ^Class (type o)) " " obj) ^Charset utf8))]
(throw (ex-info (str "Don't know how to encode a: " (type o)) {:object o}))))))
(defn general-header
"Takes a type number and a length, and encodes to the general header style.
Lengths 0-255 [2r1110tttt length]
Lengths 256-32k [2r1111tttt (low-byte length) (high-byte length)]
Lengths 32k-2G [2r1111tttt (byte0 length) (byte1 length) (byte2 length) (byte3 length)]"
[t len]
(cond
(<= len 0xFF)
(byte-array [(bit-or 0xE0 t) len])
(<= len 0x7FFF)
(byte-array [(bit-or 0xF0 t) (bit-shift-right len 8) (bit-and 0xFF len)])
:default
(byte-array [(bit-or 0xF0 t)
(bit-and 0xFF (bit-shift-right len 24))
(bit-and 0xFF (bit-shift-right len 16))
(bit-and 0xFF (bit-shift-right len 8))
(bit-and 0xFF len)])))
(declare to-counted-bytes)
(defn concat-bytes
"Takes multiple byte arrays and returns an array with all of the bytes concattenated"
^bytes [bas]
(let [len (apply + (map alength bas))
output (byte-array len)]
(reduce (fn [offset arr]
(let [l (alength arr)]
(System/arraycopy arr 0 output offset l)
(+ offset l)))
0 bas)
output))
(def zero-array
"A single element byte array containing 0"
(byte-array [(byte 0)]))
(defprotocol FlatFile
(header [this len] "Returns a byte array containing a header")
(body [this] "Returns a byte array containing the encoded data")
(encapsulate-id [this] "Returns an ID that encapsulates the type")
(comparable [this] "Returns a version of this data that can be compared"))
(def ^:const max-short-long 0x07FFFFFFFFFFFFFF)
(def ^:const max-short-len 7)
(def ^:const milli-nano "Number of nanoseconds in a millisecond" 1000000)
(defn encapsulate-sstr
"Encapsulates a short string. If the string cannot be encapsulated, then return nil."
[^String s type-mask]
(when (<= (.length s) max-short-len)
(let [abytes (.getBytes s ^Charset utf8)
len (alength abytes)]
(when (<= len max-short-len)
(reduce (fn [v n]
(-> (aget abytes n)
(bit-and byte-mask)
(bit-shift-left (- sbytes-shift (* Byte/SIZE n)))
(bit-or v)))
(bit-or type-mask (bit-shift-left len len-nybble-shift))
(range len))))))
(defn encapsulate-long
"Encapsulates a long value. If the long is too large to be encapsulated, then return nil."
[^long l]
(when (and (< l max-short-long) (> l min-short-long))
(bit-and data-mask l)))
(def ^:dynamic *number-bytes* nil)
(def ^:dynamic *number-buffer* nil)
(defn n-byte-number
"Returns an array of n bytes representing the number x.
Must be initialized for the current thread."
[^long n ^long x]
(.putLong *number-buffer* 0 x)
(let [ret (byte-array n)]
(System/arraycopy ^bytes *number-bytes* (int (- Long/BYTES n)) ret 0 (int n))
ret))
(defn num-bytes
"Determines the number of bytes that can hold a value.
From 2-4 tests, this preferences small numbers."
[^long n]
(let [f (neg? n)
nn (if f (dec (- n)) n)]
(if (<= nn 0x7FFF)
(if (<= nn 0x7F) 1 2)
(if (<= nn 0x7FFFFFFF)
(if (<= nn 0x7FFFFF) 3 4)
(if (<= nn 0x7FFFFFFFFFFF)
(if (<= nn 0x7FFFFFFFFF) 5 6)
(if (<= nn 0x7FFFFFFFFFFFFF) 7 8))))))
(def constant-length?
"The set of types that can be encoded in a constant number of bytes. Used for homogenous sequences."
#{Long Double Date Instant UUID})
(defn type-compare
"Provides a regular comparison of objects of potentially different types"
[a b]
(let [ta (type a)
tb (type b)]
(if (= ta tb)
(compare (comparable a) (comparable b))
(let [tan (type->code ta)
tab (type->code tb)]
(if (and tan tab)
(compare tan tab)
(compare (str ta) (str tb)))))))
(defn map-header
"Common function for encoding the header of the various map types"
[this len]
(general-header (type->code IPersistentMap) len))
(defn map-body
"Common function for encoding the body of the various map types"
[this]
(let [sorted-map? (sorted? this)]
(when (or (not sorted-map?) (keyword? (ffirst this)))
(doseq [id-attr [:db/id :db/ident :id]]
(when-let [id (get this id-attr)]
(vswap! *entity-offsets* assoc id @*current-offset*))))
(body (apply concat (if sorted-map?
(seq this)
(sort-by first type-compare this))))))
(defn comparable-map
"Converts a map into a vector of the equivalent data, so it may be compared"
[m]
(into [] (sort-by first type-compare m)))
(extend-protocol FlatFile
String
(header [this len]
(if (< len 0x80)
(byte-array [len])
(general-header (type->code String) len)))
(body [^String this]
(.getBytes this ^Charset utf8))
(encapsulate-id [this]
(encapsulate-sstr this sstr-type-mask))
(comparable [this] this)
Boolean
(header [this len]
(throw (ex-info "Unexpected encoding of internal node" {:node this})))
(body [this]
(throw (ex-info "Unexpected encoding of internal node" {:node this})))
(encapsulate-id [this]
(if this boolean-true-bits boolean-false-bits))
(comparable [this] this)
URI
(header [this len]
(if (< len 0x40)
(byte-array [(bit-or 0x80 len)])
(general-header (type->code URI) len)))
(body [this]
(.getBytes (str this) ^Charset utf8))
(encapsulate-id [this] nil)
(comparable [this] this)
Keyword
(header [this len]
(if (< len 0x10)
(byte-array [(bit-or 0xC0 len)])
(general-header (type->code Keyword) len)))
(body [this]
(.getBytes (subs (str this) 1) ^Charset utf8))
(encapsulate-id [this]
(encapsulate-sstr (subs (str this) 1) skey-type-mask))
(comparable [this] this)
Long
(header [this len]
(assert (<= len Long/BYTES))
(byte-array [(bit-or 0xD0 len)]))
(body [^long this]
(let [n (num-bytes this)]
(n-byte-number n this)))
(encapsulate-id [this]
(when-let [v (encapsulate-long this)]
(bit-or long-type-mask v)))
(comparable [this] this)
Double
(header [this len]
(assert (= len Double/BYTES))
(byte-array [(bit-or 0xE0 (type->code Double))]))
(body [^double this]
(let [b (byte-array Double/BYTES)
bb (ByteBuffer/wrap b)]
(.putDouble bb 0 this)
b))
(encapsulate-id [this] nil)
(comparable [this] this)
BigInt
(header [this len]
(general-header (type->code BigInt) len))
(body [this]
(.toByteArray (biginteger this)))
(encapsulate-id [this] nil)
(comparable [this] this)
BigDecimal
(header [this len]
(general-header (type->code BigDecimal) len))
(body [^BigDecimal this]
(.getBytes (str this) ^Charset utf8))
(encapsulate-id [this] nil)
(comparable [this] this)
Date
(header [this len]
(assert (= len Long/BYTES))
(byte-array [(bit-or 0xE0 (type->code Date))]))
(body [^Date this]
(n-byte-number Long/BYTES (.getTime this)))
(encapsulate-id [this]
(when-let [v (encapsulate-long (.getTime ^Date this))]
(bit-or date-type-mask v)))
(comparable [this] this)
Instant
(header [this len]
(assert (= len (+ Long/BYTES Integer/BYTES)))
(byte-array [(bit-or 0xE0 (type->code Instant))]))
(body [^Instant this]
(let [b (byte-array (+ Long/BYTES Integer/BYTES))]
(doto (ByteBuffer/wrap b)
(.putLong 0 (.getEpochSecond this))
(.putInt Long/BYTES (.getNano this)))
b))
(encapsulate-id [this]
(when-let [v (and (zero? (mod (.getNano ^Instant this) milli-nano))
(encapsulate-long (.toEpochMilli ^Instant this)))]
(bit-or inst-type-mask v)))
(comparable [this] this)
UUID
(header [this len]
(assert (= len (* 2 Long/BYTES)))
(byte-array [(bit-or 0xE0 (type->code UUID))]))
(body [^UUID this]
(let [b (byte-array (* 2 Long/BYTES))]
(doto (ByteBuffer/wrap b)
(.putLong 0 (.getLeastSignificantBits this))
(.putLong Long/BYTES (.getMostSignificantBits this)))
b))
(encapsulate-id [this] nil)
(comparable [this] this)
ISeq
(header [this len]
(general-header (type->code ISeq) len))
(body [this]
(if-not (seq this)
empty-bytes
(let [fst (first this)
t (type fst)
homogeneous (and (constant-length? t) (every? #(instance? t %) this))
[elt-fn prefix] (if homogeneous
(if (= t Long)
(let [elt-len (apply max (map num-bytes this))
0xDllll is the header byte for longs
[#(vector (n-byte-number elt-len %)) arr-hdr])
[#(vector (body %)) arr-hdr]))
[to-counted-bytes zero-array])
starting-offset @*current-offset*
2 bytes for a short header + 1 byte for the prefix array
result (->> this
(reduce (fn [arrays x]
[head body] (elt-fn x)]
(vreset! *current-offset* (+ offset (alength head) (if body (alength body) 0)))
(cond-> (conj! arrays head)
only add the body if there is one
(transient [prefix]))
persistent!
concat-bytes)
update-lengths (fn [m u]
(into {} (map (fn [[k v :as kv]]
(if (> v starting-offset) [k (+ v u)] kv))
m)))
rlen (alength result)]
(cond
total 5 after the 2 already added
total 3 after the 2 already added
result)))
(encapsulate-id [this] nil)
(comparable [this] (if (vector? this) this (into [] this)))
PersistentVector
(header [this len] (header (or (seq this) '()) len))
(body [this] (body (or (seq this) '())))
(encapsulate-id [this] nil)
(comparable [this] this)
PersistentArrayMap
(header [this len] (map-header this len))
(body [this] (map-body this))
(encapsulate-id [this] nil)
(comparable [this] (comparable-map this))
PersistentHashMap
(header [this len] (map-header this len))
(body [this] (map-body this))
(encapsulate-id [this] nil)
(comparable [this] (comparable-map this))
PersistentTreeMap
(header [this len] (map-header this len))
(body [this] (map-body this))
(encapsulate-id [this] nil)
(comparable [this] (comparable-map this))
Object
(header [this len]
(let [tc (or (type->code (type this))
(first (type-code this)))]
(general-header tc len)))
(body [this]
(if-let [tc (type->code (type this))]
(.getBytes (str this) ^Charset utf8)
(if-let [[_ encoder] (type-code this)]
(encoder this))))
(encapsulate-id [this] nil)
(comparable [this] this)
asami.graph.InternalNode
(header [this len]
(throw (ex-info "Unexpected encoding of internal node" {:node this})))
(body [this]
(throw (ex-info "Unexpected encoding of internal node" {:node this})))
(encapsulate-id [^asami.graph.InternalNode this]
(bit-or node-type-mask (bit-and data-mask (.id this))))
(comparable [this] (.id this)))
(defn to-counted-bytes
"Returns a tuple of byte arrays, representing the header and the body"
[o]
(let [^bytes b (body o)]
[(header o (alength b)) b]))
(defn to-bytes
"Returns a tuple of byte arrays, representing the header and the body"
[o]
(binding [*entity-offsets* (volatile! {})
*current-offset* (volatile! 0)
*number-bytes* (byte-array Long/BYTES)]
(binding [*number-buffer* (ByteBuffer/wrap *number-bytes*)]
(conj (to-counted-bytes o) @*entity-offsets*))))
|
bc1b07553ebd16c1075782f7510f3c6d46b995e804921fe057991a3ca73c22db | bennn/dissertation | array-sequence.rkt | #lang racket/base
(require (for-syntax racket/base)
typed/untyped-utils
typed-racket/base-env/prims
racket/unsafe/ops
"array-struct.rkt"
"utils.rkt"
(except-in "typed-array-sequence.rkt" in-array-indexes))
(require/untyped-contract
"typed-array-sequence.rkt"
[in-array-indexes ((Vectorof Integer) -> (Sequenceof (Vectorof Index)))])
(provide (rename-out [in-array-clause in-array]))
(define-sequence-syntax in-array-clause
(λ () #'in-array)
(λ (stx)
(syntax-case stx ()
[[(x) (_ arr-expr)]
(syntax/loc stx
[(x)
(:do-in
([(ds size dims js proc)
(plet: (A) ([arr : (Array A) arr-expr])
(cond [(array? arr)
(define ds (array-shape arr))
(define dims (vector-length ds))
(define size (array-size arr))
(define proc (unsafe-array-proc arr))
(define: js : Indexes (make-vector dims 0))
(values ds size dims js proc)]
[else
(raise-argument-error 'in-array "Array" arr)]))])
(void)
([j 0])
(unsafe-fx< j size)
([(x) (proc js)])
#true
#true
[(begin (next-indexes! ds dims js)
(unsafe-fx+ j 1))])])]
[[_ clause] (raise-syntax-error 'in-array "expected (in-array <Array>)" #'clause #'clause)])))
(define-sequence-syntax in-array-indexes-clause
(λ () #'in-array-indexes)
(λ (stx)
(syntax-case stx ()
[[(x) (_ ds-expr)]
(syntax/loc stx
[(x)
(:do-in
([(ds size dims js)
(let*: ([ds : In-Indexes ds-expr]
[ds : Indexes (check-array-shape
ds (λ () (raise-argument-error 'in-array-indexes "Indexes"
ds)))])
(define dims (vector-length ds))
(define size (array-shape-size ds))
(cond [(index? size) (define: js : Indexes (make-vector dims 0))
(values ds size dims js)]
[else (error 'in-array-indexes
"array size ~e (for shape ~e) is too large (is not an Index)"
size ds)]))])
(void)
([j 0])
(unsafe-fx< j size)
([(x) (vector-copy-all js)])
#true
#true
[(begin (next-indexes! ds dims js)
(unsafe-fx+ j 1))])])]
[[_ clause]
(raise-syntax-error 'in-array-indexes "expected (in-array-indexes <Indexes>)"
#'clause #'clause)])))
(define-sequence-syntax in-unsafe-array-indexes-clause
(λ () #'in-array-indexes)
(λ (stx)
(syntax-case stx ()
[[(x) (_ ds-expr)]
(syntax/loc stx
[(x)
(:do-in
([(ds size dims js)
(let: ([ds : Indexes ds-expr])
(define dims (vector-length ds))
(define size (array-shape-size ds))
(cond [(index? size) (define: js : Indexes (make-vector dims 0))
(values ds size dims js)]
[else (error 'in-array-indexes
"array size ~e (for shape ~e) is too large (is not an Index)"
size ds)]))])
(void)
([j 0])
(unsafe-fx< j size)
([(x) js])
#true
#true
[(begin (next-indexes! ds dims js)
(unsafe-fx+ j 1))])])]
[[_ clause]
(raise-syntax-error 'in-array-indexes "expected (in-unsafe-array-indexes <Indexes>)"
#'clause #'clause)])))
| null | https://raw.githubusercontent.com/bennn/dissertation/779bfe6f8fee19092849b7e2cfc476df33e9357b/dissertation/QA/math-test/array-map/transient/math/private/array/array-sequence.rkt | racket | #lang racket/base
(require (for-syntax racket/base)
typed/untyped-utils
typed-racket/base-env/prims
racket/unsafe/ops
"array-struct.rkt"
"utils.rkt"
(except-in "typed-array-sequence.rkt" in-array-indexes))
(require/untyped-contract
"typed-array-sequence.rkt"
[in-array-indexes ((Vectorof Integer) -> (Sequenceof (Vectorof Index)))])
(provide (rename-out [in-array-clause in-array]))
(define-sequence-syntax in-array-clause
(λ () #'in-array)
(λ (stx)
(syntax-case stx ()
[[(x) (_ arr-expr)]
(syntax/loc stx
[(x)
(:do-in
([(ds size dims js proc)
(plet: (A) ([arr : (Array A) arr-expr])
(cond [(array? arr)
(define ds (array-shape arr))
(define dims (vector-length ds))
(define size (array-size arr))
(define proc (unsafe-array-proc arr))
(define: js : Indexes (make-vector dims 0))
(values ds size dims js proc)]
[else
(raise-argument-error 'in-array "Array" arr)]))])
(void)
([j 0])
(unsafe-fx< j size)
([(x) (proc js)])
#true
#true
[(begin (next-indexes! ds dims js)
(unsafe-fx+ j 1))])])]
[[_ clause] (raise-syntax-error 'in-array "expected (in-array <Array>)" #'clause #'clause)])))
(define-sequence-syntax in-array-indexes-clause
(λ () #'in-array-indexes)
(λ (stx)
(syntax-case stx ()
[[(x) (_ ds-expr)]
(syntax/loc stx
[(x)
(:do-in
([(ds size dims js)
(let*: ([ds : In-Indexes ds-expr]
[ds : Indexes (check-array-shape
ds (λ () (raise-argument-error 'in-array-indexes "Indexes"
ds)))])
(define dims (vector-length ds))
(define size (array-shape-size ds))
(cond [(index? size) (define: js : Indexes (make-vector dims 0))
(values ds size dims js)]
[else (error 'in-array-indexes
"array size ~e (for shape ~e) is too large (is not an Index)"
size ds)]))])
(void)
([j 0])
(unsafe-fx< j size)
([(x) (vector-copy-all js)])
#true
#true
[(begin (next-indexes! ds dims js)
(unsafe-fx+ j 1))])])]
[[_ clause]
(raise-syntax-error 'in-array-indexes "expected (in-array-indexes <Indexes>)"
#'clause #'clause)])))
(define-sequence-syntax in-unsafe-array-indexes-clause
(λ () #'in-array-indexes)
(λ (stx)
(syntax-case stx ()
[[(x) (_ ds-expr)]
(syntax/loc stx
[(x)
(:do-in
([(ds size dims js)
(let: ([ds : Indexes ds-expr])
(define dims (vector-length ds))
(define size (array-shape-size ds))
(cond [(index? size) (define: js : Indexes (make-vector dims 0))
(values ds size dims js)]
[else (error 'in-array-indexes
"array size ~e (for shape ~e) is too large (is not an Index)"
size ds)]))])
(void)
([j 0])
(unsafe-fx< j size)
([(x) js])
#true
#true
[(begin (next-indexes! ds dims js)
(unsafe-fx+ j 1))])])]
[[_ clause]
(raise-syntax-error 'in-array-indexes "expected (in-unsafe-array-indexes <Indexes>)"
#'clause #'clause)])))
| |
bf1e0026fb5f409f2aea9c071dd93f7be7eb54f5f77a52dad84292384e830383 | ptal/AbSolute | tast.ml | Copyright 2019
This program is free software ; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation ; either
version 3 of the License , or ( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
Lesser General Public License for more details .
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. *)
open Bounds
open Core
open Lang
open Lang.Ast
open Ad_type
type tvariable = {
name: vname;
ty: Types.var_ty;
uid: ad_uid;
}
let string_of_tvar tv =
tv.name ^ ":" ^ (Types.string_of_ty tv.ty) ^ "@" ^ (string_of_int tv.uid)
type tformula = ad_uid * tformula_
and tformula_ =
| TFVar of vname
| TCmp of bconstraint
| TEquiv of tformula * tformula
| TImply of tformula * tformula
| TAnd of tformula * tformula
| TOr of tformula * tformula
| TNot of tformula
type tqformula =
| TQFFormula of tformula
| TExists of tvariable * tqformula
let rec tformula_to_formula (_,f) =
match f with
| TFVar v -> FVar v
| TCmp c -> Cmp c
| TEquiv(f1,f2) -> Equiv(tformula_to_formula f1, tformula_to_formula f2)
| TImply(f1,f2) -> Imply(tformula_to_formula f1, tformula_to_formula f2)
| TAnd(f1,f2) -> And(tformula_to_formula f1, tformula_to_formula f2)
| TOr(f1,f2) -> Or(tformula_to_formula f1, tformula_to_formula f2)
| TNot f1 -> Not (tformula_to_formula f1)
let rec tqformula_to_qformula = function
| TQFFormula f -> QFFormula (tformula_to_formula f)
| TExists(tv, qf) -> Exists (tv.name, tv.ty, tqformula_to_qformula qf)
let string_of_tformula' env tf =
let wrap uid parenthesis s =
if parenthesis then "(" ^ s ^ ")" ^ ":" ^ (string_of_int uid)
else s ^ ":" ^ (string_of_int uid) in
let rec aux (uid, f) =
match f with
| TFVar v -> wrap uid false v
| TCmp c -> wrap uid false (Pretty_print.string_of_constraint c)
| TAnd(tf1,tf2) -> binary_aux uid tf1 tf2 "/\\"
| TEquiv(tf1,tf2) -> binary_aux uid tf1 tf2 "<=>"
| TImply(tf1,tf2) -> binary_aux uid tf1 tf2 "=>"
| TOr(tf1,tf2) -> binary_aux uid tf1 tf2 "\\/"
| TNot tf1 -> wrap uid true ("not " ^ (aux tf1))
and binary_aux uid tf1 tf2 op =
wrap uid true ((aux tf1) ^ " " ^ op ^ " " ^ (aux tf2)) in
let rec top_aux (uid, f) =
match f with
| TAnd(tf1, tf2) -> (top_aux tf1) ^ (top_aux tf2)
| _ -> "constraint:" ^ (string_of_type env uid) ^ " " ^ (aux (uid,f)) ^ "\n" in
top_aux tf
let string_of_tformula adty tf =
let env = build_adenv adty in
(string_of_adty_env env) ^ (string_of_tformula' env tf)
let string_of_tqformula adty tqf =
let env = build_adenv adty in
let rec aux = function
| TExists(tv, tqf) ->
"var:" ^ (string_of_type env tv.uid) ^ ":" ^ (Types.string_of_ty tv.ty) ^ " " ^ tv.name ^ "\n" ^
aux tqf
| TQFFormula tf -> "\n" ^ (string_of_tformula' env tf)
in
(string_of_adty_env env) ^ "\n" ^ (aux tqf)
let ctrue = TCmp (zero, LEQ, zero)
let cfalse = TCmp (zero, LEQ, zero)
let ctrue' = (0, ctrue)
let cfalse' = (0, cfalse)
let ttrue = TQFFormula ctrue'
let tfalse = TQFFormula cfalse'
let vars_of_tformula tf =
let rec aux (_,f) =
match f with
| TCmp c -> Rewritting.vars_of_bconstraint c
| TFVar v -> [v]
| TEquiv (tf1, tf2) | TImply (tf1, tf2) | TAnd (tf1, tf2) | TOr (tf1, tf2) ->
(aux tf1)@(aux tf2)
| TNot tf -> aux tf
in List.sort_uniq compare (aux tf)
let quantify env tf =
let vars = vars_of_tformula tf in
let rec aux = function
| [] -> TQFFormula tf
| v::vars ->
let tqf = aux vars in
begin
match List.find_opt (fun tv -> tv.name = v) env with
| None -> tqf
| Some tv -> TExists (tv, tqf)
end
in aux vars
let rec quantifiers = function
| TQFFormula _ -> []
| TExists(tv,f) ->
let tvars = quantifiers f in
match List.find_opt (fun tv' -> tv.name = tv'.name) tvars with
| None -> tv::tvars
| Some tv' when tv.uid = tv'.uid && tv.ty = tv'.ty -> tvars
| Some tv' -> raise (Wrong_modelling
("Two quantifiers on variable `" ^ tv.name ^ "` with two distinct types (`"
^ (string_of_tvar tv) ^ "` and `" ^ (string_of_tvar tv') ^ "`."))
let rec quantifier_free_of = function
| TQFFormula tf -> tf
| TExists(_,tqf) -> quantifier_free_of tqf
let rec map_tformula next = function
| TQFFormula tqf -> TQFFormula (next tqf)
| TExists (tv,tqf) -> TExists (tv, map_tformula next tqf)
let merge_formula make qf1 qf2 =
let vars = (quantifiers qf1)@(quantifiers qf2) in
let qf =
map_tformula (fun f1 ->
quantifier_free_of (
map_tformula (fun f2 -> make f1 f2) qf2)) qf1
in
quantify vars (quantifier_free_of qf)
let rec q_conjunction uid = function
| qf1::[] -> qf1
| qf1::qfs ->
let qf2 = q_conjunction uid qfs in
merge_formula (fun f1 f2 -> (uid, TAnd(f1,f2))) qf1 qf2
| [] -> ttrue
let rec q_disjunction uid = function
| qf1::[] -> qf1
| qf1::qfs ->
let qf2 = q_disjunction uid qfs in
merge_formula (fun f1 f2 -> (uid, TOr(f1,f2))) qf1 qf2
| [] -> tfalse
let neg_formula luid tf =
let rec aux = function
| uid, TCmp(e1, EQ, e2) ->
luid, TOr((uid, TCmp(e1,LT,e2)), (uid, TCmp(e1, GT, e2)))
| uid, TCmp c -> uid, TCmp (Rewritting.neg_bconstraint c)
| uid, TFVar v -> uid, TNot (uid, TFVar v)
| _, TEquiv (tf1,tf2) -> luid, TEquiv (aux tf1, tf2)
| _, TImply (tf1,tf2) -> luid, TAnd (tf1, aux tf2)
| _, TAnd (tf1,tf2) -> luid, TOr (aux tf1, aux tf2)
| _, TOr (tf1,tf2) -> luid, TAnd (aux tf1, aux tf2)
| _, TNot tf -> tf
in aux tf
let replace_uid uid tf =
let rec aux (u, f) =
let uid = if u = fst tf then uid else u in
match f with
| TCmp c -> uid, TCmp c
| TFVar v -> uid, TFVar v
| TEquiv (tf1,tf2) -> uid, TEquiv (aux tf1, aux tf2)
| TImply (tf1,tf2) -> uid, TImply (aux tf1, aux tf2)
| TAnd (tf1,tf2) -> uid, TAnd (aux tf1, aux tf2)
| TOr (tf1,tf2) -> uid, TOr (aux tf1, aux tf2)
| TNot tf -> uid, TNot (aux tf)
in aux tf
let instantiate_vars vars tf =
let instantiate_vars_expr e =
Rewritting.replace_var_in_expr (fun v ->
try
let tvar, value = List.assoc v vars in
Cst (value, Types.to_concrete_ty tvar.ty)
with Not_found -> Var v
) e in
let rec aux (uid,f) =
match f with
| TCmp (e1,op,e2) ->
uid, TCmp(instantiate_vars_expr e1, op, instantiate_vars_expr e2)
| TFVar v ->
begin
try
let _, value = List.assoc v vars in
if Bound_rat.equal value Bound_rat.zero then
cfalse'
else ctrue'
with Not_found -> uid, TFVar v
end
| TEquiv (tf1,tf2) -> uid, TEquiv (aux tf1, aux tf2)
| TImply (tf1,tf2) -> uid, TImply (aux tf1, aux tf2)
| TAnd (tf1,tf2) -> uid, TAnd (aux tf1, aux tf2)
| TOr (tf1,tf2) -> uid, TOr (aux tf1, aux tf2)
| TNot tf -> uid, TNot (aux tf) in
aux tf
| null | https://raw.githubusercontent.com/ptal/AbSolute/469159d87e3a717499573c1e187e5cfa1b569829/src/lang/typing/tast.ml | ocaml | Copyright 2019
This program is free software ; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation ; either
version 3 of the License , or ( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
Lesser General Public License for more details .
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. *)
open Bounds
open Core
open Lang
open Lang.Ast
open Ad_type
type tvariable = {
name: vname;
ty: Types.var_ty;
uid: ad_uid;
}
let string_of_tvar tv =
tv.name ^ ":" ^ (Types.string_of_ty tv.ty) ^ "@" ^ (string_of_int tv.uid)
type tformula = ad_uid * tformula_
and tformula_ =
| TFVar of vname
| TCmp of bconstraint
| TEquiv of tformula * tformula
| TImply of tformula * tformula
| TAnd of tformula * tformula
| TOr of tformula * tformula
| TNot of tformula
type tqformula =
| TQFFormula of tformula
| TExists of tvariable * tqformula
let rec tformula_to_formula (_,f) =
match f with
| TFVar v -> FVar v
| TCmp c -> Cmp c
| TEquiv(f1,f2) -> Equiv(tformula_to_formula f1, tformula_to_formula f2)
| TImply(f1,f2) -> Imply(tformula_to_formula f1, tformula_to_formula f2)
| TAnd(f1,f2) -> And(tformula_to_formula f1, tformula_to_formula f2)
| TOr(f1,f2) -> Or(tformula_to_formula f1, tformula_to_formula f2)
| TNot f1 -> Not (tformula_to_formula f1)
let rec tqformula_to_qformula = function
| TQFFormula f -> QFFormula (tformula_to_formula f)
| TExists(tv, qf) -> Exists (tv.name, tv.ty, tqformula_to_qformula qf)
let string_of_tformula' env tf =
let wrap uid parenthesis s =
if parenthesis then "(" ^ s ^ ")" ^ ":" ^ (string_of_int uid)
else s ^ ":" ^ (string_of_int uid) in
let rec aux (uid, f) =
match f with
| TFVar v -> wrap uid false v
| TCmp c -> wrap uid false (Pretty_print.string_of_constraint c)
| TAnd(tf1,tf2) -> binary_aux uid tf1 tf2 "/\\"
| TEquiv(tf1,tf2) -> binary_aux uid tf1 tf2 "<=>"
| TImply(tf1,tf2) -> binary_aux uid tf1 tf2 "=>"
| TOr(tf1,tf2) -> binary_aux uid tf1 tf2 "\\/"
| TNot tf1 -> wrap uid true ("not " ^ (aux tf1))
and binary_aux uid tf1 tf2 op =
wrap uid true ((aux tf1) ^ " " ^ op ^ " " ^ (aux tf2)) in
let rec top_aux (uid, f) =
match f with
| TAnd(tf1, tf2) -> (top_aux tf1) ^ (top_aux tf2)
| _ -> "constraint:" ^ (string_of_type env uid) ^ " " ^ (aux (uid,f)) ^ "\n" in
top_aux tf
let string_of_tformula adty tf =
let env = build_adenv adty in
(string_of_adty_env env) ^ (string_of_tformula' env tf)
let string_of_tqformula adty tqf =
let env = build_adenv adty in
let rec aux = function
| TExists(tv, tqf) ->
"var:" ^ (string_of_type env tv.uid) ^ ":" ^ (Types.string_of_ty tv.ty) ^ " " ^ tv.name ^ "\n" ^
aux tqf
| TQFFormula tf -> "\n" ^ (string_of_tformula' env tf)
in
(string_of_adty_env env) ^ "\n" ^ (aux tqf)
let ctrue = TCmp (zero, LEQ, zero)
let cfalse = TCmp (zero, LEQ, zero)
let ctrue' = (0, ctrue)
let cfalse' = (0, cfalse)
let ttrue = TQFFormula ctrue'
let tfalse = TQFFormula cfalse'
let vars_of_tformula tf =
let rec aux (_,f) =
match f with
| TCmp c -> Rewritting.vars_of_bconstraint c
| TFVar v -> [v]
| TEquiv (tf1, tf2) | TImply (tf1, tf2) | TAnd (tf1, tf2) | TOr (tf1, tf2) ->
(aux tf1)@(aux tf2)
| TNot tf -> aux tf
in List.sort_uniq compare (aux tf)
let quantify env tf =
let vars = vars_of_tformula tf in
let rec aux = function
| [] -> TQFFormula tf
| v::vars ->
let tqf = aux vars in
begin
match List.find_opt (fun tv -> tv.name = v) env with
| None -> tqf
| Some tv -> TExists (tv, tqf)
end
in aux vars
let rec quantifiers = function
| TQFFormula _ -> []
| TExists(tv,f) ->
let tvars = quantifiers f in
match List.find_opt (fun tv' -> tv.name = tv'.name) tvars with
| None -> tv::tvars
| Some tv' when tv.uid = tv'.uid && tv.ty = tv'.ty -> tvars
| Some tv' -> raise (Wrong_modelling
("Two quantifiers on variable `" ^ tv.name ^ "` with two distinct types (`"
^ (string_of_tvar tv) ^ "` and `" ^ (string_of_tvar tv') ^ "`."))
let rec quantifier_free_of = function
| TQFFormula tf -> tf
| TExists(_,tqf) -> quantifier_free_of tqf
let rec map_tformula next = function
| TQFFormula tqf -> TQFFormula (next tqf)
| TExists (tv,tqf) -> TExists (tv, map_tformula next tqf)
let merge_formula make qf1 qf2 =
let vars = (quantifiers qf1)@(quantifiers qf2) in
let qf =
map_tformula (fun f1 ->
quantifier_free_of (
map_tformula (fun f2 -> make f1 f2) qf2)) qf1
in
quantify vars (quantifier_free_of qf)
let rec q_conjunction uid = function
| qf1::[] -> qf1
| qf1::qfs ->
let qf2 = q_conjunction uid qfs in
merge_formula (fun f1 f2 -> (uid, TAnd(f1,f2))) qf1 qf2
| [] -> ttrue
let rec q_disjunction uid = function
| qf1::[] -> qf1
| qf1::qfs ->
let qf2 = q_disjunction uid qfs in
merge_formula (fun f1 f2 -> (uid, TOr(f1,f2))) qf1 qf2
| [] -> tfalse
let neg_formula luid tf =
let rec aux = function
| uid, TCmp(e1, EQ, e2) ->
luid, TOr((uid, TCmp(e1,LT,e2)), (uid, TCmp(e1, GT, e2)))
| uid, TCmp c -> uid, TCmp (Rewritting.neg_bconstraint c)
| uid, TFVar v -> uid, TNot (uid, TFVar v)
| _, TEquiv (tf1,tf2) -> luid, TEquiv (aux tf1, tf2)
| _, TImply (tf1,tf2) -> luid, TAnd (tf1, aux tf2)
| _, TAnd (tf1,tf2) -> luid, TOr (aux tf1, aux tf2)
| _, TOr (tf1,tf2) -> luid, TAnd (aux tf1, aux tf2)
| _, TNot tf -> tf
in aux tf
let replace_uid uid tf =
let rec aux (u, f) =
let uid = if u = fst tf then uid else u in
match f with
| TCmp c -> uid, TCmp c
| TFVar v -> uid, TFVar v
| TEquiv (tf1,tf2) -> uid, TEquiv (aux tf1, aux tf2)
| TImply (tf1,tf2) -> uid, TImply (aux tf1, aux tf2)
| TAnd (tf1,tf2) -> uid, TAnd (aux tf1, aux tf2)
| TOr (tf1,tf2) -> uid, TOr (aux tf1, aux tf2)
| TNot tf -> uid, TNot (aux tf)
in aux tf
let instantiate_vars vars tf =
let instantiate_vars_expr e =
Rewritting.replace_var_in_expr (fun v ->
try
let tvar, value = List.assoc v vars in
Cst (value, Types.to_concrete_ty tvar.ty)
with Not_found -> Var v
) e in
let rec aux (uid,f) =
match f with
| TCmp (e1,op,e2) ->
uid, TCmp(instantiate_vars_expr e1, op, instantiate_vars_expr e2)
| TFVar v ->
begin
try
let _, value = List.assoc v vars in
if Bound_rat.equal value Bound_rat.zero then
cfalse'
else ctrue'
with Not_found -> uid, TFVar v
end
| TEquiv (tf1,tf2) -> uid, TEquiv (aux tf1, aux tf2)
| TImply (tf1,tf2) -> uid, TImply (aux tf1, aux tf2)
| TAnd (tf1,tf2) -> uid, TAnd (aux tf1, aux tf2)
| TOr (tf1,tf2) -> uid, TOr (aux tf1, aux tf2)
| TNot tf -> uid, TNot (aux tf) in
aux tf
| |
b95dff77beabc4571fe89ffbe8cc0fe1a100b6b3e413244fa98bc4d38971e84f | juxt/site | util.clj | Copyright © 2021 , JUXT LTD .
(ns juxt.site.alpha.util
(:require
[juxt.clojars-mirrors.nippy.v3v1v1.taoensso.nippy.utils :refer [freezable?]]))
(alias 'site (create-ns 'juxt.site.alpha))
(alias 'http (create-ns 'juxt.http.alpha))
(defn assoc-when-some [m k v]
(cond-> m v (assoc k v)))
TODO find out what is different about this compared to assoc - when - some above
(defn assoc-some
"Associates a key with a value in a map, if and only if the value is not nil."
([m k v]
(if (or (nil? v) (false? v)) m (assoc m k v)))
([m k v & kvs]
(reduce (fn [m [k v]] (assoc-some m k v))
(assoc-some m k v)
(partition 2 kvs))))
(defn hexdigest
"Returns the hex digest of an object.
computing entity-tags."
([input] (hexdigest input "SHA-256"))
([input hash-algo]
(let [hash (java.security.MessageDigest/getInstance hash-algo)]
(. hash update input)
(let [digest (.digest hash)]
(apply str (map #(format "%02x" (bit-and % 0xff)) digest))))))
(def mime-types
{"html" "text/html;charset=utf-8"
"js" "application/javascript"
"map" "application/json"
"css" "text/css"
"png" "image/png"
"adoc" "text/asciidoc"})
(defn paths
"Given a nested structure, return the paths to each leaf."
[form]
(if (coll? form)
(for [[k v] (if (map? form) form (map vector (range) form))
w (paths v)]
(cons k (if (coll? w) w [w])))
(list form)))
(comment
(for [path
(paths {:x {:y {:z [:a :b :c] :z2 [0 1 {:u {:v 1}}]}}
:p {:q {:r :s :t :u :y (fn [_] nil)}}})
:when (not (fn? (last path)))]
path))
(defn deep-replace
"Apply f to x, where x is a map value, collection member or scalar, anywhere in
the form's structure. This is similar, but not identical to,
clojure.walk/postwalk."
[form f]
(cond
(map? form) (reduce-kv (fn [acc k v] (assoc acc k (deep-replace v f))) {} form)
(vector? form) (mapv (fn [i] (deep-replace i f)) form)
(coll? form) (map (fn [i] (deep-replace i f)) form)
:else (f form)))
(comment
(deep-replace {:a :b :c [identity {:x [{:g [:a :b identity]}]}]} #(if (fn? %) :replaced %)))
(defn ->freezeable [form]
(deep-replace
form
(fn [form]
(cond-> form
(not (freezable? form))
((fn [_] ::site/unfreezable))))))
(defn etag [representation]
(format
"\"%s\""
(subs
(hexdigest
(cond
(::http/body representation)
(::http/body representation)
(::http/content representation)
(.getBytes (::http/content representation)
(get representation ::http/charset "UTF-8")))) 0 32)))
| null | https://raw.githubusercontent.com/juxt/site/ba44b0241931c5f2e2228aae68006a858333bc65/src/juxt/site/alpha/util.clj | clojure | Copyright © 2021 , JUXT LTD .
(ns juxt.site.alpha.util
(:require
[juxt.clojars-mirrors.nippy.v3v1v1.taoensso.nippy.utils :refer [freezable?]]))
(alias 'site (create-ns 'juxt.site.alpha))
(alias 'http (create-ns 'juxt.http.alpha))
(defn assoc-when-some [m k v]
(cond-> m v (assoc k v)))
TODO find out what is different about this compared to assoc - when - some above
(defn assoc-some
"Associates a key with a value in a map, if and only if the value is not nil."
([m k v]
(if (or (nil? v) (false? v)) m (assoc m k v)))
([m k v & kvs]
(reduce (fn [m [k v]] (assoc-some m k v))
(assoc-some m k v)
(partition 2 kvs))))
(defn hexdigest
"Returns the hex digest of an object.
computing entity-tags."
([input] (hexdigest input "SHA-256"))
([input hash-algo]
(let [hash (java.security.MessageDigest/getInstance hash-algo)]
(. hash update input)
(let [digest (.digest hash)]
(apply str (map #(format "%02x" (bit-and % 0xff)) digest))))))
(def mime-types
{"html" "text/html;charset=utf-8"
"js" "application/javascript"
"map" "application/json"
"css" "text/css"
"png" "image/png"
"adoc" "text/asciidoc"})
(defn paths
"Given a nested structure, return the paths to each leaf."
[form]
(if (coll? form)
(for [[k v] (if (map? form) form (map vector (range) form))
w (paths v)]
(cons k (if (coll? w) w [w])))
(list form)))
(comment
(for [path
(paths {:x {:y {:z [:a :b :c] :z2 [0 1 {:u {:v 1}}]}}
:p {:q {:r :s :t :u :y (fn [_] nil)}}})
:when (not (fn? (last path)))]
path))
(defn deep-replace
"Apply f to x, where x is a map value, collection member or scalar, anywhere in
the form's structure. This is similar, but not identical to,
clojure.walk/postwalk."
[form f]
(cond
(map? form) (reduce-kv (fn [acc k v] (assoc acc k (deep-replace v f))) {} form)
(vector? form) (mapv (fn [i] (deep-replace i f)) form)
(coll? form) (map (fn [i] (deep-replace i f)) form)
:else (f form)))
(comment
(deep-replace {:a :b :c [identity {:x [{:g [:a :b identity]}]}]} #(if (fn? %) :replaced %)))
(defn ->freezeable [form]
(deep-replace
form
(fn [form]
(cond-> form
(not (freezable? form))
((fn [_] ::site/unfreezable))))))
(defn etag [representation]
(format
"\"%s\""
(subs
(hexdigest
(cond
(::http/body representation)
(::http/body representation)
(::http/content representation)
(.getBytes (::http/content representation)
(get representation ::http/charset "UTF-8")))) 0 32)))
| |
6e3b9a7aa2596b3d372ae4c713e75c8c1a48852c4e717ab2f92c025e4deea34c | jaspervdj/advent-of-code | 14.hs | # LANGUAGE BangPatterns #
# LANGUAGE DeriveFunctor #
{-# LANGUAGE LambdaCase #-}
import AdventOfCode.Main
import qualified AdventOfCode.NanoParser as P
import Control.Applicative ((<|>))
import Data.Bits (shiftL, testBit)
import Data.List (foldl')
import Data.Monoid (Sum (..))
import Data.Word (Word64)
data Ternary = Z | O | X deriving (Eq)
instance Show Ternary where
show Z = "0"
show O = "1"
show X = "X"
toTernary :: Bool -> Ternary
toTernary x = if x then O else Z
data Trie a
= TV !a
| TZ !(Trie a)
| TO !(Trie a)
| TX !(Trie a)
| TZO !(Trie a) !(Trie a)
deriving (Functor, Show)
instance Foldable Trie where
foldMap f = \case
TV x -> f x
TZ tz -> foldMap f tz
TO to -> foldMap f to
TX tx -> let !s = foldMap f tx in s <> s
TZO tz to -> foldMap f tz <> foldMap f to
singleton :: [Ternary] -> a -> Trie a
singleton [] x = TV x
singleton (Z : ks) x = TZ $ singleton ks x
singleton (O : ks) x = TO $ singleton ks x
singleton (X : ks) x = TX $ singleton ks x
insert :: [Ternary] -> a -> Trie a -> Trie a
insert [] x _ = TV x
insert _ x (TV _) = TV x
insert (Z : ks) x (TZ tz) = TZ (insert ks x tz)
insert (Z : ks) x (TO to) = TZO (singleton ks x) to
insert (Z : ks) x (TX tx) = TZO (insert ks x tx) tx
insert (Z : ks) x (TZO tz to) = TZO (insert ks x tz) to
insert (O : ks) x (TZ tz) = TZO tz (singleton ks x)
insert (O : ks) x (TO to) = TO (insert ks x to)
insert (O : ks) x (TX tx) = TZO tx (insert ks x tx)
insert (O : ks) x (TZO tz to) = TZO tz (insert ks x to)
insert (X : ks) x (TZ tz) = TZO (insert ks x tz) (singleton ks x)
insert (X : ks) x (TO to) = TZO (singleton ks x) (insert ks x to)
insert (X : ks) x (TX tx) = TX (insert ks x tx)
insert (X : ks) x (TZO tz to) = TZO (insert ks x tz) (insert ks x to)
type Program = [Instruction]
data Instruction
= SetMask [Ternary]
| SetMem !Word64 !Word64
deriving (Show)
wordSize :: Int
wordSize = 36
wordToBinary :: Word64 -> [Bool]
wordToBinary w = [testBit w i | i <- [wordSize - 1, wordSize - 2 .. 0]]
binaryToWord :: [Bool] -> Word64
binaryToWord = foldl' (\acc x -> (acc `shiftL` 1) + if x then 1 else 0) 0
parseProgram :: P.Parser Char Program
parseProgram = P.sepBy (setMask <|> setMem) (P.char '\n')
where
setMask = SetMask . mkMask <$> (P.string "mask = " *> P.many1 mc)
setMem = SetMem
<$> (P.string "mem[" *> P.decimal <* P.string "] = ")
<*> P.decimal
mc = P.satisfy "mask" (`elem` "01X")
mkMask = map (\case '0' -> Z; '1' -> O; _ -> X)
runProgram
:: ([Ternary] -> Word64 -> Word64 -> ([Ternary], Word64))
-> Program -> Word64
runProgram f = maybe 0 (getSum . foldMap Sum) . fst . foldl' step (Nothing, [])
where
step (tree, _) (SetMask m) = (tree, m)
step (tree, mask) (SetMem a x) =
let (ks, val) = f mask a x in
(Just (maybe (singleton ks val) (insert ks val) tree), mask)
part1 :: Program -> Word64
part1 = runProgram $ \mask addr val ->
( map toTernary $ wordToBinary addr
, binaryToWord . zipWith f mask $ wordToBinary val
)
where
f X a = a
f Z _ = False
f O _ = True
part2 :: Program -> Word64
part2 = runProgram $ \mask addr val ->
(zipWith f mask . map toTernary $ wordToBinary addr, val)
where
f X _ = X
f Z a = a
f O _ = O
main :: IO ()
main = pureMain $ \input -> do
program <- P.runParser parseProgram input
pure (pure $ part1 program, pure $ part2 program)
| null | https://raw.githubusercontent.com/jaspervdj/advent-of-code/bdc9628d1495d4e7fdbd9cea2739b929f733e751/2020/14.hs | haskell | # LANGUAGE LambdaCase # | # LANGUAGE BangPatterns #
# LANGUAGE DeriveFunctor #
import AdventOfCode.Main
import qualified AdventOfCode.NanoParser as P
import Control.Applicative ((<|>))
import Data.Bits (shiftL, testBit)
import Data.List (foldl')
import Data.Monoid (Sum (..))
import Data.Word (Word64)
data Ternary = Z | O | X deriving (Eq)
instance Show Ternary where
show Z = "0"
show O = "1"
show X = "X"
toTernary :: Bool -> Ternary
toTernary x = if x then O else Z
data Trie a
= TV !a
| TZ !(Trie a)
| TO !(Trie a)
| TX !(Trie a)
| TZO !(Trie a) !(Trie a)
deriving (Functor, Show)
instance Foldable Trie where
foldMap f = \case
TV x -> f x
TZ tz -> foldMap f tz
TO to -> foldMap f to
TX tx -> let !s = foldMap f tx in s <> s
TZO tz to -> foldMap f tz <> foldMap f to
singleton :: [Ternary] -> a -> Trie a
singleton [] x = TV x
singleton (Z : ks) x = TZ $ singleton ks x
singleton (O : ks) x = TO $ singleton ks x
singleton (X : ks) x = TX $ singleton ks x
insert :: [Ternary] -> a -> Trie a -> Trie a
insert [] x _ = TV x
insert _ x (TV _) = TV x
insert (Z : ks) x (TZ tz) = TZ (insert ks x tz)
insert (Z : ks) x (TO to) = TZO (singleton ks x) to
insert (Z : ks) x (TX tx) = TZO (insert ks x tx) tx
insert (Z : ks) x (TZO tz to) = TZO (insert ks x tz) to
insert (O : ks) x (TZ tz) = TZO tz (singleton ks x)
insert (O : ks) x (TO to) = TO (insert ks x to)
insert (O : ks) x (TX tx) = TZO tx (insert ks x tx)
insert (O : ks) x (TZO tz to) = TZO tz (insert ks x to)
insert (X : ks) x (TZ tz) = TZO (insert ks x tz) (singleton ks x)
insert (X : ks) x (TO to) = TZO (singleton ks x) (insert ks x to)
insert (X : ks) x (TX tx) = TX (insert ks x tx)
insert (X : ks) x (TZO tz to) = TZO (insert ks x tz) (insert ks x to)
type Program = [Instruction]
data Instruction
= SetMask [Ternary]
| SetMem !Word64 !Word64
deriving (Show)
wordSize :: Int
wordSize = 36
wordToBinary :: Word64 -> [Bool]
wordToBinary w = [testBit w i | i <- [wordSize - 1, wordSize - 2 .. 0]]
binaryToWord :: [Bool] -> Word64
binaryToWord = foldl' (\acc x -> (acc `shiftL` 1) + if x then 1 else 0) 0
parseProgram :: P.Parser Char Program
parseProgram = P.sepBy (setMask <|> setMem) (P.char '\n')
where
setMask = SetMask . mkMask <$> (P.string "mask = " *> P.many1 mc)
setMem = SetMem
<$> (P.string "mem[" *> P.decimal <* P.string "] = ")
<*> P.decimal
mc = P.satisfy "mask" (`elem` "01X")
mkMask = map (\case '0' -> Z; '1' -> O; _ -> X)
runProgram
:: ([Ternary] -> Word64 -> Word64 -> ([Ternary], Word64))
-> Program -> Word64
runProgram f = maybe 0 (getSum . foldMap Sum) . fst . foldl' step (Nothing, [])
where
step (tree, _) (SetMask m) = (tree, m)
step (tree, mask) (SetMem a x) =
let (ks, val) = f mask a x in
(Just (maybe (singleton ks val) (insert ks val) tree), mask)
part1 :: Program -> Word64
part1 = runProgram $ \mask addr val ->
( map toTernary $ wordToBinary addr
, binaryToWord . zipWith f mask $ wordToBinary val
)
where
f X a = a
f Z _ = False
f O _ = True
part2 :: Program -> Word64
part2 = runProgram $ \mask addr val ->
(zipWith f mask . map toTernary $ wordToBinary addr, val)
where
f X _ = X
f Z a = a
f O _ = O
main :: IO ()
main = pureMain $ \input -> do
program <- P.runParser parseProgram input
pure (pure $ part1 program, pure $ part2 program)
|
3df795361bcee93b51c6761c62b74d05b3b05b7bc7298b2231c4853e335731a7 | returntocorp/semgrep | Matching_report.ml |
*
* Copyright ( C ) 2013 Facebook
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation , with the
* special exception on linking described in file LICENSE .
*
* This library is distributed in the hope that it will be useful , but
* WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the file
* LICENSE for more details .
*
* Copyright (C) 2013 Facebook
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation, with the
* special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file
* LICENSE for more details.
*)
open Common
module PI = Parse_info
(*****************************************************************************)
(* Prelude *)
(*****************************************************************************)
(*****************************************************************************)
(* Types *)
(*****************************************************************************)
type match_format =
ex : tests / misc / foo4.php:3
* foo (
* 1 ,
* 2 ) ;
* foo(
* 1,
* 2);
*)
| Normal
(* ex: tests/misc/foo4.php:3: foo( *)
| Emacs
(* ex: tests/misc/foo4.php:3: foo(1,2) *)
| OneLine
(*****************************************************************************)
(* Helpers *)
(*****************************************************************************)
When we print in the OneLine format we want to normalize the matched
* expression or code and so only print the tokens in the AST ( and not
* the extra whitespace , newlines or comments ) . It 's not enough though
* to just List.map str_of_info because some PHP expressions such as
* ' $ x = print FOO ' would then be transformed into $ x = printFOO , hence
* this function
* expression or code and so only print the tokens in the AST (and not
* the extra whitespace, newlines or comments). It's not enough though
* to just List.map str_of_info because some PHP expressions such as
* '$x = print FOO' would then be transformed into $x=printFOO, hence
* this function
*)
let rec join_with_space_if_needed xs =
match xs with
| [] -> ""
| [ x ] -> x
| x :: y :: xs ->
if x =~ ".*[a-zA-Z0-9_]$" && y =~ "^[a-zA-Z0-9_]" then
x ^ " " ^ join_with_space_if_needed (y :: xs)
else x ^ join_with_space_if_needed (y :: xs)
TODO ? slow , and maybe we should cache it to avoid rereading
* each time the same file for each match .
* Note that the returned lines do not contain .
* each time the same file for each match.
* Note that the returned lines do not contain \n.
*)
let lines_of_file (start_line, end_line) file : string list =
let arr = Common2.cat_array file in
let lines = Common2.enum start_line end_line in
lines |> Common.map (fun i -> arr.(i))
(*****************************************************************************)
(* Entry point *)
(*****************************************************************************)
let print_match ?(format = Normal) ?(str = "") ?(spaces = 0) ii =
try
let mini, maxi = PI.min_max_ii_by_pos ii in
let end_line, _, _ =
Parsing_helpers.get_token_end_info (PI.unsafe_token_location_of_info maxi)
in
let file, line = (PI.file_of_info mini, PI.line_of_info mini) in
let prefix = spf "%s:%d" file line in
let lines_str = lines_of_file (PI.line_of_info mini, end_line) file in
match format with
| Normal ->
let prefix = if str = "" then prefix else prefix ^ " " ^ str in
let spaces_string = String.init spaces (fun _ -> ' ') in
pr (spaces_string ^ prefix);
(* todo? some context too ? *)
lines_str |> List.iter (fun s -> pr (spaces_string ^ " " ^ s))
(* bugfix: do not add extra space after ':', otherwise M-x wgrep will not work *)
| Emacs -> pr (prefix ^ ":" ^ List.hd lines_str)
| OneLine ->
pr
(prefix ^ ": "
^ (ii |> Common.map PI.str_of_info |> join_with_space_if_needed))
with
| Failure "get_pos: Ab or FakeTok" ->
pr "<could not locate match, FakeTok or AbstractTok>"
| null | https://raw.githubusercontent.com/returntocorp/semgrep/dea6ebd8e95d696c04b53c10e019f72dd8908a83/src/reporting/Matching_report.ml | ocaml | ***************************************************************************
Prelude
***************************************************************************
***************************************************************************
Types
***************************************************************************
ex: tests/misc/foo4.php:3: foo(
ex: tests/misc/foo4.php:3: foo(1,2)
***************************************************************************
Helpers
***************************************************************************
***************************************************************************
Entry point
***************************************************************************
todo? some context too ?
bugfix: do not add extra space after ':', otherwise M-x wgrep will not work |
*
* Copyright ( C ) 2013 Facebook
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation , with the
* special exception on linking described in file LICENSE .
*
* This library is distributed in the hope that it will be useful , but
* WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the file
* LICENSE for more details .
*
* Copyright (C) 2013 Facebook
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation, with the
* special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file
* LICENSE for more details.
*)
open Common
module PI = Parse_info
type match_format =
ex : tests / misc / foo4.php:3
* foo (
* 1 ,
* 2 ) ;
* foo(
* 1,
* 2);
*)
| Normal
| Emacs
| OneLine
When we print in the OneLine format we want to normalize the matched
* expression or code and so only print the tokens in the AST ( and not
* the extra whitespace , newlines or comments ) . It 's not enough though
* to just List.map str_of_info because some PHP expressions such as
* ' $ x = print FOO ' would then be transformed into $ x = printFOO , hence
* this function
* expression or code and so only print the tokens in the AST (and not
* the extra whitespace, newlines or comments). It's not enough though
* to just List.map str_of_info because some PHP expressions such as
* '$x = print FOO' would then be transformed into $x=printFOO, hence
* this function
*)
let rec join_with_space_if_needed xs =
match xs with
| [] -> ""
| [ x ] -> x
| x :: y :: xs ->
if x =~ ".*[a-zA-Z0-9_]$" && y =~ "^[a-zA-Z0-9_]" then
x ^ " " ^ join_with_space_if_needed (y :: xs)
else x ^ join_with_space_if_needed (y :: xs)
TODO ? slow , and maybe we should cache it to avoid rereading
* each time the same file for each match .
* Note that the returned lines do not contain .
* each time the same file for each match.
* Note that the returned lines do not contain \n.
*)
let lines_of_file (start_line, end_line) file : string list =
let arr = Common2.cat_array file in
let lines = Common2.enum start_line end_line in
lines |> Common.map (fun i -> arr.(i))
let print_match ?(format = Normal) ?(str = "") ?(spaces = 0) ii =
try
let mini, maxi = PI.min_max_ii_by_pos ii in
let end_line, _, _ =
Parsing_helpers.get_token_end_info (PI.unsafe_token_location_of_info maxi)
in
let file, line = (PI.file_of_info mini, PI.line_of_info mini) in
let prefix = spf "%s:%d" file line in
let lines_str = lines_of_file (PI.line_of_info mini, end_line) file in
match format with
| Normal ->
let prefix = if str = "" then prefix else prefix ^ " " ^ str in
let spaces_string = String.init spaces (fun _ -> ' ') in
pr (spaces_string ^ prefix);
lines_str |> List.iter (fun s -> pr (spaces_string ^ " " ^ s))
| Emacs -> pr (prefix ^ ":" ^ List.hd lines_str)
| OneLine ->
pr
(prefix ^ ": "
^ (ii |> Common.map PI.str_of_info |> join_with_space_if_needed))
with
| Failure "get_pos: Ab or FakeTok" ->
pr "<could not locate match, FakeTok or AbstractTok>"
|
3c46c335e4d305abbd8dff7654b61faf249e6f11b60b8b01654620cf0cc8576d | janestreet/bonsai | protocol.mli | open! Core
open! Async_rpc_kernel
module Message_stream : sig
val t : (unit, Message.t, unit) Rpc.Pipe_rpc.t
end
module Messages_request : sig
val t : (Room.t, Message.t list) Rpc.Rpc.t
end
module Send_message : sig
val t : (Message.t, unit Or_error.t) Rpc.Rpc.t
end
module Create_room : sig
val t : (Room.t, unit Or_error.t) Rpc.Rpc.t
end
module List_rooms : sig
val t : (unit, Room.t list) Rpc.Rpc.t
end
| null | https://raw.githubusercontent.com/janestreet/bonsai/761d04847d5f947318b64c0a46dffa17ad413536/examples/open_source/rpc_chat/common/protocol.mli | ocaml | open! Core
open! Async_rpc_kernel
module Message_stream : sig
val t : (unit, Message.t, unit) Rpc.Pipe_rpc.t
end
module Messages_request : sig
val t : (Room.t, Message.t list) Rpc.Rpc.t
end
module Send_message : sig
val t : (Message.t, unit Or_error.t) Rpc.Rpc.t
end
module Create_room : sig
val t : (Room.t, unit Or_error.t) Rpc.Rpc.t
end
module List_rooms : sig
val t : (unit, Room.t list) Rpc.Rpc.t
end
| |
05ce22f9916d31108635ee004e03707229910c68e8e6e2d2602b1bb6243a8cc8 | craigfe/compact | uniform_array.ml | — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Copyright ( c ) 2016–2020 Jane Street Group , LLC < >
Copyright ( c ) 2020–2021 < >
Distributed under the MIT license . See terms at the end of this file .
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Copyright (c) 2016–2020 Jane Street Group, LLC <>
Copyright (c) 2020–2021 Craig Ferguson <>
Distributed under the MIT license. See terms at the end of this file.
————————————————————————————————————————————————————————————————————————————*)
* Code in this module has been extracted from [ base ] library ,
and modified to add support for [ Tuple2 ] and [ Tuple3 ] specialisations .
and modified to add support for [Tuple2] and [Tuple3] specialisations. *)
open! Import
include Uniform_array_intf
module type Trusted = sig
type ('a, 'b, 'c) t
type ('a, 'b, 'c) elt
type ('a, 'b, 'c, 'inner) with_elt
val empty : (_, _, _) t
val unsafe_create_uninitialized : len:int -> (_, _, _) t
val create_obj_array : len:int -> (_, _, _) t
val create : len:int -> ('a, 'b, 'c, ('a, 'b, 'c) t) with_elt
val singleton : ('a, 'b, 'c, ('a, 'b, 'c) t) with_elt
val get : ('a, 'b, 'c) t -> int -> ('a, 'b, 'c) elt
val set : ('a, 'b, 'c) t -> int -> ('a, 'b, 'c, unit) with_elt
val swap : (_, _, _) t -> int -> int -> unit
val unsafe_get : ('a, 'b, 'c) t -> int -> ('a, 'b, 'c) elt
val unsafe_set : ('a, 'b, 'c) t -> int -> ('a, 'b, 'c, unit) with_elt
val unsafe_set_omit_phys_equal_check :
('a, 'b, 'c) t -> int -> ('a, 'b, 'c, unit) with_elt
val unsafe_set_int : (_, _, _) t -> int -> (int, int, int, unit) with_elt
val unsafe_set_int_assuming_currently_int :
(_, _, _) t -> int -> (int, int, int, unit) with_elt
val unsafe_set_assuming_currently_int :
(_, _, _) t -> int -> (Obj.t, Obj.t, Obj.t, unit) with_elt
val length : (_, _, _) t -> int
val unsafe_blit :
src:('a, 'b, 'c) t
-> src_pos:int
-> dst:('a, 'b, 'c) t
-> dst_pos:int
-> len:int
-> unit
val unsafe_clear_if_pointer : (_, _, _) t -> int -> unit
end
(* WARNING:
We use non-memory-safe things throughout the [Trusted] module.
Most of it is only safe in combination with the type signature (e.g. exposing
[val copy : 'a t -> 'b t] would be a big mistake). *)
module Trusted : sig
type 'a t
include
Trusted
with type ('a, _, _) t := 'a t
and type ('a, _, _) elt := 'a
and type ('a, _, _, 'inner) with_elt := 'a -> 'inner
end = struct
type 'a t = Obj_array.t
let empty = Obj_array.empty
let unsafe_create_uninitialized ~len = Obj_array.create_zero ~len
let create_obj_array ~len = Obj_array.create_zero ~len
let create ~len x = Obj_array.create ~len (Obj.repr x)
let singleton x = Obj_array.singleton (Obj.repr x)
let swap t i j = Obj_array.swap t i j
let get arr i = Obj.obj (Obj_array.get arr i)
let set arr i x = Obj_array.set arr i (Obj.repr x)
let unsafe_get arr i = Obj.obj (Obj_array.unsafe_get arr i)
let unsafe_set arr i x = Obj_array.unsafe_set arr i (Obj.repr x)
let unsafe_set_int arr i x = Obj_array.unsafe_set_int arr i x
let unsafe_set_int_assuming_currently_int arr i x =
Obj_array.unsafe_set_int_assuming_currently_int arr i x
let unsafe_set_assuming_currently_int arr i x =
Obj_array.unsafe_set_assuming_currently_int arr i (Obj.repr x)
let length = Obj_array.length
let unsafe_blit = Obj_array.unsafe_blit
let unsafe_set_omit_phys_equal_check t i x =
Obj_array.unsafe_set_omit_phys_equal_check t i (Obj.repr x)
let unsafe_clear_if_pointer = Obj_array.unsafe_clear_if_pointer
end
include Trusted
let init l ~f =
if l < 0 then invalid_arg "Uniform_array.init"
else
let res = unsafe_create_uninitialized ~len:l in
for i = 0 to l - 1 do
unsafe_set res i (f i)
done;
res
let of_array arr = init ~f:(Array.unsafe_get arr) (Array.length arr)
let map a ~f = init ~f:(fun i -> f (unsafe_get a i)) (length a)
let map_inplace a ~f =
for i = 0 to length a - 1 do
unsafe_set a i (f (unsafe_get a i))
done
let iter a ~f =
for i = 0 to length a - 1 do
f (unsafe_get a i)
done
let iteri a ~f =
for i = 0 to length a - 1 do
f i (unsafe_get a i)
done
let invariant inv_a t =
assert (Obj.tag (Obj.repr t) <> Obj.double_array_tag);
iter t ~f:inv_a
let to_list t = List.init ~f:(get t) ~len:(length t)
let of_list l =
let len = List.length l in
let res = unsafe_create_uninitialized ~len in
List.iteri l ~f:(fun i x -> set res i x);
res
let of_list_rev l =
match l with
| [] -> empty
| a :: l ->
let len = 1 + List.length l in
let t = create ~len a in
let r = ref l in
(* We start at [len - 2] because we already put [a] at [t.(len - 1)]. *)
for i = len - 2 downto 0 do
match !r with
| [] -> assert false
| a :: l ->
unsafe_set t i a;
r := l
done;
t
(* It is not safe for [to_array] to be the identity function because we have code that
relies on [float array]s being unboxed, for example in [bin_write_array]. *)
let to_array t = Array.init (length t) ~f:(fun i -> unsafe_get t i)
let exists t ~f =
let rec loop t ~f i =
if i < 0 then false else f (unsafe_get t i) || loop t ~f (i - 1)
in
loop t ~f (length t - 1)
let map2_exn t1 t2 ~f =
let len = length t1 in
if length t2 <> len then invalid_arg "Array.map2_exn";
init len ~f:(fun i -> f (unsafe_get t1 i) (unsafe_get t2 i))
let fold t ~init ~f =
let r = ref init in
for i = 0 to length t - 1 do
r := f !r (unsafe_get t i)
done;
!r
module Tuple2 = struct
(** See {!Trusted} above. *)
module Trusted : sig
type ('a, 'b) t
include
Trusted
with type ('a, 'b, _) t := ('a, 'b) t
and type ('a, 'b, _) elt := 'a * 'b
and type ('a, 'b, _, 'inner) with_elt := 'a -> 'b -> 'inner
val get_fst : ('a, _) t -> int -> 'a
val get_snd : (_, 'b) t -> int -> 'b
val set_fst : ('a, _) t -> int -> 'a -> unit
val set_snd : (_, 'b) t -> int -> 'b -> unit
val unsafe_get_fst : ('a, _) t -> int -> 'a
val unsafe_get_snd : (_, 'b) t -> int -> 'b
val unsafe_set_fst : ('a, _) t -> int -> 'a -> unit
val unsafe_set_snd : (_, 'b) t -> int -> 'b -> unit
end = struct
type ('a, 'b) t = Obj_array.t
let entry_size = 2
let empty = Obj_array.empty
let unsafe_create_uninitialized ~len =
Obj_array.create_zero ~len:(len * entry_size)
let create_obj_array ~len = Obj_array.create_zero ~len:(len * entry_size)
let create ~len x y =
let t = unsafe_create_uninitialized ~len:(len * entry_size) in
for i = 0 to len - 1 do
Obj_array.unsafe_set t (entry_size * i) (Obj.repr x);
Obj_array.unsafe_set t ((entry_size * i) + 1) (Obj.repr y)
done;
t
let singleton x y = create ~len:1 x y
let swap t i j =
Obj_array.swap t (entry_size * i) (entry_size * j);
Obj_array.swap t ((entry_size * i) + 1) ((entry_size * j) + 1)
let get_fst arr i = Obj.obj (Obj_array.get arr (entry_size * i))
let get_snd arr i = Obj.obj (Obj_array.get arr ((entry_size * i) + 1))
let get arr i = (get_fst arr i, get_snd arr i)
let set_fst arr i x = Obj_array.set arr (entry_size * i) (Obj.repr x)
let set_snd arr i y = Obj_array.set arr ((entry_size * i) + 1) (Obj.repr y)
let set arr i x y =
set_fst arr i x;
set_snd arr i y
let unsafe_get_fst arr i =
Obj.obj (Obj_array.unsafe_get arr (entry_size * i))
let unsafe_get_snd arr i =
Obj.obj (Obj_array.unsafe_get arr ((entry_size * i) + 1))
let unsafe_get arr i = (unsafe_get_fst arr i, unsafe_get_snd arr i)
let unsafe_set_fst arr i x =
Obj_array.unsafe_set arr (entry_size * i) (Obj.repr x)
let unsafe_set_snd arr i y =
Obj_array.unsafe_set arr ((entry_size * i) + 1) (Obj.repr y)
let unsafe_set arr i x y =
unsafe_set_fst arr i x;
unsafe_set_snd arr i y
let length t = Obj_array.length t / entry_size
let unsafe_blit ~src ~src_pos ~dst ~dst_pos ~len =
Obj_array.unsafe_blit ~src ~src_pos:(entry_size * src_pos) ~dst
~dst_pos:(entry_size * dst_pos) ~len:(entry_size * len)
let unsafe_set_omit_phys_equal_check t i x y =
Obj_array.unsafe_set_omit_phys_equal_check t (entry_size * i) (Obj.repr x);
Obj_array.unsafe_set_omit_phys_equal_check t
((entry_size * i) + 1)
(Obj.repr y)
let unsafe_set_int arr i x y =
Obj_array.unsafe_set_int arr (entry_size * i) x;
Obj_array.unsafe_set_int arr ((entry_size * i) + 1) y
let unsafe_set_int_assuming_currently_int arr i x y =
Obj_array.unsafe_set_int_assuming_currently_int arr (entry_size * i) x;
Obj_array.unsafe_set_int_assuming_currently_int arr
((entry_size * i) + 1)
y
let unsafe_set_assuming_currently_int arr i x y =
Obj_array.unsafe_set_assuming_currently_int arr (entry_size * i) x;
Obj_array.unsafe_set_assuming_currently_int arr ((entry_size * i) + 1) y
let unsafe_clear_if_pointer arr i =
Obj_array.unsafe_clear_if_pointer arr (entry_size * i);
Obj_array.unsafe_clear_if_pointer arr ((entry_size * i) + 1)
end
include Trusted
let init l ~f =
if l < 0 then invalid_arg "Uniform_array.init"
else
let res = unsafe_create_uninitialized ~len:l in
for i = 0 to l - 1 do
let x, y = f i in
unsafe_set res i x y
done;
res
let of_array arr = init ~f:(Array.unsafe_get arr) (Array.length arr)
let map a ~f =
init ~f:(fun i -> f (unsafe_get_fst a i) (unsafe_get_snd a i)) (length a)
let map_inplace a ~f =
for i = 0 to length a - 1 do
let x, y = f (unsafe_get_fst a i) (unsafe_get_snd a i) in
unsafe_set a i x y
done
let iter a ~f =
for i = 0 to length a - 1 do
f (unsafe_get_fst a i) (unsafe_get_snd a i)
done
let iteri a ~f =
for i = 0 to length a - 1 do
f i (unsafe_get_fst a i) (unsafe_get_snd a i)
done
let invariant inv_elt t =
assert (Obj.tag (Obj.repr t) <> Obj.double_array_tag);
iter t ~f:(fun a b -> inv_elt (a, b))
let to_list t = List.init ~f:(get t) ~len:(length t)
let of_list l =
let len = List.length l in
let res = unsafe_create_uninitialized ~len in
List.iteri l ~f:(fun i (x, y) -> unsafe_set res i x y);
res
let of_list_rev l =
match l with
| [] -> empty
| (a, b) :: l ->
let len = 1 + List.length l in
let t = unsafe_create_uninitialized ~len in
unsafe_set_fst t (len - 1) a;
unsafe_set_snd t (len - 1) b;
let r = ref l in
(* We start at [len - 2] because we already put [a] at [t.(len - 1)]. *)
for i = len - 2 downto 0 do
match !r with
| [] -> assert false
| (a, b) :: l ->
unsafe_set_fst t i a;
unsafe_set_snd t i b;
r := l
done;
t
(* It is not safe for [to_array] to be the identity function because we have code that
relies on [float array]s being unboxed, for example in [bin_write_array]. *)
let to_array t = Array.init (length t) ~f:(fun i -> unsafe_get t i)
let exists t ~f =
let rec loop t ~f i =
if i < 0 then false
else f (unsafe_get_fst t i) (unsafe_get_snd t i) || loop t ~f (i - 1)
in
loop t ~f (length t - 1)
let map2_exn t1 t2 ~f =
let len = length t1 in
if length t2 <> len then invalid_arg "Array.map2_exn";
init len ~f:(fun i ->
f (unsafe_get_fst t1 i) (unsafe_get_snd t1 i) (unsafe_get_fst t2 i)
(unsafe_get_snd t2 i))
let fold t ~init ~f =
let r = ref init in
for i = 0 to length t - 1 do
r := f !r (unsafe_get_fst t i) (unsafe_get_snd t i)
done;
!r
end
module Tuple3 = struct
(** See {!Trusted} above. *)
module Trusted : sig
type ('a, 'b, 'c) t
include
Trusted
with type ('a, 'b, 'c) t := ('a, 'b, 'c) t
and type ('a, 'b, 'c) elt := 'a * 'b * 'c
and type ('a, 'b, 'c, 'inner) with_elt := 'a -> 'b -> 'c -> 'inner
val get_fst : ('a, _, _) t -> int -> 'a
val get_snd : (_, 'b, _) t -> int -> 'b
val get_thd : (_, _, 'c) t -> int -> 'c
val set_fst : ('a, _, _) t -> int -> 'a -> unit
val set_snd : (_, 'b, _) t -> int -> 'b -> unit
val set_thd : (_, _, 'c) t -> int -> 'c -> unit
val unsafe_get_fst : ('a, _, _) t -> int -> 'a
val unsafe_get_snd : (_, 'b, _) t -> int -> 'b
val unsafe_get_thd : (_, _, 'c) t -> int -> 'c
val unsafe_set_fst : ('a, _, _) t -> int -> 'a -> unit
val unsafe_set_snd : (_, 'b, _) t -> int -> 'b -> unit
val unsafe_set_thd : (_, _, 'c) t -> int -> 'c -> unit
end = struct
type ('a, 'b, 'c) t = Obj_array.t
let entry_size = 3
let empty = Obj_array.empty
let unsafe_create_uninitialized ~len =
Obj_array.create_zero ~len:(len * entry_size)
let create_obj_array ~len = Obj_array.create_zero ~len:(len * entry_size)
let create ~len x y z =
let t = unsafe_create_uninitialized ~len:(len * entry_size) in
for i = 0 to len - 1 do
Obj_array.unsafe_set t (entry_size * i) (Obj.repr x);
Obj_array.unsafe_set t ((entry_size * i) + 1) (Obj.repr y);
Obj_array.unsafe_set t ((entry_size * i) + 2) (Obj.repr z)
done;
t
let singleton x y = create ~len:1 x y
let swap t i j =
Obj_array.swap t (entry_size * i) (entry_size * j);
Obj_array.swap t ((entry_size * i) + 1) ((entry_size * j) + 1);
Obj_array.swap t ((entry_size * i) + 2) ((entry_size * j) + 2)
let get_fst arr i = Obj.obj (Obj_array.get arr (entry_size * i))
let get_snd arr i = Obj.obj (Obj_array.get arr ((entry_size * i) + 1))
let get_thd arr i = Obj.obj (Obj_array.get arr ((entry_size * i) + 2))
let get arr i = (get_fst arr i, get_snd arr i, get_thd arr i)
let set_fst arr i x = Obj_array.set arr (entry_size * i) (Obj.repr x)
let set_snd arr i y = Obj_array.set arr ((entry_size * i) + 1) (Obj.repr y)
let set_thd arr i z = Obj_array.set arr ((entry_size * i) + 2) (Obj.repr z)
let set arr i x y z =
set_fst arr i x;
set_snd arr i y;
set_thd arr i z
let unsafe_get_fst arr i =
Obj.obj (Obj_array.unsafe_get arr (entry_size * i))
let unsafe_get_snd arr i =
Obj.obj (Obj_array.unsafe_get arr ((entry_size * i) + 1))
let unsafe_get_thd arr i =
Obj.obj (Obj_array.unsafe_get arr ((entry_size * i) + 2))
let unsafe_get arr i =
(unsafe_get_fst arr i, unsafe_get_snd arr i, unsafe_get_thd arr i)
let unsafe_set_fst arr i x =
Obj_array.unsafe_set arr (entry_size * i) (Obj.repr x)
let unsafe_set_snd arr i y =
Obj_array.unsafe_set arr ((entry_size * i) + 1) (Obj.repr y)
let unsafe_set_thd arr i z =
Obj_array.unsafe_set arr ((entry_size * i) + 2) (Obj.repr z)
let unsafe_set arr i x y z =
unsafe_set_fst arr i x;
unsafe_set_snd arr i y;
unsafe_set_thd arr i z
let length t = Obj_array.length t / entry_size
let unsafe_blit ~src ~src_pos ~dst ~dst_pos ~len =
Obj_array.unsafe_blit ~src ~src_pos:(entry_size * src_pos) ~dst
~dst_pos:(entry_size * dst_pos) ~len:(entry_size * len)
let unsafe_set_omit_phys_equal_check t i x y z =
Obj_array.unsafe_set_omit_phys_equal_check t (entry_size * i) (Obj.repr x);
Obj_array.unsafe_set_omit_phys_equal_check t
((entry_size * i) + 1)
(Obj.repr y);
Obj_array.unsafe_set_omit_phys_equal_check t
((entry_size * i) + 2)
(Obj.repr z)
let unsafe_set_int arr i x y z =
Obj_array.unsafe_set_int arr (entry_size * i) x;
Obj_array.unsafe_set_int arr ((entry_size * i) + 1) y;
Obj_array.unsafe_set_int arr ((entry_size * i) + 2) z
let unsafe_set_int_assuming_currently_int arr i x y z =
Obj_array.unsafe_set_int_assuming_currently_int arr (entry_size * i) x;
Obj_array.unsafe_set_int_assuming_currently_int arr
((entry_size * i) + 1)
y;
Obj_array.unsafe_set_int_assuming_currently_int arr
((entry_size * i) + 2)
z
let unsafe_set_assuming_currently_int arr i x y z =
Obj_array.unsafe_set_assuming_currently_int arr (entry_size * i) x;
Obj_array.unsafe_set_assuming_currently_int arr ((entry_size * i) + 1) y;
Obj_array.unsafe_set_assuming_currently_int arr ((entry_size * i) + 2) z
let unsafe_clear_if_pointer arr i =
Obj_array.unsafe_clear_if_pointer arr (entry_size * i);
Obj_array.unsafe_clear_if_pointer arr ((entry_size * i) + 1);
Obj_array.unsafe_clear_if_pointer arr ((entry_size * i) + 2)
end
include Trusted
let init l ~f =
if l < 0 then invalid_arg "Uniform_array.init"
else
let res = unsafe_create_uninitialized ~len:l in
for i = 0 to l - 1 do
let x, y, z = f i in
unsafe_set res i x y z
done;
res
let of_array arr = init ~f:(Array.unsafe_get arr) (Array.length arr)
let map a ~f =
init
~f:(fun i ->
f (unsafe_get_fst a i) (unsafe_get_snd a i) (unsafe_get_thd a i))
(length a)
let map_inplace a ~f =
for i = 0 to length a - 1 do
let x, y, z =
f (unsafe_get_fst a i) (unsafe_get_snd a i) (unsafe_get_thd a i)
in
unsafe_set a i x y z
done
let iter a ~f =
for i = 0 to length a - 1 do
f (unsafe_get_fst a i) (unsafe_get_snd a i) (unsafe_get_thd a i)
done
let iteri a ~f =
for i = 0 to length a - 1 do
f i (unsafe_get_fst a i) (unsafe_get_snd a i) (unsafe_get_thd a i)
done
let invariant inv_elt t =
assert (Obj.tag (Obj.repr t) <> Obj.double_array_tag);
iter t ~f:(fun a b c -> inv_elt (a, b, c))
let to_list t = List.init ~f:(get t) ~len:(length t)
let of_list l =
let len = List.length l in
let res = unsafe_create_uninitialized ~len in
List.iteri l ~f:(fun i (x, y, z) -> unsafe_set res i x y z);
res
let of_list_rev l =
match l with
| [] -> empty
| (a, b, c) :: l ->
let len = 1 + List.length l in
let t = unsafe_create_uninitialized ~len in
unsafe_set_fst t (len - 1) a;
unsafe_set_snd t (len - 1) b;
unsafe_set_thd t (len - 1) c;
let r = ref l in
(* We start at [len - 2] because we already put [a] at [t.(len - 1)]. *)
for i = len - 2 downto 0 do
match !r with
| [] -> assert false
| (a, b, c) :: l ->
unsafe_set_fst t i a;
unsafe_set_snd t i b;
unsafe_set_thd t i c;
r := l
done;
t
(* It is not safe for [to_array] to be the identity function because we have code that
relies on [float array]s being unboxed, for example in [bin_write_array]. *)
let to_array t = Array.init (length t) ~f:(fun i -> unsafe_get t i)
let exists t ~f =
let rec loop t ~f i =
if i < 0 then false
else
f (unsafe_get_fst t i) (unsafe_get_snd t i) (unsafe_get_thd t i)
|| loop t ~f (i - 1)
in
loop t ~f (length t - 1)
let map2_exn t1 t2 ~f =
let len = length t1 in
if length t2 <> len then invalid_arg "Array.map2_exn";
init len ~f:(fun i ->
f (unsafe_get_fst t1 i) (unsafe_get_snd t1 i) (unsafe_get_thd t1 i)
(unsafe_get_fst t2 i) (unsafe_get_snd t2 i) (unsafe_get_thd t2 i))
let fold t ~init ~f =
let r = ref init in
for i = 0 to length t - 1 do
r := f !r (unsafe_get_fst t i) (unsafe_get_snd t i) (unsafe_get_thd t i)
done;
!r
end
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Copyright ( c ) 2016–2020 Jane Street Group , LLC < >
Copyright ( c ) 2020–2021 < >
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 " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE .
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Copyright (c) 2016–2020 Jane Street Group, LLC <>
Copyright (c) 2020–2021 Craig Ferguson <>
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", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
————————————————————————————————————————————————————————————————————————————*)
| null | https://raw.githubusercontent.com/craigfe/compact/fcce0432d267babeb90dbdf4f49e2d2d067b2b0f/src/uniform_array.ml | ocaml | WARNING:
We use non-memory-safe things throughout the [Trusted] module.
Most of it is only safe in combination with the type signature (e.g. exposing
[val copy : 'a t -> 'b t] would be a big mistake).
We start at [len - 2] because we already put [a] at [t.(len - 1)].
It is not safe for [to_array] to be the identity function because we have code that
relies on [float array]s being unboxed, for example in [bin_write_array].
* See {!Trusted} above.
We start at [len - 2] because we already put [a] at [t.(len - 1)].
It is not safe for [to_array] to be the identity function because we have code that
relies on [float array]s being unboxed, for example in [bin_write_array].
* See {!Trusted} above.
We start at [len - 2] because we already put [a] at [t.(len - 1)].
It is not safe for [to_array] to be the identity function because we have code that
relies on [float array]s being unboxed, for example in [bin_write_array]. | — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Copyright ( c ) 2016–2020 Jane Street Group , LLC < >
Copyright ( c ) 2020–2021 < >
Distributed under the MIT license . See terms at the end of this file .
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Copyright (c) 2016–2020 Jane Street Group, LLC <>
Copyright (c) 2020–2021 Craig Ferguson <>
Distributed under the MIT license. See terms at the end of this file.
————————————————————————————————————————————————————————————————————————————*)
* Code in this module has been extracted from [ base ] library ,
and modified to add support for [ Tuple2 ] and [ Tuple3 ] specialisations .
and modified to add support for [Tuple2] and [Tuple3] specialisations. *)
open! Import
include Uniform_array_intf
module type Trusted = sig
type ('a, 'b, 'c) t
type ('a, 'b, 'c) elt
type ('a, 'b, 'c, 'inner) with_elt
val empty : (_, _, _) t
val unsafe_create_uninitialized : len:int -> (_, _, _) t
val create_obj_array : len:int -> (_, _, _) t
val create : len:int -> ('a, 'b, 'c, ('a, 'b, 'c) t) with_elt
val singleton : ('a, 'b, 'c, ('a, 'b, 'c) t) with_elt
val get : ('a, 'b, 'c) t -> int -> ('a, 'b, 'c) elt
val set : ('a, 'b, 'c) t -> int -> ('a, 'b, 'c, unit) with_elt
val swap : (_, _, _) t -> int -> int -> unit
val unsafe_get : ('a, 'b, 'c) t -> int -> ('a, 'b, 'c) elt
val unsafe_set : ('a, 'b, 'c) t -> int -> ('a, 'b, 'c, unit) with_elt
val unsafe_set_omit_phys_equal_check :
('a, 'b, 'c) t -> int -> ('a, 'b, 'c, unit) with_elt
val unsafe_set_int : (_, _, _) t -> int -> (int, int, int, unit) with_elt
val unsafe_set_int_assuming_currently_int :
(_, _, _) t -> int -> (int, int, int, unit) with_elt
val unsafe_set_assuming_currently_int :
(_, _, _) t -> int -> (Obj.t, Obj.t, Obj.t, unit) with_elt
val length : (_, _, _) t -> int
val unsafe_blit :
src:('a, 'b, 'c) t
-> src_pos:int
-> dst:('a, 'b, 'c) t
-> dst_pos:int
-> len:int
-> unit
val unsafe_clear_if_pointer : (_, _, _) t -> int -> unit
end
module Trusted : sig
type 'a t
include
Trusted
with type ('a, _, _) t := 'a t
and type ('a, _, _) elt := 'a
and type ('a, _, _, 'inner) with_elt := 'a -> 'inner
end = struct
type 'a t = Obj_array.t
let empty = Obj_array.empty
let unsafe_create_uninitialized ~len = Obj_array.create_zero ~len
let create_obj_array ~len = Obj_array.create_zero ~len
let create ~len x = Obj_array.create ~len (Obj.repr x)
let singleton x = Obj_array.singleton (Obj.repr x)
let swap t i j = Obj_array.swap t i j
let get arr i = Obj.obj (Obj_array.get arr i)
let set arr i x = Obj_array.set arr i (Obj.repr x)
let unsafe_get arr i = Obj.obj (Obj_array.unsafe_get arr i)
let unsafe_set arr i x = Obj_array.unsafe_set arr i (Obj.repr x)
let unsafe_set_int arr i x = Obj_array.unsafe_set_int arr i x
let unsafe_set_int_assuming_currently_int arr i x =
Obj_array.unsafe_set_int_assuming_currently_int arr i x
let unsafe_set_assuming_currently_int arr i x =
Obj_array.unsafe_set_assuming_currently_int arr i (Obj.repr x)
let length = Obj_array.length
let unsafe_blit = Obj_array.unsafe_blit
let unsafe_set_omit_phys_equal_check t i x =
Obj_array.unsafe_set_omit_phys_equal_check t i (Obj.repr x)
let unsafe_clear_if_pointer = Obj_array.unsafe_clear_if_pointer
end
include Trusted
let init l ~f =
if l < 0 then invalid_arg "Uniform_array.init"
else
let res = unsafe_create_uninitialized ~len:l in
for i = 0 to l - 1 do
unsafe_set res i (f i)
done;
res
let of_array arr = init ~f:(Array.unsafe_get arr) (Array.length arr)
let map a ~f = init ~f:(fun i -> f (unsafe_get a i)) (length a)
let map_inplace a ~f =
for i = 0 to length a - 1 do
unsafe_set a i (f (unsafe_get a i))
done
let iter a ~f =
for i = 0 to length a - 1 do
f (unsafe_get a i)
done
let iteri a ~f =
for i = 0 to length a - 1 do
f i (unsafe_get a i)
done
let invariant inv_a t =
assert (Obj.tag (Obj.repr t) <> Obj.double_array_tag);
iter t ~f:inv_a
let to_list t = List.init ~f:(get t) ~len:(length t)
let of_list l =
let len = List.length l in
let res = unsafe_create_uninitialized ~len in
List.iteri l ~f:(fun i x -> set res i x);
res
let of_list_rev l =
match l with
| [] -> empty
| a :: l ->
let len = 1 + List.length l in
let t = create ~len a in
let r = ref l in
for i = len - 2 downto 0 do
match !r with
| [] -> assert false
| a :: l ->
unsafe_set t i a;
r := l
done;
t
let to_array t = Array.init (length t) ~f:(fun i -> unsafe_get t i)
let exists t ~f =
let rec loop t ~f i =
if i < 0 then false else f (unsafe_get t i) || loop t ~f (i - 1)
in
loop t ~f (length t - 1)
let map2_exn t1 t2 ~f =
let len = length t1 in
if length t2 <> len then invalid_arg "Array.map2_exn";
init len ~f:(fun i -> f (unsafe_get t1 i) (unsafe_get t2 i))
let fold t ~init ~f =
let r = ref init in
for i = 0 to length t - 1 do
r := f !r (unsafe_get t i)
done;
!r
module Tuple2 = struct
module Trusted : sig
type ('a, 'b) t
include
Trusted
with type ('a, 'b, _) t := ('a, 'b) t
and type ('a, 'b, _) elt := 'a * 'b
and type ('a, 'b, _, 'inner) with_elt := 'a -> 'b -> 'inner
val get_fst : ('a, _) t -> int -> 'a
val get_snd : (_, 'b) t -> int -> 'b
val set_fst : ('a, _) t -> int -> 'a -> unit
val set_snd : (_, 'b) t -> int -> 'b -> unit
val unsafe_get_fst : ('a, _) t -> int -> 'a
val unsafe_get_snd : (_, 'b) t -> int -> 'b
val unsafe_set_fst : ('a, _) t -> int -> 'a -> unit
val unsafe_set_snd : (_, 'b) t -> int -> 'b -> unit
end = struct
type ('a, 'b) t = Obj_array.t
let entry_size = 2
let empty = Obj_array.empty
let unsafe_create_uninitialized ~len =
Obj_array.create_zero ~len:(len * entry_size)
let create_obj_array ~len = Obj_array.create_zero ~len:(len * entry_size)
let create ~len x y =
let t = unsafe_create_uninitialized ~len:(len * entry_size) in
for i = 0 to len - 1 do
Obj_array.unsafe_set t (entry_size * i) (Obj.repr x);
Obj_array.unsafe_set t ((entry_size * i) + 1) (Obj.repr y)
done;
t
let singleton x y = create ~len:1 x y
let swap t i j =
Obj_array.swap t (entry_size * i) (entry_size * j);
Obj_array.swap t ((entry_size * i) + 1) ((entry_size * j) + 1)
let get_fst arr i = Obj.obj (Obj_array.get arr (entry_size * i))
let get_snd arr i = Obj.obj (Obj_array.get arr ((entry_size * i) + 1))
let get arr i = (get_fst arr i, get_snd arr i)
let set_fst arr i x = Obj_array.set arr (entry_size * i) (Obj.repr x)
let set_snd arr i y = Obj_array.set arr ((entry_size * i) + 1) (Obj.repr y)
let set arr i x y =
set_fst arr i x;
set_snd arr i y
let unsafe_get_fst arr i =
Obj.obj (Obj_array.unsafe_get arr (entry_size * i))
let unsafe_get_snd arr i =
Obj.obj (Obj_array.unsafe_get arr ((entry_size * i) + 1))
let unsafe_get arr i = (unsafe_get_fst arr i, unsafe_get_snd arr i)
let unsafe_set_fst arr i x =
Obj_array.unsafe_set arr (entry_size * i) (Obj.repr x)
let unsafe_set_snd arr i y =
Obj_array.unsafe_set arr ((entry_size * i) + 1) (Obj.repr y)
let unsafe_set arr i x y =
unsafe_set_fst arr i x;
unsafe_set_snd arr i y
let length t = Obj_array.length t / entry_size
let unsafe_blit ~src ~src_pos ~dst ~dst_pos ~len =
Obj_array.unsafe_blit ~src ~src_pos:(entry_size * src_pos) ~dst
~dst_pos:(entry_size * dst_pos) ~len:(entry_size * len)
let unsafe_set_omit_phys_equal_check t i x y =
Obj_array.unsafe_set_omit_phys_equal_check t (entry_size * i) (Obj.repr x);
Obj_array.unsafe_set_omit_phys_equal_check t
((entry_size * i) + 1)
(Obj.repr y)
let unsafe_set_int arr i x y =
Obj_array.unsafe_set_int arr (entry_size * i) x;
Obj_array.unsafe_set_int arr ((entry_size * i) + 1) y
let unsafe_set_int_assuming_currently_int arr i x y =
Obj_array.unsafe_set_int_assuming_currently_int arr (entry_size * i) x;
Obj_array.unsafe_set_int_assuming_currently_int arr
((entry_size * i) + 1)
y
let unsafe_set_assuming_currently_int arr i x y =
Obj_array.unsafe_set_assuming_currently_int arr (entry_size * i) x;
Obj_array.unsafe_set_assuming_currently_int arr ((entry_size * i) + 1) y
let unsafe_clear_if_pointer arr i =
Obj_array.unsafe_clear_if_pointer arr (entry_size * i);
Obj_array.unsafe_clear_if_pointer arr ((entry_size * i) + 1)
end
include Trusted
let init l ~f =
if l < 0 then invalid_arg "Uniform_array.init"
else
let res = unsafe_create_uninitialized ~len:l in
for i = 0 to l - 1 do
let x, y = f i in
unsafe_set res i x y
done;
res
let of_array arr = init ~f:(Array.unsafe_get arr) (Array.length arr)
let map a ~f =
init ~f:(fun i -> f (unsafe_get_fst a i) (unsafe_get_snd a i)) (length a)
let map_inplace a ~f =
for i = 0 to length a - 1 do
let x, y = f (unsafe_get_fst a i) (unsafe_get_snd a i) in
unsafe_set a i x y
done
let iter a ~f =
for i = 0 to length a - 1 do
f (unsafe_get_fst a i) (unsafe_get_snd a i)
done
let iteri a ~f =
for i = 0 to length a - 1 do
f i (unsafe_get_fst a i) (unsafe_get_snd a i)
done
let invariant inv_elt t =
assert (Obj.tag (Obj.repr t) <> Obj.double_array_tag);
iter t ~f:(fun a b -> inv_elt (a, b))
let to_list t = List.init ~f:(get t) ~len:(length t)
let of_list l =
let len = List.length l in
let res = unsafe_create_uninitialized ~len in
List.iteri l ~f:(fun i (x, y) -> unsafe_set res i x y);
res
let of_list_rev l =
match l with
| [] -> empty
| (a, b) :: l ->
let len = 1 + List.length l in
let t = unsafe_create_uninitialized ~len in
unsafe_set_fst t (len - 1) a;
unsafe_set_snd t (len - 1) b;
let r = ref l in
for i = len - 2 downto 0 do
match !r with
| [] -> assert false
| (a, b) :: l ->
unsafe_set_fst t i a;
unsafe_set_snd t i b;
r := l
done;
t
let to_array t = Array.init (length t) ~f:(fun i -> unsafe_get t i)
let exists t ~f =
let rec loop t ~f i =
if i < 0 then false
else f (unsafe_get_fst t i) (unsafe_get_snd t i) || loop t ~f (i - 1)
in
loop t ~f (length t - 1)
let map2_exn t1 t2 ~f =
let len = length t1 in
if length t2 <> len then invalid_arg "Array.map2_exn";
init len ~f:(fun i ->
f (unsafe_get_fst t1 i) (unsafe_get_snd t1 i) (unsafe_get_fst t2 i)
(unsafe_get_snd t2 i))
let fold t ~init ~f =
let r = ref init in
for i = 0 to length t - 1 do
r := f !r (unsafe_get_fst t i) (unsafe_get_snd t i)
done;
!r
end
module Tuple3 = struct
module Trusted : sig
type ('a, 'b, 'c) t
include
Trusted
with type ('a, 'b, 'c) t := ('a, 'b, 'c) t
and type ('a, 'b, 'c) elt := 'a * 'b * 'c
and type ('a, 'b, 'c, 'inner) with_elt := 'a -> 'b -> 'c -> 'inner
val get_fst : ('a, _, _) t -> int -> 'a
val get_snd : (_, 'b, _) t -> int -> 'b
val get_thd : (_, _, 'c) t -> int -> 'c
val set_fst : ('a, _, _) t -> int -> 'a -> unit
val set_snd : (_, 'b, _) t -> int -> 'b -> unit
val set_thd : (_, _, 'c) t -> int -> 'c -> unit
val unsafe_get_fst : ('a, _, _) t -> int -> 'a
val unsafe_get_snd : (_, 'b, _) t -> int -> 'b
val unsafe_get_thd : (_, _, 'c) t -> int -> 'c
val unsafe_set_fst : ('a, _, _) t -> int -> 'a -> unit
val unsafe_set_snd : (_, 'b, _) t -> int -> 'b -> unit
val unsafe_set_thd : (_, _, 'c) t -> int -> 'c -> unit
end = struct
type ('a, 'b, 'c) t = Obj_array.t
let entry_size = 3
let empty = Obj_array.empty
let unsafe_create_uninitialized ~len =
Obj_array.create_zero ~len:(len * entry_size)
let create_obj_array ~len = Obj_array.create_zero ~len:(len * entry_size)
let create ~len x y z =
let t = unsafe_create_uninitialized ~len:(len * entry_size) in
for i = 0 to len - 1 do
Obj_array.unsafe_set t (entry_size * i) (Obj.repr x);
Obj_array.unsafe_set t ((entry_size * i) + 1) (Obj.repr y);
Obj_array.unsafe_set t ((entry_size * i) + 2) (Obj.repr z)
done;
t
let singleton x y = create ~len:1 x y
let swap t i j =
Obj_array.swap t (entry_size * i) (entry_size * j);
Obj_array.swap t ((entry_size * i) + 1) ((entry_size * j) + 1);
Obj_array.swap t ((entry_size * i) + 2) ((entry_size * j) + 2)
let get_fst arr i = Obj.obj (Obj_array.get arr (entry_size * i))
let get_snd arr i = Obj.obj (Obj_array.get arr ((entry_size * i) + 1))
let get_thd arr i = Obj.obj (Obj_array.get arr ((entry_size * i) + 2))
let get arr i = (get_fst arr i, get_snd arr i, get_thd arr i)
let set_fst arr i x = Obj_array.set arr (entry_size * i) (Obj.repr x)
let set_snd arr i y = Obj_array.set arr ((entry_size * i) + 1) (Obj.repr y)
let set_thd arr i z = Obj_array.set arr ((entry_size * i) + 2) (Obj.repr z)
let set arr i x y z =
set_fst arr i x;
set_snd arr i y;
set_thd arr i z
let unsafe_get_fst arr i =
Obj.obj (Obj_array.unsafe_get arr (entry_size * i))
let unsafe_get_snd arr i =
Obj.obj (Obj_array.unsafe_get arr ((entry_size * i) + 1))
let unsafe_get_thd arr i =
Obj.obj (Obj_array.unsafe_get arr ((entry_size * i) + 2))
let unsafe_get arr i =
(unsafe_get_fst arr i, unsafe_get_snd arr i, unsafe_get_thd arr i)
let unsafe_set_fst arr i x =
Obj_array.unsafe_set arr (entry_size * i) (Obj.repr x)
let unsafe_set_snd arr i y =
Obj_array.unsafe_set arr ((entry_size * i) + 1) (Obj.repr y)
let unsafe_set_thd arr i z =
Obj_array.unsafe_set arr ((entry_size * i) + 2) (Obj.repr z)
let unsafe_set arr i x y z =
unsafe_set_fst arr i x;
unsafe_set_snd arr i y;
unsafe_set_thd arr i z
let length t = Obj_array.length t / entry_size
let unsafe_blit ~src ~src_pos ~dst ~dst_pos ~len =
Obj_array.unsafe_blit ~src ~src_pos:(entry_size * src_pos) ~dst
~dst_pos:(entry_size * dst_pos) ~len:(entry_size * len)
let unsafe_set_omit_phys_equal_check t i x y z =
Obj_array.unsafe_set_omit_phys_equal_check t (entry_size * i) (Obj.repr x);
Obj_array.unsafe_set_omit_phys_equal_check t
((entry_size * i) + 1)
(Obj.repr y);
Obj_array.unsafe_set_omit_phys_equal_check t
((entry_size * i) + 2)
(Obj.repr z)
let unsafe_set_int arr i x y z =
Obj_array.unsafe_set_int arr (entry_size * i) x;
Obj_array.unsafe_set_int arr ((entry_size * i) + 1) y;
Obj_array.unsafe_set_int arr ((entry_size * i) + 2) z
let unsafe_set_int_assuming_currently_int arr i x y z =
Obj_array.unsafe_set_int_assuming_currently_int arr (entry_size * i) x;
Obj_array.unsafe_set_int_assuming_currently_int arr
((entry_size * i) + 1)
y;
Obj_array.unsafe_set_int_assuming_currently_int arr
((entry_size * i) + 2)
z
let unsafe_set_assuming_currently_int arr i x y z =
Obj_array.unsafe_set_assuming_currently_int arr (entry_size * i) x;
Obj_array.unsafe_set_assuming_currently_int arr ((entry_size * i) + 1) y;
Obj_array.unsafe_set_assuming_currently_int arr ((entry_size * i) + 2) z
let unsafe_clear_if_pointer arr i =
Obj_array.unsafe_clear_if_pointer arr (entry_size * i);
Obj_array.unsafe_clear_if_pointer arr ((entry_size * i) + 1);
Obj_array.unsafe_clear_if_pointer arr ((entry_size * i) + 2)
end
include Trusted
let init l ~f =
if l < 0 then invalid_arg "Uniform_array.init"
else
let res = unsafe_create_uninitialized ~len:l in
for i = 0 to l - 1 do
let x, y, z = f i in
unsafe_set res i x y z
done;
res
let of_array arr = init ~f:(Array.unsafe_get arr) (Array.length arr)
let map a ~f =
init
~f:(fun i ->
f (unsafe_get_fst a i) (unsafe_get_snd a i) (unsafe_get_thd a i))
(length a)
let map_inplace a ~f =
for i = 0 to length a - 1 do
let x, y, z =
f (unsafe_get_fst a i) (unsafe_get_snd a i) (unsafe_get_thd a i)
in
unsafe_set a i x y z
done
let iter a ~f =
for i = 0 to length a - 1 do
f (unsafe_get_fst a i) (unsafe_get_snd a i) (unsafe_get_thd a i)
done
let iteri a ~f =
for i = 0 to length a - 1 do
f i (unsafe_get_fst a i) (unsafe_get_snd a i) (unsafe_get_thd a i)
done
let invariant inv_elt t =
assert (Obj.tag (Obj.repr t) <> Obj.double_array_tag);
iter t ~f:(fun a b c -> inv_elt (a, b, c))
let to_list t = List.init ~f:(get t) ~len:(length t)
let of_list l =
let len = List.length l in
let res = unsafe_create_uninitialized ~len in
List.iteri l ~f:(fun i (x, y, z) -> unsafe_set res i x y z);
res
let of_list_rev l =
match l with
| [] -> empty
| (a, b, c) :: l ->
let len = 1 + List.length l in
let t = unsafe_create_uninitialized ~len in
unsafe_set_fst t (len - 1) a;
unsafe_set_snd t (len - 1) b;
unsafe_set_thd t (len - 1) c;
let r = ref l in
for i = len - 2 downto 0 do
match !r with
| [] -> assert false
| (a, b, c) :: l ->
unsafe_set_fst t i a;
unsafe_set_snd t i b;
unsafe_set_thd t i c;
r := l
done;
t
let to_array t = Array.init (length t) ~f:(fun i -> unsafe_get t i)
let exists t ~f =
let rec loop t ~f i =
if i < 0 then false
else
f (unsafe_get_fst t i) (unsafe_get_snd t i) (unsafe_get_thd t i)
|| loop t ~f (i - 1)
in
loop t ~f (length t - 1)
let map2_exn t1 t2 ~f =
let len = length t1 in
if length t2 <> len then invalid_arg "Array.map2_exn";
init len ~f:(fun i ->
f (unsafe_get_fst t1 i) (unsafe_get_snd t1 i) (unsafe_get_thd t1 i)
(unsafe_get_fst t2 i) (unsafe_get_snd t2 i) (unsafe_get_thd t2 i))
let fold t ~init ~f =
let r = ref init in
for i = 0 to length t - 1 do
r := f !r (unsafe_get_fst t i) (unsafe_get_snd t i) (unsafe_get_thd t i)
done;
!r
end
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Copyright ( c ) 2016–2020 Jane Street Group , LLC < >
Copyright ( c ) 2020–2021 < >
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 " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE .
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Copyright (c) 2016–2020 Jane Street Group, LLC <>
Copyright (c) 2020–2021 Craig Ferguson <>
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", 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.
————————————————————————————————————————————————————————————————————————————*)
|
5625d28e563a1c0b3a7984ab7057cffbe7d3c7d6183c12eefd9c26ffcd3b7fb0 | crategus/cl-cffi-gtk | rtest-gdk-event-structures.lisp | (def-suite gdk-event-structures :in gdk-suite)
(in-suite gdk-event-structures)
;;; GdkScrollDirection
(test gdk-scroll-direction
;; Check the type
(is-true (g-type-is-enum "GdkScrollDirection"))
;; Check the type initializer
(is (eq (gtype "GdkScrollDirection")
(gtype (foreign-funcall "gdk_scroll_direction_get_type" g-size))))
;; Check the registered name
(is (eq 'gdk-scroll-direction
(registered-enum-type "GdkScrollDirection")))
;; Check the names
(is (equal '("GDK_SCROLL_UP" "GDK_SCROLL_DOWN" "GDK_SCROLL_LEFT"
"GDK_SCROLL_RIGHT" "GDK_SCROLL_SMOOTH")
(mapcar #'enum-item-name
(get-enum-items "GdkScrollDirection"))))
;; Check the values
(is (equal '(0 1 2 3 4)
(mapcar #'enum-item-value
(get-enum-items "GdkScrollDirection"))))
Check the nick names
(is (equal '("up" "down" "left" "right" "smooth")
(mapcar #'enum-item-nick
(get-enum-items "GdkScrollDirection"))))
;; Check the enum definition
(is (equal '(DEFINE-G-ENUM "GdkScrollDirection"
GDK-SCROLL-DIRECTION
(:EXPORT T
:TYPE-INITIALIZER "gdk_scroll_direction_get_type")
(:UP 0)
(:DOWN 1)
(:LEFT 2)
(:RIGHT 3)
(:SMOOTH 4))
(get-g-type-definition "GdkScrollDirection"))))
;;; GdkVisibilityState
(test gdk-visibility-state
;; Check the type
(is-true (g-type-is-enum "GdkVisibilityState"))
;; Check the type initializer
(is (eq (gtype "GdkVisibilityState")
(gtype (foreign-funcall "gdk_visibility_state_get_type" g-size))))
;; Check the registered name
(is (eq 'gdk-visibility-state
(registered-enum-type "GdkVisibilityState")))
;; Check the names
(is (equal '("GDK_VISIBILITY_UNOBSCURED" "GDK_VISIBILITY_PARTIAL"
"GDK_VISIBILITY_FULLY_OBSCURED")
(mapcar #'enum-item-name
(get-enum-items "GdkVisibilityState"))))
;; Check the values
(is (equal '(0 1 2)
(mapcar #'enum-item-value
(get-enum-items "GdkVisibilityState"))))
Check the nick names
(is (equal '("unobscured" "partial" "fully-obscured")
(mapcar #'enum-item-nick
(get-enum-items "GdkVisibilityState"))))
;; Check the enum definition
(is (equal '(DEFINE-G-ENUM "GdkVisibilityState"
GDK-VISIBILITY-STATE
(:EXPORT T
:TYPE-INITIALIZER "gdk_visibility_state_get_type")
(:UNOBSCURED 0)
(:PARTIAL 1)
(:FULLY-OBSCURED 2))
(get-g-type-definition "GdkVisibilityState"))))
;;; GdkCrossingMode
(test gdk-crossing-mode
;; Check the type
(is-true (g-type-is-enum "GdkCrossingMode"))
;; Check the type initializer
(is (eq (gtype "GdkCrossingMode")
(gtype (foreign-funcall "gdk_crossing_mode_get_type" g-size))))
;; Check the registered name
(is (eq 'gdk-crossing-mode
(registered-enum-type "GdkCrossingMode")))
;; Check the names
(is (equal '("GDK_CROSSING_NORMAL" "GDK_CROSSING_GRAB" "GDK_CROSSING_UNGRAB"
"GDK_CROSSING_GTK_GRAB" "GDK_CROSSING_GTK_UNGRAB"
"GDK_CROSSING_STATE_CHANGED" "GDK_CROSSING_TOUCH_BEGIN"
"GDK_CROSSING_TOUCH_END" "GDK_CROSSING_DEVICE_SWITCH")
(mapcar #'enum-item-name
(get-enum-items "GdkCrossingMode"))))
;; Check the values
(is (equal '(0 1 2 3 4 5 6 7 8)
(mapcar #'enum-item-value
(get-enum-items "GdkCrossingMode"))))
Check the nick names
(is (equal '("normal" "grab" "ungrab" "gtk-grab" "gtk-ungrab" "state-changed"
"touch-begin" "touch-end" "device-switch")
(mapcar #'enum-item-nick
(get-enum-items "GdkCrossingMode"))))
;; Check the enum definition
(is (equal '(DEFINE-G-ENUM "GdkCrossingMode"
GDK-CROSSING-MODE
(:EXPORT T
:TYPE-INITIALIZER "gdk_crossing_mode_get_type")
(:NORMAL 0)
(:GRAB 1)
(:UNGRAB 2)
(:GTK-GRAB 3)
(:GTK-UNGRAB 4)
(:STATE-CHANGED 5)
(:TOUCH-BEGIN 6)
(:TOUCH-END 7)
(:DEVICE-SWITCH 8))
(get-g-type-definition "GdkCrossingMode"))))
;;; GdkNotifyType
(test gdk-notify-type
;; Check the type
(is-true (g-type-is-enum "GdkNotifyType"))
;; Check the type initializer
(is (eq (gtype "GdkNotifyType")
(gtype (foreign-funcall "gdk_notify_type_get_type" g-size))))
;; Check the registered name
(is (eq 'gdk-notify-type (registered-enum-type "GdkNotifyType")))
;; Check the names
(is (equal '("GDK_NOTIFY_ANCESTOR" "GDK_NOTIFY_VIRTUAL" "GDK_NOTIFY_INFERIOR"
"GDK_NOTIFY_NONLINEAR" "GDK_NOTIFY_NONLINEAR_VIRTUAL"
"GDK_NOTIFY_UNKNOWN")
(mapcar #'enum-item-name
(get-enum-items "GdkNotifyType"))))
;; Check the values
(is (equal '(0 1 2 3 4 5)
(mapcar #'enum-item-value
(get-enum-items "GdkNotifyType"))))
Check the nick names
(is (equal '("ancestor" "virtual" "inferior" "nonlinear" "nonlinear-virtual"
"unknown")
(mapcar #'enum-item-nick
(get-enum-items "GdkNotifyType"))))
;; Check the enum definition
(is (equal '(DEFINE-G-ENUM "GdkNotifyType"
GDK-NOTIFY-TYPE
(:EXPORT T
:TYPE-INITIALIZER "gdk_notify_type_get_type")
(:ANCESTOR 0)
(:VIRTUAL 1)
(:INFERIOR 2)
(:NONLINEAR 3)
(:NONLINEAR-VIRTUAL 4)
(:UNKNOWN 5))
(get-g-type-definition "GdkNotifyType"))))
;;; GdkPropertyState
(test gdk-property-state
;; Check the type
(is-true (g-type-is-enum "GdkPropertyState"))
;; Check the type initializer
(is (eq (gtype "GdkPropertyState")
(gtype (foreign-funcall "gdk_property_state_get_type" g-size))))
;; Check the registered name
(is (eq 'gdk-property-state (registered-enum-type "GdkPropertyState")))
;; Check the names
(is (equal '("GDK_PROPERTY_NEW_VALUE" "GDK_PROPERTY_DELETE")
(mapcar #'enum-item-name
(get-enum-items "GdkPropertyState"))))
;; Check the values
(is (equal '(0 1)
(mapcar #'enum-item-value
(get-enum-items "GdkPropertyState"))))
Check the nick names
(is (equal '("new-value" "delete")
(mapcar #'enum-item-nick
(get-enum-items "GdkPropertyState"))))
;; Check the enum definition
(is (equal '(DEFINE-G-ENUM "GdkPropertyState"
GDK-PROPERTY-STATE
(:EXPORT T
:TYPE-INITIALIZER "gdk_property_state_get_type")
(:NEW-VALUE 0)
(:DELETE 1))
(get-g-type-definition "GdkPropertyState"))))
GdkWindowState
(test gdk-window-state
;; Check the type
(is (g-type-is-flags "GdkWindowState"))
;; Check the registered name
(is (eq 'gdk-window-state
(registered-flags-type "GdkWindowState")))
;; Check the type initializer
(is (eq (gtype "GdkWindowState")
(gtype (foreign-funcall "gdk_window_state_get_type" g-size))))
;; Check the names
(is (equal '("GDK_WINDOW_STATE_WITHDRAWN" "GDK_WINDOW_STATE_ICONIFIED"
"GDK_WINDOW_STATE_MAXIMIZED" "GDK_WINDOW_STATE_STICKY"
"GDK_WINDOW_STATE_FULLSCREEN" "GDK_WINDOW_STATE_ABOVE"
"GDK_WINDOW_STATE_BELOW" "GDK_WINDOW_STATE_FOCUSED"
"GDK_WINDOW_STATE_TILED" "GDK_WINDOW_STATE_TOP_TILED"
"GDK_WINDOW_STATE_TOP_RESIZABLE" "GDK_WINDOW_STATE_RIGHT_TILED"
"GDK_WINDOW_STATE_RIGHT_RESIZABLE"
"GDK_WINDOW_STATE_BOTTOM_TILED"
"GDK_WINDOW_STATE_BOTTOM_RESIZABLE"
"GDK_WINDOW_STATE_LEFT_TILED" "GDK_WINDOW_STATE_LEFT_RESIZABLE")
(mapcar #'flags-item-name
(get-flags-items "GdkWindowState"))))
;; Check the values
(is (equal '(1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768
65536)
(mapcar #'flags-item-value
(get-flags-items "GdkWindowState"))))
Check the nick names
(is (equal '("withdrawn" "iconified" "maximized" "sticky" "fullscreen" "above"
"below" "focused" "tiled" "top-tiled" "top-resizable"
"right-tiled" "right-resizable" "bottom-tiled" "bottom-resizable"
"left-tiled" "left-resizable")
(mapcar #'flags-item-nick
(get-flags-items "GdkWindowState"))))
;; Check the flags definition
(is (equal '(DEFINE-G-FLAGS "GdkWindowState"
GDK-WINDOW-STATE
(:EXPORT T
:TYPE-INITIALIZER "gdk_window_state_get_type")
(:WITHDRAWN 1)
(:ICONIFIED 2)
(:MAXIMIZED 4)
(:STICKY 8)
(:FULLSCREEN 16)
(:ABOVE 32)
(:BELOW 64)
(:FOCUSED 128)
(:TILED 256)
(:TOP-TILED 512)
(:TOP-RESIZABLE 1024)
(:RIGHT-TILED 2048)
(:RIGHT-RESIZABLE 4096)
(:BOTTOM-TILED 8192)
(:BOTTOM-RESIZABLE 16384)
(:LEFT-TILED 32768)
(:LEFT-RESIZABLE 65536))
(get-g-type-definition "GdkWindowState"))))
;;; GdkSettingAction
(test gdk-setting-action
;; Check the type
(is-true (g-type-is-enum "GdkSettingAction"))
;; Check the type initializer
(is (eq (gtype "GdkSettingAction")
(gtype (foreign-funcall "gdk_setting_action_get_type" g-size))))
;; Check the registered name
(is (eq 'gdk-setting-action (registered-enum-type "GdkSettingAction")))
;; Check the names
(is (equal '("GDK_SETTING_ACTION_NEW" "GDK_SETTING_ACTION_CHANGED"
"GDK_SETTING_ACTION_DELETED")
(mapcar #'enum-item-name
(get-enum-items "GdkSettingAction"))))
;; Check the values
(is (equal '(0 1 2)
(mapcar #'enum-item-value
(get-enum-items "GdkSettingAction"))))
Check the nick names
(is (equal '("new" "changed" "deleted")
(mapcar #'enum-item-nick
(get-enum-items "GdkSettingAction"))))
;; Check the enum definition
(is (equal '(DEFINE-G-ENUM "GdkSettingAction"
GDK-SETTING-ACTION
(:EXPORT T
:TYPE-INITIALIZER "gdk_setting_action_get_type")
(:NEW 0)
(:CHANGED 1)
(:DELETED 2))
(get-g-type-definition "GdkSettingAction"))))
;;; GdkOwnerChange
(test gdk-owner-change
;; Check the type
(is-true (g-type-is-enum "GdkOwnerChange"))
;; Check the type initializer
(is (eq (gtype "GdkOwnerChange")
(gtype (foreign-funcall "gdk_owner_change_get_type" g-size))))
;; Check the registered name
(is (eq 'gdk-owner-change (registered-enum-type "GdkOwnerChange")))
;; Check the names
(is (equal '("GDK_OWNER_CHANGE_NEW_OWNER" "GDK_OWNER_CHANGE_DESTROY"
"GDK_OWNER_CHANGE_CLOSE")
(mapcar #'enum-item-name
(get-enum-items "GdkOwnerChange"))))
;; Check the values
(is (equal '(0 1 2)
(mapcar #'enum-item-value
(get-enum-items "GdkOwnerChange"))))
Check the nick names
(is (equal '("new-owner" "destroy" "close")
(mapcar #'enum-item-nick
(get-enum-items "GdkOwnerChange"))))
;; Check the enum definition
(is (equal '(DEFINE-G-ENUM "GdkOwnerChange"
GDK-OWNER-CHANGE
(:EXPORT T
:TYPE-INITIALIZER "gdk_owner_change_get_type")
(:NEW-OWNER 0)
(:DESTROY 1)
(:CLOSE 2))
(get-g-type-definition "GdkOwnerChange"))))
;;; GdkEventType <-- gdk.events.lisp
(test gdk-event-type
;; Check the type
(is-true (g-type-is-enum "GdkEventType"))
;; Check the type initializer
(is (eq (gtype "GdkEventType")
(gtype (foreign-funcall "gdk_event_type_get_type" g-size))))
;; Check the registered name
(is (eq 'gdk-event-type (registered-enum-type "GdkEventType")))
;; Check the names
(is (equal '("GDK_NOTHING" "GDK_DELETE" "GDK_DESTROY" "GDK_EXPOSE"
"GDK_MOTION_NOTIFY" "GDK_BUTTON_PRESS" "GDK_2BUTTON_PRESS"
"GDK_DOUBLE_BUTTON_PRESS" "GDK_3BUTTON_PRESS"
"GDK_TRIPLE_BUTTON_PRESS" "GDK_BUTTON_RELEASE" "GDK_KEY_PRESS"
"GDK_KEY_RELEASE" "GDK_ENTER_NOTIFY" "GDK_LEAVE_NOTIFY"
"GDK_FOCUS_CHANGE" "GDK_CONFIGURE" "GDK_MAP" "GDK_UNMAP"
"GDK_PROPERTY_NOTIFY" "GDK_SELECTION_CLEAR"
"GDK_SELECTION_REQUEST" "GDK_SELECTION_NOTIFY" "GDK_PROXIMITY_IN"
"GDK_PROXIMITY_OUT" "GDK_DRAG_ENTER" "GDK_DRAG_LEAVE"
"GDK_DRAG_MOTION" "GDK_DRAG_STATUS" "GDK_DROP_START"
"GDK_DROP_FINISHED" "GDK_CLIENT_EVENT" "GDK_VISIBILITY_NOTIFY"
"GDK_SCROLL" "GDK_WINDOW_STATE" "GDK_SETTING" "GDK_OWNER_CHANGE"
"GDK_GRAB_BROKEN" "GDK_DAMAGE" "GDK_TOUCH_BEGIN"
"GDK_TOUCH_UPDATE" "GDK_TOUCH_END" "GDK_TOUCH_CANCEL"
"GDK_TOUCHPAD_SWIPE" "GDK_TOUCHPAD_PINCH" "GDK_PAD_BUTTON_PRESS"
"GDK_PAD_BUTTON_RELEASE" "GDK_PAD_RING" "GDK_PAD_STRIP"
"GDK_PAD_GROUP_MODE" "GDK_EVENT_LAST")
(mapcar #'enum-item-name
(get-enum-items "GdkEventType"))))
;; Check the values
(is (equal '(-1 0 1 2 3 4 5 5 6 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
22 23 24 25 26 27 28 29 31 32 33 34 35 36 37 38 39 40 41 42 43
44 45 46 47 48)
(mapcar #'enum-item-value
(get-enum-items "GdkEventType"))))
Check the nick names
(is (equal '("nothing" "delete" "destroy" "expose" "motion-notify"
"button-press" "2button-press" "double-button-press"
"3button-press" "triple-button-press" "button-release"
"key-press" "key-release" "enter-notify" "leave-notify"
"focus-change" "configure" "map" "unmap" "property-notify"
"selection-clear" "selection-request" "selection-notify"
"proximity-in" "proximity-out" "drag-enter" "drag-leave"
"drag-motion" "drag-status" "drop-start" "drop-finished"
"client-event" "visibility-notify" "scroll" "window-state"
"setting" "owner-change" "grab-broken" "damage" "touch-begin"
"touch-update" "touch-end" "touch-cancel" "touchpad-swipe"
"touchpad-pinch" "pad-button-press" "pad-button-release"
"pad-ring" "pad-strip" "pad-group-mode" "event-last")
(mapcar #'enum-item-nick
(get-enum-items "GdkEventType"))))
;; Check the enum definition
(is (equal '(DEFINE-G-ENUM "GdkEventType"
GDK-EVENT-TYPE
(:EXPORT T
:TYPE-INITIALIZER "gdk_event_type_get_type")
(:NOTHING -1)
(:DELETE 0)
(:DESTROY 1)
(:EXPOSE 2)
(:MOTION-NOTIFY 3)
(:BUTTON-PRESS 4)
(:2BUTTON-PRESS 5)
(:DOUBLE-BUTTON-PRESS 5)
(:3BUTTON-PRESS 6)
(:TRIPLE-BUTTON-PRESS 6)
(:BUTTON-RELEASE 7)
(:KEY-PRESS 8)
(:KEY-RELEASE 9)
(:ENTER-NOTIFY 10)
(:LEAVE-NOTIFY 11)
(:FOCUS-CHANGE 12)
(:CONFIGURE 13)
(:MAP 14)
(:UNMAP 15)
(:PROPERTY-NOTIFY 16)
(:SELECTION-CLEAR 17)
(:SELECTION-REQUEST 18)
(:SELECTION-NOTIFY 19)
(:PROXIMITY-IN 20)
(:PROXIMITY-OUT 21)
(:DRAG-ENTER 22)
(:DRAG-LEAVE 23)
(:DRAG-MOTION 24)
(:DRAG-STATUS 25)
(:DROP-START 26)
(:DROP-FINISHED 27)
(:CLIENT-EVENT 28)
(:VISIBILITY-NOTIFY 29)
(:SCROLL 31)
(:WINDOW-STATE 32)
(:SETTING 33)
(:OWNER-CHANGE 34)
(:GRAB-BROKEN 35)
(:DAMAGE 36)
(:TOUCH-BEGIN 37)
(:TOUCH-UPDATE 38)
(:TOUCH-END 39)
(:TOUCH-CANCEL 40)
(:TOUCHPAD-SWIPE 41)
(:TOUCHPAD-PINCH 42)
(:PAD-BUTTON-PRESS 43)
(:PAD-BUTTON-RELEASE 44)
(:PAD-RING 45)
(:PAD-STRIP 46)
(:PAD-GROUP-MODE 47)
(:EVENT-LAST 48))
(get-g-type-definition "GdkEventType"))))
;;; GdkModifierType <-- gdk.window.lisp
(test gdk-modifier-type
;; Check the type
(is (g-type-is-flags "GdkModifierType"))
;; Check the registered name
(is (eq 'gdk-modifier-type
(registered-flags-type "GdkModifierType")))
;; Check the type initializer
(is (eq (gtype "GdkModifierType")
(gtype (foreign-funcall "gdk_modifier_type_get_type" g-size))))
;; Check the names
(is (equal '("GDK_SHIFT_MASK" "GDK_LOCK_MASK" "GDK_CONTROL_MASK"
"GDK_MOD1_MASK" "GDK_MOD2_MASK" "GDK_MOD3_MASK" "GDK_MOD4_MASK"
"GDK_MOD5_MASK" "GDK_BUTTON1_MASK" "GDK_BUTTON2_MASK"
"GDK_BUTTON3_MASK" "GDK_BUTTON4_MASK" "GDK_BUTTON5_MASK"
"GDK_MODIFIER_RESERVED_13_MASK" "GDK_MODIFIER_RESERVED_14_MASK"
"GDK_MODIFIER_RESERVED_15_MASK" "GDK_MODIFIER_RESERVED_16_MASK"
"GDK_MODIFIER_RESERVED_17_MASK" "GDK_MODIFIER_RESERVED_18_MASK"
"GDK_MODIFIER_RESERVED_19_MASK" "GDK_MODIFIER_RESERVED_20_MASK"
"GDK_MODIFIER_RESERVED_21_MASK" "GDK_MODIFIER_RESERVED_22_MASK"
"GDK_MODIFIER_RESERVED_23_MASK" "GDK_MODIFIER_RESERVED_24_MASK"
"GDK_MODIFIER_RESERVED_25_MASK" "GDK_SUPER_MASK" "GDK_HYPER_MASK"
"GDK_META_MASK" "GDK_MODIFIER_RESERVED_29_MASK"
"GDK_RELEASE_MASK" "GDK_MODIFIER_MASK")
(mapcar #'flags-item-name
(get-flags-items "GdkModifierType"))))
;; Check the values
(is (equal '(1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768
65536 131072 262144 524288 1048576 2097152 4194304 8388608
16777216 33554432 67108864 134217728 268435456 536870912
1073741824 1543512063)
(mapcar #'flags-item-value
(get-flags-items "GdkModifierType"))))
Check the nick names
(is (equal '("shift-mask" "lock-mask" "control-mask" "mod1-mask" "mod2-mask"
"mod3-mask" "mod4-mask" "mod5-mask" "button1-mask" "button2-mask"
"button3-mask" "button4-mask" "button5-mask"
"modifier-reserved-13-mask" "modifier-reserved-14-mask"
"modifier-reserved-15-mask" "modifier-reserved-16-mask"
"modifier-reserved-17-mask" "modifier-reserved-18-mask"
"modifier-reserved-19-mask" "modifier-reserved-20-mask"
"modifier-reserved-21-mask" "modifier-reserved-22-mask"
"modifier-reserved-23-mask" "modifier-reserved-24-mask"
"modifier-reserved-25-mask" "super-mask" "hyper-mask" "meta-mask"
"modifier-reserved-29-mask" "release-mask" "modifier-mask")
(mapcar #'flags-item-nick
(get-flags-items "GdkModifierType"))))
;; Check the flags definition
(is (equal '(DEFINE-G-FLAGS "GdkModifierType"
GDK-MODIFIER-TYPE
(:EXPORT T
:TYPE-INITIALIZER "gdk_modifier_type_get_type")
(:SHIFT-MASK 1)
(:LOCK-MASK 2)
(:CONTROL-MASK 4)
(:MOD1-MASK 8)
(:MOD2-MASK 16)
(:MOD3-MASK 32)
(:MOD4-MASK 64)
(:MOD5-MASK 128)
(:BUTTON1-MASK 256)
(:BUTTON2-MASK 512)
(:BUTTON3-MASK 1024)
(:BUTTON4-MASK 2048)
(:BUTTON5-MASK 4096)
(:MODIFIER-RESERVED-13-MASK 8192)
(:MODIFIER-RESERVED-14-MASK 16384)
(:MODIFIER-RESERVED-15-MASK 32768)
(:MODIFIER-RESERVED-16-MASK 65536)
(:MODIFIER-RESERVED-17-MASK 131072)
(:MODIFIER-RESERVED-18-MASK 262144)
(:MODIFIER-RESERVED-19-MASK 524288)
(:MODIFIER-RESERVED-20-MASK 1048576)
(:MODIFIER-RESERVED-21-MASK 2097152)
(:MODIFIER-RESERVED-22-MASK 4194304)
(:MODIFIER-RESERVED-23-MASK 8388608)
(:MODIFIER-RESERVED-24-MASK 16777216)
(:MODIFIER-RESERVED-25-MASK 33554432)
(:SUPER-MASK 67108864)
(:HYPER-MASK 134217728)
(:META-MASK 268435456)
(:MODIFIER-RESERVED-29-MASK 536870912)
(:RELEASE-MASK 1073741824)
(:MODIFIER-MASK 1543512063))
(get-g-type-definition "GdkModifierType"))))
;;; GdkEventMask <-- gdk.events.lisp
(test gdk-event-mask
;; Check the type
(is (g-type-is-flags "GdkEventMask"))
;; Check the registered name
(is (eq 'gdk-event-mask
(registered-flags-type "GdkEventMask")))
;; Check the type initializer
(is (eq (gtype "GdkEventMask")
(gtype (foreign-funcall "gdk_event_mask_get_type" g-size))))
;; Check the names
(is (equal '("GDK_EXPOSURE_MASK" "GDK_POINTER_MOTION_MASK"
"GDK_POINTER_MOTION_HINT_MASK" "GDK_BUTTON_MOTION_MASK"
"GDK_BUTTON1_MOTION_MASK" "GDK_BUTTON2_MOTION_MASK"
"GDK_BUTTON3_MOTION_MASK" "GDK_BUTTON_PRESS_MASK"
"GDK_BUTTON_RELEASE_MASK" "GDK_KEY_PRESS_MASK"
"GDK_KEY_RELEASE_MASK" "GDK_ENTER_NOTIFY_MASK"
"GDK_LEAVE_NOTIFY_MASK" "GDK_FOCUS_CHANGE_MASK"
"GDK_STRUCTURE_MASK" "GDK_PROPERTY_CHANGE_MASK"
"GDK_VISIBILITY_NOTIFY_MASK" "GDK_PROXIMITY_IN_MASK"
"GDK_PROXIMITY_OUT_MASK" "GDK_SUBSTRUCTURE_MASK"
"GDK_SCROLL_MASK" "GDK_TOUCH_MASK" "GDK_SMOOTH_SCROLL_MASK"
"GDK_TOUCHPAD_GESTURE_MASK" "GDK_TABLET_PAD_MASK"
"GDK_ALL_EVENTS_MASK")
(mapcar #'flags-item-name
(get-flags-items "GdkEventMask"))))
;; Check the values
(is (equal '(2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536
131072 262144 524288 1048576 2097152 4194304 8388608 16777216
33554432 67108862)
(mapcar #'flags-item-value
(get-flags-items "GdkEventMask"))))
Check the nick names
(is (equal '("exposure-mask" "pointer-motion-mask" "pointer-motion-hint-mask"
"button-motion-mask" "button1-motion-mask" "button2-motion-mask"
"button3-motion-mask" "button-press-mask" "button-release-mask"
"key-press-mask" "key-release-mask" "enter-notify-mask"
"leave-notify-mask" "focus-change-mask" "structure-mask"
"property-change-mask" "visibility-notify-mask"
"proximity-in-mask" "proximity-out-mask" "substructure-mask"
"scroll-mask" "touch-mask" "smooth-scroll-mask"
"touchpad-gesture-mask" "tablet-pad-mask" "all-events-mask")
(mapcar #'flags-item-nick
(get-flags-items "GdkEventMask"))))
;; Check the flags definition
(is (equal '(DEFINE-G-FLAGS "GdkEventMask"
GDK-EVENT-MASK
(:EXPORT T
:TYPE-INITIALIZER "gdk_event_mask_get_type")
(:EXPOSURE-MASK 2)
(:POINTER-MOTION-MASK 4)
(:POINTER-MOTION-HINT-MASK 8)
(:BUTTON-MOTION-MASK 16)
(:BUTTON1-MOTION-MASK 32)
(:BUTTON2-MOTION-MASK 64)
(:BUTTON3-MOTION-MASK 128)
(:BUTTON-PRESS-MASK 256)
(:BUTTON-RELEASE-MASK 512)
(:KEY-PRESS-MASK 1024)
(:KEY-RELEASE-MASK 2048)
(:ENTER-NOTIFY-MASK 4096)
(:LEAVE-NOTIFY-MASK 8192)
(:FOCUS-CHANGE-MASK 16384)
(:STRUCTURE-MASK 32768)
(:PROPERTY-CHANGE-MASK 65536)
(:VISIBILITY-NOTIFY-MASK 131072)
(:PROXIMITY-IN-MASK 262144)
(:PROXIMITY-OUT-MASK 524288)
(:SUBSTRUCTURE-MASK 1048576)
(:SCROLL-MASK 2097152)
(:TOUCH-MASK 4194304)
(:SMOOTH-SCROLL-MASK 8388608)
(:TOUCHPAD-GESTURE-MASK 16777216)
(:TABLET-PAD-MASK 33554432)
(:ALL-EVENTS-MASK 67108862))
(get-g-type-definition "GdkEventMask"))))
;;; GdkEventSequence <-- gdk-events.lisp
(eval-when (:compile-toplevel :load-toplevel :execute)
(foreign-funcall "gdk_event_sequence_get_type" g-size))
(test gdk-event-sequence
;; Type check
(is-true (g-type-is-a (gtype "GdkEventSequence") +g-type-boxed+))
;; Check the type initializer
(is (eq (gtype "GdkEventSequence")
(gtype (foreign-funcall "gdk_event_sequence_get_type" g-size)))))
GdkEvent
;;; GdkEventAny
( type - event - type )
( window ( g - object - window ) )
;; (send-event (:boolean :int8))
;; (:nothing -1)
;; (:delete 0)
(: destroy 1 )
(: map 14 )
(: unmap 15 )
(: client - event 28 )
(: not - used 30 ) ; not used
(: damage 36 )
(test gdk-event-any
(let ((event (gdk-event-new :nothing)))
(is (typep event 'gdk-event))
;; Common slots
(is (eq :nothing (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))))
; ; GdkEventExpose
( (: expose ) - event - expose
( area gdk - rectangle : inline t : initform ( gdk - rectangle - new ) )
( region (: pointer (: struct cairo - region - t ) ) : initform ( null - pointer ) )
( count : int : initform 0 ) )
(test gdk-event-expose
(let ((event (gdk-event-new :expose)))
(is (typep event 'gdk-event-expose))
;; Common slots
(is (eq :expose (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
;; Slots for gdk-event-expose
(is (typep (gdk-event-expose-area event) 'gdk-rectangle))
(is-true (null-pointer-p (gdk-event-expose-region event)))
(is (= 0 (gdk-event-expose-count event)))))
;; ;; GdkEventMotion
( (: motion - notify ) - event - motion
( time : uint32 : initform 0 )
( x : double : initform 0.0d0 )
( y : double : initform 0.0d0 )
( axes ( fixed - array : double 2 ) : initform ' ( 0.0d0 0.0d0 ) )
( state - modifier - type : initform 0 )
( is - hint : int16 : initform 0 )
( device ( g - object gdk - device ) : initform ( null - pointer ) )
( x - root : double : initform 0.0d0 )
( y - root : double : initform 0.0d0 ) )
(test gdk-event-motion
(let ((event (gdk-event-new :motion-notify)))
(is (typep event 'gdk-event-motion))
;; Common slots
(is (eq :motion-notify (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
Slots for - event - motion
(is (= 0 (gdk-event-motion-time event)))
(is (= 0.0d0 (gdk-event-motion-x event)))
(is (= 0.0d0 (gdk-event-motion-y event)))
(is (equal '(0.0d0 0.0d0) (gdk-event-motion-axes event)))
(is (= 0 (gdk-event-motion-state event)))
(is (= 0 (gdk-event-motion-is-hint event)))
(is (null-pointer-p (gdk-event-motion-device event)))
(is (= 0.0d0 (gdk-event-motion-x-root event)))
(is (= 0.0d0 (gdk-event-motion-y-root event)))))
; ;
;; ((:button-press
: 2button - press
;; :double-button-press
: 3button - press
;; :triple-button-press
: button - release ) - event - button
( time : uint32 : initform 0 )
( x : double : initform 0.0d0 )
( y : double : initform 0.0d0 )
( axes ( fixed - array : double 2 ) : initform ' ( 0.0d0 0.0d0 ) )
( state - modifier - type : initform 0 )
( button : uint : initform 0 )
( device ( g - object gdk - device ) : initform ( null - pointer ) )
( x - root : double : initform 0.0d0 )
( y - root : double : initform 0.0d0 ) )
(test gdk-event-button.1
(let ((event (gdk-event-new :button-press)))
(is (typep event 'gdk-event-button))
;; Common slots
(is (eq :button-press (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
;; Slots for gdk-event-button
(is (= 0 (gdk-event-button-time event)))
(is (= 0.0d0 (gdk-event-button-x event)))
(is (= 0.0d0 (gdk-event-button-y event)))
(is (equal '(0.0d0 0.0d0) (gdk-event-button-axes event)))
(is (= 0 (gdk-event-button-state event)))
(is (= 0 (gdk-event-button-button event)))
(is (null-pointer-p (gdk-event-button-device event)))
(is (= 0.0d0 (gdk-event-button-x-root event)))
(is (= 0.0d0 (gdk-event-button-y-root event)))))
(test gdk-event-button.2
(let ((event (gdk-event-new :double-button-press)))
(is (typep event 'gdk-event-button))
;; Common slots
(is (eq :double-button-press (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
;; Slots for gdk-event-button
(is (= 0 (gdk-event-button-time event)))
(is (= 0.0d0 (gdk-event-button-x event)))
(is (= 0.0d0 (gdk-event-button-y event)))
(is (equal '(0.0d0 0.0d0) (gdk-event-button-axes event)))
(is (= 0 (gdk-event-button-state event)))
(is (= 0 (gdk-event-button-button event)))
(is (null-pointer-p (gdk-event-button-device event)))
(is (= 0.0d0 (gdk-event-button-x-root event)))
(is (= 0.0d0 (gdk-event-button-y-root event)))))
(test gdk-event-button.3
(let ((event (gdk-event-new :triple-button-press)))
(is (typep event 'gdk-event-button))
;; Common slots
(is (eq :triple-button-press (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
;; Slots for gdk-event-button
(is (= 0 (gdk-event-button-time event)))
(is (= 0.0d0 (gdk-event-button-x event)))
(is (= 0.0d0 (gdk-event-button-y event)))
(is (equal '(0.0d0 0.0d0) (gdk-event-button-axes event)))
(is (= 0 (gdk-event-button-state event)))
(is (= 0 (gdk-event-button-button event)))
(is (null-pointer-p (gdk-event-button-device event)))
(is (= 0.0d0 (gdk-event-button-x-root event)))
(is (= 0.0d0 (gdk-event-button-y-root event)))))
(test gdk-event-button.4
(let ((event (gdk-event-new :button-release)))
(is (typep event 'gdk-event-button))
;; Common slots
(is (eq :button-release (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
;; Slots for gdk-event-button
(is (= 0 (gdk-event-button-time event)))
(is (= 0.0d0 (gdk-event-button-x event)))
(is (= 0.0d0 (gdk-event-button-y event)))
(is (equal '(0.0d0 0.0d0) (gdk-event-button-axes event)))
(is (= 0 (gdk-event-button-state event)))
(is (= 0 (gdk-event-button-button event)))
(is (null-pointer-p (gdk-event-button-device event)))
(is (= 0.0d0 (gdk-event-button-x-root event)))
(is (= 0.0d0 (gdk-event-button-y-root event)))))
; ; GdkEventKey
( (: key - press : key - release ) - event - key
( time : uint32 : initform 0 )
( state - modifier - type : initform 0 )
( keyval : uint : initform 0 )
( length : int : initform 0 )
;; (string (:string :free-from-foreign nil
;; :free-to-foreign nil)
: initform " " )
( hardware - keycode : uint16 : initform 0 )
( group : uint8 : initform 0 )
( is - modifier : uint : initform 0 ) )
(test gdk-event-key.1
(let ((event (gdk-event-new :key-press)))
(is (typep event 'gdk-event-key))
;; Common slots
(is (eq :key-press (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
;; Slots for gdk-event-key
(is (= 0 (gdk-event-key-time event)))
(is (= 0 (gdk-event-key-state event)))
(is (= 0 (gdk-event-key-keyval event)))
(is (= 0 (gdk-event-key-length event)))
(is (string= "" (gdk-event-key-string event)))
(is (= 0 (gdk-event-key-hardware-keycode event)))
(is (= 0 (gdk-event-key-group event)))
(is (= 0 (gdk-event-key-is-modifier event)))))
(test gdk-event-key.2
(let ((event (gdk-event-new :key-release)))
(is (typep event 'gdk-event-key))
;; Common slots
(is (eq :key-release (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
;; Slots for gdk-event-key
(is (= 0 (gdk-event-key-time event)))
(is (= 0 (gdk-event-key-state event)))
(is (= 0 (gdk-event-key-keyval event)))
(is (= 0 (gdk-event-key-length event)))
(is (string= "" (gdk-event-key-string event)))
(is (= 0 (gdk-event-key-hardware-keycode event)))
(is (= 0 (gdk-event-key-group event)))
(is (= 0 (gdk-event-key-is-modifier event)))))
;; ;; GdkEventCrossing
( (: enter - notify : leave - notify ) - event - crossing
( subwindow ( g - object - window ) )
( time : )
;; (x :double)
;; (y :double)
;; (x-root :double)
;; (y-root :double)
( mode - crossing - mode )
( detail - notify - type )
;; (focus :boolean)
;; (state :uint))
(test gdk-event-crossing
(let ((event (gdk-event-new :enter-notify)))
(is (typep event 'gdk-event-crossing))
;; Common slots
(is (eq :enter-notify (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
;; Slots for gdk-event-crossing
(is (null-pointer-p (gdk-event-crossing-subwindow event)))
(is (= 0 (gdk-event-crossing-time event)))
(is (= 0.0d0 (gdk-event-crossing-x event)))
(is (= 0.0d0 (gdk-event-crossing-y event)))
(is (= 0.0d0 (gdk-event-crossing-x-root event)))
(is (= 0.0d0 (gdk-event-crossing-y-root event)))
(is (eq :normal (gdk-event-crossing-mode event)))
(is (eq :ancestor (gdk-event-crossing-detail event)))
(is-false (gdk-event-crossing-focus event))
(is (= 0 (gdk-event-crossing-state event)))))
; ; GdkEventFocus
( (: focus - change ) - event - focus
( in : int16 : initform 0 ) )
(test gdk-event-focus
(let ((event (gdk-event-new :focus-change)))
(is (typep event 'gdk-event-focus))
;; Common slots
(is (eq :focus-change (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
;; Slots for gdk-event-focus
(is (= 0 (gdk-event-focus-in event)))))
;; ;; GdkEventConfigure
( (: configure ) - event - configure
( x : int : initform 0 )
( y : int : initform 0 )
( width : int : initform 0 )
( height : int : initform 0 ) )
(test gdk-event-configure
(let ((event (gdk-event-new :configure)))
(is (typep event 'gdk-event-configure))
;; Common slots
(is (eq :configure (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
;; Slots for gdk-event-configure
(is (= 0 (gdk-event-configure-x event)))
(is (= 0 (gdk-event-configure-y event)))
(is (= 0 (gdk-event-configure-width event)))
(is (= 0 (gdk-event-configure-height event)))))
;; ;; GdkEventProperty
( (: property - notify ) - event - property
;; (atom gdk-atom :init-form (null-pointer))
( time : uint32 : initform 0 )
( state - property - state : init - from : new - value ) )
(test gdk-event-property
(let ((event (gdk-event-new :property-notify)))
(is (typep event 'gdk-event-property))
;; Common slots
(is (eq :property-notify (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
Slots for - event - property
(is (null-pointer-p (gdk-event-property-atom event)))
(is (= 0 (gdk-event-property-time event)))
(is (eq :new-value (gdk-event-property-state event)))))
;; ;; GdkEventSelection
;; ((:selection-clear
;; :selection-notify
: selection - request ) - event - selection
( selection gdk - atom : initform ( null - pointer ) )
( target gdk - atom : initform ( null - poiner ) )
( property gdk - atom : initform ( null - pointer ) )
( time : uint32 : initform 0 )
( requestor ( g - object - window ) ) )
(test gdk-event-selection
(let ((event (gdk-event-new :selection-clear)))
(is (typep event 'gdk-event-selection))
;; Common slots
(is (eq :selection-clear (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
Slots for - event - selection
(is (null-pointer-p (gdk-event-selection-selection event)))
(is (null-pointer-p (gdk-event-selection-target event)))
(is (null-pointer-p (gdk-event-selection-property event)))
(is (= 0 (gdk-event-selection-time event)))
(is-false (gdk-event-selection-requestor event))))
;; ;; GdkEventProximity
;; ((:proximity-in
;; :proximity-out) gdk-event-proximity
( time : uint32 : initform 0 )
;; (device (g-object gdk-device)))
(test gdk-event-proximity
(let ((event (gdk-event-new :proximity-in)))
(is (typep event 'gdk-event-proximity))
;; Common slots
(is (eq :proximity-in (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
;; Slots for gdk-event-proximity
(is (= 0 (gdk-event-proximity-time event)))
(is-false (gdk-event-proximity-device event))))
; ; GdkEventDND
;; ((:drag-enter
;; :drag-leave
;; :drag-motion
;; :drag-status
;; :drop-start
: drop - finished ) - event - dnd
;; (context (g-object gdk-drag-context))
( time : uint32 : initform 0 )
( x - root : short : initform 0 )
( y - root : short : initform 0 ) )
(test gdk-event-dnd
(let ((event (gdk-event-new :drag-enter)))
(is (typep event 'gdk-event-dnd))
;; Common slots
(is (eq :drag-enter (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
;; Slots for gdk-event-dnd
(is-false (gdk-event-dnd-context event))
(is (= 0 (gdk-event-dnd-time event)))
(is (= 0 (gdk-event-dnd-x-root event)))
(is (= 0 (gdk-event-dnd-y-root event)))))
;; ;; GdkEventVisibility
( (: visibility - notify ) - event - visibility
( state - visibility - state : initform : unobscured ) )
(test gdk-event-visibility
(let ((event (gdk-event-new :visibility-notify)))
(is (typep event 'gdk-event-visibility))
;; Common slots
(is (eq :visibility-notify (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
Slots for - event - visibility
(is (eq :unobscured (gdk-event-visibility-state event)))))
; ;
( (: scroll ) - event - scroll
( time : uint32 : initform 0 )
( x : double : initform 0.0d0 )
( y : double : initform 0.0d0 )
( state - modifier - type )
( direction - scroll - direction : initform : up )
;; (device (g-object gdk-device))
( x - root : double : initform 0.0d0 )
( y - root : double : initform 0.0d0 )
( delta - x : double : initform 0.0d0 )
( delta - y : double : initform 0.0d0 ) )
(test gdk-event-scroll
(let ((event (gdk-event-new :scroll)))
(is (typep event 'gdk-event-scroll))
;; Common slots
(is (eq :scroll (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
;; Slots for gdk-event-scroll
(is (= 0 (gdk-event-scroll-time event)))
(is (= 0 (gdk-event-scroll-x event)))
(is (= 0 (gdk-event-scroll-y event)))
(is-false (gdk-event-scroll-state event))
(is (eq :up (gdk-event-scroll-direction event)))
(is-false (gdk-event-scroll-device event))
(is (= 0 (gdk-event-scroll-x-root event)))
(is (= 0 (gdk-event-scroll-y-root event)))
(is (= 0 (gdk-event-scroll-delta-x event)))
(is (= 0 (gdk-event-scroll-delta-y event)))))
; ; GdkEventWindowState
( (: window - state ) - event - window - state
;; (changed-mask gdk-window-state)
( new - window - state - window - state ) )
(test gdk-event-window-state
(let ((event (gdk-event-new :window-state)))
(is (typep event 'gdk-event-window-state ))
;; Common slots
(is (eq :window-state (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
;; Slots for gdk-event-window-state
(is-false (gdk-event-window-state-changed-mask event))
(is-false (gdk-event-window-state-new-window-state event))))
;; ;; GdkEventSetting
( (: setting ) - event - setting
( action - setting - action : initform : new )
;; (name (:string :free-from-foreign nil :free-to-foreign nil)))
(test gdk-event-setting
(let ((event (gdk-event-new :setting)))
(is (typep event 'gdk-event-setting))
;; Common slots
(is (eq :setting (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
;; Slots for gdk-event-setting
(is (eq :new (gdk-event-setting-action event)))
(is-false (gdk-event-setting-name event))))
;; ;; GdkEventOwnerChange
( (: owner - change ) - event - owner - change
( owner ( g - object - window ) )
( reason - owner - change : initform : new - owner )
( selection gdk - atom : initform ( null - pointer ) )
( time : uint32 : initform 0 )
( selection - time : uint32 : initform 0 ) )
(test gdk-event-owner-change
(let ((event (gdk-event-new :owner-change)))
(is (typep event 'gdk-event-owner-change))
;; Common slots
(is (eq :owner-change (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
Slots for - event - owner - change
(is-false (gdk-event-owner-change-owner event))
(is (eq :new-owner (gdk-event-owner-change-reason event)))
(is (null-pointer-p (gdk-event-owner-change-selection event)))
(is (= 0 (gdk-event-owner-change-time event)))
(is (= 0 (gdk-event-owner-change-selection-time event)))))
;; ;; GdkEventGrabBroken
( (: grab - broken ) - event - grab - broken
;; (keyboard :boolean)
;; (implicit :boolean)
( grab - window ( g - object - window ) ) )
(test gdk-event-grab-broken
(let ((event (gdk-event-new :grab-broken)))
(is (typep event 'gdk-event-grab-broken))
;; Common slots
(is (eq :grab-broken (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
Slots for - event - grab - broken
(is-false (gdk-event-grab-broken-keyboard event))
(is-false (gdk-event-grab-broken-implicit event))
(is-false (gdk-event-grab-broken-grab-window event))))
;; ;; GdkEventTouch
;; ((:touch-begin
;; :touch-update
;; :touch-end
: touch - cancel ) - event - touch
( time : uint32 : initform 0 )
( x : double : initform 0.0d0 )
( y : double : initform 0.0d0 )
( axes ( fixed - array : double 2 ) : initform ' ( 0.0d0 0.0d0 ) )
( state - modifier - type )
; ; FIXME : We can not initialize sequence from the Lisp side .
( sequence ( g - boxed - foreign - event - sequence ) )
;; (emulating-pointer :boolean)
;; (device (g-object gdk-device))
( x - root : double : initform 0.0d0 )
( y - root : double : initform 0.0d0 ) )
(test gdk-event-touch
(let ((event (gdk-event-new :touch-begin)))
(is (typep event 'gdk-event-touch))
;; Common slots
(is (eq :touch-begin (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
;; Slots for gdk-event-touch
(is (= 0 (gdk-event-touch-time event)))
(is (= 0 (gdk-event-touch-x event)))
(is (= 0 (gdk-event-touch-y event)))
(is (equal '(0.0d0 0.0d0) (gdk-event-touch-axes event)))
(is-false (gdk-event-touch-state event))
;; FIXME: We can not initialize sequence from Lisp side
(is-false (gdk-event-touch-sequence event))
(is-false (gdk-event-touch-emulating-pointer event))
(is-false (gdk-event-touch-device event))
(is (= 0 (gdk-event-touch-x-root event)))
(is (= 0 (gdk-event-touch-y-root event)))))
;; ;; GdkEventTouchpadSwipe
( (: touchpad - swipe ) - event - touchpad - swipe
;; (phase :int8)
( n - fingers : int8 : initform 0 )
( time : uint32 : initform 0 )
( x : double : initform 0.0d0 )
( y : double : initform 0.0d0 )
( dx : double : initform 0.0d0 )
( dy : double : initform 0.0d0 )
( x - root : double : initform 0.0d0 )
( y - root : double : initform 0.0d0 )
( state - modifier - type ) )
(test gdk-event-touchpad-swipe
(let ((event (gdk-event-new :touchpad-swipe)))
(is (typep event 'gdk-event-touchpad-swipe))
;; Common slots
(is (eq :touchpad-swipe (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
;; Slots for gdk-event-touchpad-swipe
(is (= 0 (gdk-event-touchpad-swipe-phase event)))
(is (= 0 (gdk-event-touchpad-swipe-n-fingers event)))
(is (= 0 (gdk-event-touchpad-swipe-time event)))
(is (= 0 (gdk-event-touchpad-swipe-x event)))
(is (= 0 (gdk-event-touchpad-swipe-y event)))
(is (= 0 (gdk-event-touchpad-swipe-dx event)))
(is (= 0 (gdk-event-touchpad-swipe-dy event)))
(is (= 0 (gdk-event-touchpad-swipe-x-root event)))
(is (= 0 (gdk-event-touchpad-swipe-y-root event)))
(is-false (gdk-event-touchpad-swipe-state event))))
;; ;; GdkEventTouchpadPinch
;; ((:touchpad-pinch) gdk-event-touchpad-pinch
( phase : int8 : initform 0 )
( n - fingers : int8 : initform 0 )
( time : uint32 : initform 0 )
( x : double : initform 0.0d0 )
( y : double : initform 0.0d0 )
( dx : double : initform 0.0d0 )
( dy : double : initform 0.0d0 )
( angle - delta : double : initform 0.0d0 )
( scale : double : initform 0.0d0 )
( x - root : double : initform 0.0d0 )
( y - root : double : initform 0.0d0 )
( state - modifier - type ) )
(test gdk-event-touchpad-pinch
(let ((event (gdk-event-new :touchpad-pinch)))
(is (typep event 'gdk-event-touchpad-pinch))
;; Common slots
(is (eq :touchpad-pinch (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
;; Slots for gdk-event-touchpad-pinch
(is (= 0 (gdk-event-touchpad-pinch-phase event)))
(is (= 0 (gdk-event-touchpad-pinch-n-fingers event)))
(is (= 0 (gdk-event-touchpad-pinch-time event)))
(is (= 0 (gdk-event-touchpad-pinch-x event)))
(is (= 0 (gdk-event-touchpad-pinch-y event)))
(is (= 0 (gdk-event-touchpad-pinch-dx event)))
(is (= 0 (gdk-event-touchpad-pinch-dy event)))
(is (= 0 (gdk-event-touchpad-pinch-angle-delta event)))
(is (= 0 (gdk-event-touchpad-pinch-scale event)))
(is (= 0 (gdk-event-touchpad-pinch-x-root event)))
(is (= 0 (gdk-event-touchpad-pinch-y-root event)))
(is-false (gdk-event-touchpad-pinch-state event))))
;; ;; GdkEventPadButton
( (: pad - button - press : pad - button - release ) - event - pad - button
( time : uint32 : initform 0 )
( group : uint : initform 0 )
( button : uint : initform 0 )
( mode : uint : initform 0 ) ) ; TODO : Check the type of mode
(test gdk-event-pad-button
(let ((event (gdk-event-new :pad-button-press)))
(is (typep event 'gdk-event-pad-button))
;; Common slots
(is (eq :pad-button-press (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
;; Slots for gdk-event-pad-button
(is (= 0 (gdk-event-pad-button-time event)))
(is (= 0 (gdk-event-pad-button-group event)))
(is (= 0 (gdk-event-pad-button-button event)))
(is (= 0 (gdk-event-pad-button-mode event)))))
;; ;; GdkEventPadAxis
( (: pad - ring : pad - strip ) - event - pad - axis
( time : uint32 : initform 0 )
( group : uint : initform 0 )
( index : uint : initform 0 )
( mode : uint : initform 0 )
( value : double : initform 0.0d0 ) )
(test gdk-event-pad-axis
(let ((event (gdk-event-new :pad-ring)))
(is (typep event 'gdk-event-pad-axis))
;; Common slots
(is (eq :pad-ring (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
;; Slots for gdk-event-pad-axis
(is (= 0 (gdk-event-pad-axis-time event)))
(is (= 0 (gdk-event-pad-axis-group event)))
(is (= 0 (gdk-event-pad-axis-index event)))
(is (= 0 (gdk-event-pad-axis-mode event)))
(is (= 0 (gdk-event-pad-axis-value event)))))
; ;
;; ((:pad-group-mode) gdk-event-pad-group-mode
( time : uint32 : initform 0 )
( group : uint : initform 0 )
( mode : uint : initform 0 ) )
(test gdk-event-pad-group-mode
(let ((event (gdk-event-new :pad-group-mode)))
(is (typep event 'gdk-event-pad-group-mode))
;; Common slots
(is (eq :pad-group-mode (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
;; Slots for gdk-event-pad-group-mode
(is (= 0 (gdk-event-pad-group-mode-time event)))
(is (= 0 (gdk-event-pad-group-mode-group event)))
(is (= 0 (gdk-event-pad-group-mode-mode event)))))
2021 - 4 - 25
| null | https://raw.githubusercontent.com/crategus/cl-cffi-gtk/da748ec5300141e9f07aabeeab7a9acb2b37ecf2/test/rtest-gdk-event-structures.lisp | lisp | GdkScrollDirection
Check the type
Check the type initializer
Check the registered name
Check the names
Check the values
Check the enum definition
GdkVisibilityState
Check the type
Check the type initializer
Check the registered name
Check the names
Check the values
Check the enum definition
GdkCrossingMode
Check the type
Check the type initializer
Check the registered name
Check the names
Check the values
Check the enum definition
GdkNotifyType
Check the type
Check the type initializer
Check the registered name
Check the names
Check the values
Check the enum definition
GdkPropertyState
Check the type
Check the type initializer
Check the registered name
Check the names
Check the values
Check the enum definition
Check the type
Check the registered name
Check the type initializer
Check the names
Check the values
Check the flags definition
GdkSettingAction
Check the type
Check the type initializer
Check the registered name
Check the names
Check the values
Check the enum definition
GdkOwnerChange
Check the type
Check the type initializer
Check the registered name
Check the names
Check the values
Check the enum definition
GdkEventType <-- gdk.events.lisp
Check the type
Check the type initializer
Check the registered name
Check the names
Check the values
Check the enum definition
GdkModifierType <-- gdk.window.lisp
Check the type
Check the registered name
Check the type initializer
Check the names
Check the values
Check the flags definition
GdkEventMask <-- gdk.events.lisp
Check the type
Check the registered name
Check the type initializer
Check the names
Check the values
Check the flags definition
GdkEventSequence <-- gdk-events.lisp
Type check
Check the type initializer
GdkEventAny
(send-event (:boolean :int8))
(:nothing -1)
(:delete 0)
not used
Common slots
; GdkEventExpose
Common slots
Slots for gdk-event-expose
;; GdkEventMotion
Common slots
;
((:button-press
:double-button-press
:triple-button-press
Common slots
Slots for gdk-event-button
Common slots
Slots for gdk-event-button
Common slots
Slots for gdk-event-button
Common slots
Slots for gdk-event-button
; GdkEventKey
(string (:string :free-from-foreign nil
:free-to-foreign nil)
Common slots
Slots for gdk-event-key
Common slots
Slots for gdk-event-key
;; GdkEventCrossing
(x :double)
(y :double)
(x-root :double)
(y-root :double)
(focus :boolean)
(state :uint))
Common slots
Slots for gdk-event-crossing
; GdkEventFocus
Common slots
Slots for gdk-event-focus
;; GdkEventConfigure
Common slots
Slots for gdk-event-configure
;; GdkEventProperty
(atom gdk-atom :init-form (null-pointer))
Common slots
;; GdkEventSelection
((:selection-clear
:selection-notify
Common slots
;; GdkEventProximity
((:proximity-in
:proximity-out) gdk-event-proximity
(device (g-object gdk-device)))
Common slots
Slots for gdk-event-proximity
; GdkEventDND
((:drag-enter
:drag-leave
:drag-motion
:drag-status
:drop-start
(context (g-object gdk-drag-context))
Common slots
Slots for gdk-event-dnd
;; GdkEventVisibility
Common slots
;
(device (g-object gdk-device))
Common slots
Slots for gdk-event-scroll
; GdkEventWindowState
(changed-mask gdk-window-state)
Common slots
Slots for gdk-event-window-state
;; GdkEventSetting
(name (:string :free-from-foreign nil :free-to-foreign nil)))
Common slots
Slots for gdk-event-setting
;; GdkEventOwnerChange
Common slots
;; GdkEventGrabBroken
(keyboard :boolean)
(implicit :boolean)
Common slots
;; GdkEventTouch
((:touch-begin
:touch-update
:touch-end
; FIXME : We can not initialize sequence from the Lisp side .
(emulating-pointer :boolean)
(device (g-object gdk-device))
Common slots
Slots for gdk-event-touch
FIXME: We can not initialize sequence from Lisp side
;; GdkEventTouchpadSwipe
(phase :int8)
Common slots
Slots for gdk-event-touchpad-swipe
;; GdkEventTouchpadPinch
((:touchpad-pinch) gdk-event-touchpad-pinch
Common slots
Slots for gdk-event-touchpad-pinch
;; GdkEventPadButton
TODO : Check the type of mode
Common slots
Slots for gdk-event-pad-button
;; GdkEventPadAxis
Common slots
Slots for gdk-event-pad-axis
;
((:pad-group-mode) gdk-event-pad-group-mode
Common slots
Slots for gdk-event-pad-group-mode | (def-suite gdk-event-structures :in gdk-suite)
(in-suite gdk-event-structures)
(test gdk-scroll-direction
(is-true (g-type-is-enum "GdkScrollDirection"))
(is (eq (gtype "GdkScrollDirection")
(gtype (foreign-funcall "gdk_scroll_direction_get_type" g-size))))
(is (eq 'gdk-scroll-direction
(registered-enum-type "GdkScrollDirection")))
(is (equal '("GDK_SCROLL_UP" "GDK_SCROLL_DOWN" "GDK_SCROLL_LEFT"
"GDK_SCROLL_RIGHT" "GDK_SCROLL_SMOOTH")
(mapcar #'enum-item-name
(get-enum-items "GdkScrollDirection"))))
(is (equal '(0 1 2 3 4)
(mapcar #'enum-item-value
(get-enum-items "GdkScrollDirection"))))
Check the nick names
(is (equal '("up" "down" "left" "right" "smooth")
(mapcar #'enum-item-nick
(get-enum-items "GdkScrollDirection"))))
(is (equal '(DEFINE-G-ENUM "GdkScrollDirection"
GDK-SCROLL-DIRECTION
(:EXPORT T
:TYPE-INITIALIZER "gdk_scroll_direction_get_type")
(:UP 0)
(:DOWN 1)
(:LEFT 2)
(:RIGHT 3)
(:SMOOTH 4))
(get-g-type-definition "GdkScrollDirection"))))
(test gdk-visibility-state
(is-true (g-type-is-enum "GdkVisibilityState"))
(is (eq (gtype "GdkVisibilityState")
(gtype (foreign-funcall "gdk_visibility_state_get_type" g-size))))
(is (eq 'gdk-visibility-state
(registered-enum-type "GdkVisibilityState")))
(is (equal '("GDK_VISIBILITY_UNOBSCURED" "GDK_VISIBILITY_PARTIAL"
"GDK_VISIBILITY_FULLY_OBSCURED")
(mapcar #'enum-item-name
(get-enum-items "GdkVisibilityState"))))
(is (equal '(0 1 2)
(mapcar #'enum-item-value
(get-enum-items "GdkVisibilityState"))))
Check the nick names
(is (equal '("unobscured" "partial" "fully-obscured")
(mapcar #'enum-item-nick
(get-enum-items "GdkVisibilityState"))))
(is (equal '(DEFINE-G-ENUM "GdkVisibilityState"
GDK-VISIBILITY-STATE
(:EXPORT T
:TYPE-INITIALIZER "gdk_visibility_state_get_type")
(:UNOBSCURED 0)
(:PARTIAL 1)
(:FULLY-OBSCURED 2))
(get-g-type-definition "GdkVisibilityState"))))
(test gdk-crossing-mode
(is-true (g-type-is-enum "GdkCrossingMode"))
(is (eq (gtype "GdkCrossingMode")
(gtype (foreign-funcall "gdk_crossing_mode_get_type" g-size))))
(is (eq 'gdk-crossing-mode
(registered-enum-type "GdkCrossingMode")))
(is (equal '("GDK_CROSSING_NORMAL" "GDK_CROSSING_GRAB" "GDK_CROSSING_UNGRAB"
"GDK_CROSSING_GTK_GRAB" "GDK_CROSSING_GTK_UNGRAB"
"GDK_CROSSING_STATE_CHANGED" "GDK_CROSSING_TOUCH_BEGIN"
"GDK_CROSSING_TOUCH_END" "GDK_CROSSING_DEVICE_SWITCH")
(mapcar #'enum-item-name
(get-enum-items "GdkCrossingMode"))))
(is (equal '(0 1 2 3 4 5 6 7 8)
(mapcar #'enum-item-value
(get-enum-items "GdkCrossingMode"))))
Check the nick names
(is (equal '("normal" "grab" "ungrab" "gtk-grab" "gtk-ungrab" "state-changed"
"touch-begin" "touch-end" "device-switch")
(mapcar #'enum-item-nick
(get-enum-items "GdkCrossingMode"))))
(is (equal '(DEFINE-G-ENUM "GdkCrossingMode"
GDK-CROSSING-MODE
(:EXPORT T
:TYPE-INITIALIZER "gdk_crossing_mode_get_type")
(:NORMAL 0)
(:GRAB 1)
(:UNGRAB 2)
(:GTK-GRAB 3)
(:GTK-UNGRAB 4)
(:STATE-CHANGED 5)
(:TOUCH-BEGIN 6)
(:TOUCH-END 7)
(:DEVICE-SWITCH 8))
(get-g-type-definition "GdkCrossingMode"))))
(test gdk-notify-type
(is-true (g-type-is-enum "GdkNotifyType"))
(is (eq (gtype "GdkNotifyType")
(gtype (foreign-funcall "gdk_notify_type_get_type" g-size))))
(is (eq 'gdk-notify-type (registered-enum-type "GdkNotifyType")))
(is (equal '("GDK_NOTIFY_ANCESTOR" "GDK_NOTIFY_VIRTUAL" "GDK_NOTIFY_INFERIOR"
"GDK_NOTIFY_NONLINEAR" "GDK_NOTIFY_NONLINEAR_VIRTUAL"
"GDK_NOTIFY_UNKNOWN")
(mapcar #'enum-item-name
(get-enum-items "GdkNotifyType"))))
(is (equal '(0 1 2 3 4 5)
(mapcar #'enum-item-value
(get-enum-items "GdkNotifyType"))))
Check the nick names
(is (equal '("ancestor" "virtual" "inferior" "nonlinear" "nonlinear-virtual"
"unknown")
(mapcar #'enum-item-nick
(get-enum-items "GdkNotifyType"))))
(is (equal '(DEFINE-G-ENUM "GdkNotifyType"
GDK-NOTIFY-TYPE
(:EXPORT T
:TYPE-INITIALIZER "gdk_notify_type_get_type")
(:ANCESTOR 0)
(:VIRTUAL 1)
(:INFERIOR 2)
(:NONLINEAR 3)
(:NONLINEAR-VIRTUAL 4)
(:UNKNOWN 5))
(get-g-type-definition "GdkNotifyType"))))
(test gdk-property-state
(is-true (g-type-is-enum "GdkPropertyState"))
(is (eq (gtype "GdkPropertyState")
(gtype (foreign-funcall "gdk_property_state_get_type" g-size))))
(is (eq 'gdk-property-state (registered-enum-type "GdkPropertyState")))
(is (equal '("GDK_PROPERTY_NEW_VALUE" "GDK_PROPERTY_DELETE")
(mapcar #'enum-item-name
(get-enum-items "GdkPropertyState"))))
(is (equal '(0 1)
(mapcar #'enum-item-value
(get-enum-items "GdkPropertyState"))))
Check the nick names
(is (equal '("new-value" "delete")
(mapcar #'enum-item-nick
(get-enum-items "GdkPropertyState"))))
(is (equal '(DEFINE-G-ENUM "GdkPropertyState"
GDK-PROPERTY-STATE
(:EXPORT T
:TYPE-INITIALIZER "gdk_property_state_get_type")
(:NEW-VALUE 0)
(:DELETE 1))
(get-g-type-definition "GdkPropertyState"))))
GdkWindowState
(test gdk-window-state
(is (g-type-is-flags "GdkWindowState"))
(is (eq 'gdk-window-state
(registered-flags-type "GdkWindowState")))
(is (eq (gtype "GdkWindowState")
(gtype (foreign-funcall "gdk_window_state_get_type" g-size))))
(is (equal '("GDK_WINDOW_STATE_WITHDRAWN" "GDK_WINDOW_STATE_ICONIFIED"
"GDK_WINDOW_STATE_MAXIMIZED" "GDK_WINDOW_STATE_STICKY"
"GDK_WINDOW_STATE_FULLSCREEN" "GDK_WINDOW_STATE_ABOVE"
"GDK_WINDOW_STATE_BELOW" "GDK_WINDOW_STATE_FOCUSED"
"GDK_WINDOW_STATE_TILED" "GDK_WINDOW_STATE_TOP_TILED"
"GDK_WINDOW_STATE_TOP_RESIZABLE" "GDK_WINDOW_STATE_RIGHT_TILED"
"GDK_WINDOW_STATE_RIGHT_RESIZABLE"
"GDK_WINDOW_STATE_BOTTOM_TILED"
"GDK_WINDOW_STATE_BOTTOM_RESIZABLE"
"GDK_WINDOW_STATE_LEFT_TILED" "GDK_WINDOW_STATE_LEFT_RESIZABLE")
(mapcar #'flags-item-name
(get-flags-items "GdkWindowState"))))
(is (equal '(1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768
65536)
(mapcar #'flags-item-value
(get-flags-items "GdkWindowState"))))
Check the nick names
(is (equal '("withdrawn" "iconified" "maximized" "sticky" "fullscreen" "above"
"below" "focused" "tiled" "top-tiled" "top-resizable"
"right-tiled" "right-resizable" "bottom-tiled" "bottom-resizable"
"left-tiled" "left-resizable")
(mapcar #'flags-item-nick
(get-flags-items "GdkWindowState"))))
(is (equal '(DEFINE-G-FLAGS "GdkWindowState"
GDK-WINDOW-STATE
(:EXPORT T
:TYPE-INITIALIZER "gdk_window_state_get_type")
(:WITHDRAWN 1)
(:ICONIFIED 2)
(:MAXIMIZED 4)
(:STICKY 8)
(:FULLSCREEN 16)
(:ABOVE 32)
(:BELOW 64)
(:FOCUSED 128)
(:TILED 256)
(:TOP-TILED 512)
(:TOP-RESIZABLE 1024)
(:RIGHT-TILED 2048)
(:RIGHT-RESIZABLE 4096)
(:BOTTOM-TILED 8192)
(:BOTTOM-RESIZABLE 16384)
(:LEFT-TILED 32768)
(:LEFT-RESIZABLE 65536))
(get-g-type-definition "GdkWindowState"))))
(test gdk-setting-action
(is-true (g-type-is-enum "GdkSettingAction"))
(is (eq (gtype "GdkSettingAction")
(gtype (foreign-funcall "gdk_setting_action_get_type" g-size))))
(is (eq 'gdk-setting-action (registered-enum-type "GdkSettingAction")))
(is (equal '("GDK_SETTING_ACTION_NEW" "GDK_SETTING_ACTION_CHANGED"
"GDK_SETTING_ACTION_DELETED")
(mapcar #'enum-item-name
(get-enum-items "GdkSettingAction"))))
(is (equal '(0 1 2)
(mapcar #'enum-item-value
(get-enum-items "GdkSettingAction"))))
Check the nick names
(is (equal '("new" "changed" "deleted")
(mapcar #'enum-item-nick
(get-enum-items "GdkSettingAction"))))
(is (equal '(DEFINE-G-ENUM "GdkSettingAction"
GDK-SETTING-ACTION
(:EXPORT T
:TYPE-INITIALIZER "gdk_setting_action_get_type")
(:NEW 0)
(:CHANGED 1)
(:DELETED 2))
(get-g-type-definition "GdkSettingAction"))))
(test gdk-owner-change
(is-true (g-type-is-enum "GdkOwnerChange"))
(is (eq (gtype "GdkOwnerChange")
(gtype (foreign-funcall "gdk_owner_change_get_type" g-size))))
(is (eq 'gdk-owner-change (registered-enum-type "GdkOwnerChange")))
(is (equal '("GDK_OWNER_CHANGE_NEW_OWNER" "GDK_OWNER_CHANGE_DESTROY"
"GDK_OWNER_CHANGE_CLOSE")
(mapcar #'enum-item-name
(get-enum-items "GdkOwnerChange"))))
(is (equal '(0 1 2)
(mapcar #'enum-item-value
(get-enum-items "GdkOwnerChange"))))
Check the nick names
(is (equal '("new-owner" "destroy" "close")
(mapcar #'enum-item-nick
(get-enum-items "GdkOwnerChange"))))
(is (equal '(DEFINE-G-ENUM "GdkOwnerChange"
GDK-OWNER-CHANGE
(:EXPORT T
:TYPE-INITIALIZER "gdk_owner_change_get_type")
(:NEW-OWNER 0)
(:DESTROY 1)
(:CLOSE 2))
(get-g-type-definition "GdkOwnerChange"))))
(test gdk-event-type
(is-true (g-type-is-enum "GdkEventType"))
(is (eq (gtype "GdkEventType")
(gtype (foreign-funcall "gdk_event_type_get_type" g-size))))
(is (eq 'gdk-event-type (registered-enum-type "GdkEventType")))
(is (equal '("GDK_NOTHING" "GDK_DELETE" "GDK_DESTROY" "GDK_EXPOSE"
"GDK_MOTION_NOTIFY" "GDK_BUTTON_PRESS" "GDK_2BUTTON_PRESS"
"GDK_DOUBLE_BUTTON_PRESS" "GDK_3BUTTON_PRESS"
"GDK_TRIPLE_BUTTON_PRESS" "GDK_BUTTON_RELEASE" "GDK_KEY_PRESS"
"GDK_KEY_RELEASE" "GDK_ENTER_NOTIFY" "GDK_LEAVE_NOTIFY"
"GDK_FOCUS_CHANGE" "GDK_CONFIGURE" "GDK_MAP" "GDK_UNMAP"
"GDK_PROPERTY_NOTIFY" "GDK_SELECTION_CLEAR"
"GDK_SELECTION_REQUEST" "GDK_SELECTION_NOTIFY" "GDK_PROXIMITY_IN"
"GDK_PROXIMITY_OUT" "GDK_DRAG_ENTER" "GDK_DRAG_LEAVE"
"GDK_DRAG_MOTION" "GDK_DRAG_STATUS" "GDK_DROP_START"
"GDK_DROP_FINISHED" "GDK_CLIENT_EVENT" "GDK_VISIBILITY_NOTIFY"
"GDK_SCROLL" "GDK_WINDOW_STATE" "GDK_SETTING" "GDK_OWNER_CHANGE"
"GDK_GRAB_BROKEN" "GDK_DAMAGE" "GDK_TOUCH_BEGIN"
"GDK_TOUCH_UPDATE" "GDK_TOUCH_END" "GDK_TOUCH_CANCEL"
"GDK_TOUCHPAD_SWIPE" "GDK_TOUCHPAD_PINCH" "GDK_PAD_BUTTON_PRESS"
"GDK_PAD_BUTTON_RELEASE" "GDK_PAD_RING" "GDK_PAD_STRIP"
"GDK_PAD_GROUP_MODE" "GDK_EVENT_LAST")
(mapcar #'enum-item-name
(get-enum-items "GdkEventType"))))
(is (equal '(-1 0 1 2 3 4 5 5 6 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
22 23 24 25 26 27 28 29 31 32 33 34 35 36 37 38 39 40 41 42 43
44 45 46 47 48)
(mapcar #'enum-item-value
(get-enum-items "GdkEventType"))))
Check the nick names
(is (equal '("nothing" "delete" "destroy" "expose" "motion-notify"
"button-press" "2button-press" "double-button-press"
"3button-press" "triple-button-press" "button-release"
"key-press" "key-release" "enter-notify" "leave-notify"
"focus-change" "configure" "map" "unmap" "property-notify"
"selection-clear" "selection-request" "selection-notify"
"proximity-in" "proximity-out" "drag-enter" "drag-leave"
"drag-motion" "drag-status" "drop-start" "drop-finished"
"client-event" "visibility-notify" "scroll" "window-state"
"setting" "owner-change" "grab-broken" "damage" "touch-begin"
"touch-update" "touch-end" "touch-cancel" "touchpad-swipe"
"touchpad-pinch" "pad-button-press" "pad-button-release"
"pad-ring" "pad-strip" "pad-group-mode" "event-last")
(mapcar #'enum-item-nick
(get-enum-items "GdkEventType"))))
(is (equal '(DEFINE-G-ENUM "GdkEventType"
GDK-EVENT-TYPE
(:EXPORT T
:TYPE-INITIALIZER "gdk_event_type_get_type")
(:NOTHING -1)
(:DELETE 0)
(:DESTROY 1)
(:EXPOSE 2)
(:MOTION-NOTIFY 3)
(:BUTTON-PRESS 4)
(:2BUTTON-PRESS 5)
(:DOUBLE-BUTTON-PRESS 5)
(:3BUTTON-PRESS 6)
(:TRIPLE-BUTTON-PRESS 6)
(:BUTTON-RELEASE 7)
(:KEY-PRESS 8)
(:KEY-RELEASE 9)
(:ENTER-NOTIFY 10)
(:LEAVE-NOTIFY 11)
(:FOCUS-CHANGE 12)
(:CONFIGURE 13)
(:MAP 14)
(:UNMAP 15)
(:PROPERTY-NOTIFY 16)
(:SELECTION-CLEAR 17)
(:SELECTION-REQUEST 18)
(:SELECTION-NOTIFY 19)
(:PROXIMITY-IN 20)
(:PROXIMITY-OUT 21)
(:DRAG-ENTER 22)
(:DRAG-LEAVE 23)
(:DRAG-MOTION 24)
(:DRAG-STATUS 25)
(:DROP-START 26)
(:DROP-FINISHED 27)
(:CLIENT-EVENT 28)
(:VISIBILITY-NOTIFY 29)
(:SCROLL 31)
(:WINDOW-STATE 32)
(:SETTING 33)
(:OWNER-CHANGE 34)
(:GRAB-BROKEN 35)
(:DAMAGE 36)
(:TOUCH-BEGIN 37)
(:TOUCH-UPDATE 38)
(:TOUCH-END 39)
(:TOUCH-CANCEL 40)
(:TOUCHPAD-SWIPE 41)
(:TOUCHPAD-PINCH 42)
(:PAD-BUTTON-PRESS 43)
(:PAD-BUTTON-RELEASE 44)
(:PAD-RING 45)
(:PAD-STRIP 46)
(:PAD-GROUP-MODE 47)
(:EVENT-LAST 48))
(get-g-type-definition "GdkEventType"))))
(test gdk-modifier-type
(is (g-type-is-flags "GdkModifierType"))
(is (eq 'gdk-modifier-type
(registered-flags-type "GdkModifierType")))
(is (eq (gtype "GdkModifierType")
(gtype (foreign-funcall "gdk_modifier_type_get_type" g-size))))
(is (equal '("GDK_SHIFT_MASK" "GDK_LOCK_MASK" "GDK_CONTROL_MASK"
"GDK_MOD1_MASK" "GDK_MOD2_MASK" "GDK_MOD3_MASK" "GDK_MOD4_MASK"
"GDK_MOD5_MASK" "GDK_BUTTON1_MASK" "GDK_BUTTON2_MASK"
"GDK_BUTTON3_MASK" "GDK_BUTTON4_MASK" "GDK_BUTTON5_MASK"
"GDK_MODIFIER_RESERVED_13_MASK" "GDK_MODIFIER_RESERVED_14_MASK"
"GDK_MODIFIER_RESERVED_15_MASK" "GDK_MODIFIER_RESERVED_16_MASK"
"GDK_MODIFIER_RESERVED_17_MASK" "GDK_MODIFIER_RESERVED_18_MASK"
"GDK_MODIFIER_RESERVED_19_MASK" "GDK_MODIFIER_RESERVED_20_MASK"
"GDK_MODIFIER_RESERVED_21_MASK" "GDK_MODIFIER_RESERVED_22_MASK"
"GDK_MODIFIER_RESERVED_23_MASK" "GDK_MODIFIER_RESERVED_24_MASK"
"GDK_MODIFIER_RESERVED_25_MASK" "GDK_SUPER_MASK" "GDK_HYPER_MASK"
"GDK_META_MASK" "GDK_MODIFIER_RESERVED_29_MASK"
"GDK_RELEASE_MASK" "GDK_MODIFIER_MASK")
(mapcar #'flags-item-name
(get-flags-items "GdkModifierType"))))
(is (equal '(1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768
65536 131072 262144 524288 1048576 2097152 4194304 8388608
16777216 33554432 67108864 134217728 268435456 536870912
1073741824 1543512063)
(mapcar #'flags-item-value
(get-flags-items "GdkModifierType"))))
Check the nick names
(is (equal '("shift-mask" "lock-mask" "control-mask" "mod1-mask" "mod2-mask"
"mod3-mask" "mod4-mask" "mod5-mask" "button1-mask" "button2-mask"
"button3-mask" "button4-mask" "button5-mask"
"modifier-reserved-13-mask" "modifier-reserved-14-mask"
"modifier-reserved-15-mask" "modifier-reserved-16-mask"
"modifier-reserved-17-mask" "modifier-reserved-18-mask"
"modifier-reserved-19-mask" "modifier-reserved-20-mask"
"modifier-reserved-21-mask" "modifier-reserved-22-mask"
"modifier-reserved-23-mask" "modifier-reserved-24-mask"
"modifier-reserved-25-mask" "super-mask" "hyper-mask" "meta-mask"
"modifier-reserved-29-mask" "release-mask" "modifier-mask")
(mapcar #'flags-item-nick
(get-flags-items "GdkModifierType"))))
(is (equal '(DEFINE-G-FLAGS "GdkModifierType"
GDK-MODIFIER-TYPE
(:EXPORT T
:TYPE-INITIALIZER "gdk_modifier_type_get_type")
(:SHIFT-MASK 1)
(:LOCK-MASK 2)
(:CONTROL-MASK 4)
(:MOD1-MASK 8)
(:MOD2-MASK 16)
(:MOD3-MASK 32)
(:MOD4-MASK 64)
(:MOD5-MASK 128)
(:BUTTON1-MASK 256)
(:BUTTON2-MASK 512)
(:BUTTON3-MASK 1024)
(:BUTTON4-MASK 2048)
(:BUTTON5-MASK 4096)
(:MODIFIER-RESERVED-13-MASK 8192)
(:MODIFIER-RESERVED-14-MASK 16384)
(:MODIFIER-RESERVED-15-MASK 32768)
(:MODIFIER-RESERVED-16-MASK 65536)
(:MODIFIER-RESERVED-17-MASK 131072)
(:MODIFIER-RESERVED-18-MASK 262144)
(:MODIFIER-RESERVED-19-MASK 524288)
(:MODIFIER-RESERVED-20-MASK 1048576)
(:MODIFIER-RESERVED-21-MASK 2097152)
(:MODIFIER-RESERVED-22-MASK 4194304)
(:MODIFIER-RESERVED-23-MASK 8388608)
(:MODIFIER-RESERVED-24-MASK 16777216)
(:MODIFIER-RESERVED-25-MASK 33554432)
(:SUPER-MASK 67108864)
(:HYPER-MASK 134217728)
(:META-MASK 268435456)
(:MODIFIER-RESERVED-29-MASK 536870912)
(:RELEASE-MASK 1073741824)
(:MODIFIER-MASK 1543512063))
(get-g-type-definition "GdkModifierType"))))
(test gdk-event-mask
(is (g-type-is-flags "GdkEventMask"))
(is (eq 'gdk-event-mask
(registered-flags-type "GdkEventMask")))
(is (eq (gtype "GdkEventMask")
(gtype (foreign-funcall "gdk_event_mask_get_type" g-size))))
(is (equal '("GDK_EXPOSURE_MASK" "GDK_POINTER_MOTION_MASK"
"GDK_POINTER_MOTION_HINT_MASK" "GDK_BUTTON_MOTION_MASK"
"GDK_BUTTON1_MOTION_MASK" "GDK_BUTTON2_MOTION_MASK"
"GDK_BUTTON3_MOTION_MASK" "GDK_BUTTON_PRESS_MASK"
"GDK_BUTTON_RELEASE_MASK" "GDK_KEY_PRESS_MASK"
"GDK_KEY_RELEASE_MASK" "GDK_ENTER_NOTIFY_MASK"
"GDK_LEAVE_NOTIFY_MASK" "GDK_FOCUS_CHANGE_MASK"
"GDK_STRUCTURE_MASK" "GDK_PROPERTY_CHANGE_MASK"
"GDK_VISIBILITY_NOTIFY_MASK" "GDK_PROXIMITY_IN_MASK"
"GDK_PROXIMITY_OUT_MASK" "GDK_SUBSTRUCTURE_MASK"
"GDK_SCROLL_MASK" "GDK_TOUCH_MASK" "GDK_SMOOTH_SCROLL_MASK"
"GDK_TOUCHPAD_GESTURE_MASK" "GDK_TABLET_PAD_MASK"
"GDK_ALL_EVENTS_MASK")
(mapcar #'flags-item-name
(get-flags-items "GdkEventMask"))))
(is (equal '(2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536
131072 262144 524288 1048576 2097152 4194304 8388608 16777216
33554432 67108862)
(mapcar #'flags-item-value
(get-flags-items "GdkEventMask"))))
Check the nick names
(is (equal '("exposure-mask" "pointer-motion-mask" "pointer-motion-hint-mask"
"button-motion-mask" "button1-motion-mask" "button2-motion-mask"
"button3-motion-mask" "button-press-mask" "button-release-mask"
"key-press-mask" "key-release-mask" "enter-notify-mask"
"leave-notify-mask" "focus-change-mask" "structure-mask"
"property-change-mask" "visibility-notify-mask"
"proximity-in-mask" "proximity-out-mask" "substructure-mask"
"scroll-mask" "touch-mask" "smooth-scroll-mask"
"touchpad-gesture-mask" "tablet-pad-mask" "all-events-mask")
(mapcar #'flags-item-nick
(get-flags-items "GdkEventMask"))))
(is (equal '(DEFINE-G-FLAGS "GdkEventMask"
GDK-EVENT-MASK
(:EXPORT T
:TYPE-INITIALIZER "gdk_event_mask_get_type")
(:EXPOSURE-MASK 2)
(:POINTER-MOTION-MASK 4)
(:POINTER-MOTION-HINT-MASK 8)
(:BUTTON-MOTION-MASK 16)
(:BUTTON1-MOTION-MASK 32)
(:BUTTON2-MOTION-MASK 64)
(:BUTTON3-MOTION-MASK 128)
(:BUTTON-PRESS-MASK 256)
(:BUTTON-RELEASE-MASK 512)
(:KEY-PRESS-MASK 1024)
(:KEY-RELEASE-MASK 2048)
(:ENTER-NOTIFY-MASK 4096)
(:LEAVE-NOTIFY-MASK 8192)
(:FOCUS-CHANGE-MASK 16384)
(:STRUCTURE-MASK 32768)
(:PROPERTY-CHANGE-MASK 65536)
(:VISIBILITY-NOTIFY-MASK 131072)
(:PROXIMITY-IN-MASK 262144)
(:PROXIMITY-OUT-MASK 524288)
(:SUBSTRUCTURE-MASK 1048576)
(:SCROLL-MASK 2097152)
(:TOUCH-MASK 4194304)
(:SMOOTH-SCROLL-MASK 8388608)
(:TOUCHPAD-GESTURE-MASK 16777216)
(:TABLET-PAD-MASK 33554432)
(:ALL-EVENTS-MASK 67108862))
(get-g-type-definition "GdkEventMask"))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(foreign-funcall "gdk_event_sequence_get_type" g-size))
(test gdk-event-sequence
(is-true (g-type-is-a (gtype "GdkEventSequence") +g-type-boxed+))
(is (eq (gtype "GdkEventSequence")
(gtype (foreign-funcall "gdk_event_sequence_get_type" g-size)))))
GdkEvent
( type - event - type )
( window ( g - object - window ) )
(: destroy 1 )
(: map 14 )
(: unmap 15 )
(: client - event 28 )
(: damage 36 )
(test gdk-event-any
(let ((event (gdk-event-new :nothing)))
(is (typep event 'gdk-event))
(is (eq :nothing (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))))
( (: expose ) - event - expose
( area gdk - rectangle : inline t : initform ( gdk - rectangle - new ) )
( region (: pointer (: struct cairo - region - t ) ) : initform ( null - pointer ) )
( count : int : initform 0 ) )
(test gdk-event-expose
(let ((event (gdk-event-new :expose)))
(is (typep event 'gdk-event-expose))
(is (eq :expose (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
(is (typep (gdk-event-expose-area event) 'gdk-rectangle))
(is-true (null-pointer-p (gdk-event-expose-region event)))
(is (= 0 (gdk-event-expose-count event)))))
( (: motion - notify ) - event - motion
( time : uint32 : initform 0 )
( x : double : initform 0.0d0 )
( y : double : initform 0.0d0 )
( axes ( fixed - array : double 2 ) : initform ' ( 0.0d0 0.0d0 ) )
( state - modifier - type : initform 0 )
( is - hint : int16 : initform 0 )
( device ( g - object gdk - device ) : initform ( null - pointer ) )
( x - root : double : initform 0.0d0 )
( y - root : double : initform 0.0d0 ) )
(test gdk-event-motion
(let ((event (gdk-event-new :motion-notify)))
(is (typep event 'gdk-event-motion))
(is (eq :motion-notify (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
Slots for - event - motion
(is (= 0 (gdk-event-motion-time event)))
(is (= 0.0d0 (gdk-event-motion-x event)))
(is (= 0.0d0 (gdk-event-motion-y event)))
(is (equal '(0.0d0 0.0d0) (gdk-event-motion-axes event)))
(is (= 0 (gdk-event-motion-state event)))
(is (= 0 (gdk-event-motion-is-hint event)))
(is (null-pointer-p (gdk-event-motion-device event)))
(is (= 0.0d0 (gdk-event-motion-x-root event)))
(is (= 0.0d0 (gdk-event-motion-y-root event)))))
: 2button - press
: 3button - press
: button - release ) - event - button
( time : uint32 : initform 0 )
( x : double : initform 0.0d0 )
( y : double : initform 0.0d0 )
( axes ( fixed - array : double 2 ) : initform ' ( 0.0d0 0.0d0 ) )
( state - modifier - type : initform 0 )
( button : uint : initform 0 )
( device ( g - object gdk - device ) : initform ( null - pointer ) )
( x - root : double : initform 0.0d0 )
( y - root : double : initform 0.0d0 ) )
(test gdk-event-button.1
(let ((event (gdk-event-new :button-press)))
(is (typep event 'gdk-event-button))
(is (eq :button-press (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
(is (= 0 (gdk-event-button-time event)))
(is (= 0.0d0 (gdk-event-button-x event)))
(is (= 0.0d0 (gdk-event-button-y event)))
(is (equal '(0.0d0 0.0d0) (gdk-event-button-axes event)))
(is (= 0 (gdk-event-button-state event)))
(is (= 0 (gdk-event-button-button event)))
(is (null-pointer-p (gdk-event-button-device event)))
(is (= 0.0d0 (gdk-event-button-x-root event)))
(is (= 0.0d0 (gdk-event-button-y-root event)))))
(test gdk-event-button.2
(let ((event (gdk-event-new :double-button-press)))
(is (typep event 'gdk-event-button))
(is (eq :double-button-press (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
(is (= 0 (gdk-event-button-time event)))
(is (= 0.0d0 (gdk-event-button-x event)))
(is (= 0.0d0 (gdk-event-button-y event)))
(is (equal '(0.0d0 0.0d0) (gdk-event-button-axes event)))
(is (= 0 (gdk-event-button-state event)))
(is (= 0 (gdk-event-button-button event)))
(is (null-pointer-p (gdk-event-button-device event)))
(is (= 0.0d0 (gdk-event-button-x-root event)))
(is (= 0.0d0 (gdk-event-button-y-root event)))))
(test gdk-event-button.3
(let ((event (gdk-event-new :triple-button-press)))
(is (typep event 'gdk-event-button))
(is (eq :triple-button-press (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
(is (= 0 (gdk-event-button-time event)))
(is (= 0.0d0 (gdk-event-button-x event)))
(is (= 0.0d0 (gdk-event-button-y event)))
(is (equal '(0.0d0 0.0d0) (gdk-event-button-axes event)))
(is (= 0 (gdk-event-button-state event)))
(is (= 0 (gdk-event-button-button event)))
(is (null-pointer-p (gdk-event-button-device event)))
(is (= 0.0d0 (gdk-event-button-x-root event)))
(is (= 0.0d0 (gdk-event-button-y-root event)))))
(test gdk-event-button.4
(let ((event (gdk-event-new :button-release)))
(is (typep event 'gdk-event-button))
(is (eq :button-release (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
(is (= 0 (gdk-event-button-time event)))
(is (= 0.0d0 (gdk-event-button-x event)))
(is (= 0.0d0 (gdk-event-button-y event)))
(is (equal '(0.0d0 0.0d0) (gdk-event-button-axes event)))
(is (= 0 (gdk-event-button-state event)))
(is (= 0 (gdk-event-button-button event)))
(is (null-pointer-p (gdk-event-button-device event)))
(is (= 0.0d0 (gdk-event-button-x-root event)))
(is (= 0.0d0 (gdk-event-button-y-root event)))))
( (: key - press : key - release ) - event - key
( time : uint32 : initform 0 )
( state - modifier - type : initform 0 )
( keyval : uint : initform 0 )
( length : int : initform 0 )
: initform " " )
( hardware - keycode : uint16 : initform 0 )
( group : uint8 : initform 0 )
( is - modifier : uint : initform 0 ) )
(test gdk-event-key.1
(let ((event (gdk-event-new :key-press)))
(is (typep event 'gdk-event-key))
(is (eq :key-press (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
(is (= 0 (gdk-event-key-time event)))
(is (= 0 (gdk-event-key-state event)))
(is (= 0 (gdk-event-key-keyval event)))
(is (= 0 (gdk-event-key-length event)))
(is (string= "" (gdk-event-key-string event)))
(is (= 0 (gdk-event-key-hardware-keycode event)))
(is (= 0 (gdk-event-key-group event)))
(is (= 0 (gdk-event-key-is-modifier event)))))
(test gdk-event-key.2
(let ((event (gdk-event-new :key-release)))
(is (typep event 'gdk-event-key))
(is (eq :key-release (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
(is (= 0 (gdk-event-key-time event)))
(is (= 0 (gdk-event-key-state event)))
(is (= 0 (gdk-event-key-keyval event)))
(is (= 0 (gdk-event-key-length event)))
(is (string= "" (gdk-event-key-string event)))
(is (= 0 (gdk-event-key-hardware-keycode event)))
(is (= 0 (gdk-event-key-group event)))
(is (= 0 (gdk-event-key-is-modifier event)))))
( (: enter - notify : leave - notify ) - event - crossing
( subwindow ( g - object - window ) )
( time : )
( mode - crossing - mode )
( detail - notify - type )
(test gdk-event-crossing
(let ((event (gdk-event-new :enter-notify)))
(is (typep event 'gdk-event-crossing))
(is (eq :enter-notify (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
(is (null-pointer-p (gdk-event-crossing-subwindow event)))
(is (= 0 (gdk-event-crossing-time event)))
(is (= 0.0d0 (gdk-event-crossing-x event)))
(is (= 0.0d0 (gdk-event-crossing-y event)))
(is (= 0.0d0 (gdk-event-crossing-x-root event)))
(is (= 0.0d0 (gdk-event-crossing-y-root event)))
(is (eq :normal (gdk-event-crossing-mode event)))
(is (eq :ancestor (gdk-event-crossing-detail event)))
(is-false (gdk-event-crossing-focus event))
(is (= 0 (gdk-event-crossing-state event)))))
( (: focus - change ) - event - focus
( in : int16 : initform 0 ) )
(test gdk-event-focus
(let ((event (gdk-event-new :focus-change)))
(is (typep event 'gdk-event-focus))
(is (eq :focus-change (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
(is (= 0 (gdk-event-focus-in event)))))
( (: configure ) - event - configure
( x : int : initform 0 )
( y : int : initform 0 )
( width : int : initform 0 )
( height : int : initform 0 ) )
(test gdk-event-configure
(let ((event (gdk-event-new :configure)))
(is (typep event 'gdk-event-configure))
(is (eq :configure (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
(is (= 0 (gdk-event-configure-x event)))
(is (= 0 (gdk-event-configure-y event)))
(is (= 0 (gdk-event-configure-width event)))
(is (= 0 (gdk-event-configure-height event)))))
( (: property - notify ) - event - property
( time : uint32 : initform 0 )
( state - property - state : init - from : new - value ) )
(test gdk-event-property
(let ((event (gdk-event-new :property-notify)))
(is (typep event 'gdk-event-property))
(is (eq :property-notify (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
Slots for - event - property
(is (null-pointer-p (gdk-event-property-atom event)))
(is (= 0 (gdk-event-property-time event)))
(is (eq :new-value (gdk-event-property-state event)))))
: selection - request ) - event - selection
( selection gdk - atom : initform ( null - pointer ) )
( target gdk - atom : initform ( null - poiner ) )
( property gdk - atom : initform ( null - pointer ) )
( time : uint32 : initform 0 )
( requestor ( g - object - window ) ) )
(test gdk-event-selection
(let ((event (gdk-event-new :selection-clear)))
(is (typep event 'gdk-event-selection))
(is (eq :selection-clear (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
Slots for - event - selection
(is (null-pointer-p (gdk-event-selection-selection event)))
(is (null-pointer-p (gdk-event-selection-target event)))
(is (null-pointer-p (gdk-event-selection-property event)))
(is (= 0 (gdk-event-selection-time event)))
(is-false (gdk-event-selection-requestor event))))
( time : uint32 : initform 0 )
(test gdk-event-proximity
(let ((event (gdk-event-new :proximity-in)))
(is (typep event 'gdk-event-proximity))
(is (eq :proximity-in (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
(is (= 0 (gdk-event-proximity-time event)))
(is-false (gdk-event-proximity-device event))))
: drop - finished ) - event - dnd
( time : uint32 : initform 0 )
( x - root : short : initform 0 )
( y - root : short : initform 0 ) )
(test gdk-event-dnd
(let ((event (gdk-event-new :drag-enter)))
(is (typep event 'gdk-event-dnd))
(is (eq :drag-enter (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
(is-false (gdk-event-dnd-context event))
(is (= 0 (gdk-event-dnd-time event)))
(is (= 0 (gdk-event-dnd-x-root event)))
(is (= 0 (gdk-event-dnd-y-root event)))))
( (: visibility - notify ) - event - visibility
( state - visibility - state : initform : unobscured ) )
(test gdk-event-visibility
(let ((event (gdk-event-new :visibility-notify)))
(is (typep event 'gdk-event-visibility))
(is (eq :visibility-notify (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
Slots for - event - visibility
(is (eq :unobscured (gdk-event-visibility-state event)))))
( (: scroll ) - event - scroll
( time : uint32 : initform 0 )
( x : double : initform 0.0d0 )
( y : double : initform 0.0d0 )
( state - modifier - type )
( direction - scroll - direction : initform : up )
( x - root : double : initform 0.0d0 )
( y - root : double : initform 0.0d0 )
( delta - x : double : initform 0.0d0 )
( delta - y : double : initform 0.0d0 ) )
(test gdk-event-scroll
(let ((event (gdk-event-new :scroll)))
(is (typep event 'gdk-event-scroll))
(is (eq :scroll (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
(is (= 0 (gdk-event-scroll-time event)))
(is (= 0 (gdk-event-scroll-x event)))
(is (= 0 (gdk-event-scroll-y event)))
(is-false (gdk-event-scroll-state event))
(is (eq :up (gdk-event-scroll-direction event)))
(is-false (gdk-event-scroll-device event))
(is (= 0 (gdk-event-scroll-x-root event)))
(is (= 0 (gdk-event-scroll-y-root event)))
(is (= 0 (gdk-event-scroll-delta-x event)))
(is (= 0 (gdk-event-scroll-delta-y event)))))
( (: window - state ) - event - window - state
( new - window - state - window - state ) )
(test gdk-event-window-state
(let ((event (gdk-event-new :window-state)))
(is (typep event 'gdk-event-window-state ))
(is (eq :window-state (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
(is-false (gdk-event-window-state-changed-mask event))
(is-false (gdk-event-window-state-new-window-state event))))
( (: setting ) - event - setting
( action - setting - action : initform : new )
(test gdk-event-setting
(let ((event (gdk-event-new :setting)))
(is (typep event 'gdk-event-setting))
(is (eq :setting (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
(is (eq :new (gdk-event-setting-action event)))
(is-false (gdk-event-setting-name event))))
( (: owner - change ) - event - owner - change
( owner ( g - object - window ) )
( reason - owner - change : initform : new - owner )
( selection gdk - atom : initform ( null - pointer ) )
( time : uint32 : initform 0 )
( selection - time : uint32 : initform 0 ) )
(test gdk-event-owner-change
(let ((event (gdk-event-new :owner-change)))
(is (typep event 'gdk-event-owner-change))
(is (eq :owner-change (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
Slots for - event - owner - change
(is-false (gdk-event-owner-change-owner event))
(is (eq :new-owner (gdk-event-owner-change-reason event)))
(is (null-pointer-p (gdk-event-owner-change-selection event)))
(is (= 0 (gdk-event-owner-change-time event)))
(is (= 0 (gdk-event-owner-change-selection-time event)))))
( (: grab - broken ) - event - grab - broken
( grab - window ( g - object - window ) ) )
(test gdk-event-grab-broken
(let ((event (gdk-event-new :grab-broken)))
(is (typep event 'gdk-event-grab-broken))
(is (eq :grab-broken (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
Slots for - event - grab - broken
(is-false (gdk-event-grab-broken-keyboard event))
(is-false (gdk-event-grab-broken-implicit event))
(is-false (gdk-event-grab-broken-grab-window event))))
: touch - cancel ) - event - touch
( time : uint32 : initform 0 )
( x : double : initform 0.0d0 )
( y : double : initform 0.0d0 )
( axes ( fixed - array : double 2 ) : initform ' ( 0.0d0 0.0d0 ) )
( state - modifier - type )
( sequence ( g - boxed - foreign - event - sequence ) )
( x - root : double : initform 0.0d0 )
( y - root : double : initform 0.0d0 ) )
(test gdk-event-touch
(let ((event (gdk-event-new :touch-begin)))
(is (typep event 'gdk-event-touch))
(is (eq :touch-begin (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
(is (= 0 (gdk-event-touch-time event)))
(is (= 0 (gdk-event-touch-x event)))
(is (= 0 (gdk-event-touch-y event)))
(is (equal '(0.0d0 0.0d0) (gdk-event-touch-axes event)))
(is-false (gdk-event-touch-state event))
(is-false (gdk-event-touch-sequence event))
(is-false (gdk-event-touch-emulating-pointer event))
(is-false (gdk-event-touch-device event))
(is (= 0 (gdk-event-touch-x-root event)))
(is (= 0 (gdk-event-touch-y-root event)))))
( (: touchpad - swipe ) - event - touchpad - swipe
( n - fingers : int8 : initform 0 )
( time : uint32 : initform 0 )
( x : double : initform 0.0d0 )
( y : double : initform 0.0d0 )
( dx : double : initform 0.0d0 )
( dy : double : initform 0.0d0 )
( x - root : double : initform 0.0d0 )
( y - root : double : initform 0.0d0 )
( state - modifier - type ) )
(test gdk-event-touchpad-swipe
(let ((event (gdk-event-new :touchpad-swipe)))
(is (typep event 'gdk-event-touchpad-swipe))
(is (eq :touchpad-swipe (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
(is (= 0 (gdk-event-touchpad-swipe-phase event)))
(is (= 0 (gdk-event-touchpad-swipe-n-fingers event)))
(is (= 0 (gdk-event-touchpad-swipe-time event)))
(is (= 0 (gdk-event-touchpad-swipe-x event)))
(is (= 0 (gdk-event-touchpad-swipe-y event)))
(is (= 0 (gdk-event-touchpad-swipe-dx event)))
(is (= 0 (gdk-event-touchpad-swipe-dy event)))
(is (= 0 (gdk-event-touchpad-swipe-x-root event)))
(is (= 0 (gdk-event-touchpad-swipe-y-root event)))
(is-false (gdk-event-touchpad-swipe-state event))))
( phase : int8 : initform 0 )
( n - fingers : int8 : initform 0 )
( time : uint32 : initform 0 )
( x : double : initform 0.0d0 )
( y : double : initform 0.0d0 )
( dx : double : initform 0.0d0 )
( dy : double : initform 0.0d0 )
( angle - delta : double : initform 0.0d0 )
( scale : double : initform 0.0d0 )
( x - root : double : initform 0.0d0 )
( y - root : double : initform 0.0d0 )
( state - modifier - type ) )
(test gdk-event-touchpad-pinch
(let ((event (gdk-event-new :touchpad-pinch)))
(is (typep event 'gdk-event-touchpad-pinch))
(is (eq :touchpad-pinch (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
(is (= 0 (gdk-event-touchpad-pinch-phase event)))
(is (= 0 (gdk-event-touchpad-pinch-n-fingers event)))
(is (= 0 (gdk-event-touchpad-pinch-time event)))
(is (= 0 (gdk-event-touchpad-pinch-x event)))
(is (= 0 (gdk-event-touchpad-pinch-y event)))
(is (= 0 (gdk-event-touchpad-pinch-dx event)))
(is (= 0 (gdk-event-touchpad-pinch-dy event)))
(is (= 0 (gdk-event-touchpad-pinch-angle-delta event)))
(is (= 0 (gdk-event-touchpad-pinch-scale event)))
(is (= 0 (gdk-event-touchpad-pinch-x-root event)))
(is (= 0 (gdk-event-touchpad-pinch-y-root event)))
(is-false (gdk-event-touchpad-pinch-state event))))
( (: pad - button - press : pad - button - release ) - event - pad - button
( time : uint32 : initform 0 )
( group : uint : initform 0 )
( button : uint : initform 0 )
(test gdk-event-pad-button
(let ((event (gdk-event-new :pad-button-press)))
(is (typep event 'gdk-event-pad-button))
(is (eq :pad-button-press (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
(is (= 0 (gdk-event-pad-button-time event)))
(is (= 0 (gdk-event-pad-button-group event)))
(is (= 0 (gdk-event-pad-button-button event)))
(is (= 0 (gdk-event-pad-button-mode event)))))
( (: pad - ring : pad - strip ) - event - pad - axis
( time : uint32 : initform 0 )
( group : uint : initform 0 )
( index : uint : initform 0 )
( mode : uint : initform 0 )
( value : double : initform 0.0d0 ) )
(test gdk-event-pad-axis
(let ((event (gdk-event-new :pad-ring)))
(is (typep event 'gdk-event-pad-axis))
(is (eq :pad-ring (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
(is (= 0 (gdk-event-pad-axis-time event)))
(is (= 0 (gdk-event-pad-axis-group event)))
(is (= 0 (gdk-event-pad-axis-index event)))
(is (= 0 (gdk-event-pad-axis-mode event)))
(is (= 0 (gdk-event-pad-axis-value event)))))
( time : uint32 : initform 0 )
( group : uint : initform 0 )
( mode : uint : initform 0 ) )
(test gdk-event-pad-group-mode
(let ((event (gdk-event-new :pad-group-mode)))
(is (typep event 'gdk-event-pad-group-mode))
(is (eq :pad-group-mode (gdk-event-type event)))
(is-false (gdk-event-window event))
(is-false (gdk-event-send-event event))
(is (= 0 (gdk-event-pad-group-mode-time event)))
(is (= 0 (gdk-event-pad-group-mode-group event)))
(is (= 0 (gdk-event-pad-group-mode-mode event)))))
2021 - 4 - 25
|
8d3644020b30f1d27f62873bd0fcb4f1d8463de153cd58da18f6bcb787d63cb8 | ragkousism/Guix-on-Hurd | display-managers.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2013 < >
Copyright © 2014 < >
Copyright © 2014 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages display-managers)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix build-system cmake)
#:use-module (guix packages)
#:use-module (gnu packages)
#:use-module (gnu packages admin)
#:use-module (gnu packages fontutils)
#:use-module (gnu packages freedesktop)
#:use-module (gnu packages gl)
#:use-module (gnu packages glib)
#:use-module (gnu packages image)
#:use-module (gnu packages kde-frameworks)
#:use-module (gnu packages linux)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages qt)
#:use-module (gnu packages xdisorg)
#:use-module (gnu packages xorg))
(define-public greenisland
(package
(name "greenisland")
(version "0.8.1")
(source (origin
(method url-fetch)
(uri (string-append
""
"/releases/download/v" version "/"
"greenisland-" version ".tar.xz"))
(sha256
(base32
"1c9rlq7fqrsd5nb37anjvnp9xspqjz1kc0fvydv5xdy3abg8mw40"))))
(build-system cmake-build-system)
(native-inputs
`(("extra-cmake-modules" ,extra-cmake-modules)
("dbus" ,dbus)
("glib:bin" ,glib "bin")
("pkg-config" ,pkg-config)
("xorg-server" ,xorg-server)))
(inputs
`(("elogind" ,elogind)
("eudev" ,eudev)
("fontconfig" ,fontconfig)
("freetype" ,freetype)
("glib" ,glib)
("libdrm" ,libdrm)
("libinput" ,libinput-minimal)
("libxcursor" ,libxcursor)
("libxkbcommon" ,libxkbcommon)
("libx11" ,libx11)
("mesa" ,mesa)
("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)
("wayland" ,wayland)
("wayland-protocols" ,wayland-protocols)
("xcb-util-cursor" ,xcb-util-cursor)))
(arguments
`(#:configure-flags
(list (string-append "-DPLUGIN_INSTALL_DIR="
(assoc-ref %outputs "out") "/plugins")
(string-append "-DQML_INSTALL_DIR="
(assoc-ref %outputs "out") "/qml"))
#:modules ((guix build cmake-build-system)
(guix build qt-utils)
(guix build utils))
#:imported-modules (,@%cmake-build-system-modules
(guix build qt-utils))
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'disable-udev-tests
FIXME : Build env does n't contain /dev /
(substitute* "tests/auto/platform/tst_udev.cpp"
(("QVERIFY") "// QVERIFY")
(("QCOMPARE") "// QCOMPARE"))))
(replace 'check
(lambda _
(setenv "DBUS_FATAL_WARNINGS" "0")
(zero? (system* "dbus-launch" "ctest" "."))))
(add-before 'check 'check-setup
(lambda _
(setenv "CTEST_OUTPUT_ON_FAILURE" "1") ; Enable debug output
(setenv "QT_QPA_PLATFORM" "offscreen")
(setenv "XDG_RUNTIME_DIR" (getcwd))
#t))
(add-after 'install 'wrap-programs
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(wrap-qt-program out "greenisland")
(wrap-qt-program out "greenisland-launcher")
(wrap-qt-program out "greenisland-screencaster")
(wrap-qt-program out "greenisland-wayland-scanner")
#t))))))
(synopsis "QtQuick Wayland compositor and shell for desktop and mobile")
(description "Green Island provides a full blown Wayland compositor for
QtQuick as well as pluggable hardware abstraction, extensions, tools and a
Qt-style API for Wayland clients.")
(home-page "")
;; Choice of license at the user's opinion.
(license (list license:gpl2 license:gpl3 license:lgpl2.1 license:lgpl3))))
(define-public sddm
(package
(name "sddm")
(version "0.14.0")
(source (origin
(method url-fetch)
(uri (string-append
""
"/releases/download/v" version "/"
"sddm-" version ".tar.xz"))
(sha256
(base32
"0y3pn8g2qj7q20zkmbasrfsj925lfzizk63sfrvzf84bc5c84d3y"))))
(build-system cmake-build-system)
(native-inputs
`(("extra-cmake-modules" ,extra-cmake-modules)
("pkg-config" ,pkg-config)
("qttools" ,qttools)))
(inputs
`(("glib" ,glib)
("greenisland" ,greenisland)
("libxcb" ,libxcb)
("libxkbcommon" ,libxkbcommon)
("linux-pam" ,linux-pam)
("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)
("shadow" ,shadow)
("wayland" ,wayland)))
(arguments
`(#:configure-flags
(list
;; Currently doesn't do anything
Option added by enable wayland greeters PR
"-DENABLE_WAYLAND=ON"
"-DENABLE_PAM=ON"
"-DCONFIG_FILE=/etc/sddm.conf"
;; Set path to /etc/login.defs
;; Alternatively use -DUID_MIN and -DUID_MAX
(string-append "-DLOGIN_DEFS_PATH="
(assoc-ref %build-inputs "shadow")
"/etc/login.defs")
(string-append "-DQT_IMPORTS_DIR="
(assoc-ref %outputs "out") "/qml")
(string-append "-DCMAKE_INSTALL_SYSCONFDIR="
(assoc-ref %outputs "out") "/etc"))
#:modules ((guix build cmake-build-system)
(guix build qt-utils)
(guix build utils))
#:imported-modules (,@%cmake-build-system-modules
(guix build qt-utils))
#:phases
(modify-phases %standard-phases
(add-after 'install 'wrap-programs
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(wrap-qt-program out "sddm")
(wrap-qt-program out "sddm-greeter")
#t))))))
(synopsis "QML based X11 and Wayland display manager")
(description "SDDM is a display manager for X11 and Wayland aiming to be
fast, simple and beautiful. SDDM is themeable and puts no restrictions on the
user interface design. It uses QtQuick which gives the designer the ability to
create smooth, animated user interfaces.")
(home-page "")
QML files are MIT licensed and images are CC BY 3.0 .
(license (list license:gpl2+ license:expat license:cc-by3.0))))
(define-public slim
(package
(name "slim")
(version "1.3.6")
(source (origin
(method url-fetch)
;; Used to be available from download.berlios.de.
(uri (string-append
"mirror-"
version ".tar.gz"))
(sha256
(base32 "1pqhk22jb4aja4hkrm7rjgbgzjyh7i4zswdgf5nw862l2znzxpi1"))
(patches (search-patches "slim-config.patch"
"slim-reset.patch"
"slim-login.patch"
"slim-session.patch"
"slim-sigusr1.patch"))))
(build-system cmake-build-system)
(inputs `(("linux-pam" ,linux-pam)
("libpng" ,libpng)
("libjpeg" ,libjpeg)
("freeglut" ,freeglut)
("libxrandr" ,libxrandr)
("libxrender" ,libxrender)
("freetype" ,freetype)
("fontconfig" ,fontconfig)
("libx11" ,libx11)
("libxft" ,libxft)
("libxmu" ,libxmu)
("xauth" ,xauth)))
(native-inputs
`(("pkg-config" ,pkg-config)))
(arguments
'(#:phases (alist-cons-before
'configure 'set-new-etc-location
(lambda _
(substitute* "CMakeLists.txt"
(("/etc")
(string-append (assoc-ref %outputs "out") "/etc"))
(("install.*systemd.*")
The build system 's logic here is : if " Linux " , then
" systemd " . Strip that .
"")))
%standard-phases)
#:configure-flags '("-DUSE_PAM=yes"
"-DUSE_CONSOLEKIT=no")
#:tests? #f))
;; This used to be at </>.
(home-page "/")
(synopsis "Desktop-independent graphical login manager for X11")
(description
"SLiM is a Desktop-independent graphical login manager for X11, derived
from Login.app. It aims to be light and simple, although completely
configurable through themes and an option file; is suitable for machines on
which remote login functionalities are not needed.
Features included: PNG and XFT support for alpha transparency and antialiased
fonts, External themes support, Configurable runtime options: X server --
login / shutdown / reboot commands, Single (GDM-like) or double (XDM-like)
input control, Can load predefined user at startup, Configurable welcome /
shutdown messages, Random theme selection.")
(license license:gpl2)))
| null | https://raw.githubusercontent.com/ragkousism/Guix-on-Hurd/e951bb2c0c4961dc6ac2bda8f331b9c4cee0da95/gnu/packages/display-managers.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Enable debug output
Choice of license at the user's opinion.
Currently doesn't do anything
Set path to /etc/login.defs
Alternatively use -DUID_MIN and -DUID_MAX
Used to be available from download.berlios.de.
This used to be at </>.
is suitable for machines on | Copyright © 2013 < >
Copyright © 2014 < >
Copyright © 2014 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages display-managers)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix build-system cmake)
#:use-module (guix packages)
#:use-module (gnu packages)
#:use-module (gnu packages admin)
#:use-module (gnu packages fontutils)
#:use-module (gnu packages freedesktop)
#:use-module (gnu packages gl)
#:use-module (gnu packages glib)
#:use-module (gnu packages image)
#:use-module (gnu packages kde-frameworks)
#:use-module (gnu packages linux)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages qt)
#:use-module (gnu packages xdisorg)
#:use-module (gnu packages xorg))
(define-public greenisland
(package
(name "greenisland")
(version "0.8.1")
(source (origin
(method url-fetch)
(uri (string-append
""
"/releases/download/v" version "/"
"greenisland-" version ".tar.xz"))
(sha256
(base32
"1c9rlq7fqrsd5nb37anjvnp9xspqjz1kc0fvydv5xdy3abg8mw40"))))
(build-system cmake-build-system)
(native-inputs
`(("extra-cmake-modules" ,extra-cmake-modules)
("dbus" ,dbus)
("glib:bin" ,glib "bin")
("pkg-config" ,pkg-config)
("xorg-server" ,xorg-server)))
(inputs
`(("elogind" ,elogind)
("eudev" ,eudev)
("fontconfig" ,fontconfig)
("freetype" ,freetype)
("glib" ,glib)
("libdrm" ,libdrm)
("libinput" ,libinput-minimal)
("libxcursor" ,libxcursor)
("libxkbcommon" ,libxkbcommon)
("libx11" ,libx11)
("mesa" ,mesa)
("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)
("wayland" ,wayland)
("wayland-protocols" ,wayland-protocols)
("xcb-util-cursor" ,xcb-util-cursor)))
(arguments
`(#:configure-flags
(list (string-append "-DPLUGIN_INSTALL_DIR="
(assoc-ref %outputs "out") "/plugins")
(string-append "-DQML_INSTALL_DIR="
(assoc-ref %outputs "out") "/qml"))
#:modules ((guix build cmake-build-system)
(guix build qt-utils)
(guix build utils))
#:imported-modules (,@%cmake-build-system-modules
(guix build qt-utils))
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'disable-udev-tests
FIXME : Build env does n't contain /dev /
(substitute* "tests/auto/platform/tst_udev.cpp"
(("QVERIFY") "// QVERIFY")
(("QCOMPARE") "// QCOMPARE"))))
(replace 'check
(lambda _
(setenv "DBUS_FATAL_WARNINGS" "0")
(zero? (system* "dbus-launch" "ctest" "."))))
(add-before 'check 'check-setup
(lambda _
(setenv "QT_QPA_PLATFORM" "offscreen")
(setenv "XDG_RUNTIME_DIR" (getcwd))
#t))
(add-after 'install 'wrap-programs
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(wrap-qt-program out "greenisland")
(wrap-qt-program out "greenisland-launcher")
(wrap-qt-program out "greenisland-screencaster")
(wrap-qt-program out "greenisland-wayland-scanner")
#t))))))
(synopsis "QtQuick Wayland compositor and shell for desktop and mobile")
(description "Green Island provides a full blown Wayland compositor for
QtQuick as well as pluggable hardware abstraction, extensions, tools and a
Qt-style API for Wayland clients.")
(home-page "")
(license (list license:gpl2 license:gpl3 license:lgpl2.1 license:lgpl3))))
(define-public sddm
(package
(name "sddm")
(version "0.14.0")
(source (origin
(method url-fetch)
(uri (string-append
""
"/releases/download/v" version "/"
"sddm-" version ".tar.xz"))
(sha256
(base32
"0y3pn8g2qj7q20zkmbasrfsj925lfzizk63sfrvzf84bc5c84d3y"))))
(build-system cmake-build-system)
(native-inputs
`(("extra-cmake-modules" ,extra-cmake-modules)
("pkg-config" ,pkg-config)
("qttools" ,qttools)))
(inputs
`(("glib" ,glib)
("greenisland" ,greenisland)
("libxcb" ,libxcb)
("libxkbcommon" ,libxkbcommon)
("linux-pam" ,linux-pam)
("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)
("shadow" ,shadow)
("wayland" ,wayland)))
(arguments
`(#:configure-flags
(list
Option added by enable wayland greeters PR
"-DENABLE_WAYLAND=ON"
"-DENABLE_PAM=ON"
"-DCONFIG_FILE=/etc/sddm.conf"
(string-append "-DLOGIN_DEFS_PATH="
(assoc-ref %build-inputs "shadow")
"/etc/login.defs")
(string-append "-DQT_IMPORTS_DIR="
(assoc-ref %outputs "out") "/qml")
(string-append "-DCMAKE_INSTALL_SYSCONFDIR="
(assoc-ref %outputs "out") "/etc"))
#:modules ((guix build cmake-build-system)
(guix build qt-utils)
(guix build utils))
#:imported-modules (,@%cmake-build-system-modules
(guix build qt-utils))
#:phases
(modify-phases %standard-phases
(add-after 'install 'wrap-programs
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(wrap-qt-program out "sddm")
(wrap-qt-program out "sddm-greeter")
#t))))))
(synopsis "QML based X11 and Wayland display manager")
(description "SDDM is a display manager for X11 and Wayland aiming to be
fast, simple and beautiful. SDDM is themeable and puts no restrictions on the
user interface design. It uses QtQuick which gives the designer the ability to
create smooth, animated user interfaces.")
(home-page "")
QML files are MIT licensed and images are CC BY 3.0 .
(license (list license:gpl2+ license:expat license:cc-by3.0))))
(define-public slim
(package
(name "slim")
(version "1.3.6")
(source (origin
(method url-fetch)
(uri (string-append
"mirror-"
version ".tar.gz"))
(sha256
(base32 "1pqhk22jb4aja4hkrm7rjgbgzjyh7i4zswdgf5nw862l2znzxpi1"))
(patches (search-patches "slim-config.patch"
"slim-reset.patch"
"slim-login.patch"
"slim-session.patch"
"slim-sigusr1.patch"))))
(build-system cmake-build-system)
(inputs `(("linux-pam" ,linux-pam)
("libpng" ,libpng)
("libjpeg" ,libjpeg)
("freeglut" ,freeglut)
("libxrandr" ,libxrandr)
("libxrender" ,libxrender)
("freetype" ,freetype)
("fontconfig" ,fontconfig)
("libx11" ,libx11)
("libxft" ,libxft)
("libxmu" ,libxmu)
("xauth" ,xauth)))
(native-inputs
`(("pkg-config" ,pkg-config)))
(arguments
'(#:phases (alist-cons-before
'configure 'set-new-etc-location
(lambda _
(substitute* "CMakeLists.txt"
(("/etc")
(string-append (assoc-ref %outputs "out") "/etc"))
(("install.*systemd.*")
The build system 's logic here is : if " Linux " , then
" systemd " . Strip that .
"")))
%standard-phases)
#:configure-flags '("-DUSE_PAM=yes"
"-DUSE_CONSOLEKIT=no")
#:tests? #f))
(home-page "/")
(synopsis "Desktop-independent graphical login manager for X11")
(description
"SLiM is a Desktop-independent graphical login manager for X11, derived
from Login.app. It aims to be light and simple, although completely
which remote login functionalities are not needed.
Features included: PNG and XFT support for alpha transparency and antialiased
fonts, External themes support, Configurable runtime options: X server --
login / shutdown / reboot commands, Single (GDM-like) or double (XDM-like)
input control, Can load predefined user at startup, Configurable welcome /
shutdown messages, Random theme selection.")
(license license:gpl2)))
|
89ab0a0d47c459ad9d41fd74fe26fdcb60d902a4d5b465bd8e9b9f9c77115423 | mlabs-haskell/apropos | Generator.hs | module Apropos.Generator (
runTest,
decorateTests,
selfTest,
selfTestWhere,
) where
import Apropos.Description (
Description (describe, genDescribed),
scenarios,
variablesToDescription,
)
import Data.Bifunctor (first)
import Data.Kind (Type)
import Data.Map (Map)
import Data.Map qualified as Map
import Data.Proxy (Proxy)
import Data.Set qualified as Set
import Data.String (IsString, fromString)
import Hedgehog (Property, PropertyT, forAll, property, (===))
runTest ::
forall (a :: Type) (d :: Type).
(Show a, Description d a) =>
(a -> PropertyT IO ()) ->
d ->
Property
runTest cond d = property $ forAll (genDescribed d) >>= cond
decorateTests ::
forall (s :: Type) (d :: Type).
(IsString s, Show d) =>
Map d Property ->
[(s, Property)]
decorateTests = map (first $ fromString . show) . Map.toList
TODO caching calls to the solver in genSatisfying would probably be worth it
selfTestForDescription ::
forall (d :: Type) (a :: Type).
(Eq d, Show d, Show a, Description d a) =>
d ->
Property
selfTestForDescription d = runTest (\a -> describe a === d) d
|
Test the lawfulness of a ' Description ' instance .
The result type is @IsString s = > [ ( s , Property)]@ so it can be plugged directly
into the Hedgehog ' Hedgehog . Group ' constructor .
Test the lawfulness of a 'Description' instance.
The result type is @IsString s => [(s, Property)]@ so it can be plugged directly
into the Hedgehog 'Hedgehog.Group' constructor.
-}
selfTest ::
forall (d :: Type) (a :: Type) (s :: Type).
(Ord d, Show d, Show a, Description d a, IsString s) =>
Proxy d ->
[(s, Property)]
selfTest _ = selfTestWhere @d (const True)
-- | Like 'selfTest', but you can filter which descriptions are tested.
selfTestWhere ::
forall (d :: Type) (a :: Type) (s :: Type).
(Ord d, Show d, Show a, Description d a, IsString s) =>
(d -> Bool) ->
[(s, Property)]
selfTestWhere f =
decorateTests
. Map.fromSet selfTestForDescription
. Set.filter f
. Set.map variablesToDescription
$ scenarios
| null | https://raw.githubusercontent.com/mlabs-haskell/apropos/17bb6f7b05549fd7ce67f99b5473d19bba93e6b8/src/Apropos/Generator.hs | haskell | | Like 'selfTest', but you can filter which descriptions are tested. | module Apropos.Generator (
runTest,
decorateTests,
selfTest,
selfTestWhere,
) where
import Apropos.Description (
Description (describe, genDescribed),
scenarios,
variablesToDescription,
)
import Data.Bifunctor (first)
import Data.Kind (Type)
import Data.Map (Map)
import Data.Map qualified as Map
import Data.Proxy (Proxy)
import Data.Set qualified as Set
import Data.String (IsString, fromString)
import Hedgehog (Property, PropertyT, forAll, property, (===))
runTest ::
forall (a :: Type) (d :: Type).
(Show a, Description d a) =>
(a -> PropertyT IO ()) ->
d ->
Property
runTest cond d = property $ forAll (genDescribed d) >>= cond
decorateTests ::
forall (s :: Type) (d :: Type).
(IsString s, Show d) =>
Map d Property ->
[(s, Property)]
decorateTests = map (first $ fromString . show) . Map.toList
TODO caching calls to the solver in genSatisfying would probably be worth it
selfTestForDescription ::
forall (d :: Type) (a :: Type).
(Eq d, Show d, Show a, Description d a) =>
d ->
Property
selfTestForDescription d = runTest (\a -> describe a === d) d
|
Test the lawfulness of a ' Description ' instance .
The result type is @IsString s = > [ ( s , Property)]@ so it can be plugged directly
into the Hedgehog ' Hedgehog . Group ' constructor .
Test the lawfulness of a 'Description' instance.
The result type is @IsString s => [(s, Property)]@ so it can be plugged directly
into the Hedgehog 'Hedgehog.Group' constructor.
-}
selfTest ::
forall (d :: Type) (a :: Type) (s :: Type).
(Ord d, Show d, Show a, Description d a, IsString s) =>
Proxy d ->
[(s, Property)]
selfTest _ = selfTestWhere @d (const True)
selfTestWhere ::
forall (d :: Type) (a :: Type) (s :: Type).
(Ord d, Show d, Show a, Description d a, IsString s) =>
(d -> Bool) ->
[(s, Property)]
selfTestWhere f =
decorateTests
. Map.fromSet selfTestForDescription
. Set.filter f
. Set.map variablesToDescription
$ scenarios
|
4e1e6b0420e6545d32d54c5a65faffaeaa248fff65dacdb1a3ee8b64a722ab7e | iu-parfunc/HSBencher | Dribble.hs | # LANGUAGE RecordWildCards , TypeFamilies , NamedFieldPuns , DeriveDataTypeable #
-- | A simple backend that dribbles benchmark results (i.e. rows/tuples) into a
-- series of files in an "hsbencher" subdir of the the users ".cabal/" directory.
--
-- This is often useful as a failsafe to reinforce other backends that depend on
-- connecting to internet services for upload. Even if the upload fails, you still
-- have a local copy of the data.
module HSBencher.Backend.Dribble
( defaultDribblePlugin,
DribblePlugin(), DribbleConf(..)
)
where
import HSBencher.Types
import HSBencher.Internal.Logging (log)
import Control.Concurrent.MVar
import Control.Monad.Reader
import Data.Default (Default(def))
import qualified Data.List as L
import Data.Typeable
import Prelude hiding (log)
import System.Directory
import System.FilePath ((</>),(<.>))
import System.IO.Unsafe (unsafePerformIO)
--------------------------------------------------------------------------------
-- | A simple singleton type -- a unique signifier.
data DribblePlugin = DribblePlugin deriving (Read,Show,Eq,Ord)
-- | A plugin with the basic options (if any) included.
defaultDribblePlugin :: DribblePlugin
defaultDribblePlugin = DribblePlugin
-- | The configuration consists only of the location of a single file, which is where
-- the results will be fed. If no file is provided, the default location is selected
-- during plugin initialization.
data DribbleConf = DribbleConf { csvfile :: Maybe String }
deriving (Read,Show,Eq,Ord, Typeable)
-- TODO: expose command line option to change directory for dribbling. This is not
urgent however , because the user can dig around and set the directly
-- if they wish.
--------------------------------------------------------------------------------
instance Default DribblePlugin where
def = defaultDribblePlugin
instance Default DribbleConf where
def = DribbleConf { csvfile = Nothing }
instance Plugin DribblePlugin where
-- | No configuration info for this plugin currently:
type PlugConf DribblePlugin = DribbleConf
-- | No command line flags either:
type PlugFlag DribblePlugin = ()
-- | Going with simple names, but had better make them unique!
plugName _ = "dribble"
-- plugName _ = "DribbleToFile_Backend"
plugCmdOpts _ = ("Dribble plugin loaded.\n"++
" No additional flags, but uses --name for the base filename.\n"
,[])
plugUploadRow _p cfg row = runReaderT (writeBenchResult row) cfg
plugInitialize p gconf = do
putStrLn " [dribble] Dribble-to-file plugin initializing..."
let DribbleConf{csvfile} = getMyConf DribblePlugin gconf
case csvfile of
Just x -> do putStrLn$ " [dribble] Using dribble file specified in configuration: "++show x
return gconf
Nothing -> do
cabalD <- getAppUserDataDirectory "cabal"
chk1 <- doesDirectoryExist cabalD
unless chk1 $ error $ " [dribble] Plugin cannot initialize, cabal data directory does not exist: "++cabalD
let dribbleD = cabalD </> "hsbencher"
createDirectoryIfMissing False dribbleD
base <- case benchsetName gconf of
Nothing -> do putStrLn " [dribble] no --name set, chosing default.csv for dribble file.."
return "dribble"
Just x -> return x
let path = dribbleD </> base <.> "csv"
putStrLn $ " [dribble] Defaulting to dribble location "++show path++", done initializing."
return $! setMyConf p (DribbleConf{csvfile=Just path}) gconf
-- Flags can only be unit here:
foldFlags _p _flgs cnf0 = cnf0
--------------------------------------------------------------------------------
-- TEMP: Hack
fileLock :: MVar ()
fileLock = unsafePerformIO (newMVar ())
# NOINLINE fileLock #
TODO / FIXME : Make this configurable .
writeBenchResult :: BenchmarkResult -> BenchM ()
writeBenchResult br@BenchmarkResult{..} = do
let tuple = resultToTuple br
(cols,vals) = unzip tuple
conf <- ask
let DribbleConf{csvfile} = getMyConf DribblePlugin conf
case csvfile of
Nothing -> error "[dribble] internal plugin error, csvfile config should have been set during initialization."
Just path -> do
log$ " [dribble] Adding a row of data to: "++path
lift $ withMVar fileLock $ \ () -> do
b <- doesFileExist path
If we 're the first to write the file ... append the header :
unless b$ writeFile path (concat (L.intersperse "," cols)++"\n")
appendFile path (concat (L.intersperse "," (map show vals))++"\n")
return ()
| null | https://raw.githubusercontent.com/iu-parfunc/HSBencher/76782b75b3a4b276c45a2c159e0b4cb6bd8a2360/hsbencher/src/HSBencher/Backend/Dribble.hs | haskell | | A simple backend that dribbles benchmark results (i.e. rows/tuples) into a
series of files in an "hsbencher" subdir of the the users ".cabal/" directory.
This is often useful as a failsafe to reinforce other backends that depend on
connecting to internet services for upload. Even if the upload fails, you still
have a local copy of the data.
------------------------------------------------------------------------------
| A simple singleton type -- a unique signifier.
| A plugin with the basic options (if any) included.
| The configuration consists only of the location of a single file, which is where
the results will be fed. If no file is provided, the default location is selected
during plugin initialization.
TODO: expose command line option to change directory for dribbling. This is not
if they wish.
------------------------------------------------------------------------------
| No configuration info for this plugin currently:
| No command line flags either:
| Going with simple names, but had better make them unique!
plugName _ = "DribbleToFile_Backend"
Flags can only be unit here:
------------------------------------------------------------------------------
TEMP: Hack | # LANGUAGE RecordWildCards , TypeFamilies , NamedFieldPuns , DeriveDataTypeable #
module HSBencher.Backend.Dribble
( defaultDribblePlugin,
DribblePlugin(), DribbleConf(..)
)
where
import HSBencher.Types
import HSBencher.Internal.Logging (log)
import Control.Concurrent.MVar
import Control.Monad.Reader
import Data.Default (Default(def))
import qualified Data.List as L
import Data.Typeable
import Prelude hiding (log)
import System.Directory
import System.FilePath ((</>),(<.>))
import System.IO.Unsafe (unsafePerformIO)
data DribblePlugin = DribblePlugin deriving (Read,Show,Eq,Ord)
defaultDribblePlugin :: DribblePlugin
defaultDribblePlugin = DribblePlugin
data DribbleConf = DribbleConf { csvfile :: Maybe String }
deriving (Read,Show,Eq,Ord, Typeable)
urgent however , because the user can dig around and set the directly
instance Default DribblePlugin where
def = defaultDribblePlugin
instance Default DribbleConf where
def = DribbleConf { csvfile = Nothing }
instance Plugin DribblePlugin where
type PlugConf DribblePlugin = DribbleConf
type PlugFlag DribblePlugin = ()
plugName _ = "dribble"
plugCmdOpts _ = ("Dribble plugin loaded.\n"++
" No additional flags, but uses --name for the base filename.\n"
,[])
plugUploadRow _p cfg row = runReaderT (writeBenchResult row) cfg
plugInitialize p gconf = do
putStrLn " [dribble] Dribble-to-file plugin initializing..."
let DribbleConf{csvfile} = getMyConf DribblePlugin gconf
case csvfile of
Just x -> do putStrLn$ " [dribble] Using dribble file specified in configuration: "++show x
return gconf
Nothing -> do
cabalD <- getAppUserDataDirectory "cabal"
chk1 <- doesDirectoryExist cabalD
unless chk1 $ error $ " [dribble] Plugin cannot initialize, cabal data directory does not exist: "++cabalD
let dribbleD = cabalD </> "hsbencher"
createDirectoryIfMissing False dribbleD
base <- case benchsetName gconf of
Nothing -> do putStrLn " [dribble] no --name set, chosing default.csv for dribble file.."
return "dribble"
Just x -> return x
let path = dribbleD </> base <.> "csv"
putStrLn $ " [dribble] Defaulting to dribble location "++show path++", done initializing."
return $! setMyConf p (DribbleConf{csvfile=Just path}) gconf
foldFlags _p _flgs cnf0 = cnf0
fileLock :: MVar ()
fileLock = unsafePerformIO (newMVar ())
# NOINLINE fileLock #
TODO / FIXME : Make this configurable .
writeBenchResult :: BenchmarkResult -> BenchM ()
writeBenchResult br@BenchmarkResult{..} = do
let tuple = resultToTuple br
(cols,vals) = unzip tuple
conf <- ask
let DribbleConf{csvfile} = getMyConf DribblePlugin conf
case csvfile of
Nothing -> error "[dribble] internal plugin error, csvfile config should have been set during initialization."
Just path -> do
log$ " [dribble] Adding a row of data to: "++path
lift $ withMVar fileLock $ \ () -> do
b <- doesFileExist path
If we 're the first to write the file ... append the header :
unless b$ writeFile path (concat (L.intersperse "," cols)++"\n")
appendFile path (concat (L.intersperse "," (map show vals))++"\n")
return ()
|
154de379d5f5edfc866b46735395ad5d46a754433bbb3201753ec685b44fd8d7 | deadpendency/deadpendency | GHAppRawPrivateKey.hs | module Common.Model.GitHub.GHAppRawPrivateKey
( GHAppRawPrivateKey (..),
)
where
newtype GHAppRawPrivateKey = GHAppRawPrivateKey
{ _ntByteString :: ByteString
}
deriving stock (Eq, Show, Generic)
| null | https://raw.githubusercontent.com/deadpendency/deadpendency/170d6689658f81842168b90aa3d9e235d416c8bd/apps/common/src/Common/Model/GitHub/GHAppRawPrivateKey.hs | haskell | module Common.Model.GitHub.GHAppRawPrivateKey
( GHAppRawPrivateKey (..),
)
where
newtype GHAppRawPrivateKey = GHAppRawPrivateKey
{ _ntByteString :: ByteString
}
deriving stock (Eq, Show, Generic)
| |
e7b0049d6496895c79ad6dedef6b34b92569b86b4b56611b5ab3f13d433d504d | caribou/caribou-core | asset.clj | (ns caribou.field.asset
(:require [caribou.util :as util]
[caribou.validation :as validation]
[caribou.asset :as asset]
[caribou.field :as field]
[caribou.db :as db]
[caribou.association :as assoc]))
(defn asset-fusion
[this prefix archetype skein opts]
(assoc/join-fusion
this (field/models :asset) prefix archetype skein opts
(fn [master]
(if master
(assoc master :path (asset/asset-path master))))))
(defn asset-build-where
[field prefix opts]
(assoc/part-where field (field/models :asset) prefix opts))
(defn asset-join-fields
[field prefix opts]
(assoc/model-select-fields
(field/models :asset)
(str prefix "$" (-> field :row :slug))
(update-in
(dissoc opts :include)
[:fields]
#(concat % [:id :filename :size :content-type]))))
(defn commit-asset-source
[field content values original]
(let [row (:row field)
slug (:slug row)
posted (get content (keyword slug))
id-key (keyword (str slug "-id"))]
(if posted
(let [asset ((resolve 'caribou.model/create) :asset posted)]
(assoc values id-key (:id asset)))
values)))
(defrecord AssetField [row env]
field/Field
(table-additions [this field] [])
(subfield-names [this field] [(str field "-id")])
(setup-field [this spec]
(let [id-slug (str (:slug row) "-id")
localized (-> this :row :localized)]
((resolve 'caribou.model/update) :model (:model-id row)
{:fields [{:name (util/titleize id-slug)
:type "integer"
:localized localized
:editable false
:reference :asset}]} {:op :migration})))
(rename-model [this old-slug new-slug]
(field/rename-model-index old-slug new-slug (str (-> this :row :slug) "-id")))
(rename-field [this old-slug new-slug]
(field/rename-index this (str old-slug "-id") (str new-slug "-id")))
(cleanup-field [this]
(let [model (field/models (:model-id row))
id-slug (keyword (str (:slug row) "-id"))]
(db/drop-index (:slug model) id-slug)
((resolve 'caribou.model/destroy) :field (-> model :fields id-slug :row :id))))
(target-for [this] nil)
(update-values [this content values original]
(commit-asset-source this content values original))
(post-update [this content opts] content)
(pre-destroy [this content] content)
(join-fields [this prefix opts]
(asset-join-fields this prefix opts))
(join-conditions [this prefix opts]
(let [model (field/models (:model-id row))
slug (:slug row)
id-slug (keyword (str slug "-id"))
id-field (-> model :fields id-slug)
field-select (field/coalesce-locale
model id-field prefix
(name id-slug) opts)
table-alias (str prefix "$" (:slug row))]
[{:table ["asset" table-alias]
:on [field-select (str table-alias ".id")]}]))
(build-where
[this prefix opts]
(asset-build-where this prefix opts))
(natural-orderings [this prefix opts])
(build-order [this prefix opts]
(assoc/join-order this (field/models :asset) prefix opts))
(field-generator [this generators]
generators)
(fuse-field [this prefix archetype skein opts]
(asset-fusion this prefix archetype skein opts))
(localized? [this] false)
(models-involved [this opts all] all)
(field-from [this content opts]
(let [asset-id (content (keyword (str (:slug row) "-id")))
asset (or (db/choose :asset asset-id) {})]
(assoc asset :path (asset/asset-path asset))))
(propagate-order [this id orderings])
(render [this content opts]
(assoc/join-render this (field/models :asset) content opts))
(validate [this opts] (validation/for-asset this opts)))
(defn constructor
[row]
(AssetField. row {}))
| null | https://raw.githubusercontent.com/caribou/caribou-core/6ebd9db4e14cddb1d6b4e152e771e016fa9c55f6/src/caribou/field/asset.clj | clojure | (ns caribou.field.asset
(:require [caribou.util :as util]
[caribou.validation :as validation]
[caribou.asset :as asset]
[caribou.field :as field]
[caribou.db :as db]
[caribou.association :as assoc]))
(defn asset-fusion
[this prefix archetype skein opts]
(assoc/join-fusion
this (field/models :asset) prefix archetype skein opts
(fn [master]
(if master
(assoc master :path (asset/asset-path master))))))
(defn asset-build-where
[field prefix opts]
(assoc/part-where field (field/models :asset) prefix opts))
(defn asset-join-fields
[field prefix opts]
(assoc/model-select-fields
(field/models :asset)
(str prefix "$" (-> field :row :slug))
(update-in
(dissoc opts :include)
[:fields]
#(concat % [:id :filename :size :content-type]))))
(defn commit-asset-source
[field content values original]
(let [row (:row field)
slug (:slug row)
posted (get content (keyword slug))
id-key (keyword (str slug "-id"))]
(if posted
(let [asset ((resolve 'caribou.model/create) :asset posted)]
(assoc values id-key (:id asset)))
values)))
(defrecord AssetField [row env]
field/Field
(table-additions [this field] [])
(subfield-names [this field] [(str field "-id")])
(setup-field [this spec]
(let [id-slug (str (:slug row) "-id")
localized (-> this :row :localized)]
((resolve 'caribou.model/update) :model (:model-id row)
{:fields [{:name (util/titleize id-slug)
:type "integer"
:localized localized
:editable false
:reference :asset}]} {:op :migration})))
(rename-model [this old-slug new-slug]
(field/rename-model-index old-slug new-slug (str (-> this :row :slug) "-id")))
(rename-field [this old-slug new-slug]
(field/rename-index this (str old-slug "-id") (str new-slug "-id")))
(cleanup-field [this]
(let [model (field/models (:model-id row))
id-slug (keyword (str (:slug row) "-id"))]
(db/drop-index (:slug model) id-slug)
((resolve 'caribou.model/destroy) :field (-> model :fields id-slug :row :id))))
(target-for [this] nil)
(update-values [this content values original]
(commit-asset-source this content values original))
(post-update [this content opts] content)
(pre-destroy [this content] content)
(join-fields [this prefix opts]
(asset-join-fields this prefix opts))
(join-conditions [this prefix opts]
(let [model (field/models (:model-id row))
slug (:slug row)
id-slug (keyword (str slug "-id"))
id-field (-> model :fields id-slug)
field-select (field/coalesce-locale
model id-field prefix
(name id-slug) opts)
table-alias (str prefix "$" (:slug row))]
[{:table ["asset" table-alias]
:on [field-select (str table-alias ".id")]}]))
(build-where
[this prefix opts]
(asset-build-where this prefix opts))
(natural-orderings [this prefix opts])
(build-order [this prefix opts]
(assoc/join-order this (field/models :asset) prefix opts))
(field-generator [this generators]
generators)
(fuse-field [this prefix archetype skein opts]
(asset-fusion this prefix archetype skein opts))
(localized? [this] false)
(models-involved [this opts all] all)
(field-from [this content opts]
(let [asset-id (content (keyword (str (:slug row) "-id")))
asset (or (db/choose :asset asset-id) {})]
(assoc asset :path (asset/asset-path asset))))
(propagate-order [this id orderings])
(render [this content opts]
(assoc/join-render this (field/models :asset) content opts))
(validate [this opts] (validation/for-asset this opts)))
(defn constructor
[row]
(AssetField. row {}))
| |
2bbc7e19ca3e890bacdc7ce16015da1c904d5b400bb4bca06ce2d58310092437 | dgtized/shimmers | particles.cljs | (ns shimmers.sketches.particles
"Loosely derived from Coding Challenge #24: Perlin Noise Flow Field
"
(:require
[quil.core :as q :include-macros true]
[quil.middleware :as m]
[quil.sketch]
[shimmers.common.framerate :as framerate]
[shimmers.common.particle-system :as particles]
[shimmers.common.quil :as cq]
[shimmers.math.color :as color]
[shimmers.math.core :as sm]
[shimmers.math.vector :as v]
[shimmers.sketch :as sketch :include-macros true]
[thi.ng.geom.core :as g]
[thi.ng.geom.vector :as gv]
[thi.ng.math.core :as tm]))
random distribution between 1 and 20 units of mass
(def mass-range [1.0 20.0])
(defn make-particle []
(let [initial-pos (cq/rel-vec (rand) (rand))]
{:last-pos initial-pos
:position initial-pos
:velocity (gv/vec2 0 0)
:acceleration (gv/vec2 0 0)
:mass (apply q/random mass-range)
;; :color (color/random)
:color (color/random-gradient :blue-cyan)}))
(defn stokes-drag
"Viscous resistance is a negative force proportional to velocity.
From (physics)"
[velocity]
;; (tm/+ velocity (g/scale velocity -0.1))
(g/scale velocity 0.90))
;; Because of discontinuity when noise wraps around, there were often competing
;; forces at the borders. We fix this by reflecting x and y coordinates around
;; the halfway point for the purposes of calculating noise to ensure they are
;; continuous at edges.
(defn force-at-position [[x y]]
(let [factor 100
rx (sm/reflect-into x (q/width))
ry (sm/reflect-into y (q/height))
n (q/noise (/ rx factor) (/ ry factor)
(/ (q/frame-count) 2000))
r (* 4 Math/PI n)]
(gv/vec2 (q/cos r) (q/sin r))))
(defn acceleration-at-point [{:keys [position mass]}]
(let [;; Pretending that wind-force at a position is inversely proportional to
;; mass of object ie a = F/m. It's not particularly correct as a rule of
;; physics, but it looks nice if the larger objects have slower
;; acceleration.
wind (g/scale (force-at-position position) (/ 1 mass))
;; Arbitrarily making additional random hops in some small direction
;; inversely proportional to mass.
brownian (g/scale (gv/vec2 (q/random-2d)) (/ 0.1 mass))]
(tm/+ wind brownian)))
(defn update-particle
[{:keys [position velocity acceleration] :as particle}]
(let [new-velocity (stokes-drag (tm/+ velocity acceleration))
new-position (tm/+ position new-velocity)
wrapped-position (v/wrap2d new-position (q/width) (q/height))]
(assoc particle
:last-pos (if (= wrapped-position new-position) position wrapped-position)
:position wrapped-position
:velocity new-velocity
:acceleration (acceleration-at-point particle))))
(defn make-user-interface [{:keys [ui] :as state}]
(let [forces (-> (quil.sketch/current-applet)
(.createCheckbox "Draw Forces" (:draw-forces @ui)))
_ (-> (quil.sketch/current-applet) (.createDiv "Background Opacity"))
background (-> (quil.sketch/current-applet)
(.createSlider 0 256 (:opacity @ui) 1))]
;; Use /#/p5/changed to toggle :draw-forces
(.changed forces (fn [] (swap! ui assoc :draw-forces (.checked forces))))
(.changed background (fn [] (swap! ui assoc :opacity (.value background))))
state))
(defn setup []
(q/background "white")
(make-user-interface
{:particles (repeatedly 1000 make-particle)
:particle-graphics (q/create-graphics (q/width) (q/height))
:ui (atom {:draw-forces false
:opacity 0})}))
(defn update-state [state]
(update-in state [:particles] (partial map update-particle)))
(defn draw-forces []
(q/stroke-weight 0.33)
(q/stroke 0 128)
(let [cols (q/floor (/ (q/width) 20))
hcols (/ cols 2)
len (/ cols 4)]
(doseq [x (range 0 (q/width) cols)
y (range 0 (q/height) cols)
:let [force (force-at-position [x y])
from (tm/+ (gv/vec2 x y) (gv/vec2 hcols hcols))]]
(q/line from (tm/+ from (g/scale force len))))))
(defn draw [{:keys [particles ui particle-graphics]}]
(let [opacity (:opacity @ui)]
(q/with-graphics particle-graphics
(q/background 256 opacity)
(let [[lightest heaviest] mass-range
weight-fn (fn [{:keys [mass]}]
(q/map-range mass lightest heaviest 0.2 0.5))]
(particles/draw particles :weight weight-fn))))
(q/background 256)
(q/image particle-graphics 0 0)
(when (:draw-forces @ui)
(draw-forces)))
(sketch/defquil particles
:created-at "2020-10-20"
:size [900 600]
:setup setup
:update update-state
:draw draw
:middleware [m/fun-mode framerate/mode])
| null | https://raw.githubusercontent.com/dgtized/shimmers/f096c20d7ebcb9796c7830efcd7e3f24767a46db/src/shimmers/sketches/particles.cljs | clojure | :color (color/random)
(tm/+ velocity (g/scale velocity -0.1))
Because of discontinuity when noise wraps around, there were often competing
forces at the borders. We fix this by reflecting x and y coordinates around
the halfway point for the purposes of calculating noise to ensure they are
continuous at edges.
Pretending that wind-force at a position is inversely proportional to
mass of object ie a = F/m. It's not particularly correct as a rule of
physics, but it looks nice if the larger objects have slower
acceleration.
Arbitrarily making additional random hops in some small direction
inversely proportional to mass.
Use /#/p5/changed to toggle :draw-forces | (ns shimmers.sketches.particles
"Loosely derived from Coding Challenge #24: Perlin Noise Flow Field
"
(:require
[quil.core :as q :include-macros true]
[quil.middleware :as m]
[quil.sketch]
[shimmers.common.framerate :as framerate]
[shimmers.common.particle-system :as particles]
[shimmers.common.quil :as cq]
[shimmers.math.color :as color]
[shimmers.math.core :as sm]
[shimmers.math.vector :as v]
[shimmers.sketch :as sketch :include-macros true]
[thi.ng.geom.core :as g]
[thi.ng.geom.vector :as gv]
[thi.ng.math.core :as tm]))
random distribution between 1 and 20 units of mass
(def mass-range [1.0 20.0])
(defn make-particle []
(let [initial-pos (cq/rel-vec (rand) (rand))]
{:last-pos initial-pos
:position initial-pos
:velocity (gv/vec2 0 0)
:acceleration (gv/vec2 0 0)
:mass (apply q/random mass-range)
:color (color/random-gradient :blue-cyan)}))
(defn stokes-drag
"Viscous resistance is a negative force proportional to velocity.
From (physics)"
[velocity]
(g/scale velocity 0.90))
(defn force-at-position [[x y]]
(let [factor 100
rx (sm/reflect-into x (q/width))
ry (sm/reflect-into y (q/height))
n (q/noise (/ rx factor) (/ ry factor)
(/ (q/frame-count) 2000))
r (* 4 Math/PI n)]
(gv/vec2 (q/cos r) (q/sin r))))
(defn acceleration-at-point [{:keys [position mass]}]
wind (g/scale (force-at-position position) (/ 1 mass))
brownian (g/scale (gv/vec2 (q/random-2d)) (/ 0.1 mass))]
(tm/+ wind brownian)))
(defn update-particle
[{:keys [position velocity acceleration] :as particle}]
(let [new-velocity (stokes-drag (tm/+ velocity acceleration))
new-position (tm/+ position new-velocity)
wrapped-position (v/wrap2d new-position (q/width) (q/height))]
(assoc particle
:last-pos (if (= wrapped-position new-position) position wrapped-position)
:position wrapped-position
:velocity new-velocity
:acceleration (acceleration-at-point particle))))
(defn make-user-interface [{:keys [ui] :as state}]
(let [forces (-> (quil.sketch/current-applet)
(.createCheckbox "Draw Forces" (:draw-forces @ui)))
_ (-> (quil.sketch/current-applet) (.createDiv "Background Opacity"))
background (-> (quil.sketch/current-applet)
(.createSlider 0 256 (:opacity @ui) 1))]
(.changed forces (fn [] (swap! ui assoc :draw-forces (.checked forces))))
(.changed background (fn [] (swap! ui assoc :opacity (.value background))))
state))
(defn setup []
(q/background "white")
(make-user-interface
{:particles (repeatedly 1000 make-particle)
:particle-graphics (q/create-graphics (q/width) (q/height))
:ui (atom {:draw-forces false
:opacity 0})}))
(defn update-state [state]
(update-in state [:particles] (partial map update-particle)))
(defn draw-forces []
(q/stroke-weight 0.33)
(q/stroke 0 128)
(let [cols (q/floor (/ (q/width) 20))
hcols (/ cols 2)
len (/ cols 4)]
(doseq [x (range 0 (q/width) cols)
y (range 0 (q/height) cols)
:let [force (force-at-position [x y])
from (tm/+ (gv/vec2 x y) (gv/vec2 hcols hcols))]]
(q/line from (tm/+ from (g/scale force len))))))
(defn draw [{:keys [particles ui particle-graphics]}]
(let [opacity (:opacity @ui)]
(q/with-graphics particle-graphics
(q/background 256 opacity)
(let [[lightest heaviest] mass-range
weight-fn (fn [{:keys [mass]}]
(q/map-range mass lightest heaviest 0.2 0.5))]
(particles/draw particles :weight weight-fn))))
(q/background 256)
(q/image particle-graphics 0 0)
(when (:draw-forces @ui)
(draw-forces)))
(sketch/defquil particles
:created-at "2020-10-20"
:size [900 600]
:setup setup
:update update-state
:draw draw
:middleware [m/fun-mode framerate/mode])
|
e77b204d6673e3a0fc86c648a7a14074f6eef137a657d45723346cf75f92cf7a | junjihashimoto/hugs-js | JsWrapper.hs | # LANGUAGE ForeignFunctionInterface #
module JsWrapper where
import Foreign.C.String
import Foreign.Ptr
--import Hugs.Prelude
{-# CFILES jswrapper.c #-}
typedef void ( * ) ;
--extern void emscripten_set_main_loop(em_callback_func func, int fps, int simulate_infinite_loop);
foreign import ccall "emscripten.h" emscripten_run_script :: CString -> IO ()
foreign import ccall "emscripten.h" emscripten_set_main_loop :: (FunPtr (IO ())) -> Int -> Int -> IO ();
emRunScript :: String -> IO ()
emRunScript script = withCString script emscripten_run_script
emSetMainLoop :: IO () -> IO ()
emSetMainLoop loopfunc = do
callbackC <-wrap_callback loopfunc
emscripten_set_main_loop callbackC 1000 1
foreign import ccall "wrapper" wrap_callback :: IO () -> IO (FunPtr (IO ()))
foreign import ccall "jswrapper.h" add_event_callback :: CString -> CString -> (FunPtr (IO ())) -> IO ()
foreign import ccall "jswrapper.h" set_class_name :: CString -> CString -> IO ()
foreign import ccall "jswrapper.h" ready :: (FunPtr (IO ())) -> IO ()
foreign import ccall "jswrapper.h" set_message :: CString -> IO ()
foreign import ccall "jswrapper.h" get_cpu_flag :: IO Int
foreign import ccall "jswrapper.h" is_node_js :: IO Int
addClickCallback :: String -> IO () -> IO ()
addClickCallback idName callback = do
callbackC <- wrap_callback callback
-- print "callbackC"
withCString idName $ \idNameC -> do
-- print "withcstring"
withCString "click" $ \eventNameC -> do
-- print "withcstring"
add_event_callback idNameC eventNameC callbackC
setClassName :: String -> String -> IO ()
setClassName idName className =
withCString idName $ \idNameC ->
withCString className $ \classNameC ->
set_class_name idNameC classNameC
waitReady :: IO () -> IO ()
waitReady callback = do
callbackC <- wrap_callback callback
ready callbackC
setMessage :: String -> IO ()
setMessage message = do
withCString message $ \messageC ->
set_message messageC
getCpuFlag :: IO Bool
getCpuFlag = do
val <- get_cpu_flag
return (val == 1)
isNodeJs :: IO Bool
isNodeJs = do
val <- is_node_js
return (val == 1)
| null | https://raw.githubusercontent.com/junjihashimoto/hugs-js/5a38dbe8310b5d56746ec83c24f7a9f520fbdcd3/sample/JsWrapper.hs | haskell | import Hugs.Prelude
# CFILES jswrapper.c #
extern void emscripten_set_main_loop(em_callback_func func, int fps, int simulate_infinite_loop);
print "callbackC"
print "withcstring"
print "withcstring" | # LANGUAGE ForeignFunctionInterface #
module JsWrapper where
import Foreign.C.String
import Foreign.Ptr
typedef void ( * ) ;
foreign import ccall "emscripten.h" emscripten_run_script :: CString -> IO ()
foreign import ccall "emscripten.h" emscripten_set_main_loop :: (FunPtr (IO ())) -> Int -> Int -> IO ();
emRunScript :: String -> IO ()
emRunScript script = withCString script emscripten_run_script
emSetMainLoop :: IO () -> IO ()
emSetMainLoop loopfunc = do
callbackC <-wrap_callback loopfunc
emscripten_set_main_loop callbackC 1000 1
foreign import ccall "wrapper" wrap_callback :: IO () -> IO (FunPtr (IO ()))
foreign import ccall "jswrapper.h" add_event_callback :: CString -> CString -> (FunPtr (IO ())) -> IO ()
foreign import ccall "jswrapper.h" set_class_name :: CString -> CString -> IO ()
foreign import ccall "jswrapper.h" ready :: (FunPtr (IO ())) -> IO ()
foreign import ccall "jswrapper.h" set_message :: CString -> IO ()
foreign import ccall "jswrapper.h" get_cpu_flag :: IO Int
foreign import ccall "jswrapper.h" is_node_js :: IO Int
addClickCallback :: String -> IO () -> IO ()
addClickCallback idName callback = do
callbackC <- wrap_callback callback
withCString idName $ \idNameC -> do
withCString "click" $ \eventNameC -> do
add_event_callback idNameC eventNameC callbackC
setClassName :: String -> String -> IO ()
setClassName idName className =
withCString idName $ \idNameC ->
withCString className $ \classNameC ->
set_class_name idNameC classNameC
waitReady :: IO () -> IO ()
waitReady callback = do
callbackC <- wrap_callback callback
ready callbackC
setMessage :: String -> IO ()
setMessage message = do
withCString message $ \messageC ->
set_message messageC
getCpuFlag :: IO Bool
getCpuFlag = do
val <- get_cpu_flag
return (val == 1)
isNodeJs :: IO Bool
isNodeJs = do
val <- is_node_js
return (val == 1)
|
a54a5b06b55771c70f8f0a51b111d32ae94632a0f7de9cefd58e90109614dbe4 | cedlemo/OCaml-GI-ctypes-bindings-generator | Pad_action_type.mli | open Ctypes
type t = Button | Ring | Strip
val of_value:
Unsigned.uint32 -> t
val to_value:
t -> Unsigned.uint32
val t_view: t typ
| null | https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Pad_action_type.mli | ocaml | open Ctypes
type t = Button | Ring | Strip
val of_value:
Unsigned.uint32 -> t
val to_value:
t -> Unsigned.uint32
val t_view: t typ
| |
c5a43b24ae50cb7105a6ac721f91e4688be50c6570175786bab782b954e970fc | vmchale/atspkg | C.hs | {-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE DeriveGeneric #
{-# LANGUAGE TypeFamilies #-}
-- | This module provides functions for easy C builds of binaries, static
-- libraries, and dynamic libraries.
module Development.Shake.C ( -- * Types
CConfig (..)
, CCompiler (..)
-- * Rules
, staticLibR
, sharedLibR
, objectFileR
, dynLibR
, cBin
, cToLib
, preprocessA
, preprocessR
-- * Oracles
, idOracle
-- * Actions
, pkgConfig
, binaryA
, staticLibA
, sharedLibA
, stripA
* from " Language . C.Dependency "
, getCDepends
, getAll
-- * Helper functions
, cconfigToArgs
, ccToString
, ccFromString
, host
, isCross
) where
import Control.Composition
import Control.Monad
import Data.List (isPrefixOf, isSuffixOf)
import Development.Shake hiding ((*>))
import Development.Shake.Classes
import Development.Shake.FilePath
import GHC.Generics (Generic)
import Language.C.Dependency
import System.Info
-- | Given a package name or path to a @.pc@ file, output flags for C compiler.
pkgConfig :: String -> Action [String]
pkgConfig pkg = do
(Stdout o) <- command [] "pkg-config" ["--cflags", pkg]
(Stdout o') <- command [] "pkg-config" ["--libs", pkg]
pure (words o ++ words o')
mkQualified :: Monoid a => Maybe a -> Maybe a -> a -> a
mkQualified pre suff = h [f suff, g pre]
where g = maybe id mappend
f = maybe id (mappend -$)
h = thread
-- | The target triple of the host machine.
host :: String
host = arch ++ withManufacturer os
where withManufacturer "darwin" = "-apple-" ++ os
withManufacturer _ = "-unknown-" ++ os
-- | Get the executable name for a 'CCompiler'
ccToString :: CCompiler -> String
ccToString ICC = "icc"
ccToString (Clang suff) = mkQualified Nothing suff "clang"
ccToString (Other s) = s
ccToString (GCC pre suff) = mkQualified pre suff "gcc"
ccToString (GHC pre suff) = mkQualified pre suff "ghc"
ccToString CompCert = "ccomp"
ccToString TCC = "tcc"
ccToString Pgi = "pgcc"
stripToString :: CCompiler -> String
stripToString (GCC pre _) = mkQualified pre Nothing "strip"
stripToString (GHC pre _) = mkQualified pre Nothing "strip"
stripToString _ = "strip"
arToString :: CCompiler -> String
arToString (GCC pre _) = mkQualified pre Nothing "ar"
arToString (GHC pre _) = mkQualified pre Nothing "ar"
arToString _ = "ar"
isCross :: CCompiler -> Bool
isCross (GCC Just{} _) = True
isCross (GHC Just{} _) = True
isCross _ = False
-- | Attempt to parse a string as a 'CCompiler', defaulting to @cc@ if parsing
-- fails.
ccFromString :: String -> CCompiler
ccFromString "icc" = ICC
ccFromString "gcc" = GCC Nothing Nothing
ccFromString "pgcc" = Pgi
ccFromString "ccomp" = CompCert
ccFromString "clang" = Clang Nothing
ccFromString "ghc" = GHC Nothing Nothing
ccFromString "tcc" = TCC
ccFromString s
| "gcc" `isSuffixOf` s = GCC (Just (reverse . drop 3 . reverse $ s)) Nothing
| "ghc" `isSuffixOf` s = GHC (Just (reverse . drop 3 . reverse $ s)) Nothing
| "clang" `isPrefixOf` s = Clang (Just (drop 5 s))
| "ghc" `isPrefixOf` s = GHC Nothing (Just (drop 3 s))
| "gcc" `isPrefixOf` s = GCC Nothing (Just (drop 3 s))
ccFromString _ = Other "cc"
ALSO consider using Haskell - > C - > ICC ? ?
-- TODO TCC
-- | A data type representing the C compiler to be used.
data CCompiler = GCC { _prefix :: Maybe String -- ^ Usually the target triple
, _postfix :: Maybe String -- ^ The compiler version
}
| Clang { _postfix :: Maybe String -- ^ The compiler version
}
| GHC { _prefix :: Maybe String -- ^ The target triple
, _postfix :: Maybe String -- ^ The compiler version
}
| CompCert
| ICC
| TCC
| Pgi
| Other String
deriving (Generic, Binary, Show, Typeable, Eq, Hashable, NFData)
mapFlags :: String -> ([String] -> [String])
mapFlags s = fmap (s ++)
data CConfig = CConfig { includes :: [String] -- ^ Directories to be included.
, libraries :: [String] -- ^ Libraries against which to link.
, libDirs :: [String] -- ^ Directories to find libraries.
, extras :: [String] -- ^ Extra flags to be passed to the compiler
, staticLink :: Bool -- ^ Whether to link against static versions of libraries
}
deriving (Generic, Binary, Show, Typeable, Eq, Hashable, NFData)
type instance RuleResult CCompiler = CCompiler
type instance RuleResult CConfig = CConfig
| Use this for tracking e.g. ' CCompiler ' or ' CConfig '
--
@since
idOracle :: (RuleResult q ~ a, q ~ a, ShakeValue q) => Rules (q -> Action a)
idOracle = addOracle pure
-- | Rules for making a static library from C source files. Unlike 'staticLibR',
-- this also creates rules for creating object files.
cToLib :: CCompiler
-> [FilePath] -- ^ C source files
-> FilePattern -- ^ Static libary output
-> CConfig
-> Rules ()
cToLib cc sources lib cfg =
sequence_ ( staticLibR cc (g sources) lib cfg : objRules)
where objRules = objectFileR cc cfg <$> g sources <*> pure lib
g = fmap (-<.> "o")
-- | Rules for preprocessing a C source file.
--
-- @since 0.4.3.0
preprocessR :: CCompiler
-> FilePath -- ^ C source file
-> FilePattern -- ^ Preprocessed file output
-> CConfig
-> Rules ()
preprocessR cc source proc cfg = proc %> \out -> preprocessA cc source out cfg
-- | Rules for generating a binary from C source files. Can have at most have
one @main@ function .
cBin :: CCompiler
-> [FilePath] -- ^ C source files
-> FilePattern -- ^ Binary file output
-> CConfig
-> Rules ()
cBin cc sources bin cfg = bin %> \out -> binaryA cc sources out cfg
TODO depend on config ! !
TODO depend on the source files transitively ( optionally )
stripA :: CmdResult r
=> FilePath -- ^ Build product to be stripped
-> CCompiler -- ^ C compiler
-> Action r
stripA out cc = command mempty (stripToString cc) [out]
-- | @since 0.4.3.0
preprocessA :: CmdResult r
=> CCompiler
-> FilePath -- ^ Source file
-> FilePath -- ^ Preprocessed output
-> CConfig
-> Action r
preprocessA cc source out cfg =
need [source] *>
(command [EchoStderr False] (ccToString cc) . (("-E" : "-o" : out : [source]) ++) . cconfigToArgs) cfg
-- | This action builds an executable.
binaryA :: CmdResult r
=> CCompiler
-> [FilePath] -- ^ Source files
-> FilePath -- ^ Executable output
-> CConfig
-> Action r
binaryA cc sources out cfg =
need sources *>
(command [EchoStderr False] (ccToString cc) . (("-o" : out : sources) ++) . cconfigToArgs) cfg
-- | Generate compiler flags for a given configuration.
cconfigToArgs :: CConfig -> [String]
cconfigToArgs (CConfig is ls ds es sl) = join [ mapFlags "-I" is, mapFlags "-l" (g sl <$> ls), mapFlags "-L" ds, es ]
where g :: Bool -> (String -> String)
g False = id
g True = (":lib" ++) . (++ ".a")
| These rules build a dynamic library ( @.so@ on Linux ) .
dynLibR :: CCompiler
-> [FilePath] -- ^ C source files
-> FilePattern -- ^ Shared object file to be generated.
-> CConfig
-> Rules ()
dynLibR cc objFiles shLib cfg =
shLib %> \out -> do
need objFiles
command [EchoStderr False] (ccToString cc) ("-shared" : "-o" : out : objFiles ++ cconfigToArgs cfg)
-- | These rules build an object file from a C source file.
objectFileR :: CCompiler
-> CConfig
-> FilePath -- ^ C source file
-> FilePattern -- ^ Object file output
-> Rules ()
objectFileR cc cfg srcFile objFile =
objFile %> \out -> do
need [srcFile]
command [EchoStderr False] (ccToString cc) (srcFile : "-c" : "-fPIC" : "-o" : out : cconfigToArgs cfg)
sharedLibA :: CmdResult r
=> CCompiler
-> [FilePath] -- ^ Object files to be linked
-> FilePattern -- ^ File pattern for shared library outputs
-> CConfig
-> Action r
sharedLibA cc objFiles shrLib _ =
need objFiles *>
command mempty (ccToString cc) ("-shared" : "-o" : shrLib : objFiles)
staticLibA :: CmdResult r
=> CCompiler
-> [FilePath] -- ^ Object files to be linked
-> FilePattern -- ^ File pattern for static library outputs
-> CConfig
-> Action r
staticLibA ar objFiles stalib _ =
need objFiles *>
command mempty (arToString ar) ("rcs" : stalib : objFiles)
sharedLibR :: CCompiler
-> [FilePath] -- ^ Object files to be linked
-> FilePattern -- ^ File pattern for shared library outputs
-> CConfig
-> Rules ()
sharedLibR cc objFiles shrLib cfg =
shrLib %> \out ->
sharedLibA cc objFiles out cfg
staticLibR :: CCompiler
-> [FilePath] -- ^ Object files to be linked
-> FilePattern -- ^ File pattern for static library outputs
-> CConfig
-> Rules ()
staticLibR ar objFiles stalib cfg =
stalib %> \out ->
staticLibA ar objFiles out cfg
| null | https://raw.githubusercontent.com/vmchale/atspkg/45be7ece6b9e9b09a7151efe53ff7e278112e84d/shake-c/src/Development/Shake/C.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE DeriveDataTypeable #
# LANGUAGE TypeFamilies #
| This module provides functions for easy C builds of binaries, static
libraries, and dynamic libraries.
* Types
* Rules
* Oracles
* Actions
* Helper functions
| Given a package name or path to a @.pc@ file, output flags for C compiler.
| The target triple of the host machine.
| Get the executable name for a 'CCompiler'
| Attempt to parse a string as a 'CCompiler', defaulting to @cc@ if parsing
fails.
TODO TCC
| A data type representing the C compiler to be used.
^ Usually the target triple
^ The compiler version
^ The compiler version
^ The target triple
^ The compiler version
^ Directories to be included.
^ Libraries against which to link.
^ Directories to find libraries.
^ Extra flags to be passed to the compiler
^ Whether to link against static versions of libraries
| Rules for making a static library from C source files. Unlike 'staticLibR',
this also creates rules for creating object files.
^ C source files
^ Static libary output
| Rules for preprocessing a C source file.
@since 0.4.3.0
^ C source file
^ Preprocessed file output
| Rules for generating a binary from C source files. Can have at most have
^ C source files
^ Binary file output
^ Build product to be stripped
^ C compiler
| @since 0.4.3.0
^ Source file
^ Preprocessed output
| This action builds an executable.
^ Source files
^ Executable output
| Generate compiler flags for a given configuration.
^ C source files
^ Shared object file to be generated.
| These rules build an object file from a C source file.
^ C source file
^ Object file output
^ Object files to be linked
^ File pattern for shared library outputs
^ Object files to be linked
^ File pattern for static library outputs
^ Object files to be linked
^ File pattern for shared library outputs
^ Object files to be linked
^ File pattern for static library outputs | # LANGUAGE DeriveGeneric #
CConfig (..)
, CCompiler (..)
, staticLibR
, sharedLibR
, objectFileR
, dynLibR
, cBin
, cToLib
, preprocessA
, preprocessR
, idOracle
, pkgConfig
, binaryA
, staticLibA
, sharedLibA
, stripA
* from " Language . C.Dependency "
, getCDepends
, getAll
, cconfigToArgs
, ccToString
, ccFromString
, host
, isCross
) where
import Control.Composition
import Control.Monad
import Data.List (isPrefixOf, isSuffixOf)
import Development.Shake hiding ((*>))
import Development.Shake.Classes
import Development.Shake.FilePath
import GHC.Generics (Generic)
import Language.C.Dependency
import System.Info
pkgConfig :: String -> Action [String]
pkgConfig pkg = do
(Stdout o) <- command [] "pkg-config" ["--cflags", pkg]
(Stdout o') <- command [] "pkg-config" ["--libs", pkg]
pure (words o ++ words o')
mkQualified :: Monoid a => Maybe a -> Maybe a -> a -> a
mkQualified pre suff = h [f suff, g pre]
where g = maybe id mappend
f = maybe id (mappend -$)
h = thread
host :: String
host = arch ++ withManufacturer os
where withManufacturer "darwin" = "-apple-" ++ os
withManufacturer _ = "-unknown-" ++ os
ccToString :: CCompiler -> String
ccToString ICC = "icc"
ccToString (Clang suff) = mkQualified Nothing suff "clang"
ccToString (Other s) = s
ccToString (GCC pre suff) = mkQualified pre suff "gcc"
ccToString (GHC pre suff) = mkQualified pre suff "ghc"
ccToString CompCert = "ccomp"
ccToString TCC = "tcc"
ccToString Pgi = "pgcc"
stripToString :: CCompiler -> String
stripToString (GCC pre _) = mkQualified pre Nothing "strip"
stripToString (GHC pre _) = mkQualified pre Nothing "strip"
stripToString _ = "strip"
arToString :: CCompiler -> String
arToString (GCC pre _) = mkQualified pre Nothing "ar"
arToString (GHC pre _) = mkQualified pre Nothing "ar"
arToString _ = "ar"
isCross :: CCompiler -> Bool
isCross (GCC Just{} _) = True
isCross (GHC Just{} _) = True
isCross _ = False
ccFromString :: String -> CCompiler
ccFromString "icc" = ICC
ccFromString "gcc" = GCC Nothing Nothing
ccFromString "pgcc" = Pgi
ccFromString "ccomp" = CompCert
ccFromString "clang" = Clang Nothing
ccFromString "ghc" = GHC Nothing Nothing
ccFromString "tcc" = TCC
ccFromString s
| "gcc" `isSuffixOf` s = GCC (Just (reverse . drop 3 . reverse $ s)) Nothing
| "ghc" `isSuffixOf` s = GHC (Just (reverse . drop 3 . reverse $ s)) Nothing
| "clang" `isPrefixOf` s = Clang (Just (drop 5 s))
| "ghc" `isPrefixOf` s = GHC Nothing (Just (drop 3 s))
| "gcc" `isPrefixOf` s = GCC Nothing (Just (drop 3 s))
ccFromString _ = Other "cc"
ALSO consider using Haskell - > C - > ICC ? ?
}
}
}
| CompCert
| ICC
| TCC
| Pgi
| Other String
deriving (Generic, Binary, Show, Typeable, Eq, Hashable, NFData)
mapFlags :: String -> ([String] -> [String])
mapFlags s = fmap (s ++)
}
deriving (Generic, Binary, Show, Typeable, Eq, Hashable, NFData)
type instance RuleResult CCompiler = CCompiler
type instance RuleResult CConfig = CConfig
| Use this for tracking e.g. ' CCompiler ' or ' CConfig '
@since
idOracle :: (RuleResult q ~ a, q ~ a, ShakeValue q) => Rules (q -> Action a)
idOracle = addOracle pure
cToLib :: CCompiler
-> CConfig
-> Rules ()
cToLib cc sources lib cfg =
sequence_ ( staticLibR cc (g sources) lib cfg : objRules)
where objRules = objectFileR cc cfg <$> g sources <*> pure lib
g = fmap (-<.> "o")
preprocessR :: CCompiler
-> CConfig
-> Rules ()
preprocessR cc source proc cfg = proc %> \out -> preprocessA cc source out cfg
one @main@ function .
cBin :: CCompiler
-> CConfig
-> Rules ()
cBin cc sources bin cfg = bin %> \out -> binaryA cc sources out cfg
TODO depend on config ! !
TODO depend on the source files transitively ( optionally )
stripA :: CmdResult r
-> Action r
stripA out cc = command mempty (stripToString cc) [out]
preprocessA :: CmdResult r
=> CCompiler
-> CConfig
-> Action r
preprocessA cc source out cfg =
need [source] *>
(command [EchoStderr False] (ccToString cc) . (("-E" : "-o" : out : [source]) ++) . cconfigToArgs) cfg
binaryA :: CmdResult r
=> CCompiler
-> CConfig
-> Action r
binaryA cc sources out cfg =
need sources *>
(command [EchoStderr False] (ccToString cc) . (("-o" : out : sources) ++) . cconfigToArgs) cfg
cconfigToArgs :: CConfig -> [String]
cconfigToArgs (CConfig is ls ds es sl) = join [ mapFlags "-I" is, mapFlags "-l" (g sl <$> ls), mapFlags "-L" ds, es ]
where g :: Bool -> (String -> String)
g False = id
g True = (":lib" ++) . (++ ".a")
| These rules build a dynamic library ( @.so@ on Linux ) .
dynLibR :: CCompiler
-> CConfig
-> Rules ()
dynLibR cc objFiles shLib cfg =
shLib %> \out -> do
need objFiles
command [EchoStderr False] (ccToString cc) ("-shared" : "-o" : out : objFiles ++ cconfigToArgs cfg)
objectFileR :: CCompiler
-> CConfig
-> Rules ()
objectFileR cc cfg srcFile objFile =
objFile %> \out -> do
need [srcFile]
command [EchoStderr False] (ccToString cc) (srcFile : "-c" : "-fPIC" : "-o" : out : cconfigToArgs cfg)
sharedLibA :: CmdResult r
=> CCompiler
-> CConfig
-> Action r
sharedLibA cc objFiles shrLib _ =
need objFiles *>
command mempty (ccToString cc) ("-shared" : "-o" : shrLib : objFiles)
staticLibA :: CmdResult r
=> CCompiler
-> CConfig
-> Action r
staticLibA ar objFiles stalib _ =
need objFiles *>
command mempty (arToString ar) ("rcs" : stalib : objFiles)
sharedLibR :: CCompiler
-> CConfig
-> Rules ()
sharedLibR cc objFiles shrLib cfg =
shrLib %> \out ->
sharedLibA cc objFiles out cfg
staticLibR :: CCompiler
-> CConfig
-> Rules ()
staticLibR ar objFiles stalib cfg =
stalib %> \out ->
staticLibA ar objFiles out cfg
|
55e682a54c4057f15749e7d260ccded375412dfb224c7a79a80cdfa547dbc02f | albertoruiz/easyVision | single.hs | import Vision.GUI
import Image.Processing
import Image.Capture
import System.Environment
f = sumPixels . grayscale . channelsFromRGB
main = getArgs >>= readImages >>= runITrans (arr f) >>= print
| null | https://raw.githubusercontent.com/albertoruiz/easyVision/26bb2efaa676c902cecb12047560a09377a969f2/projects/tour/single.hs | haskell | import Vision.GUI
import Image.Processing
import Image.Capture
import System.Environment
f = sumPixels . grayscale . channelsFromRGB
main = getArgs >>= readImages >>= runITrans (arr f) >>= print
| |
ff396ee4e3352105bc507065d06fdad1d701e68388919dfa12f93c5c6c0dedf9 | transient-haskell/transient-stack | api.hs | #!/usr/bin/env ./execthirdline.sh
set -e & & port=`echo $ { 3 } | awk -F/ ' { print $ ( 3 ) } ' ` & & docker run -it -p $ { port}:${port } -v /c / Users / magocoal / OneDrive / Haskell / devel:/devel testtls bash -c " cd /devel / transient - universe - tls / tests/ ; -j2 -isrc -i / devel / transient / src -i / devel / transient - universe / src -i / devel / transient - universe - tls / src -i / devel / ghcjs - hplay / src -i / devel / ghcjs - perch / src $ 1 $ 2 $ 3 $ 4 "
-- compile it with ghcjs and execute it with runghc
set -e & & port=`echo $ { 3 } | awk -F/ ' { print $ ( 3 ) } ' ` & & docker run -it -p $ { port}:${port } -v $ ( pwd):/work agocorona / transient:05 - 02 - 2017 bash -c " runghc /work/${1 } $ { 2 } $ { 3 } "
execute as ./api.hs -p start/<docker ip>/<port >
invoque : curl http://<docker ip>/<port>/api / hello / http://<docker ip>/<port>/api / hellos / --data " birthyear=1905&press=%20OK%20 "
92.168.99.100:8080/api/
invoque: curl http://<docker ip>/<port>/api/hello/john
curl http://<docker ip>/<port>/api/hellos/john
curl --data "birthyear=1905&press=%20OK%20"
92.168.99.100:8080/api/
-}
# LANGUAGE ScopedTypeVariables #
import Transient.Internals
import Transient.TLS
import Transient.Move
import Transient.Move.Utils
import Transient.Logged
import Transient.Indeterminism
import Control.Applicative
import Control.Concurrent(threadDelay)
import Control.Monad.IO.Class
import qualified Data.ByteString.Lazy.Char8 as BS
import Control.Exception hiding (onException)
main = do
initTLS
keep' $ initNode apisample
apisample= api $ gets <|> posts -- <|> err
where
posts= do
received POST
postParams <- param
liftIO $ print (postParams :: PostParams)
let msg= "received" ++ show postParams
len= length msg
return $ BS.pack $ "HTTP/1.0 200 OK\nContent-Type: text/plain\nContent-Length: "++ show len
++ "\nConnection: close\n\n" ++ msg
gets= received GET >> hello <|> hellostream
hello= do
received "hello"
name <- param
let msg= "hello " ++ name ++ "\n"
len= length msg
return $ BS.pack $ "HTTP/1.0 200 OK\nContent-Type: text/plain\nContent-Length: "++ show len
++ "\nConnection: close\n\n" ++ msg
hellostream = do
received "hellos"
name <- param
threads 0 $ header <|> stream name
where
header=async $ return $ BS.pack $
"HTTP/1.0 200 OK\nContent-Type: text/plain\nConnection: close\n\n"++
"here follows a stream\n"
stream name= do
i <- choose [1 ..]
liftIO $ threadDelay 1000000
return . BS.pack $ " hello " ++ name ++ " "++ show i
err= return $ BS.pack $ " HTTP/1.0 404 Not Founds\nContent - Length : 0\nConnection : close\n\n "
| null | https://raw.githubusercontent.com/transient-haskell/transient-stack/dde6f6613a946d57bb70879a5c0e7e5a73a91dbe/transient-universe-tls/tests/api.hs | haskell | compile it with ghcjs and execute it with runghc
data " birthyear=1905&press=%20OK%20 "
data "birthyear=1905&press=%20OK%20"
<|> err | #!/usr/bin/env ./execthirdline.sh
set -e & & port=`echo $ { 3 } | awk -F/ ' { print $ ( 3 ) } ' ` & & docker run -it -p $ { port}:${port } -v /c / Users / magocoal / OneDrive / Haskell / devel:/devel testtls bash -c " cd /devel / transient - universe - tls / tests/ ; -j2 -isrc -i / devel / transient / src -i / devel / transient - universe / src -i / devel / transient - universe - tls / src -i / devel / ghcjs - hplay / src -i / devel / ghcjs - perch / src $ 1 $ 2 $ 3 $ 4 "
set -e & & port=`echo $ { 3 } | awk -F/ ' { print $ ( 3 ) } ' ` & & docker run -it -p $ { port}:${port } -v $ ( pwd):/work agocorona / transient:05 - 02 - 2017 bash -c " runghc /work/${1 } $ { 2 } $ { 3 } "
execute as ./api.hs -p start/<docker ip>/<port >
92.168.99.100:8080/api/
invoque: curl http://<docker ip>/<port>/api/hello/john
curl http://<docker ip>/<port>/api/hellos/john
92.168.99.100:8080/api/
-}
# LANGUAGE ScopedTypeVariables #
import Transient.Internals
import Transient.TLS
import Transient.Move
import Transient.Move.Utils
import Transient.Logged
import Transient.Indeterminism
import Control.Applicative
import Control.Concurrent(threadDelay)
import Control.Monad.IO.Class
import qualified Data.ByteString.Lazy.Char8 as BS
import Control.Exception hiding (onException)
main = do
initTLS
keep' $ initNode apisample
where
posts= do
received POST
postParams <- param
liftIO $ print (postParams :: PostParams)
let msg= "received" ++ show postParams
len= length msg
return $ BS.pack $ "HTTP/1.0 200 OK\nContent-Type: text/plain\nContent-Length: "++ show len
++ "\nConnection: close\n\n" ++ msg
gets= received GET >> hello <|> hellostream
hello= do
received "hello"
name <- param
let msg= "hello " ++ name ++ "\n"
len= length msg
return $ BS.pack $ "HTTP/1.0 200 OK\nContent-Type: text/plain\nContent-Length: "++ show len
++ "\nConnection: close\n\n" ++ msg
hellostream = do
received "hellos"
name <- param
threads 0 $ header <|> stream name
where
header=async $ return $ BS.pack $
"HTTP/1.0 200 OK\nContent-Type: text/plain\nConnection: close\n\n"++
"here follows a stream\n"
stream name= do
i <- choose [1 ..]
liftIO $ threadDelay 1000000
return . BS.pack $ " hello " ++ name ++ " "++ show i
err= return $ BS.pack $ " HTTP/1.0 404 Not Founds\nContent - Length : 0\nConnection : close\n\n "
|
28bb94d398391295af50f0a7367457808130b6fed83c118306fcd764137d4f49 | polysemy-research/polysemy | NonDet.hs | {-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE TemplateHaskell #
-- | Description: Interpreters for 'NonDet'
module Polysemy.NonDet
( -- * Effect
NonDet (..)
-- * Interpretations
, runNonDet
, runNonDetMaybe
, nonDetToError
) where
import Control.Applicative
import Control.Monad.Trans.Maybe
import Data.Maybe
import Polysemy
import Polysemy.Error
import Polysemy.Internal
import Polysemy.Internal.NonDet
import Polysemy.Internal.Union
------------------------------------------------------------------------------
| Run a ' NonDet ' effect in terms of some underlying ' Alternative ' @f@.
runNonDet :: Alternative f => Sem (NonDet ': r) a -> Sem r (f a)
runNonDet = runNonDetC . runNonDetInC
# INLINE runNonDet #
------------------------------------------------------------------------------
| Run a ' NonDet ' effect in terms of an underlying ' Maybe '
--
-- Unlike 'runNonDet', uses of '<|>' will not execute the
second branch at all if the first option succeeds .
--
-- @since 1.1.0.0
runNonDetMaybe :: Sem (NonDet ': r) a -> Sem r (Maybe a)
runNonDetMaybe (Sem sem) = Sem $ \k -> runMaybeT $ sem $ \u ->
case decomp u of
Right (Weaving e s wv ex _) ->
case e of
Empty -> empty
Choose left right ->
MaybeT $ usingSem k $ runMaybeT $ fmap ex $
MaybeT (runNonDetMaybe (wv (left <$ s)))
<|> MaybeT (runNonDetMaybe (wv (right <$ s)))
Left x -> MaybeT $
k $ weave (Just ())
(maybe (pure Nothing) runNonDetMaybe)
id
x
# INLINE runNonDetMaybe #
------------------------------------------------------------------------------
| Transform a ' NonDet ' effect into an @'Error ' e@ effect ,
-- through providing an exception that 'empty' may be mapped to.
--
-- This allows '<|>' to handle 'throw's of the @'Error' e@ effect.
--
-- @since 1.1.0.0
nonDetToError :: Member (Error e) r
=> e
-> Sem (NonDet ': r) a
-> Sem r a
nonDetToError (e :: e) = interpretH $ \case
Empty -> throw e
Choose left right -> do
left' <- nonDetToError e <$> runT left
right' <- nonDetToError e <$> runT right
raise (left' `catch` \(_ :: e) -> right')
# INLINE nonDetToError #
--------------------------------------------------------------------------------
-- This stuff is lifted from 'fused-effects'. Thanks guys!
runNonDetC :: (Alternative f, Applicative m) => NonDetC m a -> m (f a)
runNonDetC (NonDetC m) = m (fmap . (<|>) . pure) (pure empty)
# INLINE runNonDetC #
newtype NonDetC m a = NonDetC
| A higher - order function receiving two parameters : a function to combine
-- each solution with the rest of the solutions, and an action to run when no
-- results are produced.
unNonDetC :: forall b . (a -> m b -> m b) -> m b -> m b
}
deriving (Functor)
instance Applicative (NonDetC m) where
pure a = NonDetC (\ cons -> cons a)
# INLINE pure #
NonDetC f <*> NonDetC a = NonDetC $ \ cons ->
f (\ f' -> a (cons . f'))
{-# INLINE (<*>) #-}
instance Alternative (NonDetC m) where
empty = NonDetC (\ _ nil -> nil)
{-# INLINE empty #-}
NonDetC l <|> NonDetC r = NonDetC $ \ cons -> l cons . r cons
{-# INLINE (<|>) #-}
instance Monad (NonDetC m) where
NonDetC a >>= f = NonDetC $ \ cons ->
a (\ a' -> unNonDetC (f a') cons)
{-# INLINE (>>=) #-}
runNonDetInC :: Sem (NonDet ': r) a -> NonDetC (Sem r) a
runNonDetInC = usingSem $ \u ->
case decomp u of
Left x -> NonDetC $ \c b -> do
l <- liftSem $ weave [()]
KingoftheHomeless : This is NOT the right semantics , but
the known alternatives are worse . See Issue # 246 .
(fmap concat . traverse runNonDet)
listToMaybe
x
foldr c b l
Right (Weaving Empty _ _ _ _) -> empty
Right (Weaving (Choose left right) s wv ex _) -> fmap ex $
runNonDetInC (wv (left <$ s)) <|> runNonDetInC (wv (right <$ s))
# INLINE runNonDetInC #
| null | https://raw.githubusercontent.com/polysemy-research/polysemy/10a1336f32438c2d308313f8ad55ac736145390f/src/Polysemy/NonDet.hs | haskell | # LANGUAGE DeriveAnyClass #
| Description: Interpreters for 'NonDet'
* Effect
* Interpretations
----------------------------------------------------------------------------
----------------------------------------------------------------------------
Unlike 'runNonDet', uses of '<|>' will not execute the
@since 1.1.0.0
----------------------------------------------------------------------------
through providing an exception that 'empty' may be mapped to.
This allows '<|>' to handle 'throw's of the @'Error' e@ effect.
@since 1.1.0.0
------------------------------------------------------------------------------
This stuff is lifted from 'fused-effects'. Thanks guys!
each solution with the rest of the solutions, and an action to run when no
results are produced.
# INLINE (<*>) #
# INLINE empty #
# INLINE (<|>) #
# INLINE (>>=) # | # LANGUAGE TemplateHaskell #
module Polysemy.NonDet
NonDet (..)
, runNonDet
, runNonDetMaybe
, nonDetToError
) where
import Control.Applicative
import Control.Monad.Trans.Maybe
import Data.Maybe
import Polysemy
import Polysemy.Error
import Polysemy.Internal
import Polysemy.Internal.NonDet
import Polysemy.Internal.Union
| Run a ' NonDet ' effect in terms of some underlying ' Alternative ' @f@.
runNonDet :: Alternative f => Sem (NonDet ': r) a -> Sem r (f a)
runNonDet = runNonDetC . runNonDetInC
# INLINE runNonDet #
| Run a ' NonDet ' effect in terms of an underlying ' Maybe '
second branch at all if the first option succeeds .
runNonDetMaybe :: Sem (NonDet ': r) a -> Sem r (Maybe a)
runNonDetMaybe (Sem sem) = Sem $ \k -> runMaybeT $ sem $ \u ->
case decomp u of
Right (Weaving e s wv ex _) ->
case e of
Empty -> empty
Choose left right ->
MaybeT $ usingSem k $ runMaybeT $ fmap ex $
MaybeT (runNonDetMaybe (wv (left <$ s)))
<|> MaybeT (runNonDetMaybe (wv (right <$ s)))
Left x -> MaybeT $
k $ weave (Just ())
(maybe (pure Nothing) runNonDetMaybe)
id
x
# INLINE runNonDetMaybe #
| Transform a ' NonDet ' effect into an @'Error ' e@ effect ,
nonDetToError :: Member (Error e) r
=> e
-> Sem (NonDet ': r) a
-> Sem r a
nonDetToError (e :: e) = interpretH $ \case
Empty -> throw e
Choose left right -> do
left' <- nonDetToError e <$> runT left
right' <- nonDetToError e <$> runT right
raise (left' `catch` \(_ :: e) -> right')
# INLINE nonDetToError #
runNonDetC :: (Alternative f, Applicative m) => NonDetC m a -> m (f a)
runNonDetC (NonDetC m) = m (fmap . (<|>) . pure) (pure empty)
# INLINE runNonDetC #
newtype NonDetC m a = NonDetC
| A higher - order function receiving two parameters : a function to combine
unNonDetC :: forall b . (a -> m b -> m b) -> m b -> m b
}
deriving (Functor)
instance Applicative (NonDetC m) where
pure a = NonDetC (\ cons -> cons a)
# INLINE pure #
NonDetC f <*> NonDetC a = NonDetC $ \ cons ->
f (\ f' -> a (cons . f'))
instance Alternative (NonDetC m) where
empty = NonDetC (\ _ nil -> nil)
NonDetC l <|> NonDetC r = NonDetC $ \ cons -> l cons . r cons
instance Monad (NonDetC m) where
NonDetC a >>= f = NonDetC $ \ cons ->
a (\ a' -> unNonDetC (f a') cons)
runNonDetInC :: Sem (NonDet ': r) a -> NonDetC (Sem r) a
runNonDetInC = usingSem $ \u ->
case decomp u of
Left x -> NonDetC $ \c b -> do
l <- liftSem $ weave [()]
KingoftheHomeless : This is NOT the right semantics , but
the known alternatives are worse . See Issue # 246 .
(fmap concat . traverse runNonDet)
listToMaybe
x
foldr c b l
Right (Weaving Empty _ _ _ _) -> empty
Right (Weaving (Choose left right) s wv ex _) -> fmap ex $
runNonDetInC (wv (left <$ s)) <|> runNonDetInC (wv (right <$ s))
# INLINE runNonDetInC #
|
51150886e2f44e2cfaba33e8a5339019d87845547a8a5537cdd33f4d4c12d5e2 | soegaard/cairo | dot-method.rkt | #lang racket/base
(require racket/match racket/list racket/class
(for-syntax racket/base syntax/parse racket/syntax
racket/string))
(provide
dot-field
dot-assign-field
declare-struct-fields
app-dot-method
define-method
:=
;apply-dot-method
; get-dot-method
; define-method
dot-top
dot-app
)
(define-syntax (dot-app stx)
(syntax-parse stx
; calls to a o.m is a method call
; calls to an f is a normal call
[(app proc-id:id . args)
; (display ".")
(define str (symbol->string (syntax-e #'proc-id)))
(cond
[(string-contains? str ".")
(define ids (map string->symbol (string-split str ".")))
(with-syntax ([(id ...) (for/list ([id ids])
(datum->syntax #'proc-id id))])
#'(app-dot-method (id ...) . args))]
[else
#'(#%app proc-id . args)])]
[(app . more)
(syntax/loc stx
(#%app . more))]))
(define-syntax (dot-top stx)
(syntax-parse stx
[(top . top-id)
(display ".")
(define str (symbol->string (syntax-e #'top-id)))
(cond
[(string-contains? str ".")
(define ids (map string->symbol (string-split str ".")))
(with-syntax ([(id ...) (for/list ([id ids])
(datum->syntax #'top-id id))])
#'(dot-field id ...))]
[else
#'(#%top . top-id)])]))
;;;
;;; Dot Fields and Methods
;;;
For a struct Circle defined as :
( struct Circle ( x y r ) )
; we would like to write
( define c ( Circle 10 20 30 ) )
( circle c.x c.y c.r )
; in order to draw the circle. Here circle is the draw-a-circle
; primitive provided by Sketching.
The value stored in c is a Circle struct , so we need
associate Circle structs with a set of fields .
( define - fields Circle Circle ? ( x y r ) )
; We can now write:
; (define (draw-circle c)
( circle c.x c.y c.r ) )
; (here draw is called a method).
; To do that we use define-method:
( define - method Circle Circle ? ( draw color )
; (stroke color)
( circle ( Circle - x this ) ( Circle - y this )
;; (define-method struct-name struct-predicate
;; (method-name . formals) . more)
;;;
;;; Implementation
;;;
; Each "class" e.g. struct or vector is identified by an unique symbol,
; called the class symbol.
For ( define - fields Circle Circle ? ( x y r ) ) the class symbol will be Circle .
Each class has a list of fields , here the list of fields are x , y and
Now at runtime c.x must called the accessor Circle - x ,
; so we also need to store the accessor of each field.
And later we want to support assignments of the form (: = c.x 10 ) ,
; so we also store mutators for the fields.
(struct info (accessor mutator))
; symbol -> (list (cons symbol info) ...)
(define class-symbol-to-fields+infos-ht (make-hasheq))
(define (add-fields! class-symbol fields accessors mutators)
; todo: signal error, if class symbol is in use?
(define fields+infos (map cons fields (map info accessors mutators)))
(hash-set! class-symbol-to-fields+infos-ht class-symbol fields+infos))
(define (get-fields+infos class-symbol)
(hash-ref class-symbol-to-fields+infos-ht class-symbol #f))
(define (find-info fields+infos field)
(cond
[(assq field fields+infos) => (λ (x) (cdr x))]
[else #f]))
(define (find-accessor fields+infos field)
(cond
[(assq field fields+infos) => (λ (x) (info-accessor (cdr x)))]
[else #f]))
(define (find-mutator fields+infos field)
(cond
[(assq field fields+infos) => (λ (x) (info-mutator (cdr x)))]
[else #f]))
; In an expression like c.x the identifier c is bound to
; a value. To get from the value to the class symbol, we
; need some predicates.
(define class-symbol-to-predicate-ht (make-hasheq)) ; symbol -> (value -> boolean)
(define predicate-to-class-symbol-assoc '()) ; (list (cons predicate symbol) ...)
(define (add-predicate! class-symbol predicate)
(hash-set! class-symbol-to-predicate-ht class-symbol predicate)
(set! predicate-to-class-symbol-assoc
(cons (cons predicate class-symbol)
predicate-to-class-symbol-assoc)))
(define (find-class-symbol value)
(let loop ([as predicate-to-class-symbol-assoc])
(cond
[(empty? as) #f] ; the value has no associated class symbol
[else (define predicate+symbol (car as))
(define predicate (car predicate+symbol))
(if (predicate value)
(cdr predicate+symbol)
(loop (cdr as)))])))
(define (find-class-symbol+predicate value)
(let loop ([as predicate-to-class-symbol-assoc])
(cond
[(empty? as) (values #f #f)] ; the value has no associated class symbol
[else (define predicate+symbol (car as))
(define predicate (car predicate+symbol))
(if (predicate value)
(values (cdr predicate+symbol) predicate)
(loop (cdr as)))])))
Finally we need address how c.x eventually evaluates ( Circle - x c ) .
; Since c.x isn't bound in our program, the expander expands
c.x into ( # % top c.x ) . In " main.rkt " we have defined a
# % sketching - top , which will be used as # % top by programs
; written in the Sketching language.
In # % sketching - top we detect that the unbound identifier contains
; a dot, and we can then expand it into:
; (dot-field c x)
; The naive implementation of dot-field will expand into:
;; (let ()
;; (define class-symbol (find-class-symbol c))
( define fields+accessors ( get - fields+accessors class - symbol ) )
( define accessor ( find - accessor fields+accessors ' x ) )
;; (accessor c))
; However, if c.x is being used in a loop where c runs through a series of circles,
; then it is a waste of time to search for the same class symbol and accessor
; each time. Instead we can cache the accessor (and a predicate) so we can reuse
; the next time. The predicate is used to check that we got a value of the
; same time as last - if not, then we need to look for the new class.
(define-syntax (dot-field stx)
(syntax-parse stx
[(_dot-field object:id field:id)
(with-syntax
([cached-accessor (syntax-local-lift-expression #'#f)] ; think: (define cached-accessor #f)
[cached-predicate (syntax-local-lift-expression #'#f)] ; is added at the top-level
[stx stx])
#'(let ()
(define accessor
(cond
[(and cached-predicate (cached-predicate object)) cached-accessor]
[(object? object)
(set! cached-accessor (λ (obj) (get-field field obj)))
; (class-field-accessor class-expr field-id) ; todo !!
(set! cached-predicate object?)
cached-accessor]
[else
(define-values (class-symbol predicate) (find-class-symbol+predicate object))
(define fields+infos (get-fields+infos class-symbol))
(define a (find-accessor fields+infos 'field))
(set! cached-accessor a)
(set! cached-predicate predicate)
(unless a
(raise-syntax-error 'dot-field "object does not have this field" #'stx))
a]))
(accessor object)))]
[(_dot-field object:id field:id ... last-field:id)
(syntax/loc stx
(let ([t (dot-field object field ...)])
(dot-field t last-field)))]))
(define-syntax (dot-assign-field stx)
(syntax-parse stx
[(_dot-assign-field object:id field:id e:expr)
(with-syntax ([cached-mutator (syntax-local-lift-expression #'#f)]
[cached-predicate (syntax-local-lift-expression #'#f)]
[stx stx])
#'(let ()
(define mutator
(cond
[(and cached-predicate (cached-predicate object)) cached-mutator]
[(object? object)
(set! cached-mutator (λ (obj v) (set-field! field obj v)))
(set! cached-predicate object?)
cached-mutator]
[else
(define-values (class-symbol predicate) (find-class-symbol+predicate object))
(define fields+infos (get-fields+infos class-symbol))
(define m (find-mutator fields+infos 'field))
(set! cached-mutator m)
(set! cached-predicate predicate)
m]))
(mutator object e)))]
[(_dot-field object:id field:id ... last-field:id e:expr)
(syntax/loc stx
(let ([w e] [t (dot-field object field ...)])
(dot-assign-field t last-field w)))]))
;;;
;;; Defining class with fields
;;;
; We would like to write:
( declare - struct - fields Circle Circle ? ( x y r ) )
to declare that the Circle " class " has fields x , y and r.
; The general form is:
; (declare-struct-fields class-symbol predicate (field ...))
(define-syntax (declare-struct-fields stx)
(syntax-parse stx
[(_declare-struct-fields struct-name:id predicate:id (field:id ...))
(with-syntax ([class-symbol #'struct-name]
[(accessor ...)
(for/list ([f (syntax->list #'(field ...))])
(format-id f "~a-~a" #'struct-name f))]
[(mutator ...)
(for/list ([f (syntax->list #'(field ...))])
(format-id f "set-~a-~a!" #'struct-name f))])
(syntax/loc stx
(begin
(add-predicate! 'class-symbol predicate)
(add-fields! 'class-symbol '(field ...)
(list accessor ...)
(list mutator ...)))))]))
;;;
;;; Assignment
;;;
;; (define str (symbol->string (syntax-e #'top-id)))
;; (cond
;; [(string-contains? str ".")
;; (define ids (map string->symbol (string-split str ".")))
;; (with-syntax ([(id ...) (for/list ([id ids])
;; (datum->syntax #'top-id id))])
;; #'(dot-field id ...))]
;; [else
# ' ( # % top . top - id ) ] )
(: = v.i.j 42 )
; (vector-set! (vector-ref v i) j 42)
(define-syntax (:= stx)
(syntax-parse stx
[(_ x:id e)
(define str (symbol->string (syntax-e #'x)))
(cond
[(string-contains? str ".")
(define ids (map string->symbol (string-split str ".")))
(with-syntax ([(x ...) (for/list ([id ids])
(datum->syntax #'x id))])
(syntax/loc stx
(dot-assign-field x ... e)))]
[else
(syntax/loc stx
(set! x e))])]
[(_ v:id e1 e2)
(syntax/loc stx
(let ()
(when (vector? v)
(define i e1)
(when (and (integer? i) (not (negative? i)))
(vector-set! v i e2)))))]))
;;;
;;; Methods
;;;
For a struct Circle defined as :
( struct Circle ( x y r ) )
; we would like to write
( define c ( Circle 10 20 30 ) )
( define - method Circle ( draw this color )
; (stroke color)
; (circle this.x this.y this.r))
; (c.draw "red")
; in order to draw the circle.
The method draw of the class Circle is called as ( c.draw " red " )
and turns into ( Circle - draw c " red " ) .
(struct minfo (procedure)) ; "method onfo"
symbol - > ( list ( cons symbol ) ... )
(define class-symbol-to-methods+minfos-ht (make-hasheq))
(define (add-method! class-symbol method procedure)
(define methods+minfos (hash-ref class-symbol-to-methods+minfos-ht class-symbol '()))
(define method+minfo (cons method (minfo procedure)))
(hash-set! class-symbol-to-methods+minfos-ht class-symbol (cons method+minfo methods+minfos)))
(define (get-methods+minfos class-symbol)
(hash-ref class-symbol-to-methods+minfos-ht class-symbol #f))
(define (find-method-procedure methods+minfos method)
(cond
[(assq method methods+minfos) => (λ (x) (minfo-procedure (cdr x)))]
[else #f]))
(define-syntax (app-dot-method stx)
(syntax-parse stx
[(_app-dot-method (object:id method:id) . args)
(with-syntax
([cached-procedure (syntax-local-lift-expression #'#f)] ; think: (define cached-procedure #f)
[cached-predicate (syntax-local-lift-expression #'#f)] ; is added at the top-level
[stx stx])
#'(let ()
(define procedure
(cond
[(and cached-predicate (cached-predicate object)) cached-procedure]
[(object? object)
; XXX
(set! cached-predicate object?)
(set! cached-procedure (λ (obj . as)
( ( list ' obj obj ) )
( ( list ' args args ) )
(send/apply obj method as)))
cached-procedure]
[else
(define-values (class-symbol predicate) (find-class-symbol+predicate object))
(define methods+minfos (get-methods+minfos class-symbol))
(define p (find-method-procedure methods+minfos 'method))
(set! cached-procedure p)
(set! cached-predicate predicate)
(unless p
(raise-syntax-error 'app-dot-methods "object does not have this method" #'stx))
p]))
(procedure object . args)))]
[(_app-dot-field (object:id field:id ... method:id) . args)
(syntax/loc stx
(let ([obj (dot-field object field ...)])
(app-dot-method (obj method) . args)))]))
(define-syntax (define-method stx)
(syntax-parse stx
[(_define-method struct-name:id (method-name:id . formals) . more)
(with-syntax ([struct-predicate (format-id stx "~a?" #'struct-name)]
[struct-method (format-id stx "~a-~a" #'struct-name #'method-name)]
[this (format-id stx "this")])
(syntax/loc stx
(begin
(define (struct-method this . formals) . more)
(add-predicate! 'struct-name struct-predicate)
(add-method! 'struct-name 'method-name struct-method))))]))
;;;
Builtin " classes "
;;;
(add-predicate! 'vector vector?)
(add-predicate! 'list list?)
(add-predicate! 'string string?)
Builtin fields for builtin " classes "
(add-fields! 'vector '(ref x y z)
(list (λ (this) (λ (index) (vector-ref this index)))
(λ (v) (vector-ref v 0))
(λ (v) (vector-ref v 1))
(λ (v) (vector-ref v 2)))
(list #f
(λ (v e) (vector-set! v 0 e))
(λ (v e) (vector-set! v 1 e))
(λ (v e) (vector-set! v 2 e))))
(add-fields! 'list '(x y z)
(list first second third)
(list #f #f #f))
(add-method! 'vector 'length vector-length)
(add-method! 'vector 'ref vector-ref)
(add-method! 'vector 'list vector->list)
(add-method! 'vector 'fill! vector-fill!)
(add-method! 'vector 'values vector->values)
(add-method! 'list 'length length)
(add-method! 'list 'ref list-ref)
(add-method! 'list 'vector list->vector)
(add-method! 'string 'length string-length)
(add-method! 'string 'ref string-ref)
(add-method! 'string 'list string->list)
;; ;;;
;; ;;; Methods
;; ;;;
;; (hash-set*! class-symbol-to-methods-ht
;; 'vector
;; (make-methods-ht 'length vector-length
;; 'ref vector-ref
;; 'list vector->list
;; 'fill! vector-fill!
;; 'values vector->values)
;; 'list
;; (make-methods-ht 'length length
;; 'ref list-ref
;; 'vector list->vector
;; 'values (λ (xs) (apply values xs)))
;; 'string
;; (make-methods-ht 'length string-length
;; 'ref string-ref
' list string->list )
;; ; unknown class
;; #f (make-hasheq))
;; (define class-symbol-to-methods-ht (make-hasheq))
;; (define (make-methods-ht . args)
;; (define key-methods
;; (let loop ([args args])
;; (match args
;; [(list* key method more)
;; (cons (cons key method)
;; (loop more))]
;; ['()
;; '()])))
;; (make-hasheq key-methods))
;; (define (predicates->symbol x)
;; ...)
;; (define (value->class-symbol v)
;; (cond
;; [(vector? v) 'vector]
;; [(list? v) 'list]
;; [(string? v) 'string]
;; [else #f]))
( define - syntax ( apply - dot - method stx )
( syntax - parse stx
;; [(_get object:id method-name:id more ...)
;; #'(let ()
;; (define class (value->class-symbol object))
;; (define methods (hash-ref class-symbol-to-methods-ht class #f))
;; (define method (hash-ref methods 'method-name ))
;; (method object more ...))]))
( define - syntax ( get - dot - method stx )
( syntax - parse stx
;; [(_get object:id method-name:id)
;; #'(let ()
;; (define cached-method #f)
;; (define cached-predicate #f)
;; (λ args
;; (define method
;; (cond
;; [(and cached-predicate (cached-predicate object)) cached-method]
;; [else
;; (define class (value->class-symbol object))
( ( list ' class class ) )
( define p ( hash - ref class - symbol - to - predicates - ht class # f ) )
( ( list ' p p ) )
;; (define ms (hash-ref class-symbol-to-methods-ht class #f))
( ( list ' ms ms ) )
;; (define m (hash-ref ms 'method-name))
( ( list ' m m ) )
;; (set! cached-predicate p)
;; (set! cached-method m)
;; m]))
;; (apply method (cons object args))))]))
( define - syntax ( define - method stx )
( syntax - parse stx
;; [(_define-method struct-name:id struct-predicate:id
;; (method-name:id . formals)
;; . more)
;; (with-syntax ([struct-method (format-id stx "~a-~a" #'struct-name #'method-name)])
( syntax /
;; (begin
;; (define (struct-method this . formals) . more)
;; (hash-set*! class-symbol-to-predicates-ht 'struct-name struct-predicate)
;; (define ht (hash-ref class-symbol-to-methods-ht 'struct-name #f))
;; (unless ht
;; (define new-ht (make-hasheq))
;; (hash-set! class-symbol-to-methods-ht 'struct-name new-ht)
;; (set! ht new-ht))
;; (hash-set! ht 'method-name struct-method)
( " -- " )
( displayln class - symbol - to - methods - ht )
;; (newline)
( displayln ht ) ( newline )
;; )))]))
; ; ( define - syntax ( # % top stx )
;; ;; (display ".")
; ; ( syntax - parse stx
;; ;; [(_ . s:id) #'id]))
; ; ( struct Circle ( x y r c ) )
; ; ; ; ( define - method Circle ( draw C [ color " red " ] )
;; ;; ;; (fill color)
;; ;; ;; (circle C.x C.y C.r))
; ; ; ( obj.name foo bar ) = > ( mehthod foo
; ; ( define c ( Circle 10 20 30 " white " ) )
;; ;c.x
| null | https://raw.githubusercontent.com/soegaard/cairo/cac25d351af234e0af935bfe138c397dca49fc1a/cairo-test/dot-method.rkt | racket | apply-dot-method
get-dot-method
define-method
calls to a o.m is a method call
calls to an f is a normal call
(display ".")
Dot Fields and Methods
we would like to write
in order to draw the circle. Here circle is the draw-a-circle
primitive provided by Sketching.
We can now write:
(define (draw-circle c)
(here draw is called a method).
To do that we use define-method:
(stroke color)
(define-method struct-name struct-predicate
(method-name . formals) . more)
Implementation
Each "class" e.g. struct or vector is identified by an unique symbol,
called the class symbol.
so we also need to store the accessor of each field.
so we also store mutators for the fields.
symbol -> (list (cons symbol info) ...)
todo: signal error, if class symbol is in use?
In an expression like c.x the identifier c is bound to
a value. To get from the value to the class symbol, we
need some predicates.
symbol -> (value -> boolean)
(list (cons predicate symbol) ...)
the value has no associated class symbol
the value has no associated class symbol
Since c.x isn't bound in our program, the expander expands
written in the Sketching language.
a dot, and we can then expand it into:
(dot-field c x)
The naive implementation of dot-field will expand into:
(let ()
(define class-symbol (find-class-symbol c))
(accessor c))
However, if c.x is being used in a loop where c runs through a series of circles,
then it is a waste of time to search for the same class symbol and accessor
each time. Instead we can cache the accessor (and a predicate) so we can reuse
the next time. The predicate is used to check that we got a value of the
same time as last - if not, then we need to look for the new class.
think: (define cached-accessor #f)
is added at the top-level
(class-field-accessor class-expr field-id) ; todo !!
Defining class with fields
We would like to write:
The general form is:
(declare-struct-fields class-symbol predicate (field ...))
Assignment
(define str (symbol->string (syntax-e #'top-id)))
(cond
[(string-contains? str ".")
(define ids (map string->symbol (string-split str ".")))
(with-syntax ([(id ...) (for/list ([id ids])
(datum->syntax #'top-id id))])
#'(dot-field id ...))]
[else
(vector-set! (vector-ref v i) j 42)
Methods
we would like to write
(stroke color)
(circle this.x this.y this.r))
(c.draw "red")
in order to draw the circle.
"method onfo"
think: (define cached-procedure #f)
is added at the top-level
XXX
;;;
;;; Methods
;;;
(hash-set*! class-symbol-to-methods-ht
'vector
(make-methods-ht 'length vector-length
'ref vector-ref
'list vector->list
'fill! vector-fill!
'values vector->values)
'list
(make-methods-ht 'length length
'ref list-ref
'vector list->vector
'values (λ (xs) (apply values xs)))
'string
(make-methods-ht 'length string-length
'ref string-ref
; unknown class
#f (make-hasheq))
(define class-symbol-to-methods-ht (make-hasheq))
(define (make-methods-ht . args)
(define key-methods
(let loop ([args args])
(match args
[(list* key method more)
(cons (cons key method)
(loop more))]
['()
'()])))
(make-hasheq key-methods))
(define (predicates->symbol x)
...)
(define (value->class-symbol v)
(cond
[(vector? v) 'vector]
[(list? v) 'list]
[(string? v) 'string]
[else #f]))
[(_get object:id method-name:id more ...)
#'(let ()
(define class (value->class-symbol object))
(define methods (hash-ref class-symbol-to-methods-ht class #f))
(define method (hash-ref methods 'method-name ))
(method object more ...))]))
[(_get object:id method-name:id)
#'(let ()
(define cached-method #f)
(define cached-predicate #f)
(λ args
(define method
(cond
[(and cached-predicate (cached-predicate object)) cached-method]
[else
(define class (value->class-symbol object))
(define ms (hash-ref class-symbol-to-methods-ht class #f))
(define m (hash-ref ms 'method-name))
(set! cached-predicate p)
(set! cached-method m)
m]))
(apply method (cons object args))))]))
[(_define-method struct-name:id struct-predicate:id
(method-name:id . formals)
. more)
(with-syntax ([struct-method (format-id stx "~a-~a" #'struct-name #'method-name)])
(begin
(define (struct-method this . formals) . more)
(hash-set*! class-symbol-to-predicates-ht 'struct-name struct-predicate)
(define ht (hash-ref class-symbol-to-methods-ht 'struct-name #f))
(unless ht
(define new-ht (make-hasheq))
(hash-set! class-symbol-to-methods-ht 'struct-name new-ht)
(set! ht new-ht))
(hash-set! ht 'method-name struct-method)
(newline)
)))]))
; ( define - syntax ( # % top stx )
;; (display ".")
; ( syntax - parse stx
;; [(_ . s:id) #'id]))
; ( struct Circle ( x y r c ) )
; ; ; ( define - method Circle ( draw C [ color " red " ] )
;; ;; (fill color)
;; ;; (circle C.x C.y C.r))
; ; ( obj.name foo bar ) = > ( mehthod foo
; ( define c ( Circle 10 20 30 " white " ) )
;c.x | #lang racket/base
(require racket/match racket/list racket/class
(for-syntax racket/base syntax/parse racket/syntax
racket/string))
(provide
dot-field
dot-assign-field
declare-struct-fields
app-dot-method
define-method
:=
dot-top
dot-app
)
(define-syntax (dot-app stx)
(syntax-parse stx
[(app proc-id:id . args)
(define str (symbol->string (syntax-e #'proc-id)))
(cond
[(string-contains? str ".")
(define ids (map string->symbol (string-split str ".")))
(with-syntax ([(id ...) (for/list ([id ids])
(datum->syntax #'proc-id id))])
#'(app-dot-method (id ...) . args))]
[else
#'(#%app proc-id . args)])]
[(app . more)
(syntax/loc stx
(#%app . more))]))
(define-syntax (dot-top stx)
(syntax-parse stx
[(top . top-id)
(display ".")
(define str (symbol->string (syntax-e #'top-id)))
(cond
[(string-contains? str ".")
(define ids (map string->symbol (string-split str ".")))
(with-syntax ([(id ...) (for/list ([id ids])
(datum->syntax #'top-id id))])
#'(dot-field id ...))]
[else
#'(#%top . top-id)])]))
For a struct Circle defined as :
( struct Circle ( x y r ) )
( define c ( Circle 10 20 30 ) )
( circle c.x c.y c.r )
The value stored in c is a Circle struct , so we need
associate Circle structs with a set of fields .
( define - fields Circle Circle ? ( x y r ) )
( circle c.x c.y c.r ) )
( define - method Circle Circle ? ( draw color )
( circle ( Circle - x this ) ( Circle - y this )
For ( define - fields Circle Circle ? ( x y r ) ) the class symbol will be Circle .
Each class has a list of fields , here the list of fields are x , y and
Now at runtime c.x must called the accessor Circle - x ,
And later we want to support assignments of the form (: = c.x 10 ) ,
(struct info (accessor mutator))
(define class-symbol-to-fields+infos-ht (make-hasheq))
(define (add-fields! class-symbol fields accessors mutators)
(define fields+infos (map cons fields (map info accessors mutators)))
(hash-set! class-symbol-to-fields+infos-ht class-symbol fields+infos))
(define (get-fields+infos class-symbol)
(hash-ref class-symbol-to-fields+infos-ht class-symbol #f))
(define (find-info fields+infos field)
(cond
[(assq field fields+infos) => (λ (x) (cdr x))]
[else #f]))
(define (find-accessor fields+infos field)
(cond
[(assq field fields+infos) => (λ (x) (info-accessor (cdr x)))]
[else #f]))
(define (find-mutator fields+infos field)
(cond
[(assq field fields+infos) => (λ (x) (info-mutator (cdr x)))]
[else #f]))
(define (add-predicate! class-symbol predicate)
(hash-set! class-symbol-to-predicate-ht class-symbol predicate)
(set! predicate-to-class-symbol-assoc
(cons (cons predicate class-symbol)
predicate-to-class-symbol-assoc)))
(define (find-class-symbol value)
(let loop ([as predicate-to-class-symbol-assoc])
(cond
[else (define predicate+symbol (car as))
(define predicate (car predicate+symbol))
(if (predicate value)
(cdr predicate+symbol)
(loop (cdr as)))])))
(define (find-class-symbol+predicate value)
(let loop ([as predicate-to-class-symbol-assoc])
(cond
[else (define predicate+symbol (car as))
(define predicate (car predicate+symbol))
(if (predicate value)
(values (cdr predicate+symbol) predicate)
(loop (cdr as)))])))
Finally we need address how c.x eventually evaluates ( Circle - x c ) .
c.x into ( # % top c.x ) . In " main.rkt " we have defined a
# % sketching - top , which will be used as # % top by programs
In # % sketching - top we detect that the unbound identifier contains
( define fields+accessors ( get - fields+accessors class - symbol ) )
( define accessor ( find - accessor fields+accessors ' x ) )
(define-syntax (dot-field stx)
(syntax-parse stx
[(_dot-field object:id field:id)
(with-syntax
[stx stx])
#'(let ()
(define accessor
(cond
[(and cached-predicate (cached-predicate object)) cached-accessor]
[(object? object)
(set! cached-accessor (λ (obj) (get-field field obj)))
(set! cached-predicate object?)
cached-accessor]
[else
(define-values (class-symbol predicate) (find-class-symbol+predicate object))
(define fields+infos (get-fields+infos class-symbol))
(define a (find-accessor fields+infos 'field))
(set! cached-accessor a)
(set! cached-predicate predicate)
(unless a
(raise-syntax-error 'dot-field "object does not have this field" #'stx))
a]))
(accessor object)))]
[(_dot-field object:id field:id ... last-field:id)
(syntax/loc stx
(let ([t (dot-field object field ...)])
(dot-field t last-field)))]))
(define-syntax (dot-assign-field stx)
(syntax-parse stx
[(_dot-assign-field object:id field:id e:expr)
(with-syntax ([cached-mutator (syntax-local-lift-expression #'#f)]
[cached-predicate (syntax-local-lift-expression #'#f)]
[stx stx])
#'(let ()
(define mutator
(cond
[(and cached-predicate (cached-predicate object)) cached-mutator]
[(object? object)
(set! cached-mutator (λ (obj v) (set-field! field obj v)))
(set! cached-predicate object?)
cached-mutator]
[else
(define-values (class-symbol predicate) (find-class-symbol+predicate object))
(define fields+infos (get-fields+infos class-symbol))
(define m (find-mutator fields+infos 'field))
(set! cached-mutator m)
(set! cached-predicate predicate)
m]))
(mutator object e)))]
[(_dot-field object:id field:id ... last-field:id e:expr)
(syntax/loc stx
(let ([w e] [t (dot-field object field ...)])
(dot-assign-field t last-field w)))]))
( declare - struct - fields Circle Circle ? ( x y r ) )
to declare that the Circle " class " has fields x , y and r.
(define-syntax (declare-struct-fields stx)
(syntax-parse stx
[(_declare-struct-fields struct-name:id predicate:id (field:id ...))
(with-syntax ([class-symbol #'struct-name]
[(accessor ...)
(for/list ([f (syntax->list #'(field ...))])
(format-id f "~a-~a" #'struct-name f))]
[(mutator ...)
(for/list ([f (syntax->list #'(field ...))])
(format-id f "set-~a-~a!" #'struct-name f))])
(syntax/loc stx
(begin
(add-predicate! 'class-symbol predicate)
(add-fields! 'class-symbol '(field ...)
(list accessor ...)
(list mutator ...)))))]))
# ' ( # % top . top - id ) ] )
(: = v.i.j 42 )
(define-syntax (:= stx)
(syntax-parse stx
[(_ x:id e)
(define str (symbol->string (syntax-e #'x)))
(cond
[(string-contains? str ".")
(define ids (map string->symbol (string-split str ".")))
(with-syntax ([(x ...) (for/list ([id ids])
(datum->syntax #'x id))])
(syntax/loc stx
(dot-assign-field x ... e)))]
[else
(syntax/loc stx
(set! x e))])]
[(_ v:id e1 e2)
(syntax/loc stx
(let ()
(when (vector? v)
(define i e1)
(when (and (integer? i) (not (negative? i)))
(vector-set! v i e2)))))]))
For a struct Circle defined as :
( struct Circle ( x y r ) )
( define c ( Circle 10 20 30 ) )
( define - method Circle ( draw this color )
The method draw of the class Circle is called as ( c.draw " red " )
and turns into ( Circle - draw c " red " ) .
symbol - > ( list ( cons symbol ) ... )
(define class-symbol-to-methods+minfos-ht (make-hasheq))
(define (add-method! class-symbol method procedure)
(define methods+minfos (hash-ref class-symbol-to-methods+minfos-ht class-symbol '()))
(define method+minfo (cons method (minfo procedure)))
(hash-set! class-symbol-to-methods+minfos-ht class-symbol (cons method+minfo methods+minfos)))
(define (get-methods+minfos class-symbol)
(hash-ref class-symbol-to-methods+minfos-ht class-symbol #f))
(define (find-method-procedure methods+minfos method)
(cond
[(assq method methods+minfos) => (λ (x) (minfo-procedure (cdr x)))]
[else #f]))
(define-syntax (app-dot-method stx)
(syntax-parse stx
[(_app-dot-method (object:id method:id) . args)
(with-syntax
[stx stx])
#'(let ()
(define procedure
(cond
[(and cached-predicate (cached-predicate object)) cached-procedure]
[(object? object)
(set! cached-predicate object?)
(set! cached-procedure (λ (obj . as)
( ( list ' obj obj ) )
( ( list ' args args ) )
(send/apply obj method as)))
cached-procedure]
[else
(define-values (class-symbol predicate) (find-class-symbol+predicate object))
(define methods+minfos (get-methods+minfos class-symbol))
(define p (find-method-procedure methods+minfos 'method))
(set! cached-procedure p)
(set! cached-predicate predicate)
(unless p
(raise-syntax-error 'app-dot-methods "object does not have this method" #'stx))
p]))
(procedure object . args)))]
[(_app-dot-field (object:id field:id ... method:id) . args)
(syntax/loc stx
(let ([obj (dot-field object field ...)])
(app-dot-method (obj method) . args)))]))
(define-syntax (define-method stx)
(syntax-parse stx
[(_define-method struct-name:id (method-name:id . formals) . more)
(with-syntax ([struct-predicate (format-id stx "~a?" #'struct-name)]
[struct-method (format-id stx "~a-~a" #'struct-name #'method-name)]
[this (format-id stx "this")])
(syntax/loc stx
(begin
(define (struct-method this . formals) . more)
(add-predicate! 'struct-name struct-predicate)
(add-method! 'struct-name 'method-name struct-method))))]))
Builtin " classes "
(add-predicate! 'vector vector?)
(add-predicate! 'list list?)
(add-predicate! 'string string?)
Builtin fields for builtin " classes "
(add-fields! 'vector '(ref x y z)
(list (λ (this) (λ (index) (vector-ref this index)))
(λ (v) (vector-ref v 0))
(λ (v) (vector-ref v 1))
(λ (v) (vector-ref v 2)))
(list #f
(λ (v e) (vector-set! v 0 e))
(λ (v e) (vector-set! v 1 e))
(λ (v e) (vector-set! v 2 e))))
(add-fields! 'list '(x y z)
(list first second third)
(list #f #f #f))
(add-method! 'vector 'length vector-length)
(add-method! 'vector 'ref vector-ref)
(add-method! 'vector 'list vector->list)
(add-method! 'vector 'fill! vector-fill!)
(add-method! 'vector 'values vector->values)
(add-method! 'list 'length length)
(add-method! 'list 'ref list-ref)
(add-method! 'list 'vector list->vector)
(add-method! 'string 'length string-length)
(add-method! 'string 'ref string-ref)
(add-method! 'string 'list string->list)
' list string->list )
( define - syntax ( apply - dot - method stx )
( syntax - parse stx
( define - syntax ( get - dot - method stx )
( syntax - parse stx
( ( list ' class class ) )
( define p ( hash - ref class - symbol - to - predicates - ht class # f ) )
( ( list ' p p ) )
( ( list ' ms ms ) )
( ( list ' m m ) )
( define - syntax ( define - method stx )
( syntax - parse stx
( syntax /
( " -- " )
( displayln class - symbol - to - methods - ht )
( displayln ht ) ( newline )
|
990942f78d9275990e41130cad18426467f5e7f4201c57f3432c629bfb16a48c | haskell-opengl/OpenGL | TextureUnit.hs | {-# OPTIONS_HADDOCK hide #-}
--------------------------------------------------------------------------------
-- |
Module : Graphics . Rendering . OpenGL.GL.Texturing . TextureUnit
Copyright : ( c ) 2002 - 2019
-- License : BSD3
--
Maintainer : < >
-- Stability : stable
-- Portability : portable
--
This is a purely internal module for ( un-)marshaling TextureUnit .
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.Texturing.TextureUnit (
TextureUnit(..), marshalTextureUnit, unmarshalTextureUnit
) where
import Foreign.Ptr
import Foreign.Storable
import Graphics.GL
--------------------------------------------------------------------------------
-- | Identifies a texture unit via its number, which must be in the range of
-- (0 .. 'maxTextureUnit').
newtype TextureUnit = TextureUnit GLuint
deriving ( Eq, Ord, Show )
Internal note , when setting a sampler ( TextureUnit ) uniform the GLint
-- functions should be used.
instance Storable TextureUnit where
sizeOf _ = sizeOf (undefined :: GLuint)
alignment _ = alignment (undefined :: GLuint)
peek pt = peek (castPtr pt) >>= return . TextureUnit
poke pt (TextureUnit tu) = poke (castPtr pt) tu
peekByteOff pt off = peekByteOff pt off >>= return . TextureUnit
pokeByteOff pt off (TextureUnit tu)
= pokeByteOff pt off tu
marshalTextureUnit :: TextureUnit -> GLenum
marshalTextureUnit (TextureUnit x) = GL_TEXTURE0 + fromIntegral x
unmarshalTextureUnit :: GLenum -> TextureUnit
unmarshalTextureUnit x = TextureUnit (fromIntegral (x - GL_TEXTURE0))
| null | https://raw.githubusercontent.com/haskell-opengl/OpenGL/f7af8fe04b0f19c260a85c9ebcad612737cd7c8c/src/Graphics/Rendering/OpenGL/GL/Texturing/TextureUnit.hs | haskell | # OPTIONS_HADDOCK hide #
------------------------------------------------------------------------------
|
License : BSD3
Stability : stable
Portability : portable
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Identifies a texture unit via its number, which must be in the range of
(0 .. 'maxTextureUnit').
functions should be used. | Module : Graphics . Rendering . OpenGL.GL.Texturing . TextureUnit
Copyright : ( c ) 2002 - 2019
Maintainer : < >
This is a purely internal module for ( un-)marshaling TextureUnit .
module Graphics.Rendering.OpenGL.GL.Texturing.TextureUnit (
TextureUnit(..), marshalTextureUnit, unmarshalTextureUnit
) where
import Foreign.Ptr
import Foreign.Storable
import Graphics.GL
newtype TextureUnit = TextureUnit GLuint
deriving ( Eq, Ord, Show )
Internal note , when setting a sampler ( TextureUnit ) uniform the GLint
instance Storable TextureUnit where
sizeOf _ = sizeOf (undefined :: GLuint)
alignment _ = alignment (undefined :: GLuint)
peek pt = peek (castPtr pt) >>= return . TextureUnit
poke pt (TextureUnit tu) = poke (castPtr pt) tu
peekByteOff pt off = peekByteOff pt off >>= return . TextureUnit
pokeByteOff pt off (TextureUnit tu)
= pokeByteOff pt off tu
marshalTextureUnit :: TextureUnit -> GLenum
marshalTextureUnit (TextureUnit x) = GL_TEXTURE0 + fromIntegral x
unmarshalTextureUnit :: GLenum -> TextureUnit
unmarshalTextureUnit x = TextureUnit (fromIntegral (x - GL_TEXTURE0))
|
800c54a8a2bd2a6c98ffd9b67becb319dd1a7256fe4ed5deb8c3e789bc8ef992 | avillega/generative-art | circle_packing.clj | (ns generative-artistry.circle-packing
(:require [quil.core :as q]
[quil.middleware :as m]
[generative-artistry.utils :refer :all]))
(def ratio 0.3)
(defn collide? [{x1 :x y1 :y r1 :r stroke1 :stroke}
{x2 :x y2 :y r2 :r stroke2 :stroke}]
(let [x (- x1 x2)
y (- y1 y2)
a (+ r1 r2 stroke2 stroke1)]
(> a (Math/sqrt (+ (* x x) (* y y))))))
(defn update-growing [{:keys [x y r growing stroke max-r] :as circle} others]
(let [should-grow (and (not-any? #(collide? circle %) others)
(< 0 (- x r stroke) (+ x r stroke) 100)
(< 0 (- y r stroke) (+ y r stroke) 100)
(< r max-r)
growing)]
(assoc circle :growing should-grow)))
(defn grow-circle [circle circles]
(loop [c (update-growing circle circles)]
(let [new-c (update c :r + ratio)]
(if (:growing c)
(recur (update-growing new-c circles))
c))))
(defn create-circle [tries others]
(let [x (q/random 0.5 99.5)
y (q/random 0.5 99.5)
new-c {:x x :y y :r 0.03 :stroke 1/5 :growing true :max-r (q/random 10 20)}]
(cond
(> tries 2000) nil
(not-any? #(collide? new-c %) others) new-c
:else (recur (inc tries) others))))
(defn create-circles []
(loop [circles []]
(let [c (some-> (create-circle 0 circles)
(update-growing circles)
(grow-circle circles))]
(if c
(recur (conj circles c))
circles))))
(defn setup []
(q/ellipse-mode :radius)
(q/color-mode :hsb 360 100 100 1.0)
(q/no-loop))
(defn draw []
(q/background 45 10 100)
(let [circles (create-circles)]
(doseq [{:keys [x y r stroke]} circles]
(q/stroke-weight (w stroke))
(q/no-fill)
(q/ellipse (w x) (h y) (w r) (h r))
(q/point (w x) (h y)))))
(q/defsketch circle-packing
:title "Circle packing"
:size [2000 2000]
:setup setup
:draw draw
:features [])
| null | https://raw.githubusercontent.com/avillega/generative-art/cd3be0a40ff9a7972b875df0e9e8f6981e45ee40/src/generative_artistry/circle_packing.clj | clojure | (ns generative-artistry.circle-packing
(:require [quil.core :as q]
[quil.middleware :as m]
[generative-artistry.utils :refer :all]))
(def ratio 0.3)
(defn collide? [{x1 :x y1 :y r1 :r stroke1 :stroke}
{x2 :x y2 :y r2 :r stroke2 :stroke}]
(let [x (- x1 x2)
y (- y1 y2)
a (+ r1 r2 stroke2 stroke1)]
(> a (Math/sqrt (+ (* x x) (* y y))))))
(defn update-growing [{:keys [x y r growing stroke max-r] :as circle} others]
(let [should-grow (and (not-any? #(collide? circle %) others)
(< 0 (- x r stroke) (+ x r stroke) 100)
(< 0 (- y r stroke) (+ y r stroke) 100)
(< r max-r)
growing)]
(assoc circle :growing should-grow)))
(defn grow-circle [circle circles]
(loop [c (update-growing circle circles)]
(let [new-c (update c :r + ratio)]
(if (:growing c)
(recur (update-growing new-c circles))
c))))
(defn create-circle [tries others]
(let [x (q/random 0.5 99.5)
y (q/random 0.5 99.5)
new-c {:x x :y y :r 0.03 :stroke 1/5 :growing true :max-r (q/random 10 20)}]
(cond
(> tries 2000) nil
(not-any? #(collide? new-c %) others) new-c
:else (recur (inc tries) others))))
(defn create-circles []
(loop [circles []]
(let [c (some-> (create-circle 0 circles)
(update-growing circles)
(grow-circle circles))]
(if c
(recur (conj circles c))
circles))))
(defn setup []
(q/ellipse-mode :radius)
(q/color-mode :hsb 360 100 100 1.0)
(q/no-loop))
(defn draw []
(q/background 45 10 100)
(let [circles (create-circles)]
(doseq [{:keys [x y r stroke]} circles]
(q/stroke-weight (w stroke))
(q/no-fill)
(q/ellipse (w x) (h y) (w r) (h r))
(q/point (w x) (h y)))))
(q/defsketch circle-packing
:title "Circle packing"
:size [2000 2000]
:setup setup
:draw draw
:features [])
| |
5f4a7b5823c4922d9d5cc218d0e59932d491a119fa188f03d985827ca9ad0c65 | brendanhay/terrafomo | Resources.hs | -- This module is auto-generated.
# LANGUAGE NoImplicitPrelude #
# LANGUAGE RecordWildCards #
# LANGUAGE StrictData #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -fno - warn - unused - imports #
-- |
Module : . Gitlab . Resources
Copyright : ( c ) 2017 - 2018
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
module Terrafomo.Gitlab.Resources
(
-- * gitlab_deploy_key
newDeployKeyR
, DeployKeyR (..)
, DeployKeyR_Required (..)
-- * gitlab_group
, newGroupR
, GroupR (..)
, GroupR_Required (..)
-- * gitlab_label
, newLabelR
, LabelR (..)
, LabelR_Required (..)
-- * gitlab_project_hook
, newProjectHookR
, ProjectHookR (..)
, ProjectHookR_Required (..)
-- * gitlab_project_membership
, newProjectMembershipR
, ProjectMembershipR (..)
-- * gitlab_project
, newProjectR
, ProjectR (..)
, ProjectR_Required (..)
-- * gitlab_user
, newUserR
, UserR (..)
, UserR_Required (..)
) where
import Data.Functor ((<$>))
import Data.Semigroup ((<>))
import GHC.Base (Proxy#, proxy#, ($))
import qualified Data.Functor.Const as P
import qualified Data.List.NonEmpty as P
import qualified Data.Map.Strict as P
import qualified Data.Maybe as P
import qualified Data.Text.Lazy as P
import qualified Prelude as P
import qualified Terrafomo.Encode as Encode
import qualified Terrafomo.Gitlab.Provider as P
import qualified Terrafomo.Gitlab.Types as P
import qualified Terrafomo.HCL as TF
import qualified Terrafomo.HIL as TF
import qualified Terrafomo.Lens as Lens
import qualified Terrafomo.Schema as TF
-- | The main @gitlab_deploy_key@ resource definition.
data DeployKeyR s = DeployKeyR_Internal
{ can_push :: TF.Expr s P.Bool
-- ^ @can_push@
-- - (Default __@false@__, Forces New)
, key :: TF.Expr s P.Text
-- ^ @key@
-- - (Required, Forces New)
, project :: TF.Expr s P.Text
-- ^ @project@
-- - (Required, Forces New)
, title :: TF.Expr s P.Text
-- ^ @title@
-- - (Required, Forces New)
} deriving (P.Show)
| Construct a new @gitlab_deploy_key@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @gitlab_deploy_key@ via :
@
Gitlab.newDeployKeyR
( Gitlab . DeployKeyR
{ = key -- Expr s Text
, Gitlab.project = project -- Expr s Text
, = title -- s Text
} )
@
= = = Argument Reference
The following arguments are supported :
@
# can_push : : ' ( Resource DeployKeyR s ) ( s Bool )
# key : : ' ( Resource DeployKeyR s ) ( Expr s Text )
# project : : ' ( Resource DeployKeyR s ) ( Expr s Text )
# title : : Lens ' ( Resource DeployKeyR s ) ( Expr s Text )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref DeployKeyR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource DeployKeyR s ) Bool
# create_before_destroy : : ' ( Resource DeployKeyR s ) Bool
# ignore_changes : : ' ( Resource DeployKeyR s ) ( Changes s )
# depends_on : : ' ( Resource DeployKeyR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource DeployKeyR s ) ( Maybe Gitlab )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @gitlab_deploy_key@ via:
@
Gitlab.newDeployKeyR
(Gitlab.DeployKeyR
{ Gitlab.key = key -- Expr s Text
, Gitlab.project = project -- Expr s Text
, Gitlab.title = title -- Expr s Text
})
@
=== Argument Reference
The following arguments are supported:
@
#can_push :: Lens' (Resource DeployKeyR s) (Expr s Bool)
#key :: Lens' (Resource DeployKeyR s) (Expr s Text)
#project :: Lens' (Resource DeployKeyR s) (Expr s Text)
#title :: Lens' (Resource DeployKeyR s) (Expr s Text)
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref DeployKeyR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource DeployKeyR s) Bool
#create_before_destroy :: Lens' (Resource DeployKeyR s) Bool
#ignore_changes :: Lens' (Resource DeployKeyR s) (Changes s)
#depends_on :: Lens' (Resource DeployKeyR s) (Set (Depends s))
#provider :: Lens' (Resource DeployKeyR s) (Maybe Gitlab)
@
-}
newDeployKeyR
:: DeployKeyR_Required s -- ^ The minimal/required arguments.
-> P.Resource DeployKeyR s
newDeployKeyR x =
TF.unsafeResource "gitlab_deploy_key" Encode.metadata
(\DeployKeyR_Internal{..} ->
P.mempty
<> TF.pair "can_push" can_push
<> TF.pair "key" key
<> TF.pair "project" project
<> TF.pair "title" title
)
(let DeployKeyR{..} = x in DeployKeyR_Internal
{ can_push = TF.expr P.False
, key = key
, project = project
, title = title
})
| The required arguments for ' ' .
data DeployKeyR_Required s = DeployKeyR
{ key :: TF.Expr s P.Text
^ ( Required , Forces New )
, project :: TF.Expr s P.Text
^ ( Required , Forces New )
, title :: TF.Expr s P.Text
^ ( Required , Forces New )
} deriving (P.Show)
instance Lens.HasField "can_push" f (P.Resource DeployKeyR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(can_push :: DeployKeyR s -> TF.Expr s P.Bool)
(\s a -> s { can_push = a } :: DeployKeyR s)
instance Lens.HasField "key" f (P.Resource DeployKeyR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(key :: DeployKeyR s -> TF.Expr s P.Text)
(\s a -> s { key = a } :: DeployKeyR s)
instance Lens.HasField "project" f (P.Resource DeployKeyR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(project :: DeployKeyR s -> TF.Expr s P.Text)
(\s a -> s { project = a } :: DeployKeyR s)
instance Lens.HasField "title" f (P.Resource DeployKeyR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(title :: DeployKeyR s -> TF.Expr s P.Text)
(\s a -> s { title = a } :: DeployKeyR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref DeployKeyR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
-- | The main @gitlab_group@ resource definition.
data GroupR s = GroupR_Internal
{ description :: P.Maybe (TF.Expr s P.Text)
-- ^ @description@
-- - (Optional)
, lfs_enabled :: TF.Expr s P.Bool
-- ^ @lfs_enabled@
-- - (Default __@true@__)
, name :: TF.Expr s P.Text
-- ^ @name@
-- - (Required)
, parent_id :: TF.Expr s P.Int
-- ^ @parent_id@
-- - (Default __@0@__, Forces New)
, path :: TF.Expr s P.Text
-- ^ @path@
-- - (Required)
, request_access_enabled :: TF.Expr s P.Bool
-- ^ @request_access_enabled@
-- - (Default __@false@__)
, visibility_level :: P.Maybe (TF.Expr s P.Text)
-- ^ @visibility_level@
-- - (Optional)
} deriving (P.Show)
| Construct a new @gitlab_group@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @gitlab_group@ via :
@
Gitlab.newGroupR
( Gitlab . GroupR
{ Gitlab.name = name -- s Text
, Gitlab.path = path -- s Text
} )
@
= = = Argument Reference
The following arguments are supported :
@
# description : : ' ( Resource GroupR s ) ( Maybe ( s Text ) )
# lfs_enabled : : ' ( Resource GroupR s ) ( s Bool )
# name : : ' ( Resource GroupR s ) ( Expr s Text )
# parent_id : : ' ( Resource GroupR s ) ( s Int )
# path : : ' ( Resource GroupR s ) ( Expr s Text )
# request_access_enabled : : ' ( Resource GroupR s ) ( s Bool )
# visibility_level : : ' ( Resource GroupR s ) ( Maybe ( s Text ) )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref GroupR s ) ( s I d )
# visibility_level : : Getting r ( Ref GroupR s ) ( Expr s Text )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource GroupR s ) Bool
# create_before_destroy : : ' ( Resource GroupR s ) Bool
# ignore_changes : : ' ( Resource GroupR s ) ( Changes s )
# depends_on : : ' ( Resource GroupR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource GroupR s ) ( Maybe Gitlab )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @gitlab_group@ via:
@
Gitlab.newGroupR
(Gitlab.GroupR
{ Gitlab.name = name -- Expr s Text
, Gitlab.path = path -- Expr s Text
})
@
=== Argument Reference
The following arguments are supported:
@
#description :: Lens' (Resource GroupR s) (Maybe (Expr s Text))
#lfs_enabled :: Lens' (Resource GroupR s) (Expr s Bool)
#name :: Lens' (Resource GroupR s) (Expr s Text)
#parent_id :: Lens' (Resource GroupR s) (Expr s Int)
#path :: Lens' (Resource GroupR s) (Expr s Text)
#request_access_enabled :: Lens' (Resource GroupR s) (Expr s Bool)
#visibility_level :: Lens' (Resource GroupR s) (Maybe (Expr s Text))
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref GroupR s) (Expr s Id)
#visibility_level :: Getting r (Ref GroupR s) (Expr s Text)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource GroupR s) Bool
#create_before_destroy :: Lens' (Resource GroupR s) Bool
#ignore_changes :: Lens' (Resource GroupR s) (Changes s)
#depends_on :: Lens' (Resource GroupR s) (Set (Depends s))
#provider :: Lens' (Resource GroupR s) (Maybe Gitlab)
@
-}
newGroupR
:: GroupR_Required s -- ^ The minimal/required arguments.
-> P.Resource GroupR s
newGroupR x =
TF.unsafeResource "gitlab_group" Encode.metadata
(\GroupR_Internal{..} ->
P.mempty
<> P.maybe P.mempty (TF.pair "description") description
<> TF.pair "lfs_enabled" lfs_enabled
<> TF.pair "name" name
<> TF.pair "parent_id" parent_id
<> TF.pair "path" path
<> TF.pair "request_access_enabled" request_access_enabled
<> P.maybe P.mempty (TF.pair "visibility_level") visibility_level
)
(let GroupR{..} = x in GroupR_Internal
{ description = P.Nothing
, lfs_enabled = TF.expr P.True
, name = name
, parent_id = TF.expr 0
, path = path
, request_access_enabled = TF.expr P.False
, visibility_level = P.Nothing
})
-- | The required arguments for 'newGroupR'.
data GroupR_Required s = GroupR
{ name :: TF.Expr s P.Text
-- ^ (Required)
, path :: TF.Expr s P.Text
-- ^ (Required)
} deriving (P.Show)
instance Lens.HasField "description" f (P.Resource GroupR s) (P.Maybe (TF.Expr s P.Text)) where
field = Lens.resourceLens P.. Lens.lens'
(description :: GroupR s -> P.Maybe (TF.Expr s P.Text))
(\s a -> s { description = a } :: GroupR s)
instance Lens.HasField "lfs_enabled" f (P.Resource GroupR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(lfs_enabled :: GroupR s -> TF.Expr s P.Bool)
(\s a -> s { lfs_enabled = a } :: GroupR s)
instance Lens.HasField "name" f (P.Resource GroupR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(name :: GroupR s -> TF.Expr s P.Text)
(\s a -> s { name = a } :: GroupR s)
instance Lens.HasField "parent_id" f (P.Resource GroupR s) (TF.Expr s P.Int) where
field = Lens.resourceLens P.. Lens.lens'
(parent_id :: GroupR s -> TF.Expr s P.Int)
(\s a -> s { parent_id = a } :: GroupR s)
instance Lens.HasField "path" f (P.Resource GroupR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(path :: GroupR s -> TF.Expr s P.Text)
(\s a -> s { path = a } :: GroupR s)
instance Lens.HasField "request_access_enabled" f (P.Resource GroupR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(request_access_enabled :: GroupR s -> TF.Expr s P.Bool)
(\s a -> s { request_access_enabled = a } :: GroupR s)
instance Lens.HasField "visibility_level" f (P.Resource GroupR s) (P.Maybe (TF.Expr s P.Text)) where
field = Lens.resourceLens P.. Lens.lens'
(visibility_level :: GroupR s -> P.Maybe (TF.Expr s P.Text))
(\s a -> s { visibility_level = a } :: GroupR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref GroupR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
instance Lens.HasField "visibility_level" (P.Const r) (TF.Ref GroupR s) (TF.Expr s P.Text) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "visibility_level"))
-- | The main @gitlab_label@ resource definition.
data LabelR s = LabelR_Internal
{ color :: TF.Expr s P.Text
-- ^ @color@
-- - (Required)
, description :: P.Maybe (TF.Expr s P.Text)
-- ^ @description@
-- - (Optional)
, name :: TF.Expr s P.Text
-- ^ @name@
-- - (Required, Forces New)
, project :: TF.Expr s P.Text
-- ^ @project@
-- - (Required)
} deriving (P.Show)
| Construct a new @gitlab_label@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @gitlab_label@ via :
@
( Gitlab .
{ Gitlab.color = color -- Expr s Text
, Gitlab.name = name -- s Text
, Gitlab.project = project -- Expr s Text
} )
@
= = = Argument Reference
The following arguments are supported :
@
# color : : Lens ' ( Resource LabelR s ) ( Expr s Text )
# description : : ' ( Resource LabelR s ) ( Maybe ( s Text ) )
# name : : ' ( Resource LabelR s ) ( Expr s Text )
# project : : ' ( Resource LabelR s ) ( Expr s Text )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref LabelR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource LabelR s ) Bool
# create_before_destroy : : ' ( Resource LabelR s ) Bool
# ignore_changes : : ' ( Resource LabelR s ) ( Changes s )
# depends_on : : ' ( Resource LabelR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource LabelR s ) ( Maybe Gitlab )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @gitlab_label@ via:
@
Gitlab.newLabelR
(Gitlab.LabelR
{ Gitlab.color = color -- Expr s Text
, Gitlab.name = name -- Expr s Text
, Gitlab.project = project -- Expr s Text
})
@
=== Argument Reference
The following arguments are supported:
@
#color :: Lens' (Resource LabelR s) (Expr s Text)
#description :: Lens' (Resource LabelR s) (Maybe (Expr s Text))
#name :: Lens' (Resource LabelR s) (Expr s Text)
#project :: Lens' (Resource LabelR s) (Expr s Text)
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref LabelR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource LabelR s) Bool
#create_before_destroy :: Lens' (Resource LabelR s) Bool
#ignore_changes :: Lens' (Resource LabelR s) (Changes s)
#depends_on :: Lens' (Resource LabelR s) (Set (Depends s))
#provider :: Lens' (Resource LabelR s) (Maybe Gitlab)
@
-}
newLabelR
:: LabelR_Required s -- ^ The minimal/required arguments.
-> P.Resource LabelR s
newLabelR x =
TF.unsafeResource "gitlab_label" Encode.metadata
(\LabelR_Internal{..} ->
P.mempty
<> TF.pair "color" color
<> P.maybe P.mempty (TF.pair "description") description
<> TF.pair "name" name
<> TF.pair "project" project
)
(let LabelR{..} = x in LabelR_Internal
{ color = color
, description = P.Nothing
, name = name
, project = project
})
| The required arguments for ' ' .
data LabelR_Required s = LabelR
{ color :: TF.Expr s P.Text
-- ^ (Required)
, name :: TF.Expr s P.Text
^ ( Required , Forces New )
, project :: TF.Expr s P.Text
-- ^ (Required)
} deriving (P.Show)
instance Lens.HasField "color" f (P.Resource LabelR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(color :: LabelR s -> TF.Expr s P.Text)
(\s a -> s { color = a } :: LabelR s)
instance Lens.HasField "description" f (P.Resource LabelR s) (P.Maybe (TF.Expr s P.Text)) where
field = Lens.resourceLens P.. Lens.lens'
(description :: LabelR s -> P.Maybe (TF.Expr s P.Text))
(\s a -> s { description = a } :: LabelR s)
instance Lens.HasField "name" f (P.Resource LabelR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(name :: LabelR s -> TF.Expr s P.Text)
(\s a -> s { name = a } :: LabelR s)
instance Lens.HasField "project" f (P.Resource LabelR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(project :: LabelR s -> TF.Expr s P.Text)
(\s a -> s { project = a } :: LabelR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref LabelR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
-- | The main @gitlab_project_hook@ resource definition.
data ProjectHookR s = ProjectHookR_Internal
{ enable_ssl_verification :: TF.Expr s P.Bool
-- ^ @enable_ssl_verification@
-- - (Default __@true@__)
, issues_events :: TF.Expr s P.Bool
-- ^ @issues_events@
-- - (Default __@false@__)
, job_events :: TF.Expr s P.Bool
-- ^ @job_events@
-- - (Default __@false@__)
, merge_requests_events :: TF.Expr s P.Bool
-- ^ @merge_requests_events@
-- - (Default __@false@__)
, note_events :: TF.Expr s P.Bool
-- ^ @note_events@
-- - (Default __@false@__)
, pipeline_events :: TF.Expr s P.Bool
-- ^ @pipeline_events@
-- - (Default __@false@__)
, project :: TF.Expr s P.Text
-- ^ @project@
-- - (Required)
, push_events :: TF.Expr s P.Bool
^ @push_events@
-- - (Default __@true@__)
, tag_push_events :: TF.Expr s P.Bool
-- ^ @tag_push_events@
-- - (Default __@false@__)
, token :: P.Maybe (TF.Expr s P.Text)
-- ^ @token@
-- - (Optional)
, url :: TF.Expr s P.Text
-- ^ @url@
-- - (Required)
, wiki_page_events :: TF.Expr s P.Bool
-- ^ @wiki_page_events@
-- - (Default __@false@__)
} deriving (P.Show)
| Construct a new @gitlab_project_hook@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @gitlab_project_hook@ via :
@
Gitlab.newProjectHookR
( Gitlab . ProjectHookR
{ Gitlab.project = project -- Expr s Text
, Gitlab.url = url -- Expr s Text
} )
@
= = = Argument Reference
The following arguments are supported :
@
# enable_ssl_verification : : ' ( Resource ProjectHookR s ) ( s Bool )
# issues_events : : ' ( Resource ProjectHookR s ) ( s Bool )
# job_events : : ' ( Resource ProjectHookR s ) ( s Bool )
# merge_requests_events : : ' ( Resource ProjectHookR s ) ( s Bool )
# : : ' ( Resource ProjectHookR s ) ( s Bool )
# pipeline_events : : Lens ' ( Resource ProjectHookR s ) ( s Bool )
# project : : ' ( Resource ProjectHookR s ) ( Expr s Text )
# push_events : : ' ( Resource ProjectHookR s ) ( s Bool )
# tag_push_events : : Lens ' ( Resource ProjectHookR s ) ( s Bool )
# token : : Lens ' ( Resource ProjectHookR s ) ( Maybe ( s Text ) )
# url : : ' ( Resource ProjectHookR s ) ( Expr s Text )
# wiki_page_events : : ' ( Resource ProjectHookR s ) ( s Bool )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref ProjectHookR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource ProjectHookR s ) Bool
# create_before_destroy : : ' ( Resource ProjectHookR s ) Bool
# ignore_changes : : ' ( Resource ProjectHookR s ) ( Changes s )
# depends_on : : ' ( Resource ProjectHookR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource ProjectHookR s ) ( Maybe Gitlab )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @gitlab_project_hook@ via:
@
Gitlab.newProjectHookR
(Gitlab.ProjectHookR
{ Gitlab.project = project -- Expr s Text
, Gitlab.url = url -- Expr s Text
})
@
=== Argument Reference
The following arguments are supported:
@
#enable_ssl_verification :: Lens' (Resource ProjectHookR s) (Expr s Bool)
#issues_events :: Lens' (Resource ProjectHookR s) (Expr s Bool)
#job_events :: Lens' (Resource ProjectHookR s) (Expr s Bool)
#merge_requests_events :: Lens' (Resource ProjectHookR s) (Expr s Bool)
#note_events :: Lens' (Resource ProjectHookR s) (Expr s Bool)
#pipeline_events :: Lens' (Resource ProjectHookR s) (Expr s Bool)
#project :: Lens' (Resource ProjectHookR s) (Expr s Text)
#push_events :: Lens' (Resource ProjectHookR s) (Expr s Bool)
#tag_push_events :: Lens' (Resource ProjectHookR s) (Expr s Bool)
#token :: Lens' (Resource ProjectHookR s) (Maybe (Expr s Text))
#url :: Lens' (Resource ProjectHookR s) (Expr s Text)
#wiki_page_events :: Lens' (Resource ProjectHookR s) (Expr s Bool)
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref ProjectHookR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource ProjectHookR s) Bool
#create_before_destroy :: Lens' (Resource ProjectHookR s) Bool
#ignore_changes :: Lens' (Resource ProjectHookR s) (Changes s)
#depends_on :: Lens' (Resource ProjectHookR s) (Set (Depends s))
#provider :: Lens' (Resource ProjectHookR s) (Maybe Gitlab)
@
-}
newProjectHookR
:: ProjectHookR_Required s -- ^ The minimal/required arguments.
-> P.Resource ProjectHookR s
newProjectHookR x =
TF.unsafeResource "gitlab_project_hook" Encode.metadata
(\ProjectHookR_Internal{..} ->
P.mempty
<> TF.pair "enable_ssl_verification" enable_ssl_verification
<> TF.pair "issues_events" issues_events
<> TF.pair "job_events" job_events
<> TF.pair "merge_requests_events" merge_requests_events
<> TF.pair "note_events" note_events
<> TF.pair "pipeline_events" pipeline_events
<> TF.pair "project" project
<> TF.pair "push_events" push_events
<> TF.pair "tag_push_events" tag_push_events
<> P.maybe P.mempty (TF.pair "token") token
<> TF.pair "url" url
<> TF.pair "wiki_page_events" wiki_page_events
)
(let ProjectHookR{..} = x in ProjectHookR_Internal
{ enable_ssl_verification = TF.expr P.True
, issues_events = TF.expr P.False
, job_events = TF.expr P.False
, merge_requests_events = TF.expr P.False
, note_events = TF.expr P.False
, pipeline_events = TF.expr P.False
, project = project
, push_events = TF.expr P.True
, tag_push_events = TF.expr P.False
, token = P.Nothing
, url = url
, wiki_page_events = TF.expr P.False
})
-- | The required arguments for 'newProjectHookR'.
data ProjectHookR_Required s = ProjectHookR
{ project :: TF.Expr s P.Text
-- ^ (Required)
, url :: TF.Expr s P.Text
-- ^ (Required)
} deriving (P.Show)
instance Lens.HasField "enable_ssl_verification" f (P.Resource ProjectHookR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(enable_ssl_verification :: ProjectHookR s -> TF.Expr s P.Bool)
(\s a -> s { enable_ssl_verification = a } :: ProjectHookR s)
instance Lens.HasField "issues_events" f (P.Resource ProjectHookR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(issues_events :: ProjectHookR s -> TF.Expr s P.Bool)
(\s a -> s { issues_events = a } :: ProjectHookR s)
instance Lens.HasField "job_events" f (P.Resource ProjectHookR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(job_events :: ProjectHookR s -> TF.Expr s P.Bool)
(\s a -> s { job_events = a } :: ProjectHookR s)
instance Lens.HasField "merge_requests_events" f (P.Resource ProjectHookR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(merge_requests_events :: ProjectHookR s -> TF.Expr s P.Bool)
(\s a -> s { merge_requests_events = a } :: ProjectHookR s)
instance Lens.HasField "note_events" f (P.Resource ProjectHookR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(note_events :: ProjectHookR s -> TF.Expr s P.Bool)
(\s a -> s { note_events = a } :: ProjectHookR s)
instance Lens.HasField "pipeline_events" f (P.Resource ProjectHookR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(pipeline_events :: ProjectHookR s -> TF.Expr s P.Bool)
(\s a -> s { pipeline_events = a } :: ProjectHookR s)
instance Lens.HasField "project" f (P.Resource ProjectHookR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(project :: ProjectHookR s -> TF.Expr s P.Text)
(\s a -> s { project = a } :: ProjectHookR s)
instance Lens.HasField "push_events" f (P.Resource ProjectHookR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(push_events :: ProjectHookR s -> TF.Expr s P.Bool)
(\s a -> s { push_events = a } :: ProjectHookR s)
instance Lens.HasField "tag_push_events" f (P.Resource ProjectHookR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(tag_push_events :: ProjectHookR s -> TF.Expr s P.Bool)
(\s a -> s { tag_push_events = a } :: ProjectHookR s)
instance Lens.HasField "token" f (P.Resource ProjectHookR s) (P.Maybe (TF.Expr s P.Text)) where
field = Lens.resourceLens P.. Lens.lens'
(token :: ProjectHookR s -> P.Maybe (TF.Expr s P.Text))
(\s a -> s { token = a } :: ProjectHookR s)
instance Lens.HasField "url" f (P.Resource ProjectHookR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(url :: ProjectHookR s -> TF.Expr s P.Text)
(\s a -> s { url = a } :: ProjectHookR s)
instance Lens.HasField "wiki_page_events" f (P.Resource ProjectHookR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(wiki_page_events :: ProjectHookR s -> TF.Expr s P.Bool)
(\s a -> s { wiki_page_events = a } :: ProjectHookR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref ProjectHookR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
-- | The main @gitlab_project_membership@ resource definition.
data ProjectMembershipR s = ProjectMembershipR
{ access_level :: TF.Expr s P.Text
-- ^ @access_level@
-- - (Required)
, project_id :: TF.Expr s TF.Id
-- ^ @project_id@
-- - (Required, Forces New)
, user_id :: TF.Expr s P.Int
-- ^ @user_id@
-- - (Required, Forces New)
} deriving (P.Show)
| Construct a new @gitlab_project_membership@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @gitlab_project_membership@ via :
@
Gitlab.newProjectMembershipR
( Gitlab . ProjectMembershipR
{ Gitlab.project_id = project_id -- Expr s I d
, Gitlab.user_id = user_id -- Expr s Int
, Gitlab.access_level = access_level -- s Text
} )
@
= = = Argument Reference
The following arguments are supported :
@
# access_level : : ' ( Resource ProjectMembershipR s ) ( Expr s Text )
# project_id : : ' ( Resource ProjectMembershipR s ) ( s I d )
# user_id : : ' ( Resource ProjectMembershipR s ) ( s Int )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref ProjectMembershipR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource ProjectMembershipR s ) Bool
# create_before_destroy : : ' ( Resource ProjectMembershipR s ) Bool
# ignore_changes : : ' ( Resource ProjectMembershipR s ) ( Changes s )
# depends_on : : ' ( Resource ProjectMembershipR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource ProjectMembershipR s ) ( Maybe Gitlab )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @gitlab_project_membership@ via:
@
Gitlab.newProjectMembershipR
(Gitlab.ProjectMembershipR
{ Gitlab.project_id = project_id -- Expr s Id
, Gitlab.user_id = user_id -- Expr s Int
, Gitlab.access_level = access_level -- Expr s Text
})
@
=== Argument Reference
The following arguments are supported:
@
#access_level :: Lens' (Resource ProjectMembershipR s) (Expr s Text)
#project_id :: Lens' (Resource ProjectMembershipR s) (Expr s Id)
#user_id :: Lens' (Resource ProjectMembershipR s) (Expr s Int)
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref ProjectMembershipR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource ProjectMembershipR s) Bool
#create_before_destroy :: Lens' (Resource ProjectMembershipR s) Bool
#ignore_changes :: Lens' (Resource ProjectMembershipR s) (Changes s)
#depends_on :: Lens' (Resource ProjectMembershipR s) (Set (Depends s))
#provider :: Lens' (Resource ProjectMembershipR s) (Maybe Gitlab)
@
-}
newProjectMembershipR
:: ProjectMembershipR s -- ^ The minimal/required arguments.
-> P.Resource ProjectMembershipR s
newProjectMembershipR =
TF.unsafeResource "gitlab_project_membership" Encode.metadata
(\ProjectMembershipR{..} ->
P.mempty
<> TF.pair "access_level" access_level
<> TF.pair "project_id" project_id
<> TF.pair "user_id" user_id
)
instance Lens.HasField "access_level" f (P.Resource ProjectMembershipR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(access_level :: ProjectMembershipR s -> TF.Expr s P.Text)
(\s a -> s { access_level = a } :: ProjectMembershipR s)
instance Lens.HasField "project_id" f (P.Resource ProjectMembershipR s) (TF.Expr s TF.Id) where
field = Lens.resourceLens P.. Lens.lens'
(project_id :: ProjectMembershipR s -> TF.Expr s TF.Id)
(\s a -> s { project_id = a } :: ProjectMembershipR s)
instance Lens.HasField "user_id" f (P.Resource ProjectMembershipR s) (TF.Expr s P.Int) where
field = Lens.resourceLens P.. Lens.lens'
(user_id :: ProjectMembershipR s -> TF.Expr s P.Int)
(\s a -> s { user_id = a } :: ProjectMembershipR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref ProjectMembershipR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
-- | The main @gitlab_project@ resource definition.
data ProjectR s = ProjectR_Internal
{ default_branch :: P.Maybe (TF.Expr s P.Text)
^ @default_branch@
-- - (Optional)
, description :: P.Maybe (TF.Expr s P.Text)
-- ^ @description@
-- - (Optional)
, issues_enabled :: TF.Expr s P.Bool
^ @issues_enabled@
-- - (Default __@true@__)
, merge_requests_enabled :: TF.Expr s P.Bool
^ @merge_requests_enabled@
-- - (Default __@true@__)
, name :: TF.Expr s P.Text
-- ^ @name@
-- - (Required)
, namespace_id :: P.Maybe (TF.Expr s P.Int)
-- ^ @namespace_id@
-- - (Optional, Forces New)
, path :: P.Maybe (TF.Expr s P.Text)
-- ^ @path@
-- - (Optional)
, snippets_enabled :: TF.Expr s P.Bool
-- ^ @snippets_enabled@
-- - (Default __@true@__)
, visibility_level :: TF.Expr s P.Text
-- ^ @visibility_level@
-- - (Default __@private@__)
, wiki_enabled :: TF.Expr s P.Bool
-- ^ @wiki_enabled@
-- - (Default __@true@__)
} deriving (P.Show)
| Construct a new @gitlab_project@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @gitlab_project@ via :
@
Gitlab.newProjectR
( Gitlab . ProjectR
{ Gitlab.name = name -- s Text
} )
@
= = = Argument Reference
The following arguments are supported :
@
# default_branch : : ' ( Resource ProjectR s ) ( Maybe ( s Text ) )
# description : : ' ( Resource ProjectR s ) ( Maybe ( s Text ) )
# issues_enabled : : ' ( Resource ProjectR s ) ( s Bool )
# merge_requests_enabled : : ' ( Resource ProjectR s ) ( s Bool )
# name : : ' ( Resource ProjectR s ) ( Expr s Text )
# namespace_id : : ' ( Resource ProjectR s ) ( Maybe ( s Int ) )
# path : : ' ( Resource ProjectR s ) ( Maybe ( s Text ) )
# snippets_enabled : : ' ( Resource ProjectR s ) ( s Bool )
# visibility_level : : ' ( Resource ProjectR s ) ( Expr s Text )
# wiki_enabled : : ' ( Resource ProjectR s ) ( s Bool )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref ProjectR s ) ( s I d )
# http_url_to_repo : : Getting r ( Ref ProjectR s ) ( Expr s Text )
# namespace_id : : Getting r ( Ref ProjectR s ) ( s Int )
# ssh_url_to_repo : : Getting r ( Ref ProjectR s ) ( Expr s Text )
# web_url : : Getting r ( Ref ProjectR s ) ( Expr s Text )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource ProjectR s ) Bool
# create_before_destroy : : ' ( Resource ProjectR s ) Bool
# ignore_changes : : ' ( Resource ProjectR s ) ( Changes s )
# depends_on : : ' ( Resource ProjectR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource ProjectR s ) ( Maybe Gitlab )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @gitlab_project@ via:
@
Gitlab.newProjectR
(Gitlab.ProjectR
{ Gitlab.name = name -- Expr s Text
})
@
=== Argument Reference
The following arguments are supported:
@
#default_branch :: Lens' (Resource ProjectR s) (Maybe (Expr s Text))
#description :: Lens' (Resource ProjectR s) (Maybe (Expr s Text))
#issues_enabled :: Lens' (Resource ProjectR s) (Expr s Bool)
#merge_requests_enabled :: Lens' (Resource ProjectR s) (Expr s Bool)
#name :: Lens' (Resource ProjectR s) (Expr s Text)
#namespace_id :: Lens' (Resource ProjectR s) (Maybe (Expr s Int))
#path :: Lens' (Resource ProjectR s) (Maybe (Expr s Text))
#snippets_enabled :: Lens' (Resource ProjectR s) (Expr s Bool)
#visibility_level :: Lens' (Resource ProjectR s) (Expr s Text)
#wiki_enabled :: Lens' (Resource ProjectR s) (Expr s Bool)
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref ProjectR s) (Expr s Id)
#http_url_to_repo :: Getting r (Ref ProjectR s) (Expr s Text)
#namespace_id :: Getting r (Ref ProjectR s) (Expr s Int)
#ssh_url_to_repo :: Getting r (Ref ProjectR s) (Expr s Text)
#web_url :: Getting r (Ref ProjectR s) (Expr s Text)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource ProjectR s) Bool
#create_before_destroy :: Lens' (Resource ProjectR s) Bool
#ignore_changes :: Lens' (Resource ProjectR s) (Changes s)
#depends_on :: Lens' (Resource ProjectR s) (Set (Depends s))
#provider :: Lens' (Resource ProjectR s) (Maybe Gitlab)
@
-}
newProjectR
:: ProjectR_Required s -- ^ The minimal/required arguments.
-> P.Resource ProjectR s
newProjectR x =
TF.unsafeResource "gitlab_project" Encode.metadata
(\ProjectR_Internal{..} ->
P.mempty
<> P.maybe P.mempty (TF.pair "default_branch") default_branch
<> P.maybe P.mempty (TF.pair "description") description
<> TF.pair "issues_enabled" issues_enabled
<> TF.pair "merge_requests_enabled" merge_requests_enabled
<> TF.pair "name" name
<> P.maybe P.mempty (TF.pair "namespace_id") namespace_id
<> P.maybe P.mempty (TF.pair "path") path
<> TF.pair "snippets_enabled" snippets_enabled
<> TF.pair "visibility_level" visibility_level
<> TF.pair "wiki_enabled" wiki_enabled
)
(let ProjectR{..} = x in ProjectR_Internal
{ default_branch = P.Nothing
, description = P.Nothing
, issues_enabled = TF.expr P.True
, merge_requests_enabled = TF.expr P.True
, name = name
, namespace_id = P.Nothing
, path = P.Nothing
, snippets_enabled = TF.expr P.True
, visibility_level = TF.expr "private"
, wiki_enabled = TF.expr P.True
})
-- | The required arguments for 'newProjectR'.
data ProjectR_Required s = ProjectR
{ name :: TF.Expr s P.Text
-- ^ (Required)
} deriving (P.Show)
instance Lens.HasField "default_branch" f (P.Resource ProjectR s) (P.Maybe (TF.Expr s P.Text)) where
field = Lens.resourceLens P.. Lens.lens'
(default_branch :: ProjectR s -> P.Maybe (TF.Expr s P.Text))
(\s a -> s { default_branch = a } :: ProjectR s)
instance Lens.HasField "description" f (P.Resource ProjectR s) (P.Maybe (TF.Expr s P.Text)) where
field = Lens.resourceLens P.. Lens.lens'
(description :: ProjectR s -> P.Maybe (TF.Expr s P.Text))
(\s a -> s { description = a } :: ProjectR s)
instance Lens.HasField "issues_enabled" f (P.Resource ProjectR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(issues_enabled :: ProjectR s -> TF.Expr s P.Bool)
(\s a -> s { issues_enabled = a } :: ProjectR s)
instance Lens.HasField "merge_requests_enabled" f (P.Resource ProjectR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(merge_requests_enabled :: ProjectR s -> TF.Expr s P.Bool)
(\s a -> s { merge_requests_enabled = a } :: ProjectR s)
instance Lens.HasField "name" f (P.Resource ProjectR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(name :: ProjectR s -> TF.Expr s P.Text)
(\s a -> s { name = a } :: ProjectR s)
instance Lens.HasField "namespace_id" f (P.Resource ProjectR s) (P.Maybe (TF.Expr s P.Int)) where
field = Lens.resourceLens P.. Lens.lens'
(namespace_id :: ProjectR s -> P.Maybe (TF.Expr s P.Int))
(\s a -> s { namespace_id = a } :: ProjectR s)
instance Lens.HasField "path" f (P.Resource ProjectR s) (P.Maybe (TF.Expr s P.Text)) where
field = Lens.resourceLens P.. Lens.lens'
(path :: ProjectR s -> P.Maybe (TF.Expr s P.Text))
(\s a -> s { path = a } :: ProjectR s)
instance Lens.HasField "snippets_enabled" f (P.Resource ProjectR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(snippets_enabled :: ProjectR s -> TF.Expr s P.Bool)
(\s a -> s { snippets_enabled = a } :: ProjectR s)
instance Lens.HasField "visibility_level" f (P.Resource ProjectR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(visibility_level :: ProjectR s -> TF.Expr s P.Text)
(\s a -> s { visibility_level = a } :: ProjectR s)
instance Lens.HasField "wiki_enabled" f (P.Resource ProjectR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(wiki_enabled :: ProjectR s -> TF.Expr s P.Bool)
(\s a -> s { wiki_enabled = a } :: ProjectR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref ProjectR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
instance Lens.HasField "http_url_to_repo" (P.Const r) (TF.Ref ProjectR s) (TF.Expr s P.Text) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "http_url_to_repo"))
instance Lens.HasField "namespace_id" (P.Const r) (TF.Ref ProjectR s) (TF.Expr s P.Int) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "namespace_id"))
instance Lens.HasField "ssh_url_to_repo" (P.Const r) (TF.Ref ProjectR s) (TF.Expr s P.Text) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "ssh_url_to_repo"))
instance Lens.HasField "web_url" (P.Const r) (TF.Ref ProjectR s) (TF.Expr s P.Text) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "web_url"))
| The main @gitlab_user@ resource definition .
data UserR s = UserR_Internal
{ can_create_group :: TF.Expr s P.Bool
-- ^ @can_create_group@
-- - (Default __@false@__)
, email :: TF.Expr s P.Text
-- ^ @email@
-- - (Required, Forces New)
, is_admin :: TF.Expr s P.Bool
-- ^ @is_admin@
-- - (Default __@false@__)
, is_external :: TF.Expr s P.Bool
-- ^ @is_external@
-- - (Default __@false@__)
, name :: TF.Expr s P.Text
-- ^ @name@
-- - (Required)
, password :: TF.Expr s P.Text
-- ^ @password@
-- - (Required)
, projects_limit :: TF.Expr s P.Int
-- ^ @projects_limit@
-- - (Default __@0@__)
, skip_confirmation :: TF.Expr s P.Bool
-- ^ @skip_confirmation@
-- - (Default __@true@__)
, username :: TF.Expr s P.Text
-- ^ @username@
-- - (Required)
} deriving (P.Show)
| Construct a new @gitlab_user@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @gitlab_user@ via :
@
( Gitlab . UserR
email -- s Text
, Gitlab.name = name -- s Text
, Gitlab.password = password -- Expr s Text
, Gitlab.username = username -- s Text
} )
@
= = = Argument Reference
The following arguments are supported :
@
# can_create_group : : ' ( Resource UserR s ) ( s Bool )
# email : : Lens ' ( Resource UserR s ) ( Expr s Text )
# is_admin : : ' ( Resource UserR s ) ( s Bool )
# is_external : : ' ( Resource UserR s ) ( s Bool )
# name : : ' ( Resource UserR s ) ( Expr s Text )
# password : : ' ( Resource UserR s ) ( Expr s Text )
# projects_limit : : ' ( Resource UserR s ) ( s Int )
# skip_confirmation : : Lens ' ( Resource UserR s ) ( s Bool )
# username : : ' ( Resource UserR s ) ( Expr s Text )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref UserR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource UserR s ) Bool
# create_before_destroy : : ' ( Resource UserR s ) Bool
# ignore_changes : : ' ( Resource UserR s ) ( Changes s )
# depends_on : : ' ( Resource UserR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource UserR s ) ( Maybe Gitlab )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @gitlab_user@ via:
@
Gitlab.newUserR
(Gitlab.UserR
{ Gitlab.email = email -- Expr s Text
, Gitlab.name = name -- Expr s Text
, Gitlab.password = password -- Expr s Text
, Gitlab.username = username -- Expr s Text
})
@
=== Argument Reference
The following arguments are supported:
@
#can_create_group :: Lens' (Resource UserR s) (Expr s Bool)
#email :: Lens' (Resource UserR s) (Expr s Text)
#is_admin :: Lens' (Resource UserR s) (Expr s Bool)
#is_external :: Lens' (Resource UserR s) (Expr s Bool)
#name :: Lens' (Resource UserR s) (Expr s Text)
#password :: Lens' (Resource UserR s) (Expr s Text)
#projects_limit :: Lens' (Resource UserR s) (Expr s Int)
#skip_confirmation :: Lens' (Resource UserR s) (Expr s Bool)
#username :: Lens' (Resource UserR s) (Expr s Text)
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref UserR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource UserR s) Bool
#create_before_destroy :: Lens' (Resource UserR s) Bool
#ignore_changes :: Lens' (Resource UserR s) (Changes s)
#depends_on :: Lens' (Resource UserR s) (Set (Depends s))
#provider :: Lens' (Resource UserR s) (Maybe Gitlab)
@
-}
newUserR
:: UserR_Required s -- ^ The minimal/required arguments.
-> P.Resource UserR s
newUserR x =
TF.unsafeResource "gitlab_user" Encode.metadata
(\UserR_Internal{..} ->
P.mempty
<> TF.pair "can_create_group" can_create_group
<> TF.pair "email" email
<> TF.pair "is_admin" is_admin
<> TF.pair "is_external" is_external
<> TF.pair "name" name
<> TF.pair "password" password
<> TF.pair "projects_limit" projects_limit
<> TF.pair "skip_confirmation" skip_confirmation
<> TF.pair "username" username
)
(let UserR{..} = x in UserR_Internal
{ can_create_group = TF.expr P.False
, email = email
, is_admin = TF.expr P.False
, is_external = TF.expr P.False
, name = name
, password = password
, projects_limit = TF.expr 0
, skip_confirmation = TF.expr P.True
, username = username
})
-- | The required arguments for 'newUserR'.
data UserR_Required s = UserR
{ email :: TF.Expr s P.Text
^ ( Required , Forces New )
, name :: TF.Expr s P.Text
-- ^ (Required)
, password :: TF.Expr s P.Text
-- ^ (Required)
, username :: TF.Expr s P.Text
-- ^ (Required)
} deriving (P.Show)
instance Lens.HasField "can_create_group" f (P.Resource UserR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(can_create_group :: UserR s -> TF.Expr s P.Bool)
(\s a -> s { can_create_group = a } :: UserR s)
instance Lens.HasField "email" f (P.Resource UserR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(email :: UserR s -> TF.Expr s P.Text)
(\s a -> s { email = a } :: UserR s)
instance Lens.HasField "is_admin" f (P.Resource UserR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(is_admin :: UserR s -> TF.Expr s P.Bool)
(\s a -> s { is_admin = a } :: UserR s)
instance Lens.HasField "is_external" f (P.Resource UserR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(is_external :: UserR s -> TF.Expr s P.Bool)
(\s a -> s { is_external = a } :: UserR s)
instance Lens.HasField "name" f (P.Resource UserR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(name :: UserR s -> TF.Expr s P.Text)
(\s a -> s { name = a } :: UserR s)
instance Lens.HasField "password" f (P.Resource UserR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(password :: UserR s -> TF.Expr s P.Text)
(\s a -> s { password = a } :: UserR s)
instance Lens.HasField "projects_limit" f (P.Resource UserR s) (TF.Expr s P.Int) where
field = Lens.resourceLens P.. Lens.lens'
(projects_limit :: UserR s -> TF.Expr s P.Int)
(\s a -> s { projects_limit = a } :: UserR s)
instance Lens.HasField "skip_confirmation" f (P.Resource UserR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(skip_confirmation :: UserR s -> TF.Expr s P.Bool)
(\s a -> s { skip_confirmation = a } :: UserR s)
instance Lens.HasField "username" f (P.Resource UserR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(username :: UserR s -> TF.Expr s P.Text)
(\s a -> s { username = a } :: UserR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref UserR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
| null | https://raw.githubusercontent.com/brendanhay/terrafomo/387a0e9341fb9cd5543ef8332dea126f50f1070e/provider/terrafomo-gitlab/gen/Terrafomo/Gitlab/Resources.hs | haskell | This module is auto-generated.
|
Stability : auto-generated
* gitlab_deploy_key
* gitlab_group
* gitlab_label
* gitlab_project_hook
* gitlab_project_membership
* gitlab_project
* gitlab_user
| The main @gitlab_deploy_key@ resource definition.
^ @can_push@
- (Default __@false@__, Forces New)
^ @key@
- (Required, Forces New)
^ @project@
- (Required, Forces New)
^ @title@
- (Required, Forces New)
Expr s Text
Expr s Text
s Text
Expr s Text
Expr s Text
Expr s Text
^ The minimal/required arguments.
| The main @gitlab_group@ resource definition.
^ @description@
- (Optional)
^ @lfs_enabled@
- (Default __@true@__)
^ @name@
- (Required)
^ @parent_id@
- (Default __@0@__, Forces New)
^ @path@
- (Required)
^ @request_access_enabled@
- (Default __@false@__)
^ @visibility_level@
- (Optional)
s Text
s Text
Expr s Text
Expr s Text
^ The minimal/required arguments.
| The required arguments for 'newGroupR'.
^ (Required)
^ (Required)
| The main @gitlab_label@ resource definition.
^ @color@
- (Required)
^ @description@
- (Optional)
^ @name@
- (Required, Forces New)
^ @project@
- (Required)
Expr s Text
s Text
Expr s Text
Expr s Text
Expr s Text
Expr s Text
^ The minimal/required arguments.
^ (Required)
^ (Required)
| The main @gitlab_project_hook@ resource definition.
^ @enable_ssl_verification@
- (Default __@true@__)
^ @issues_events@
- (Default __@false@__)
^ @job_events@
- (Default __@false@__)
^ @merge_requests_events@
- (Default __@false@__)
^ @note_events@
- (Default __@false@__)
^ @pipeline_events@
- (Default __@false@__)
^ @project@
- (Required)
- (Default __@true@__)
^ @tag_push_events@
- (Default __@false@__)
^ @token@
- (Optional)
^ @url@
- (Required)
^ @wiki_page_events@
- (Default __@false@__)
Expr s Text
Expr s Text
Expr s Text
Expr s Text
^ The minimal/required arguments.
| The required arguments for 'newProjectHookR'.
^ (Required)
^ (Required)
| The main @gitlab_project_membership@ resource definition.
^ @access_level@
- (Required)
^ @project_id@
- (Required, Forces New)
^ @user_id@
- (Required, Forces New)
Expr s I d
Expr s Int
s Text
Expr s Id
Expr s Int
Expr s Text
^ The minimal/required arguments.
| The main @gitlab_project@ resource definition.
- (Optional)
^ @description@
- (Optional)
- (Default __@true@__)
- (Default __@true@__)
^ @name@
- (Required)
^ @namespace_id@
- (Optional, Forces New)
^ @path@
- (Optional)
^ @snippets_enabled@
- (Default __@true@__)
^ @visibility_level@
- (Default __@private@__)
^ @wiki_enabled@
- (Default __@true@__)
s Text
Expr s Text
^ The minimal/required arguments.
| The required arguments for 'newProjectR'.
^ (Required)
^ @can_create_group@
- (Default __@false@__)
^ @email@
- (Required, Forces New)
^ @is_admin@
- (Default __@false@__)
^ @is_external@
- (Default __@false@__)
^ @name@
- (Required)
^ @password@
- (Required)
^ @projects_limit@
- (Default __@0@__)
^ @skip_confirmation@
- (Default __@true@__)
^ @username@
- (Required)
s Text
s Text
Expr s Text
s Text
Expr s Text
Expr s Text
Expr s Text
Expr s Text
^ The minimal/required arguments.
| The required arguments for 'newUserR'.
^ (Required)
^ (Required)
^ (Required) |
# LANGUAGE NoImplicitPrelude #
# LANGUAGE RecordWildCards #
# LANGUAGE StrictData #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -fno - warn - unused - imports #
Module : . Gitlab . Resources
Copyright : ( c ) 2017 - 2018
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
module Terrafomo.Gitlab.Resources
(
newDeployKeyR
, DeployKeyR (..)
, DeployKeyR_Required (..)
, newGroupR
, GroupR (..)
, GroupR_Required (..)
, newLabelR
, LabelR (..)
, LabelR_Required (..)
, newProjectHookR
, ProjectHookR (..)
, ProjectHookR_Required (..)
, newProjectMembershipR
, ProjectMembershipR (..)
, newProjectR
, ProjectR (..)
, ProjectR_Required (..)
, newUserR
, UserR (..)
, UserR_Required (..)
) where
import Data.Functor ((<$>))
import Data.Semigroup ((<>))
import GHC.Base (Proxy#, proxy#, ($))
import qualified Data.Functor.Const as P
import qualified Data.List.NonEmpty as P
import qualified Data.Map.Strict as P
import qualified Data.Maybe as P
import qualified Data.Text.Lazy as P
import qualified Prelude as P
import qualified Terrafomo.Encode as Encode
import qualified Terrafomo.Gitlab.Provider as P
import qualified Terrafomo.Gitlab.Types as P
import qualified Terrafomo.HCL as TF
import qualified Terrafomo.HIL as TF
import qualified Terrafomo.Lens as Lens
import qualified Terrafomo.Schema as TF
data DeployKeyR s = DeployKeyR_Internal
{ can_push :: TF.Expr s P.Bool
, key :: TF.Expr s P.Text
, project :: TF.Expr s P.Text
, title :: TF.Expr s P.Text
} deriving (P.Show)
| Construct a new @gitlab_deploy_key@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @gitlab_deploy_key@ via :
@
Gitlab.newDeployKeyR
( Gitlab . DeployKeyR
} )
@
= = = Argument Reference
The following arguments are supported :
@
# can_push : : ' ( Resource DeployKeyR s ) ( s Bool )
# key : : ' ( Resource DeployKeyR s ) ( Expr s Text )
# project : : ' ( Resource DeployKeyR s ) ( Expr s Text )
# title : : Lens ' ( Resource DeployKeyR s ) ( Expr s Text )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref DeployKeyR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource DeployKeyR s ) Bool
# create_before_destroy : : ' ( Resource DeployKeyR s ) Bool
# ignore_changes : : ' ( Resource DeployKeyR s ) ( Changes s )
# depends_on : : ' ( Resource DeployKeyR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource DeployKeyR s ) ( Maybe Gitlab )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @gitlab_deploy_key@ via:
@
Gitlab.newDeployKeyR
(Gitlab.DeployKeyR
})
@
=== Argument Reference
The following arguments are supported:
@
#can_push :: Lens' (Resource DeployKeyR s) (Expr s Bool)
#key :: Lens' (Resource DeployKeyR s) (Expr s Text)
#project :: Lens' (Resource DeployKeyR s) (Expr s Text)
#title :: Lens' (Resource DeployKeyR s) (Expr s Text)
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref DeployKeyR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource DeployKeyR s) Bool
#create_before_destroy :: Lens' (Resource DeployKeyR s) Bool
#ignore_changes :: Lens' (Resource DeployKeyR s) (Changes s)
#depends_on :: Lens' (Resource DeployKeyR s) (Set (Depends s))
#provider :: Lens' (Resource DeployKeyR s) (Maybe Gitlab)
@
-}
newDeployKeyR
-> P.Resource DeployKeyR s
newDeployKeyR x =
TF.unsafeResource "gitlab_deploy_key" Encode.metadata
(\DeployKeyR_Internal{..} ->
P.mempty
<> TF.pair "can_push" can_push
<> TF.pair "key" key
<> TF.pair "project" project
<> TF.pair "title" title
)
(let DeployKeyR{..} = x in DeployKeyR_Internal
{ can_push = TF.expr P.False
, key = key
, project = project
, title = title
})
| The required arguments for ' ' .
data DeployKeyR_Required s = DeployKeyR
{ key :: TF.Expr s P.Text
^ ( Required , Forces New )
, project :: TF.Expr s P.Text
^ ( Required , Forces New )
, title :: TF.Expr s P.Text
^ ( Required , Forces New )
} deriving (P.Show)
instance Lens.HasField "can_push" f (P.Resource DeployKeyR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(can_push :: DeployKeyR s -> TF.Expr s P.Bool)
(\s a -> s { can_push = a } :: DeployKeyR s)
instance Lens.HasField "key" f (P.Resource DeployKeyR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(key :: DeployKeyR s -> TF.Expr s P.Text)
(\s a -> s { key = a } :: DeployKeyR s)
instance Lens.HasField "project" f (P.Resource DeployKeyR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(project :: DeployKeyR s -> TF.Expr s P.Text)
(\s a -> s { project = a } :: DeployKeyR s)
instance Lens.HasField "title" f (P.Resource DeployKeyR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(title :: DeployKeyR s -> TF.Expr s P.Text)
(\s a -> s { title = a } :: DeployKeyR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref DeployKeyR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
data GroupR s = GroupR_Internal
{ description :: P.Maybe (TF.Expr s P.Text)
, lfs_enabled :: TF.Expr s P.Bool
, name :: TF.Expr s P.Text
, parent_id :: TF.Expr s P.Int
, path :: TF.Expr s P.Text
, request_access_enabled :: TF.Expr s P.Bool
, visibility_level :: P.Maybe (TF.Expr s P.Text)
} deriving (P.Show)
| Construct a new @gitlab_group@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @gitlab_group@ via :
@
Gitlab.newGroupR
( Gitlab . GroupR
} )
@
= = = Argument Reference
The following arguments are supported :
@
# description : : ' ( Resource GroupR s ) ( Maybe ( s Text ) )
# lfs_enabled : : ' ( Resource GroupR s ) ( s Bool )
# name : : ' ( Resource GroupR s ) ( Expr s Text )
# parent_id : : ' ( Resource GroupR s ) ( s Int )
# path : : ' ( Resource GroupR s ) ( Expr s Text )
# request_access_enabled : : ' ( Resource GroupR s ) ( s Bool )
# visibility_level : : ' ( Resource GroupR s ) ( Maybe ( s Text ) )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref GroupR s ) ( s I d )
# visibility_level : : Getting r ( Ref GroupR s ) ( Expr s Text )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource GroupR s ) Bool
# create_before_destroy : : ' ( Resource GroupR s ) Bool
# ignore_changes : : ' ( Resource GroupR s ) ( Changes s )
# depends_on : : ' ( Resource GroupR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource GroupR s ) ( Maybe Gitlab )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @gitlab_group@ via:
@
Gitlab.newGroupR
(Gitlab.GroupR
})
@
=== Argument Reference
The following arguments are supported:
@
#description :: Lens' (Resource GroupR s) (Maybe (Expr s Text))
#lfs_enabled :: Lens' (Resource GroupR s) (Expr s Bool)
#name :: Lens' (Resource GroupR s) (Expr s Text)
#parent_id :: Lens' (Resource GroupR s) (Expr s Int)
#path :: Lens' (Resource GroupR s) (Expr s Text)
#request_access_enabled :: Lens' (Resource GroupR s) (Expr s Bool)
#visibility_level :: Lens' (Resource GroupR s) (Maybe (Expr s Text))
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref GroupR s) (Expr s Id)
#visibility_level :: Getting r (Ref GroupR s) (Expr s Text)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource GroupR s) Bool
#create_before_destroy :: Lens' (Resource GroupR s) Bool
#ignore_changes :: Lens' (Resource GroupR s) (Changes s)
#depends_on :: Lens' (Resource GroupR s) (Set (Depends s))
#provider :: Lens' (Resource GroupR s) (Maybe Gitlab)
@
-}
newGroupR
-> P.Resource GroupR s
newGroupR x =
TF.unsafeResource "gitlab_group" Encode.metadata
(\GroupR_Internal{..} ->
P.mempty
<> P.maybe P.mempty (TF.pair "description") description
<> TF.pair "lfs_enabled" lfs_enabled
<> TF.pair "name" name
<> TF.pair "parent_id" parent_id
<> TF.pair "path" path
<> TF.pair "request_access_enabled" request_access_enabled
<> P.maybe P.mempty (TF.pair "visibility_level") visibility_level
)
(let GroupR{..} = x in GroupR_Internal
{ description = P.Nothing
, lfs_enabled = TF.expr P.True
, name = name
, parent_id = TF.expr 0
, path = path
, request_access_enabled = TF.expr P.False
, visibility_level = P.Nothing
})
data GroupR_Required s = GroupR
{ name :: TF.Expr s P.Text
, path :: TF.Expr s P.Text
} deriving (P.Show)
instance Lens.HasField "description" f (P.Resource GroupR s) (P.Maybe (TF.Expr s P.Text)) where
field = Lens.resourceLens P.. Lens.lens'
(description :: GroupR s -> P.Maybe (TF.Expr s P.Text))
(\s a -> s { description = a } :: GroupR s)
instance Lens.HasField "lfs_enabled" f (P.Resource GroupR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(lfs_enabled :: GroupR s -> TF.Expr s P.Bool)
(\s a -> s { lfs_enabled = a } :: GroupR s)
instance Lens.HasField "name" f (P.Resource GroupR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(name :: GroupR s -> TF.Expr s P.Text)
(\s a -> s { name = a } :: GroupR s)
instance Lens.HasField "parent_id" f (P.Resource GroupR s) (TF.Expr s P.Int) where
field = Lens.resourceLens P.. Lens.lens'
(parent_id :: GroupR s -> TF.Expr s P.Int)
(\s a -> s { parent_id = a } :: GroupR s)
instance Lens.HasField "path" f (P.Resource GroupR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(path :: GroupR s -> TF.Expr s P.Text)
(\s a -> s { path = a } :: GroupR s)
instance Lens.HasField "request_access_enabled" f (P.Resource GroupR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(request_access_enabled :: GroupR s -> TF.Expr s P.Bool)
(\s a -> s { request_access_enabled = a } :: GroupR s)
instance Lens.HasField "visibility_level" f (P.Resource GroupR s) (P.Maybe (TF.Expr s P.Text)) where
field = Lens.resourceLens P.. Lens.lens'
(visibility_level :: GroupR s -> P.Maybe (TF.Expr s P.Text))
(\s a -> s { visibility_level = a } :: GroupR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref GroupR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
instance Lens.HasField "visibility_level" (P.Const r) (TF.Ref GroupR s) (TF.Expr s P.Text) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "visibility_level"))
data LabelR s = LabelR_Internal
{ color :: TF.Expr s P.Text
, description :: P.Maybe (TF.Expr s P.Text)
, name :: TF.Expr s P.Text
, project :: TF.Expr s P.Text
} deriving (P.Show)
| Construct a new @gitlab_label@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @gitlab_label@ via :
@
( Gitlab .
} )
@
= = = Argument Reference
The following arguments are supported :
@
# color : : Lens ' ( Resource LabelR s ) ( Expr s Text )
# description : : ' ( Resource LabelR s ) ( Maybe ( s Text ) )
# name : : ' ( Resource LabelR s ) ( Expr s Text )
# project : : ' ( Resource LabelR s ) ( Expr s Text )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref LabelR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource LabelR s ) Bool
# create_before_destroy : : ' ( Resource LabelR s ) Bool
# ignore_changes : : ' ( Resource LabelR s ) ( Changes s )
# depends_on : : ' ( Resource LabelR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource LabelR s ) ( Maybe Gitlab )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @gitlab_label@ via:
@
Gitlab.newLabelR
(Gitlab.LabelR
})
@
=== Argument Reference
The following arguments are supported:
@
#color :: Lens' (Resource LabelR s) (Expr s Text)
#description :: Lens' (Resource LabelR s) (Maybe (Expr s Text))
#name :: Lens' (Resource LabelR s) (Expr s Text)
#project :: Lens' (Resource LabelR s) (Expr s Text)
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref LabelR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource LabelR s) Bool
#create_before_destroy :: Lens' (Resource LabelR s) Bool
#ignore_changes :: Lens' (Resource LabelR s) (Changes s)
#depends_on :: Lens' (Resource LabelR s) (Set (Depends s))
#provider :: Lens' (Resource LabelR s) (Maybe Gitlab)
@
-}
newLabelR
-> P.Resource LabelR s
newLabelR x =
TF.unsafeResource "gitlab_label" Encode.metadata
(\LabelR_Internal{..} ->
P.mempty
<> TF.pair "color" color
<> P.maybe P.mempty (TF.pair "description") description
<> TF.pair "name" name
<> TF.pair "project" project
)
(let LabelR{..} = x in LabelR_Internal
{ color = color
, description = P.Nothing
, name = name
, project = project
})
| The required arguments for ' ' .
data LabelR_Required s = LabelR
{ color :: TF.Expr s P.Text
, name :: TF.Expr s P.Text
^ ( Required , Forces New )
, project :: TF.Expr s P.Text
} deriving (P.Show)
instance Lens.HasField "color" f (P.Resource LabelR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(color :: LabelR s -> TF.Expr s P.Text)
(\s a -> s { color = a } :: LabelR s)
instance Lens.HasField "description" f (P.Resource LabelR s) (P.Maybe (TF.Expr s P.Text)) where
field = Lens.resourceLens P.. Lens.lens'
(description :: LabelR s -> P.Maybe (TF.Expr s P.Text))
(\s a -> s { description = a } :: LabelR s)
instance Lens.HasField "name" f (P.Resource LabelR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(name :: LabelR s -> TF.Expr s P.Text)
(\s a -> s { name = a } :: LabelR s)
instance Lens.HasField "project" f (P.Resource LabelR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(project :: LabelR s -> TF.Expr s P.Text)
(\s a -> s { project = a } :: LabelR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref LabelR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
data ProjectHookR s = ProjectHookR_Internal
{ enable_ssl_verification :: TF.Expr s P.Bool
, issues_events :: TF.Expr s P.Bool
, job_events :: TF.Expr s P.Bool
, merge_requests_events :: TF.Expr s P.Bool
, note_events :: TF.Expr s P.Bool
, pipeline_events :: TF.Expr s P.Bool
, project :: TF.Expr s P.Text
, push_events :: TF.Expr s P.Bool
^ @push_events@
, tag_push_events :: TF.Expr s P.Bool
, token :: P.Maybe (TF.Expr s P.Text)
, url :: TF.Expr s P.Text
, wiki_page_events :: TF.Expr s P.Bool
} deriving (P.Show)
| Construct a new @gitlab_project_hook@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @gitlab_project_hook@ via :
@
Gitlab.newProjectHookR
( Gitlab . ProjectHookR
} )
@
= = = Argument Reference
The following arguments are supported :
@
# enable_ssl_verification : : ' ( Resource ProjectHookR s ) ( s Bool )
# issues_events : : ' ( Resource ProjectHookR s ) ( s Bool )
# job_events : : ' ( Resource ProjectHookR s ) ( s Bool )
# merge_requests_events : : ' ( Resource ProjectHookR s ) ( s Bool )
# : : ' ( Resource ProjectHookR s ) ( s Bool )
# pipeline_events : : Lens ' ( Resource ProjectHookR s ) ( s Bool )
# project : : ' ( Resource ProjectHookR s ) ( Expr s Text )
# push_events : : ' ( Resource ProjectHookR s ) ( s Bool )
# tag_push_events : : Lens ' ( Resource ProjectHookR s ) ( s Bool )
# token : : Lens ' ( Resource ProjectHookR s ) ( Maybe ( s Text ) )
# url : : ' ( Resource ProjectHookR s ) ( Expr s Text )
# wiki_page_events : : ' ( Resource ProjectHookR s ) ( s Bool )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref ProjectHookR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource ProjectHookR s ) Bool
# create_before_destroy : : ' ( Resource ProjectHookR s ) Bool
# ignore_changes : : ' ( Resource ProjectHookR s ) ( Changes s )
# depends_on : : ' ( Resource ProjectHookR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource ProjectHookR s ) ( Maybe Gitlab )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @gitlab_project_hook@ via:
@
Gitlab.newProjectHookR
(Gitlab.ProjectHookR
})
@
=== Argument Reference
The following arguments are supported:
@
#enable_ssl_verification :: Lens' (Resource ProjectHookR s) (Expr s Bool)
#issues_events :: Lens' (Resource ProjectHookR s) (Expr s Bool)
#job_events :: Lens' (Resource ProjectHookR s) (Expr s Bool)
#merge_requests_events :: Lens' (Resource ProjectHookR s) (Expr s Bool)
#note_events :: Lens' (Resource ProjectHookR s) (Expr s Bool)
#pipeline_events :: Lens' (Resource ProjectHookR s) (Expr s Bool)
#project :: Lens' (Resource ProjectHookR s) (Expr s Text)
#push_events :: Lens' (Resource ProjectHookR s) (Expr s Bool)
#tag_push_events :: Lens' (Resource ProjectHookR s) (Expr s Bool)
#token :: Lens' (Resource ProjectHookR s) (Maybe (Expr s Text))
#url :: Lens' (Resource ProjectHookR s) (Expr s Text)
#wiki_page_events :: Lens' (Resource ProjectHookR s) (Expr s Bool)
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref ProjectHookR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource ProjectHookR s) Bool
#create_before_destroy :: Lens' (Resource ProjectHookR s) Bool
#ignore_changes :: Lens' (Resource ProjectHookR s) (Changes s)
#depends_on :: Lens' (Resource ProjectHookR s) (Set (Depends s))
#provider :: Lens' (Resource ProjectHookR s) (Maybe Gitlab)
@
-}
newProjectHookR
-> P.Resource ProjectHookR s
newProjectHookR x =
TF.unsafeResource "gitlab_project_hook" Encode.metadata
(\ProjectHookR_Internal{..} ->
P.mempty
<> TF.pair "enable_ssl_verification" enable_ssl_verification
<> TF.pair "issues_events" issues_events
<> TF.pair "job_events" job_events
<> TF.pair "merge_requests_events" merge_requests_events
<> TF.pair "note_events" note_events
<> TF.pair "pipeline_events" pipeline_events
<> TF.pair "project" project
<> TF.pair "push_events" push_events
<> TF.pair "tag_push_events" tag_push_events
<> P.maybe P.mempty (TF.pair "token") token
<> TF.pair "url" url
<> TF.pair "wiki_page_events" wiki_page_events
)
(let ProjectHookR{..} = x in ProjectHookR_Internal
{ enable_ssl_verification = TF.expr P.True
, issues_events = TF.expr P.False
, job_events = TF.expr P.False
, merge_requests_events = TF.expr P.False
, note_events = TF.expr P.False
, pipeline_events = TF.expr P.False
, project = project
, push_events = TF.expr P.True
, tag_push_events = TF.expr P.False
, token = P.Nothing
, url = url
, wiki_page_events = TF.expr P.False
})
data ProjectHookR_Required s = ProjectHookR
{ project :: TF.Expr s P.Text
, url :: TF.Expr s P.Text
} deriving (P.Show)
instance Lens.HasField "enable_ssl_verification" f (P.Resource ProjectHookR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(enable_ssl_verification :: ProjectHookR s -> TF.Expr s P.Bool)
(\s a -> s { enable_ssl_verification = a } :: ProjectHookR s)
instance Lens.HasField "issues_events" f (P.Resource ProjectHookR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(issues_events :: ProjectHookR s -> TF.Expr s P.Bool)
(\s a -> s { issues_events = a } :: ProjectHookR s)
instance Lens.HasField "job_events" f (P.Resource ProjectHookR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(job_events :: ProjectHookR s -> TF.Expr s P.Bool)
(\s a -> s { job_events = a } :: ProjectHookR s)
instance Lens.HasField "merge_requests_events" f (P.Resource ProjectHookR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(merge_requests_events :: ProjectHookR s -> TF.Expr s P.Bool)
(\s a -> s { merge_requests_events = a } :: ProjectHookR s)
instance Lens.HasField "note_events" f (P.Resource ProjectHookR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(note_events :: ProjectHookR s -> TF.Expr s P.Bool)
(\s a -> s { note_events = a } :: ProjectHookR s)
instance Lens.HasField "pipeline_events" f (P.Resource ProjectHookR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(pipeline_events :: ProjectHookR s -> TF.Expr s P.Bool)
(\s a -> s { pipeline_events = a } :: ProjectHookR s)
instance Lens.HasField "project" f (P.Resource ProjectHookR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(project :: ProjectHookR s -> TF.Expr s P.Text)
(\s a -> s { project = a } :: ProjectHookR s)
instance Lens.HasField "push_events" f (P.Resource ProjectHookR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(push_events :: ProjectHookR s -> TF.Expr s P.Bool)
(\s a -> s { push_events = a } :: ProjectHookR s)
instance Lens.HasField "tag_push_events" f (P.Resource ProjectHookR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(tag_push_events :: ProjectHookR s -> TF.Expr s P.Bool)
(\s a -> s { tag_push_events = a } :: ProjectHookR s)
instance Lens.HasField "token" f (P.Resource ProjectHookR s) (P.Maybe (TF.Expr s P.Text)) where
field = Lens.resourceLens P.. Lens.lens'
(token :: ProjectHookR s -> P.Maybe (TF.Expr s P.Text))
(\s a -> s { token = a } :: ProjectHookR s)
instance Lens.HasField "url" f (P.Resource ProjectHookR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(url :: ProjectHookR s -> TF.Expr s P.Text)
(\s a -> s { url = a } :: ProjectHookR s)
instance Lens.HasField "wiki_page_events" f (P.Resource ProjectHookR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(wiki_page_events :: ProjectHookR s -> TF.Expr s P.Bool)
(\s a -> s { wiki_page_events = a } :: ProjectHookR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref ProjectHookR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
data ProjectMembershipR s = ProjectMembershipR
{ access_level :: TF.Expr s P.Text
, project_id :: TF.Expr s TF.Id
, user_id :: TF.Expr s P.Int
} deriving (P.Show)
| Construct a new @gitlab_project_membership@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @gitlab_project_membership@ via :
@
Gitlab.newProjectMembershipR
( Gitlab . ProjectMembershipR
} )
@
= = = Argument Reference
The following arguments are supported :
@
# access_level : : ' ( Resource ProjectMembershipR s ) ( Expr s Text )
# project_id : : ' ( Resource ProjectMembershipR s ) ( s I d )
# user_id : : ' ( Resource ProjectMembershipR s ) ( s Int )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref ProjectMembershipR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource ProjectMembershipR s ) Bool
# create_before_destroy : : ' ( Resource ProjectMembershipR s ) Bool
# ignore_changes : : ' ( Resource ProjectMembershipR s ) ( Changes s )
# depends_on : : ' ( Resource ProjectMembershipR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource ProjectMembershipR s ) ( Maybe Gitlab )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @gitlab_project_membership@ via:
@
Gitlab.newProjectMembershipR
(Gitlab.ProjectMembershipR
})
@
=== Argument Reference
The following arguments are supported:
@
#access_level :: Lens' (Resource ProjectMembershipR s) (Expr s Text)
#project_id :: Lens' (Resource ProjectMembershipR s) (Expr s Id)
#user_id :: Lens' (Resource ProjectMembershipR s) (Expr s Int)
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref ProjectMembershipR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource ProjectMembershipR s) Bool
#create_before_destroy :: Lens' (Resource ProjectMembershipR s) Bool
#ignore_changes :: Lens' (Resource ProjectMembershipR s) (Changes s)
#depends_on :: Lens' (Resource ProjectMembershipR s) (Set (Depends s))
#provider :: Lens' (Resource ProjectMembershipR s) (Maybe Gitlab)
@
-}
newProjectMembershipR
-> P.Resource ProjectMembershipR s
newProjectMembershipR =
TF.unsafeResource "gitlab_project_membership" Encode.metadata
(\ProjectMembershipR{..} ->
P.mempty
<> TF.pair "access_level" access_level
<> TF.pair "project_id" project_id
<> TF.pair "user_id" user_id
)
instance Lens.HasField "access_level" f (P.Resource ProjectMembershipR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(access_level :: ProjectMembershipR s -> TF.Expr s P.Text)
(\s a -> s { access_level = a } :: ProjectMembershipR s)
instance Lens.HasField "project_id" f (P.Resource ProjectMembershipR s) (TF.Expr s TF.Id) where
field = Lens.resourceLens P.. Lens.lens'
(project_id :: ProjectMembershipR s -> TF.Expr s TF.Id)
(\s a -> s { project_id = a } :: ProjectMembershipR s)
instance Lens.HasField "user_id" f (P.Resource ProjectMembershipR s) (TF.Expr s P.Int) where
field = Lens.resourceLens P.. Lens.lens'
(user_id :: ProjectMembershipR s -> TF.Expr s P.Int)
(\s a -> s { user_id = a } :: ProjectMembershipR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref ProjectMembershipR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
data ProjectR s = ProjectR_Internal
{ default_branch :: P.Maybe (TF.Expr s P.Text)
^ @default_branch@
, description :: P.Maybe (TF.Expr s P.Text)
, issues_enabled :: TF.Expr s P.Bool
^ @issues_enabled@
, merge_requests_enabled :: TF.Expr s P.Bool
^ @merge_requests_enabled@
, name :: TF.Expr s P.Text
, namespace_id :: P.Maybe (TF.Expr s P.Int)
, path :: P.Maybe (TF.Expr s P.Text)
, snippets_enabled :: TF.Expr s P.Bool
, visibility_level :: TF.Expr s P.Text
, wiki_enabled :: TF.Expr s P.Bool
} deriving (P.Show)
| Construct a new @gitlab_project@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @gitlab_project@ via :
@
Gitlab.newProjectR
( Gitlab . ProjectR
} )
@
= = = Argument Reference
The following arguments are supported :
@
# default_branch : : ' ( Resource ProjectR s ) ( Maybe ( s Text ) )
# description : : ' ( Resource ProjectR s ) ( Maybe ( s Text ) )
# issues_enabled : : ' ( Resource ProjectR s ) ( s Bool )
# merge_requests_enabled : : ' ( Resource ProjectR s ) ( s Bool )
# name : : ' ( Resource ProjectR s ) ( Expr s Text )
# namespace_id : : ' ( Resource ProjectR s ) ( Maybe ( s Int ) )
# path : : ' ( Resource ProjectR s ) ( Maybe ( s Text ) )
# snippets_enabled : : ' ( Resource ProjectR s ) ( s Bool )
# visibility_level : : ' ( Resource ProjectR s ) ( Expr s Text )
# wiki_enabled : : ' ( Resource ProjectR s ) ( s Bool )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref ProjectR s ) ( s I d )
# http_url_to_repo : : Getting r ( Ref ProjectR s ) ( Expr s Text )
# namespace_id : : Getting r ( Ref ProjectR s ) ( s Int )
# ssh_url_to_repo : : Getting r ( Ref ProjectR s ) ( Expr s Text )
# web_url : : Getting r ( Ref ProjectR s ) ( Expr s Text )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource ProjectR s ) Bool
# create_before_destroy : : ' ( Resource ProjectR s ) Bool
# ignore_changes : : ' ( Resource ProjectR s ) ( Changes s )
# depends_on : : ' ( Resource ProjectR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource ProjectR s ) ( Maybe Gitlab )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @gitlab_project@ via:
@
Gitlab.newProjectR
(Gitlab.ProjectR
})
@
=== Argument Reference
The following arguments are supported:
@
#default_branch :: Lens' (Resource ProjectR s) (Maybe (Expr s Text))
#description :: Lens' (Resource ProjectR s) (Maybe (Expr s Text))
#issues_enabled :: Lens' (Resource ProjectR s) (Expr s Bool)
#merge_requests_enabled :: Lens' (Resource ProjectR s) (Expr s Bool)
#name :: Lens' (Resource ProjectR s) (Expr s Text)
#namespace_id :: Lens' (Resource ProjectR s) (Maybe (Expr s Int))
#path :: Lens' (Resource ProjectR s) (Maybe (Expr s Text))
#snippets_enabled :: Lens' (Resource ProjectR s) (Expr s Bool)
#visibility_level :: Lens' (Resource ProjectR s) (Expr s Text)
#wiki_enabled :: Lens' (Resource ProjectR s) (Expr s Bool)
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref ProjectR s) (Expr s Id)
#http_url_to_repo :: Getting r (Ref ProjectR s) (Expr s Text)
#namespace_id :: Getting r (Ref ProjectR s) (Expr s Int)
#ssh_url_to_repo :: Getting r (Ref ProjectR s) (Expr s Text)
#web_url :: Getting r (Ref ProjectR s) (Expr s Text)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource ProjectR s) Bool
#create_before_destroy :: Lens' (Resource ProjectR s) Bool
#ignore_changes :: Lens' (Resource ProjectR s) (Changes s)
#depends_on :: Lens' (Resource ProjectR s) (Set (Depends s))
#provider :: Lens' (Resource ProjectR s) (Maybe Gitlab)
@
-}
newProjectR
-> P.Resource ProjectR s
newProjectR x =
TF.unsafeResource "gitlab_project" Encode.metadata
(\ProjectR_Internal{..} ->
P.mempty
<> P.maybe P.mempty (TF.pair "default_branch") default_branch
<> P.maybe P.mempty (TF.pair "description") description
<> TF.pair "issues_enabled" issues_enabled
<> TF.pair "merge_requests_enabled" merge_requests_enabled
<> TF.pair "name" name
<> P.maybe P.mempty (TF.pair "namespace_id") namespace_id
<> P.maybe P.mempty (TF.pair "path") path
<> TF.pair "snippets_enabled" snippets_enabled
<> TF.pair "visibility_level" visibility_level
<> TF.pair "wiki_enabled" wiki_enabled
)
(let ProjectR{..} = x in ProjectR_Internal
{ default_branch = P.Nothing
, description = P.Nothing
, issues_enabled = TF.expr P.True
, merge_requests_enabled = TF.expr P.True
, name = name
, namespace_id = P.Nothing
, path = P.Nothing
, snippets_enabled = TF.expr P.True
, visibility_level = TF.expr "private"
, wiki_enabled = TF.expr P.True
})
data ProjectR_Required s = ProjectR
{ name :: TF.Expr s P.Text
} deriving (P.Show)
instance Lens.HasField "default_branch" f (P.Resource ProjectR s) (P.Maybe (TF.Expr s P.Text)) where
field = Lens.resourceLens P.. Lens.lens'
(default_branch :: ProjectR s -> P.Maybe (TF.Expr s P.Text))
(\s a -> s { default_branch = a } :: ProjectR s)
instance Lens.HasField "description" f (P.Resource ProjectR s) (P.Maybe (TF.Expr s P.Text)) where
field = Lens.resourceLens P.. Lens.lens'
(description :: ProjectR s -> P.Maybe (TF.Expr s P.Text))
(\s a -> s { description = a } :: ProjectR s)
instance Lens.HasField "issues_enabled" f (P.Resource ProjectR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(issues_enabled :: ProjectR s -> TF.Expr s P.Bool)
(\s a -> s { issues_enabled = a } :: ProjectR s)
instance Lens.HasField "merge_requests_enabled" f (P.Resource ProjectR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(merge_requests_enabled :: ProjectR s -> TF.Expr s P.Bool)
(\s a -> s { merge_requests_enabled = a } :: ProjectR s)
instance Lens.HasField "name" f (P.Resource ProjectR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(name :: ProjectR s -> TF.Expr s P.Text)
(\s a -> s { name = a } :: ProjectR s)
instance Lens.HasField "namespace_id" f (P.Resource ProjectR s) (P.Maybe (TF.Expr s P.Int)) where
field = Lens.resourceLens P.. Lens.lens'
(namespace_id :: ProjectR s -> P.Maybe (TF.Expr s P.Int))
(\s a -> s { namespace_id = a } :: ProjectR s)
instance Lens.HasField "path" f (P.Resource ProjectR s) (P.Maybe (TF.Expr s P.Text)) where
field = Lens.resourceLens P.. Lens.lens'
(path :: ProjectR s -> P.Maybe (TF.Expr s P.Text))
(\s a -> s { path = a } :: ProjectR s)
instance Lens.HasField "snippets_enabled" f (P.Resource ProjectR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(snippets_enabled :: ProjectR s -> TF.Expr s P.Bool)
(\s a -> s { snippets_enabled = a } :: ProjectR s)
instance Lens.HasField "visibility_level" f (P.Resource ProjectR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(visibility_level :: ProjectR s -> TF.Expr s P.Text)
(\s a -> s { visibility_level = a } :: ProjectR s)
instance Lens.HasField "wiki_enabled" f (P.Resource ProjectR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(wiki_enabled :: ProjectR s -> TF.Expr s P.Bool)
(\s a -> s { wiki_enabled = a } :: ProjectR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref ProjectR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
instance Lens.HasField "http_url_to_repo" (P.Const r) (TF.Ref ProjectR s) (TF.Expr s P.Text) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "http_url_to_repo"))
instance Lens.HasField "namespace_id" (P.Const r) (TF.Ref ProjectR s) (TF.Expr s P.Int) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "namespace_id"))
instance Lens.HasField "ssh_url_to_repo" (P.Const r) (TF.Ref ProjectR s) (TF.Expr s P.Text) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "ssh_url_to_repo"))
instance Lens.HasField "web_url" (P.Const r) (TF.Ref ProjectR s) (TF.Expr s P.Text) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "web_url"))
| The main @gitlab_user@ resource definition .
data UserR s = UserR_Internal
{ can_create_group :: TF.Expr s P.Bool
, email :: TF.Expr s P.Text
, is_admin :: TF.Expr s P.Bool
, is_external :: TF.Expr s P.Bool
, name :: TF.Expr s P.Text
, password :: TF.Expr s P.Text
, projects_limit :: TF.Expr s P.Int
, skip_confirmation :: TF.Expr s P.Bool
, username :: TF.Expr s P.Text
} deriving (P.Show)
| Construct a new @gitlab_user@ resource . The
available argument lenses and computed attribute getters are documented below .
See the < terraform documentation > for more information .
= = = Example Usage
You can define a minimal @gitlab_user@ via :
@
( Gitlab . UserR
} )
@
= = = Argument Reference
The following arguments are supported :
@
# can_create_group : : ' ( Resource UserR s ) ( s Bool )
# email : : Lens ' ( Resource UserR s ) ( Expr s Text )
# is_admin : : ' ( Resource UserR s ) ( s Bool )
# is_external : : ' ( Resource UserR s ) ( s Bool )
# name : : ' ( Resource UserR s ) ( Expr s Text )
# password : : ' ( Resource UserR s ) ( Expr s Text )
# projects_limit : : ' ( Resource UserR s ) ( s Int )
# skip_confirmation : : Lens ' ( Resource UserR s ) ( s Bool )
# username : : ' ( Resource UserR s ) ( Expr s Text )
@
= = = Attributes Reference
In addition to the arguments above , the following computed attributes are available :
@
# i d : : Getting r ( Ref UserR s ) ( s I d )
@
= = = Configuring Meta - parameters
The following additional configuration is supported :
@
# prevent_destroy : : Lens ' ( Resource UserR s ) Bool
# create_before_destroy : : ' ( Resource UserR s ) Bool
# ignore_changes : : ' ( Resource UserR s ) ( Changes s )
# depends_on : : ' ( Resource UserR s ) ( Set ( Depends s ) )
# provider : : ' ( Resource UserR s ) ( Maybe Gitlab )
@
available argument lenses and computed attribute getters are documented below.
See the < terraform documentation> for more information.
=== Example Usage
You can define a minimal @gitlab_user@ via:
@
Gitlab.newUserR
(Gitlab.UserR
})
@
=== Argument Reference
The following arguments are supported:
@
#can_create_group :: Lens' (Resource UserR s) (Expr s Bool)
#email :: Lens' (Resource UserR s) (Expr s Text)
#is_admin :: Lens' (Resource UserR s) (Expr s Bool)
#is_external :: Lens' (Resource UserR s) (Expr s Bool)
#name :: Lens' (Resource UserR s) (Expr s Text)
#password :: Lens' (Resource UserR s) (Expr s Text)
#projects_limit :: Lens' (Resource UserR s) (Expr s Int)
#skip_confirmation :: Lens' (Resource UserR s) (Expr s Bool)
#username :: Lens' (Resource UserR s) (Expr s Text)
@
=== Attributes Reference
In addition to the arguments above, the following computed attributes are available:
@
#id :: Getting r (Ref UserR s) (Expr s Id)
@
=== Configuring Meta-parameters
The following additional configuration is supported:
@
#prevent_destroy :: Lens' (Resource UserR s) Bool
#create_before_destroy :: Lens' (Resource UserR s) Bool
#ignore_changes :: Lens' (Resource UserR s) (Changes s)
#depends_on :: Lens' (Resource UserR s) (Set (Depends s))
#provider :: Lens' (Resource UserR s) (Maybe Gitlab)
@
-}
newUserR
-> P.Resource UserR s
newUserR x =
TF.unsafeResource "gitlab_user" Encode.metadata
(\UserR_Internal{..} ->
P.mempty
<> TF.pair "can_create_group" can_create_group
<> TF.pair "email" email
<> TF.pair "is_admin" is_admin
<> TF.pair "is_external" is_external
<> TF.pair "name" name
<> TF.pair "password" password
<> TF.pair "projects_limit" projects_limit
<> TF.pair "skip_confirmation" skip_confirmation
<> TF.pair "username" username
)
(let UserR{..} = x in UserR_Internal
{ can_create_group = TF.expr P.False
, email = email
, is_admin = TF.expr P.False
, is_external = TF.expr P.False
, name = name
, password = password
, projects_limit = TF.expr 0
, skip_confirmation = TF.expr P.True
, username = username
})
data UserR_Required s = UserR
{ email :: TF.Expr s P.Text
^ ( Required , Forces New )
, name :: TF.Expr s P.Text
, password :: TF.Expr s P.Text
, username :: TF.Expr s P.Text
} deriving (P.Show)
instance Lens.HasField "can_create_group" f (P.Resource UserR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(can_create_group :: UserR s -> TF.Expr s P.Bool)
(\s a -> s { can_create_group = a } :: UserR s)
instance Lens.HasField "email" f (P.Resource UserR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(email :: UserR s -> TF.Expr s P.Text)
(\s a -> s { email = a } :: UserR s)
instance Lens.HasField "is_admin" f (P.Resource UserR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(is_admin :: UserR s -> TF.Expr s P.Bool)
(\s a -> s { is_admin = a } :: UserR s)
instance Lens.HasField "is_external" f (P.Resource UserR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(is_external :: UserR s -> TF.Expr s P.Bool)
(\s a -> s { is_external = a } :: UserR s)
instance Lens.HasField "name" f (P.Resource UserR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(name :: UserR s -> TF.Expr s P.Text)
(\s a -> s { name = a } :: UserR s)
instance Lens.HasField "password" f (P.Resource UserR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(password :: UserR s -> TF.Expr s P.Text)
(\s a -> s { password = a } :: UserR s)
instance Lens.HasField "projects_limit" f (P.Resource UserR s) (TF.Expr s P.Int) where
field = Lens.resourceLens P.. Lens.lens'
(projects_limit :: UserR s -> TF.Expr s P.Int)
(\s a -> s { projects_limit = a } :: UserR s)
instance Lens.HasField "skip_confirmation" f (P.Resource UserR s) (TF.Expr s P.Bool) where
field = Lens.resourceLens P.. Lens.lens'
(skip_confirmation :: UserR s -> TF.Expr s P.Bool)
(\s a -> s { skip_confirmation = a } :: UserR s)
instance Lens.HasField "username" f (P.Resource UserR s) (TF.Expr s P.Text) where
field = Lens.resourceLens P.. Lens.lens'
(username :: UserR s -> TF.Expr s P.Text)
(\s a -> s { username = a } :: UserR s)
instance Lens.HasField "id" (P.Const r) (TF.Ref UserR s) (TF.Expr s TF.Id) where
field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id"))
|
cbf0ad37774e331137aa1de2b1523bf8d43ecdc25d5a75aa05b25fbd1ae3903f | mauricioszabo/paprika | byte_array.clj | (ns paprika.io.byte-array
(:refer-clojure :exclude [slurp spit])
(:require [clojure.java.io :as io])
(:import [java.io ByteArrayOutputStream ByteArrayInputStream]))
(defn slurp
"Reads a binary file and returns a byte array instead of a string"
[file-name]
(let [in (io/input-stream file-name)
out (ByteArrayOutputStream.)]
(io/copy in out)
(.toByteArray out)))
(defn spit
"Saves a binary data (byte array) to a file"
[file-name contents]
(io/copy (ByteArrayInputStream. contents)
(io/file file-name)))
| null | https://raw.githubusercontent.com/mauricioszabo/paprika/b1923abb581ab12ce00971fa4e184c0974602ef9/src/paprika/io/byte_array.clj | clojure | (ns paprika.io.byte-array
(:refer-clojure :exclude [slurp spit])
(:require [clojure.java.io :as io])
(:import [java.io ByteArrayOutputStream ByteArrayInputStream]))
(defn slurp
"Reads a binary file and returns a byte array instead of a string"
[file-name]
(let [in (io/input-stream file-name)
out (ByteArrayOutputStream.)]
(io/copy in out)
(.toByteArray out)))
(defn spit
"Saves a binary data (byte array) to a file"
[file-name contents]
(io/copy (ByteArrayInputStream. contents)
(io/file file-name)))
| |
eabc989d0b585cfb99fa27313451b72b6666c9320cbc88bdb96fd2d976c44f26 | stchang/lazyprofile-tool | deque-implicit-profiled.rkt | #lang s-exp "../../lazy-profile.rkt"
(struct Zero ())
(struct One (elem))
(struct Two (first second))
(struct Three (first second third))
( define - type ( D A ) ( U Zero ( One A ) ( Two A ) ( Three A ) ) )
( define - type ( D1 A ) ( U Zero ( One A ) ( Two A ) ) )
(struct Shallow (elem))
(struct Deep (F M R))
( define - type ( Deque A ) ( U ( Shallow A ) ( Deep A ) ) )
;; An empty deque
(define empty (Shallow (Zero)))
;; Check for empty deque
(: empty ? : ( All ( A ) ( ( Deque A ) - > Boolean ) ) )
(define (empty? que) (and (Shallow? que) (Zero? (Shallow-elem que))))
;; Inserts an element into the front of deque
(: enqueue - front : ( All ( A ) ( A ( Deque A ) - > ( ) ) ) )
(define (enqueue-front elem que)
(match que
[(Shallow (Zero)) (Shallow (One elem))]
[(Shallow (One a)) (Shallow (Two elem a))]
[(Shallow (Two a b))
(Shallow (Three elem a b))]
[(Shallow (Three f s t))
(Deep (Two elem f) (cons empty empty) (Two s t))]
[(Deep (Zero) m r) (Deep (One elem) m r)]
[(Deep (One a) m r) (Deep (Two elem a) m r)]
[(Deep (Two a b) m r)
(Deep (Three elem a b) m r)]
[(Deep (Three f s t) m r)
(Deep (Two elem f)
(let* ([forced-mid m]
[first (car forced-mid)]
[second (cdr forced-mid)])
(cons (enqueue-front s first) (enqueue-front t second)))
r)]))
;; Inserts into the rear of the queue
(: enqueue : ( All ( A ) ( A ( Deque A ) - > ( ) ) ) )
(define (enqueue elem que)
(match que
[(Shallow (Zero)) (Shallow (One elem))]
[(Shallow (One a)) (Shallow (Two a elem))]
[(Shallow (Two a b))
(Shallow (Three a b elem))]
[(Shallow (Three f s t))
(Deep (Two f s) (cons empty empty) (Two t elem))]
[(Deep f m (Zero)) (Deep f m (One elem))]
[(Deep f m (One a)) (Deep f m (Two a elem))]
[(Deep f m (Two a b))
(Deep f m (Three a b elem))]
[(Deep fi m (Three f s t))
(Deep fi
(let* ([forced-mid m]
[first (car forced-mid)]
[second (cdr forced-mid)])
(cons (enqueue f first) (enqueue s second)))
(Two t elem))]))
Returns the first element of the deque
(: head : ( All ( A ) ( ( Deque A ) - > A ) ) )
(define (head que)
(match que
[(Shallow (Zero)) (error 'head "given deque is empty")]
[(Shallow (One f)) f]
[(Shallow (Two f s)) f]
[(Shallow (Three f s t)) f]
[(Deep (Zero) m r) (error 'head "given deque is empty")]
[(Deep (One f) m r) f]
[(Deep (Two f s) m r) f]
[(Deep (Three f s t) m r) f]))
;; Returns the last element of the deque
(: last : ( All ( A ) ( ( Deque A ) - > A ) ) )
(define (last que)
(match que
[(Shallow (Zero)) (error 'last "given deque is empty")]
[(Shallow (One f)) f]
[(Shallow (Two f s)) s]
[(Shallow (Three f s t)) t]
[(Deep f m (Zero)) (error 'last "given deque is empty")]
[(Deep fi m (One f)) f]
[(Deep fi m (Two f s)) s]
[(Deep fi m (Three f s t)) t]))
Returns a deque without the first element
(: tail : ( All ( A ) ( ( Deque A ) - > ( ) ) ) )
(define (tail que)
(match que
[(Shallow (Zero)) (error 'tail "given deque is empty")]
[(Shallow (One _)) (Shallow (Zero))]
[(Shallow (Two _ s)) (Shallow (One s))]
[(Shallow (Three _ s t)) (Shallow (Two s t))]
[(Deep (Zero) m r) (error 'tail "given deque is empty")]
[(Deep (One _) mid r)
(let ([m mid])
(if (empty? (car m))
(Shallow r)
(let* ([carm (car m)]
[cdrm (cdr m)]
[first (head carm)]
[second (head cdrm)])
(Deep (Two first second)
(cons (tail carm) (tail cdrm)) r))))]
[(Deep (Two _ s) m r) (Deep (One s) m r)]
[(Deep (Three _ s t) m r)
(Deep (Two s t) m r)]))
;; Returns a deque without the last element
(: init : ( All ( A ) ( ( Deque A ) - > ( ) ) ) )
(define (init que)
(match que
[(Shallow (Zero)) (error 'init "given deque is empty")]
[(Shallow (One f)) (Shallow (Zero))]
[(Shallow (Two f _))
(Shallow (One f))]
[(Shallow (Three f s _)) (Shallow (Two f s))]
[(Deep f m (Zero)) (error 'init "given deque is empty")]
[(Deep f mid (One a))
(let* ([m mid]
[carm (car m)])
(if (empty? carm)
(Shallow f)
(let* ([cdrm (cdr m)]
[first (last carm)]
[second (last cdrm)])
(Deep f (cons (init carm) (init cdrm))
(Two first second)))))]
[(Deep fi m (Two f _)) (Deep fi m (One f))]
[(Deep fi m (Three f s t))
(Deep fi m (Two f s))]))
;; Similar to build-list
(: build - deque : ( All ( A ) ( Natural ( Natural - > A ) - > ( ) ) ) )
(define (build-deque size func)
(let loop ([n size])
(if (zero? n)
empty
(let ([nsub1 (sub1 n)])
(enqueue (func nsub1) (loop nsub1))))))
(define (build-deque-front size func)
(let loop ([n size])
(if (zero? n)
empty
(let ([nsub1 (sub1 n)])
(enqueue-front (func nsub1) (loop nsub1))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; tests
suggests delaying ln77,col15 and ( maintainR )
;; - because we are inserting from rear
( build - deque 1024 add1 )
;; suggests delaying ln67,col15 and ln66,col15 (maintainF)
;; - because we are inserting from the front
( build - deque - front 1024 add1 )
suggests delay in both maintainR and maintainF ( F first ) , and in append
( let loop ( [ d ( build - deque 1024 add1 ) ] [ n 0 ] )
(if (= n 50) 0
(+ (head d) (loop (tail d) (add1 n)))))
suggests delay in both maintainR and maintainF ( R first ) ( no append )
( let loop ( [ d ( build - deque 1024 add1 ) ] [ n 0 ] )
(if (= n 50) 0
(+ (last d) (loop (init d) (add1 n)))))
; suggests delay in maintainF only (no append)
( let loop ( [ d ( build - deque - front 1024 add1 ) ] [ n 0 ] )
(if (= n 50) 0
(+ (head d) (loop (tail d) (add1 n)))))
; suggests delay in maintainF only, and in append
(let loop ([d (build-deque-front 256 add1)] [n 0])
(if (= n 50) 0
(+ (last d) (loop (init d) (add1 n)))))
| null | https://raw.githubusercontent.com/stchang/lazyprofile-tool/f347cbe6e91f671320d025d9217dfe1795b8d0f0/examples-popl2014/okasaki/deque-implicit-profiled.rkt | racket | An empty deque
Check for empty deque
Inserts an element into the front of deque
Inserts into the rear of the queue
Returns the last element of the deque
Returns a deque without the last element
Similar to build-list
tests
- because we are inserting from rear
suggests delaying ln67,col15 and ln66,col15 (maintainF)
- because we are inserting from the front
suggests delay in maintainF only (no append)
suggests delay in maintainF only, and in append | #lang s-exp "../../lazy-profile.rkt"
(struct Zero ())
(struct One (elem))
(struct Two (first second))
(struct Three (first second third))
( define - type ( D A ) ( U Zero ( One A ) ( Two A ) ( Three A ) ) )
( define - type ( D1 A ) ( U Zero ( One A ) ( Two A ) ) )
(struct Shallow (elem))
(struct Deep (F M R))
( define - type ( Deque A ) ( U ( Shallow A ) ( Deep A ) ) )
(define empty (Shallow (Zero)))
(: empty ? : ( All ( A ) ( ( Deque A ) - > Boolean ) ) )
(define (empty? que) (and (Shallow? que) (Zero? (Shallow-elem que))))
(: enqueue - front : ( All ( A ) ( A ( Deque A ) - > ( ) ) ) )
(define (enqueue-front elem que)
(match que
[(Shallow (Zero)) (Shallow (One elem))]
[(Shallow (One a)) (Shallow (Two elem a))]
[(Shallow (Two a b))
(Shallow (Three elem a b))]
[(Shallow (Three f s t))
(Deep (Two elem f) (cons empty empty) (Two s t))]
[(Deep (Zero) m r) (Deep (One elem) m r)]
[(Deep (One a) m r) (Deep (Two elem a) m r)]
[(Deep (Two a b) m r)
(Deep (Three elem a b) m r)]
[(Deep (Three f s t) m r)
(Deep (Two elem f)
(let* ([forced-mid m]
[first (car forced-mid)]
[second (cdr forced-mid)])
(cons (enqueue-front s first) (enqueue-front t second)))
r)]))
(: enqueue : ( All ( A ) ( A ( Deque A ) - > ( ) ) ) )
(define (enqueue elem que)
(match que
[(Shallow (Zero)) (Shallow (One elem))]
[(Shallow (One a)) (Shallow (Two a elem))]
[(Shallow (Two a b))
(Shallow (Three a b elem))]
[(Shallow (Three f s t))
(Deep (Two f s) (cons empty empty) (Two t elem))]
[(Deep f m (Zero)) (Deep f m (One elem))]
[(Deep f m (One a)) (Deep f m (Two a elem))]
[(Deep f m (Two a b))
(Deep f m (Three a b elem))]
[(Deep fi m (Three f s t))
(Deep fi
(let* ([forced-mid m]
[first (car forced-mid)]
[second (cdr forced-mid)])
(cons (enqueue f first) (enqueue s second)))
(Two t elem))]))
Returns the first element of the deque
(: head : ( All ( A ) ( ( Deque A ) - > A ) ) )
(define (head que)
(match que
[(Shallow (Zero)) (error 'head "given deque is empty")]
[(Shallow (One f)) f]
[(Shallow (Two f s)) f]
[(Shallow (Three f s t)) f]
[(Deep (Zero) m r) (error 'head "given deque is empty")]
[(Deep (One f) m r) f]
[(Deep (Two f s) m r) f]
[(Deep (Three f s t) m r) f]))
(: last : ( All ( A ) ( ( Deque A ) - > A ) ) )
(define (last que)
(match que
[(Shallow (Zero)) (error 'last "given deque is empty")]
[(Shallow (One f)) f]
[(Shallow (Two f s)) s]
[(Shallow (Three f s t)) t]
[(Deep f m (Zero)) (error 'last "given deque is empty")]
[(Deep fi m (One f)) f]
[(Deep fi m (Two f s)) s]
[(Deep fi m (Three f s t)) t]))
Returns a deque without the first element
(: tail : ( All ( A ) ( ( Deque A ) - > ( ) ) ) )
(define (tail que)
(match que
[(Shallow (Zero)) (error 'tail "given deque is empty")]
[(Shallow (One _)) (Shallow (Zero))]
[(Shallow (Two _ s)) (Shallow (One s))]
[(Shallow (Three _ s t)) (Shallow (Two s t))]
[(Deep (Zero) m r) (error 'tail "given deque is empty")]
[(Deep (One _) mid r)
(let ([m mid])
(if (empty? (car m))
(Shallow r)
(let* ([carm (car m)]
[cdrm (cdr m)]
[first (head carm)]
[second (head cdrm)])
(Deep (Two first second)
(cons (tail carm) (tail cdrm)) r))))]
[(Deep (Two _ s) m r) (Deep (One s) m r)]
[(Deep (Three _ s t) m r)
(Deep (Two s t) m r)]))
(: init : ( All ( A ) ( ( Deque A ) - > ( ) ) ) )
(define (init que)
(match que
[(Shallow (Zero)) (error 'init "given deque is empty")]
[(Shallow (One f)) (Shallow (Zero))]
[(Shallow (Two f _))
(Shallow (One f))]
[(Shallow (Three f s _)) (Shallow (Two f s))]
[(Deep f m (Zero)) (error 'init "given deque is empty")]
[(Deep f mid (One a))
(let* ([m mid]
[carm (car m)])
(if (empty? carm)
(Shallow f)
(let* ([cdrm (cdr m)]
[first (last carm)]
[second (last cdrm)])
(Deep f (cons (init carm) (init cdrm))
(Two first second)))))]
[(Deep fi m (Two f _)) (Deep fi m (One f))]
[(Deep fi m (Three f s t))
(Deep fi m (Two f s))]))
(: build - deque : ( All ( A ) ( Natural ( Natural - > A ) - > ( ) ) ) )
(define (build-deque size func)
(let loop ([n size])
(if (zero? n)
empty
(let ([nsub1 (sub1 n)])
(enqueue (func nsub1) (loop nsub1))))))
(define (build-deque-front size func)
(let loop ([n size])
(if (zero? n)
empty
(let ([nsub1 (sub1 n)])
(enqueue-front (func nsub1) (loop nsub1))))))
suggests delaying ln77,col15 and ( maintainR )
( build - deque 1024 add1 )
( build - deque - front 1024 add1 )
suggests delay in both maintainR and maintainF ( F first ) , and in append
( let loop ( [ d ( build - deque 1024 add1 ) ] [ n 0 ] )
(if (= n 50) 0
(+ (head d) (loop (tail d) (add1 n)))))
suggests delay in both maintainR and maintainF ( R first ) ( no append )
( let loop ( [ d ( build - deque 1024 add1 ) ] [ n 0 ] )
(if (= n 50) 0
(+ (last d) (loop (init d) (add1 n)))))
( let loop ( [ d ( build - deque - front 1024 add1 ) ] [ n 0 ] )
(if (= n 50) 0
(+ (head d) (loop (tail d) (add1 n)))))
(let loop ([d (build-deque-front 256 add1)] [n 0])
(if (= n 50) 0
(+ (last d) (loop (init d) (add1 n)))))
|
d385ee0f46183009ea6e43e7b265fec96893f308b0ec3237999c08774bb56547 | deg/sodium | core_test.cljs | (ns sodium.core-test
(:require [cljs.test :refer-macros [deftest testing is are]]
[sodium.core :as na]))
| null | https://raw.githubusercontent.com/deg/sodium/1855fe870c3719af7d16d85c2558df1799a9bd32/test/sodium/core_test.cljs | clojure | (ns sodium.core-test
(:require [cljs.test :refer-macros [deftest testing is are]]
[sodium.core :as na]))
| |
2c26ad2177deaf7746594514be45fd675d726ffd5554dc08e6348a496fd5db25 | astrada/ocaml-extjs | window.ml | let () =
Ext.instance##require(
Js.array [|
Js.string "Ext.window.Window";
Js.string "Ext.tab.*";
Js.string "Ext.toolbar.Spacer";
Js.string "Ext.layout.container.Card";
Js.string "Ext.layout.container.Border";
|],
Js.undefined,
Js.undefined,
Js.undefined)
let () =
Ext.instance##onReady(
Js.wrap_callback (fun () ->
(Js.Unsafe.coerce (Ext_util_Region.get_static ()))##override({|
colors = Js.array [|
Js.string "red";
Js.string "orange";
Js.string "yellow";
Js.string "green";
Js.string "blue";
Js.string "indigo";
Js.string "violet"
|];
nextColor = 0;
show = Js.wrap_meth_callback (fun this () ->
let style = {|
display = Js.string "block";
position = Js.string "absolute";
top = this##top##toString()##concat(Js.string "px");
left = this##left##toString()##concat(Js.string "px");
height = (Js.number_of_float (
(Js.float_of_number this##bottom) -.
(Js.float_of_number this##top) +.
1.0))##toString()##concat(Js.string "px");
width = (Js.number_of_float (
(Js.float_of_number this##right) -.
(Js.float_of_number this##left) +.
1.0))##toString()##concat(Js.string "px");
opacity = Js.number_of_float 0.3;
|} in
Js.Unsafe.set style (Js.string "pointer-events") (Js.string "none");
Js.Unsafe.set style (Js.string "z-index") 9999999;
if not (Js.Optdef.test (Js.Unsafe.coerce this)##highlightEl) then begin
Js.Unsafe.set style (Js.string "background-color")
(Js.Unsafe.get this##colors this##nextColor);
(Js.Unsafe.coerce Ext_util_Region.static)##prototype##nextColor <-
(Js.Unsafe.coerce Ext_util_Region.static)##prototype##nextColor + 1;
this##highlightEl <- Ext.instance##getBody()##createChild({|
style = style
|},
Js.undefined,
Js.undefined);
if this##nextColor >= this##colors##length then begin
this##nextColor <- 0;
end;
end else begin
ignore (this##highlightEl##setStyle(style));
end);
hide = Js.wrap_meth_callback (fun this () ->
if Js.Optdef.test (Js.Unsafe.coerce this)##highlightEl then begin
this##highlightEl##setStyle({|
display = Js.string "none";
|});
end);
|},
ExtUtils.undef);
let constrainedWin =
Ext.instance##create(Js.def (Js.string "Ext.Window"), Js.def {|
title = Js.string "Constrained Window";
width = 200;
height = 100;
Constraining will pull the Window leftwards so that it 's within the
* parent Window
* parent Window *)
x = 1000;
y = 20;
constrain = Js._true;
layout = Js.string "fit";
items = {|
border = Js._false;
|};
|}) in
let constrainedWin2 =
Ext.instance##create(Js.def (Js.string "Ext.Window"), Js.def {|
title = Js.string "Header-Constrained Win";
width = 200;
height = 100;
x = 120;
y = 120;
constrainHeader = Js._true;
layout = Js.string "fit";
items = {|
border = Js._false;
|};
|}) in
let win2 =
Ext.instance##create(Js.def (Js.string "Ext.Window"), Js.def {|
height = 200;
width = 400;
x = 450;
y = 450;
title = Js.string "Constraining Window, plain: true";
closable = Js._false;
plain = Js._true;
layout = Js.string "fit";
items = Js.array [|
Js.Unsafe.inject constrainedWin;
Js.Unsafe.inject constrainedWin2;
Js.Unsafe.inject {|
border = Js._false;
|};
|];
|}) in
win2##show();
constrainedWin##show();
constrainedWin2##show();
Ext.instance##create(Js.def (Js.string "Ext.Window"), Js.def {|
title = Js.string "Left Header, plain: true";
width = 400;
height = 200;
x = 10;
y = 200;
plain = Js._true;
headerPosition = Js.string "left";
layout = Js.string "fit";
items = {|
border = Js._false;
|};
|})##show();
Ext.instance##create(Js.def (Js.string "Ext.Window"), Js.def {|
title = Js.string "Right Header, plain: true";
width = 400;
height = 200;
x = 450;
y = 200;
headerPosition = Js.string "right";
layout = Js.string "fit";
items = {|
border = Js._false;
|};
|})##show();
Ext.instance##create(Js.def (Js.string "Ext.Window"), Js.def {|
title = Js.string "Bottom Header, plain: true";
width = 400;
height = 200;
x = 10;
y = 450;
plain = true;
headerPosition = Js.string "bottom";
layout = Js.string "fit";
items = {|
border = Js._false;
|};
|})##show();
),
ExtUtils.undef,
ExtUtils.undef)
| null | https://raw.githubusercontent.com/astrada/ocaml-extjs/77df630a75fb84667ee953f218c9ce375b3e7484/examples/window/window/window.ml | ocaml | let () =
Ext.instance##require(
Js.array [|
Js.string "Ext.window.Window";
Js.string "Ext.tab.*";
Js.string "Ext.toolbar.Spacer";
Js.string "Ext.layout.container.Card";
Js.string "Ext.layout.container.Border";
|],
Js.undefined,
Js.undefined,
Js.undefined)
let () =
Ext.instance##onReady(
Js.wrap_callback (fun () ->
(Js.Unsafe.coerce (Ext_util_Region.get_static ()))##override({|
colors = Js.array [|
Js.string "red";
Js.string "orange";
Js.string "yellow";
Js.string "green";
Js.string "blue";
Js.string "indigo";
Js.string "violet"
|];
nextColor = 0;
show = Js.wrap_meth_callback (fun this () ->
let style = {|
display = Js.string "block";
position = Js.string "absolute";
top = this##top##toString()##concat(Js.string "px");
left = this##left##toString()##concat(Js.string "px");
height = (Js.number_of_float (
(Js.float_of_number this##bottom) -.
(Js.float_of_number this##top) +.
1.0))##toString()##concat(Js.string "px");
width = (Js.number_of_float (
(Js.float_of_number this##right) -.
(Js.float_of_number this##left) +.
1.0))##toString()##concat(Js.string "px");
opacity = Js.number_of_float 0.3;
|} in
Js.Unsafe.set style (Js.string "pointer-events") (Js.string "none");
Js.Unsafe.set style (Js.string "z-index") 9999999;
if not (Js.Optdef.test (Js.Unsafe.coerce this)##highlightEl) then begin
Js.Unsafe.set style (Js.string "background-color")
(Js.Unsafe.get this##colors this##nextColor);
(Js.Unsafe.coerce Ext_util_Region.static)##prototype##nextColor <-
(Js.Unsafe.coerce Ext_util_Region.static)##prototype##nextColor + 1;
this##highlightEl <- Ext.instance##getBody()##createChild({|
style = style
|},
Js.undefined,
Js.undefined);
if this##nextColor >= this##colors##length then begin
this##nextColor <- 0;
end;
end else begin
ignore (this##highlightEl##setStyle(style));
end);
hide = Js.wrap_meth_callback (fun this () ->
if Js.Optdef.test (Js.Unsafe.coerce this)##highlightEl then begin
this##highlightEl##setStyle({|
display = Js.string "none";
|});
end);
|},
ExtUtils.undef);
let constrainedWin =
Ext.instance##create(Js.def (Js.string "Ext.Window"), Js.def {|
title = Js.string "Constrained Window";
width = 200;
height = 100;
Constraining will pull the Window leftwards so that it 's within the
* parent Window
* parent Window *)
x = 1000;
y = 20;
constrain = Js._true;
layout = Js.string "fit";
items = {|
border = Js._false;
|};
|}) in
let constrainedWin2 =
Ext.instance##create(Js.def (Js.string "Ext.Window"), Js.def {|
title = Js.string "Header-Constrained Win";
width = 200;
height = 100;
x = 120;
y = 120;
constrainHeader = Js._true;
layout = Js.string "fit";
items = {|
border = Js._false;
|};
|}) in
let win2 =
Ext.instance##create(Js.def (Js.string "Ext.Window"), Js.def {|
height = 200;
width = 400;
x = 450;
y = 450;
title = Js.string "Constraining Window, plain: true";
closable = Js._false;
plain = Js._true;
layout = Js.string "fit";
items = Js.array [|
Js.Unsafe.inject constrainedWin;
Js.Unsafe.inject constrainedWin2;
Js.Unsafe.inject {|
border = Js._false;
|};
|];
|}) in
win2##show();
constrainedWin##show();
constrainedWin2##show();
Ext.instance##create(Js.def (Js.string "Ext.Window"), Js.def {|
title = Js.string "Left Header, plain: true";
width = 400;
height = 200;
x = 10;
y = 200;
plain = Js._true;
headerPosition = Js.string "left";
layout = Js.string "fit";
items = {|
border = Js._false;
|};
|})##show();
Ext.instance##create(Js.def (Js.string "Ext.Window"), Js.def {|
title = Js.string "Right Header, plain: true";
width = 400;
height = 200;
x = 450;
y = 200;
headerPosition = Js.string "right";
layout = Js.string "fit";
items = {|
border = Js._false;
|};
|})##show();
Ext.instance##create(Js.def (Js.string "Ext.Window"), Js.def {|
title = Js.string "Bottom Header, plain: true";
width = 400;
height = 200;
x = 10;
y = 450;
plain = true;
headerPosition = Js.string "bottom";
layout = Js.string "fit";
items = {|
border = Js._false;
|};
|})##show();
),
ExtUtils.undef,
ExtUtils.undef)
| |
db4fefc371689e8c4eb904223ea231f8370655d4bf25a479b3fea7601c2c98b7 | metawilm/cl-python | habitat.lisp | -*- Mode : LISP ; Syntax : COMMON - LISP ; Package : ; : PY - AST - USER - READTABLE -*-
;;
This software is Copyright ( c ) Franz Inc. and .
Franz Inc. and grant you the rights to
;; distribute and use this software as governed by the terms
of the Lisp Lesser GNU Public License
;; (),
;; known as the LLGPL.
;;;; Habitat: "Where the snakes live"
(in-package :clpython)
(in-syntax *user-readtable*)
(defclass habitat ()
((stdin :initform nil :initarg :stdin :accessor %habitat-stdin)
(stdout :initform nil :initarg :stdout :accessor %habitat-stdout)
(stderr :initform nil :initarg :stderr :accessor %habitat-stderr)
(loaded-mods :initform () :initarg :loaded-mods :accessor habitat-loaded-mods)
(cmd-line-args :initform () :initarg :cmd-line-args :accessor %habitat-cmd-line-args)
(search-paths :initform (make-py-list-from-list (list ".")) :accessor habitat-search-paths)
(module-globals :initform (make-eq-hash-table) :reader habitat-module-globals)
(exitfunc :initform nil :accessor habitat-exitfunc))
(:documentation "Python execution context"))
(defmethod print-object ((habitat habitat) stream)
(with-slots (stdin stdout stderr loaded-mods cmd-line-args search-paths)
habitat
(print-unreadable-object (habitat stream :type t :identity t)
(format stream "stdin=~A stdout=~A stderr=~A #loaded-modules=~A cmd-line-args=~A search-paths=~S"
stdin stdout stderr (length loaded-mods) cmd-line-args search-paths))))
(defgeneric habitat-stdin (habitat))
(defmethod habitat-stdin ((x habitat))
(or (%habitat-stdin x) *standard-input*))
(defgeneric (setf habitat-stdin) (val habitat))
(defmethod (setf habitat-stdin) (val (x habitat))
(setf (%habitat-stdin x) val))
(defgeneric habitat-stdout (habitat))
(defmethod habitat-stdout ((x habitat))
(or (%habitat-stdout x) *standard-output*))
(defgeneric (setf habitat-stdout) (val habitat))
(defmethod (setf habitat-stdout) (val (x habitat))
(setf (%habitat-stdout x) val))
(defgeneric (setf habitat-stderr) (val habitat))
(defgeneric habitat-stderr (habitat))
(defmethod habitat-stderr ((x habitat))
(or (%habitat-stderr x) *error-output*))
(defmethod (setf habitat-stderr) (val (x habitat))
(setf (%habitat-stderr x) val))
(defgeneric (setf habitat-cmd-line-args) (val habitat))
(defmethod (setf habitat-cmd-line-args) (val (x habitat))
(let ((old-val (%habitat-cmd-line-args x))
(new-val (typecase val
(string (py-string.split val " "))
(list (make-py-list-from-list val))
(t val))))
(unless (equalp old-val new-val)
(warn "Changing habitat command-line-args for ~A~%from:~% ~S~%to:~% ~S"
x old-val new-val))
(setf (%habitat-cmd-line-args x) new-val)))
(defgeneric habitat-cmd-line-args (habitat))
(defmethod habitat-cmd-line-args ((x habitat))
(or (%habitat-cmd-line-args x)
(make-py-list-from-list '("???.py"))))
(defun make-habitat (&rest options)
(apply #'make-instance 'habitat options))
(defun get-loaded-module (&key src-pathname bin-pathname
src-file-write-date bin-file-write-date
habitat)
(check-type habitat habitat)
(loop named search
for m in (habitat-loaded-mods habitat)
when (and (or (null src-pathname)
(pathname-considered-equal (module-src-pathname m) src-pathname))
(or (null bin-pathname)
(pathname-considered-equal (module-bin-pathname m) bin-pathname))
(or (null src-file-write-date)
(= (module-src-file-write-date m) src-file-write-date))
(or (null bin-file-write-date)
(= (module-bin-file-write-date m) bin-file-write-date)))
return m))
(defun get-sys.modules ()
(or (builtin-module-attribute 'sys "modules")
(error "Cannot access builtin module 'sys' or its field 'sys.modules'.")))
(defun add-loaded-module (module habitat)
(check-type module module)
(check-type habitat habitat)
(remove-loaded-module module habitat)
(push module (habitat-loaded-mods habitat))
(with-py-dict
(setf (gethash (module-name module) (get-sys.modules)) module)))
(defun remove-loaded-module (module habitat)
(setf (habitat-loaded-mods habitat)
(remove (module-bin-pathname module) (habitat-loaded-mods habitat)
:key #'module-bin-pathname
:test #'pathname-considered-equal))
(with-py-dict
(remhash (module-name module) (get-sys.modules))))
(defun pathname-considered-equal (x y)
(check-type x pathname)
(check-type y pathname)
(if (and (careful-probe-file x)
(careful-probe-file y))
(equal (truename x) (truename y))
(string-equal (namestring x) (namestring y))))
| null | https://raw.githubusercontent.com/metawilm/cl-python/bce7f80b0c67d3c9f514556f2d14d098efecdde8/runtime/habitat.lisp | lisp | Syntax : COMMON - LISP ; Package : ; : PY - AST - USER - READTABLE -*-
distribute and use this software as governed by the terms
(),
known as the LLGPL.
Habitat: "Where the snakes live" | This software is Copyright ( c ) Franz Inc. and .
Franz Inc. and grant you the rights to
of the Lisp Lesser GNU Public License
(in-package :clpython)
(in-syntax *user-readtable*)
(defclass habitat ()
((stdin :initform nil :initarg :stdin :accessor %habitat-stdin)
(stdout :initform nil :initarg :stdout :accessor %habitat-stdout)
(stderr :initform nil :initarg :stderr :accessor %habitat-stderr)
(loaded-mods :initform () :initarg :loaded-mods :accessor habitat-loaded-mods)
(cmd-line-args :initform () :initarg :cmd-line-args :accessor %habitat-cmd-line-args)
(search-paths :initform (make-py-list-from-list (list ".")) :accessor habitat-search-paths)
(module-globals :initform (make-eq-hash-table) :reader habitat-module-globals)
(exitfunc :initform nil :accessor habitat-exitfunc))
(:documentation "Python execution context"))
(defmethod print-object ((habitat habitat) stream)
(with-slots (stdin stdout stderr loaded-mods cmd-line-args search-paths)
habitat
(print-unreadable-object (habitat stream :type t :identity t)
(format stream "stdin=~A stdout=~A stderr=~A #loaded-modules=~A cmd-line-args=~A search-paths=~S"
stdin stdout stderr (length loaded-mods) cmd-line-args search-paths))))
(defgeneric habitat-stdin (habitat))
(defmethod habitat-stdin ((x habitat))
(or (%habitat-stdin x) *standard-input*))
(defgeneric (setf habitat-stdin) (val habitat))
(defmethod (setf habitat-stdin) (val (x habitat))
(setf (%habitat-stdin x) val))
(defgeneric habitat-stdout (habitat))
(defmethod habitat-stdout ((x habitat))
(or (%habitat-stdout x) *standard-output*))
(defgeneric (setf habitat-stdout) (val habitat))
(defmethod (setf habitat-stdout) (val (x habitat))
(setf (%habitat-stdout x) val))
(defgeneric (setf habitat-stderr) (val habitat))
(defgeneric habitat-stderr (habitat))
(defmethod habitat-stderr ((x habitat))
(or (%habitat-stderr x) *error-output*))
(defmethod (setf habitat-stderr) (val (x habitat))
(setf (%habitat-stderr x) val))
(defgeneric (setf habitat-cmd-line-args) (val habitat))
(defmethod (setf habitat-cmd-line-args) (val (x habitat))
(let ((old-val (%habitat-cmd-line-args x))
(new-val (typecase val
(string (py-string.split val " "))
(list (make-py-list-from-list val))
(t val))))
(unless (equalp old-val new-val)
(warn "Changing habitat command-line-args for ~A~%from:~% ~S~%to:~% ~S"
x old-val new-val))
(setf (%habitat-cmd-line-args x) new-val)))
(defgeneric habitat-cmd-line-args (habitat))
(defmethod habitat-cmd-line-args ((x habitat))
(or (%habitat-cmd-line-args x)
(make-py-list-from-list '("???.py"))))
(defun make-habitat (&rest options)
(apply #'make-instance 'habitat options))
(defun get-loaded-module (&key src-pathname bin-pathname
src-file-write-date bin-file-write-date
habitat)
(check-type habitat habitat)
(loop named search
for m in (habitat-loaded-mods habitat)
when (and (or (null src-pathname)
(pathname-considered-equal (module-src-pathname m) src-pathname))
(or (null bin-pathname)
(pathname-considered-equal (module-bin-pathname m) bin-pathname))
(or (null src-file-write-date)
(= (module-src-file-write-date m) src-file-write-date))
(or (null bin-file-write-date)
(= (module-bin-file-write-date m) bin-file-write-date)))
return m))
(defun get-sys.modules ()
(or (builtin-module-attribute 'sys "modules")
(error "Cannot access builtin module 'sys' or its field 'sys.modules'.")))
(defun add-loaded-module (module habitat)
(check-type module module)
(check-type habitat habitat)
(remove-loaded-module module habitat)
(push module (habitat-loaded-mods habitat))
(with-py-dict
(setf (gethash (module-name module) (get-sys.modules)) module)))
(defun remove-loaded-module (module habitat)
(setf (habitat-loaded-mods habitat)
(remove (module-bin-pathname module) (habitat-loaded-mods habitat)
:key #'module-bin-pathname
:test #'pathname-considered-equal))
(with-py-dict
(remhash (module-name module) (get-sys.modules))))
(defun pathname-considered-equal (x y)
(check-type x pathname)
(check-type y pathname)
(if (and (careful-probe-file x)
(careful-probe-file y))
(equal (truename x) (truename y))
(string-equal (namestring x) (namestring y))))
|
881338beb946c0ed78b04d55e1d2894ad3daf6a58fa882d32ff043ab1f8f6fdb | BramvanVeenschoten1/qtt | Termination.hs | module Termination where
import Data.Set
import Data.Map
import Data.List
import Data.Maybe
import Control.Monad
import Control.Applicative hiding (Const)
import qualified Core as C
import Core hiding (Inductive,Fixpoint)
import Elaborator
import Elab
import Utils
import Normalization
import Substitution
import Parser
import Multiplicity
import Lexer(Loc)
import Prettyprint
import Debug.Trace
{-
nested function calls will be handled in getRecursiveCalls
-}
data Subdata
= Recursive Int -- a recursive occurrence and its number
| Seed Int -- an argument to the function and its number
| Sub Int -- a term smaller than an argument and the number of said argument
| Other -- a variable that is neither recursive nor smaller
-- information on which debruijn indices are possibly recursive arguments
-- with regular inference, all top-level lambda arguments are possibly recursive
-- with nested inference, the recursive argument is already known
data RecArg
= Past
| Unknown Int
| Known Int Int Int
argSucc :: RecArg -> RecArg
argSucc Past = Past
argSucc (Unknown x) = Unknown (x + 1)
argSucc (Known x recpno unipno) = Known (x + 1) recpno unipno
isRecArg :: RecArg -> Subdata
isRecArg Past = Other
isRecArg (Unknown x) = Seed x
isRecArg (Known x recpno unipno)
| x == recpno - unipno = Seed recpno
| otherwise = Other
, [ ( caller , ) ]
{-
returns a list of recursive calls, with for each callee argument whether it is a subdatum and
which caller argument it is derived from if so
-}
getRecursiveCalls :: Objects -> Context -> Term -> [RecCall]
getRecursiveCalls glob ctx = getRecCalls ctx (fmap Recursive [0 .. length ctx - 1]) (Unknown 0) where
-- find if a term is a seed or smaller than a seed, returns argument number if so
isSeed :: Context -> [Subdata] -> Term -> Subdata
isSeed ctx subs t = case whd glob ctx t of
Var n -> subs !! n
App f x -> isSeed ctx subs f
_ -> Other
-- check whether some match branches are all subterms of some seed
isCaseSmaller :: [Maybe Int] -> Maybe Int
isCaseSmaller (Just n : xs)
| all (\x -> (==) (Just n) x) xs = Just n
isCaseSmaller _ = Nothing
-- find if a term is smaller and if so, return argument number
-- case branches need to have lambda's stripped
isSmaller :: Context -> [Subdata] -> Term -> Maybe Int
isSmaller ctx subs t = case whd glob ctx t of
Var n -> case subs !! n of
Sub m -> Just m
_ -> Nothing
App f x -> isSmaller ctx subs f
Case dat -> isCaseSmaller (fmap (isSmaller ctx subs . snd) (branches dat))
_ -> Nothing
-- check whether a term returns an inductive type
returnsInductive ctx ta = case whd glob ctx ta of
Pi _ name ta tb -> returnsInductive (Hypothesis name ta Nothing : ctx) tb
App fun _ -> returnsInductive ctx fun
Const _ (IndRef _ _ _) -> True
_ -> False
-- traverse the body of a fixpoint function and gather recursive path information
getRecCalls :: Context -> [Subdata] -> RecArg -> Term -> [RecCall]
getRecCalls ctx subs argc t = case whd glob ctx t of
Var n -> case subs !! n of
Recursive defno -> [(defno,[])]
_ -> []
App (Const _ (FixRef obj_id defno recparamno height uniparamno)) args -> let
(left_args,right_args) = Data.List.splitAt uniparamno args
left_calls = concatMap (getRecCalls ctx subs Past) left_args
right_calls = concatMap (getRecCalls ctx subs Past) right_args
fix_bodies = fmap fixBody (fromJust (Data.Map.lookup obj_id (globalFix glob)))
dummy_bodies = fmap (substWithDummy obj_id) fix_bodies
applied_bodies = fmap (\fun -> App fun left_args) dummy_bodies
expand = Data.List.concatMap (getRecCalls ctx subs (Known 0 recparamno uniparamno)) applied_bodies
traceExpand = trace (
show (fmap (showTerm ctx) dummy_bodies) ++ "\n" ++
show (fmap (showTerm ctx . whd glob ctx) applied_bodies) ++ "\n" ++
show expand ++ "\n") expand
in if Prelude.null left_calls
then right_calls
else traceExpand ++ right_calls
App fun args -> let
arg_calls = concatMap (getRecCalls ctx subs Past) args
in case fun of
Var n -> case subs !! n of
Recursive defno -> let
small_args = fmap (isSmaller ctx subs) args
in (defno, small_args) : arg_calls
_ -> arg_calls
_ -> arg_calls
Lam _ name ta b -> getRecCalls (Hypothesis name ta Nothing : ctx) (isRecArg argc : subs) (argSucc argc) b
Let name ta a b -> getRecCalls (Hypothesis name ta (Just a) : ctx) (isRecArg argc : subs) (argSucc argc) b
Pi _ name ta tb -> getRecCalls (Hypothesis name ta Nothing : ctx) (Other : subs) Past tb
Case distinct -> let
(obj_id,defno) = case whd glob ctx (elimType distinct) of
App (Const _ (IndRef obj_id defno _)) _ -> (obj_id,defno)
Const _ (IndRef obj_id defno _) -> (obj_id,defno)
x -> error (showTerm ctx x)
block = fromJust (Data.Map.lookup obj_id (globalInd glob))
def = block !! defno
ctor_arities = fmap (\(_,x,_) -> x) (introRules def)
elimineeIsSeed = isSeed ctx subs (eliminee distinct)
unrollArgs :: Context -> [Subdata] -> Int -> Term -> [RecCall]
unrollArgs ctx subs 0 branch = getRecCalls ctx subs argc branch
unrollArgs ctx subs m (Lam _ name ta b) = let
cont sub = unrollArgs (Hypothesis name ta Nothing : ctx) (sub : subs) (m - 1) b
in case elimineeIsSeed of
Other -> cont Other
Sub k ->
if returnsInductive ctx ta
then cont (Sub k)
else cont Other
Seed k ->
if returnsInductive ctx ta
then cont (Sub k)
else cont Other
regular_calls = concat (zipWith (unrollArgs ctx subs) ctor_arities (fmap snd (branches distinct)))
in regular_calls
_ -> []
Given the recursive calls , check the totality of a fixpoint by computing recursive parameters of the mutually recursive functions .
a fixpoint is guarded if in each recursive call , the recursive parameter of the callee is smaller than the
recursive parameter of the caller . What exactly constitutes a smaller argument is defined in getRecursiveCalls .
Finding the parameters is done by lazily traversing all possible configurations of recursive parameters ,
then returning the first that is completely guarded , if it exists .
Given the recursive calls, check the totality of a fixpoint by computing recursive parameters of the mutually recursive functions.
a fixpoint is guarded if in each recursive call, the recursive parameter of the callee is smaller than the
recursive parameter of the caller. What exactly constitutes a smaller argument is defined in getRecursiveCalls.
Finding the parameters is done by lazily traversing all possible configurations of recursive parameters,
then returning the first that is completely guarded, if it exists.
-}
findRecparams :: [[RecCall]] -> Maybe [Int]
findRecparams rec_calls = let
defcount = length rec_calls
compute the possibly recursive parameters for the current definition .
The candidates are constrained by 3 factors :
- previous definitions in the same fixpoint will have been assigned a recursive parameter ,
so only the argument that guards these calls is allowed
- The nth parameter passed to the recursive call is only guarded if it is
smaller than the nth parameter of the function itself
- Other definitions are not yet constrained , but serve as heuristic .
so for each argument , if a term smaller than it is passed to a later function ,
it becomes a candidate .
compute the possibly recursive parameters for the current definition.
The candidates are constrained by 3 factors:
- previous definitions in the same fixpoint will have been assigned a recursive parameter,
so only the argument that guards these calls is allowed
- The nth parameter passed to the recursive call is only guarded if it is
smaller than the nth parameter of the function itself
- Other definitions are not yet constrained, but serve as heuristic.
so for each argument, if a term smaller than it is passed to a later function,
it becomes a candidate.
-}
allowed_args :: Int -> [RecCall] -> [Int] -> [Int]
allowed_args defno calls recparams = let
inter :: RecCall -> [Int] -> [Int]
inter (defno',args) acc = let
allowed :: [Int]
allowed
-- in calls to self, caller and callee recparamno have to be the same
| defno == defno' = [x | (x,y) <- zip [0..] args, Just x == y]
| otherwise = case nth defno' recparams of
-- in calls to previously constrained functions,
-- only the caller argument that the callees' recursive argument is derived from is allowed
Just n -> maybe [] (:[]) (join (nth n args))
-- other calls are only limited to smaller arguments
Nothing -> Data.List.nub (catMaybes args)
we use a special intersection that works with an infinite list as acc
in [x | x <- allowed, elem x acc]
in Data.List.foldr inter [0..] calls
-- check recursive calls to defno in all previous definitions
checkCalls :: Int -> Int -> [Int] -> Maybe ()
checkCalls callee callee_recparamno recparams = zipWithM_ (mapM_ . checkCall) recparams rec_calls where
--checkCall :: Int -> [RecCall] -> Maybe ()
checkCall caller_paramno (defno,args)
-- only calls to defno need to be checked, the argument in the given callee_recparamno position must be
-- derived from the recursive argument of the caller
| callee == defno = case join (nth callee_recparamno args) of
Just argno -> if caller_paramno == argno then pure () else Nothing
Nothing -> Nothing
| otherwise = pure ()
-- given the recursive calls, find an assignment of recursive parameters to definitions such that
the fixpoint is guarded
solve :: Int -> [Int] -> Maybe [Int]
solve defno recparams
| defno >= defcount = pure recparams
| otherwise = let
-- with the given constraints, get the possibly recursive arguments
allowed = allowed_args defno (rec_calls !! defno) recparams
-- for a given recursive argument, check the guardedness of its calls in previous definitions,
-- then continue with the other definitions
pick :: Int -> Maybe [Int]
pick x = checkCalls defno x recparams *> solve (defno + 1) (recparams ++ [x])
-- try every possibly allowed argument if necessary
in Data.List.foldr (<|>) Nothing (fmap pick allowed)
in solve 0 [] | null | https://raw.githubusercontent.com/BramvanVeenschoten1/qtt/ece216ac2e6126b25e0894e93bd146a838b084b3/lamcvii/Termination.hs | haskell |
nested function calls will be handled in getRecursiveCalls
a recursive occurrence and its number
an argument to the function and its number
a term smaller than an argument and the number of said argument
a variable that is neither recursive nor smaller
information on which debruijn indices are possibly recursive arguments
with regular inference, all top-level lambda arguments are possibly recursive
with nested inference, the recursive argument is already known
returns a list of recursive calls, with for each callee argument whether it is a subdatum and
which caller argument it is derived from if so
find if a term is a seed or smaller than a seed, returns argument number if so
check whether some match branches are all subterms of some seed
find if a term is smaller and if so, return argument number
case branches need to have lambda's stripped
check whether a term returns an inductive type
traverse the body of a fixpoint function and gather recursive path information
in calls to self, caller and callee recparamno have to be the same
in calls to previously constrained functions,
only the caller argument that the callees' recursive argument is derived from is allowed
other calls are only limited to smaller arguments
check recursive calls to defno in all previous definitions
checkCall :: Int -> [RecCall] -> Maybe ()
only calls to defno need to be checked, the argument in the given callee_recparamno position must be
derived from the recursive argument of the caller
given the recursive calls, find an assignment of recursive parameters to definitions such that
with the given constraints, get the possibly recursive arguments
for a given recursive argument, check the guardedness of its calls in previous definitions,
then continue with the other definitions
try every possibly allowed argument if necessary
| module Termination where
import Data.Set
import Data.Map
import Data.List
import Data.Maybe
import Control.Monad
import Control.Applicative hiding (Const)
import qualified Core as C
import Core hiding (Inductive,Fixpoint)
import Elaborator
import Elab
import Utils
import Normalization
import Substitution
import Parser
import Multiplicity
import Lexer(Loc)
import Prettyprint
import Debug.Trace
data Subdata
data RecArg
= Past
| Unknown Int
| Known Int Int Int
argSucc :: RecArg -> RecArg
argSucc Past = Past
argSucc (Unknown x) = Unknown (x + 1)
argSucc (Known x recpno unipno) = Known (x + 1) recpno unipno
isRecArg :: RecArg -> Subdata
isRecArg Past = Other
isRecArg (Unknown x) = Seed x
isRecArg (Known x recpno unipno)
| x == recpno - unipno = Seed recpno
| otherwise = Other
, [ ( caller , ) ]
getRecursiveCalls :: Objects -> Context -> Term -> [RecCall]
getRecursiveCalls glob ctx = getRecCalls ctx (fmap Recursive [0 .. length ctx - 1]) (Unknown 0) where
isSeed :: Context -> [Subdata] -> Term -> Subdata
isSeed ctx subs t = case whd glob ctx t of
Var n -> subs !! n
App f x -> isSeed ctx subs f
_ -> Other
isCaseSmaller :: [Maybe Int] -> Maybe Int
isCaseSmaller (Just n : xs)
| all (\x -> (==) (Just n) x) xs = Just n
isCaseSmaller _ = Nothing
isSmaller :: Context -> [Subdata] -> Term -> Maybe Int
isSmaller ctx subs t = case whd glob ctx t of
Var n -> case subs !! n of
Sub m -> Just m
_ -> Nothing
App f x -> isSmaller ctx subs f
Case dat -> isCaseSmaller (fmap (isSmaller ctx subs . snd) (branches dat))
_ -> Nothing
returnsInductive ctx ta = case whd glob ctx ta of
Pi _ name ta tb -> returnsInductive (Hypothesis name ta Nothing : ctx) tb
App fun _ -> returnsInductive ctx fun
Const _ (IndRef _ _ _) -> True
_ -> False
getRecCalls :: Context -> [Subdata] -> RecArg -> Term -> [RecCall]
getRecCalls ctx subs argc t = case whd glob ctx t of
Var n -> case subs !! n of
Recursive defno -> [(defno,[])]
_ -> []
App (Const _ (FixRef obj_id defno recparamno height uniparamno)) args -> let
(left_args,right_args) = Data.List.splitAt uniparamno args
left_calls = concatMap (getRecCalls ctx subs Past) left_args
right_calls = concatMap (getRecCalls ctx subs Past) right_args
fix_bodies = fmap fixBody (fromJust (Data.Map.lookup obj_id (globalFix glob)))
dummy_bodies = fmap (substWithDummy obj_id) fix_bodies
applied_bodies = fmap (\fun -> App fun left_args) dummy_bodies
expand = Data.List.concatMap (getRecCalls ctx subs (Known 0 recparamno uniparamno)) applied_bodies
traceExpand = trace (
show (fmap (showTerm ctx) dummy_bodies) ++ "\n" ++
show (fmap (showTerm ctx . whd glob ctx) applied_bodies) ++ "\n" ++
show expand ++ "\n") expand
in if Prelude.null left_calls
then right_calls
else traceExpand ++ right_calls
App fun args -> let
arg_calls = concatMap (getRecCalls ctx subs Past) args
in case fun of
Var n -> case subs !! n of
Recursive defno -> let
small_args = fmap (isSmaller ctx subs) args
in (defno, small_args) : arg_calls
_ -> arg_calls
_ -> arg_calls
Lam _ name ta b -> getRecCalls (Hypothesis name ta Nothing : ctx) (isRecArg argc : subs) (argSucc argc) b
Let name ta a b -> getRecCalls (Hypothesis name ta (Just a) : ctx) (isRecArg argc : subs) (argSucc argc) b
Pi _ name ta tb -> getRecCalls (Hypothesis name ta Nothing : ctx) (Other : subs) Past tb
Case distinct -> let
(obj_id,defno) = case whd glob ctx (elimType distinct) of
App (Const _ (IndRef obj_id defno _)) _ -> (obj_id,defno)
Const _ (IndRef obj_id defno _) -> (obj_id,defno)
x -> error (showTerm ctx x)
block = fromJust (Data.Map.lookup obj_id (globalInd glob))
def = block !! defno
ctor_arities = fmap (\(_,x,_) -> x) (introRules def)
elimineeIsSeed = isSeed ctx subs (eliminee distinct)
unrollArgs :: Context -> [Subdata] -> Int -> Term -> [RecCall]
unrollArgs ctx subs 0 branch = getRecCalls ctx subs argc branch
unrollArgs ctx subs m (Lam _ name ta b) = let
cont sub = unrollArgs (Hypothesis name ta Nothing : ctx) (sub : subs) (m - 1) b
in case elimineeIsSeed of
Other -> cont Other
Sub k ->
if returnsInductive ctx ta
then cont (Sub k)
else cont Other
Seed k ->
if returnsInductive ctx ta
then cont (Sub k)
else cont Other
regular_calls = concat (zipWith (unrollArgs ctx subs) ctor_arities (fmap snd (branches distinct)))
in regular_calls
_ -> []
Given the recursive calls , check the totality of a fixpoint by computing recursive parameters of the mutually recursive functions .
a fixpoint is guarded if in each recursive call , the recursive parameter of the callee is smaller than the
recursive parameter of the caller . What exactly constitutes a smaller argument is defined in getRecursiveCalls .
Finding the parameters is done by lazily traversing all possible configurations of recursive parameters ,
then returning the first that is completely guarded , if it exists .
Given the recursive calls, check the totality of a fixpoint by computing recursive parameters of the mutually recursive functions.
a fixpoint is guarded if in each recursive call, the recursive parameter of the callee is smaller than the
recursive parameter of the caller. What exactly constitutes a smaller argument is defined in getRecursiveCalls.
Finding the parameters is done by lazily traversing all possible configurations of recursive parameters,
then returning the first that is completely guarded, if it exists.
-}
findRecparams :: [[RecCall]] -> Maybe [Int]
findRecparams rec_calls = let
defcount = length rec_calls
compute the possibly recursive parameters for the current definition .
The candidates are constrained by 3 factors :
- previous definitions in the same fixpoint will have been assigned a recursive parameter ,
so only the argument that guards these calls is allowed
- The nth parameter passed to the recursive call is only guarded if it is
smaller than the nth parameter of the function itself
- Other definitions are not yet constrained , but serve as heuristic .
so for each argument , if a term smaller than it is passed to a later function ,
it becomes a candidate .
compute the possibly recursive parameters for the current definition.
The candidates are constrained by 3 factors:
- previous definitions in the same fixpoint will have been assigned a recursive parameter,
so only the argument that guards these calls is allowed
- The nth parameter passed to the recursive call is only guarded if it is
smaller than the nth parameter of the function itself
- Other definitions are not yet constrained, but serve as heuristic.
so for each argument, if a term smaller than it is passed to a later function,
it becomes a candidate.
-}
allowed_args :: Int -> [RecCall] -> [Int] -> [Int]
allowed_args defno calls recparams = let
inter :: RecCall -> [Int] -> [Int]
inter (defno',args) acc = let
allowed :: [Int]
allowed
| defno == defno' = [x | (x,y) <- zip [0..] args, Just x == y]
| otherwise = case nth defno' recparams of
Just n -> maybe [] (:[]) (join (nth n args))
Nothing -> Data.List.nub (catMaybes args)
we use a special intersection that works with an infinite list as acc
in [x | x <- allowed, elem x acc]
in Data.List.foldr inter [0..] calls
checkCalls :: Int -> Int -> [Int] -> Maybe ()
checkCalls callee callee_recparamno recparams = zipWithM_ (mapM_ . checkCall) recparams rec_calls where
checkCall caller_paramno (defno,args)
| callee == defno = case join (nth callee_recparamno args) of
Just argno -> if caller_paramno == argno then pure () else Nothing
Nothing -> Nothing
| otherwise = pure ()
the fixpoint is guarded
solve :: Int -> [Int] -> Maybe [Int]
solve defno recparams
| defno >= defcount = pure recparams
| otherwise = let
allowed = allowed_args defno (rec_calls !! defno) recparams
pick :: Int -> Maybe [Int]
pick x = checkCalls defno x recparams *> solve (defno + 1) (recparams ++ [x])
in Data.List.foldr (<|>) Nothing (fmap pick allowed)
in solve 0 [] |
5e5c403c2476406231cb612f395b7cee7bd4e59623cf3d8ab379de2bc4eb4315 | tisnik/clojure-examples | core.clj | ;
Druha varianta velmi jednoducheho IRC :
bot nyni odpovida na zpravy , ktere urceny
;
Autor :
;
(ns ircbot2.core
(:gen-class))
(require '[irclj.core :as irc])
(def configuration
"Datova struktura obsahujici informace o pripojeni na IRC server."
vsem dostupny IRC server
:port 6667 ; vychozi port
kanal , ktery je urceny pro testovani
( mj . )
tuto cast , nehadejte se
prosim o stejny :)
(defn message-to-channel?
"Test, zda se jedna o zpravu poslanou na kanal."
[message]
(.startsWith (:target message) "#"))
(defn message-for-me?
"Vrati logickou 'pravdu' v pripade, ze se byla prijata
prima zprava ci privatni zprava."
[my-name message]
privatni zprava
(.startsWith (:text message) (str my-name ":")); prima zprava
))
(defn create-reply
"Vytvoreni datove struktury popisujici odpoved."
[incoming-message]
rozhodnuti , zda se ma odpoved poslat zpet do kanalu nebo na soukromy chat
pokud primo
- > posleme odpoved zpet na kanal
v posleme zpravu primo uzivateli
cilem bude prezdivka uzivatele
(assoc incoming-message :target (:nick incoming-message))))
(defn on-incoming-message
"Callback funkce volana pri prichodu zpravy na kanal ci na soukromy chat."
[connection incoming-message]
rozdeleni zpravy na jednotlive prvky
(let [{text :text
target :target
nick :nick
host :host
command :command} incoming-message]
zalogujeme , co se prave stalo
(println "Received message from" nick "to" target ":" text "(" host command ")")
test , zda je zprava pro
(if (message-for-me? (:nick configuration) incoming-message)
vytvorime vhodnou odpoved
(irc/reply connection (create-reply incoming-message) (str "hello " nick)))))
(defn start-irc-bot
"Funkce, ktera zajisti spusteni IRC bota a jeho pripojeni na zvoleny server a kanal(y)."
[configuration callback-function]
(println "Connecting to" (:server configuration) "port" (:port configuration))
; vlastni pripojeni na server
(let [connection (irc/connect (:server configuration)
(:port configuration)
(:nick configuration)
:callbacks {:privmsg callback-function})]
(println "Connected, joining to channel" (:channel configuration))
pripojeni ke zvolenemu
(irc/join connection (:channel configuration))
ok :)
(println "Connected...")))
(defn -main
"Vstupni bod do teto aplikace."
[& args]
(start-irc-bot configuration on-incoming-message))
| null | https://raw.githubusercontent.com/tisnik/clojure-examples/984af4a3e20d994b4f4989678ee1330e409fdae3/ircbot2/src/ircbot2/core.clj | clojure |
vychozi port
prima zprava
vlastni pripojeni na server | Druha varianta velmi jednoducheho IRC :
bot nyni odpovida na zpravy , ktere urceny
Autor :
(ns ircbot2.core
(:gen-class))
(require '[irclj.core :as irc])
(def configuration
"Datova struktura obsahujici informace o pripojeni na IRC server."
vsem dostupny IRC server
kanal , ktery je urceny pro testovani
( mj . )
tuto cast , nehadejte se
prosim o stejny :)
(defn message-to-channel?
"Test, zda se jedna o zpravu poslanou na kanal."
[message]
(.startsWith (:target message) "#"))
(defn message-for-me?
"Vrati logickou 'pravdu' v pripade, ze se byla prijata
prima zprava ci privatni zprava."
[my-name message]
privatni zprava
))
(defn create-reply
"Vytvoreni datove struktury popisujici odpoved."
[incoming-message]
rozhodnuti , zda se ma odpoved poslat zpet do kanalu nebo na soukromy chat
pokud primo
- > posleme odpoved zpet na kanal
v posleme zpravu primo uzivateli
cilem bude prezdivka uzivatele
(assoc incoming-message :target (:nick incoming-message))))
(defn on-incoming-message
"Callback funkce volana pri prichodu zpravy na kanal ci na soukromy chat."
[connection incoming-message]
rozdeleni zpravy na jednotlive prvky
(let [{text :text
target :target
nick :nick
host :host
command :command} incoming-message]
zalogujeme , co se prave stalo
(println "Received message from" nick "to" target ":" text "(" host command ")")
test , zda je zprava pro
(if (message-for-me? (:nick configuration) incoming-message)
vytvorime vhodnou odpoved
(irc/reply connection (create-reply incoming-message) (str "hello " nick)))))
(defn start-irc-bot
"Funkce, ktera zajisti spusteni IRC bota a jeho pripojeni na zvoleny server a kanal(y)."
[configuration callback-function]
(println "Connecting to" (:server configuration) "port" (:port configuration))
(let [connection (irc/connect (:server configuration)
(:port configuration)
(:nick configuration)
:callbacks {:privmsg callback-function})]
(println "Connected, joining to channel" (:channel configuration))
pripojeni ke zvolenemu
(irc/join connection (:channel configuration))
ok :)
(println "Connected...")))
(defn -main
"Vstupni bod do teto aplikace."
[& args]
(start-irc-bot configuration on-incoming-message))
|
dafda3a0892afe9e22df03aa3bc7f0154942b757dc8f0350b57e36c792693dff | bobatkey/CS316-2022 | Week02Intro.hs | # OPTIONS_GHC -fwarn - incomplete - patterns #
module Week02Intro where
import Prelude hiding (Maybe, Nothing, Just)
Week 02 ; Lecture 03
MAKING DECISIONS and DEALING WITH FAILURE
MAKING DECISIONS and DEALING WITH FAILURE
-}
-- isMember; using if-then-else
isMember :: Eq a
=> a -> [a] -> Bool
isMember y [] = False
isMember y (x:xs) = if x == y then True else isMember y xs
-- y :: a
-- x :: a
-- xs :: [a]
-- We can't repeat the 'y' twice in the pattern to stand for equality
-- isMember2; using guards
isMember2 :: Eq a
=> a -> [a] -> Bool
isMember2 y [] = False
isMember2 y (x:xs)
| x == y = True
-- | x /= y = isMember2 y xs --- this by itself is not enough to guarantee completeness
| otherwise = isMember2 y xs
isMember3 :: Eq a => a -> [a] -> Bool
isMember3 y [] = False
isMember3 y (x:xs) = (x == y) || isMember3 y xs
isMember4 ; using case
isMember4 :: Eq a => a -> [a] -> Bool
isMember4 y [] = False
isMember4 y (x:xs) =
case x == y of
True -> True
False -> isMember y xs
{-
case x - y of
0 -> True
1 -> True
_ -> isMember y xs
-}
isMember5 :: Ord a => a -> [a] -> Bool
isMember5 y [] = False
isMember5 y (x:xs) =
case compare x y of
EQ -> True
LT -> isMember5 y xs
GT -> isMember5 y xs
-- Trees
data Tree a
= Leaf
| Node (Tree a) a (Tree a)
deriving Show
1
/ \
2 L
/\
L L
/ \
2 L
/\
L L
-}
example = Node (Node Leaf 2 Leaf) 1 Leaf
sortedExample = Node Leaf 1 (Node Leaf 2 Leaf)
isTreeMember :: Ord a => a -> Tree a -> Bool
isTreeMember y (Node l x r) =
{-
if x == y then
True
else if y < x then
isTreeMember y l
else
isTreeMember y r
-}
case compare y x of
EQ -> True
LT -> isTreeMember y l
GT -> isTreeMember y r
isTreeMember y Leaf = False
-- Maybe
data Maybe a
= Nothing
| Just a
deriving Show
exampleKV :: Tree (String,Int)
exampleKV = Node (Node Leaf ("a",1) Leaf) ("b",2) Leaf
-- getKey
Optional < B > getKey(A a , Tree < A , B > t ) throws KeyNotFound
getKey :: Ord a => a -> Tree (a,b) -> Maybe b
getKey k Leaf = Nothing
getKey k (Node l (k', v) r) =
case compare k k' of
EQ -> Just v
LT -> getKey k l
GT -> getKey k r
-- dealing with Failure: reading a list of keys from a tree
getKeys :: Ord a => [a] -> Tree (a,b) -> Maybe [b]
getKeys [] tree = Just []
getKeys (k:ks) tree =
case getKey k tree of
Nothing -> Nothing
Just v ->
case getKeys ks tree of
Nothing -> Nothing
Just vs ->
Just (v:vs)
getKeys0 :: Ord a => [a] -> Tree (a,b) -> [Maybe b]
getKeys0 [] tree = []
getKeys0 (k:ks) tree = getKey k tree : getKeys0 ks tree
getKeys ( getKeys0 ks tree )
catMaybes0 :: [Maybe a] -> Maybe [a]
catMaybes0 list = if isThereANothing list then Nothing else Just (extractJusts list)
extractJusts :: [Maybe a] -> [a]
extractJusts [] = []
extractJusts (Just x:xs) = x : extractJusts xs
extractJusts (Nothing:xs) = extractJusts xs
isThereANothing :: [Maybe a] -> Bool
isThereANothing [] = False
isThereANothing (Nothing : _) = True
isThereANothing (Just _ : xs) = isThereANothing xs
catMaybes :: [Maybe a] -> Maybe [a]
catMaybes [] = Just []
catMaybes (Nothing:_) = Nothing
catMaybes (Just x:xs) =
case catMaybes xs of
Nothing -> Nothing
Just ys -> Just (x:ys)
[ Just 1 , Just 2 , Just 3 ] = = Just [ 1,2,3 ]
[ Nothing , Just 1 , Just 2 ] = = Nothing
[ Just 1 , Nothing , Just 2 ] = = Nothing
{- if (itIsSafe) {
//
do thing that might fail
}
-}
{-
getKeys list tree =
case list of
[] ->
Just []
(k:ks) ->
-- as above
-}
| null | https://raw.githubusercontent.com/bobatkey/CS316-2022/02bba64b6a5674201244c1cf8f5cda49df51100e/lecture-notes/Week02Intro.hs | haskell | isMember; using if-then-else
y :: a
x :: a
xs :: [a]
We can't repeat the 'y' twice in the pattern to stand for equality
isMember2; using guards
| x /= y = isMember2 y xs --- this by itself is not enough to guarantee completeness
case x - y of
0 -> True
1 -> True
_ -> isMember y xs
Trees
if x == y then
True
else if y < x then
isTreeMember y l
else
isTreeMember y r
Maybe
getKey
dealing with Failure: reading a list of keys from a tree
if (itIsSafe) {
//
do thing that might fail
}
getKeys list tree =
case list of
[] ->
Just []
(k:ks) ->
-- as above
| # OPTIONS_GHC -fwarn - incomplete - patterns #
module Week02Intro where
import Prelude hiding (Maybe, Nothing, Just)
Week 02 ; Lecture 03
MAKING DECISIONS and DEALING WITH FAILURE
MAKING DECISIONS and DEALING WITH FAILURE
-}
isMember :: Eq a
=> a -> [a] -> Bool
isMember y [] = False
isMember y (x:xs) = if x == y then True else isMember y xs
isMember2 :: Eq a
=> a -> [a] -> Bool
isMember2 y [] = False
isMember2 y (x:xs)
| x == y = True
| otherwise = isMember2 y xs
isMember3 :: Eq a => a -> [a] -> Bool
isMember3 y [] = False
isMember3 y (x:xs) = (x == y) || isMember3 y xs
isMember4 ; using case
isMember4 :: Eq a => a -> [a] -> Bool
isMember4 y [] = False
isMember4 y (x:xs) =
case x == y of
True -> True
False -> isMember y xs
isMember5 :: Ord a => a -> [a] -> Bool
isMember5 y [] = False
isMember5 y (x:xs) =
case compare x y of
EQ -> True
LT -> isMember5 y xs
GT -> isMember5 y xs
data Tree a
= Leaf
| Node (Tree a) a (Tree a)
deriving Show
1
/ \
2 L
/\
L L
/ \
2 L
/\
L L
-}
example = Node (Node Leaf 2 Leaf) 1 Leaf
sortedExample = Node Leaf 1 (Node Leaf 2 Leaf)
isTreeMember :: Ord a => a -> Tree a -> Bool
isTreeMember y (Node l x r) =
case compare y x of
EQ -> True
LT -> isTreeMember y l
GT -> isTreeMember y r
isTreeMember y Leaf = False
data Maybe a
= Nothing
| Just a
deriving Show
exampleKV :: Tree (String,Int)
exampleKV = Node (Node Leaf ("a",1) Leaf) ("b",2) Leaf
Optional < B > getKey(A a , Tree < A , B > t ) throws KeyNotFound
getKey :: Ord a => a -> Tree (a,b) -> Maybe b
getKey k Leaf = Nothing
getKey k (Node l (k', v) r) =
case compare k k' of
EQ -> Just v
LT -> getKey k l
GT -> getKey k r
getKeys :: Ord a => [a] -> Tree (a,b) -> Maybe [b]
getKeys [] tree = Just []
getKeys (k:ks) tree =
case getKey k tree of
Nothing -> Nothing
Just v ->
case getKeys ks tree of
Nothing -> Nothing
Just vs ->
Just (v:vs)
getKeys0 :: Ord a => [a] -> Tree (a,b) -> [Maybe b]
getKeys0 [] tree = []
getKeys0 (k:ks) tree = getKey k tree : getKeys0 ks tree
getKeys ( getKeys0 ks tree )
catMaybes0 :: [Maybe a] -> Maybe [a]
catMaybes0 list = if isThereANothing list then Nothing else Just (extractJusts list)
extractJusts :: [Maybe a] -> [a]
extractJusts [] = []
extractJusts (Just x:xs) = x : extractJusts xs
extractJusts (Nothing:xs) = extractJusts xs
isThereANothing :: [Maybe a] -> Bool
isThereANothing [] = False
isThereANothing (Nothing : _) = True
isThereANothing (Just _ : xs) = isThereANothing xs
catMaybes :: [Maybe a] -> Maybe [a]
catMaybes [] = Just []
catMaybes (Nothing:_) = Nothing
catMaybes (Just x:xs) =
case catMaybes xs of
Nothing -> Nothing
Just ys -> Just (x:ys)
[ Just 1 , Just 2 , Just 3 ] = = Just [ 1,2,3 ]
[ Nothing , Just 1 , Just 2 ] = = Nothing
[ Just 1 , Nothing , Just 2 ] = = Nothing
|
dc58dc898e3907c5d225c5eddd2a92d515b17bea30e92c2b1c9692e6a50c796b | alakahakai/hackerrank | lists-and-gcd.hs | {-
List and gcd
-and-gcd
-}
import Control.Applicative ((<$>))
import Control.Monad (forM)
import Data.Maybe
newtype Power = Power (Int, Int)
deriving Show
readNumbers :: String -> [Power]
readNumbers s = go [] (map (\x -> read x :: Int) $ words s) where
go ps [] = ps
go ps (x:y:ys) = go (Power (x,y) : ps) ys
listGcd :: [[Power]] -> [Power]
listGcd = foldr1 reduce
reduce :: [Power] -> [Power] -> [Power]
reduce = reduce' [] where
reduce' rs _ [] = rs
reduce' rs [] _ = rs
reduce' rs (x:xs) ys = reduce' (f x ys ++ rs) xs ys where
f x [] = []
f x (y:ys) = case reducePower x y of
Nothing -> f x ys
Just v -> [v]
reducePower :: Power -> Power -> Maybe Power
reducePower (Power (x,y)) (Power (x',y'))
| x == x' && y > y' = Just (Power (x, y'))
| x == x' && y < y' = Just (Power (x, y))
| x == x' && y == y' = Just (Power (x, y))
| otherwise = Nothing
showGcd :: [Power] -> String
sjowGcd [] = []
showGcd [Power (a, b)] = show a ++ " " ++ show b
showGcd ((Power (a, b)):gs) = show a ++ " " ++ show b ++ " " ++ showGcd gs
main :: IO ()
main = do
n <- (\x -> read x :: Int) <$> getLine
ns <- forM [1..n] $ \_ -> do
getLine
putStrLn . showGcd . listGcd $ map readNumbers ns
| null | https://raw.githubusercontent.com/alakahakai/hackerrank/465d17107bbe402daf750651bb57cf092305acf9/fp/lists-and-gcd.hs | haskell |
List and gcd
-and-gcd
|
import Control.Applicative ((<$>))
import Control.Monad (forM)
import Data.Maybe
newtype Power = Power (Int, Int)
deriving Show
readNumbers :: String -> [Power]
readNumbers s = go [] (map (\x -> read x :: Int) $ words s) where
go ps [] = ps
go ps (x:y:ys) = go (Power (x,y) : ps) ys
listGcd :: [[Power]] -> [Power]
listGcd = foldr1 reduce
reduce :: [Power] -> [Power] -> [Power]
reduce = reduce' [] where
reduce' rs _ [] = rs
reduce' rs [] _ = rs
reduce' rs (x:xs) ys = reduce' (f x ys ++ rs) xs ys where
f x [] = []
f x (y:ys) = case reducePower x y of
Nothing -> f x ys
Just v -> [v]
reducePower :: Power -> Power -> Maybe Power
reducePower (Power (x,y)) (Power (x',y'))
| x == x' && y > y' = Just (Power (x, y'))
| x == x' && y < y' = Just (Power (x, y))
| x == x' && y == y' = Just (Power (x, y))
| otherwise = Nothing
showGcd :: [Power] -> String
sjowGcd [] = []
showGcd [Power (a, b)] = show a ++ " " ++ show b
showGcd ((Power (a, b)):gs) = show a ++ " " ++ show b ++ " " ++ showGcd gs
main :: IO ()
main = do
n <- (\x -> read x :: Int) <$> getLine
ns <- forM [1..n] $ \_ -> do
getLine
putStrLn . showGcd . listGcd $ map readNumbers ns
|
ca9dea1ae84c75dcf9b3afb41edce8a74eeff394daf5fe33557c857b78559e49 | ghc/testsuite | tcrun008.hs | {-# LANGUAGE Rank2Types #-}
-- !!! Check that record selectors for polymorphic fields work right
module Main where
class Foo a where
bar :: a -> [a]
instance Foo Int where
bar x = replicate x x
instance Foo Bool where
bar x = [x, not x]
data Record = R {
blub :: Foo a => a -> [a]
}
main = do { let r = R {blub = bar}
; print (blub r (3::Int))
; print (blub r True)
}
| null | https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/typecheck/should_run/tcrun008.hs | haskell | # LANGUAGE Rank2Types #
!!! Check that record selectors for polymorphic fields work right |
module Main where
class Foo a where
bar :: a -> [a]
instance Foo Int where
bar x = replicate x x
instance Foo Bool where
bar x = [x, not x]
data Record = R {
blub :: Foo a => a -> [a]
}
main = do { let r = R {blub = bar}
; print (blub r (3::Int))
; print (blub r True)
}
|
6a5dc207941e810da841517eadebc11887782c382b4b46ab38d9397060904271 | helvm/helma | IntCellType.hs | module HelVM.HelMA.Automaton.Types.IntCellType where
import HelVM.HelIO.SwitchEnum
-- | Constructors
defaultIntCellType :: IntCellType
defaultIntCellType = defaultEnum
intCellTypes :: [IntCellType]
intCellTypes = generateEnums 5
-- | Types
data IntCellType = IntegerType | Int8Type | Int16Type | Int32Type | Int64Type
deriving stock (Bounded , Enum , Eq , Read , Show)
| null | https://raw.githubusercontent.com/helvm/helma/a843fb86f4f51c84fd8c65970d0fb0221d551218/hs/src/HelVM/HelMA/Automaton/Types/IntCellType.hs | haskell | | Constructors
| Types | module HelVM.HelMA.Automaton.Types.IntCellType where
import HelVM.HelIO.SwitchEnum
defaultIntCellType :: IntCellType
defaultIntCellType = defaultEnum
intCellTypes :: [IntCellType]
intCellTypes = generateEnums 5
data IntCellType = IntegerType | Int8Type | Int16Type | Int32Type | Int64Type
deriving stock (Bounded , Enum , Eq , Read , Show)
|
c9de280845519eaf877cdc4272e49410689709a5d99e2d81c997e95304320a22 | UU-ComputerScience/uhc | data-field5.hs | -- data fields construction: duplicate field
% % inline test ( ) --
data X
= X { b :: Int, a, c :: Char }
x1 = X { c = 'y', a = 'x', b = 4, b = 5 }
main = c x1
| null | https://raw.githubusercontent.com/UU-ComputerScience/uhc/f2b94a90d26e2093d84044b3832a9a3e3c36b129/EHC/test/regress/7/data-field5.hs | haskell | data fields construction: duplicate field
|
data X
= X { b :: Int, a, c :: Char }
x1 = X { c = 'y', a = 'x', b = 4, b = 5 }
main = c x1
|
da9684374466f03fbde848c0c65b80bccdf43d5b43779f6f458037a3d16292dc | Vigilans/hscc | Semantic.hs | module Language.C.Semantic (module Semantic) where
import Language.C.Semantic.Analysis as Semantic
import Language.C.Semantic.Evaluate as Semantic
import Language.C.Semantic.Validate as Semantic
| null | https://raw.githubusercontent.com/Vigilans/hscc/d612c54f9263d90fb01673aea1820a62fdf62551/src/Language/C/Semantic.hs | haskell | module Language.C.Semantic (module Semantic) where
import Language.C.Semantic.Analysis as Semantic
import Language.C.Semantic.Evaluate as Semantic
import Language.C.Semantic.Validate as Semantic
| |
45b17cd5c32c93e91f7613e2580096fd5f2a0116f2894442a07de0451d633fdd | kadena-io/chainweb-node | Trace.hs | {-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveGeneric #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
-- |
-- Module: Utils.Logging.Trace
Copyright : Copyright © 2018 - 2020 Kadena LLC .
License : MIT
Maintainer : < >
-- Stability: experimental
--
-- Tools for tracing and logging the runtime of functions.
--
-- This should be used with care, since it adds overhead to the system. /It is
not meant to replace a profiling/. There is a reason why GHC uses a dedicated
-- runtime for profiling: performance.
--
-- The tools in this module are indented to measure and log the runtime of
-- long-running high-level operations in production.
--
module Utils.Logging.Trace
( trace
, Trace
) where
import Control.DeepSeq
import Control.Monad.IO.Class
import Control.StopWatch
import Data.Aeson
import qualified Data.Text as T
import GHC.Generics
import System.Clock
import System.LogLevel
-- internal modules
import Chainweb.Time
import Data.LogMessage
-- -------------------------------------------------------------------------- --
-- Logging
data Trace = Trace
{ _traceAction :: !T.Text
, _traceParam :: !Value
, _traceWeight :: !Int
, _traceTime :: !Micros
}
deriving (Show, Eq, Generic, NFData)
traceProperties :: KeyValue kv => Trace -> [kv]
traceProperties o =
[ "action" .= _traceAction o
, "param" .= _traceParam o
, "weight" .= _traceWeight o
, "time" .= _traceTime o
]
# INLINE traceProperties #
instance ToJSON Trace where
toJSON = object . traceProperties
toEncoding = pairs . mconcat . traceProperties
# INLINE toJSON #
# INLINE toEncoding #
trace
:: MonadIO m
=> ToJSON param
=> LogFunction
-> T.Text
-> param
-> Int
-> m a
-> m a
trace logg label param weight a = do
(!r, t) <- stopWatch a
liftIO $ logg Info $ JsonLog $ Trace label
(toJSON param)
weight
(fromIntegral $ toNanoSecs t `div` 1000)
return r
| null | https://raw.githubusercontent.com/kadena-io/chainweb-node/62e5eeccd1ae4a5e4ca56452f7c85d07cdb483c4/src/Utils/Logging/Trace.hs | haskell | # LANGUAGE BangPatterns #
# LANGUAGE DeriveAnyClass #
# LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
|
Module: Utils.Logging.Trace
Stability: experimental
Tools for tracing and logging the runtime of functions.
This should be used with care, since it adds overhead to the system. /It is
runtime for profiling: performance.
The tools in this module are indented to measure and log the runtime of
long-running high-level operations in production.
internal modules
-------------------------------------------------------------------------- --
Logging | # LANGUAGE DeriveGeneric #
# LANGUAGE ScopedTypeVariables #
Copyright : Copyright © 2018 - 2020 Kadena LLC .
License : MIT
Maintainer : < >
not meant to replace a profiling/. There is a reason why GHC uses a dedicated
module Utils.Logging.Trace
( trace
, Trace
) where
import Control.DeepSeq
import Control.Monad.IO.Class
import Control.StopWatch
import Data.Aeson
import qualified Data.Text as T
import GHC.Generics
import System.Clock
import System.LogLevel
import Chainweb.Time
import Data.LogMessage
data Trace = Trace
{ _traceAction :: !T.Text
, _traceParam :: !Value
, _traceWeight :: !Int
, _traceTime :: !Micros
}
deriving (Show, Eq, Generic, NFData)
traceProperties :: KeyValue kv => Trace -> [kv]
traceProperties o =
[ "action" .= _traceAction o
, "param" .= _traceParam o
, "weight" .= _traceWeight o
, "time" .= _traceTime o
]
# INLINE traceProperties #
instance ToJSON Trace where
toJSON = object . traceProperties
toEncoding = pairs . mconcat . traceProperties
# INLINE toJSON #
# INLINE toEncoding #
trace
:: MonadIO m
=> ToJSON param
=> LogFunction
-> T.Text
-> param
-> Int
-> m a
-> m a
trace logg label param weight a = do
(!r, t) <- stopWatch a
liftIO $ logg Info $ JsonLog $ Trace label
(toJSON param)
weight
(fromIntegral $ toNanoSecs t `div` 1000)
return r
|
54271bfd43422989b91bcbf640bde1a335884e71c02eefa7155be54bf7134600 | SjVer/Som-Lang | context.ml | open Parse.Ast
module IMap = Symboltable.IMap
(* ast symbol table stuff *)
type ast_symbol_table = (value_definition, type_definition) Symboltable.t
let print_ast_table (table : ast_symbol_table) =
let fmt i w n = "("^string_of_int i^") <def "^w^" "^n^">" in
let open Symboltable in
let valuefn {index = i; symbol = s; uses = _} =
Parse.PrintAst.p 2
(fmt i "value" s.vd_name.item)
s.vd_name.span;
Parse.PrintAst.print_expr_node' 3 s.vd_expr;
print_newline ()
in
let typefn {index = i; symbol = s; uses = _} =
let rec join = function
| [] -> ""
| v :: vs -> "'" ^ v.item ^ " " ^ join vs
in
Parse.PrintAst.p 2
(fmt i "type" (join s.td_params ^ s.td_name.item))
s.td_name.span;
Parse.PrintAst.print_type_node' 3 s.td_type;
print_newline ()
in
print_table table valuefn typefn
(* context stuff *)
type t =
{
(* path of module *)
name: Ident.t;
(* present submodules *)
subcontexts: Ident.t list;
(* maps of local to qualified identifiers *)
value_map: Ident.t IMap.t;
type_map: Ident.t IMap.t;
(* table with qualified identifiers *)
table: ast_symbol_table;
}
let print ctx =
print_endline ("======== " ^ (Ident.to_string ctx.name) ^ " ========");
print_endline "Subcontexts:";
List.iter
(fun i -> print_endline ("\t" ^ Ident.to_string i))
ctx.subcontexts;
if ctx.subcontexts = [] then print_endline "\t<none>";
print_newline ();
let f k v = Printf.printf "\t%s -> %s\n"
(Ident.to_string k)
(Ident.to_string v)
in
print_endline "Value bindings: ";
if IMap.is_empty ctx.value_map then print_endline "\t<none>"
else IMap.iter f ctx.value_map;
print_newline ();
print_endline "Type bindings: ";
if IMap.is_empty ctx.type_map then print_endline "\t<none>"
else IMap.iter f ctx.type_map;
print_newline ();
print_ast_table ctx.table;
print_endline "=============================="
let qualify ctx ident = Ident.append ctx.name ident
(* initializers *)
let empty name =
{
name;
subcontexts = [];
value_map = IMap.empty;
type_map = IMap.empty;
table = Symboltable.empty;
}
(* finding *)
let lookup_qual_value_ident ctx ident = IMap.find ident ctx.value_map
let lookup_qual_type_ident ctx ident = IMap.find ident ctx.type_map
let check_subcontext ctx ident =
List.exists ( (= ) ident )
List.exists ((=) ident) ctx.subcontexts *)
(* adding *)
let add_local_value ctx vdef =
let ident = Ident.Ident vdef.vd_name.item in
let qual_ident = qualify ctx ident in
let table = Symboltable.add_new_value ctx.table qual_ident vdef in
let value_map = IMap.add ident qual_ident ctx.value_map in
{ctx with table; value_map}
let add_local_type ctx tdef =
let ident = Ident.Ident tdef.td_name.item in
let qual_ident = qualify ctx ident in
let table = Symboltable.add_new_type ctx.table qual_ident tdef in
let type_map = IMap.add ident qual_ident ctx.type_map in
{ctx with table; type_map}
let bind_qual_value_ident ctx ident qual =
{ctx with value_map = IMap.add ident qual ctx.value_map}
let bind_qual_type_ident ctx ident qual =
{ctx with type_map = IMap.add ident qual ctx.type_map}
(* let add_subcontext ctx ident =
{ctx with subcontexts = ctx.subcontexts @ [ident]} *)
(* ugly shit *)
let add_table ctx table bindings =
let f k _ m = IMap.add k k m in
let open Symboltable in
let value_map = if bindings then
IMap.fold f table.values ctx.value_map
else ctx.value_map
in
let type_map = if bindings then
IMap.fold f table.types ctx.type_map
else ctx.type_map
in
let table = merge_tables ctx.table table in
{ctx with value_map; type_map; table}
let add_subcontext_prefixed ctx subctx prefix =
let f k e m = IMap.add (Ident.prepend (Ident prefix) k) e m in
{
ctx with
subcontexts = ctx.subcontexts @ subctx.subcontexts @ [subctx.name];
value_map = IMap.fold f subctx.value_map ctx.value_map;
type_map = IMap.fold f subctx.type_map ctx.type_map;
table = Symboltable.merge_tables ctx.table subctx.table;
}
(* only changes the bindings *)
let extract_subcontext ctx prefix =
let f m =
let filter k _ = Ident.has_prefix k prefix
and fold k e m = IMap.add (Ident.remove_prefix k prefix) e m in
IMap.fold fold (IMap.filter filter m) IMap.empty
in
let filter_map i =
if not (Ident.has_prefix i prefix) then Some i
else try Some (Ident.remove_prefix i prefix)
with Ident.Empty_ident -> None
in
{
name = Ident (Ident.last prefix);
subcontexts = List.filter_map filter_map ctx.subcontexts;
value_map = f ctx.value_map;
type_map = f ctx.type_map;
table = ctx.table;
(* {
values = f ctx.table.values;
types = f ctx.table.types;
}; *)
} | null | https://raw.githubusercontent.com/SjVer/Som-Lang/c4a606c745d04746cdbf839dddd2603738d217e4/somc/lib/analysis/context.ml | ocaml | ast symbol table stuff
context stuff
path of module
present submodules
maps of local to qualified identifiers
table with qualified identifiers
initializers
finding
adding
let add_subcontext ctx ident =
{ctx with subcontexts = ctx.subcontexts @ [ident]}
ugly shit
only changes the bindings
{
values = f ctx.table.values;
types = f ctx.table.types;
}; | open Parse.Ast
module IMap = Symboltable.IMap
type ast_symbol_table = (value_definition, type_definition) Symboltable.t
let print_ast_table (table : ast_symbol_table) =
let fmt i w n = "("^string_of_int i^") <def "^w^" "^n^">" in
let open Symboltable in
let valuefn {index = i; symbol = s; uses = _} =
Parse.PrintAst.p 2
(fmt i "value" s.vd_name.item)
s.vd_name.span;
Parse.PrintAst.print_expr_node' 3 s.vd_expr;
print_newline ()
in
let typefn {index = i; symbol = s; uses = _} =
let rec join = function
| [] -> ""
| v :: vs -> "'" ^ v.item ^ " " ^ join vs
in
Parse.PrintAst.p 2
(fmt i "type" (join s.td_params ^ s.td_name.item))
s.td_name.span;
Parse.PrintAst.print_type_node' 3 s.td_type;
print_newline ()
in
print_table table valuefn typefn
type t =
{
name: Ident.t;
subcontexts: Ident.t list;
value_map: Ident.t IMap.t;
type_map: Ident.t IMap.t;
table: ast_symbol_table;
}
let print ctx =
print_endline ("======== " ^ (Ident.to_string ctx.name) ^ " ========");
print_endline "Subcontexts:";
List.iter
(fun i -> print_endline ("\t" ^ Ident.to_string i))
ctx.subcontexts;
if ctx.subcontexts = [] then print_endline "\t<none>";
print_newline ();
let f k v = Printf.printf "\t%s -> %s\n"
(Ident.to_string k)
(Ident.to_string v)
in
print_endline "Value bindings: ";
if IMap.is_empty ctx.value_map then print_endline "\t<none>"
else IMap.iter f ctx.value_map;
print_newline ();
print_endline "Type bindings: ";
if IMap.is_empty ctx.type_map then print_endline "\t<none>"
else IMap.iter f ctx.type_map;
print_newline ();
print_ast_table ctx.table;
print_endline "=============================="
let qualify ctx ident = Ident.append ctx.name ident
let empty name =
{
name;
subcontexts = [];
value_map = IMap.empty;
type_map = IMap.empty;
table = Symboltable.empty;
}
let lookup_qual_value_ident ctx ident = IMap.find ident ctx.value_map
let lookup_qual_type_ident ctx ident = IMap.find ident ctx.type_map
let check_subcontext ctx ident =
List.exists ( (= ) ident )
List.exists ((=) ident) ctx.subcontexts *)
let add_local_value ctx vdef =
let ident = Ident.Ident vdef.vd_name.item in
let qual_ident = qualify ctx ident in
let table = Symboltable.add_new_value ctx.table qual_ident vdef in
let value_map = IMap.add ident qual_ident ctx.value_map in
{ctx with table; value_map}
let add_local_type ctx tdef =
let ident = Ident.Ident tdef.td_name.item in
let qual_ident = qualify ctx ident in
let table = Symboltable.add_new_type ctx.table qual_ident tdef in
let type_map = IMap.add ident qual_ident ctx.type_map in
{ctx with table; type_map}
let bind_qual_value_ident ctx ident qual =
{ctx with value_map = IMap.add ident qual ctx.value_map}
let bind_qual_type_ident ctx ident qual =
{ctx with type_map = IMap.add ident qual ctx.type_map}
let add_table ctx table bindings =
let f k _ m = IMap.add k k m in
let open Symboltable in
let value_map = if bindings then
IMap.fold f table.values ctx.value_map
else ctx.value_map
in
let type_map = if bindings then
IMap.fold f table.types ctx.type_map
else ctx.type_map
in
let table = merge_tables ctx.table table in
{ctx with value_map; type_map; table}
let add_subcontext_prefixed ctx subctx prefix =
let f k e m = IMap.add (Ident.prepend (Ident prefix) k) e m in
{
ctx with
subcontexts = ctx.subcontexts @ subctx.subcontexts @ [subctx.name];
value_map = IMap.fold f subctx.value_map ctx.value_map;
type_map = IMap.fold f subctx.type_map ctx.type_map;
table = Symboltable.merge_tables ctx.table subctx.table;
}
let extract_subcontext ctx prefix =
let f m =
let filter k _ = Ident.has_prefix k prefix
and fold k e m = IMap.add (Ident.remove_prefix k prefix) e m in
IMap.fold fold (IMap.filter filter m) IMap.empty
in
let filter_map i =
if not (Ident.has_prefix i prefix) then Some i
else try Some (Ident.remove_prefix i prefix)
with Ident.Empty_ident -> None
in
{
name = Ident (Ident.last prefix);
subcontexts = List.filter_map filter_map ctx.subcontexts;
value_map = f ctx.value_map;
type_map = f ctx.type_map;
table = ctx.table;
} |
3bfb0e2858dd4265a89af37e0af06575e5afb4896d366d960fc235ec4ef878c6 | dstcruz/Write-Yourself-A-Scheme-In-48-Hours | listing2.hs | module Main where
import System.Environment
import Text.ParserCombinators.Parsec hiding (spaces)
main :: IO ()
main = do
args <- getArgs
putStrLn (readExpr (args !! 0))
symbol :: Parser Char
symbol = oneOf "!#$%&|*+-/:<=>?@^_~"
readExpr :: String -> String
readExpr input = case parse symbol "lisp" input of
Left err -> "No match: " ++ show err
Right val -> "Found value"
| null | https://raw.githubusercontent.com/dstcruz/Write-Yourself-A-Scheme-In-48-Hours/19765a03fb01d788066259d115c7798518224ad9/ch02/parsing/listing2.hs | haskell | module Main where
import System.Environment
import Text.ParserCombinators.Parsec hiding (spaces)
main :: IO ()
main = do
args <- getArgs
putStrLn (readExpr (args !! 0))
symbol :: Parser Char
symbol = oneOf "!#$%&|*+-/:<=>?@^_~"
readExpr :: String -> String
readExpr input = case parse symbol "lisp" input of
Left err -> "No match: " ++ show err
Right val -> "Found value"
| |
e8af8fb15cbea763b2b87485cb83e0c2040dcc9394c3d3883cdb6d1fbc7a1b03 | chef/chef-server | chef_solr_tests.erl | Copyright Chef Software , 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.
%%
-module(chef_solr_tests).
-include_lib("eunit/include/eunit.hrl").
-include("chef_solr.hrl").
search_test_() ->
{foreach,
fun() ->
meck:new(chef_index_http)
end,
fun(_) ->
meck:unload([chef_index_http])
end,
[
{"error if org filter not set",
fun() ->
Query = #chef_solr_query{
query_string = "*:*",
%% note the missing org filter
filter_query = "+X_CHEF_type_CHEF_X:node",
sort = "X_CHEF_id_CHEF_X asc",
start = 0,
rows = 1000},
?assertError({badmatch, _X}, chef_solr:search(Query))
end},
{"parse non-empty solr result",
fun() ->
Docs = [{[{<<"X_CHEF_id_CHEF_X">>, "d1"}]},
{[{<<"X_CHEF_id_CHEF_X">>, "d2"}]}],
Solr = {[{<<"response">>,
{[{<<"start">>, 2},
{<<"numFound">>, 10},
{<<"docs">>, Docs}]}}]},
SolrJson = jiffy:encode(Solr),
meck:expect(chef_index_http, request,
fun(_Url, get, []) -> {ok, "200", [], SolrJson} end),
Query0 = #chef_solr_query{
query_string = "*:*",
filter_query = "+X_CHEF_type_CHEF_X:node",
sort = "X_CHEF_id_CHEF_X asc",
start = 0,
rows = 1000},
Query1 = chef_index:add_org_guid_to_query(Query0, <<"0123abc">>),
?assertEqual({ok, 2, 10, ["d1", "d2"]}, chef_solr:search(Query1)),
?assert(meck:validate(chef_index_http))
end}
]}.
| null | https://raw.githubusercontent.com/chef/chef-server/6d31841ecd73d984d819244add7ad6ebac284323/src/oc_erchef/apps/chef_index/test/chef_solr_tests.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.
note the missing org filter | Copyright Chef Software , 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
-module(chef_solr_tests).
-include_lib("eunit/include/eunit.hrl").
-include("chef_solr.hrl").
search_test_() ->
{foreach,
fun() ->
meck:new(chef_index_http)
end,
fun(_) ->
meck:unload([chef_index_http])
end,
[
{"error if org filter not set",
fun() ->
Query = #chef_solr_query{
query_string = "*:*",
filter_query = "+X_CHEF_type_CHEF_X:node",
sort = "X_CHEF_id_CHEF_X asc",
start = 0,
rows = 1000},
?assertError({badmatch, _X}, chef_solr:search(Query))
end},
{"parse non-empty solr result",
fun() ->
Docs = [{[{<<"X_CHEF_id_CHEF_X">>, "d1"}]},
{[{<<"X_CHEF_id_CHEF_X">>, "d2"}]}],
Solr = {[{<<"response">>,
{[{<<"start">>, 2},
{<<"numFound">>, 10},
{<<"docs">>, Docs}]}}]},
SolrJson = jiffy:encode(Solr),
meck:expect(chef_index_http, request,
fun(_Url, get, []) -> {ok, "200", [], SolrJson} end),
Query0 = #chef_solr_query{
query_string = "*:*",
filter_query = "+X_CHEF_type_CHEF_X:node",
sort = "X_CHEF_id_CHEF_X asc",
start = 0,
rows = 1000},
Query1 = chef_index:add_org_guid_to_query(Query0, <<"0123abc">>),
?assertEqual({ok, 2, 10, ["d1", "d2"]}, chef_solr:search(Query1)),
?assert(meck:validate(chef_index_http))
end}
]}.
|
7503fb74d6f01fcce7b01965ef40ab01a42098b6432afc5390fd007bf7a719fb | atgreen/red-light-green-light | tests.lisp | -*- Mode : LISP ; Syntax : Ansi - Common - Lisp ; Base : 10 ; Package : POSTMODERN - TESTS ; -*-
(in-package :postmodern-tests)
;; Adjust the above to some db/user/pass/host combination that refers
;; to a valid postgresql database in which no table named test_data
;; currently exists. Then after loading the file, run the tests with
;; (run! :postmodern)
(def-suite :postmodern
:description "Test suite for postmodern subdirectory files")
(def-suite :postmodern-base
:description "Base Test suite for postmodern subdirectory files")
(in-suite :postmodern-base)
(def-suite :postmodern-base
:description "Base test suite for postmodern"
:in :postmodern)
(in-suite :postmodern-base)
(defmacro with-binary (&body body)
`(let ((old-use-binary-parameters (connection-use-binary *database*)))
(use-binary-parameters *database* t)
(unwind-protect (progn ,@body)
(use-binary-parameters *database* old-use-binary-parameters))))
(defmacro without-binary (&body body)
`(let ((old-use-binary-parameters (connection-use-binary *database*)))
(use-binary-parameters *database* nil)
(unwind-protect (progn ,@body)
(use-binary-parameters *database* old-use-binary-parameters))))
(defun prompt-connection-to-postmodern-db-spec (param-lst)
"Takes the 6 item parameter list from prompt-connection and restates it for pomo:with-connection. Note that cl-postgres does not provide the pooled connection - that is only in postmodern - so that parameter is not passed."
(when (and (listp param-lst)
(= 6 (length param-lst)))
(destructuring-bind (db user password host port use-ssl) param-lst
(list db user password host :port port :use-ssl use-ssl))))
(defmacro with-test-connection (&body body)
`(with-connection (prompt-connection-to-postmodern-db-spec
(cl-postgres-tests:prompt-connection))
,@body))
(defmacro with-binary-test-connection (&body body)
`(with-connection (append (prompt-connection-to-postmodern-db-spec
(cl-postgres-tests:prompt-connection))
'(:use-binary t))
,@body))
(defmacro with-pooled-test-connection (&body body)
`(with-connection (append (prompt-connection-to-postmodern-db-spec
(cl-postgres-tests:prompt-connection))
'(:pooled-p t))
,@body))
(defmacro with-binary-pooled-test-connection (&body body)
`(with-connection (append (prompt-connection-to-postmodern-db-spec
(cl-postgres-tests:prompt-connection))
'(:pooled-p t :use-binary t))
,@body))
(defmacro protect (&body body)
`(unwind-protect (progn ,@(butlast body)) ,(car (last body))))
(test connect-sanely
"Check that with-test-connection and with-binary-test-connection actually connect"
(with-test-connection
(is (not (null *database*))))
(with-binary-test-connection
(is (not (null *database*)))
(is (connection-use-binary *database*))))
(defmacro with-application-connection (&body body)
`(with-connection
(append
(prompt-connection-to-postmodern-db-spec (cl-postgres-tests:prompt-connection))
'(:application-name "george"))
,@body))
(test application-name
(with-application-connection
(is (equal
(query "select distinct application_name from pg_stat_activity where application_name = 'george'"
:single)
"george"))))
(test connection-pool
(let* ((db-params (append (prompt-connection-to-postmodern-db-spec
(cl-postgres-tests:prompt-connection)) '(:pooled-p t)))
(pooled (apply 'connect db-params)))
(disconnect pooled)
(let ((pooled* (apply 'connect db-params)))
(is (eq pooled pooled*))
(disconnect pooled*))
(clear-connection-pool)
(let ((pooled* (apply 'connect db-params)))
(is (not (eq pooled pooled*)))
(disconnect pooled*))
(clear-connection-pool)))
(test reconnect
(with-test-connection
(disconnect *database*)
(is (not (connected-p *database*)))
(reconnect *database*)
(is (connected-p *database*))
(is (equal (get-search-path)
"\"$user\", public"))
(is (equal
(with-schema ("a")
(disconnect *database*)
(reconnect *database*)
(get-search-path))
"a"))
(is (equal (get-search-path)
"\"$user\", public"))))
(test simple-query
(with-test-connection
(destructuring-bind (a b c d e f)
(query (:select 22 (:type 44.5 double-precision) "abcde" t (:type 9/2 (numeric 5 2))
(:[] #("A" "B") 2)) :row)
(is (eql a 22))
(is (eql b 44.5d0))
(is (string= c "abcde"))
(is (eql d t))
(is (eql e 9/2))
(is (equal f "B")))))
(test reserved-words
(with-test-connection
(is (= (query (:select '*
:from (:as (:select (:as 1 'as)) 'where)
:where (:= 'where.as 1)) :single!)
1))))
(test time-types
"Ensure that we are using a readtable that reads into simple-dates."
(setf cl-postgres:*sql-readtable*
(cl-postgres:copy-sql-readtable
simple-date-cl-postgres-glue:*simple-date-sql-readtable*))
(with-test-connection
(is (time= (query (:select (:type (simple-date:encode-date 1980 2 1) date)) :single)
(encode-date 1980 2 1)))
(is (time= (query (:select (:type (simple-date:encode-timestamp 2040 3 19 12 15 0 2) timestamp))
:single)
(encode-timestamp 2040 3 19 12 15 0 2)))
(is (time= (query (:select (:type (simple-date:encode-interval :month -1 :hour 24) interval))
:single)
(encode-interval :month -1 :hour 24))))
;;; Reset readtable to default
(setf cl-postgres:*sql-readtable*
(cl-postgres:copy-sql-readtable
cl-postgres::*default-sql-readtable*)))
(test table-skeleton
(with-test-connection
(when (table-exists-p 'test-data) (execute (:drop-table 'test-data)))
(execute (:create-table test-data ((a :type integer :primary-key t) (b :type real)
(c :type (or text db-null))) (:unique c)))
(protect
(is (table-exists-p 'test-data))
(execute (:insert-into 'test-data :set 'a 1 'b 5.4 'c "foobar"))
(execute (:insert-into 'test-data :set 'a 2 'b 88 'c :null))
(is (equal (query (:order-by (:select '* :from 'test-data) 'a))
'((1 5.4 "foobar")
(2 88.0 :null))))
(execute (:drop-table 'test-data)))
(is (not (table-exists-p 'test-data)))))
(test doquery
(with-test-connection
(doquery (:select 55 "foobar") (number string)
(is (= number 55))
(is (string= string "foobar")))))
(test doquery-params
(with-test-connection
(doquery ("select $1::integer + 10" 20) (answer)
(is (= answer 30)))))
(test notification
(with-test-connection
(execute (:listen 'foo))
(with-test-connection
(execute (:notify 'foo)))
(is (cl-postgres:wait-for-notification *database*) "foo")))
(test split-fully-qualified-tablename
(is (equal (split-fully-qualified-tablename 'uniq.george)
'("george" "uniq" NIL)))
(is (equal (split-fully-qualified-tablename "george-and-gracie")
'("george_and_gracie" "public" NIL)))
(is (equal (split-fully-qualified-tablename "test.uniq.george-and-gracie")
'("george_and_gracie" "uniq" "test")))
(is (equal (split-fully-qualified-tablename 'test.uniq.george-and-gracie)
'("george_and_gracie" "uniq" "test"))))
create two tables with the same name in two different
;; namespaces.
(test namespace
(with-test-connection
(let ((excess-schemas
(set-difference (list-schemas)
'("public" "information_schema" "uniq")
:test #'equal)))
(when excess-schemas (loop for x in excess-schemas do
(drop-schema x :cascade 't))))
(when (table-exists-p 'test-uniq)
(execute (:drop-table 'test-uniq)))
(is (schema-exists-p :public))
(is (not (table-exists-p 'test-uniq)))
(unless (table-exists-p 'test-uniq)
(execute (:create-table test-uniq ((value :type integer)))))
(is (table-exists-p 'test-uniq))
(is (not (schema-exists-p 'uniq)))
(is (eq (column-exists-p 'public.test-uniq 'value) t))
(is (not (eq (column-exists-p 'public.test-uniq 'valuea) t)))
(is (eq (column-exists-p 'test-uniq 'value 'public) t))
(is (not (eq (column-exists-p 'test-uniq 'valuea 'public) t)))
(with-schema ('uniq :if-not-exist :create) ;; changing the search path
(is (schema-exists-p 'uniq))
(is (schema-exists-p "uniq"))
(is (not (table-exists-p 'test-uniq 'uniq)))
(execute (:create-table test-uniq ((value :type integer))))
(is (table-exists-p 'test-uniq))
(execute (:drop-table 'test-uniq)))
(query (:create-table 'uniq.gracie ((id :type integer))))
(is (equal (list-tables-in-schema "uniq")
'("gracie")))
(is (equal (list-tables-in-schema 'uniq)
'("gracie")))
(query (:create-table "uniq.george" ((id :type integer))))
(is (equal (list-tables-in-schema "uniq")
'("george" "gracie")))
(is (table-exists-p "test.uniq.george"))
(is (table-exists-p "uniq.george"))
(is (table-exists-p "george" "uniq"))
(is (table-exists-p 'test.uniq.george))
(is (table-exists-p 'uniq.george))
(is (table-exists-p 'george 'uniq))
(is (schema-exists-p 'uniq))
(drop-schema 'uniq :cascade 't)
(is (not (schema-exists-p 'uniq)))
(create-schema 'uniq)
(format t "List-schemas ~a~%" (list-schemas))
(is (equal "uniq" (find "uniq" (list-schemas) :test #'equal)))
(drop-schema "uniq" :cascade 't)
(is (not (schema-exists-p "uniq")))
(create-schema "uniq")
(is (equal "uniq" (find "uniq" (list-schemas) :test #'equal)))
(drop-schema 'uniq :cascade 't)
(is (equal (get-search-path)
"\"$user\", public"))
(execute (:drop-table 'test-uniq))))
(test arrays-skeleton
(with-test-connection
(when (table-exists-p 'test-data) (execute (:drop-table 'test-data)))
(execute (:create-table test-data ((a :type integer[]))))
(protect
(is (table-exists-p 'test-data))
(execute (:insert-into 'test-data :set 'a (vector 3 4 5)))
(execute (:insert-into 'test-data :set 'a #()))
(execute (:drop-table 'test-data)))
(is (not (table-exists-p 'test-data)))))
(test find-primary-key-info
"Testing find-primary-key-info function. Given a table name, it returns
a list of two strings. First the column name of the primary key of the table
and second the string name for the datatype."
(with-test-connection
(execute "create temporary table tasks_lists (id integer primary key)")
(is (equal (postmodern:find-primary-key-info (s-sql:to-sql-name "tasks_lists"))
'(("id" "integer"))))
(is (equal (postmodern:find-primary-key-info (s-sql:to-sql-name "tasks_lists") t)
'("id")))))
(test list-indices
"Check the sql generated by the list-indices code"
(is (equal (sql (postmodern::make-list-query "i"))
"E'((SELECT relname FROM pg_catalog.pg_class INNER JOIN pg_catalog.pg_namespace ON (relnamespace = pg_namespace.oid) WHERE ((relkind = E''i'') and (nspname NOT IN (E''pg_catalog'', E''pg_toast'')) and pg_catalog.pg_table_is_visible(pg_class.oid))) ORDER BY relname)'")))
(test list-indices-and-constraints
"Test various index functions"
(with-test-connection
(pomo:drop-table 'people :if-exists t :cascade t)
(query (:create-table 'people ((id :type (or integer db-null) :primary-key :identity-by-default)
(first-name :type (or (varchar 50) db-null))
(last-name :type (or (varchar 50) db-null)))))
(query (:create-index 'idx-people-names :on 'people :fields 'last-name 'first-name))
(query (:create-index 'idx-people-first-names :on 'people :fields 'first-name))
(query (:insert-rows-into 'people
:columns 'first-name 'last-name
:values '(("Eliza" "Gregory") ("Dean" "Rodgers") ("Christine" "Alvarez")
("Dennis" "Peterson") ("Ernest" "Roberts") ("Jorge" "Wood")
("Harvey" "Strickland") ("Eugene" "Rivera")
("Tillie" "Bell") ("Marie" "Lloyd") ("John" "Lyons")
("Lucas" "Gray") ("Edward" "May")
("Randy" "Fields") ("Nell" "Malone") ("Jacob" "Maxwell")
("Vincent" "Adams") ("Henrietta" "Schneider")
("Ernest" "Mendez") ("Jean" "Adams") ("Olivia" "Adams"))))
(let ((idx-symbol (first (list-indices)))
(idx-string (first (list-indices t))))
(is (pomo:index-exists-p idx-symbol))
(is (pomo:index-exists-p idx-string)))
(is (equal (list-table-indices 'people)
'((:IDX-PEOPLE-FIRST-NAMES :FIRST-NAME) (:IDX-PEOPLE-NAMES :FIRST-NAME)
(:IDX-PEOPLE-NAMES :LAST-NAME) (:PEOPLE-PKEY :ID))))
(is (equal (list-table-indices 'people t)
'(("idx_people_first_names" "first_name") ("idx_people_names" "first_name")
("idx_people_names" "last_name") ("people_pkey" "id"))))
(is (equal (list-table-indices "people")
'((:IDX-PEOPLE-FIRST-NAMES :FIRST-NAME) (:IDX-PEOPLE-NAMES :FIRST-NAME)
(:IDX-PEOPLE-NAMES :LAST-NAME) (:PEOPLE-PKEY :ID))))
(is (equal (list-table-indices "people" t)
'(("idx_people_first_names" "first_name") ("idx_people_names" "first_name")
("idx_people_names" "last_name") ("people_pkey" "id"))))
(is (equal (list-unique-or-primary-constraints "people" t)
'(("people_pkey"))))
(is (equal (list-unique-or-primary-constraints "people")
'((:PEOPLE-PKEY))))
(is (equal (length (list-all-constraints 'people))
2))
(is (equal (length (list-all-constraints "people"))
2))
(query (:alter-table 'people :drop-constraint 'people-pkey))
(is (equal (length (list-all-constraints "people"))
1))
(execute (:drop-table 'people))))
(test drop-indices
"Test drop index variations"
(with-test-connection
(query (:drop-table :if-exists 'george :cascade))
(query (:create-table 'george ((id :type integer))))
(query (:create-index 'george-idx :on 'george :fields 'id))
(is (equal (list-table-indices 'george)
'((:GEORGE-IDX :ID))))
(is (index-exists-p 'george-idx))
(query (:drop-index :if-exists 'george-idx))
(is (not (index-exists-p 'george-idx)))
(is (equal (sql (:drop-index :if-exists 'george-idx :cascade))
"DROP INDEX IF EXISTS george_idx CASCADE"))
(is (equal (sql (:drop-index (:if-exists 'george-idx) :cascade))
"DROP INDEX IF EXISTS george_idx CASCADE"))
(is (equal (sql (:drop-index :concurrently (:if-exists 'george-idx) :cascade))
"DROP INDEX CONCURRENTLY IF EXISTS george_idx CASCADE"))
(is (equal (sql (:drop-index :concurrently (:if-exists 'george-idx)))
"DROP INDEX CONCURRENTLY IF EXISTS george_idx"))
(is (equal (sql (:drop-index :concurrently 'george-idx))
"DROP INDEX CONCURRENTLY george_idx"))
(is (equal (sql (:drop-index 'george-idx))
"DROP INDEX george_idx"))
(query (:drop-table :if-exists 'george :cascade))))
(test sequence
"Sequence testing"
(with-test-connection
(when (sequence-exists-p 'my-seq)
(execute (:drop-sequence 'my-seq)))
(execute (:create-sequence 'my-seq :increment 4 :start 10))
(protect
(is (sequence-exists-p 'my-seq))
(is (= (sequence-next 'my-seq) 10))
(is (= (sequence-next 'my-seq) 14))
(execute (:drop-sequence 'my-seq)))
(is (not (sequence-exists-p 'my-seq)))
(when (sequence-exists-p :knobo-seq)
(query (:drop-sequence :knobo-seq)))
;; Setup new sequence
(is (eq
(query (:create-sequence 'knobo-seq) :single)
nil))
;; test sequence-exists-p with string
(is (sequence-exists-p (first (list-sequences t))))
;; Test that we can set increment
(is (equal (sql (:alter-sequence :knobo-seq :increment 1))
"ALTER SEQUENCE knobo_seq INCREMENT BY 1"))
(is (equal (sql (:alter-sequence 'knobo-seq :increment 1))
"ALTER SEQUENCE knobo_seq INCREMENT BY 1"))
(is (eq (query (:alter-sequence 'knobo-seq :increment 1))
nil))
;; Test that currval is not yet set
(is (equal (sql (:select (:currval 'knobo-seq)))
"(SELECT currval(E'knobo_seq'))"))
(is (equal (sql (:select (:currval :knobo-seq)))
"(SELECT currval(E'knobo_seq'))"))
(signals error (query (:select (:currval 'knobo-seq)) :single))
;; Test next value
(is (equal (query (:select (:nextval 'knobo-seq)) :single)
1))
;; Test currval
(is (eq (query (:select (:currval 'knobo-seq)) :single) 1))
Test that we can set restart at 2
TODO Test that when we restart , we get 2 .
(is (equal (sql (:alter-sequence 'knobo-seq :start 2))
"ALTER SEQUENCE knobo_seq START 2"))
(is (eq (query (:alter-sequence 'knobo-seq :start 2))
nil))
;; Testing that we can set max value
(is (equal (sql (:alter-sequence 'knobo-seq :max-value 5))
"ALTER SEQUENCE knobo_seq MAXVALUE 5"))
(is (eq (query (:alter-sequence 'knobo-seq :max-value 5))
nil))
;; TODO: check here that we don't can do next past max-value
(is (equal (query (:select (:nextval 'knobo-seq)) :single) 2))
(is (equal (sql (:alter-sequence 'knobo-seq :start 3))
"ALTER SEQUENCE knobo_seq START 3"))
(is (eq (query (:alter-sequence 'knobo-seq :start 3))
nil))
;; Test set min value
(is (equal (sql (:alter-sequence 'knobo-seq :min-value 2))
"ALTER SEQUENCE knobo_seq MINVALUE 2"))
(signals error (query (:alter-sequence 'knobo-seq :min-value 3)))
(is (equal (query (:alter-sequence 'knobo-seq :min-value 2)) nil))
;; test remove max value
(is (equal (sql (:alter-sequence 'knobo-seq :no-max))
"ALTER SEQUENCE knobo_seq NO MAXVALUE"))
(is (eq (query (:alter-sequence 'knobo-seq :no-max))
nil))
;; test remove min value
(is (equal (sql (:alter-sequence 'knobo-seq :no-min))
"ALTER SEQUENCE knobo_seq NO MINVALUE"))
(is (eq (query (:alter-sequence 'knobo-seq :no-min))
nil))
(is (eq (query (:alter-sequence 'knobo-seq :cycle))
nil))
(is (eq (query (:alter-sequence 'knobo-seq :no-cycle))
nil))
(is (eq (query (:alter-sequence 'knobo-seq :cache 1))
nil))
(unless (table-exists-p 'seq-test)
(query (:create-table 'seq-test ((:id :type :int)))))
(is (eq (query (:alter-sequence 'knobo-seq :owned-by :seq-test.id))
nil))
;; cleanup
(is (eq (sequence-exists-p 'knobo-seq)
t))
(query (:drop-sequence 'knobo-seq))
(is (eq (sequence-exists-p 'knobo-seq)
nil))
(query (:drop-table 'seq-test))))
(test schema-comments
(with-test-connection
(when (schema-exists-p "schema_1")
(drop-schema "schema_1" :cascade t))
(create-schema "schema_1")
(when (table-exists-p "p1")
(drop-table "p1" :cascade t))
(query (:create-table "p1"
((id :type integer :generated-as-identity-always t)
(text :type text))))
(query (:create-table "schema_1.s1"
((id :type integer :generated-as-identity-always t)
(text :type text))))
(add-comment :table 'p1 "a comment on recipes")
(add-comment :table 'schema-1.s1 "a comment on schema-1 s1")
(is (equal (get-table-comment 'p1)
"a comment on recipes"))
(is (equal (integerp (get-table-oid 'schema-1.s1)) t))
(is (equal (integerp (get-table-oid 'information-schema.columns)) t))
(is (equal (get-table-comment 'schema-1.s1)
"a comment on schema-1 s1"))
(drop-schema "schema_1" :cascade t)
(drop-table "p1" :cascade t)))
(test valid-sql-identifier-p
(is (equal (valid-sql-identifier-p "abc") T))
(is (equal (valid-sql-identifier-p "_abc3") T))
(is (equal (valid-sql-identifier-p "abc-3") NIL))
(is (equal (valid-sql-identifier-p "abc$q7") T))
(is (equal (valid-sql-identifier-p "_abc;'sd") NIL))
(is (equal (valid-sql-identifier-p "haček") T))
(is (equal (valid-sql-identifier-p "Tuđman") T))
(is (equal (valid-sql-identifier-p "Åland") T))
(is (equal (valid-sql-identifier-p "hôtel") T))
(is (equal (valid-sql-identifier-p "piñata") T))
(is (equal (valid-sql-identifier-p "frappé") T))
(is (equal (valid-sql-identifier-p "تَشْكِيل") NIL))
(is (equal (valid-sql-identifier-p "تسير") T))
(is (equal (valid-sql-identifier-p "إمرأة") T))
(is (equal (valid-sql-identifier-p "أهلا") T))
(is (equal (valid-sql-identifier-p "أداة") T))
(is (equal (valid-sql-identifier-p "شخصا") T))
(is (equal (valid-sql-identifier-p "새우") T))
(is (equal (valid-sql-identifier-p "이해") T))
(is (equal (valid-sql-identifier-p "죄") T))
(is (equal (valid-sql-identifier-p "国") T))
(is (equal (valid-sql-identifier-p "高さ") T))
(is (equal (valid-sql-identifier-p "たかさ") T))
(is (equal (valid-sql-identifier-p "住所") T))
(is (equal (valid-sql-identifier-p "会议") T))
(is (equal (valid-sql-identifier-p "kusipää") T)))
(test rename-table-and-columns
(with-test-connection
(when (schema-exists-p 'test-schema)
(drop-schema 'test-schema :cascade t :if-exists t))
(create-schema 'test-schema)
(when (table-exists-p 'test-schema.t1)
(drop-table 'test-schema.t1 :if-exists t :cascade t))
(when (table-exists-p 'test-rename-t1)
(drop-table 'test-rename-t1 :if-exists t :cascade t))
(when (table-exists-p 'test-rename-t2)
(drop-table 'test-rename-t2 :if-exists t :cascade t))
(when (table-exists-p 'test-rename-t3)
(drop-table 'test-rename-t3 :if-exists t :cascade t))
(query (:create-table 'test-schema.t1 ((id :type (or integer db-null)))))
(query (:create-table 'test-rename-t1 ((id :type (or integer db-null)))))
(is (table-exists-p 'test-schema.t1))
(is (rename-table 'test-schema.t1 'test-schema.t2))
(is (table-exists-p 'test-schema.t2))
(is (rename-table 'test-schema.t2 't3))
(is (table-exists-p 'test-schema.t3))
(is (column-exists-p 'test-schema.t3 'id))
(is (rename-column 'test-schema.t3 'id 'new-id))
(is (column-exists-p 'test-schema.t3 'new-id))
(is (rename-column 'test-schema.t3 "new_id" "id"))
(is (column-exists-p "test-schema.t3" "id"))
(is (rename-table "test-schema.t3" "t2"))
(is (table-exists-p "test-schema.t2"))
(is (table-exists-p 'test-rename-t1))
(is (rename-table 'test-rename-t1 'test-rename-t2))
(is (table-exists-p 'test-rename-t2))
(is (rename-table 'test-rename-t2 'test-rename-t3))
(is (table-exists-p 'test-rename-t3))
(is (column-exists-p 'test-rename-t3 'id))
(is (rename-column 'test-rename-t3 'id 'new-id))
(is (column-exists-p 'test-rename-t3 'new-id))
(is (rename-column 'test-rename-t3 "new_id" "id"))
(is (column-exists-p "test-rename-t3" "id"))
(is (rename-table "test-rename-t3" "test-rename-t2"))
(is (table-exists-p "test-rename-t2"))
(drop-table 'test-rename-t2 :if-exists t :cascade t)
(drop-table 'test-schema.t2 :if-exists t :cascade t)
(drop-schema 'test-schema :cascade t :if-exists t)))
| null | https://raw.githubusercontent.com/atgreen/red-light-green-light/f067507721bbab4aa973866db5276c83df3e8784/local-projects/postmodern-20220220-git/postmodern/tests/tests.lisp | lisp | Syntax : Ansi - Common - Lisp ; Base : 10 ; Package : POSTMODERN - TESTS ; -*-
Adjust the above to some db/user/pass/host combination that refers
to a valid postgresql database in which no table named test_data
currently exists. Then after loading the file, run the tests with
(run! :postmodern)
Reset readtable to default
namespaces.
changing the search path
Setup new sequence
test sequence-exists-p with string
Test that we can set increment
Test that currval is not yet set
Test next value
Test currval
Testing that we can set max value
TODO: check here that we don't can do next past max-value
Test set min value
test remove max value
test remove min value
cleanup | (in-package :postmodern-tests)
(def-suite :postmodern
:description "Test suite for postmodern subdirectory files")
(def-suite :postmodern-base
:description "Base Test suite for postmodern subdirectory files")
(in-suite :postmodern-base)
(def-suite :postmodern-base
:description "Base test suite for postmodern"
:in :postmodern)
(in-suite :postmodern-base)
(defmacro with-binary (&body body)
`(let ((old-use-binary-parameters (connection-use-binary *database*)))
(use-binary-parameters *database* t)
(unwind-protect (progn ,@body)
(use-binary-parameters *database* old-use-binary-parameters))))
(defmacro without-binary (&body body)
`(let ((old-use-binary-parameters (connection-use-binary *database*)))
(use-binary-parameters *database* nil)
(unwind-protect (progn ,@body)
(use-binary-parameters *database* old-use-binary-parameters))))
(defun prompt-connection-to-postmodern-db-spec (param-lst)
"Takes the 6 item parameter list from prompt-connection and restates it for pomo:with-connection. Note that cl-postgres does not provide the pooled connection - that is only in postmodern - so that parameter is not passed."
(when (and (listp param-lst)
(= 6 (length param-lst)))
(destructuring-bind (db user password host port use-ssl) param-lst
(list db user password host :port port :use-ssl use-ssl))))
(defmacro with-test-connection (&body body)
`(with-connection (prompt-connection-to-postmodern-db-spec
(cl-postgres-tests:prompt-connection))
,@body))
(defmacro with-binary-test-connection (&body body)
`(with-connection (append (prompt-connection-to-postmodern-db-spec
(cl-postgres-tests:prompt-connection))
'(:use-binary t))
,@body))
(defmacro with-pooled-test-connection (&body body)
`(with-connection (append (prompt-connection-to-postmodern-db-spec
(cl-postgres-tests:prompt-connection))
'(:pooled-p t))
,@body))
(defmacro with-binary-pooled-test-connection (&body body)
`(with-connection (append (prompt-connection-to-postmodern-db-spec
(cl-postgres-tests:prompt-connection))
'(:pooled-p t :use-binary t))
,@body))
(defmacro protect (&body body)
`(unwind-protect (progn ,@(butlast body)) ,(car (last body))))
(test connect-sanely
"Check that with-test-connection and with-binary-test-connection actually connect"
(with-test-connection
(is (not (null *database*))))
(with-binary-test-connection
(is (not (null *database*)))
(is (connection-use-binary *database*))))
(defmacro with-application-connection (&body body)
`(with-connection
(append
(prompt-connection-to-postmodern-db-spec (cl-postgres-tests:prompt-connection))
'(:application-name "george"))
,@body))
(test application-name
(with-application-connection
(is (equal
(query "select distinct application_name from pg_stat_activity where application_name = 'george'"
:single)
"george"))))
(test connection-pool
(let* ((db-params (append (prompt-connection-to-postmodern-db-spec
(cl-postgres-tests:prompt-connection)) '(:pooled-p t)))
(pooled (apply 'connect db-params)))
(disconnect pooled)
(let ((pooled* (apply 'connect db-params)))
(is (eq pooled pooled*))
(disconnect pooled*))
(clear-connection-pool)
(let ((pooled* (apply 'connect db-params)))
(is (not (eq pooled pooled*)))
(disconnect pooled*))
(clear-connection-pool)))
(test reconnect
(with-test-connection
(disconnect *database*)
(is (not (connected-p *database*)))
(reconnect *database*)
(is (connected-p *database*))
(is (equal (get-search-path)
"\"$user\", public"))
(is (equal
(with-schema ("a")
(disconnect *database*)
(reconnect *database*)
(get-search-path))
"a"))
(is (equal (get-search-path)
"\"$user\", public"))))
(test simple-query
(with-test-connection
(destructuring-bind (a b c d e f)
(query (:select 22 (:type 44.5 double-precision) "abcde" t (:type 9/2 (numeric 5 2))
(:[] #("A" "B") 2)) :row)
(is (eql a 22))
(is (eql b 44.5d0))
(is (string= c "abcde"))
(is (eql d t))
(is (eql e 9/2))
(is (equal f "B")))))
(test reserved-words
(with-test-connection
(is (= (query (:select '*
:from (:as (:select (:as 1 'as)) 'where)
:where (:= 'where.as 1)) :single!)
1))))
(test time-types
"Ensure that we are using a readtable that reads into simple-dates."
(setf cl-postgres:*sql-readtable*
(cl-postgres:copy-sql-readtable
simple-date-cl-postgres-glue:*simple-date-sql-readtable*))
(with-test-connection
(is (time= (query (:select (:type (simple-date:encode-date 1980 2 1) date)) :single)
(encode-date 1980 2 1)))
(is (time= (query (:select (:type (simple-date:encode-timestamp 2040 3 19 12 15 0 2) timestamp))
:single)
(encode-timestamp 2040 3 19 12 15 0 2)))
(is (time= (query (:select (:type (simple-date:encode-interval :month -1 :hour 24) interval))
:single)
(encode-interval :month -1 :hour 24))))
(setf cl-postgres:*sql-readtable*
(cl-postgres:copy-sql-readtable
cl-postgres::*default-sql-readtable*)))
(test table-skeleton
(with-test-connection
(when (table-exists-p 'test-data) (execute (:drop-table 'test-data)))
(execute (:create-table test-data ((a :type integer :primary-key t) (b :type real)
(c :type (or text db-null))) (:unique c)))
(protect
(is (table-exists-p 'test-data))
(execute (:insert-into 'test-data :set 'a 1 'b 5.4 'c "foobar"))
(execute (:insert-into 'test-data :set 'a 2 'b 88 'c :null))
(is (equal (query (:order-by (:select '* :from 'test-data) 'a))
'((1 5.4 "foobar")
(2 88.0 :null))))
(execute (:drop-table 'test-data)))
(is (not (table-exists-p 'test-data)))))
(test doquery
(with-test-connection
(doquery (:select 55 "foobar") (number string)
(is (= number 55))
(is (string= string "foobar")))))
(test doquery-params
(with-test-connection
(doquery ("select $1::integer + 10" 20) (answer)
(is (= answer 30)))))
(test notification
(with-test-connection
(execute (:listen 'foo))
(with-test-connection
(execute (:notify 'foo)))
(is (cl-postgres:wait-for-notification *database*) "foo")))
(test split-fully-qualified-tablename
(is (equal (split-fully-qualified-tablename 'uniq.george)
'("george" "uniq" NIL)))
(is (equal (split-fully-qualified-tablename "george-and-gracie")
'("george_and_gracie" "public" NIL)))
(is (equal (split-fully-qualified-tablename "test.uniq.george-and-gracie")
'("george_and_gracie" "uniq" "test")))
(is (equal (split-fully-qualified-tablename 'test.uniq.george-and-gracie)
'("george_and_gracie" "uniq" "test"))))
create two tables with the same name in two different
(test namespace
(with-test-connection
(let ((excess-schemas
(set-difference (list-schemas)
'("public" "information_schema" "uniq")
:test #'equal)))
(when excess-schemas (loop for x in excess-schemas do
(drop-schema x :cascade 't))))
(when (table-exists-p 'test-uniq)
(execute (:drop-table 'test-uniq)))
(is (schema-exists-p :public))
(is (not (table-exists-p 'test-uniq)))
(unless (table-exists-p 'test-uniq)
(execute (:create-table test-uniq ((value :type integer)))))
(is (table-exists-p 'test-uniq))
(is (not (schema-exists-p 'uniq)))
(is (eq (column-exists-p 'public.test-uniq 'value) t))
(is (not (eq (column-exists-p 'public.test-uniq 'valuea) t)))
(is (eq (column-exists-p 'test-uniq 'value 'public) t))
(is (not (eq (column-exists-p 'test-uniq 'valuea 'public) t)))
(is (schema-exists-p 'uniq))
(is (schema-exists-p "uniq"))
(is (not (table-exists-p 'test-uniq 'uniq)))
(execute (:create-table test-uniq ((value :type integer))))
(is (table-exists-p 'test-uniq))
(execute (:drop-table 'test-uniq)))
(query (:create-table 'uniq.gracie ((id :type integer))))
(is (equal (list-tables-in-schema "uniq")
'("gracie")))
(is (equal (list-tables-in-schema 'uniq)
'("gracie")))
(query (:create-table "uniq.george" ((id :type integer))))
(is (equal (list-tables-in-schema "uniq")
'("george" "gracie")))
(is (table-exists-p "test.uniq.george"))
(is (table-exists-p "uniq.george"))
(is (table-exists-p "george" "uniq"))
(is (table-exists-p 'test.uniq.george))
(is (table-exists-p 'uniq.george))
(is (table-exists-p 'george 'uniq))
(is (schema-exists-p 'uniq))
(drop-schema 'uniq :cascade 't)
(is (not (schema-exists-p 'uniq)))
(create-schema 'uniq)
(format t "List-schemas ~a~%" (list-schemas))
(is (equal "uniq" (find "uniq" (list-schemas) :test #'equal)))
(drop-schema "uniq" :cascade 't)
(is (not (schema-exists-p "uniq")))
(create-schema "uniq")
(is (equal "uniq" (find "uniq" (list-schemas) :test #'equal)))
(drop-schema 'uniq :cascade 't)
(is (equal (get-search-path)
"\"$user\", public"))
(execute (:drop-table 'test-uniq))))
(test arrays-skeleton
(with-test-connection
(when (table-exists-p 'test-data) (execute (:drop-table 'test-data)))
(execute (:create-table test-data ((a :type integer[]))))
(protect
(is (table-exists-p 'test-data))
(execute (:insert-into 'test-data :set 'a (vector 3 4 5)))
(execute (:insert-into 'test-data :set 'a #()))
(execute (:drop-table 'test-data)))
(is (not (table-exists-p 'test-data)))))
(test find-primary-key-info
"Testing find-primary-key-info function. Given a table name, it returns
a list of two strings. First the column name of the primary key of the table
and second the string name for the datatype."
(with-test-connection
(execute "create temporary table tasks_lists (id integer primary key)")
(is (equal (postmodern:find-primary-key-info (s-sql:to-sql-name "tasks_lists"))
'(("id" "integer"))))
(is (equal (postmodern:find-primary-key-info (s-sql:to-sql-name "tasks_lists") t)
'("id")))))
(test list-indices
"Check the sql generated by the list-indices code"
(is (equal (sql (postmodern::make-list-query "i"))
"E'((SELECT relname FROM pg_catalog.pg_class INNER JOIN pg_catalog.pg_namespace ON (relnamespace = pg_namespace.oid) WHERE ((relkind = E''i'') and (nspname NOT IN (E''pg_catalog'', E''pg_toast'')) and pg_catalog.pg_table_is_visible(pg_class.oid))) ORDER BY relname)'")))
(test list-indices-and-constraints
"Test various index functions"
(with-test-connection
(pomo:drop-table 'people :if-exists t :cascade t)
(query (:create-table 'people ((id :type (or integer db-null) :primary-key :identity-by-default)
(first-name :type (or (varchar 50) db-null))
(last-name :type (or (varchar 50) db-null)))))
(query (:create-index 'idx-people-names :on 'people :fields 'last-name 'first-name))
(query (:create-index 'idx-people-first-names :on 'people :fields 'first-name))
(query (:insert-rows-into 'people
:columns 'first-name 'last-name
:values '(("Eliza" "Gregory") ("Dean" "Rodgers") ("Christine" "Alvarez")
("Dennis" "Peterson") ("Ernest" "Roberts") ("Jorge" "Wood")
("Harvey" "Strickland") ("Eugene" "Rivera")
("Tillie" "Bell") ("Marie" "Lloyd") ("John" "Lyons")
("Lucas" "Gray") ("Edward" "May")
("Randy" "Fields") ("Nell" "Malone") ("Jacob" "Maxwell")
("Vincent" "Adams") ("Henrietta" "Schneider")
("Ernest" "Mendez") ("Jean" "Adams") ("Olivia" "Adams"))))
(let ((idx-symbol (first (list-indices)))
(idx-string (first (list-indices t))))
(is (pomo:index-exists-p idx-symbol))
(is (pomo:index-exists-p idx-string)))
(is (equal (list-table-indices 'people)
'((:IDX-PEOPLE-FIRST-NAMES :FIRST-NAME) (:IDX-PEOPLE-NAMES :FIRST-NAME)
(:IDX-PEOPLE-NAMES :LAST-NAME) (:PEOPLE-PKEY :ID))))
(is (equal (list-table-indices 'people t)
'(("idx_people_first_names" "first_name") ("idx_people_names" "first_name")
("idx_people_names" "last_name") ("people_pkey" "id"))))
(is (equal (list-table-indices "people")
'((:IDX-PEOPLE-FIRST-NAMES :FIRST-NAME) (:IDX-PEOPLE-NAMES :FIRST-NAME)
(:IDX-PEOPLE-NAMES :LAST-NAME) (:PEOPLE-PKEY :ID))))
(is (equal (list-table-indices "people" t)
'(("idx_people_first_names" "first_name") ("idx_people_names" "first_name")
("idx_people_names" "last_name") ("people_pkey" "id"))))
(is (equal (list-unique-or-primary-constraints "people" t)
'(("people_pkey"))))
(is (equal (list-unique-or-primary-constraints "people")
'((:PEOPLE-PKEY))))
(is (equal (length (list-all-constraints 'people))
2))
(is (equal (length (list-all-constraints "people"))
2))
(query (:alter-table 'people :drop-constraint 'people-pkey))
(is (equal (length (list-all-constraints "people"))
1))
(execute (:drop-table 'people))))
(test drop-indices
"Test drop index variations"
(with-test-connection
(query (:drop-table :if-exists 'george :cascade))
(query (:create-table 'george ((id :type integer))))
(query (:create-index 'george-idx :on 'george :fields 'id))
(is (equal (list-table-indices 'george)
'((:GEORGE-IDX :ID))))
(is (index-exists-p 'george-idx))
(query (:drop-index :if-exists 'george-idx))
(is (not (index-exists-p 'george-idx)))
(is (equal (sql (:drop-index :if-exists 'george-idx :cascade))
"DROP INDEX IF EXISTS george_idx CASCADE"))
(is (equal (sql (:drop-index (:if-exists 'george-idx) :cascade))
"DROP INDEX IF EXISTS george_idx CASCADE"))
(is (equal (sql (:drop-index :concurrently (:if-exists 'george-idx) :cascade))
"DROP INDEX CONCURRENTLY IF EXISTS george_idx CASCADE"))
(is (equal (sql (:drop-index :concurrently (:if-exists 'george-idx)))
"DROP INDEX CONCURRENTLY IF EXISTS george_idx"))
(is (equal (sql (:drop-index :concurrently 'george-idx))
"DROP INDEX CONCURRENTLY george_idx"))
(is (equal (sql (:drop-index 'george-idx))
"DROP INDEX george_idx"))
(query (:drop-table :if-exists 'george :cascade))))
(test sequence
"Sequence testing"
(with-test-connection
(when (sequence-exists-p 'my-seq)
(execute (:drop-sequence 'my-seq)))
(execute (:create-sequence 'my-seq :increment 4 :start 10))
(protect
(is (sequence-exists-p 'my-seq))
(is (= (sequence-next 'my-seq) 10))
(is (= (sequence-next 'my-seq) 14))
(execute (:drop-sequence 'my-seq)))
(is (not (sequence-exists-p 'my-seq)))
(when (sequence-exists-p :knobo-seq)
(query (:drop-sequence :knobo-seq)))
(is (eq
(query (:create-sequence 'knobo-seq) :single)
nil))
(is (sequence-exists-p (first (list-sequences t))))
(is (equal (sql (:alter-sequence :knobo-seq :increment 1))
"ALTER SEQUENCE knobo_seq INCREMENT BY 1"))
(is (equal (sql (:alter-sequence 'knobo-seq :increment 1))
"ALTER SEQUENCE knobo_seq INCREMENT BY 1"))
(is (eq (query (:alter-sequence 'knobo-seq :increment 1))
nil))
(is (equal (sql (:select (:currval 'knobo-seq)))
"(SELECT currval(E'knobo_seq'))"))
(is (equal (sql (:select (:currval :knobo-seq)))
"(SELECT currval(E'knobo_seq'))"))
(signals error (query (:select (:currval 'knobo-seq)) :single))
(is (equal (query (:select (:nextval 'knobo-seq)) :single)
1))
(is (eq (query (:select (:currval 'knobo-seq)) :single) 1))
Test that we can set restart at 2
TODO Test that when we restart , we get 2 .
(is (equal (sql (:alter-sequence 'knobo-seq :start 2))
"ALTER SEQUENCE knobo_seq START 2"))
(is (eq (query (:alter-sequence 'knobo-seq :start 2))
nil))
(is (equal (sql (:alter-sequence 'knobo-seq :max-value 5))
"ALTER SEQUENCE knobo_seq MAXVALUE 5"))
(is (eq (query (:alter-sequence 'knobo-seq :max-value 5))
nil))
(is (equal (query (:select (:nextval 'knobo-seq)) :single) 2))
(is (equal (sql (:alter-sequence 'knobo-seq :start 3))
"ALTER SEQUENCE knobo_seq START 3"))
(is (eq (query (:alter-sequence 'knobo-seq :start 3))
nil))
(is (equal (sql (:alter-sequence 'knobo-seq :min-value 2))
"ALTER SEQUENCE knobo_seq MINVALUE 2"))
(signals error (query (:alter-sequence 'knobo-seq :min-value 3)))
(is (equal (query (:alter-sequence 'knobo-seq :min-value 2)) nil))
(is (equal (sql (:alter-sequence 'knobo-seq :no-max))
"ALTER SEQUENCE knobo_seq NO MAXVALUE"))
(is (eq (query (:alter-sequence 'knobo-seq :no-max))
nil))
(is (equal (sql (:alter-sequence 'knobo-seq :no-min))
"ALTER SEQUENCE knobo_seq NO MINVALUE"))
(is (eq (query (:alter-sequence 'knobo-seq :no-min))
nil))
(is (eq (query (:alter-sequence 'knobo-seq :cycle))
nil))
(is (eq (query (:alter-sequence 'knobo-seq :no-cycle))
nil))
(is (eq (query (:alter-sequence 'knobo-seq :cache 1))
nil))
(unless (table-exists-p 'seq-test)
(query (:create-table 'seq-test ((:id :type :int)))))
(is (eq (query (:alter-sequence 'knobo-seq :owned-by :seq-test.id))
nil))
(is (eq (sequence-exists-p 'knobo-seq)
t))
(query (:drop-sequence 'knobo-seq))
(is (eq (sequence-exists-p 'knobo-seq)
nil))
(query (:drop-table 'seq-test))))
(test schema-comments
(with-test-connection
(when (schema-exists-p "schema_1")
(drop-schema "schema_1" :cascade t))
(create-schema "schema_1")
(when (table-exists-p "p1")
(drop-table "p1" :cascade t))
(query (:create-table "p1"
((id :type integer :generated-as-identity-always t)
(text :type text))))
(query (:create-table "schema_1.s1"
((id :type integer :generated-as-identity-always t)
(text :type text))))
(add-comment :table 'p1 "a comment on recipes")
(add-comment :table 'schema-1.s1 "a comment on schema-1 s1")
(is (equal (get-table-comment 'p1)
"a comment on recipes"))
(is (equal (integerp (get-table-oid 'schema-1.s1)) t))
(is (equal (integerp (get-table-oid 'information-schema.columns)) t))
(is (equal (get-table-comment 'schema-1.s1)
"a comment on schema-1 s1"))
(drop-schema "schema_1" :cascade t)
(drop-table "p1" :cascade t)))
(test valid-sql-identifier-p
(is (equal (valid-sql-identifier-p "abc") T))
(is (equal (valid-sql-identifier-p "_abc3") T))
(is (equal (valid-sql-identifier-p "abc-3") NIL))
(is (equal (valid-sql-identifier-p "abc$q7") T))
(is (equal (valid-sql-identifier-p "_abc;'sd") NIL))
(is (equal (valid-sql-identifier-p "haček") T))
(is (equal (valid-sql-identifier-p "Tuđman") T))
(is (equal (valid-sql-identifier-p "Åland") T))
(is (equal (valid-sql-identifier-p "hôtel") T))
(is (equal (valid-sql-identifier-p "piñata") T))
(is (equal (valid-sql-identifier-p "frappé") T))
(is (equal (valid-sql-identifier-p "تَشْكِيل") NIL))
(is (equal (valid-sql-identifier-p "تسير") T))
(is (equal (valid-sql-identifier-p "إمرأة") T))
(is (equal (valid-sql-identifier-p "أهلا") T))
(is (equal (valid-sql-identifier-p "أداة") T))
(is (equal (valid-sql-identifier-p "شخصا") T))
(is (equal (valid-sql-identifier-p "새우") T))
(is (equal (valid-sql-identifier-p "이해") T))
(is (equal (valid-sql-identifier-p "죄") T))
(is (equal (valid-sql-identifier-p "国") T))
(is (equal (valid-sql-identifier-p "高さ") T))
(is (equal (valid-sql-identifier-p "たかさ") T))
(is (equal (valid-sql-identifier-p "住所") T))
(is (equal (valid-sql-identifier-p "会议") T))
(is (equal (valid-sql-identifier-p "kusipää") T)))
(test rename-table-and-columns
(with-test-connection
(when (schema-exists-p 'test-schema)
(drop-schema 'test-schema :cascade t :if-exists t))
(create-schema 'test-schema)
(when (table-exists-p 'test-schema.t1)
(drop-table 'test-schema.t1 :if-exists t :cascade t))
(when (table-exists-p 'test-rename-t1)
(drop-table 'test-rename-t1 :if-exists t :cascade t))
(when (table-exists-p 'test-rename-t2)
(drop-table 'test-rename-t2 :if-exists t :cascade t))
(when (table-exists-p 'test-rename-t3)
(drop-table 'test-rename-t3 :if-exists t :cascade t))
(query (:create-table 'test-schema.t1 ((id :type (or integer db-null)))))
(query (:create-table 'test-rename-t1 ((id :type (or integer db-null)))))
(is (table-exists-p 'test-schema.t1))
(is (rename-table 'test-schema.t1 'test-schema.t2))
(is (table-exists-p 'test-schema.t2))
(is (rename-table 'test-schema.t2 't3))
(is (table-exists-p 'test-schema.t3))
(is (column-exists-p 'test-schema.t3 'id))
(is (rename-column 'test-schema.t3 'id 'new-id))
(is (column-exists-p 'test-schema.t3 'new-id))
(is (rename-column 'test-schema.t3 "new_id" "id"))
(is (column-exists-p "test-schema.t3" "id"))
(is (rename-table "test-schema.t3" "t2"))
(is (table-exists-p "test-schema.t2"))
(is (table-exists-p 'test-rename-t1))
(is (rename-table 'test-rename-t1 'test-rename-t2))
(is (table-exists-p 'test-rename-t2))
(is (rename-table 'test-rename-t2 'test-rename-t3))
(is (table-exists-p 'test-rename-t3))
(is (column-exists-p 'test-rename-t3 'id))
(is (rename-column 'test-rename-t3 'id 'new-id))
(is (column-exists-p 'test-rename-t3 'new-id))
(is (rename-column 'test-rename-t3 "new_id" "id"))
(is (column-exists-p "test-rename-t3" "id"))
(is (rename-table "test-rename-t3" "test-rename-t2"))
(is (table-exists-p "test-rename-t2"))
(drop-table 'test-rename-t2 :if-exists t :cascade t)
(drop-table 'test-schema.t2 :if-exists t :cascade t)
(drop-schema 'test-schema :cascade t :if-exists t)))
|
0150176fba0c70b00103f13d29dbf85b8c4b75c075c5d2edea00b7f51774b641 | tomjridge/mini-btree | btree_impl_intf.ml | (** Main implementation types *)
type constants = {
max_leaf_keys : int;
max_branch_keys : int;
}
(** Calculate constants given blk size and k and v size. NOTE assumes type r = int *)
let make_constants ~blk_sz ~k_sz ~v_sz =
let bytes_per_int = 10 in (* over estimate *)
let r_sz = bytes_per_int in
NOTE subtract bytes_per_int for the tag
let constants = {
FIXME why 2 * ( .. ) ?
max_branch_keys = (blk_sz - bytes_per_int)/(k_sz+r_sz)
}
in
constants
type 'k k_cmp = {
k_cmp: 'k -> 'k -> int
}
(** NOTE Leaves are mutable *)
type ('k,'v,'leaf) leaf_ops = {
lookup : 'k -> 'leaf -> 'v option;
insert : 'k -> 'v -> 'leaf -> unit;
remove : 'k -> 'leaf -> unit;
leaf_nkeys : 'leaf -> int;
split_leaf : int -> 'leaf -> 'leaf*'k*'leaf; (* first leaf has n keys *)
to_kvs : 'leaf -> ('k*'v) list;
of_kvs : ('k*'v) list -> 'leaf;
}
module Top_or_bottom = struct
type 'k or_top = 'k option
type 'k or_bottom = 'k option
end
open Top_or_bottom
let k_lt ~k_cmp ~k1 ~k2 =
match k2 with
| None -> true
| Some k2 -> k_cmp.k_cmp k1 k2 < 0
let k_leq ~k_cmp ~k1 ~k2 =
match k1 with
| None -> true
| Some k1 -> k_cmp.k_cmp k1 k2 < 0
type ('k,'r) segment = 'k or_bottom * 'r * ('k*'r) list * 'k or_top
(** NOTE Nodes are mutable *)
type ('k,'r,'branch) branch_ops = {
find : 'k -> 'branch -> ('k or_bottom*'r*'k or_top);
branch_nkeys : 'branch -> int;
first branch has n keys ; n>=1
make_small_root : 'r*'k*'r -> 'branch;
to_krs : 'branch -> ('k list * 'r list);
of_krs : ('k list * 'r list) -> 'branch;
replace : ('k,'r) segment -> ('k,'r) segment -> 'branch -> unit;
}
type ('branch,'leaf,'node) node_ops = {
cases: 'a. 'node -> leaf:('leaf -> 'a) -> branch:('branch -> 'a) -> 'a;
of_leaf: 'leaf -> 'node;
of_branch: 'branch -> 'node;
}
type ('r,'node) store_ops = {
read : 'r -> 'node;
write : 'r -> 'node -> unit;
flush : unit -> unit;
}
type 'r free = { free: 'r list }[@@inline]
type 'r new_root = { new_root: 'r }[@@inline]
type ('k,'v,'r) insert_many_return_type =
| Rebuilt of 'r free * 'r new_root option * ('k * 'v) list
| Remaining of ('k * 'v) list
| Unchanged_no_kvs
(** Types used for exporting/importing only *)
type ('k,'v,'r) export_t =
[ `On_disk of 'r * [ `Leaf of ('k*'v) list | `Branch of 'k list * ('k,'v,'r) export_t list ] ]
type ('k,'v,'r) btree_ops = {
find: r:'r -> k:'k -> 'v option;
insert: k:'k -> v:'v -> r:'r -> ('r free * 'r new_root option);
insert_many:
kvs:('k * 'v) list ->
r:'r ->
('k,'v,'r) insert_many_return_type;
delete: k:'k -> r:'r -> unit;
export: 'r -> ('k,'v,'r) export_t;
}
(** What we need to construct the B-tree *)
module type S_kvr = sig
type k
type v
type r
val constants : constants
val k_cmp : k k_cmp
end
(** What we get after constructing the B-tree *)
module type T = sig
type k
type v
type r
(* Leaf, branch implementations *)
type leaf
type branch
type node
val leaf : (k, v, leaf) leaf_ops
val branch : (k, r, branch) branch_ops
val node : (branch, leaf, node) node_ops
(* Make function *)
val make :
store : (r, node) store_ops ->
alloc : (unit -> r) ->
(k, v, r) btree_ops
end
(** Type of the make functor *)
module type MAKE = functor (S:S_kvr) -> T with type k=S.k and type v=S.v and type r=S.r
let blk_sz_4096 = 4096
(** Example, k=int, v=int, r=int *)
module Int_int = struct
let blk_sz = blk_sz_4096
type k = int
type v = int
type r = int
let k_cmp = {k_cmp=Int.compare}
NOTE 10 is max size of marshalled int
let constants = make_constants ~blk_sz ~k_sz:10 ~v_sz:10
end
module type EXAMPLE_INT_INT = T with type k=int and type v=int and type r=int
| null | https://raw.githubusercontent.com/tomjridge/mini-btree/63085e877adf9d27d9ebc82a87914f9f1686f55d/src/btree_impl_intf.ml | ocaml | * Main implementation types
* Calculate constants given blk size and k and v size. NOTE assumes type r = int
over estimate
* NOTE Leaves are mutable
first leaf has n keys
* NOTE Nodes are mutable
* Types used for exporting/importing only
* What we need to construct the B-tree
* What we get after constructing the B-tree
Leaf, branch implementations
Make function
* Type of the make functor
* Example, k=int, v=int, r=int |
type constants = {
max_leaf_keys : int;
max_branch_keys : int;
}
let make_constants ~blk_sz ~k_sz ~v_sz =
let r_sz = bytes_per_int in
NOTE subtract bytes_per_int for the tag
let constants = {
FIXME why 2 * ( .. ) ?
max_branch_keys = (blk_sz - bytes_per_int)/(k_sz+r_sz)
}
in
constants
type 'k k_cmp = {
k_cmp: 'k -> 'k -> int
}
type ('k,'v,'leaf) leaf_ops = {
lookup : 'k -> 'leaf -> 'v option;
insert : 'k -> 'v -> 'leaf -> unit;
remove : 'k -> 'leaf -> unit;
leaf_nkeys : 'leaf -> int;
to_kvs : 'leaf -> ('k*'v) list;
of_kvs : ('k*'v) list -> 'leaf;
}
module Top_or_bottom = struct
type 'k or_top = 'k option
type 'k or_bottom = 'k option
end
open Top_or_bottom
let k_lt ~k_cmp ~k1 ~k2 =
match k2 with
| None -> true
| Some k2 -> k_cmp.k_cmp k1 k2 < 0
let k_leq ~k_cmp ~k1 ~k2 =
match k1 with
| None -> true
| Some k1 -> k_cmp.k_cmp k1 k2 < 0
type ('k,'r) segment = 'k or_bottom * 'r * ('k*'r) list * 'k or_top
type ('k,'r,'branch) branch_ops = {
find : 'k -> 'branch -> ('k or_bottom*'r*'k or_top);
branch_nkeys : 'branch -> int;
first branch has n keys ; n>=1
make_small_root : 'r*'k*'r -> 'branch;
to_krs : 'branch -> ('k list * 'r list);
of_krs : ('k list * 'r list) -> 'branch;
replace : ('k,'r) segment -> ('k,'r) segment -> 'branch -> unit;
}
type ('branch,'leaf,'node) node_ops = {
cases: 'a. 'node -> leaf:('leaf -> 'a) -> branch:('branch -> 'a) -> 'a;
of_leaf: 'leaf -> 'node;
of_branch: 'branch -> 'node;
}
type ('r,'node) store_ops = {
read : 'r -> 'node;
write : 'r -> 'node -> unit;
flush : unit -> unit;
}
type 'r free = { free: 'r list }[@@inline]
type 'r new_root = { new_root: 'r }[@@inline]
type ('k,'v,'r) insert_many_return_type =
| Rebuilt of 'r free * 'r new_root option * ('k * 'v) list
| Remaining of ('k * 'v) list
| Unchanged_no_kvs
type ('k,'v,'r) export_t =
[ `On_disk of 'r * [ `Leaf of ('k*'v) list | `Branch of 'k list * ('k,'v,'r) export_t list ] ]
type ('k,'v,'r) btree_ops = {
find: r:'r -> k:'k -> 'v option;
insert: k:'k -> v:'v -> r:'r -> ('r free * 'r new_root option);
insert_many:
kvs:('k * 'v) list ->
r:'r ->
('k,'v,'r) insert_many_return_type;
delete: k:'k -> r:'r -> unit;
export: 'r -> ('k,'v,'r) export_t;
}
module type S_kvr = sig
type k
type v
type r
val constants : constants
val k_cmp : k k_cmp
end
module type T = sig
type k
type v
type r
type leaf
type branch
type node
val leaf : (k, v, leaf) leaf_ops
val branch : (k, r, branch) branch_ops
val node : (branch, leaf, node) node_ops
val make :
store : (r, node) store_ops ->
alloc : (unit -> r) ->
(k, v, r) btree_ops
end
module type MAKE = functor (S:S_kvr) -> T with type k=S.k and type v=S.v and type r=S.r
let blk_sz_4096 = 4096
module Int_int = struct
let blk_sz = blk_sz_4096
type k = int
type v = int
type r = int
let k_cmp = {k_cmp=Int.compare}
NOTE 10 is max size of marshalled int
let constants = make_constants ~blk_sz ~k_sz:10 ~v_sz:10
end
module type EXAMPLE_INT_INT = T with type k=int and type v=int and type r=int
|
48dff044c31d577146e9b126af1cbae5ebf969e784891e8b99859fba3ab8ea04 | S8A/htdp-exercises | ex172.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-reader.ss" "lang")((modname ex172) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp")) #f)))
A List - of - strings ( LS ) is one of :
; - '()
; - (cons String LS)
(define ex1 (cons "TTT"
(cons ""
(cons "Put up in a place"
(cons "something" '())))))
(define ex2 (cons "TTT"
(cons "Put"
(cons "up"
(cons "in"
(cons "a" '()))))))
(define ttt1 (read-lines "ttt.txt"))
(define ttt2 (read-words "ttt.txt"))
List - of - list - of - strings ( LLS ) is one of :
; - '()
- ( cons List - of - strings LLS )
(define ex3 (cons (cons "TTT" '())
(cons '()
(cons (cons "Put"
(cons "up"
(cons "in" '())))
(cons (cons "damn" '()) '())))))
(define ttt3 (read-words/line "ttt.txt"))
(define line0 (cons "hello" (cons "world" '())))
(define line1 '())
(define lls0 '())
(define lls1 (cons line0 (cons line1 '())))
; LLS -> String
; converts a list of lines into a string, words separated by blank spaces
; and lines separated by newlines.
(define (collapse lls)
(cond
[(empty? lls) "\n"]
[(cons? lls)
(string-append (line-string (first lls)) (collapse (rest lls)))]))
(check-expect (collapse lls0) "")
(check-expect (collapse lls1) "hello world\n")
(check-expect (collapse ex3) "TTT\nPut up in\ndamn\n")
; List-of-strings -> String
; converts a line into a string, words separated by blank spaces
(define (line-string los)
(cond
[(empty? los) ""]
[(cons? los)
(string-append (first los) " " (line-string (rest los)))]))
(check-expect (line-string line0) "hello world")
(check-expect (line-string line1) "")
| null | https://raw.githubusercontent.com/S8A/htdp-exercises/578e49834a9513f29ef81b7589b28081c5e0b69f/ex172.rkt | racket | about the language level of this file in a form that our tools can easily process.
- '()
- (cons String LS)
- '()
LLS -> String
converts a list of lines into a string, words separated by blank spaces
and lines separated by newlines.
List-of-strings -> String
converts a line into a string, words separated by blank spaces | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-beginner-reader.ss" "lang")((modname ex172) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp")) #f)))
A List - of - strings ( LS ) is one of :
(define ex1 (cons "TTT"
(cons ""
(cons "Put up in a place"
(cons "something" '())))))
(define ex2 (cons "TTT"
(cons "Put"
(cons "up"
(cons "in"
(cons "a" '()))))))
(define ttt1 (read-lines "ttt.txt"))
(define ttt2 (read-words "ttt.txt"))
List - of - list - of - strings ( LLS ) is one of :
- ( cons List - of - strings LLS )
(define ex3 (cons (cons "TTT" '())
(cons '()
(cons (cons "Put"
(cons "up"
(cons "in" '())))
(cons (cons "damn" '()) '())))))
(define ttt3 (read-words/line "ttt.txt"))
(define line0 (cons "hello" (cons "world" '())))
(define line1 '())
(define lls0 '())
(define lls1 (cons line0 (cons line1 '())))
(define (collapse lls)
(cond
[(empty? lls) "\n"]
[(cons? lls)
(string-append (line-string (first lls)) (collapse (rest lls)))]))
(check-expect (collapse lls0) "")
(check-expect (collapse lls1) "hello world\n")
(check-expect (collapse ex3) "TTT\nPut up in\ndamn\n")
(define (line-string los)
(cond
[(empty? los) ""]
[(cons? los)
(string-append (first los) " " (line-string (rest los)))]))
(check-expect (line-string line0) "hello world")
(check-expect (line-string line1) "")
|
5552f816dff877ca6edda4e37bf12ec10b0c5f2da763e05b9c59b2971aaf523f | tmcgilchrist/ocaml-gitlab | types.mli | type binding = string * string (* Key/value pair *)
type section = string * binding list (* Section name and contents *)
type config = section list
| null | https://raw.githubusercontent.com/tmcgilchrist/ocaml-gitlab/de4d1cc31d172e599943fe712269f165f1c88909/cli/gitconfig/types.mli | ocaml | Key/value pair
Section name and contents | type config = section list
|
d172feabb42760d62e78cd0dbf9b6550122cb58c28371b4760315b6903822e00 | nomeata/haskell-via-sokoban | 03-list-fun.hs | {-# LANGUAGE OverloadedStrings #-}
import CodeWorld
wall, ground, storage, box :: Picture
wall = colored grey (solidRectangle 1 1)
ground = colored yellow (solidRectangle 1 1)
storage = colored white (solidCircle 0.3) & ground
box = colored brown (solidRectangle 1 1)
data Tile = Wall | Ground | Storage | Box | Blank
drawTile :: Tile -> Picture
drawTile Wall = wall
drawTile Ground = ground
drawTile Storage = storage
drawTile Box = box
drawTile Blank = blank
pictureOfMaze :: Picture
pictureOfMaze = draw21times (\r -> draw21times (\c -> drawTileAt (C r c)))
draw21times :: (Integer -> Picture) -> Picture
draw21times something = go (-10)
where
go :: Integer -> Picture
go 11 = blank
go n = something n & go (n+1)
drawTileAt :: Coord -> Picture
drawTileAt c = atCoord c (drawTile (maze c))
maze :: Coord -> Tile
maze (C x y)
| abs x > 4 || abs y > 4 = Blank
| abs x == 4 || abs y == 4 = Wall
| x == 2 && y <= 0 = Wall
| x == 3 && y <= 0 = Storage
| x >= -2 && y == 0 = Box
| otherwise = Ground
data Direction = R | U | L | D
data Coord = C Integer Integer
initialCoord :: Coord
initialCoord = C 0 0
atCoord :: Coord -> Picture -> Picture
atCoord (C x y) pic = translated (fromIntegral x) (fromIntegral y) pic
adjacentCoord :: Direction -> Coord -> Coord
adjacentCoord R (C x y) = C (x+1) y
adjacentCoord U (C x y) = C x (y+1)
adjacentCoord L (C x y) = C (x-1) y
adjacentCoord D (C x y) = C x (y-1)
Exercise 1
handleEvent :: Event -> State -> State
handleEvent (KeyPress key) c
| key == "Right" = tryGoTo c R
| key == "Up" = tryGoTo c U
| key == "Left" = tryGoTo c L
| key == "Down" = tryGoTo c D
| otherwise = c
handleEvent _ c = c
isOk :: Tile -> Bool
isOk Ground = True
isOk Storage = True
isOk _ = False
player :: Direction -> Picture
player R = translated 0 0.3 cranium
& polyline [(0,0),(0.3,0.05)]
& polyline [(0,0),(0.3,-0.05)]
& polyline [(0,-0.2),(0,0.1)]
& polyline [(0,-0.2),(0.1,-0.5)]
& polyline [(0,-0.2),(-0.1,-0.5)]
where cranium = circle 0.18
& sector (7/6*pi) (1/6*pi) 0.18
player L = scaled (-1) 1 (player R) -- Cunning!
player U = translated 0 0.3 cranium
& polyline [(0,0),(0.3,0.05)]
& polyline [(0,0),(-0.3,0.05)]
& polyline [(0,-0.2),(0,0.1)]
& polyline [(0,-0.2),(0.1,-0.5)]
& polyline [(0,-0.2),(-0.1,-0.5)]
where cranium = solidCircle 0.18
player D = translated 0 0.3 cranium
& polyline [(0,0),(0.3,-0.05)]
& polyline [(0,0),(-0.3,-0.05)]
& polyline [(0,-0.2),(0,0.1)]
& polyline [(0,-0.2),(0.1,-0.5)]
& polyline [(0,-0.2),(-0.1,-0.5)]
where cranium = circle 0.18
& translated 0.06 0.08 (solidCircle 0.04)
& translated (-0.06) 0.08 (solidCircle 0.04)
data State = State Coord Direction
initialState :: State
initialState = State (C 0 1) R
tryGoTo :: State -> Direction -> State
tryGoTo (State from _) d
| isOk (maze to) = State to d
| otherwise = State from d
where to = adjacentCoord d from
drawState :: State -> Picture
drawState (State c d) = atCoord c (player d) & pictureOfMaze
data Activity world = Activity
world
(Event -> world -> world)
(world -> Picture)
resetable :: Activity s -> Activity s
resetable (Activity state0 handle draw)
= Activity state0 handle' draw
where handle' (KeyPress key) _ | key == "Esc" = state0
handle' e s = handle e s
startScreen :: Picture
startScreen = scaled 3 3 (lettering "Sokoban!")
data SSState world = StartScreen | Running world
withStartScreen :: Activity s-> Activity (SSState s)
withStartScreen (Activity state0 handle draw)
= Activity state0' handle' draw'
where
state0' = StartScreen
handle' (KeyPress key) StartScreen
| key == " " = Running state0
handle' _ StartScreen = StartScreen
handle' e (Running s) = Running (handle e s)
draw' StartScreen = startScreen
draw' (Running s) = draw s
runActivity :: Activity s -> IO ()
runActivity (Activity state0 handle draw)
= activityOf state0 handle draw
sokoban :: Activity State
sokoban = Activity initialState handleEvent drawState
data List a = Empty | Entry a (List a)
someBoxCoords :: List Coord
someBoxCoords = Entry (C 2 2) (Entry (C 3 3) (Entry (C (-1) 0) Empty))
combine :: List Picture -> Picture
combine Empty = blank
combine (Entry p ps) = p & combine ps
boxes :: List Coord -> Picture
boxes cs = combine (mapList (\c -> atCoord c (drawTile Box)) cs)
movingBoxes :: Activity (List Coord)
movingBoxes = Activity someBoxCoords handle draw
where
draw = boxes
handle (KeyPress key) s
| key == "Right" = mapList (adjacentCoord R) s
| key == "Up" = mapList (adjacentCoord U) s
| key == "Left" = mapList (adjacentCoord L) s
| key == "Down" = mapList (adjacentCoord D) s
handle _ s = s
mapList :: (a -> b) -> List a -> List b
mapList _ Empty = Empty
mapList f (Entry c cs) = Entry (f c) (mapList f cs)
main :: IO ()
main = runActivity movingBoxes
| null | https://raw.githubusercontent.com/nomeata/haskell-via-sokoban/0ae9d6e120c2851eca158c01e08e2c4c7f2b06d0/code/03-list-fun.hs | haskell | # LANGUAGE OverloadedStrings #
Cunning! | import CodeWorld
wall, ground, storage, box :: Picture
wall = colored grey (solidRectangle 1 1)
ground = colored yellow (solidRectangle 1 1)
storage = colored white (solidCircle 0.3) & ground
box = colored brown (solidRectangle 1 1)
data Tile = Wall | Ground | Storage | Box | Blank
drawTile :: Tile -> Picture
drawTile Wall = wall
drawTile Ground = ground
drawTile Storage = storage
drawTile Box = box
drawTile Blank = blank
pictureOfMaze :: Picture
pictureOfMaze = draw21times (\r -> draw21times (\c -> drawTileAt (C r c)))
draw21times :: (Integer -> Picture) -> Picture
draw21times something = go (-10)
where
go :: Integer -> Picture
go 11 = blank
go n = something n & go (n+1)
drawTileAt :: Coord -> Picture
drawTileAt c = atCoord c (drawTile (maze c))
maze :: Coord -> Tile
maze (C x y)
| abs x > 4 || abs y > 4 = Blank
| abs x == 4 || abs y == 4 = Wall
| x == 2 && y <= 0 = Wall
| x == 3 && y <= 0 = Storage
| x >= -2 && y == 0 = Box
| otherwise = Ground
data Direction = R | U | L | D
data Coord = C Integer Integer
initialCoord :: Coord
initialCoord = C 0 0
atCoord :: Coord -> Picture -> Picture
atCoord (C x y) pic = translated (fromIntegral x) (fromIntegral y) pic
adjacentCoord :: Direction -> Coord -> Coord
adjacentCoord R (C x y) = C (x+1) y
adjacentCoord U (C x y) = C x (y+1)
adjacentCoord L (C x y) = C (x-1) y
adjacentCoord D (C x y) = C x (y-1)
Exercise 1
handleEvent :: Event -> State -> State
handleEvent (KeyPress key) c
| key == "Right" = tryGoTo c R
| key == "Up" = tryGoTo c U
| key == "Left" = tryGoTo c L
| key == "Down" = tryGoTo c D
| otherwise = c
handleEvent _ c = c
isOk :: Tile -> Bool
isOk Ground = True
isOk Storage = True
isOk _ = False
player :: Direction -> Picture
player R = translated 0 0.3 cranium
& polyline [(0,0),(0.3,0.05)]
& polyline [(0,0),(0.3,-0.05)]
& polyline [(0,-0.2),(0,0.1)]
& polyline [(0,-0.2),(0.1,-0.5)]
& polyline [(0,-0.2),(-0.1,-0.5)]
where cranium = circle 0.18
& sector (7/6*pi) (1/6*pi) 0.18
player U = translated 0 0.3 cranium
& polyline [(0,0),(0.3,0.05)]
& polyline [(0,0),(-0.3,0.05)]
& polyline [(0,-0.2),(0,0.1)]
& polyline [(0,-0.2),(0.1,-0.5)]
& polyline [(0,-0.2),(-0.1,-0.5)]
where cranium = solidCircle 0.18
player D = translated 0 0.3 cranium
& polyline [(0,0),(0.3,-0.05)]
& polyline [(0,0),(-0.3,-0.05)]
& polyline [(0,-0.2),(0,0.1)]
& polyline [(0,-0.2),(0.1,-0.5)]
& polyline [(0,-0.2),(-0.1,-0.5)]
where cranium = circle 0.18
& translated 0.06 0.08 (solidCircle 0.04)
& translated (-0.06) 0.08 (solidCircle 0.04)
data State = State Coord Direction
initialState :: State
initialState = State (C 0 1) R
tryGoTo :: State -> Direction -> State
tryGoTo (State from _) d
| isOk (maze to) = State to d
| otherwise = State from d
where to = adjacentCoord d from
drawState :: State -> Picture
drawState (State c d) = atCoord c (player d) & pictureOfMaze
data Activity world = Activity
world
(Event -> world -> world)
(world -> Picture)
resetable :: Activity s -> Activity s
resetable (Activity state0 handle draw)
= Activity state0 handle' draw
where handle' (KeyPress key) _ | key == "Esc" = state0
handle' e s = handle e s
startScreen :: Picture
startScreen = scaled 3 3 (lettering "Sokoban!")
data SSState world = StartScreen | Running world
withStartScreen :: Activity s-> Activity (SSState s)
withStartScreen (Activity state0 handle draw)
= Activity state0' handle' draw'
where
state0' = StartScreen
handle' (KeyPress key) StartScreen
| key == " " = Running state0
handle' _ StartScreen = StartScreen
handle' e (Running s) = Running (handle e s)
draw' StartScreen = startScreen
draw' (Running s) = draw s
runActivity :: Activity s -> IO ()
runActivity (Activity state0 handle draw)
= activityOf state0 handle draw
sokoban :: Activity State
sokoban = Activity initialState handleEvent drawState
data List a = Empty | Entry a (List a)
someBoxCoords :: List Coord
someBoxCoords = Entry (C 2 2) (Entry (C 3 3) (Entry (C (-1) 0) Empty))
combine :: List Picture -> Picture
combine Empty = blank
combine (Entry p ps) = p & combine ps
boxes :: List Coord -> Picture
boxes cs = combine (mapList (\c -> atCoord c (drawTile Box)) cs)
movingBoxes :: Activity (List Coord)
movingBoxes = Activity someBoxCoords handle draw
where
draw = boxes
handle (KeyPress key) s
| key == "Right" = mapList (adjacentCoord R) s
| key == "Up" = mapList (adjacentCoord U) s
| key == "Left" = mapList (adjacentCoord L) s
| key == "Down" = mapList (adjacentCoord D) s
handle _ s = s
mapList :: (a -> b) -> List a -> List b
mapList _ Empty = Empty
mapList f (Entry c cs) = Entry (f c) (mapList f cs)
main :: IO ()
main = runActivity movingBoxes
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.