_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
|
---|---|---|---|---|---|---|---|---|
98d12cf65b979185ad8d5c27b69d5fc919948f85c30a80e7d5ce4c491fb8a0b7
|
ocaml-ppx/ocamlformat
|
attributes.ml
|
open MenhirSdk.Cmly_api
open Utils
Attributes guide the recovery .
Some information can be passed to Menhir - recover via attributes . These are
pieces of string that are ignored by Menhir itself and are transmitted to
Menhir - recover .
The attributes that are relevant to Menhir - recover are always prefixed with
` recover . ` .
An attribute with the same prefix and that is not understood by
Menhir - recover will produce a warning message ( to detect a typo or a
misplaced attribute ) .
Some information can be passed to Menhir-recover via attributes. These are
pieces of string that are ignored by Menhir itself and are transmitted to
Menhir-recover.
The attributes that are relevant to Menhir-recover are always prefixed with
`recover.`.
An attribute with the same prefix and that is not understood by
Menhir-recover will produce a warning message (to detect a typo or a
misplaced attribute).
*)
(** Specification of attributes that are meaningful for recovery *)
module type ATTRIBUTES = sig
module G : GRAMMAR
* The Menhir grammar to which these apply
* Recovery cost
When the parser is in an error state , Menhir - recover will invent some
input that recovers from this error . In most grammars , this problem has
many solutions , often an infinity .
But not all solutions are equally nice . Some will have repetitions , some
will generate undesirable AST nodes or trigger error reductions ...
To guide this process , a cost can be associated to each symbol ( terminal
or non - terminal ) , and the cost of the recovery will be the sum of the cost
of all symbols in the generated sentence .
When the parser is in an error state, Menhir-recover will invent some
input that recovers from this error. In most grammars, this problem has
many solutions, often an infinity.
But not all solutions are equally nice. Some will have repetitions, some
will generate undesirable AST nodes or trigger error reductions...
To guide this process, a cost can be associated to each symbol (terminal
or non-terminal), and the cost of the recovery will be the sum of the cost
of all symbols in the generated sentence. *)
* Symbol cost
The ` recover.cost ` attribute is attached to the definition of symbols
( terminals and non - terminals ) and takes a floating point value .
% token PLUS [ @recover.cost 1.0 ]
expr [ @recover.cost 1.0 ] : ... ;
The `recover.cost` attribute is attached to the definition of symbols
(terminals and non-terminals) and takes a floating point value.
%token PLUS [@recover.cost 1.0]
expr [@recover.cost 1.0]: ... ; *)
val cost_of_symbol : G.symbol -> Cost.t
(** Cost of a grammar symbol *)
* Item cost
The cost can be applied to a specific item ( an occurrence of a symbol in a
rule ) .
In this case , the more specific cost will replace the global cost for this
specific occurrence .
{ v
expr :
| INT PLUS [ @recover.cost 0.0 ] INT { ... }
| INT TIMES [ @recover.cost 10.0 ] INT { ... }
;
v }
In this example , if an error happens just after an integer in an
expression , the ` PLUS ` rule will be favored over the ` TIMES ` rule because
the first token is more expensive .
The cost can be applied to a specific item (an occurrence of a symbol in a
rule).
In this case, the more specific cost will replace the global cost for this
specific occurrence.
{v
expr:
| INT PLUS [@recover.cost 0.0] INT { ... }
| INT TIMES [@recover.cost 10.0] INT { ... }
;
v}
In this example, if an error happens just after an integer in an
expression, the `PLUS` rule will be favored over the `TIMES` rule because
the first token is more expensive. *)
val penalty_of_item : G.production * int -> Cost.t
(** Penalty (added cost) for shifting an item *)
* Reduction cost
The last place where a ` recover.cost ` is accepted is in a production . This
is convenient to prevent the recovery to trigger some semantic actions .
{ v
expr :
expr error { ... } [ @recover.cost infinity ]
;
v }
It would not make much sense for the recovery to select an error rule .
Associating an infinite cost to the production ensures that this never
happen .
The last place where a `recover.cost` is accepted is in a production. This
is convenient to prevent the recovery to trigger some semantic actions.
{v
expr:
LPAREN expr error { ... } [@recover.cost infinity]
;
v}
It would not make much sense for the recovery to select an error rule.
Associating an infinite cost to the production ensures that this never
happen. *)
val cost_of_prod : G.production -> Cost.t
(** Cost of reducing a production *)
* Meaning of costs
The cost should be a positive floating - point value . + ∞ and 0.0 are
accepted .
If not specified , the default cost depends on the presence of a semantic
value :
- for a terminal without semantic value ( such as ` % token DOT ` ) it is 0.0 .
- for a terminal with a semantic value ( such as ` % token < int > INT ` ) or a
non - terminal it is + ∞.
If the attribute happens multiple times , the sum of all occurrences is
used .
* * TODO * * : specify how null values are treated with respect to minimal
cost , can the algorithm diverge ?
The cost should be a positive floating-point value. +∞ and 0.0 are
accepted.
If not specified, the default cost depends on the presence of a semantic
value:
- for a terminal without semantic value (such as `%token DOT`) it is 0.0.
- for a terminal with a semantic value (such as `%token<int> INT`) or a
non-terminal it is +∞.
If the attribute happens multiple times, the sum of all occurrences is
used.
**TODO**: specify how null values are treated with respect to minimal
cost, can the algorithm diverge? *)
* Recovery expressions
Symbols with a semantic value can not be picked by the recovery algorithm
if it does not know how to produce this value .
The ` recover.expr ` attribute associates an ocaml expression to a symbol .
This expression should evaluate to a semantic value for this symbol .
% token < string > IDENT [ @recover.expr " invalid - identifier " ]
When applied to non - terminals , it is particularly useful to produce a
value that could not be the result of a normal parse .
expr [ @recover.expr Invalid_expression ] : ... ;
Here ` Invalid_expression ` is a node added to the AST for the purpose of
identifying parts that were recovered .
Furthermore , specifying fallback values for non - terminals prevents
Menhir - recover from generating a hardly predictable sequence of tokens
just for filling holes in the AST .
Symbols with a semantic value cannot be picked by the recovery algorithm
if it does not know how to produce this value.
The `recover.expr` attribute associates an ocaml expression to a symbol.
This expression should evaluate to a semantic value for this symbol.
%token<string> IDENT [@recover.expr "invalid-identifier"]
When applied to non-terminals, it is particularly useful to produce a
value that could not be the result of a normal parse.
expr [@recover.expr Invalid_expression]: ... ;
Here `Invalid_expression` is a node added to the AST for the purpose of
identifying parts that were recovered.
Furthermore, specifying fallback values for non-terminals prevents
Menhir-recover from generating a hardly predictable sequence of tokens
just for filling holes in the AST. *)
val default_terminal : G.terminal -> string option
(** An optional ocaml expression that should evaluate to a semantic value
valid for this terminal. *)
val default_nonterminal : G.nonterminal -> string option
(** An optional ocaml expression that should evaluate to a semantic value
valid for this non-terminal. *)
(** The expressions are evaluated every time a new instance of a symbol is
needed, although it is not specified whether every evaluation will be kept
in the final solution (at run time, the algorithm is free to explore
different branches and throw them away as needed).
**TODO**: decide how information can be communicated with recovery
expressions (for instance the current location of the parser) *)
(** Recovery prelude
The `recover.prelude` attribute is attached to the grammar.
It is an arbitrary piece of OCaml code that will be inserted before the
code of `recover.expr` expressions.
It is useful for defining definitions shared by the recovery expressions,
in the same way as [%{ ... %}] is used to share definitions in semantic
actions of the grammar. *)
val default_prelude : Format.formatter -> unit
(** Output the grammar prelude in this formatter *)
end
(* module type ATTRIBUTES *)
module Recover_attributes (G : GRAMMAR) : ATTRIBUTES with module G = G = struct
module G = G
open G
let string_starts_with str ~prefix =
let len = String.length prefix in
String.length str >= len
&&
try
for i = 0 to len - 1 do
if str.[i] <> prefix.[i] then raise Exit
done;
true
with Exit -> false
let prefix = "recover."
let all_attributes = [ "recover.cost"; "recover.expr"; "recover.prelude" ]
let validate_attribute accepted kind attr =
let label = Attribute.label attr in
if string_starts_with ~prefix label && not (List.mem label accepted) then
let split_pos pos =
( pos.Lexing.pos_fname,
pos.Lexing.pos_lnum,
pos.Lexing.pos_cnum - pos.Lexing.pos_bol )
in
let range () range =
let s = Printf.sprintf in
let sf, sl, sc = split_pos (Range.startp range) in
let ef, el, ec = split_pos (Range.endp range) in
if sf <> ef then s "%s:%d.%d-%s:%d.%d" sf sl sc ef el ec
else if sl <> el then s "%s:%d.%d-%d.%d" sf sl sc el ec
else if sc <> ec then s "%s:%d.%d-%d" sf sl sc ec
else s "%s:%d.%d" sf sl sc
in
let f fmt = Printf.ksprintf prerr_endline fmt in
if List.mem label all_attributes then
f "%a: attribute %S cannot be put in %s" range (Attribute.position attr)
label kind
else
f "%a: attribute %S is not recognized (found in %s)" range
(Attribute.position attr) label kind
let validate_attributes accepted kind attrs =
List.iter (validate_attribute accepted kind) attrs
let () =
validate_attributes [ "recover.prelude" ] "grammar attributes"
Grammar.attributes;
let symbol prj attrs =
validate_attributes
[ "recover.cost"; "recover.expr" ]
"symbol attributes" (prj attrs)
in
Nonterminal.iter (symbol G.Nonterminal.attributes);
Terminal.iter (symbol G.Terminal.attributes);
Production.iter (fun p ->
validate_attributes
[
"recover.cost";
recover.expr : a lie to prevent warnings on an unfortunate
interaction between menhir inlining and attributes
interaction between menhir inlining and attributes *)
"recover.expr";
]
"production attributes" (Production.attributes p);
Array.iter
(fun (_, _, attrs) ->
validate_attributes [ "recover.cost" ] "item attributes" attrs)
(Production.rhs p))
let cost_of_attributes prj attrs =
Cost.of_int
(List.fold_left
(fun total attr ->
if Attribute.has_label "recover.cost" attr then
total + int_of_string (Attribute.payload attr)
else total)
0 (prj attrs))
let cost_of_symbol =
let measure ~has_default prj attrs =
if
List.exists (Attribute.has_label "recover.expr") (prj attrs)
|| has_default
then cost_of_attributes prj attrs
else Cost.infinite
in
let ft =
Terminal.tabulate (fun t ->
measure ~has_default:(Terminal.typ t = None) Terminal.attributes t)
in
let fn =
Nonterminal.tabulate (measure ~has_default:false Nonterminal.attributes)
in
function
| T t -> (
match Terminal.kind t with `ERROR -> Cost.infinite | _ -> ft t )
| N n -> fn n
let cost_of_prod =
Production.tabulate (cost_of_attributes Production.attributes)
let penalty_of_item =
let f =
Production.tabulate @@ fun p ->
Array.map (cost_of_attributes (fun (_, _, a) -> a)) (Production.rhs p)
in
fun (p, i) ->
let costs = f p in
if i < Array.length costs then costs.(i) else cost_of_prod p
let default_prelude ppf =
List.iter
(fun a ->
if Attribute.has_label "recover.prelude" a then
Format.fprintf ppf "%s\n" (Attribute.payload a))
Grammar.attributes
let default_expr ?(fallback = "raise Not_found") attrs =
match List.find (Attribute.has_label "recover.expr") attrs with
| exception Not_found -> fallback
| attr -> Attribute.payload attr
let default_terminal t =
match Terminal.kind t with
| `REGULAR | `ERROR | `EOF ->
let fallback =
match Terminal.typ t with None -> Some "()" | Some _ -> None
in
Some (default_expr ?fallback (Terminal.attributes t))
| `PSEUDO -> None
let default_nonterminal n =
match Nonterminal.kind n with
| `REGULAR -> Some (default_expr (Nonterminal.attributes n))
| `START -> None
end
| null |
https://raw.githubusercontent.com/ocaml-ppx/ocamlformat/9324ea439a77b4f3a31e9302b97ce1812cf8f17d/vendor/parser-recovery/menhir-recover/attributes.ml
|
ocaml
|
* Specification of attributes that are meaningful for recovery
* Cost of a grammar symbol
* Penalty (added cost) for shifting an item
* Cost of reducing a production
* An optional ocaml expression that should evaluate to a semantic value
valid for this terminal.
* An optional ocaml expression that should evaluate to a semantic value
valid for this non-terminal.
* The expressions are evaluated every time a new instance of a symbol is
needed, although it is not specified whether every evaluation will be kept
in the final solution (at run time, the algorithm is free to explore
different branches and throw them away as needed).
**TODO**: decide how information can be communicated with recovery
expressions (for instance the current location of the parser)
* Recovery prelude
The `recover.prelude` attribute is attached to the grammar.
It is an arbitrary piece of OCaml code that will be inserted before the
code of `recover.expr` expressions.
It is useful for defining definitions shared by the recovery expressions,
in the same way as [%{ ... %}] is used to share definitions in semantic
actions of the grammar.
* Output the grammar prelude in this formatter
module type ATTRIBUTES
|
open MenhirSdk.Cmly_api
open Utils
Attributes guide the recovery .
Some information can be passed to Menhir - recover via attributes . These are
pieces of string that are ignored by Menhir itself and are transmitted to
Menhir - recover .
The attributes that are relevant to Menhir - recover are always prefixed with
` recover . ` .
An attribute with the same prefix and that is not understood by
Menhir - recover will produce a warning message ( to detect a typo or a
misplaced attribute ) .
Some information can be passed to Menhir-recover via attributes. These are
pieces of string that are ignored by Menhir itself and are transmitted to
Menhir-recover.
The attributes that are relevant to Menhir-recover are always prefixed with
`recover.`.
An attribute with the same prefix and that is not understood by
Menhir-recover will produce a warning message (to detect a typo or a
misplaced attribute).
*)
module type ATTRIBUTES = sig
module G : GRAMMAR
* The Menhir grammar to which these apply
* Recovery cost
When the parser is in an error state , Menhir - recover will invent some
input that recovers from this error . In most grammars , this problem has
many solutions , often an infinity .
But not all solutions are equally nice . Some will have repetitions , some
will generate undesirable AST nodes or trigger error reductions ...
To guide this process , a cost can be associated to each symbol ( terminal
or non - terminal ) , and the cost of the recovery will be the sum of the cost
of all symbols in the generated sentence .
When the parser is in an error state, Menhir-recover will invent some
input that recovers from this error. In most grammars, this problem has
many solutions, often an infinity.
But not all solutions are equally nice. Some will have repetitions, some
will generate undesirable AST nodes or trigger error reductions...
To guide this process, a cost can be associated to each symbol (terminal
or non-terminal), and the cost of the recovery will be the sum of the cost
of all symbols in the generated sentence. *)
* Symbol cost
The ` recover.cost ` attribute is attached to the definition of symbols
( terminals and non - terminals ) and takes a floating point value .
% token PLUS [ @recover.cost 1.0 ]
expr [ @recover.cost 1.0 ] : ... ;
The `recover.cost` attribute is attached to the definition of symbols
(terminals and non-terminals) and takes a floating point value.
%token PLUS [@recover.cost 1.0]
expr [@recover.cost 1.0]: ... ; *)
val cost_of_symbol : G.symbol -> Cost.t
* Item cost
The cost can be applied to a specific item ( an occurrence of a symbol in a
rule ) .
In this case , the more specific cost will replace the global cost for this
specific occurrence .
{ v
expr :
| INT PLUS [ @recover.cost 0.0 ] INT { ... }
| INT TIMES [ @recover.cost 10.0 ] INT { ... }
;
v }
In this example , if an error happens just after an integer in an
expression , the ` PLUS ` rule will be favored over the ` TIMES ` rule because
the first token is more expensive .
The cost can be applied to a specific item (an occurrence of a symbol in a
rule).
In this case, the more specific cost will replace the global cost for this
specific occurrence.
{v
expr:
| INT PLUS [@recover.cost 0.0] INT { ... }
| INT TIMES [@recover.cost 10.0] INT { ... }
;
v}
In this example, if an error happens just after an integer in an
expression, the `PLUS` rule will be favored over the `TIMES` rule because
the first token is more expensive. *)
val penalty_of_item : G.production * int -> Cost.t
* Reduction cost
The last place where a ` recover.cost ` is accepted is in a production . This
is convenient to prevent the recovery to trigger some semantic actions .
{ v
expr :
expr error { ... } [ @recover.cost infinity ]
;
v }
It would not make much sense for the recovery to select an error rule .
Associating an infinite cost to the production ensures that this never
happen .
The last place where a `recover.cost` is accepted is in a production. This
is convenient to prevent the recovery to trigger some semantic actions.
{v
expr:
LPAREN expr error { ... } [@recover.cost infinity]
;
v}
It would not make much sense for the recovery to select an error rule.
Associating an infinite cost to the production ensures that this never
happen. *)
val cost_of_prod : G.production -> Cost.t
* Meaning of costs
The cost should be a positive floating - point value . + ∞ and 0.0 are
accepted .
If not specified , the default cost depends on the presence of a semantic
value :
- for a terminal without semantic value ( such as ` % token DOT ` ) it is 0.0 .
- for a terminal with a semantic value ( such as ` % token < int > INT ` ) or a
non - terminal it is + ∞.
If the attribute happens multiple times , the sum of all occurrences is
used .
* * TODO * * : specify how null values are treated with respect to minimal
cost , can the algorithm diverge ?
The cost should be a positive floating-point value. +∞ and 0.0 are
accepted.
If not specified, the default cost depends on the presence of a semantic
value:
- for a terminal without semantic value (such as `%token DOT`) it is 0.0.
- for a terminal with a semantic value (such as `%token<int> INT`) or a
non-terminal it is +∞.
If the attribute happens multiple times, the sum of all occurrences is
used.
**TODO**: specify how null values are treated with respect to minimal
cost, can the algorithm diverge? *)
* Recovery expressions
Symbols with a semantic value can not be picked by the recovery algorithm
if it does not know how to produce this value .
The ` recover.expr ` attribute associates an ocaml expression to a symbol .
This expression should evaluate to a semantic value for this symbol .
% token < string > IDENT [ @recover.expr " invalid - identifier " ]
When applied to non - terminals , it is particularly useful to produce a
value that could not be the result of a normal parse .
expr [ @recover.expr Invalid_expression ] : ... ;
Here ` Invalid_expression ` is a node added to the AST for the purpose of
identifying parts that were recovered .
Furthermore , specifying fallback values for non - terminals prevents
Menhir - recover from generating a hardly predictable sequence of tokens
just for filling holes in the AST .
Symbols with a semantic value cannot be picked by the recovery algorithm
if it does not know how to produce this value.
The `recover.expr` attribute associates an ocaml expression to a symbol.
This expression should evaluate to a semantic value for this symbol.
%token<string> IDENT [@recover.expr "invalid-identifier"]
When applied to non-terminals, it is particularly useful to produce a
value that could not be the result of a normal parse.
expr [@recover.expr Invalid_expression]: ... ;
Here `Invalid_expression` is a node added to the AST for the purpose of
identifying parts that were recovered.
Furthermore, specifying fallback values for non-terminals prevents
Menhir-recover from generating a hardly predictable sequence of tokens
just for filling holes in the AST. *)
val default_terminal : G.terminal -> string option
val default_nonterminal : G.nonterminal -> string option
val default_prelude : Format.formatter -> unit
end
module Recover_attributes (G : GRAMMAR) : ATTRIBUTES with module G = G = struct
module G = G
open G
let string_starts_with str ~prefix =
let len = String.length prefix in
String.length str >= len
&&
try
for i = 0 to len - 1 do
if str.[i] <> prefix.[i] then raise Exit
done;
true
with Exit -> false
let prefix = "recover."
let all_attributes = [ "recover.cost"; "recover.expr"; "recover.prelude" ]
let validate_attribute accepted kind attr =
let label = Attribute.label attr in
if string_starts_with ~prefix label && not (List.mem label accepted) then
let split_pos pos =
( pos.Lexing.pos_fname,
pos.Lexing.pos_lnum,
pos.Lexing.pos_cnum - pos.Lexing.pos_bol )
in
let range () range =
let s = Printf.sprintf in
let sf, sl, sc = split_pos (Range.startp range) in
let ef, el, ec = split_pos (Range.endp range) in
if sf <> ef then s "%s:%d.%d-%s:%d.%d" sf sl sc ef el ec
else if sl <> el then s "%s:%d.%d-%d.%d" sf sl sc el ec
else if sc <> ec then s "%s:%d.%d-%d" sf sl sc ec
else s "%s:%d.%d" sf sl sc
in
let f fmt = Printf.ksprintf prerr_endline fmt in
if List.mem label all_attributes then
f "%a: attribute %S cannot be put in %s" range (Attribute.position attr)
label kind
else
f "%a: attribute %S is not recognized (found in %s)" range
(Attribute.position attr) label kind
let validate_attributes accepted kind attrs =
List.iter (validate_attribute accepted kind) attrs
let () =
validate_attributes [ "recover.prelude" ] "grammar attributes"
Grammar.attributes;
let symbol prj attrs =
validate_attributes
[ "recover.cost"; "recover.expr" ]
"symbol attributes" (prj attrs)
in
Nonterminal.iter (symbol G.Nonterminal.attributes);
Terminal.iter (symbol G.Terminal.attributes);
Production.iter (fun p ->
validate_attributes
[
"recover.cost";
recover.expr : a lie to prevent warnings on an unfortunate
interaction between menhir inlining and attributes
interaction between menhir inlining and attributes *)
"recover.expr";
]
"production attributes" (Production.attributes p);
Array.iter
(fun (_, _, attrs) ->
validate_attributes [ "recover.cost" ] "item attributes" attrs)
(Production.rhs p))
let cost_of_attributes prj attrs =
Cost.of_int
(List.fold_left
(fun total attr ->
if Attribute.has_label "recover.cost" attr then
total + int_of_string (Attribute.payload attr)
else total)
0 (prj attrs))
let cost_of_symbol =
let measure ~has_default prj attrs =
if
List.exists (Attribute.has_label "recover.expr") (prj attrs)
|| has_default
then cost_of_attributes prj attrs
else Cost.infinite
in
let ft =
Terminal.tabulate (fun t ->
measure ~has_default:(Terminal.typ t = None) Terminal.attributes t)
in
let fn =
Nonterminal.tabulate (measure ~has_default:false Nonterminal.attributes)
in
function
| T t -> (
match Terminal.kind t with `ERROR -> Cost.infinite | _ -> ft t )
| N n -> fn n
let cost_of_prod =
Production.tabulate (cost_of_attributes Production.attributes)
let penalty_of_item =
let f =
Production.tabulate @@ fun p ->
Array.map (cost_of_attributes (fun (_, _, a) -> a)) (Production.rhs p)
in
fun (p, i) ->
let costs = f p in
if i < Array.length costs then costs.(i) else cost_of_prod p
let default_prelude ppf =
List.iter
(fun a ->
if Attribute.has_label "recover.prelude" a then
Format.fprintf ppf "%s\n" (Attribute.payload a))
Grammar.attributes
let default_expr ?(fallback = "raise Not_found") attrs =
match List.find (Attribute.has_label "recover.expr") attrs with
| exception Not_found -> fallback
| attr -> Attribute.payload attr
let default_terminal t =
match Terminal.kind t with
| `REGULAR | `ERROR | `EOF ->
let fallback =
match Terminal.typ t with None -> Some "()" | Some _ -> None
in
Some (default_expr ?fallback (Terminal.attributes t))
| `PSEUDO -> None
let default_nonterminal n =
match Nonterminal.kind n with
| `REGULAR -> Some (default_expr (Nonterminal.attributes n))
| `START -> None
end
|
61cacab2fccbb6c141b83679232140812ce80910678b66ed5467a7b728bb4a4f
|
RolfRolles/PandemicML
|
X86Disasm.mli
|
(** Functions for converting X86 instruction parts into strings. These
functions are pure, and their names are self-explanatory. *)
* { 6 X86 - parts - to - strings functions }
val string_of_x86mnem : X86.x86mnem -> string
val string_of_x86_reg32 : X86.x86_reg32 -> string
val string_of_x86_debug_reg : X86.x86_debug_reg -> string
val string_of_x86_control_reg : X86.x86_control_reg -> string
val string_of_x86_reg16 : X86.x86_reg16 -> string
val string_of_x86_reg8 : X86.x86_reg8 -> string
val string_of_x86_segreg : X86.x86_segreg -> string
val string_of_x86_fpureg : X86.x86_fpureg -> string
val string_of_x86_mmxreg : X86.x86_mmxreg -> string
val string_of_x86_xmmreg : X86.x86_xmmreg -> string
val string_of_x86_immediate : X86.x86_immediate -> string
val string_of_x86_far_target : X86.x86_far_target -> string
val string_of_displ : int32 -> string
val string_of_x86_general_reg : X86.x86_general_reg -> string
val string_of_scalefac : int -> string
val string_of_x86_memexpr : X86.x86_mem_expr -> string
val string_of_x86operand : X86.x86operand -> string
val string_of_x86instr : X86.x86instrpref -> string
val string_of_x86_flags : X86.x86_flags -> string
| null |
https://raw.githubusercontent.com/RolfRolles/PandemicML/9c31ecaf9c782dbbeb6cf502bc2a6730316d681e/X86/X86Disasm.mli
|
ocaml
|
* Functions for converting X86 instruction parts into strings. These
functions are pure, and their names are self-explanatory.
|
* { 6 X86 - parts - to - strings functions }
val string_of_x86mnem : X86.x86mnem -> string
val string_of_x86_reg32 : X86.x86_reg32 -> string
val string_of_x86_debug_reg : X86.x86_debug_reg -> string
val string_of_x86_control_reg : X86.x86_control_reg -> string
val string_of_x86_reg16 : X86.x86_reg16 -> string
val string_of_x86_reg8 : X86.x86_reg8 -> string
val string_of_x86_segreg : X86.x86_segreg -> string
val string_of_x86_fpureg : X86.x86_fpureg -> string
val string_of_x86_mmxreg : X86.x86_mmxreg -> string
val string_of_x86_xmmreg : X86.x86_xmmreg -> string
val string_of_x86_immediate : X86.x86_immediate -> string
val string_of_x86_far_target : X86.x86_far_target -> string
val string_of_displ : int32 -> string
val string_of_x86_general_reg : X86.x86_general_reg -> string
val string_of_scalefac : int -> string
val string_of_x86_memexpr : X86.x86_mem_expr -> string
val string_of_x86operand : X86.x86operand -> string
val string_of_x86instr : X86.x86instrpref -> string
val string_of_x86_flags : X86.x86_flags -> string
|
8315cb02c7ea18cbeb7a073be76a59f2f385e05ade486683b7febad501815bb8
|
vouillon/osm
|
display.ml
|
OSM tools
* Copyright ( C ) 2013
*
* 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 , with linking exception ;
* either version 2.1 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 .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
* Copyright (C) 2013 Jérôme Vouillon
*
* 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, with linking exception;
* either version 2.1 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.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
* aeroway = runway can be a surface
* When a leaf bounding box is very large , perform clipping of the
objects it contains , to avoid rendering artifacts ( Cairo uses
integers internally , + /- 8 millions , bug # 20091 )
* Redesign R - tree of linear features
mostly constant :
layer 4 bits
bridge / tunnel 2 bit
category 5 bits
oneway / access 5 bits ( car 2 , bikes 2 , pedestrian 1 )
= = > 2 bytes = > 6 bits remaining for the number of ways
* Rendering performance :
* do not render railway = rail;service= * at low zoom levels
* multiple surface R - trees :
R - tree of small surfaces ; R - tree of other surfaces ;
R - tree with about the 1 % largest surfaces ; ...
* Rendering fixes
= = > Highway with area = yes
= = > do not draw them as ways as well
= = > Outline of highway surfaces
= = > Notre Dame de Paris and Sacré Coeur are missing !
= = > use same algorithm as osm2pgsql to deal with tags
* We could improve the rendering of tunnels , ... by classifying nodes :
- do not use round linecap at tunnel extremities
- draw additional circles when a path extremities do not agree
- detect nodes with level mismatch
* One - way arrows ( foot , bicycle , car ) , accessibility ( foot , bicycle , car )
= = = > share between ways !
* aeroway=runway can be a surface
* When a leaf bounding box is very large, perform clipping of the
objects it contains, to avoid rendering artifacts (Cairo uses
integers internally, +/- 8 millions, bug #20091)
* Redesign R-tree of linear features
mostly constant:
layer 4 bits
bridge/tunnel 2 bit
category 5 bits
oneway/access 5 bits (car 2, bikes 2, pedestrian 1)
==> 2 bytes => 6 bits remaining for the number of ways
* Rendering performance:
* do not render railway=rail;service=* at low zoom levels
* multiple surface R-trees:
R-tree of small surfaces; R-tree of other surfaces;
R-tree with about the 1% largest surfaces; ...
* Rendering fixes
==> Highway with area=yes
==> do not draw them as ways as well
==> Outline of highway surfaces
==> Notre Dame de Paris and Sacré Coeur are missing!
==> use same algorithm as osm2pgsql to deal with multipolygon tags
* We could improve the rendering of tunnels, ... by classifying nodes:
- do not use round linecap at tunnel extremities
- draw additional circles when a path extremities do not agree
- detect nodes with level mismatch
* One-way arrows (foot, bicycle, car), accessibility (foot, bicycle, car)
===> share between ways!
*)
let _ = Printexc.record_backtrace true
let _ = Column.set_database "/tmp/osm"
(****)
open Osm_display
let _ =
let width = 512 in
let height = 512 in
let st =
{ rect = { x = 0; y = 0; width = width; height = height };
prev_rect = { x = 0; y = 0; width = width; height = height };
level = 17.; prev_level = 17.; active = true; timeout = None;
surface = make_surface ();
marker1 = None; marker2 = None; path = [] } in
let lat = ref 48.850 in
let lon = ref 2.350 in
begin
let (ratio, _, tree) = Lazy.force large_surfaces in
let bbox = Rtree.bounding_box tree in
let c x = truncate (x *. 10_000_000. /. float ratio +. 0.5) in
Format.eprintf "%a %d %d@." Bbox.print bbox (c !lat) (c !lon);
if not (Bbox.contains_point bbox (c !lat) (c !lon)) then begin
let c x = float x /. 10_000_000. *. float ratio in
lat := c ((bbox.Bbox.min_lat + bbox.Bbox.max_lat) / 2);
lon := c ((bbox.Bbox.min_lon + bbox.Bbox.max_lon) / 2)
end
end;
let scale = compute_scale st in
st.rect <-
{ st.rect with
x = truncate (!lon *. scale) - width / 2;
y = - truncate (Geometry.lat_to_y (!lat *. 10_000_000.) /. 10_000_000. *. scale) - height / 2 };
Format.eprintf "%d %d@." st.rect.x st.rect.y;
ignore (GMain.Main.init ());
let w = GWindow.window () in
ignore (w#connect#destroy GMain.quit);
let b = GPack.hbox ~packing:w#add () in
let table =
GPack.table ~width ~height ~columns:1 ~rows:1 ~packing:(b#pack ~expand:true) () in
let display =
GMisc.drawing_area
~packing:(table#attach ~left:0 ~top:0 ~fill:`BOTH ~expand:`BOTH) () in
display#misc#set_can_focus true;
(*
display#misc#set_double_buffered false;
*)
let queue_draw () = GtkBase.Widget.queue_draw display#as_widget in
let refresh () =
invalidate_surface st.surface;
queue_draw ()
in
let update_size () =
let a = display#misc#allocation in
st.rect <-
{ x = st.rect.x + (st.rect.width - a.Gtk.width) / 2;
y = st.rect.y + (st.rect.height - a.Gtk.height) / 2;
width = a.Gtk.width;
height = a.Gtk.height }
in
(*
ignore (display#event#connect#configure
(fun ev -> false));
ignore (display#event#connect#map
(fun ev -> false));
display#event#add [`STRUCTURE];
*)
ignore (display#event#connect#expose
(fun ev ->
let t = Unix.gettimeofday () in
let area = GdkEvent.Expose.area ev in
let x = Gdk.Rectangle.x area in
let y = Gdk.Rectangle.y area in
let width = Gdk.Rectangle.width area in
let height = Gdk.Rectangle.height area in
(*
Format.eprintf "EXPOSE %d %d %d %d@." x y width height;
*)
update_size ();
let a = st.rect in
let ctx = Cairo_gtk.create (display#misc#window) in
let pm = st.surface in
if st.active then begin
grow_surface st.surface display a.width a.height;
let dx = pm.valid_rect.x - st.rect.x in
let dy = pm.valid_rect.y - st.rect.y in
let p = get_surface pm in
if
(dx > 0 && pm.valid_rect.width + dx < a.width) ||
(dy > 0 && pm.valid_rect.height + dy < a.height)
then begin
We would have to redraw four rectangles
pm.valid_rect <- empty_rectangle
end else if not (rectangle_is_empty pm.valid_rect) then begin
let r = pm.valid_rect in
if (dx <> 0 || dy <> 0) then begin
let ctx = Cairo.create p in
Cairo.set_source_surface ctx p (float dx) (float dy);
Cairo.rectangle ctx
(float dx) (float dy) (float r.width) (float r.height);
Cairo.set_operator ctx Cairo.SOURCE;
Cairo.fill ctx
end;
0 < = p ; 0 < = l ; p + l < = m
if p + d + l <= 0 then
(0, 0)
else if p + d < 0 then
(0, l + p + d)
else if p + d >= m then
(m, 0)
else if p + d + l > m then
(p + d, m - p - d)
else
(p + d, l)
in
let (x, width) = offset 0 r.width dx pm.p_width in
let (y, height) = offset 0 r.height dy pm.p_height in
if height > 0 then begin
if x > 0 then begin
assert (x + width >= a.width);
draw_map st p 0 y x height
end else begin
assert (x = 0);
if a.width > width then
draw_map st p width y (a.width - width) height
end
end;
if y > 0 then begin
assert (y + height >= a.height);
draw_map st p 0 0 a.width y;
end else begin
assert (y = 0);
if a.height > height then
draw_map st p 0 height a.width (a.height - height)
end;
pm.valid_rect <- st.rect
end;
let r = pm.valid_rect in
if x + width > r.width || y + height > r.height then begin
draw_map st p 0 0 a.width a.height;
pm.valid_rect <- st.rect
end;
Cairo.set_source_surface ctx p 0. 0.;
end else begin
Cairo.set_source_rgb ctx 0.8 0.8 0.8;
Cairo.rectangle ctx (float x) (float y) (float width) (float height);
Cairo.fill ctx;
let p = get_surface pm in
Cairo.set_source_surface ctx p 0. 0.;
let coeff = 2. ** (st.prev_level -. st.level) in
let matrix = Cairo.Matrix.init_identity () in
Cairo.Matrix.translate matrix
(-. float st.prev_rect.x) (-. float st.prev_rect.y);
Cairo.Matrix.scale matrix coeff coeff;
Cairo.Matrix.translate matrix (float st.rect.x) (float st.rect.y);
Cairo.Pattern.set_matrix (Cairo.get_source ctx) matrix;
end;
Cairo.rectangle ctx (float x) (float y) (float width) (float height);
Cairo.save ctx;
Workaround for a Cairo bug ( in ATI Catalyst drivers ? ):
if st.active then Cairo.set_operator ctx Cairo.SOURCE;
Cairo.fill_preserve ctx;
Cairo.restore ctx;
Cairo.clip ctx;
draw_route st ctx;
Format.eprintf "Redraw: %f@." (Unix.gettimeofday () -. t);
true));
let pos = ref None in
ignore (display#event#connect#button_press
(fun ev ->
display#misc#grab_focus ();
if !pos = None then
pos := Some (GdkEvent.Button.x ev, GdkEvent.Button.y ev,
GdkEvent.Button.button ev, false);
false));
ignore (display#event#connect#button_release
(fun ev ->
let but' = GdkEvent.Button.button ev in
begin match !pos with
Some (x, y, but, move) when but = but' ->
update_size ();
if not move && but = 1 then begin
st.marker1 <- find_marker st x y;
update_route st;
queue_draw ()
end else if not move && but = 3 then begin
st.marker2 <- find_marker st x y;
update_route st;
queue_draw ()
end;
pos := None
| _ ->
()
end;
false));
ignore (display#event#connect#motion_notify
(fun ev ->
(*Format.eprintf "MOVE@.";*)
let (x', y') =
if GdkEvent.Motion.is_hint ev then
let (x', y') = display#misc#pointer in
(float x', float y')
else
(GdkEvent.Motion.x ev, GdkEvent.Motion.y ev)
in
begin match !pos with
Some (x, y, but, move)
when but = 1
&& (move || abs_float (x -. x') > 3. || abs_float (y -. y') > 3.) ->
st.rect <-
{st.rect with
x = st.rect.x + truncate (x -. x');
y = st.rect.y + truncate (y -. y') };
pos := Some (x', y', 1, true);
queue_draw ()
| _ ->
()
end;
false));
display#event#add
[`BUTTON_PRESS; `BUTTON_RELEASE; `BUTTON1_MOTION; `POINTER_MOTION_HINT];
let perform_zoom ev delta =
let x = truncate (GdkEvent.Scroll.x ev) in
let y = truncate (GdkEvent.Scroll.y ev) in
if (async_zoom || (delta > 0. && async_zoom_in)) && st.active then begin
st.prev_level <- st.level;
st.prev_rect <- st.rect;
st.active <- false
end;
st.level <- st.level +. delta;
Format.eprintf "level: %f@." st.level;
update_size ();
st.rect <-
{ st.rect with
x = truncate ((float (st.rect.x + x)) *. 2. ** delta) - x;
y = truncate ((float (st.rect.y + y)) *. 2. ** delta) - y };
begin match st.timeout with
Some id -> Glib.Timeout.remove id
| None -> ()
end;
if not st.active then
st.timeout <-
Some (Glib.Timeout.add async_delay
(fun () ->
st.timeout<- None; st.active <- true; refresh (); false));
refresh ();
in
ignore (display#event#connect#scroll
(fun ev ->
match GdkEvent.Scroll.direction ev with
`UP ->
perform_zoom ev 0.125;
true
| `DOWN ->
perform_zoom ev (-0.125);
true
| _ ->
false));
display#event#add [`SCROLL];
w#show ();
GMain.main ()
| null |
https://raw.githubusercontent.com/vouillon/osm/a42d1bcc82a4ad73c26c81ac7a75f9f1c7470344/osm/display.ml
|
ocaml
|
**
display#misc#set_double_buffered false;
ignore (display#event#connect#configure
(fun ev -> false));
ignore (display#event#connect#map
(fun ev -> false));
display#event#add [`STRUCTURE];
Format.eprintf "EXPOSE %d %d %d %d@." x y width height;
Format.eprintf "MOVE@.";
|
OSM tools
* Copyright ( C ) 2013
*
* 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 , with linking exception ;
* either version 2.1 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 .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
* Copyright (C) 2013 Jérôme Vouillon
*
* 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, with linking exception;
* either version 2.1 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.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
* aeroway = runway can be a surface
* When a leaf bounding box is very large , perform clipping of the
objects it contains , to avoid rendering artifacts ( Cairo uses
integers internally , + /- 8 millions , bug # 20091 )
* Redesign R - tree of linear features
mostly constant :
layer 4 bits
bridge / tunnel 2 bit
category 5 bits
oneway / access 5 bits ( car 2 , bikes 2 , pedestrian 1 )
= = > 2 bytes = > 6 bits remaining for the number of ways
* Rendering performance :
* do not render railway = rail;service= * at low zoom levels
* multiple surface R - trees :
R - tree of small surfaces ; R - tree of other surfaces ;
R - tree with about the 1 % largest surfaces ; ...
* Rendering fixes
= = > Highway with area = yes
= = > do not draw them as ways as well
= = > Outline of highway surfaces
= = > Notre Dame de Paris and Sacré Coeur are missing !
= = > use same algorithm as osm2pgsql to deal with tags
* We could improve the rendering of tunnels , ... by classifying nodes :
- do not use round linecap at tunnel extremities
- draw additional circles when a path extremities do not agree
- detect nodes with level mismatch
* One - way arrows ( foot , bicycle , car ) , accessibility ( foot , bicycle , car )
= = = > share between ways !
* aeroway=runway can be a surface
* When a leaf bounding box is very large, perform clipping of the
objects it contains, to avoid rendering artifacts (Cairo uses
integers internally, +/- 8 millions, bug #20091)
* Redesign R-tree of linear features
mostly constant:
layer 4 bits
bridge/tunnel 2 bit
category 5 bits
oneway/access 5 bits (car 2, bikes 2, pedestrian 1)
==> 2 bytes => 6 bits remaining for the number of ways
* Rendering performance:
* do not render railway=rail;service=* at low zoom levels
* multiple surface R-trees:
R-tree of small surfaces; R-tree of other surfaces;
R-tree with about the 1% largest surfaces; ...
* Rendering fixes
==> Highway with area=yes
==> do not draw them as ways as well
==> Outline of highway surfaces
==> Notre Dame de Paris and Sacré Coeur are missing!
==> use same algorithm as osm2pgsql to deal with multipolygon tags
* We could improve the rendering of tunnels, ... by classifying nodes:
- do not use round linecap at tunnel extremities
- draw additional circles when a path extremities do not agree
- detect nodes with level mismatch
* One-way arrows (foot, bicycle, car), accessibility (foot, bicycle, car)
===> share between ways!
*)
let _ = Printexc.record_backtrace true
let _ = Column.set_database "/tmp/osm"
open Osm_display
let _ =
let width = 512 in
let height = 512 in
let st =
{ rect = { x = 0; y = 0; width = width; height = height };
prev_rect = { x = 0; y = 0; width = width; height = height };
level = 17.; prev_level = 17.; active = true; timeout = None;
surface = make_surface ();
marker1 = None; marker2 = None; path = [] } in
let lat = ref 48.850 in
let lon = ref 2.350 in
begin
let (ratio, _, tree) = Lazy.force large_surfaces in
let bbox = Rtree.bounding_box tree in
let c x = truncate (x *. 10_000_000. /. float ratio +. 0.5) in
Format.eprintf "%a %d %d@." Bbox.print bbox (c !lat) (c !lon);
if not (Bbox.contains_point bbox (c !lat) (c !lon)) then begin
let c x = float x /. 10_000_000. *. float ratio in
lat := c ((bbox.Bbox.min_lat + bbox.Bbox.max_lat) / 2);
lon := c ((bbox.Bbox.min_lon + bbox.Bbox.max_lon) / 2)
end
end;
let scale = compute_scale st in
st.rect <-
{ st.rect with
x = truncate (!lon *. scale) - width / 2;
y = - truncate (Geometry.lat_to_y (!lat *. 10_000_000.) /. 10_000_000. *. scale) - height / 2 };
Format.eprintf "%d %d@." st.rect.x st.rect.y;
ignore (GMain.Main.init ());
let w = GWindow.window () in
ignore (w#connect#destroy GMain.quit);
let b = GPack.hbox ~packing:w#add () in
let table =
GPack.table ~width ~height ~columns:1 ~rows:1 ~packing:(b#pack ~expand:true) () in
let display =
GMisc.drawing_area
~packing:(table#attach ~left:0 ~top:0 ~fill:`BOTH ~expand:`BOTH) () in
display#misc#set_can_focus true;
let queue_draw () = GtkBase.Widget.queue_draw display#as_widget in
let refresh () =
invalidate_surface st.surface;
queue_draw ()
in
let update_size () =
let a = display#misc#allocation in
st.rect <-
{ x = st.rect.x + (st.rect.width - a.Gtk.width) / 2;
y = st.rect.y + (st.rect.height - a.Gtk.height) / 2;
width = a.Gtk.width;
height = a.Gtk.height }
in
ignore (display#event#connect#expose
(fun ev ->
let t = Unix.gettimeofday () in
let area = GdkEvent.Expose.area ev in
let x = Gdk.Rectangle.x area in
let y = Gdk.Rectangle.y area in
let width = Gdk.Rectangle.width area in
let height = Gdk.Rectangle.height area in
update_size ();
let a = st.rect in
let ctx = Cairo_gtk.create (display#misc#window) in
let pm = st.surface in
if st.active then begin
grow_surface st.surface display a.width a.height;
let dx = pm.valid_rect.x - st.rect.x in
let dy = pm.valid_rect.y - st.rect.y in
let p = get_surface pm in
if
(dx > 0 && pm.valid_rect.width + dx < a.width) ||
(dy > 0 && pm.valid_rect.height + dy < a.height)
then begin
We would have to redraw four rectangles
pm.valid_rect <- empty_rectangle
end else if not (rectangle_is_empty pm.valid_rect) then begin
let r = pm.valid_rect in
if (dx <> 0 || dy <> 0) then begin
let ctx = Cairo.create p in
Cairo.set_source_surface ctx p (float dx) (float dy);
Cairo.rectangle ctx
(float dx) (float dy) (float r.width) (float r.height);
Cairo.set_operator ctx Cairo.SOURCE;
Cairo.fill ctx
end;
0 < = p ; 0 < = l ; p + l < = m
if p + d + l <= 0 then
(0, 0)
else if p + d < 0 then
(0, l + p + d)
else if p + d >= m then
(m, 0)
else if p + d + l > m then
(p + d, m - p - d)
else
(p + d, l)
in
let (x, width) = offset 0 r.width dx pm.p_width in
let (y, height) = offset 0 r.height dy pm.p_height in
if height > 0 then begin
if x > 0 then begin
assert (x + width >= a.width);
draw_map st p 0 y x height
end else begin
assert (x = 0);
if a.width > width then
draw_map st p width y (a.width - width) height
end
end;
if y > 0 then begin
assert (y + height >= a.height);
draw_map st p 0 0 a.width y;
end else begin
assert (y = 0);
if a.height > height then
draw_map st p 0 height a.width (a.height - height)
end;
pm.valid_rect <- st.rect
end;
let r = pm.valid_rect in
if x + width > r.width || y + height > r.height then begin
draw_map st p 0 0 a.width a.height;
pm.valid_rect <- st.rect
end;
Cairo.set_source_surface ctx p 0. 0.;
end else begin
Cairo.set_source_rgb ctx 0.8 0.8 0.8;
Cairo.rectangle ctx (float x) (float y) (float width) (float height);
Cairo.fill ctx;
let p = get_surface pm in
Cairo.set_source_surface ctx p 0. 0.;
let coeff = 2. ** (st.prev_level -. st.level) in
let matrix = Cairo.Matrix.init_identity () in
Cairo.Matrix.translate matrix
(-. float st.prev_rect.x) (-. float st.prev_rect.y);
Cairo.Matrix.scale matrix coeff coeff;
Cairo.Matrix.translate matrix (float st.rect.x) (float st.rect.y);
Cairo.Pattern.set_matrix (Cairo.get_source ctx) matrix;
end;
Cairo.rectangle ctx (float x) (float y) (float width) (float height);
Cairo.save ctx;
Workaround for a Cairo bug ( in ATI Catalyst drivers ? ):
if st.active then Cairo.set_operator ctx Cairo.SOURCE;
Cairo.fill_preserve ctx;
Cairo.restore ctx;
Cairo.clip ctx;
draw_route st ctx;
Format.eprintf "Redraw: %f@." (Unix.gettimeofday () -. t);
true));
let pos = ref None in
ignore (display#event#connect#button_press
(fun ev ->
display#misc#grab_focus ();
if !pos = None then
pos := Some (GdkEvent.Button.x ev, GdkEvent.Button.y ev,
GdkEvent.Button.button ev, false);
false));
ignore (display#event#connect#button_release
(fun ev ->
let but' = GdkEvent.Button.button ev in
begin match !pos with
Some (x, y, but, move) when but = but' ->
update_size ();
if not move && but = 1 then begin
st.marker1 <- find_marker st x y;
update_route st;
queue_draw ()
end else if not move && but = 3 then begin
st.marker2 <- find_marker st x y;
update_route st;
queue_draw ()
end;
pos := None
| _ ->
()
end;
false));
ignore (display#event#connect#motion_notify
(fun ev ->
let (x', y') =
if GdkEvent.Motion.is_hint ev then
let (x', y') = display#misc#pointer in
(float x', float y')
else
(GdkEvent.Motion.x ev, GdkEvent.Motion.y ev)
in
begin match !pos with
Some (x, y, but, move)
when but = 1
&& (move || abs_float (x -. x') > 3. || abs_float (y -. y') > 3.) ->
st.rect <-
{st.rect with
x = st.rect.x + truncate (x -. x');
y = st.rect.y + truncate (y -. y') };
pos := Some (x', y', 1, true);
queue_draw ()
| _ ->
()
end;
false));
display#event#add
[`BUTTON_PRESS; `BUTTON_RELEASE; `BUTTON1_MOTION; `POINTER_MOTION_HINT];
let perform_zoom ev delta =
let x = truncate (GdkEvent.Scroll.x ev) in
let y = truncate (GdkEvent.Scroll.y ev) in
if (async_zoom || (delta > 0. && async_zoom_in)) && st.active then begin
st.prev_level <- st.level;
st.prev_rect <- st.rect;
st.active <- false
end;
st.level <- st.level +. delta;
Format.eprintf "level: %f@." st.level;
update_size ();
st.rect <-
{ st.rect with
x = truncate ((float (st.rect.x + x)) *. 2. ** delta) - x;
y = truncate ((float (st.rect.y + y)) *. 2. ** delta) - y };
begin match st.timeout with
Some id -> Glib.Timeout.remove id
| None -> ()
end;
if not st.active then
st.timeout <-
Some (Glib.Timeout.add async_delay
(fun () ->
st.timeout<- None; st.active <- true; refresh (); false));
refresh ();
in
ignore (display#event#connect#scroll
(fun ev ->
match GdkEvent.Scroll.direction ev with
`UP ->
perform_zoom ev 0.125;
true
| `DOWN ->
perform_zoom ev (-0.125);
true
| _ ->
false));
display#event#add [`SCROLL];
w#show ();
GMain.main ()
|
5b5c9874e5487ab6187d93de0e001151d32765eb8db4ee424eb5a3aae192a0ca
|
ocamllabs/ocaml-modular-implicits
|
pr5673_bad.ml
|
module Classdef = struct
class virtual ['a, 'b, 'c] cl0 =
object
constraint 'c = < m : 'a -> 'b -> int; .. >
end
class virtual ['a, 'b] cl1 =
object
method virtual raise_trouble : int -> 'a
method virtual m : 'a -> 'b -> int
end
class virtual ['a, 'b] cl2 =
object
method virtual as_cl0 : ('a, 'b, ('a, 'b) cl1) cl0
end
end
type refer1 = < poly : 'a 'b 'c . (('b, 'c) #Classdef.cl2 as 'a) >
type refer2 = < poly : 'a 'b 'c . (('b, 'c) #Classdef.cl2 as 'a) >
(* Actually this should succeed ... *)
let f (x : refer1) = (x : refer2)
| null |
https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/testsuite/tests/typing-poly-bugs/pr5673_bad.ml
|
ocaml
|
Actually this should succeed ...
|
module Classdef = struct
class virtual ['a, 'b, 'c] cl0 =
object
constraint 'c = < m : 'a -> 'b -> int; .. >
end
class virtual ['a, 'b] cl1 =
object
method virtual raise_trouble : int -> 'a
method virtual m : 'a -> 'b -> int
end
class virtual ['a, 'b] cl2 =
object
method virtual as_cl0 : ('a, 'b, ('a, 'b) cl1) cl0
end
end
type refer1 = < poly : 'a 'b 'c . (('b, 'c) #Classdef.cl2 as 'a) >
type refer2 = < poly : 'a 'b 'c . (('b, 'c) #Classdef.cl2 as 'a) >
let f (x : refer1) = (x : refer2)
|
89f786864696c11e4da78f845b0c76e1cfee8f267d91c112eb1800a7222d776c
|
huangjs/cl
|
isamax.lisp
|
;;; Compiled by f2cl version:
( " f2cl1.l , v 1.215 2009/04/07 22:05:21 rtoy Exp $ "
" f2cl2.l , v 1.37 2008/02/22 22:19:33 rtoy Exp $ "
" f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Exp $ "
" f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Exp $ "
" f2cl5.l , v 1.200 2009/01/19 02:38:17 rtoy Exp $ "
" f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ "
" macros.l , v 1.112 2009/01/08 12:57:19 " )
Using Lisp CMU Common Lisp 19f ( 19F )
;;;
;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
;;; (:coerce-assigns :as-needed) (:array-type ':array)
;;; (:array-slicing t) (:declare-common nil)
;;; (:float-format double-float))
(in-package :blas)
(defun isamax (n sx incx)
(declare (type (array single-float (*)) sx)
(type (f2cl-lib:integer4) incx n))
(f2cl-lib:with-multi-array-data
((sx single-float sx-%data% sx-%offset%))
(prog ((i 0) (ix 0) (smax 0.0f0) (isamax 0))
(declare (type (single-float) smax)
(type (f2cl-lib:integer4) isamax ix i))
(setf isamax 0)
(if (or (< n 1) (<= incx 0)) (go end_label))
(setf isamax 1)
(if (= n 1) (go end_label))
(if (= incx 1) (go label20))
(setf ix 1)
(setf smax (abs (f2cl-lib:fref sx-%data% (1) ((1 *)) sx-%offset%)))
(setf ix (f2cl-lib:int-add ix incx))
(f2cl-lib:fdo (i 2 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(if
(<= (abs (f2cl-lib:fref sx-%data% (ix) ((1 *)) sx-%offset%)) smax)
(go label5))
(setf isamax i)
(setf smax (abs (f2cl-lib:fref sx-%data% (ix) ((1 *)) sx-%offset%)))
label5
(setf ix (f2cl-lib:int-add ix incx))
label10))
(go end_label)
label20
(setf smax (abs (f2cl-lib:fref sx-%data% (1) ((1 *)) sx-%offset%)))
(f2cl-lib:fdo (i 2 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(if (<= (abs (f2cl-lib:fref sx-%data% (i) ((1 *)) sx-%offset%)) smax)
(go label30))
(setf isamax i)
(setf smax (abs (f2cl-lib:fref sx-%data% (i) ((1 *)) sx-%offset%)))
label30))
(go end_label)
end_label
(return (values isamax nil nil nil)))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::isamax
fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((fortran-to-lisp::integer4) (array single-float (*))
(fortran-to-lisp::integer4))
:return-values '(nil nil nil)
:calls 'nil)))
| null |
https://raw.githubusercontent.com/huangjs/cl/96158b3f82f82a6b7d53ef04b3b29c5c8de2dbf7/lib/maxima/share/lapack/blas/isamax.lisp
|
lisp
|
Compiled by f2cl version:
Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
(:coerce-assigns :as-needed) (:array-type ':array)
(:array-slicing t) (:declare-common nil)
(:float-format double-float))
|
( " f2cl1.l , v 1.215 2009/04/07 22:05:21 rtoy Exp $ "
" f2cl2.l , v 1.37 2008/02/22 22:19:33 rtoy Exp $ "
" f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Exp $ "
" f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Exp $ "
" f2cl5.l , v 1.200 2009/01/19 02:38:17 rtoy Exp $ "
" f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ "
" macros.l , v 1.112 2009/01/08 12:57:19 " )
Using Lisp CMU Common Lisp 19f ( 19F )
(in-package :blas)
(defun isamax (n sx incx)
(declare (type (array single-float (*)) sx)
(type (f2cl-lib:integer4) incx n))
(f2cl-lib:with-multi-array-data
((sx single-float sx-%data% sx-%offset%))
(prog ((i 0) (ix 0) (smax 0.0f0) (isamax 0))
(declare (type (single-float) smax)
(type (f2cl-lib:integer4) isamax ix i))
(setf isamax 0)
(if (or (< n 1) (<= incx 0)) (go end_label))
(setf isamax 1)
(if (= n 1) (go end_label))
(if (= incx 1) (go label20))
(setf ix 1)
(setf smax (abs (f2cl-lib:fref sx-%data% (1) ((1 *)) sx-%offset%)))
(setf ix (f2cl-lib:int-add ix incx))
(f2cl-lib:fdo (i 2 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(if
(<= (abs (f2cl-lib:fref sx-%data% (ix) ((1 *)) sx-%offset%)) smax)
(go label5))
(setf isamax i)
(setf smax (abs (f2cl-lib:fref sx-%data% (ix) ((1 *)) sx-%offset%)))
label5
(setf ix (f2cl-lib:int-add ix incx))
label10))
(go end_label)
label20
(setf smax (abs (f2cl-lib:fref sx-%data% (1) ((1 *)) sx-%offset%)))
(f2cl-lib:fdo (i 2 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(if (<= (abs (f2cl-lib:fref sx-%data% (i) ((1 *)) sx-%offset%)) smax)
(go label30))
(setf isamax i)
(setf smax (abs (f2cl-lib:fref sx-%data% (i) ((1 *)) sx-%offset%)))
label30))
(go end_label)
end_label
(return (values isamax nil nil nil)))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::isamax
fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((fortran-to-lisp::integer4) (array single-float (*))
(fortran-to-lisp::integer4))
:return-values '(nil nil nil)
:calls 'nil)))
|
b673fc226bdbeb0491df464675ad80e5ed54b2543a4c36bef98c508179ea6708
|
BinaryAnalysisPlatform/bap
|
regular_seq.ml
|
open Core_kernel[@@warning "-D"]
open Sequence
let of_array arr =
init (Array.length arr) ~f:Array.(unsafe_get arr)
let sexp_of_seq sexp_of_elt t =
[%sexp_of:list] sexp_of_elt (to_list t)
let seq_of_sexp elt_of_sexp t =
of_list ([%of_sexp:list] elt_of_sexp t)
let t_of_sexp = seq_of_sexp
let sexp_of_t = sexp_of_seq
let cons x xs = append (singleton x) xs
let is_empty : 'a Sequence.t -> bool = length_is_bounded_by ~max:0
let filter s ~f = filteri s ~f:(fun _ x -> f x)
(* honestly stolen from newer core_kernel, to
get compatibility with older library versions *)
let compare compare_a t1 t2 =
with_return (fun r ->
iter (zip_full t1 t2) ~f:(function
| `Left _ -> r.return 1
| `Right _ -> r.return (-1)
| `Both (v1, v2) ->
let c = compare_a v1 v2 in
if c <> 0
then r.return c);
0)
module Binable = Bin_prot.Utils.Make_binable1(struct
module Binable = List
type 'a t = 'a Sequence.t
let to_binable = Sequence.to_list
let of_binable = Sequence.of_list
end)[@@warning "-D"]
include Binable
let compare_seq = compare
module Export = struct
let (^::) = cons
end
open Format
let max_printer_depth = ref 100
let pp_comma ppf () = pp_print_string ppf ", "
let pp_body ?max pp_elem ppf seq =
mapi seq ~f:(fun i elem () -> match max with
| Some m when m = i -> fprintf ppf "..."
| _ -> pp_elem ppf elem) |>
intersperse ~sep:(pp_comma ppf) |>
iter ~f:(fun pp -> pp ())
let pp_head ppf = fprintf ppf "{@[<2>"
let pp_tail ppf = fprintf ppf "}@]"
let pp_all pp_elem ppf seq =
pp_head ppf;
pp_body pp_elem ppf seq;
pp_tail ppf
let pp_some pp_elt ppf xs =
let xs = take xs (!max_printer_depth + 1) in
pp_head ppf;
pp_body ~max:!max_printer_depth pp_elt ppf xs;
pp_tail ppf
let pp pp_elt ppf xs =
if Sys.interactive.contents
then pp_some pp_elt ppf xs
else pp_all pp_elt ppf xs
type 'a seq = 'a t [@@deriving bin_io, compare, sexp]
let () = Pretty_printer.register "Regular.Std.Seq.pp"
| null |
https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap/253afc171bbfd0fe1b34f6442795dbf4b1798348/lib/regular/regular_seq.ml
|
ocaml
|
honestly stolen from newer core_kernel, to
get compatibility with older library versions
|
open Core_kernel[@@warning "-D"]
open Sequence
let of_array arr =
init (Array.length arr) ~f:Array.(unsafe_get arr)
let sexp_of_seq sexp_of_elt t =
[%sexp_of:list] sexp_of_elt (to_list t)
let seq_of_sexp elt_of_sexp t =
of_list ([%of_sexp:list] elt_of_sexp t)
let t_of_sexp = seq_of_sexp
let sexp_of_t = sexp_of_seq
let cons x xs = append (singleton x) xs
let is_empty : 'a Sequence.t -> bool = length_is_bounded_by ~max:0
let filter s ~f = filteri s ~f:(fun _ x -> f x)
let compare compare_a t1 t2 =
with_return (fun r ->
iter (zip_full t1 t2) ~f:(function
| `Left _ -> r.return 1
| `Right _ -> r.return (-1)
| `Both (v1, v2) ->
let c = compare_a v1 v2 in
if c <> 0
then r.return c);
0)
module Binable = Bin_prot.Utils.Make_binable1(struct
module Binable = List
type 'a t = 'a Sequence.t
let to_binable = Sequence.to_list
let of_binable = Sequence.of_list
end)[@@warning "-D"]
include Binable
let compare_seq = compare
module Export = struct
let (^::) = cons
end
open Format
let max_printer_depth = ref 100
let pp_comma ppf () = pp_print_string ppf ", "
let pp_body ?max pp_elem ppf seq =
mapi seq ~f:(fun i elem () -> match max with
| Some m when m = i -> fprintf ppf "..."
| _ -> pp_elem ppf elem) |>
intersperse ~sep:(pp_comma ppf) |>
iter ~f:(fun pp -> pp ())
let pp_head ppf = fprintf ppf "{@[<2>"
let pp_tail ppf = fprintf ppf "}@]"
let pp_all pp_elem ppf seq =
pp_head ppf;
pp_body pp_elem ppf seq;
pp_tail ppf
let pp_some pp_elt ppf xs =
let xs = take xs (!max_printer_depth + 1) in
pp_head ppf;
pp_body ~max:!max_printer_depth pp_elt ppf xs;
pp_tail ppf
let pp pp_elt ppf xs =
if Sys.interactive.contents
then pp_some pp_elt ppf xs
else pp_all pp_elt ppf xs
type 'a seq = 'a t [@@deriving bin_io, compare, sexp]
let () = Pretty_printer.register "Regular.Std.Seq.pp"
|
fcb25d19b2362645ac264acf54a34c21286645d794160872a904f78a75c01d73
|
Clozure/dpf
|
build.lisp
|
(in-package "CL-USER")
#+32-bit-target (error "use a 64-bit lisp")
(setq ccl:*save-source-locations* nil)
(defparameter *source-dir* (make-pathname :name nil :type nil
:defaults *load-truename*))
(defparameter *build-dir* (merge-pathnames "build/" *source-dir*))
(defparameter *dpf-files* '("application" "package" "misc" "window" "dpf"))
(defvar *bundle-dir*)
(defvar *contents-dir*)
(defvar *resources-dir*)
(defvar *macos-dir*)
(defparameter *resource-files* '("Credits.html"
"help.html"
"app.icns"))
(defun build-dpf (&optional (build-dir *build-dir*))
(let* ((*build-dir* build-dir)
(*bundle-dir* (merge-pathnames "Picture Window.app/" *build-dir*))
(*contents-dir* (merge-pathnames "Contents/" *bundle-dir*))
(*resources-dir* (merge-pathnames "Resources/" *contents-dir*))
(*macos-dir* (merge-pathnames "MacOS/" *contents-dir*))
(*default-pathname-defaults* *source-dir*))
(format t "~&Building from ~s, output to ~s" *source-dir* *build-dir*)
(ensure-directories-exist *resources-dir*)
(ensure-directories-exist (merge-pathnames "ccl/" *resources-dir*))
(ensure-directories-exist *macos-dir*)
(copy-file "Info.plist" (merge-pathnames "Info.plist" *contents-dir*)
:if-exists :supersede)
(dolist (f *resource-files*)
(copy-file f (merge-pathnames f *resources-dir*)
:if-exists :supersede))
(dolist (f *dpf-files*)
(let* ((src (make-pathname :name f
:type (pathname-type *.lisp-pathname*)
:defaults *source-dir*))
(dst (make-pathname :name f
:type (pathname-type *.fasl-pathname*)
:defaults *build-dir*)))
(compile-file src :output-file dst :verbose t :load t)))
(copy-file (ccl::kernel-path) (merge-pathnames "Picture Window"
*macos-dir*)
:if-exists :supersede
:preserve-attributes t)
(format t "~&saving...~%")
(finish-output t)
(save-application (merge-pathnames "ccl/Picture Window.image"
*resources-dir*)
:application-class (find-symbol "COCOA-APPLICATION"
"CCL"))))
(require 'objc-support)
(ccl::define-special-objc-word "DPF")
Core Animation lives in QuartzCore
(objc:load-framework "QuartzCore" :quartzcore)
(load "ccl:mac-ui;cf-utils")
(load "ccl:mac-ui;event-process")
(build-dpf)
| null |
https://raw.githubusercontent.com/Clozure/dpf/174ae4ed065b66329df34b8bc1ba28ae7f48c806/build.lisp
|
lisp
|
(in-package "CL-USER")
#+32-bit-target (error "use a 64-bit lisp")
(setq ccl:*save-source-locations* nil)
(defparameter *source-dir* (make-pathname :name nil :type nil
:defaults *load-truename*))
(defparameter *build-dir* (merge-pathnames "build/" *source-dir*))
(defparameter *dpf-files* '("application" "package" "misc" "window" "dpf"))
(defvar *bundle-dir*)
(defvar *contents-dir*)
(defvar *resources-dir*)
(defvar *macos-dir*)
(defparameter *resource-files* '("Credits.html"
"help.html"
"app.icns"))
(defun build-dpf (&optional (build-dir *build-dir*))
(let* ((*build-dir* build-dir)
(*bundle-dir* (merge-pathnames "Picture Window.app/" *build-dir*))
(*contents-dir* (merge-pathnames "Contents/" *bundle-dir*))
(*resources-dir* (merge-pathnames "Resources/" *contents-dir*))
(*macos-dir* (merge-pathnames "MacOS/" *contents-dir*))
(*default-pathname-defaults* *source-dir*))
(format t "~&Building from ~s, output to ~s" *source-dir* *build-dir*)
(ensure-directories-exist *resources-dir*)
(ensure-directories-exist (merge-pathnames "ccl/" *resources-dir*))
(ensure-directories-exist *macos-dir*)
(copy-file "Info.plist" (merge-pathnames "Info.plist" *contents-dir*)
:if-exists :supersede)
(dolist (f *resource-files*)
(copy-file f (merge-pathnames f *resources-dir*)
:if-exists :supersede))
(dolist (f *dpf-files*)
(let* ((src (make-pathname :name f
:type (pathname-type *.lisp-pathname*)
:defaults *source-dir*))
(dst (make-pathname :name f
:type (pathname-type *.fasl-pathname*)
:defaults *build-dir*)))
(compile-file src :output-file dst :verbose t :load t)))
(copy-file (ccl::kernel-path) (merge-pathnames "Picture Window"
*macos-dir*)
:if-exists :supersede
:preserve-attributes t)
(format t "~&saving...~%")
(finish-output t)
(save-application (merge-pathnames "ccl/Picture Window.image"
*resources-dir*)
:application-class (find-symbol "COCOA-APPLICATION"
"CCL"))))
(require 'objc-support)
(ccl::define-special-objc-word "DPF")
Core Animation lives in QuartzCore
(objc:load-framework "QuartzCore" :quartzcore)
(load "ccl:mac-ui;cf-utils")
(load "ccl:mac-ui;event-process")
(build-dpf)
|
|
744f14dd76727296b98f8d08b46fc62a8ec4eb7bf9135bc25519950e1b608419
|
brendanhay/amazonka
|
ImportClientBranding.hs
|
# LANGUAGE DeriveGeneric #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE NamedFieldPuns #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
{-# LANGUAGE StrictData #-}
# LANGUAGE TypeFamilies #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Derived from AWS service descriptions , licensed under Apache 2.0 .
-- |
-- Module : Amazonka.WorkSpaces.ImportClientBranding
Copyright : ( c ) 2013 - 2023
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
-- Imports client branding. Client branding allows you to customize your
WorkSpace\ 's client login portal . You can tailor your login portal
-- company logo, the support email address, support link, link to reset
-- password, and a custom message for users trying to sign in.
--
-- After you import client branding, the default branding experience for
-- the specified platform type is replaced with the imported experience
--
- You must specify at least one platform type when importing client
-- branding.
--
- You can import up to 6 MB of data with each request . If your request
-- exceeds this limit, you can import client branding for different
-- platform types using separate requests.
--
- In each platform type , the @SupportEmail@ and @SupportLink@
parameters are mutually exclusive . You can specify only one
-- parameter for each platform type, but not both.
--
- Imported data can take up to a minute to appear in the WorkSpaces
-- client.
module Amazonka.WorkSpaces.ImportClientBranding
( -- * Creating a Request
ImportClientBranding (..),
newImportClientBranding,
-- * Request Lenses
importClientBranding_deviceTypeAndroid,
importClientBranding_deviceTypeIos,
importClientBranding_deviceTypeLinux,
importClientBranding_deviceTypeOsx,
importClientBranding_deviceTypeWeb,
importClientBranding_deviceTypeWindows,
importClientBranding_resourceId,
-- * Destructuring the Response
ImportClientBrandingResponse (..),
newImportClientBrandingResponse,
-- * Response Lenses
importClientBrandingResponse_deviceTypeAndroid,
importClientBrandingResponse_deviceTypeIos,
importClientBrandingResponse_deviceTypeLinux,
importClientBrandingResponse_deviceTypeOsx,
importClientBrandingResponse_deviceTypeWeb,
importClientBrandingResponse_deviceTypeWindows,
importClientBrandingResponse_httpStatus,
)
where
import qualified Amazonka.Core as Core
import qualified Amazonka.Core.Lens.Internal as Lens
import qualified Amazonka.Data as Data
import qualified Amazonka.Prelude as Prelude
import qualified Amazonka.Request as Request
import qualified Amazonka.Response as Response
import Amazonka.WorkSpaces.Types
-- | /See:/ 'newImportClientBranding' smart constructor.
data ImportClientBranding = ImportClientBranding'
{ -- | The branding information to import for Android devices.
deviceTypeAndroid :: Prelude.Maybe DefaultImportClientBrandingAttributes,
-- | The branding information to import for iOS devices.
deviceTypeIos :: Prelude.Maybe IosImportClientBrandingAttributes,
-- | The branding information to import for Linux devices.
deviceTypeLinux :: Prelude.Maybe DefaultImportClientBrandingAttributes,
-- | The branding information to import for macOS devices.
deviceTypeOsx :: Prelude.Maybe DefaultImportClientBrandingAttributes,
-- | The branding information to import for web access.
deviceTypeWeb :: Prelude.Maybe DefaultImportClientBrandingAttributes,
| The branding information to import for Windows devices .
deviceTypeWindows :: Prelude.Maybe DefaultImportClientBrandingAttributes,
| The directory identifier of the WorkSpace for which you want to import
-- client branding.
resourceId :: Prelude.Text
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
-- |
Create a value of ' ' with all optional fields omitted .
--
Use < -lens generic - lens > or < optics > to modify other optional fields .
--
-- The following record fields are available, with the corresponding lenses provided
-- for backwards compatibility:
--
-- 'deviceTypeAndroid', 'importClientBranding_deviceTypeAndroid' - The branding information to import for Android devices.
--
-- 'deviceTypeIos', 'importClientBranding_deviceTypeIos' - The branding information to import for iOS devices.
--
-- 'deviceTypeLinux', 'importClientBranding_deviceTypeLinux' - The branding information to import for Linux devices.
--
-- 'deviceTypeOsx', 'importClientBranding_deviceTypeOsx' - The branding information to import for macOS devices.
--
-- 'deviceTypeWeb', 'importClientBranding_deviceTypeWeb' - The branding information to import for web access.
--
' deviceTypeWindows ' , ' importClientBranding_deviceTypeWindows ' - The branding information to import for Windows devices .
--
' resourceId ' , ' importClientBranding_resourceId ' - The directory identifier of the WorkSpace for which you want to import
-- client branding.
newImportClientBranding ::
-- | 'resourceId'
Prelude.Text ->
ImportClientBranding
newImportClientBranding pResourceId_ =
ImportClientBranding'
{ deviceTypeAndroid =
Prelude.Nothing,
deviceTypeIos = Prelude.Nothing,
deviceTypeLinux = Prelude.Nothing,
deviceTypeOsx = Prelude.Nothing,
deviceTypeWeb = Prelude.Nothing,
deviceTypeWindows = Prelude.Nothing,
resourceId = pResourceId_
}
-- | The branding information to import for Android devices.
importClientBranding_deviceTypeAndroid :: Lens.Lens' ImportClientBranding (Prelude.Maybe DefaultImportClientBrandingAttributes)
importClientBranding_deviceTypeAndroid = Lens.lens (\ImportClientBranding' {deviceTypeAndroid} -> deviceTypeAndroid) (\s@ImportClientBranding' {} a -> s {deviceTypeAndroid = a} :: ImportClientBranding)
-- | The branding information to import for iOS devices.
importClientBranding_deviceTypeIos :: Lens.Lens' ImportClientBranding (Prelude.Maybe IosImportClientBrandingAttributes)
importClientBranding_deviceTypeIos = Lens.lens (\ImportClientBranding' {deviceTypeIos} -> deviceTypeIos) (\s@ImportClientBranding' {} a -> s {deviceTypeIos = a} :: ImportClientBranding)
-- | The branding information to import for Linux devices.
importClientBranding_deviceTypeLinux :: Lens.Lens' ImportClientBranding (Prelude.Maybe DefaultImportClientBrandingAttributes)
importClientBranding_deviceTypeLinux = Lens.lens (\ImportClientBranding' {deviceTypeLinux} -> deviceTypeLinux) (\s@ImportClientBranding' {} a -> s {deviceTypeLinux = a} :: ImportClientBranding)
-- | The branding information to import for macOS devices.
importClientBranding_deviceTypeOsx :: Lens.Lens' ImportClientBranding (Prelude.Maybe DefaultImportClientBrandingAttributes)
importClientBranding_deviceTypeOsx = Lens.lens (\ImportClientBranding' {deviceTypeOsx} -> deviceTypeOsx) (\s@ImportClientBranding' {} a -> s {deviceTypeOsx = a} :: ImportClientBranding)
-- | The branding information to import for web access.
importClientBranding_deviceTypeWeb :: Lens.Lens' ImportClientBranding (Prelude.Maybe DefaultImportClientBrandingAttributes)
importClientBranding_deviceTypeWeb = Lens.lens (\ImportClientBranding' {deviceTypeWeb} -> deviceTypeWeb) (\s@ImportClientBranding' {} a -> s {deviceTypeWeb = a} :: ImportClientBranding)
| The branding information to import for Windows devices .
importClientBranding_deviceTypeWindows :: Lens.Lens' ImportClientBranding (Prelude.Maybe DefaultImportClientBrandingAttributes)
importClientBranding_deviceTypeWindows = Lens.lens (\ImportClientBranding' {deviceTypeWindows} -> deviceTypeWindows) (\s@ImportClientBranding' {} a -> s {deviceTypeWindows = a} :: ImportClientBranding)
| The directory identifier of the WorkSpace for which you want to import
-- client branding.
importClientBranding_resourceId :: Lens.Lens' ImportClientBranding Prelude.Text
importClientBranding_resourceId = Lens.lens (\ImportClientBranding' {resourceId} -> resourceId) (\s@ImportClientBranding' {} a -> s {resourceId = a} :: ImportClientBranding)
instance Core.AWSRequest ImportClientBranding where
type
AWSResponse ImportClientBranding =
ImportClientBrandingResponse
request overrides =
Request.postJSON (overrides defaultService)
response =
Response.receiveJSON
( \s h x ->
ImportClientBrandingResponse'
Prelude.<$> (x Data..?> "DeviceTypeAndroid")
Prelude.<*> (x Data..?> "DeviceTypeIos")
Prelude.<*> (x Data..?> "DeviceTypeLinux")
Prelude.<*> (x Data..?> "DeviceTypeOsx")
Prelude.<*> (x Data..?> "DeviceTypeWeb")
Prelude.<*> (x Data..?> "DeviceTypeWindows")
Prelude.<*> (Prelude.pure (Prelude.fromEnum s))
)
instance Prelude.Hashable ImportClientBranding where
hashWithSalt _salt ImportClientBranding' {..} =
_salt `Prelude.hashWithSalt` deviceTypeAndroid
`Prelude.hashWithSalt` deviceTypeIos
`Prelude.hashWithSalt` deviceTypeLinux
`Prelude.hashWithSalt` deviceTypeOsx
`Prelude.hashWithSalt` deviceTypeWeb
`Prelude.hashWithSalt` deviceTypeWindows
`Prelude.hashWithSalt` resourceId
instance Prelude.NFData ImportClientBranding where
rnf ImportClientBranding' {..} =
Prelude.rnf deviceTypeAndroid
`Prelude.seq` Prelude.rnf deviceTypeIos
`Prelude.seq` Prelude.rnf deviceTypeLinux
`Prelude.seq` Prelude.rnf deviceTypeOsx
`Prelude.seq` Prelude.rnf deviceTypeWeb
`Prelude.seq` Prelude.rnf deviceTypeWindows
`Prelude.seq` Prelude.rnf resourceId
instance Data.ToHeaders ImportClientBranding where
toHeaders =
Prelude.const
( Prelude.mconcat
[ "X-Amz-Target"
Data.=# ( "WorkspacesService.ImportClientBranding" ::
Prelude.ByteString
),
"Content-Type"
Data.=# ( "application/x-amz-json-1.1" ::
Prelude.ByteString
)
]
)
instance Data.ToJSON ImportClientBranding where
toJSON ImportClientBranding' {..} =
Data.object
( Prelude.catMaybes
[ ("DeviceTypeAndroid" Data..=)
Prelude.<$> deviceTypeAndroid,
("DeviceTypeIos" Data..=) Prelude.<$> deviceTypeIos,
("DeviceTypeLinux" Data..=)
Prelude.<$> deviceTypeLinux,
("DeviceTypeOsx" Data..=) Prelude.<$> deviceTypeOsx,
("DeviceTypeWeb" Data..=) Prelude.<$> deviceTypeWeb,
("DeviceTypeWindows" Data..=)
Prelude.<$> deviceTypeWindows,
Prelude.Just ("ResourceId" Data..= resourceId)
]
)
instance Data.ToPath ImportClientBranding where
toPath = Prelude.const "/"
instance Data.ToQuery ImportClientBranding where
toQuery = Prelude.const Prelude.mempty
| /See:/ ' newImportClientBrandingResponse ' smart constructor .
data ImportClientBrandingResponse = ImportClientBrandingResponse'
| The branding information configured for Android devices .
deviceTypeAndroid :: Prelude.Maybe DefaultClientBrandingAttributes,
-- | The branding information configured for iOS devices.
deviceTypeIos :: Prelude.Maybe IosClientBrandingAttributes,
-- | The branding information configured for Linux devices.
deviceTypeLinux :: Prelude.Maybe DefaultClientBrandingAttributes,
-- | The branding information configured for macOS devices.
deviceTypeOsx :: Prelude.Maybe DefaultClientBrandingAttributes,
-- | The branding information configured for web access.
deviceTypeWeb :: Prelude.Maybe DefaultClientBrandingAttributes,
-- | The branding information configured for Windows devices.
deviceTypeWindows :: Prelude.Maybe DefaultClientBrandingAttributes,
-- | The response's http status code.
httpStatus :: Prelude.Int
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
-- |
-- Create a value of 'ImportClientBrandingResponse' with all optional fields omitted.
--
Use < -lens generic - lens > or < optics > to modify other optional fields .
--
-- The following record fields are available, with the corresponding lenses provided
-- for backwards compatibility:
--
' deviceTypeAndroid ' , ' importClientBrandingResponse_deviceTypeAndroid ' - The branding information configured for Android devices .
--
-- 'deviceTypeIos', 'importClientBrandingResponse_deviceTypeIos' - The branding information configured for iOS devices.
--
-- 'deviceTypeLinux', 'importClientBrandingResponse_deviceTypeLinux' - The branding information configured for Linux devices.
--
-- 'deviceTypeOsx', 'importClientBrandingResponse_deviceTypeOsx' - The branding information configured for macOS devices.
--
-- 'deviceTypeWeb', 'importClientBrandingResponse_deviceTypeWeb' - The branding information configured for web access.
--
-- 'deviceTypeWindows', 'importClientBrandingResponse_deviceTypeWindows' - The branding information configured for Windows devices.
--
-- 'httpStatus', 'importClientBrandingResponse_httpStatus' - The response's http status code.
newImportClientBrandingResponse ::
-- | 'httpStatus'
Prelude.Int ->
ImportClientBrandingResponse
newImportClientBrandingResponse pHttpStatus_ =
ImportClientBrandingResponse'
{ deviceTypeAndroid =
Prelude.Nothing,
deviceTypeIos = Prelude.Nothing,
deviceTypeLinux = Prelude.Nothing,
deviceTypeOsx = Prelude.Nothing,
deviceTypeWeb = Prelude.Nothing,
deviceTypeWindows = Prelude.Nothing,
httpStatus = pHttpStatus_
}
| The branding information configured for Android devices .
importClientBrandingResponse_deviceTypeAndroid :: Lens.Lens' ImportClientBrandingResponse (Prelude.Maybe DefaultClientBrandingAttributes)
importClientBrandingResponse_deviceTypeAndroid = Lens.lens (\ImportClientBrandingResponse' {deviceTypeAndroid} -> deviceTypeAndroid) (\s@ImportClientBrandingResponse' {} a -> s {deviceTypeAndroid = a} :: ImportClientBrandingResponse)
-- | The branding information configured for iOS devices.
importClientBrandingResponse_deviceTypeIos :: Lens.Lens' ImportClientBrandingResponse (Prelude.Maybe IosClientBrandingAttributes)
importClientBrandingResponse_deviceTypeIos = Lens.lens (\ImportClientBrandingResponse' {deviceTypeIos} -> deviceTypeIos) (\s@ImportClientBrandingResponse' {} a -> s {deviceTypeIos = a} :: ImportClientBrandingResponse)
-- | The branding information configured for Linux devices.
importClientBrandingResponse_deviceTypeLinux :: Lens.Lens' ImportClientBrandingResponse (Prelude.Maybe DefaultClientBrandingAttributes)
importClientBrandingResponse_deviceTypeLinux = Lens.lens (\ImportClientBrandingResponse' {deviceTypeLinux} -> deviceTypeLinux) (\s@ImportClientBrandingResponse' {} a -> s {deviceTypeLinux = a} :: ImportClientBrandingResponse)
-- | The branding information configured for macOS devices.
importClientBrandingResponse_deviceTypeOsx :: Lens.Lens' ImportClientBrandingResponse (Prelude.Maybe DefaultClientBrandingAttributes)
importClientBrandingResponse_deviceTypeOsx = Lens.lens (\ImportClientBrandingResponse' {deviceTypeOsx} -> deviceTypeOsx) (\s@ImportClientBrandingResponse' {} a -> s {deviceTypeOsx = a} :: ImportClientBrandingResponse)
-- | The branding information configured for web access.
importClientBrandingResponse_deviceTypeWeb :: Lens.Lens' ImportClientBrandingResponse (Prelude.Maybe DefaultClientBrandingAttributes)
importClientBrandingResponse_deviceTypeWeb = Lens.lens (\ImportClientBrandingResponse' {deviceTypeWeb} -> deviceTypeWeb) (\s@ImportClientBrandingResponse' {} a -> s {deviceTypeWeb = a} :: ImportClientBrandingResponse)
-- | The branding information configured for Windows devices.
importClientBrandingResponse_deviceTypeWindows :: Lens.Lens' ImportClientBrandingResponse (Prelude.Maybe DefaultClientBrandingAttributes)
importClientBrandingResponse_deviceTypeWindows = Lens.lens (\ImportClientBrandingResponse' {deviceTypeWindows} -> deviceTypeWindows) (\s@ImportClientBrandingResponse' {} a -> s {deviceTypeWindows = a} :: ImportClientBrandingResponse)
-- | The response's http status code.
importClientBrandingResponse_httpStatus :: Lens.Lens' ImportClientBrandingResponse Prelude.Int
importClientBrandingResponse_httpStatus = Lens.lens (\ImportClientBrandingResponse' {httpStatus} -> httpStatus) (\s@ImportClientBrandingResponse' {} a -> s {httpStatus = a} :: ImportClientBrandingResponse)
instance Prelude.NFData ImportClientBrandingResponse where
rnf ImportClientBrandingResponse' {..} =
Prelude.rnf deviceTypeAndroid
`Prelude.seq` Prelude.rnf deviceTypeIos
`Prelude.seq` Prelude.rnf deviceTypeLinux
`Prelude.seq` Prelude.rnf deviceTypeOsx
`Prelude.seq` Prelude.rnf deviceTypeWeb
`Prelude.seq` Prelude.rnf deviceTypeWindows
`Prelude.seq` Prelude.rnf httpStatus
| null |
https://raw.githubusercontent.com/brendanhay/amazonka/09f52b75d2cfdff221b439280d3279d22690d6a6/lib/services/amazonka-workspaces/gen/Amazonka/WorkSpaces/ImportClientBranding.hs
|
haskell
|
# LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Module : Amazonka.WorkSpaces.ImportClientBranding
Stability : auto-generated
Imports client branding. Client branding allows you to customize your
company logo, the support email address, support link, link to reset
password, and a custom message for users trying to sign in.
After you import client branding, the default branding experience for
the specified platform type is replaced with the imported experience
branding.
exceeds this limit, you can import client branding for different
platform types using separate requests.
parameter for each platform type, but not both.
client.
* Creating a Request
* Request Lenses
* Destructuring the Response
* Response Lenses
| /See:/ 'newImportClientBranding' smart constructor.
| The branding information to import for Android devices.
| The branding information to import for iOS devices.
| The branding information to import for Linux devices.
| The branding information to import for macOS devices.
| The branding information to import for web access.
client branding.
|
The following record fields are available, with the corresponding lenses provided
for backwards compatibility:
'deviceTypeAndroid', 'importClientBranding_deviceTypeAndroid' - The branding information to import for Android devices.
'deviceTypeIos', 'importClientBranding_deviceTypeIos' - The branding information to import for iOS devices.
'deviceTypeLinux', 'importClientBranding_deviceTypeLinux' - The branding information to import for Linux devices.
'deviceTypeOsx', 'importClientBranding_deviceTypeOsx' - The branding information to import for macOS devices.
'deviceTypeWeb', 'importClientBranding_deviceTypeWeb' - The branding information to import for web access.
client branding.
| 'resourceId'
| The branding information to import for Android devices.
| The branding information to import for iOS devices.
| The branding information to import for Linux devices.
| The branding information to import for macOS devices.
| The branding information to import for web access.
client branding.
| The branding information configured for iOS devices.
| The branding information configured for Linux devices.
| The branding information configured for macOS devices.
| The branding information configured for web access.
| The branding information configured for Windows devices.
| The response's http status code.
|
Create a value of 'ImportClientBrandingResponse' with all optional fields omitted.
The following record fields are available, with the corresponding lenses provided
for backwards compatibility:
'deviceTypeIos', 'importClientBrandingResponse_deviceTypeIos' - The branding information configured for iOS devices.
'deviceTypeLinux', 'importClientBrandingResponse_deviceTypeLinux' - The branding information configured for Linux devices.
'deviceTypeOsx', 'importClientBrandingResponse_deviceTypeOsx' - The branding information configured for macOS devices.
'deviceTypeWeb', 'importClientBrandingResponse_deviceTypeWeb' - The branding information configured for web access.
'deviceTypeWindows', 'importClientBrandingResponse_deviceTypeWindows' - The branding information configured for Windows devices.
'httpStatus', 'importClientBrandingResponse_httpStatus' - The response's http status code.
| 'httpStatus'
| The branding information configured for iOS devices.
| The branding information configured for Linux devices.
| The branding information configured for macOS devices.
| The branding information configured for web access.
| The branding information configured for Windows devices.
| The response's http status code.
|
# LANGUAGE DeriveGeneric #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE NamedFieldPuns #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Derived from AWS service descriptions , licensed under Apache 2.0 .
Copyright : ( c ) 2013 - 2023
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
WorkSpace\ 's client login portal . You can tailor your login portal
- You must specify at least one platform type when importing client
- You can import up to 6 MB of data with each request . If your request
- In each platform type , the @SupportEmail@ and @SupportLink@
parameters are mutually exclusive . You can specify only one
- Imported data can take up to a minute to appear in the WorkSpaces
module Amazonka.WorkSpaces.ImportClientBranding
ImportClientBranding (..),
newImportClientBranding,
importClientBranding_deviceTypeAndroid,
importClientBranding_deviceTypeIos,
importClientBranding_deviceTypeLinux,
importClientBranding_deviceTypeOsx,
importClientBranding_deviceTypeWeb,
importClientBranding_deviceTypeWindows,
importClientBranding_resourceId,
ImportClientBrandingResponse (..),
newImportClientBrandingResponse,
importClientBrandingResponse_deviceTypeAndroid,
importClientBrandingResponse_deviceTypeIos,
importClientBrandingResponse_deviceTypeLinux,
importClientBrandingResponse_deviceTypeOsx,
importClientBrandingResponse_deviceTypeWeb,
importClientBrandingResponse_deviceTypeWindows,
importClientBrandingResponse_httpStatus,
)
where
import qualified Amazonka.Core as Core
import qualified Amazonka.Core.Lens.Internal as Lens
import qualified Amazonka.Data as Data
import qualified Amazonka.Prelude as Prelude
import qualified Amazonka.Request as Request
import qualified Amazonka.Response as Response
import Amazonka.WorkSpaces.Types
data ImportClientBranding = ImportClientBranding'
deviceTypeAndroid :: Prelude.Maybe DefaultImportClientBrandingAttributes,
deviceTypeIos :: Prelude.Maybe IosImportClientBrandingAttributes,
deviceTypeLinux :: Prelude.Maybe DefaultImportClientBrandingAttributes,
deviceTypeOsx :: Prelude.Maybe DefaultImportClientBrandingAttributes,
deviceTypeWeb :: Prelude.Maybe DefaultImportClientBrandingAttributes,
| The branding information to import for Windows devices .
deviceTypeWindows :: Prelude.Maybe DefaultImportClientBrandingAttributes,
| The directory identifier of the WorkSpace for which you want to import
resourceId :: Prelude.Text
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
Create a value of ' ' with all optional fields omitted .
Use < -lens generic - lens > or < optics > to modify other optional fields .
' deviceTypeWindows ' , ' importClientBranding_deviceTypeWindows ' - The branding information to import for Windows devices .
' resourceId ' , ' importClientBranding_resourceId ' - The directory identifier of the WorkSpace for which you want to import
newImportClientBranding ::
Prelude.Text ->
ImportClientBranding
newImportClientBranding pResourceId_ =
ImportClientBranding'
{ deviceTypeAndroid =
Prelude.Nothing,
deviceTypeIos = Prelude.Nothing,
deviceTypeLinux = Prelude.Nothing,
deviceTypeOsx = Prelude.Nothing,
deviceTypeWeb = Prelude.Nothing,
deviceTypeWindows = Prelude.Nothing,
resourceId = pResourceId_
}
importClientBranding_deviceTypeAndroid :: Lens.Lens' ImportClientBranding (Prelude.Maybe DefaultImportClientBrandingAttributes)
importClientBranding_deviceTypeAndroid = Lens.lens (\ImportClientBranding' {deviceTypeAndroid} -> deviceTypeAndroid) (\s@ImportClientBranding' {} a -> s {deviceTypeAndroid = a} :: ImportClientBranding)
importClientBranding_deviceTypeIos :: Lens.Lens' ImportClientBranding (Prelude.Maybe IosImportClientBrandingAttributes)
importClientBranding_deviceTypeIos = Lens.lens (\ImportClientBranding' {deviceTypeIos} -> deviceTypeIos) (\s@ImportClientBranding' {} a -> s {deviceTypeIos = a} :: ImportClientBranding)
importClientBranding_deviceTypeLinux :: Lens.Lens' ImportClientBranding (Prelude.Maybe DefaultImportClientBrandingAttributes)
importClientBranding_deviceTypeLinux = Lens.lens (\ImportClientBranding' {deviceTypeLinux} -> deviceTypeLinux) (\s@ImportClientBranding' {} a -> s {deviceTypeLinux = a} :: ImportClientBranding)
importClientBranding_deviceTypeOsx :: Lens.Lens' ImportClientBranding (Prelude.Maybe DefaultImportClientBrandingAttributes)
importClientBranding_deviceTypeOsx = Lens.lens (\ImportClientBranding' {deviceTypeOsx} -> deviceTypeOsx) (\s@ImportClientBranding' {} a -> s {deviceTypeOsx = a} :: ImportClientBranding)
importClientBranding_deviceTypeWeb :: Lens.Lens' ImportClientBranding (Prelude.Maybe DefaultImportClientBrandingAttributes)
importClientBranding_deviceTypeWeb = Lens.lens (\ImportClientBranding' {deviceTypeWeb} -> deviceTypeWeb) (\s@ImportClientBranding' {} a -> s {deviceTypeWeb = a} :: ImportClientBranding)
| The branding information to import for Windows devices .
importClientBranding_deviceTypeWindows :: Lens.Lens' ImportClientBranding (Prelude.Maybe DefaultImportClientBrandingAttributes)
importClientBranding_deviceTypeWindows = Lens.lens (\ImportClientBranding' {deviceTypeWindows} -> deviceTypeWindows) (\s@ImportClientBranding' {} a -> s {deviceTypeWindows = a} :: ImportClientBranding)
| The directory identifier of the WorkSpace for which you want to import
importClientBranding_resourceId :: Lens.Lens' ImportClientBranding Prelude.Text
importClientBranding_resourceId = Lens.lens (\ImportClientBranding' {resourceId} -> resourceId) (\s@ImportClientBranding' {} a -> s {resourceId = a} :: ImportClientBranding)
instance Core.AWSRequest ImportClientBranding where
type
AWSResponse ImportClientBranding =
ImportClientBrandingResponse
request overrides =
Request.postJSON (overrides defaultService)
response =
Response.receiveJSON
( \s h x ->
ImportClientBrandingResponse'
Prelude.<$> (x Data..?> "DeviceTypeAndroid")
Prelude.<*> (x Data..?> "DeviceTypeIos")
Prelude.<*> (x Data..?> "DeviceTypeLinux")
Prelude.<*> (x Data..?> "DeviceTypeOsx")
Prelude.<*> (x Data..?> "DeviceTypeWeb")
Prelude.<*> (x Data..?> "DeviceTypeWindows")
Prelude.<*> (Prelude.pure (Prelude.fromEnum s))
)
instance Prelude.Hashable ImportClientBranding where
hashWithSalt _salt ImportClientBranding' {..} =
_salt `Prelude.hashWithSalt` deviceTypeAndroid
`Prelude.hashWithSalt` deviceTypeIos
`Prelude.hashWithSalt` deviceTypeLinux
`Prelude.hashWithSalt` deviceTypeOsx
`Prelude.hashWithSalt` deviceTypeWeb
`Prelude.hashWithSalt` deviceTypeWindows
`Prelude.hashWithSalt` resourceId
instance Prelude.NFData ImportClientBranding where
rnf ImportClientBranding' {..} =
Prelude.rnf deviceTypeAndroid
`Prelude.seq` Prelude.rnf deviceTypeIos
`Prelude.seq` Prelude.rnf deviceTypeLinux
`Prelude.seq` Prelude.rnf deviceTypeOsx
`Prelude.seq` Prelude.rnf deviceTypeWeb
`Prelude.seq` Prelude.rnf deviceTypeWindows
`Prelude.seq` Prelude.rnf resourceId
instance Data.ToHeaders ImportClientBranding where
toHeaders =
Prelude.const
( Prelude.mconcat
[ "X-Amz-Target"
Data.=# ( "WorkspacesService.ImportClientBranding" ::
Prelude.ByteString
),
"Content-Type"
Data.=# ( "application/x-amz-json-1.1" ::
Prelude.ByteString
)
]
)
instance Data.ToJSON ImportClientBranding where
toJSON ImportClientBranding' {..} =
Data.object
( Prelude.catMaybes
[ ("DeviceTypeAndroid" Data..=)
Prelude.<$> deviceTypeAndroid,
("DeviceTypeIos" Data..=) Prelude.<$> deviceTypeIos,
("DeviceTypeLinux" Data..=)
Prelude.<$> deviceTypeLinux,
("DeviceTypeOsx" Data..=) Prelude.<$> deviceTypeOsx,
("DeviceTypeWeb" Data..=) Prelude.<$> deviceTypeWeb,
("DeviceTypeWindows" Data..=)
Prelude.<$> deviceTypeWindows,
Prelude.Just ("ResourceId" Data..= resourceId)
]
)
instance Data.ToPath ImportClientBranding where
toPath = Prelude.const "/"
instance Data.ToQuery ImportClientBranding where
toQuery = Prelude.const Prelude.mempty
| /See:/ ' newImportClientBrandingResponse ' smart constructor .
data ImportClientBrandingResponse = ImportClientBrandingResponse'
| The branding information configured for Android devices .
deviceTypeAndroid :: Prelude.Maybe DefaultClientBrandingAttributes,
deviceTypeIos :: Prelude.Maybe IosClientBrandingAttributes,
deviceTypeLinux :: Prelude.Maybe DefaultClientBrandingAttributes,
deviceTypeOsx :: Prelude.Maybe DefaultClientBrandingAttributes,
deviceTypeWeb :: Prelude.Maybe DefaultClientBrandingAttributes,
deviceTypeWindows :: Prelude.Maybe DefaultClientBrandingAttributes,
httpStatus :: Prelude.Int
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
Use < -lens generic - lens > or < optics > to modify other optional fields .
' deviceTypeAndroid ' , ' importClientBrandingResponse_deviceTypeAndroid ' - The branding information configured for Android devices .
newImportClientBrandingResponse ::
Prelude.Int ->
ImportClientBrandingResponse
newImportClientBrandingResponse pHttpStatus_ =
ImportClientBrandingResponse'
{ deviceTypeAndroid =
Prelude.Nothing,
deviceTypeIos = Prelude.Nothing,
deviceTypeLinux = Prelude.Nothing,
deviceTypeOsx = Prelude.Nothing,
deviceTypeWeb = Prelude.Nothing,
deviceTypeWindows = Prelude.Nothing,
httpStatus = pHttpStatus_
}
| The branding information configured for Android devices .
importClientBrandingResponse_deviceTypeAndroid :: Lens.Lens' ImportClientBrandingResponse (Prelude.Maybe DefaultClientBrandingAttributes)
importClientBrandingResponse_deviceTypeAndroid = Lens.lens (\ImportClientBrandingResponse' {deviceTypeAndroid} -> deviceTypeAndroid) (\s@ImportClientBrandingResponse' {} a -> s {deviceTypeAndroid = a} :: ImportClientBrandingResponse)
importClientBrandingResponse_deviceTypeIos :: Lens.Lens' ImportClientBrandingResponse (Prelude.Maybe IosClientBrandingAttributes)
importClientBrandingResponse_deviceTypeIos = Lens.lens (\ImportClientBrandingResponse' {deviceTypeIos} -> deviceTypeIos) (\s@ImportClientBrandingResponse' {} a -> s {deviceTypeIos = a} :: ImportClientBrandingResponse)
importClientBrandingResponse_deviceTypeLinux :: Lens.Lens' ImportClientBrandingResponse (Prelude.Maybe DefaultClientBrandingAttributes)
importClientBrandingResponse_deviceTypeLinux = Lens.lens (\ImportClientBrandingResponse' {deviceTypeLinux} -> deviceTypeLinux) (\s@ImportClientBrandingResponse' {} a -> s {deviceTypeLinux = a} :: ImportClientBrandingResponse)
importClientBrandingResponse_deviceTypeOsx :: Lens.Lens' ImportClientBrandingResponse (Prelude.Maybe DefaultClientBrandingAttributes)
importClientBrandingResponse_deviceTypeOsx = Lens.lens (\ImportClientBrandingResponse' {deviceTypeOsx} -> deviceTypeOsx) (\s@ImportClientBrandingResponse' {} a -> s {deviceTypeOsx = a} :: ImportClientBrandingResponse)
importClientBrandingResponse_deviceTypeWeb :: Lens.Lens' ImportClientBrandingResponse (Prelude.Maybe DefaultClientBrandingAttributes)
importClientBrandingResponse_deviceTypeWeb = Lens.lens (\ImportClientBrandingResponse' {deviceTypeWeb} -> deviceTypeWeb) (\s@ImportClientBrandingResponse' {} a -> s {deviceTypeWeb = a} :: ImportClientBrandingResponse)
importClientBrandingResponse_deviceTypeWindows :: Lens.Lens' ImportClientBrandingResponse (Prelude.Maybe DefaultClientBrandingAttributes)
importClientBrandingResponse_deviceTypeWindows = Lens.lens (\ImportClientBrandingResponse' {deviceTypeWindows} -> deviceTypeWindows) (\s@ImportClientBrandingResponse' {} a -> s {deviceTypeWindows = a} :: ImportClientBrandingResponse)
importClientBrandingResponse_httpStatus :: Lens.Lens' ImportClientBrandingResponse Prelude.Int
importClientBrandingResponse_httpStatus = Lens.lens (\ImportClientBrandingResponse' {httpStatus} -> httpStatus) (\s@ImportClientBrandingResponse' {} a -> s {httpStatus = a} :: ImportClientBrandingResponse)
instance Prelude.NFData ImportClientBrandingResponse where
rnf ImportClientBrandingResponse' {..} =
Prelude.rnf deviceTypeAndroid
`Prelude.seq` Prelude.rnf deviceTypeIos
`Prelude.seq` Prelude.rnf deviceTypeLinux
`Prelude.seq` Prelude.rnf deviceTypeOsx
`Prelude.seq` Prelude.rnf deviceTypeWeb
`Prelude.seq` Prelude.rnf deviceTypeWindows
`Prelude.seq` Prelude.rnf httpStatus
|
73233889486b5e0d2cd2fcfb294dc4a7322372b7ac70cab6cfb7d3b0bb4d4207
|
stevenvar/OMicroB
|
simul.ml
|
(* Tools *)
let int_of_hex1 c =
match c with
| '0' .. '9' -> int_of_char c - int_of_char '0'
| 'a' .. 'f' -> int_of_char c - int_of_char 'a' + 10
| 'A' .. 'F' -> int_of_char c - int_of_char 'A' + 10
| _ -> invalid_arg "Simul.int_of_hex1"
let int_of_hex2 c1 c0 =
(int_of_hex1 c1 lsl 4) lor int_of_hex1 c0
;;
let int_of_hex3 c2 c1 c0 =
(int_of_hex1 c2 lsl 8) lor (int_of_hex1 c1 lsl 4) lor int_of_hex1 c0
;;
(***)
module type MCUSimul = sig
type 'a pin
type register
type bit
type analog_channel
val pin_of_string : string -> [ `SIMUL ] pin
val analog_pin_of_string : string -> [ `AREAD | `SIMUL ] pin
val name_of_pin : [ `SIMUL ] pin -> string
val nb_pins : int
val num_of_pin : [ `SIMUL ] pin -> int
val pin_of_num : int -> [ `SIMUL ] pin option
val spdr : register
val register_of_char : char -> register
val char_of_register : register -> char
val register_of_index : int -> register
val index_of_register : register -> int
val nb_registers : int
val index_of_bit : bit -> int
val bit_of_index : int -> bit
val register_of_pin : [ `SIMUL ] pin -> register
val bit_of_pin : [ `SIMUL ] pin -> bit
val pin_of_register_bit : register -> bit -> [ `SIMUL ] pin
val analog_of_pin : [ `SIMUL | `AREAD ] pin -> analog_channel
val pin_of_analog : analog_channel -> [< `SIMUL | `AREAD ] pin
val int_of_analog : analog_channel -> int
val analog_of_int : int -> analog_channel
end
module type Simul = sig
include MCUSimul
val string_of_analog : analog_channel -> string
val analog_of_string : string -> analog_channel
type input =
IWrite of register * int
| ITris of register * int
| IWriteAnalog of analog_channel * int
| IConfigAnalog of int
| ISync
| IStop
val input_of_string : string -> input
type output =
| OSet of [ `SIMUL ] pin
| OClear of [ `SIMUL ] pin
| OWrite of register * int
| OWriteAnalog of analog_channel * int
| ODone
| OStop
val string_of_output : output -> string
val channel : output Event.channel
val send : output -> unit
type handler =
| Exit_handler of (unit -> unit)
| Write_handler of (register -> int -> unit)
| Write_register_handler of register * (int -> unit)
| Tris_handler of (register -> int -> unit)
| Tris_register_handler of register * (int -> unit)
| Set_handler of ([ `SIMUL ] pin -> unit)
| Clear_handler of ([ `SIMUL ] pin -> unit)
| Change_handler of ([ `SIMUL ] pin -> bool -> unit)
| Set_pin_handler of [ `SIMUL ] pin * (unit -> unit)
| Clear_pin_handler of [ `SIMUL ] pin * (unit -> unit)
| Change_pin_handler of [ `SIMUL ] pin * (bool -> unit)
| Setin_handler of ([ `SIMUL ] pin -> unit)
| Setout_handler of ([ `SIMUL ] pin -> unit)
| Setstate_handler of ([ `SIMUL ] pin -> bool -> unit)
| Setin_pin_handler of [ `SIMUL ] pin * (unit -> unit)
| Setout_pin_handler of [ `SIMUL ] pin * (unit -> unit)
| Setstate_pin_handler of [ `SIMUL ] pin * (bool -> unit)
| Write_analog_handler of (analog_channel -> int -> unit)
| Write_an_analog_handler of analog_channel * (int -> unit)
| Config_analogs_handler of (int -> unit)
val handlers_mutex : Mutex.t
val handlers : handler list ref
val add_handler : handler -> unit
val remove_handler : handler -> unit
val registers : int array
val triss : int array
val analogs : int array
val analog_cnt : int ref
val scall1 : ('a -> unit) -> 'a -> unit
val scall2 : ('a -> 'b -> unit) -> 'a -> 'b -> unit
val exec : input -> bool
val start : unit -> unit
val join : unit -> unit
val write_register : register -> int -> unit
val set_pin : [ `SIMUL ] pin -> unit
val clear_pin : [ `SIMUL ] pin -> unit
val change_pin : [ `SIMUL ] pin -> bool -> unit
val write_analog : analog_channel -> int -> unit
val read_register : register -> int
val read_tris : register -> int
val test_pin : [ `SIMUL ] pin -> bool
val state_pin : [ `SIMUL ] pin -> bool
val analog_input_count : unit -> int
end
module Make(M : MCUSimul) : Simul = struct
include M
let string_of_analog an =
name_of_pin (pin_of_analog an)
let analog_of_string str =
analog_of_pin (analog_pin_of_string str)
(***)
type input =
| IWrite of register * int
| ITris of register * int
| IWriteAnalog of analog_channel * int
| IConfigAnalog of int | ISync | IStop
let input_of_string s =
let error e = invalid_arg (Printf.sprintf "Simul.input_of_string : %s, %s" s (Printexc.to_string e)) in
match s with
| "SYNC" -> ISync
| "STOP" -> IStop
| _ ->
try
match s.[0] with
| 'W' ->
assert (String.length s = 4);
IWrite (register_of_index @@ (fun x -> int_of_char x - 1) @@ s.[1], int_of_hex2 s.[2] s.[3])
| 'T' ->
assert (String.length s = 4);
ITris (register_of_index @@ (fun x -> int_of_char x - 1) @@ s.[1], int_of_hex2 s.[2] s.[3])
| 'Z' ->
assert (String.length s = 5);
IWriteAnalog (analog_of_int @@ (fun x -> int_of_char x - 1) @@ s.[1], int_of_hex3 s.[2] s.[3] s.[4])
| 'C' ->
assert (String.length s = 2);
IConfigAnalog (int_of_hex1 s.[1])
| _ -> error (Failure "First character")
with e -> error e
(***)
type output =
| OSet of [ `SIMUL ] pin
| OClear of [ `SIMUL ] pin
| OWrite of register * int
| OWriteAnalog of analog_channel * int
| ODone
| OStop
let index_of_pin p = index_of_bit @@ bit_of_pin @@ p
let string_of_output output =
match output with
| OSet pin ->
Printf.sprintf "S%c%d" (char_of_int (index_of_register (register_of_pin pin) + 1))
(index_of_pin pin)
| OClear pin ->
Printf.sprintf "C%c%d" (char_of_int (index_of_register (register_of_pin pin) + 1))
(index_of_pin pin)
| OWrite (register, value) ->
if value < 0 || value > 0xFF
then failwith (Printf.sprintf "value %d of OWrite is out of range [ 0x0; 0xFF ]" value);
Printf.sprintf "W%c%02X" (char_of_int (index_of_register register + 1)) value
| OWriteAnalog (an, value) ->
if value < 0 || value > 0x3FF
then failwith (Printf.sprintf "value %d of OWriteAnalog is out of range [ 0x0; 0x3FF ]" value);
Printf.sprintf "Z%c%03X" (char_of_int @@ (fun x -> int_of_analog x + 1) an) value
| ODone -> "DONE"
| OStop -> "STOP"
;;
(***)
let channel = Event.new_channel ();;
let rec send_loop () =
begin try
let output = (Event.sync (Event.receive channel)) in
print_string (string_of_output output);
print_char '\n';
flush stdout;
with exn ->
Printf.eprintf "Unhandled exception %s\n%!" (Printexc.to_string exn)
end;
send_loop ();
in
ignore (Thread.create send_loop ());
;;
let send output = Event.sync (Event.send channel output);;
(***)
type handler =
| Exit_handler of (unit -> unit)
| Write_handler of (register -> int -> unit)
| Write_register_handler of register * (int -> unit)
| Tris_handler of (register -> int -> unit)
| Tris_register_handler of register * (int -> unit)
| Set_handler of ([ `SIMUL ] pin -> unit)
| Clear_handler of ([ `SIMUL ] pin -> unit)
| Change_handler of ([ `SIMUL ] pin -> bool -> unit)
| Set_pin_handler of [ `SIMUL ] pin * (unit -> unit)
| Clear_pin_handler of [ `SIMUL ] pin * (unit -> unit)
| Change_pin_handler of [ `SIMUL ] pin * (bool -> unit)
| Setin_handler of ([ `SIMUL ] pin -> unit)
| Setout_handler of ([ `SIMUL ] pin -> unit)
| Setstate_handler of ([ `SIMUL ] pin -> bool -> unit)
| Setin_pin_handler of [ `SIMUL ] pin * (unit -> unit)
| Setout_pin_handler of [ `SIMUL ] pin * (unit -> unit)
| Setstate_pin_handler of [ `SIMUL ] pin * (bool -> unit)
| Write_analog_handler of (analog_channel -> int -> unit)
| Write_an_analog_handler of analog_channel * (int -> unit)
| Config_analogs_handler of (int -> unit)
let handlers_mutex = Mutex.create ();;
let handlers = ref [];;
let add_handler handler =
Mutex.lock handlers_mutex;
handlers := handler :: !handlers;
Mutex.unlock handlers_mutex;
;;
let remove_handler handler =
Mutex.lock handlers_mutex;
handlers := List.filter ((!=) handler) !handlers;
Mutex.unlock handlers_mutex;
;;
(***)
let registers = Array.make nb_registers 0;;
let triss = Array.make nb_registers 0xFF;;
let analogs = Array.make 13 0;;
let analog_cnt = ref 0;;
let scall1 f arg =
try Printexc.print f arg with _ -> ();
;;
let scall2 f arg1 arg2 =
try Printexc.print (Printexc.print f arg1) arg2 with _ -> ();
;;
let pin_of_register_index register bit =
pin_of_register_bit register (bit_of_index bit)
let exec input =
match input with
| IWrite (register, new_value) ->
(* let s = Printf.sprintf "register %s = %d" (string_of_register register) new_value in *)
if true then failwith s ;
assert (new_value >= 0 && new_value <= 255);
let index = index_of_register register in
let old_value = registers.(index) in
let lxor_values = old_value lxor new_value in
let set_pins = ref [] in
let clear_pins = ref [] in
let () =
for i = 0 to 7 do
let mask = 1 lsl i in
if lxor_values land mask <> 0 then
if old_value land mask <> 0 then
try
clear_pins := pin_of_register_index register i :: !clear_pins
with _ -> ()
else
try
set_pins := pin_of_register_index register i :: !set_pins
with _ -> ()
done;
in
let set_pins = !set_pins in
let clear_pins = !clear_pins in
let call h =
match h with
| Write_handler f -> scall2 f register new_value;
| Write_register_handler (p, f) -> if p = register then scall1 f new_value;
| Set_handler f -> List.iter (scall1 f) set_pins;
| Clear_handler f -> List.iter (scall1 f) clear_pins;
| Change_handler f ->
List.iter (fun p -> scall2 f p true) set_pins;
List.iter (fun p -> scall2 f p false) clear_pins;
| Set_pin_handler (p, f) ->
List.iter (fun q -> if p = q then scall1 f ()) set_pins;
| Clear_pin_handler (p, f) ->
List.iter (fun q -> if p = q then scall1 f ()) clear_pins;
| Change_pin_handler (p, f) ->
List.iter (fun q -> if p = q then scall1 f true) set_pins;
List.iter (fun q -> if p = q then scall1 f false) clear_pins;
| _ -> ()
in
registers.(index) <- new_value;
List.iter call !handlers;
true
| ITris (register, new_value) ->
assert (new_value >= 0 && new_value <= 0xFF);
let index = index_of_register register in
let old_value = registers.(index) in
let lxor_values = old_value lxor new_value in
let new_in_pins = ref [] in
let new_out_pins = ref [] in
let () =
for i = 0 to 7 do
let mask = 1 lsl i in
if lxor_values land mask <> 0 then
if old_value land mask <> 0 then
try
new_out_pins := pin_of_register_index register i :: !new_out_pins
with _ -> ()
else
try
new_in_pins := pin_of_register_index register i :: !new_in_pins
with _ -> ()
done;
in
let new_in_pins = !new_in_pins in
let new_out_pins = !new_out_pins in
let call h =
match h with
| Tris_handler f -> scall2 f register new_value;
| Tris_register_handler (p, f) -> if p = register then scall1 f new_value;
| Setin_handler f -> List.iter (scall1 f) new_in_pins;
| Setout_handler f -> List.iter (scall1 f) new_out_pins;
| Setstate_handler f ->
List.iter (fun p -> scall2 f p true) new_in_pins;
List.iter (fun p -> scall2 f p false) new_out_pins;
| Setin_pin_handler (p, f) ->
List.iter (fun q -> if p = q then scall1 f ()) new_in_pins;
| Setout_pin_handler (p, f) ->
List.iter (fun q -> if p = q then scall1 f ()) new_out_pins;
| Setstate_pin_handler (p, f) ->
List.iter (fun q -> if p = q then scall1 f true) new_in_pins;
List.iter (fun q -> if p = q then scall1 f false) new_out_pins;
| _ -> ()
in
triss.(index) <- new_value;
List.iter call !handlers;
true
| IWriteAnalog (an, value) ->
assert (value >= 0 && value <= 0x3FF);
analogs.(int_of_analog an) <- value;
List.iter (fun handler -> match handler with
| Write_analog_handler f -> f an value
| Write_an_analog_handler (an', f) when an' = an -> f value
| _ -> ()
) !handlers;
true
| IConfigAnalog cnt ->
assert (cnt >= 0 && cnt <= 13);
analog_cnt := cnt;
List.iter (fun handler -> match handler with
| Config_analogs_handler f -> f cnt
| _ -> ()
) !handlers;
true
| ISync -> send ODone; true
| IStop ->
let call h = match h with Exit_handler f -> scall1 f () | _ -> () in
List.iter call !handlers;
false
;;
(***)
let (start, join) =
let rec receive_loop () =
let s = read_line () in
match
try Some (input_of_string s)
with Invalid_argument _ ->
Printf.eprintf "Invalid instruction: `%s'\n%!" s;
None
with
| Some input -> if exec input then receive_loop ();
| None -> receive_loop ();
in
let loop_thread_mutex = Mutex.create () in
let loop_thread = ref None in
let start () =
Mutex.lock loop_thread_mutex;
match !loop_thread with
| Some _ ->
Mutex.unlock loop_thread_mutex;
failwith "invalid call to Simul.start, simulator already running";
| None ->
loop_thread := Some (Thread.create receive_loop ());
Mutex.unlock loop_thread_mutex;
and join () =
Mutex.lock loop_thread_mutex;
match !loop_thread with
| None ->
Mutex.unlock loop_thread_mutex;
failwith "invalid call to Simul.join, simulator is not running";
| Some th ->
Mutex.unlock loop_thread_mutex;
Thread.join th;
in
(start, join)
;;
(***)
let write_register register value =
send (OWrite (register, value mod 256));;
let set_pin pin = send (OSet pin);;
let clear_pin pin = send (OClear pin);;
let change_pin pin b = send (if b then OSet pin else OClear pin);;
let write_analog an value = send (OWriteAnalog (an, value));;
let read_register register = registers.(index_of_register register);;
let read_tris register = triss.(index_of_register register);;
let test_pin pin =
try
let value = registers.(index_of_register (register_of_pin pin)) in
let mask = 1 lsl (index_of_pin pin) in
(value land mask) <> 0
with _ -> invalid_arg "test_pin"
;;
let state_pin pin =
try
let value = triss.(index_of_register (register_of_pin pin)) in
let mask = 1 lsl (index_of_pin pin) in
(value land mask) <> 0
with _ -> invalid_arg "state_pin"
;;
let analog_input_count () =
!analog_cnt
;;
end
| null |
https://raw.githubusercontent.com/stevenvar/OMicroB/6f412973e924aebc9fe845ef1bf3d260dcfecdbf/src/simulators/simul.ml
|
ocaml
|
Tools
*
*
*
*
*
*
let s = Printf.sprintf "register %s = %d" (string_of_register register) new_value in
*
*
|
let int_of_hex1 c =
match c with
| '0' .. '9' -> int_of_char c - int_of_char '0'
| 'a' .. 'f' -> int_of_char c - int_of_char 'a' + 10
| 'A' .. 'F' -> int_of_char c - int_of_char 'A' + 10
| _ -> invalid_arg "Simul.int_of_hex1"
let int_of_hex2 c1 c0 =
(int_of_hex1 c1 lsl 4) lor int_of_hex1 c0
;;
let int_of_hex3 c2 c1 c0 =
(int_of_hex1 c2 lsl 8) lor (int_of_hex1 c1 lsl 4) lor int_of_hex1 c0
;;
module type MCUSimul = sig
type 'a pin
type register
type bit
type analog_channel
val pin_of_string : string -> [ `SIMUL ] pin
val analog_pin_of_string : string -> [ `AREAD | `SIMUL ] pin
val name_of_pin : [ `SIMUL ] pin -> string
val nb_pins : int
val num_of_pin : [ `SIMUL ] pin -> int
val pin_of_num : int -> [ `SIMUL ] pin option
val spdr : register
val register_of_char : char -> register
val char_of_register : register -> char
val register_of_index : int -> register
val index_of_register : register -> int
val nb_registers : int
val index_of_bit : bit -> int
val bit_of_index : int -> bit
val register_of_pin : [ `SIMUL ] pin -> register
val bit_of_pin : [ `SIMUL ] pin -> bit
val pin_of_register_bit : register -> bit -> [ `SIMUL ] pin
val analog_of_pin : [ `SIMUL | `AREAD ] pin -> analog_channel
val pin_of_analog : analog_channel -> [< `SIMUL | `AREAD ] pin
val int_of_analog : analog_channel -> int
val analog_of_int : int -> analog_channel
end
module type Simul = sig
include MCUSimul
val string_of_analog : analog_channel -> string
val analog_of_string : string -> analog_channel
type input =
IWrite of register * int
| ITris of register * int
| IWriteAnalog of analog_channel * int
| IConfigAnalog of int
| ISync
| IStop
val input_of_string : string -> input
type output =
| OSet of [ `SIMUL ] pin
| OClear of [ `SIMUL ] pin
| OWrite of register * int
| OWriteAnalog of analog_channel * int
| ODone
| OStop
val string_of_output : output -> string
val channel : output Event.channel
val send : output -> unit
type handler =
| Exit_handler of (unit -> unit)
| Write_handler of (register -> int -> unit)
| Write_register_handler of register * (int -> unit)
| Tris_handler of (register -> int -> unit)
| Tris_register_handler of register * (int -> unit)
| Set_handler of ([ `SIMUL ] pin -> unit)
| Clear_handler of ([ `SIMUL ] pin -> unit)
| Change_handler of ([ `SIMUL ] pin -> bool -> unit)
| Set_pin_handler of [ `SIMUL ] pin * (unit -> unit)
| Clear_pin_handler of [ `SIMUL ] pin * (unit -> unit)
| Change_pin_handler of [ `SIMUL ] pin * (bool -> unit)
| Setin_handler of ([ `SIMUL ] pin -> unit)
| Setout_handler of ([ `SIMUL ] pin -> unit)
| Setstate_handler of ([ `SIMUL ] pin -> bool -> unit)
| Setin_pin_handler of [ `SIMUL ] pin * (unit -> unit)
| Setout_pin_handler of [ `SIMUL ] pin * (unit -> unit)
| Setstate_pin_handler of [ `SIMUL ] pin * (bool -> unit)
| Write_analog_handler of (analog_channel -> int -> unit)
| Write_an_analog_handler of analog_channel * (int -> unit)
| Config_analogs_handler of (int -> unit)
val handlers_mutex : Mutex.t
val handlers : handler list ref
val add_handler : handler -> unit
val remove_handler : handler -> unit
val registers : int array
val triss : int array
val analogs : int array
val analog_cnt : int ref
val scall1 : ('a -> unit) -> 'a -> unit
val scall2 : ('a -> 'b -> unit) -> 'a -> 'b -> unit
val exec : input -> bool
val start : unit -> unit
val join : unit -> unit
val write_register : register -> int -> unit
val set_pin : [ `SIMUL ] pin -> unit
val clear_pin : [ `SIMUL ] pin -> unit
val change_pin : [ `SIMUL ] pin -> bool -> unit
val write_analog : analog_channel -> int -> unit
val read_register : register -> int
val read_tris : register -> int
val test_pin : [ `SIMUL ] pin -> bool
val state_pin : [ `SIMUL ] pin -> bool
val analog_input_count : unit -> int
end
module Make(M : MCUSimul) : Simul = struct
include M
let string_of_analog an =
name_of_pin (pin_of_analog an)
let analog_of_string str =
analog_of_pin (analog_pin_of_string str)
type input =
| IWrite of register * int
| ITris of register * int
| IWriteAnalog of analog_channel * int
| IConfigAnalog of int | ISync | IStop
let input_of_string s =
let error e = invalid_arg (Printf.sprintf "Simul.input_of_string : %s, %s" s (Printexc.to_string e)) in
match s with
| "SYNC" -> ISync
| "STOP" -> IStop
| _ ->
try
match s.[0] with
| 'W' ->
assert (String.length s = 4);
IWrite (register_of_index @@ (fun x -> int_of_char x - 1) @@ s.[1], int_of_hex2 s.[2] s.[3])
| 'T' ->
assert (String.length s = 4);
ITris (register_of_index @@ (fun x -> int_of_char x - 1) @@ s.[1], int_of_hex2 s.[2] s.[3])
| 'Z' ->
assert (String.length s = 5);
IWriteAnalog (analog_of_int @@ (fun x -> int_of_char x - 1) @@ s.[1], int_of_hex3 s.[2] s.[3] s.[4])
| 'C' ->
assert (String.length s = 2);
IConfigAnalog (int_of_hex1 s.[1])
| _ -> error (Failure "First character")
with e -> error e
type output =
| OSet of [ `SIMUL ] pin
| OClear of [ `SIMUL ] pin
| OWrite of register * int
| OWriteAnalog of analog_channel * int
| ODone
| OStop
let index_of_pin p = index_of_bit @@ bit_of_pin @@ p
let string_of_output output =
match output with
| OSet pin ->
Printf.sprintf "S%c%d" (char_of_int (index_of_register (register_of_pin pin) + 1))
(index_of_pin pin)
| OClear pin ->
Printf.sprintf "C%c%d" (char_of_int (index_of_register (register_of_pin pin) + 1))
(index_of_pin pin)
| OWrite (register, value) ->
if value < 0 || value > 0xFF
then failwith (Printf.sprintf "value %d of OWrite is out of range [ 0x0; 0xFF ]" value);
Printf.sprintf "W%c%02X" (char_of_int (index_of_register register + 1)) value
| OWriteAnalog (an, value) ->
if value < 0 || value > 0x3FF
then failwith (Printf.sprintf "value %d of OWriteAnalog is out of range [ 0x0; 0x3FF ]" value);
Printf.sprintf "Z%c%03X" (char_of_int @@ (fun x -> int_of_analog x + 1) an) value
| ODone -> "DONE"
| OStop -> "STOP"
;;
let channel = Event.new_channel ();;
let rec send_loop () =
begin try
let output = (Event.sync (Event.receive channel)) in
print_string (string_of_output output);
print_char '\n';
flush stdout;
with exn ->
Printf.eprintf "Unhandled exception %s\n%!" (Printexc.to_string exn)
end;
send_loop ();
in
ignore (Thread.create send_loop ());
;;
let send output = Event.sync (Event.send channel output);;
type handler =
| Exit_handler of (unit -> unit)
| Write_handler of (register -> int -> unit)
| Write_register_handler of register * (int -> unit)
| Tris_handler of (register -> int -> unit)
| Tris_register_handler of register * (int -> unit)
| Set_handler of ([ `SIMUL ] pin -> unit)
| Clear_handler of ([ `SIMUL ] pin -> unit)
| Change_handler of ([ `SIMUL ] pin -> bool -> unit)
| Set_pin_handler of [ `SIMUL ] pin * (unit -> unit)
| Clear_pin_handler of [ `SIMUL ] pin * (unit -> unit)
| Change_pin_handler of [ `SIMUL ] pin * (bool -> unit)
| Setin_handler of ([ `SIMUL ] pin -> unit)
| Setout_handler of ([ `SIMUL ] pin -> unit)
| Setstate_handler of ([ `SIMUL ] pin -> bool -> unit)
| Setin_pin_handler of [ `SIMUL ] pin * (unit -> unit)
| Setout_pin_handler of [ `SIMUL ] pin * (unit -> unit)
| Setstate_pin_handler of [ `SIMUL ] pin * (bool -> unit)
| Write_analog_handler of (analog_channel -> int -> unit)
| Write_an_analog_handler of analog_channel * (int -> unit)
| Config_analogs_handler of (int -> unit)
let handlers_mutex = Mutex.create ();;
let handlers = ref [];;
let add_handler handler =
Mutex.lock handlers_mutex;
handlers := handler :: !handlers;
Mutex.unlock handlers_mutex;
;;
let remove_handler handler =
Mutex.lock handlers_mutex;
handlers := List.filter ((!=) handler) !handlers;
Mutex.unlock handlers_mutex;
;;
let registers = Array.make nb_registers 0;;
let triss = Array.make nb_registers 0xFF;;
let analogs = Array.make 13 0;;
let analog_cnt = ref 0;;
let scall1 f arg =
try Printexc.print f arg with _ -> ();
;;
let scall2 f arg1 arg2 =
try Printexc.print (Printexc.print f arg1) arg2 with _ -> ();
;;
let pin_of_register_index register bit =
pin_of_register_bit register (bit_of_index bit)
let exec input =
match input with
| IWrite (register, new_value) ->
if true then failwith s ;
assert (new_value >= 0 && new_value <= 255);
let index = index_of_register register in
let old_value = registers.(index) in
let lxor_values = old_value lxor new_value in
let set_pins = ref [] in
let clear_pins = ref [] in
let () =
for i = 0 to 7 do
let mask = 1 lsl i in
if lxor_values land mask <> 0 then
if old_value land mask <> 0 then
try
clear_pins := pin_of_register_index register i :: !clear_pins
with _ -> ()
else
try
set_pins := pin_of_register_index register i :: !set_pins
with _ -> ()
done;
in
let set_pins = !set_pins in
let clear_pins = !clear_pins in
let call h =
match h with
| Write_handler f -> scall2 f register new_value;
| Write_register_handler (p, f) -> if p = register then scall1 f new_value;
| Set_handler f -> List.iter (scall1 f) set_pins;
| Clear_handler f -> List.iter (scall1 f) clear_pins;
| Change_handler f ->
List.iter (fun p -> scall2 f p true) set_pins;
List.iter (fun p -> scall2 f p false) clear_pins;
| Set_pin_handler (p, f) ->
List.iter (fun q -> if p = q then scall1 f ()) set_pins;
| Clear_pin_handler (p, f) ->
List.iter (fun q -> if p = q then scall1 f ()) clear_pins;
| Change_pin_handler (p, f) ->
List.iter (fun q -> if p = q then scall1 f true) set_pins;
List.iter (fun q -> if p = q then scall1 f false) clear_pins;
| _ -> ()
in
registers.(index) <- new_value;
List.iter call !handlers;
true
| ITris (register, new_value) ->
assert (new_value >= 0 && new_value <= 0xFF);
let index = index_of_register register in
let old_value = registers.(index) in
let lxor_values = old_value lxor new_value in
let new_in_pins = ref [] in
let new_out_pins = ref [] in
let () =
for i = 0 to 7 do
let mask = 1 lsl i in
if lxor_values land mask <> 0 then
if old_value land mask <> 0 then
try
new_out_pins := pin_of_register_index register i :: !new_out_pins
with _ -> ()
else
try
new_in_pins := pin_of_register_index register i :: !new_in_pins
with _ -> ()
done;
in
let new_in_pins = !new_in_pins in
let new_out_pins = !new_out_pins in
let call h =
match h with
| Tris_handler f -> scall2 f register new_value;
| Tris_register_handler (p, f) -> if p = register then scall1 f new_value;
| Setin_handler f -> List.iter (scall1 f) new_in_pins;
| Setout_handler f -> List.iter (scall1 f) new_out_pins;
| Setstate_handler f ->
List.iter (fun p -> scall2 f p true) new_in_pins;
List.iter (fun p -> scall2 f p false) new_out_pins;
| Setin_pin_handler (p, f) ->
List.iter (fun q -> if p = q then scall1 f ()) new_in_pins;
| Setout_pin_handler (p, f) ->
List.iter (fun q -> if p = q then scall1 f ()) new_out_pins;
| Setstate_pin_handler (p, f) ->
List.iter (fun q -> if p = q then scall1 f true) new_in_pins;
List.iter (fun q -> if p = q then scall1 f false) new_out_pins;
| _ -> ()
in
triss.(index) <- new_value;
List.iter call !handlers;
true
| IWriteAnalog (an, value) ->
assert (value >= 0 && value <= 0x3FF);
analogs.(int_of_analog an) <- value;
List.iter (fun handler -> match handler with
| Write_analog_handler f -> f an value
| Write_an_analog_handler (an', f) when an' = an -> f value
| _ -> ()
) !handlers;
true
| IConfigAnalog cnt ->
assert (cnt >= 0 && cnt <= 13);
analog_cnt := cnt;
List.iter (fun handler -> match handler with
| Config_analogs_handler f -> f cnt
| _ -> ()
) !handlers;
true
| ISync -> send ODone; true
| IStop ->
let call h = match h with Exit_handler f -> scall1 f () | _ -> () in
List.iter call !handlers;
false
;;
let (start, join) =
let rec receive_loop () =
let s = read_line () in
match
try Some (input_of_string s)
with Invalid_argument _ ->
Printf.eprintf "Invalid instruction: `%s'\n%!" s;
None
with
| Some input -> if exec input then receive_loop ();
| None -> receive_loop ();
in
let loop_thread_mutex = Mutex.create () in
let loop_thread = ref None in
let start () =
Mutex.lock loop_thread_mutex;
match !loop_thread with
| Some _ ->
Mutex.unlock loop_thread_mutex;
failwith "invalid call to Simul.start, simulator already running";
| None ->
loop_thread := Some (Thread.create receive_loop ());
Mutex.unlock loop_thread_mutex;
and join () =
Mutex.lock loop_thread_mutex;
match !loop_thread with
| None ->
Mutex.unlock loop_thread_mutex;
failwith "invalid call to Simul.join, simulator is not running";
| Some th ->
Mutex.unlock loop_thread_mutex;
Thread.join th;
in
(start, join)
;;
let write_register register value =
send (OWrite (register, value mod 256));;
let set_pin pin = send (OSet pin);;
let clear_pin pin = send (OClear pin);;
let change_pin pin b = send (if b then OSet pin else OClear pin);;
let write_analog an value = send (OWriteAnalog (an, value));;
let read_register register = registers.(index_of_register register);;
let read_tris register = triss.(index_of_register register);;
let test_pin pin =
try
let value = registers.(index_of_register (register_of_pin pin)) in
let mask = 1 lsl (index_of_pin pin) in
(value land mask) <> 0
with _ -> invalid_arg "test_pin"
;;
let state_pin pin =
try
let value = triss.(index_of_register (register_of_pin pin)) in
let mask = 1 lsl (index_of_pin pin) in
(value land mask) <> 0
with _ -> invalid_arg "state_pin"
;;
let analog_input_count () =
!analog_cnt
;;
end
|
d7151f73e96ceea758dc2debe0470d82da15c45e16962b0b1a2264dab9dacc91
|
VMatthijs/CHAD
|
Examples.hs
|
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
-- | Examples of programs in the source languages. The testsuite checks that AD
-- on these programs does the right thing.
module Examples where
import GHC.TypeNats
import qualified Data.Vector.Unboxed.Sized as V
import Env
import Operation
import SourceLanguage
import Types
bin :: (a ~ Df1 a, b ~ Df1 b, c ~ Df1 c, a ~ Dr1 a, b ~ Dr1 b, c ~ Dr1 c
,a ~ UnLin a, b ~ UnLin b, c ~ UnLin c
,LT2 a, LT2 b, LT2 c, LT (UnLin (Df2 c)))
=> Operation (a, b) c -> STerm env a -> STerm env b -> STerm env c
bin op x y = SOp op (SPair x y)
infixl 6 `scaladd`
scaladd :: STerm env Scal -> STerm env Scal -> STerm env Scal
scaladd = bin EScalAdd
infixl 7 `scalprod`
scalprod :: STerm env Scal -> STerm env Scal -> STerm env Scal
scalprod = bin EScalProd
constant :: (a ~ Df1 a, a ~ Dr1 a, a ~ UnLin a, LT a, LT2 a, LT (UnLin (Df2 a)), Show a) => a -> STerm env a
constant x = SOp (Constant x) SUnit
| Mixed - second - order map ( as used in the examples in the paper ) expressed in
terms of the first - order map in the AD macros .
--
-- > map2 f xs = map1 (f x) with x from xs
map2 :: KnownNat n
=> STerm env (Scal -> Scal)
-> STerm env (Vect n)
-> STerm env (Vect n)
map2 fun arg = SMap1 (sinkSt1 fun `SApp` SVar Z) arg
First example program in the paper
paper_ex1 :: STerm '[Scal] ((Scal, Scal), Scal)
paper_ex1 =
SLet (constant 2 `scalprod` SVar Z) $ -- y
SLet (SVar (S Z) `scalprod` SVar Z) $ -- z
SLet (SOp EScalCos (SVar Z)) $ -- w
SLet (SPair (SPair (SVar (S (S Z))) (SVar (S Z))) (SVar Z)) $ -- v
SVar Z
paper_ex1_ref :: ((), Scal) -> ((Scal, Scal), Scal)
paper_ex1_ref ((), x) =
let y = 2 * x
z = x * y
w = cos z
v = ((y, z), w)
in v
Second example program in the paper
--
-- Simplified: sin (x1 * x4 * x3 + 2 * x2 * x3 + x4)
paper_ex2 :: STerm '[Scal, Scal, Scal, Scal] Scal
paper_ex2 =
SLet (SVar (S (S (S Z))) `scalprod` SVar Z
`scaladd` constant 2 `scalprod` SVar (S (S Z))) $ -- y
SLet (SVar Z `scalprod` SVar (S (S Z))) $ -- z
SLet (SVar Z `scaladd` SVar (S (S Z))) $ -- w
SLet (SOp EScalSin (SVar Z)) $ -- v
SVar Z
paper_ex2_ref :: (((((), Scal), Scal), Scal), Scal) -> Scal
paper_ex2_ref (((((), x1), x2), x3), x4) =
let y = x1 * x4 + 2 * x2
z = y * x3
w = z + x4
v = sin w
in v
Third example program in the paper
--
-- Simplified, this program is equivalent to:
-- map (\z -> x * z + 1) (replicate x)
-- = replicate (x * x + 1)
and hence the reverse derivative , given x : Scal and d : dScal^n , is :
sum ( map ( \dx - > dx * 2 * x ) d )
= 2 * sum ( map ( * x ) d )
paper_ex3 :: KnownNat n => STerm '[Scal] (Vect n)
paper_ex3 =
SLet (SLambda $ SVar (S Z) `scalprod` SVar Z `scaladd` constant 1) $ -- f
SLet (SReplicate (SVar (S Z))) $ -- zs
SLet (map2 (SVar (S Z)) (SVar Z)) $ -- ys
SVar Z
paper_ex3_ref :: KnownNat n => ((), Scal) -> Vect n
paper_ex3_ref ((), x) =
let f = \z -> x * z + 1
zs = V.replicate x
ys = V.map f zs
in ys
Fourth example program in the paper
--
-- Simplified, this program is equivalent to:
-- sum (map (x1 *) x2)
and hence the reverse derivative , given x1 : Scal , x2 : Scal^n and d : dScal , is :
-- - with respect to x1:
-- d * sum x2
-- - with respect to x2:
-- replicate (d * x1)
paper_ex4 :: KnownNat n => STerm '[Vect n, Scal] Scal
paper_ex4 =
SLet (SLambda $ SVar (S (S Z)) `scalprod` SVar Z) $ -- f
SLet (map2 (SVar Z) (SVar (S Z))) $ -- ys
SLet (SSum (SVar Z)) $ -- w
SVar Z
paper_ex4_ref :: KnownNat n => (((), Scal), Vect n) -> Scal
paper_ex4_ref (((), x1), x2) =
let f = \x2i -> x1 * x2i
ys = V.map f x2
w = V.sum ys
in w
x : Scal |- 2 * ( ( \y - > y * y ) x ) + 7 * x + 3
polynomial :: STerm '[Scal] Scal
polynomial =
constant 2 `scalprod` (square `SApp` SVar Z)
`scaladd` constant 7 `scalprod` SVar Z
`scaladd` constant 3
where square :: STerm env (Scal -> Scal)
square = SLambda (SVar Z `scalprod` SVar Z)
-- x
slid :: STerm '[Scal] Scal
slid = SVar Z
-- (x, x)
pair :: STerm '[Scal] (Scal, Scal)
pair = SPair (SVar Z) (SVar Z)
-- x + y
add :: STerm '[Scal, Scal] Scal
add = SVar (S Z) `scaladd` SVar Z
-- x + y, from a tuple
add2 :: STerm '[(Scal, Scal)] Scal
add2 = SOp EScalAdd (SVar Z)
-- x * y
prod :: STerm '[Scal, Scal] Scal
prod = SVar (S Z) `scalprod` SVar Z
-- x * y, from a tuple
prod2 :: STerm '[(Scal, Scal)] Scal
prod2 = SOp EScalProd (SVar Z)
-- let z = x + y in (z, z)
addCopy :: STerm '[Scal, Scal] (Scal, Scal)
addCopy = SLet (SVar (S Z) `scaladd` SVar Z)
(SPair (SVar Z) (SVar Z))
-- c * x
cX :: Double -> STerm '[Scal] Scal
cX c = SOp (Constant c) SUnit `scalprod` SVar Z
-- x^2
xSquared :: STerm '[Scal] Scal
xSquared = SVar Z `scalprod` SVar Z
-- x^3
xCubed :: STerm '[Scal] Scal
xCubed = xSquared `scalprod` SVar Z
-- c * x + x^2
quadratic :: Double -> STerm '[Scal] Scal
quadratic c = cX c `scaladd` xSquared
Map a quadratic function ( c*x + x^2 ) over an input vector
mapQuadratic :: Double -> STerm '[Vect 3] (Vect 3)
mapQuadratic c = SMap1 (generaliseEnv (quadratic c)) (SVar Z)
where
generaliseEnv :: STerm '[a] t -> STerm (a ': env) t
generaliseEnv = sinkSt (wSink wNil)
abs' :: STerm (Scal ': env) Scal
abs' =
SCase (SOp EScalSign (SVar Z))
(SOp EScalSubt (SPair (SOp (Constant 0) SUnit) (SVar (S Z))))
(SVar (S Z))
| null |
https://raw.githubusercontent.com/VMatthijs/CHAD/755fc47e1f8d1c3d91455f123338f44a353fc265/src/Examples.hs
|
haskell
|
| Examples of programs in the source languages. The testsuite checks that AD
on these programs does the right thing.
> map2 f xs = map1 (f x) with x from xs
y
z
w
v
Simplified: sin (x1 * x4 * x3 + 2 * x2 * x3 + x4)
y
z
w
v
Simplified, this program is equivalent to:
map (\z -> x * z + 1) (replicate x)
= replicate (x * x + 1)
f
zs
ys
Simplified, this program is equivalent to:
sum (map (x1 *) x2)
- with respect to x1:
d * sum x2
- with respect to x2:
replicate (d * x1)
f
ys
w
x
(x, x)
x + y
x + y, from a tuple
x * y
x * y, from a tuple
let z = x + y in (z, z)
c * x
x^2
x^3
c * x + x^2
|
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
module Examples where
import GHC.TypeNats
import qualified Data.Vector.Unboxed.Sized as V
import Env
import Operation
import SourceLanguage
import Types
bin :: (a ~ Df1 a, b ~ Df1 b, c ~ Df1 c, a ~ Dr1 a, b ~ Dr1 b, c ~ Dr1 c
,a ~ UnLin a, b ~ UnLin b, c ~ UnLin c
,LT2 a, LT2 b, LT2 c, LT (UnLin (Df2 c)))
=> Operation (a, b) c -> STerm env a -> STerm env b -> STerm env c
bin op x y = SOp op (SPair x y)
infixl 6 `scaladd`
scaladd :: STerm env Scal -> STerm env Scal -> STerm env Scal
scaladd = bin EScalAdd
infixl 7 `scalprod`
scalprod :: STerm env Scal -> STerm env Scal -> STerm env Scal
scalprod = bin EScalProd
constant :: (a ~ Df1 a, a ~ Dr1 a, a ~ UnLin a, LT a, LT2 a, LT (UnLin (Df2 a)), Show a) => a -> STerm env a
constant x = SOp (Constant x) SUnit
| Mixed - second - order map ( as used in the examples in the paper ) expressed in
terms of the first - order map in the AD macros .
map2 :: KnownNat n
=> STerm env (Scal -> Scal)
-> STerm env (Vect n)
-> STerm env (Vect n)
map2 fun arg = SMap1 (sinkSt1 fun `SApp` SVar Z) arg
First example program in the paper
paper_ex1 :: STerm '[Scal] ((Scal, Scal), Scal)
paper_ex1 =
SVar Z
paper_ex1_ref :: ((), Scal) -> ((Scal, Scal), Scal)
paper_ex1_ref ((), x) =
let y = 2 * x
z = x * y
w = cos z
v = ((y, z), w)
in v
Second example program in the paper
paper_ex2 :: STerm '[Scal, Scal, Scal, Scal] Scal
paper_ex2 =
SLet (SVar (S (S (S Z))) `scalprod` SVar Z
SVar Z
paper_ex2_ref :: (((((), Scal), Scal), Scal), Scal) -> Scal
paper_ex2_ref (((((), x1), x2), x3), x4) =
let y = x1 * x4 + 2 * x2
z = y * x3
w = z + x4
v = sin w
in v
Third example program in the paper
and hence the reverse derivative , given x : Scal and d : dScal^n , is :
sum ( map ( \dx - > dx * 2 * x ) d )
= 2 * sum ( map ( * x ) d )
paper_ex3 :: KnownNat n => STerm '[Scal] (Vect n)
paper_ex3 =
SVar Z
paper_ex3_ref :: KnownNat n => ((), Scal) -> Vect n
paper_ex3_ref ((), x) =
let f = \z -> x * z + 1
zs = V.replicate x
ys = V.map f zs
in ys
Fourth example program in the paper
and hence the reverse derivative , given x1 : Scal , x2 : Scal^n and d : dScal , is :
paper_ex4 :: KnownNat n => STerm '[Vect n, Scal] Scal
paper_ex4 =
SVar Z
paper_ex4_ref :: KnownNat n => (((), Scal), Vect n) -> Scal
paper_ex4_ref (((), x1), x2) =
let f = \x2i -> x1 * x2i
ys = V.map f x2
w = V.sum ys
in w
x : Scal |- 2 * ( ( \y - > y * y ) x ) + 7 * x + 3
polynomial :: STerm '[Scal] Scal
polynomial =
constant 2 `scalprod` (square `SApp` SVar Z)
`scaladd` constant 7 `scalprod` SVar Z
`scaladd` constant 3
where square :: STerm env (Scal -> Scal)
square = SLambda (SVar Z `scalprod` SVar Z)
slid :: STerm '[Scal] Scal
slid = SVar Z
pair :: STerm '[Scal] (Scal, Scal)
pair = SPair (SVar Z) (SVar Z)
add :: STerm '[Scal, Scal] Scal
add = SVar (S Z) `scaladd` SVar Z
add2 :: STerm '[(Scal, Scal)] Scal
add2 = SOp EScalAdd (SVar Z)
prod :: STerm '[Scal, Scal] Scal
prod = SVar (S Z) `scalprod` SVar Z
prod2 :: STerm '[(Scal, Scal)] Scal
prod2 = SOp EScalProd (SVar Z)
addCopy :: STerm '[Scal, Scal] (Scal, Scal)
addCopy = SLet (SVar (S Z) `scaladd` SVar Z)
(SPair (SVar Z) (SVar Z))
cX :: Double -> STerm '[Scal] Scal
cX c = SOp (Constant c) SUnit `scalprod` SVar Z
xSquared :: STerm '[Scal] Scal
xSquared = SVar Z `scalprod` SVar Z
xCubed :: STerm '[Scal] Scal
xCubed = xSquared `scalprod` SVar Z
quadratic :: Double -> STerm '[Scal] Scal
quadratic c = cX c `scaladd` xSquared
Map a quadratic function ( c*x + x^2 ) over an input vector
mapQuadratic :: Double -> STerm '[Vect 3] (Vect 3)
mapQuadratic c = SMap1 (generaliseEnv (quadratic c)) (SVar Z)
where
generaliseEnv :: STerm '[a] t -> STerm (a ': env) t
generaliseEnv = sinkSt (wSink wNil)
abs' :: STerm (Scal ': env) Scal
abs' =
SCase (SOp EScalSign (SVar Z))
(SOp EScalSubt (SPair (SOp (Constant 0) SUnit) (SVar (S Z))))
(SVar (S Z))
|
158f6a583391f253dc29d3636dc1519f74084e8aa44d3af542ce6eda6cf305f8
|
mirage/ocaml-dns
|
tsig.ml
|
( c ) 2017 , all rights reserved
let cs =
let module M = struct
type t = Cstruct.t
let pp = Cstruct.hexdump_pp
let equal = Cstruct.equal
end in
(module M: Alcotest.TESTABLE with type t = M.t)
let msg =
let module M = struct
type t = [ `Msg of string ]
let pp ppf = function `Msg str -> Fmt.string ppf str
let equal _ _ = true
end in
(module M: Alcotest.TESTABLE with type t = M.t)
let key =
match Base64.decode "GSnQJ+fHuzwj5yKzCOkXdISyGQXBUxMrjEjL4Kr1WIs=" with
| Error _ -> assert false
| Ok x -> Cstruct.of_string x
let key_name = Domain_name.of_string_exn "mykey.bla.example"
let of_h = Cstruct.of_hex
let tsig ?(fudge = 300) algorithm signed =
let fudge = Ptime.Span.of_int_s fudge in
let signed =
match Ptime.of_float_s signed with
| None -> assert false
| Some x -> x
in
match Dns.Tsig.tsig ~algorithm ~signed ~fudge () with
| None -> assert false
| Some x -> x
let example0 () =
let buf = of_h {__|62 d7 28 00 00 01 00 00 00 02 00 00 07 65 78 61
6d 70 6c 65 03 63 6f 6d 00 00 06 00 01 03 66 6f
6f c0 0c 00 ff 00 ff 00 00 00 00 00 00 03 62 61
72 c0 0c 00 01 00 01 00 00 01 2c 00 04 01 02 03
04|__}
and now = 1506887417.
and mac = of_h {__|bf 5d 77 ba 97 ba 7b 95 9e 1b 0d 95 64 a7 5b a6
95 bf 24 15 3b 9d a2 1b bf 6f ae 61 9d 0f 28 a1|__}
in
Alcotest.(check cs "tsig is the same" mac
(Dns_tsig.compute_tsig key_name (tsig Dns.Tsig.SHA256 now) ~key buf))
let example1 () =
let buf = of_h {__|4c 56 28 00 00 01 00 00 00 01 00 00 07 45 78 41
6d 50 6c 45 03 63 6f 6d 00 00 06 00 01 03 66 6f
6f 07 65 78 61 6d 70 6c 65 c0 14 00 ff 00 ff 00
00 00 00 00 00|__}
and now = 1506887742.
and mac = of_h {__|70 67 ae 70 9e fd 22 9e ce d9 65 25 8a db 8c 96
10 95 80 89 a7 ee 4f bb 13 81 e7 38 e3 a0 78 80|__}
in
Alcotest.(check cs "tsig is the same" mac
(Dns_tsig.compute_tsig key_name (tsig Dns.Tsig.SHA256 now) ~key buf))
let example2 () =
let buf = of_h {__|76 8a 28 00 00 01 00 00 00 01 00 00 07 65 78 61
6d 70 6c 65 00 00 06 00 01 03 66 6f 6f c0 0c 00
ff 00 ff 00 00 00 00 00 00|__}
and now = 1506888104.
and mac = of_h {__|e7 76 e6 df 4e 73 14 c8 eb ba 4c c7 a5 39 b3 93
a7 df 6d de 47 b6 fa cc 81 c8 47 29 20 77 40 44|__}
in
Alcotest.(check cs "tsig is the same" mac
(Dns_tsig.compute_tsig key_name (tsig Dns.Tsig.SHA256 now) ~key buf))
let tsig_tests = [
"example0", `Quick, example0 ;
"example1", `Quick, example1 ;
"example2", `Quick, example2 ;
]
let tests = [
"Tsig example", tsig_tests ;
]
let () = Alcotest.run "DNS name tests" tests
| null |
https://raw.githubusercontent.com/mirage/ocaml-dns/29168a8c464796fda77b50d721176f122ee724ae/test/tsig.ml
|
ocaml
|
( c ) 2017 , all rights reserved
let cs =
let module M = struct
type t = Cstruct.t
let pp = Cstruct.hexdump_pp
let equal = Cstruct.equal
end in
(module M: Alcotest.TESTABLE with type t = M.t)
let msg =
let module M = struct
type t = [ `Msg of string ]
let pp ppf = function `Msg str -> Fmt.string ppf str
let equal _ _ = true
end in
(module M: Alcotest.TESTABLE with type t = M.t)
let key =
match Base64.decode "GSnQJ+fHuzwj5yKzCOkXdISyGQXBUxMrjEjL4Kr1WIs=" with
| Error _ -> assert false
| Ok x -> Cstruct.of_string x
let key_name = Domain_name.of_string_exn "mykey.bla.example"
let of_h = Cstruct.of_hex
let tsig ?(fudge = 300) algorithm signed =
let fudge = Ptime.Span.of_int_s fudge in
let signed =
match Ptime.of_float_s signed with
| None -> assert false
| Some x -> x
in
match Dns.Tsig.tsig ~algorithm ~signed ~fudge () with
| None -> assert false
| Some x -> x
let example0 () =
let buf = of_h {__|62 d7 28 00 00 01 00 00 00 02 00 00 07 65 78 61
6d 70 6c 65 03 63 6f 6d 00 00 06 00 01 03 66 6f
6f c0 0c 00 ff 00 ff 00 00 00 00 00 00 03 62 61
72 c0 0c 00 01 00 01 00 00 01 2c 00 04 01 02 03
04|__}
and now = 1506887417.
and mac = of_h {__|bf 5d 77 ba 97 ba 7b 95 9e 1b 0d 95 64 a7 5b a6
95 bf 24 15 3b 9d a2 1b bf 6f ae 61 9d 0f 28 a1|__}
in
Alcotest.(check cs "tsig is the same" mac
(Dns_tsig.compute_tsig key_name (tsig Dns.Tsig.SHA256 now) ~key buf))
let example1 () =
let buf = of_h {__|4c 56 28 00 00 01 00 00 00 01 00 00 07 45 78 41
6d 50 6c 45 03 63 6f 6d 00 00 06 00 01 03 66 6f
6f 07 65 78 61 6d 70 6c 65 c0 14 00 ff 00 ff 00
00 00 00 00 00|__}
and now = 1506887742.
and mac = of_h {__|70 67 ae 70 9e fd 22 9e ce d9 65 25 8a db 8c 96
10 95 80 89 a7 ee 4f bb 13 81 e7 38 e3 a0 78 80|__}
in
Alcotest.(check cs "tsig is the same" mac
(Dns_tsig.compute_tsig key_name (tsig Dns.Tsig.SHA256 now) ~key buf))
let example2 () =
let buf = of_h {__|76 8a 28 00 00 01 00 00 00 01 00 00 07 65 78 61
6d 70 6c 65 00 00 06 00 01 03 66 6f 6f c0 0c 00
ff 00 ff 00 00 00 00 00 00|__}
and now = 1506888104.
and mac = of_h {__|e7 76 e6 df 4e 73 14 c8 eb ba 4c c7 a5 39 b3 93
a7 df 6d de 47 b6 fa cc 81 c8 47 29 20 77 40 44|__}
in
Alcotest.(check cs "tsig is the same" mac
(Dns_tsig.compute_tsig key_name (tsig Dns.Tsig.SHA256 now) ~key buf))
let tsig_tests = [
"example0", `Quick, example0 ;
"example1", `Quick, example1 ;
"example2", `Quick, example2 ;
]
let tests = [
"Tsig example", tsig_tests ;
]
let () = Alcotest.run "DNS name tests" tests
|
|
3ebee98c328780ba09450bfa06b49c77607c4b161cbf34b80a565c2a40834cbc
|
novalabsxyz/libp2p-peerbook
|
peerbook_SUITE.erl
|
-module(peerbook_SUITE).
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
-export([all/0, init_per_testcase/2, end_per_testcase/2]).
all() ->
[
listen_addr_test,
session_test,
nat_type_test,
get_put_test,
blacklist_test,
heartbeat_test,
notify_test,
stale_test,
signed_metadata_test
].
start_peerbook(OptOverride, Config) ->
#{public := PubKey, secret := PrivKey} = libp2p_crypto:generate_keys(ecc_compact),
SigFun = libp2p_crypto:mk_sig_fun(PrivKey),
PubKeyBin = libp2p_crypto:pubkey_to_bin(PubKey),
DataDir = ?config(priv_dir, Config),
Opts = maps:merge(#{ pubkey_bin => PubKeyBin,
data_dir => DataDir,
sig_fun => SigFun },
OptOverride),
{ok, Pid} = libp2p_peerbook:start_link(Opts),
{ok, Handle} = libp2p_peerbook:peerbook_handle(Pid),
[{peerbook, Handle}, {pubkey_bin, PubKeyBin} | Config].
init_per_testcase(heartbeat_test, Config) ->
%% have the peer refresh itself quickly and send out notifications
%% quick
start_peerbook(#{peer_time => 20,
notify_time => 20}, Config);
init_per_testcase(notify_test, Config) ->
%% only send out notifications quickly
start_peerbook(#{notify_time => 50}, Config);
init_per_testcase(stale_test, Config) ->
%% Set stale time to something short
StaleTime = 50,
[{stale_time, StaleTime} |
start_peerbook(#{stale_time => StaleTime}, Config)];
init_per_testcase(signed_metadata_test, Config) ->
Tab = ets:new(signed_metadata_test, [set, public, {write_concurrency, true}]),
Fun = fun() ->
case ets:lookup(Tab, metadata_fun) of
[] -> #{};
[{_, Fun}] -> Fun()
end
end,
start_peerbook(#{metadata_fun => Fun, peer_time => 50 },
[{tab, Tab} | Config]);
init_per_testcase(_, Config) ->
start_peerbook(#{}, Config).
end_per_testcase(_, Config) ->
Handle = ?config(peerbook, Config),
gen_server:stop(libp2p_peerbook:peerbook_pid(Handle)),
ok.
-define(assertAsync(Expr, BoolExpr),
case test_util:wait_until(fun() -> (Expr),(BoolExpr) end) of
true -> ok;
false -> erlang:error({assert,
[{module, ?MODULE},
{line, ?LINE},
{expression, (??BoolExpr)},
{expected, true},
{value ,false}
]
})
end).
-define(assertAsyncTimes(Tab, K,C),
?assertAsync(Count = case ets:lookup((Tab), (K)) of
[] -> 0;
[{(K), N}] -> N
end,
Count > (C))).
nat_type_test(Config) ->
Handle = ?config(peerbook, Config),
PubKeyBin = ?config(pubkey_bin, Config),
Set type
libp2p_peerbook:set_nat_type(Handle, symmetric),
?assertAsync({ok, ThisPeer} = libp2p_peerbook:get(Handle, PubKeyBin),
symmetric == libp2p_peer:nat_type(ThisPeer)),
ok.
listen_addr_test(Config) ->
Handle = ?config(peerbook, Config),
PubKeyBin = ?config(pubkey_bin, Config),
confirm empty listen
{ok, ThisPeer0} = libp2p_peerbook:get(Handle, PubKeyBin),
?assertEqual([], libp2p_peer:listen_addrs(ThisPeer0)),
%% register a listen address
ListenAddr = "/ip4/8.8.8.8/tcp/1234",
libp2p_peerbook:register_listen_addr(Handle, ListenAddr),
%% confirm it's stored
?assertAsync({ok, ThisPeer} = libp2p_peerbook:get(Handle, PubKeyBin),
[ListenAddr] == libp2p_peer:listen_addrs(ThisPeer)),
%% unregister the listen address
libp2p_peerbook:unregister_listen_addr(Handle, ListenAddr),
%% confirm it's cleared
?assertAsync({ok, Peer} = libp2p_peerbook:get(Handle, PubKeyBin),
[] == libp2p_peer:listen_addrs(Peer)),
ok.
session_test(Config) ->
Handle = ?config(peerbook, Config),
PubKeyBin = ?config(pubkey_bin, Config),
confirm empty listen
{ok, ThisPeer} = libp2p_peerbook:get(Handle, PubKeyBin),
?assertEqual([], libp2p_peer:connected_peers(ThisPeer)),
%% register a session key.. just reuse the one we already have
libp2p_peerbook:register_session(Handle, PubKeyBin),
%% And register it again to ensure it only comes listed once
libp2p_peerbook:register_session(Handle, PubKeyBin),
%% confirm it's stored
?assertAsync({ok, Peer} = libp2p_peerbook:get(Handle, PubKeyBin),
[PubKeyBin] == libp2p_peer:connected_peers(Peer)),
%% unregister the session address
libp2p_peerbook:unregister_session(Handle, PubKeyBin),
%% Unregistering again has no effect
libp2p_peerbook:unregister_session(Handle, PubKeyBin),
%% confirm it's cleared
?assertAsync({ok, Peer} = libp2p_peerbook:get(Handle, PubKeyBin),
[] == libp2p_peer:connected_peers(Peer)),
ok.
get_put_test(Config) ->
Handle = ?config(peerbook, Config),
PubKeyBin = ?config(pubkey_bin, Config),
{ok, ThisPeer} = libp2p_peerbook:get(Handle, PubKeyBin),
?assertEqual(PubKeyBin, libp2p_peer:pubkey_bin(ThisPeer)),
%% Add a peer beyond the self peer
{ok, NewPeer} = mk_peer(#{}),
ok = libp2p_peerbook:put(Handle, NewPeer),
Check is_key for self adnd new peer
?assert(libp2p_peerbook:is_key(Handle, PubKeyBin)),
?assert(libp2p_peerbook:is_key(Handle, libp2p_peer:pubkey_bin(NewPeer))),
%% And fail to fetch a non-existent key
?assertNot(libp2p_peerbook:is_key(Handle, <<>>)),
%% Check that self and new peer are in the store
?assertEqual(2, length(libp2p_peerbook:keys(Handle))),
?assertEqual(2, length(libp2p_peerbook:values(Handle))),
%% removing self should fail
?assertMatch({error, _}, libp2p_peerbook:remove(Handle, PubKeyBin)),
%% check removing other peer
?assertEqual(ok, libp2p_peerbook:remove(Handle, libp2p_peer:pubkey_bin(NewPeer))),
?assertNot(libp2p_peerbook:is_key(Handle, libp2p_peer:pubkey_bin(NewPeer))),
?assertEqual(1, length(libp2p_peerbook:keys(Handle))),
ok.
blacklist_test(Config) ->
Handle = ?config(peerbook, Config),
BlackListAddr = "/ip4/9.9.9.9/tcp/4321",
ListenAddrs = [BlackListAddr, "/ip4/8.8.8.8/tcp/1234"],
%% Add a peer beyond the self peer
{ok, NewPeer} = mk_peer(#{listen_addrs => ListenAddrs}),
ok = libp2p_peerbook:put(Handle, NewPeer),
%% black list an address
libp2p_peerbook:blacklist_listen_addr(Handle, libp2p_peer:pubkey_bin(NewPeer), BlackListAddr),
%% check that it's no longer in the cleared listen addresses for the peer
?assertAsync({ok, Peer} = libp2p_peerbook:get(Handle, libp2p_peer:pubkey_bin(NewPeer)),
not lists:member(BlackListAddr, libp2p_peer:cleared_listen_addrs(Peer))),
%% blacklisting for an unkown peer returns an error
?assertMatch({error, not_found}, libp2p_peerbook:blacklist_listen_addr(Handle, <<>>, BlackListAddr)),
ok.
heartbeat_test(Config) ->
Handle = ?config(peerbook, Config),
PubKeyBin = ?config(pubkey_bin, Config),
libp2p_peerbook:join_notify(Handle, self()),
%% joining twise is fine
libp2p_peerbook:join_notify(Handle, self()),
receive
{changed_peers, {{add, Add}, {remove, _}}} ->
?assert(maps:is_key(PubKeyBin, Add))
after 1000 ->
ct:fail(timeout_heartbeat)
end,
ok.
notify_test(Config) ->
Handle = ?config(peerbook, Config),
PubKeyBin = ?config(pubkey_bin, Config),
Add two peers
{ok, Peer1} = mk_peer(#{}),
{ok, Peer2} = mk_peer(#{}),
ok = libp2p_peerbook:put(Handle, Peer1),
ok = libp2p_peerbook:put(Handle, Peer2),
libp2p_peerbook:join_notify(Handle, self()),
%% cause a change in the self peer
libp2p_peerbook:set_nat_type(Handle, static),
And remove one of the two peers
Peer2PubKeyBin = libp2p_peer:pubkey_bin(Peer2),
libp2p_peerbook:remove(Handle, Peer2PubKeyBin),
receive
{changed_peers, {{add, Add}, {remove, Remove}}} ->
We should see the self peer and peer1 added and peer 2
%% removed
?assert(lists:member(Peer2PubKeyBin, Remove)),
?assert(maps:is_key(PubKeyBin, Add)),
?assert(maps:is_key(libp2p_peer:pubkey_bin(Peer1), Add))
after 1000 ->
ct:fail(timeout_notify)
end,
libp2p_peerbook:leave_notify(Handle, self()),
ok.
stale_test(Config) ->
Handle = ?config(peerbook, Config),
StaleTime = ?config(stale_time, Config),
%% Ensure stale time is what we configured it as
?assertEqual(StaleTime, libp2p_peerbook:stale_time(Handle)),
%% Add a peer
{ok, NewPeer} = mk_peer(#{}),
ok = libp2p_peerbook:put(Handle, NewPeer),
?assert(libp2p_peerbook:is_key(Handle, libp2p_peer:pubkey_bin(NewPeer))),
%% Wait for it to get stale and no longer be gettable
?assertAsync(Result = libp2p_peerbook:get(Handle, libp2p_peer:pubkey_bin(NewPeer)),
Result == {error, not_found}),
ok.
signed_metadata_test(Config) ->
Handle = ?config(peerbook, Config),
PubKeyBin = ?config(pubkey_bin, Config),
Tab = ?config(tab, Config),
%% Set the metdata function to a given fun
SetMetaDataFun = fun(F) -> ets:insert(Tab, {metadata_fun, F}) end,
%% Set the metadata function to a function that counts the number
%% of times a given fun is executed
SetCountedMetaDataFun = fun(K, F) ->
SetMetaDataFun(fun() ->
ets:update_counter(Tab, K, 1, {K, 0}),
F()
end)
end,
%% Try a normal metadata set
SetMetaDataFun(fun() -> #{<<"hello">> => <<"world">>} end),
?assertAsync({ok, Peer} = libp2p_peerbook:get(Handle, PubKeyBin),
#{ <<"hello">> => <<"world">> } == libp2p_peer:signed_metadata(Peer)),
Let the metedata crash a number of times
SetCountedMetaDataFun(crash_count,
fun() -> exit(fail_metadata) end),
?assertAsyncTimes(Tab, crash_count, 20),
%% Set to a slow function
SetCountedMetaDataFun(sleep_count,
fun() ->
timer:sleep(300),
#{}
end),
?assertAsyncTimes(Tab, sleep_count, 3),
ok.
%%
Utilities
%%
mk_peer(MapOveride) ->
#{public := PubKey, secret := PrivKey} = libp2p_crypto:generate_keys(ecc_compact),
SigFun = libp2p_crypto:mk_sig_fun(PrivKey),
mk_peer(MapOveride, libp2p_crypto:pubkey_to_bin(PubKey), SigFun).
mk_peer(MapOverride, PubKeyBin, SigFun) ->
PeerMap = maps:merge(#{pubkey_bin => PubKeyBin,
listen_addrs => ["/ip4/8.8.8.8/tcp/1234"],
nat_type => static
}, MapOverride),
libp2p_peer:from_map(PeerMap, SigFun).
| null |
https://raw.githubusercontent.com/novalabsxyz/libp2p-peerbook/210d73b3fc74d949dc360913f10e31a76987bb5f/test/peerbook_SUITE.erl
|
erlang
|
have the peer refresh itself quickly and send out notifications
quick
only send out notifications quickly
Set stale time to something short
register a listen address
confirm it's stored
unregister the listen address
confirm it's cleared
register a session key.. just reuse the one we already have
And register it again to ensure it only comes listed once
confirm it's stored
unregister the session address
Unregistering again has no effect
confirm it's cleared
Add a peer beyond the self peer
And fail to fetch a non-existent key
Check that self and new peer are in the store
removing self should fail
check removing other peer
Add a peer beyond the self peer
black list an address
check that it's no longer in the cleared listen addresses for the peer
blacklisting for an unkown peer returns an error
joining twise is fine
cause a change in the self peer
removed
Ensure stale time is what we configured it as
Add a peer
Wait for it to get stale and no longer be gettable
Set the metdata function to a given fun
Set the metadata function to a function that counts the number
of times a given fun is executed
Try a normal metadata set
Set to a slow function
|
-module(peerbook_SUITE).
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
-export([all/0, init_per_testcase/2, end_per_testcase/2]).
all() ->
[
listen_addr_test,
session_test,
nat_type_test,
get_put_test,
blacklist_test,
heartbeat_test,
notify_test,
stale_test,
signed_metadata_test
].
start_peerbook(OptOverride, Config) ->
#{public := PubKey, secret := PrivKey} = libp2p_crypto:generate_keys(ecc_compact),
SigFun = libp2p_crypto:mk_sig_fun(PrivKey),
PubKeyBin = libp2p_crypto:pubkey_to_bin(PubKey),
DataDir = ?config(priv_dir, Config),
Opts = maps:merge(#{ pubkey_bin => PubKeyBin,
data_dir => DataDir,
sig_fun => SigFun },
OptOverride),
{ok, Pid} = libp2p_peerbook:start_link(Opts),
{ok, Handle} = libp2p_peerbook:peerbook_handle(Pid),
[{peerbook, Handle}, {pubkey_bin, PubKeyBin} | Config].
init_per_testcase(heartbeat_test, Config) ->
start_peerbook(#{peer_time => 20,
notify_time => 20}, Config);
init_per_testcase(notify_test, Config) ->
start_peerbook(#{notify_time => 50}, Config);
init_per_testcase(stale_test, Config) ->
StaleTime = 50,
[{stale_time, StaleTime} |
start_peerbook(#{stale_time => StaleTime}, Config)];
init_per_testcase(signed_metadata_test, Config) ->
Tab = ets:new(signed_metadata_test, [set, public, {write_concurrency, true}]),
Fun = fun() ->
case ets:lookup(Tab, metadata_fun) of
[] -> #{};
[{_, Fun}] -> Fun()
end
end,
start_peerbook(#{metadata_fun => Fun, peer_time => 50 },
[{tab, Tab} | Config]);
init_per_testcase(_, Config) ->
start_peerbook(#{}, Config).
end_per_testcase(_, Config) ->
Handle = ?config(peerbook, Config),
gen_server:stop(libp2p_peerbook:peerbook_pid(Handle)),
ok.
-define(assertAsync(Expr, BoolExpr),
case test_util:wait_until(fun() -> (Expr),(BoolExpr) end) of
true -> ok;
false -> erlang:error({assert,
[{module, ?MODULE},
{line, ?LINE},
{expression, (??BoolExpr)},
{expected, true},
{value ,false}
]
})
end).
-define(assertAsyncTimes(Tab, K,C),
?assertAsync(Count = case ets:lookup((Tab), (K)) of
[] -> 0;
[{(K), N}] -> N
end,
Count > (C))).
nat_type_test(Config) ->
Handle = ?config(peerbook, Config),
PubKeyBin = ?config(pubkey_bin, Config),
Set type
libp2p_peerbook:set_nat_type(Handle, symmetric),
?assertAsync({ok, ThisPeer} = libp2p_peerbook:get(Handle, PubKeyBin),
symmetric == libp2p_peer:nat_type(ThisPeer)),
ok.
listen_addr_test(Config) ->
Handle = ?config(peerbook, Config),
PubKeyBin = ?config(pubkey_bin, Config),
confirm empty listen
{ok, ThisPeer0} = libp2p_peerbook:get(Handle, PubKeyBin),
?assertEqual([], libp2p_peer:listen_addrs(ThisPeer0)),
ListenAddr = "/ip4/8.8.8.8/tcp/1234",
libp2p_peerbook:register_listen_addr(Handle, ListenAddr),
?assertAsync({ok, ThisPeer} = libp2p_peerbook:get(Handle, PubKeyBin),
[ListenAddr] == libp2p_peer:listen_addrs(ThisPeer)),
libp2p_peerbook:unregister_listen_addr(Handle, ListenAddr),
?assertAsync({ok, Peer} = libp2p_peerbook:get(Handle, PubKeyBin),
[] == libp2p_peer:listen_addrs(Peer)),
ok.
session_test(Config) ->
Handle = ?config(peerbook, Config),
PubKeyBin = ?config(pubkey_bin, Config),
confirm empty listen
{ok, ThisPeer} = libp2p_peerbook:get(Handle, PubKeyBin),
?assertEqual([], libp2p_peer:connected_peers(ThisPeer)),
libp2p_peerbook:register_session(Handle, PubKeyBin),
libp2p_peerbook:register_session(Handle, PubKeyBin),
?assertAsync({ok, Peer} = libp2p_peerbook:get(Handle, PubKeyBin),
[PubKeyBin] == libp2p_peer:connected_peers(Peer)),
libp2p_peerbook:unregister_session(Handle, PubKeyBin),
libp2p_peerbook:unregister_session(Handle, PubKeyBin),
?assertAsync({ok, Peer} = libp2p_peerbook:get(Handle, PubKeyBin),
[] == libp2p_peer:connected_peers(Peer)),
ok.
get_put_test(Config) ->
Handle = ?config(peerbook, Config),
PubKeyBin = ?config(pubkey_bin, Config),
{ok, ThisPeer} = libp2p_peerbook:get(Handle, PubKeyBin),
?assertEqual(PubKeyBin, libp2p_peer:pubkey_bin(ThisPeer)),
{ok, NewPeer} = mk_peer(#{}),
ok = libp2p_peerbook:put(Handle, NewPeer),
Check is_key for self adnd new peer
?assert(libp2p_peerbook:is_key(Handle, PubKeyBin)),
?assert(libp2p_peerbook:is_key(Handle, libp2p_peer:pubkey_bin(NewPeer))),
?assertNot(libp2p_peerbook:is_key(Handle, <<>>)),
?assertEqual(2, length(libp2p_peerbook:keys(Handle))),
?assertEqual(2, length(libp2p_peerbook:values(Handle))),
?assertMatch({error, _}, libp2p_peerbook:remove(Handle, PubKeyBin)),
?assertEqual(ok, libp2p_peerbook:remove(Handle, libp2p_peer:pubkey_bin(NewPeer))),
?assertNot(libp2p_peerbook:is_key(Handle, libp2p_peer:pubkey_bin(NewPeer))),
?assertEqual(1, length(libp2p_peerbook:keys(Handle))),
ok.
blacklist_test(Config) ->
Handle = ?config(peerbook, Config),
BlackListAddr = "/ip4/9.9.9.9/tcp/4321",
ListenAddrs = [BlackListAddr, "/ip4/8.8.8.8/tcp/1234"],
{ok, NewPeer} = mk_peer(#{listen_addrs => ListenAddrs}),
ok = libp2p_peerbook:put(Handle, NewPeer),
libp2p_peerbook:blacklist_listen_addr(Handle, libp2p_peer:pubkey_bin(NewPeer), BlackListAddr),
?assertAsync({ok, Peer} = libp2p_peerbook:get(Handle, libp2p_peer:pubkey_bin(NewPeer)),
not lists:member(BlackListAddr, libp2p_peer:cleared_listen_addrs(Peer))),
?assertMatch({error, not_found}, libp2p_peerbook:blacklist_listen_addr(Handle, <<>>, BlackListAddr)),
ok.
heartbeat_test(Config) ->
Handle = ?config(peerbook, Config),
PubKeyBin = ?config(pubkey_bin, Config),
libp2p_peerbook:join_notify(Handle, self()),
libp2p_peerbook:join_notify(Handle, self()),
receive
{changed_peers, {{add, Add}, {remove, _}}} ->
?assert(maps:is_key(PubKeyBin, Add))
after 1000 ->
ct:fail(timeout_heartbeat)
end,
ok.
notify_test(Config) ->
Handle = ?config(peerbook, Config),
PubKeyBin = ?config(pubkey_bin, Config),
Add two peers
{ok, Peer1} = mk_peer(#{}),
{ok, Peer2} = mk_peer(#{}),
ok = libp2p_peerbook:put(Handle, Peer1),
ok = libp2p_peerbook:put(Handle, Peer2),
libp2p_peerbook:join_notify(Handle, self()),
libp2p_peerbook:set_nat_type(Handle, static),
And remove one of the two peers
Peer2PubKeyBin = libp2p_peer:pubkey_bin(Peer2),
libp2p_peerbook:remove(Handle, Peer2PubKeyBin),
receive
{changed_peers, {{add, Add}, {remove, Remove}}} ->
We should see the self peer and peer1 added and peer 2
?assert(lists:member(Peer2PubKeyBin, Remove)),
?assert(maps:is_key(PubKeyBin, Add)),
?assert(maps:is_key(libp2p_peer:pubkey_bin(Peer1), Add))
after 1000 ->
ct:fail(timeout_notify)
end,
libp2p_peerbook:leave_notify(Handle, self()),
ok.
stale_test(Config) ->
Handle = ?config(peerbook, Config),
StaleTime = ?config(stale_time, Config),
?assertEqual(StaleTime, libp2p_peerbook:stale_time(Handle)),
{ok, NewPeer} = mk_peer(#{}),
ok = libp2p_peerbook:put(Handle, NewPeer),
?assert(libp2p_peerbook:is_key(Handle, libp2p_peer:pubkey_bin(NewPeer))),
?assertAsync(Result = libp2p_peerbook:get(Handle, libp2p_peer:pubkey_bin(NewPeer)),
Result == {error, not_found}),
ok.
signed_metadata_test(Config) ->
Handle = ?config(peerbook, Config),
PubKeyBin = ?config(pubkey_bin, Config),
Tab = ?config(tab, Config),
SetMetaDataFun = fun(F) -> ets:insert(Tab, {metadata_fun, F}) end,
SetCountedMetaDataFun = fun(K, F) ->
SetMetaDataFun(fun() ->
ets:update_counter(Tab, K, 1, {K, 0}),
F()
end)
end,
SetMetaDataFun(fun() -> #{<<"hello">> => <<"world">>} end),
?assertAsync({ok, Peer} = libp2p_peerbook:get(Handle, PubKeyBin),
#{ <<"hello">> => <<"world">> } == libp2p_peer:signed_metadata(Peer)),
Let the metedata crash a number of times
SetCountedMetaDataFun(crash_count,
fun() -> exit(fail_metadata) end),
?assertAsyncTimes(Tab, crash_count, 20),
SetCountedMetaDataFun(sleep_count,
fun() ->
timer:sleep(300),
#{}
end),
?assertAsyncTimes(Tab, sleep_count, 3),
ok.
Utilities
mk_peer(MapOveride) ->
#{public := PubKey, secret := PrivKey} = libp2p_crypto:generate_keys(ecc_compact),
SigFun = libp2p_crypto:mk_sig_fun(PrivKey),
mk_peer(MapOveride, libp2p_crypto:pubkey_to_bin(PubKey), SigFun).
mk_peer(MapOverride, PubKeyBin, SigFun) ->
PeerMap = maps:merge(#{pubkey_bin => PubKeyBin,
listen_addrs => ["/ip4/8.8.8.8/tcp/1234"],
nat_type => static
}, MapOverride),
libp2p_peer:from_map(PeerMap, SigFun).
|
b606aa3f09052e4dc921c47ee3ec47450f2b5ed321d236ccd8d451fcd476bfcb
|
mvoidex/hsdev
|
Compat.hs
|
# LANGUAGE CPP #
module HsDev.Project.Compat (
showVer, componentName, testSuiteEnabled,
flattenCondTree,
parsePackageDesc
) where
import Data.Maybe (maybeToList)
import Data.Text (Text, pack)
import qualified Distribution.PackageDescription as PD
import Distribution.Version (Version)
import Distribution.Text (display)
#if MIN_VERSION_Cabal(2,2,0)
import Distribution.PackageDescription.Parsec
import qualified Data.ByteString.Char8 as C8 (pack)
import GHC.Exts (toList)
#endif
#if MIN_VERSION_Cabal(3,0,0)
import Distribution.Parsec (showPError)
#elif MIN_VERSION_Cabal(2,2,0)
import Distribution.Parsec.Common (showPError)
#else
import Distribution.PackageDescription.Parse
#endif
#if MIN_VERSION_Cabal(2,0,0)
import Distribution.Types.CondTree
#else
import Distribution.PackageDescription (CondTree(..))
#endif
#if MIN_VERSION_Cabal(2,0,0)
import Distribution.Types.UnqualComponentName
#else
import Data.Version (showVersion)
#endif
showVer :: Version -> String
#if MIN_VERSION_Cabal(2,0,0)
showVer = display
#else
showVer = showVersion
#endif
#if MIN_VERSION_Cabal(2,0,0)
componentName :: UnqualComponentName -> Text
componentName = pack . unUnqualComponentName
#else
componentName :: String -> Text
componentName = pack
#endif
testSuiteEnabled :: PD.TestSuite -> Bool
#if MIN_VERSION_Cabal(2,0,0)
testSuiteEnabled _ = True
#else
testSuiteEnabled = PD.testEnabled
#endif
flattenCondTree :: Monoid a => (c -> a -> a) -> CondTree v c a -> a
flattenCondTree f (PD.CondNode x cs cmps) = f cs x `mappend` mconcat (concatMap flattenBranch cmps) where
#if MIN_VERSION_Cabal(2,0,0)
flattenBranch (CondBranch _ t mb) = go t mb
#else
flattenBranch (_, t, mb) = go t mb
#endif
go t mb = flattenCondTree f t : map (flattenCondTree f) (maybeToList mb)
parsePackageDesc :: String -> Either String PD.GenericPackageDescription
#if MIN_VERSION_Cabal(2,2,0)
parsePackageDesc s = case snd . runParseResult . parseGenericPackageDescription . C8.pack $ s of
Left (_, errs) -> Left $ unlines $ map (showPError "cabal") $ toList errs
Right r -> Right r
#elif MIN_VERSION_Cabal(2,0,0)
parsePackageDesc s = case parseGenericPackageDescription s of
ParseOk _ r -> Right r
ParseFailed e -> Left $ show e
#else
parsePackageDesc s = case parsePackageDescription s of
ParseOk _ r -> Right r
ParseFailed e -> Left $ show e
#endif
| null |
https://raw.githubusercontent.com/mvoidex/hsdev/016646080a6859e4d9b4a1935fc1d732e388db1a/src/HsDev/Project/Compat.hs
|
haskell
|
# LANGUAGE CPP #
module HsDev.Project.Compat (
showVer, componentName, testSuiteEnabled,
flattenCondTree,
parsePackageDesc
) where
import Data.Maybe (maybeToList)
import Data.Text (Text, pack)
import qualified Distribution.PackageDescription as PD
import Distribution.Version (Version)
import Distribution.Text (display)
#if MIN_VERSION_Cabal(2,2,0)
import Distribution.PackageDescription.Parsec
import qualified Data.ByteString.Char8 as C8 (pack)
import GHC.Exts (toList)
#endif
#if MIN_VERSION_Cabal(3,0,0)
import Distribution.Parsec (showPError)
#elif MIN_VERSION_Cabal(2,2,0)
import Distribution.Parsec.Common (showPError)
#else
import Distribution.PackageDescription.Parse
#endif
#if MIN_VERSION_Cabal(2,0,0)
import Distribution.Types.CondTree
#else
import Distribution.PackageDescription (CondTree(..))
#endif
#if MIN_VERSION_Cabal(2,0,0)
import Distribution.Types.UnqualComponentName
#else
import Data.Version (showVersion)
#endif
showVer :: Version -> String
#if MIN_VERSION_Cabal(2,0,0)
showVer = display
#else
showVer = showVersion
#endif
#if MIN_VERSION_Cabal(2,0,0)
componentName :: UnqualComponentName -> Text
componentName = pack . unUnqualComponentName
#else
componentName :: String -> Text
componentName = pack
#endif
testSuiteEnabled :: PD.TestSuite -> Bool
#if MIN_VERSION_Cabal(2,0,0)
testSuiteEnabled _ = True
#else
testSuiteEnabled = PD.testEnabled
#endif
flattenCondTree :: Monoid a => (c -> a -> a) -> CondTree v c a -> a
flattenCondTree f (PD.CondNode x cs cmps) = f cs x `mappend` mconcat (concatMap flattenBranch cmps) where
#if MIN_VERSION_Cabal(2,0,0)
flattenBranch (CondBranch _ t mb) = go t mb
#else
flattenBranch (_, t, mb) = go t mb
#endif
go t mb = flattenCondTree f t : map (flattenCondTree f) (maybeToList mb)
parsePackageDesc :: String -> Either String PD.GenericPackageDescription
#if MIN_VERSION_Cabal(2,2,0)
parsePackageDesc s = case snd . runParseResult . parseGenericPackageDescription . C8.pack $ s of
Left (_, errs) -> Left $ unlines $ map (showPError "cabal") $ toList errs
Right r -> Right r
#elif MIN_VERSION_Cabal(2,0,0)
parsePackageDesc s = case parseGenericPackageDescription s of
ParseOk _ r -> Right r
ParseFailed e -> Left $ show e
#else
parsePackageDesc s = case parsePackageDescription s of
ParseOk _ r -> Right r
ParseFailed e -> Left $ show e
#endif
|
|
9a0aa30c56e31cbd27d55f9647651871c02e2ebe707813dd4660586b7e4041ec
|
tenpureto/tenpureto
|
MergeOptimizer.hs
|
# LANGUAGE DeriveFunctor #
module Tenpureto.MergeOptimizer
( MergedBranchInformation(..)
, MergedBranchDescriptor(..)
, MergeBranchesResult(..)
, descriptorToTemplateYaml
, mergeBranchesGraph
, mergeGraph
, propagateBranchesGraph
) where
import Control.Monad
import Data.Maybe
import Data.Semigroup.Foldable
import qualified Data.Set as Set
import Data.Set ( Set )
import Data.Text ( Text )
import Tenpureto.Graph
import Tenpureto.OrderedMap ( OrderedMap )
import qualified Tenpureto.OrderedMap as OrderedMap
import Tenpureto.TemplateLoader ( TemplateBranchInformation(..)
, TemplateYaml(..)
, TemplateYamlFeature
, branchVariables
, isFeatureBranch
, isHiddenBranch
)
data MergedBranchInformation a = MergedBranchInformation
{ mergedBranchMeta :: a
, mergedBranchDescriptor :: MergedBranchDescriptor
}
deriving (Show, Eq, Ord, Functor)
data MergedBranchDescriptor = MergedBranchDescriptor
{ mergedBranchName :: Text
, mergedVariables :: OrderedMap Text Text
, mergedExcludes :: Set Text
, mergedConflicts :: Set Text
, mergedFeatures :: Set TemplateYamlFeature
}
deriving (Show, Eq, Ord)
data MergeBranchesResult a = MergeBranchesResult
{ mergeBranchesResultMeta :: a
, mergeBranchesResultTemplateYaml :: TemplateYaml
}
deriving (Show, Eq)
descriptorToTemplateYaml :: MergedBranchDescriptor -> TemplateYaml
descriptorToTemplateYaml d = TemplateYaml { yamlVariables = mergedVariables d
, yamlFeatures = mergedFeatures d
, yamlExcludes = mergedExcludes d
, yamlConflicts = mergedConflicts d
}
mergedBranchInformationToResult
:: MergedBranchInformation a -> MergeBranchesResult a
mergedBranchInformationToResult mbi = MergeBranchesResult
{ mergeBranchesResultMeta = mergedBranchMeta mbi
, mergeBranchesResultTemplateYaml = descriptorToTemplateYaml mbd
}
where mbd = mergedBranchDescriptor mbi
templateBranchInformationData
:: (TemplateBranchInformation -> a)
-> TemplateBranchInformation
-> MergedBranchInformation a
templateBranchInformationData extract bi = MergedBranchInformation
{ mergedBranchMeta = extract bi
, mergedBranchDescriptor = MergedBranchDescriptor
{ mergedBranchName = branchName bi
, mergedVariables = branchVariables bi
, mergedExcludes = (yamlExcludes . templateYaml) bi
, mergedConflicts = (yamlConflicts . templateYaml) bi
, mergedFeatures = (yamlFeatures . templateYaml) bi
}
}
mergeBranchesGraph
:: (Ord a, Monad m)
=> (TemplateBranchInformation -> a)
-> (a -> a -> MergedBranchDescriptor -> m a)
-> Graph TemplateBranchInformation
-> Set TemplateBranchInformation
-> m (Maybe (MergeBranchesResult a))
mergeBranchesGraph extract mergeCommits graph selectedBranches =
fmap (fmap mergedBranchInformationToResult)
$ mergeGraph mergeCommits
$ mapVertices (templateBranchInformationData extract)
$ graphSubset (vertexDecision selectedBranches) graph
propagateBranchesGraph
:: (Ord a, Monoid b, Monad m)
=> (TemplateBranchInformation -> a)
-> (MergedBranchInformation a -> a -> m (a, b))
-> (MergedBranchInformation a -> m b)
-> Graph TemplateBranchInformation
-> Set TemplateBranchInformation
-> m b
propagateBranchesGraph extract propagateOne propagateMerge graph selectedBranches
= propagateGraph propagateOne' propagateMerge'
$ mapVertices (templateBranchInformationData extract') graph
where
extract' bi = (extract bi, branchName bi)
branchNames = Set.map branchName selectedBranches
name = mergedBranchName . mergedBranchDescriptor
propagateOne' mi (a, aname)
| (name mi `Set.member` branchNames) || (aname `Set.member` branchNames) = do
(a', b) <- propagateOne (fmap fst mi) a
return ((a', name mi), b)
| otherwise = return (mergedBranchMeta mi, mempty)
propagateMerge' mi = propagateMerge (fmap fst mi)
vertexDecision
:: Set TemplateBranchInformation
-> TemplateBranchInformation
-> GraphSubsetDecision
vertexDecision selectedBranches v | v `Set.member` selectedBranches = MustKeep
| isHiddenBranch v = PreferDrop
| isFeatureBranch v = MustDrop
| otherwise = PreferKeep
mergeGraph
:: (Ord a, Monad m)
=> (a -> a -> MergedBranchDescriptor -> m a)
-> Graph (MergedBranchInformation a)
-> m (Maybe (MergedBranchInformation a))
mergeGraph mergeCommits = foldTopologically vcombine hcombine
where
hcombineD d1 d2 = MergedBranchDescriptor
{ mergedBranchName = mergedBranchName d1 <> "+" <> mergedBranchName d2
, mergedVariables = mergedVariables d1
`OrderedMap.union` mergedVariables d2
, mergedExcludes = mergedExcludes d1 <> mergedExcludes d2
, mergedConflicts = mergedConflicts d1 <> mergedConflicts d2
, mergedFeatures = mergedFeatures d1 <> mergedFeatures d2
}
combine combineD b1 b2 =
let d = combineD (mergedBranchDescriptor b1)
(mergedBranchDescriptor b2)
in do
c <- mergeCommits (mergedBranchMeta b1) (mergedBranchMeta b2) d
return $ MergedBranchInformation { mergedBranchMeta = c
, mergedBranchDescriptor = d
}
vcombine v _ = return v
hcombine = foldlM1 (combine hcombineD)
propagateGraph
:: (Ord a, Monoid b, Monad m)
=> (MergedBranchInformation a -> a -> m (a, b))
-> (MergedBranchInformation a -> m b)
-> Graph (MergedBranchInformation a)
-> m b
propagateGraph propagateOne propagateMerge graph =
fromMaybe mempty <$> foldTopologically vcombine hcombine graph
where
vcombine v ps = do
(combined, acc) <- foldM vcombineOne (v, mempty) ps
acc' <- propagateMerge combined
return (combined, acc' <> acc)
vcombineOne (v, vacc) (p, pacc) =
let md = vcombineD (mergedBranchDescriptor v)
(mergedBranchDescriptor p)
in do
(v', acc') <- propagateOne
(MergedBranchInformation (mergedBranchMeta v) md)
(mergedBranchMeta p)
return (MergedBranchInformation v' md, acc' <> vacc <> pacc)
hcombine = return . foldMap snd
vcombineD
:: MergedBranchDescriptor
-> MergedBranchDescriptor
-> MergedBranchDescriptor
vcombineD d1 d2 = MergedBranchDescriptor
{ mergedBranchName = mergedBranchName d1
, mergedVariables = mergedVariables d1 `OrderedMap.union` mergedVariables d2
, mergedExcludes = mergedExcludes d1 <> mergedExcludes d2
, mergedConflicts = mergedConflicts d1
, mergedFeatures = mergedFeatures d1 <> mergedFeatures d2
}
| null |
https://raw.githubusercontent.com/tenpureto/tenpureto/886df860200e1a6f44ce07c24a5e7597009f71ef/src/Tenpureto/MergeOptimizer.hs
|
haskell
|
# LANGUAGE DeriveFunctor #
module Tenpureto.MergeOptimizer
( MergedBranchInformation(..)
, MergedBranchDescriptor(..)
, MergeBranchesResult(..)
, descriptorToTemplateYaml
, mergeBranchesGraph
, mergeGraph
, propagateBranchesGraph
) where
import Control.Monad
import Data.Maybe
import Data.Semigroup.Foldable
import qualified Data.Set as Set
import Data.Set ( Set )
import Data.Text ( Text )
import Tenpureto.Graph
import Tenpureto.OrderedMap ( OrderedMap )
import qualified Tenpureto.OrderedMap as OrderedMap
import Tenpureto.TemplateLoader ( TemplateBranchInformation(..)
, TemplateYaml(..)
, TemplateYamlFeature
, branchVariables
, isFeatureBranch
, isHiddenBranch
)
data MergedBranchInformation a = MergedBranchInformation
{ mergedBranchMeta :: a
, mergedBranchDescriptor :: MergedBranchDescriptor
}
deriving (Show, Eq, Ord, Functor)
data MergedBranchDescriptor = MergedBranchDescriptor
{ mergedBranchName :: Text
, mergedVariables :: OrderedMap Text Text
, mergedExcludes :: Set Text
, mergedConflicts :: Set Text
, mergedFeatures :: Set TemplateYamlFeature
}
deriving (Show, Eq, Ord)
data MergeBranchesResult a = MergeBranchesResult
{ mergeBranchesResultMeta :: a
, mergeBranchesResultTemplateYaml :: TemplateYaml
}
deriving (Show, Eq)
descriptorToTemplateYaml :: MergedBranchDescriptor -> TemplateYaml
descriptorToTemplateYaml d = TemplateYaml { yamlVariables = mergedVariables d
, yamlFeatures = mergedFeatures d
, yamlExcludes = mergedExcludes d
, yamlConflicts = mergedConflicts d
}
mergedBranchInformationToResult
:: MergedBranchInformation a -> MergeBranchesResult a
mergedBranchInformationToResult mbi = MergeBranchesResult
{ mergeBranchesResultMeta = mergedBranchMeta mbi
, mergeBranchesResultTemplateYaml = descriptorToTemplateYaml mbd
}
where mbd = mergedBranchDescriptor mbi
templateBranchInformationData
:: (TemplateBranchInformation -> a)
-> TemplateBranchInformation
-> MergedBranchInformation a
templateBranchInformationData extract bi = MergedBranchInformation
{ mergedBranchMeta = extract bi
, mergedBranchDescriptor = MergedBranchDescriptor
{ mergedBranchName = branchName bi
, mergedVariables = branchVariables bi
, mergedExcludes = (yamlExcludes . templateYaml) bi
, mergedConflicts = (yamlConflicts . templateYaml) bi
, mergedFeatures = (yamlFeatures . templateYaml) bi
}
}
mergeBranchesGraph
:: (Ord a, Monad m)
=> (TemplateBranchInformation -> a)
-> (a -> a -> MergedBranchDescriptor -> m a)
-> Graph TemplateBranchInformation
-> Set TemplateBranchInformation
-> m (Maybe (MergeBranchesResult a))
mergeBranchesGraph extract mergeCommits graph selectedBranches =
fmap (fmap mergedBranchInformationToResult)
$ mergeGraph mergeCommits
$ mapVertices (templateBranchInformationData extract)
$ graphSubset (vertexDecision selectedBranches) graph
propagateBranchesGraph
:: (Ord a, Monoid b, Monad m)
=> (TemplateBranchInformation -> a)
-> (MergedBranchInformation a -> a -> m (a, b))
-> (MergedBranchInformation a -> m b)
-> Graph TemplateBranchInformation
-> Set TemplateBranchInformation
-> m b
propagateBranchesGraph extract propagateOne propagateMerge graph selectedBranches
= propagateGraph propagateOne' propagateMerge'
$ mapVertices (templateBranchInformationData extract') graph
where
extract' bi = (extract bi, branchName bi)
branchNames = Set.map branchName selectedBranches
name = mergedBranchName . mergedBranchDescriptor
propagateOne' mi (a, aname)
| (name mi `Set.member` branchNames) || (aname `Set.member` branchNames) = do
(a', b) <- propagateOne (fmap fst mi) a
return ((a', name mi), b)
| otherwise = return (mergedBranchMeta mi, mempty)
propagateMerge' mi = propagateMerge (fmap fst mi)
vertexDecision
:: Set TemplateBranchInformation
-> TemplateBranchInformation
-> GraphSubsetDecision
vertexDecision selectedBranches v | v `Set.member` selectedBranches = MustKeep
| isHiddenBranch v = PreferDrop
| isFeatureBranch v = MustDrop
| otherwise = PreferKeep
mergeGraph
:: (Ord a, Monad m)
=> (a -> a -> MergedBranchDescriptor -> m a)
-> Graph (MergedBranchInformation a)
-> m (Maybe (MergedBranchInformation a))
mergeGraph mergeCommits = foldTopologically vcombine hcombine
where
hcombineD d1 d2 = MergedBranchDescriptor
{ mergedBranchName = mergedBranchName d1 <> "+" <> mergedBranchName d2
, mergedVariables = mergedVariables d1
`OrderedMap.union` mergedVariables d2
, mergedExcludes = mergedExcludes d1 <> mergedExcludes d2
, mergedConflicts = mergedConflicts d1 <> mergedConflicts d2
, mergedFeatures = mergedFeatures d1 <> mergedFeatures d2
}
combine combineD b1 b2 =
let d = combineD (mergedBranchDescriptor b1)
(mergedBranchDescriptor b2)
in do
c <- mergeCommits (mergedBranchMeta b1) (mergedBranchMeta b2) d
return $ MergedBranchInformation { mergedBranchMeta = c
, mergedBranchDescriptor = d
}
vcombine v _ = return v
hcombine = foldlM1 (combine hcombineD)
propagateGraph
:: (Ord a, Monoid b, Monad m)
=> (MergedBranchInformation a -> a -> m (a, b))
-> (MergedBranchInformation a -> m b)
-> Graph (MergedBranchInformation a)
-> m b
propagateGraph propagateOne propagateMerge graph =
fromMaybe mempty <$> foldTopologically vcombine hcombine graph
where
vcombine v ps = do
(combined, acc) <- foldM vcombineOne (v, mempty) ps
acc' <- propagateMerge combined
return (combined, acc' <> acc)
vcombineOne (v, vacc) (p, pacc) =
let md = vcombineD (mergedBranchDescriptor v)
(mergedBranchDescriptor p)
in do
(v', acc') <- propagateOne
(MergedBranchInformation (mergedBranchMeta v) md)
(mergedBranchMeta p)
return (MergedBranchInformation v' md, acc' <> vacc <> pacc)
hcombine = return . foldMap snd
vcombineD
:: MergedBranchDescriptor
-> MergedBranchDescriptor
-> MergedBranchDescriptor
vcombineD d1 d2 = MergedBranchDescriptor
{ mergedBranchName = mergedBranchName d1
, mergedVariables = mergedVariables d1 `OrderedMap.union` mergedVariables d2
, mergedExcludes = mergedExcludes d1 <> mergedExcludes d2
, mergedConflicts = mergedConflicts d1
, mergedFeatures = mergedFeatures d1 <> mergedFeatures d2
}
|
|
f193cb19301699f00cca63f91f3b02479cab11e56ad10a2c2ef7b3d7df2380e3
|
bobbae/gosling-emacs
|
mh-keymap.ml
|
; This file, when loaded, creates the mh keymap. Explicitly loaded from the
; root.
(progn loop
(save-excursion
(temp-use-buffer "+inbox")
(define-keymap "&mh-keymap")
(define-keymap "&mh-x-keymap")
(use-local-map "&mh-keymap")
(setq loop 0)
(while (<= loop 127)
(local-bind-to-key "&mh-summary" loop)
(setq loop (+ loop 1))
)
(setq loop '0')
(while (<= loop '9')
(local-bind-to-key "digit" loop)
(setq loop (+ loop 1))
)
(local-bind-to-key "&mh-help" "?")
(local-bind-to-key "&mh-Mark-file-deleted" "d")
(local-bind-to-key "&mh-Mark-file-deleted" "D")
(local-bind-to-key "&mh-Mark-file-deleted" "")
(local-bind-to-key "&mh-move" "^")
(local-bind-to-key "&mh-re-move" "!")
(local-bind-to-key "&mh-previous-line" "\")
(local-bind-to-key "&mh-previous-line" "\")
(local-bind-to-key "&mh-previous-line" "p")
(local-bind-to-key "&mh-previous-line" "P")
(local-bind-to-key "previous-line" "\^P")
(local-bind-to-key "next-line" "\^N")
(local-bind-to-key "&mh-next-line" "n")
(local-bind-to-key "&mh-next-line" "N")
(local-bind-to-key "&mh-next-line" "\")
(local-bind-to-key "redraw-display" "\")
(local-bind-to-key "search-forward" "\")
(local-bind-to-key "search-reverse" "\")
(local-bind-to-key "argument-prefix" "\^U")
(local-bind-to-key "previous-window" "\^Xp")
(local-bind-to-key "previous-window" "\^XP")
(local-bind-to-key "next-window" "\^Xn")
(local-bind-to-key "next-window" "\^XN")
(local-bind-to-key "delete-window" "\^Xd")
(local-bind-to-key "delete-window" "\^XD")
(local-bind-to-key "delete-other-windows" "\^X1")
(local-bind-to-key "visit-file" "\^X\^V")
(local-bind-to-key "next-page" "\^V")
(local-bind-to-key "redraw-display" "\")
(local-bind-to-key "previous-page" "\ev")
(local-bind-to-key "previous-page" "\eV")
(local-bind-to-key "scroll-one-line-up" "")
(local-bind-to-key "scroll-one-line-down" "\e")
(local-bind-to-key "beginning-of-file" "\e<")
(local-bind-to-key "end-of-file" "\e>")
(local-bind-to-key "return-to-monitor" "\")
(local-bind-to-key "&mh-unmark" "u")
(local-bind-to-key "&mh-unmark" "U")
(local-bind-to-key "exit-emacs" "\\")
(local-bind-to-key "&mh-show" "t")
(local-bind-to-key "&mh-show" "T")
(local-bind-to-key "&mh-list" "l")
(local-bind-to-key "&mh-list" "L")
(local-bind-to-key "&mh-edit" "e")
(local-bind-to-key "&mh-edit" "E")
(local-bind-to-key "&mh-repl" "R")
(local-bind-to-key "&mh-repl" "r")
(local-bind-to-key "&mh-send" "m")
(local-bind-to-key "&mh-send" "M")
(local-bind-to-key "&mh-forw" "f")
(local-bind-to-key "&mh-forw" "F")
(local-bind-to-key "&mh-remove" "\")
(local-bind-to-key "&mh-new-folder" "\\")
(local-bind-to-key "&mh-new-folder" "g")
(local-bind-to-key "&mh-new-folder" "G")
(local-bind-to-key "&mh-bboard" "b")
(local-bind-to-key "&mh-bboard" "B")
(local-bind-to-key "&mh-inc" "i")
(local-bind-to-key "&mh-inc" "I")
(local-bind-to-key "&mh-extras" "x")
(local-bind-to-key "&mh-extras" "X")
;; DG
(local-bind-to-key "novalue" "\^Q")
(local-bind-to-key "novalue" "\^S")
(temp-use-buffer "mh-xcommands")
(use-local-map "&mh-x-keymap")
(setq loop 0)
(while (<= loop 255)
(local-bind-to-key "&mh-beep" loop)
(setq loop (+ loop 1))
)
(local-bind-to-key "exit-emacs" "q")
(local-bind-to-key "next-page" "")
(local-bind-to-key "previous-page" "\ev")
(local-bind-to-key "previous-page" "\eV")
(local-bind-to-key "beginning-of-file" "\e<")
(local-bind-to-key "end-of-file" "\e>")
(local-bind-to-key "exit-emacs" "Q")
(local-bind-to-key "exit-emacs" "")
;; DG
(local-bind-to-key "novalue" "\^Q")
(local-bind-to-key "novalue" "\^S")
)
)
| null |
https://raw.githubusercontent.com/bobbae/gosling-emacs/8fdda532abbffb0c952251a0b5a4857e0f27495a/lib/maclib/stanford/mh-keymap.ml
|
ocaml
|
; This file, when loaded, creates the mh keymap. Explicitly loaded from the
; root.
(progn loop
(save-excursion
(temp-use-buffer "+inbox")
(define-keymap "&mh-keymap")
(define-keymap "&mh-x-keymap")
(use-local-map "&mh-keymap")
(setq loop 0)
(while (<= loop 127)
(local-bind-to-key "&mh-summary" loop)
(setq loop (+ loop 1))
)
(setq loop '0')
(while (<= loop '9')
(local-bind-to-key "digit" loop)
(setq loop (+ loop 1))
)
(local-bind-to-key "&mh-help" "?")
(local-bind-to-key "&mh-Mark-file-deleted" "d")
(local-bind-to-key "&mh-Mark-file-deleted" "D")
(local-bind-to-key "&mh-Mark-file-deleted" "")
(local-bind-to-key "&mh-move" "^")
(local-bind-to-key "&mh-re-move" "!")
(local-bind-to-key "&mh-previous-line" "\")
(local-bind-to-key "&mh-previous-line" "\")
(local-bind-to-key "&mh-previous-line" "p")
(local-bind-to-key "&mh-previous-line" "P")
(local-bind-to-key "previous-line" "\^P")
(local-bind-to-key "next-line" "\^N")
(local-bind-to-key "&mh-next-line" "n")
(local-bind-to-key "&mh-next-line" "N")
(local-bind-to-key "&mh-next-line" "\")
(local-bind-to-key "redraw-display" "\")
(local-bind-to-key "search-forward" "\")
(local-bind-to-key "search-reverse" "\")
(local-bind-to-key "argument-prefix" "\^U")
(local-bind-to-key "previous-window" "\^Xp")
(local-bind-to-key "previous-window" "\^XP")
(local-bind-to-key "next-window" "\^Xn")
(local-bind-to-key "next-window" "\^XN")
(local-bind-to-key "delete-window" "\^Xd")
(local-bind-to-key "delete-window" "\^XD")
(local-bind-to-key "delete-other-windows" "\^X1")
(local-bind-to-key "visit-file" "\^X\^V")
(local-bind-to-key "next-page" "\^V")
(local-bind-to-key "redraw-display" "\")
(local-bind-to-key "previous-page" "\ev")
(local-bind-to-key "previous-page" "\eV")
(local-bind-to-key "scroll-one-line-up" "")
(local-bind-to-key "scroll-one-line-down" "\e")
(local-bind-to-key "beginning-of-file" "\e<")
(local-bind-to-key "end-of-file" "\e>")
(local-bind-to-key "return-to-monitor" "\")
(local-bind-to-key "&mh-unmark" "u")
(local-bind-to-key "&mh-unmark" "U")
(local-bind-to-key "exit-emacs" "\\")
(local-bind-to-key "&mh-show" "t")
(local-bind-to-key "&mh-show" "T")
(local-bind-to-key "&mh-list" "l")
(local-bind-to-key "&mh-list" "L")
(local-bind-to-key "&mh-edit" "e")
(local-bind-to-key "&mh-edit" "E")
(local-bind-to-key "&mh-repl" "R")
(local-bind-to-key "&mh-repl" "r")
(local-bind-to-key "&mh-send" "m")
(local-bind-to-key "&mh-send" "M")
(local-bind-to-key "&mh-forw" "f")
(local-bind-to-key "&mh-forw" "F")
(local-bind-to-key "&mh-remove" "\")
(local-bind-to-key "&mh-new-folder" "\\")
(local-bind-to-key "&mh-new-folder" "g")
(local-bind-to-key "&mh-new-folder" "G")
(local-bind-to-key "&mh-bboard" "b")
(local-bind-to-key "&mh-bboard" "B")
(local-bind-to-key "&mh-inc" "i")
(local-bind-to-key "&mh-inc" "I")
(local-bind-to-key "&mh-extras" "x")
(local-bind-to-key "&mh-extras" "X")
;; DG
(local-bind-to-key "novalue" "\^Q")
(local-bind-to-key "novalue" "\^S")
(temp-use-buffer "mh-xcommands")
(use-local-map "&mh-x-keymap")
(setq loop 0)
(while (<= loop 255)
(local-bind-to-key "&mh-beep" loop)
(setq loop (+ loop 1))
)
(local-bind-to-key "exit-emacs" "q")
(local-bind-to-key "next-page" "")
(local-bind-to-key "previous-page" "\ev")
(local-bind-to-key "previous-page" "\eV")
(local-bind-to-key "beginning-of-file" "\e<")
(local-bind-to-key "end-of-file" "\e>")
(local-bind-to-key "exit-emacs" "Q")
(local-bind-to-key "exit-emacs" "")
;; DG
(local-bind-to-key "novalue" "\^Q")
(local-bind-to-key "novalue" "\^S")
)
)
|
|
cad488cc02ca1dcd1d8df5b2ea7227d4018125971222034c33015d997d2c4998
|
JHU-PL-Lab/jaylang
|
jay.ml
|
open Core
open Jay
let usage_msg = "jay -i <file>"
let source_file = ref ""
let anon_fun _ = failwith "No anonymous argument allowed!"
let run_program source =
let program = File_util.read_source source in
try Interpreter.eval program with _ -> failwith "TBI!"
(* | Interpreter.Terminate v -> Format.printf "%a" Jayil.Ast_pp.pp_value v
| ex -> raise ex *)
let () =
Arg.parse
[ ("-i", Arg.Set_string source_file, "Iutput source file") ]
anon_fun usage_msg ;
run_program !source_file
| null |
https://raw.githubusercontent.com/JHU-PL-Lab/jaylang/484b3876986a515fb57b11768a1b3b50418cde0c/src/bin/jay.ml
|
ocaml
|
| Interpreter.Terminate v -> Format.printf "%a" Jayil.Ast_pp.pp_value v
| ex -> raise ex
|
open Core
open Jay
let usage_msg = "jay -i <file>"
let source_file = ref ""
let anon_fun _ = failwith "No anonymous argument allowed!"
let run_program source =
let program = File_util.read_source source in
try Interpreter.eval program with _ -> failwith "TBI!"
let () =
Arg.parse
[ ("-i", Arg.Set_string source_file, "Iutput source file") ]
anon_fun usage_msg ;
run_program !source_file
|
d7728257b517a8a916b479c50ebec08072c8e315b6556b96a3c66592a222dc30
|
wmannis/cl-svg
|
format-xml.lisp
|
;;; -*- Mode: LISP; Syntax: Common-lisp; Package: cl-svg; Lowercase: Yes -*-
$ Id$
;;;
Copyright ( c ) 2008 . All rights reserved .
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
1 . Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
2 . Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ` ` AS IS '' AND
;;; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
;;; OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
;;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
;;; OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
;;; SUCH DAMAGE.
(in-package :cl-svg)
;;; I'm prepared to waste bytes of spaces for more or less readable XML.
;;; The output has some quirks, but it's better than nothing.
(defvar *indent-level* 0)
(defvar *indent-spacing* 2)
(defvar *float-format-precision* 2
"Constrains how many digits are printed after the decimal point in XML
attribute values.")
(defvar *precision-epsilon* 0.01)
(defun set-float-precision (p)
(when (> p 6)
(warn "Some browsers' SVG will fail on floats with more than six places."))
(setf *float-format-precision* p
*precision-epsilon* (/ 1.0 (expt 10 p))))
(defmacro with-indentation (&body body)
`(let ((*indent-level* (+ *indent-level* *indent-spacing*)))
,@body))
(defgeneric pp-xml-attr (stream keyword &optional colon-p at-p)
(:documentation "This turns a keyword slot of a p-list into something XML
will recognize, in particular making the case correct. It is intended
for ~/pp-xml-attr/ use in a FORMAT string."))
(defgeneric pp-xml-value (stream value &optional colon-p at-p)
(:documentation "This function exists entirely to restrain the floating
point representation in the SVG, which is bloated by pointless precision.
*FLOAT-FORMAT-PRECISION* (2, by default) determines how many digits are
printed after the decimal point."))
;;; Some of these keyword name transformations could be done
;;; programatically, but there are enough oddities that this wouldn't
;;; be at all reliable.
(defun xmlify-keyword (kw)
"Convert a ':view-box' lisp-style name into XMLish 'viewBox'."
(let ((translation
(case kw
(:view-box "viewBox")
(:xlink-href "xlink:href")
(:gradient-units "gradientUnits")
(:gradient-transform "gradientTransform")
(:spread-method "spreadMethod")
(:zoom-and-pan "zoomAndPan")
(:preserve-aspect-ratio "preserveAspectRatio")
(:pattern-units "patternUnits")
(:pattern-content-units "patternContentUnits")
(:pattern-transform "patternTransform")
(:marker-units "markerUnits")
(:marker-width "markerWidth")
(:marker-height "markerHeight")
(:mask-units "maskUnits")
(:mask-content-units "maskContentUnits")
((:ref-x :refx) "refX")
((:ref-y :refy) "refY")
(:text-length "textLength")
(:start-offset "startOffset")
(:glyph-ref "glyphRef")
(:length-adjust "lengthAdjust"))))
(if translation
translation
(string-downcase (symbol-name kw)))))
(defmethod pp-xml-value ((s stream) value &optional colon-p at-p)
(declare (ignore colon-p at-p))
(format s "~A" value))
(defmethod pp-xml-attr ((s stream) (kw symbol) &optional colon-p at-p)
(declare (ignore colon-p at-p))
(format s "~A" (xmlify-keyword kw)))
(defmethod pp-xml-attr ((s stream) (kw string) &optional colon-p at-p)
(declare (ignore colon-p at-p))
(format s "~A" kw))
;;; CLHS 12.1.3.2 - if a ratio can be simplified to an integer, it
;;; will be. This includes the tricky 0/n, which is just 0, so I don't
;;; have to watch for that here.
(defmethod pp-xml-value ((s stream) (value ratio) &optional colon-p at-p)
(declare (ignore colon-p at-p))
(format s "~v$" *float-format-precision* value))
Several browser SVG implementations refuse " 0.0 " as a legal
representation of zero , some accept it . The standard apparently
;;; admits several interpretations. This code filters out fpns
arbitrarily close to zero , and just dumps in a single integer 0 .
(defmethod pp-xml-value ((s stream) (value float) &optional colon-p at-p)
(declare (ignore colon-p at-p))
(if (< (- (abs value) *precision-epsilon*) 0.00000001)
(format s "0")
(format s "~v$" *float-format-precision* value)))
(defun element->xml (stream element properties)
FORMAT ~/ functions not in CL - USER have to state their package .
(format
stream
"~v,0T<~A ~@<~{~/cl-svg:pp-xml-attr/=\"~/cl-svg:pp-xml-value/\"~^ ~}~:@>/>~&"
*indent-level*
element
properties))
(defun string->xml (stream string)
(format stream "~v,0T~@<~A~:@>~&" *indent-level* string))
(defun begin-group->xml (stream element properties)
(format
stream
"~v,0T<~A~@<~{ ~/cl-svg:pp-xml-attr/=\"~/cl-svg:pp-xml-value/\"~}~:@>>~&"
*indent-level*
element
properties))
(defun end-group->xml (stream element)
(format stream "~v,0T</~A>~&" *indent-level* element))
(defmacro with-xml-group-element ((stream element properties) &body body)
(let ((s (gensym "stream"))
(e (gensym "element")))
`(let ((,s ,stream)
(,e ,element))
(begin-group->xml ,s ,e ,properties)
(with-indentation
,@body)
(end-group->xml ,s ,e))))
;;; Does this need some helpers to restrain precision that only
;;; bloats the SVG size?
(defun points (points)
(let ((*print-pretty* t))
(if (> (length points) 10)
(format nil "~&~8T~@<~:{ ~A,~A~}~:@>" points)
;; a small number of points doesn't need the full-on emprettying
(format nil "~:{ ~A,~A~}" points))))
format-xml.lisp ends here
| null |
https://raw.githubusercontent.com/wmannis/cl-svg/1e988ebd2d6e2ee7be4744208828ef1b59e5dcdc/format-xml.lisp
|
lisp
|
-*- Mode: LISP; Syntax: Common-lisp; Package: cl-svg; Lowercase: Yes -*-
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
I'm prepared to waste bytes of spaces for more or less readable XML.
The output has some quirks, but it's better than nothing.
Some of these keyword name transformations could be done
programatically, but there are enough oddities that this wouldn't
be at all reliable.
CLHS 12.1.3.2 - if a ratio can be simplified to an integer, it
will be. This includes the tricky 0/n, which is just 0, so I don't
have to watch for that here.
admits several interpretations. This code filters out fpns
Does this need some helpers to restrain precision that only
bloats the SVG size?
a small number of points doesn't need the full-on emprettying
|
$ Id$
Copyright ( c ) 2008 . All rights reserved .
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ` ` AS IS '' AND
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
(in-package :cl-svg)
(defvar *indent-level* 0)
(defvar *indent-spacing* 2)
(defvar *float-format-precision* 2
"Constrains how many digits are printed after the decimal point in XML
attribute values.")
(defvar *precision-epsilon* 0.01)
(defun set-float-precision (p)
(when (> p 6)
(warn "Some browsers' SVG will fail on floats with more than six places."))
(setf *float-format-precision* p
*precision-epsilon* (/ 1.0 (expt 10 p))))
(defmacro with-indentation (&body body)
`(let ((*indent-level* (+ *indent-level* *indent-spacing*)))
,@body))
(defgeneric pp-xml-attr (stream keyword &optional colon-p at-p)
(:documentation "This turns a keyword slot of a p-list into something XML
will recognize, in particular making the case correct. It is intended
for ~/pp-xml-attr/ use in a FORMAT string."))
(defgeneric pp-xml-value (stream value &optional colon-p at-p)
(:documentation "This function exists entirely to restrain the floating
point representation in the SVG, which is bloated by pointless precision.
*FLOAT-FORMAT-PRECISION* (2, by default) determines how many digits are
printed after the decimal point."))
(defun xmlify-keyword (kw)
"Convert a ':view-box' lisp-style name into XMLish 'viewBox'."
(let ((translation
(case kw
(:view-box "viewBox")
(:xlink-href "xlink:href")
(:gradient-units "gradientUnits")
(:gradient-transform "gradientTransform")
(:spread-method "spreadMethod")
(:zoom-and-pan "zoomAndPan")
(:preserve-aspect-ratio "preserveAspectRatio")
(:pattern-units "patternUnits")
(:pattern-content-units "patternContentUnits")
(:pattern-transform "patternTransform")
(:marker-units "markerUnits")
(:marker-width "markerWidth")
(:marker-height "markerHeight")
(:mask-units "maskUnits")
(:mask-content-units "maskContentUnits")
((:ref-x :refx) "refX")
((:ref-y :refy) "refY")
(:text-length "textLength")
(:start-offset "startOffset")
(:glyph-ref "glyphRef")
(:length-adjust "lengthAdjust"))))
(if translation
translation
(string-downcase (symbol-name kw)))))
(defmethod pp-xml-value ((s stream) value &optional colon-p at-p)
(declare (ignore colon-p at-p))
(format s "~A" value))
(defmethod pp-xml-attr ((s stream) (kw symbol) &optional colon-p at-p)
(declare (ignore colon-p at-p))
(format s "~A" (xmlify-keyword kw)))
(defmethod pp-xml-attr ((s stream) (kw string) &optional colon-p at-p)
(declare (ignore colon-p at-p))
(format s "~A" kw))
(defmethod pp-xml-value ((s stream) (value ratio) &optional colon-p at-p)
(declare (ignore colon-p at-p))
(format s "~v$" *float-format-precision* value))
Several browser SVG implementations refuse " 0.0 " as a legal
representation of zero , some accept it . The standard apparently
arbitrarily close to zero , and just dumps in a single integer 0 .
(defmethod pp-xml-value ((s stream) (value float) &optional colon-p at-p)
(declare (ignore colon-p at-p))
(if (< (- (abs value) *precision-epsilon*) 0.00000001)
(format s "0")
(format s "~v$" *float-format-precision* value)))
(defun element->xml (stream element properties)
FORMAT ~/ functions not in CL - USER have to state their package .
(format
stream
"~v,0T<~A ~@<~{~/cl-svg:pp-xml-attr/=\"~/cl-svg:pp-xml-value/\"~^ ~}~:@>/>~&"
*indent-level*
element
properties))
(defun string->xml (stream string)
(format stream "~v,0T~@<~A~:@>~&" *indent-level* string))
(defun begin-group->xml (stream element properties)
(format
stream
"~v,0T<~A~@<~{ ~/cl-svg:pp-xml-attr/=\"~/cl-svg:pp-xml-value/\"~}~:@>>~&"
*indent-level*
element
properties))
(defun end-group->xml (stream element)
(format stream "~v,0T</~A>~&" *indent-level* element))
(defmacro with-xml-group-element ((stream element properties) &body body)
(let ((s (gensym "stream"))
(e (gensym "element")))
`(let ((,s ,stream)
(,e ,element))
(begin-group->xml ,s ,e ,properties)
(with-indentation
,@body)
(end-group->xml ,s ,e))))
(defun points (points)
(let ((*print-pretty* t))
(if (> (length points) 10)
(format nil "~&~8T~@<~:{ ~A,~A~}~:@>" points)
(format nil "~:{ ~A,~A~}" points))))
format-xml.lisp ends here
|
d8c91b5ebcea1bbce6083d689668a7568c5add491a8064a5ff6694d8d32fed16
|
aliter/aliter
|
aliter.erl
|
-module(aliter).
-behaviour(application).
-include("include/records.hrl").
-export([
start/2,
shutdown/0,
stop/1,
path/1,
install/0,
uninstall/0,
reinstall/0]).
start(_Type, StartArgs) ->
aliter_sup:start_link(StartArgs).
shutdown() ->
application:stop(aliter).
stop(_State) ->
ok.
path(A) ->
"-pa " ++ A ++ "/ebin -pa " ++ A ++ "/scbin" ++
" -pa " ++ A ++ "/lib/erlang-redis/ebin" ++
" -pa " ++ A ++ "/lib/elixir/ebin -pa " ++ A ++ "/lib/elixir/exbin".
call_all(Fun) ->
{Login, Char, Zone} = config:load(),
{host, {LoginHost, LoginName}} = config:find(server.host, Login),
{aliter, LoginAliter} = config:find(server.aliter, Login),
case slave:start_link(LoginHost, LoginName, path(LoginAliter)) of
{ok, LoginNode} ->
LoginRes = rpc:block_call(LoginNode, login, Fun, []),
error_logger:info_report(
[login_install_report, {result, LoginRes}]
),
slave:stop(LoginNode);
{ error, LoginReason} ->
error_logger:warning_report(
[login_install_canceled, {reason, LoginReason}]
)
end,
lists:foreach(
fun({Node, Conf}) ->
{host, {Host, Name}} = config:find(server.host, Conf),
{aliter, Aliter} = config:find(server.aliter, Conf),
case slave:start_link(
Host, Name, path(Aliter)) of {ok, Node} ->
CharRes = rpc:block_call(Node, char, Fun, []),
error_logger:info_report(
[char_install_report, {name, Name}, {result, CharRes}]
),
slave:stop(Node);
{ error, CharReason} ->
error_logger:warning_report(
[char_install_canceled, {name, Name}, {reason, CharReason}]
)
end
end,
Char
),
lists:foreach(
fun({Node, Conf}) ->
{host, {Host, Name}} = config:find(server.host, Conf),
{aliter, Aliter} = config:find(server.aliter, Conf),
case slave:start_link(
Host, Name, path(Aliter)) of {ok, Node} ->
ZoneRes = rpc:block_call(Node, zone, Fun, []),
error_logger:info_report(
[zone_install_report, {name, Name}, {result, ZoneRes}]
),
slave:stop(Node);
{ error, ZoneReason} ->
error_logger:warning_report(
[zone_install_canceled, {name, Name}, {reason, ZoneReason}]
)
end
end,
Zone
).
install() ->
call_all(install).
uninstall() ->
call_all(uninstall).
reinstall() ->
uninstall(),
install().
| null |
https://raw.githubusercontent.com/aliter/aliter/03c7d395d5812887aecdca20b16369f8a8abd278/src/aliter.erl
|
erlang
|
-module(aliter).
-behaviour(application).
-include("include/records.hrl").
-export([
start/2,
shutdown/0,
stop/1,
path/1,
install/0,
uninstall/0,
reinstall/0]).
start(_Type, StartArgs) ->
aliter_sup:start_link(StartArgs).
shutdown() ->
application:stop(aliter).
stop(_State) ->
ok.
path(A) ->
"-pa " ++ A ++ "/ebin -pa " ++ A ++ "/scbin" ++
" -pa " ++ A ++ "/lib/erlang-redis/ebin" ++
" -pa " ++ A ++ "/lib/elixir/ebin -pa " ++ A ++ "/lib/elixir/exbin".
call_all(Fun) ->
{Login, Char, Zone} = config:load(),
{host, {LoginHost, LoginName}} = config:find(server.host, Login),
{aliter, LoginAliter} = config:find(server.aliter, Login),
case slave:start_link(LoginHost, LoginName, path(LoginAliter)) of
{ok, LoginNode} ->
LoginRes = rpc:block_call(LoginNode, login, Fun, []),
error_logger:info_report(
[login_install_report, {result, LoginRes}]
),
slave:stop(LoginNode);
{ error, LoginReason} ->
error_logger:warning_report(
[login_install_canceled, {reason, LoginReason}]
)
end,
lists:foreach(
fun({Node, Conf}) ->
{host, {Host, Name}} = config:find(server.host, Conf),
{aliter, Aliter} = config:find(server.aliter, Conf),
case slave:start_link(
Host, Name, path(Aliter)) of {ok, Node} ->
CharRes = rpc:block_call(Node, char, Fun, []),
error_logger:info_report(
[char_install_report, {name, Name}, {result, CharRes}]
),
slave:stop(Node);
{ error, CharReason} ->
error_logger:warning_report(
[char_install_canceled, {name, Name}, {reason, CharReason}]
)
end
end,
Char
),
lists:foreach(
fun({Node, Conf}) ->
{host, {Host, Name}} = config:find(server.host, Conf),
{aliter, Aliter} = config:find(server.aliter, Conf),
case slave:start_link(
Host, Name, path(Aliter)) of {ok, Node} ->
ZoneRes = rpc:block_call(Node, zone, Fun, []),
error_logger:info_report(
[zone_install_report, {name, Name}, {result, ZoneRes}]
),
slave:stop(Node);
{ error, ZoneReason} ->
error_logger:warning_report(
[zone_install_canceled, {name, Name}, {reason, ZoneReason}]
)
end
end,
Zone
).
install() ->
call_all(install).
uninstall() ->
call_all(uninstall).
reinstall() ->
uninstall(),
install().
|
|
9786db35d12540757ce6d1f29504ff752d9fc76f8a2d1ffa749ff64dbab594b3
|
mbj/stratosphere
|
Server.hs
|
module Stratosphere.Transfer.Server (
module Exports, Server(..), mkServer
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import {-# SOURCE #-} Stratosphere.Transfer.Server.EndpointDetailsProperty as Exports
import {-# SOURCE #-} Stratosphere.Transfer.Server.IdentityProviderDetailsProperty as Exports
import {-# SOURCE #-} Stratosphere.Transfer.Server.ProtocolProperty as Exports
import {-# SOURCE #-} Stratosphere.Transfer.Server.ProtocolDetailsProperty as Exports
import {-# SOURCE #-} Stratosphere.Transfer.Server.WorkflowDetailsProperty as Exports
import Stratosphere.ResourceProperties
import Stratosphere.Tag
import Stratosphere.Value
data Server
= Server {certificate :: (Prelude.Maybe (Value Prelude.Text)),
domain :: (Prelude.Maybe (Value Prelude.Text)),
endpointDetails :: (Prelude.Maybe EndpointDetailsProperty),
endpointType :: (Prelude.Maybe (Value Prelude.Text)),
identityProviderDetails :: (Prelude.Maybe IdentityProviderDetailsProperty),
identityProviderType :: (Prelude.Maybe (Value Prelude.Text)),
loggingRole :: (Prelude.Maybe (Value Prelude.Text)),
postAuthenticationLoginBanner :: (Prelude.Maybe (Value Prelude.Text)),
preAuthenticationLoginBanner :: (Prelude.Maybe (Value Prelude.Text)),
protocolDetails :: (Prelude.Maybe ProtocolDetailsProperty),
protocols :: (Prelude.Maybe [ProtocolProperty]),
securityPolicyName :: (Prelude.Maybe (Value Prelude.Text)),
tags :: (Prelude.Maybe [Tag]),
workflowDetails :: (Prelude.Maybe WorkflowDetailsProperty)}
mkServer :: Server
mkServer
= Server
{certificate = Prelude.Nothing, domain = Prelude.Nothing,
endpointDetails = Prelude.Nothing, endpointType = Prelude.Nothing,
identityProviderDetails = Prelude.Nothing,
identityProviderType = Prelude.Nothing,
loggingRole = Prelude.Nothing,
postAuthenticationLoginBanner = Prelude.Nothing,
preAuthenticationLoginBanner = Prelude.Nothing,
protocolDetails = Prelude.Nothing, protocols = Prelude.Nothing,
securityPolicyName = Prelude.Nothing, tags = Prelude.Nothing,
workflowDetails = Prelude.Nothing}
instance ToResourceProperties Server where
toResourceProperties Server {..}
= ResourceProperties
{awsType = "AWS::Transfer::Server", supportsTags = Prelude.True,
properties = Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "Certificate" Prelude.<$> certificate,
(JSON..=) "Domain" Prelude.<$> domain,
(JSON..=) "EndpointDetails" Prelude.<$> endpointDetails,
(JSON..=) "EndpointType" Prelude.<$> endpointType,
(JSON..=) "IdentityProviderDetails"
Prelude.<$> identityProviderDetails,
(JSON..=) "IdentityProviderType" Prelude.<$> identityProviderType,
(JSON..=) "LoggingRole" Prelude.<$> loggingRole,
(JSON..=) "PostAuthenticationLoginBanner"
Prelude.<$> postAuthenticationLoginBanner,
(JSON..=) "PreAuthenticationLoginBanner"
Prelude.<$> preAuthenticationLoginBanner,
(JSON..=) "ProtocolDetails" Prelude.<$> protocolDetails,
(JSON..=) "Protocols" Prelude.<$> protocols,
(JSON..=) "SecurityPolicyName" Prelude.<$> securityPolicyName,
(JSON..=) "Tags" Prelude.<$> tags,
(JSON..=) "WorkflowDetails" Prelude.<$> workflowDetails])}
instance JSON.ToJSON Server where
toJSON Server {..}
= JSON.object
(Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "Certificate" Prelude.<$> certificate,
(JSON..=) "Domain" Prelude.<$> domain,
(JSON..=) "EndpointDetails" Prelude.<$> endpointDetails,
(JSON..=) "EndpointType" Prelude.<$> endpointType,
(JSON..=) "IdentityProviderDetails"
Prelude.<$> identityProviderDetails,
(JSON..=) "IdentityProviderType" Prelude.<$> identityProviderType,
(JSON..=) "LoggingRole" Prelude.<$> loggingRole,
(JSON..=) "PostAuthenticationLoginBanner"
Prelude.<$> postAuthenticationLoginBanner,
(JSON..=) "PreAuthenticationLoginBanner"
Prelude.<$> preAuthenticationLoginBanner,
(JSON..=) "ProtocolDetails" Prelude.<$> protocolDetails,
(JSON..=) "Protocols" Prelude.<$> protocols,
(JSON..=) "SecurityPolicyName" Prelude.<$> securityPolicyName,
(JSON..=) "Tags" Prelude.<$> tags,
(JSON..=) "WorkflowDetails" Prelude.<$> workflowDetails]))
instance Property "Certificate" Server where
type PropertyType "Certificate" Server = Value Prelude.Text
set newValue Server {..}
= Server {certificate = Prelude.pure newValue, ..}
instance Property "Domain" Server where
type PropertyType "Domain" Server = Value Prelude.Text
set newValue Server {..}
= Server {domain = Prelude.pure newValue, ..}
instance Property "EndpointDetails" Server where
type PropertyType "EndpointDetails" Server = EndpointDetailsProperty
set newValue Server {..}
= Server {endpointDetails = Prelude.pure newValue, ..}
instance Property "EndpointType" Server where
type PropertyType "EndpointType" Server = Value Prelude.Text
set newValue Server {..}
= Server {endpointType = Prelude.pure newValue, ..}
instance Property "IdentityProviderDetails" Server where
type PropertyType "IdentityProviderDetails" Server = IdentityProviderDetailsProperty
set newValue Server {..}
= Server {identityProviderDetails = Prelude.pure newValue, ..}
instance Property "IdentityProviderType" Server where
type PropertyType "IdentityProviderType" Server = Value Prelude.Text
set newValue Server {..}
= Server {identityProviderType = Prelude.pure newValue, ..}
instance Property "LoggingRole" Server where
type PropertyType "LoggingRole" Server = Value Prelude.Text
set newValue Server {..}
= Server {loggingRole = Prelude.pure newValue, ..}
instance Property "PostAuthenticationLoginBanner" Server where
type PropertyType "PostAuthenticationLoginBanner" Server = Value Prelude.Text
set newValue Server {..}
= Server
{postAuthenticationLoginBanner = Prelude.pure newValue, ..}
instance Property "PreAuthenticationLoginBanner" Server where
type PropertyType "PreAuthenticationLoginBanner" Server = Value Prelude.Text
set newValue Server {..}
= Server {preAuthenticationLoginBanner = Prelude.pure newValue, ..}
instance Property "ProtocolDetails" Server where
type PropertyType "ProtocolDetails" Server = ProtocolDetailsProperty
set newValue Server {..}
= Server {protocolDetails = Prelude.pure newValue, ..}
instance Property "Protocols" Server where
type PropertyType "Protocols" Server = [ProtocolProperty]
set newValue Server {..}
= Server {protocols = Prelude.pure newValue, ..}
instance Property "SecurityPolicyName" Server where
type PropertyType "SecurityPolicyName" Server = Value Prelude.Text
set newValue Server {..}
= Server {securityPolicyName = Prelude.pure newValue, ..}
instance Property "Tags" Server where
type PropertyType "Tags" Server = [Tag]
set newValue Server {..}
= Server {tags = Prelude.pure newValue, ..}
instance Property "WorkflowDetails" Server where
type PropertyType "WorkflowDetails" Server = WorkflowDetailsProperty
set newValue Server {..}
= Server {workflowDetails = Prelude.pure newValue, ..}
| null |
https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/transfer/gen/Stratosphere/Transfer/Server.hs
|
haskell
|
# SOURCE #
# SOURCE #
# SOURCE #
# SOURCE #
# SOURCE #
|
module Stratosphere.Transfer.Server (
module Exports, Server(..), mkServer
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Tag
import Stratosphere.Value
data Server
= Server {certificate :: (Prelude.Maybe (Value Prelude.Text)),
domain :: (Prelude.Maybe (Value Prelude.Text)),
endpointDetails :: (Prelude.Maybe EndpointDetailsProperty),
endpointType :: (Prelude.Maybe (Value Prelude.Text)),
identityProviderDetails :: (Prelude.Maybe IdentityProviderDetailsProperty),
identityProviderType :: (Prelude.Maybe (Value Prelude.Text)),
loggingRole :: (Prelude.Maybe (Value Prelude.Text)),
postAuthenticationLoginBanner :: (Prelude.Maybe (Value Prelude.Text)),
preAuthenticationLoginBanner :: (Prelude.Maybe (Value Prelude.Text)),
protocolDetails :: (Prelude.Maybe ProtocolDetailsProperty),
protocols :: (Prelude.Maybe [ProtocolProperty]),
securityPolicyName :: (Prelude.Maybe (Value Prelude.Text)),
tags :: (Prelude.Maybe [Tag]),
workflowDetails :: (Prelude.Maybe WorkflowDetailsProperty)}
mkServer :: Server
mkServer
= Server
{certificate = Prelude.Nothing, domain = Prelude.Nothing,
endpointDetails = Prelude.Nothing, endpointType = Prelude.Nothing,
identityProviderDetails = Prelude.Nothing,
identityProviderType = Prelude.Nothing,
loggingRole = Prelude.Nothing,
postAuthenticationLoginBanner = Prelude.Nothing,
preAuthenticationLoginBanner = Prelude.Nothing,
protocolDetails = Prelude.Nothing, protocols = Prelude.Nothing,
securityPolicyName = Prelude.Nothing, tags = Prelude.Nothing,
workflowDetails = Prelude.Nothing}
instance ToResourceProperties Server where
toResourceProperties Server {..}
= ResourceProperties
{awsType = "AWS::Transfer::Server", supportsTags = Prelude.True,
properties = Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "Certificate" Prelude.<$> certificate,
(JSON..=) "Domain" Prelude.<$> domain,
(JSON..=) "EndpointDetails" Prelude.<$> endpointDetails,
(JSON..=) "EndpointType" Prelude.<$> endpointType,
(JSON..=) "IdentityProviderDetails"
Prelude.<$> identityProviderDetails,
(JSON..=) "IdentityProviderType" Prelude.<$> identityProviderType,
(JSON..=) "LoggingRole" Prelude.<$> loggingRole,
(JSON..=) "PostAuthenticationLoginBanner"
Prelude.<$> postAuthenticationLoginBanner,
(JSON..=) "PreAuthenticationLoginBanner"
Prelude.<$> preAuthenticationLoginBanner,
(JSON..=) "ProtocolDetails" Prelude.<$> protocolDetails,
(JSON..=) "Protocols" Prelude.<$> protocols,
(JSON..=) "SecurityPolicyName" Prelude.<$> securityPolicyName,
(JSON..=) "Tags" Prelude.<$> tags,
(JSON..=) "WorkflowDetails" Prelude.<$> workflowDetails])}
instance JSON.ToJSON Server where
toJSON Server {..}
= JSON.object
(Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "Certificate" Prelude.<$> certificate,
(JSON..=) "Domain" Prelude.<$> domain,
(JSON..=) "EndpointDetails" Prelude.<$> endpointDetails,
(JSON..=) "EndpointType" Prelude.<$> endpointType,
(JSON..=) "IdentityProviderDetails"
Prelude.<$> identityProviderDetails,
(JSON..=) "IdentityProviderType" Prelude.<$> identityProviderType,
(JSON..=) "LoggingRole" Prelude.<$> loggingRole,
(JSON..=) "PostAuthenticationLoginBanner"
Prelude.<$> postAuthenticationLoginBanner,
(JSON..=) "PreAuthenticationLoginBanner"
Prelude.<$> preAuthenticationLoginBanner,
(JSON..=) "ProtocolDetails" Prelude.<$> protocolDetails,
(JSON..=) "Protocols" Prelude.<$> protocols,
(JSON..=) "SecurityPolicyName" Prelude.<$> securityPolicyName,
(JSON..=) "Tags" Prelude.<$> tags,
(JSON..=) "WorkflowDetails" Prelude.<$> workflowDetails]))
instance Property "Certificate" Server where
type PropertyType "Certificate" Server = Value Prelude.Text
set newValue Server {..}
= Server {certificate = Prelude.pure newValue, ..}
instance Property "Domain" Server where
type PropertyType "Domain" Server = Value Prelude.Text
set newValue Server {..}
= Server {domain = Prelude.pure newValue, ..}
instance Property "EndpointDetails" Server where
type PropertyType "EndpointDetails" Server = EndpointDetailsProperty
set newValue Server {..}
= Server {endpointDetails = Prelude.pure newValue, ..}
instance Property "EndpointType" Server where
type PropertyType "EndpointType" Server = Value Prelude.Text
set newValue Server {..}
= Server {endpointType = Prelude.pure newValue, ..}
instance Property "IdentityProviderDetails" Server where
type PropertyType "IdentityProviderDetails" Server = IdentityProviderDetailsProperty
set newValue Server {..}
= Server {identityProviderDetails = Prelude.pure newValue, ..}
instance Property "IdentityProviderType" Server where
type PropertyType "IdentityProviderType" Server = Value Prelude.Text
set newValue Server {..}
= Server {identityProviderType = Prelude.pure newValue, ..}
instance Property "LoggingRole" Server where
type PropertyType "LoggingRole" Server = Value Prelude.Text
set newValue Server {..}
= Server {loggingRole = Prelude.pure newValue, ..}
instance Property "PostAuthenticationLoginBanner" Server where
type PropertyType "PostAuthenticationLoginBanner" Server = Value Prelude.Text
set newValue Server {..}
= Server
{postAuthenticationLoginBanner = Prelude.pure newValue, ..}
instance Property "PreAuthenticationLoginBanner" Server where
type PropertyType "PreAuthenticationLoginBanner" Server = Value Prelude.Text
set newValue Server {..}
= Server {preAuthenticationLoginBanner = Prelude.pure newValue, ..}
instance Property "ProtocolDetails" Server where
type PropertyType "ProtocolDetails" Server = ProtocolDetailsProperty
set newValue Server {..}
= Server {protocolDetails = Prelude.pure newValue, ..}
instance Property "Protocols" Server where
type PropertyType "Protocols" Server = [ProtocolProperty]
set newValue Server {..}
= Server {protocols = Prelude.pure newValue, ..}
instance Property "SecurityPolicyName" Server where
type PropertyType "SecurityPolicyName" Server = Value Prelude.Text
set newValue Server {..}
= Server {securityPolicyName = Prelude.pure newValue, ..}
instance Property "Tags" Server where
type PropertyType "Tags" Server = [Tag]
set newValue Server {..}
= Server {tags = Prelude.pure newValue, ..}
instance Property "WorkflowDetails" Server where
type PropertyType "WorkflowDetails" Server = WorkflowDetailsProperty
set newValue Server {..}
= Server {workflowDetails = Prelude.pure newValue, ..}
|
3d45633cd07b28efb61cdb8c6d50e0f13c889f311e54df83b1e3b9080775d077
|
melisgl/higgsml
|
config.lisp
|
(in-package :higgs-boson)
(defun parse-config-line (string)
(let ((position (position #\= string)))
(assert position)
(cons (subseq string 0 position)
(let ((*read-eval* nil))
(read-from-string (subseq string (1+ position)))))))
(defun parse-config (stream)
(loop for line = (read-line stream nil nil)
while line
collect (parse-config-line line)))
(defun load-config ()
(with-open-file (stream (asdf:system-relative-pathname :rumcajsz "SETTINGS"))
(parse-config stream)))
(defparameter *config* (load-config))
(defun lookup-config (key)
(or (cdr (assoc key *config* :test #'string=))
(error "Unknown key in config: ~S" key)))
(defun lookup-config-path (key)
(asdf:system-relative-pathname :rumcajsz (lookup-config key)))
(defparameter *data-dir* (lookup-config-path "DATADIR"))
(defparameter *model-dir* (lookup-config-path "MODELDIR"))
(defparameter *submission-dir* (lookup-config-path "SUBMISSIONDIR"))
(defparameter *training-file* (merge-pathnames "training.csv" *data-dir*))
(defparameter *test-file* (merge-pathnames "test.csv" *data-dir*))
(defparameter *opendata-file* (merge-pathnames "opendata.csv" *data-dir*))
| null |
https://raw.githubusercontent.com/melisgl/higgsml/a49679354f1b1896ea6472a5f615e9bcdee65638/src/config.lisp
|
lisp
|
(in-package :higgs-boson)
(defun parse-config-line (string)
(let ((position (position #\= string)))
(assert position)
(cons (subseq string 0 position)
(let ((*read-eval* nil))
(read-from-string (subseq string (1+ position)))))))
(defun parse-config (stream)
(loop for line = (read-line stream nil nil)
while line
collect (parse-config-line line)))
(defun load-config ()
(with-open-file (stream (asdf:system-relative-pathname :rumcajsz "SETTINGS"))
(parse-config stream)))
(defparameter *config* (load-config))
(defun lookup-config (key)
(or (cdr (assoc key *config* :test #'string=))
(error "Unknown key in config: ~S" key)))
(defun lookup-config-path (key)
(asdf:system-relative-pathname :rumcajsz (lookup-config key)))
(defparameter *data-dir* (lookup-config-path "DATADIR"))
(defparameter *model-dir* (lookup-config-path "MODELDIR"))
(defparameter *submission-dir* (lookup-config-path "SUBMISSIONDIR"))
(defparameter *training-file* (merge-pathnames "training.csv" *data-dir*))
(defparameter *test-file* (merge-pathnames "test.csv" *data-dir*))
(defparameter *opendata-file* (merge-pathnames "opendata.csv" *data-dir*))
|
|
6a55bc2f4a8ef706a58afed217153f7b6e1f1754152f6b6651279db569eceaa9
|
cbaggers/varjo
|
type-spec.lisp
|
(in-package :varjo.internals)
(in-readtable :fn.reader)
;;------------------------------------------------------------
(defun register-type-name (name)
(assert (symbolp name))
(setf (gethash name *registered-types*) t))
(defun type-name-known (name)
(gethash name *registered-types*))
(defun vtype-existsp (type-name)
(let ((type-name (resolve-name-from-alternative type-name)))
(etypecase type-name
(symbol (type-name-known type-name))
(list (type-name-known (first type-name))))))
;;------------------------------------------------------------
| null |
https://raw.githubusercontent.com/cbaggers/varjo/9e77f30220053155d2ef8870ceba157f75e538d4/src/varjo.internals/types/type-spec.lisp
|
lisp
|
------------------------------------------------------------
------------------------------------------------------------
|
(in-package :varjo.internals)
(in-readtable :fn.reader)
(defun register-type-name (name)
(assert (symbolp name))
(setf (gethash name *registered-types*) t))
(defun type-name-known (name)
(gethash name *registered-types*))
(defun vtype-existsp (type-name)
(let ((type-name (resolve-name-from-alternative type-name)))
(etypecase type-name
(symbol (type-name-known type-name))
(list (type-name-known (first type-name))))))
|
41f5262a5a17bfd6a32a53ccbc5e0c82982c80fb4da23899ff10c81ba233081f
|
ideas-edu/ideas
|
Run.hs
|
-----------------------------------------------------------------------------
Copyright 2019 , Ideas project team . This file is distributed under the
terms of the Apache License 2.0 . For more information , see the files
" LICENSE.txt " and " NOTICE.txt " , which are included in the distribution .
-----------------------------------------------------------------------------
-- |
-- Maintainer :
-- Stability : provisional
Portability : portable ( depends on ghc )
--
-- Run a feedbackscript
--
-----------------------------------------------------------------------------
module Ideas.Service.FeedbackScript.Run
( Script
, Environment(..), newEnvironment
, feedbackDiagnosis, feedbackHint, feedbackHints
, ruleToString, feedbackIds, attributeIds, conditionIds
, eval
) where
import Data.List
import Data.Maybe
import Ideas.Common.Library hiding (ready, Environment)
import Ideas.Service.BasicServices
import Ideas.Service.Diagnose
import Ideas.Service.FeedbackScript.Syntax
import Ideas.Service.State
data Environment a = Env
{ oldReady :: Bool
, expected :: Maybe (Rule (Context a))
, recognized :: Maybe (Rule (Context a))
, motivation :: Maybe (Rule (Context a))
, diffPair :: Maybe (String, String)
, before :: Maybe Term
, after :: Maybe Term
, afterText :: Maybe String
}
newEnvironment :: State a -> Maybe (Rule (Context a)) -> Environment a
newEnvironment st motivationRule = newEnvironmentFor st motivationRule next
where
next = either (const Nothing) Just (onefirst st)
newEnvironmentFor :: State a -> Maybe (Rule (Context a)) -> Maybe ((Rule (Context a), b, c), State a) -> Environment a
newEnvironmentFor st motivationRule next = Env
{ oldReady = finished st
, expected = fmap (\((x,_,_),_) -> x) next
, motivation = motivationRule
, recognized = Nothing
, diffPair = Nothing
, before = f st
, after = fmap snd next >>= f
, afterText = fmap snd next >>= g
}
where
f s = fmap (`build` stateTerm s) (hasTermView (exercise s))
g s = return $ prettyPrinter (exercise s) (stateTerm s)
toText :: Environment a -> Script -> Text -> Maybe Text
toText env script = eval env script . Right
ruleToString :: Environment a -> Script -> Rule b -> String
ruleToString env script r =
let f = eval env script . Left . getId
in maybe (showId r) show (f r)
eval :: Environment a -> Script -> Either Id Text -> Maybe Text
eval env script = either (return . findIdRef) evalText
where
evalText :: Text -> Maybe Text
evalText = fmap mconcat . mapM unref . textItems
where
unref (TextRef a)
| a == expectedId = fmap (findIdRef . getId) (expected env)
| a == recognizedId = fmap (findIdRef . getId) (recognized env)
| a == diffbeforeId = fmap (TextString . fst) (diffPair env)
| a == diffafterId = fmap (TextString . snd) (diffPair env)
| a == beforeId = fmap TextTerm (before env)
| a == afterId = fmap TextTerm (after env)
| a == afterTextId = fmap TextString (afterText env)
| a == motivationId = fmap (findIdRef . getId) (motivation env)
| otherwise = findRef (==a)
unref t = Just t
evalBool :: Condition -> Bool
evalBool (RecognizedIs a) = maybe False (eqId a . getId) (recognized env)
evalBool (MotivationIs a) = maybe False (eqId a . getId) (motivation env)
evalBool (CondNot c) = not (evalBool c)
evalBool (CondConst b) = b
evalBool (CondRef a)
| a == oldreadyId = oldReady env
| a == hasexpectedId = isJust (expected env)
| a == hasrecognizedId = isJust (recognized env)
| a == hasmotivationId = isJust (motivation env)
| a == recognizedbuggyId = maybe False isBuggy (recognized env)
| otherwise = False
namespaces = nub $ mempty : [ a | NameSpace as <- scriptDecls script, a <- as ]
-- equality with namespaces
eqId :: Id -> Id -> Bool
eqId a b = any (\n -> n#a == b) namespaces
findIdRef :: Id -> Text
findIdRef x = fromMaybe (TextString (showId x)) (findRef (`eqId` x))
findRef :: (Id -> Bool) -> Maybe Text
findRef p = listToMaybe $ catMaybes
[ evalText t
| (as, c, t) <- allDecls
, any p as && evalBool c
]
allDecls =
let f (Simple _ as t) = [ (as, CondConst True, t) ]
f (Guarded _ as xs) = [ (as, c, t) | (c, t) <- xs ]
f _ = []
in concatMap f (scriptDecls script)
feedbackDiagnosis :: Diagnosis a -> Environment a -> Script -> Text
feedbackDiagnosis diagnosis env =
case diagnosis of
SyntaxError s -> const (makeText s)
Buggy _ r -> makeWrong "buggy" env {recognized = Just r}
NotEquivalent s -> makeNotEq s "noteq" env
Expected _ _ r -> makeOk "ok" env {recognized = Just r}
WrongRule _ _ mr -> makeWrong "wrongrule" env {recognized = mr}
Similar _ _ mr -> makeOk "same" env {recognized = mr}
Detour _ _ _ r -> makeOk "detour" env {recognized = Just r}
Correct _ _ -> makeOk "correct" env
Unknown _ _ -> makeOk "unknown" env
where
makeOk = makeDefault "Well done!"
makeWrong = makeDefault "This is incorrect."
makeNotEq s = if null s then makeWrong else makeDefault s
makeDefault dt s e = fromMaybe (TextString dt) . make (newId s) e
feedbackHint :: Id -> Environment a -> Script -> Text
feedbackHint feedbackId env script =
fromMaybe (defaultHint env script) $ make feedbackId env script
feedbackHints :: Id -> [((Rule (Context a), b, c), State a)] -> State a -> Maybe (Rule (Context a)) -> Script -> [Text]
feedbackHints feedbackId nexts state motivationRule script =
map (\env -> fromMaybe (defaultHint env script) $
make feedbackId env script) envs
where
envs = map (newEnvironmentFor state motivationRule . Just) nexts
defaultHint :: Environment a -> Script -> Text
defaultHint env script = makeText $
case expected env of
Just r -> ruleToString env script r
Nothing -> "Sorry, no hint available."
make :: Id -> Environment a -> Script -> Maybe Text
make feedbackId env script = toText env script (TextRef feedbackId)
feedbackIds :: [Id]
feedbackIds = map newId
["same", "noteq", "correct", "unknown", "ok", "buggy", "detour", "wrongrule", "hint", "step", "label"]
attributeIds :: [Id]
attributeIds =
[expectedId, recognizedId, diffbeforeId, diffafterId, beforeId, afterId, afterTextId, motivationId]
conditionIds :: [Id]
conditionIds = [oldreadyId, hasexpectedId, hasrecognizedId, hasmotivationId, recognizedbuggyId]
expectedId, recognizedId, diffbeforeId, diffafterId, beforeId, afterId, afterTextId, motivationId :: Id
expectedId = newId "expected"
recognizedId = newId "recognized"
diffbeforeId = newId "diffbefore"
diffafterId = newId "diffafter"
beforeId = newId "before"
afterId = newId "after"
afterTextId = newId "aftertext"
motivationId = newId "motivation"
oldreadyId, hasexpectedId, hasrecognizedId, hasmotivationId, recognizedbuggyId :: Id
oldreadyId = newId "oldready"
hasexpectedId = newId "hasexpected"
hasrecognizedId = newId "hasrecognized"
hasmotivationId = newId "hasmotivation"
recognizedbuggyId = newId "recognizedbuggy"
| null |
https://raw.githubusercontent.com/ideas-edu/ideas/f84907f92a8c407b7313f99e65a08d2646dc1565/src/Ideas/Service/FeedbackScript/Run.hs
|
haskell
|
---------------------------------------------------------------------------
---------------------------------------------------------------------------
|
Maintainer :
Stability : provisional
Run a feedbackscript
---------------------------------------------------------------------------
equality with namespaces
|
Copyright 2019 , Ideas project team . This file is distributed under the
terms of the Apache License 2.0 . For more information , see the files
" LICENSE.txt " and " NOTICE.txt " , which are included in the distribution .
Portability : portable ( depends on ghc )
module Ideas.Service.FeedbackScript.Run
( Script
, Environment(..), newEnvironment
, feedbackDiagnosis, feedbackHint, feedbackHints
, ruleToString, feedbackIds, attributeIds, conditionIds
, eval
) where
import Data.List
import Data.Maybe
import Ideas.Common.Library hiding (ready, Environment)
import Ideas.Service.BasicServices
import Ideas.Service.Diagnose
import Ideas.Service.FeedbackScript.Syntax
import Ideas.Service.State
data Environment a = Env
{ oldReady :: Bool
, expected :: Maybe (Rule (Context a))
, recognized :: Maybe (Rule (Context a))
, motivation :: Maybe (Rule (Context a))
, diffPair :: Maybe (String, String)
, before :: Maybe Term
, after :: Maybe Term
, afterText :: Maybe String
}
newEnvironment :: State a -> Maybe (Rule (Context a)) -> Environment a
newEnvironment st motivationRule = newEnvironmentFor st motivationRule next
where
next = either (const Nothing) Just (onefirst st)
newEnvironmentFor :: State a -> Maybe (Rule (Context a)) -> Maybe ((Rule (Context a), b, c), State a) -> Environment a
newEnvironmentFor st motivationRule next = Env
{ oldReady = finished st
, expected = fmap (\((x,_,_),_) -> x) next
, motivation = motivationRule
, recognized = Nothing
, diffPair = Nothing
, before = f st
, after = fmap snd next >>= f
, afterText = fmap snd next >>= g
}
where
f s = fmap (`build` stateTerm s) (hasTermView (exercise s))
g s = return $ prettyPrinter (exercise s) (stateTerm s)
toText :: Environment a -> Script -> Text -> Maybe Text
toText env script = eval env script . Right
ruleToString :: Environment a -> Script -> Rule b -> String
ruleToString env script r =
let f = eval env script . Left . getId
in maybe (showId r) show (f r)
eval :: Environment a -> Script -> Either Id Text -> Maybe Text
eval env script = either (return . findIdRef) evalText
where
evalText :: Text -> Maybe Text
evalText = fmap mconcat . mapM unref . textItems
where
unref (TextRef a)
| a == expectedId = fmap (findIdRef . getId) (expected env)
| a == recognizedId = fmap (findIdRef . getId) (recognized env)
| a == diffbeforeId = fmap (TextString . fst) (diffPair env)
| a == diffafterId = fmap (TextString . snd) (diffPair env)
| a == beforeId = fmap TextTerm (before env)
| a == afterId = fmap TextTerm (after env)
| a == afterTextId = fmap TextString (afterText env)
| a == motivationId = fmap (findIdRef . getId) (motivation env)
| otherwise = findRef (==a)
unref t = Just t
evalBool :: Condition -> Bool
evalBool (RecognizedIs a) = maybe False (eqId a . getId) (recognized env)
evalBool (MotivationIs a) = maybe False (eqId a . getId) (motivation env)
evalBool (CondNot c) = not (evalBool c)
evalBool (CondConst b) = b
evalBool (CondRef a)
| a == oldreadyId = oldReady env
| a == hasexpectedId = isJust (expected env)
| a == hasrecognizedId = isJust (recognized env)
| a == hasmotivationId = isJust (motivation env)
| a == recognizedbuggyId = maybe False isBuggy (recognized env)
| otherwise = False
namespaces = nub $ mempty : [ a | NameSpace as <- scriptDecls script, a <- as ]
eqId :: Id -> Id -> Bool
eqId a b = any (\n -> n#a == b) namespaces
findIdRef :: Id -> Text
findIdRef x = fromMaybe (TextString (showId x)) (findRef (`eqId` x))
findRef :: (Id -> Bool) -> Maybe Text
findRef p = listToMaybe $ catMaybes
[ evalText t
| (as, c, t) <- allDecls
, any p as && evalBool c
]
allDecls =
let f (Simple _ as t) = [ (as, CondConst True, t) ]
f (Guarded _ as xs) = [ (as, c, t) | (c, t) <- xs ]
f _ = []
in concatMap f (scriptDecls script)
feedbackDiagnosis :: Diagnosis a -> Environment a -> Script -> Text
feedbackDiagnosis diagnosis env =
case diagnosis of
SyntaxError s -> const (makeText s)
Buggy _ r -> makeWrong "buggy" env {recognized = Just r}
NotEquivalent s -> makeNotEq s "noteq" env
Expected _ _ r -> makeOk "ok" env {recognized = Just r}
WrongRule _ _ mr -> makeWrong "wrongrule" env {recognized = mr}
Similar _ _ mr -> makeOk "same" env {recognized = mr}
Detour _ _ _ r -> makeOk "detour" env {recognized = Just r}
Correct _ _ -> makeOk "correct" env
Unknown _ _ -> makeOk "unknown" env
where
makeOk = makeDefault "Well done!"
makeWrong = makeDefault "This is incorrect."
makeNotEq s = if null s then makeWrong else makeDefault s
makeDefault dt s e = fromMaybe (TextString dt) . make (newId s) e
feedbackHint :: Id -> Environment a -> Script -> Text
feedbackHint feedbackId env script =
fromMaybe (defaultHint env script) $ make feedbackId env script
feedbackHints :: Id -> [((Rule (Context a), b, c), State a)] -> State a -> Maybe (Rule (Context a)) -> Script -> [Text]
feedbackHints feedbackId nexts state motivationRule script =
map (\env -> fromMaybe (defaultHint env script) $
make feedbackId env script) envs
where
envs = map (newEnvironmentFor state motivationRule . Just) nexts
defaultHint :: Environment a -> Script -> Text
defaultHint env script = makeText $
case expected env of
Just r -> ruleToString env script r
Nothing -> "Sorry, no hint available."
make :: Id -> Environment a -> Script -> Maybe Text
make feedbackId env script = toText env script (TextRef feedbackId)
feedbackIds :: [Id]
feedbackIds = map newId
["same", "noteq", "correct", "unknown", "ok", "buggy", "detour", "wrongrule", "hint", "step", "label"]
attributeIds :: [Id]
attributeIds =
[expectedId, recognizedId, diffbeforeId, diffafterId, beforeId, afterId, afterTextId, motivationId]
conditionIds :: [Id]
conditionIds = [oldreadyId, hasexpectedId, hasrecognizedId, hasmotivationId, recognizedbuggyId]
expectedId, recognizedId, diffbeforeId, diffafterId, beforeId, afterId, afterTextId, motivationId :: Id
expectedId = newId "expected"
recognizedId = newId "recognized"
diffbeforeId = newId "diffbefore"
diffafterId = newId "diffafter"
beforeId = newId "before"
afterId = newId "after"
afterTextId = newId "aftertext"
motivationId = newId "motivation"
oldreadyId, hasexpectedId, hasrecognizedId, hasmotivationId, recognizedbuggyId :: Id
oldreadyId = newId "oldready"
hasexpectedId = newId "hasexpected"
hasrecognizedId = newId "hasrecognized"
hasmotivationId = newId "hasmotivation"
recognizedbuggyId = newId "recognizedbuggy"
|
0a1323d72fb6013e8ba3337175c2dfcf201a754f481fa705fa9fe25e5488ca26
|
sol/doctest
|
Fib.hs
|
module Fib where
| Calculate Fibonacci number of given ' ' .
--
-- >>> import System.IO
-- >>> hPutStrLn stderr "foobar"
-- foobar
fib :: (Num t, Num t1) => t -> t1
fib _ = undefined
| null |
https://raw.githubusercontent.com/sol/doctest/ec6498542986b659f50e961b02144923f6f41eba/test/integration/bugfixOutputToStdErr/Fib.hs
|
haskell
|
>>> import System.IO
>>> hPutStrLn stderr "foobar"
foobar
|
module Fib where
| Calculate Fibonacci number of given ' ' .
fib :: (Num t, Num t1) => t -> t1
fib _ = undefined
|
c97886dd99c6714b88b087f2bdb81fbef606c477e27402e55f9433f860fee3dd
|
aistrate/Okasaki
|
Deque.hs
|
module Deque (Deque(..), list2Front, list2Rear, front2List, rear2List) where
import Prelude hiding (head, tail, last, init)
class Deque q where
empty :: q a
isEmpty :: q a -> Bool
cons :: a -> q a -> q a
head :: q a -> a
tail :: q a -> q a
snoc :: q a -> a -> q a
last :: q a -> a
init :: q a -> q a
list2Front, list2Rear :: Deque q => [a] -> q a
list2Front = foldl (flip cons) empty
list2Rear = foldl snoc empty
front2List, rear2List :: Deque q => q a -> [a]
front2List q | isEmpty q = []
| otherwise = head q : front2List (tail q)
rear2List q | isEmpty q = []
| otherwise = last q : rear2List (init q)
| null |
https://raw.githubusercontent.com/aistrate/Okasaki/cc1473c81d053483bb5e327409346da7fda10fb4/MyCode/Ch05/Deque.hs
|
haskell
|
module Deque (Deque(..), list2Front, list2Rear, front2List, rear2List) where
import Prelude hiding (head, tail, last, init)
class Deque q where
empty :: q a
isEmpty :: q a -> Bool
cons :: a -> q a -> q a
head :: q a -> a
tail :: q a -> q a
snoc :: q a -> a -> q a
last :: q a -> a
init :: q a -> q a
list2Front, list2Rear :: Deque q => [a] -> q a
list2Front = foldl (flip cons) empty
list2Rear = foldl snoc empty
front2List, rear2List :: Deque q => q a -> [a]
front2List q | isEmpty q = []
| otherwise = head q : front2List (tail q)
rear2List q | isEmpty q = []
| otherwise = last q : rear2List (init q)
|
|
64d805547baee13659d3dec3cd7aab947050691478bb2b46237f927736e9021a
|
gedge-platform/gedge-platform
|
rabbit_mgmt_wm_user.erl
|
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%
Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved .
%%
-module(rabbit_mgmt_wm_user).
-export([init/2, resource_exists/2, to_json/2,
content_types_provided/2, content_types_accepted/2,
is_authorized/2, allowed_methods/2, accept_content/2,
delete_resource/2, user/1, put_user/2, put_user/3]).
-export([variances/2]).
-include_lib("rabbitmq_management_agent/include/rabbit_mgmt_records.hrl").
-include_lib("rabbit_common/include/rabbit.hrl").
%%--------------------------------------------------------------------
init(Req, _State) ->
{cowboy_rest, rabbit_mgmt_headers:set_common_permission_headers(Req, ?MODULE), #context{}}.
variances(Req, Context) ->
{[<<"accept-encoding">>, <<"origin">>], Req, Context}.
content_types_provided(ReqData, Context) ->
{rabbit_mgmt_util:responder_map(to_json), ReqData, Context}.
content_types_accepted(ReqData, Context) ->
{[{'*', accept_content}], ReqData, Context}.
allowed_methods(ReqData, Context) ->
{[<<"HEAD">>, <<"GET">>, <<"PUT">>, <<"DELETE">>, <<"OPTIONS">>], ReqData, Context}.
resource_exists(ReqData, Context) ->
{case user(ReqData) of
{ok, _} -> true;
{error, _} -> false
end, ReqData, Context}.
to_json(ReqData, Context) ->
{ok, User} = user(ReqData),
rabbit_mgmt_util:reply(rabbit_mgmt_format:internal_user(User),
ReqData, Context).
accept_content(ReqData0, Context = #context{user = #user{username = ActingUser}}) ->
Username = rabbit_mgmt_util:id(user, ReqData0),
rabbit_mgmt_util:with_decode(
[], ReqData0, Context,
fun(_, User, ReqData) ->
put_user(User#{name => Username}, ActingUser),
{true, ReqData, Context}
end).
delete_resource(ReqData, Context = #context{user = #user{username = ActingUser}}) ->
User = rabbit_mgmt_util:id(user, ReqData),
rabbit_auth_backend_internal:delete_user(User, ActingUser),
{true, ReqData, Context}.
is_authorized(ReqData, Context) ->
rabbit_mgmt_util:is_authorized_admin(ReqData, Context).
%%--------------------------------------------------------------------
user(ReqData) ->
rabbit_auth_backend_internal:lookup_user(rabbit_mgmt_util:id(user, ReqData)).
put_user(User, ActingUser) ->
put_user(User, undefined, ActingUser).
put_user(User, Version, ActingUser) ->
rabbit_auth_backend_internal:put_user(User, Version, ActingUser).
| null |
https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/rabbitmq_management/src/rabbit_mgmt_wm_user.erl
|
erlang
|
--------------------------------------------------------------------
--------------------------------------------------------------------
|
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved .
-module(rabbit_mgmt_wm_user).
-export([init/2, resource_exists/2, to_json/2,
content_types_provided/2, content_types_accepted/2,
is_authorized/2, allowed_methods/2, accept_content/2,
delete_resource/2, user/1, put_user/2, put_user/3]).
-export([variances/2]).
-include_lib("rabbitmq_management_agent/include/rabbit_mgmt_records.hrl").
-include_lib("rabbit_common/include/rabbit.hrl").
init(Req, _State) ->
{cowboy_rest, rabbit_mgmt_headers:set_common_permission_headers(Req, ?MODULE), #context{}}.
variances(Req, Context) ->
{[<<"accept-encoding">>, <<"origin">>], Req, Context}.
content_types_provided(ReqData, Context) ->
{rabbit_mgmt_util:responder_map(to_json), ReqData, Context}.
content_types_accepted(ReqData, Context) ->
{[{'*', accept_content}], ReqData, Context}.
allowed_methods(ReqData, Context) ->
{[<<"HEAD">>, <<"GET">>, <<"PUT">>, <<"DELETE">>, <<"OPTIONS">>], ReqData, Context}.
resource_exists(ReqData, Context) ->
{case user(ReqData) of
{ok, _} -> true;
{error, _} -> false
end, ReqData, Context}.
to_json(ReqData, Context) ->
{ok, User} = user(ReqData),
rabbit_mgmt_util:reply(rabbit_mgmt_format:internal_user(User),
ReqData, Context).
accept_content(ReqData0, Context = #context{user = #user{username = ActingUser}}) ->
Username = rabbit_mgmt_util:id(user, ReqData0),
rabbit_mgmt_util:with_decode(
[], ReqData0, Context,
fun(_, User, ReqData) ->
put_user(User#{name => Username}, ActingUser),
{true, ReqData, Context}
end).
delete_resource(ReqData, Context = #context{user = #user{username = ActingUser}}) ->
User = rabbit_mgmt_util:id(user, ReqData),
rabbit_auth_backend_internal:delete_user(User, ActingUser),
{true, ReqData, Context}.
is_authorized(ReqData, Context) ->
rabbit_mgmt_util:is_authorized_admin(ReqData, Context).
user(ReqData) ->
rabbit_auth_backend_internal:lookup_user(rabbit_mgmt_util:id(user, ReqData)).
put_user(User, ActingUser) ->
put_user(User, undefined, ActingUser).
put_user(User, Version, ActingUser) ->
rabbit_auth_backend_internal:put_user(User, Version, ActingUser).
|
6dc97564d351fcee81b41d86bdc1ddf14013854541817a20a85376ddcda0c9b7
|
mtnygard/simulant-example
|
main.clj
|
(ns simtest.main)
(defmulti run-command (fn [command & _] command))
(def output (agent 0))
(defn prflush [s v] (do (print v) (flush) v))
(defn dot [a]
(send-off output prflush
(cond
(< 25 (count a)) \*
(< 15 (count a)) \#
(< 10 (count a) 16) \+
(< 5 (count a) 11) \-
:else \.))
a)
(defn error [reason detail] {:result :error :reason reason :detail detail})
(defmacro error-generators
[& reasons]
(assert (every? keyword? reasons))
(list* `do
(for [r reasons]
`(def ~(symbol (name r)) (partial error ~r)))))
(error-generators :argument-error :missing-model :missing-resource :transaction-error :required-argument)
(defn print-errors
"Replace this with a hook into your preferred logging framework."
[errors]
(binding [*out* *err*]
(doseq [e (filter #(not= :ok (:result %)) (flatten errors))]
(println e))))
(defmacro condp->
"Takes an expression and a set of predicate/form pairs. Threads expr (via ->)
through each form for which the corresponding predicate is true of expr.
Note that, unlike cond branching, condp-> threading does not short circuit
after the first true test expression."
[expr & clauses]
(assert (even? (count clauses)))
(let [g (gensym)
pstep (fn [[pred step]] `(if (~pred ~g) (-> ~g ~step) ~g))]
`(let [~g ~expr
~@(interleave (repeat g) (map pstep (partition 2 clauses)))]
~g)))
| null |
https://raw.githubusercontent.com/mtnygard/simulant-example/dcb76b2eda47dfb6be10a2077ade319873eacce1/simtest/src/simtest/main.clj
|
clojure
|
(ns simtest.main)
(defmulti run-command (fn [command & _] command))
(def output (agent 0))
(defn prflush [s v] (do (print v) (flush) v))
(defn dot [a]
(send-off output prflush
(cond
(< 25 (count a)) \*
(< 15 (count a)) \#
(< 10 (count a) 16) \+
(< 5 (count a) 11) \-
:else \.))
a)
(defn error [reason detail] {:result :error :reason reason :detail detail})
(defmacro error-generators
[& reasons]
(assert (every? keyword? reasons))
(list* `do
(for [r reasons]
`(def ~(symbol (name r)) (partial error ~r)))))
(error-generators :argument-error :missing-model :missing-resource :transaction-error :required-argument)
(defn print-errors
"Replace this with a hook into your preferred logging framework."
[errors]
(binding [*out* *err*]
(doseq [e (filter #(not= :ok (:result %)) (flatten errors))]
(println e))))
(defmacro condp->
"Takes an expression and a set of predicate/form pairs. Threads expr (via ->)
through each form for which the corresponding predicate is true of expr.
Note that, unlike cond branching, condp-> threading does not short circuit
after the first true test expression."
[expr & clauses]
(assert (even? (count clauses)))
(let [g (gensym)
pstep (fn [[pred step]] `(if (~pred ~g) (-> ~g ~step) ~g))]
`(let [~g ~expr
~@(interleave (repeat g) (map pstep (partition 2 clauses)))]
~g)))
|
|
87260e60f00b3d12413887212119745ec440f27f9d850b4b6c857d2799de2241
|
robert-strandh/SICL
|
nsubst-defun.lisp
|
(cl:in-package #:sicl-cons)
(defun |nsubst key=identity test=eq| (new old tree)
(labels ((traverse (tree)
(cond ((eq (car tree) old)
(setf (car tree) new))
((atom (car tree))
nil)
(t
(traverse (car tree))))
(cond ((eq (cdr tree) old)
(setf (cdr tree) new))
((atom (cdr tree))
nil)
(t
(traverse (cdr tree))))))
(cond ((eq tree old) new)
((atom tree) tree)
(t (traverse tree) tree))))
(defun |nsubst key=identity test=eql| (new old tree)
(labels ((traverse (tree)
(cond ((eql (car tree) old)
(setf (car tree) new))
((atom (car tree))
nil)
(t
(traverse (car tree))))
(cond ((eql (cdr tree) old)
(setf (cdr tree) new))
((atom (cdr tree))
nil)
(t
(traverse (cdr tree))))))
(cond ((eql tree old) new)
((atom tree) tree)
(t (traverse tree) tree))))
(defun |nsubst key=other test=eq| (new old tree key)
(labels ((traverse (tree)
(cond ((eq (funcall key (car tree)) old)
(setf (car tree) new))
((atom (car tree))
nil)
(t
(traverse (car tree))))
(cond ((eq (funcall key (cdr tree)) old)
(setf (cdr tree) new))
((atom (cdr tree))
nil)
(t
(traverse (cdr tree))))))
(cond ((eq (funcall key tree) old) new)
((atom tree) tree)
(t (traverse tree) tree))))
(defun |nsubst key=other test=eql| (new old tree key)
(labels ((traverse (tree)
(cond ((eql (funcall key (car tree)) old)
(setf (car tree) new))
((atom (car tree))
nil)
(t
(traverse (car tree))))
(cond ((eql (funcall key (cdr tree)) old)
(setf (cdr tree) new))
((atom (cdr tree))
nil)
(t
(traverse (cdr tree))))))
(cond ((eql (funcall key tree) old) new)
((atom tree) tree)
(t (traverse tree) tree))))
(defun |nsubst key=identity test=other| (new old tree test)
(labels ((traverse (tree)
(cond ((funcall test old (car tree))
(setf (car tree) new))
((atom (car tree))
nil)
(t
(traverse (car tree))))
(cond ((funcall test old (cdr tree))
(setf (cdr tree) new))
((atom (cdr tree))
nil)
(t
(traverse (cdr tree))))))
(cond ((funcall test old tree) new)
((atom tree) tree)
(t (traverse tree) tree))))
(defun |nsubst key=other-test-other| (new old tree test key)
(labels ((traverse (tree)
(cond ((funcall test old (funcall key (car tree)))
(setf (car tree) new))
((atom (car tree))
nil)
(t
(traverse (car tree))))
(cond ((funcall test old (funcall key (cdr tree)))
(setf (cdr tree) new))
((atom (cdr tree))
nil)
(t
(traverse (cdr tree))))))
(cond ((funcall test old (funcall key tree)) new)
((atom tree) tree)
(t (traverse tree) tree))))
;;; As with subst, we do not provide special versions for a :test-not
of eq or . See comment above for an explanation .
(defun |nsubst key=identity test-not=other| (new old tree test)
(labels ((traverse (tree)
(cond ((not (funcall test old (car tree)))
(setf (car tree) new))
((atom (car tree))
nil)
(t
(traverse (car tree))))
(cond ((not (funcall test old (cdr tree)))
(setf (cdr tree) new))
((atom (cdr tree))
nil)
(t
(traverse (cdr tree))))))
(cond ((not (funcall test old tree)) new)
((atom tree) tree)
(t (traverse tree) tree))))
(defun |nsubst key=other test-not=other| (new old tree test key)
(labels ((traverse (tree)
(cond ((not (funcall test old (funcall key (car tree))))
(setf (car tree) new))
((atom (car tree))
nil)
(t
(traverse (car tree))))
(cond ((not (funcall test old (funcall key (cdr tree))))
(setf (cdr tree) new))
((atom (cdr tree))
nil)
(t
(traverse (cdr tree))))))
(cond ((not (funcall test old (funcall key tree))) new)
((atom tree) tree)
(t (traverse tree) tree))))
(defun nsubst (new old tree
&key key (test nil test-given) (test-not nil test-not-given))
(when (and test-given test-not-given)
(error 'both-test-and-test-not-given))
(if key
(if test-given
(if (or (eq test #'eq) (eq test 'eq))
(|nsubst key=other test=eq| new old tree key)
(if (or (eq test #'eql) (eq test 'eql))
(|nsubst key=other test=eql| new old tree key)
(|nsubst key=other-test-other| new old tree test key)))
(if test-not-given
(|nsubst key=other test-not=other| new old tree test-not key)
(|nsubst key=other test=eql| new old tree key)))
(if test-given
(if (or (eq test #'eq) (eq test 'eq))
(|nsubst key=identity test=eq| new old tree)
(if (or (eq test #'eql) (eq test 'eql))
(|nsubst key=identity test=eql| new old tree)
(|nsubst key=identity test=other| new old tree test)))
(if test-not-given
(|nsubst key=identity test-not=other| new old tree test-not)
(|nsubst key=identity test=eql| new old tree)))))
| null |
https://raw.githubusercontent.com/robert-strandh/SICL/32d995c4f8e7d228e9c0cda6f670b2fa53ad0287/Code/Cons/nsubst-defun.lisp
|
lisp
|
As with subst, we do not provide special versions for a :test-not
|
(cl:in-package #:sicl-cons)
(defun |nsubst key=identity test=eq| (new old tree)
(labels ((traverse (tree)
(cond ((eq (car tree) old)
(setf (car tree) new))
((atom (car tree))
nil)
(t
(traverse (car tree))))
(cond ((eq (cdr tree) old)
(setf (cdr tree) new))
((atom (cdr tree))
nil)
(t
(traverse (cdr tree))))))
(cond ((eq tree old) new)
((atom tree) tree)
(t (traverse tree) tree))))
(defun |nsubst key=identity test=eql| (new old tree)
(labels ((traverse (tree)
(cond ((eql (car tree) old)
(setf (car tree) new))
((atom (car tree))
nil)
(t
(traverse (car tree))))
(cond ((eql (cdr tree) old)
(setf (cdr tree) new))
((atom (cdr tree))
nil)
(t
(traverse (cdr tree))))))
(cond ((eql tree old) new)
((atom tree) tree)
(t (traverse tree) tree))))
(defun |nsubst key=other test=eq| (new old tree key)
(labels ((traverse (tree)
(cond ((eq (funcall key (car tree)) old)
(setf (car tree) new))
((atom (car tree))
nil)
(t
(traverse (car tree))))
(cond ((eq (funcall key (cdr tree)) old)
(setf (cdr tree) new))
((atom (cdr tree))
nil)
(t
(traverse (cdr tree))))))
(cond ((eq (funcall key tree) old) new)
((atom tree) tree)
(t (traverse tree) tree))))
(defun |nsubst key=other test=eql| (new old tree key)
(labels ((traverse (tree)
(cond ((eql (funcall key (car tree)) old)
(setf (car tree) new))
((atom (car tree))
nil)
(t
(traverse (car tree))))
(cond ((eql (funcall key (cdr tree)) old)
(setf (cdr tree) new))
((atom (cdr tree))
nil)
(t
(traverse (cdr tree))))))
(cond ((eql (funcall key tree) old) new)
((atom tree) tree)
(t (traverse tree) tree))))
(defun |nsubst key=identity test=other| (new old tree test)
(labels ((traverse (tree)
(cond ((funcall test old (car tree))
(setf (car tree) new))
((atom (car tree))
nil)
(t
(traverse (car tree))))
(cond ((funcall test old (cdr tree))
(setf (cdr tree) new))
((atom (cdr tree))
nil)
(t
(traverse (cdr tree))))))
(cond ((funcall test old tree) new)
((atom tree) tree)
(t (traverse tree) tree))))
(defun |nsubst key=other-test-other| (new old tree test key)
(labels ((traverse (tree)
(cond ((funcall test old (funcall key (car tree)))
(setf (car tree) new))
((atom (car tree))
nil)
(t
(traverse (car tree))))
(cond ((funcall test old (funcall key (cdr tree)))
(setf (cdr tree) new))
((atom (cdr tree))
nil)
(t
(traverse (cdr tree))))))
(cond ((funcall test old (funcall key tree)) new)
((atom tree) tree)
(t (traverse tree) tree))))
of eq or . See comment above for an explanation .
(defun |nsubst key=identity test-not=other| (new old tree test)
(labels ((traverse (tree)
(cond ((not (funcall test old (car tree)))
(setf (car tree) new))
((atom (car tree))
nil)
(t
(traverse (car tree))))
(cond ((not (funcall test old (cdr tree)))
(setf (cdr tree) new))
((atom (cdr tree))
nil)
(t
(traverse (cdr tree))))))
(cond ((not (funcall test old tree)) new)
((atom tree) tree)
(t (traverse tree) tree))))
(defun |nsubst key=other test-not=other| (new old tree test key)
(labels ((traverse (tree)
(cond ((not (funcall test old (funcall key (car tree))))
(setf (car tree) new))
((atom (car tree))
nil)
(t
(traverse (car tree))))
(cond ((not (funcall test old (funcall key (cdr tree))))
(setf (cdr tree) new))
((atom (cdr tree))
nil)
(t
(traverse (cdr tree))))))
(cond ((not (funcall test old (funcall key tree))) new)
((atom tree) tree)
(t (traverse tree) tree))))
(defun nsubst (new old tree
&key key (test nil test-given) (test-not nil test-not-given))
(when (and test-given test-not-given)
(error 'both-test-and-test-not-given))
(if key
(if test-given
(if (or (eq test #'eq) (eq test 'eq))
(|nsubst key=other test=eq| new old tree key)
(if (or (eq test #'eql) (eq test 'eql))
(|nsubst key=other test=eql| new old tree key)
(|nsubst key=other-test-other| new old tree test key)))
(if test-not-given
(|nsubst key=other test-not=other| new old tree test-not key)
(|nsubst key=other test=eql| new old tree key)))
(if test-given
(if (or (eq test #'eq) (eq test 'eq))
(|nsubst key=identity test=eq| new old tree)
(if (or (eq test #'eql) (eq test 'eql))
(|nsubst key=identity test=eql| new old tree)
(|nsubst key=identity test=other| new old tree test)))
(if test-not-given
(|nsubst key=identity test-not=other| new old tree test-not)
(|nsubst key=identity test=eql| new old tree)))))
|
58c08823aaa70d4522f3cc17c778041c2107009130fe6c4c9c6dae2f4d07435e
|
unison-code/uni-instr-sel
|
Base.hs
|
|
Copyright : Copyright ( c ) 2012 - 2017 , < >
License : BSD3 ( see the LICENSE file )
Maintainer :
Copyright : Copyright (c) 2012-2017, Gabriel Hjort Blindell <>
License : BSD3 (see the LICENSE file)
Maintainer :
-}
Main authors :
< >
Main authors:
Gabriel Hjort Blindell <>
-}
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE OverloadedStrings , FlexibleInstances #
module Language.InstrSel.Graphs.Base
( DomSet (..)
, DstNode
, Edge (..)
, EdgeLabel (..)
, EdgeType (..)
, EdgeNr (..)
, Graph (..)
, IntGraph
, Mapping (..)
, Match (..)
, Node (..)
, NodeLabel (..)
, NodeType (..)
, SrcNode
, addMappingToMatch
, addNewEdge
, addNewEdges
, addNewCtrlFlowEdge
, addNewCtrlFlowEdges
, addNewDtFlowEdge
, addNewDtFlowEdges
, addNewDefEdge
, addNewDefEdges
, addNewStFlowEdge
, addNewStFlowEdges
, addNewNode
, addOriginToValueNode
, areInEdgesEquivalent
, areOutEdgesEquivalent
, computeDomSets
, convertDomSetN2ID
, convertMappingN2ID
, convertMatchN2ID
, copyNodeLabel
, customPatternMatchingSemanticsCheck
, delEdge
, delNode
, delFNodeInMatch
, delNodeKeepEdges
, delPNodeInMatch
, doEdgeListsMatch
, doNodesMatch
, extractCFG
, extractSSAG
, findFNInMapping
, findFNInMatch
, findFNsInMapping
, findFNsInMatch
, findNodesWithNodeID
, findPNInMapping
, findPNInMatch
, findPNsInMapping
, findPNsInMatch
, findCallNodesWithName
, findBlockNodesWithName
, findValueNodesWithOrigin
, fromEdgeNr
, getAllNodes
, getAllEdges
, findDefEdgeOfDtInEdge
, findDefEdgeOfDtOutEdge
, getCtrlFlowInEdges
, getCtrlFlowOutEdges
, getCopiesOfValue
, getCopyRelatedValues
, getDataTypeOfValueNode
, getDtFlowInEdges
, getDtFlowOutEdges
, getDefInEdges
, getDefOutEdges
, getStFlowInEdges
, getStFlowOutEdges
, getEdgeType
, getEdges
, getEdgesBetween
, getEdgeLabel
, getEdgeInNr
, getEdgeOutNr
, getInEdges
, getNeighbors
, getNodeID
, getNodeLabel
, getNodeType
, getNumNodes
, getNameOfCallNode
, getNameOfBlockNode
, getOpOfComputationNode
, getOriginOfValueNode
, getOutEdges
, getPredecessors
, getSourceNode
, getSuccessors
, getTargetNode
, groupNodesByID
, hasAnyPredecessors
, hasAnySuccessors
, haveSameInEdgeNrs
, haveSameOutEdgeNrs
, insertNewNodeAlongEdge
, isBrControlNode
, isCondBrControlNode
, isCallNode
, isIndirCallNode
, isComputationNode
, isControlFlowEdge
, isControlNode
, isCopyNode
, isDataFlowEdge
, isDatumNode
, isValueNode
, isValueNodeWithConstValue
, isValueNodeWithOrigin
, isValueNodeWithPointerDataType
, isDefEdge
, isInGraph
, isBlockNode
, isGraphEmpty
, isNodeInGraph
, isOperationNode
, isStateFlowEdge
, isOfCallNodeType
, isOfIndirCallNodeType
, isOfComputationNodeType
, isOfControlFlowEdgeType
, isOfControlNodeType
, isOfCopyNodeType
, isOfDataFlowEdgeType
, isOfValueNodeType
, isOfDefEdgeType
, isOfBlockNodeType
, isOfPhiNodeType
, isOfStateFlowEdgeType
, isOfStateNodeType
, isPhiNode
, isRetControlNode
, isStateNode
, mergeMatches
, mergeNodes
, mkEmpty
, mkGraph
, redirectEdges
, redirectInEdges
, redirectOutEdges
, redirectEdgesWhen
, redirectInEdgesWhen
, redirectOutEdgesWhen
, rootInCFG
, sortByEdgeNr
, toEdgeNr
, fromMatch
, toMatch
, subGraph
, updateOpOfComputationNode
, updateDataTypeOfValueNode
, updateEdgeLabel
, updateEdgeSource
, updateEdgeTarget
, updateEdgeInNr
, updateEdgeOutNr
, updateFNodeInMatch
, updateNameOfCallNode
, updateNodeID
, updateNodeLabel
, updateNodeType
, updatePNodeInMatch
)
where
import Language.InstrSel.PrettyShow
import qualified Language.InstrSel.DataTypes as D
import Language.InstrSel.Functions.IDs
( BlockName
, FunctionName
)
import Language.InstrSel.Graphs.IDs
import qualified Language.InstrSel.OpTypes as O
import Language.InstrSel.Utils
( groupBy )
import Language.InstrSel.Utils.Natural
import Language.InstrSel.Utils.JSON
import qualified Data.Graph.Inductive as I
import Data.List
( nubBy
, sortBy
)
import Data.Maybe
import qualified Data.Map as M
import qualified Data.Vector as V
import Control.DeepSeq
( NFData
, rnf
)
--------------
-- Data types
--------------
-- | Alias for the internal graph representation.
type IntGraph = I.Gr NodeLabel EdgeLabel
-- | The outer-most data type which contains the graph itself. It also caches
-- all nodes in a map with node IDs as keys for efficient access.
data Graph
= Graph { intGraph :: IntGraph
, intNodeMap :: M.Map NodeID [Node]
, entryBlockNode :: Maybe Node
}
deriving (Show)
-- | Represents a distinct node.
newtype Node
= Node (I.LNode NodeLabel)
deriving (Show)
instance Ord Node where
(Node (n1, _)) <= (Node (n2, _)) = n1 <= n2
instance Eq Node where
(Node (n1, _)) == (Node (n2, _)) = n1 == n2
instance PrettyShow Node where
pShow n = "{ID: " ++ pShow (getNodeID n) ++ ", " ++ pShow (getNodeType n) ++
"}"
-- | A synonym for indicating the source node of an edge.
type SrcNode = Node
-- | A synonym for indicating the destination node of an edge.
type DstNode = Node
-- | Node label, consisting of an ID that can be shared by multiple nodes (thus
-- representing that they are actually the same node) and node information which
-- denotes the type of node and other auxiliary information.
data NodeLabel
= NodeLabel
{ nodeID :: NodeID
, nodeType :: NodeType
}
deriving (Show)
-- | The node type information.
data NodeType
= ComputationNode { compOp :: O.CompOp }
| ControlNode { ctrlOp :: O.ControlOp }
| CallNode { nameOfCall :: FunctionName }
-- | An indirect call to a function whose address is provided through a
-- value node.
| IndirCallNode
-- | Temporary and constant nodes (appearing in IR and pattern code), as
-- well as register and immediate nodes (appearing only in pattern code),
are all represented as value nodes . What distinguishes one from another
-- are the constraints applied to it.
| ValueNode
{ typeOfValue :: D.DataType
, originOfValue :: [String]
-- ^ If the value node represents a particular temporary or variable or
-- which is specified in the source code, then the name of that item can
-- be given here as a string. A value node is allowed to have any number
of origins , but the most current origin should always be placed first
-- in the list.
}
| BlockNode { nameOfBlock :: BlockName }
| PhiNode
| StateNode
| CopyNode
deriving (Show)
instance PrettyShow NodeType where
pShow (ComputationNode op) = "computation node (" ++ pShow op ++ ")"
pShow (ControlNode op) = "control node (" ++ pShow op ++ ")"
pShow (CallNode func) = "call node (" ++ pShow func ++ ")"
pShow IndirCallNode = "indirect call node"
pShow (ValueNode dt origin) = "value node (" ++ pShow dt ++ ", "
++ pShow origin ++ ")"
pShow (BlockNode name) = "block node (" ++ pShow name ++ ")"
pShow PhiNode = "phi node"
pShow StateNode = "state node"
pShow CopyNode = "copy node"
-- | Represents a distinct edge.
newtype Edge
= Edge (I.LEdge EdgeLabel)
deriving (Show, Eq)
instance PrettyShow Edge where
pShow (Edge (s, t, l)) =
"<" ++ pShow (edgeType l) ++ ", " ++ pShow s ++
": " ++ pShow (outEdgeNr l) ++ " -> " ++ pShow (inEdgeNr l) ++
": " ++ pShow t ++ ">"
| Data type for describing how an edge relates to the two nodes .
data EdgeLabel
= EdgeLabel
{ edgeType :: EdgeType
, outEdgeNr :: EdgeNr
, inEdgeNr :: EdgeNr
}
deriving (Show, Eq)
-- | Data type for determining the edge type.
data EdgeType
= ControlFlowEdge
| DataFlowEdge
| StateFlowEdge
| DefEdge
deriving (Show, Eq)
instance PrettyShow EdgeType where
pShow ControlFlowEdge = "control-flow"
pShow DataFlowEdge = "data-flow"
pShow StateFlowEdge = "state-flow"
pShow DefEdge = "definition"
-- | Edge number, used for ordering edges.
newtype EdgeNr
= EdgeNr Natural
deriving (Show, Eq, Ord, Num, Enum, Integral, Real)
instance PrettyShow EdgeNr where
pShow (EdgeNr i) = pShow i
| Represents a mapping between two entities ( typically ' 's or ' NodeID 's ) .
data Mapping n
= Mapping
{ fNode :: n
-- ^ The mapped node appearing in the function graph.
, pNode :: n
-- ^ The mapped node appearing in the pattern graph.
}
deriving (Show, Eq, Ord)
instance (PrettyShow a) => PrettyShow (Mapping a) where
| The mapping is shown as a tuple , where the ' is the first element
and the ' pNode ' is the second element .
pShow m = pShow (fNode m, pNode m)
-- | Represents a match between a function graph and a pattern graph. Note that
-- it is allowed that a node in the pattern graph may be mapped to multiple
-- nodes in the function graph, and vice versa.
--
For efficiency , the mappings are stored in two forms : one as mappings from
-- function nodes to pattern nodes, and another as mappings from pattern nodes
-- to function nodes.
data Match n
= Match { f2pMaps :: M.Map n [n]
-- ^ Mappings from function nodes to pattern nodes.
, p2fMaps :: M.Map n [n]
-- ^ Mappings from pattern nodes to function nodes.
}
deriving (Show, Eq, Ord)
instance (PrettyShow a, Ord a) => PrettyShow (Match a) where
pShow m = pShow $ fromMatch m
-- | Represents a dominator set.
data DomSet t
= DomSet
{ domNode :: t
-- ^ The item that this dominator set concerns.
, domSet :: [t]
-- ^ The items that dominate this item.
}
deriving (Show)
-------------------------------------
-- JSON-related type class instances
-------------------------------------
instance FromJSON Graph where
parseJSON (Object v) =
do g <- v .: "graph"
entry <- v .:? "entry-block-node"
let ns = map Node $ I.labNodes g
return $ Graph { intGraph = g
, intNodeMap = M.fromList $ groupNodesByID ns
, entryBlockNode = if isJust entry
then Just $ toNode $ fromJust entry
else Nothing
}
parseJSON _ = mzero
instance ToJSON Graph where
toJSON g =
let entry = entryBlockNode g
in object [ "graph" .= (intGraph g)
, "entry-block-node" .= ( if isJust entry
then Just $ fromNode $ fromJust entry
else Nothing
)
]
instance FromJSON IntGraph where
parseJSON (Object v) =
I.mkGraph
<$> v .: "nodes"
<*> v .: "edges"
parseJSON _ = mzero
instance ToJSON IntGraph where
toJSON g =
object [ "nodes" .= (I.labNodes g)
, "edges" .= (I.labEdges g)
]
instance FromJSON NodeLabel where
parseJSON (Object v) =
NodeLabel
<$> v .: "id"
<*> v .: "type"
parseJSON _ = mzero
instance ToJSON NodeLabel where
toJSON l =
object [ "id" .= (nodeID l)
, "type" .= (nodeType l)
]
instance FromJSON NodeType where
parseJSON (Object v) =
do str <- v .: "ntype"
let typ = unpack str
case typ of "comp" -> ComputationNode
<$> v .: "op"
"ctrl" -> ControlNode
<$> v .: "op"
"call" -> CallNode
<$> v .: "func"
"indir-call" -> return IndirCallNode
"data" -> ValueNode
<$> v .: "dtype"
<*> v .: "origin"
"lab" -> BlockNode
<$> v .: "block-name"
"phi" -> return PhiNode
"stat" -> return StateNode
"copy" -> return CopyNode
_ -> mzero
parseJSON _ = mzero
instance ToJSON NodeType where
toJSON n@(ComputationNode {}) =
object [ "ntype" .= String "comp"
, "op" .= toJSON (compOp n)
]
toJSON n@(ControlNode {}) =
object [ "ntype" .= String "ctrl"
, "op" .= toJSON (ctrlOp n)
]
toJSON n@(CallNode {}) =
object [ "ntype" .= String "call"
, "func" .= toJSON (nameOfCall n)
]
toJSON IndirCallNode =
object [ "ntype" .= String "indir-call" ]
toJSON n@(ValueNode {}) =
object [ "ntype" .= String "data"
, "dtype" .= toJSON (typeOfValue n)
, "origin" .= toJSON (originOfValue n)
]
toJSON n@(BlockNode {}) =
object [ "ntype" .= String "lab"
, "block-name" .= toJSON (nameOfBlock n)
]
toJSON (PhiNode {}) =
object [ "ntype" .= String "phi" ]
toJSON (StateNode {}) =
object [ "ntype" .= String "stat" ]
toJSON (CopyNode {}) =
object [ "ntype" .= String "copy" ]
instance FromJSON EdgeLabel where
parseJSON (Object v) =
EdgeLabel
<$> v .: "etype"
<*> v .: "out-nr"
<*> v .: "in-nr"
parseJSON _ = mzero
instance ToJSON EdgeLabel where
toJSON l =
object [ "etype" .= (edgeType l)
, "out-nr" .= (outEdgeNr l)
, "in-nr" .= (inEdgeNr l)
]
instance FromJSON EdgeType where
parseJSON (String str) =
case str of "ctrl" -> return ControlFlowEdge
"data" -> return DataFlowEdge
"stat" -> return StateFlowEdge
"def" -> return DefEdge
_ -> mzero
parseJSON _ = mzero
instance ToJSON EdgeType where
toJSON ControlFlowEdge = "ctrl"
toJSON DataFlowEdge = "data"
toJSON StateFlowEdge = "stat"
toJSON DefEdge = "def"
instance FromJSON EdgeNr where
parseJSON v = EdgeNr <$> parseJSON v
instance ToJSON EdgeNr where
toJSON (EdgeNr nr) = toJSON nr
instance FromJSON (DomSet NodeID) where
parseJSON (Object v) =
DomSet
<$> v .: "node"
<*> v .: "dom-set"
parseJSON _ = mzero
instance ToJSON (DomSet NodeID) where
toJSON d =
object [ "node" .= (domNode d)
, "dom-set" .= (domSet d)
]
instance FromJSON (Match NodeID) where
parseJSON v@(Array _) =
do list <- parseJSON v
return $ toMatch list
parseJSON _ = mzero
instance ToJSON (Match NodeID) where
toJSON m = toJSON $ fromMatch m
instance FromJSON (Mapping NodeID) where
parseJSON v@(Array _) =
do list <- parseJSON v
when (length list /= 2) mzero
return Mapping { fNode = head list
, pNode = last list
}
parseJSON _ = mzero
instance ToJSON (Mapping NodeID) where
toJSON m = Array (V.fromList [toJSON $ fNode m, toJSON $ pNode m])
----------------------------------------
DeepSeq - related type class instances
--
-- These are needed to be able to time
-- how long it takes to produce the
-- matchsets
----------------------------------------
instance NFData n => NFData (Mapping n) where
rnf (Mapping a b) = rnf a `seq` rnf b
instance NFData n => NFData (Match n) where
rnf (Match a b) = rnf a `seq` rnf b
-------------
-- Functions
-------------
toNode :: I.LNode NodeLabel -> Node
toNode = Node
fromNode :: Node -> I.LNode NodeLabel
fromNode (Node n) = n
toEdge :: I.LEdge EdgeLabel -> Edge
toEdge = Edge
fromEdge :: Edge -> I.LEdge EdgeLabel
fromEdge (Edge e) = e
toEdgeNr :: (Integral i) => i -> EdgeNr
toEdgeNr = EdgeNr . toNatural
fromEdgeNr :: EdgeNr -> Natural
fromEdgeNr (EdgeNr n) = n
-- | Checks if a given node is an operation.
isOperationNode :: Node -> Bool
isOperationNode n =
isComputationNode n ||
isControlNode n ||
isCallNode n ||
isIndirCallNode n ||
isPhiNode n ||
isCopyNode n
-- | Checks if a given node is a datum.
isDatumNode :: Node -> Bool
isDatumNode n =
isValueNode n ||
isStateNode n
-- | Checks if a node exists inside a graph.
isNodeInGraph :: Graph -> Node -> Bool
isNodeInGraph g n = n `elem` getAllNodes g
-- | Checks if a given node is a computation node.
isComputationNode :: Node -> Bool
isComputationNode n = isOfComputationNodeType $ getNodeType n
-- | Checks if a given node is a control node.
isControlNode :: Node -> Bool
isControlNode n = isOfControlNodeType $ getNodeType n
-- | Checks if a given node is a call node.
isCallNode :: Node -> Bool
isCallNode n = isOfCallNodeType $ getNodeType n
-- | Checks if a given node is an indirect-call node.
isIndirCallNode :: Node -> Bool
isIndirCallNode n = isOfIndirCallNodeType $ getNodeType n
-- | Checks if a given node is a return control node.
isRetControlNode :: Node -> Bool
isRetControlNode n = isControlNode n && (ctrlOp $ getNodeType n) == O.Ret
-- | Checks if a given node is an unconditional-branch control node.
isBrControlNode :: Node -> Bool
isBrControlNode n = isControlNode n && (ctrlOp $ getNodeType n) == O.Br
-- | Checks if a given node is an conditional-branch control node.
isCondBrControlNode :: Node -> Bool
isCondBrControlNode n = isControlNode n && (ctrlOp $ getNodeType n) == O.CondBr
-- | Checks if a given node is a value node.
isValueNode :: Node -> Bool
isValueNode n = isOfValueNodeType $ getNodeType n
-- | Checks if a given node is a value node representing a constant value.
isValueNodeWithConstValue :: Node -> Bool
isValueNodeWithConstValue n =
if isValueNode n
then D.isTypeAConstValue $ getDataTypeOfValueNode n
else False
-- | Checks if a given node is a value node representing a pointer.
isValueNodeWithPointerDataType :: Node -> Bool
isValueNodeWithPointerDataType n =
if isValueNode n
then D.isTypeAPointer $ getDataTypeOfValueNode n
else False
-- | Checks if a given node is a value node whose value has an origin (name) in
-- the source code.
isValueNodeWithOrigin :: Node -> Bool
isValueNodeWithOrigin n =
if isValueNode n
then length (originOfValue $ getNodeType n) > 0
else False
-- | Gets the origin of a given value node. Note that a value may have more
-- than one origin.
getOriginOfValueNode :: Node -> [String]
getOriginOfValueNode = originOfValue . getNodeType
-- | Gets the name of a given block node.
getNameOfBlockNode :: Node -> BlockName
getNameOfBlockNode = nameOfBlock . getNodeType
-- | Gets the name of a given call node.
getNameOfCallNode :: Node -> FunctionName
getNameOfCallNode = nameOfCall . getNodeType
-- | Checks if a given node is a block node.
isBlockNode :: Node -> Bool
isBlockNode n = isOfBlockNodeType $ getNodeType n
| Checks if a given node is a phi node .
isPhiNode :: Node -> Bool
isPhiNode n = isOfPhiNodeType $ getNodeType n
-- | Checks if a given node is a state node.
isStateNode :: Node -> Bool
isStateNode n = isOfStateNodeType $ getNodeType n
-- | Checks if a given node is a copy node.
isCopyNode :: Node -> Bool
isCopyNode n = isOfCopyNodeType $ getNodeType n
-- | Checks if a given node type represents a computation node.
isOfComputationNodeType :: NodeType -> Bool
isOfComputationNodeType (ComputationNode _) = True
isOfComputationNodeType _ = False
-- | Checks if a given node type represents a call node.
isOfCallNodeType :: NodeType -> Bool
isOfCallNodeType (CallNode _) = True
isOfCallNodeType _ = False
-- | Checks if a given node type represents an indirect-call node.
isOfIndirCallNodeType :: NodeType -> Bool
isOfIndirCallNodeType IndirCallNode = True
isOfIndirCallNodeType _ = False
-- | Checks if a given node type represents a control node.
isOfControlNodeType :: NodeType -> Bool
isOfControlNodeType (ControlNode _) = True
isOfControlNodeType _ = False
-- | Checks if a given node type represents a value node.
isOfValueNodeType :: NodeType -> Bool
isOfValueNodeType (ValueNode _ _) = True
isOfValueNodeType _ = False
-- | Checks if a given node type represents a block node.
isOfBlockNodeType :: NodeType -> Bool
isOfBlockNodeType (BlockNode _) = True
isOfBlockNodeType _ = False
| Checks if a given node type represents a phi node .
isOfPhiNodeType :: NodeType -> Bool
isOfPhiNodeType PhiNode = True
isOfPhiNodeType _ = False
-- | Checks if a given node type represents a state node.
isOfStateNodeType :: NodeType -> Bool
isOfStateNodeType StateNode = True
isOfStateNodeType _ = False
-- | Checks if a given node type represents a copy node.
isOfCopyNodeType :: NodeType -> Bool
isOfCopyNodeType CopyNode = True
isOfCopyNodeType _ = False
-- | Checks if a given edge is a data-flow edge.
isDataFlowEdge :: Edge -> Bool
isDataFlowEdge = isOfDataFlowEdgeType . getEdgeType
-- | Checks if a given edge is a state-flow edge.
isStateFlowEdge :: Edge -> Bool
isStateFlowEdge = isOfStateFlowEdgeType . getEdgeType
-- | Checks if a given edge is a control-flow edge.
isControlFlowEdge :: Edge -> Bool
isControlFlowEdge = isOfControlFlowEdgeType . getEdgeType
-- | Checks if a given edge is a definition edge.
isDefEdge :: Edge -> Bool
isDefEdge = isOfDefEdgeType . getEdgeType
-- | Checks if a given edge type represents a data-flow edge.
isOfDataFlowEdgeType :: EdgeType -> Bool
isOfDataFlowEdgeType DataFlowEdge = True
isOfDataFlowEdgeType _ = False
-- | Checks if a given edge type represents a control-flow edge.
isOfControlFlowEdgeType :: EdgeType -> Bool
isOfControlFlowEdgeType ControlFlowEdge = True
isOfControlFlowEdgeType _ = False
-- | Checks if a given edge type represents a state-flow edge.
isOfStateFlowEdgeType :: EdgeType -> Bool
isOfStateFlowEdgeType StateFlowEdge = True
isOfStateFlowEdgeType _ = False
-- | Checks if a given edge type represents a definition edge.
isOfDefEdgeType :: EdgeType -> Bool
isOfDefEdgeType DefEdge = True
isOfDefEdgeType _ = False
-- | Creates an empty graph.
mkEmpty :: Graph
mkEmpty = Graph { intGraph = I.empty
, intNodeMap = M.empty
, entryBlockNode = Nothing
}
-- | Makes a graph from a list of nodes and edges.
mkGraph :: [Node] -> [Edge] -> Maybe Node -> Graph
mkGraph ns es entry =
Graph { intGraph = I.mkGraph (map fromNode ns) (map fromEdge es)
, intNodeMap = M.fromList $ groupNodesByID ns
, entryBlockNode = entry
}
-- | Gets the next internal node ID which does not already appear in the graph.
getNextIntNodeID :: IntGraph -> I.Node
getNextIntNodeID g =
let existing_nodes = I.nodes g
in if length existing_nodes > 0
then 1 + maximum existing_nodes
else 0
-- | Gets the node ID from a node.
getNodeID :: Node -> NodeID
getNodeID (Node (_, NodeLabel i _)) = i
-- | Gets the node label from a node.
getNodeLabel :: Node -> NodeLabel
getNodeLabel (Node (_, nl)) = nl
-- | Gets the node type from a node.
getNodeType :: Node -> NodeType
getNodeType (Node (_, NodeLabel _ nt)) = nt
-- | Gets the data type from a value node.
getDataTypeOfValueNode :: Node -> D.DataType
getDataTypeOfValueNode n = typeOfValue $ getNodeType n
-- | Gets the operation from a computation node.
getOpOfComputationNode :: Node -> O.CompOp
getOpOfComputationNode n = compOp $ getNodeType n
-- | Gets the internal node ID from a node.
getIntNodeID :: Node -> I.Node
getIntNodeID (Node (nid, _)) = nid
-- | Gets the number of nodes.
getNumNodes :: Graph -> Int
getNumNodes g = length $ getAllNodes g
-- | Gets a list of all nodes.
getAllNodes :: Graph -> [Node]
getAllNodes g = map Node $
I.labNodes $
intGraph g
-- | Deletes a node from the graph. Any edges involving the given node will be
-- removed.
delNode :: Node -> Graph -> Graph
delNode n g =
let new_int_g = I.delNode (getIntNodeID n) (intGraph g)
new_nmap = M.update ( \ns -> let new_ns = filter (/= n) ns
in if not (null new_ns)
then Just new_ns
else Nothing
)
(getNodeID n)
(intNodeMap g)
entry = entryBlockNode g
new_entry = if isJust entry && (fromJust entry) == n
then Nothing
else entry
in Graph { intGraph = new_int_g
, intNodeMap = new_nmap
, entryBlockNode = new_entry
}
-- | Deletes an edge from the graph.
delEdge :: Edge -> Graph -> Graph
delEdge (Edge e) g = g { intGraph = I.delLEdge e (intGraph g) }
-- | Gets a list of nodes with the same node ID.
findNodesWithNodeID :: Graph -> NodeID -> [Node]
findNodesWithNodeID g i =
let ns = M.lookup i (intNodeMap g)
in if isJust ns then fromJust ns else []
-- | Gets a list of value nodes with the same origin.
findValueNodesWithOrigin :: Graph -> String -> [Node]
findValueNodesWithOrigin g o =
let vs = filter isValueNodeWithOrigin $ getAllNodes g
in filter (\v -> o `elem` getOriginOfValueNode v) vs
-- | Gets a list of block nodes with the same block name.
findBlockNodesWithName :: Graph -> BlockName -> [Node]
findBlockNodesWithName g name =
let bs = filter isBlockNode $ getAllNodes g
in filter ((==) name . getNameOfBlockNode) bs
-- | Gets a list of call nodes with the same function name.
findCallNodesWithName :: Graph -> FunctionName -> [Node]
findCallNodesWithName g name =
let bs = filter isCallNode $ getAllNodes g
in filter ((==) name . getNameOfCallNode) bs
-- | Updates the data type of an already existing value node.
updateDataTypeOfValueNode :: D.DataType -> Node -> Graph -> Graph
updateDataTypeOfValueNode new_dt n g =
let nt = getNodeType n
new_nt = nt { typeOfValue = new_dt }
in case nt of (ValueNode {}) -> updateNodeType new_nt n g
_ -> error $ "updateDataTypeOfValueNode: node " ++ show n ++
" is not a value node"
-- | Updates the function name of an already existing call node.
updateNameOfCallNode :: FunctionName -> Node -> Graph -> Graph
updateNameOfCallNode new_name n g =
let nt = getNodeType n
new_nt = nt { nameOfCall = new_name }
in case nt of (CallNode {}) -> updateNodeType new_nt n g
_ -> error $ "updateNameOfCallNode: node " ++ show n ++
" is not a call node"
-- | Adds a new origin to an already existing value node.
addOriginToValueNode :: String -> Node -> Graph -> Graph
addOriginToValueNode new_origin n g =
let nt = getNodeType n
new_nt = nt { originOfValue = (new_origin:originOfValue nt) }
in case nt of (ValueNode {}) -> updateNodeType new_nt n g
_ -> error $ "addOriginToValueNode: node " ++ show n ++
" is not a value node"
-- | Updates the operation of an already existing computation node.
updateOpOfComputationNode :: O.CompOp -> Node -> Graph -> Graph
updateOpOfComputationNode new_op n g =
let nt = getNodeType n
new_nt = nt { compOp = new_op }
in case nt of (ComputationNode {}) -> updateNodeType new_nt n g
_ -> error $ "updateOpOfComputationNode: node " ++ show n ++
" is not a computation node"
-- | Updates the node label of an already existing node.
updateNodeLabel :: NodeLabel -> Node -> Graph -> Graph
updateNodeLabel new_label n g =
let all_nodes_but_n = filter (/= n) (getAllNodes g)
new_n = Node (getIntNodeID n, new_label)
entry = entryBlockNode g
new_entry = if isJust entry && (fromJust entry) == n
then Just new_n
else entry
in mkGraph (new_n:all_nodes_but_n) (getAllEdges g) new_entry
-- | Updates the node type of a node.
updateNodeType :: NodeType -> Node -> Graph -> Graph
updateNodeType new_type n g =
let all_nodes_but_n = filter (/= n) (getAllNodes g)
new_n = Node ( getIntNodeID n
, NodeLabel { nodeID = getNodeID n
, nodeType = new_type
}
)
entry = entryBlockNode g
new_entry = if isJust entry && (fromJust entry) == n
then Just new_n
else entry
in mkGraph (new_n:all_nodes_but_n) (getAllEdges g) new_entry
-- | Updates the node ID of an already existing node.
updateNodeID :: NodeID -> Node -> Graph -> Graph
updateNodeID new_id n g =
let all_nodes_but_n = filter (/= n) (getAllNodes g)
new_n = Node (getIntNodeID n, NodeLabel new_id (getNodeType n))
entry = entryBlockNode g
new_entry = if isJust entry && (fromJust entry) == n
then Just new_n
else entry
in mkGraph (new_n:all_nodes_but_n) (getAllEdges g) new_entry
| Copies the node label from one node to another node . If the two nodes are
-- actually the same node, nothing happens.
copyNodeLabel
:: Node
-- ^ Node to copy label to.
-> Node
-- ^ Node to copy label from.
-> Graph
-> Graph
copyNodeLabel to_n from_n g
| (getIntNodeID from_n) == (getIntNodeID to_n) = g
| otherwise = updateNodeLabel (getNodeLabel from_n) to_n g
| Merges two nodes by redirecting the edges to the node to merge to , and then
removes the merged node . If the two nodes are actually the same node , nothing
happens . Any edges already involving the two nodes will be removed . Edge
-- number invariants between data-flow and definition edges are maintained.
mergeNodes
:: Node
-- ^ Node to merge with (will be kept).
-> Node
-- ^ Node to merge with (will be discarded).
-> Graph
-> Graph
mergeNodes n_to_keep n_to_discard g
| (getIntNodeID n_to_keep) == (getIntNodeID n_to_discard) = g
| otherwise =
let edges_to_ignore = getEdgesBetween g n_to_discard n_to_keep ++
getEdgesBetween g n_to_keep n_to_discard
in delNode n_to_discard
( redirectEdges n_to_keep
n_to_discard
(foldr delEdge g edges_to_ignore)
)
| Redirects all edges involving one node to another node . Edge number
-- invariants between data-flow and definition edges are maintained.
redirectEdges
:: Node
-- ^ Node to redirect edges to.
-> Node
-- ^ Node to redirect edges from.
-> Graph
-> Graph
redirectEdges = redirectEdgesWhen (\_ -> True)
| Redirects all inbound edges to one node to another node .
redirectInEdges
:: Node
-- ^ Node to redirect edges to.
-> Node
-- ^ Node to redirect edges from.
-> Graph
-> Graph
redirectInEdges = redirectInEdgesWhen (\_ -> True)
| Redirects the outbound edges from one node to another . Edge number
-- invariants between data-flow and definition edges are maintained.
redirectOutEdges
:: Node
-- ^ Node to redirect edges to.
-> Node
-- ^ Node to redirect edges from.
-> Graph
-> Graph
redirectOutEdges = redirectOutEdgesWhen (\_ -> True)
-- | Same as 'redirectEdges' but takes a predicate for which edges to redirect.
redirectEdgesWhen
:: (Edge -> Bool)
-- ^ Predicate.
-> Node
-- ^ Node to redirect edges to.
-> Node
-- ^ Node to redirect edges from.
-> Graph
-> Graph
redirectEdgesWhen p to_n from_n g =
redirectInEdgesWhen p to_n from_n $
redirectOutEdgesWhen p to_n from_n g
-- | Same as 'redirectInEdges' but takes a predicate for which edges to
-- redirect.
redirectInEdgesWhen
:: (Edge -> Bool)
-- ^ Predicate.
-> Node
-- ^ Node to redirect edges to.
-> Node
-- ^ Node to redirect edges from.
-> Graph
-> Graph
redirectInEdgesWhen p to_n from_n g0 =
let es = filter p $ getInEdges g0 from_n
df_def_es =
if isValueNode from_n
then map ( \e ->
let df_es = filter ( \e' ->
getEdgeInNr e == getEdgeInNr e'
) $
filter isDataFlowEdge $
es
in if length df_es == 1
then (head df_es, e)
else if length df_es == 0
then error $ "redirectInEdgesWhen: no data-flow " ++
"edge to redirect to redirect that " ++
"matches definition edge " ++ pShow e
else error $ "redirectInEdgesWhen: multiple data-" ++
"flow edges to redirect that " ++
"matches definition edge " ++ pShow e
) $
filter isDefEdge $
es
else []
-- Redirect all edges not related to the definition edges
g1 = foldr (\e g -> fst $ updateEdgeTarget to_n e g) g0 $
filter ( \e -> e `notElem` map fst df_def_es &&
e `notElem` map snd df_def_es
) $
es
-- Redirect data-flow and related definition edge, making sure the edge
-- numbers are consistent
(g2, new_df_es) = foldr ( \e (g, new_es) ->
let (g', e') = updateEdgeTarget to_n e g
in (g', (e':new_es))
)
(g1, []) $
map fst df_def_es
g3 = foldr ( \(df_e, e) g ->
let (g', e') = updateEdgeTarget to_n e g
(g'', _) = updateEdgeInNr (getEdgeInNr df_e) e' g'
in g''
)
g2 $
zip new_df_es $
map snd df_def_es
in g3
-- | Same as 'redirectOutEdges' but takes a predicate for which edges to
-- redirect.
redirectOutEdgesWhen
:: (Edge -> Bool)
-- ^ Predicate.
-> Node
-- ^ Node to redirect edges to.
-> Node
-- ^ Node to redirect edges from.
-> Graph
-> Graph
redirectOutEdgesWhen p to_n from_n g0 =
let es = filter p $ getOutEdges g0 from_n
df_def_es =
if isValueNode from_n
then map ( \e ->
let df_es = filter ( \e' ->
getEdgeOutNr e == getEdgeOutNr e'
) $
filter isDataFlowEdge $
es
in if length df_es == 1
then (head df_es, e)
else if length df_es == 0
then error $ "redirectOutEdgesWhen: no data-flow " ++
"edge that to redirect that matches " ++
"definition edge " ++ pShow e
else error $ "redirectOutEdgesWhen: multiple " ++
"data-flow edges to redirect that " ++
"matches definition edge " ++ pShow e
) $
filter isDefEdge $
es
else []
-- Redirect all edges not related to the definition edges
g1 = foldr (\e g -> fst $ updateEdgeSource to_n e g) g0 $
filter ( \e -> e `notElem` map fst df_def_es &&
e `notElem` map snd df_def_es
) $
es
-- Redirect data-flow and related definition edge, making sure the edge
-- numbers are consistent
(g2, new_df_es) = foldr ( \e (g, new_es) ->
let (g', e') = updateEdgeSource to_n e g
in (g', (e':new_es))
)
(g1, []) $
map fst df_def_es
g3 = foldr ( \(df_e, e) g ->
let (g', e') = updateEdgeSource to_n e g
(g'', _) = updateEdgeOutNr (getEdgeOutNr df_e) e' g'
in g''
)
g2 $
zip new_df_es $
map snd df_def_es
in g3
-- | Updates the target of an edge. The edge-in number is also set to the next,
-- unused edge number.
updateEdgeTarget
:: Node
-- ^ New target.
-> Edge
-- ^ The edge to update.
-> Graph
-> (Graph, Edge)
-- ^ The new graph and the updated edge.
updateEdgeTarget new_trg (Edge e@(src, _, l)) g =
let int_g = intGraph g
new_trg_id = getIntNodeID new_trg
new_e = ( src
, new_trg_id
, l { inEdgeNr = getNextInEdgeNr int_g
new_trg_id
( \e' ->
getEdgeType e' == edgeType l
)
}
)
in ( g { intGraph = I.insEdge new_e (I.delLEdge e int_g) }
, Edge new_e
)
-- | Updates the source of an edge. The edge-out number is also set to the next,
-- unused edge number.
updateEdgeSource
:: Node
-- ^ New source.
-> Edge
-- ^ The edge to update.
-> Graph
-> (Graph, Edge)
-- ^ The new graph and the updated edge.
updateEdgeSource new_src (Edge e@(_, trg, l)) g =
let int_g = intGraph g
new_src_id = getIntNodeID new_src
new_e = ( new_src_id
, trg
, l { outEdgeNr = getNextOutEdgeNr int_g
new_src_id
( \e' ->
getEdgeType e' == edgeType l
)
}
)
in ( g { intGraph = I.insEdge new_e (I.delLEdge e int_g) }
, Edge new_e
)
-- | Updates the in number of an edge.
updateEdgeInNr
:: EdgeNr
-- ^ New number.
-> Edge
-- ^ The edge to update.
-> Graph
-> (Graph, Edge)
-- ^ The new graph and the updated edge.
updateEdgeInNr new_nr e@(Edge (_, _, l)) g =
let new_l = l { inEdgeNr = new_nr }
in updateEdgeLabel new_l e g
-- | Updates the out number of an edge.
updateEdgeOutNr
:: EdgeNr
-- ^ New number.
-> Edge
-- ^ The edge to update.
-> Graph
-> (Graph, Edge)
-- ^ The new graph and the updated edge.
updateEdgeOutNr new_nr e@(Edge (_, _, l)) g =
let new_l = l { outEdgeNr = new_nr }
in updateEdgeLabel new_l e g
-- | Gets the next input edge number to use for a given node, only regarding the
-- edges that pass the user-provided check function. The function can be used to
-- the next edge number for a particular edge type.
getNextInEdgeNr :: IntGraph -> I.Node -> (Edge -> Bool) -> EdgeNr
getNextInEdgeNr g int f =
let existing_numbers = map getEdgeInNr (filter f $ map toEdge (I.inn g int))
in if length existing_numbers > 0
then maximum existing_numbers + 1
else 0
-- | Gets the next output edge number to use for a given node, only regarding
-- the edges that pass the user-provided check function. The function can be
-- used to the next edge number for a particular edge type.
getNextOutEdgeNr :: IntGraph -> I.Node -> (Edge -> Bool) -> EdgeNr
getNextOutEdgeNr g int f =
let existing_numbers = map getEdgeOutNr (filter f $ map toEdge (I.out g int))
in if length existing_numbers > 0
then maximum existing_numbers + 1
else 0
-- | Gets the edge label from an edge.
getEdgeLabel :: Edge -> EdgeLabel
getEdgeLabel (Edge (_, _, l)) = l
-- | Gets the in-edge number component from an edge.
getEdgeInNr :: Edge -> EdgeNr
getEdgeInNr = inEdgeNr . getEdgeLabel
-- | Gets the out-edge number component from an edge.
getEdgeOutNr :: Edge -> EdgeNr
getEdgeOutNr = outEdgeNr . getEdgeLabel
-- | Gets the edge type from an edge.
getEdgeType :: Edge -> EdgeType
getEdgeType = edgeType . getEdgeLabel
-- | Adds a new node of a given node type to a graph, returning both the new
-- graph and the new node.
addNewNode :: NodeType -> Graph -> (Graph, Node)
addNewNode nt g =
let int_g = intGraph g
new_int_id = getNextIntNodeID int_g
new_id = toNodeID new_int_id
new_int_n = (new_int_id, NodeLabel new_id nt)
new_int_g = I.insNode new_int_n int_g
new_n = Node new_int_n
new_nmap = M.alter ( \ns -> if isJust ns
then Just $ (new_n:fromJust ns)
else Just $ [new_n]
)
new_id
(intNodeMap g)
in (g { intGraph = new_int_g, intNodeMap = new_nmap }, new_n)
| Adds a new edge between two nodes to the graph , returning both the new
-- graph and the new edge. The edge numberings will be set accordingly.
addNewEdge :: EdgeType -> (SrcNode, DstNode) -> Graph -> (Graph, Edge)
addNewEdge et (from_n, to_n) g =
let int_g = intGraph g
from_n_id = getIntNodeID from_n
to_n_id = getIntNodeID to_n
out_edge_nr = getNextOutEdgeNr int_g from_n_id (\e -> et == getEdgeType e)
in_edge_nr = getNextInEdgeNr int_g to_n_id (\e -> et == getEdgeType e)
new_e = ( from_n_id
, to_n_id
, EdgeLabel { edgeType = et
, outEdgeNr = out_edge_nr
, inEdgeNr = in_edge_nr
}
)
new_int_g = I.insEdge new_e int_g
in (g { intGraph = new_int_g }, Edge new_e)
| Adds many new edges between two nodes to the graph . The edges will be
-- inserted in the order of the list, and the edge numberings will be set
-- accordingly.
addNewEdges :: EdgeType -> [(SrcNode, DstNode)] -> Graph -> Graph
addNewEdges et ps g = foldl (\g' p -> fst $ addNewEdge et p g') g ps
-- | Adds a new data-flow edge to the graph.
--
-- @see 'addNewEdge'
addNewDtFlowEdge :: (SrcNode, DstNode) -> Graph -> (Graph, Edge)
addNewDtFlowEdge = addNewEdge DataFlowEdge
-- | Adds multiple new data-flow edges to the graph.
--
-- @see 'addNewEdges'
addNewDtFlowEdges :: [(SrcNode, DstNode)] -> Graph -> Graph
addNewDtFlowEdges = addNewEdges DataFlowEdge
-- | Adds a new control-flow edge to the graph.
--
-- @see 'addNewEdge'
addNewCtrlFlowEdge :: (SrcNode, DstNode) -> Graph -> (Graph, Edge)
addNewCtrlFlowEdge = addNewEdge ControlFlowEdge
-- | Adds multiple new control-flow edges to the graph.
--
-- @see 'addNewEdges'
addNewCtrlFlowEdges :: [(SrcNode, DstNode)] -> Graph -> Graph
addNewCtrlFlowEdges = addNewEdges ControlFlowEdge
-- | Adds a new state-flow edge to the graph.
--
-- @see 'addNewEdge'
addNewStFlowEdge :: (SrcNode, DstNode) -> Graph -> (Graph, Edge)
addNewStFlowEdge = addNewEdge StateFlowEdge
-- | Adds multiple new state-flow edges to the graph.
--
-- @see 'addNewEdges'
addNewStFlowEdges :: [(SrcNode, DstNode)] -> Graph -> Graph
addNewStFlowEdges = addNewEdges StateFlowEdge
-- | Adds a new definition edge to the graph.
--
-- @see 'addNewEdge'
addNewDefEdge :: (SrcNode, DstNode) -> Graph -> (Graph, Edge)
addNewDefEdge = addNewEdge DefEdge
-- | Adds multiple new definition edges to the graph.
--
-- @see 'addNewEdges'
addNewDefEdges :: [(SrcNode, DstNode)] -> Graph -> Graph
addNewDefEdges = addNewEdges DefEdge
-- | Inserts a new node along an existing edge in the graph, returning both the
new graph and the new node . The existing edge will be split into two edges
-- which will be connected to the new node. The edge numbers will be retained as
-- appropriate.
insertNewNodeAlongEdge :: NodeType -> Edge -> Graph -> (Graph, Node)
insertNewNodeAlongEdge
nt
e@(Edge (from_nid, to_nid, el))
g0
=
let (g1, new_n) = addNewNode nt g0
g2 = delEdge e g1
et = edgeType el
new_e1 = (from_nid, getIntNodeID new_n, EdgeLabel et (outEdgeNr el) 0)
new_e2 = (getIntNodeID new_n, to_nid, EdgeLabel et 0 (inEdgeNr el))
int_g2 = intGraph g2
int_g3 = I.insEdge new_e2 $
I.insEdge new_e1 int_g2
g3 = g2 { intGraph = int_g3 }
in (g3, new_n)
-- | Updates the edge label of an already existing edge.
updateEdgeLabel
:: EdgeLabel
-> Edge
-> Graph
-> (Graph, Edge)
-- ^ The new graph and the updated edge.
updateEdgeLabel new_label e@(Edge (src, dst, _)) g =
let all_edges_but_e = filter (/= e) (getAllEdges g)
new_e = Edge (src, dst, new_label)
in (mkGraph (getAllNodes g) (new_e:all_edges_but_e) (entryBlockNode g), new_e)
-- | Gets the corresponding node from an internal node ID.
getNodeWithIntNodeID :: IntGraph -> I.Node -> Maybe Node
getNodeWithIntNodeID g nid =
maybe Nothing (\l -> Just (Node (nid, l))) (I.lab g nid)
| Gets the predecessors ( if any ) of a given node . A node @n@ is a predecessor
-- of another node @m@ if there is a directed edge from @m@ to @n@.
getPredecessors :: Graph -> Node -> [Node]
getPredecessors g n =
let int_g = intGraph g
in map (fromJust . getNodeWithIntNodeID int_g) (I.pre int_g (getIntNodeID n))
| Gets the successors ( if any ) of a given node . A node @n@ is a successor of
another node @m@ if there is a directed edge from @n@ to @m@.
getSuccessors :: Graph -> Node -> [Node]
getSuccessors g n =
let int_g = intGraph g
in map (fromJust . getNodeWithIntNodeID int_g) (I.suc int_g (getIntNodeID n))
-- | Gets both the predecessors and successors of a given node.
getNeighbors :: Graph -> Node -> [Node]
getNeighbors g n = getPredecessors g n ++ getSuccessors g n
-- | Checks if a given node is within the graph.
isInGraph :: Graph -> Node -> Bool
isInGraph g n = isJust $ getNodeWithIntNodeID (intGraph g) (getIntNodeID n)
-- | Gets a list of all edges.
getAllEdges :: Graph -> [Edge]
getAllEdges g = map toEdge $ I.labEdges (intGraph g)
-- | Gets all inbound edges (regardless of type) to a particular node.
getInEdges :: Graph -> Node -> [Edge]
getInEdges g n = map toEdge $ I.inn (intGraph g) (getIntNodeID n)
-- | Gets all inbound data-flow edges to a particular node.
getDtFlowInEdges :: Graph -> Node -> [Edge]
getDtFlowInEdges g n = filter isDataFlowEdge $ getInEdges g n
-- | Gets all inbound control-flow edges to a particular node.
getCtrlFlowInEdges :: Graph -> Node -> [Edge]
getCtrlFlowInEdges g n = filter isControlFlowEdge $ getInEdges g n
-- | Gets all inbound state flow edges to a particular node.
getStFlowInEdges :: Graph -> Node -> [Edge]
getStFlowInEdges g n = filter isStateFlowEdge $ getInEdges g n
-- | Gets all inbound definition edges to a particular node.
getDefInEdges :: Graph -> Node -> [Edge]
getDefInEdges g n = filter isDefEdge $ getInEdges g n
-- | Gets all outbound edges (regardless of type) from a particular node.
getOutEdges :: Graph -> Node -> [Edge]
getOutEdges g n = map toEdge $ I.out (intGraph g) (getIntNodeID n)
-- | Gets all outbound data-flow edges to a particular node.
getDtFlowOutEdges :: Graph -> Node -> [Edge]
getDtFlowOutEdges g n = filter isDataFlowEdge $ getOutEdges g n
-- | Gets all outbound control-flow edges to a particular node.
getCtrlFlowOutEdges :: Graph -> Node -> [Edge]
getCtrlFlowOutEdges g n = filter isControlFlowEdge $ getOutEdges g n
-- | Gets all outbound state flow edges to a particular node.
getStFlowOutEdges :: Graph -> Node -> [Edge]
getStFlowOutEdges g n = filter isStateFlowEdge $ getOutEdges g n
-- | Gets all outbound definition edges to a particular node.
getDefOutEdges :: Graph -> Node -> [Edge]
getDefOutEdges g n = filter isDefEdge $ getOutEdges g n
-- | Gets the edges involving a given node.
getEdges :: Graph -> Node -> [Edge]
getEdges g n =
filter (\e -> getSourceNode g e == n || getTargetNode g e == n) $
getAllEdges g
| Gets the edges between two nodes .
getEdgesBetween :: Graph -> SrcNode -> DstNode -> [Edge]
getEdgesBetween g from_n to_n =
let out_edges = map fromEdge $ getOutEdges g from_n
from_id = getIntNodeID from_n
to_id = getIntNodeID to_n
es = map toEdge $
filter (\(n1, n2, _) -> from_id == n1 && to_id == n2) $
out_edges
in es
-- | Sorts a list of edges according to their edge numbers (in increasing
-- order), which are provided by a given function.
sortByEdgeNr :: (Edge -> EdgeNr) -> [Edge] -> [Edge]
sortByEdgeNr f = sortBy (\e1 -> \e2 -> if f e1 < f e2 then LT else GT)
-- | Gets the source node of an edge.
getSourceNode :: Graph -> Edge -> Node
getSourceNode g (Edge (n, _, _)) =
fromJust $ getNodeWithIntNodeID (intGraph g) n
-- | Gets the target node of an edge.
getTargetNode :: Graph -> Edge -> Node
getTargetNode g (Edge (_, n, _)) =
fromJust $ getNodeWithIntNodeID (intGraph g) n
-- | Converts a dominator set of nodes into a dominator set of node IDs.
convertDomSetN2ID :: DomSet Node -> DomSet NodeID
convertDomSetN2ID d =
DomSet { domNode = getNodeID $ domNode d
, domSet = map getNodeID (domSet d)
}
-- | Converts a mapping of nodes into a mapping of node IDs.
convertMappingN2ID :: Mapping Node -> Mapping NodeID
convertMappingN2ID m =
Mapping { fNode = getNodeID $ fNode m
, pNode = getNodeID $ pNode m
}
-- | Converts a match with nodes into a match with node IDs.
convertMatchN2ID :: Match Node -> Match NodeID
convertMatchN2ID m =
let convert k a = M.insert (getNodeID k) (map getNodeID a)
in Match { f2pMaps = M.foldrWithKey convert M.empty (f2pMaps m)
, p2fMaps = M.foldrWithKey convert M.empty (p2fMaps m)
}
| Checks if a node matches another node . Two nodes match if they are of
-- compatible node types and, depending on the node type, they have the same
-- number of edges of a specific edge type.
doNodesMatch
:: Graph
-- ^ The function graph.
-> Graph
-- ^ The pattern graph.
-> Node
-- ^ A node from the function graph.
-> Node
-- ^ A node from the pattern graph.
-> Bool
doNodesMatch fg pg fn pn =
(getNodeType pn) `isNodeTypeCompatibleWith` (getNodeType fn) &&
doNumEdgesMatch fg pg fn pn
-- | Checks if a node type is compatible with another node type. Note that this
-- function is not necessarily commutative.
isNodeTypeCompatibleWith :: NodeType -> NodeType -> Bool
isNodeTypeCompatibleWith (ComputationNode op1) (ComputationNode op2) =
op1 `O.isCompatibleWith` op2
isNodeTypeCompatibleWith (ControlNode op1) (ControlNode op2) =
op1 `O.isCompatibleWith` op2
isNodeTypeCompatibleWith (CallNode {}) (CallNode {}) = True
isNodeTypeCompatibleWith IndirCallNode IndirCallNode = True
isNodeTypeCompatibleWith (ValueNode d1 _) (ValueNode d2 _) =
d1 `D.isCompatibleWith` d2
isNodeTypeCompatibleWith (BlockNode {}) (BlockNode {}) = True
isNodeTypeCompatibleWith PhiNode PhiNode = True
isNodeTypeCompatibleWith StateNode StateNode = True
isNodeTypeCompatibleWith CopyNode CopyNode = True
isNodeTypeCompatibleWith _ _ = False
-- | Checks if a block node is an intermediate block node, meaning that it has
at least one in - edge to a control node , and at least one out - edge to another
-- control node.
isBlockNodeAndIntermediate :: Graph -> Node -> Bool
isBlockNodeAndIntermediate g n
| ( isBlockNode n &&
( not ( isJust (entryBlockNode g) &&
n == fromJust (entryBlockNode g)
)
) &&
(length $ getCtrlFlowInEdges g n) > 0 &&
(length $ getCtrlFlowOutEdges g n) > 0
) = True
| otherwise = False
| Checks if two matching nodes have matching number of edges of particular
-- edge type.
doNumEdgesMatch :: Graph -> Graph -> Node -> Node -> Bool
doNumEdgesMatch fg pg fn pn =
let checkEdges f getENr es1 es2 =
let areEdgeNrsSame e1 e2 = getENr e1 == getENr e2
pruned_es1 = nubBy areEdgeNrsSame $ filter f es1
pruned_es2 = nubBy areEdgeNrsSame $ filter f es2
in length pruned_es1 == length pruned_es2
f_in_es = getInEdges fg fn
p_in_es = getInEdges pg pn
f_out_es = getOutEdges fg fn
p_out_es = getOutEdges pg pn
in checkEdges (\e -> doesNumCFInEdgesMatter pg pn && isControlFlowEdge e)
getEdgeInNr
f_in_es
p_in_es
&&
checkEdges (\e -> doesNumCFOutEdgesMatter pg pn && isControlFlowEdge e)
getEdgeOutNr
f_out_es
p_out_es
&&
checkEdges (\e -> doesNumDFInEdgesMatter pg pn && isDataFlowEdge e)
getEdgeInNr
f_in_es
p_in_es
&&
checkEdges (\e -> doesNumDFOutEdgesMatter pg pn && isDataFlowEdge e)
getEdgeOutNr
f_out_es
p_out_es
&&
checkEdges (\e -> doesNumSFInEdgesMatter pg pn && isStateFlowEdge e)
getEdgeInNr
f_in_es
p_in_es
&&
checkEdges (\e -> doesNumSFOutEdgesMatter pg pn && isStateFlowEdge e)
getEdgeOutNr
f_out_es
p_out_es
-- | Checks if the number of control-flow in-edges matters for a given pattern
-- node.
doesNumCFInEdgesMatter :: Graph -> Node -> Bool
doesNumCFInEdgesMatter g n
| isControlNode n = True
| isBlockNodeAndIntermediate g n = True
| otherwise = False
-- | Checks if the number of control-flow out-edges matters for a given pattern
-- node.
doesNumCFOutEdgesMatter :: Graph -> Node -> Bool
doesNumCFOutEdgesMatter _ n
| isControlNode n = True
| otherwise = False
-- | Checks if the number of data-flow in-edges matters for a given pattern
-- node.
doesNumDFInEdgesMatter :: Graph -> Node -> Bool
doesNumDFInEdgesMatter g n
| isOperationNode n = True
| isValueNode n = (length $ getDtFlowInEdges g n) > 0
| otherwise = False
-- | Checks if the number of data-flow out-edges matters for a given pattern
-- node.
doesNumDFOutEdgesMatter :: Graph -> Node -> Bool
doesNumDFOutEdgesMatter _ n
| isOperationNode n = True
| otherwise = False
-- | Checks if the number of state flow in-edges matters for a given pattern
-- node.
doesNumSFInEdgesMatter :: Graph -> Node -> Bool
doesNumSFInEdgesMatter _ n
| isOperationNode n = True
| otherwise = False
-- | Checks if the number of state flow out-edges matters for a given pattern
-- node.
doesNumSFOutEdgesMatter :: Graph -> Node -> Bool
doesNumSFOutEdgesMatter _ n
| isOperationNode n = True
| otherwise = False
-- | Checks if every edge in a list of edges from the pattern graph has at least
one edge in a list of edges from the function graph with matching edge number
-- (which is retrieved from a predicate function). It is assumed that each edge
-- number in the list from the pattern graph appears at most once.
doEdgeNrsMatch
:: (Edge -> EdgeNr)
-> [Edge]
-- ^ In-edges from the function graph.
-> [Edge]
-- ^ In-edges from the pattern graph.
-> Bool
doEdgeNrsMatch f es1 es2 =
all (\e -> length (filter (\e' -> f e == f e') es1) > 0) es2
-- | Checks if a list of edges from the pattern graph matches a list of edges
-- from the function graph. It is assumed that the source and target nodes are
-- the same for every edge in each list. The lists match if all edges from the
-- pattern graph have a corresponding edge in the list from the function graph
-- (hence it is allowed that the latter list contain edges that have no
-- corresponding edge in the former list).
doEdgeListsMatch
:: Graph
-- ^ The function graph.
-> Graph
-- ^ The pattern graph.
-> [Edge]
-- ^ In-edges from the function graph.
-> [Edge]
-- ^ In-edges from the pattern graph.
-> Bool
doEdgeListsMatch _ _ [] [] = True
doEdgeListsMatch fg pg fes pes =
doInEdgeListsMatch fg pg fes pes && doOutEdgeListsMatch fg pg fes pes
-- | Checks if a list of in-edges from the pattern graph matches list of
-- in-edges from the function graph. It is assumed that the source and target
-- nodes are the same for every edge in each list.
doInEdgeListsMatch
:: Graph
-- ^ The function graph.
-> Graph
-- ^ The pattern graph.
-> [Edge]
-- ^ In-edges from the function graph.
-> [Edge]
-- ^ In-edges from the pattern graph.
-> Bool
doInEdgeListsMatch _ pg fes pes =
let checkEdges f = doEdgeNrsMatch getEdgeInNr (filter f fes) (filter f pes)
pn = getTargetNode pg (head pes)
in (not (doesOrderCFInEdgesMatter pg pn) || checkEdges isControlFlowEdge) &&
(not (doesOrderDFInEdgesMatter pg pn) || checkEdges isDataFlowEdge) &&
(not (doesOrderSFInEdgesMatter pg pn) || checkEdges isStateFlowEdge)
-- | Same as 'doInEdgeListsMatch' but for out-edges.
doOutEdgeListsMatch
:: Graph
-- ^ The function graph.
-> Graph
-- ^ The pattern graph.
-> [Edge]
-- ^ In-edges from the function graph.
-> [Edge]
-- ^ In-edges from the pattern graph.
-> Bool
doOutEdgeListsMatch _ pg fes pes =
let checkEdges f = doEdgeNrsMatch getEdgeOutNr (filter f fes) (filter f pes)
pn = getSourceNode pg (head pes)
in (not (doesOrderCFOutEdgesMatter pg pn) || checkEdges isControlFlowEdge) &&
(not (doesOrderDFOutEdgesMatter pg pn) || checkEdges isDataFlowEdge) &&
(not (doesOrderSFOutEdgesMatter pg pn) || checkEdges isStateFlowEdge)
-- | Checks if the order of control-flow in-edges matters for a given pattern
-- node.
doesOrderCFInEdgesMatter :: Graph -> Node -> Bool
doesOrderCFInEdgesMatter g n
| isBlockNodeAndIntermediate g n = True
| otherwise = False
-- | Checks if the order of control-flow out-edges matters for a given pattern
-- node.
doesOrderCFOutEdgesMatter :: Graph -> Node -> Bool
doesOrderCFOutEdgesMatter _ n
| isControlNode n = True
| otherwise = False
-- | Checks if the order of data-flow in-edges matters for a given pattern
-- node.
doesOrderDFInEdgesMatter :: Graph -> Node -> Bool
doesOrderDFInEdgesMatter _ n
| isComputationNode n = not $ O.isCommutative $ getOpOfComputationNode n
| isOperationNode n = True
| otherwise = False
-- | Checks if the order of data-flow out-edges matters for a given pattern
-- node.
doesOrderDFOutEdgesMatter :: Graph -> Node -> Bool
doesOrderDFOutEdgesMatter _ n
| isOperationNode n = True
| otherwise = False
-- | Checks if the order of state flow in-edges matters for a given pattern
-- node.
doesOrderSFInEdgesMatter :: Graph -> Node -> Bool
doesOrderSFInEdgesMatter _ _ = False
-- | Checks if the order of state flow out-edges matters for a given pattern
-- node.
doesOrderSFOutEdgesMatter :: Graph -> Node -> Bool
doesOrderSFOutEdgesMatter _ _ = False
| If the pattern contains phi nodes , check that there is a matching
definition edge for each value - phi and phi - value edge .
customPatternMatchingSemanticsCheck
:: Graph
-- ^ The function graph.
-> Graph
-- ^ The pattern graph.
-> [Mapping Node]
-- ^ Current mapping state.
-> Mapping Node
-- ^ Candidate mapping.
-> Bool
customPatternMatchingSemanticsCheck fg pg st c =
let pn = pNode c
in if isPhiNode pn
then let es = filter isDataFlowEdge $ getInEdges pg pn
val_es = filter (isValueNode . getSourceNode pg) es
in all (checkPhiValBlockMappings fg pg (c:st)) val_es
else if isValueNode pn
then let es = filter isDataFlowEdge $ getOutEdges pg pn
phi_es = filter (isPhiNode . getTargetNode pg) es
in all (checkPhiValBlockMappings fg pg (c:st)) phi_es
else if isBlockNode pn
then let es = filter isDefEdge $ getInEdges pg pn
v_ns = map (getSourceNode pg) es
in all ( \n ->
let es' = filter isDataFlowEdge $ getOutEdges pg n
phi_es = filter (isPhiNode . getTargetNode pg) es'
in all (checkPhiValBlockMappings fg pg (c:st)) phi_es
) v_ns
else True
| For a given data - flow edge between a phi node and a value node in the
-- pattern graph, check that the function graph has a matching definition edge.
checkPhiValBlockMappings
:: Graph
-- ^ The function graph.
-> Graph
-- ^ The pattern graph.
-> [Mapping Node]
-- ^ Current mapping state together with the candidate mapping.
-> Edge
^ The pattern data - flow edge between the phi node and the value node to
-- check.
-> Bool
checkPhiValBlockMappings fg pg st pe =
let findSingleFNInSt pn =
let n = findFNInMapping st pn
in if length n == 1
then Just $ head n
else if length n == 0
then Nothing
else error $ "checkPhiValBlockMappings: multiple mappings " ++
"for pattern node " ++ show pn
v_pn = getSourceNode pg pe
v_fn = findSingleFNInSt v_pn
p_pn = getTargetNode pg pe
p_fn = findSingleFNInSt p_pn
def_pes = filter (haveSameOutEdgeNrs pe) $
filter isDefEdge $
getOutEdges pg v_pn
def_pe = if length def_pes == 1
then head def_pes
else if length def_pes == 0
then error $ "checkPhiValBlockMappings: data-flow edge " ++
show pe ++ " in pattern graph has no " ++
" matching definition edge"
else error $ "checkPhiValBlockMappings: data-flow edge " ++
show pe ++ " in pattern graph has more " ++
"than one matching definition edge"
b_pn = getTargetNode pg def_pe
b_fn = findSingleFNInSt b_pn
in if isJust p_fn && isJust v_fn && isJust b_fn
-- Check if all necessary nodes have been mapped
then let df_fes = filter isDataFlowEdge $
getEdgesBetween fg (fromJust v_fn) (fromJust p_fn)
hasMatchingDefEdge fe =
let def_fes = filter (haveSameOutEdgeNrs fe) $
filter isDefEdge $
getOutEdges fg (getSourceNode fg fe)
in if length def_fes == 1
then getTargetNode fg (head def_fes) == fromJust b_fn
else False
in any hasMatchingDefEdge df_fes
else True
| Checks if two in - edges are equivalent , meaning they must be of the same
-- edge type, have target nodes with the same node ID, and have the same in-edge
-- numbers.
areInEdgesEquivalent
:: Graph
-- ^ The graph to which the edges belong.
-> Edge
-> Edge
-> Bool
areInEdgesEquivalent g e1 e2 =
getEdgeType e1 == getEdgeType e2 &&
(getNodeID $ getTargetNode g e1) == (getNodeID $ getTargetNode g e2) &&
getEdgeInNr e1 == getEdgeInNr e2
| Checks if two out - edges are equivalent , meaning they must be of the same
-- edge type, have source nodes with the same node ID, and have the same
-- out-edge numbers.
areOutEdgesEquivalent
:: Graph
-- ^ The graph to which the edges belong.
-> Edge
-> Edge
-> Bool
areOutEdgesEquivalent g e1 e2 =
getEdgeType e1 == getEdgeType e2 &&
(getNodeID $ getSourceNode g e1) == (getNodeID $ getSourceNode g e2) &&
getEdgeOutNr e1 == getEdgeOutNr e2
-- | Same as 'findPNsInMapping'.
findPNsInMatch
:: (Eq n, Ord n)
=> Match n
-- ^ The match.
-> [n]
-- ^ List of function nodes.
-> [[n]]
-- ^ List of corresponding pattern nodes.
findPNsInMatch m ns = map (findPNInMatch m) ns
-- | Same as 'findFNsInMapping'.
findFNsInMatch
:: (Eq n, Ord n)
=> Match n
-- ^ The match.
-> [n]
-- ^ List of pattern nodes.
-> [[n]]
-- ^ List of corresponding function nodes.
findFNsInMatch m ns = map (findFNInMatch m) ns
-- | Same as 'findPNInMapping'.
findPNInMatch
:: (Eq n, Ord n)
=> Match n
-- ^ The current mapping state.
-> n
-- ^ Function node.
-> [n]
-- ^ Corresponding pattern nodes.
findPNInMatch m fn = M.findWithDefault [] fn (f2pMaps m)
-- | Same as 'findFNInMapping'.
findFNInMatch
:: (Eq n, Ord n)
=> Match n
-- ^ The current mapping state.
-> n
-- ^ Pattern node.
-> [n]
-- ^ Corresponding function nodes.
findFNInMatch m pn = M.findWithDefault [] pn (p2fMaps m)
-- | From a match and a list of function nodes, get the list of corresponding
-- pattern nodes for which there exists a mapping. The order of the list will be
-- conserved.
findPNsInMapping
:: (Eq n)
=> [Mapping n]
-- ^ The current mapping state.
-> [n]
-- ^ List of function nodes.
-> [[n]]
-- ^ List of corresponding pattern nodes.
findPNsInMapping m fns = map (findPNInMapping m) fns
-- | From a match and a list of pattern nodes, get the list of corresponding
-- function nodes for which there exists a mapping. The order of the list will
-- be conserved.
findFNsInMapping
:: (Eq n)
=> [Mapping n]
-- ^ The current mapping state.
-> [n]
-- ^ List of pattern nodes.
-> [[n]]
-- ^ List of corresponding function nodes.
findFNsInMapping m pns = map (findFNInMapping m) pns
-- | From a mapping state and a function node, get the corresponding pattern
-- nodes if there exist such mappings.
findPNInMapping
:: (Eq n)
=> [Mapping n]
-- ^ The current mapping state.
-> n
-- ^ Function node.
-> [n]
-- ^ Corresponding pattern nodes.
findPNInMapping st fn = [ pNode m | m <- st, fn == fNode m ]
-- | From a mapping state and a pattern node, get the corresponding function
-- nodes if there exist such mappings.
findFNInMapping
:: (Eq n)
=> [Mapping n]
-- ^ The current mapping state.
-> n
-- ^ Pattern node.
-> [n]
-- ^ Corresponding function nodes.
findFNInMapping st pn = [ fNode m | m <- st, pn == pNode m ]
-- | Computes the dominator sets for a given graph and root node.
computeDomSets :: Graph -> Node -> [DomSet Node]
computeDomSets g n =
let int_g = intGraph g
mkNode = fromJust . getNodeWithIntNodeID int_g
doms = map ( \(n1, ns2) -> DomSet { domNode = mkNode n1
, domSet = map mkNode ns2
}
)
(I.dom int_g (getIntNodeID n))
in doms
-- | Checks whether the given graph is empty. A graph is empty if it contains no
-- nodes.
isGraphEmpty :: Graph -> Bool
isGraphEmpty = I.isEmpty . intGraph
-- | Extracts the control-flow graph from a graph. If there are no block nodes
-- in the graph, an empty graph is returned.
extractCFG :: Graph -> Graph
extractCFG g =
let nodes_to_remove = filter (\n -> not (isBlockNode n || isControlNode n)) $
getAllNodes g
cfg_with_ctrl_nodes = foldr delNode g nodes_to_remove
cfg = foldr delNodeKeepEdges
cfg_with_ctrl_nodes
(filter isControlNode $ getAllNodes cfg_with_ctrl_nodes)
in cfg
-- | Extracts the SSA graph (including nodes which represent data) from a
-- graph. If there are no operation nodes in the graph, an empty graph is
-- returned.
extractSSAG :: Graph -> Graph
extractSSAG g =
let nodes_to_remove =
filter ( \n -> not (isOperationNode n || isDatumNode n) ||
(isControlNode n && not (isRetControlNode n))
) $
getAllNodes g
ssa = foldr delNode g nodes_to_remove
in ssa
-- | Deletes a node from the graph, and redirects any edges involving the given
-- node such that all outbound edges will become outbound edges of the node's
-- parent. It is assumed the graph has at most one predecessor of the node to
remove ( if there are more than one predecessor then the edges will be
redirected to one of them , but it is undefined which ) .
delNodeKeepEdges :: Node -> Graph -> Graph
delNodeKeepEdges n g =
let preds = getPredecessors g n
in if length preds > 0
then mergeNodes (head preds) n g
else delNode n g
-- | Gets the root from a control-flow graph. If there is no root, 'Nothing' is
returned . If there is more than one root , an error is produced .
rootInCFG :: Graph -> Maybe Node
rootInCFG g =
let roots = filter (\n -> length (getPredecessors g n) == 0) (getAllNodes g)
in if length roots > 0
then if length roots == 1
then Just $ head roots
else error "More than one root in CFG"
else Nothing
-- | Checks if a given node has any predecessors.
hasAnyPredecessors :: Graph -> Node -> Bool
hasAnyPredecessors g n = length (getPredecessors g n) > 0
-- | Checks if a given node has any successors.
hasAnySuccessors :: Graph -> Node -> Bool
hasAnySuccessors g n = length (getSuccessors g n) > 0
-- | Converts a list of mappings to a match.
toMatch :: Ord n => [Mapping n] -> Match n
toMatch ms =
let insert (n1, n2) m = M.insertWith (++) n1 [n2] m
in Match { f2pMaps = foldr insert M.empty $
map (\m -> (fNode m, pNode m)) ms
, p2fMaps = foldr insert M.empty $
map (\m -> (pNode m, fNode m)) ms
}
-- | Converts a match to a list of mappings.
fromMatch :: Ord n => Match n -> [Mapping n]
fromMatch m =
M.foldrWithKey
(\fn pns ms -> (ms ++ map (\pn -> Mapping { fNode = fn, pNode = pn }) pns))
[]
(f2pMaps m)
-- | Gives the subgraph induced by a given list of nodes
subGraph :: Graph -> [Node] -> Graph
subGraph g ns =
let sns = filter (\n -> n `elem` ns) $ getAllNodes g
ses = filter ( \e -> getSourceNode g e `elem` ns &&
getTargetNode g e `elem` ns
) $
getAllEdges g
entry = entryBlockNode g
new_entry = if isJust entry && (fromJust entry) `elem` sns
then entry
else Nothing
in mkGraph sns ses new_entry
| Checks if two edges have the same in - edge numbers .
haveSameInEdgeNrs :: Edge -> Edge -> Bool
haveSameInEdgeNrs e1 e2 = getEdgeInNr e1 == getEdgeInNr e2
| Checks if two edges have the same out - edge numbers .
haveSameOutEdgeNrs :: Edge -> Edge -> Bool
haveSameOutEdgeNrs e1 e2 = getEdgeOutNr e1 == getEdgeOutNr e2
-- | Groups a list of nodes into groups according to their node IDs.
groupNodesByID :: [Node] -> [(NodeID, [Node])]
groupNodesByID ns =
let ns_by_id = groupBy (\n1 n2 -> getNodeID n1 == getNodeID n2) ns
in map (\ns' -> (getNodeID $ head ns', ns')) ns_by_id
-- | Returns the definition edges with matching edge-in number as the given
-- edge.
findDefEdgeOfDtInEdge :: Graph -> Edge -> [Edge]
findDefEdgeOfDtInEdge g e =
let v = getTargetNode g e
nr = getEdgeInNr e
def_es = filter (\e' -> getEdgeInNr e' == nr) $
getDefInEdges g v
in def_es
-- | Returns the definition edges with matching edge-out number as the given
-- edge.
findDefEdgeOfDtOutEdge :: Graph -> Edge -> [Edge]
findDefEdgeOfDtOutEdge g e =
let v = getSourceNode g e
nr = getEdgeOutNr e
def_es = filter (\e' -> getEdgeOutNr e' == nr) $
getDefOutEdges g v
in def_es
-- | Removes a function node from a given 'Match'.
delFNodeInMatch :: (Eq n, Ord n) => n -> Match n -> Match n
delFNodeInMatch fn m =
let pns = M.findWithDefault [] fn (f2pMaps m)
new_f2p_maps = M.delete fn (f2pMaps m)
new_p2f_maps = foldr (\pn m' -> M.update (Just . filter (/= fn)) pn m')
(p2fMaps m)
pns
in Match { f2pMaps = new_f2p_maps, p2fMaps = new_p2f_maps }
-- | Removes a pattern node from a given 'Match'.
delPNodeInMatch :: (Eq n, Ord n) => n -> Match n -> Match n
delPNodeInMatch pn m =
let fns = M.findWithDefault [] pn (p2fMaps m)
new_p2f_maps = M.delete pn (p2fMaps m)
new_f2p_maps = foldr (\fn m' -> M.update (Just . filter (/= pn)) fn m')
(f2pMaps m)
fns
in Match { f2pMaps = new_f2p_maps, p2fMaps = new_p2f_maps }
-- | Merges a list of matches into a single match. If there is an overlap in the
-- mappings, then the mapping lists are simply concatenated.
mergeMatches :: (Eq n, Ord n) => [Match n] -> Match n
mergeMatches [] = error "mergeMatches: empty list"
mergeMatches ms =
let new_f2p_maps = M.unionsWith (++) $ map f2pMaps ms
new_p2f_maps = M.unionsWith (++) $ map p2fMaps ms
in Match { f2pMaps = new_f2p_maps, p2fMaps = new_p2f_maps }
-- | Adds a new mapping to the given match.
addMappingToMatch :: (Eq n, Ord n) => Mapping n -> Match n -> Match n
addMappingToMatch m match =
let fn = fNode m
pn = pNode m
new_f2p_maps = M.insertWith (++) fn [pn] $ f2pMaps match
new_p2f_maps = M.insertWith (++) pn [fn] $ p2fMaps match
in Match { f2pMaps = new_f2p_maps, p2fMaps = new_p2f_maps }
-- | Replaces a function node in the given match with another function node.
updateFNodeInMatch
:: (Eq n, Ord n)
=> n
-- ^ Old node.
-> n
-- ^ New node.
-> Match n
-> Match n
updateFNodeInMatch old_fn new_fn match =
let f2p_maps0 = f2pMaps match
(maybe_pns, f2p_maps1) = M.updateLookupWithKey (\_ _ -> Nothing)
old_fn
f2p_maps0
Do a lookup and delete in one go
pns = maybe [] id maybe_pns
f2p_maps2 = M.insert new_fn pns f2p_maps1
p2f_maps0 = p2fMaps match
p2f_maps1 = foldr (M.adjust (\pns' -> (new_fn:filter (/= old_fn) pns')))
p2f_maps0
pns
in Match { f2pMaps = f2p_maps2, p2fMaps = p2f_maps1 }
-- | Replaces a pattern node in the given match with another pattern node.
updatePNodeInMatch
:: (Eq n, Ord n)
=> n
-- ^ Old node.
-> n
-- ^ New node.
-> Match n
-> Match n
updatePNodeInMatch old_pn new_pn match =
let p2f_maps0 = p2fMaps match
(maybe_fns, p2f_maps1) = M.updateLookupWithKey (\_ _ -> Nothing)
old_pn
p2f_maps0
Do a lookup and delete in one go
fns = maybe [] id maybe_fns
p2f_maps2 = M.insert new_pn fns p2f_maps1
f2p_maps0 = f2pMaps match
f2p_maps1 = foldr (M.adjust (\fns' -> (new_pn:filter (/= old_pn) fns')))
f2p_maps0
fns
in Match { f2pMaps = f2p_maps1, p2fMaps = p2f_maps2 }
-- | Gets all sets of copy-related values. A value is copy-related to another
-- value if both are copies of the same other value.
getCopyRelatedValues :: Graph -> [[Node]]
getCopyRelatedValues g =
let v_ns = filter isValueNode $ getAllNodes g
copy_related_vs = filter ((> 1) . length) $
concat $
map ( groupBy ( \v1 v2 -> getDataTypeOfValueNode v1 ==
getDataTypeOfValueNode v2
)
) $
map (getCopiesOfValue g) v_ns
in copy_related_vs
-- | Given a graph and value node, returns all value nodes that are copies of
-- the given value node.
getCopiesOfValue :: Graph -> Node -> [Node]
getCopiesOfValue g n =
let es = getDtFlowOutEdges g n
copies = filter isCopyNode $ map (getTargetNode g) es
cp_vs = map ( \n' ->
let es' = getDtFlowOutEdges g n'
in if length es' == 1
then getTargetNode g (head es')
else if length es' == 0
then error $
"getCopiesOfValue: " ++ show n' ++
" has no data-flow edges"
else error $
"getCopiesOfValue: " ++ show n' ++
" has multiple data-flow edges"
) $
copies
in cp_vs
| null |
https://raw.githubusercontent.com/unison-code/uni-instr-sel/2edb2f3399ea43e75f33706261bd6b93bedc6762/hlib/instr-sel/Language/InstrSel/Graphs/Base.hs
|
haskell
|
------------
Data types
------------
| Alias for the internal graph representation.
| The outer-most data type which contains the graph itself. It also caches
all nodes in a map with node IDs as keys for efficient access.
| Represents a distinct node.
| A synonym for indicating the source node of an edge.
| A synonym for indicating the destination node of an edge.
| Node label, consisting of an ID that can be shared by multiple nodes (thus
representing that they are actually the same node) and node information which
denotes the type of node and other auxiliary information.
| The node type information.
| An indirect call to a function whose address is provided through a
value node.
| Temporary and constant nodes (appearing in IR and pattern code), as
well as register and immediate nodes (appearing only in pattern code),
are the constraints applied to it.
^ If the value node represents a particular temporary or variable or
which is specified in the source code, then the name of that item can
be given here as a string. A value node is allowed to have any number
in the list.
| Represents a distinct edge.
| Data type for determining the edge type.
| Edge number, used for ordering edges.
^ The mapped node appearing in the function graph.
^ The mapped node appearing in the pattern graph.
| Represents a match between a function graph and a pattern graph. Note that
it is allowed that a node in the pattern graph may be mapped to multiple
nodes in the function graph, and vice versa.
function nodes to pattern nodes, and another as mappings from pattern nodes
to function nodes.
^ Mappings from function nodes to pattern nodes.
^ Mappings from pattern nodes to function nodes.
| Represents a dominator set.
^ The item that this dominator set concerns.
^ The items that dominate this item.
-----------------------------------
JSON-related type class instances
-----------------------------------
--------------------------------------
These are needed to be able to time
how long it takes to produce the
matchsets
--------------------------------------
-----------
Functions
-----------
| Checks if a given node is an operation.
| Checks if a given node is a datum.
| Checks if a node exists inside a graph.
| Checks if a given node is a computation node.
| Checks if a given node is a control node.
| Checks if a given node is a call node.
| Checks if a given node is an indirect-call node.
| Checks if a given node is a return control node.
| Checks if a given node is an unconditional-branch control node.
| Checks if a given node is an conditional-branch control node.
| Checks if a given node is a value node.
| Checks if a given node is a value node representing a constant value.
| Checks if a given node is a value node representing a pointer.
| Checks if a given node is a value node whose value has an origin (name) in
the source code.
| Gets the origin of a given value node. Note that a value may have more
than one origin.
| Gets the name of a given block node.
| Gets the name of a given call node.
| Checks if a given node is a block node.
| Checks if a given node is a state node.
| Checks if a given node is a copy node.
| Checks if a given node type represents a computation node.
| Checks if a given node type represents a call node.
| Checks if a given node type represents an indirect-call node.
| Checks if a given node type represents a control node.
| Checks if a given node type represents a value node.
| Checks if a given node type represents a block node.
| Checks if a given node type represents a state node.
| Checks if a given node type represents a copy node.
| Checks if a given edge is a data-flow edge.
| Checks if a given edge is a state-flow edge.
| Checks if a given edge is a control-flow edge.
| Checks if a given edge is a definition edge.
| Checks if a given edge type represents a data-flow edge.
| Checks if a given edge type represents a control-flow edge.
| Checks if a given edge type represents a state-flow edge.
| Checks if a given edge type represents a definition edge.
| Creates an empty graph.
| Makes a graph from a list of nodes and edges.
| Gets the next internal node ID which does not already appear in the graph.
| Gets the node ID from a node.
| Gets the node label from a node.
| Gets the node type from a node.
| Gets the data type from a value node.
| Gets the operation from a computation node.
| Gets the internal node ID from a node.
| Gets the number of nodes.
| Gets a list of all nodes.
| Deletes a node from the graph. Any edges involving the given node will be
removed.
| Deletes an edge from the graph.
| Gets a list of nodes with the same node ID.
| Gets a list of value nodes with the same origin.
| Gets a list of block nodes with the same block name.
| Gets a list of call nodes with the same function name.
| Updates the data type of an already existing value node.
| Updates the function name of an already existing call node.
| Adds a new origin to an already existing value node.
| Updates the operation of an already existing computation node.
| Updates the node label of an already existing node.
| Updates the node type of a node.
| Updates the node ID of an already existing node.
actually the same node, nothing happens.
^ Node to copy label to.
^ Node to copy label from.
number invariants between data-flow and definition edges are maintained.
^ Node to merge with (will be kept).
^ Node to merge with (will be discarded).
invariants between data-flow and definition edges are maintained.
^ Node to redirect edges to.
^ Node to redirect edges from.
^ Node to redirect edges to.
^ Node to redirect edges from.
invariants between data-flow and definition edges are maintained.
^ Node to redirect edges to.
^ Node to redirect edges from.
| Same as 'redirectEdges' but takes a predicate for which edges to redirect.
^ Predicate.
^ Node to redirect edges to.
^ Node to redirect edges from.
| Same as 'redirectInEdges' but takes a predicate for which edges to
redirect.
^ Predicate.
^ Node to redirect edges to.
^ Node to redirect edges from.
Redirect all edges not related to the definition edges
Redirect data-flow and related definition edge, making sure the edge
numbers are consistent
| Same as 'redirectOutEdges' but takes a predicate for which edges to
redirect.
^ Predicate.
^ Node to redirect edges to.
^ Node to redirect edges from.
Redirect all edges not related to the definition edges
Redirect data-flow and related definition edge, making sure the edge
numbers are consistent
| Updates the target of an edge. The edge-in number is also set to the next,
unused edge number.
^ New target.
^ The edge to update.
^ The new graph and the updated edge.
| Updates the source of an edge. The edge-out number is also set to the next,
unused edge number.
^ New source.
^ The edge to update.
^ The new graph and the updated edge.
| Updates the in number of an edge.
^ New number.
^ The edge to update.
^ The new graph and the updated edge.
| Updates the out number of an edge.
^ New number.
^ The edge to update.
^ The new graph and the updated edge.
| Gets the next input edge number to use for a given node, only regarding the
edges that pass the user-provided check function. The function can be used to
the next edge number for a particular edge type.
| Gets the next output edge number to use for a given node, only regarding
the edges that pass the user-provided check function. The function can be
used to the next edge number for a particular edge type.
| Gets the edge label from an edge.
| Gets the in-edge number component from an edge.
| Gets the out-edge number component from an edge.
| Gets the edge type from an edge.
| Adds a new node of a given node type to a graph, returning both the new
graph and the new node.
graph and the new edge. The edge numberings will be set accordingly.
inserted in the order of the list, and the edge numberings will be set
accordingly.
| Adds a new data-flow edge to the graph.
@see 'addNewEdge'
| Adds multiple new data-flow edges to the graph.
@see 'addNewEdges'
| Adds a new control-flow edge to the graph.
@see 'addNewEdge'
| Adds multiple new control-flow edges to the graph.
@see 'addNewEdges'
| Adds a new state-flow edge to the graph.
@see 'addNewEdge'
| Adds multiple new state-flow edges to the graph.
@see 'addNewEdges'
| Adds a new definition edge to the graph.
@see 'addNewEdge'
| Adds multiple new definition edges to the graph.
@see 'addNewEdges'
| Inserts a new node along an existing edge in the graph, returning both the
which will be connected to the new node. The edge numbers will be retained as
appropriate.
| Updates the edge label of an already existing edge.
^ The new graph and the updated edge.
| Gets the corresponding node from an internal node ID.
of another node @m@ if there is a directed edge from @m@ to @n@.
| Gets both the predecessors and successors of a given node.
| Checks if a given node is within the graph.
| Gets a list of all edges.
| Gets all inbound edges (regardless of type) to a particular node.
| Gets all inbound data-flow edges to a particular node.
| Gets all inbound control-flow edges to a particular node.
| Gets all inbound state flow edges to a particular node.
| Gets all inbound definition edges to a particular node.
| Gets all outbound edges (regardless of type) from a particular node.
| Gets all outbound data-flow edges to a particular node.
| Gets all outbound control-flow edges to a particular node.
| Gets all outbound state flow edges to a particular node.
| Gets all outbound definition edges to a particular node.
| Gets the edges involving a given node.
| Sorts a list of edges according to their edge numbers (in increasing
order), which are provided by a given function.
| Gets the source node of an edge.
| Gets the target node of an edge.
| Converts a dominator set of nodes into a dominator set of node IDs.
| Converts a mapping of nodes into a mapping of node IDs.
| Converts a match with nodes into a match with node IDs.
compatible node types and, depending on the node type, they have the same
number of edges of a specific edge type.
^ The function graph.
^ The pattern graph.
^ A node from the function graph.
^ A node from the pattern graph.
| Checks if a node type is compatible with another node type. Note that this
function is not necessarily commutative.
| Checks if a block node is an intermediate block node, meaning that it has
control node.
edge type.
| Checks if the number of control-flow in-edges matters for a given pattern
node.
| Checks if the number of control-flow out-edges matters for a given pattern
node.
| Checks if the number of data-flow in-edges matters for a given pattern
node.
| Checks if the number of data-flow out-edges matters for a given pattern
node.
| Checks if the number of state flow in-edges matters for a given pattern
node.
| Checks if the number of state flow out-edges matters for a given pattern
node.
| Checks if every edge in a list of edges from the pattern graph has at least
(which is retrieved from a predicate function). It is assumed that each edge
number in the list from the pattern graph appears at most once.
^ In-edges from the function graph.
^ In-edges from the pattern graph.
| Checks if a list of edges from the pattern graph matches a list of edges
from the function graph. It is assumed that the source and target nodes are
the same for every edge in each list. The lists match if all edges from the
pattern graph have a corresponding edge in the list from the function graph
(hence it is allowed that the latter list contain edges that have no
corresponding edge in the former list).
^ The function graph.
^ The pattern graph.
^ In-edges from the function graph.
^ In-edges from the pattern graph.
| Checks if a list of in-edges from the pattern graph matches list of
in-edges from the function graph. It is assumed that the source and target
nodes are the same for every edge in each list.
^ The function graph.
^ The pattern graph.
^ In-edges from the function graph.
^ In-edges from the pattern graph.
| Same as 'doInEdgeListsMatch' but for out-edges.
^ The function graph.
^ The pattern graph.
^ In-edges from the function graph.
^ In-edges from the pattern graph.
| Checks if the order of control-flow in-edges matters for a given pattern
node.
| Checks if the order of control-flow out-edges matters for a given pattern
node.
| Checks if the order of data-flow in-edges matters for a given pattern
node.
| Checks if the order of data-flow out-edges matters for a given pattern
node.
| Checks if the order of state flow in-edges matters for a given pattern
node.
| Checks if the order of state flow out-edges matters for a given pattern
node.
^ The function graph.
^ The pattern graph.
^ Current mapping state.
^ Candidate mapping.
pattern graph, check that the function graph has a matching definition edge.
^ The function graph.
^ The pattern graph.
^ Current mapping state together with the candidate mapping.
check.
Check if all necessary nodes have been mapped
edge type, have target nodes with the same node ID, and have the same in-edge
numbers.
^ The graph to which the edges belong.
edge type, have source nodes with the same node ID, and have the same
out-edge numbers.
^ The graph to which the edges belong.
| Same as 'findPNsInMapping'.
^ The match.
^ List of function nodes.
^ List of corresponding pattern nodes.
| Same as 'findFNsInMapping'.
^ The match.
^ List of pattern nodes.
^ List of corresponding function nodes.
| Same as 'findPNInMapping'.
^ The current mapping state.
^ Function node.
^ Corresponding pattern nodes.
| Same as 'findFNInMapping'.
^ The current mapping state.
^ Pattern node.
^ Corresponding function nodes.
| From a match and a list of function nodes, get the list of corresponding
pattern nodes for which there exists a mapping. The order of the list will be
conserved.
^ The current mapping state.
^ List of function nodes.
^ List of corresponding pattern nodes.
| From a match and a list of pattern nodes, get the list of corresponding
function nodes for which there exists a mapping. The order of the list will
be conserved.
^ The current mapping state.
^ List of pattern nodes.
^ List of corresponding function nodes.
| From a mapping state and a function node, get the corresponding pattern
nodes if there exist such mappings.
^ The current mapping state.
^ Function node.
^ Corresponding pattern nodes.
| From a mapping state and a pattern node, get the corresponding function
nodes if there exist such mappings.
^ The current mapping state.
^ Pattern node.
^ Corresponding function nodes.
| Computes the dominator sets for a given graph and root node.
| Checks whether the given graph is empty. A graph is empty if it contains no
nodes.
| Extracts the control-flow graph from a graph. If there are no block nodes
in the graph, an empty graph is returned.
| Extracts the SSA graph (including nodes which represent data) from a
graph. If there are no operation nodes in the graph, an empty graph is
returned.
| Deletes a node from the graph, and redirects any edges involving the given
node such that all outbound edges will become outbound edges of the node's
parent. It is assumed the graph has at most one predecessor of the node to
| Gets the root from a control-flow graph. If there is no root, 'Nothing' is
| Checks if a given node has any predecessors.
| Checks if a given node has any successors.
| Converts a list of mappings to a match.
| Converts a match to a list of mappings.
| Gives the subgraph induced by a given list of nodes
| Groups a list of nodes into groups according to their node IDs.
| Returns the definition edges with matching edge-in number as the given
edge.
| Returns the definition edges with matching edge-out number as the given
edge.
| Removes a function node from a given 'Match'.
| Removes a pattern node from a given 'Match'.
| Merges a list of matches into a single match. If there is an overlap in the
mappings, then the mapping lists are simply concatenated.
| Adds a new mapping to the given match.
| Replaces a function node in the given match with another function node.
^ Old node.
^ New node.
| Replaces a pattern node in the given match with another pattern node.
^ Old node.
^ New node.
| Gets all sets of copy-related values. A value is copy-related to another
value if both are copies of the same other value.
| Given a graph and value node, returns all value nodes that are copies of
the given value node.
|
|
Copyright : Copyright ( c ) 2012 - 2017 , < >
License : BSD3 ( see the LICENSE file )
Maintainer :
Copyright : Copyright (c) 2012-2017, Gabriel Hjort Blindell <>
License : BSD3 (see the LICENSE file)
Maintainer :
-}
Main authors :
< >
Main authors:
Gabriel Hjort Blindell <>
-}
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE OverloadedStrings , FlexibleInstances #
module Language.InstrSel.Graphs.Base
( DomSet (..)
, DstNode
, Edge (..)
, EdgeLabel (..)
, EdgeType (..)
, EdgeNr (..)
, Graph (..)
, IntGraph
, Mapping (..)
, Match (..)
, Node (..)
, NodeLabel (..)
, NodeType (..)
, SrcNode
, addMappingToMatch
, addNewEdge
, addNewEdges
, addNewCtrlFlowEdge
, addNewCtrlFlowEdges
, addNewDtFlowEdge
, addNewDtFlowEdges
, addNewDefEdge
, addNewDefEdges
, addNewStFlowEdge
, addNewStFlowEdges
, addNewNode
, addOriginToValueNode
, areInEdgesEquivalent
, areOutEdgesEquivalent
, computeDomSets
, convertDomSetN2ID
, convertMappingN2ID
, convertMatchN2ID
, copyNodeLabel
, customPatternMatchingSemanticsCheck
, delEdge
, delNode
, delFNodeInMatch
, delNodeKeepEdges
, delPNodeInMatch
, doEdgeListsMatch
, doNodesMatch
, extractCFG
, extractSSAG
, findFNInMapping
, findFNInMatch
, findFNsInMapping
, findFNsInMatch
, findNodesWithNodeID
, findPNInMapping
, findPNInMatch
, findPNsInMapping
, findPNsInMatch
, findCallNodesWithName
, findBlockNodesWithName
, findValueNodesWithOrigin
, fromEdgeNr
, getAllNodes
, getAllEdges
, findDefEdgeOfDtInEdge
, findDefEdgeOfDtOutEdge
, getCtrlFlowInEdges
, getCtrlFlowOutEdges
, getCopiesOfValue
, getCopyRelatedValues
, getDataTypeOfValueNode
, getDtFlowInEdges
, getDtFlowOutEdges
, getDefInEdges
, getDefOutEdges
, getStFlowInEdges
, getStFlowOutEdges
, getEdgeType
, getEdges
, getEdgesBetween
, getEdgeLabel
, getEdgeInNr
, getEdgeOutNr
, getInEdges
, getNeighbors
, getNodeID
, getNodeLabel
, getNodeType
, getNumNodes
, getNameOfCallNode
, getNameOfBlockNode
, getOpOfComputationNode
, getOriginOfValueNode
, getOutEdges
, getPredecessors
, getSourceNode
, getSuccessors
, getTargetNode
, groupNodesByID
, hasAnyPredecessors
, hasAnySuccessors
, haveSameInEdgeNrs
, haveSameOutEdgeNrs
, insertNewNodeAlongEdge
, isBrControlNode
, isCondBrControlNode
, isCallNode
, isIndirCallNode
, isComputationNode
, isControlFlowEdge
, isControlNode
, isCopyNode
, isDataFlowEdge
, isDatumNode
, isValueNode
, isValueNodeWithConstValue
, isValueNodeWithOrigin
, isValueNodeWithPointerDataType
, isDefEdge
, isInGraph
, isBlockNode
, isGraphEmpty
, isNodeInGraph
, isOperationNode
, isStateFlowEdge
, isOfCallNodeType
, isOfIndirCallNodeType
, isOfComputationNodeType
, isOfControlFlowEdgeType
, isOfControlNodeType
, isOfCopyNodeType
, isOfDataFlowEdgeType
, isOfValueNodeType
, isOfDefEdgeType
, isOfBlockNodeType
, isOfPhiNodeType
, isOfStateFlowEdgeType
, isOfStateNodeType
, isPhiNode
, isRetControlNode
, isStateNode
, mergeMatches
, mergeNodes
, mkEmpty
, mkGraph
, redirectEdges
, redirectInEdges
, redirectOutEdges
, redirectEdgesWhen
, redirectInEdgesWhen
, redirectOutEdgesWhen
, rootInCFG
, sortByEdgeNr
, toEdgeNr
, fromMatch
, toMatch
, subGraph
, updateOpOfComputationNode
, updateDataTypeOfValueNode
, updateEdgeLabel
, updateEdgeSource
, updateEdgeTarget
, updateEdgeInNr
, updateEdgeOutNr
, updateFNodeInMatch
, updateNameOfCallNode
, updateNodeID
, updateNodeLabel
, updateNodeType
, updatePNodeInMatch
)
where
import Language.InstrSel.PrettyShow
import qualified Language.InstrSel.DataTypes as D
import Language.InstrSel.Functions.IDs
( BlockName
, FunctionName
)
import Language.InstrSel.Graphs.IDs
import qualified Language.InstrSel.OpTypes as O
import Language.InstrSel.Utils
( groupBy )
import Language.InstrSel.Utils.Natural
import Language.InstrSel.Utils.JSON
import qualified Data.Graph.Inductive as I
import Data.List
( nubBy
, sortBy
)
import Data.Maybe
import qualified Data.Map as M
import qualified Data.Vector as V
import Control.DeepSeq
( NFData
, rnf
)
type IntGraph = I.Gr NodeLabel EdgeLabel
data Graph
= Graph { intGraph :: IntGraph
, intNodeMap :: M.Map NodeID [Node]
, entryBlockNode :: Maybe Node
}
deriving (Show)
newtype Node
= Node (I.LNode NodeLabel)
deriving (Show)
instance Ord Node where
(Node (n1, _)) <= (Node (n2, _)) = n1 <= n2
instance Eq Node where
(Node (n1, _)) == (Node (n2, _)) = n1 == n2
instance PrettyShow Node where
pShow n = "{ID: " ++ pShow (getNodeID n) ++ ", " ++ pShow (getNodeType n) ++
"}"
type SrcNode = Node
type DstNode = Node
data NodeLabel
= NodeLabel
{ nodeID :: NodeID
, nodeType :: NodeType
}
deriving (Show)
data NodeType
= ComputationNode { compOp :: O.CompOp }
| ControlNode { ctrlOp :: O.ControlOp }
| CallNode { nameOfCall :: FunctionName }
| IndirCallNode
are all represented as value nodes . What distinguishes one from another
| ValueNode
{ typeOfValue :: D.DataType
, originOfValue :: [String]
of origins , but the most current origin should always be placed first
}
| BlockNode { nameOfBlock :: BlockName }
| PhiNode
| StateNode
| CopyNode
deriving (Show)
instance PrettyShow NodeType where
pShow (ComputationNode op) = "computation node (" ++ pShow op ++ ")"
pShow (ControlNode op) = "control node (" ++ pShow op ++ ")"
pShow (CallNode func) = "call node (" ++ pShow func ++ ")"
pShow IndirCallNode = "indirect call node"
pShow (ValueNode dt origin) = "value node (" ++ pShow dt ++ ", "
++ pShow origin ++ ")"
pShow (BlockNode name) = "block node (" ++ pShow name ++ ")"
pShow PhiNode = "phi node"
pShow StateNode = "state node"
pShow CopyNode = "copy node"
newtype Edge
= Edge (I.LEdge EdgeLabel)
deriving (Show, Eq)
instance PrettyShow Edge where
pShow (Edge (s, t, l)) =
"<" ++ pShow (edgeType l) ++ ", " ++ pShow s ++
": " ++ pShow (outEdgeNr l) ++ " -> " ++ pShow (inEdgeNr l) ++
": " ++ pShow t ++ ">"
| Data type for describing how an edge relates to the two nodes .
data EdgeLabel
= EdgeLabel
{ edgeType :: EdgeType
, outEdgeNr :: EdgeNr
, inEdgeNr :: EdgeNr
}
deriving (Show, Eq)
data EdgeType
= ControlFlowEdge
| DataFlowEdge
| StateFlowEdge
| DefEdge
deriving (Show, Eq)
instance PrettyShow EdgeType where
pShow ControlFlowEdge = "control-flow"
pShow DataFlowEdge = "data-flow"
pShow StateFlowEdge = "state-flow"
pShow DefEdge = "definition"
newtype EdgeNr
= EdgeNr Natural
deriving (Show, Eq, Ord, Num, Enum, Integral, Real)
instance PrettyShow EdgeNr where
pShow (EdgeNr i) = pShow i
| Represents a mapping between two entities ( typically ' 's or ' NodeID 's ) .
data Mapping n
= Mapping
{ fNode :: n
, pNode :: n
}
deriving (Show, Eq, Ord)
instance (PrettyShow a) => PrettyShow (Mapping a) where
| The mapping is shown as a tuple , where the ' is the first element
and the ' pNode ' is the second element .
pShow m = pShow (fNode m, pNode m)
For efficiency , the mappings are stored in two forms : one as mappings from
data Match n
= Match { f2pMaps :: M.Map n [n]
, p2fMaps :: M.Map n [n]
}
deriving (Show, Eq, Ord)
instance (PrettyShow a, Ord a) => PrettyShow (Match a) where
pShow m = pShow $ fromMatch m
data DomSet t
= DomSet
{ domNode :: t
, domSet :: [t]
}
deriving (Show)
instance FromJSON Graph where
parseJSON (Object v) =
do g <- v .: "graph"
entry <- v .:? "entry-block-node"
let ns = map Node $ I.labNodes g
return $ Graph { intGraph = g
, intNodeMap = M.fromList $ groupNodesByID ns
, entryBlockNode = if isJust entry
then Just $ toNode $ fromJust entry
else Nothing
}
parseJSON _ = mzero
instance ToJSON Graph where
toJSON g =
let entry = entryBlockNode g
in object [ "graph" .= (intGraph g)
, "entry-block-node" .= ( if isJust entry
then Just $ fromNode $ fromJust entry
else Nothing
)
]
instance FromJSON IntGraph where
parseJSON (Object v) =
I.mkGraph
<$> v .: "nodes"
<*> v .: "edges"
parseJSON _ = mzero
instance ToJSON IntGraph where
toJSON g =
object [ "nodes" .= (I.labNodes g)
, "edges" .= (I.labEdges g)
]
instance FromJSON NodeLabel where
parseJSON (Object v) =
NodeLabel
<$> v .: "id"
<*> v .: "type"
parseJSON _ = mzero
instance ToJSON NodeLabel where
toJSON l =
object [ "id" .= (nodeID l)
, "type" .= (nodeType l)
]
instance FromJSON NodeType where
parseJSON (Object v) =
do str <- v .: "ntype"
let typ = unpack str
case typ of "comp" -> ComputationNode
<$> v .: "op"
"ctrl" -> ControlNode
<$> v .: "op"
"call" -> CallNode
<$> v .: "func"
"indir-call" -> return IndirCallNode
"data" -> ValueNode
<$> v .: "dtype"
<*> v .: "origin"
"lab" -> BlockNode
<$> v .: "block-name"
"phi" -> return PhiNode
"stat" -> return StateNode
"copy" -> return CopyNode
_ -> mzero
parseJSON _ = mzero
instance ToJSON NodeType where
toJSON n@(ComputationNode {}) =
object [ "ntype" .= String "comp"
, "op" .= toJSON (compOp n)
]
toJSON n@(ControlNode {}) =
object [ "ntype" .= String "ctrl"
, "op" .= toJSON (ctrlOp n)
]
toJSON n@(CallNode {}) =
object [ "ntype" .= String "call"
, "func" .= toJSON (nameOfCall n)
]
toJSON IndirCallNode =
object [ "ntype" .= String "indir-call" ]
toJSON n@(ValueNode {}) =
object [ "ntype" .= String "data"
, "dtype" .= toJSON (typeOfValue n)
, "origin" .= toJSON (originOfValue n)
]
toJSON n@(BlockNode {}) =
object [ "ntype" .= String "lab"
, "block-name" .= toJSON (nameOfBlock n)
]
toJSON (PhiNode {}) =
object [ "ntype" .= String "phi" ]
toJSON (StateNode {}) =
object [ "ntype" .= String "stat" ]
toJSON (CopyNode {}) =
object [ "ntype" .= String "copy" ]
instance FromJSON EdgeLabel where
parseJSON (Object v) =
EdgeLabel
<$> v .: "etype"
<*> v .: "out-nr"
<*> v .: "in-nr"
parseJSON _ = mzero
instance ToJSON EdgeLabel where
toJSON l =
object [ "etype" .= (edgeType l)
, "out-nr" .= (outEdgeNr l)
, "in-nr" .= (inEdgeNr l)
]
instance FromJSON EdgeType where
parseJSON (String str) =
case str of "ctrl" -> return ControlFlowEdge
"data" -> return DataFlowEdge
"stat" -> return StateFlowEdge
"def" -> return DefEdge
_ -> mzero
parseJSON _ = mzero
instance ToJSON EdgeType where
toJSON ControlFlowEdge = "ctrl"
toJSON DataFlowEdge = "data"
toJSON StateFlowEdge = "stat"
toJSON DefEdge = "def"
instance FromJSON EdgeNr where
parseJSON v = EdgeNr <$> parseJSON v
instance ToJSON EdgeNr where
toJSON (EdgeNr nr) = toJSON nr
instance FromJSON (DomSet NodeID) where
parseJSON (Object v) =
DomSet
<$> v .: "node"
<*> v .: "dom-set"
parseJSON _ = mzero
instance ToJSON (DomSet NodeID) where
toJSON d =
object [ "node" .= (domNode d)
, "dom-set" .= (domSet d)
]
instance FromJSON (Match NodeID) where
parseJSON v@(Array _) =
do list <- parseJSON v
return $ toMatch list
parseJSON _ = mzero
instance ToJSON (Match NodeID) where
toJSON m = toJSON $ fromMatch m
instance FromJSON (Mapping NodeID) where
parseJSON v@(Array _) =
do list <- parseJSON v
when (length list /= 2) mzero
return Mapping { fNode = head list
, pNode = last list
}
parseJSON _ = mzero
instance ToJSON (Mapping NodeID) where
toJSON m = Array (V.fromList [toJSON $ fNode m, toJSON $ pNode m])
DeepSeq - related type class instances
instance NFData n => NFData (Mapping n) where
rnf (Mapping a b) = rnf a `seq` rnf b
instance NFData n => NFData (Match n) where
rnf (Match a b) = rnf a `seq` rnf b
toNode :: I.LNode NodeLabel -> Node
toNode = Node
fromNode :: Node -> I.LNode NodeLabel
fromNode (Node n) = n
toEdge :: I.LEdge EdgeLabel -> Edge
toEdge = Edge
fromEdge :: Edge -> I.LEdge EdgeLabel
fromEdge (Edge e) = e
toEdgeNr :: (Integral i) => i -> EdgeNr
toEdgeNr = EdgeNr . toNatural
fromEdgeNr :: EdgeNr -> Natural
fromEdgeNr (EdgeNr n) = n
isOperationNode :: Node -> Bool
isOperationNode n =
isComputationNode n ||
isControlNode n ||
isCallNode n ||
isIndirCallNode n ||
isPhiNode n ||
isCopyNode n
isDatumNode :: Node -> Bool
isDatumNode n =
isValueNode n ||
isStateNode n
isNodeInGraph :: Graph -> Node -> Bool
isNodeInGraph g n = n `elem` getAllNodes g
isComputationNode :: Node -> Bool
isComputationNode n = isOfComputationNodeType $ getNodeType n
isControlNode :: Node -> Bool
isControlNode n = isOfControlNodeType $ getNodeType n
isCallNode :: Node -> Bool
isCallNode n = isOfCallNodeType $ getNodeType n
isIndirCallNode :: Node -> Bool
isIndirCallNode n = isOfIndirCallNodeType $ getNodeType n
isRetControlNode :: Node -> Bool
isRetControlNode n = isControlNode n && (ctrlOp $ getNodeType n) == O.Ret
isBrControlNode :: Node -> Bool
isBrControlNode n = isControlNode n && (ctrlOp $ getNodeType n) == O.Br
isCondBrControlNode :: Node -> Bool
isCondBrControlNode n = isControlNode n && (ctrlOp $ getNodeType n) == O.CondBr
isValueNode :: Node -> Bool
isValueNode n = isOfValueNodeType $ getNodeType n
isValueNodeWithConstValue :: Node -> Bool
isValueNodeWithConstValue n =
if isValueNode n
then D.isTypeAConstValue $ getDataTypeOfValueNode n
else False
isValueNodeWithPointerDataType :: Node -> Bool
isValueNodeWithPointerDataType n =
if isValueNode n
then D.isTypeAPointer $ getDataTypeOfValueNode n
else False
isValueNodeWithOrigin :: Node -> Bool
isValueNodeWithOrigin n =
if isValueNode n
then length (originOfValue $ getNodeType n) > 0
else False
getOriginOfValueNode :: Node -> [String]
getOriginOfValueNode = originOfValue . getNodeType
getNameOfBlockNode :: Node -> BlockName
getNameOfBlockNode = nameOfBlock . getNodeType
getNameOfCallNode :: Node -> FunctionName
getNameOfCallNode = nameOfCall . getNodeType
isBlockNode :: Node -> Bool
isBlockNode n = isOfBlockNodeType $ getNodeType n
| Checks if a given node is a phi node .
isPhiNode :: Node -> Bool
isPhiNode n = isOfPhiNodeType $ getNodeType n
isStateNode :: Node -> Bool
isStateNode n = isOfStateNodeType $ getNodeType n
isCopyNode :: Node -> Bool
isCopyNode n = isOfCopyNodeType $ getNodeType n
isOfComputationNodeType :: NodeType -> Bool
isOfComputationNodeType (ComputationNode _) = True
isOfComputationNodeType _ = False
isOfCallNodeType :: NodeType -> Bool
isOfCallNodeType (CallNode _) = True
isOfCallNodeType _ = False
isOfIndirCallNodeType :: NodeType -> Bool
isOfIndirCallNodeType IndirCallNode = True
isOfIndirCallNodeType _ = False
isOfControlNodeType :: NodeType -> Bool
isOfControlNodeType (ControlNode _) = True
isOfControlNodeType _ = False
isOfValueNodeType :: NodeType -> Bool
isOfValueNodeType (ValueNode _ _) = True
isOfValueNodeType _ = False
isOfBlockNodeType :: NodeType -> Bool
isOfBlockNodeType (BlockNode _) = True
isOfBlockNodeType _ = False
| Checks if a given node type represents a phi node .
isOfPhiNodeType :: NodeType -> Bool
isOfPhiNodeType PhiNode = True
isOfPhiNodeType _ = False
isOfStateNodeType :: NodeType -> Bool
isOfStateNodeType StateNode = True
isOfStateNodeType _ = False
isOfCopyNodeType :: NodeType -> Bool
isOfCopyNodeType CopyNode = True
isOfCopyNodeType _ = False
isDataFlowEdge :: Edge -> Bool
isDataFlowEdge = isOfDataFlowEdgeType . getEdgeType
isStateFlowEdge :: Edge -> Bool
isStateFlowEdge = isOfStateFlowEdgeType . getEdgeType
isControlFlowEdge :: Edge -> Bool
isControlFlowEdge = isOfControlFlowEdgeType . getEdgeType
isDefEdge :: Edge -> Bool
isDefEdge = isOfDefEdgeType . getEdgeType
isOfDataFlowEdgeType :: EdgeType -> Bool
isOfDataFlowEdgeType DataFlowEdge = True
isOfDataFlowEdgeType _ = False
isOfControlFlowEdgeType :: EdgeType -> Bool
isOfControlFlowEdgeType ControlFlowEdge = True
isOfControlFlowEdgeType _ = False
isOfStateFlowEdgeType :: EdgeType -> Bool
isOfStateFlowEdgeType StateFlowEdge = True
isOfStateFlowEdgeType _ = False
isOfDefEdgeType :: EdgeType -> Bool
isOfDefEdgeType DefEdge = True
isOfDefEdgeType _ = False
mkEmpty :: Graph
mkEmpty = Graph { intGraph = I.empty
, intNodeMap = M.empty
, entryBlockNode = Nothing
}
mkGraph :: [Node] -> [Edge] -> Maybe Node -> Graph
mkGraph ns es entry =
Graph { intGraph = I.mkGraph (map fromNode ns) (map fromEdge es)
, intNodeMap = M.fromList $ groupNodesByID ns
, entryBlockNode = entry
}
getNextIntNodeID :: IntGraph -> I.Node
getNextIntNodeID g =
let existing_nodes = I.nodes g
in if length existing_nodes > 0
then 1 + maximum existing_nodes
else 0
getNodeID :: Node -> NodeID
getNodeID (Node (_, NodeLabel i _)) = i
getNodeLabel :: Node -> NodeLabel
getNodeLabel (Node (_, nl)) = nl
getNodeType :: Node -> NodeType
getNodeType (Node (_, NodeLabel _ nt)) = nt
getDataTypeOfValueNode :: Node -> D.DataType
getDataTypeOfValueNode n = typeOfValue $ getNodeType n
getOpOfComputationNode :: Node -> O.CompOp
getOpOfComputationNode n = compOp $ getNodeType n
getIntNodeID :: Node -> I.Node
getIntNodeID (Node (nid, _)) = nid
getNumNodes :: Graph -> Int
getNumNodes g = length $ getAllNodes g
getAllNodes :: Graph -> [Node]
getAllNodes g = map Node $
I.labNodes $
intGraph g
delNode :: Node -> Graph -> Graph
delNode n g =
let new_int_g = I.delNode (getIntNodeID n) (intGraph g)
new_nmap = M.update ( \ns -> let new_ns = filter (/= n) ns
in if not (null new_ns)
then Just new_ns
else Nothing
)
(getNodeID n)
(intNodeMap g)
entry = entryBlockNode g
new_entry = if isJust entry && (fromJust entry) == n
then Nothing
else entry
in Graph { intGraph = new_int_g
, intNodeMap = new_nmap
, entryBlockNode = new_entry
}
delEdge :: Edge -> Graph -> Graph
delEdge (Edge e) g = g { intGraph = I.delLEdge e (intGraph g) }
findNodesWithNodeID :: Graph -> NodeID -> [Node]
findNodesWithNodeID g i =
let ns = M.lookup i (intNodeMap g)
in if isJust ns then fromJust ns else []
findValueNodesWithOrigin :: Graph -> String -> [Node]
findValueNodesWithOrigin g o =
let vs = filter isValueNodeWithOrigin $ getAllNodes g
in filter (\v -> o `elem` getOriginOfValueNode v) vs
findBlockNodesWithName :: Graph -> BlockName -> [Node]
findBlockNodesWithName g name =
let bs = filter isBlockNode $ getAllNodes g
in filter ((==) name . getNameOfBlockNode) bs
findCallNodesWithName :: Graph -> FunctionName -> [Node]
findCallNodesWithName g name =
let bs = filter isCallNode $ getAllNodes g
in filter ((==) name . getNameOfCallNode) bs
updateDataTypeOfValueNode :: D.DataType -> Node -> Graph -> Graph
updateDataTypeOfValueNode new_dt n g =
let nt = getNodeType n
new_nt = nt { typeOfValue = new_dt }
in case nt of (ValueNode {}) -> updateNodeType new_nt n g
_ -> error $ "updateDataTypeOfValueNode: node " ++ show n ++
" is not a value node"
updateNameOfCallNode :: FunctionName -> Node -> Graph -> Graph
updateNameOfCallNode new_name n g =
let nt = getNodeType n
new_nt = nt { nameOfCall = new_name }
in case nt of (CallNode {}) -> updateNodeType new_nt n g
_ -> error $ "updateNameOfCallNode: node " ++ show n ++
" is not a call node"
addOriginToValueNode :: String -> Node -> Graph -> Graph
addOriginToValueNode new_origin n g =
let nt = getNodeType n
new_nt = nt { originOfValue = (new_origin:originOfValue nt) }
in case nt of (ValueNode {}) -> updateNodeType new_nt n g
_ -> error $ "addOriginToValueNode: node " ++ show n ++
" is not a value node"
updateOpOfComputationNode :: O.CompOp -> Node -> Graph -> Graph
updateOpOfComputationNode new_op n g =
let nt = getNodeType n
new_nt = nt { compOp = new_op }
in case nt of (ComputationNode {}) -> updateNodeType new_nt n g
_ -> error $ "updateOpOfComputationNode: node " ++ show n ++
" is not a computation node"
updateNodeLabel :: NodeLabel -> Node -> Graph -> Graph
updateNodeLabel new_label n g =
let all_nodes_but_n = filter (/= n) (getAllNodes g)
new_n = Node (getIntNodeID n, new_label)
entry = entryBlockNode g
new_entry = if isJust entry && (fromJust entry) == n
then Just new_n
else entry
in mkGraph (new_n:all_nodes_but_n) (getAllEdges g) new_entry
updateNodeType :: NodeType -> Node -> Graph -> Graph
updateNodeType new_type n g =
let all_nodes_but_n = filter (/= n) (getAllNodes g)
new_n = Node ( getIntNodeID n
, NodeLabel { nodeID = getNodeID n
, nodeType = new_type
}
)
entry = entryBlockNode g
new_entry = if isJust entry && (fromJust entry) == n
then Just new_n
else entry
in mkGraph (new_n:all_nodes_but_n) (getAllEdges g) new_entry
updateNodeID :: NodeID -> Node -> Graph -> Graph
updateNodeID new_id n g =
let all_nodes_but_n = filter (/= n) (getAllNodes g)
new_n = Node (getIntNodeID n, NodeLabel new_id (getNodeType n))
entry = entryBlockNode g
new_entry = if isJust entry && (fromJust entry) == n
then Just new_n
else entry
in mkGraph (new_n:all_nodes_but_n) (getAllEdges g) new_entry
| Copies the node label from one node to another node . If the two nodes are
copyNodeLabel
:: Node
-> Node
-> Graph
-> Graph
copyNodeLabel to_n from_n g
| (getIntNodeID from_n) == (getIntNodeID to_n) = g
| otherwise = updateNodeLabel (getNodeLabel from_n) to_n g
| Merges two nodes by redirecting the edges to the node to merge to , and then
removes the merged node . If the two nodes are actually the same node , nothing
happens . Any edges already involving the two nodes will be removed . Edge
mergeNodes
:: Node
-> Node
-> Graph
-> Graph
mergeNodes n_to_keep n_to_discard g
| (getIntNodeID n_to_keep) == (getIntNodeID n_to_discard) = g
| otherwise =
let edges_to_ignore = getEdgesBetween g n_to_discard n_to_keep ++
getEdgesBetween g n_to_keep n_to_discard
in delNode n_to_discard
( redirectEdges n_to_keep
n_to_discard
(foldr delEdge g edges_to_ignore)
)
| Redirects all edges involving one node to another node . Edge number
redirectEdges
:: Node
-> Node
-> Graph
-> Graph
redirectEdges = redirectEdgesWhen (\_ -> True)
| Redirects all inbound edges to one node to another node .
redirectInEdges
:: Node
-> Node
-> Graph
-> Graph
redirectInEdges = redirectInEdgesWhen (\_ -> True)
| Redirects the outbound edges from one node to another . Edge number
redirectOutEdges
:: Node
-> Node
-> Graph
-> Graph
redirectOutEdges = redirectOutEdgesWhen (\_ -> True)
redirectEdgesWhen
:: (Edge -> Bool)
-> Node
-> Node
-> Graph
-> Graph
redirectEdgesWhen p to_n from_n g =
redirectInEdgesWhen p to_n from_n $
redirectOutEdgesWhen p to_n from_n g
redirectInEdgesWhen
:: (Edge -> Bool)
-> Node
-> Node
-> Graph
-> Graph
redirectInEdgesWhen p to_n from_n g0 =
let es = filter p $ getInEdges g0 from_n
df_def_es =
if isValueNode from_n
then map ( \e ->
let df_es = filter ( \e' ->
getEdgeInNr e == getEdgeInNr e'
) $
filter isDataFlowEdge $
es
in if length df_es == 1
then (head df_es, e)
else if length df_es == 0
then error $ "redirectInEdgesWhen: no data-flow " ++
"edge to redirect to redirect that " ++
"matches definition edge " ++ pShow e
else error $ "redirectInEdgesWhen: multiple data-" ++
"flow edges to redirect that " ++
"matches definition edge " ++ pShow e
) $
filter isDefEdge $
es
else []
g1 = foldr (\e g -> fst $ updateEdgeTarget to_n e g) g0 $
filter ( \e -> e `notElem` map fst df_def_es &&
e `notElem` map snd df_def_es
) $
es
(g2, new_df_es) = foldr ( \e (g, new_es) ->
let (g', e') = updateEdgeTarget to_n e g
in (g', (e':new_es))
)
(g1, []) $
map fst df_def_es
g3 = foldr ( \(df_e, e) g ->
let (g', e') = updateEdgeTarget to_n e g
(g'', _) = updateEdgeInNr (getEdgeInNr df_e) e' g'
in g''
)
g2 $
zip new_df_es $
map snd df_def_es
in g3
redirectOutEdgesWhen
:: (Edge -> Bool)
-> Node
-> Node
-> Graph
-> Graph
redirectOutEdgesWhen p to_n from_n g0 =
let es = filter p $ getOutEdges g0 from_n
df_def_es =
if isValueNode from_n
then map ( \e ->
let df_es = filter ( \e' ->
getEdgeOutNr e == getEdgeOutNr e'
) $
filter isDataFlowEdge $
es
in if length df_es == 1
then (head df_es, e)
else if length df_es == 0
then error $ "redirectOutEdgesWhen: no data-flow " ++
"edge that to redirect that matches " ++
"definition edge " ++ pShow e
else error $ "redirectOutEdgesWhen: multiple " ++
"data-flow edges to redirect that " ++
"matches definition edge " ++ pShow e
) $
filter isDefEdge $
es
else []
g1 = foldr (\e g -> fst $ updateEdgeSource to_n e g) g0 $
filter ( \e -> e `notElem` map fst df_def_es &&
e `notElem` map snd df_def_es
) $
es
(g2, new_df_es) = foldr ( \e (g, new_es) ->
let (g', e') = updateEdgeSource to_n e g
in (g', (e':new_es))
)
(g1, []) $
map fst df_def_es
g3 = foldr ( \(df_e, e) g ->
let (g', e') = updateEdgeSource to_n e g
(g'', _) = updateEdgeOutNr (getEdgeOutNr df_e) e' g'
in g''
)
g2 $
zip new_df_es $
map snd df_def_es
in g3
updateEdgeTarget
:: Node
-> Edge
-> Graph
-> (Graph, Edge)
updateEdgeTarget new_trg (Edge e@(src, _, l)) g =
let int_g = intGraph g
new_trg_id = getIntNodeID new_trg
new_e = ( src
, new_trg_id
, l { inEdgeNr = getNextInEdgeNr int_g
new_trg_id
( \e' ->
getEdgeType e' == edgeType l
)
}
)
in ( g { intGraph = I.insEdge new_e (I.delLEdge e int_g) }
, Edge new_e
)
updateEdgeSource
:: Node
-> Edge
-> Graph
-> (Graph, Edge)
updateEdgeSource new_src (Edge e@(_, trg, l)) g =
let int_g = intGraph g
new_src_id = getIntNodeID new_src
new_e = ( new_src_id
, trg
, l { outEdgeNr = getNextOutEdgeNr int_g
new_src_id
( \e' ->
getEdgeType e' == edgeType l
)
}
)
in ( g { intGraph = I.insEdge new_e (I.delLEdge e int_g) }
, Edge new_e
)
updateEdgeInNr
:: EdgeNr
-> Edge
-> Graph
-> (Graph, Edge)
updateEdgeInNr new_nr e@(Edge (_, _, l)) g =
let new_l = l { inEdgeNr = new_nr }
in updateEdgeLabel new_l e g
updateEdgeOutNr
:: EdgeNr
-> Edge
-> Graph
-> (Graph, Edge)
updateEdgeOutNr new_nr e@(Edge (_, _, l)) g =
let new_l = l { outEdgeNr = new_nr }
in updateEdgeLabel new_l e g
getNextInEdgeNr :: IntGraph -> I.Node -> (Edge -> Bool) -> EdgeNr
getNextInEdgeNr g int f =
let existing_numbers = map getEdgeInNr (filter f $ map toEdge (I.inn g int))
in if length existing_numbers > 0
then maximum existing_numbers + 1
else 0
getNextOutEdgeNr :: IntGraph -> I.Node -> (Edge -> Bool) -> EdgeNr
getNextOutEdgeNr g int f =
let existing_numbers = map getEdgeOutNr (filter f $ map toEdge (I.out g int))
in if length existing_numbers > 0
then maximum existing_numbers + 1
else 0
getEdgeLabel :: Edge -> EdgeLabel
getEdgeLabel (Edge (_, _, l)) = l
getEdgeInNr :: Edge -> EdgeNr
getEdgeInNr = inEdgeNr . getEdgeLabel
getEdgeOutNr :: Edge -> EdgeNr
getEdgeOutNr = outEdgeNr . getEdgeLabel
getEdgeType :: Edge -> EdgeType
getEdgeType = edgeType . getEdgeLabel
addNewNode :: NodeType -> Graph -> (Graph, Node)
addNewNode nt g =
let int_g = intGraph g
new_int_id = getNextIntNodeID int_g
new_id = toNodeID new_int_id
new_int_n = (new_int_id, NodeLabel new_id nt)
new_int_g = I.insNode new_int_n int_g
new_n = Node new_int_n
new_nmap = M.alter ( \ns -> if isJust ns
then Just $ (new_n:fromJust ns)
else Just $ [new_n]
)
new_id
(intNodeMap g)
in (g { intGraph = new_int_g, intNodeMap = new_nmap }, new_n)
| Adds a new edge between two nodes to the graph , returning both the new
addNewEdge :: EdgeType -> (SrcNode, DstNode) -> Graph -> (Graph, Edge)
addNewEdge et (from_n, to_n) g =
let int_g = intGraph g
from_n_id = getIntNodeID from_n
to_n_id = getIntNodeID to_n
out_edge_nr = getNextOutEdgeNr int_g from_n_id (\e -> et == getEdgeType e)
in_edge_nr = getNextInEdgeNr int_g to_n_id (\e -> et == getEdgeType e)
new_e = ( from_n_id
, to_n_id
, EdgeLabel { edgeType = et
, outEdgeNr = out_edge_nr
, inEdgeNr = in_edge_nr
}
)
new_int_g = I.insEdge new_e int_g
in (g { intGraph = new_int_g }, Edge new_e)
| Adds many new edges between two nodes to the graph . The edges will be
addNewEdges :: EdgeType -> [(SrcNode, DstNode)] -> Graph -> Graph
addNewEdges et ps g = foldl (\g' p -> fst $ addNewEdge et p g') g ps
addNewDtFlowEdge :: (SrcNode, DstNode) -> Graph -> (Graph, Edge)
addNewDtFlowEdge = addNewEdge DataFlowEdge
addNewDtFlowEdges :: [(SrcNode, DstNode)] -> Graph -> Graph
addNewDtFlowEdges = addNewEdges DataFlowEdge
addNewCtrlFlowEdge :: (SrcNode, DstNode) -> Graph -> (Graph, Edge)
addNewCtrlFlowEdge = addNewEdge ControlFlowEdge
addNewCtrlFlowEdges :: [(SrcNode, DstNode)] -> Graph -> Graph
addNewCtrlFlowEdges = addNewEdges ControlFlowEdge
addNewStFlowEdge :: (SrcNode, DstNode) -> Graph -> (Graph, Edge)
addNewStFlowEdge = addNewEdge StateFlowEdge
addNewStFlowEdges :: [(SrcNode, DstNode)] -> Graph -> Graph
addNewStFlowEdges = addNewEdges StateFlowEdge
addNewDefEdge :: (SrcNode, DstNode) -> Graph -> (Graph, Edge)
addNewDefEdge = addNewEdge DefEdge
addNewDefEdges :: [(SrcNode, DstNode)] -> Graph -> Graph
addNewDefEdges = addNewEdges DefEdge
new graph and the new node . The existing edge will be split into two edges
insertNewNodeAlongEdge :: NodeType -> Edge -> Graph -> (Graph, Node)
insertNewNodeAlongEdge
nt
e@(Edge (from_nid, to_nid, el))
g0
=
let (g1, new_n) = addNewNode nt g0
g2 = delEdge e g1
et = edgeType el
new_e1 = (from_nid, getIntNodeID new_n, EdgeLabel et (outEdgeNr el) 0)
new_e2 = (getIntNodeID new_n, to_nid, EdgeLabel et 0 (inEdgeNr el))
int_g2 = intGraph g2
int_g3 = I.insEdge new_e2 $
I.insEdge new_e1 int_g2
g3 = g2 { intGraph = int_g3 }
in (g3, new_n)
updateEdgeLabel
:: EdgeLabel
-> Edge
-> Graph
-> (Graph, Edge)
updateEdgeLabel new_label e@(Edge (src, dst, _)) g =
let all_edges_but_e = filter (/= e) (getAllEdges g)
new_e = Edge (src, dst, new_label)
in (mkGraph (getAllNodes g) (new_e:all_edges_but_e) (entryBlockNode g), new_e)
getNodeWithIntNodeID :: IntGraph -> I.Node -> Maybe Node
getNodeWithIntNodeID g nid =
maybe Nothing (\l -> Just (Node (nid, l))) (I.lab g nid)
| Gets the predecessors ( if any ) of a given node . A node @n@ is a predecessor
getPredecessors :: Graph -> Node -> [Node]
getPredecessors g n =
let int_g = intGraph g
in map (fromJust . getNodeWithIntNodeID int_g) (I.pre int_g (getIntNodeID n))
| Gets the successors ( if any ) of a given node . A node @n@ is a successor of
another node @m@ if there is a directed edge from @n@ to @m@.
getSuccessors :: Graph -> Node -> [Node]
getSuccessors g n =
let int_g = intGraph g
in map (fromJust . getNodeWithIntNodeID int_g) (I.suc int_g (getIntNodeID n))
getNeighbors :: Graph -> Node -> [Node]
getNeighbors g n = getPredecessors g n ++ getSuccessors g n
isInGraph :: Graph -> Node -> Bool
isInGraph g n = isJust $ getNodeWithIntNodeID (intGraph g) (getIntNodeID n)
getAllEdges :: Graph -> [Edge]
getAllEdges g = map toEdge $ I.labEdges (intGraph g)
getInEdges :: Graph -> Node -> [Edge]
getInEdges g n = map toEdge $ I.inn (intGraph g) (getIntNodeID n)
getDtFlowInEdges :: Graph -> Node -> [Edge]
getDtFlowInEdges g n = filter isDataFlowEdge $ getInEdges g n
getCtrlFlowInEdges :: Graph -> Node -> [Edge]
getCtrlFlowInEdges g n = filter isControlFlowEdge $ getInEdges g n
getStFlowInEdges :: Graph -> Node -> [Edge]
getStFlowInEdges g n = filter isStateFlowEdge $ getInEdges g n
getDefInEdges :: Graph -> Node -> [Edge]
getDefInEdges g n = filter isDefEdge $ getInEdges g n
getOutEdges :: Graph -> Node -> [Edge]
getOutEdges g n = map toEdge $ I.out (intGraph g) (getIntNodeID n)
getDtFlowOutEdges :: Graph -> Node -> [Edge]
getDtFlowOutEdges g n = filter isDataFlowEdge $ getOutEdges g n
getCtrlFlowOutEdges :: Graph -> Node -> [Edge]
getCtrlFlowOutEdges g n = filter isControlFlowEdge $ getOutEdges g n
getStFlowOutEdges :: Graph -> Node -> [Edge]
getStFlowOutEdges g n = filter isStateFlowEdge $ getOutEdges g n
getDefOutEdges :: Graph -> Node -> [Edge]
getDefOutEdges g n = filter isDefEdge $ getOutEdges g n
getEdges :: Graph -> Node -> [Edge]
getEdges g n =
filter (\e -> getSourceNode g e == n || getTargetNode g e == n) $
getAllEdges g
| Gets the edges between two nodes .
getEdgesBetween :: Graph -> SrcNode -> DstNode -> [Edge]
getEdgesBetween g from_n to_n =
let out_edges = map fromEdge $ getOutEdges g from_n
from_id = getIntNodeID from_n
to_id = getIntNodeID to_n
es = map toEdge $
filter (\(n1, n2, _) -> from_id == n1 && to_id == n2) $
out_edges
in es
sortByEdgeNr :: (Edge -> EdgeNr) -> [Edge] -> [Edge]
sortByEdgeNr f = sortBy (\e1 -> \e2 -> if f e1 < f e2 then LT else GT)
getSourceNode :: Graph -> Edge -> Node
getSourceNode g (Edge (n, _, _)) =
fromJust $ getNodeWithIntNodeID (intGraph g) n
getTargetNode :: Graph -> Edge -> Node
getTargetNode g (Edge (_, n, _)) =
fromJust $ getNodeWithIntNodeID (intGraph g) n
convertDomSetN2ID :: DomSet Node -> DomSet NodeID
convertDomSetN2ID d =
DomSet { domNode = getNodeID $ domNode d
, domSet = map getNodeID (domSet d)
}
convertMappingN2ID :: Mapping Node -> Mapping NodeID
convertMappingN2ID m =
Mapping { fNode = getNodeID $ fNode m
, pNode = getNodeID $ pNode m
}
convertMatchN2ID :: Match Node -> Match NodeID
convertMatchN2ID m =
let convert k a = M.insert (getNodeID k) (map getNodeID a)
in Match { f2pMaps = M.foldrWithKey convert M.empty (f2pMaps m)
, p2fMaps = M.foldrWithKey convert M.empty (p2fMaps m)
}
| Checks if a node matches another node . Two nodes match if they are of
doNodesMatch
:: Graph
-> Graph
-> Node
-> Node
-> Bool
doNodesMatch fg pg fn pn =
(getNodeType pn) `isNodeTypeCompatibleWith` (getNodeType fn) &&
doNumEdgesMatch fg pg fn pn
isNodeTypeCompatibleWith :: NodeType -> NodeType -> Bool
isNodeTypeCompatibleWith (ComputationNode op1) (ComputationNode op2) =
op1 `O.isCompatibleWith` op2
isNodeTypeCompatibleWith (ControlNode op1) (ControlNode op2) =
op1 `O.isCompatibleWith` op2
isNodeTypeCompatibleWith (CallNode {}) (CallNode {}) = True
isNodeTypeCompatibleWith IndirCallNode IndirCallNode = True
isNodeTypeCompatibleWith (ValueNode d1 _) (ValueNode d2 _) =
d1 `D.isCompatibleWith` d2
isNodeTypeCompatibleWith (BlockNode {}) (BlockNode {}) = True
isNodeTypeCompatibleWith PhiNode PhiNode = True
isNodeTypeCompatibleWith StateNode StateNode = True
isNodeTypeCompatibleWith CopyNode CopyNode = True
isNodeTypeCompatibleWith _ _ = False
at least one in - edge to a control node , and at least one out - edge to another
isBlockNodeAndIntermediate :: Graph -> Node -> Bool
isBlockNodeAndIntermediate g n
| ( isBlockNode n &&
( not ( isJust (entryBlockNode g) &&
n == fromJust (entryBlockNode g)
)
) &&
(length $ getCtrlFlowInEdges g n) > 0 &&
(length $ getCtrlFlowOutEdges g n) > 0
) = True
| otherwise = False
| Checks if two matching nodes have matching number of edges of particular
doNumEdgesMatch :: Graph -> Graph -> Node -> Node -> Bool
doNumEdgesMatch fg pg fn pn =
let checkEdges f getENr es1 es2 =
let areEdgeNrsSame e1 e2 = getENr e1 == getENr e2
pruned_es1 = nubBy areEdgeNrsSame $ filter f es1
pruned_es2 = nubBy areEdgeNrsSame $ filter f es2
in length pruned_es1 == length pruned_es2
f_in_es = getInEdges fg fn
p_in_es = getInEdges pg pn
f_out_es = getOutEdges fg fn
p_out_es = getOutEdges pg pn
in checkEdges (\e -> doesNumCFInEdgesMatter pg pn && isControlFlowEdge e)
getEdgeInNr
f_in_es
p_in_es
&&
checkEdges (\e -> doesNumCFOutEdgesMatter pg pn && isControlFlowEdge e)
getEdgeOutNr
f_out_es
p_out_es
&&
checkEdges (\e -> doesNumDFInEdgesMatter pg pn && isDataFlowEdge e)
getEdgeInNr
f_in_es
p_in_es
&&
checkEdges (\e -> doesNumDFOutEdgesMatter pg pn && isDataFlowEdge e)
getEdgeOutNr
f_out_es
p_out_es
&&
checkEdges (\e -> doesNumSFInEdgesMatter pg pn && isStateFlowEdge e)
getEdgeInNr
f_in_es
p_in_es
&&
checkEdges (\e -> doesNumSFOutEdgesMatter pg pn && isStateFlowEdge e)
getEdgeOutNr
f_out_es
p_out_es
doesNumCFInEdgesMatter :: Graph -> Node -> Bool
doesNumCFInEdgesMatter g n
| isControlNode n = True
| isBlockNodeAndIntermediate g n = True
| otherwise = False
doesNumCFOutEdgesMatter :: Graph -> Node -> Bool
doesNumCFOutEdgesMatter _ n
| isControlNode n = True
| otherwise = False
doesNumDFInEdgesMatter :: Graph -> Node -> Bool
doesNumDFInEdgesMatter g n
| isOperationNode n = True
| isValueNode n = (length $ getDtFlowInEdges g n) > 0
| otherwise = False
doesNumDFOutEdgesMatter :: Graph -> Node -> Bool
doesNumDFOutEdgesMatter _ n
| isOperationNode n = True
| otherwise = False
doesNumSFInEdgesMatter :: Graph -> Node -> Bool
doesNumSFInEdgesMatter _ n
| isOperationNode n = True
| otherwise = False
doesNumSFOutEdgesMatter :: Graph -> Node -> Bool
doesNumSFOutEdgesMatter _ n
| isOperationNode n = True
| otherwise = False
one edge in a list of edges from the function graph with matching edge number
doEdgeNrsMatch
:: (Edge -> EdgeNr)
-> [Edge]
-> [Edge]
-> Bool
doEdgeNrsMatch f es1 es2 =
all (\e -> length (filter (\e' -> f e == f e') es1) > 0) es2
doEdgeListsMatch
:: Graph
-> Graph
-> [Edge]
-> [Edge]
-> Bool
doEdgeListsMatch _ _ [] [] = True
doEdgeListsMatch fg pg fes pes =
doInEdgeListsMatch fg pg fes pes && doOutEdgeListsMatch fg pg fes pes
doInEdgeListsMatch
:: Graph
-> Graph
-> [Edge]
-> [Edge]
-> Bool
doInEdgeListsMatch _ pg fes pes =
let checkEdges f = doEdgeNrsMatch getEdgeInNr (filter f fes) (filter f pes)
pn = getTargetNode pg (head pes)
in (not (doesOrderCFInEdgesMatter pg pn) || checkEdges isControlFlowEdge) &&
(not (doesOrderDFInEdgesMatter pg pn) || checkEdges isDataFlowEdge) &&
(not (doesOrderSFInEdgesMatter pg pn) || checkEdges isStateFlowEdge)
doOutEdgeListsMatch
:: Graph
-> Graph
-> [Edge]
-> [Edge]
-> Bool
doOutEdgeListsMatch _ pg fes pes =
let checkEdges f = doEdgeNrsMatch getEdgeOutNr (filter f fes) (filter f pes)
pn = getSourceNode pg (head pes)
in (not (doesOrderCFOutEdgesMatter pg pn) || checkEdges isControlFlowEdge) &&
(not (doesOrderDFOutEdgesMatter pg pn) || checkEdges isDataFlowEdge) &&
(not (doesOrderSFOutEdgesMatter pg pn) || checkEdges isStateFlowEdge)
doesOrderCFInEdgesMatter :: Graph -> Node -> Bool
doesOrderCFInEdgesMatter g n
| isBlockNodeAndIntermediate g n = True
| otherwise = False
doesOrderCFOutEdgesMatter :: Graph -> Node -> Bool
doesOrderCFOutEdgesMatter _ n
| isControlNode n = True
| otherwise = False
doesOrderDFInEdgesMatter :: Graph -> Node -> Bool
doesOrderDFInEdgesMatter _ n
| isComputationNode n = not $ O.isCommutative $ getOpOfComputationNode n
| isOperationNode n = True
| otherwise = False
doesOrderDFOutEdgesMatter :: Graph -> Node -> Bool
doesOrderDFOutEdgesMatter _ n
| isOperationNode n = True
| otherwise = False
doesOrderSFInEdgesMatter :: Graph -> Node -> Bool
doesOrderSFInEdgesMatter _ _ = False
doesOrderSFOutEdgesMatter :: Graph -> Node -> Bool
doesOrderSFOutEdgesMatter _ _ = False
| If the pattern contains phi nodes , check that there is a matching
definition edge for each value - phi and phi - value edge .
customPatternMatchingSemanticsCheck
:: Graph
-> Graph
-> [Mapping Node]
-> Mapping Node
-> Bool
customPatternMatchingSemanticsCheck fg pg st c =
let pn = pNode c
in if isPhiNode pn
then let es = filter isDataFlowEdge $ getInEdges pg pn
val_es = filter (isValueNode . getSourceNode pg) es
in all (checkPhiValBlockMappings fg pg (c:st)) val_es
else if isValueNode pn
then let es = filter isDataFlowEdge $ getOutEdges pg pn
phi_es = filter (isPhiNode . getTargetNode pg) es
in all (checkPhiValBlockMappings fg pg (c:st)) phi_es
else if isBlockNode pn
then let es = filter isDefEdge $ getInEdges pg pn
v_ns = map (getSourceNode pg) es
in all ( \n ->
let es' = filter isDataFlowEdge $ getOutEdges pg n
phi_es = filter (isPhiNode . getTargetNode pg) es'
in all (checkPhiValBlockMappings fg pg (c:st)) phi_es
) v_ns
else True
| For a given data - flow edge between a phi node and a value node in the
checkPhiValBlockMappings
:: Graph
-> Graph
-> [Mapping Node]
-> Edge
^ The pattern data - flow edge between the phi node and the value node to
-> Bool
checkPhiValBlockMappings fg pg st pe =
let findSingleFNInSt pn =
let n = findFNInMapping st pn
in if length n == 1
then Just $ head n
else if length n == 0
then Nothing
else error $ "checkPhiValBlockMappings: multiple mappings " ++
"for pattern node " ++ show pn
v_pn = getSourceNode pg pe
v_fn = findSingleFNInSt v_pn
p_pn = getTargetNode pg pe
p_fn = findSingleFNInSt p_pn
def_pes = filter (haveSameOutEdgeNrs pe) $
filter isDefEdge $
getOutEdges pg v_pn
def_pe = if length def_pes == 1
then head def_pes
else if length def_pes == 0
then error $ "checkPhiValBlockMappings: data-flow edge " ++
show pe ++ " in pattern graph has no " ++
" matching definition edge"
else error $ "checkPhiValBlockMappings: data-flow edge " ++
show pe ++ " in pattern graph has more " ++
"than one matching definition edge"
b_pn = getTargetNode pg def_pe
b_fn = findSingleFNInSt b_pn
in if isJust p_fn && isJust v_fn && isJust b_fn
then let df_fes = filter isDataFlowEdge $
getEdgesBetween fg (fromJust v_fn) (fromJust p_fn)
hasMatchingDefEdge fe =
let def_fes = filter (haveSameOutEdgeNrs fe) $
filter isDefEdge $
getOutEdges fg (getSourceNode fg fe)
in if length def_fes == 1
then getTargetNode fg (head def_fes) == fromJust b_fn
else False
in any hasMatchingDefEdge df_fes
else True
| Checks if two in - edges are equivalent , meaning they must be of the same
areInEdgesEquivalent
:: Graph
-> Edge
-> Edge
-> Bool
areInEdgesEquivalent g e1 e2 =
getEdgeType e1 == getEdgeType e2 &&
(getNodeID $ getTargetNode g e1) == (getNodeID $ getTargetNode g e2) &&
getEdgeInNr e1 == getEdgeInNr e2
| Checks if two out - edges are equivalent , meaning they must be of the same
areOutEdgesEquivalent
:: Graph
-> Edge
-> Edge
-> Bool
areOutEdgesEquivalent g e1 e2 =
getEdgeType e1 == getEdgeType e2 &&
(getNodeID $ getSourceNode g e1) == (getNodeID $ getSourceNode g e2) &&
getEdgeOutNr e1 == getEdgeOutNr e2
findPNsInMatch
:: (Eq n, Ord n)
=> Match n
-> [n]
-> [[n]]
findPNsInMatch m ns = map (findPNInMatch m) ns
findFNsInMatch
:: (Eq n, Ord n)
=> Match n
-> [n]
-> [[n]]
findFNsInMatch m ns = map (findFNInMatch m) ns
findPNInMatch
:: (Eq n, Ord n)
=> Match n
-> n
-> [n]
findPNInMatch m fn = M.findWithDefault [] fn (f2pMaps m)
findFNInMatch
:: (Eq n, Ord n)
=> Match n
-> n
-> [n]
findFNInMatch m pn = M.findWithDefault [] pn (p2fMaps m)
findPNsInMapping
:: (Eq n)
=> [Mapping n]
-> [n]
-> [[n]]
findPNsInMapping m fns = map (findPNInMapping m) fns
findFNsInMapping
:: (Eq n)
=> [Mapping n]
-> [n]
-> [[n]]
findFNsInMapping m pns = map (findFNInMapping m) pns
findPNInMapping
:: (Eq n)
=> [Mapping n]
-> n
-> [n]
findPNInMapping st fn = [ pNode m | m <- st, fn == fNode m ]
findFNInMapping
:: (Eq n)
=> [Mapping n]
-> n
-> [n]
findFNInMapping st pn = [ fNode m | m <- st, pn == pNode m ]
computeDomSets :: Graph -> Node -> [DomSet Node]
computeDomSets g n =
let int_g = intGraph g
mkNode = fromJust . getNodeWithIntNodeID int_g
doms = map ( \(n1, ns2) -> DomSet { domNode = mkNode n1
, domSet = map mkNode ns2
}
)
(I.dom int_g (getIntNodeID n))
in doms
isGraphEmpty :: Graph -> Bool
isGraphEmpty = I.isEmpty . intGraph
extractCFG :: Graph -> Graph
extractCFG g =
let nodes_to_remove = filter (\n -> not (isBlockNode n || isControlNode n)) $
getAllNodes g
cfg_with_ctrl_nodes = foldr delNode g nodes_to_remove
cfg = foldr delNodeKeepEdges
cfg_with_ctrl_nodes
(filter isControlNode $ getAllNodes cfg_with_ctrl_nodes)
in cfg
extractSSAG :: Graph -> Graph
extractSSAG g =
let nodes_to_remove =
filter ( \n -> not (isOperationNode n || isDatumNode n) ||
(isControlNode n && not (isRetControlNode n))
) $
getAllNodes g
ssa = foldr delNode g nodes_to_remove
in ssa
remove ( if there are more than one predecessor then the edges will be
redirected to one of them , but it is undefined which ) .
delNodeKeepEdges :: Node -> Graph -> Graph
delNodeKeepEdges n g =
let preds = getPredecessors g n
in if length preds > 0
then mergeNodes (head preds) n g
else delNode n g
returned . If there is more than one root , an error is produced .
rootInCFG :: Graph -> Maybe Node
rootInCFG g =
let roots = filter (\n -> length (getPredecessors g n) == 0) (getAllNodes g)
in if length roots > 0
then if length roots == 1
then Just $ head roots
else error "More than one root in CFG"
else Nothing
hasAnyPredecessors :: Graph -> Node -> Bool
hasAnyPredecessors g n = length (getPredecessors g n) > 0
hasAnySuccessors :: Graph -> Node -> Bool
hasAnySuccessors g n = length (getSuccessors g n) > 0
toMatch :: Ord n => [Mapping n] -> Match n
toMatch ms =
let insert (n1, n2) m = M.insertWith (++) n1 [n2] m
in Match { f2pMaps = foldr insert M.empty $
map (\m -> (fNode m, pNode m)) ms
, p2fMaps = foldr insert M.empty $
map (\m -> (pNode m, fNode m)) ms
}
fromMatch :: Ord n => Match n -> [Mapping n]
fromMatch m =
M.foldrWithKey
(\fn pns ms -> (ms ++ map (\pn -> Mapping { fNode = fn, pNode = pn }) pns))
[]
(f2pMaps m)
subGraph :: Graph -> [Node] -> Graph
subGraph g ns =
let sns = filter (\n -> n `elem` ns) $ getAllNodes g
ses = filter ( \e -> getSourceNode g e `elem` ns &&
getTargetNode g e `elem` ns
) $
getAllEdges g
entry = entryBlockNode g
new_entry = if isJust entry && (fromJust entry) `elem` sns
then entry
else Nothing
in mkGraph sns ses new_entry
| Checks if two edges have the same in - edge numbers .
haveSameInEdgeNrs :: Edge -> Edge -> Bool
haveSameInEdgeNrs e1 e2 = getEdgeInNr e1 == getEdgeInNr e2
| Checks if two edges have the same out - edge numbers .
haveSameOutEdgeNrs :: Edge -> Edge -> Bool
haveSameOutEdgeNrs e1 e2 = getEdgeOutNr e1 == getEdgeOutNr e2
groupNodesByID :: [Node] -> [(NodeID, [Node])]
groupNodesByID ns =
let ns_by_id = groupBy (\n1 n2 -> getNodeID n1 == getNodeID n2) ns
in map (\ns' -> (getNodeID $ head ns', ns')) ns_by_id
findDefEdgeOfDtInEdge :: Graph -> Edge -> [Edge]
findDefEdgeOfDtInEdge g e =
let v = getTargetNode g e
nr = getEdgeInNr e
def_es = filter (\e' -> getEdgeInNr e' == nr) $
getDefInEdges g v
in def_es
findDefEdgeOfDtOutEdge :: Graph -> Edge -> [Edge]
findDefEdgeOfDtOutEdge g e =
let v = getSourceNode g e
nr = getEdgeOutNr e
def_es = filter (\e' -> getEdgeOutNr e' == nr) $
getDefOutEdges g v
in def_es
delFNodeInMatch :: (Eq n, Ord n) => n -> Match n -> Match n
delFNodeInMatch fn m =
let pns = M.findWithDefault [] fn (f2pMaps m)
new_f2p_maps = M.delete fn (f2pMaps m)
new_p2f_maps = foldr (\pn m' -> M.update (Just . filter (/= fn)) pn m')
(p2fMaps m)
pns
in Match { f2pMaps = new_f2p_maps, p2fMaps = new_p2f_maps }
delPNodeInMatch :: (Eq n, Ord n) => n -> Match n -> Match n
delPNodeInMatch pn m =
let fns = M.findWithDefault [] pn (p2fMaps m)
new_p2f_maps = M.delete pn (p2fMaps m)
new_f2p_maps = foldr (\fn m' -> M.update (Just . filter (/= pn)) fn m')
(f2pMaps m)
fns
in Match { f2pMaps = new_f2p_maps, p2fMaps = new_p2f_maps }
mergeMatches :: (Eq n, Ord n) => [Match n] -> Match n
mergeMatches [] = error "mergeMatches: empty list"
mergeMatches ms =
let new_f2p_maps = M.unionsWith (++) $ map f2pMaps ms
new_p2f_maps = M.unionsWith (++) $ map p2fMaps ms
in Match { f2pMaps = new_f2p_maps, p2fMaps = new_p2f_maps }
addMappingToMatch :: (Eq n, Ord n) => Mapping n -> Match n -> Match n
addMappingToMatch m match =
let fn = fNode m
pn = pNode m
new_f2p_maps = M.insertWith (++) fn [pn] $ f2pMaps match
new_p2f_maps = M.insertWith (++) pn [fn] $ p2fMaps match
in Match { f2pMaps = new_f2p_maps, p2fMaps = new_p2f_maps }
updateFNodeInMatch
:: (Eq n, Ord n)
=> n
-> n
-> Match n
-> Match n
updateFNodeInMatch old_fn new_fn match =
let f2p_maps0 = f2pMaps match
(maybe_pns, f2p_maps1) = M.updateLookupWithKey (\_ _ -> Nothing)
old_fn
f2p_maps0
Do a lookup and delete in one go
pns = maybe [] id maybe_pns
f2p_maps2 = M.insert new_fn pns f2p_maps1
p2f_maps0 = p2fMaps match
p2f_maps1 = foldr (M.adjust (\pns' -> (new_fn:filter (/= old_fn) pns')))
p2f_maps0
pns
in Match { f2pMaps = f2p_maps2, p2fMaps = p2f_maps1 }
updatePNodeInMatch
:: (Eq n, Ord n)
=> n
-> n
-> Match n
-> Match n
updatePNodeInMatch old_pn new_pn match =
let p2f_maps0 = p2fMaps match
(maybe_fns, p2f_maps1) = M.updateLookupWithKey (\_ _ -> Nothing)
old_pn
p2f_maps0
Do a lookup and delete in one go
fns = maybe [] id maybe_fns
p2f_maps2 = M.insert new_pn fns p2f_maps1
f2p_maps0 = f2pMaps match
f2p_maps1 = foldr (M.adjust (\fns' -> (new_pn:filter (/= old_pn) fns')))
f2p_maps0
fns
in Match { f2pMaps = f2p_maps1, p2fMaps = p2f_maps2 }
getCopyRelatedValues :: Graph -> [[Node]]
getCopyRelatedValues g =
let v_ns = filter isValueNode $ getAllNodes g
copy_related_vs = filter ((> 1) . length) $
concat $
map ( groupBy ( \v1 v2 -> getDataTypeOfValueNode v1 ==
getDataTypeOfValueNode v2
)
) $
map (getCopiesOfValue g) v_ns
in copy_related_vs
getCopiesOfValue :: Graph -> Node -> [Node]
getCopiesOfValue g n =
let es = getDtFlowOutEdges g n
copies = filter isCopyNode $ map (getTargetNode g) es
cp_vs = map ( \n' ->
let es' = getDtFlowOutEdges g n'
in if length es' == 1
then getTargetNode g (head es')
else if length es' == 0
then error $
"getCopiesOfValue: " ++ show n' ++
" has no data-flow edges"
else error $
"getCopiesOfValue: " ++ show n' ++
" has multiple data-flow edges"
) $
copies
in cp_vs
|
1cd4afc036ca25ccd559f9e56b7f1f600c39d579576898953438b2f8f42879d5
|
mikpe/pdp10-tools
|
ld_input.erl
|
-*- erlang - indent - level : 2 -*-
%%%
input processing for pdp10 - elf ld
Copyright ( C ) 2020
%%%
This file is part of pdp10 - tools .
%%%
pdp10 - tools 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.
%%%
pdp10 - tools 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 pdp10 - tools . If not , see < / > .
-module(ld_input).
-export([ input/2
, format_error/1
]).
-include("ld_internal.hrl").
%% error reasons
-define(badelf, badelf).
-define(badfile, badfile).
-define(muldef_symbol, muldef_symbol).
-define(noinputfiles, noinputfiles).
-define(undefined_symbols, undefined_symbols).
%% Input Processing ============================================================
-spec input([{file, string()}], [string()])
-> {ok, [#input{}]} | {error, {module(), term()}}.
input(_Files = [], _UndefSyms) -> {error, {?MODULE, ?noinputfiles}};
input(Files, UndefSyms) ->
UndefMap =
lists:foldl(fun(UndefSym, UndefMap0) ->
maps:put(UndefSym, false, UndefMap0)
end, maps:new(), UndefSyms),
input(Files, maps:new(), UndefMap, []).
input([{file, File} | Files], DefMap, UndefMap, Inputs) ->
case read_file(File) of
{ok, {ShTab, SymTab, StShNdx}} ->
case update_sym_maps(SymTab, File, DefMap, UndefMap) of
{ok, {NewDefMap, NewUndefMap}} ->
Input = #input{file = File, shtab = ShTab, symtab = SymTab, stshndx = StShNdx},
input(Files, NewDefMap, NewUndefMap, [Input | Inputs]);
{error, _Reason} = Error -> Error
end;
{error, _Reason} = Error -> Error
end;
input([], _DefMap, UndefMap, Inputs) ->
case maps:keys(UndefMap) of
[] -> {ok, lists:reverse(Inputs)};
UndefSyms -> {error, {?MODULE, {?undefined_symbols, UndefSyms}}}
end.
update_sym_maps([Sym | Syms], File, DefMap, UndefMap) ->
case do_update_sym_maps(Sym, File, DefMap, UndefMap) of
{ok, {NewDefMap, NewUndefMap}} ->
update_sym_maps(Syms, File, NewDefMap, NewUndefMap);
{error, _Reason} = Error -> Error
end;
update_sym_maps([], _File, DefMap, UndefMap) ->
{ok, {DefMap, UndefMap}}.
do_update_sym_maps(Sym, File, DefMap, UndefMap) ->
#elf36_Sym{st_name = Name} = Sym,
case classify_sym(Sym) of
local -> {ok, {DefMap, UndefMap}};
undefined ->
case maps:is_key(Name, DefMap) of
true -> {ok, {DefMap, UndefMap}};
false ->
case maps:is_key(Name, UndefMap) of
true -> {ok, {DefMap, UndefMap}};
false -> {ok, {DefMap, maps:put(Name, File, UndefMap)}}
end
end;
defined ->
case maps:get(Name, DefMap, false) of
false -> {ok, {maps:put(Name, File, DefMap), maps:remove(Name, UndefMap)}};
File0 -> {error, {?MODULE, {?muldef_symbol, Name, File0, File}}}
end
end.
classify_sym(Sym) ->
case ?ELF36_ST_BIND(Sym#elf36_Sym.st_info) of
?STB_GLOBAL ->
case Sym#elf36_Sym.st_shndx of
?SHN_UNDEF -> undefined;
_ -> defined
end;
_ -> local
end.
read_file(File) ->
case pdp10_stdio:fopen(File, [read]) of
{ok, FP} ->
try read_file(File, FP)
after pdp10_stdio:fclose(FP)
end;
{error, Reason} -> {error, {?MODULE, {?badfile, File, Reason}}}
end.
read_file(File, FP) ->
case pdp10_elf36:read_Ehdr(FP) of
{ok, Ehdr} ->
case pdp10_elf36:read_ShTab(FP, Ehdr) of
{ok, ShTab} ->
case pdp10_elf36:read_SymTab(FP, ShTab) of
{ok, {SymTab, ShNdx}} -> {ok, {ShTab, SymTab, ShNdx}};
{error, Reason} -> badelf(File, Reason)
end;
{error, Reason} -> badelf(File, Reason)
end;
{error, Reason} -> badelf(File, Reason)
end.
badelf(File, Reason) ->
{error, {?MODULE, {?badelf, File, Reason}}}.
%% Error Formatting ============================================================
-spec format_error(term()) -> io_lib:chars().
format_error(Reason) ->
case Reason of
{?badelf, File, Reason} ->
io:format("invalid ELF file ~s: ~s", [File, error:format(Reason)]);
{?badfile, File, Reason} ->
io:format("~s: ~s", [File, error:format(Reason)]);
{?muldef_symbol, Symbol, File0, File} ->
io:format("~s: ~s already defined in ~s", [File, Symbol, File0]);
?noinputfiles ->
"no input files";
{?undefined_symbols, Symbols} ->
["undefined symbols:" |
["\n" ++ Symbol || Symbol <- Symbols]]
end.
| null |
https://raw.githubusercontent.com/mikpe/pdp10-tools/99216b63317fe5b5ac18f1a0d3c81b464f8b8f40/erlang/apps/ld/src/ld_input.erl
|
erlang
|
(at your option) any later version.
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.
error reasons
Input Processing ============================================================
Error Formatting ============================================================
|
-*- erlang - indent - level : 2 -*-
input processing for pdp10 - elf ld
Copyright ( C ) 2020
This file is part of pdp10 - tools .
pdp10 - tools 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
pdp10 - tools is distributed in the hope that it will be useful ,
You should have received a copy of the GNU General Public License
along with pdp10 - tools . If not , see < / > .
-module(ld_input).
-export([ input/2
, format_error/1
]).
-include("ld_internal.hrl").
-define(badelf, badelf).
-define(badfile, badfile).
-define(muldef_symbol, muldef_symbol).
-define(noinputfiles, noinputfiles).
-define(undefined_symbols, undefined_symbols).
-spec input([{file, string()}], [string()])
-> {ok, [#input{}]} | {error, {module(), term()}}.
input(_Files = [], _UndefSyms) -> {error, {?MODULE, ?noinputfiles}};
input(Files, UndefSyms) ->
UndefMap =
lists:foldl(fun(UndefSym, UndefMap0) ->
maps:put(UndefSym, false, UndefMap0)
end, maps:new(), UndefSyms),
input(Files, maps:new(), UndefMap, []).
input([{file, File} | Files], DefMap, UndefMap, Inputs) ->
case read_file(File) of
{ok, {ShTab, SymTab, StShNdx}} ->
case update_sym_maps(SymTab, File, DefMap, UndefMap) of
{ok, {NewDefMap, NewUndefMap}} ->
Input = #input{file = File, shtab = ShTab, symtab = SymTab, stshndx = StShNdx},
input(Files, NewDefMap, NewUndefMap, [Input | Inputs]);
{error, _Reason} = Error -> Error
end;
{error, _Reason} = Error -> Error
end;
input([], _DefMap, UndefMap, Inputs) ->
case maps:keys(UndefMap) of
[] -> {ok, lists:reverse(Inputs)};
UndefSyms -> {error, {?MODULE, {?undefined_symbols, UndefSyms}}}
end.
update_sym_maps([Sym | Syms], File, DefMap, UndefMap) ->
case do_update_sym_maps(Sym, File, DefMap, UndefMap) of
{ok, {NewDefMap, NewUndefMap}} ->
update_sym_maps(Syms, File, NewDefMap, NewUndefMap);
{error, _Reason} = Error -> Error
end;
update_sym_maps([], _File, DefMap, UndefMap) ->
{ok, {DefMap, UndefMap}}.
do_update_sym_maps(Sym, File, DefMap, UndefMap) ->
#elf36_Sym{st_name = Name} = Sym,
case classify_sym(Sym) of
local -> {ok, {DefMap, UndefMap}};
undefined ->
case maps:is_key(Name, DefMap) of
true -> {ok, {DefMap, UndefMap}};
false ->
case maps:is_key(Name, UndefMap) of
true -> {ok, {DefMap, UndefMap}};
false -> {ok, {DefMap, maps:put(Name, File, UndefMap)}}
end
end;
defined ->
case maps:get(Name, DefMap, false) of
false -> {ok, {maps:put(Name, File, DefMap), maps:remove(Name, UndefMap)}};
File0 -> {error, {?MODULE, {?muldef_symbol, Name, File0, File}}}
end
end.
classify_sym(Sym) ->
case ?ELF36_ST_BIND(Sym#elf36_Sym.st_info) of
?STB_GLOBAL ->
case Sym#elf36_Sym.st_shndx of
?SHN_UNDEF -> undefined;
_ -> defined
end;
_ -> local
end.
read_file(File) ->
case pdp10_stdio:fopen(File, [read]) of
{ok, FP} ->
try read_file(File, FP)
after pdp10_stdio:fclose(FP)
end;
{error, Reason} -> {error, {?MODULE, {?badfile, File, Reason}}}
end.
read_file(File, FP) ->
case pdp10_elf36:read_Ehdr(FP) of
{ok, Ehdr} ->
case pdp10_elf36:read_ShTab(FP, Ehdr) of
{ok, ShTab} ->
case pdp10_elf36:read_SymTab(FP, ShTab) of
{ok, {SymTab, ShNdx}} -> {ok, {ShTab, SymTab, ShNdx}};
{error, Reason} -> badelf(File, Reason)
end;
{error, Reason} -> badelf(File, Reason)
end;
{error, Reason} -> badelf(File, Reason)
end.
badelf(File, Reason) ->
{error, {?MODULE, {?badelf, File, Reason}}}.
-spec format_error(term()) -> io_lib:chars().
format_error(Reason) ->
case Reason of
{?badelf, File, Reason} ->
io:format("invalid ELF file ~s: ~s", [File, error:format(Reason)]);
{?badfile, File, Reason} ->
io:format("~s: ~s", [File, error:format(Reason)]);
{?muldef_symbol, Symbol, File0, File} ->
io:format("~s: ~s already defined in ~s", [File, Symbol, File0]);
?noinputfiles ->
"no input files";
{?undefined_symbols, Symbols} ->
["undefined symbols:" |
["\n" ++ Symbol || Symbol <- Symbols]]
end.
|
6fbe70f23036710df2a23269bac5818f2f88f6f766e3fa3c6b5ffa744d54c27d
|
williamleferrand/aws
|
eC2.mli
|
val describe_regions :
?expires_minutes:int ->
Creds.t ->
(string * string) list Lwt.t
(* return a list of region identifiers and their associated api url *)
type instance_type = [
| `m1_small
| `m1_large
| `m1_xlarge
| `c1_medium
| `c1_xlarge
| `m2_xlarge
| `m2_2xlarge
| `m2_4xlarge
| `cc1_4xlarge
| `cg1_4xlarge
| `t1_micro
]
val string_of_instance_type : instance_type -> string
val instance_type_of_string : string -> instance_type option
val describe_spot_price_history :
?expires_minutes:int ->
?region:string ->
?instance_type:instance_type ->
Creds.t -> <
instance_type : string;
product_description : string;
spot_price : float;
timestamp : float
> list Lwt.t
type instance_state = [
| `pending
| `running
| `shutting_down
| `terminated
| `stopping
| `stopped
]
val string_of_instance_state : instance_state -> string
val terminate_instances :
?expires_minutes:int ->
?region:string ->
Creds.t ->
string list ->
[> `Error of string
| `Ok of <
current_state : instance_state;
instance_id : string;
previous_state : instance_state
> list
] Lwt.t
type instance = <
id : string;
ami_launch_index : int;
architecture_opt : string option;
placement_availability_zone_opt : string option;
dns_name_opt : string option;
placement_group_opt : string option;
image_id : string;
instance_type : instance_type;
ip_address_opt : string option;
kernel_id_opt : string option;
key_name_opt : string option;
launch_time : float;
lifecycle_opt : string option;
private_dns_name_opt : string option;
private_ip_address_opt : string option;
ramdisk_id_opt : string option;
reason_opt : string option;
root_device_name_opt : string option;
root_device_type : string;
state : instance_state;
virtualization_type_opt : string option;
monitoring : string
>
type reservation = <
id : string;
groups : string list;
owner_id : string;
instances : instance list
>
val describe_instances :
?expires_minutes:int ->
?region:string ->
Creds.t ->
string list ->
[> `Error of string | `Ok of reservation list ] Lwt.t
val run_instances :
?expires_minutes:int ->
?key_name:string ->
?placement_availability_zone:string ->
?region:string ->
?placement_group:string ->
?instance_type:instance_type ->
Creds.t ->
image_id:string ->
min_count:int ->
max_count:int ->
[> `Error of string | `Ok of reservation ] Lwt.t
type spot_instance_request_type = [`OneTime | `Persistent]
val string_of_spot_instance_request_type : spot_instance_request_type -> string
type spot_instance_request_state = [ `Active | `Open | `Closed | `Cancelled | `Failed ]
val string_of_spot_instance_request_state : spot_instance_request_state -> string
type spot_instance_request = {
sir_spot_price : float ;
sir_instance_count : int option;
sir_type : spot_instance_request_type option;
sir_valid_from : float option;
sir_valid_until: float option;
sir_launch_group : string option;
sir_image_id : string ;
sir_security_group : string option ;
sir_user_data : string option;
sir_instance_type : instance_type option;
sir_kernel_id : string option;
sir_ramdisk_id : string option;
sir_availability_zone : string option;
sir_monitoring_enabled : bool option;
sir_key_name : string option;
sir_availability_zone_group : string option;
sir_placement_group : string option;
as distinct from LaunchGroup ; assuming this works , although not documented
}
val minimal_spot_instance_request :
spot_price:float ->
image_id:string ->
spot_instance_request
type spot_instance_request_description = <
id : string;
instance_id_opt : string option;
sir_type : spot_instance_request_type;
spot_price : float;
state : spot_instance_request_state;
image_id_opt : string option;
key_name_opt : string option;
groups : string list;
placement_group_opt : string option;
>
val request_spot_instances :
?region:string ->
Creds.t ->
spot_instance_request ->
[> `Error of string | `Ok of spot_instance_request_description list ] Lwt.t
val describe_spot_instance_requests :
?region:string ->
Creds.t ->
string list ->
[> `Error of string | `Ok of spot_instance_request_description list ] Lwt.t
(* [describe_spot_instance_requests region ~return creds ids] returns
a description of the spot instance requests associated with each of
the id's in [ids]; when [ids] is an empty list, all the spot
instance request descriptions are returned. *)
val cancel_spot_instance_requests :
?region:string ->
Creds.t ->
string list ->
[> `Error of string | `Ok of (string * spot_instance_request_state) list ] Lwt.t
(** return a list of spot instance request id's and their associated state *)
| null |
https://raw.githubusercontent.com/williamleferrand/aws/d591ef0a2b89082caac6ddd6850b2d8b7824e577/src/sig/eC2.mli
|
ocaml
|
return a list of region identifiers and their associated api url
[describe_spot_instance_requests region ~return creds ids] returns
a description of the spot instance requests associated with each of
the id's in [ids]; when [ids] is an empty list, all the spot
instance request descriptions are returned.
* return a list of spot instance request id's and their associated state
|
val describe_regions :
?expires_minutes:int ->
Creds.t ->
(string * string) list Lwt.t
type instance_type = [
| `m1_small
| `m1_large
| `m1_xlarge
| `c1_medium
| `c1_xlarge
| `m2_xlarge
| `m2_2xlarge
| `m2_4xlarge
| `cc1_4xlarge
| `cg1_4xlarge
| `t1_micro
]
val string_of_instance_type : instance_type -> string
val instance_type_of_string : string -> instance_type option
val describe_spot_price_history :
?expires_minutes:int ->
?region:string ->
?instance_type:instance_type ->
Creds.t -> <
instance_type : string;
product_description : string;
spot_price : float;
timestamp : float
> list Lwt.t
type instance_state = [
| `pending
| `running
| `shutting_down
| `terminated
| `stopping
| `stopped
]
val string_of_instance_state : instance_state -> string
val terminate_instances :
?expires_minutes:int ->
?region:string ->
Creds.t ->
string list ->
[> `Error of string
| `Ok of <
current_state : instance_state;
instance_id : string;
previous_state : instance_state
> list
] Lwt.t
type instance = <
id : string;
ami_launch_index : int;
architecture_opt : string option;
placement_availability_zone_opt : string option;
dns_name_opt : string option;
placement_group_opt : string option;
image_id : string;
instance_type : instance_type;
ip_address_opt : string option;
kernel_id_opt : string option;
key_name_opt : string option;
launch_time : float;
lifecycle_opt : string option;
private_dns_name_opt : string option;
private_ip_address_opt : string option;
ramdisk_id_opt : string option;
reason_opt : string option;
root_device_name_opt : string option;
root_device_type : string;
state : instance_state;
virtualization_type_opt : string option;
monitoring : string
>
type reservation = <
id : string;
groups : string list;
owner_id : string;
instances : instance list
>
val describe_instances :
?expires_minutes:int ->
?region:string ->
Creds.t ->
string list ->
[> `Error of string | `Ok of reservation list ] Lwt.t
val run_instances :
?expires_minutes:int ->
?key_name:string ->
?placement_availability_zone:string ->
?region:string ->
?placement_group:string ->
?instance_type:instance_type ->
Creds.t ->
image_id:string ->
min_count:int ->
max_count:int ->
[> `Error of string | `Ok of reservation ] Lwt.t
type spot_instance_request_type = [`OneTime | `Persistent]
val string_of_spot_instance_request_type : spot_instance_request_type -> string
type spot_instance_request_state = [ `Active | `Open | `Closed | `Cancelled | `Failed ]
val string_of_spot_instance_request_state : spot_instance_request_state -> string
type spot_instance_request = {
sir_spot_price : float ;
sir_instance_count : int option;
sir_type : spot_instance_request_type option;
sir_valid_from : float option;
sir_valid_until: float option;
sir_launch_group : string option;
sir_image_id : string ;
sir_security_group : string option ;
sir_user_data : string option;
sir_instance_type : instance_type option;
sir_kernel_id : string option;
sir_ramdisk_id : string option;
sir_availability_zone : string option;
sir_monitoring_enabled : bool option;
sir_key_name : string option;
sir_availability_zone_group : string option;
sir_placement_group : string option;
as distinct from LaunchGroup ; assuming this works , although not documented
}
val minimal_spot_instance_request :
spot_price:float ->
image_id:string ->
spot_instance_request
type spot_instance_request_description = <
id : string;
instance_id_opt : string option;
sir_type : spot_instance_request_type;
spot_price : float;
state : spot_instance_request_state;
image_id_opt : string option;
key_name_opt : string option;
groups : string list;
placement_group_opt : string option;
>
val request_spot_instances :
?region:string ->
Creds.t ->
spot_instance_request ->
[> `Error of string | `Ok of spot_instance_request_description list ] Lwt.t
val describe_spot_instance_requests :
?region:string ->
Creds.t ->
string list ->
[> `Error of string | `Ok of spot_instance_request_description list ] Lwt.t
val cancel_spot_instance_requests :
?region:string ->
Creds.t ->
string list ->
[> `Error of string | `Ok of (string * spot_instance_request_state) list ] Lwt.t
|
b7c62162952acd704b61152e60e9b0c12b709446eef96b6abed10a76519876ab
|
mirage/ocaml-matrix
|
room_listing.ml
|
open Json_encoding
open Matrix_common
module Get_visibility = struct
module Query = Empty.Query
module Response = struct
type t = {visibility: Room.Visibility.t} [@@deriving accessor]
let encoding =
let to_tuple t = t.visibility in
let of_tuple v =
let visibility = v in
{visibility} in
let with_tuple = obj1 (req "visibility" Room.Visibility.encoding) in
conv to_tuple of_tuple with_tuple
end
end
module Set_visibility = struct
module Query = Empty.Query
module Request = struct
type t = {visibility: Room.Visibility.t option} [@@deriving accessor]
let encoding =
let to_tuple t = t.visibility in
let of_tuple v =
let visibility = v in
{visibility} in
let with_tuple = obj1 (opt "visibility" Room.Visibility.encoding) in
conv to_tuple of_tuple with_tuple
end
module Response = Empty.Json
end
module Get_public_rooms = struct
module Query = struct
type t = {limit: int option; since: string option; server: string option}
[@@deriving accessor]
let args t =
let l =
match t.limit with
| None -> []
| Some limit -> ["limit", [Int.to_string limit]] in
let l =
match t.since with None -> l | Some since -> ("since", [since]) :: l
in
match t.server with None -> l | Some server -> ("server", [server]) :: l
end
module Response = struct
module Public_rooms_chunk = struct
type t = {
aliases: string list option;
canonical_alias: string option;
name: string option;
num_joined_members: int;
room_id: string;
topic: string option;
world_readable: bool;
guest_can_join: bool;
avatar_url: string option;
federate: bool option;
(* What ? I was supposed to follow the documentation ? - field present when calling synapse but not in the documentation *)
}
[@@deriving accessor]
let encoding =
let to_tuple t =
( t.aliases,
t.canonical_alias,
t.name,
t.num_joined_members,
t.room_id,
t.topic,
t.world_readable,
t.guest_can_join,
t.avatar_url,
t.federate ) in
let of_tuple v =
let ( aliases,
canonical_alias,
name,
num_joined_members,
room_id,
topic,
world_readable,
guest_can_join,
avatar_url,
federate ) =
v in
{
aliases;
canonical_alias;
name;
num_joined_members;
room_id;
topic;
world_readable;
guest_can_join;
avatar_url;
federate;
} in
let with_tuple =
obj10
(opt "aliases" (list string))
(opt "canonical_alias" string)
(opt "name" string)
(req "num_joined_members" int)
(req "room_id" string) (opt "topic" string)
(req "world_readable" bool)
(req "guest_can_join" bool)
(opt "avatar_url" string) (opt "m.federate" bool) in
conv to_tuple of_tuple with_tuple
end
type t = {
chunk: Public_rooms_chunk.t list;
next_batch: string option;
prev_batch: string option;
total_room_count_estimate: int option;
}
[@@deriving accessor]
let encoding =
let to_tuple t =
t.chunk, t.next_batch, t.prev_batch, t.total_room_count_estimate in
let of_tuple v =
let chunk, next_batch, prev_batch, total_room_count_estimate = v in
{chunk; next_batch; prev_batch; total_room_count_estimate} in
let with_tuple =
obj4
(req "chunk" (list Public_rooms_chunk.encoding))
(opt "next_batch" string) (opt "prev_batch" string)
(opt "total_room_count_estimate" int) in
conv to_tuple of_tuple with_tuple
end
end
module Filter_public_rooms = struct
module Query = struct
type t = {server: string option} [@@deriving accessor]
let args t =
match t.server with None -> [] | Some server -> ["server", [server]]
end
module Request = struct
module Filter = struct
type t = {generic_search_term: string option} [@@deriving accessor]
let encoding =
let to_tuple t = t.generic_search_term in
let of_tuple v =
let generic_search_term = v in
{generic_search_term} in
let with_tuple = obj1 (opt "generic_search_term" string) in
conv to_tuple of_tuple with_tuple
end
type t = {
limit: int option;
since: string option;
filter: Filter.t option;
include_all_networks: bool option;
third_party_instance_id: string option;
}
[@@deriving accessor]
let encoding =
let to_tuple t =
( t.limit,
t.since,
t.filter,
t.include_all_networks,
t.third_party_instance_id ) in
let of_tuple v =
let limit, since, filter, include_all_networks, third_party_instance_id
=
v in
{limit; since; filter; include_all_networks; third_party_instance_id}
in
let with_tuple =
obj5 (opt "limit" int) (opt "since" string)
(opt "filter" Filter.encoding)
(opt "include_all_networks" bool)
(opt "third_party_instance_id" string) in
conv to_tuple of_tuple with_tuple
end
module Response = Get_public_rooms.Response
end
| null |
https://raw.githubusercontent.com/mirage/ocaml-matrix/2a58d3d41c43404741f2dfdaf1d2d0f3757b2b69/lib/matrix-ctos/room_listing.ml
|
ocaml
|
What ? I was supposed to follow the documentation ? - field present when calling synapse but not in the documentation
|
open Json_encoding
open Matrix_common
module Get_visibility = struct
module Query = Empty.Query
module Response = struct
type t = {visibility: Room.Visibility.t} [@@deriving accessor]
let encoding =
let to_tuple t = t.visibility in
let of_tuple v =
let visibility = v in
{visibility} in
let with_tuple = obj1 (req "visibility" Room.Visibility.encoding) in
conv to_tuple of_tuple with_tuple
end
end
module Set_visibility = struct
module Query = Empty.Query
module Request = struct
type t = {visibility: Room.Visibility.t option} [@@deriving accessor]
let encoding =
let to_tuple t = t.visibility in
let of_tuple v =
let visibility = v in
{visibility} in
let with_tuple = obj1 (opt "visibility" Room.Visibility.encoding) in
conv to_tuple of_tuple with_tuple
end
module Response = Empty.Json
end
module Get_public_rooms = struct
module Query = struct
type t = {limit: int option; since: string option; server: string option}
[@@deriving accessor]
let args t =
let l =
match t.limit with
| None -> []
| Some limit -> ["limit", [Int.to_string limit]] in
let l =
match t.since with None -> l | Some since -> ("since", [since]) :: l
in
match t.server with None -> l | Some server -> ("server", [server]) :: l
end
module Response = struct
module Public_rooms_chunk = struct
type t = {
aliases: string list option;
canonical_alias: string option;
name: string option;
num_joined_members: int;
room_id: string;
topic: string option;
world_readable: bool;
guest_can_join: bool;
avatar_url: string option;
federate: bool option;
}
[@@deriving accessor]
let encoding =
let to_tuple t =
( t.aliases,
t.canonical_alias,
t.name,
t.num_joined_members,
t.room_id,
t.topic,
t.world_readable,
t.guest_can_join,
t.avatar_url,
t.federate ) in
let of_tuple v =
let ( aliases,
canonical_alias,
name,
num_joined_members,
room_id,
topic,
world_readable,
guest_can_join,
avatar_url,
federate ) =
v in
{
aliases;
canonical_alias;
name;
num_joined_members;
room_id;
topic;
world_readable;
guest_can_join;
avatar_url;
federate;
} in
let with_tuple =
obj10
(opt "aliases" (list string))
(opt "canonical_alias" string)
(opt "name" string)
(req "num_joined_members" int)
(req "room_id" string) (opt "topic" string)
(req "world_readable" bool)
(req "guest_can_join" bool)
(opt "avatar_url" string) (opt "m.federate" bool) in
conv to_tuple of_tuple with_tuple
end
type t = {
chunk: Public_rooms_chunk.t list;
next_batch: string option;
prev_batch: string option;
total_room_count_estimate: int option;
}
[@@deriving accessor]
let encoding =
let to_tuple t =
t.chunk, t.next_batch, t.prev_batch, t.total_room_count_estimate in
let of_tuple v =
let chunk, next_batch, prev_batch, total_room_count_estimate = v in
{chunk; next_batch; prev_batch; total_room_count_estimate} in
let with_tuple =
obj4
(req "chunk" (list Public_rooms_chunk.encoding))
(opt "next_batch" string) (opt "prev_batch" string)
(opt "total_room_count_estimate" int) in
conv to_tuple of_tuple with_tuple
end
end
module Filter_public_rooms = struct
module Query = struct
type t = {server: string option} [@@deriving accessor]
let args t =
match t.server with None -> [] | Some server -> ["server", [server]]
end
module Request = struct
module Filter = struct
type t = {generic_search_term: string option} [@@deriving accessor]
let encoding =
let to_tuple t = t.generic_search_term in
let of_tuple v =
let generic_search_term = v in
{generic_search_term} in
let with_tuple = obj1 (opt "generic_search_term" string) in
conv to_tuple of_tuple with_tuple
end
type t = {
limit: int option;
since: string option;
filter: Filter.t option;
include_all_networks: bool option;
third_party_instance_id: string option;
}
[@@deriving accessor]
let encoding =
let to_tuple t =
( t.limit,
t.since,
t.filter,
t.include_all_networks,
t.third_party_instance_id ) in
let of_tuple v =
let limit, since, filter, include_all_networks, third_party_instance_id
=
v in
{limit; since; filter; include_all_networks; third_party_instance_id}
in
let with_tuple =
obj5 (opt "limit" int) (opt "since" string)
(opt "filter" Filter.encoding)
(opt "include_all_networks" bool)
(opt "third_party_instance_id" string) in
conv to_tuple of_tuple with_tuple
end
module Response = Get_public_rooms.Response
end
|
eb8089ed8f02057c98446afb5ce54802c2510249837a285846fc486897a6470d
|
8c6794b6/haskell-sc-scratch
|
SbHeap.hs
|
{-# LANGUAGE BangPatterns #-}
# LANGUAGE NoImplicitPrelude #
|
Module : $ Header$
CopyRight : ( c ) 8c6794b6
License : :
Stability : unstable
Portability : non - portable
Scratch written while reading /Purely Functional Fata Structure/ , by .
This codes contains skew binomial heap , shown in figure 6.10 .
Module : $Header$
CopyRight : (c) 8c6794b6
License : BSD3
Maintainer :
Stability : unstable
Portability : non-portable
Scratch written while reading /Purely Functional Fata Structure/, by Chris Okasaki.
This codes contains skew binomial heap, shown in figure 6.10.
-}
module Data.BsbHeap.SbHeap where
import Prelude hiding (null)
import qualified Prelude as P
import Control.DeepSeq (NFData(..))
import Data.BsbHeap.Exception
------------------------------------------------------------------------------
--
-- * Tree for skew binomial heap.
--
data Tree a = Node {-# UNPACK #-} !Int !a [a] [Tree a]
deriving Show
instance Eq a => Eq (Tree a) where
# INLINE (= =) #
Node r1 x1 xs1 ts1 == Node r2 x2 xs2 ts2 =
r1 == r2 && x1 == x2 && xs1 == xs2 && ts1 == ts2
instance Functor Tree where
# INLINE fmap #
fmap f (Node r x xs ts) = Node r (f x) (map f xs) (map (fmap f) ts)
instance NFData a => NFData (Tree a) where
# INLINE rnf #
rnf (Node i x ns ts) = rnf i `seq` rnf x `seq` rnf ns `seq` rnf ts
rank :: Tree a -> Int
rank (Node !r _ _ _) = r
# INLINE rank #
root :: Tree a -> a
root (Node _ !x _ _) = x
# INLINE root #
link :: Ord a => Tree a -> Tree a -> Tree a
link t1@(Node !r !x1 xs1 c1) t2@(Node _ !x2 xs2 c2)
| x1 <= x2 = Node (r+1) x1 xs1 (t2:c1)
| otherwise = Node (r+1) x2 xs2 (t1:c2)
# INLINE link #
skewLink :: Ord a => a -> Tree a -> Tree a -> Tree a
skewLink !x t1 t2 = case link t1 t2 of
Node !r !y ys c
| x <= y -> Node r x (y:ys) c
| otherwise -> Node r y (x:ys) c
# INLINE skewLink #
insTree :: Ord a => Tree a -> [Tree a] -> [Tree a]
insTree t ts = case ts of
[] -> [t]
(t'):ts'
| rank t < rank t' -> t:t':ts'
| otherwise -> insTree (link t t') ts'
# INLINE insTree #
mergeTrees :: Ord a => [Tree a] -> [Tree a] -> [Tree a]
mergeTrees ts1 ts2 = case (ts1,ts2) of
(_,[]) -> ts1
([],_) -> ts2
(t1:ts1', t2:ts2')
| rank t1 < rank t2 -> t1 : mergeTrees ts1' ts2
| rank t1 > rank t2 -> t2 : mergeTrees ts1 ts2'
| otherwise -> insTree (link t1 t2) (mergeTrees ts1' ts2')
# INLINE mergeTrees #
normalize :: Ord a => [Tree a] -> [Tree a]
normalize ts = case ts of
[] -> []
(t:ts') -> insTree t ts'
# INLINE normalize #
------------------------------------------------------------------------------
--
-- * Functions for heap
--
newtype SbHeap a = SbHeap [Tree a] deriving (Show)
instance Eq a => Eq (SbHeap a) where
# INLINE (= =) #
SbHeap as == SbHeap bs = as == bs
instance Functor SbHeap where
fmap f (SbHeap ts) = SbHeap (map (fmap f) ts)
instance NFData a => NFData (SbHeap a) where
# INLINE rnf #
rnf (SbHeap xs) = rnf xs
empty :: SbHeap a
empty = SbHeap []
{-# INLINE empty #-}
null :: SbHeap a -> Bool
null (SbHeap hs) = P.null hs
# INLINE null #
insert :: Ord a => a -> SbHeap a -> SbHeap a
insert !x (SbHeap ts) = SbHeap $ case ts of
(t1:t2:rest)
| rank t1 == rank t2 -> skewLink x t1 t2 : rest
| otherwise -> Node 0 x [] [] : ts
_ -> Node 0 x [] [] : ts
# INLINE insert #
merge :: Ord a => SbHeap a -> SbHeap a -> SbHeap a
merge (SbHeap ts1) (SbHeap ts2) =
SbHeap $ mergeTrees (normalize ts1) (normalize ts2)
# INLINE merge #
findMin :: Ord a => SbHeap a -> a
findMin (SbHeap ts) = case ts of
[] -> emptyHeap
[t] -> root t
(t:ts') -> case (root t, findMin (SbHeap ts')) of
(!x,!y) | x <= y -> x
| otherwise -> y
# INLINE findMin #
deleteMin :: Ord a => SbHeap a -> SbHeap a
deleteMin (SbHeap ts) = case ts of
[] -> emptyHeap
_ ->
let (Node _ _ xs c, ts') = getMin ts
in SbHeap $ insertAll xs (mergeTrees (reverse c) (normalize ts'))
# INLINE deleteMin #
getMin :: Ord a => [Tree a] -> (Tree a, [Tree a])
getMin xs = case xs of
[] -> treeIndexOutOfRange
[y] -> (y,[])
(y:ys) -> case getMin ys of
(z,zs) | root y <= root z -> (y,ys)
| otherwise -> (z,y:zs)
# INLINE getMin #
insertAll :: Ord a => [a] -> [Tree a] -> [Tree a]
insertAll as bs = case (as,bs) of
([],_) -> bs
((!a):as',_) -> case insert a (SbHeap bs) of SbHeap bs' -> insertAll as' bs'
# INLINE insertAll #
toList :: SbHeap a -> [a]
toList (SbHeap ts) = concatMap go ts where
go (Node _ r rs ns) = r : rs ++ concatMap go ns
# INLINE toList #
toSortedList :: Ord a => SbHeap a -> [a]
toSortedList (SbHeap ts) = go ts where
go ns = case ns of
[] -> []
_ -> case getMin ns of
(Node _ x xs c, ns') ->
x : go (insertAll xs (mergeTrees (reverse c) (normalize ns')))
# INLINE toSortedList #
| null |
https://raw.githubusercontent.com/8c6794b6/haskell-sc-scratch/22de2199359fa56f256b544609cd6513b5e40f43/Scratch/Data/bsb-heap/Data/BsbHeap/SbHeap.hs
|
haskell
|
# LANGUAGE BangPatterns #
----------------------------------------------------------------------------
* Tree for skew binomial heap.
# UNPACK #
----------------------------------------------------------------------------
* Functions for heap
# INLINE empty #
|
# LANGUAGE NoImplicitPrelude #
|
Module : $ Header$
CopyRight : ( c ) 8c6794b6
License : :
Stability : unstable
Portability : non - portable
Scratch written while reading /Purely Functional Fata Structure/ , by .
This codes contains skew binomial heap , shown in figure 6.10 .
Module : $Header$
CopyRight : (c) 8c6794b6
License : BSD3
Maintainer :
Stability : unstable
Portability : non-portable
Scratch written while reading /Purely Functional Fata Structure/, by Chris Okasaki.
This codes contains skew binomial heap, shown in figure 6.10.
-}
module Data.BsbHeap.SbHeap where
import Prelude hiding (null)
import qualified Prelude as P
import Control.DeepSeq (NFData(..))
import Data.BsbHeap.Exception
deriving Show
instance Eq a => Eq (Tree a) where
# INLINE (= =) #
Node r1 x1 xs1 ts1 == Node r2 x2 xs2 ts2 =
r1 == r2 && x1 == x2 && xs1 == xs2 && ts1 == ts2
instance Functor Tree where
# INLINE fmap #
fmap f (Node r x xs ts) = Node r (f x) (map f xs) (map (fmap f) ts)
instance NFData a => NFData (Tree a) where
# INLINE rnf #
rnf (Node i x ns ts) = rnf i `seq` rnf x `seq` rnf ns `seq` rnf ts
rank :: Tree a -> Int
rank (Node !r _ _ _) = r
# INLINE rank #
root :: Tree a -> a
root (Node _ !x _ _) = x
# INLINE root #
link :: Ord a => Tree a -> Tree a -> Tree a
link t1@(Node !r !x1 xs1 c1) t2@(Node _ !x2 xs2 c2)
| x1 <= x2 = Node (r+1) x1 xs1 (t2:c1)
| otherwise = Node (r+1) x2 xs2 (t1:c2)
# INLINE link #
skewLink :: Ord a => a -> Tree a -> Tree a -> Tree a
skewLink !x t1 t2 = case link t1 t2 of
Node !r !y ys c
| x <= y -> Node r x (y:ys) c
| otherwise -> Node r y (x:ys) c
# INLINE skewLink #
insTree :: Ord a => Tree a -> [Tree a] -> [Tree a]
insTree t ts = case ts of
[] -> [t]
(t'):ts'
| rank t < rank t' -> t:t':ts'
| otherwise -> insTree (link t t') ts'
# INLINE insTree #
mergeTrees :: Ord a => [Tree a] -> [Tree a] -> [Tree a]
mergeTrees ts1 ts2 = case (ts1,ts2) of
(_,[]) -> ts1
([],_) -> ts2
(t1:ts1', t2:ts2')
| rank t1 < rank t2 -> t1 : mergeTrees ts1' ts2
| rank t1 > rank t2 -> t2 : mergeTrees ts1 ts2'
| otherwise -> insTree (link t1 t2) (mergeTrees ts1' ts2')
# INLINE mergeTrees #
normalize :: Ord a => [Tree a] -> [Tree a]
normalize ts = case ts of
[] -> []
(t:ts') -> insTree t ts'
# INLINE normalize #
newtype SbHeap a = SbHeap [Tree a] deriving (Show)
instance Eq a => Eq (SbHeap a) where
# INLINE (= =) #
SbHeap as == SbHeap bs = as == bs
instance Functor SbHeap where
fmap f (SbHeap ts) = SbHeap (map (fmap f) ts)
instance NFData a => NFData (SbHeap a) where
# INLINE rnf #
rnf (SbHeap xs) = rnf xs
empty :: SbHeap a
empty = SbHeap []
null :: SbHeap a -> Bool
null (SbHeap hs) = P.null hs
# INLINE null #
insert :: Ord a => a -> SbHeap a -> SbHeap a
insert !x (SbHeap ts) = SbHeap $ case ts of
(t1:t2:rest)
| rank t1 == rank t2 -> skewLink x t1 t2 : rest
| otherwise -> Node 0 x [] [] : ts
_ -> Node 0 x [] [] : ts
# INLINE insert #
merge :: Ord a => SbHeap a -> SbHeap a -> SbHeap a
merge (SbHeap ts1) (SbHeap ts2) =
SbHeap $ mergeTrees (normalize ts1) (normalize ts2)
# INLINE merge #
findMin :: Ord a => SbHeap a -> a
findMin (SbHeap ts) = case ts of
[] -> emptyHeap
[t] -> root t
(t:ts') -> case (root t, findMin (SbHeap ts')) of
(!x,!y) | x <= y -> x
| otherwise -> y
# INLINE findMin #
deleteMin :: Ord a => SbHeap a -> SbHeap a
deleteMin (SbHeap ts) = case ts of
[] -> emptyHeap
_ ->
let (Node _ _ xs c, ts') = getMin ts
in SbHeap $ insertAll xs (mergeTrees (reverse c) (normalize ts'))
# INLINE deleteMin #
getMin :: Ord a => [Tree a] -> (Tree a, [Tree a])
getMin xs = case xs of
[] -> treeIndexOutOfRange
[y] -> (y,[])
(y:ys) -> case getMin ys of
(z,zs) | root y <= root z -> (y,ys)
| otherwise -> (z,y:zs)
# INLINE getMin #
insertAll :: Ord a => [a] -> [Tree a] -> [Tree a]
insertAll as bs = case (as,bs) of
([],_) -> bs
((!a):as',_) -> case insert a (SbHeap bs) of SbHeap bs' -> insertAll as' bs'
# INLINE insertAll #
toList :: SbHeap a -> [a]
toList (SbHeap ts) = concatMap go ts where
go (Node _ r rs ns) = r : rs ++ concatMap go ns
# INLINE toList #
toSortedList :: Ord a => SbHeap a -> [a]
toSortedList (SbHeap ts) = go ts where
go ns = case ns of
[] -> []
_ -> case getMin ns of
(Node _ x xs c, ns') ->
x : go (insertAll xs (mergeTrees (reverse c) (normalize ns')))
# INLINE toSortedList #
|
26a42d48c93d5503bf0eca23306be8c9f692699f193787965a5142c4adc29ea7
|
herbelin/coq-hh
|
ccalgo.ml
|
(************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(* This file implements the basic congruence-closure algorithm by *)
Downey , and Tarjan .
open Util
open Pp
open Goptions
open Names
open Term
open Tacmach
open Evd
open Proof_type
let init_size=5
let cc_verbose=ref false
let debug f x =
if !cc_verbose then f x
let _=
let gdopt=
{ optsync=true;
optname="Congruence Verbose";
optkey=["Congruence";"Verbose"];
optread=(fun ()-> !cc_verbose);
optwrite=(fun b -> cc_verbose := b)}
in
declare_bool_option gdopt
Signature table
module ST=struct
(* l: sign -> term r: term -> sign *)
type t = {toterm:(int*int,int) Hashtbl.t;
tosign:(int,int*int) Hashtbl.t}
let empty ()=
{toterm=Hashtbl.create init_size;
tosign=Hashtbl.create init_size}
let enter t sign st=
if Hashtbl.mem st.toterm sign then
anomaly "enter: signature already entered"
else
Hashtbl.replace st.toterm sign t;
Hashtbl.replace st.tosign t sign
let query sign st=Hashtbl.find st.toterm sign
let rev_query term st=Hashtbl.find st.tosign term
let delete st t=
try let sign=Hashtbl.find st.tosign t in
Hashtbl.remove st.toterm sign;
Hashtbl.remove st.tosign t
with
Not_found -> ()
let rec delete_set st s = Intset.iter (delete st) s
end
type pa_constructor=
{ cnode : int;
arity : int;
args : int list}
type pa_fun=
{fsym:int;
fnargs:int}
type pa_mark=
Fmark of pa_fun
| Cmark of pa_constructor
module PacMap=Map.Make(struct
type t=pa_constructor
let compare=Pervasives.compare end)
module PafMap=Map.Make(struct
type t=pa_fun
let compare=Pervasives.compare end)
type cinfo=
{ci_constr: constructor; (* inductive type *)
ci_arity: int; (* # args *)
ci_nhyps: int} (* # projectable args *)
type term=
Symb of constr
| Product of sorts_family * sorts_family
| Eps of identifier
| Appli of term*term
constructor arity + nhyps
type ccpattern =
PApp of term * ccpattern list (* arguments are reversed *)
| PVar of int
type rule=
Congruence
| Axiom of constr * bool
| Injection of int * pa_constructor * int * pa_constructor * int
type from=
Goal
| Hyp of constr
| HeqG of constr
| HeqnH of constr * constr
type 'a eq = {lhs:int;rhs:int;rule:'a}
type equality = rule eq
type disequality = from eq
type patt_kind =
Normal
| Trivial of types
| Creates_variables
type quant_eq =
{qe_hyp_id: identifier;
qe_pol: bool;
qe_nvars:int;
qe_lhs: ccpattern;
qe_lhs_valid:patt_kind;
qe_rhs: ccpattern;
qe_rhs_valid:patt_kind}
let swap eq : equality =
let swap_rule=match eq.rule with
Congruence -> Congruence
| Injection (i,pi,j,pj,k) -> Injection (j,pj,i,pi,k)
| Axiom (id,reversed) -> Axiom (id,not reversed)
in {lhs=eq.rhs;rhs=eq.lhs;rule=swap_rule}
type inductive_status =
Unknown
| Partial of pa_constructor
| Partial_applied
| Total of (int * pa_constructor)
type representative=
{mutable weight:int;
mutable lfathers:Intset.t;
mutable fathers:Intset.t;
mutable inductive_status: inductive_status;
class_type : Term.types;
mutable functions: Intset.t PafMap.t;
mutable constructors: int PacMap.t} (*pac -> term = app(constr,t) *)
type cl = Rep of representative| Eqto of int*equality
type vertex = Leaf| Node of (int*int)
type node =
{mutable clas:cl;
mutable cpath: int;
vertex:vertex;
term:term}
type forest=
{mutable max_size:int;
mutable size:int;
mutable map: node array;
axioms: (constr,term*term) Hashtbl.t;
mutable epsilons: pa_constructor list;
syms:(term,int) Hashtbl.t}
type state =
{uf: forest;
sigtable:ST.t;
mutable terms: Intset.t;
combine: equality Queue.t;
marks: (int * pa_mark) Queue.t;
mutable diseq: disequality list;
mutable quant: quant_eq list;
mutable pa_classes: Intset.t;
q_history: (identifier,int array) Hashtbl.t;
mutable rew_depth:int;
mutable changed:bool;
by_type: (types,Intset.t) Hashtbl.t;
mutable gls:Proof_type.goal Tacmach.sigma}
let dummy_node =
{clas=Eqto(min_int,{lhs=min_int;rhs=min_int;rule=Congruence});
cpath=min_int;
vertex=Leaf;
term=Symb (mkRel min_int)}
let empty depth gls:state =
{uf=
{max_size=init_size;
size=0;
map=Array.create init_size dummy_node;
epsilons=[];
axioms=Hashtbl.create init_size;
syms=Hashtbl.create init_size};
terms=Intset.empty;
combine=Queue.create ();
marks=Queue.create ();
sigtable=ST.empty ();
diseq=[];
quant=[];
pa_classes=Intset.empty;
q_history=Hashtbl.create init_size;
rew_depth=depth;
by_type=Hashtbl.create init_size;
changed=false;
gls=gls}
let forest state = state.uf
let compress_path uf i j = uf.map.(j).cpath<-i
let rec find_aux uf visited i=
let j = uf.map.(i).cpath in
if j<0 then let _ = List.iter (compress_path uf i) visited in i else
find_aux uf (i::visited) j
let find uf i= find_aux uf [] i
let get_representative uf i=
match uf.map.(i).clas with
Rep r -> r
| _ -> anomaly "get_representative: not a representative"
let find_pac uf i pac =
PacMap.find pac (get_representative uf i).constructors
let get_constructor_info uf i=
match uf.map.(i).term with
Constructor cinfo->cinfo
| _ -> anomaly "get_constructor: not a constructor"
let size uf i=
(get_representative uf i).weight
let axioms uf = uf.axioms
let epsilons uf = uf.epsilons
let add_lfather uf i t=
let r=get_representative uf i in
r.weight<-r.weight+1;
r.lfathers<-Intset.add t r.lfathers;
r.fathers <-Intset.add t r.fathers
let add_rfather uf i t=
let r=get_representative uf i in
r.weight<-r.weight+1;
r.fathers <-Intset.add t r.fathers
exception Discriminable of int * pa_constructor * int * pa_constructor
let append_pac t p =
{p with arity=pred p.arity;args=t::p.args}
let tail_pac p=
{p with arity=succ p.arity;args=List.tl p.args}
let fsucc paf =
{paf with fnargs=succ paf.fnargs}
let add_pac rep pac t =
if not (PacMap.mem pac rep.constructors) then
rep.constructors<-PacMap.add pac t rep.constructors
let add_paf rep paf t =
let already =
try PafMap.find paf rep.functions with Not_found -> Intset.empty in
rep.functions<- PafMap.add paf (Intset.add t already) rep.functions
let term uf i=uf.map.(i).term
let subterms uf i=
match uf.map.(i).vertex with
Node(j,k) -> (j,k)
| _ -> anomaly "subterms: not a node"
let signature uf i=
let j,k=subterms uf i in (find uf j,find uf k)
let next uf=
let size=uf.size in
let nsize= succ size in
if nsize=uf.max_size then
let newmax=uf.max_size * 3 / 2 + 1 in
let newmap=Array.create newmax dummy_node in
begin
uf.max_size<-newmax;
Array.blit uf.map 0 newmap 0 size;
uf.map<-newmap
end
else ();
uf.size<-nsize;
size
let new_representative typ =
{weight=0;
lfathers=Intset.empty;
fathers=Intset.empty;
inductive_status=Unknown;
class_type=typ;
functions=PafMap.empty;
constructors=PacMap.empty}
(* rebuild a constr from an applicative term *)
let _A_ = Name (id_of_string "A")
let _B_ = Name (id_of_string "A")
let _body_ = mkProd(Anonymous,mkRel 2,mkRel 2)
let cc_product s1 s2 =
mkLambda(_A_,mkSort(Termops.new_sort_in_family s1),
mkLambda(_B_,mkSort(Termops.new_sort_in_family s2),_body_))
let rec constr_of_term = function
Symb s->s
| Product(s1,s2) -> cc_product s1 s2
| Eps id -> mkVar id
| Constructor cinfo -> mkConstruct cinfo.ci_constr
| Appli (s1,s2)->
make_app [(constr_of_term s2)] s1
and make_app l=function
Appli (s1,s2)->make_app ((constr_of_term s2)::l) s1
| other -> applistc (constr_of_term other) l
let rec canonize_name c =
let func = canonize_name in
match kind_of_term c with
| Const kn ->
let canon_const = constant_of_kn (canonical_con kn) in
(mkConst canon_const)
| Ind (kn,i) ->
let canon_mind = mind_of_kn (canonical_mind kn) in
(mkInd (canon_mind,i))
| Construct ((kn,i),j) ->
let canon_mind = mind_of_kn (canonical_mind kn) in
mkConstruct ((canon_mind,i),j)
| Prod (na,t,ct) ->
mkProd (na,func t, func ct)
| Lambda (na,t,ct) ->
mkLambda (na, func t,func ct)
| LetIn (na,b,t,ct) ->
mkLetIn (na, func b,func t,func ct)
| App (ct,l) ->
mkApp (func ct,array_smartmap func l)
| _ -> c
(* rebuild a term from a pattern and a substitution *)
let build_subst uf subst =
Array.map (fun i ->
try term uf i
with _ -> anomaly "incomplete matching") subst
let rec inst_pattern subst = function
PVar i ->
subst.(pred i)
| PApp (t, args) ->
List.fold_right
(fun spat f -> Appli (f,inst_pattern subst spat))
args t
let pr_idx_term state i = str "[" ++ int i ++ str ":=" ++
Termops.print_constr (constr_of_term (term state.uf i)) ++ str "]"
let pr_term t = str "[" ++
Termops.print_constr (constr_of_term t) ++ str "]"
let rec add_term state t=
let uf=state.uf in
try Hashtbl.find uf.syms t with
Not_found ->
let b=next uf in
let typ = pf_type_of state.gls (constr_of_term t) in
let typ = canonize_name typ in
let new_node=
match t with
Symb _ | Product (_,_) ->
let paf =
{fsym=b;
fnargs=0} in
Queue.add (b,Fmark paf) state.marks;
{clas= Rep (new_representative typ);
cpath= -1;
vertex= Leaf;
term= t}
| Eps id ->
{clas= Rep (new_representative typ);
cpath= -1;
vertex= Leaf;
term= t}
| Appli (t1,t2) ->
let i1=add_term state t1 and i2=add_term state t2 in
add_lfather uf (find uf i1) b;
add_rfather uf (find uf i2) b;
state.terms<-Intset.add b state.terms;
{clas= Rep (new_representative typ);
cpath= -1;
vertex= Node(i1,i2);
term= t}
| Constructor cinfo ->
let paf =
{fsym=b;
fnargs=0} in
Queue.add (b,Fmark paf) state.marks;
let pac =
{cnode= b;
arity= cinfo.ci_arity;
args=[]} in
Queue.add (b,Cmark pac) state.marks;
{clas=Rep (new_representative typ);
cpath= -1;
vertex=Leaf;
term=t}
in
uf.map.(b)<-new_node;
Hashtbl.add uf.syms t b;
Hashtbl.replace state.by_type typ
(Intset.add b
(try Hashtbl.find state.by_type typ with
Not_found -> Intset.empty));
b
let add_equality state c s t=
let i = add_term state s in
let j = add_term state t in
Queue.add {lhs=i;rhs=j;rule=Axiom(c,false)} state.combine;
Hashtbl.add state.uf.axioms c (s,t)
let add_disequality state from s t =
let i = add_term state s in
let j = add_term state t in
state.diseq<-{lhs=i;rhs=j;rule=from}::state.diseq
let add_quant state id pol (nvars,valid1,patt1,valid2,patt2) =
state.quant<-
{qe_hyp_id= id;
qe_pol= pol;
qe_nvars=nvars;
qe_lhs= patt1;
qe_lhs_valid=valid1;
qe_rhs= patt2;
qe_rhs_valid=valid2}::state.quant
let is_redundant state id args =
try
let norm_args = Array.map (find state.uf) args in
let prev_args = Hashtbl.find_all state.q_history id in
List.exists
(fun old_args ->
Util.array_for_all2 (fun i j -> i = find state.uf j)
norm_args old_args)
prev_args
with Not_found -> false
let add_inst state (inst,int_subst) =
check_for_interrupt ();
if state.rew_depth > 0 then
if is_redundant state inst.qe_hyp_id int_subst then
debug msgnl (str "discarding redundant (dis)equality")
else
begin
Hashtbl.add state.q_history inst.qe_hyp_id int_subst;
let subst = build_subst (forest state) int_subst in
let prfhead= mkVar inst.qe_hyp_id in
let args = Array.map constr_of_term subst in
highest deBruijn index first
let prf= mkApp(prfhead,args) in
let s = inst_pattern subst inst.qe_lhs
and t = inst_pattern subst inst.qe_rhs in
state.changed<-true;
state.rew_depth<-pred state.rew_depth;
if inst.qe_pol then
begin
debug (fun () ->
msgnl
(str "Adding new equality, depth="++ int state.rew_depth);
msgnl (str " [" ++ Termops.print_constr prf ++ str " : " ++
pr_term s ++ str " == " ++ pr_term t ++ str "]")) ();
add_equality state prf s t
end
else
begin
debug (fun () ->
msgnl
(str "Adding new disequality, depth="++ int state.rew_depth);
msgnl (str " [" ++ Termops.print_constr prf ++ str " : " ++
pr_term s ++ str " <> " ++ pr_term t ++ str "]")) ();
add_disequality state (Hyp prf) s t
end
end
let link uf i j eq = (* links i -> j *)
let node=uf.map.(i) in
node.clas<-Eqto (j,eq);
node.cpath<-j
let rec down_path uf i l=
match uf.map.(i).clas with
Eqto(j,t)->down_path uf j (((i,j),t)::l)
| Rep _ ->l
let rec min_path=function
([],l2)->([],l2)
| (l1,[])->(l1,[])
| (((c1,t1)::q1),((c2,t2)::q2)) when c1=c2 -> min_path (q1,q2)
| cpl -> cpl
let join_path uf i j=
assert (find uf i=find uf j);
min_path (down_path uf i [],down_path uf j [])
let union state i1 i2 eq=
debug (fun () -> msgnl (str "Linking " ++ pr_idx_term state i1 ++
str " and " ++ pr_idx_term state i2 ++ str ".")) ();
let r1= get_representative state.uf i1
and r2= get_representative state.uf i2 in
link state.uf i1 i2 eq;
Hashtbl.replace state.by_type r1.class_type
(Intset.remove i1
(try Hashtbl.find state.by_type r1.class_type with
Not_found -> Intset.empty));
let f= Intset.union r1.fathers r2.fathers in
r2.weight<-Intset.cardinal f;
r2.fathers<-f;
r2.lfathers<-Intset.union r1.lfathers r2.lfathers;
ST.delete_set state.sigtable r1.fathers;
state.terms<-Intset.union state.terms r1.fathers;
PacMap.iter
(fun pac b -> Queue.add (b,Cmark pac) state.marks)
r1.constructors;
PafMap.iter
(fun paf -> Intset.iter
(fun b -> Queue.add (b,Fmark paf) state.marks))
r1.functions;
match r1.inductive_status,r2.inductive_status with
Unknown,_ -> ()
| Partial pac,Unknown ->
r2.inductive_status<-Partial pac;
state.pa_classes<-Intset.remove i1 state.pa_classes;
state.pa_classes<-Intset.add i2 state.pa_classes
| Partial _ ,(Partial _ |Partial_applied) ->
state.pa_classes<-Intset.remove i1 state.pa_classes
| Partial_applied,Unknown ->
r2.inductive_status<-Partial_applied
| Partial_applied,Partial _ ->
state.pa_classes<-Intset.remove i2 state.pa_classes;
r2.inductive_status<-Partial_applied
| Total cpl,Unknown -> r2.inductive_status<-Total cpl;
| Total (i,pac),Total _ -> Queue.add (i,Cmark pac) state.marks
| _,_ -> ()
let merge eq state = (* merge and no-merge *)
debug (fun () -> msgnl
(str "Merging " ++ pr_idx_term state eq.lhs ++
str " and " ++ pr_idx_term state eq.rhs ++ str ".")) ();
let uf=state.uf in
let i=find uf eq.lhs
and j=find uf eq.rhs in
if i<>j then
if (size uf i)<(size uf j) then
union state i j eq
else
union state j i (swap eq)
update 1 and 2
debug (fun () -> msgnl
(str "Updating term " ++ pr_idx_term state t ++ str ".")) ();
let (i,j) as sign = signature state.uf t in
let (u,v) = subterms state.uf t in
let rep = get_representative state.uf i in
begin
match rep.inductive_status with
Partial _ ->
rep.inductive_status <- Partial_applied;
state.pa_classes <- Intset.remove i state.pa_classes
| _ -> ()
end;
PacMap.iter
(fun pac _ -> Queue.add (t,Cmark (append_pac v pac)) state.marks)
rep.constructors;
PafMap.iter
(fun paf _ -> Queue.add (t,Fmark (fsucc paf)) state.marks)
rep.functions;
try
let s = ST.query sign state.sigtable in
Queue.add {lhs=t;rhs=s;rule=Congruence} state.combine
with
Not_found -> ST.enter t sign state.sigtable
let process_function_mark t rep paf state =
add_paf rep paf t;
state.terms<-Intset.union rep.lfathers state.terms
let process_constructor_mark t i rep pac state =
match rep.inductive_status with
Total (s,opac) ->
if pac.cnode <> opac.cnode then (* Conflict *)
raise (Discriminable (s,opac,t,pac))
else (* Match *)
let cinfo = get_constructor_info state.uf pac.cnode in
let rec f n oargs args=
if n > 0 then
match (oargs,args) with
s1::q1,s2::q2->
Queue.add
{lhs=s1;rhs=s2;rule=Injection(s,opac,t,pac,n)}
state.combine;
f (n-1) q1 q2
| _-> anomaly
"add_pacs : weird error in injection subterms merge"
in f cinfo.ci_nhyps opac.args pac.args
| Partial_applied | Partial _ ->
add_pac rep pac t;
state.terms<-Intset.union rep.lfathers state.terms
| Unknown ->
if pac.arity = 0 then
rep.inductive_status <- Total (t,pac)
else
begin
add_pac rep pac t;
state.terms<-Intset.union rep.lfathers state.terms;
rep.inductive_status <- Partial pac;
state.pa_classes<- Intset.add i state.pa_classes
end
let process_mark t m state =
debug (fun () -> msgnl
(str "Processing mark for term " ++ pr_idx_term state t ++ str ".")) ();
let i=find state.uf t in
let rep=get_representative state.uf i in
match m with
Fmark paf -> process_function_mark t rep paf state
| Cmark pac -> process_constructor_mark t i rep pac state
type explanation =
Discrimination of (int*pa_constructor*int*pa_constructor)
| Contradiction of disequality
| Incomplete
let check_disequalities state =
let uf=state.uf in
let rec check_aux = function
dis::q ->
debug (fun () -> msg
(str "Checking if " ++ pr_idx_term state dis.lhs ++ str " = " ++
pr_idx_term state dis.rhs ++ str " ... ")) ();
if find uf dis.lhs=find uf dis.rhs then
begin debug msgnl (str "Yes");Some dis end
else
begin debug msgnl (str "No");check_aux q end
| [] -> None
in
check_aux state.diseq
let one_step state =
try
let eq = Queue.take state.combine in
merge eq state;
true
with Queue.Empty ->
try
let (t,m) = Queue.take state.marks in
process_mark t m state;
true
with Queue.Empty ->
try
let t = Intset.choose state.terms in
state.terms<-Intset.remove t state.terms;
update t state;
true
with Not_found -> false
let __eps__ = id_of_string "_eps_"
let new_state_var typ state =
let id = pf_get_new_id __eps__ state.gls in
let {it=gl ; sigma=sigma} = state.gls in
let new_hyps =
Environ.push_named_context_val (id,None,typ) (Goal.V82.hyps sigma gl) in
let gls = Goal.V82.new_goal_with sigma gl new_hyps in
state.gls<- gls;
id
let complete_one_class state i=
match (get_representative state.uf i).inductive_status with
Partial pac ->
let rec app t typ n =
if n<=0 then t else
let _,etyp,rest= destProd typ in
let id = new_state_var etyp state in
app (Appli(t,Eps id)) (substl [mkVar id] rest) (n-1) in
let _c = pf_type_of state.gls
(constr_of_term (term state.uf pac.cnode)) in
let _args =
List.map (fun i -> constr_of_term (term state.uf i))
pac.args in
let typ = prod_applist _c (List.rev _args) in
let ct = app (term state.uf i) typ pac.arity in
state.uf.epsilons <- pac :: state.uf.epsilons;
ignore (add_term state ct)
| _ -> anomaly "wrong incomplete class"
let complete state =
Intset.iter (complete_one_class state) state.pa_classes
type matching_problem =
{mp_subst : int array;
mp_inst : quant_eq;
mp_stack : (ccpattern*int) list }
let make_fun_table state =
let uf= state.uf in
let funtab=ref PafMap.empty in
Array.iteri
(fun i inode -> if i < uf.size then
match inode.clas with
Rep rep ->
PafMap.iter
(fun paf _ ->
let elem =
try PafMap.find paf !funtab
with Not_found -> Intset.empty in
funtab:= PafMap.add paf (Intset.add i elem) !funtab)
rep.functions
| _ -> ()) state.uf.map;
!funtab
let rec do_match state res pb_stack =
let mp=Stack.pop pb_stack in
match mp.mp_stack with
[] ->
res:= (mp.mp_inst,mp.mp_subst) :: !res
| (patt,cl)::remains ->
let uf=state.uf in
match patt with
PVar i ->
if mp.mp_subst.(pred i)<0 then
begin
mp.mp_subst.(pred i)<- cl; (* no aliasing problem here *)
Stack.push {mp with mp_stack=remains} pb_stack
end
else
if mp.mp_subst.(pred i) = cl then
Stack.push {mp with mp_stack=remains} pb_stack
else (* mismatch for non-linear variable in pattern *) ()
| PApp (f,[]) ->
begin
try let j=Hashtbl.find uf.syms f in
if find uf j =cl then
Stack.push {mp with mp_stack=remains} pb_stack
with Not_found -> ()
end
| PApp(f, ((last_arg::rem_args) as args)) ->
try
let j=Hashtbl.find uf.syms f in
let paf={fsym=j;fnargs=List.length args} in
let rep=get_representative uf cl in
let good_terms = PafMap.find paf rep.functions in
let aux i =
let (s,t) = signature state.uf i in
Stack.push
{mp with
mp_subst=Array.copy mp.mp_subst;
mp_stack=
(PApp(f,rem_args),s) ::
(last_arg,t) :: remains} pb_stack in
Intset.iter aux good_terms
with Not_found -> ()
let paf_of_patt syms = function
PVar _ -> invalid_arg "paf_of_patt: pattern is trivial"
| PApp (f,args) ->
{fsym=Hashtbl.find syms f;
fnargs=List.length args}
let init_pb_stack state =
let syms= state.uf.syms in
let pb_stack = Stack.create () in
let funtab = make_fun_table state in
let aux inst =
begin
let good_classes =
match inst.qe_lhs_valid with
Creates_variables -> Intset.empty
| Normal ->
begin
try
let paf= paf_of_patt syms inst.qe_lhs in
PafMap.find paf funtab
with Not_found -> Intset.empty
end
| Trivial typ ->
begin
try
Hashtbl.find state.by_type typ
with Not_found -> Intset.empty
end in
Intset.iter (fun i ->
Stack.push
{mp_subst = Array.make inst.qe_nvars (-1);
mp_inst=inst;
mp_stack=[inst.qe_lhs,i]} pb_stack) good_classes
end;
begin
let good_classes =
match inst.qe_rhs_valid with
Creates_variables -> Intset.empty
| Normal ->
begin
try
let paf= paf_of_patt syms inst.qe_rhs in
PafMap.find paf funtab
with Not_found -> Intset.empty
end
| Trivial typ ->
begin
try
Hashtbl.find state.by_type typ
with Not_found -> Intset.empty
end in
Intset.iter (fun i ->
Stack.push
{mp_subst = Array.make inst.qe_nvars (-1);
mp_inst=inst;
mp_stack=[inst.qe_rhs,i]} pb_stack) good_classes
end in
List.iter aux state.quant;
pb_stack
let find_instances state =
let pb_stack= init_pb_stack state in
let res =ref [] in
let _ =
debug msgnl (str "Running E-matching algorithm ... ");
try
while true do
check_for_interrupt ();
do_match state res pb_stack
done;
anomaly "get out of here !"
with Stack.Empty -> () in
!res
let rec execute first_run state =
debug msgnl (str "Executing ... ");
try
while
check_for_interrupt ();
one_step state do ()
done;
match check_disequalities state with
None ->
if not(Intset.is_empty state.pa_classes) then
begin
debug msgnl (str "First run was incomplete, completing ... ");
complete state;
execute false state
end
else
if state.rew_depth>0 then
let l=find_instances state in
List.iter (add_inst state) l;
if state.changed then
begin
state.changed <- false;
execute true state
end
else
begin
debug msgnl (str "Out of instances ... ");
None
end
else
begin
debug msgnl (str "Out of depth ... ");
None
end
| Some dis -> Some
begin
if first_run then Contradiction dis
else Incomplete
end
with Discriminable(s,spac,t,tpac) -> Some
begin
if first_run then Discrimination (s,spac,t,tpac)
else Incomplete
end
| null |
https://raw.githubusercontent.com/herbelin/coq-hh/296d03d5049fea661e8bdbaf305ed4bf6d2001d2/plugins/cc/ccalgo.ml
|
ocaml
|
**********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
This file implements the basic congruence-closure algorithm by
l: sign -> term r: term -> sign
inductive type
# args
# projectable args
arguments are reversed
pac -> term = app(constr,t)
rebuild a constr from an applicative term
rebuild a term from a pattern and a substitution
links i -> j
merge and no-merge
Conflict
Match
no aliasing problem here
mismatch for non-linear variable in pattern
|
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Downey , and Tarjan .
open Util
open Pp
open Goptions
open Names
open Term
open Tacmach
open Evd
open Proof_type
let init_size=5
let cc_verbose=ref false
let debug f x =
if !cc_verbose then f x
let _=
let gdopt=
{ optsync=true;
optname="Congruence Verbose";
optkey=["Congruence";"Verbose"];
optread=(fun ()-> !cc_verbose);
optwrite=(fun b -> cc_verbose := b)}
in
declare_bool_option gdopt
Signature table
module ST=struct
type t = {toterm:(int*int,int) Hashtbl.t;
tosign:(int,int*int) Hashtbl.t}
let empty ()=
{toterm=Hashtbl.create init_size;
tosign=Hashtbl.create init_size}
let enter t sign st=
if Hashtbl.mem st.toterm sign then
anomaly "enter: signature already entered"
else
Hashtbl.replace st.toterm sign t;
Hashtbl.replace st.tosign t sign
let query sign st=Hashtbl.find st.toterm sign
let rev_query term st=Hashtbl.find st.tosign term
let delete st t=
try let sign=Hashtbl.find st.tosign t in
Hashtbl.remove st.toterm sign;
Hashtbl.remove st.tosign t
with
Not_found -> ()
let rec delete_set st s = Intset.iter (delete st) s
end
type pa_constructor=
{ cnode : int;
arity : int;
args : int list}
type pa_fun=
{fsym:int;
fnargs:int}
type pa_mark=
Fmark of pa_fun
| Cmark of pa_constructor
module PacMap=Map.Make(struct
type t=pa_constructor
let compare=Pervasives.compare end)
module PafMap=Map.Make(struct
type t=pa_fun
let compare=Pervasives.compare end)
type cinfo=
type term=
Symb of constr
| Product of sorts_family * sorts_family
| Eps of identifier
| Appli of term*term
constructor arity + nhyps
type ccpattern =
| PVar of int
type rule=
Congruence
| Axiom of constr * bool
| Injection of int * pa_constructor * int * pa_constructor * int
type from=
Goal
| Hyp of constr
| HeqG of constr
| HeqnH of constr * constr
type 'a eq = {lhs:int;rhs:int;rule:'a}
type equality = rule eq
type disequality = from eq
type patt_kind =
Normal
| Trivial of types
| Creates_variables
type quant_eq =
{qe_hyp_id: identifier;
qe_pol: bool;
qe_nvars:int;
qe_lhs: ccpattern;
qe_lhs_valid:patt_kind;
qe_rhs: ccpattern;
qe_rhs_valid:patt_kind}
let swap eq : equality =
let swap_rule=match eq.rule with
Congruence -> Congruence
| Injection (i,pi,j,pj,k) -> Injection (j,pj,i,pi,k)
| Axiom (id,reversed) -> Axiom (id,not reversed)
in {lhs=eq.rhs;rhs=eq.lhs;rule=swap_rule}
type inductive_status =
Unknown
| Partial of pa_constructor
| Partial_applied
| Total of (int * pa_constructor)
type representative=
{mutable weight:int;
mutable lfathers:Intset.t;
mutable fathers:Intset.t;
mutable inductive_status: inductive_status;
class_type : Term.types;
mutable functions: Intset.t PafMap.t;
type cl = Rep of representative| Eqto of int*equality
type vertex = Leaf| Node of (int*int)
type node =
{mutable clas:cl;
mutable cpath: int;
vertex:vertex;
term:term}
type forest=
{mutable max_size:int;
mutable size:int;
mutable map: node array;
axioms: (constr,term*term) Hashtbl.t;
mutable epsilons: pa_constructor list;
syms:(term,int) Hashtbl.t}
type state =
{uf: forest;
sigtable:ST.t;
mutable terms: Intset.t;
combine: equality Queue.t;
marks: (int * pa_mark) Queue.t;
mutable diseq: disequality list;
mutable quant: quant_eq list;
mutable pa_classes: Intset.t;
q_history: (identifier,int array) Hashtbl.t;
mutable rew_depth:int;
mutable changed:bool;
by_type: (types,Intset.t) Hashtbl.t;
mutable gls:Proof_type.goal Tacmach.sigma}
let dummy_node =
{clas=Eqto(min_int,{lhs=min_int;rhs=min_int;rule=Congruence});
cpath=min_int;
vertex=Leaf;
term=Symb (mkRel min_int)}
let empty depth gls:state =
{uf=
{max_size=init_size;
size=0;
map=Array.create init_size dummy_node;
epsilons=[];
axioms=Hashtbl.create init_size;
syms=Hashtbl.create init_size};
terms=Intset.empty;
combine=Queue.create ();
marks=Queue.create ();
sigtable=ST.empty ();
diseq=[];
quant=[];
pa_classes=Intset.empty;
q_history=Hashtbl.create init_size;
rew_depth=depth;
by_type=Hashtbl.create init_size;
changed=false;
gls=gls}
let forest state = state.uf
let compress_path uf i j = uf.map.(j).cpath<-i
let rec find_aux uf visited i=
let j = uf.map.(i).cpath in
if j<0 then let _ = List.iter (compress_path uf i) visited in i else
find_aux uf (i::visited) j
let find uf i= find_aux uf [] i
let get_representative uf i=
match uf.map.(i).clas with
Rep r -> r
| _ -> anomaly "get_representative: not a representative"
let find_pac uf i pac =
PacMap.find pac (get_representative uf i).constructors
let get_constructor_info uf i=
match uf.map.(i).term with
Constructor cinfo->cinfo
| _ -> anomaly "get_constructor: not a constructor"
let size uf i=
(get_representative uf i).weight
let axioms uf = uf.axioms
let epsilons uf = uf.epsilons
let add_lfather uf i t=
let r=get_representative uf i in
r.weight<-r.weight+1;
r.lfathers<-Intset.add t r.lfathers;
r.fathers <-Intset.add t r.fathers
let add_rfather uf i t=
let r=get_representative uf i in
r.weight<-r.weight+1;
r.fathers <-Intset.add t r.fathers
exception Discriminable of int * pa_constructor * int * pa_constructor
let append_pac t p =
{p with arity=pred p.arity;args=t::p.args}
let tail_pac p=
{p with arity=succ p.arity;args=List.tl p.args}
let fsucc paf =
{paf with fnargs=succ paf.fnargs}
let add_pac rep pac t =
if not (PacMap.mem pac rep.constructors) then
rep.constructors<-PacMap.add pac t rep.constructors
let add_paf rep paf t =
let already =
try PafMap.find paf rep.functions with Not_found -> Intset.empty in
rep.functions<- PafMap.add paf (Intset.add t already) rep.functions
let term uf i=uf.map.(i).term
let subterms uf i=
match uf.map.(i).vertex with
Node(j,k) -> (j,k)
| _ -> anomaly "subterms: not a node"
let signature uf i=
let j,k=subterms uf i in (find uf j,find uf k)
let next uf=
let size=uf.size in
let nsize= succ size in
if nsize=uf.max_size then
let newmax=uf.max_size * 3 / 2 + 1 in
let newmap=Array.create newmax dummy_node in
begin
uf.max_size<-newmax;
Array.blit uf.map 0 newmap 0 size;
uf.map<-newmap
end
else ();
uf.size<-nsize;
size
let new_representative typ =
{weight=0;
lfathers=Intset.empty;
fathers=Intset.empty;
inductive_status=Unknown;
class_type=typ;
functions=PafMap.empty;
constructors=PacMap.empty}
let _A_ = Name (id_of_string "A")
let _B_ = Name (id_of_string "A")
let _body_ = mkProd(Anonymous,mkRel 2,mkRel 2)
let cc_product s1 s2 =
mkLambda(_A_,mkSort(Termops.new_sort_in_family s1),
mkLambda(_B_,mkSort(Termops.new_sort_in_family s2),_body_))
let rec constr_of_term = function
Symb s->s
| Product(s1,s2) -> cc_product s1 s2
| Eps id -> mkVar id
| Constructor cinfo -> mkConstruct cinfo.ci_constr
| Appli (s1,s2)->
make_app [(constr_of_term s2)] s1
and make_app l=function
Appli (s1,s2)->make_app ((constr_of_term s2)::l) s1
| other -> applistc (constr_of_term other) l
let rec canonize_name c =
let func = canonize_name in
match kind_of_term c with
| Const kn ->
let canon_const = constant_of_kn (canonical_con kn) in
(mkConst canon_const)
| Ind (kn,i) ->
let canon_mind = mind_of_kn (canonical_mind kn) in
(mkInd (canon_mind,i))
| Construct ((kn,i),j) ->
let canon_mind = mind_of_kn (canonical_mind kn) in
mkConstruct ((canon_mind,i),j)
| Prod (na,t,ct) ->
mkProd (na,func t, func ct)
| Lambda (na,t,ct) ->
mkLambda (na, func t,func ct)
| LetIn (na,b,t,ct) ->
mkLetIn (na, func b,func t,func ct)
| App (ct,l) ->
mkApp (func ct,array_smartmap func l)
| _ -> c
let build_subst uf subst =
Array.map (fun i ->
try term uf i
with _ -> anomaly "incomplete matching") subst
let rec inst_pattern subst = function
PVar i ->
subst.(pred i)
| PApp (t, args) ->
List.fold_right
(fun spat f -> Appli (f,inst_pattern subst spat))
args t
let pr_idx_term state i = str "[" ++ int i ++ str ":=" ++
Termops.print_constr (constr_of_term (term state.uf i)) ++ str "]"
let pr_term t = str "[" ++
Termops.print_constr (constr_of_term t) ++ str "]"
let rec add_term state t=
let uf=state.uf in
try Hashtbl.find uf.syms t with
Not_found ->
let b=next uf in
let typ = pf_type_of state.gls (constr_of_term t) in
let typ = canonize_name typ in
let new_node=
match t with
Symb _ | Product (_,_) ->
let paf =
{fsym=b;
fnargs=0} in
Queue.add (b,Fmark paf) state.marks;
{clas= Rep (new_representative typ);
cpath= -1;
vertex= Leaf;
term= t}
| Eps id ->
{clas= Rep (new_representative typ);
cpath= -1;
vertex= Leaf;
term= t}
| Appli (t1,t2) ->
let i1=add_term state t1 and i2=add_term state t2 in
add_lfather uf (find uf i1) b;
add_rfather uf (find uf i2) b;
state.terms<-Intset.add b state.terms;
{clas= Rep (new_representative typ);
cpath= -1;
vertex= Node(i1,i2);
term= t}
| Constructor cinfo ->
let paf =
{fsym=b;
fnargs=0} in
Queue.add (b,Fmark paf) state.marks;
let pac =
{cnode= b;
arity= cinfo.ci_arity;
args=[]} in
Queue.add (b,Cmark pac) state.marks;
{clas=Rep (new_representative typ);
cpath= -1;
vertex=Leaf;
term=t}
in
uf.map.(b)<-new_node;
Hashtbl.add uf.syms t b;
Hashtbl.replace state.by_type typ
(Intset.add b
(try Hashtbl.find state.by_type typ with
Not_found -> Intset.empty));
b
let add_equality state c s t=
let i = add_term state s in
let j = add_term state t in
Queue.add {lhs=i;rhs=j;rule=Axiom(c,false)} state.combine;
Hashtbl.add state.uf.axioms c (s,t)
let add_disequality state from s t =
let i = add_term state s in
let j = add_term state t in
state.diseq<-{lhs=i;rhs=j;rule=from}::state.diseq
let add_quant state id pol (nvars,valid1,patt1,valid2,patt2) =
state.quant<-
{qe_hyp_id= id;
qe_pol= pol;
qe_nvars=nvars;
qe_lhs= patt1;
qe_lhs_valid=valid1;
qe_rhs= patt2;
qe_rhs_valid=valid2}::state.quant
let is_redundant state id args =
try
let norm_args = Array.map (find state.uf) args in
let prev_args = Hashtbl.find_all state.q_history id in
List.exists
(fun old_args ->
Util.array_for_all2 (fun i j -> i = find state.uf j)
norm_args old_args)
prev_args
with Not_found -> false
let add_inst state (inst,int_subst) =
check_for_interrupt ();
if state.rew_depth > 0 then
if is_redundant state inst.qe_hyp_id int_subst then
debug msgnl (str "discarding redundant (dis)equality")
else
begin
Hashtbl.add state.q_history inst.qe_hyp_id int_subst;
let subst = build_subst (forest state) int_subst in
let prfhead= mkVar inst.qe_hyp_id in
let args = Array.map constr_of_term subst in
highest deBruijn index first
let prf= mkApp(prfhead,args) in
let s = inst_pattern subst inst.qe_lhs
and t = inst_pattern subst inst.qe_rhs in
state.changed<-true;
state.rew_depth<-pred state.rew_depth;
if inst.qe_pol then
begin
debug (fun () ->
msgnl
(str "Adding new equality, depth="++ int state.rew_depth);
msgnl (str " [" ++ Termops.print_constr prf ++ str " : " ++
pr_term s ++ str " == " ++ pr_term t ++ str "]")) ();
add_equality state prf s t
end
else
begin
debug (fun () ->
msgnl
(str "Adding new disequality, depth="++ int state.rew_depth);
msgnl (str " [" ++ Termops.print_constr prf ++ str " : " ++
pr_term s ++ str " <> " ++ pr_term t ++ str "]")) ();
add_disequality state (Hyp prf) s t
end
end
let node=uf.map.(i) in
node.clas<-Eqto (j,eq);
node.cpath<-j
let rec down_path uf i l=
match uf.map.(i).clas with
Eqto(j,t)->down_path uf j (((i,j),t)::l)
| Rep _ ->l
let rec min_path=function
([],l2)->([],l2)
| (l1,[])->(l1,[])
| (((c1,t1)::q1),((c2,t2)::q2)) when c1=c2 -> min_path (q1,q2)
| cpl -> cpl
let join_path uf i j=
assert (find uf i=find uf j);
min_path (down_path uf i [],down_path uf j [])
let union state i1 i2 eq=
debug (fun () -> msgnl (str "Linking " ++ pr_idx_term state i1 ++
str " and " ++ pr_idx_term state i2 ++ str ".")) ();
let r1= get_representative state.uf i1
and r2= get_representative state.uf i2 in
link state.uf i1 i2 eq;
Hashtbl.replace state.by_type r1.class_type
(Intset.remove i1
(try Hashtbl.find state.by_type r1.class_type with
Not_found -> Intset.empty));
let f= Intset.union r1.fathers r2.fathers in
r2.weight<-Intset.cardinal f;
r2.fathers<-f;
r2.lfathers<-Intset.union r1.lfathers r2.lfathers;
ST.delete_set state.sigtable r1.fathers;
state.terms<-Intset.union state.terms r1.fathers;
PacMap.iter
(fun pac b -> Queue.add (b,Cmark pac) state.marks)
r1.constructors;
PafMap.iter
(fun paf -> Intset.iter
(fun b -> Queue.add (b,Fmark paf) state.marks))
r1.functions;
match r1.inductive_status,r2.inductive_status with
Unknown,_ -> ()
| Partial pac,Unknown ->
r2.inductive_status<-Partial pac;
state.pa_classes<-Intset.remove i1 state.pa_classes;
state.pa_classes<-Intset.add i2 state.pa_classes
| Partial _ ,(Partial _ |Partial_applied) ->
state.pa_classes<-Intset.remove i1 state.pa_classes
| Partial_applied,Unknown ->
r2.inductive_status<-Partial_applied
| Partial_applied,Partial _ ->
state.pa_classes<-Intset.remove i2 state.pa_classes;
r2.inductive_status<-Partial_applied
| Total cpl,Unknown -> r2.inductive_status<-Total cpl;
| Total (i,pac),Total _ -> Queue.add (i,Cmark pac) state.marks
| _,_ -> ()
debug (fun () -> msgnl
(str "Merging " ++ pr_idx_term state eq.lhs ++
str " and " ++ pr_idx_term state eq.rhs ++ str ".")) ();
let uf=state.uf in
let i=find uf eq.lhs
and j=find uf eq.rhs in
if i<>j then
if (size uf i)<(size uf j) then
union state i j eq
else
union state j i (swap eq)
update 1 and 2
debug (fun () -> msgnl
(str "Updating term " ++ pr_idx_term state t ++ str ".")) ();
let (i,j) as sign = signature state.uf t in
let (u,v) = subterms state.uf t in
let rep = get_representative state.uf i in
begin
match rep.inductive_status with
Partial _ ->
rep.inductive_status <- Partial_applied;
state.pa_classes <- Intset.remove i state.pa_classes
| _ -> ()
end;
PacMap.iter
(fun pac _ -> Queue.add (t,Cmark (append_pac v pac)) state.marks)
rep.constructors;
PafMap.iter
(fun paf _ -> Queue.add (t,Fmark (fsucc paf)) state.marks)
rep.functions;
try
let s = ST.query sign state.sigtable in
Queue.add {lhs=t;rhs=s;rule=Congruence} state.combine
with
Not_found -> ST.enter t sign state.sigtable
let process_function_mark t rep paf state =
add_paf rep paf t;
state.terms<-Intset.union rep.lfathers state.terms
let process_constructor_mark t i rep pac state =
match rep.inductive_status with
Total (s,opac) ->
raise (Discriminable (s,opac,t,pac))
let cinfo = get_constructor_info state.uf pac.cnode in
let rec f n oargs args=
if n > 0 then
match (oargs,args) with
s1::q1,s2::q2->
Queue.add
{lhs=s1;rhs=s2;rule=Injection(s,opac,t,pac,n)}
state.combine;
f (n-1) q1 q2
| _-> anomaly
"add_pacs : weird error in injection subterms merge"
in f cinfo.ci_nhyps opac.args pac.args
| Partial_applied | Partial _ ->
add_pac rep pac t;
state.terms<-Intset.union rep.lfathers state.terms
| Unknown ->
if pac.arity = 0 then
rep.inductive_status <- Total (t,pac)
else
begin
add_pac rep pac t;
state.terms<-Intset.union rep.lfathers state.terms;
rep.inductive_status <- Partial pac;
state.pa_classes<- Intset.add i state.pa_classes
end
let process_mark t m state =
debug (fun () -> msgnl
(str "Processing mark for term " ++ pr_idx_term state t ++ str ".")) ();
let i=find state.uf t in
let rep=get_representative state.uf i in
match m with
Fmark paf -> process_function_mark t rep paf state
| Cmark pac -> process_constructor_mark t i rep pac state
type explanation =
Discrimination of (int*pa_constructor*int*pa_constructor)
| Contradiction of disequality
| Incomplete
let check_disequalities state =
let uf=state.uf in
let rec check_aux = function
dis::q ->
debug (fun () -> msg
(str "Checking if " ++ pr_idx_term state dis.lhs ++ str " = " ++
pr_idx_term state dis.rhs ++ str " ... ")) ();
if find uf dis.lhs=find uf dis.rhs then
begin debug msgnl (str "Yes");Some dis end
else
begin debug msgnl (str "No");check_aux q end
| [] -> None
in
check_aux state.diseq
let one_step state =
try
let eq = Queue.take state.combine in
merge eq state;
true
with Queue.Empty ->
try
let (t,m) = Queue.take state.marks in
process_mark t m state;
true
with Queue.Empty ->
try
let t = Intset.choose state.terms in
state.terms<-Intset.remove t state.terms;
update t state;
true
with Not_found -> false
let __eps__ = id_of_string "_eps_"
let new_state_var typ state =
let id = pf_get_new_id __eps__ state.gls in
let {it=gl ; sigma=sigma} = state.gls in
let new_hyps =
Environ.push_named_context_val (id,None,typ) (Goal.V82.hyps sigma gl) in
let gls = Goal.V82.new_goal_with sigma gl new_hyps in
state.gls<- gls;
id
let complete_one_class state i=
match (get_representative state.uf i).inductive_status with
Partial pac ->
let rec app t typ n =
if n<=0 then t else
let _,etyp,rest= destProd typ in
let id = new_state_var etyp state in
app (Appli(t,Eps id)) (substl [mkVar id] rest) (n-1) in
let _c = pf_type_of state.gls
(constr_of_term (term state.uf pac.cnode)) in
let _args =
List.map (fun i -> constr_of_term (term state.uf i))
pac.args in
let typ = prod_applist _c (List.rev _args) in
let ct = app (term state.uf i) typ pac.arity in
state.uf.epsilons <- pac :: state.uf.epsilons;
ignore (add_term state ct)
| _ -> anomaly "wrong incomplete class"
let complete state =
Intset.iter (complete_one_class state) state.pa_classes
type matching_problem =
{mp_subst : int array;
mp_inst : quant_eq;
mp_stack : (ccpattern*int) list }
let make_fun_table state =
let uf= state.uf in
let funtab=ref PafMap.empty in
Array.iteri
(fun i inode -> if i < uf.size then
match inode.clas with
Rep rep ->
PafMap.iter
(fun paf _ ->
let elem =
try PafMap.find paf !funtab
with Not_found -> Intset.empty in
funtab:= PafMap.add paf (Intset.add i elem) !funtab)
rep.functions
| _ -> ()) state.uf.map;
!funtab
let rec do_match state res pb_stack =
let mp=Stack.pop pb_stack in
match mp.mp_stack with
[] ->
res:= (mp.mp_inst,mp.mp_subst) :: !res
| (patt,cl)::remains ->
let uf=state.uf in
match patt with
PVar i ->
if mp.mp_subst.(pred i)<0 then
begin
Stack.push {mp with mp_stack=remains} pb_stack
end
else
if mp.mp_subst.(pred i) = cl then
Stack.push {mp with mp_stack=remains} pb_stack
| PApp (f,[]) ->
begin
try let j=Hashtbl.find uf.syms f in
if find uf j =cl then
Stack.push {mp with mp_stack=remains} pb_stack
with Not_found -> ()
end
| PApp(f, ((last_arg::rem_args) as args)) ->
try
let j=Hashtbl.find uf.syms f in
let paf={fsym=j;fnargs=List.length args} in
let rep=get_representative uf cl in
let good_terms = PafMap.find paf rep.functions in
let aux i =
let (s,t) = signature state.uf i in
Stack.push
{mp with
mp_subst=Array.copy mp.mp_subst;
mp_stack=
(PApp(f,rem_args),s) ::
(last_arg,t) :: remains} pb_stack in
Intset.iter aux good_terms
with Not_found -> ()
let paf_of_patt syms = function
PVar _ -> invalid_arg "paf_of_patt: pattern is trivial"
| PApp (f,args) ->
{fsym=Hashtbl.find syms f;
fnargs=List.length args}
let init_pb_stack state =
let syms= state.uf.syms in
let pb_stack = Stack.create () in
let funtab = make_fun_table state in
let aux inst =
begin
let good_classes =
match inst.qe_lhs_valid with
Creates_variables -> Intset.empty
| Normal ->
begin
try
let paf= paf_of_patt syms inst.qe_lhs in
PafMap.find paf funtab
with Not_found -> Intset.empty
end
| Trivial typ ->
begin
try
Hashtbl.find state.by_type typ
with Not_found -> Intset.empty
end in
Intset.iter (fun i ->
Stack.push
{mp_subst = Array.make inst.qe_nvars (-1);
mp_inst=inst;
mp_stack=[inst.qe_lhs,i]} pb_stack) good_classes
end;
begin
let good_classes =
match inst.qe_rhs_valid with
Creates_variables -> Intset.empty
| Normal ->
begin
try
let paf= paf_of_patt syms inst.qe_rhs in
PafMap.find paf funtab
with Not_found -> Intset.empty
end
| Trivial typ ->
begin
try
Hashtbl.find state.by_type typ
with Not_found -> Intset.empty
end in
Intset.iter (fun i ->
Stack.push
{mp_subst = Array.make inst.qe_nvars (-1);
mp_inst=inst;
mp_stack=[inst.qe_rhs,i]} pb_stack) good_classes
end in
List.iter aux state.quant;
pb_stack
let find_instances state =
let pb_stack= init_pb_stack state in
let res =ref [] in
let _ =
debug msgnl (str "Running E-matching algorithm ... ");
try
while true do
check_for_interrupt ();
do_match state res pb_stack
done;
anomaly "get out of here !"
with Stack.Empty -> () in
!res
let rec execute first_run state =
debug msgnl (str "Executing ... ");
try
while
check_for_interrupt ();
one_step state do ()
done;
match check_disequalities state with
None ->
if not(Intset.is_empty state.pa_classes) then
begin
debug msgnl (str "First run was incomplete, completing ... ");
complete state;
execute false state
end
else
if state.rew_depth>0 then
let l=find_instances state in
List.iter (add_inst state) l;
if state.changed then
begin
state.changed <- false;
execute true state
end
else
begin
debug msgnl (str "Out of instances ... ");
None
end
else
begin
debug msgnl (str "Out of depth ... ");
None
end
| Some dis -> Some
begin
if first_run then Contradiction dis
else Incomplete
end
with Discriminable(s,spac,t,tpac) -> Some
begin
if first_run then Discrimination (s,spac,t,tpac)
else Incomplete
end
|
3f01c4fb924b246af460df3e31c5f7f13787ddf53a220e47cb446908f2609054
|
softwarelanguageslab/maf
|
R5RS_ad_all-4.scm
|
; Changes:
* removed : 1
* added : 1
* swaps : 1
; * negated predicates: 0
; * swapped branches: 0
* calls to i d fun : 3
(letrec ((bubble-sort (lambda (vector)
(letrec ((swap (lambda (vector index1 index2)
(let ((temp (vector-ref vector index1)))
(<change>
()
(vector-set! vector index1 (vector-ref vector index2)))
(<change>
(vector-set! vector index1 (vector-ref vector index2))
(vector-set! vector index2 temp))
(<change>
(vector-set! vector index2 temp)
(vector-set! vector index1 (vector-ref vector index2))))))
(bubble (lambda (index)
(letrec ((bubble-iter (lambda (index1 changed)
(if (<= index1 index)
(begin
(<change>
(if (> (vector-ref vector index1) (vector-ref vector (+ index1 1)))
(begin
(swap vector index1 (+ index1 1))
(set! changed #t))
#f)
((lambda (x) x)
(if (> (vector-ref vector index1) (vector-ref vector (+ index1 1)))
(begin
(swap vector index1 (+ index1 1))
(set! changed #t))
#f)))
(bubble-iter (+ index1 1) changed))
changed))))
(bubble-iter 0 #f))))
(bubble-sort-iter (lambda (index)
(if (>= index 0)
(if (bubble index)
(bubble-sort-iter (- index 1))
#f)
#f))))
(<change>
(bubble-sort-iter (- (vector-length vector) 2))
((lambda (x) x) (bubble-sort-iter (- (vector-length vector) 2)))))))
(vect (vector 9 5 1 7 8 9 4 6 2 3)))
(bubble-sort vect)
(<change>
(equal? vect (vector 1 2 3 4 5 6 7 8 9 9))
((lambda (x) x) (equal? vect (vector 1 2 3 4 5 6 7 8 9 9))))
(letrec ((selection-sort (lambda (vector)
(letrec ((swap (lambda (vector index1 index2)
(let ((temp (vector-ref vector index1)))
(vector-set! vector index1 (vector-ref vector index2))
(vector-set! vector index2 temp))))
(pos-of-min (lambda (vector low high)
(letrec ((min-iter (lambda (index pos-of-min-so-far)
(if (<= index high)
(if (< (vector-ref vector index) (vector-ref vector pos-of-min-so-far))
(min-iter (+ index 1) index)
(min-iter (+ index 1) pos-of-min-so-far))
pos-of-min-so-far))))
(min-iter (+ low 1) low)))))
(let ((high (- (vector-length vector) 1)))
(letrec ((selection-sort-iter (lambda (index)
(if (< index high)
(begin
(swap vector index (pos-of-min vector index high))
(selection-sort-iter (+ index 1)))
#f))))
(selection-sort-iter 0))))))
(vect2 (vector 5 7 0 9 6 4 3 8 2 1)))
(selection-sort vect2)
(<change>
(equal? vect2 (vector 0 1 2 3 4 5 6 7 8 9))
())
(letrec ((result ())
(display2 (lambda (item)
(set! result (cons item result))))
(newline2 (lambda ()
(set! result (cons 'newline result))))
(make-row (lambda (key name age wage)
(vector key name age wage)))
(key-ref (lambda (row)
(vector-ref row 0)))
(name-ref (lambda (row)
(vector-ref row 1)))
(age-ref (lambda (row)
(vector-ref row 2)))
(wage-ref (lambda (row)
(vector-ref row 3)))
(key-set! (lambda (row value)
(vector-set! row 0 value)))
(name-set! (lambda (row value)
(vector-set! row 1 value)))
(age-set! (lambda (row value)
(vector-set! row 2 value)))
(wage-set! (lambda (row value)
(vector-set! row 3 value)))
(show-row (lambda (row)
(display2 "[Sleutel:")
(display2 (key-ref row))
(display2 "]")
(display2 "[Naam:")
(display2 (name-ref row))
(display2 "]")
(display2 "[Leeftijd:")
(display2 (age-ref row))
(display2 "]")
(display2 "[Salaris:")
(display2 (wage-ref row))
(display2 "]")))
(make-table (lambda (rows)
(make-vector rows 0)))
(table-size (lambda (table)
(vector-length table)))
(row-ref (lambda (table pos)
(if (< pos (table-size table))
(vector-ref table pos)
#f)))
(row-set! (lambda (table pos row)
(if (< pos (table-size table))
(vector-set! table pos row)
#f)))
(show-table (lambda (table)
(letrec ((iter (lambda (index)
(if (= index (table-size table))
(newline2)
(begin
(show-row (row-ref table index))
(newline2)
(iter (+ index 1)))))))
(iter 0))))
(table (make-table 10)))
(row-set! table 0 (make-row 8 'Bernard 45 120000))
(row-set! table 1 (make-row 3 'Dirk 26 93000))
(row-set! table 2 (make-row 6 'George 48 130000))
(row-set! table 3 (make-row 6 'Greet 27 75000))
(row-set! table 4 (make-row 1 'Kaat 18 69000))
(row-set! table 5 (make-row 5 'Mauranne 21 69000))
(row-set! table 6 (make-row 4 'Peter 33 80000))
(row-set! table 7 (make-row 2 'Piet 25 96000))
(row-set! table 8 (make-row 9 'Tom 26 96000))
(row-set! table 9 (make-row 6 'Veronique 36 115000))
(letrec ((expected-result (__toplevel_cons
'newline
(__toplevel_cons
'newline
(__toplevel_cons
"]"
(__toplevel_cons
115000
(__toplevel_cons
"[Salaris:"
(__toplevel_cons
"]"
(__toplevel_cons
36
(__toplevel_cons
"[Leeftijd:"
(__toplevel_cons
"]"
(__toplevel_cons
'Veronique
(__toplevel_cons
"[Naam:"
(__toplevel_cons
"]"
(__toplevel_cons
6
(__toplevel_cons
"[Sleutel:"
(__toplevel_cons
'newline
(__toplevel_cons
"]"
(__toplevel_cons
96000
(__toplevel_cons
"[Salaris:"
(__toplevel_cons
"]"
(__toplevel_cons
26
(__toplevel_cons
"[Leeftijd:"
(__toplevel_cons
"]"
(__toplevel_cons
'Tom
(__toplevel_cons
"[Naam:"
(__toplevel_cons
"]"
(__toplevel_cons
9
(__toplevel_cons
"[Sleutel:"
(__toplevel_cons
'newline
(__toplevel_cons
"]"
(__toplevel_cons
96000
(__toplevel_cons
"[Salaris:"
(__toplevel_cons
"]"
(__toplevel_cons
25
(__toplevel_cons
"[Leeftijd:"
(__toplevel_cons
"]"
(__toplevel_cons
'Piet
(__toplevel_cons
"[Naam:"
(__toplevel_cons
"]"
(__toplevel_cons
2
(__toplevel_cons
"[Sleutel:"
(__toplevel_cons
'newline
(__toplevel_cons
"]"
(__toplevel_cons
80000
(__toplevel_cons
"[Salaris:"
(__toplevel_cons
"]"
(__toplevel_cons
33
(__toplevel_cons
"[Leeftijd:"
(__toplevel_cons
"]"
(__toplevel_cons
'Peter
(__toplevel_cons
"[Naam:"
(__toplevel_cons
"]"
(__toplevel_cons
4
(__toplevel_cons
"[Sleutel:"
(__toplevel_cons
'newline
(__toplevel_cons
"]"
(__toplevel_cons
69000
(__toplevel_cons
"[Salaris:"
(__toplevel_cons
"]"
(__toplevel_cons
21
(__toplevel_cons
"[Leeftijd:"
(__toplevel_cons
"]"
(__toplevel_cons
'Mauranne
(__toplevel_cons
"[Naam:"
(__toplevel_cons
"]"
(__toplevel_cons
5
(__toplevel_cons
"[Sleutel:"
(__toplevel_cons
'newline
(__toplevel_cons
"]"
(__toplevel_cons
69000
(__toplevel_cons
"[Salaris:"
(__toplevel_cons
"]"
(__toplevel_cons
18
(__toplevel_cons
"[Leeftijd:"
(__toplevel_cons
"]"
(__toplevel_cons
'Kaat
(__toplevel_cons
"[Naam:"
(__toplevel_cons
"]"
(__toplevel_cons
1
(__toplevel_cons
"[Sleutel:"
(__toplevel_cons
'newline
(__toplevel_cons
"]"
(__toplevel_cons
75000
(__toplevel_cons
"[Salaris:"
(__toplevel_cons
"]"
(__toplevel_cons
27
(__toplevel_cons
"[Leeftijd:"
(__toplevel_cons
"]"
(__toplevel_cons
'Greet
(__toplevel_cons
"[Naam:"
(__toplevel_cons
"]"
(__toplevel_cons
6
(__toplevel_cons
"[Sleutel:"
(__toplevel_cons
'newline
(__toplevel_cons
"]"
(__toplevel_cons
130000
(__toplevel_cons
"[Salaris:"
(__toplevel_cons
"]"
(__toplevel_cons
48
(__toplevel_cons
"[Leeftijd:"
(__toplevel_cons
"]"
(__toplevel_cons
'George
(__toplevel_cons
"[Naam:"
(__toplevel_cons
"]"
(__toplevel_cons
6
(__toplevel_cons
"[Sleutel:"
(__toplevel_cons
'newline
(__toplevel_cons
"]"
(__toplevel_cons
93000
(__toplevel_cons
"[Salaris:"
(__toplevel_cons
"]"
(__toplevel_cons
26
(__toplevel_cons
"[Leeftijd:"
(__toplevel_cons
"]"
(__toplevel_cons
'Dirk
(__toplevel_cons
"[Naam:"
(__toplevel_cons
"]"
(__toplevel_cons
3
(__toplevel_cons
"[Sleutel:"
(__toplevel_cons
'newline
(__toplevel_cons
"]"
(__toplevel_cons
120000
(__toplevel_cons
"[Salaris:"
(__toplevel_cons
"]"
(__toplevel_cons
45
(__toplevel_cons
"[Leeftijd:"
(__toplevel_cons
"]"
(__toplevel_cons
'Bernard
(__toplevel_cons
"[Naam:"
(__toplevel_cons "]" (__toplevel_cons 8 (__toplevel_cons "[Sleutel:" ())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
(show-table table)
(equal? expected-result result)
(letrec ((create-dictionary (lambda ()
(let ((content ()))
(letrec ((empty? (lambda ()
(null? content)))
(insert (lambda (key info)
(let ((temp (assoc key content)))
(if temp
(set-cdr! temp info)
(set! content (cons (cons key info) content))))
#t))
(delete (lambda (key)
(letrec ((remove-iter (lambda (current prev)
(if (null? current)
#f
(if (eq? key (caar current))
(begin
(if (null? prev)
(set! content (cdr content))
(set-cdr! prev (cdr current)))
#t)
(remove-iter (cdr current) current))))))
(remove-iter content ()))))
(lookup (lambda (key)
(let ((temp (assoc key content)))
(if temp (cdr temp) #f))))
(map (lambda (a-function)
(letrec ((map-iter (lambda (the-current result)
(if (null? the-current)
(reverse result)
(map-iter (cdr the-current) (cons (a-function (caar the-current) (cdar the-current)) result))))))
(map-iter content ()))))
(foreach (lambda (a-action)
(letrec ((foreach-iter (lambda (the-current)
(if (null? the-current)
#t
(begin
(a-action (caar the-current) (cdar the-current))
(foreach-iter (cdr the-current)))))))
(foreach-iter content)
#t)))
(display-dict (lambda ()
(foreach (lambda (key info) (display key) (display " ") (display info) (newline)))))
(dispatch (lambda (msg args)
(if (eq? msg 'empty?)
(empty?)
(if (eq? msg 'insert)
(insert (car args) (cadr args))
(if (eq? msg 'delete)
(delete (car args))
(if (eq? msg 'lookup)
(lookup (car args))
(if (eq? msg 'map)
(map (car args))
(if (eq? msg 'foreach)
(foreach (car args))
(if (eq? msg 'display)
(display-dict)
(error "unknown request -- create-dictionary" msg)))))))))))
dispatch))))
(nl->fr (create-dictionary)))
(nl->fr 'insert (__toplevel_cons 'fiets (__toplevel_cons (__toplevel_cons 'bicyclette ()) ())))
(nl->fr 'insert (__toplevel_cons 'auto (__toplevel_cons (__toplevel_cons 'voiture ()) ())))
(nl->fr 'insert (__toplevel_cons 'huis (__toplevel_cons (__toplevel_cons 'maison ()) ())))
(nl->fr 'insert (__toplevel_cons 'vrachtwagen (__toplevel_cons (__toplevel_cons 'camion ()) ())))
(nl->fr 'insert (__toplevel_cons 'tientonner (__toplevel_cons (__toplevel_cons 'camion ()) ())))
(nl->fr 'lookup (__toplevel_cons 'fiets ()))
(nl->fr 'display ())
(letrec ((fr->eng (create-dictionary)))
(fr->eng 'insert (__toplevel_cons 'bicyclette (__toplevel_cons (__toplevel_cons 'bike ()) ())))
(fr->eng 'insert (__toplevel_cons 'voiture (__toplevel_cons (__toplevel_cons 'car ()) ())))
(fr->eng
'insert
(__toplevel_cons 'maison (__toplevel_cons (__toplevel_cons 'house (__toplevel_cons 'home ())) ())))
(fr->eng 'insert (__toplevel_cons 'camion (__toplevel_cons (__toplevel_cons 'truck ()) ())))
(fr->eng 'lookup (__toplevel_cons 'bicyclette ()))
#t
(letrec ((my-++ (lambda (n)
(+ n 1)))
(my--- (lambda (n)
(- n 1)))
(false #f)
(true #t)
(nil ())
(key (lambda (x)
x))
(make-heap (lambda (a-vector nr-of-elements)
(letrec ((iter (lambda (index)
(if (> index 0)
(begin
(sift-down a-vector index nr-of-elements)
(iter (my--- index)))
#f))))
(iter (quotient nr-of-elements 2)))))
(sift-down (lambda (heap from to)
(letrec ((smallest-child (lambda (parent)
(let* ((child1 (* 2 parent))
(child2 (my-++ child1)))
(if (> child1 to)
false
(if (> child2 to)
child1
(if (< (key (vector-ref heap child1)) (key (vector-ref heap child2)))
child1
child2))))))
(iter (lambda (parent)
(let ((child (smallest-child parent)))
(if child
(if (> (key (vector-ref heap parent)) (key (vector-ref heap child)))
(begin
(swap heap child parent)
(iter child))
#f)
#f)))))
(iter from))))
(swap (lambda (a-vector i1 i2)
(let ((temp (vector-ref a-vector i1)))
(vector-set! a-vector i1 (vector-ref a-vector i2))
(vector-set! a-vector i2 temp))))
(sift-up (lambda (heap from)
(letrec ((iter (lambda (child)
(let ((parent (quotient child 2)))
(if (> parent 0)
(if (> (key (vector-ref heap parent)) (key (vector-ref heap child)))
(begin
(swap heap child parent)
(iter parent))
#f)
#f)))))
(iter from))))
(create-heap (lambda (size)
(cons 0 (make-vector (my-++ size)))))
(is-empty? (lambda (heap)
(eq? (car heap) 0)))
(insert (lambda (heap item)
(let* ((content (cdr heap))
(new-nr-of-elements (my-++ (car heap)))
(size (my--- (vector-length content))))
(display "insert ")
(if (> new-nr-of-elements size)
false
(begin
(vector-set! content new-nr-of-elements item)
(sift-up content new-nr-of-elements)
(set-car! heap new-nr-of-elements)))
(display heap)
(newline))))
(v (vector 'lol 5 8 1 3 9 10 2 0)))
(make-heap v 8)
(equal? v (vector 'lol 0 3 1 5 9 10 2 8))
(letrec ((quick-sort (lambda (a-list)
(letrec ((rearrange (lambda (pivot some-list)
(letrec ((rearrange-iter (lambda (rest result)
(if (null? rest)
result
(if (<= (car rest) pivot)
(rearrange-iter (cdr rest) (cons (cons (car rest) (car result)) (cdr result)))
(rearrange-iter (cdr rest) (cons (car result) (cons (car rest) (cdr result)))))))))
(rearrange-iter some-list (cons () ()))))))
(if (<= (length a-list) 1)
a-list
(let* ((pivot (car a-list))
(sub-lists (rearrange pivot (cdr a-list))))
(append (quick-sort (car sub-lists)) (append (list pivot) (quick-sort (cdr sub-lists))))))))))
(equal?
(quick-sort
(__toplevel_cons
9
(__toplevel_cons
8
(__toplevel_cons
7
(__toplevel_cons
6
(__toplevel_cons
5
(__toplevel_cons
4
(__toplevel_cons
3
(__toplevel_cons 2 (__toplevel_cons 1 (__toplevel_cons 0 (__toplevel_cons 9 ()))))))))))))
(__toplevel_cons
0
(__toplevel_cons
1
(__toplevel_cons
2
(__toplevel_cons
3
(__toplevel_cons
4
(__toplevel_cons
5
(__toplevel_cons
6
(__toplevel_cons 7 (__toplevel_cons 8 (__toplevel_cons 9 (__toplevel_cons 9 ()))))))))))))
(letrec ((insertion-sort (lambda (vector)
(let ((high (- (vector-length vector) 1)))
(letrec ((shift-left (lambda (vector index)
(vector-set! vector (- index 1) (vector-ref vector index))))
(insert-sort-iter (lambda (index1)
(letrec ((insert (lambda (index1)
(let ((insert-value (vector-ref vector (- index1 1))))
(letrec ((insert-iter (lambda (index2)
(if (if (<= index2 high) (< (vector-ref vector index2) insert-value) #f)
(begin
(shift-left vector index2)
(insert-iter (+ index2 1)))
(vector-set! vector (- index2 1) insert-value)))))
(insert-iter index1))))))
(if (> index1 0)
(begin
(insert index1)
(insert-sort-iter (- index1 1)))
#f)))))
(insert-sort-iter high)))))
(vect3 (vector 5 2 7 1 0 9 8 6 3 4)))
(insertion-sort vect3)
(equal? vect3 (vector 0 1 2 3 4 5 6 7 8 9))
(letrec ((make-item (lambda (priority element)
(cons priority element)))
(get-priority (lambda (item)
(car item)))
(get-element (lambda (item)
(cdr item)))
(create-priority-queue (lambda ()
(let ((front (cons 'boe ())))
(letrec ((content (lambda ()
(cdr front)))
(insert-after! (lambda (cell item)
(let ((new-cell (cons item ())))
(set-cdr! new-cell (cdr cell))
(set-cdr! cell new-cell))))
(find-prev-cell (lambda (priority)
(letrec ((find-iter (lambda (rest prev)
(if (null? rest)
prev
(if (> (get-priority (car rest)) priority)
(find-iter (cdr rest) rest)
prev)))))
(find-iter (content) front))))
(empty? (lambda ()
(null? (content))))
(enqueue (lambda (priority element)
(insert-after! (find-prev-cell priority) (make-item priority element))
true))
(dequeue (lambda ()
(if (null? (content))
false
(let ((temp (car (content))))
(set-cdr! front (cdr (content)))
(get-element temp)))))
(serve (lambda ()
(if (null? (content))
false
(get-element (car (content))))))
(dispatch (lambda (m)
(if (eq? m 'empty?)
empty?
(if (eq? m 'enqueue)
enqueue
(if (eq? m 'dequeue)
dequeue
(if (eq? m 'serve)
serve
(error "unknown request
-- create-priority-queue" m))))))))
dispatch))))
(pq (create-priority-queue)))
((pq 'enqueue) 66 'Patrick)
((pq 'enqueue) -106 'Octo)
((pq 'enqueue) 0 'Sandy)
((pq 'enqueue) 89 'Spongebob)
((pq 'dequeue))
(equal? ((pq 'dequeue)) 'Patrick)
(letrec ((copy (lambda (from-vector to-vector from-index to-index)
(vector-set! to-vector to-index (vector-ref from-vector from-index))))
(move (lambda (from-vector to-vector from-low from-high to-index)
(letrec ((move-iter (lambda (n)
(if (<= (+ from-low n) from-high)
(begin
(copy from-vector to-vector (+ from-low n) (+ to-index n))
(move-iter (+ n 1)))
#f))))
(move-iter 0))))
(merge (lambda (vector1 vector2 vector low1 high1 low2 high2 to-index)
(letrec ((merge-iter (lambda (index index1 index2)
(if (> index1 high1)
(move vector2 vector index2 high2 index)
(if (> index2 high2)
(move vector1 vector index1 high1 index)
(if (< (vector-ref vector1 index1) (vector-ref vector2 index2))
(begin
(copy vector1 vector index1 index)
(merge-iter (+ index 1) (+ index1 1) index2))
(begin
(copy vector2 vector index2 index)
(merge-iter (+ index 1) index1 (+ index2 1)))))))))
(merge-iter to-index low1 low2))))
(bottom-up-merge-sort (lambda (vector)
(letrec ((merge-subs (lambda (len)
(let ((aux-vector (make-vector (vector-length vector) 0)))
(letrec ((merge-subs-iter (lambda (index)
(if (< index (- (vector-length vector) (* 2 len)))
(begin
(merge vector vector aux-vector index (+ index len -1) (+ index len) (+ index len len -1) index)
(move aux-vector vector index (+ index len len -1) index)
(merge-subs-iter (+ index len len)))
(if (< index (- (vector-length vector) len))
(begin
(merge
vector
vector
aux-vector
index
(+ index len -1)
(+ index len)
(- (vector-length vector) 1)
index)
(move aux-vector vector index (- (vector-length vector) 1) index))
#f)))))
(merge-subs-iter 0)))))
(merge-sort-iter (lambda (len)
(if (< len (vector-length vector))
(begin
(merge-subs len)
(merge-sort-iter (* 2 len)))
#f))))
(merge-sort-iter 1)))))
(let ((aVector (vector 8 3 6 6 0 5 4 2 9 6)))
(bottom-up-merge-sort aVector)
(equal? aVector (vector 0 2 3 4 5 6 6 6 8 9)))
(letrec ((quick-sort2 (lambda (vector)
(letrec ((swap (lambda (v index1 index2)
(let ((temp (vector-ref v index1)))
(vector-set! v index1 (vector-ref v index2))
(vector-set! v index2 temp))))
(quick-sort-aux (lambda (low high)
(letrec ((quick-sort-aux-iter (lambda (mid-value from to)
(letrec ((quick-right (lambda (index1)
(if (if (< index1 high) (< (vector-ref vector index1) mid-value) #f)
(quick-right (+ index1 1))
index1)))
(quick-left (lambda (index2)
(if (if (> index2 low) (> (vector-ref vector index2) mid-value) #f)
(quick-left (- index2 1))
index2))))
(let ((index1 (quick-right (+ from 1)))
(index2 (quick-left to)))
(if (< index1 index2)
(begin
(swap vector index1 index2)
(quick-sort-aux-iter mid-value index1 index2))
index2))))))
(if (< low high)
(let ((middle (quotient (+ low high) 2))
(pivot-index (+ low 1)))
(swap vector middle pivot-index)
(if (> (vector-ref vector pivot-index) (vector-ref vector high))
(swap vector pivot-index high)
#f)
(if (> (vector-ref vector low) (vector-ref vector high))
(swap vector low high)
#f)
(if (< (vector-ref vector pivot-index) (vector-ref vector low))
(swap vector pivot-index low)
#f)
(let ((mid-index (quick-sort-aux-iter (vector-ref vector pivot-index) (+ low 1) high)))
(swap vector mid-index pivot-index)
(quick-sort-aux low (- mid-index 1))
(quick-sort-aux (+ mid-index 1) high)))
#f)))))
(quick-sort-aux 0 (- (vector-length vector) 1)))))
(test3 (vector 8 3 6 6 1 5 4 2 9 6)))
(quick-sort2 test3)
(equal? test3 (vector 1 2 3 4 5 6 6 6 8 9))
(letrec ((create-stack (lambda (eq-fnct)
(let ((content ()))
(letrec ((empty? (lambda ()
(null? content)))
(push (lambda (element)
(set! content (cons element content))
#t))
(pop (lambda ()
(if (null? content)
#f
(let ((temp (car content)))
(set! content (cdr content))
temp))))
(top (lambda ()
(if (null? content) #f (car content))))
(is-in (lambda (element)
(if (member element content) #t #f)))
(dispatch (lambda (m)
(if (eq? m 'empty?)
empty?
(if (eq? m 'push)
push
(if (eq? m 'pop)
pop
(if (eq? m 'top)
top
(if (eq? m 'is-in)
is-in
(error "unknown request -- create-stack" m)))))))))
dispatch)))))
(let ((stack (create-stack =)))
(if ((stack 'empty?))
(if (begin ((stack 'push) 13) (not ((stack 'empty?))))
(if ((stack 'is-in) 13)
(if (= ((stack 'top)) 13)
(begin
((stack 'push) 14)
(= ((stack 'pop)) 14))
#f)
#f)
#f)
#f)))))))))))))))
| null |
https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_ad_all-4.scm
|
scheme
|
Changes:
* negated predicates: 0
* swapped branches: 0
|
* removed : 1
* added : 1
* swaps : 1
* calls to i d fun : 3
(letrec ((bubble-sort (lambda (vector)
(letrec ((swap (lambda (vector index1 index2)
(let ((temp (vector-ref vector index1)))
(<change>
()
(vector-set! vector index1 (vector-ref vector index2)))
(<change>
(vector-set! vector index1 (vector-ref vector index2))
(vector-set! vector index2 temp))
(<change>
(vector-set! vector index2 temp)
(vector-set! vector index1 (vector-ref vector index2))))))
(bubble (lambda (index)
(letrec ((bubble-iter (lambda (index1 changed)
(if (<= index1 index)
(begin
(<change>
(if (> (vector-ref vector index1) (vector-ref vector (+ index1 1)))
(begin
(swap vector index1 (+ index1 1))
(set! changed #t))
#f)
((lambda (x) x)
(if (> (vector-ref vector index1) (vector-ref vector (+ index1 1)))
(begin
(swap vector index1 (+ index1 1))
(set! changed #t))
#f)))
(bubble-iter (+ index1 1) changed))
changed))))
(bubble-iter 0 #f))))
(bubble-sort-iter (lambda (index)
(if (>= index 0)
(if (bubble index)
(bubble-sort-iter (- index 1))
#f)
#f))))
(<change>
(bubble-sort-iter (- (vector-length vector) 2))
((lambda (x) x) (bubble-sort-iter (- (vector-length vector) 2)))))))
(vect (vector 9 5 1 7 8 9 4 6 2 3)))
(bubble-sort vect)
(<change>
(equal? vect (vector 1 2 3 4 5 6 7 8 9 9))
((lambda (x) x) (equal? vect (vector 1 2 3 4 5 6 7 8 9 9))))
(letrec ((selection-sort (lambda (vector)
(letrec ((swap (lambda (vector index1 index2)
(let ((temp (vector-ref vector index1)))
(vector-set! vector index1 (vector-ref vector index2))
(vector-set! vector index2 temp))))
(pos-of-min (lambda (vector low high)
(letrec ((min-iter (lambda (index pos-of-min-so-far)
(if (<= index high)
(if (< (vector-ref vector index) (vector-ref vector pos-of-min-so-far))
(min-iter (+ index 1) index)
(min-iter (+ index 1) pos-of-min-so-far))
pos-of-min-so-far))))
(min-iter (+ low 1) low)))))
(let ((high (- (vector-length vector) 1)))
(letrec ((selection-sort-iter (lambda (index)
(if (< index high)
(begin
(swap vector index (pos-of-min vector index high))
(selection-sort-iter (+ index 1)))
#f))))
(selection-sort-iter 0))))))
(vect2 (vector 5 7 0 9 6 4 3 8 2 1)))
(selection-sort vect2)
(<change>
(equal? vect2 (vector 0 1 2 3 4 5 6 7 8 9))
())
(letrec ((result ())
(display2 (lambda (item)
(set! result (cons item result))))
(newline2 (lambda ()
(set! result (cons 'newline result))))
(make-row (lambda (key name age wage)
(vector key name age wage)))
(key-ref (lambda (row)
(vector-ref row 0)))
(name-ref (lambda (row)
(vector-ref row 1)))
(age-ref (lambda (row)
(vector-ref row 2)))
(wage-ref (lambda (row)
(vector-ref row 3)))
(key-set! (lambda (row value)
(vector-set! row 0 value)))
(name-set! (lambda (row value)
(vector-set! row 1 value)))
(age-set! (lambda (row value)
(vector-set! row 2 value)))
(wage-set! (lambda (row value)
(vector-set! row 3 value)))
(show-row (lambda (row)
(display2 "[Sleutel:")
(display2 (key-ref row))
(display2 "]")
(display2 "[Naam:")
(display2 (name-ref row))
(display2 "]")
(display2 "[Leeftijd:")
(display2 (age-ref row))
(display2 "]")
(display2 "[Salaris:")
(display2 (wage-ref row))
(display2 "]")))
(make-table (lambda (rows)
(make-vector rows 0)))
(table-size (lambda (table)
(vector-length table)))
(row-ref (lambda (table pos)
(if (< pos (table-size table))
(vector-ref table pos)
#f)))
(row-set! (lambda (table pos row)
(if (< pos (table-size table))
(vector-set! table pos row)
#f)))
(show-table (lambda (table)
(letrec ((iter (lambda (index)
(if (= index (table-size table))
(newline2)
(begin
(show-row (row-ref table index))
(newline2)
(iter (+ index 1)))))))
(iter 0))))
(table (make-table 10)))
(row-set! table 0 (make-row 8 'Bernard 45 120000))
(row-set! table 1 (make-row 3 'Dirk 26 93000))
(row-set! table 2 (make-row 6 'George 48 130000))
(row-set! table 3 (make-row 6 'Greet 27 75000))
(row-set! table 4 (make-row 1 'Kaat 18 69000))
(row-set! table 5 (make-row 5 'Mauranne 21 69000))
(row-set! table 6 (make-row 4 'Peter 33 80000))
(row-set! table 7 (make-row 2 'Piet 25 96000))
(row-set! table 8 (make-row 9 'Tom 26 96000))
(row-set! table 9 (make-row 6 'Veronique 36 115000))
(letrec ((expected-result (__toplevel_cons
'newline
(__toplevel_cons
'newline
(__toplevel_cons
"]"
(__toplevel_cons
115000
(__toplevel_cons
"[Salaris:"
(__toplevel_cons
"]"
(__toplevel_cons
36
(__toplevel_cons
"[Leeftijd:"
(__toplevel_cons
"]"
(__toplevel_cons
'Veronique
(__toplevel_cons
"[Naam:"
(__toplevel_cons
"]"
(__toplevel_cons
6
(__toplevel_cons
"[Sleutel:"
(__toplevel_cons
'newline
(__toplevel_cons
"]"
(__toplevel_cons
96000
(__toplevel_cons
"[Salaris:"
(__toplevel_cons
"]"
(__toplevel_cons
26
(__toplevel_cons
"[Leeftijd:"
(__toplevel_cons
"]"
(__toplevel_cons
'Tom
(__toplevel_cons
"[Naam:"
(__toplevel_cons
"]"
(__toplevel_cons
9
(__toplevel_cons
"[Sleutel:"
(__toplevel_cons
'newline
(__toplevel_cons
"]"
(__toplevel_cons
96000
(__toplevel_cons
"[Salaris:"
(__toplevel_cons
"]"
(__toplevel_cons
25
(__toplevel_cons
"[Leeftijd:"
(__toplevel_cons
"]"
(__toplevel_cons
'Piet
(__toplevel_cons
"[Naam:"
(__toplevel_cons
"]"
(__toplevel_cons
2
(__toplevel_cons
"[Sleutel:"
(__toplevel_cons
'newline
(__toplevel_cons
"]"
(__toplevel_cons
80000
(__toplevel_cons
"[Salaris:"
(__toplevel_cons
"]"
(__toplevel_cons
33
(__toplevel_cons
"[Leeftijd:"
(__toplevel_cons
"]"
(__toplevel_cons
'Peter
(__toplevel_cons
"[Naam:"
(__toplevel_cons
"]"
(__toplevel_cons
4
(__toplevel_cons
"[Sleutel:"
(__toplevel_cons
'newline
(__toplevel_cons
"]"
(__toplevel_cons
69000
(__toplevel_cons
"[Salaris:"
(__toplevel_cons
"]"
(__toplevel_cons
21
(__toplevel_cons
"[Leeftijd:"
(__toplevel_cons
"]"
(__toplevel_cons
'Mauranne
(__toplevel_cons
"[Naam:"
(__toplevel_cons
"]"
(__toplevel_cons
5
(__toplevel_cons
"[Sleutel:"
(__toplevel_cons
'newline
(__toplevel_cons
"]"
(__toplevel_cons
69000
(__toplevel_cons
"[Salaris:"
(__toplevel_cons
"]"
(__toplevel_cons
18
(__toplevel_cons
"[Leeftijd:"
(__toplevel_cons
"]"
(__toplevel_cons
'Kaat
(__toplevel_cons
"[Naam:"
(__toplevel_cons
"]"
(__toplevel_cons
1
(__toplevel_cons
"[Sleutel:"
(__toplevel_cons
'newline
(__toplevel_cons
"]"
(__toplevel_cons
75000
(__toplevel_cons
"[Salaris:"
(__toplevel_cons
"]"
(__toplevel_cons
27
(__toplevel_cons
"[Leeftijd:"
(__toplevel_cons
"]"
(__toplevel_cons
'Greet
(__toplevel_cons
"[Naam:"
(__toplevel_cons
"]"
(__toplevel_cons
6
(__toplevel_cons
"[Sleutel:"
(__toplevel_cons
'newline
(__toplevel_cons
"]"
(__toplevel_cons
130000
(__toplevel_cons
"[Salaris:"
(__toplevel_cons
"]"
(__toplevel_cons
48
(__toplevel_cons
"[Leeftijd:"
(__toplevel_cons
"]"
(__toplevel_cons
'George
(__toplevel_cons
"[Naam:"
(__toplevel_cons
"]"
(__toplevel_cons
6
(__toplevel_cons
"[Sleutel:"
(__toplevel_cons
'newline
(__toplevel_cons
"]"
(__toplevel_cons
93000
(__toplevel_cons
"[Salaris:"
(__toplevel_cons
"]"
(__toplevel_cons
26
(__toplevel_cons
"[Leeftijd:"
(__toplevel_cons
"]"
(__toplevel_cons
'Dirk
(__toplevel_cons
"[Naam:"
(__toplevel_cons
"]"
(__toplevel_cons
3
(__toplevel_cons
"[Sleutel:"
(__toplevel_cons
'newline
(__toplevel_cons
"]"
(__toplevel_cons
120000
(__toplevel_cons
"[Salaris:"
(__toplevel_cons
"]"
(__toplevel_cons
45
(__toplevel_cons
"[Leeftijd:"
(__toplevel_cons
"]"
(__toplevel_cons
'Bernard
(__toplevel_cons
"[Naam:"
(__toplevel_cons "]" (__toplevel_cons 8 (__toplevel_cons "[Sleutel:" ())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
(show-table table)
(equal? expected-result result)
(letrec ((create-dictionary (lambda ()
(let ((content ()))
(letrec ((empty? (lambda ()
(null? content)))
(insert (lambda (key info)
(let ((temp (assoc key content)))
(if temp
(set-cdr! temp info)
(set! content (cons (cons key info) content))))
#t))
(delete (lambda (key)
(letrec ((remove-iter (lambda (current prev)
(if (null? current)
#f
(if (eq? key (caar current))
(begin
(if (null? prev)
(set! content (cdr content))
(set-cdr! prev (cdr current)))
#t)
(remove-iter (cdr current) current))))))
(remove-iter content ()))))
(lookup (lambda (key)
(let ((temp (assoc key content)))
(if temp (cdr temp) #f))))
(map (lambda (a-function)
(letrec ((map-iter (lambda (the-current result)
(if (null? the-current)
(reverse result)
(map-iter (cdr the-current) (cons (a-function (caar the-current) (cdar the-current)) result))))))
(map-iter content ()))))
(foreach (lambda (a-action)
(letrec ((foreach-iter (lambda (the-current)
(if (null? the-current)
#t
(begin
(a-action (caar the-current) (cdar the-current))
(foreach-iter (cdr the-current)))))))
(foreach-iter content)
#t)))
(display-dict (lambda ()
(foreach (lambda (key info) (display key) (display " ") (display info) (newline)))))
(dispatch (lambda (msg args)
(if (eq? msg 'empty?)
(empty?)
(if (eq? msg 'insert)
(insert (car args) (cadr args))
(if (eq? msg 'delete)
(delete (car args))
(if (eq? msg 'lookup)
(lookup (car args))
(if (eq? msg 'map)
(map (car args))
(if (eq? msg 'foreach)
(foreach (car args))
(if (eq? msg 'display)
(display-dict)
(error "unknown request -- create-dictionary" msg)))))))))))
dispatch))))
(nl->fr (create-dictionary)))
(nl->fr 'insert (__toplevel_cons 'fiets (__toplevel_cons (__toplevel_cons 'bicyclette ()) ())))
(nl->fr 'insert (__toplevel_cons 'auto (__toplevel_cons (__toplevel_cons 'voiture ()) ())))
(nl->fr 'insert (__toplevel_cons 'huis (__toplevel_cons (__toplevel_cons 'maison ()) ())))
(nl->fr 'insert (__toplevel_cons 'vrachtwagen (__toplevel_cons (__toplevel_cons 'camion ()) ())))
(nl->fr 'insert (__toplevel_cons 'tientonner (__toplevel_cons (__toplevel_cons 'camion ()) ())))
(nl->fr 'lookup (__toplevel_cons 'fiets ()))
(nl->fr 'display ())
(letrec ((fr->eng (create-dictionary)))
(fr->eng 'insert (__toplevel_cons 'bicyclette (__toplevel_cons (__toplevel_cons 'bike ()) ())))
(fr->eng 'insert (__toplevel_cons 'voiture (__toplevel_cons (__toplevel_cons 'car ()) ())))
(fr->eng
'insert
(__toplevel_cons 'maison (__toplevel_cons (__toplevel_cons 'house (__toplevel_cons 'home ())) ())))
(fr->eng 'insert (__toplevel_cons 'camion (__toplevel_cons (__toplevel_cons 'truck ()) ())))
(fr->eng 'lookup (__toplevel_cons 'bicyclette ()))
#t
(letrec ((my-++ (lambda (n)
(+ n 1)))
(my--- (lambda (n)
(- n 1)))
(false #f)
(true #t)
(nil ())
(key (lambda (x)
x))
(make-heap (lambda (a-vector nr-of-elements)
(letrec ((iter (lambda (index)
(if (> index 0)
(begin
(sift-down a-vector index nr-of-elements)
(iter (my--- index)))
#f))))
(iter (quotient nr-of-elements 2)))))
(sift-down (lambda (heap from to)
(letrec ((smallest-child (lambda (parent)
(let* ((child1 (* 2 parent))
(child2 (my-++ child1)))
(if (> child1 to)
false
(if (> child2 to)
child1
(if (< (key (vector-ref heap child1)) (key (vector-ref heap child2)))
child1
child2))))))
(iter (lambda (parent)
(let ((child (smallest-child parent)))
(if child
(if (> (key (vector-ref heap parent)) (key (vector-ref heap child)))
(begin
(swap heap child parent)
(iter child))
#f)
#f)))))
(iter from))))
(swap (lambda (a-vector i1 i2)
(let ((temp (vector-ref a-vector i1)))
(vector-set! a-vector i1 (vector-ref a-vector i2))
(vector-set! a-vector i2 temp))))
(sift-up (lambda (heap from)
(letrec ((iter (lambda (child)
(let ((parent (quotient child 2)))
(if (> parent 0)
(if (> (key (vector-ref heap parent)) (key (vector-ref heap child)))
(begin
(swap heap child parent)
(iter parent))
#f)
#f)))))
(iter from))))
(create-heap (lambda (size)
(cons 0 (make-vector (my-++ size)))))
(is-empty? (lambda (heap)
(eq? (car heap) 0)))
(insert (lambda (heap item)
(let* ((content (cdr heap))
(new-nr-of-elements (my-++ (car heap)))
(size (my--- (vector-length content))))
(display "insert ")
(if (> new-nr-of-elements size)
false
(begin
(vector-set! content new-nr-of-elements item)
(sift-up content new-nr-of-elements)
(set-car! heap new-nr-of-elements)))
(display heap)
(newline))))
(v (vector 'lol 5 8 1 3 9 10 2 0)))
(make-heap v 8)
(equal? v (vector 'lol 0 3 1 5 9 10 2 8))
(letrec ((quick-sort (lambda (a-list)
(letrec ((rearrange (lambda (pivot some-list)
(letrec ((rearrange-iter (lambda (rest result)
(if (null? rest)
result
(if (<= (car rest) pivot)
(rearrange-iter (cdr rest) (cons (cons (car rest) (car result)) (cdr result)))
(rearrange-iter (cdr rest) (cons (car result) (cons (car rest) (cdr result)))))))))
(rearrange-iter some-list (cons () ()))))))
(if (<= (length a-list) 1)
a-list
(let* ((pivot (car a-list))
(sub-lists (rearrange pivot (cdr a-list))))
(append (quick-sort (car sub-lists)) (append (list pivot) (quick-sort (cdr sub-lists))))))))))
(equal?
(quick-sort
(__toplevel_cons
9
(__toplevel_cons
8
(__toplevel_cons
7
(__toplevel_cons
6
(__toplevel_cons
5
(__toplevel_cons
4
(__toplevel_cons
3
(__toplevel_cons 2 (__toplevel_cons 1 (__toplevel_cons 0 (__toplevel_cons 9 ()))))))))))))
(__toplevel_cons
0
(__toplevel_cons
1
(__toplevel_cons
2
(__toplevel_cons
3
(__toplevel_cons
4
(__toplevel_cons
5
(__toplevel_cons
6
(__toplevel_cons 7 (__toplevel_cons 8 (__toplevel_cons 9 (__toplevel_cons 9 ()))))))))))))
(letrec ((insertion-sort (lambda (vector)
(let ((high (- (vector-length vector) 1)))
(letrec ((shift-left (lambda (vector index)
(vector-set! vector (- index 1) (vector-ref vector index))))
(insert-sort-iter (lambda (index1)
(letrec ((insert (lambda (index1)
(let ((insert-value (vector-ref vector (- index1 1))))
(letrec ((insert-iter (lambda (index2)
(if (if (<= index2 high) (< (vector-ref vector index2) insert-value) #f)
(begin
(shift-left vector index2)
(insert-iter (+ index2 1)))
(vector-set! vector (- index2 1) insert-value)))))
(insert-iter index1))))))
(if (> index1 0)
(begin
(insert index1)
(insert-sort-iter (- index1 1)))
#f)))))
(insert-sort-iter high)))))
(vect3 (vector 5 2 7 1 0 9 8 6 3 4)))
(insertion-sort vect3)
(equal? vect3 (vector 0 1 2 3 4 5 6 7 8 9))
(letrec ((make-item (lambda (priority element)
(cons priority element)))
(get-priority (lambda (item)
(car item)))
(get-element (lambda (item)
(cdr item)))
(create-priority-queue (lambda ()
(let ((front (cons 'boe ())))
(letrec ((content (lambda ()
(cdr front)))
(insert-after! (lambda (cell item)
(let ((new-cell (cons item ())))
(set-cdr! new-cell (cdr cell))
(set-cdr! cell new-cell))))
(find-prev-cell (lambda (priority)
(letrec ((find-iter (lambda (rest prev)
(if (null? rest)
prev
(if (> (get-priority (car rest)) priority)
(find-iter (cdr rest) rest)
prev)))))
(find-iter (content) front))))
(empty? (lambda ()
(null? (content))))
(enqueue (lambda (priority element)
(insert-after! (find-prev-cell priority) (make-item priority element))
true))
(dequeue (lambda ()
(if (null? (content))
false
(let ((temp (car (content))))
(set-cdr! front (cdr (content)))
(get-element temp)))))
(serve (lambda ()
(if (null? (content))
false
(get-element (car (content))))))
(dispatch (lambda (m)
(if (eq? m 'empty?)
empty?
(if (eq? m 'enqueue)
enqueue
(if (eq? m 'dequeue)
dequeue
(if (eq? m 'serve)
serve
(error "unknown request
-- create-priority-queue" m))))))))
dispatch))))
(pq (create-priority-queue)))
((pq 'enqueue) 66 'Patrick)
((pq 'enqueue) -106 'Octo)
((pq 'enqueue) 0 'Sandy)
((pq 'enqueue) 89 'Spongebob)
((pq 'dequeue))
(equal? ((pq 'dequeue)) 'Patrick)
(letrec ((copy (lambda (from-vector to-vector from-index to-index)
(vector-set! to-vector to-index (vector-ref from-vector from-index))))
(move (lambda (from-vector to-vector from-low from-high to-index)
(letrec ((move-iter (lambda (n)
(if (<= (+ from-low n) from-high)
(begin
(copy from-vector to-vector (+ from-low n) (+ to-index n))
(move-iter (+ n 1)))
#f))))
(move-iter 0))))
(merge (lambda (vector1 vector2 vector low1 high1 low2 high2 to-index)
(letrec ((merge-iter (lambda (index index1 index2)
(if (> index1 high1)
(move vector2 vector index2 high2 index)
(if (> index2 high2)
(move vector1 vector index1 high1 index)
(if (< (vector-ref vector1 index1) (vector-ref vector2 index2))
(begin
(copy vector1 vector index1 index)
(merge-iter (+ index 1) (+ index1 1) index2))
(begin
(copy vector2 vector index2 index)
(merge-iter (+ index 1) index1 (+ index2 1)))))))))
(merge-iter to-index low1 low2))))
(bottom-up-merge-sort (lambda (vector)
(letrec ((merge-subs (lambda (len)
(let ((aux-vector (make-vector (vector-length vector) 0)))
(letrec ((merge-subs-iter (lambda (index)
(if (< index (- (vector-length vector) (* 2 len)))
(begin
(merge vector vector aux-vector index (+ index len -1) (+ index len) (+ index len len -1) index)
(move aux-vector vector index (+ index len len -1) index)
(merge-subs-iter (+ index len len)))
(if (< index (- (vector-length vector) len))
(begin
(merge
vector
vector
aux-vector
index
(+ index len -1)
(+ index len)
(- (vector-length vector) 1)
index)
(move aux-vector vector index (- (vector-length vector) 1) index))
#f)))))
(merge-subs-iter 0)))))
(merge-sort-iter (lambda (len)
(if (< len (vector-length vector))
(begin
(merge-subs len)
(merge-sort-iter (* 2 len)))
#f))))
(merge-sort-iter 1)))))
(let ((aVector (vector 8 3 6 6 0 5 4 2 9 6)))
(bottom-up-merge-sort aVector)
(equal? aVector (vector 0 2 3 4 5 6 6 6 8 9)))
(letrec ((quick-sort2 (lambda (vector)
(letrec ((swap (lambda (v index1 index2)
(let ((temp (vector-ref v index1)))
(vector-set! v index1 (vector-ref v index2))
(vector-set! v index2 temp))))
(quick-sort-aux (lambda (low high)
(letrec ((quick-sort-aux-iter (lambda (mid-value from to)
(letrec ((quick-right (lambda (index1)
(if (if (< index1 high) (< (vector-ref vector index1) mid-value) #f)
(quick-right (+ index1 1))
index1)))
(quick-left (lambda (index2)
(if (if (> index2 low) (> (vector-ref vector index2) mid-value) #f)
(quick-left (- index2 1))
index2))))
(let ((index1 (quick-right (+ from 1)))
(index2 (quick-left to)))
(if (< index1 index2)
(begin
(swap vector index1 index2)
(quick-sort-aux-iter mid-value index1 index2))
index2))))))
(if (< low high)
(let ((middle (quotient (+ low high) 2))
(pivot-index (+ low 1)))
(swap vector middle pivot-index)
(if (> (vector-ref vector pivot-index) (vector-ref vector high))
(swap vector pivot-index high)
#f)
(if (> (vector-ref vector low) (vector-ref vector high))
(swap vector low high)
#f)
(if (< (vector-ref vector pivot-index) (vector-ref vector low))
(swap vector pivot-index low)
#f)
(let ((mid-index (quick-sort-aux-iter (vector-ref vector pivot-index) (+ low 1) high)))
(swap vector mid-index pivot-index)
(quick-sort-aux low (- mid-index 1))
(quick-sort-aux (+ mid-index 1) high)))
#f)))))
(quick-sort-aux 0 (- (vector-length vector) 1)))))
(test3 (vector 8 3 6 6 1 5 4 2 9 6)))
(quick-sort2 test3)
(equal? test3 (vector 1 2 3 4 5 6 6 6 8 9))
(letrec ((create-stack (lambda (eq-fnct)
(let ((content ()))
(letrec ((empty? (lambda ()
(null? content)))
(push (lambda (element)
(set! content (cons element content))
#t))
(pop (lambda ()
(if (null? content)
#f
(let ((temp (car content)))
(set! content (cdr content))
temp))))
(top (lambda ()
(if (null? content) #f (car content))))
(is-in (lambda (element)
(if (member element content) #t #f)))
(dispatch (lambda (m)
(if (eq? m 'empty?)
empty?
(if (eq? m 'push)
push
(if (eq? m 'pop)
pop
(if (eq? m 'top)
top
(if (eq? m 'is-in)
is-in
(error "unknown request -- create-stack" m)))))))))
dispatch)))))
(let ((stack (create-stack =)))
(if ((stack 'empty?))
(if (begin ((stack 'push) 13) (not ((stack 'empty?))))
(if ((stack 'is-in) 13)
(if (= ((stack 'top)) 13)
(begin
((stack 'push) 14)
(= ((stack 'pop)) 14))
#f)
#f)
#f)
#f)))))))))))))))
|
493df54374a30f4dba1ebb87d4eee8b3ce50ef46f60834a0efdc11f39ac5b353
|
informatimago/lisp
|
missing.lisp
|
-*- mode : lisp;coding : utf-8 -*-
;;;;**************************************************************************
FILE : missing.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
USER - INTERFACE :
;;;;DESCRIPTION
;;;;
Implements CL standard operators missing from MoCL .
;;;;
;;;; !!!! NOTICE THE LICENSE OF THIS FILE !!!!
;;;;
< PJB > < >
MODIFICATIONS
2015 - 03 - 01 < PJB > Created .
;;;;LEGAL
AGPL3
;;;;
Copyright 2015 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details .
;;;;
You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see </>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.MOCL.KLUDGES.MISSING"
(:use "COMMON-LISP")
(:shadow "*TRACE-OUTPUT*"
"*LOAD-VERBOSE*"
"*LOAD-PRINT*"
"ARRAY-DISPLACEMENT"
"CHANGE-CLASS"
"COMPILE"
"COMPLEX"
"ENSURE-DIRECTORIES-EXIST"
"FILE-WRITE-DATE"
"INVOKE-DEBUGGER" "*DEBUGGER-HOOK*"
"LOAD"
"LOGICAL-PATHNAME-TRANSLATIONS"
"MACHINE-INSTANCE"
"MACHINE-VERSION"
"NSET-DIFFERENCE"
"RENAME-FILE"
"SUBSTITUTE-IF"
"TRANSLATE-LOGICAL-PATHNAME"
"PRINT-NOT-READABLE"
"PRINT-NOT-READABLE-OBJECT")
(:export "*TRACE-OUTPUT*"
"*LOAD-VERBOSE*"
"*LOAD-PRINT*"
"ARRAY-DISPLACEMENT"
"CHANGE-CLASS"
"COMPILE"
"COMPLEX"
"ENSURE-DIRECTORIES-EXIST"
"FILE-WRITE-DATE"
"INVOKE-DEBUGGER" "*DEBUGGER-HOOK*"
"LOAD"
"LOGICAL-PATHNAME-TRANSLATIONS"
"MACHINE-INSTANCE"
"MACHINE-VERSION"
"NSET-DIFFERENCE"
"RENAME-FILE"
"SUBSTITUTE-IF"
"TRANSLATE-LOGICAL-PATHNAME"
"PRINT-NOT-READABLE"
"PRINT-NOT-READABLE-OBJECT")
(:documentation "
Implements CL standard operators missing from MoCL.
LEGAL
AGPL3
Copyright Pascal J. Bourguignon 2015 - 2015
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see </>.
"))
(in-package "COM.INFORMATIMAGO.MOCL.KLUDGES.MISSING")
CHANGE - CLASS ; ; CLOS !
COMPLEX ; ; all complex is missing .
(defvar *load-verbose* nil)
(defvar *load-print* nil)
(defvar *trace-output* *standard-output*)
(define-condition print-not-readable (error)
((object :initarg :object :reader print-not-readable-object))
(:report (lambda (condition stream)
(let ((*print-readably* nil))
(format stream "Object to printable readably ~S"
(print-not-readable-object condition))))))
(defun array-displacement (array)
;; if not provided, then displaced array don't exist!
(declare (ignore array))
(values nil 0))
COMPILE ; ; required to implement minimal compilation .
(defun load (filespec &key verbose print if-does-not-exist external-format)
)
(defun ensure-directories-exist (pathspec &key verbose)
(error "~S not implemented yet" 'ensure-directories-exist)
(let ((created nil))
(values pathspec created)))
(defun rename-file (filespec new-name)
(error "~S not implemented yet" 'rename-file)
(let (defaulted-new-name old-truename new-truename)
(values defaulted-new-name old-truename new-truename)))
(defun file-write-date (pathspec)
(declare (ignore pathspec))
nil)
(defvar *debugger-hook* nil)
(defun invoke-debugger (condition)
(when *debugger-hook*
(let ((saved-hook *debugger-hook*)
(*debugger-hook* nil))
(funcall saved-hook condition)))
(rt:formatd "Debugger invoked on condition ~A; aborting." condition)
(rt:quit))
(defvar *hosts* '())
(defun logical-pathname-translations (host)
(cdr (assoc host *hosts* :test (function equalp))))
(defun (setf logical-pathname-translations) (new-translations host)
(let ((entry (assoc host *hosts* :test (function equalp))))
(if entry
(setf (cdr entry) (copy-tree new-translations))
(push (cons (nstring-upcase (copy-seq host))
(copy-tree new-translations))
*hosts*))))
(defun translate-logical-pathname (pathname &key &allow-other-keys)
(error "~S not implemented yet" 'translate-logical-pathname)
pathname)
(defun machine-instance ()
;; TODO: find the hostname of the machine, or some other machine identification.
#+android "Android"
#+ios "iOS")
(defun machine-version ()
;; TODO: find the hardware version, or some other machine version.
#+android "0.0"
#+ios "0.0")
Clozure Common Lisp -- > ( " larissa.local " " MacBookAir6,2 " )
CLISP -- > ( " larissa.local [ 192.168.7.8 ] " " X86_64 " )
ECL -- > ( " larissa.local " NIL )
SBCL -- > ( " larissa.local " " Intel(R ) Core(TM ) i7 - 4650U CPU @ 1.70GHz " )
(defun nset-difference (list-1 list-2 &rest rest &key key test test-not)
(declare (ignore key test test-not))
(apply (function set-difference) list-1 list-2 rest))
(defun nsubstitute-if (new-item predicate sequence &key from-end start end count key)
(let* ((length (length sequence))
(start (or start 0))
(end (or end lengh))
(key (or key (function identity))))
(assert (<= 0 start end length))
(etypecase sequence
(list (cond
(from-end
(nreverse (nsubstitute-if new-item predicate (nreverse sequence)
:start (- length end) :end (- length start)
:count count :key key)))
(count
(when (plusp count)
(loop
:repeat (- end start)
:for current :on (nthcdr start sequence)
:do (when (funcall predicate (funcall key (car current)))
(setf (car current) new-item)
(decf count)
(when (zerop count)
(return))))))
(t
(loop
:repeat (- end start)
:for current :on (nthcdr start sequence)
:do (when (funcall predicate (funcall key (car current)))
(setf (car current) new-item))))))
(vector (if from-end
(if count
(when (plusp count)
(loop
:for i :from (1- end) :downto start
:do (when (funcall predicate (funcall key (aref sequence i)))
(setf (aref sequence i) new-item)
(decf count)
(when (zerop count)
(return)))))
(loop
:for i :from (1- end) :downto start
:do (when (funcall predicate (funcall key (aref sequence i)))
(setf (aref sequence i) new-item))))
(if count
(when (plusp count)
(loop
:for i :from start :below end
:do (when (funcall predicate (funcall key (aref sequence i)))
(setf (aref sequence i) new-item)
(decf count)
(when (zerop count)
(return)))))
(loop
:for i :from start :below end
:do (when (funcall predicate (funcall key (aref sequence i)))
(setf (aref sequence i) new-item)))))))
sequence))
(defun substitute-if (new-item predicate sequence &rest rest &key from-end start end count key)
(apply (function nsubstitute-if) new-item predicate (copy-seq sequence) rest))
(defun nsubstitute-if-not (new-item predicate sequence &rest rest &key from-end start end count key)
(apply (function nsubstitute-if) new-item (complement predicate) sequence rest))
(defun substitute-if-not (new-item predicate sequence &rest rest &key from-end start end count key)
(apply (function nsubstitute-if) new-item (complement predicate) (copy-seq sequence) rest))
;; Warning: Function ASDF:FIND-SYSTEM is referenced but not defined.
Warning : Function ASDF : is referenced but not defined .
Warning : Function ASDF : RUN - SHELL - COMMAND is referenced but not defined .
;;;; THE END ;;;;
| null |
https://raw.githubusercontent.com/informatimago/lisp/571af24c06ba466e01b4c9483f8bb7690bc46d03/mocl/kludges/missing.lisp
|
lisp
|
coding : utf-8 -*-
**************************************************************************
LANGUAGE: Common-Lisp
SYSTEM: Common-Lisp
DESCRIPTION
!!!! NOTICE THE LICENSE OF THIS FILE !!!!
LEGAL
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see </>.
**************************************************************************
without even the implied warranty of
; CLOS !
; all complex is missing .
if not provided, then displaced array don't exist!
; required to implement minimal compilation .
TODO: find the hostname of the machine, or some other machine identification.
TODO: find the hardware version, or some other machine version.
Warning: Function ASDF:FIND-SYSTEM is referenced but not defined.
THE END ;;;;
|
FILE : missing.lisp
USER - INTERFACE :
Implements CL standard operators missing from MoCL .
< PJB > < >
MODIFICATIONS
2015 - 03 - 01 < PJB > Created .
AGPL3
Copyright 2015 - 2016
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation , either version 3 of the License , or
GNU Affero General Public License for more details .
You should have received a copy of the GNU Affero General Public License
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.MOCL.KLUDGES.MISSING"
(:use "COMMON-LISP")
(:shadow "*TRACE-OUTPUT*"
"*LOAD-VERBOSE*"
"*LOAD-PRINT*"
"ARRAY-DISPLACEMENT"
"CHANGE-CLASS"
"COMPILE"
"COMPLEX"
"ENSURE-DIRECTORIES-EXIST"
"FILE-WRITE-DATE"
"INVOKE-DEBUGGER" "*DEBUGGER-HOOK*"
"LOAD"
"LOGICAL-PATHNAME-TRANSLATIONS"
"MACHINE-INSTANCE"
"MACHINE-VERSION"
"NSET-DIFFERENCE"
"RENAME-FILE"
"SUBSTITUTE-IF"
"TRANSLATE-LOGICAL-PATHNAME"
"PRINT-NOT-READABLE"
"PRINT-NOT-READABLE-OBJECT")
(:export "*TRACE-OUTPUT*"
"*LOAD-VERBOSE*"
"*LOAD-PRINT*"
"ARRAY-DISPLACEMENT"
"CHANGE-CLASS"
"COMPILE"
"COMPLEX"
"ENSURE-DIRECTORIES-EXIST"
"FILE-WRITE-DATE"
"INVOKE-DEBUGGER" "*DEBUGGER-HOOK*"
"LOAD"
"LOGICAL-PATHNAME-TRANSLATIONS"
"MACHINE-INSTANCE"
"MACHINE-VERSION"
"NSET-DIFFERENCE"
"RENAME-FILE"
"SUBSTITUTE-IF"
"TRANSLATE-LOGICAL-PATHNAME"
"PRINT-NOT-READABLE"
"PRINT-NOT-READABLE-OBJECT")
(:documentation "
Implements CL standard operators missing from MoCL.
LEGAL
AGPL3
Copyright Pascal J. Bourguignon 2015 - 2015
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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,
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see </>.
"))
(in-package "COM.INFORMATIMAGO.MOCL.KLUDGES.MISSING")
(defvar *load-verbose* nil)
(defvar *load-print* nil)
(defvar *trace-output* *standard-output*)
(define-condition print-not-readable (error)
((object :initarg :object :reader print-not-readable-object))
(:report (lambda (condition stream)
(let ((*print-readably* nil))
(format stream "Object to printable readably ~S"
(print-not-readable-object condition))))))
(defun array-displacement (array)
(declare (ignore array))
(values nil 0))
(defun load (filespec &key verbose print if-does-not-exist external-format)
)
(defun ensure-directories-exist (pathspec &key verbose)
(error "~S not implemented yet" 'ensure-directories-exist)
(let ((created nil))
(values pathspec created)))
(defun rename-file (filespec new-name)
(error "~S not implemented yet" 'rename-file)
(let (defaulted-new-name old-truename new-truename)
(values defaulted-new-name old-truename new-truename)))
(defun file-write-date (pathspec)
(declare (ignore pathspec))
nil)
(defvar *debugger-hook* nil)
(defun invoke-debugger (condition)
(when *debugger-hook*
(let ((saved-hook *debugger-hook*)
(*debugger-hook* nil))
(funcall saved-hook condition)))
(rt:formatd "Debugger invoked on condition ~A; aborting." condition)
(rt:quit))
(defvar *hosts* '())
(defun logical-pathname-translations (host)
(cdr (assoc host *hosts* :test (function equalp))))
(defun (setf logical-pathname-translations) (new-translations host)
(let ((entry (assoc host *hosts* :test (function equalp))))
(if entry
(setf (cdr entry) (copy-tree new-translations))
(push (cons (nstring-upcase (copy-seq host))
(copy-tree new-translations))
*hosts*))))
(defun translate-logical-pathname (pathname &key &allow-other-keys)
(error "~S not implemented yet" 'translate-logical-pathname)
pathname)
(defun machine-instance ()
#+android "Android"
#+ios "iOS")
(defun machine-version ()
#+android "0.0"
#+ios "0.0")
Clozure Common Lisp -- > ( " larissa.local " " MacBookAir6,2 " )
CLISP -- > ( " larissa.local [ 192.168.7.8 ] " " X86_64 " )
ECL -- > ( " larissa.local " NIL )
SBCL -- > ( " larissa.local " " Intel(R ) Core(TM ) i7 - 4650U CPU @ 1.70GHz " )
(defun nset-difference (list-1 list-2 &rest rest &key key test test-not)
(declare (ignore key test test-not))
(apply (function set-difference) list-1 list-2 rest))
(defun nsubstitute-if (new-item predicate sequence &key from-end start end count key)
(let* ((length (length sequence))
(start (or start 0))
(end (or end lengh))
(key (or key (function identity))))
(assert (<= 0 start end length))
(etypecase sequence
(list (cond
(from-end
(nreverse (nsubstitute-if new-item predicate (nreverse sequence)
:start (- length end) :end (- length start)
:count count :key key)))
(count
(when (plusp count)
(loop
:repeat (- end start)
:for current :on (nthcdr start sequence)
:do (when (funcall predicate (funcall key (car current)))
(setf (car current) new-item)
(decf count)
(when (zerop count)
(return))))))
(t
(loop
:repeat (- end start)
:for current :on (nthcdr start sequence)
:do (when (funcall predicate (funcall key (car current)))
(setf (car current) new-item))))))
(vector (if from-end
(if count
(when (plusp count)
(loop
:for i :from (1- end) :downto start
:do (when (funcall predicate (funcall key (aref sequence i)))
(setf (aref sequence i) new-item)
(decf count)
(when (zerop count)
(return)))))
(loop
:for i :from (1- end) :downto start
:do (when (funcall predicate (funcall key (aref sequence i)))
(setf (aref sequence i) new-item))))
(if count
(when (plusp count)
(loop
:for i :from start :below end
:do (when (funcall predicate (funcall key (aref sequence i)))
(setf (aref sequence i) new-item)
(decf count)
(when (zerop count)
(return)))))
(loop
:for i :from start :below end
:do (when (funcall predicate (funcall key (aref sequence i)))
(setf (aref sequence i) new-item)))))))
sequence))
(defun substitute-if (new-item predicate sequence &rest rest &key from-end start end count key)
(apply (function nsubstitute-if) new-item predicate (copy-seq sequence) rest))
(defun nsubstitute-if-not (new-item predicate sequence &rest rest &key from-end start end count key)
(apply (function nsubstitute-if) new-item (complement predicate) sequence rest))
(defun substitute-if-not (new-item predicate sequence &rest rest &key from-end start end count key)
(apply (function nsubstitute-if) new-item (complement predicate) (copy-seq sequence) rest))
Warning : Function ASDF : is referenced but not defined .
Warning : Function ASDF : RUN - SHELL - COMMAND is referenced but not defined .
|
5ce4cb4e1bbd7012aab0f63e1931a8007bfb340279f2d5879e5922a6dd83d0a0
|
larcenists/larceny
|
srfi-25-test.sps
|
;;; array test
2001
;;;
$ Id$
(import (rnrs base)
(rnrs io simple)
(srfi :25 multi-dimensional-arrays))
(define (writeln . xs)
(for-each display xs)
(newline))
(define (fail token . more)
(writeln "Error: test failed: " token)
#f)
(define past
(let ((stones '()))
(lambda stone
(if (null? stone)
(reverse stones)
(set! stones (cons (apply (lambda (stone) stone) stone) stones))))))
(define (tail n)
(if (< n (length (past)))
(list-tail (past) (- (length (past)) n))
(past)))
;;; Simple tests
(or (and (shape)
(shape -1 -1)
(shape -1 0)
(shape -1 1)
(shape 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8))
(fail "(shape ...) failed"))
(past "shape")
(or (and (make-array (shape))
(make-array (shape) *)
(make-array (shape -1 -1))
(make-array (shape -1 -1) *)
(make-array (shape -1 1))
(make-array (shape 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4) *))
(fail "(make-array (shape ...) [o]) failed"))
(past "make-array")
(or (and (array (shape) *)
(array (shape -1 -1))
(array (shape -1 1) * *)
(array (shape 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8) *))
(fail "(array (shape ...) ...) failed"))
(past "array")
(or (and (= (array-rank (shape)) 2)
(= (array-rank (shape -1 -1)) 2)
(= (array-rank (shape -1 1)) 2)
(= (array-rank (shape 1 2 3 4 5 6 7 8)) 2))
(fail "(array-rank (shape ...)) failed"))
(past "array-rank of shape")
(or (and (= (array-rank (make-array (shape))) 0)
(= (array-rank (make-array (shape -1 -1))) 1)
(= (array-rank (make-array (shape -1 1))) 1)
(= (array-rank (make-array (shape 1 2 3 4 5 6 7 8))) 4))
(fail "(array-rank (make-array ...)) failed"))
(past "array-rank of make-array")
(or (and (= (array-rank (array (shape) *)) 0)
(= (array-rank (array (shape -1 -1))) 1)
(= (array-rank (array (shape -1 1) * *)) 1)
(= (array-rank (array (shape 1 2 3 4 5 6 7 8) *)) 4))
(fail "(array-rank (array ...)) failed"))
(past "array-rank of array")
(or (and (= (array-start (shape -1 -1) 0) 0)
(= (array-start (shape -1 -1) 1) 0)
(= (array-start (shape -1 1) 0) 0)
(= (array-start (shape -1 1) 1) 0)
(= (array-start (shape 1 2 3 4 5 6 7 8) 0) 0)
(= (array-start (shape 1 2 3 4 5 6 7 8) 1) 0))
(fail "(array-start (shape ...)) failed"))
(past "array-start of shape")
(or (and (= (array-end (shape -1 -1) 0) 1)
(= (array-end (shape -1 -1) 1) 2)
(= (array-end (shape -1 1) 0) 1)
(= (array-end (shape -1 1) 1) 2)
(= (array-end (shape 1 2 3 4 5 6 7 8) 0) 4)
(= (array-end (shape 1 2 3 4 5 6 7 8) 1) 2))
(fail "(array-end (shape ...)) failed"))
(past "array-end of shape")
(or (and (= (array-start (make-array (shape -1 -1)) 0) -1)
(= (array-start (make-array (shape -1 1)) 0) -1)
(= (array-start (make-array (shape 1 2 3 4 5 6 7 8)) 0) 1)
(= (array-start (make-array (shape 1 2 3 4 5 6 7 8)) 1) 3)
(= (array-start (make-array (shape 1 2 3 4 5 6 7 8)) 2) 5)
(= (array-start (make-array (shape 1 2 3 4 5 6 7 8)) 3) 7))
(fail "(array-start (make-array ...)) failed"))
(past "array-start of make-array")
(or (and (= (array-end (make-array (shape -1 -1)) 0) -1)
(= (array-end (make-array (shape -1 1)) 0) 1)
(= (array-end (make-array (shape 1 2 3 4 5 6 7 8)) 0) 2)
(= (array-end (make-array (shape 1 2 3 4 5 6 7 8)) 1) 4)
(= (array-end (make-array (shape 1 2 3 4 5 6 7 8)) 2) 6)
(= (array-end (make-array (shape 1 2 3 4 5 6 7 8)) 3) 8))
(fail "(array-end (make-array ...)) failed"))
(past "array-end of make-array")
(or (and (= (array-start (array (shape -1 -1)) 0) -1)
(= (array-start (array (shape -1 1) * *) 0) -1)
(= (array-start (array (shape 1 2 3 4 5 6 7 8) *) 0) 1)
(= (array-start (array (shape 1 2 3 4 5 6 7 8) *) 1) 3)
(= (array-start (array (shape 1 2 3 4 5 6 7 8) *) 2) 5)
(= (array-start (array (shape 1 2 3 4 5 6 7 8) *) 3) 7))
(fail "(array-start (array ...)) failed"))
(past "array-start of array")
(or (and (= (array-end (array (shape -1 -1)) 0) -1)
(= (array-end (array (shape -1 1) * *) 0) 1)
(= (array-end (array (shape 1 2 3 4 5 6 7 8) *) 0) 2)
(= (array-end (array (shape 1 2 3 4 5 6 7 8) *) 1) 4)
(= (array-end (array (shape 1 2 3 4 5 6 7 8) *) 2) 6)
(= (array-end (array (shape 1 2 3 4 5 6 7 8) *) 3) 8))
(fail "(array-end (array ...)) failed"))
(past "array-end of array")
(or (and (eq? (array-ref (make-array (shape) 'a)) 'a)
(eq? (array-ref (make-array (shape -1 1) 'b) -1) 'b)
(eq? (array-ref (make-array (shape -1 1) 'c) 0) 'c)
(eq? (array-ref (make-array (shape 1 2 3 4 5 6 7 8) 'd) 1 3 5 7) 'd))
(fail "array-ref of make-array with arguments failed"))
(past "array-ref of make-array with arguments")
(or (and (eq? (array-ref (make-array (shape) 'a) '#()) 'a)
(eq? (array-ref (make-array (shape -1 1) 'b) '#(-1)) 'b)
(eq? (array-ref (make-array (shape -1 1) 'c) '#(0)) 'c)
(eq? (array-ref (make-array (shape 1 2 3 4 5 6 7 8) 'd)
'#(1 3 5 7))
'd))
(fail "array-ref of make-array with vector failed"))
(past "array-ref of make-array with vector")
(or (and (eq? (array-ref (make-array (shape) 'a)
(array (shape 0 0)))
'a)
(eq? (array-ref (make-array (shape -1 1) 'b)
(array (shape 0 1) -1))
'b)
(eq? (array-ref (make-array (shape -1 1) 'c)
(array (shape 0 1) 0))
'c)
(eq? (array-ref (make-array (shape 1 2 3 4 5 6 7 8) 'd)
(array (shape 0 4) 1 3 5 7))
'd))
(fail "(array-ref of make-array with array failed"))
(past "array-ref of make-array with array")
(or (and (let ((arr (make-array (shape) 'o)))
(array-set! arr 'a)
(eq? (array-ref arr) 'a))
(let ((arr (make-array (shape -1 1) 'o)))
(array-set! arr -1 'b)
(array-set! arr 0 'c)
(and (eq? (array-ref arr -1) 'b)
(eq? (array-ref arr 0) 'c)))
(let ((arr (make-array (shape 1 2 3 4 5 6 7 8) 'o)))
(array-set! arr 1 3 5 7 'd)
(eq? (array-ref arr 1 3 5 7) 'd)))
(fail "array-set! with arguments failed"))
(past "array-set! of make-array with arguments")
(or (and (let ((arr (make-array (shape) 'o)))
(array-set! arr '#() 'a)
(eq? (array-ref arr) 'a))
(let ((arr (make-array (shape -1 1) 'o)))
(array-set! arr '#(-1) 'b)
(array-set! arr '#(0) 'c)
(and (eq? (array-ref arr -1) 'b)
(eq? (array-ref arr 0) 'c)))
(let ((arr (make-array (shape 1 2 3 4 5 6 7 8) 'o)))
(array-set! arr '#(1 3 5 7) 'd)
(eq? (array-ref arr 1 3 5 7) 'd)))
(fail "array-set! with vector failed"))
(past "array-set! of make-array with vector")
(or (and (let ((arr (make-array (shape) 'o)))
(array-set! arr 'a)
(eq? (array-ref arr) 'a))
(let ((arr (make-array (shape -1 1) 'o)))
(array-set! arr (array (shape 0 1) -1) 'b)
(array-set! arr (array (shape 0 1) 0) 'c)
(and (eq? (array-ref arr -1) 'b)
(eq? (array-ref arr 0) 'c)))
(let ((arr (make-array (shape 1 2 3 4 5 6 7 8) 'o)))
(array-set! arr (array (shape 0 4) 1 3 5 7) 'd)
(eq? (array-ref arr 1 3 5 7) 'd)))
(fail "array-set! with arguments failed"))
(past "array-set! of make-array with array")
;;; Share and change:
;;;
org brk swp box
;;;
0 1 1 2 5 6
6 a b 2 a b 3 d c 0 2 4 6 8 : e
7 c d 3 e f 4 f e
8 e f
(or (let* ((org (array (shape 6 9 0 2) 'a 'b 'c 'd 'e 'f))
(brk (share-array
org
(shape 2 4 1 3)
(lambda (r k)
(values
(+ 6 (* 2 (- r 2)))
(- k 1)))))
(swp (share-array
org
(shape 3 5 5 7)
(lambda (r k)
(values
(+ 7 (- r 3))
(- 1 (- k 5))))))
(box (share-array
swp
(shape 0 1 2 3 4 5 6 7 8 9)
(lambda _ (values 4 6))))
(org-contents (lambda ()
(list (array-ref org 6 0) (array-ref org 6 1)
(array-ref org 7 0) (array-ref org 7 1)
(array-ref org 8 0) (array-ref org 8 1))))
(brk-contents (lambda ()
(list (array-ref brk 2 1) (array-ref brk 2 2)
(array-ref brk 3 1) (array-ref brk 3 2))))
(swp-contents (lambda ()
(list (array-ref swp 3 5) (array-ref swp 3 6)
(array-ref swp 4 5) (array-ref swp 4 6))))
(box-contents (lambda ()
(list (array-ref box 0 2 4 6 8)))))
(and (equal? (org-contents) '(a b c d e f))
(equal? (brk-contents) '(a b e f))
(equal? (swp-contents) '(d c f e))
(equal? (box-contents) '(e))
(begin (array-set! org 6 0 'x) #t)
(equal? (org-contents) '(x b c d e f))
(equal? (brk-contents) '(x b e f))
(equal? (swp-contents) '(d c f e))
(equal? (box-contents) '(e))
(begin (array-set! brk 3 1 'y) #t)
(equal? (org-contents) '(x b c d y f))
(equal? (brk-contents) '(x b y f))
(equal? (swp-contents) '(d c f y))
(equal? (box-contents) '(y))
(begin (array-set! swp 4 5 'z) #t)
(equal? (org-contents) '(x b c d y z))
(equal? (brk-contents) '(x b y z))
(equal? (swp-contents) '(d c z y))
(equal? (box-contents) '(y))
(begin (array-set! box 0 2 4 6 8 'e) #t)
(equal? (org-contents) '(x b c d e z))
(equal? (brk-contents) '(x b e z))
(equal? (swp-contents) '(d c z e))
(equal? (box-contents) '(e))))
(fail "shared change failed"))
(past "shared change")
;;; Check that arrays copy the shape specification
(or (let ((shp (shape 10 12)))
(let ((arr (make-array shp))
(ars (array shp * *))
(art (share-array (make-array shp) shp (lambda (k) k))))
(array-set! shp 0 0 '?)
(array-set! shp 0 1 '!)
(and (= (array-rank shp) 2)
(= (array-start shp 0) 0)
(= (array-end shp 0) 1)
(= (array-start shp 1) 0)
(= (array-end shp 1) 2)
(eq? (array-ref shp 0 0) '?)
(eq? (array-ref shp 0 1) '!)
(= (array-rank arr) 1)
(= (array-start arr 0) 10)
(= (array-end arr 0) 12)
(= (array-rank ars) 1)
(= (array-start ars 0) 10)
(= (array-end ars 0) 12)
(= (array-rank art) 1)
(= (array-start art 0) 10)
(= (array-end art 0) 12))))
(fail "array-set! of shape failed"))
(past "array-set! of shape")
;;; Check that index arrays work even when they share
;;;
arr
5 6 0 1
4 nw ne 0 4 6
5 sw se 1 5 4
(or (let ((arr (array (shape 4 6 5 7) 'nw 'ne 'sw 'se))
(ixn (array (shape 0 2 0 2) 4 6 5 4)))
(let ((col0 (share-array
ixn
(shape 0 2)
(lambda (k)
(values k 0))))
(row0 (share-array
ixn
(shape 0 2)
(lambda (k)
(values 0 k))))
(wor1 (share-array
ixn
(shape 0 2)
(lambda (k)
(values 1 (- 1 k)))))
(cod (share-array
ixn
(shape 0 2)
(lambda (k)
(case k
((0) (values 1 0))
((1) (values 0 1))))))
(box (share-array
ixn
(shape 0 2)
(lambda (k)
(values 1 0)))))
(and (eq? (array-ref arr col0) 'nw)
(eq? (array-ref arr row0) 'ne)
(eq? (array-ref arr wor1) 'nw)
(eq? (array-ref arr cod) 'se)
(eq? (array-ref arr box) 'sw)
(begin
(array-set! arr col0 'ul)
(array-set! arr row0 'ur)
(array-set! arr cod 'lr)
(array-set! arr box 'll)
#t)
(eq? (array-ref arr 4 5) 'ul)
(eq? (array-ref arr 4 6) 'ur)
(eq? (array-ref arr 5 5) 'll)
(eq? (array-ref arr 5 6) 'lr)
(begin
(array-set! arr wor1 'xx)
(eq? (array-ref arr 4 5) 'xx)))))
(fail "array access with sharing index array failed"))
(past "array access with sharing index array")
;;; Check that shape arrays work even when they share
;;;
arr shp shq shr shs
1 2 3 4 0 1 0 1 0 1 0 1
1 10 12 16 20 0 10 12 0 12 20 0 10 10 0 12 12
;;; 2 10 11 12 13 1 10 11 1 11 13 1 11 12 1 12 12
;;; 2 12 16
;;; 3 13 20
(or (let ((arr (array (shape 1 3 1 5) 10 12 16 20 10 11 12 13)))
(let ((shp (share-array
arr
(shape 0 2 0 2)
(lambda (r k)
(values (+ r 1) (+ k 1)))))
(shq (share-array
arr
(shape 0 2 0 2)
(lambda (r k)
(values (+ r 1) (* 2 (+ 1 k))))))
(shr (share-array
arr
(shape 0 4 0 2)
(lambda (r k)
(values (- 2 k) (+ r 1)))))
(shs (share-array
arr
(shape 0 2 0 2)
(lambda (r k)
(values 2 3)))))
(and (let ((arr-p (make-array shp)))
(and (= (array-rank arr-p) 2)
(= (array-start arr-p 0) 10)
(= (array-end arr-p 0) 12)
(= (array-start arr-p 1) 10)
(= (array-end arr-p 1) 11)))
(let ((arr-q (array shq * * * * * * * * * * * * * * * *)))
(and (= (array-rank arr-q) 2)
(= (array-start arr-q 0) 12)
(= (array-end arr-q 0) 20)
(= (array-start arr-q 1) 11)
(= (array-end arr-q 1) 13)))
(let ((arr-r (share-array
(array (shape) *)
shr
(lambda _ (values)))))
(and (= (array-rank arr-r) 4)
(= (array-start arr-r 0) 10)
(= (array-end arr-r 0) 10)
(= (array-start arr-r 1) 11)
(= (array-end arr-r 1) 12)
(= (array-start arr-r 2) 12)
(= (array-end arr-r 2) 16)
(= (array-start arr-r 3) 13)
(= (array-end arr-r 3) 20)))
(let ((arr-s (make-array shs)))
(and (= (array-rank arr-s) 2)
(= (array-start arr-s 0) 12)
(= (array-end arr-s 0) 12)
(= (array-start arr-s 1) 12)
(= (array-end arr-s 1) 12))))))
(fail "sharing shape array failed"))
(past "sharing shape array")
(let ((super (array (shape 4 7 4 7)
1 * *
* 2 *
* * 3))
(subshape (share-array
(array (shape 0 2 0 3)
* 4 *
* 7 *)
(shape 0 1 0 2)
(lambda (r k)
(values k 1)))))
(let ((sub (share-array super subshape (lambda (k) (values k k)))))
( array - equal ? ( shape 4 7 ) )
(or (and (= (array-rank subshape) 2)
(= (array-start subshape 0) 0)
(= (array-end subshape 0) 1)
(= (array-start subshape 1) 0)
(= (array-end subshape 1) 2)
(= (array-ref subshape 0 0) 4)
(= (array-ref subshape 0 1) 7))
(fail "sharing subshape failed"))
( array - equal ? sub ( array ( shape 4 7 ) 1 2 3 ) )
(or (and (= (array-rank sub) 1)
(= (array-start sub 0) 4)
(= (array-end sub 0) 7)
(= (array-ref sub 4) 1)
(= (array-ref sub 5) 2)
(= (array-ref sub 6) 3))
(fail "sharing with sharing subshape failed"))))
(past "sharing with sharing subshape")
(writeln "Done.")
| null |
https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/lib/SRFI/test/srfi-25-test.sps
|
scheme
|
array test
Simple tests
Share and change:
Check that arrays copy the shape specification
Check that index arrays work even when they share
Check that shape arrays work even when they share
2 10 11 12 13 1 10 11 1 11 13 1 11 12 1 12 12
2 12 16
3 13 20
|
2001
$ Id$
(import (rnrs base)
(rnrs io simple)
(srfi :25 multi-dimensional-arrays))
(define (writeln . xs)
(for-each display xs)
(newline))
(define (fail token . more)
(writeln "Error: test failed: " token)
#f)
(define past
(let ((stones '()))
(lambda stone
(if (null? stone)
(reverse stones)
(set! stones (cons (apply (lambda (stone) stone) stone) stones))))))
(define (tail n)
(if (< n (length (past)))
(list-tail (past) (- (length (past)) n))
(past)))
(or (and (shape)
(shape -1 -1)
(shape -1 0)
(shape -1 1)
(shape 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8))
(fail "(shape ...) failed"))
(past "shape")
(or (and (make-array (shape))
(make-array (shape) *)
(make-array (shape -1 -1))
(make-array (shape -1 -1) *)
(make-array (shape -1 1))
(make-array (shape 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4) *))
(fail "(make-array (shape ...) [o]) failed"))
(past "make-array")
(or (and (array (shape) *)
(array (shape -1 -1))
(array (shape -1 1) * *)
(array (shape 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8) *))
(fail "(array (shape ...) ...) failed"))
(past "array")
(or (and (= (array-rank (shape)) 2)
(= (array-rank (shape -1 -1)) 2)
(= (array-rank (shape -1 1)) 2)
(= (array-rank (shape 1 2 3 4 5 6 7 8)) 2))
(fail "(array-rank (shape ...)) failed"))
(past "array-rank of shape")
(or (and (= (array-rank (make-array (shape))) 0)
(= (array-rank (make-array (shape -1 -1))) 1)
(= (array-rank (make-array (shape -1 1))) 1)
(= (array-rank (make-array (shape 1 2 3 4 5 6 7 8))) 4))
(fail "(array-rank (make-array ...)) failed"))
(past "array-rank of make-array")
(or (and (= (array-rank (array (shape) *)) 0)
(= (array-rank (array (shape -1 -1))) 1)
(= (array-rank (array (shape -1 1) * *)) 1)
(= (array-rank (array (shape 1 2 3 4 5 6 7 8) *)) 4))
(fail "(array-rank (array ...)) failed"))
(past "array-rank of array")
(or (and (= (array-start (shape -1 -1) 0) 0)
(= (array-start (shape -1 -1) 1) 0)
(= (array-start (shape -1 1) 0) 0)
(= (array-start (shape -1 1) 1) 0)
(= (array-start (shape 1 2 3 4 5 6 7 8) 0) 0)
(= (array-start (shape 1 2 3 4 5 6 7 8) 1) 0))
(fail "(array-start (shape ...)) failed"))
(past "array-start of shape")
(or (and (= (array-end (shape -1 -1) 0) 1)
(= (array-end (shape -1 -1) 1) 2)
(= (array-end (shape -1 1) 0) 1)
(= (array-end (shape -1 1) 1) 2)
(= (array-end (shape 1 2 3 4 5 6 7 8) 0) 4)
(= (array-end (shape 1 2 3 4 5 6 7 8) 1) 2))
(fail "(array-end (shape ...)) failed"))
(past "array-end of shape")
(or (and (= (array-start (make-array (shape -1 -1)) 0) -1)
(= (array-start (make-array (shape -1 1)) 0) -1)
(= (array-start (make-array (shape 1 2 3 4 5 6 7 8)) 0) 1)
(= (array-start (make-array (shape 1 2 3 4 5 6 7 8)) 1) 3)
(= (array-start (make-array (shape 1 2 3 4 5 6 7 8)) 2) 5)
(= (array-start (make-array (shape 1 2 3 4 5 6 7 8)) 3) 7))
(fail "(array-start (make-array ...)) failed"))
(past "array-start of make-array")
(or (and (= (array-end (make-array (shape -1 -1)) 0) -1)
(= (array-end (make-array (shape -1 1)) 0) 1)
(= (array-end (make-array (shape 1 2 3 4 5 6 7 8)) 0) 2)
(= (array-end (make-array (shape 1 2 3 4 5 6 7 8)) 1) 4)
(= (array-end (make-array (shape 1 2 3 4 5 6 7 8)) 2) 6)
(= (array-end (make-array (shape 1 2 3 4 5 6 7 8)) 3) 8))
(fail "(array-end (make-array ...)) failed"))
(past "array-end of make-array")
(or (and (= (array-start (array (shape -1 -1)) 0) -1)
(= (array-start (array (shape -1 1) * *) 0) -1)
(= (array-start (array (shape 1 2 3 4 5 6 7 8) *) 0) 1)
(= (array-start (array (shape 1 2 3 4 5 6 7 8) *) 1) 3)
(= (array-start (array (shape 1 2 3 4 5 6 7 8) *) 2) 5)
(= (array-start (array (shape 1 2 3 4 5 6 7 8) *) 3) 7))
(fail "(array-start (array ...)) failed"))
(past "array-start of array")
(or (and (= (array-end (array (shape -1 -1)) 0) -1)
(= (array-end (array (shape -1 1) * *) 0) 1)
(= (array-end (array (shape 1 2 3 4 5 6 7 8) *) 0) 2)
(= (array-end (array (shape 1 2 3 4 5 6 7 8) *) 1) 4)
(= (array-end (array (shape 1 2 3 4 5 6 7 8) *) 2) 6)
(= (array-end (array (shape 1 2 3 4 5 6 7 8) *) 3) 8))
(fail "(array-end (array ...)) failed"))
(past "array-end of array")
(or (and (eq? (array-ref (make-array (shape) 'a)) 'a)
(eq? (array-ref (make-array (shape -1 1) 'b) -1) 'b)
(eq? (array-ref (make-array (shape -1 1) 'c) 0) 'c)
(eq? (array-ref (make-array (shape 1 2 3 4 5 6 7 8) 'd) 1 3 5 7) 'd))
(fail "array-ref of make-array with arguments failed"))
(past "array-ref of make-array with arguments")
(or (and (eq? (array-ref (make-array (shape) 'a) '#()) 'a)
(eq? (array-ref (make-array (shape -1 1) 'b) '#(-1)) 'b)
(eq? (array-ref (make-array (shape -1 1) 'c) '#(0)) 'c)
(eq? (array-ref (make-array (shape 1 2 3 4 5 6 7 8) 'd)
'#(1 3 5 7))
'd))
(fail "array-ref of make-array with vector failed"))
(past "array-ref of make-array with vector")
(or (and (eq? (array-ref (make-array (shape) 'a)
(array (shape 0 0)))
'a)
(eq? (array-ref (make-array (shape -1 1) 'b)
(array (shape 0 1) -1))
'b)
(eq? (array-ref (make-array (shape -1 1) 'c)
(array (shape 0 1) 0))
'c)
(eq? (array-ref (make-array (shape 1 2 3 4 5 6 7 8) 'd)
(array (shape 0 4) 1 3 5 7))
'd))
(fail "(array-ref of make-array with array failed"))
(past "array-ref of make-array with array")
(or (and (let ((arr (make-array (shape) 'o)))
(array-set! arr 'a)
(eq? (array-ref arr) 'a))
(let ((arr (make-array (shape -1 1) 'o)))
(array-set! arr -1 'b)
(array-set! arr 0 'c)
(and (eq? (array-ref arr -1) 'b)
(eq? (array-ref arr 0) 'c)))
(let ((arr (make-array (shape 1 2 3 4 5 6 7 8) 'o)))
(array-set! arr 1 3 5 7 'd)
(eq? (array-ref arr 1 3 5 7) 'd)))
(fail "array-set! with arguments failed"))
(past "array-set! of make-array with arguments")
(or (and (let ((arr (make-array (shape) 'o)))
(array-set! arr '#() 'a)
(eq? (array-ref arr) 'a))
(let ((arr (make-array (shape -1 1) 'o)))
(array-set! arr '#(-1) 'b)
(array-set! arr '#(0) 'c)
(and (eq? (array-ref arr -1) 'b)
(eq? (array-ref arr 0) 'c)))
(let ((arr (make-array (shape 1 2 3 4 5 6 7 8) 'o)))
(array-set! arr '#(1 3 5 7) 'd)
(eq? (array-ref arr 1 3 5 7) 'd)))
(fail "array-set! with vector failed"))
(past "array-set! of make-array with vector")
(or (and (let ((arr (make-array (shape) 'o)))
(array-set! arr 'a)
(eq? (array-ref arr) 'a))
(let ((arr (make-array (shape -1 1) 'o)))
(array-set! arr (array (shape 0 1) -1) 'b)
(array-set! arr (array (shape 0 1) 0) 'c)
(and (eq? (array-ref arr -1) 'b)
(eq? (array-ref arr 0) 'c)))
(let ((arr (make-array (shape 1 2 3 4 5 6 7 8) 'o)))
(array-set! arr (array (shape 0 4) 1 3 5 7) 'd)
(eq? (array-ref arr 1 3 5 7) 'd)))
(fail "array-set! with arguments failed"))
(past "array-set! of make-array with array")
org brk swp box
0 1 1 2 5 6
6 a b 2 a b 3 d c 0 2 4 6 8 : e
7 c d 3 e f 4 f e
8 e f
(or (let* ((org (array (shape 6 9 0 2) 'a 'b 'c 'd 'e 'f))
(brk (share-array
org
(shape 2 4 1 3)
(lambda (r k)
(values
(+ 6 (* 2 (- r 2)))
(- k 1)))))
(swp (share-array
org
(shape 3 5 5 7)
(lambda (r k)
(values
(+ 7 (- r 3))
(- 1 (- k 5))))))
(box (share-array
swp
(shape 0 1 2 3 4 5 6 7 8 9)
(lambda _ (values 4 6))))
(org-contents (lambda ()
(list (array-ref org 6 0) (array-ref org 6 1)
(array-ref org 7 0) (array-ref org 7 1)
(array-ref org 8 0) (array-ref org 8 1))))
(brk-contents (lambda ()
(list (array-ref brk 2 1) (array-ref brk 2 2)
(array-ref brk 3 1) (array-ref brk 3 2))))
(swp-contents (lambda ()
(list (array-ref swp 3 5) (array-ref swp 3 6)
(array-ref swp 4 5) (array-ref swp 4 6))))
(box-contents (lambda ()
(list (array-ref box 0 2 4 6 8)))))
(and (equal? (org-contents) '(a b c d e f))
(equal? (brk-contents) '(a b e f))
(equal? (swp-contents) '(d c f e))
(equal? (box-contents) '(e))
(begin (array-set! org 6 0 'x) #t)
(equal? (org-contents) '(x b c d e f))
(equal? (brk-contents) '(x b e f))
(equal? (swp-contents) '(d c f e))
(equal? (box-contents) '(e))
(begin (array-set! brk 3 1 'y) #t)
(equal? (org-contents) '(x b c d y f))
(equal? (brk-contents) '(x b y f))
(equal? (swp-contents) '(d c f y))
(equal? (box-contents) '(y))
(begin (array-set! swp 4 5 'z) #t)
(equal? (org-contents) '(x b c d y z))
(equal? (brk-contents) '(x b y z))
(equal? (swp-contents) '(d c z y))
(equal? (box-contents) '(y))
(begin (array-set! box 0 2 4 6 8 'e) #t)
(equal? (org-contents) '(x b c d e z))
(equal? (brk-contents) '(x b e z))
(equal? (swp-contents) '(d c z e))
(equal? (box-contents) '(e))))
(fail "shared change failed"))
(past "shared change")
(or (let ((shp (shape 10 12)))
(let ((arr (make-array shp))
(ars (array shp * *))
(art (share-array (make-array shp) shp (lambda (k) k))))
(array-set! shp 0 0 '?)
(array-set! shp 0 1 '!)
(and (= (array-rank shp) 2)
(= (array-start shp 0) 0)
(= (array-end shp 0) 1)
(= (array-start shp 1) 0)
(= (array-end shp 1) 2)
(eq? (array-ref shp 0 0) '?)
(eq? (array-ref shp 0 1) '!)
(= (array-rank arr) 1)
(= (array-start arr 0) 10)
(= (array-end arr 0) 12)
(= (array-rank ars) 1)
(= (array-start ars 0) 10)
(= (array-end ars 0) 12)
(= (array-rank art) 1)
(= (array-start art 0) 10)
(= (array-end art 0) 12))))
(fail "array-set! of shape failed"))
(past "array-set! of shape")
arr
5 6 0 1
4 nw ne 0 4 6
5 sw se 1 5 4
(or (let ((arr (array (shape 4 6 5 7) 'nw 'ne 'sw 'se))
(ixn (array (shape 0 2 0 2) 4 6 5 4)))
(let ((col0 (share-array
ixn
(shape 0 2)
(lambda (k)
(values k 0))))
(row0 (share-array
ixn
(shape 0 2)
(lambda (k)
(values 0 k))))
(wor1 (share-array
ixn
(shape 0 2)
(lambda (k)
(values 1 (- 1 k)))))
(cod (share-array
ixn
(shape 0 2)
(lambda (k)
(case k
((0) (values 1 0))
((1) (values 0 1))))))
(box (share-array
ixn
(shape 0 2)
(lambda (k)
(values 1 0)))))
(and (eq? (array-ref arr col0) 'nw)
(eq? (array-ref arr row0) 'ne)
(eq? (array-ref arr wor1) 'nw)
(eq? (array-ref arr cod) 'se)
(eq? (array-ref arr box) 'sw)
(begin
(array-set! arr col0 'ul)
(array-set! arr row0 'ur)
(array-set! arr cod 'lr)
(array-set! arr box 'll)
#t)
(eq? (array-ref arr 4 5) 'ul)
(eq? (array-ref arr 4 6) 'ur)
(eq? (array-ref arr 5 5) 'll)
(eq? (array-ref arr 5 6) 'lr)
(begin
(array-set! arr wor1 'xx)
(eq? (array-ref arr 4 5) 'xx)))))
(fail "array access with sharing index array failed"))
(past "array access with sharing index array")
arr shp shq shr shs
1 2 3 4 0 1 0 1 0 1 0 1
1 10 12 16 20 0 10 12 0 12 20 0 10 10 0 12 12
(or (let ((arr (array (shape 1 3 1 5) 10 12 16 20 10 11 12 13)))
(let ((shp (share-array
arr
(shape 0 2 0 2)
(lambda (r k)
(values (+ r 1) (+ k 1)))))
(shq (share-array
arr
(shape 0 2 0 2)
(lambda (r k)
(values (+ r 1) (* 2 (+ 1 k))))))
(shr (share-array
arr
(shape 0 4 0 2)
(lambda (r k)
(values (- 2 k) (+ r 1)))))
(shs (share-array
arr
(shape 0 2 0 2)
(lambda (r k)
(values 2 3)))))
(and (let ((arr-p (make-array shp)))
(and (= (array-rank arr-p) 2)
(= (array-start arr-p 0) 10)
(= (array-end arr-p 0) 12)
(= (array-start arr-p 1) 10)
(= (array-end arr-p 1) 11)))
(let ((arr-q (array shq * * * * * * * * * * * * * * * *)))
(and (= (array-rank arr-q) 2)
(= (array-start arr-q 0) 12)
(= (array-end arr-q 0) 20)
(= (array-start arr-q 1) 11)
(= (array-end arr-q 1) 13)))
(let ((arr-r (share-array
(array (shape) *)
shr
(lambda _ (values)))))
(and (= (array-rank arr-r) 4)
(= (array-start arr-r 0) 10)
(= (array-end arr-r 0) 10)
(= (array-start arr-r 1) 11)
(= (array-end arr-r 1) 12)
(= (array-start arr-r 2) 12)
(= (array-end arr-r 2) 16)
(= (array-start arr-r 3) 13)
(= (array-end arr-r 3) 20)))
(let ((arr-s (make-array shs)))
(and (= (array-rank arr-s) 2)
(= (array-start arr-s 0) 12)
(= (array-end arr-s 0) 12)
(= (array-start arr-s 1) 12)
(= (array-end arr-s 1) 12))))))
(fail "sharing shape array failed"))
(past "sharing shape array")
(let ((super (array (shape 4 7 4 7)
1 * *
* 2 *
* * 3))
(subshape (share-array
(array (shape 0 2 0 3)
* 4 *
* 7 *)
(shape 0 1 0 2)
(lambda (r k)
(values k 1)))))
(let ((sub (share-array super subshape (lambda (k) (values k k)))))
( array - equal ? ( shape 4 7 ) )
(or (and (= (array-rank subshape) 2)
(= (array-start subshape 0) 0)
(= (array-end subshape 0) 1)
(= (array-start subshape 1) 0)
(= (array-end subshape 1) 2)
(= (array-ref subshape 0 0) 4)
(= (array-ref subshape 0 1) 7))
(fail "sharing subshape failed"))
( array - equal ? sub ( array ( shape 4 7 ) 1 2 3 ) )
(or (and (= (array-rank sub) 1)
(= (array-start sub 0) 4)
(= (array-end sub 0) 7)
(= (array-ref sub 4) 1)
(= (array-ref sub 5) 2)
(= (array-ref sub 6) 3))
(fail "sharing with sharing subshape failed"))))
(past "sharing with sharing subshape")
(writeln "Done.")
|
1ab6f9659a9266cdc045958fc71c0d87cd1aaf684b6bf81548b703843845fc26
|
nebogeo/weavingcodes
|
wwloomsim.scm
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; weavecoding raspberry pi installation
( scale 0.6 )
(rotate (vector 0 -45 0))
(define weft (build-jellyfish 4096))
(define warp (build-jellyfish 4096))
(define weave-scale (vector 0.2 -0.2 0.2))
(with-primitive
weft
(program-jelly
30 prim-triangles
'(let ((vertex positions-start)
(t 0)
(v 0)
(weft-direction (vector 2 0 0))
(weft-position (vector -20 0 0))
(weft-t 0)
(draft-pos 0)
(draft-size 5)
(draft 0) (d-b 0) (d-c 1) (d-d 0) (d-e 0)
(d-f 0) (d-g 0) (d-h 0) (d-i 0) (d-j 1)
(d-k 0) (d-l 1) (d-m 0) (d-n 0) (d-o 0)
(d-p 0) (d-q 0) (d-r 0) (d-s 1) (d-t 0)
(d-u 1) (d-v 0) (d-w 0) (d-x 0) (d-y 0)
(weft-z (vector 0 0 0))
(weft-count 0)
(weft-total 21))
(trace (addr draft))
(define read-draft
(lambda ()
(read
(+ (addr draft)
(+ (* draft-pos draft-size)
(if (> weft-direction 0)
(modulo weft-count (+ draft-size (vector 0 1 1)) )
(modulo (- (- weft-total 1) weft-count) (+ draft-size (vector 0 1 1)) )))))))
(define calc-weft-z
(lambda ()
(set! weft-count (+ weft-count 1))
(set! weft-z
(if (> (read-draft) 0.5)
(vector 0 0 0.01)
(vector 0 0 -0.01)))))
(define right-selvedge
(lambda (gap)
;; top corner
(write! vertex
(- (+ weft-position (vector 2 0 0)) gap)
(- (+ weft-position (vector 3 1 0)) gap)
(- (+ weft-position (vector 2 1 0)) gap))
(set! vertex (+ vertex 3))
;; vertical connection
(write! vertex
(- (+ weft-position (vector 3 1 0)) gap)
(- (+ weft-position (vector 2 1 0)) gap)
(+ weft-position (vector 2 0 0))
(- (+ weft-position (vector 3 1 0)) gap)
(+ weft-position (vector 2 0 0))
(+ weft-position (vector 3 0 0)))
(set! vertex (+ vertex 6))
;; bottom corner
(write! vertex
(+ weft-position (vector 2 0 0))
(+ weft-position (vector 3 0 0))
(+ weft-position (vector 2 1 0)))
(set! vertex (+ vertex 3))
))
(define left-selvedge
(lambda (gap)
;; top corner
(write! vertex
(- (+ weft-position (vector 0 0 0)) gap)
(- (+ weft-position (vector -1 1 0)) gap)
(- (+ weft-position (vector 0 1 0)) gap))
(set! vertex (+ vertex 3))
;; vertical connection
(write! vertex
(- (+ weft-position (vector -1 1 0)) gap)
(- (+ weft-position (vector 0 1 0)) gap)
(+ weft-position (vector 0 0 0))
(- (+ weft-position (vector -1 1 0)) gap)
(+ weft-position (vector 0 0 0))
(+ weft-position (vector -1 0 0)))
(set! vertex (+ vertex 6))
;; bottom corner
(write! vertex
(+ weft-position (vector 0 0 0))
(+ weft-position (vector -1 0 0))
(+ weft-position (vector 0 1 0)))
(set! vertex (+ vertex 3))
))
(forever
(set! vertex positions-start)
(loop (< vertex positions-end)
(calc-weft-z)
(set! weft-position (+ weft-position weft-direction))
;; selvedge time?
(when (> weft-count weft-total)
(set! weft-count 0)
(set! draft-pos (+ draft-pos 1))
(when (> draft-pos draft-size)
(set! draft-pos 0))
(set! weft-position (- (+ weft-position (vector 0 1.5 0))
weft-direction))
(set! weft-direction (* weft-direction -1))
(if (> 0 weft-direction)
(right-selvedge (vector 0 1.5 0))
(left-selvedge (vector 0 1.5 0))))
(set! weft-t (/ weft-count 21))
(write! vertex
(+ weft-z weft-position)
(+ weft-position (+ weft-z (vector 2 1 0)))
(+ weft-position (+ weft-z (vector 2 0 0)))
(+ weft-z weft-position)
(+ weft-position (+ weft-z (vector 2 1 0)))
(+ weft-position (+ weft-z (vector 0 1 0))))
(set! vertex (+ vertex 6)))
( set ! t ( + t 0.01 ) )
)))
(hint-unlit)
(hint-wire)
(texture (load-texture "thread.png"))
(scale weave-scale)
(pdata-index-map! (lambda (i t)
(cond
((eqv? (modulo i 6) 0) (vector 0 0 0))
((eqv? (modulo i 6) 1) (vector 1 1 0))
((eqv? (modulo i 6) 2) (vector 1 0 0))
((eqv? (modulo i 6) 3) (vector 0 0 0))
((eqv? (modulo i 6) 4) (vector 1 1 0))
((eqv? (modulo i 6) 5) (vector 0 1 0))
)) "t")
(pdata-map! (lambda (c) (vector 0 0 1)) "c")
(pdata-map! (lambda (n) (vector 0 0 0)) "n"))
;; weave section
;; top shed
;; bottom shed
;; back section
(with-primitive
warp
(program-jelly
800 prim-triangles
'(let ((vertex positions-start)
(warp-end 0)
(warp-position (vector 0 0 0))
(v 0)
(weft-t 0)
(draft-pos 0)
(draft-size 5)
(draft 0) (d-b 0) (d-c 1) (d-d 0) (d-e 0)
(d-f 0) (d-g 0) (d-h 0) (d-i 0) (d-j 1)
(d-k 0) (d-l 1) (d-m 0) (d-n 0) (d-o 0)
(d-p 0) (d-q 0) (d-r 0) (d-s 1) (d-t 0)
(d-u 1) (d-v 0) (d-w 0) (d-x 0) (d-y 0)
(last-t 0))
(define build-quad
(lambda (tl size)
(write! vertex
tl (+ tl size)
(+ tl (*v size (vector 1 0 0)))
tl (+ tl size)
(+ tl (*v size (vector 0 1 0))))
(set! vertex (+ vertex 6))))
;; like weft but don't need to take account of direction
(define read-draft
(lambda ()
(read (+ (addr draft)
(+ (* draft-pos draft-size)
(modulo warp-end (+ draft-size (vector 0 1 1)) ))))))
(define animate-shed
(lambda (i)
(set! v (if (< weft-t 0.2)
(vector 0 0 2)
(if (> weft-t 0.8)
(vector 0 0 -1.3)
(vector 0 0 0))))
(set! warp-end 0)
(loop (< warp-end 20)
(when (< (read-draft) 0.5)
(write-add! (- i 6) 0 v 0 0 v v
v 0 v v))
(set! i (+ i 24))
(set! warp-end (+ warp-end 1)))))
(define build-warp
(lambda ()
(set! vertex positions-start)
build 4 segments X warp - ends
(set! warp-end 0)
(loop (< warp-end 20)
(set! warp-position (+ (vector -19 -35.5 0)
(* (vector 2 0 0) warp-end)))
(build-quad warp-position (vector 1 35 0))
(build-quad (+ warp-position (vector 0 35 0)) (vector 1 10 0))
(build-quad (+ warp-position (vector 0 45 0)) (vector 1 15 0))
(build-quad (+ warp-position (vector 0 60 0)) (vector 1 25 0))
(set! warp-end (+ warp-end 1)))))
(build-warp)
(forever
(set! vertex (+ positions-start 12))
(animate-shed vertex)
(when (> (- last-t weft-t) 0.1)
(set! draft-pos (+ draft-pos 1))
(when (> draft-pos draft-size) (set! draft-pos 0))
(build-warp))
(set! last-t weft-t)
)))
(hint-unlit)
(texture (load-texture "thread.png"))
(scale weave-scale)
(pdata-index-map! (lambda (i t)
(cond
((eqv? (modulo i 6) 0) (vector 0 0 0))
((eqv? (modulo i 6) 1) (vector 10 1 0))
((eqv? (modulo i 6) 2) (vector 0 1 0))
((eqv? (modulo i 6) 3) (vector 0 0 0))
((eqv? (modulo i 6) 4) (vector 10 1 0))
((eqv? (modulo i 6) 5) (vector 10 0 0))
)) "t")
(pdata-map! (lambda (c) (vector 1 0.5 0.2)) "c")
(pdata-map! (lambda (n) (vector 0 0 0)) "n")
)
(define weft-draft-start 15)
(define warp-draft-start 14)
(define (set-draft! start data)
(when (not (null? data))
(pdata-set! "x" start
(if (zero? (car data))
(vector 0 0 0) (vector 1 0 0)))
(set-draft! (+ start 1) (cdr data))))
(msg "hello")
(every-frame
(with-primitive
warp
(pdata-set!
"x" 11 (with-primitive
weft
(pdata-ref "x" 12)))
(pdata-set!
"x" 12 (with-primitive
weft
(pdata-ref "x" 13))))
(with-primitive
weft
(when
(< (vy (vtransform (pdata-ref "x" 11) (get-transform))) 0)
(translate (vector 0 -0.1 0)))))
| null |
https://raw.githubusercontent.com/nebogeo/weavingcodes/e305a28a38ef745ca31de3074c8aec3953a72aa2/pattern-matrix/wwloomsim.scm
|
scheme
|
weavecoding raspberry pi installation
top corner
vertical connection
bottom corner
top corner
vertical connection
bottom corner
selvedge time?
weave section
top shed
bottom shed
back section
like weft but don't need to take account of direction
|
( scale 0.6 )
(rotate (vector 0 -45 0))
(define weft (build-jellyfish 4096))
(define warp (build-jellyfish 4096))
(define weave-scale (vector 0.2 -0.2 0.2))
(with-primitive
weft
(program-jelly
30 prim-triangles
'(let ((vertex positions-start)
(t 0)
(v 0)
(weft-direction (vector 2 0 0))
(weft-position (vector -20 0 0))
(weft-t 0)
(draft-pos 0)
(draft-size 5)
(draft 0) (d-b 0) (d-c 1) (d-d 0) (d-e 0)
(d-f 0) (d-g 0) (d-h 0) (d-i 0) (d-j 1)
(d-k 0) (d-l 1) (d-m 0) (d-n 0) (d-o 0)
(d-p 0) (d-q 0) (d-r 0) (d-s 1) (d-t 0)
(d-u 1) (d-v 0) (d-w 0) (d-x 0) (d-y 0)
(weft-z (vector 0 0 0))
(weft-count 0)
(weft-total 21))
(trace (addr draft))
(define read-draft
(lambda ()
(read
(+ (addr draft)
(+ (* draft-pos draft-size)
(if (> weft-direction 0)
(modulo weft-count (+ draft-size (vector 0 1 1)) )
(modulo (- (- weft-total 1) weft-count) (+ draft-size (vector 0 1 1)) )))))))
(define calc-weft-z
(lambda ()
(set! weft-count (+ weft-count 1))
(set! weft-z
(if (> (read-draft) 0.5)
(vector 0 0 0.01)
(vector 0 0 -0.01)))))
(define right-selvedge
(lambda (gap)
(write! vertex
(- (+ weft-position (vector 2 0 0)) gap)
(- (+ weft-position (vector 3 1 0)) gap)
(- (+ weft-position (vector 2 1 0)) gap))
(set! vertex (+ vertex 3))
(write! vertex
(- (+ weft-position (vector 3 1 0)) gap)
(- (+ weft-position (vector 2 1 0)) gap)
(+ weft-position (vector 2 0 0))
(- (+ weft-position (vector 3 1 0)) gap)
(+ weft-position (vector 2 0 0))
(+ weft-position (vector 3 0 0)))
(set! vertex (+ vertex 6))
(write! vertex
(+ weft-position (vector 2 0 0))
(+ weft-position (vector 3 0 0))
(+ weft-position (vector 2 1 0)))
(set! vertex (+ vertex 3))
))
(define left-selvedge
(lambda (gap)
(write! vertex
(- (+ weft-position (vector 0 0 0)) gap)
(- (+ weft-position (vector -1 1 0)) gap)
(- (+ weft-position (vector 0 1 0)) gap))
(set! vertex (+ vertex 3))
(write! vertex
(- (+ weft-position (vector -1 1 0)) gap)
(- (+ weft-position (vector 0 1 0)) gap)
(+ weft-position (vector 0 0 0))
(- (+ weft-position (vector -1 1 0)) gap)
(+ weft-position (vector 0 0 0))
(+ weft-position (vector -1 0 0)))
(set! vertex (+ vertex 6))
(write! vertex
(+ weft-position (vector 0 0 0))
(+ weft-position (vector -1 0 0))
(+ weft-position (vector 0 1 0)))
(set! vertex (+ vertex 3))
))
(forever
(set! vertex positions-start)
(loop (< vertex positions-end)
(calc-weft-z)
(set! weft-position (+ weft-position weft-direction))
(when (> weft-count weft-total)
(set! weft-count 0)
(set! draft-pos (+ draft-pos 1))
(when (> draft-pos draft-size)
(set! draft-pos 0))
(set! weft-position (- (+ weft-position (vector 0 1.5 0))
weft-direction))
(set! weft-direction (* weft-direction -1))
(if (> 0 weft-direction)
(right-selvedge (vector 0 1.5 0))
(left-selvedge (vector 0 1.5 0))))
(set! weft-t (/ weft-count 21))
(write! vertex
(+ weft-z weft-position)
(+ weft-position (+ weft-z (vector 2 1 0)))
(+ weft-position (+ weft-z (vector 2 0 0)))
(+ weft-z weft-position)
(+ weft-position (+ weft-z (vector 2 1 0)))
(+ weft-position (+ weft-z (vector 0 1 0))))
(set! vertex (+ vertex 6)))
( set ! t ( + t 0.01 ) )
)))
(hint-unlit)
(hint-wire)
(texture (load-texture "thread.png"))
(scale weave-scale)
(pdata-index-map! (lambda (i t)
(cond
((eqv? (modulo i 6) 0) (vector 0 0 0))
((eqv? (modulo i 6) 1) (vector 1 1 0))
((eqv? (modulo i 6) 2) (vector 1 0 0))
((eqv? (modulo i 6) 3) (vector 0 0 0))
((eqv? (modulo i 6) 4) (vector 1 1 0))
((eqv? (modulo i 6) 5) (vector 0 1 0))
)) "t")
(pdata-map! (lambda (c) (vector 0 0 1)) "c")
(pdata-map! (lambda (n) (vector 0 0 0)) "n"))
(with-primitive
warp
(program-jelly
800 prim-triangles
'(let ((vertex positions-start)
(warp-end 0)
(warp-position (vector 0 0 0))
(v 0)
(weft-t 0)
(draft-pos 0)
(draft-size 5)
(draft 0) (d-b 0) (d-c 1) (d-d 0) (d-e 0)
(d-f 0) (d-g 0) (d-h 0) (d-i 0) (d-j 1)
(d-k 0) (d-l 1) (d-m 0) (d-n 0) (d-o 0)
(d-p 0) (d-q 0) (d-r 0) (d-s 1) (d-t 0)
(d-u 1) (d-v 0) (d-w 0) (d-x 0) (d-y 0)
(last-t 0))
(define build-quad
(lambda (tl size)
(write! vertex
tl (+ tl size)
(+ tl (*v size (vector 1 0 0)))
tl (+ tl size)
(+ tl (*v size (vector 0 1 0))))
(set! vertex (+ vertex 6))))
(define read-draft
(lambda ()
(read (+ (addr draft)
(+ (* draft-pos draft-size)
(modulo warp-end (+ draft-size (vector 0 1 1)) ))))))
(define animate-shed
(lambda (i)
(set! v (if (< weft-t 0.2)
(vector 0 0 2)
(if (> weft-t 0.8)
(vector 0 0 -1.3)
(vector 0 0 0))))
(set! warp-end 0)
(loop (< warp-end 20)
(when (< (read-draft) 0.5)
(write-add! (- i 6) 0 v 0 0 v v
v 0 v v))
(set! i (+ i 24))
(set! warp-end (+ warp-end 1)))))
(define build-warp
(lambda ()
(set! vertex positions-start)
build 4 segments X warp - ends
(set! warp-end 0)
(loop (< warp-end 20)
(set! warp-position (+ (vector -19 -35.5 0)
(* (vector 2 0 0) warp-end)))
(build-quad warp-position (vector 1 35 0))
(build-quad (+ warp-position (vector 0 35 0)) (vector 1 10 0))
(build-quad (+ warp-position (vector 0 45 0)) (vector 1 15 0))
(build-quad (+ warp-position (vector 0 60 0)) (vector 1 25 0))
(set! warp-end (+ warp-end 1)))))
(build-warp)
(forever
(set! vertex (+ positions-start 12))
(animate-shed vertex)
(when (> (- last-t weft-t) 0.1)
(set! draft-pos (+ draft-pos 1))
(when (> draft-pos draft-size) (set! draft-pos 0))
(build-warp))
(set! last-t weft-t)
)))
(hint-unlit)
(texture (load-texture "thread.png"))
(scale weave-scale)
(pdata-index-map! (lambda (i t)
(cond
((eqv? (modulo i 6) 0) (vector 0 0 0))
((eqv? (modulo i 6) 1) (vector 10 1 0))
((eqv? (modulo i 6) 2) (vector 0 1 0))
((eqv? (modulo i 6) 3) (vector 0 0 0))
((eqv? (modulo i 6) 4) (vector 10 1 0))
((eqv? (modulo i 6) 5) (vector 10 0 0))
)) "t")
(pdata-map! (lambda (c) (vector 1 0.5 0.2)) "c")
(pdata-map! (lambda (n) (vector 0 0 0)) "n")
)
(define weft-draft-start 15)
(define warp-draft-start 14)
(define (set-draft! start data)
(when (not (null? data))
(pdata-set! "x" start
(if (zero? (car data))
(vector 0 0 0) (vector 1 0 0)))
(set-draft! (+ start 1) (cdr data))))
(msg "hello")
(every-frame
(with-primitive
warp
(pdata-set!
"x" 11 (with-primitive
weft
(pdata-ref "x" 12)))
(pdata-set!
"x" 12 (with-primitive
weft
(pdata-ref "x" 13))))
(with-primitive
weft
(when
(< (vy (vtransform (pdata-ref "x" 11) (get-transform))) 0)
(translate (vector 0 -0.1 0)))))
|
a54e866afb6a1cd0c122c4893107fa21084838146e4514da7a602f3f49d126bf
|
bvaugon/ocamlpp
|
ocamlpp.ml
|
(*************************************************************************)
(* *)
(* OCamlPP *)
(* *)
(* *)
This file is distributed under the terms of the CeCILL license .
(* See file ../LICENSE-en. *)
(* *)
(*************************************************************************)
let error msg =
Printf.eprintf "Error: %s\n" msg;
exit 1;
;;
let usage () =
Printf.eprintf "Usage: %s [ -version ] (<file.cmo> | <file.byte>)\n"
Sys.argv.(0);
exit 1;
;;
if Array.length Sys.argv <> 2 then usage ();;
if Sys.argv.(1) = "-version" then (
print_endline Config.version;
exit 0;
);;
begin try
let ((compunit, _code) as cmo) = Cmoparser.parse Sys.argv.(1) in
Cmoprinter.print (Globals.find (Globals.Reloc compunit)) stdout cmo;
with Cmoparser.Not_a_cmo -> begin try
let ic = open_in_bin Sys.argv.(1) in
let index = Index.parse ic in Index.print stdout index;
let prims = Prim.parse ic index in Prim.print stdout prims;
let data = Data.parse ic index in Data.print stdout data;
let code = Code.parse ic index in
let globnames = Globals.find (Globals.Glob (prims, Array.of_list data)) in
Code.print globnames stdout code;
close_in ic;
with Index.Not_a_byte ->
error "not a bytecode executable file nor an OCaml object file"
| Failure msg -> error msg end
| Failure msg -> error msg end
| null |
https://raw.githubusercontent.com/bvaugon/ocamlpp/ee8dbf90b2012cb20bb2a9730524e12bc59dc1f2/src/ocamlpp.ml
|
ocaml
|
***********************************************************************
OCamlPP
See file ../LICENSE-en.
***********************************************************************
|
This file is distributed under the terms of the CeCILL license .
let error msg =
Printf.eprintf "Error: %s\n" msg;
exit 1;
;;
let usage () =
Printf.eprintf "Usage: %s [ -version ] (<file.cmo> | <file.byte>)\n"
Sys.argv.(0);
exit 1;
;;
if Array.length Sys.argv <> 2 then usage ();;
if Sys.argv.(1) = "-version" then (
print_endline Config.version;
exit 0;
);;
begin try
let ((compunit, _code) as cmo) = Cmoparser.parse Sys.argv.(1) in
Cmoprinter.print (Globals.find (Globals.Reloc compunit)) stdout cmo;
with Cmoparser.Not_a_cmo -> begin try
let ic = open_in_bin Sys.argv.(1) in
let index = Index.parse ic in Index.print stdout index;
let prims = Prim.parse ic index in Prim.print stdout prims;
let data = Data.parse ic index in Data.print stdout data;
let code = Code.parse ic index in
let globnames = Globals.find (Globals.Glob (prims, Array.of_list data)) in
Code.print globnames stdout code;
close_in ic;
with Index.Not_a_byte ->
error "not a bytecode executable file nor an OCaml object file"
| Failure msg -> error msg end
| Failure msg -> error msg end
|
4bd16da9df63d7a924e095d5047ff19c141d6ffdc0653a69c05daca1b1b63af0
|
ananthakumaran/eopl
|
37.clj
|
(ns eopl.chap-5.37
(:use eopl.core.exception-lang)
(:use clojure.test))
;; Modify the defined language to raise an exception when a procedure
;; is called with the wrong number of arguments
(deftest wrong-number-of-args
(is (= (with-out-str
(result "let f = proc(x) x
in (f 5 5)"))
"unhandled exception Wrong number of arguments expected 1 actual 2")))
| null |
https://raw.githubusercontent.com/ananthakumaran/eopl/876d6c2e44865e2c89a05a683d99a289c71f1487/src/eopl/chap_5/37.clj
|
clojure
|
Modify the defined language to raise an exception when a procedure
is called with the wrong number of arguments
|
(ns eopl.chap-5.37
(:use eopl.core.exception-lang)
(:use clojure.test))
(deftest wrong-number-of-args
(is (= (with-out-str
(result "let f = proc(x) x
in (f 5 5)"))
"unhandled exception Wrong number of arguments expected 1 actual 2")))
|
65f0414898bd439829cc19badbf09f45347bab8ef44d9c0e46691a704edd1fb8
|
dyoo/ragg
|
simple-arithmetic-grammar.rkt
|
#lang ragg
expr : term ('+' term)*
term : factor ('*' factor)*
factor : INT
| null |
https://raw.githubusercontent.com/dyoo/ragg/9cc648e045f7195702599b88e6b8db9364f88302/ragg/examples/simple-arithmetic-grammar.rkt
|
racket
|
#lang ragg
expr : term ('+' term)*
term : factor ('*' factor)*
factor : INT
|
|
fd3de4e03f4dfc93d4ba57c8ebe1072138a237f03cf166e59ca7d0d4bea3efd9
|
tel/saltine
|
Sign.hs
|
-- |
-- Module : Crypto.Saltine.Core.Sign
Copyright : ( c ) 2013
License : MIT
--
Maintainer :
-- Stability : experimental
-- Portability : non-portable
--
-- Signatures: "Crypto.Saltine.Core.Sign"
--
The ' newKeypair ' function randomly generates a secret key and a
-- corresponding public key. The 'sign' function signs a message
' ByteString ' using the signer 's secret key and returns the
-- resulting signed message. The 'signOpen' function verifies the
-- signature in a signed message using the signer's public key then
-- returns the message without its signature.
--
" Crypto . Saltine . Core . Sign " is an EdDSA signature using
elliptic - curve ( see : < / > ) . See
also , \"Daniel , , ,
Schwabe , Bo - . High - speed high - security signatures . Journal
of Cryptographic Engineering 2 ( 2012 ) , 77–89.\ "
-- <-20110926.pdf>.
--
This is current information as of 2013 June 6 .
module Crypto.Saltine.Core.Sign (
SecretKey, PublicKey, Keypair(..), Signature,
newKeypair,
sign, signOpen,
signDetached, signVerifyDetached
) where
import Crypto.Saltine.Internal.Sign
( c_sign_keypair
, c_sign
, c_sign_open
, c_sign_detached
, c_sign_verify_detached
, SecretKey(..)
, PublicKey(..)
, Keypair(..)
, Signature(..)
)
import Crypto.Saltine.Internal.Util as U
import Data.ByteString (ByteString)
import Foreign.Marshal.Alloc
import Foreign.Storable
import System.IO.Unsafe
import qualified Crypto.Saltine.Internal.Sign as Bytes
import qualified Data.ByteString as S
-- | Creates a random key of the correct size for 'sign' and
' signOpen ' of form @(secretKey , publicKey)@.
newKeypair :: IO Keypair
newKeypair = do
-- This is a little bizarre and a likely source of errors.
-- _err ought to always be 0.
((_err, sk), pk) <- buildUnsafeByteString' Bytes.sign_publickeybytes $ \pkbuf ->
buildUnsafeByteString' Bytes.sign_secretkeybytes $ \skbuf ->
c_sign_keypair pkbuf skbuf
return $ Keypair (SK sk) (PK pk)
-- | Augments a message with a signature forming a \"signed
-- message\".
sign :: SecretKey
-> ByteString
-- ^ Message
-> ByteString
-- ^ Signed message
sign (SK k) m = unsafePerformIO $
alloca $ \psmlen -> do
(_err, sm) <- buildUnsafeByteString' (len + Bytes.sign_bytes) $ \psmbuf ->
constByteStrings [k, m] $ \[(pk, _), (pm, _)] ->
c_sign psmbuf psmlen pm (fromIntegral len) pk
smlen <- peek psmlen
return $ S.take (fromIntegral smlen) sm
where len = S.length m
-- | Checks a \"signed message\" returning 'Just' the original message
iff the signature was generated using the ' SecretKey ' corresponding
to the given ' PublicKey ' . Returns ' Nothing ' otherwise .
signOpen :: PublicKey
-> ByteString
-- ^ Signed message
-> Maybe ByteString
-- ^ Maybe the restored message
signOpen (PK k) sm = unsafePerformIO $
alloca $ \pmlen -> do
(err, m) <- buildUnsafeByteString' smlen $ \pmbuf ->
constByteStrings [k, sm] $ \[(pk, _), (psm, _)] ->
c_sign_open pmbuf pmlen psm (fromIntegral smlen) pk
mlen <- peek pmlen
case err of
0 -> return $ Just $ S.take (fromIntegral mlen) m
_ -> return Nothing
where smlen = S.length sm
| Returns just the signature for a message using a SecretKey .
signDetached :: SecretKey
-> ByteString
-- ^ Message
-> Signature
-- ^ Signature
signDetached (SK k) m = unsafePerformIO $
alloca $ \psmlen -> do
(_err, sm) <- buildUnsafeByteString' Bytes.sign_bytes $ \sigbuf ->
constByteStrings [k, m] $ \[(pk, _), (pm, _)] ->
c_sign_detached sigbuf psmlen pm (fromIntegral len) pk
smlen <- peek psmlen
return $ Signature $ S.take (fromIntegral smlen) sm
where len = S.length m
-- | Returns @True@ if the signature is valid for the given public key and
-- message.
signVerifyDetached :: PublicKey
-> Signature
-- ^ Signature
-> ByteString
-- ^ Message (not signed)
-> Bool
signVerifyDetached (PK k) (Signature sig) sm = unsafePerformIO $
constByteStrings [k, sig, sm] $ \[(pk, _), (psig, _), (psm, _)] -> do
res <- c_sign_verify_detached psig psm (fromIntegral len) pk
return (res == 0)
where len = S.length sm
| null |
https://raw.githubusercontent.com/tel/saltine/3a02e9f988a15249afd3f0a0a8ce6bf0bbc97fb1/src/Crypto/Saltine/Core/Sign.hs
|
haskell
|
|
Module : Crypto.Saltine.Core.Sign
Stability : experimental
Portability : non-portable
Signatures: "Crypto.Saltine.Core.Sign"
corresponding public key. The 'sign' function signs a message
resulting signed message. The 'signOpen' function verifies the
signature in a signed message using the signer's public key then
returns the message without its signature.
<-20110926.pdf>.
| Creates a random key of the correct size for 'sign' and
This is a little bizarre and a likely source of errors.
_err ought to always be 0.
| Augments a message with a signature forming a \"signed
message\".
^ Message
^ Signed message
| Checks a \"signed message\" returning 'Just' the original message
^ Signed message
^ Maybe the restored message
^ Message
^ Signature
| Returns @True@ if the signature is valid for the given public key and
message.
^ Signature
^ Message (not signed)
|
Copyright : ( c ) 2013
License : MIT
Maintainer :
The ' newKeypair ' function randomly generates a secret key and a
' ByteString ' using the signer 's secret key and returns the
" Crypto . Saltine . Core . Sign " is an EdDSA signature using
elliptic - curve ( see : < / > ) . See
also , \"Daniel , , ,
Schwabe , Bo - . High - speed high - security signatures . Journal
of Cryptographic Engineering 2 ( 2012 ) , 77–89.\ "
This is current information as of 2013 June 6 .
module Crypto.Saltine.Core.Sign (
SecretKey, PublicKey, Keypair(..), Signature,
newKeypair,
sign, signOpen,
signDetached, signVerifyDetached
) where
import Crypto.Saltine.Internal.Sign
( c_sign_keypair
, c_sign
, c_sign_open
, c_sign_detached
, c_sign_verify_detached
, SecretKey(..)
, PublicKey(..)
, Keypair(..)
, Signature(..)
)
import Crypto.Saltine.Internal.Util as U
import Data.ByteString (ByteString)
import Foreign.Marshal.Alloc
import Foreign.Storable
import System.IO.Unsafe
import qualified Crypto.Saltine.Internal.Sign as Bytes
import qualified Data.ByteString as S
' signOpen ' of form @(secretKey , publicKey)@.
newKeypair :: IO Keypair
newKeypair = do
((_err, sk), pk) <- buildUnsafeByteString' Bytes.sign_publickeybytes $ \pkbuf ->
buildUnsafeByteString' Bytes.sign_secretkeybytes $ \skbuf ->
c_sign_keypair pkbuf skbuf
return $ Keypair (SK sk) (PK pk)
sign :: SecretKey
-> ByteString
-> ByteString
sign (SK k) m = unsafePerformIO $
alloca $ \psmlen -> do
(_err, sm) <- buildUnsafeByteString' (len + Bytes.sign_bytes) $ \psmbuf ->
constByteStrings [k, m] $ \[(pk, _), (pm, _)] ->
c_sign psmbuf psmlen pm (fromIntegral len) pk
smlen <- peek psmlen
return $ S.take (fromIntegral smlen) sm
where len = S.length m
iff the signature was generated using the ' SecretKey ' corresponding
to the given ' PublicKey ' . Returns ' Nothing ' otherwise .
signOpen :: PublicKey
-> ByteString
-> Maybe ByteString
signOpen (PK k) sm = unsafePerformIO $
alloca $ \pmlen -> do
(err, m) <- buildUnsafeByteString' smlen $ \pmbuf ->
constByteStrings [k, sm] $ \[(pk, _), (psm, _)] ->
c_sign_open pmbuf pmlen psm (fromIntegral smlen) pk
mlen <- peek pmlen
case err of
0 -> return $ Just $ S.take (fromIntegral mlen) m
_ -> return Nothing
where smlen = S.length sm
| Returns just the signature for a message using a SecretKey .
signDetached :: SecretKey
-> ByteString
-> Signature
signDetached (SK k) m = unsafePerformIO $
alloca $ \psmlen -> do
(_err, sm) <- buildUnsafeByteString' Bytes.sign_bytes $ \sigbuf ->
constByteStrings [k, m] $ \[(pk, _), (pm, _)] ->
c_sign_detached sigbuf psmlen pm (fromIntegral len) pk
smlen <- peek psmlen
return $ Signature $ S.take (fromIntegral smlen) sm
where len = S.length m
signVerifyDetached :: PublicKey
-> Signature
-> ByteString
-> Bool
signVerifyDetached (PK k) (Signature sig) sm = unsafePerformIO $
constByteStrings [k, sig, sm] $ \[(pk, _), (psig, _), (psm, _)] -> do
res <- c_sign_verify_detached psig psm (fromIntegral len) pk
return (res == 0)
where len = S.length sm
|
885c86b7067ed26529cf055046b774c56e8fd07c4c16dd9dee89963eb7746bb7
|
CSCfi/rems
|
test_workflow.clj
|
(ns ^:integration rems.service.test-workflow
(:require [clojure.test :refer :all]
[rems.service.workflow :as workflow]
[rems.db.test-data-helpers :as test-helpers]
[rems.db.testing :refer [reset-caches-fixture rollback-db-fixture test-db-fixture]]
[rems.testing-util :refer [with-user]]))
(use-fixtures
:once
test-db-fixture
reset-caches-fixture)
(use-fixtures :each rollback-db-fixture)
(defn- create-users []
(test-helpers/create-user! {:userid "user1" :name "User 1" :email ""})
(test-helpers/create-user! {:userid "user2" :name "User 2" :email ""})
(test-helpers/create-user! {:userid "user3" :name "User 3" :email ""})
(test-helpers/create-user! {:userid "owner" :name "owner" :email ""} :owner))
(deftest test-create-workflow
(create-users)
(with-user "owner"
(test-helpers/create-organization! {:organization/id "abc" :organization/name {:en "ABC"} :organization/short-name {:en "ABC"}})
(testing "default workflow with forms"
(let [form-id (test-helpers/create-form! {:form/internal-name "workflow form"
:form/external-title {:en "Workflow Form EN"
:fi "Workflow Form FI"
:sv "Workflow Form SV"}
:form/fields [{:field/type :text
:field/title {:fi "fi" :sv "sv" :en "en"}
:field/optional true}]})
wf-id (test-helpers/create-workflow! {:organization {:organization/id "abc"}
:type :workflow/default
:title "the title"
:handlers ["user1" "user2"]
:forms [{:form/id form-id}]})]
(is (= {:id wf-id
:organization {:organization/id "abc" :organization/name {:en "ABC"} :organization/short-name {:en "ABC"}}
:title "the title"
:workflow {:type :workflow/default
:handlers [{:userid "user1" :name "User 1" :email ""}
{:userid "user2" :name "User 2" :email ""}]
:forms [{:form/id form-id
:form/internal-name "workflow form"
:form/external-title {:en "Workflow Form EN"
:fi "Workflow Form FI"
:sv "Workflow Form SV"}}]
:licenses []}
:enabled true
:archived false}
(workflow/get-workflow wf-id)))))
(testing "decider workflow"
(let [wf-id (test-helpers/create-workflow! {:organization {:organization/id "abc"}
:type :workflow/decider
:title "the title"
:handlers ["user1" "user2"]})]
(is (= {:id wf-id
:organization {:organization/id "abc" :organization/name {:en "ABC"} :organization/short-name {:en "ABC"}}
:title "the title"
:workflow {:type :workflow/decider
:handlers [{:userid "user1" :name "User 1" :email ""}
{:userid "user2" :name "User 2" :email ""}]
:forms []
:licenses []}
:enabled true
:archived false}
(workflow/get-workflow wf-id)))))
(testing "master workflow"
(let [wf-id (test-helpers/create-workflow! {:organization {:organization/id "abc"}
:type :workflow/master
:title "the title"
:handlers ["user1" "user2"]})]
(is (= {:id wf-id
:organization {:organization/id "abc" :organization/name {:en "ABC"} :organization/short-name {:en "ABC"}}
:title "the title"
:workflow {:type :workflow/master
:handlers [{:userid "user1" :name "User 1" :email ""}
{:userid "user2" :name "User 2" :email ""}]
:forms []
:licenses []}
:enabled true
:archived false}
(workflow/get-workflow wf-id)))))))
(deftest test-edit-workflow
(create-users)
(with-user "owner"
(test-helpers/create-organization! {:organization/id "abc" :organization/name {:en "ABC"} :organization/short-name {:en "ABC"}})
(testing "change title"
(let [licid (test-helpers/create-license! {:organization {:organization/id "abc"}})
wf-id (test-helpers/create-workflow! {:organization {:organization/id "abc"}
:type :workflow/master
:title "original title"
:handlers ["user1"]
:licenses [licid]})]
(workflow/edit-workflow! {:id wf-id
:title "changed title"})
(is (= {:id wf-id
:title "changed title"
:workflow {:type :workflow/master
:handlers [{:userid "user1" :name "User 1" :email ""}]
:forms []
:licenses [{:license/id licid}]}}
(-> (workflow/get-workflow wf-id)
(select-keys [:id :title :workflow])
(update-in [:workflow :licenses]
(partial map #(select-keys % [:license/id]))))))))
(testing "change handlers"
(let [wf-id (test-helpers/create-workflow! {:organization {:organization/id "abc"}
:type :workflow/master
:title "original title"
:handlers ["user1"]})]
(workflow/edit-workflow! {:id wf-id
:handlers ["user2"]})
(is (= {:id wf-id
:title "original title"
:workflow {:type :workflow/master
:handlers [{:userid "user2" :name "User 2" :email ""}]
:forms []
:licenses []}}
(-> (workflow/get-workflow wf-id)
(select-keys [:id :title :workflow]))))))))
(deftest test-get-workflow
(create-users)
(with-user "owner"
(testing "not found"
(is (nil? (workflow/get-workflow 123))))))
(deftest test-get-handlers
(create-users)
(with-user "owner"
(let [simplify #(map :userid %)
wf1 (test-helpers/create-workflow! {:type :workflow/default
:title "workflow2"
:handlers ["user1"
"user2"]})
wf2 (test-helpers/create-workflow! {:type :workflow/default
:title "workflow2"
:handlers ["user2"
"user3"]})]
(testing "returns distinct handlers from all workflows"
(is (= ["user1" "user2" "user3"]
(simplify (workflow/get-handlers)))))
(testing "ignores disabled workflows"
(workflow/set-workflow-enabled! {:id wf1 :enabled false})
(is (= ["user2" "user3"]
(simplify (workflow/get-handlers)))))
(testing "ignores archived workflows"
(workflow/set-workflow-archived! {:id wf2 :archived true})
(is (= []
(simplify (workflow/get-handlers))))))))
| null |
https://raw.githubusercontent.com/CSCfi/rems/490087c4d58339c908da792111029fbaf817a26f/test/clj/rems/service/test_workflow.clj
|
clojure
|
(ns ^:integration rems.service.test-workflow
(:require [clojure.test :refer :all]
[rems.service.workflow :as workflow]
[rems.db.test-data-helpers :as test-helpers]
[rems.db.testing :refer [reset-caches-fixture rollback-db-fixture test-db-fixture]]
[rems.testing-util :refer [with-user]]))
(use-fixtures
:once
test-db-fixture
reset-caches-fixture)
(use-fixtures :each rollback-db-fixture)
(defn- create-users []
(test-helpers/create-user! {:userid "user1" :name "User 1" :email ""})
(test-helpers/create-user! {:userid "user2" :name "User 2" :email ""})
(test-helpers/create-user! {:userid "user3" :name "User 3" :email ""})
(test-helpers/create-user! {:userid "owner" :name "owner" :email ""} :owner))
(deftest test-create-workflow
(create-users)
(with-user "owner"
(test-helpers/create-organization! {:organization/id "abc" :organization/name {:en "ABC"} :organization/short-name {:en "ABC"}})
(testing "default workflow with forms"
(let [form-id (test-helpers/create-form! {:form/internal-name "workflow form"
:form/external-title {:en "Workflow Form EN"
:fi "Workflow Form FI"
:sv "Workflow Form SV"}
:form/fields [{:field/type :text
:field/title {:fi "fi" :sv "sv" :en "en"}
:field/optional true}]})
wf-id (test-helpers/create-workflow! {:organization {:organization/id "abc"}
:type :workflow/default
:title "the title"
:handlers ["user1" "user2"]
:forms [{:form/id form-id}]})]
(is (= {:id wf-id
:organization {:organization/id "abc" :organization/name {:en "ABC"} :organization/short-name {:en "ABC"}}
:title "the title"
:workflow {:type :workflow/default
:handlers [{:userid "user1" :name "User 1" :email ""}
{:userid "user2" :name "User 2" :email ""}]
:forms [{:form/id form-id
:form/internal-name "workflow form"
:form/external-title {:en "Workflow Form EN"
:fi "Workflow Form FI"
:sv "Workflow Form SV"}}]
:licenses []}
:enabled true
:archived false}
(workflow/get-workflow wf-id)))))
(testing "decider workflow"
(let [wf-id (test-helpers/create-workflow! {:organization {:organization/id "abc"}
:type :workflow/decider
:title "the title"
:handlers ["user1" "user2"]})]
(is (= {:id wf-id
:organization {:organization/id "abc" :organization/name {:en "ABC"} :organization/short-name {:en "ABC"}}
:title "the title"
:workflow {:type :workflow/decider
:handlers [{:userid "user1" :name "User 1" :email ""}
{:userid "user2" :name "User 2" :email ""}]
:forms []
:licenses []}
:enabled true
:archived false}
(workflow/get-workflow wf-id)))))
(testing "master workflow"
(let [wf-id (test-helpers/create-workflow! {:organization {:organization/id "abc"}
:type :workflow/master
:title "the title"
:handlers ["user1" "user2"]})]
(is (= {:id wf-id
:organization {:organization/id "abc" :organization/name {:en "ABC"} :organization/short-name {:en "ABC"}}
:title "the title"
:workflow {:type :workflow/master
:handlers [{:userid "user1" :name "User 1" :email ""}
{:userid "user2" :name "User 2" :email ""}]
:forms []
:licenses []}
:enabled true
:archived false}
(workflow/get-workflow wf-id)))))))
(deftest test-edit-workflow
(create-users)
(with-user "owner"
(test-helpers/create-organization! {:organization/id "abc" :organization/name {:en "ABC"} :organization/short-name {:en "ABC"}})
(testing "change title"
(let [licid (test-helpers/create-license! {:organization {:organization/id "abc"}})
wf-id (test-helpers/create-workflow! {:organization {:organization/id "abc"}
:type :workflow/master
:title "original title"
:handlers ["user1"]
:licenses [licid]})]
(workflow/edit-workflow! {:id wf-id
:title "changed title"})
(is (= {:id wf-id
:title "changed title"
:workflow {:type :workflow/master
:handlers [{:userid "user1" :name "User 1" :email ""}]
:forms []
:licenses [{:license/id licid}]}}
(-> (workflow/get-workflow wf-id)
(select-keys [:id :title :workflow])
(update-in [:workflow :licenses]
(partial map #(select-keys % [:license/id]))))))))
(testing "change handlers"
(let [wf-id (test-helpers/create-workflow! {:organization {:organization/id "abc"}
:type :workflow/master
:title "original title"
:handlers ["user1"]})]
(workflow/edit-workflow! {:id wf-id
:handlers ["user2"]})
(is (= {:id wf-id
:title "original title"
:workflow {:type :workflow/master
:handlers [{:userid "user2" :name "User 2" :email ""}]
:forms []
:licenses []}}
(-> (workflow/get-workflow wf-id)
(select-keys [:id :title :workflow]))))))))
(deftest test-get-workflow
(create-users)
(with-user "owner"
(testing "not found"
(is (nil? (workflow/get-workflow 123))))))
(deftest test-get-handlers
(create-users)
(with-user "owner"
(let [simplify #(map :userid %)
wf1 (test-helpers/create-workflow! {:type :workflow/default
:title "workflow2"
:handlers ["user1"
"user2"]})
wf2 (test-helpers/create-workflow! {:type :workflow/default
:title "workflow2"
:handlers ["user2"
"user3"]})]
(testing "returns distinct handlers from all workflows"
(is (= ["user1" "user2" "user3"]
(simplify (workflow/get-handlers)))))
(testing "ignores disabled workflows"
(workflow/set-workflow-enabled! {:id wf1 :enabled false})
(is (= ["user2" "user3"]
(simplify (workflow/get-handlers)))))
(testing "ignores archived workflows"
(workflow/set-workflow-archived! {:id wf2 :archived true})
(is (= []
(simplify (workflow/get-handlers))))))))
|
|
32e6c4c186e9b5e5df15fe97b5b9dd86f2c2eb4c93a1f75923b60d8074315975
|
thelema/ocaml-community
|
builtin_text.ml
|
(* Not a string as such, more like a symbol *)
(* type *)
type textMark = string;;
/type
(* type *)
type textTag = string;;
/type
##ifdef CAMLTK
(* type *)
type textModifier =
tk keyword : + /-
| LineOffset of int (* tk keyword: +/- Xlines *)
| LineStart (* tk keyword: linestart *)
| LineEnd (* tk keyword: lineend *)
tk keyword : wordstart
| WordEnd (* tk keyword: wordend *)
;;
/type
(* type *)
type textIndex =
| TextIndex of index * textModifier list
| TextIndexNone
;;
/type
##else
(* type *)
type textModifier = [
tk keyword : + /-
| `Line of int (* tk keyword: +/- Xlines *)
| `Linestart (* tk keyword: linestart *)
| `Lineend (* tk keyword: lineend *)
tk keyword : wordstart
| `Wordend (* tk keyword: wordend *)
]
;;
/type
(* type *)
type textIndex = text_index * textModifier list
;;
/type
##endif
| null |
https://raw.githubusercontent.com/thelema/ocaml-community/ed0a2424bbf13d1b33292725e089f0d7ba94b540/otherlibs/labltk/builtin/builtin_text.ml
|
ocaml
|
Not a string as such, more like a symbol
type
type
type
tk keyword: +/- Xlines
tk keyword: linestart
tk keyword: lineend
tk keyword: wordend
type
type
tk keyword: +/- Xlines
tk keyword: linestart
tk keyword: lineend
tk keyword: wordend
type
|
type textMark = string;;
/type
type textTag = string;;
/type
##ifdef CAMLTK
type textModifier =
tk keyword : + /-
tk keyword : wordstart
;;
/type
type textIndex =
| TextIndex of index * textModifier list
| TextIndexNone
;;
/type
##else
type textModifier = [
tk keyword : + /-
tk keyword : wordstart
]
;;
/type
type textIndex = text_index * textModifier list
;;
/type
##endif
|
66693fcfe954435345b6fc9a398f38dc70adaa3a5b1b66056bbd7514f01fae10
|
calvis/cKanren
|
neq.rkt
|
#lang racket
(require
"../tester.rkt"
"../ck.rkt"
"../tree-unify.rkt"
"../neq.rkt"
"../matche.rkt"
"../src/operators.rkt")
(provide distincto rembero test-neq test-neq-long)
(defmatche (distincto l)
[[()]]
[[(,a)]]
[[(,a ,ad . ,dd)]
(=/= a ad)
(distincto `(,a . ,dd))
(distincto `(,ad . ,dd))])
(defmatche (rembero x ls out)
[[,x () ()]]
[[,x (,x . ,d) ,out]
(rembero x d out)]
[[,x (,a . ,d) ,out]
(=/= a x)
(fresh (res)
(rembero x d res)
(== `(,a . ,res) out))])
(define (test-neq)
;; SIMPLE
(test (run* (q) (=/= 5 6)) '(_.0))
(test (run* (q) (=/= 3 3)) '())
(test (run* (q) (== q 3) (=/= 3 q))
'())
(test (run* (q) (=/= 3 q) (== q 3))
'())
(test (run* (x y) (== x y) (=/= x y))
'())
(test (run* (x y) (=/= x y) (== x y))
'())
(test (run* (q) (=/= q q))
'())
(test (run* (q) (fresh (a) (=/= a a)))
'())
(test
(run* (x y)
(=/= x y)
(== 3 x)
(== 3 y))
'())
(test
(run* (x y)
(== 3 x)
(=/= x y)
(== 3 y))
'())
(test
(run* (x y)
(== 3 x)
(== 3 y)
(=/= x y))
'())
(test
(run* (x y)
(== 3 x)
(== 3 y)
(=/= y x))
'())
(test
(run* (x y z)
(== x y)
(== y z)
(=/= x 4)
(== z (+ 2 2)))
'())
(test
(run* (x y z)
(== x y)
(== y z)
(== z (+ 2 2))
(=/= x 4))
'())
(test
(run* (x y z)
(=/= x 4)
(== y z)
(== x y)
(== z (+ 2 2)))
'())
(test
(run* (x y z)
(=/= x y)
(== x `(0 ,z 1))
(== y `(0 1 1))
(== z 1))
'())
(test
(run* (x y z)
(== z 1)
(=/= x y)
(== x `(0 ,z 1))
(== y `(0 1 1)))
'())
(test
(run* (x y z)
(== z 1)
(== x `(0 ,z 1))
(== y `(0 1 1))
(=/= x y))
'())
(test
(run* (q)
(fresh (x y z)
(=/= x y)
(== x `(0 ,z 1))
(== y `(0 1 1))
(== z 0)))
'(_.0))
(test
(run* (x y)
(=/= `(,x 1) `(2 ,y))
(== x 2)
(== y 1))
'())
(test
(run* (a x z)
(=/= a `(,x 1))
(== a `(,z 1))
(== x z))
'())
(test
(run* (x y)
(=/= `(,x 1) `(2 ,y))
(== x 2)
(== y 1))
'())
(test
(run* (q)
(fresh (x y z)
(== z 0)
(=/= x y)
(== x `(0 ,z 1))
(== y `(0 1 1))))
'(_.0))
(test
(run* (q)
(fresh (x y z)
(== x `(0 ,z 1))
(== y `(0 1 1))
(=/= x y)))
'(_.0))
(test
(run* (q)
(fresh (x y)
(=/= `(,x 1) `(2 ,y))
(== x 2)))
'(_.0))
(test
(run* (q)
(fresh (x y)
(=/= `(,x 1) `(2 ,y))
(== y 1)))
'(_.0))
(test
(run* (x y z)
(=/= `(,x 2 ,z) `(1 ,z 3))
(=/= `(,x 6 ,z) `(4 ,z 6))
(=/= `(,x ,y ,z) `(7 ,z 9))
(== x z))
'((_.0 _.1 _.0)))
(test
(run* (x y)
(=/= `(,x 1) `(2 ,y))
(== x 2)
(== y 9))
'((2 9)))
(test
(run* (q)
(fresh (a)
(== 3 a)
(=/= a 4)))
'(_.0))
;; MEDIUM
;; these test reification
(test
(run* (q) (=/= q #f))
'((_.0 : (=/= ((_.0 . #f))))))
(test
(run* (x y) (=/= x y))
'(((_.0 _.1) : (=/= ((_.0 . _.1))))))
;; this tests the constraint-interaction
(test
(run* (q)
(=/= q 5)
(=/= 5 q))
'((_.0 : (=/= ((_.0 . 5))))))
(test
(run* (x y)
(=/= y x))
'(((_.0 _.1) : (=/= ((_.0 . _.1))))))
(test
(run* (x y)
(=/= x y)
(=/= x y))
'(((_.0 _.1) : (=/= ((_.0 . _.1))))))
(test
(run* (x y)
(=/= x y)
(=/= y x))
'(((_.0 _.1) : (=/= ((_.0 . _.1))))))
(test
(run* (x y)
(=/= `(,x 1) `(2 ,y)))
'(((_.0 _.1) : (=/= ((_.0 . 2) (_.1 . 1))))))
(test
(run* (q)
(=/= 4 q)
(=/= 3 q))
'((_.0 : (=/= ((_.0 . 3)) ((_.0 . 4))))))
(test
(run* (q) (=/= q 5) (=/= q 5))
'((_.0 : (=/= ((_.0 . 5))))))
;; HARD
(test
(run* (x y)
(=/= `(,x 1) `(2 ,y))
(== x 2))
'(((2 _.0) : (=/= ((_.0 . 1))))))
(test
(run* (q)
(fresh (a x z)
(=/= a `(,x 1))
(== a `(,z 1))
(== x 5)
(== `(,x ,z) q)))
'(((5 _.0) : (=/= ((_.0 . 5))))))
(test
(run* (x y)
(=/= `(,x ,y) `(5 6))
(=/= x 5))
'(((_.0 _.1) : (=/= ((_.0 . 5))))))
(test
(run* (x y)
(=/= x 5)
(=/= `(,x ,y) `(5 6)))
'(((_.0 _.1) : (=/= ((_.0 . 5))))))
(test
(run* (x y)
(=/= 5 x)
(=/= `( ,y ,x) `(6 5)))
'(((_.0 _.1) : (=/= ((_.0 . 5))))))
(test
(run* (x)
(fresh (y z)
(=/= x `(,y 2))
(== x `(,z 2))))
'((_.0 2)))
(test
(run* (x)
(fresh (y z)
(=/= x `(,y 2))
(== x `((,z) 2))))
'(((_.0) 2)))
(test
(run* (x)
(fresh (y z)
(=/= x `((,y) 2))
(== x `(,z 2))))
'((_.0 2)))
(test
(run* (q)
(distincto `(2 3 ,q)))
'((_.0 : (=/= ((_.0 . 2)) ((_.0 . 3))))))
(test
(run* (q) (rembero 'x '() q))
'(()))
(test
(run* (q) (rembero 'x '(x) '()))
'(_.0))
(test
(run* (q) (rembero 'a '(a b a c) q))
'((b c)))
(test
(run* (q) (rembero 'a '(a b c) '(a b c)))
'())
(test
(run* (w x y z)
(=/= `(,w . ,x) `(,y . ,z)))
'(((_.0 _.1 _.2 _.3)
:
(=/= ((_.0 . _.2) (_.1 . _.3))))))
(test
(run* (w x y z)
(=/= `(,w . ,x) `(,y . ,z))
(== w y))
'(((_.0 _.1 _.0 _.2)
:
(=/= ((_.1 . _.2))))))
)
(define (test-neq-long)
(test-neq))
(module+ main
(test-neq-long))
| null |
https://raw.githubusercontent.com/calvis/cKanren/8714bdd442ca03dbf5b1d6250904cbc5fd275e68/cKanren/tests/neq.rkt
|
racket
|
SIMPLE
MEDIUM
these test reification
this tests the constraint-interaction
HARD
|
#lang racket
(require
"../tester.rkt"
"../ck.rkt"
"../tree-unify.rkt"
"../neq.rkt"
"../matche.rkt"
"../src/operators.rkt")
(provide distincto rembero test-neq test-neq-long)
(defmatche (distincto l)
[[()]]
[[(,a)]]
[[(,a ,ad . ,dd)]
(=/= a ad)
(distincto `(,a . ,dd))
(distincto `(,ad . ,dd))])
(defmatche (rembero x ls out)
[[,x () ()]]
[[,x (,x . ,d) ,out]
(rembero x d out)]
[[,x (,a . ,d) ,out]
(=/= a x)
(fresh (res)
(rembero x d res)
(== `(,a . ,res) out))])
(define (test-neq)
(test (run* (q) (=/= 5 6)) '(_.0))
(test (run* (q) (=/= 3 3)) '())
(test (run* (q) (== q 3) (=/= 3 q))
'())
(test (run* (q) (=/= 3 q) (== q 3))
'())
(test (run* (x y) (== x y) (=/= x y))
'())
(test (run* (x y) (=/= x y) (== x y))
'())
(test (run* (q) (=/= q q))
'())
(test (run* (q) (fresh (a) (=/= a a)))
'())
(test
(run* (x y)
(=/= x y)
(== 3 x)
(== 3 y))
'())
(test
(run* (x y)
(== 3 x)
(=/= x y)
(== 3 y))
'())
(test
(run* (x y)
(== 3 x)
(== 3 y)
(=/= x y))
'())
(test
(run* (x y)
(== 3 x)
(== 3 y)
(=/= y x))
'())
(test
(run* (x y z)
(== x y)
(== y z)
(=/= x 4)
(== z (+ 2 2)))
'())
(test
(run* (x y z)
(== x y)
(== y z)
(== z (+ 2 2))
(=/= x 4))
'())
(test
(run* (x y z)
(=/= x 4)
(== y z)
(== x y)
(== z (+ 2 2)))
'())
(test
(run* (x y z)
(=/= x y)
(== x `(0 ,z 1))
(== y `(0 1 1))
(== z 1))
'())
(test
(run* (x y z)
(== z 1)
(=/= x y)
(== x `(0 ,z 1))
(== y `(0 1 1)))
'())
(test
(run* (x y z)
(== z 1)
(== x `(0 ,z 1))
(== y `(0 1 1))
(=/= x y))
'())
(test
(run* (q)
(fresh (x y z)
(=/= x y)
(== x `(0 ,z 1))
(== y `(0 1 1))
(== z 0)))
'(_.0))
(test
(run* (x y)
(=/= `(,x 1) `(2 ,y))
(== x 2)
(== y 1))
'())
(test
(run* (a x z)
(=/= a `(,x 1))
(== a `(,z 1))
(== x z))
'())
(test
(run* (x y)
(=/= `(,x 1) `(2 ,y))
(== x 2)
(== y 1))
'())
(test
(run* (q)
(fresh (x y z)
(== z 0)
(=/= x y)
(== x `(0 ,z 1))
(== y `(0 1 1))))
'(_.0))
(test
(run* (q)
(fresh (x y z)
(== x `(0 ,z 1))
(== y `(0 1 1))
(=/= x y)))
'(_.0))
(test
(run* (q)
(fresh (x y)
(=/= `(,x 1) `(2 ,y))
(== x 2)))
'(_.0))
(test
(run* (q)
(fresh (x y)
(=/= `(,x 1) `(2 ,y))
(== y 1)))
'(_.0))
(test
(run* (x y z)
(=/= `(,x 2 ,z) `(1 ,z 3))
(=/= `(,x 6 ,z) `(4 ,z 6))
(=/= `(,x ,y ,z) `(7 ,z 9))
(== x z))
'((_.0 _.1 _.0)))
(test
(run* (x y)
(=/= `(,x 1) `(2 ,y))
(== x 2)
(== y 9))
'((2 9)))
(test
(run* (q)
(fresh (a)
(== 3 a)
(=/= a 4)))
'(_.0))
(test
(run* (q) (=/= q #f))
'((_.0 : (=/= ((_.0 . #f))))))
(test
(run* (x y) (=/= x y))
'(((_.0 _.1) : (=/= ((_.0 . _.1))))))
(test
(run* (q)
(=/= q 5)
(=/= 5 q))
'((_.0 : (=/= ((_.0 . 5))))))
(test
(run* (x y)
(=/= y x))
'(((_.0 _.1) : (=/= ((_.0 . _.1))))))
(test
(run* (x y)
(=/= x y)
(=/= x y))
'(((_.0 _.1) : (=/= ((_.0 . _.1))))))
(test
(run* (x y)
(=/= x y)
(=/= y x))
'(((_.0 _.1) : (=/= ((_.0 . _.1))))))
(test
(run* (x y)
(=/= `(,x 1) `(2 ,y)))
'(((_.0 _.1) : (=/= ((_.0 . 2) (_.1 . 1))))))
(test
(run* (q)
(=/= 4 q)
(=/= 3 q))
'((_.0 : (=/= ((_.0 . 3)) ((_.0 . 4))))))
(test
(run* (q) (=/= q 5) (=/= q 5))
'((_.0 : (=/= ((_.0 . 5))))))
(test
(run* (x y)
(=/= `(,x 1) `(2 ,y))
(== x 2))
'(((2 _.0) : (=/= ((_.0 . 1))))))
(test
(run* (q)
(fresh (a x z)
(=/= a `(,x 1))
(== a `(,z 1))
(== x 5)
(== `(,x ,z) q)))
'(((5 _.0) : (=/= ((_.0 . 5))))))
(test
(run* (x y)
(=/= `(,x ,y) `(5 6))
(=/= x 5))
'(((_.0 _.1) : (=/= ((_.0 . 5))))))
(test
(run* (x y)
(=/= x 5)
(=/= `(,x ,y) `(5 6)))
'(((_.0 _.1) : (=/= ((_.0 . 5))))))
(test
(run* (x y)
(=/= 5 x)
(=/= `( ,y ,x) `(6 5)))
'(((_.0 _.1) : (=/= ((_.0 . 5))))))
(test
(run* (x)
(fresh (y z)
(=/= x `(,y 2))
(== x `(,z 2))))
'((_.0 2)))
(test
(run* (x)
(fresh (y z)
(=/= x `(,y 2))
(== x `((,z) 2))))
'(((_.0) 2)))
(test
(run* (x)
(fresh (y z)
(=/= x `((,y) 2))
(== x `(,z 2))))
'((_.0 2)))
(test
(run* (q)
(distincto `(2 3 ,q)))
'((_.0 : (=/= ((_.0 . 2)) ((_.0 . 3))))))
(test
(run* (q) (rembero 'x '() q))
'(()))
(test
(run* (q) (rembero 'x '(x) '()))
'(_.0))
(test
(run* (q) (rembero 'a '(a b a c) q))
'((b c)))
(test
(run* (q) (rembero 'a '(a b c) '(a b c)))
'())
(test
(run* (w x y z)
(=/= `(,w . ,x) `(,y . ,z)))
'(((_.0 _.1 _.2 _.3)
:
(=/= ((_.0 . _.2) (_.1 . _.3))))))
(test
(run* (w x y z)
(=/= `(,w . ,x) `(,y . ,z))
(== w y))
'(((_.0 _.1 _.0 _.2)
:
(=/= ((_.1 . _.2))))))
)
(define (test-neq-long)
(test-neq))
(module+ main
(test-neq-long))
|
70b6583d2b2a4df016cf62dd178a2f2546d8a67710b3b09b8ab2f2c2d30f6562
|
pepeiborra/narradar
|
Test-Gen.hs
|
#!/usr/bin/env runhaskell
# LANGUAGE TypeFamilies #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE TypeSynonymInstances #-}
# LANGUAGE OverlappingInstances #
# LANGUAGE UndecidableInstances #
# LANGUAGE NoMonomorphismRestriction #
import Control.Monad
import Data.Maybe
import qualified Language.Prolog.Syntax as Prolog
import Narradar
import Narradar.Types.Problem.Rewriting
import Narradar.Types.Problem.NarrowingGen
import Narradar.Processor.RPO
import Narradar.Framework.GraphViz
import Narradar . Utils
main = narradarMain listToMaybe
-- Missing dispatcher cases
instance (IsProblem typ, Pretty typ) => Dispatch (Problem typ trs) where
dispatch p = error ("missing dispatcher for problem of type " ++ show (pPrint $ getProblemType p))
instance Dispatch thing where dispatch _ = error "missing dispatcher"
-- Prolog
instance Dispatch PrologProblem where
-- dispatch = apply SKTransformInfinitary > = > dispatch
dispatch = apply SKTransformNarrowing > = > dispatch
-- Prolog
instance Dispatch PrologProblem where
-- dispatch = apply SKTransformInfinitary >=> dispatch
dispatch = apply SKTransformNarrowing >=> dispatch
-}
-- Rewriting
instance () => Dispatch (NProblem Rewriting Id) where
dispatch = mkDispatcher (sc >=> rpoPlusTransforms LPOSAF)
instance (id ~ DPIdentifier a, Pretty id, Ord a, HasTrie id) => Dispatch (NProblem IRewriting id) where
dispatch = mkDispatcher (sc >=> rpoPlusTransforms LPOSAF)
-- Narrowing Goal
instance (Pretty (DPIdentifier id), Pretty (GenId id), Ord id, HasTrie id) => Dispatch (NProblem (NarrowingGoal (DPIdentifier id)) (DPIdentifier id)) where
dispatch = apply NarrowingGoalToRelativeRewriting >=> dispatch
instance (Pretty (DPIdentifier id), Pretty (GenId id), Ord id, HasTrie id) => Dispatch (NProblem (CNarrowingGoal (DPIdentifier id)) (DPIdentifier id)) where
dispatch = apply NarrowingGoalToRelativeRewriting >=> dispatch
-- Initial Goal
type GId id = DPIdentifier (GenId id)
instance Dispatch (NProblem (InitialGoal (TermF Id) Rewriting) Id) where
dispatch = mkDispatcher (sc >=> rpoPlusTransforms LPOSAF)
instance (Pretty (GenId id), Ord id, HasTrie id) => Dispatch (NProblem (InitialGoal (TermF (GId id)) CNarrowingGen) (GId id)) where
dispatch = mkDispatcher (rpoPlusTransforms LPOSAF)
instance (Pretty (GenId id), Ord id, HasTrie id) =>
Dispatch (NProblem (InitialGoal (TermF (GId id)) NarrowingGen) (GId id)) where
dispatch = mkDispatcher (rpoPlusTransforms LPOSAF)
-- Relative
instance (Dispatch (NProblem base id)
,Pretty id, Ord id, HasTrie id
,Pretty base, Pretty (TermN id)
,IsDPProblem base, MkProblem base (NTRS id)
,PprTPDB (NProblem base id), ProblemColor (NProblem base id)
,Pretty (NProblem base id)
,HasMinimality base
) => Dispatch (NProblem (Relative (NTRS id) base) id) where
dispatch = apply RelativeToRegular >=> dispatch
sc = apply DependencyGraphSCC >=> apply SubtermCriterion
rpoPlusTransforms rpo = apply DependencyGraphSCC >=>
repeatSolver 9 (apply (RPOProc LPOAF (Yices 60))
.|. apply (RPOProc rpo (Yices 60))
.|. graphTransform >=>
apply DependencyGraphSCC
)
graphTransform = apply NarrowingP .|. apply FInstantiation .|. apply Instantiation
instance ( Pretty i d , Pretty ( DPIdentifier i d ) , i d , Lattice ( AF _ ( DPIdentifier i d ) ) ) = >
Dispatch ( DPProblem Narrowing ( NarradarTRS ( TermF ( DPIdentifier i d ) ) ) ) where
dispatch = mkDispatcher (
apply DependencyGraphCycles
> = > apply ( NarrowingToRewritingICLP08 bestHeu )
> = > apply ( AproveServer 10 Default )
)
instance (Pretty id, Pretty (DPIdentifier id), Ord id, Lattice (AF_ (DPIdentifier id))) =>
Dispatch (DPProblem Narrowing (NarradarTRS (TermF (DPIdentifier id)) Var)) where
dispatch = mkDispatcher(
apply DependencyGraphCycles
>=> apply (NarrowingToRewritingICLP08 bestHeu)
>=> apply (AproveServer 10 Default)
)
-}
| null |
https://raw.githubusercontent.com/pepeiborra/narradar/bc53dcad9aee480ab3424a75239bac67e4794456/test/Test-Gen.hs
|
haskell
|
# LANGUAGE TypeSynonymInstances #
Missing dispatcher cases
Prolog
dispatch = apply SKTransformInfinitary > = > dispatch
Prolog
dispatch = apply SKTransformInfinitary >=> dispatch
Rewriting
Narrowing Goal
Initial Goal
Relative
|
#!/usr/bin/env runhaskell
# LANGUAGE TypeFamilies #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverlappingInstances #
# LANGUAGE UndecidableInstances #
# LANGUAGE NoMonomorphismRestriction #
import Control.Monad
import Data.Maybe
import qualified Language.Prolog.Syntax as Prolog
import Narradar
import Narradar.Types.Problem.Rewriting
import Narradar.Types.Problem.NarrowingGen
import Narradar.Processor.RPO
import Narradar.Framework.GraphViz
import Narradar . Utils
main = narradarMain listToMaybe
instance (IsProblem typ, Pretty typ) => Dispatch (Problem typ trs) where
dispatch p = error ("missing dispatcher for problem of type " ++ show (pPrint $ getProblemType p))
instance Dispatch thing where dispatch _ = error "missing dispatcher"
instance Dispatch PrologProblem where
dispatch = apply SKTransformNarrowing > = > dispatch
instance Dispatch PrologProblem where
dispatch = apply SKTransformNarrowing >=> dispatch
-}
instance () => Dispatch (NProblem Rewriting Id) where
dispatch = mkDispatcher (sc >=> rpoPlusTransforms LPOSAF)
instance (id ~ DPIdentifier a, Pretty id, Ord a, HasTrie id) => Dispatch (NProblem IRewriting id) where
dispatch = mkDispatcher (sc >=> rpoPlusTransforms LPOSAF)
instance (Pretty (DPIdentifier id), Pretty (GenId id), Ord id, HasTrie id) => Dispatch (NProblem (NarrowingGoal (DPIdentifier id)) (DPIdentifier id)) where
dispatch = apply NarrowingGoalToRelativeRewriting >=> dispatch
instance (Pretty (DPIdentifier id), Pretty (GenId id), Ord id, HasTrie id) => Dispatch (NProblem (CNarrowingGoal (DPIdentifier id)) (DPIdentifier id)) where
dispatch = apply NarrowingGoalToRelativeRewriting >=> dispatch
type GId id = DPIdentifier (GenId id)
instance Dispatch (NProblem (InitialGoal (TermF Id) Rewriting) Id) where
dispatch = mkDispatcher (sc >=> rpoPlusTransforms LPOSAF)
instance (Pretty (GenId id), Ord id, HasTrie id) => Dispatch (NProblem (InitialGoal (TermF (GId id)) CNarrowingGen) (GId id)) where
dispatch = mkDispatcher (rpoPlusTransforms LPOSAF)
instance (Pretty (GenId id), Ord id, HasTrie id) =>
Dispatch (NProblem (InitialGoal (TermF (GId id)) NarrowingGen) (GId id)) where
dispatch = mkDispatcher (rpoPlusTransforms LPOSAF)
instance (Dispatch (NProblem base id)
,Pretty id, Ord id, HasTrie id
,Pretty base, Pretty (TermN id)
,IsDPProblem base, MkProblem base (NTRS id)
,PprTPDB (NProblem base id), ProblemColor (NProblem base id)
,Pretty (NProblem base id)
,HasMinimality base
) => Dispatch (NProblem (Relative (NTRS id) base) id) where
dispatch = apply RelativeToRegular >=> dispatch
sc = apply DependencyGraphSCC >=> apply SubtermCriterion
rpoPlusTransforms rpo = apply DependencyGraphSCC >=>
repeatSolver 9 (apply (RPOProc LPOAF (Yices 60))
.|. apply (RPOProc rpo (Yices 60))
.|. graphTransform >=>
apply DependencyGraphSCC
)
graphTransform = apply NarrowingP .|. apply FInstantiation .|. apply Instantiation
instance ( Pretty i d , Pretty ( DPIdentifier i d ) , i d , Lattice ( AF _ ( DPIdentifier i d ) ) ) = >
Dispatch ( DPProblem Narrowing ( NarradarTRS ( TermF ( DPIdentifier i d ) ) ) ) where
dispatch = mkDispatcher (
apply DependencyGraphCycles
> = > apply ( NarrowingToRewritingICLP08 bestHeu )
> = > apply ( AproveServer 10 Default )
)
instance (Pretty id, Pretty (DPIdentifier id), Ord id, Lattice (AF_ (DPIdentifier id))) =>
Dispatch (DPProblem Narrowing (NarradarTRS (TermF (DPIdentifier id)) Var)) where
dispatch = mkDispatcher(
apply DependencyGraphCycles
>=> apply (NarrowingToRewritingICLP08 bestHeu)
>=> apply (AproveServer 10 Default)
)
-}
|
3e153c4c3ed5975c42b0e2f2a4b0983fd1e3929278c8263a2229b9b06bba63c0
|
DATX02-17-26/DATX02-17-26
|
VarDecl.hs
|
DATX02 - 17 - 26 , automated assessment of imperative programs .
- Copyright , 2017 , see AUTHORS.md .
-
- This program is free software ; you can redistribute it and/or
- modify it under the terms of the GNU General Public License
- as published by the Free Software Foundation ; either version 2
- of the License , or ( at your option ) any later version .
-
- This program is distributed in the hope that it will be useful ,
- but WITHOUT ANY WARRANTY ; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
- GNU General Public License for more details .
-
- You should have received a copy of the GNU General Public License
- along with this program ; if not , write to the Free Software
- Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 , USA .
- Copyright, 2017, see AUTHORS.md.
-
- This program is free software; you can redistribute it and/or
- modify it under the terms of the GNU General Public License
- as published by the Free Software Foundation; either version 2
- of the License, or (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-}
# LANGUAGE LambdaCase #
-- | Normalizers for variable declarations.
module Norm.VarDecl (
-- * Normalizers
normMoveForTVD
, normSingleTVDs
, normVDIArrLeft
, normSplitInit
, normVDTop
, normSortT
-- * The executor functions:
, execMoveForTVD
, execSingleTVDs
, execVDIArrLeft
, execSplitInit
, execVDTop
, execSortT
) where
import qualified Data.Ord as O
import Data.Maybe (isNothing, fromMaybe)
import Data.List (sortBy, isPrefixOf)
import Control.Arrow ((***), (&&&), first, second)
import Control.Category ((>>>))
import Control.Lens (Traversal', (^?), (%%~), (%~), (.~))
import Control.Monad.Writer (Writer, runWriter)
import Util.Monad (traverseJ, sortByM)
import Class.Sizeables (growN)
import Norm.NormCS
stage :: Int
stage = 9 -- ALLOCATE TODO
--------------------------------------------------------------------------------
-- Exported Rules:
--------------------------------------------------------------------------------
-- | Moves the variable declarations (+ any inits) out of a basic for loop:
-- > for ( T x, [y..] ; cond ; post ) si
-- normalizes to:
-- > T x, [y..] ; for ( ; cond ; post ) si
normMoveForTVD :: NormCUR
normMoveForTVD = makeRule' "vardecl.stmt.move_bfor_tvd" [stage] execMoveForTVD
-- | Split variable declarations
-- > { T x [= e], y [= e], .. ; }
-- into:
-- > { T x [= e]; T y [= e] ; .. }
normSingleTVDs :: NormCUR
normSingleTVDs = makeRule' "vardecl.stmt.to_single" [stage + 1] execSingleTVDs
| Move array dimensions in VarDeclId to the type , i.e :
-- > T x[].. ; ==> T[].. x ;
-- Requires that "vardecl.stmt.to_single" has been run before.
normVDIArrLeft :: NormCUR
normVDIArrLeft = makeRule' "vardecl.stmt.array_type" [stage + 2] execVDIArrLeft
| Split variable declaration and initialization into 2 statements .
normSplitInit :: NormCUR
normSplitInit = makeRule' "vardecl.stmt.init_split" [stage + 3] execSplitInit
-- | Moves all variable declarations (without initializers) to the top.
-- The AST must be alpha renamed right before this is executed to preserve
-- type correctness.
normVDTop :: NormCUR
normVDTop = makeRule' "vardecl.stmt.move_to_top" [stage + 4] execVDTop
-- | Sort variable declarations by type.
-- Will not sort any declarator that has initializer.
-- The sorting MUST be stable.
normSortT :: NormCUR
normSortT = makeRule' "vardecl.stmt.decl_sort_by_type" [stage + 5] execSortT
--------------------------------------------------------------------------------
-- vardecl.stmt.move_bfor_tvd:
--------------------------------------------------------------------------------
execMoveForTVD :: NormCUA
execMoveForTVD = normEvery $ traverseJ $ \x -> case x of
SForB (Just (FIVars tvd)) me mps si ->
change [SVars tvd, sForInit .~ Nothing $ x]
x -> unique [x]
--------------------------------------------------------------------------------
-- vardecl.stmt.to_single:
--------------------------------------------------------------------------------
execSingleTVDs :: NormCUA
execSingleTVDs = normEvery $ traverseJ $ \case
SVars (TypedVVDecl t vds) | length vds > 1 ->
change $ SVars . TypedVVDecl t . pure <$> vds
x -> unique [x]
--------------------------------------------------------------------------------
vardecl.stmt.array_type :
--------------------------------------------------------------------------------
execVDIArrLeft :: NormCUA
execVDIArrLeft = normEvery $ withError' $ \case
(TypedVVDecl vmt [vd]) -> do
(vdi, mvi) <- mayDecline $ vd ^? _VarDecl
(vdi', dim) <- first VarDId <$> mayDecline (vdi ^? _VarDArr)
let vmt' = vmType %~ growN (fromInteger dim) $ vmt
change $ TypedVVDecl vmt' [VarDecl vdi' mvi]
x -> unique x
--------------------------------------------------------------------------------
-- vardecl.stmt.init_split:
--------------------------------------------------------------------------------
execSplitInit :: NormCUA
execSplitInit = normEvery $ traverseJ $ \case
s@(SVars (TypedVVDecl t [vd])) -> splitVD' t vd [s]
x -> unique [x]
-- | VarInit to an Expr.
viToExpr :: VMType -> VarDeclId -> VarInit -> NormE Expr
viToExpr vmt vdi vi = do
(baseT, dims) <- mayDecline $ (typeBase &&& typeDimens) <$> vmt ^? vmType
let dims' = fromMaybe 0 $ vdi ^? vdiDimen
case vi of
InitExpr e -> change e
InitArr a -> change $ EArrNewI baseT (dims + dims') a
HoleVarInit h -> decline
| VarDeclId to an LValue .
vdiToLV :: VarDeclId -> NormE LValue
vdiToLV = mayDecline . fmap singVar . (^? vdiIdent)
splitVD' :: VMType -> VarDecl -> NormArr [Stmt]
splitVD' vmt vd = withError $ \_ -> splitVD vmt vd
isFinal :: VMType -> Maybe Bool
isFinal = fmap (VMFinal ==) . (^? vmMod)
splitVD :: VMType -> VarDecl -> NormE [Stmt]
splitVD vmt vd = do
mayDecline (isFinal vmt) >>= (`when` decline) -- can't split final.
(vdi, mvi) <- mayDecline $ vd ^? _VarDecl
exp <- mayDecline mvi >>= viToExpr vmt vdi
lv <- vdiToLV vdi >>= change
pure [ SVars $ TypedVVDecl vmt [VarDecl vdi Nothing]
, SExpr $ EAssign lv exp
]
--------------------------------------------------------------------------------
-- vardecl.stmt.decl_sort_by_type:
--------------------------------------------------------------------------------
execSortT :: NormCUA
execSortT = normEvery $ sortByM $ curry $ (varType *** varType) >>> \case
(Nothing, Nothing) -> pure O.EQ
(Just t1, Nothing) -> pure O.LT
(Nothing, Just t2) -> change O.GT
(Just t1, Just t2) -> let o = compare t1 t2
in if o == O.GT then change o else pure o
varType :: Stmt -> Maybe Type
varType s = extTVD s >>= \tvd -> ensureMovable tvd >> fst tvd ^? vmType
extTVD :: Stmt -> Maybe (VMType, [VarDecl])
extTVD = (^? sVDecl . _TypedVVDecl)
ensureMovable :: (VMType, [VarDecl]) -> Maybe ()
ensureMovable (vmt, vds) = do
final <- isFinal vmt
hasNoInits <- all isNothing <$> forM vds (^? vdVInit)
when (final || not hasNoInits) Nothing
--------------------------------------------------------------------------------
-- vardecl.stmt.move_to_top:
--------------------------------------------------------------------------------
travMD :: Traversal' CompilationUnit MemberDecl
travMD = cuTDecls.traverse.tdClass.cdBody.cbDecls.traverse.declMem
execVDTop :: NormCUA
execVDTop = travMD.mdBlock.bStmts %%~ vdMove
vdMove :: NormArr [Stmt]
vdMove ss = let (ssF, ssT) = second reverse $ runWriter (normEveryT vdSteal ss)
in (if ssT `isPrefixOf` ss then unique else change) $ ssT ++ ssF
vdSteal :: [Stmt] -> Writer [Stmt] [Stmt]
vdSteal = filterM $ \s -> maybe (pure True) (const $ tell [s] >> pure False) $
extTVD s >>= ensureMovable
| null |
https://raw.githubusercontent.com/DATX02-17-26/DATX02-17-26/f5eeec0b2034d5b1adcc66071f8cb5cd1b089acb/libsrc/Norm/VarDecl.hs
|
haskell
|
| Normalizers for variable declarations.
* Normalizers
* The executor functions:
ALLOCATE TODO
------------------------------------------------------------------------------
Exported Rules:
------------------------------------------------------------------------------
| Moves the variable declarations (+ any inits) out of a basic for loop:
> for ( T x, [y..] ; cond ; post ) si
normalizes to:
> T x, [y..] ; for ( ; cond ; post ) si
| Split variable declarations
> { T x [= e], y [= e], .. ; }
into:
> { T x [= e]; T y [= e] ; .. }
> T x[].. ; ==> T[].. x ;
Requires that "vardecl.stmt.to_single" has been run before.
| Moves all variable declarations (without initializers) to the top.
The AST must be alpha renamed right before this is executed to preserve
type correctness.
| Sort variable declarations by type.
Will not sort any declarator that has initializer.
The sorting MUST be stable.
------------------------------------------------------------------------------
vardecl.stmt.move_bfor_tvd:
------------------------------------------------------------------------------
------------------------------------------------------------------------------
vardecl.stmt.to_single:
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
vardecl.stmt.init_split:
------------------------------------------------------------------------------
| VarInit to an Expr.
can't split final.
------------------------------------------------------------------------------
vardecl.stmt.decl_sort_by_type:
------------------------------------------------------------------------------
------------------------------------------------------------------------------
vardecl.stmt.move_to_top:
------------------------------------------------------------------------------
|
DATX02 - 17 - 26 , automated assessment of imperative programs .
- Copyright , 2017 , see AUTHORS.md .
-
- This program is free software ; you can redistribute it and/or
- modify it under the terms of the GNU General Public License
- as published by the Free Software Foundation ; either version 2
- of the License , or ( at your option ) any later version .
-
- This program is distributed in the hope that it will be useful ,
- but WITHOUT ANY WARRANTY ; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
- GNU General Public License for more details .
-
- You should have received a copy of the GNU General Public License
- along with this program ; if not , write to the Free Software
- Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 , USA .
- Copyright, 2017, see AUTHORS.md.
-
- This program is free software; you can redistribute it and/or
- modify it under the terms of the GNU General Public License
- as published by the Free Software Foundation; either version 2
- of the License, or (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-}
# LANGUAGE LambdaCase #
module Norm.VarDecl (
normMoveForTVD
, normSingleTVDs
, normVDIArrLeft
, normSplitInit
, normVDTop
, normSortT
, execMoveForTVD
, execSingleTVDs
, execVDIArrLeft
, execSplitInit
, execVDTop
, execSortT
) where
import qualified Data.Ord as O
import Data.Maybe (isNothing, fromMaybe)
import Data.List (sortBy, isPrefixOf)
import Control.Arrow ((***), (&&&), first, second)
import Control.Category ((>>>))
import Control.Lens (Traversal', (^?), (%%~), (%~), (.~))
import Control.Monad.Writer (Writer, runWriter)
import Util.Monad (traverseJ, sortByM)
import Class.Sizeables (growN)
import Norm.NormCS
stage :: Int
normMoveForTVD :: NormCUR
normMoveForTVD = makeRule' "vardecl.stmt.move_bfor_tvd" [stage] execMoveForTVD
normSingleTVDs :: NormCUR
normSingleTVDs = makeRule' "vardecl.stmt.to_single" [stage + 1] execSingleTVDs
| Move array dimensions in VarDeclId to the type , i.e :
normVDIArrLeft :: NormCUR
normVDIArrLeft = makeRule' "vardecl.stmt.array_type" [stage + 2] execVDIArrLeft
| Split variable declaration and initialization into 2 statements .
normSplitInit :: NormCUR
normSplitInit = makeRule' "vardecl.stmt.init_split" [stage + 3] execSplitInit
normVDTop :: NormCUR
normVDTop = makeRule' "vardecl.stmt.move_to_top" [stage + 4] execVDTop
normSortT :: NormCUR
normSortT = makeRule' "vardecl.stmt.decl_sort_by_type" [stage + 5] execSortT
execMoveForTVD :: NormCUA
execMoveForTVD = normEvery $ traverseJ $ \x -> case x of
SForB (Just (FIVars tvd)) me mps si ->
change [SVars tvd, sForInit .~ Nothing $ x]
x -> unique [x]
execSingleTVDs :: NormCUA
execSingleTVDs = normEvery $ traverseJ $ \case
SVars (TypedVVDecl t vds) | length vds > 1 ->
change $ SVars . TypedVVDecl t . pure <$> vds
x -> unique [x]
vardecl.stmt.array_type :
execVDIArrLeft :: NormCUA
execVDIArrLeft = normEvery $ withError' $ \case
(TypedVVDecl vmt [vd]) -> do
(vdi, mvi) <- mayDecline $ vd ^? _VarDecl
(vdi', dim) <- first VarDId <$> mayDecline (vdi ^? _VarDArr)
let vmt' = vmType %~ growN (fromInteger dim) $ vmt
change $ TypedVVDecl vmt' [VarDecl vdi' mvi]
x -> unique x
execSplitInit :: NormCUA
execSplitInit = normEvery $ traverseJ $ \case
s@(SVars (TypedVVDecl t [vd])) -> splitVD' t vd [s]
x -> unique [x]
viToExpr :: VMType -> VarDeclId -> VarInit -> NormE Expr
viToExpr vmt vdi vi = do
(baseT, dims) <- mayDecline $ (typeBase &&& typeDimens) <$> vmt ^? vmType
let dims' = fromMaybe 0 $ vdi ^? vdiDimen
case vi of
InitExpr e -> change e
InitArr a -> change $ EArrNewI baseT (dims + dims') a
HoleVarInit h -> decline
| VarDeclId to an LValue .
vdiToLV :: VarDeclId -> NormE LValue
vdiToLV = mayDecline . fmap singVar . (^? vdiIdent)
splitVD' :: VMType -> VarDecl -> NormArr [Stmt]
splitVD' vmt vd = withError $ \_ -> splitVD vmt vd
isFinal :: VMType -> Maybe Bool
isFinal = fmap (VMFinal ==) . (^? vmMod)
splitVD :: VMType -> VarDecl -> NormE [Stmt]
splitVD vmt vd = do
(vdi, mvi) <- mayDecline $ vd ^? _VarDecl
exp <- mayDecline mvi >>= viToExpr vmt vdi
lv <- vdiToLV vdi >>= change
pure [ SVars $ TypedVVDecl vmt [VarDecl vdi Nothing]
, SExpr $ EAssign lv exp
]
execSortT :: NormCUA
execSortT = normEvery $ sortByM $ curry $ (varType *** varType) >>> \case
(Nothing, Nothing) -> pure O.EQ
(Just t1, Nothing) -> pure O.LT
(Nothing, Just t2) -> change O.GT
(Just t1, Just t2) -> let o = compare t1 t2
in if o == O.GT then change o else pure o
varType :: Stmt -> Maybe Type
varType s = extTVD s >>= \tvd -> ensureMovable tvd >> fst tvd ^? vmType
extTVD :: Stmt -> Maybe (VMType, [VarDecl])
extTVD = (^? sVDecl . _TypedVVDecl)
ensureMovable :: (VMType, [VarDecl]) -> Maybe ()
ensureMovable (vmt, vds) = do
final <- isFinal vmt
hasNoInits <- all isNothing <$> forM vds (^? vdVInit)
when (final || not hasNoInits) Nothing
travMD :: Traversal' CompilationUnit MemberDecl
travMD = cuTDecls.traverse.tdClass.cdBody.cbDecls.traverse.declMem
execVDTop :: NormCUA
execVDTop = travMD.mdBlock.bStmts %%~ vdMove
vdMove :: NormArr [Stmt]
vdMove ss = let (ssF, ssT) = second reverse $ runWriter (normEveryT vdSteal ss)
in (if ssT `isPrefixOf` ss then unique else change) $ ssT ++ ssF
vdSteal :: [Stmt] -> Writer [Stmt] [Stmt]
vdSteal = filterM $ \s -> maybe (pure True) (const $ tell [s] >> pure False) $
extTVD s >>= ensureMovable
|
9b2c39c6e7b0a2de090b88da84d47030e1f3bf5b329e9d9ca7a5f8fca1724bac
|
samrushing/irken-compiler
|
t8.scm
|
(include "lib/core.scm")
(let ((x 7)
(y 3))
(+ x y))
| null |
https://raw.githubusercontent.com/samrushing/irken-compiler/690da48852d55497f873738df54f14e8e135d006/vm/tests/t8.scm
|
scheme
|
(include "lib/core.scm")
(let ((x 7)
(y 3))
(+ x y))
|
|
91f82dd96cb7493f6a3416b4f0589aeaa64431980fc2324b7448856a57b95a46
|
crategus/cl-cffi-gtk
|
gtk.menu-item.lisp
|
;;; ----------------------------------------------------------------------------
;;; gtk.menu-item.lisp
;;;
;;; The documentation of this file is taken from the GTK 3 Reference Manual
Version 3.24 and modified to document the Lisp binding to the GTK library .
;;; See <>. The API documentation of the Lisp binding is
available from < -cffi-gtk/ > .
;;;
Copyright ( C ) 2009 - 2011
Copyright ( C ) 2011 - 2021
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU Lesser General Public License for Lisp
as published by the Free Software Foundation , either version 3 of the
;;; License, or (at your option) any later version and with a preamble to
the GNU Lesser General Public License that clarifies the terms for use
;;; with Lisp programs and is referred as the LLGPL.
;;;
;;; 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 .
;;;
You should have received a copy of the GNU Lesser General Public
License along with this program and the preamble to the Gnu Lesser
;;; General Public License. If not, see </>
;;; and <>.
;;; ----------------------------------------------------------------------------
;;;
;;; GtkMenuItem
;;;
;;; The widget used for item in menus.
;;;
;;; Types and Values
;;;
;;; GtkMenuItem
;;;
;;; Functions
;;;
gtk_menu_item_new
;;; gtk_menu_item_new_with_label
;;; gtk_menu_item_new_with_mnemonic
;;; gtk_menu_item_set_right_justified
;;; gtk_menu_item_get_right_justified
;;; gtk_menu_item_get_label
;;; gtk_menu_item_set_label
;;; gtk_menu_item_get_use_underline
;;; gtk_menu_item_set_use_underline
;;; gtk_menu_item_set_submenu
;;; gtk_menu_item_get_submenu
;;; gtk_menu_item_set_accel_path
;;; gtk_menu_item_get_accel_path
gtk_menu_item_select
gtk_menu_item_deselect
;;; gtk_menu_item_activate
;;; gtk_menu_item_toggle_size_request
;;; gtk_menu_item_toggle_size_allocate
;;; gtk_menu_item_get_reserve_indicator
;;; gtk_menu_item_set_reserve_indicator
;;;
;;; Properties
;;;
gchar * accel - path Read / Write
;;; gchar* label Read / Write
;;; gboolean right-justified Read / Write
;;; GtkMenu* submenu Read / Write
;;; gboolean use-underline Read / Write
;;;
;;; Style Properties
;;;
;;; gfloat arrow-scaling Read
;;; gint arrow-spacing Read
;;; gint horizontal-padding Read
;;; GtkShadowType selected-shadow-type Read
;;; gint toggle-spacing Read
;;; gint width-chars Read
;;;
;;; Signals
;;;
;;; void activate Action
;;; void activate-item Run First
;;; void deselect Run First
;;; void select Run First
;;; void toggle-size-allocate Run First
void toggle - size - request Run First
;;;
;;; Object Hierarchy
;;;
;;; GObject
;;; ╰── GInitiallyUnowned
╰ ─ ─
╰ ─ ─ GtkContainer
╰ ─ ─
;;; ╰── GtkMenuItem
├ ─ ─
;;; ├── GtkImageMenuItem
├ ─ ─
;;; ╰── GtkTearoffMenuItem
;;;
;;; Implemented Interfaces
;;;
GtkMenuItem implements AtkImplementorIface , GtkBuildable , GtkActivatable
and GtkActionable .
;;; ----------------------------------------------------------------------------
(in-package :gtk)
;;; ----------------------------------------------------------------------------
;;; struct GtkMenuItem
;;; ----------------------------------------------------------------------------
(define-g-object-class "GtkMenuItem" gtk-menu-item
(:superclass gtk-bin
:export t
:interfaces ("AtkImplementorIface"
"GtkBuildable"
"GtkActivatable")
:type-initializer "gtk_menu_item_get_type")
((accel-path
gtk-menu-item-accel-path
"accel-path" "gchararray" t t)
(label
gtk-menu-item-label "label" "gchararray" t t)
(right-justified
gtk-menu-item-right-justified
"right-justified" "gboolean" t t)
(submenu
gtk-menu-item-submenu
"submenu" "GtkMenu" t t)
(use-underline
gtk-menu-item-use-underline
"use-underline" "gboolean" t t)))
#+cl-cffi-gtk-documentation
(setf (documentation 'gtk-menu-item 'type)
"@version{*2021-11-13}
@begin{short}
The @sym{gtk-menu-item} widget and the derived widgets are the only valid
childs for menus. Their function is to correctly handle highlighting,
alignment, events and submenus.
@end{short}
As it derives from the @class{gtk-bin} class it can hold any valid child
widget, although only a few are really useful.
@begin[GtkMenuItem as GtkBuildable]{dictionary}
The @sym{gtk-menu-item} implementation of the @class{gtk-buildable}
interface supports adding a submenu by specifying @code{\"submenu\"} as the
@code{\"type\"} attribute of a @code{<child>} element.
@b{Example:} A UI definition fragment with submenus.
@begin{pre}
<object class=\"GtkMenuItem\">
<child type=\"submenu\">
<object class=\"GtkMenu\"/>
</child>
</object>
@end{pre}
@end{dictionary}
@begin[CSS nodes]{dictionary}
@begin{pre}
menuitem
├── <child>
╰── [arrow.right]
@end{pre}
The @sym{gtk-menu-item} class has a single CSS node with name
@code{menuitem}. If the menu item has a submenu, it gets another CSS node
with name @code{arrow}, which has the @code{.left} or @code{.right} style
class.
@end{dictionary}
@begin[Style Property Details]{dictionary}
@begin[code]{table}
@begin[arrow-scaling]{entry}
The @code{arrow-scaling} style property of type @code{:float} (Read)
@br{}
Amount of space used up by arrow, relative to the font size of the menu
item. @br{}
@em{Warning:} The @code{arrow-scaling} style property has been
deprecated since version 3.20 and should not be used in newly written
code. Use the standard min-width/min-height CSS properties on the arrow
node. The value of this style property is ignored. @br{}
Allowed values: [0,2] @br{}
Default value: 0.8
@end{entry}
@begin[arrow-spacing]{entry}
The @code{arrow-spacing} style property of type @code{:int} (Read) @br{}
Space between label and arrow. @br{}
@em{Warning:} The @code{arrow-spacing} style property has been
deprecated since version 3.20 and should not be used in newly written
code. Use the standard margin CSS property on the arrow node. The value
of this style property is ignored. @br{}
Allowed values: >= 0 @br{}
Default value: 10
@end{entry}
@begin[horizontal-padding]{entry}
The @code{horizontal-padding} style property of type @code{:int} (Read)
@br{}
Padding to left and right of the menu item. @br{}
@em{Warning:} The @code{horizontal-padding} style property has been
deprecated since version 3.8 and should not be used in newly written
code. Use the standard padding CSS property, through objects like
@class{gtk-style-context} and @class{gtk-css-provider}. The value of
this style property is ignored. @br{}
Allowed values: >= 0 @br{}
Default value: 3
@end{entry}
@begin[selected-shadow-type]{entry}
The @code{selected-shadow-type} style property of type
@symbol{gtk-shadow-type} (Read) @br{}
Shadow type when the menu item is selected. @br{}
@em{Warning:} The @code{selected-shadow-type} style property has been
deprecated since version 3.20 and should not be used in newly written
code. Use CSS to determine the shadow. The value of this style property
is ignored. @br{}
Default value: @code{:none}
@end{entry}
@begin[toggle-spacing]{entry}
The @code{toggle-spacing} style property of type @code{:int} (Read)@br{}
Space between icon and label. @br{}
@em{Warning:} The @code{toggle-spacing} style property has been
deprecated since version 3.20 and should not be used in newly written
code. Use the standard margin CSS property on the check or radio nodes.
The value of this style property is ignored. @br{}
Allowed values: >= 0 @br{}
Default value: 5
@end{entry}
@begin[width-chars]{entry}
The @code{width-chars} style property of type @code{:int} (Read) @br{}
The minimum desired width of the menu item in characters. @br{}
@em{Warning:} The @code{width-chars} style property has been deprecated
since version 3.20 and should not be used in newly written code. Use the
standard CSS property min-width. The value of this style property is
ignored. @br{}
Allowed values: >= 0 @br{}
Default value: 12
@end{entry}
@end{table}
@end{dictionary}
@begin[Signal Details]{dictionary}
@subheading{The \"activate\" signal}
@begin{pre}
lambda (item) :action
@end{pre}
Emitted when the menu item is activated.
@begin[code]{table}
@entry[item]{The @sym{gtk-menu-item} widget which received the signal.}
@end{table}
@subheading{The \"activate-item\" signal}
@begin{pre}
lambda (item) :run-first
@end{pre}
Emitted when the menu item is activated, but also if the menu item has a
submenu. For normal applications, the relevant signal is \"activate\".
@begin[code]{table}
@entry[item]{The @sym{gtk-menu-item} widget which received the signal.}
@end{table}
@subheading{The \"deselect\" signal}
@begin{pre}
lambda (item) :run-first
@end{pre}
@begin[code]{table}
@entry[item]{The @sym{gtk-menu-item} widget which received the signal.}
@end{table}
@subheading{The \"select\" signal}
@begin{pre}
lambda (item) :run-first
@end{pre}
@begin[code]{table}
@entry[item]{The @sym{gtk-menu-item} widget which received the signal.}
@end{table}
@subheading{The \"toggle-size-allocate\" signal}
@begin{pre}
lambda (item arg) :run-first
@end{pre}
@begin[code]{table}
@entry[item]{The @sym{gtk-menu-item} widget which received the signal.}
@entry[arg]{An integer which is not documented.}
@end{table}
@subheading{The \"toggle-size-request\" signal}
@begin{pre}
lambda (item arg) :run-first
@end{pre}
@begin[code]{table}
@entry[item]{The @sym{gtk-menu-item} widget which received the signal.}
@entry[arg]{A pointer which is not documented.}
@end{table}
@end{dictionary}
@see-slot{gtk-menu-item-accel-path}
@see-slot{gtk-menu-item-label}
@see-slot{gtk-menu-item-right-justified}
@see-slot{gtk-menu-item-submenu}
@see-slot{gtk-menu-item-use-underline}
@see-class{gtk-bin}
@see-class{gtk-menu-shell}")
;;; ----------------------------------------------------------------------------
;;; Property and Accessor Details
;;; ----------------------------------------------------------------------------
;;; --- gtk-menu-item-accel-path -----------------------------------------------
#+cl-cffi-gtk-documentation
(setf (documentation (atdoc:get-slot-from-name "accel-path" 'gtk-menu-item) 't)
"The @code{accel-path} property of type @code{:string} (Read / Write) @br{}
Sets the accelerator path of the menu item, through which runtime changes of
the accelerator of the menu item caused by the user can be identified and
saved to persistant storage. @br{}
Default value: @code{nil}")
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-menu-item-accel-path atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-menu-item-accel-path 'function)
"@version{2021-11-13}
@syntax[]{(gtk-menu-item-accel-path object) => path}
@syntax[]{(setf (gtk-menu-item-accel-path object) path)}
@argument[item]{a valid @class{gtk-menu-item} widget}
@argument[path]{a string with the accelerator path, corresponding to
this functionality of the menu item, or @code{nil} to unset the current
path}
@begin{short}
Accessor of the @slot[gtk-menu-item]{accel-path} slot of the
@class{gtk-menu-item} class.
@end{short}
The @sym{gtk-menu-item-accel-path} slot access function retrieve the
accelerator path that was previously set on the menu item. The
@sym{(setf gtk-menu-item-accel-path)} slot access function sets the
accelerator path on the menu item, through which runtime changes of the
accelerator of the menu item caused by the user can be identified and saved to
persistent storage, see the @fun{gtk-accel-map-save} function on this.
To set up a default accelerator for this menu item, call the
@fun{gtk-accel-map-add-entry} function with the same @arg{path}. See
also the @fun{gtk-accel-map-add-entry} function on the specifics of
accelerator paths, and the @fun{gtk-menu-accel-path} function for a more
convenient variant of this function.
This function is basically a convenience wrapper that handles calling
the @fun{gtk-widget-set-accel-path} function with the appropriate accelerator
group for the menu item.
Note that you do need to set an accelerator on the parent menu with the
@fun{gtk-menu-accel-group} function for this to work.
@see-class{gtk-menu-item}
@see-function{gtk-accel-map-save}
@see-function{gtk-accel-map-add-entry}
@see-function{gtk-menu-accel-path}
@see-function{gtk-menu-accel-group}
@see-function{gtk-widget-set-accel-path}")
;;; --- gtk-menu-item-label ----------------------------------------------------
#+cl-cffi-gtk-documentation
(setf (documentation (atdoc:get-slot-from-name "label" 'gtk-menu-item) 't)
"The @code{label} property of type @code{:string} (Read / Write) @br{}
The text for the child label. @br{}
Default value: \"\"")
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-menu-item-label atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-menu-item-label 'function)
"@version{2021-11-13}
@syntax[]{(gtk-menu-item-label object) => label}
@syntax[]{(setf (gtk-menu-item-label object) label)}
@argument[object]{a @class{gtk-menu-item} widget}
@argument[label]{a string with the text you want to set}
@begin{short}
Accessor of the @slot[gtk-menu-item]{label} slot of the
@class{gtk-menu-item} class.
@end{short}
The @sym{gtk-menu-item-label} slot access function gets the text on the menu
item label. The @sym{(setf gtk-menu-item-label)} slot access function sets
the text.
@see-class{gtk-menu-item}")
;;; --- gtk-menu-item-right-justified ------------------------------------------
#+cl-cffi-gtk-documentation
(setf (documentation (atdoc:get-slot-from-name "right-justified"
'gtk-menu-item) 't)
"The @code{right-justified} property of type @code{:boolean} (Read / Write)
@br{}
Sets whether the menu item appears justified at the right side of a menu
bar. @br{}
Default value: @em{false}")
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-menu-item-right-justified atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-menu-item-right-justified 'function)
"@version{2021-11-13}
@syntax[]{(gtk-menu-item-right-justified object) => justified}
@syntax[]{(setf (gtk-menu-item-right-justified object) justified)}
@argument[item]{a @class{gtk-menu-item} widget}
@argument[justified]{if @em{true} the menu item will appear at the far right
if added to a menu bar}
@begin{short}
Accessor of the @slot[gtk-menu-item]{right-justified} slot of the
@class{gtk-menu-item} class.
@end{short}
The @sym{gtk-menu-item-right-justified} slot access function gets whether the
menu item appears justified at the right side of the menu bar. The
@sym{(setf gtk-menu-item-right-justified)} slot access function sets whether
the menu item appears justified at the right side.
This was traditionally done for \"Help\" menu items, but is now considered a
bad idea. If the widget layout is reversed for a right-to-left language like
Hebrew or Arabic, right-justified menu items appear at the left.
@begin[Warning]{dictionary}
The @sym{gtk-menu-item-right-justified} function has been deprecated since
version 3.2 and should not be used in newly written code. If you insist on
using it, use the @fun{gtk-widget-hexpand} and @fun{gtk-widget-halign}
functions.
@end{dictionary}
@see-class{gtk-menu-item}
@see-function{gtk-widget-halign}
@see-function{gtk-widget-hexpand}")
;;; --- gtk-menu-item-submenu --------------------------------------------------
#+cl-cffi-gtk-documentation
(setf (documentation (atdoc:get-slot-from-name "submenu" 'gtk-menu-item) 't)
"The @code{submenu} property of type @class{gtk-menu} (Read / Write) @br{}
The submenu attached to the menu item, or @code{nil} if it has none.")
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-menu-item-submenu atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-menu-item-submenu 'function)
"@version{2021-11-13}
@syntax[]{(gtk-menu-item-submenu object) => submenu}
@syntax[]{(setf (gtk-menu-item-submenu object) submenu)}
@argument[object]{a @class{gtk-menu-item} widget}
@argument[submenu]{a @class{gtk-menu} submenu, or @code{nil}}
@begin{short}
Accessor of the @slot[gtk-menu-item]{submenu} slot of the
@class{gtk-menu-item} class.
@end{short}
The @sym{gtk-menu-item-submenu} slot access function gets the submenu
underneath this menu item, if any. The @sym{(setf gtk-menu-item-submenu)} slot
access function sets or replaces the submenu of the menu item, or removes it
when a @code{nil} submenu is passed.
@see-class{gtk-menu-item}
@see-class{gtk-menu}")
;;; --- gtk-menu-item-use-underline --------------------------------------------
#+cl-cffi-gtk-documentation
(setf (documentation (atdoc:get-slot-from-name "use-underline"
'gtk-menu-item) 't)
"The @code{use-underline} property of type @code{:boolean} (Read / Write) @br{}
@em{True} if underlines in the text indicate mnemonics. @br{}
Default value: @em{false}")
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-menu-item-use-underline atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-menu-item-use-underline 'function)
"@version{2021-11-13}
@syntax[]{(gtk-menu-item-use-underline object) => setting}
@syntax[]{(setf (gtk-menu-item-use-underline object) setting)}
@argument[item]{a @class{gtk-menu-item} widget}
@argument[setting]{@em{true} if underlines in the text indicate mnemonics}
@begin{short}
Accessor of the @slot[gtk-menu-item]{use-underline} slot of the
@class{gtk-menu-item} class.
@end{short}
The @sym{gtk-menu-item-use-underline} slot access function checks if an
underline in the text indicates the next character should be used for the
mnemonic accelerator key. If @em{true}, an underline in the text indicates
the next character should be used for the mnemonic accelerator key.
@see-class{gtk-menu-item}")
;;; ----------------------------------------------------------------------------
;;; gtk_menu_item_new ()
;;; ----------------------------------------------------------------------------
(declaim (inline gtk-menu-item-new))
(defun gtk-menu-item-new ()
#+cl-cffi-gtk-documentation
"@version{2021-11-13}
@return{The newly created @class{gtk-menu-item} widget.}
@begin{short}
Creates a new menu item.
@end{short}
@see-class{gtk-menu-item}"
(make-instance 'gtk-menu-item))
(export 'gtk-menu-item-new)
;;; ----------------------------------------------------------------------------
;;; gtk_menu_item_new_with_label ()
;;; ----------------------------------------------------------------------------
(declaim (inline gtk-menu-item-new-with-label))
(defun gtk-menu-item-new-with-label (label)
#+cl-cffi-gtk-documentation
"@version{2021-11-13}
@argument[label]{a string with the text for the label}
@return{The newly created @class{gtk-menu-item} widget.}
@begin{short}
Creates a new menu item whose child is a @class{gtk-label} widget.
@end{short}
@see-class{gtk-menu-item}
@see-class{gtk-label}
@see-function{gtk-menu-item-new-with-mnemonic}"
(make-instance 'gtk-menu-item
:label label))
(export 'gtk-menu-item-new-with-label)
;;; ----------------------------------------------------------------------------
;;; gtk_menu_item_new_with_mnemonic ()
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_menu_item_new_with_mnemonic" gtk-menu-item-new-with-mnemonic)
(g-object gtk-menu-item)
#+cl-cffi-gtk-documentation
"@version{2021-11-13}
@argument[label]{a string with the text of the button, with an underscore in
front of the mnemonic character}
@return{A new @class{gtk-menu-item} widget.}
@begin{short}
Creates a new menu item containing a label.
@end{short}
The label will be created using the @fun{gtk-label-new-with-mnemonic}
function, so underscores in label indicate the mnemonic for the menu item.
@see-class{gtk-menu-item}
@see-function{gtk-menu-item-new-with-label}
@see-function{gtk-label-new-with-mnemonic}"
(label :string))
(export 'gtk-menu-item-new-with-mnemonic)
;;; ----------------------------------------------------------------------------
gtk_menu_item_select ( )
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_menu_item_select" gtk-menu-item-select) :void
#+cl-cffi-gtk-documentation
"@version{2021-11-13}
@argument[item]{a @class{gtk-menu-item} widget}
@begin{short}
Emits the \"select\" signal on the given menu item.
@end{short}
@see-class{gtk-menu-item}
@see-function{gtk-menu-item-deselect}"
(item (g-object gtk-menu-item)))
(export 'gtk-menu-item-select)
;;; ----------------------------------------------------------------------------
gtk_menu_item_deselect ( )
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_menu_item_deselect" gtk-menu-item-deselect) :void
#+cl-cffi-gtk-documentation
"@version{2021-11-13}
@argument[item]{a @class{gtk-menu-item} widget}
@begin{short}
Emits the \"deselect\" signal on the given menu item.
@end{short}
@see-class{gtk-menu-item}
@see-function{gtk-menu-item-select}"
(item (g-object gtk-menu-item)))
(export 'gtk-menu-item-deselect)
;;; ----------------------------------------------------------------------------
;;; gtk_menu_item_activate ()
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_menu_item_activate" gtk-menu-item-activate) :void
#+cl-cffi-gtk-documentation
"@version{2021-11-13}
@argument[item]{a @class{gtk-menu-item} widget}
@begin{short}
Emits the \"activate\" signal on the given menu item.
@end{short}
@see-class{gtk-menu-item}"
(item (g-object gtk-menu-item)))
(export 'gtk-menu-item-activate)
;;; ----------------------------------------------------------------------------
;;; gtk_menu_item_toggle_size_request ()
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_menu_item_toggle_size_request" gtk-menu-item-toggle-size-request)
:void
#+cl-cffi-gtk-documentation
"@version{2021-11-13}
@argument[item]{a @class{gtk-menu-item} widget}
@argument[requisition]{an integer with the requisition to use as signal data}
@begin{short}
Emits the \"toggle-size-request\" signal on the given menu item.
@end{short}
@see-class{gtk-menu-item}
@see-function{gtk-menu-item-toggle-size-allocate}"
(item (g-object gtk-menu-item))
(requisition :int))
(export 'gtk-menu-item-toggle-size-request)
;;; ----------------------------------------------------------------------------
;;; gtk_menu_item_toggle_size_allocate ()
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_menu_item_toggle_size_allocate"
gtk-menu-item-toggle-size-allocate) :void
#+cl-cffi-gtk-documentation
"@version{2021-11-13}
@argument[item]{a @class{gtk-menu-item} widget}
@argument[allocation]{an integer with the allocation to use as signal data}
@begin{short}
Emits the \"toggle-size-allocate\" signal on the given item.
@end{short}
@see-class{gtk-menu-item}
@see-function{gtk-menu-item-toggle-size-request}"
(item (g-object gtk-menu-item))
(allocation :int))
(export 'gtk-menu-item-toggle-size-allocate)
;;; ----------------------------------------------------------------------------
;;; gtk_menu_item_get_reserve_indicator
;;; gtk_menu_item_set_reserve_indicator -> gtk-menu-item-reserve-indicator
;;; ----------------------------------------------------------------------------
(defun (setf gtk-menu-item-reserve-indicator) (reserve item)
(foreign-funcall "gtk_menu_item_set_reserve_indicator"
(g-object gtk-menu-item) item
:boolean reserve
:void)
reserve)
(defcfun ("gtk_menu_item_get_reserve_indicator" gtk-menu-item-reserve-indicator)
:boolean
#+cl-cffi-gtk-documentation
"@version{2021-11-13}
@syntax[]{(gtk-menu-item-reserve-indicator item) => reserve}
@syntax[]{(setf (gtk-menu-item-reserve-indicator item) reserve)}
@argument[item]{a @class{gtk-menu-item} widget}
@argument[reserve]{a boolean whether the menu item always reserves space for
the submenu indicator}
@begin{short}
Accessor of the reserve indicator of the menu item.
@end{short}
The @sym{gtk-menu-item-reserve-indicator} function returns whether the menu
item reserves space for the submenu indicator, regardless if it has a submenu
or not. The @sym{(setf gtk-menu-item-reserve-indicator)} function sets whether
the menu item should reserve space. There should be little need for
applications to call this functions.
@see-class{gtk-menu-item}"
(item (g-object gtk-menu-item)))
(export 'gtk-menu-item-reserve-indicator)
;;; --- End of file gtk.menu-item.lisp -----------------------------------------
| null |
https://raw.githubusercontent.com/crategus/cl-cffi-gtk/ba198f7d29cb06de1e8965e1b8a78522d5430516/gtk/gtk.menu-item.lisp
|
lisp
|
----------------------------------------------------------------------------
gtk.menu-item.lisp
The documentation of this file is taken from the GTK 3 Reference Manual
See <>. The API documentation of the Lisp binding is
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License for Lisp
License, or (at your option) any later version and with a preamble to
with Lisp programs and is referred as the LLGPL.
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
General Public License. If not, see </>
and <>.
----------------------------------------------------------------------------
GtkMenuItem
The widget used for item in menus.
Types and Values
GtkMenuItem
Functions
gtk_menu_item_new_with_label
gtk_menu_item_new_with_mnemonic
gtk_menu_item_set_right_justified
gtk_menu_item_get_right_justified
gtk_menu_item_get_label
gtk_menu_item_set_label
gtk_menu_item_get_use_underline
gtk_menu_item_set_use_underline
gtk_menu_item_set_submenu
gtk_menu_item_get_submenu
gtk_menu_item_set_accel_path
gtk_menu_item_get_accel_path
gtk_menu_item_activate
gtk_menu_item_toggle_size_request
gtk_menu_item_toggle_size_allocate
gtk_menu_item_get_reserve_indicator
gtk_menu_item_set_reserve_indicator
Properties
gchar* label Read / Write
gboolean right-justified Read / Write
GtkMenu* submenu Read / Write
gboolean use-underline Read / Write
Style Properties
gfloat arrow-scaling Read
gint arrow-spacing Read
gint horizontal-padding Read
GtkShadowType selected-shadow-type Read
gint toggle-spacing Read
gint width-chars Read
Signals
void activate Action
void activate-item Run First
void deselect Run First
void select Run First
void toggle-size-allocate Run First
Object Hierarchy
GObject
╰── GInitiallyUnowned
╰── GtkMenuItem
├── GtkImageMenuItem
╰── GtkTearoffMenuItem
Implemented Interfaces
----------------------------------------------------------------------------
----------------------------------------------------------------------------
struct GtkMenuItem
----------------------------------------------------------------------------
----------------------------------------------------------------------------
Property and Accessor Details
----------------------------------------------------------------------------
--- gtk-menu-item-accel-path -----------------------------------------------
--- gtk-menu-item-label ----------------------------------------------------
--- gtk-menu-item-right-justified ------------------------------------------
--- gtk-menu-item-submenu --------------------------------------------------
--- gtk-menu-item-use-underline --------------------------------------------
----------------------------------------------------------------------------
gtk_menu_item_new ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_menu_item_new_with_label ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_menu_item_new_with_mnemonic ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_menu_item_activate ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_menu_item_toggle_size_request ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_menu_item_toggle_size_allocate ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_menu_item_get_reserve_indicator
gtk_menu_item_set_reserve_indicator -> gtk-menu-item-reserve-indicator
----------------------------------------------------------------------------
--- End of file gtk.menu-item.lisp -----------------------------------------
|
Version 3.24 and modified to document the Lisp binding to the GTK library .
available from < -cffi-gtk/ > .
Copyright ( C ) 2009 - 2011
Copyright ( C ) 2011 - 2021
as published by the Free Software Foundation , either version 3 of the
the GNU Lesser General Public License that clarifies the terms for use
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public
License along with this program and the preamble to the Gnu Lesser
gtk_menu_item_new
gtk_menu_item_select
gtk_menu_item_deselect
gchar * accel - path Read / Write
void toggle - size - request Run First
╰ ─ ─
╰ ─ ─ GtkContainer
╰ ─ ─
├ ─ ─
├ ─ ─
GtkMenuItem implements AtkImplementorIface , GtkBuildable , GtkActivatable
and GtkActionable .
(in-package :gtk)
(define-g-object-class "GtkMenuItem" gtk-menu-item
(:superclass gtk-bin
:export t
:interfaces ("AtkImplementorIface"
"GtkBuildable"
"GtkActivatable")
:type-initializer "gtk_menu_item_get_type")
((accel-path
gtk-menu-item-accel-path
"accel-path" "gchararray" t t)
(label
gtk-menu-item-label "label" "gchararray" t t)
(right-justified
gtk-menu-item-right-justified
"right-justified" "gboolean" t t)
(submenu
gtk-menu-item-submenu
"submenu" "GtkMenu" t t)
(use-underline
gtk-menu-item-use-underline
"use-underline" "gboolean" t t)))
#+cl-cffi-gtk-documentation
(setf (documentation 'gtk-menu-item 'type)
"@version{*2021-11-13}
@begin{short}
The @sym{gtk-menu-item} widget and the derived widgets are the only valid
childs for menus. Their function is to correctly handle highlighting,
alignment, events and submenus.
@end{short}
As it derives from the @class{gtk-bin} class it can hold any valid child
widget, although only a few are really useful.
@begin[GtkMenuItem as GtkBuildable]{dictionary}
The @sym{gtk-menu-item} implementation of the @class{gtk-buildable}
interface supports adding a submenu by specifying @code{\"submenu\"} as the
@code{\"type\"} attribute of a @code{<child>} element.
@b{Example:} A UI definition fragment with submenus.
@begin{pre}
<object class=\"GtkMenuItem\">
<child type=\"submenu\">
<object class=\"GtkMenu\"/>
</child>
</object>
@end{pre}
@end{dictionary}
@begin[CSS nodes]{dictionary}
@begin{pre}
menuitem
├── <child>
╰── [arrow.right]
@end{pre}
The @sym{gtk-menu-item} class has a single CSS node with name
@code{menuitem}. If the menu item has a submenu, it gets another CSS node
with name @code{arrow}, which has the @code{.left} or @code{.right} style
class.
@end{dictionary}
@begin[Style Property Details]{dictionary}
@begin[code]{table}
@begin[arrow-scaling]{entry}
The @code{arrow-scaling} style property of type @code{:float} (Read)
@br{}
Amount of space used up by arrow, relative to the font size of the menu
item. @br{}
@em{Warning:} The @code{arrow-scaling} style property has been
deprecated since version 3.20 and should not be used in newly written
code. Use the standard min-width/min-height CSS properties on the arrow
node. The value of this style property is ignored. @br{}
Allowed values: [0,2] @br{}
Default value: 0.8
@end{entry}
@begin[arrow-spacing]{entry}
The @code{arrow-spacing} style property of type @code{:int} (Read) @br{}
Space between label and arrow. @br{}
@em{Warning:} The @code{arrow-spacing} style property has been
deprecated since version 3.20 and should not be used in newly written
code. Use the standard margin CSS property on the arrow node. The value
of this style property is ignored. @br{}
Allowed values: >= 0 @br{}
Default value: 10
@end{entry}
@begin[horizontal-padding]{entry}
The @code{horizontal-padding} style property of type @code{:int} (Read)
@br{}
Padding to left and right of the menu item. @br{}
@em{Warning:} The @code{horizontal-padding} style property has been
deprecated since version 3.8 and should not be used in newly written
code. Use the standard padding CSS property, through objects like
@class{gtk-style-context} and @class{gtk-css-provider}. The value of
this style property is ignored. @br{}
Allowed values: >= 0 @br{}
Default value: 3
@end{entry}
@begin[selected-shadow-type]{entry}
The @code{selected-shadow-type} style property of type
@symbol{gtk-shadow-type} (Read) @br{}
Shadow type when the menu item is selected. @br{}
@em{Warning:} The @code{selected-shadow-type} style property has been
deprecated since version 3.20 and should not be used in newly written
code. Use CSS to determine the shadow. The value of this style property
is ignored. @br{}
Default value: @code{:none}
@end{entry}
@begin[toggle-spacing]{entry}
The @code{toggle-spacing} style property of type @code{:int} (Read)@br{}
Space between icon and label. @br{}
@em{Warning:} The @code{toggle-spacing} style property has been
deprecated since version 3.20 and should not be used in newly written
code. Use the standard margin CSS property on the check or radio nodes.
The value of this style property is ignored. @br{}
Allowed values: >= 0 @br{}
Default value: 5
@end{entry}
@begin[width-chars]{entry}
The @code{width-chars} style property of type @code{:int} (Read) @br{}
The minimum desired width of the menu item in characters. @br{}
@em{Warning:} The @code{width-chars} style property has been deprecated
since version 3.20 and should not be used in newly written code. Use the
standard CSS property min-width. The value of this style property is
ignored. @br{}
Allowed values: >= 0 @br{}
Default value: 12
@end{entry}
@end{table}
@end{dictionary}
@begin[Signal Details]{dictionary}
@subheading{The \"activate\" signal}
@begin{pre}
lambda (item) :action
@end{pre}
Emitted when the menu item is activated.
@begin[code]{table}
@entry[item]{The @sym{gtk-menu-item} widget which received the signal.}
@end{table}
@subheading{The \"activate-item\" signal}
@begin{pre}
lambda (item) :run-first
@end{pre}
Emitted when the menu item is activated, but also if the menu item has a
submenu. For normal applications, the relevant signal is \"activate\".
@begin[code]{table}
@entry[item]{The @sym{gtk-menu-item} widget which received the signal.}
@end{table}
@subheading{The \"deselect\" signal}
@begin{pre}
lambda (item) :run-first
@end{pre}
@begin[code]{table}
@entry[item]{The @sym{gtk-menu-item} widget which received the signal.}
@end{table}
@subheading{The \"select\" signal}
@begin{pre}
lambda (item) :run-first
@end{pre}
@begin[code]{table}
@entry[item]{The @sym{gtk-menu-item} widget which received the signal.}
@end{table}
@subheading{The \"toggle-size-allocate\" signal}
@begin{pre}
lambda (item arg) :run-first
@end{pre}
@begin[code]{table}
@entry[item]{The @sym{gtk-menu-item} widget which received the signal.}
@entry[arg]{An integer which is not documented.}
@end{table}
@subheading{The \"toggle-size-request\" signal}
@begin{pre}
lambda (item arg) :run-first
@end{pre}
@begin[code]{table}
@entry[item]{The @sym{gtk-menu-item} widget which received the signal.}
@entry[arg]{A pointer which is not documented.}
@end{table}
@end{dictionary}
@see-slot{gtk-menu-item-accel-path}
@see-slot{gtk-menu-item-label}
@see-slot{gtk-menu-item-right-justified}
@see-slot{gtk-menu-item-submenu}
@see-slot{gtk-menu-item-use-underline}
@see-class{gtk-bin}
@see-class{gtk-menu-shell}")
#+cl-cffi-gtk-documentation
(setf (documentation (atdoc:get-slot-from-name "accel-path" 'gtk-menu-item) 't)
"The @code{accel-path} property of type @code{:string} (Read / Write) @br{}
Sets the accelerator path of the menu item, through which runtime changes of
the accelerator of the menu item caused by the user can be identified and
saved to persistant storage. @br{}
Default value: @code{nil}")
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-menu-item-accel-path atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-menu-item-accel-path 'function)
"@version{2021-11-13}
@syntax[]{(gtk-menu-item-accel-path object) => path}
@syntax[]{(setf (gtk-menu-item-accel-path object) path)}
@argument[item]{a valid @class{gtk-menu-item} widget}
@argument[path]{a string with the accelerator path, corresponding to
this functionality of the menu item, or @code{nil} to unset the current
path}
@begin{short}
Accessor of the @slot[gtk-menu-item]{accel-path} slot of the
@class{gtk-menu-item} class.
@end{short}
The @sym{gtk-menu-item-accel-path} slot access function retrieve the
accelerator path that was previously set on the menu item. The
@sym{(setf gtk-menu-item-accel-path)} slot access function sets the
accelerator path on the menu item, through which runtime changes of the
accelerator of the menu item caused by the user can be identified and saved to
persistent storage, see the @fun{gtk-accel-map-save} function on this.
To set up a default accelerator for this menu item, call the
@fun{gtk-accel-map-add-entry} function with the same @arg{path}. See
also the @fun{gtk-accel-map-add-entry} function on the specifics of
accelerator paths, and the @fun{gtk-menu-accel-path} function for a more
convenient variant of this function.
This function is basically a convenience wrapper that handles calling
the @fun{gtk-widget-set-accel-path} function with the appropriate accelerator
group for the menu item.
Note that you do need to set an accelerator on the parent menu with the
@fun{gtk-menu-accel-group} function for this to work.
@see-class{gtk-menu-item}
@see-function{gtk-accel-map-save}
@see-function{gtk-accel-map-add-entry}
@see-function{gtk-menu-accel-path}
@see-function{gtk-menu-accel-group}
@see-function{gtk-widget-set-accel-path}")
#+cl-cffi-gtk-documentation
(setf (documentation (atdoc:get-slot-from-name "label" 'gtk-menu-item) 't)
"The @code{label} property of type @code{:string} (Read / Write) @br{}
The text for the child label. @br{}
Default value: \"\"")
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-menu-item-label atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-menu-item-label 'function)
"@version{2021-11-13}
@syntax[]{(gtk-menu-item-label object) => label}
@syntax[]{(setf (gtk-menu-item-label object) label)}
@argument[object]{a @class{gtk-menu-item} widget}
@argument[label]{a string with the text you want to set}
@begin{short}
Accessor of the @slot[gtk-menu-item]{label} slot of the
@class{gtk-menu-item} class.
@end{short}
The @sym{gtk-menu-item-label} slot access function gets the text on the menu
item label. The @sym{(setf gtk-menu-item-label)} slot access function sets
the text.
@see-class{gtk-menu-item}")
#+cl-cffi-gtk-documentation
(setf (documentation (atdoc:get-slot-from-name "right-justified"
'gtk-menu-item) 't)
"The @code{right-justified} property of type @code{:boolean} (Read / Write)
@br{}
Sets whether the menu item appears justified at the right side of a menu
bar. @br{}
Default value: @em{false}")
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-menu-item-right-justified atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-menu-item-right-justified 'function)
"@version{2021-11-13}
@syntax[]{(gtk-menu-item-right-justified object) => justified}
@syntax[]{(setf (gtk-menu-item-right-justified object) justified)}
@argument[item]{a @class{gtk-menu-item} widget}
@argument[justified]{if @em{true} the menu item will appear at the far right
if added to a menu bar}
@begin{short}
Accessor of the @slot[gtk-menu-item]{right-justified} slot of the
@class{gtk-menu-item} class.
@end{short}
The @sym{gtk-menu-item-right-justified} slot access function gets whether the
menu item appears justified at the right side of the menu bar. The
@sym{(setf gtk-menu-item-right-justified)} slot access function sets whether
the menu item appears justified at the right side.
This was traditionally done for \"Help\" menu items, but is now considered a
bad idea. If the widget layout is reversed for a right-to-left language like
Hebrew or Arabic, right-justified menu items appear at the left.
@begin[Warning]{dictionary}
The @sym{gtk-menu-item-right-justified} function has been deprecated since
version 3.2 and should not be used in newly written code. If you insist on
using it, use the @fun{gtk-widget-hexpand} and @fun{gtk-widget-halign}
functions.
@end{dictionary}
@see-class{gtk-menu-item}
@see-function{gtk-widget-halign}
@see-function{gtk-widget-hexpand}")
#+cl-cffi-gtk-documentation
(setf (documentation (atdoc:get-slot-from-name "submenu" 'gtk-menu-item) 't)
"The @code{submenu} property of type @class{gtk-menu} (Read / Write) @br{}
The submenu attached to the menu item, or @code{nil} if it has none.")
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-menu-item-submenu atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-menu-item-submenu 'function)
"@version{2021-11-13}
@syntax[]{(gtk-menu-item-submenu object) => submenu}
@syntax[]{(setf (gtk-menu-item-submenu object) submenu)}
@argument[object]{a @class{gtk-menu-item} widget}
@argument[submenu]{a @class{gtk-menu} submenu, or @code{nil}}
@begin{short}
Accessor of the @slot[gtk-menu-item]{submenu} slot of the
@class{gtk-menu-item} class.
@end{short}
The @sym{gtk-menu-item-submenu} slot access function gets the submenu
underneath this menu item, if any. The @sym{(setf gtk-menu-item-submenu)} slot
access function sets or replaces the submenu of the menu item, or removes it
when a @code{nil} submenu is passed.
@see-class{gtk-menu-item}
@see-class{gtk-menu}")
#+cl-cffi-gtk-documentation
(setf (documentation (atdoc:get-slot-from-name "use-underline"
'gtk-menu-item) 't)
"The @code{use-underline} property of type @code{:boolean} (Read / Write) @br{}
@em{True} if underlines in the text indicate mnemonics. @br{}
Default value: @em{false}")
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-menu-item-use-underline atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-menu-item-use-underline 'function)
"@version{2021-11-13}
@syntax[]{(gtk-menu-item-use-underline object) => setting}
@syntax[]{(setf (gtk-menu-item-use-underline object) setting)}
@argument[item]{a @class{gtk-menu-item} widget}
@argument[setting]{@em{true} if underlines in the text indicate mnemonics}
@begin{short}
Accessor of the @slot[gtk-menu-item]{use-underline} slot of the
@class{gtk-menu-item} class.
@end{short}
The @sym{gtk-menu-item-use-underline} slot access function checks if an
underline in the text indicates the next character should be used for the
mnemonic accelerator key. If @em{true}, an underline in the text indicates
the next character should be used for the mnemonic accelerator key.
@see-class{gtk-menu-item}")
(declaim (inline gtk-menu-item-new))
(defun gtk-menu-item-new ()
#+cl-cffi-gtk-documentation
"@version{2021-11-13}
@return{The newly created @class{gtk-menu-item} widget.}
@begin{short}
Creates a new menu item.
@end{short}
@see-class{gtk-menu-item}"
(make-instance 'gtk-menu-item))
(export 'gtk-menu-item-new)
(declaim (inline gtk-menu-item-new-with-label))
(defun gtk-menu-item-new-with-label (label)
#+cl-cffi-gtk-documentation
"@version{2021-11-13}
@argument[label]{a string with the text for the label}
@return{The newly created @class{gtk-menu-item} widget.}
@begin{short}
Creates a new menu item whose child is a @class{gtk-label} widget.
@end{short}
@see-class{gtk-menu-item}
@see-class{gtk-label}
@see-function{gtk-menu-item-new-with-mnemonic}"
(make-instance 'gtk-menu-item
:label label))
(export 'gtk-menu-item-new-with-label)
(defcfun ("gtk_menu_item_new_with_mnemonic" gtk-menu-item-new-with-mnemonic)
(g-object gtk-menu-item)
#+cl-cffi-gtk-documentation
"@version{2021-11-13}
@argument[label]{a string with the text of the button, with an underscore in
front of the mnemonic character}
@return{A new @class{gtk-menu-item} widget.}
@begin{short}
Creates a new menu item containing a label.
@end{short}
The label will be created using the @fun{gtk-label-new-with-mnemonic}
function, so underscores in label indicate the mnemonic for the menu item.
@see-class{gtk-menu-item}
@see-function{gtk-menu-item-new-with-label}
@see-function{gtk-label-new-with-mnemonic}"
(label :string))
(export 'gtk-menu-item-new-with-mnemonic)
gtk_menu_item_select ( )
(defcfun ("gtk_menu_item_select" gtk-menu-item-select) :void
#+cl-cffi-gtk-documentation
"@version{2021-11-13}
@argument[item]{a @class{gtk-menu-item} widget}
@begin{short}
Emits the \"select\" signal on the given menu item.
@end{short}
@see-class{gtk-menu-item}
@see-function{gtk-menu-item-deselect}"
(item (g-object gtk-menu-item)))
(export 'gtk-menu-item-select)
gtk_menu_item_deselect ( )
(defcfun ("gtk_menu_item_deselect" gtk-menu-item-deselect) :void
#+cl-cffi-gtk-documentation
"@version{2021-11-13}
@argument[item]{a @class{gtk-menu-item} widget}
@begin{short}
Emits the \"deselect\" signal on the given menu item.
@end{short}
@see-class{gtk-menu-item}
@see-function{gtk-menu-item-select}"
(item (g-object gtk-menu-item)))
(export 'gtk-menu-item-deselect)
(defcfun ("gtk_menu_item_activate" gtk-menu-item-activate) :void
#+cl-cffi-gtk-documentation
"@version{2021-11-13}
@argument[item]{a @class{gtk-menu-item} widget}
@begin{short}
Emits the \"activate\" signal on the given menu item.
@end{short}
@see-class{gtk-menu-item}"
(item (g-object gtk-menu-item)))
(export 'gtk-menu-item-activate)
(defcfun ("gtk_menu_item_toggle_size_request" gtk-menu-item-toggle-size-request)
:void
#+cl-cffi-gtk-documentation
"@version{2021-11-13}
@argument[item]{a @class{gtk-menu-item} widget}
@argument[requisition]{an integer with the requisition to use as signal data}
@begin{short}
Emits the \"toggle-size-request\" signal on the given menu item.
@end{short}
@see-class{gtk-menu-item}
@see-function{gtk-menu-item-toggle-size-allocate}"
(item (g-object gtk-menu-item))
(requisition :int))
(export 'gtk-menu-item-toggle-size-request)
(defcfun ("gtk_menu_item_toggle_size_allocate"
gtk-menu-item-toggle-size-allocate) :void
#+cl-cffi-gtk-documentation
"@version{2021-11-13}
@argument[item]{a @class{gtk-menu-item} widget}
@argument[allocation]{an integer with the allocation to use as signal data}
@begin{short}
Emits the \"toggle-size-allocate\" signal on the given item.
@end{short}
@see-class{gtk-menu-item}
@see-function{gtk-menu-item-toggle-size-request}"
(item (g-object gtk-menu-item))
(allocation :int))
(export 'gtk-menu-item-toggle-size-allocate)
(defun (setf gtk-menu-item-reserve-indicator) (reserve item)
(foreign-funcall "gtk_menu_item_set_reserve_indicator"
(g-object gtk-menu-item) item
:boolean reserve
:void)
reserve)
(defcfun ("gtk_menu_item_get_reserve_indicator" gtk-menu-item-reserve-indicator)
:boolean
#+cl-cffi-gtk-documentation
"@version{2021-11-13}
@syntax[]{(gtk-menu-item-reserve-indicator item) => reserve}
@syntax[]{(setf (gtk-menu-item-reserve-indicator item) reserve)}
@argument[item]{a @class{gtk-menu-item} widget}
@argument[reserve]{a boolean whether the menu item always reserves space for
the submenu indicator}
@begin{short}
Accessor of the reserve indicator of the menu item.
@end{short}
The @sym{gtk-menu-item-reserve-indicator} function returns whether the menu
item reserves space for the submenu indicator, regardless if it has a submenu
or not. The @sym{(setf gtk-menu-item-reserve-indicator)} function sets whether
the menu item should reserve space. There should be little need for
applications to call this functions.
@see-class{gtk-menu-item}"
(item (g-object gtk-menu-item)))
(export 'gtk-menu-item-reserve-indicator)
|
0975a79aa819a18ab6b888f96a5399b7bda7eb04a346b2bb312811b335ce128b
|
mbenke/zpf2013
|
arr2.hs
|
add1 :: Monad m => m Int -> m Int -> m Int
add1 mx my = mx >>= \x-> my >>= \y -> return $ x+y
-- liftM2 (+)
(?) = undefined
addInt :: Int -> Int -> Int
addInt = (+)
-- infixr 5 <+>
infixr 3 ***
infixr 3 &&&
infixr 2 + + +
infixr 2 |||
infixr 1 ^ > > , > > ^
infixr 1 ^ < < , < < ^
infixr 1 >>>, <<<
class Arrow a where
arr :: (b->c) -> a b c
(>>>) :: a b c -> a c d -> a b d
first :: a b c -> a (b,d) (c,d)
second :: a b c -> a (d, b) (d, c)
second g = arr swap >>> first g >>> arr swap
where swap (x,y) = (y,x)
(<<<) :: a c d -> a b c -> a b d
(<<<) = flip (>>>)
(***) :: Arrow a => a b c -> a b' c' -> a (b, b') (c, c')
f *** g = first f >>> second g
(&&&) :: Arrow a => a b c -> a b c' -> a b (c, c')
f &&& g = arr dup >>> (f *** g)
where dup x = (x,x)
add2 :: Arrow a => a b Int -> a b Int -> a b Int
add2 f g = (f &&& g) >>> arr (\(u,v) -> u + v)
-- uncurry (+)
| null |
https://raw.githubusercontent.com/mbenke/zpf2013/85f32747e17f07a74e1c3cb064b1d6acaca3f2f0/Slides/12Arrow/arr2.hs
|
haskell
|
liftM2 (+)
infixr 5 <+>
uncurry (+)
|
add1 :: Monad m => m Int -> m Int -> m Int
add1 mx my = mx >>= \x-> my >>= \y -> return $ x+y
(?) = undefined
addInt :: Int -> Int -> Int
addInt = (+)
infixr 3 ***
infixr 3 &&&
infixr 2 + + +
infixr 2 |||
infixr 1 ^ > > , > > ^
infixr 1 ^ < < , < < ^
infixr 1 >>>, <<<
class Arrow a where
arr :: (b->c) -> a b c
(>>>) :: a b c -> a c d -> a b d
first :: a b c -> a (b,d) (c,d)
second :: a b c -> a (d, b) (d, c)
second g = arr swap >>> first g >>> arr swap
where swap (x,y) = (y,x)
(<<<) :: a c d -> a b c -> a b d
(<<<) = flip (>>>)
(***) :: Arrow a => a b c -> a b' c' -> a (b, b') (c, c')
f *** g = first f >>> second g
(&&&) :: Arrow a => a b c -> a b c' -> a b (c, c')
f &&& g = arr dup >>> (f *** g)
where dup x = (x,x)
add2 :: Arrow a => a b Int -> a b Int -> a b Int
add2 f g = (f &&& g) >>> arr (\(u,v) -> u + v)
|
1dab9609e6b44ebe3b685e2368612a679711155399cd7df4dfad34a889833079
|
serioga/webapp-clojure-2020
|
app_config.clj
|
(ns app.system.service.app-config
(:require [clojure.edn :as edn]
[clojure.string :as string]
[integrant.core :as ig]
[lib.config.props :as props]
[lib.util.secret :as secret]))
(set! *warn-on-reflection* true)
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
(defn- split [v] (string/split v #"[\s,]+"))
(props/add-conform-rule :edn,,, edn/read-string)
(props/add-conform-rule :vector split)
(props/add-conform-rule :set,,, (comp set split))
(props/add-conform-rule :secret secret/->Secret)
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
(defmethod ig/init-key :app.system.service/app-config
[_ {:keys [prop-files conform-rules prop-defaults :dev/prepare-prop-files]}]
(let [prepare-prop-files (or prepare-prop-files identity)
loaded (-> prop-files
(prepare-prop-files)
(props/load-prop-files))
merged (merge prop-defaults
(-> loaded
(merge (System/getProperties))
(props/apply-conform-rules conform-rules)))]
(with-meta merged (meta loaded))))
(comment
(into (sorted-map)
(ig/init-key :app.system.service/app-config
{:prop-files "dev/app/config/default.props"
:prop-defaults {"xxx" :xxx
"Vk.App.Id" nil}
:conform-rules {"Mailer.Smtp.Port" :edn
"Mailer.Smtp.Options" :edn
#"System\.Switch\..+" :edn
#"Webapp\.Hosts\(.+\)" :set}})))
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
| null |
https://raw.githubusercontent.com/serioga/webapp-clojure-2020/91a7170a1be287bbfa5b9279d697208f7f806f9b/src/app/system/service/app_config.clj
|
clojure
|
(ns app.system.service.app-config
(:require [clojure.edn :as edn]
[clojure.string :as string]
[integrant.core :as ig]
[lib.config.props :as props]
[lib.util.secret :as secret]))
(set! *warn-on-reflection* true)
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
(defn- split [v] (string/split v #"[\s,]+"))
(props/add-conform-rule :edn,,, edn/read-string)
(props/add-conform-rule :vector split)
(props/add-conform-rule :set,,, (comp set split))
(props/add-conform-rule :secret secret/->Secret)
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
(defmethod ig/init-key :app.system.service/app-config
[_ {:keys [prop-files conform-rules prop-defaults :dev/prepare-prop-files]}]
(let [prepare-prop-files (or prepare-prop-files identity)
loaded (-> prop-files
(prepare-prop-files)
(props/load-prop-files))
merged (merge prop-defaults
(-> loaded
(merge (System/getProperties))
(props/apply-conform-rules conform-rules)))]
(with-meta merged (meta loaded))))
(comment
(into (sorted-map)
(ig/init-key :app.system.service/app-config
{:prop-files "dev/app/config/default.props"
:prop-defaults {"xxx" :xxx
"Vk.App.Id" nil}
:conform-rules {"Mailer.Smtp.Port" :edn
"Mailer.Smtp.Options" :edn
#"System\.Switch\..+" :edn
#"Webapp\.Hosts\(.+\)" :set}})))
••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
|
|
731fc7c70d4800ac9737c42af8ddf98a1a518b14d25501db3fce9f7bbbb903e4
|
sgbj/MaximaSharp
|
powers.lisp
|
Maxima code for extracting powers , finding leading and trailing
;; coefficients, and finding the degree of polynomials.
Author , University of Nebraska at Kearney ( aka UNK )
December 2001 , December 2002
;; License: GPL
;; The user of this code assumes all risk for its use. It has no warranty.
;; If you don't know the meaning of "no warranty," don't use this code. :)
(in-package :maxima)
($put '$powers 1 '$version)
Acknowledgement : helped find and correct bugs . He
;; also wrote user documentation and a test routine.
;; posintp(x) returns true iff x is a positive integer or if x has been declared
to be an integer and has been assumed to be greater than zero . Thus
( C1 ) declare(m , integer)$
( C2 ) assume(m > 0)$
;; (C3) posintp(m);
;; (D3) TRUE
posintp is n't used by any functions in powers ; it could be expunged .
(defun $posintp (x)
(and (or ($integerp x) ($featurep x '$integer)) (mgrp x 0)))
;; Set ratfac to nil, return rat(e,x), and reset ratfac to
;; its previous value.
(defun myrat (e &rest x)
(let ((save-ratfac $ratfac))
(setq $ratfac nil)
(unwind-protect
(apply '$rat `(,e ,@x))
(setq $ratfac save-ratfac))))
If x list a Maxima list of symbols , return true iff the expression p
;; doesn't depend on any member of x. If x is a symbol, return true
iff p does n't depend on x. This function is similar to $ freeof , but
it maybe somewhat more efficient when p is a CRE expression . Finally ,
if x ( any member of x when x is a Maxima list ) is n't a symbol signal
;; an error.
(defun $ratfreeof (x p)
(setq x (require-list-of-symbols x "$ratfreeof" 2))
(let ((p-vars (cdr ($showratvars p))))
(cond ((every #'(lambda (z) (or ($symbolp z) ($subvarp z))) p-vars)
(every #'(lambda (z) (null (member z p-vars :test #'like))) x))
(t
(setq p ($totaldisrep p))
(every #'(lambda(z) ($freeof ($totaldisrep z) p)) x)))))
variablep(e ) evaluates to true if and only if e is a non - constant symbol
;; or a subscripted symbol. Because symbolp(pi) evaluates to true, we need to
check whether cd mae is constant .
(defun $variablep (e)
(and (or ($symbolp e) ($subvarp e)) (not ($constantp e))))
;; ordinal_string(i) returns the ordinal name of the integer i. When
i > 10 , i < 1 , or i is n't an integer , give up and return i - th .
(defun $ordinal_string (i)
(case i
(1 "first")
(2 "second")
(3 "third")
(4 "fourth")
(5 "fifth")
(6 "sixth")
(7 "seventh")
(8 "eighth")
(9 "ninth")
(10 "tenth")
(otherwise
(format nil "~A-th" (mfuncall '$string i)))))
;; If variablep(v) evaluates to false, signal an error saying that
;; the i-th argument of the function f requires a symbol; otherwise,
;; return true.
(defun require-symbol (v f i)
(if (not ($variablep v))
(merror "The ~A argument of ~:M must be a symbol, instead found ~:M"
($ordinal_string i) f v) t))
If v is a Maxima list and each element of v is a symbol , return the
;; cdr of v. When v isn't a list, but is a symbol, return the Lisp list
;; (list v). Otherwise signal an error saying that the i-th argument of the
;; function f requires a symbol or a list of symbols.
(defun require-list-of-symbols (v f i)
(let ((x))
(if ($listp v) (setq x (cdr v)) (setq x (list v)))
(if (every #'$variablep x) x
(merror "The ~A argument of ~:M must be a symbol or a list of symbols, instead found ~:M" ($ordinal_string i) f v))))
(defun require-poly (p v f i)
(setq p (myrat p v))
(if ($polynomialp p v) p
(merror "The ~A argument of ~:M requires a polynomial, instead found ~:M" ($ordinal_string i) f p)))
(defun require-nonlist (e f i)
(if ($listp e)
(merror "The ~A argument of ~:M requires a nonlist, instead found ~:M"
($ordinal_string i) f e)))
Return a Maxima list of the non - constant rat variables in e.
(defun non-constant-ratvars (e)
(let ((v (cdr ($showratvars e)))
(acc))
(dolist (vi v `((mlist simp) ,@acc))
(if (not ($constantp vi)) (push vi acc)))))
;; If e is a list, map $powers over the list. If e is a sum of powers
;; of powers of x, return a list of the exponents.
(defun $powers (e x)
(require-symbol x "$powers" 2)
(cond (($listp e)
(cons '(mlist simp) (mapcar #'(lambda (p) ($powers p x)) (cdr e))))
(t
(setq e (require-poly (myrat e x) x "$powers" 1))
(cond (($ratfreeof x e)
`((mlist simp) 0))
(t
(cons '(mlist simp) (odds (cadr e) 0)))))))
odds is defined in mactex.lisp . Here is its definition .
(defun odds (n c)
if c = 1 , get the odd terms ( first , third ... )
(cond ((null n) nil)
((= c 1) (cons (car n) (odds (cdr n) 0)))
((= c 0) (odds (cdr n) 1))))
;; Return the highest power of the polynomial e in the variable x.
(defun $hipower (e x)
(require-symbol x "$hipower" 2)
(setq e (require-poly (myrat e x) x "$hipower" 1))
(if (or ($constantp e) ($ratfreeof x e)) 0 (cadadr e)))
;; Return the lowest power of the polynomial e in the variable x.
(defun $lowpower (e x)
(require-symbol x "$lowpower" 2)
(setq e (require-poly (myrat e x) x "$lowpower" 1))
(if (or ($constantp e) ($ratfreeof x e)) 0 (nth 1 (reverse (cadr e)))))
Flatten a Maxima list .
(defun flatten-list (e)
(cond (($listp e)
(let ((acc))
(dolist (ei (cdr e) (cons '(mlist simp) (nreverse acc)))
(setq acc (if ($listp ei) (nconc (cdr (flatten-list ei)) acc)
(cons ei acc))))))
(t e)))
;; If e is a sum of powers of x, return a list of the coefficients
;; of powers of x. When e isn't a sum of powers, return false. This
function is based on a function written by and
referenced in " Mathematics and System Reference Manual , " 16th edition ,
1996 .
(defun $allcoeffs (e x)
(flatten-list (allcoeffs e x)))
(defun allcoeffs (e x)
(cond (($listp e)
(cons '(mlist simp) (mapcar #'(lambda (s) (allcoeffs s x)) (cdr e))))
(($listp x)
(cond ((= 0 ($length x)) e)
(t (allcoeffs (allcoeffs e ($first x)) ($rest x)))))
(t
(require-symbol x "$allcoeffs" 2)
(setq e (myrat e x))
(let ((p ($powers e x)))
(cons '(mlist simp)
(mapcar #'(lambda (n) ($ratcoef e x n)) (cdr p)))))))
;; Return the coefficient of the term of the polynomial e that
;; contains the highest power of x. When x = [x1,x2,...,xn], return
lcoeff(lcoeff ( ... ( lcoeff(e , x1),x2), ... ,xn ) ... )
(defun $lcoeff (e &optional v)
(require-nonlist e "$lcoeff" 1)
(if (null v) (setq v (non-constant-ratvars e)))
(lcoeff (require-poly (myrat e) v "$lcoeff" 1)
(require-list-of-symbols v "$lcoeff" 2)))
(defun lcoeff (e x)
(if (null x) e (lcoeff ($ratcoef e (car x) ($hipower e (car x))) (cdr x))))
;; Return the coefficient of the term of the polynomial e that
;; contains the least power of x. When x = [x1,x2,...,xn], return
lcoeff(lcoeff ( ... ( lcoeff(e , x1),x2), ... ,xn ) ... )
(defun $tcoeff (e &optional v)
(require-nonlist e "$tcoeff" 1)
(if (null v) (setq v (non-constant-ratvars e)))
(tcoeff (require-poly (myrat e) v "$tcoeff" 1)
(require-list-of-symbols v "$tcoeff" 2)))
(defun tcoeff (e x)
(if (null x) e (tcoeff ($ratcoef e (car x) ($lowpower e (car x))) (cdr x))))
;; Return the degree of the symbol x in the polynomial p. When
x is a list , degree(p , [ x1,x2, ... ,xn ] ) returns
;; degree(p,x1) + degree(lcoeff(p, x1),[x2,...xn]).
;; Finally, degree(p,[]) returns 0.
(defun $degree (p x)
(degree (require-poly (myrat p) x "$degree" 1)
(require-list-of-symbols x "$degree" 2)))
(defun degree (p x)
(if (null x) 0
(add ($hipower p (car x)) (degree (lcoeff p `(,(car x))) (cdr x)))))
Return the total degree of the polynomial . Four cases :
;; (a) total_degree(p) returns the total degree of the polynomial
;; in the variables listofvars(p).
;; (b) total_degree(p,x), where x isn't a list returns the
;; total_degree of p in the variable x.
;; (c) total_degree(p,[x1,x2,...,xn]), where x = [x1,x2,...,xn]
returns the total_degree of p in the variables x1 thru xn .
;; (d) total_degree(p,x1,x2,...xn), where the x's are symbols
returns the total_degree of p in the variables x1 thru xn .
(defun $total_degree (p &optional v)
(if (null v) (setq v (non-constant-ratvars p)))
(setq v (require-list-of-symbols v "$total_degree" 2))
(total-degree (cadr (apply 'myrat `(,p ,@v)))))
(defun total-degree (e)
(cond ((consp (nth 2 e))
(+ (nth 1 e) (total-degree (nth 2 e))))
(t
(nth 1 e))))
(defun $lcm (p q)
(nth 1 ($divide (mul p q) ($gcd p q))))
Compute the s - polynomial of f and For a definition of the
s - polynomial , see Davenport , , and Tournier , " Computer Algebra , "
1988 , page 100 .
(defun $spoly (f g v)
(setq v (cons '(mlist simp) (require-list-of-symbols v "$spoly" 3)))
(setq f (myrat f))
(setq g (myrat g))
(let ((fp ($lterm f v))
(gp ($lterm g v)))
(mul ($lcm fp gp) (add (div f fp) (mul -1 (div g gp))))))
(defun $lterm (p &optional v)
(if (null v) (setq v (non-constant-ratvars p)))
(lterm (require-poly (myrat p) v "$lterm" 1)
(require-list-of-symbols v "$lterm" 2)))
(defun lterm (p v)
(cond ((null v) p)
(t
(let* ((vo (car v))
(n ($hipower p vo)))
(lterm (mult ($ratcoef p vo n) (power vo n)) (cdr v))))))
(defun $get_exponents (p x)
(setq x (require-list-of-symbols x "$get_exponents" 2))
(let ((acc))
(setq p (myrat p))
(require-poly p (cons '(mlist simp) x) "$get_exponents" 1)
(dolist (xi x (cons '(mlist simp) (nreverse acc)))
(push ($hipower p xi) acc)
(setq p ($lcoeff p xi)))))
;; Return true iff and only if e is a polynomial in the variables var.
(defun $polynomialp (e &optional vars cp ep)
(declare (ignore cp ep))
(if (null vars) (setq vars (non-constant-ratvars e)))
(setq vars (require-list-of-symbols vars "$polynomialp" 2))
(setq vars `((mlist simp) ,@vars))
(and (every #'(lambda (x) (or ($variablep x) ($ratfreeof vars x)
($constantp x)))
(cdr ($showratvars e)))
(not ($taylorp e)) ($ratfreeof vars ($ratdenom e))))
| null |
https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/share/contrib/powers.lisp
|
lisp
|
coefficients, and finding the degree of polynomials.
License: GPL
The user of this code assumes all risk for its use. It has no warranty.
If you don't know the meaning of "no warranty," don't use this code. :)
also wrote user documentation and a test routine.
posintp(x) returns true iff x is a positive integer or if x has been declared
(C3) posintp(m);
(D3) TRUE
it could be expunged .
Set ratfac to nil, return rat(e,x), and reset ratfac to
its previous value.
doesn't depend on any member of x. If x is a symbol, return true
an error.
or a subscripted symbol. Because symbolp(pi) evaluates to true, we need to
ordinal_string(i) returns the ordinal name of the integer i. When
If variablep(v) evaluates to false, signal an error saying that
the i-th argument of the function f requires a symbol; otherwise,
return true.
cdr of v. When v isn't a list, but is a symbol, return the Lisp list
(list v). Otherwise signal an error saying that the i-th argument of the
function f requires a symbol or a list of symbols.
If e is a list, map $powers over the list. If e is a sum of powers
of powers of x, return a list of the exponents.
Return the highest power of the polynomial e in the variable x.
Return the lowest power of the polynomial e in the variable x.
If e is a sum of powers of x, return a list of the coefficients
of powers of x. When e isn't a sum of powers, return false. This
Return the coefficient of the term of the polynomial e that
contains the highest power of x. When x = [x1,x2,...,xn], return
Return the coefficient of the term of the polynomial e that
contains the least power of x. When x = [x1,x2,...,xn], return
Return the degree of the symbol x in the polynomial p. When
degree(p,x1) + degree(lcoeff(p, x1),[x2,...xn]).
Finally, degree(p,[]) returns 0.
(a) total_degree(p) returns the total degree of the polynomial
in the variables listofvars(p).
(b) total_degree(p,x), where x isn't a list returns the
total_degree of p in the variable x.
(c) total_degree(p,[x1,x2,...,xn]), where x = [x1,x2,...,xn]
(d) total_degree(p,x1,x2,...xn), where the x's are symbols
Return true iff and only if e is a polynomial in the variables var.
|
Maxima code for extracting powers , finding leading and trailing
Author , University of Nebraska at Kearney ( aka UNK )
December 2001 , December 2002
(in-package :maxima)
($put '$powers 1 '$version)
Acknowledgement : helped find and correct bugs . He
to be an integer and has been assumed to be greater than zero . Thus
( C1 ) declare(m , integer)$
( C2 ) assume(m > 0)$
(defun $posintp (x)
(and (or ($integerp x) ($featurep x '$integer)) (mgrp x 0)))
(defun myrat (e &rest x)
(let ((save-ratfac $ratfac))
(setq $ratfac nil)
(unwind-protect
(apply '$rat `(,e ,@x))
(setq $ratfac save-ratfac))))
If x list a Maxima list of symbols , return true iff the expression p
iff p does n't depend on x. This function is similar to $ freeof , but
it maybe somewhat more efficient when p is a CRE expression . Finally ,
if x ( any member of x when x is a Maxima list ) is n't a symbol signal
(defun $ratfreeof (x p)
(setq x (require-list-of-symbols x "$ratfreeof" 2))
(let ((p-vars (cdr ($showratvars p))))
(cond ((every #'(lambda (z) (or ($symbolp z) ($subvarp z))) p-vars)
(every #'(lambda (z) (null (member z p-vars :test #'like))) x))
(t
(setq p ($totaldisrep p))
(every #'(lambda(z) ($freeof ($totaldisrep z) p)) x)))))
variablep(e ) evaluates to true if and only if e is a non - constant symbol
check whether cd mae is constant .
(defun $variablep (e)
(and (or ($symbolp e) ($subvarp e)) (not ($constantp e))))
i > 10 , i < 1 , or i is n't an integer , give up and return i - th .
(defun $ordinal_string (i)
(case i
(1 "first")
(2 "second")
(3 "third")
(4 "fourth")
(5 "fifth")
(6 "sixth")
(7 "seventh")
(8 "eighth")
(9 "ninth")
(10 "tenth")
(otherwise
(format nil "~A-th" (mfuncall '$string i)))))
(defun require-symbol (v f i)
(if (not ($variablep v))
(merror "The ~A argument of ~:M must be a symbol, instead found ~:M"
($ordinal_string i) f v) t))
If v is a Maxima list and each element of v is a symbol , return the
(defun require-list-of-symbols (v f i)
(let ((x))
(if ($listp v) (setq x (cdr v)) (setq x (list v)))
(if (every #'$variablep x) x
(merror "The ~A argument of ~:M must be a symbol or a list of symbols, instead found ~:M" ($ordinal_string i) f v))))
(defun require-poly (p v f i)
(setq p (myrat p v))
(if ($polynomialp p v) p
(merror "The ~A argument of ~:M requires a polynomial, instead found ~:M" ($ordinal_string i) f p)))
(defun require-nonlist (e f i)
(if ($listp e)
(merror "The ~A argument of ~:M requires a nonlist, instead found ~:M"
($ordinal_string i) f e)))
Return a Maxima list of the non - constant rat variables in e.
(defun non-constant-ratvars (e)
(let ((v (cdr ($showratvars e)))
(acc))
(dolist (vi v `((mlist simp) ,@acc))
(if (not ($constantp vi)) (push vi acc)))))
(defun $powers (e x)
(require-symbol x "$powers" 2)
(cond (($listp e)
(cons '(mlist simp) (mapcar #'(lambda (p) ($powers p x)) (cdr e))))
(t
(setq e (require-poly (myrat e x) x "$powers" 1))
(cond (($ratfreeof x e)
`((mlist simp) 0))
(t
(cons '(mlist simp) (odds (cadr e) 0)))))))
odds is defined in mactex.lisp . Here is its definition .
(defun odds (n c)
if c = 1 , get the odd terms ( first , third ... )
(cond ((null n) nil)
((= c 1) (cons (car n) (odds (cdr n) 0)))
((= c 0) (odds (cdr n) 1))))
(defun $hipower (e x)
(require-symbol x "$hipower" 2)
(setq e (require-poly (myrat e x) x "$hipower" 1))
(if (or ($constantp e) ($ratfreeof x e)) 0 (cadadr e)))
(defun $lowpower (e x)
(require-symbol x "$lowpower" 2)
(setq e (require-poly (myrat e x) x "$lowpower" 1))
(if (or ($constantp e) ($ratfreeof x e)) 0 (nth 1 (reverse (cadr e)))))
Flatten a Maxima list .
(defun flatten-list (e)
(cond (($listp e)
(let ((acc))
(dolist (ei (cdr e) (cons '(mlist simp) (nreverse acc)))
(setq acc (if ($listp ei) (nconc (cdr (flatten-list ei)) acc)
(cons ei acc))))))
(t e)))
function is based on a function written by and
referenced in " Mathematics and System Reference Manual , " 16th edition ,
1996 .
(defun $allcoeffs (e x)
(flatten-list (allcoeffs e x)))
(defun allcoeffs (e x)
(cond (($listp e)
(cons '(mlist simp) (mapcar #'(lambda (s) (allcoeffs s x)) (cdr e))))
(($listp x)
(cond ((= 0 ($length x)) e)
(t (allcoeffs (allcoeffs e ($first x)) ($rest x)))))
(t
(require-symbol x "$allcoeffs" 2)
(setq e (myrat e x))
(let ((p ($powers e x)))
(cons '(mlist simp)
(mapcar #'(lambda (n) ($ratcoef e x n)) (cdr p)))))))
lcoeff(lcoeff ( ... ( lcoeff(e , x1),x2), ... ,xn ) ... )
(defun $lcoeff (e &optional v)
(require-nonlist e "$lcoeff" 1)
(if (null v) (setq v (non-constant-ratvars e)))
(lcoeff (require-poly (myrat e) v "$lcoeff" 1)
(require-list-of-symbols v "$lcoeff" 2)))
(defun lcoeff (e x)
(if (null x) e (lcoeff ($ratcoef e (car x) ($hipower e (car x))) (cdr x))))
lcoeff(lcoeff ( ... ( lcoeff(e , x1),x2), ... ,xn ) ... )
(defun $tcoeff (e &optional v)
(require-nonlist e "$tcoeff" 1)
(if (null v) (setq v (non-constant-ratvars e)))
(tcoeff (require-poly (myrat e) v "$tcoeff" 1)
(require-list-of-symbols v "$tcoeff" 2)))
(defun tcoeff (e x)
(if (null x) e (tcoeff ($ratcoef e (car x) ($lowpower e (car x))) (cdr x))))
x is a list , degree(p , [ x1,x2, ... ,xn ] ) returns
(defun $degree (p x)
(degree (require-poly (myrat p) x "$degree" 1)
(require-list-of-symbols x "$degree" 2)))
(defun degree (p x)
(if (null x) 0
(add ($hipower p (car x)) (degree (lcoeff p `(,(car x))) (cdr x)))))
Return the total degree of the polynomial . Four cases :
returns the total_degree of p in the variables x1 thru xn .
returns the total_degree of p in the variables x1 thru xn .
(defun $total_degree (p &optional v)
(if (null v) (setq v (non-constant-ratvars p)))
(setq v (require-list-of-symbols v "$total_degree" 2))
(total-degree (cadr (apply 'myrat `(,p ,@v)))))
(defun total-degree (e)
(cond ((consp (nth 2 e))
(+ (nth 1 e) (total-degree (nth 2 e))))
(t
(nth 1 e))))
(defun $lcm (p q)
(nth 1 ($divide (mul p q) ($gcd p q))))
Compute the s - polynomial of f and For a definition of the
s - polynomial , see Davenport , , and Tournier , " Computer Algebra , "
1988 , page 100 .
(defun $spoly (f g v)
(setq v (cons '(mlist simp) (require-list-of-symbols v "$spoly" 3)))
(setq f (myrat f))
(setq g (myrat g))
(let ((fp ($lterm f v))
(gp ($lterm g v)))
(mul ($lcm fp gp) (add (div f fp) (mul -1 (div g gp))))))
(defun $lterm (p &optional v)
(if (null v) (setq v (non-constant-ratvars p)))
(lterm (require-poly (myrat p) v "$lterm" 1)
(require-list-of-symbols v "$lterm" 2)))
(defun lterm (p v)
(cond ((null v) p)
(t
(let* ((vo (car v))
(n ($hipower p vo)))
(lterm (mult ($ratcoef p vo n) (power vo n)) (cdr v))))))
(defun $get_exponents (p x)
(setq x (require-list-of-symbols x "$get_exponents" 2))
(let ((acc))
(setq p (myrat p))
(require-poly p (cons '(mlist simp) x) "$get_exponents" 1)
(dolist (xi x (cons '(mlist simp) (nreverse acc)))
(push ($hipower p xi) acc)
(setq p ($lcoeff p xi)))))
(defun $polynomialp (e &optional vars cp ep)
(declare (ignore cp ep))
(if (null vars) (setq vars (non-constant-ratvars e)))
(setq vars (require-list-of-symbols vars "$polynomialp" 2))
(setq vars `((mlist simp) ,@vars))
(and (every #'(lambda (x) (or ($variablep x) ($ratfreeof vars x)
($constantp x)))
(cdr ($showratvars e)))
(not ($taylorp e)) ($ratfreeof vars ($ratdenom e))))
|
b1ceebcb5379bae7a08278fc9b7d7ae308579c1e3d69a000378a5fffdc2434d9
|
roman01la/minimax
|
shadow.clj
|
(ns fg.passes.shadow
(:require
[bgfx.core :as bgfx]
[fg.state :as state]
[minimax.object :as obj]
[minimax.objects.camera :as camera]
[minimax.passes :as passes]
[minimax.renderer.frame-buffer :as fb]
[minimax.renderer.view :as view])
(:import (org.joml Matrix4f Vector3f)
(org.lwjgl.bgfx BGFX)))
(def render-state
(bit-or
0
BGFX/BGFX_STATE_WRITE_Z
BGFX/BGFX_STATE_DEPTH_TEST_LESS
BGFX/BGFX_STATE_CULL_CW))
(defn create-shadow-map-fb [shadow-size]
(fb/create
{:width shadow-size
:height shadow-size
:format BGFX/BGFX_TEXTURE_FORMAT_D24
:flags (bit-or BGFX/BGFX_TEXTURE_RT
BGFX/BGFX_SAMPLER_COMPARE_LEQUAL)}))
(def shadow-map-fb
;; TODO: Maybe make it dependant on `:shadow-map-size` if the value is dynamic
(delay (create-shadow-map-fb (:shadow-map-size @state/state))))
(def shadow-map-texture
;; TODO: Maybe make it dependant on `shadow-map-fb`
(delay (bgfx/get-texture @@shadow-map-fb 0)))
(def ortho-camera
(camera/create-orthographic-camera
{:area 6
:near -100
:far 10}))
(defn update-ortho-view-projection [id camera eye-vec3 at-vec3]
(camera/look-at camera at-vec3 eye-vec3)
(obj/render camera id))
(def ^Matrix4f shadow-mtx (Matrix4f.))
(defn setup [d-light]
(let [shadow-map-size (:shadow-map-size @state/state)]
(view/rect passes/shadow 0 0 shadow-map-size shadow-map-size)
(view/frame-buffer passes/shadow @@shadow-map-fb)
(update-ortho-view-projection (:id passes/shadow) ortho-camera
(.negate ^Vector3f (:position d-light) (Vector3f.))
(:at @state/state)))
(view/clear passes/shadow
(bit-or BGFX/BGFX_CLEAR_COLOR BGFX/BGFX_CLEAR_DEPTH BGFX/BGFX_CLEAR_STENCIL)
(:background-color @state/state))
(.mul ^Matrix4f @(:proj-mtx ortho-camera) ^Matrix4f (:view-mtx ortho-camera) ^Matrix4f shadow-mtx))
| null |
https://raw.githubusercontent.com/roman01la/minimax/f371c199d55a2a219ed7cf5f2dd2e079be99f963/src/fg/passes/shadow.clj
|
clojure
|
TODO: Maybe make it dependant on `:shadow-map-size` if the value is dynamic
TODO: Maybe make it dependant on `shadow-map-fb`
|
(ns fg.passes.shadow
(:require
[bgfx.core :as bgfx]
[fg.state :as state]
[minimax.object :as obj]
[minimax.objects.camera :as camera]
[minimax.passes :as passes]
[minimax.renderer.frame-buffer :as fb]
[minimax.renderer.view :as view])
(:import (org.joml Matrix4f Vector3f)
(org.lwjgl.bgfx BGFX)))
(def render-state
(bit-or
0
BGFX/BGFX_STATE_WRITE_Z
BGFX/BGFX_STATE_DEPTH_TEST_LESS
BGFX/BGFX_STATE_CULL_CW))
(defn create-shadow-map-fb [shadow-size]
(fb/create
{:width shadow-size
:height shadow-size
:format BGFX/BGFX_TEXTURE_FORMAT_D24
:flags (bit-or BGFX/BGFX_TEXTURE_RT
BGFX/BGFX_SAMPLER_COMPARE_LEQUAL)}))
(def shadow-map-fb
(delay (create-shadow-map-fb (:shadow-map-size @state/state))))
(def shadow-map-texture
(delay (bgfx/get-texture @@shadow-map-fb 0)))
(def ortho-camera
(camera/create-orthographic-camera
{:area 6
:near -100
:far 10}))
(defn update-ortho-view-projection [id camera eye-vec3 at-vec3]
(camera/look-at camera at-vec3 eye-vec3)
(obj/render camera id))
(def ^Matrix4f shadow-mtx (Matrix4f.))
(defn setup [d-light]
(let [shadow-map-size (:shadow-map-size @state/state)]
(view/rect passes/shadow 0 0 shadow-map-size shadow-map-size)
(view/frame-buffer passes/shadow @@shadow-map-fb)
(update-ortho-view-projection (:id passes/shadow) ortho-camera
(.negate ^Vector3f (:position d-light) (Vector3f.))
(:at @state/state)))
(view/clear passes/shadow
(bit-or BGFX/BGFX_CLEAR_COLOR BGFX/BGFX_CLEAR_DEPTH BGFX/BGFX_CLEAR_STENCIL)
(:background-color @state/state))
(.mul ^Matrix4f @(:proj-mtx ortho-camera) ^Matrix4f (:view-mtx ortho-camera) ^Matrix4f shadow-mtx))
|
85fac5fd1b037aa06c2ef9c5664cb3a612b82e4d042bf0503b8e04c021ce6ad2
|
janestreet/vcaml
|
serialize_small.ml
|
(* tests automatically generated from a subset of
-msgpack-python/blob/master/test_umsgpack.py *)
open Core
open Msgpack
let print_hex = String.iter ~f:(fun c -> printf "\\x%02x" (Char.to_int c))
let%expect_test "nil" =
let obj = Nil in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xc0 |}]
;;
let%expect_test "bool false" =
let obj = Boolean false in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xc2 |}]
;;
let%expect_test "bool true" =
let obj = Boolean true in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xc3 |}]
;;
let%expect_test "7-bit uint0" =
let obj = Integer 0 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \x00 |}]
;;
let%expect_test "7-bit uint1" =
let obj = Integer 16 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \x10 |}]
;;
let%expect_test "7-bit uint2" =
let obj = Integer 127 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \x7f |}]
;;
let%expect_test "5-bit sint0" =
let obj = Integer (-1) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xff |}]
;;
let%expect_test "5-bit sint1" =
let obj = Integer (-16) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xf0 |}]
;;
let%expect_test "5-bit sint2" =
let obj = Integer (-32) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xe0 |}]
;;
let%expect_test "8-bit uint0" =
let obj = Integer 128 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xcc\x80 |}]
;;
let%expect_test "8-bit uint1" =
let obj = Integer 240 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xcc\xf0 |}]
;;
let%expect_test "8-bit uint2" =
let obj = Integer 255 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xcc\xff |}]
;;
let%expect_test "16-bit uint0" =
let obj = Integer 256 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xcd\x01\x00 |}]
;;
let%expect_test "16-bit uint1" =
let obj = Integer 8192 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xcd\x20\x00 |}]
;;
let%expect_test "16-bit uint2" =
let obj = Integer 65535 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xcd\xff\xff |}]
;;
let%expect_test "32-bit uint0" =
let obj = Integer 65536 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xce\x00\x01\x00\x00 |}]
;;
let%expect_test "32-bit uint1" =
let obj = Integer 2097152 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xce\x00\x20\x00\x00 |}]
;;
let%expect_test "32-bit uint2" =
let obj = Int64 4294967295L in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xce\xff\xff\xff\xff |}]
;;
let%expect_test "64-bit uint0" =
let obj = Int64 4294967296L in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xcf\x00\x00\x00\x01\x00\x00\x00\x00 |}]
;;
let%expect_test "64-bit uint1" =
let obj = Int64 35184372088832L in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xcf\x00\x00\x20\x00\x00\x00\x00\x00 |}]
;;
let%expect_test "64-bit uint2" =
let obj = UInt64 Int64.minus_one in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xcf\xff\xff\xff\xff\xff\xff\xff\xff |}]
;;
let%expect_test "8-bit int0" =
let obj = Integer (-33) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd0\xdf |}]
;;
let%expect_test "8-bit int1" =
let obj = Integer (-100) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd0\x9c |}]
;;
let%expect_test "8-bit int2" =
let obj = Integer (-128) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd0\x80 |}]
;;
let%expect_test "16-bit int0" =
let obj = Integer (-129) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd1\xff\x7f |}]
;;
let%expect_test "16-bit int1" =
let obj = Integer (-2000) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd1\xf8\x30 |}]
;;
let%expect_test "16-bit int2" =
let obj = Integer (-32768) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd1\x80\x00 |}]
;;
let%expect_test "32-bit int0" =
let obj = Integer (-32769) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd2\xff\xff\x7f\xff |}]
;;
let%expect_test "32-bit int1" =
let obj = Integer (-1000000000) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd2\xc4\x65\x36\x00 |}]
;;
let%expect_test "32-bit int2" =
let obj = Int64 (-2147483648L) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd2\x80\x00\x00\x00 |}]
;;
let%expect_test "64-bit int0" =
let obj = Int64 (-2147483649L) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd3\xff\xff\xff\xff\x7f\xff\xff\xff |}]
;;
let%expect_test "64-bit int1" =
let obj = Int64 (-1000000000000000002L) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd3\xf2\x1f\x49\x4c\x58\x9b\xff\xfe |}]
;;
let%expect_test "64-bit int2" =
let obj = Int64 (-9223372036854775808L) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd3\x80\x00\x00\x00\x00\x00\x00\x00 |}]
;;
let%expect_test "64-bit float0" =
let obj = Floating 0.0 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xcb\x00\x00\x00\x00\x00\x00\x00\x00 |}]
;;
let%expect_test "64-bit float1" =
let obj = Floating 2.5 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xcb\x40\x04\x00\x00\x00\x00\x00\x00 |}]
;;
let%expect_test "64-bit float2" =
let obj = Floating 1e+35 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xcb\x47\x33\x42\x61\x72\xc7\x4d\x82 |}]
;;
let%expect_test "fix string0" =
let obj = String "" in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xa0 |}]
;;
let%expect_test "fix string1" =
let obj = String "a" in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xa1\x61 |}]
;;
let%expect_test "fix string2" =
let obj = String "abc" in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xa3\x61\x62\x63 |}]
;;
let%expect_test "wide char string0" =
let obj = String "Allagbé" in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xa8\x41\x6c\x6c\x61\x67\x62\xc3\xa9 |}]
;;
let%expect_test "wide char string1" =
let obj = String "По оживлённым берегам" in
let s = string_of_t_exn obj in
print_hex s;
[%expect
{| \xd9\x28\xd0\x9f\xd0\xbe\x20\xd0\xbe\xd0\xb6\xd0\xb8\xd0\xb2\xd0\xbb\xd1\x91\xd0\xbd\xd0\xbd\xd1\x8b\xd0\xbc\x20\xd0\xb1\xd0\xb5\xd1\x80\xd0\xb5\xd0\xb3\xd0\xb0\xd0\xbc |}]
;;
let%expect_test "fixext1" =
let obj = Extension { type_id = 0x5; data = Bytes.init 1 ~f:(fun _ -> '\x80') } in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd4\x05\x80 |}]
;;
let%expect_test "fixext2" =
let obj = Extension { type_id = 0x5; data = Bytes.init 2 ~f:(fun _ -> '\x80') } in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd5\x05\x80\x80 |}]
;;
let%expect_test "fixext4" =
let obj = Extension { type_id = 0x5; data = Bytes.init 4 ~f:(fun _ -> '\x80') } in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd6\x05\x80\x80\x80\x80 |}]
;;
let%expect_test "fixext8" =
let obj = Extension { type_id = 0x5; data = Bytes.init 8 ~f:(fun _ -> '\x80') } in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd7\x05\x80\x80\x80\x80\x80\x80\x80\x80 |}]
;;
let%expect_test "fixext16" =
let obj = Extension { type_id = 0x5; data = Bytes.init 16 ~f:(fun _ -> '\x80') } in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd8\x05\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80 |}]
;;
| null |
https://raw.githubusercontent.com/janestreet/vcaml/b02fc56c48746fa18a6bc9a0f8fb85776db76977/msgpack/protocol/test/serialize_small.ml
|
ocaml
|
tests automatically generated from a subset of
-msgpack-python/blob/master/test_umsgpack.py
|
open Core
open Msgpack
let print_hex = String.iter ~f:(fun c -> printf "\\x%02x" (Char.to_int c))
let%expect_test "nil" =
let obj = Nil in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xc0 |}]
;;
let%expect_test "bool false" =
let obj = Boolean false in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xc2 |}]
;;
let%expect_test "bool true" =
let obj = Boolean true in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xc3 |}]
;;
let%expect_test "7-bit uint0" =
let obj = Integer 0 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \x00 |}]
;;
let%expect_test "7-bit uint1" =
let obj = Integer 16 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \x10 |}]
;;
let%expect_test "7-bit uint2" =
let obj = Integer 127 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \x7f |}]
;;
let%expect_test "5-bit sint0" =
let obj = Integer (-1) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xff |}]
;;
let%expect_test "5-bit sint1" =
let obj = Integer (-16) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xf0 |}]
;;
let%expect_test "5-bit sint2" =
let obj = Integer (-32) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xe0 |}]
;;
let%expect_test "8-bit uint0" =
let obj = Integer 128 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xcc\x80 |}]
;;
let%expect_test "8-bit uint1" =
let obj = Integer 240 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xcc\xf0 |}]
;;
let%expect_test "8-bit uint2" =
let obj = Integer 255 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xcc\xff |}]
;;
let%expect_test "16-bit uint0" =
let obj = Integer 256 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xcd\x01\x00 |}]
;;
let%expect_test "16-bit uint1" =
let obj = Integer 8192 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xcd\x20\x00 |}]
;;
let%expect_test "16-bit uint2" =
let obj = Integer 65535 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xcd\xff\xff |}]
;;
let%expect_test "32-bit uint0" =
let obj = Integer 65536 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xce\x00\x01\x00\x00 |}]
;;
let%expect_test "32-bit uint1" =
let obj = Integer 2097152 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xce\x00\x20\x00\x00 |}]
;;
let%expect_test "32-bit uint2" =
let obj = Int64 4294967295L in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xce\xff\xff\xff\xff |}]
;;
let%expect_test "64-bit uint0" =
let obj = Int64 4294967296L in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xcf\x00\x00\x00\x01\x00\x00\x00\x00 |}]
;;
let%expect_test "64-bit uint1" =
let obj = Int64 35184372088832L in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xcf\x00\x00\x20\x00\x00\x00\x00\x00 |}]
;;
let%expect_test "64-bit uint2" =
let obj = UInt64 Int64.minus_one in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xcf\xff\xff\xff\xff\xff\xff\xff\xff |}]
;;
let%expect_test "8-bit int0" =
let obj = Integer (-33) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd0\xdf |}]
;;
let%expect_test "8-bit int1" =
let obj = Integer (-100) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd0\x9c |}]
;;
let%expect_test "8-bit int2" =
let obj = Integer (-128) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd0\x80 |}]
;;
let%expect_test "16-bit int0" =
let obj = Integer (-129) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd1\xff\x7f |}]
;;
let%expect_test "16-bit int1" =
let obj = Integer (-2000) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd1\xf8\x30 |}]
;;
let%expect_test "16-bit int2" =
let obj = Integer (-32768) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd1\x80\x00 |}]
;;
let%expect_test "32-bit int0" =
let obj = Integer (-32769) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd2\xff\xff\x7f\xff |}]
;;
let%expect_test "32-bit int1" =
let obj = Integer (-1000000000) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd2\xc4\x65\x36\x00 |}]
;;
let%expect_test "32-bit int2" =
let obj = Int64 (-2147483648L) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd2\x80\x00\x00\x00 |}]
;;
let%expect_test "64-bit int0" =
let obj = Int64 (-2147483649L) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd3\xff\xff\xff\xff\x7f\xff\xff\xff |}]
;;
let%expect_test "64-bit int1" =
let obj = Int64 (-1000000000000000002L) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd3\xf2\x1f\x49\x4c\x58\x9b\xff\xfe |}]
;;
let%expect_test "64-bit int2" =
let obj = Int64 (-9223372036854775808L) in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd3\x80\x00\x00\x00\x00\x00\x00\x00 |}]
;;
let%expect_test "64-bit float0" =
let obj = Floating 0.0 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xcb\x00\x00\x00\x00\x00\x00\x00\x00 |}]
;;
let%expect_test "64-bit float1" =
let obj = Floating 2.5 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xcb\x40\x04\x00\x00\x00\x00\x00\x00 |}]
;;
let%expect_test "64-bit float2" =
let obj = Floating 1e+35 in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xcb\x47\x33\x42\x61\x72\xc7\x4d\x82 |}]
;;
let%expect_test "fix string0" =
let obj = String "" in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xa0 |}]
;;
let%expect_test "fix string1" =
let obj = String "a" in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xa1\x61 |}]
;;
let%expect_test "fix string2" =
let obj = String "abc" in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xa3\x61\x62\x63 |}]
;;
let%expect_test "wide char string0" =
let obj = String "Allagbé" in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xa8\x41\x6c\x6c\x61\x67\x62\xc3\xa9 |}]
;;
let%expect_test "wide char string1" =
let obj = String "По оживлённым берегам" in
let s = string_of_t_exn obj in
print_hex s;
[%expect
{| \xd9\x28\xd0\x9f\xd0\xbe\x20\xd0\xbe\xd0\xb6\xd0\xb8\xd0\xb2\xd0\xbb\xd1\x91\xd0\xbd\xd0\xbd\xd1\x8b\xd0\xbc\x20\xd0\xb1\xd0\xb5\xd1\x80\xd0\xb5\xd0\xb3\xd0\xb0\xd0\xbc |}]
;;
let%expect_test "fixext1" =
let obj = Extension { type_id = 0x5; data = Bytes.init 1 ~f:(fun _ -> '\x80') } in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd4\x05\x80 |}]
;;
let%expect_test "fixext2" =
let obj = Extension { type_id = 0x5; data = Bytes.init 2 ~f:(fun _ -> '\x80') } in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd5\x05\x80\x80 |}]
;;
let%expect_test "fixext4" =
let obj = Extension { type_id = 0x5; data = Bytes.init 4 ~f:(fun _ -> '\x80') } in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd6\x05\x80\x80\x80\x80 |}]
;;
let%expect_test "fixext8" =
let obj = Extension { type_id = 0x5; data = Bytes.init 8 ~f:(fun _ -> '\x80') } in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd7\x05\x80\x80\x80\x80\x80\x80\x80\x80 |}]
;;
let%expect_test "fixext16" =
let obj = Extension { type_id = 0x5; data = Bytes.init 16 ~f:(fun _ -> '\x80') } in
let s = string_of_t_exn obj in
print_hex s;
[%expect {| \xd8\x05\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80 |}]
;;
|
940aa11b17e22e97d8550b0e40833b3b1aebafbd4e27b90b990a2ac85548d2b0
|
bobzhang/fan
|
test_fan_lang_include.ml
|
open Format
open Fan_lang_include
| null |
https://raw.githubusercontent.com/bobzhang/fan/7ed527d96c5a006da43d3813f32ad8a5baa31b7f/src/todoml/test/test_fan_lang_include.ml
|
ocaml
|
open Format
open Fan_lang_include
|
|
5f4a1d9a5ef204786b389905d75884d3290a0191a8c35f5e2569c40298fc6f86
|
d-cent/objective8
|
storage_test.clj
|
(ns objective8.unit.storage.storage_test
(:require [midje.sweet :refer :all]
[korma.core :as korma]
[objective8.back-end.storage.storage :as s]
[objective8.back-end.storage.mappings :as m]))
(fact "attempts to store an object by looking up the entity mapping"
(let [some-map {:foo "bar" :entity :i-am-entity}]
(s/pg-store! some-map) => :the-id
(provided
(m/get-mapping some-map) => :fake-entity
(s/insert :fake-entity anything) => :the-id)))
(fact "attempts to find an object based on a query containing entity"
(let [some-query {:entity :i-am-entity :foo "bar" :zap "pow"}]
(s/pg-retrieve some-query) => {:query some-query
:options {}
:result :expected-object }
(provided
(m/get-mapping some-query) => :fake-entity
(s/select :fake-entity {:foo "bar" :zap "pow"} {}) => :expected-object)))
(fact "attempts to update a bearer token for a given bearer name"
(let [some-update {:entity :bearer-token :bearer-name "name" :bearer-token "new-token"}]
(s/pg-update-bearer-token! some-update) => anything
(provided
(m/get-mapping some-update) => :fake-entity
(s/update :fake-entity
some-update
{:bearer_name "name"}) => anything)))
(fact "converts hyphens to underscores"
(let [some-query {:entity :ent :foo-bar "wibble"}]
(s/pg-retrieve some-query) => {:query some-query :options {} :result :expected-object}
(provided
(m/get-mapping some-query) => :fake-entity
(s/select :fake-entity {:foo_bar "wibble"} {}) => :expected-object)))
(fact "throws exception if no entity key is present"
(s/pg-retrieve {}) => (throws Exception "Query map requires an :entity key"))
| null |
https://raw.githubusercontent.com/d-cent/objective8/db8344ba4425ca0b38a31c99a3b282d7c8ddaef0/test/objective8/unit/storage/storage_test.clj
|
clojure
|
(ns objective8.unit.storage.storage_test
(:require [midje.sweet :refer :all]
[korma.core :as korma]
[objective8.back-end.storage.storage :as s]
[objective8.back-end.storage.mappings :as m]))
(fact "attempts to store an object by looking up the entity mapping"
(let [some-map {:foo "bar" :entity :i-am-entity}]
(s/pg-store! some-map) => :the-id
(provided
(m/get-mapping some-map) => :fake-entity
(s/insert :fake-entity anything) => :the-id)))
(fact "attempts to find an object based on a query containing entity"
(let [some-query {:entity :i-am-entity :foo "bar" :zap "pow"}]
(s/pg-retrieve some-query) => {:query some-query
:options {}
:result :expected-object }
(provided
(m/get-mapping some-query) => :fake-entity
(s/select :fake-entity {:foo "bar" :zap "pow"} {}) => :expected-object)))
(fact "attempts to update a bearer token for a given bearer name"
(let [some-update {:entity :bearer-token :bearer-name "name" :bearer-token "new-token"}]
(s/pg-update-bearer-token! some-update) => anything
(provided
(m/get-mapping some-update) => :fake-entity
(s/update :fake-entity
some-update
{:bearer_name "name"}) => anything)))
(fact "converts hyphens to underscores"
(let [some-query {:entity :ent :foo-bar "wibble"}]
(s/pg-retrieve some-query) => {:query some-query :options {} :result :expected-object}
(provided
(m/get-mapping some-query) => :fake-entity
(s/select :fake-entity {:foo_bar "wibble"} {}) => :expected-object)))
(fact "throws exception if no entity key is present"
(s/pg-retrieve {}) => (throws Exception "Query map requires an :entity key"))
|
|
d97f4d06097b290785ceeb3e0140ebe9367bbef040712bd0a60816455034350d
|
lispnik/cl-http
|
dtd.lisp
|
;;; -*- mode: LISP; package: "XML-PARSER"; -*-
;;;
"
<DOCUMENTATION>
<DESCRIPTION>
support for document type definitions. these comprise the declarations for elements,
attributes, entities, and notations.
the early versions (< 0.42) collected the definitions established as part of
a given definition and encapsulated then in a DTD object. later versions rely on
universal identifiers to assert that once a definition exists, it is globally valid.
if another appears, it replaces the first. attributes are a special case in that they
are relative to a global element definition.
to replace the DTD for the purpose of serialization, the DOCTYPE instance is used
to cache declarations.
</DESCRIPTION>
<COPYRIGHT HREF='defsystem.lisp|root().descendant(1,COPYRIGHT)'/>
<CHRONOLOGY>
<DELTA><DATE>19971125</DATE>
<LI>dtd.dtd-element-reference (t symbol)
changed the search strategy for reference elements:
1. search the present dtd if one is present; if that fails
2. look for a matching dtd as a) one from which the symbol's package is
reachable and b) in which the element is defined; if that fails,
3. otherwise, or if no dtd is present, make an autonomous reference
</DELTA>
<DELTA><DATE>199711128</DATE>
fixed DTD-ELEMENT args for RESERVED-DECLARATION </DELTA>
<DELTA><DATE>19971218</DATE>
the 'as' slot is superfluous: a dtd is always loaded as something
since the name in the doctype plays the same selective role as that in
a namespace pi</DELTA>
<DELTA><DATE>19980223</DATE>
patched dtd.dtd-element to prevent references to references</DELTA>
<DELTA><DATE>19980331</DATE>
changed reinitialize slot for dtd class to eliminate symbol conflict
from DI package</DELTA>
<DELTA><DATE>19980817</DATE>
the DTD class ind the DTD-IDENTITY-CLASS meta-object are eliminated.
definitions are now bound directly to the name symbols and simply
collected in the DOCTYPE instance for serialization convenience.
</DELTA>
</CHRONOLOGY>
</DOCUMENTATION>
"
(in-package "XML-PARSER")
(defVar *dtd-write-element-references* nil)
(defVar *dtd-write-doctype* nil)
(defMethod %dtd-clear
((name symbol))
(remf (symbol-plist name) 'element-declaration)
(remf (symbol-plist name) 'notation-declaration)
(remf (symbol-plist name) 'parameter-entity-declaration)
(remf (symbol-plist name) 'general-entity-declaration)
(remf (symbol-plist name) 'attribute-declaration))
(defMethod %dtd-clear
((dtd list))
(dolist (sym dtd)
(%dtd-clear sym)))
(defMethod %dtd-clear
((package package))
(do-symbols (sym package) (%dtd-clear sym)))
(defMethod %dtd-clear
((package (eql t)))
(map nil #'%dtd-clear (list-all-packages)))
"<H3>element lookup</H3>
dtd's are indexed by url to make it possible for multiple dtd's with the
same document type name, but different content, to be held simultaneously.
a dtd must be recognised in order to map element names to the correct
element models (through dtd-element's)
a link to a dtd must be established under one of several circumstances:
<OL>
<LI>the dtd is itself being read</LI>
<LI>the dtd was specified as the document type for an xml document which is
being read.</LI>
</OL>
<P>
the containment erlation between dtd and declaration is not, however, followed
strictly: since the names can be namespace-qualified, qualifying again by dtd
is redundant. the dtd implementation manages the collection in order that
it is possible to serialize, but declarations are bound globally to the
respective name symbols.
<DL>
<DT>reading a dtd
<DD>
when a dtd itself is read, it supplants the global dtd and collects any
definitions present in the stream.
<DT>reading an xml document
<DD>
if the document declares a dtd, it will be located and established for the
duration of the document. note, as mentioned above that this has no effect
on the definitions associated with the respective names.
</DL>
"
(defMethod element-declaration
((id symbol) (context t)
&optional (error-p *undefined-element-condition*)
&aux declaration)
(cond ((reserved-name-p id)
(reserved-element-declaration id))
((setf declaration (get id 'element-declaration))
(element-declaration declaration context error-p))
(error-p
(raise-xml-condition 'xml-1.0::element
error-p
"undeclared element: ~s"
id )
(make-instance 'element-declaration
:name id :model '|xml|::ANY))))
(defMethod element-declaration
((id list) (context t) &optional (error-p *undefined-element-condition*))
(mapcar #'(lambda (id) (element-declaration id context error-p)) id))
(defMethod element-declaration
((id string) (context t) &optional (error-p *undefined-element-condition*))
(element-declaration (intern-name id) context error-p))
(defMethod (setf element-declaration)
((entity symbol) (id symbol) (context t))
(setf (get id 'element-declaration) entity))
(defMethod (setf element-declaration)
((entity t) (id string) (context t))
(setf (element-declaration (intern-name id)) entity))
(defMethod general-entity-declaration
((id symbol) (context t)
&optional (error-p *undefined-entity-condition*)
&aux entity)
(cond ((setf entity (get id 'general-entity-declaration))
(general-entity-declaration entity context error-p))
(error-p
(raise-xml-condition 'xml-1.0::Reference
error-p
"undeclared general entity: ~s."
id )
(make-instance 'internal-general-entity-declaration
:name id :content ""))))
(defMethod general-entity-declaration
((id string) (context t) &optional (error-p *undefined-entity-condition*))
(general-entity-declaration (intern-name id) context error-p))
(defMethod (setf general-entity-declaration)
((entity symbol) (id symbol) (context t))
(setf (get id 'general-entity-declaration) entity))
(defMethod (setf general-entity-declaration)
((entity t) (id string) (context t))
(setf (general-entity-declaration (intern-name id)) entity))
(defMethod parameter-entity-declaration
((id symbol) (context t)
&optional (error-p *undefined-entity-condition*)
&aux entity)
(cond ((setf entity (get id 'parameter-entity-declaration))
(parameter-entity-declaration entity context error-p))
(error-p
(raise-xml-condition 'xml-1.0::Reference
error-p
"undeclared parameter entity: ~s."
id )
(make-instance 'internal-parameter-entity-declaration
:name id :content ""))))
(defMethod parameter-entity-declaration
((id string) (context t) &optional (error-p *undefined-entity-condition*))
(parameter-entity-declaration (intern-name id) context error-p))
(defMethod (setf parameter-entity-declaration)
((entity symbol) (id symbol) (context t))
(setf (get id 'parameter-entity-declaration) entity))
(defMethod (setf parameter-entity-declaration)
((entity t) (id string) (context t))
(setf (parameter-entity-declaration (intern-name id)) entity))
(defMethod notation-declaration
((id symbol) (context t)
&optional (error-p *undefined-notation-condition*)
&aux notation)
(cond ((setf notation (get id 'notation-declaration))
(notation-declaration notation context error-p))
(error-p
(raise-xml-condition 'xml-1.0::element
error-p
"undeclared notation: ~s."
id )
(make-instance 'element-declaration
:name id :model '|xml|::ANY))))
(defMethod notation-declaration
((id list) (context t)
&optional (error-p *undefined-notation-condition*))
(mapcar #'(lambda (id) (notation-declaration id context error-p)) id))
(defMethod notation-declaration
((id string) (context t)
&optional (error-p *undefined-notation-condition*))
(notation-declaration (intern-name id) context error-p))
(defMethod (setf notation-declaration)
((entity symbol) (id symbol) (context t))
(setf (get id 'notation-declaration) entity))
(defMethod (setf notation-declaration)
((entity t) (id string) (context t))
(setf (notation-declaration (intern-name id)) entity))
(defMethod attribute-declaration
((gi symbol)
(attribute-name symbol)
(context t)
&optional
(error-p *undefined-attribute-condition*)
&aux entity)
(cond ((setf entity (element-declaration gi context))
(attribute-declaration entity attribute-name context error-p))
(error-p
(raise-xml-condition 'xml-1.0::Attribute
error-p
"undeclared attribute: ~s, ~s"
gi attribute-name)
(make-instance 'attribute-declaration
:name attribute-name ))))
(defMethod attribute-declaration
((gi string) (attribute-name t) (context t)
&optional (error-p *undefined-attribute-condition*))
(attribute-declaration (intern-name gi) attribute-name context error-p))
(defMethod attribute-declaration
((gi t) (attribute-name string) (context t)
&optional (error-p *undefined-attribute-condition*))
(attribute-declaration gi (intern-name attribute-name) context error-p))
(defMethod (setf attribute-declaration)
((entity t) (gi string) (attribute-name t) (context t))
(setf (attribute-declaration (intern-name gi) attribute-name context) entity))
(defMethod (setf attribute-declaration)
((entity t) (gi t) (attribute-name string) (context t))
(setf (attribute-declaration gi (intern-name attribute-name) context) entity))
(defMethod (setf attribute-declaration)
((attdef t) (gi symbol) (attribute-name symbol) (context t)
&aux entity)
(cond ((setf entity (element-declaration gi))
(setf (attribute-declaration entity attribute-name context) attdef))
(t
(xml-form-error 'internal "undeclared element: ~s, ~s."
gi attribute-name))))
(defMethod reserved-element-declaration
((id symbol))
(or (gethash id (xml-token-class.map (find-class 'reserved-element-declaration)))
(xml-form-error 'internal "reserved element not defined: ~s." id)))
(defMethod map-declarations
((context (eql t)) selector operator)
(dolist (package (list-all-packages))
(when (string= "XMLNS" (package-name package) :end2 5)
(map-declarations package selector operator))))
(defMethod map-declarations
((context package) selector operator &aux decl)
(do-symbols (sym context)
(when (setf decl (funcall selector sym))
(funcall operator decl))))
(defMethod map-declarations
((context document-type) selector operator &aux decl)
(flet ((do-sym (sym)
(when (setf decl (funcall selector sym context))
(funcall operator decl))))
(dolist (sym (document-type.internal-subset context))
(do-sym sym))
(dolist (sym (document-type.external-subset context))
(do-sym sym))))
(defun collect-declarations
(context selector &rest args &aux list)
(destructuring-bind (&optional
(collector #'(lambda (decl) (push decl list))))
args
(map-declarations context selector collector)
(nreverse list)))
(defMethod element-declarations
()
(collect-declarations
t #'(lambda (d) (typep d 'element-declaration))))
(defMethod parameter-entity-declarations
()
(collect-declarations
t #'(lambda (d) (typep d 'parameter-entity-declaration))))
(defMethod general-entity-declarations
()
(collect-declarations
t #'(lambda (d) (typep d 'general-entity-declaration))))
(defMethod notation-declarations
()
(collect-declarations
t #'(lambda (d) (typep d 'notation-declaration))))
(defMethod attribute-declarations
(&aux list)
(collect-declarations
t #'element-declaration
#'(lambda (decl)
(setf list (append list (element-declaration.attdefs decl))))))
( xml-node.string ( make - instance ' general - entity - reference : name ' ) )
"XMLP"
| null |
https://raw.githubusercontent.com/lispnik/cl-http/84391892d88c505aed705762a153eb65befb6409/contrib/janderson/xml-1999-05-03/dtd.lisp
|
lisp
|
-*- mode: LISP; package: "XML-PARSER"; -*-
if that fails
if that fails,
|
"
<DOCUMENTATION>
<DESCRIPTION>
support for document type definitions. these comprise the declarations for elements,
attributes, entities, and notations.
the early versions (< 0.42) collected the definitions established as part of
a given definition and encapsulated then in a DTD object. later versions rely on
universal identifiers to assert that once a definition exists, it is globally valid.
if another appears, it replaces the first. attributes are a special case in that they
are relative to a global element definition.
to replace the DTD for the purpose of serialization, the DOCTYPE instance is used
to cache declarations.
</DESCRIPTION>
<COPYRIGHT HREF='defsystem.lisp|root().descendant(1,COPYRIGHT)'/>
<CHRONOLOGY>
<DELTA><DATE>19971125</DATE>
<LI>dtd.dtd-element-reference (t symbol)
changed the search strategy for reference elements:
2. look for a matching dtd as a) one from which the symbol's package is
3. otherwise, or if no dtd is present, make an autonomous reference
</DELTA>
<DELTA><DATE>199711128</DATE>
fixed DTD-ELEMENT args for RESERVED-DECLARATION </DELTA>
<DELTA><DATE>19971218</DATE>
the 'as' slot is superfluous: a dtd is always loaded as something
since the name in the doctype plays the same selective role as that in
a namespace pi</DELTA>
<DELTA><DATE>19980223</DATE>
patched dtd.dtd-element to prevent references to references</DELTA>
<DELTA><DATE>19980331</DATE>
changed reinitialize slot for dtd class to eliminate symbol conflict
from DI package</DELTA>
<DELTA><DATE>19980817</DATE>
the DTD class ind the DTD-IDENTITY-CLASS meta-object are eliminated.
definitions are now bound directly to the name symbols and simply
collected in the DOCTYPE instance for serialization convenience.
</DELTA>
</CHRONOLOGY>
</DOCUMENTATION>
"
(in-package "XML-PARSER")
(defVar *dtd-write-element-references* nil)
(defVar *dtd-write-doctype* nil)
(defMethod %dtd-clear
((name symbol))
(remf (symbol-plist name) 'element-declaration)
(remf (symbol-plist name) 'notation-declaration)
(remf (symbol-plist name) 'parameter-entity-declaration)
(remf (symbol-plist name) 'general-entity-declaration)
(remf (symbol-plist name) 'attribute-declaration))
(defMethod %dtd-clear
((dtd list))
(dolist (sym dtd)
(%dtd-clear sym)))
(defMethod %dtd-clear
((package package))
(do-symbols (sym package) (%dtd-clear sym)))
(defMethod %dtd-clear
((package (eql t)))
(map nil #'%dtd-clear (list-all-packages)))
"<H3>element lookup</H3>
dtd's are indexed by url to make it possible for multiple dtd's with the
same document type name, but different content, to be held simultaneously.
a dtd must be recognised in order to map element names to the correct
element models (through dtd-element's)
a link to a dtd must be established under one of several circumstances:
<OL>
<LI>the dtd is itself being read</LI>
<LI>the dtd was specified as the document type for an xml document which is
being read.</LI>
</OL>
<P>
the containment erlation between dtd and declaration is not, however, followed
strictly: since the names can be namespace-qualified, qualifying again by dtd
is redundant. the dtd implementation manages the collection in order that
it is possible to serialize, but declarations are bound globally to the
respective name symbols.
<DL>
<DT>reading a dtd
<DD>
when a dtd itself is read, it supplants the global dtd and collects any
definitions present in the stream.
<DT>reading an xml document
<DD>
if the document declares a dtd, it will be located and established for the
duration of the document. note, as mentioned above that this has no effect
on the definitions associated with the respective names.
</DL>
"
(defMethod element-declaration
((id symbol) (context t)
&optional (error-p *undefined-element-condition*)
&aux declaration)
(cond ((reserved-name-p id)
(reserved-element-declaration id))
((setf declaration (get id 'element-declaration))
(element-declaration declaration context error-p))
(error-p
(raise-xml-condition 'xml-1.0::element
error-p
"undeclared element: ~s"
id )
(make-instance 'element-declaration
:name id :model '|xml|::ANY))))
(defMethod element-declaration
((id list) (context t) &optional (error-p *undefined-element-condition*))
(mapcar #'(lambda (id) (element-declaration id context error-p)) id))
(defMethod element-declaration
((id string) (context t) &optional (error-p *undefined-element-condition*))
(element-declaration (intern-name id) context error-p))
(defMethod (setf element-declaration)
((entity symbol) (id symbol) (context t))
(setf (get id 'element-declaration) entity))
(defMethod (setf element-declaration)
((entity t) (id string) (context t))
(setf (element-declaration (intern-name id)) entity))
(defMethod general-entity-declaration
((id symbol) (context t)
&optional (error-p *undefined-entity-condition*)
&aux entity)
(cond ((setf entity (get id 'general-entity-declaration))
(general-entity-declaration entity context error-p))
(error-p
(raise-xml-condition 'xml-1.0::Reference
error-p
"undeclared general entity: ~s."
id )
(make-instance 'internal-general-entity-declaration
:name id :content ""))))
(defMethod general-entity-declaration
((id string) (context t) &optional (error-p *undefined-entity-condition*))
(general-entity-declaration (intern-name id) context error-p))
(defMethod (setf general-entity-declaration)
((entity symbol) (id symbol) (context t))
(setf (get id 'general-entity-declaration) entity))
(defMethod (setf general-entity-declaration)
((entity t) (id string) (context t))
(setf (general-entity-declaration (intern-name id)) entity))
(defMethod parameter-entity-declaration
((id symbol) (context t)
&optional (error-p *undefined-entity-condition*)
&aux entity)
(cond ((setf entity (get id 'parameter-entity-declaration))
(parameter-entity-declaration entity context error-p))
(error-p
(raise-xml-condition 'xml-1.0::Reference
error-p
"undeclared parameter entity: ~s."
id )
(make-instance 'internal-parameter-entity-declaration
:name id :content ""))))
(defMethod parameter-entity-declaration
((id string) (context t) &optional (error-p *undefined-entity-condition*))
(parameter-entity-declaration (intern-name id) context error-p))
(defMethod (setf parameter-entity-declaration)
((entity symbol) (id symbol) (context t))
(setf (get id 'parameter-entity-declaration) entity))
(defMethod (setf parameter-entity-declaration)
((entity t) (id string) (context t))
(setf (parameter-entity-declaration (intern-name id)) entity))
(defMethod notation-declaration
((id symbol) (context t)
&optional (error-p *undefined-notation-condition*)
&aux notation)
(cond ((setf notation (get id 'notation-declaration))
(notation-declaration notation context error-p))
(error-p
(raise-xml-condition 'xml-1.0::element
error-p
"undeclared notation: ~s."
id )
(make-instance 'element-declaration
:name id :model '|xml|::ANY))))
(defMethod notation-declaration
((id list) (context t)
&optional (error-p *undefined-notation-condition*))
(mapcar #'(lambda (id) (notation-declaration id context error-p)) id))
(defMethod notation-declaration
((id string) (context t)
&optional (error-p *undefined-notation-condition*))
(notation-declaration (intern-name id) context error-p))
(defMethod (setf notation-declaration)
((entity symbol) (id symbol) (context t))
(setf (get id 'notation-declaration) entity))
(defMethod (setf notation-declaration)
((entity t) (id string) (context t))
(setf (notation-declaration (intern-name id)) entity))
(defMethod attribute-declaration
((gi symbol)
(attribute-name symbol)
(context t)
&optional
(error-p *undefined-attribute-condition*)
&aux entity)
(cond ((setf entity (element-declaration gi context))
(attribute-declaration entity attribute-name context error-p))
(error-p
(raise-xml-condition 'xml-1.0::Attribute
error-p
"undeclared attribute: ~s, ~s"
gi attribute-name)
(make-instance 'attribute-declaration
:name attribute-name ))))
(defMethod attribute-declaration
((gi string) (attribute-name t) (context t)
&optional (error-p *undefined-attribute-condition*))
(attribute-declaration (intern-name gi) attribute-name context error-p))
(defMethod attribute-declaration
((gi t) (attribute-name string) (context t)
&optional (error-p *undefined-attribute-condition*))
(attribute-declaration gi (intern-name attribute-name) context error-p))
(defMethod (setf attribute-declaration)
((entity t) (gi string) (attribute-name t) (context t))
(setf (attribute-declaration (intern-name gi) attribute-name context) entity))
(defMethod (setf attribute-declaration)
((entity t) (gi t) (attribute-name string) (context t))
(setf (attribute-declaration gi (intern-name attribute-name) context) entity))
(defMethod (setf attribute-declaration)
((attdef t) (gi symbol) (attribute-name symbol) (context t)
&aux entity)
(cond ((setf entity (element-declaration gi))
(setf (attribute-declaration entity attribute-name context) attdef))
(t
(xml-form-error 'internal "undeclared element: ~s, ~s."
gi attribute-name))))
(defMethod reserved-element-declaration
((id symbol))
(or (gethash id (xml-token-class.map (find-class 'reserved-element-declaration)))
(xml-form-error 'internal "reserved element not defined: ~s." id)))
(defMethod map-declarations
((context (eql t)) selector operator)
(dolist (package (list-all-packages))
(when (string= "XMLNS" (package-name package) :end2 5)
(map-declarations package selector operator))))
(defMethod map-declarations
((context package) selector operator &aux decl)
(do-symbols (sym context)
(when (setf decl (funcall selector sym))
(funcall operator decl))))
(defMethod map-declarations
((context document-type) selector operator &aux decl)
(flet ((do-sym (sym)
(when (setf decl (funcall selector sym context))
(funcall operator decl))))
(dolist (sym (document-type.internal-subset context))
(do-sym sym))
(dolist (sym (document-type.external-subset context))
(do-sym sym))))
(defun collect-declarations
(context selector &rest args &aux list)
(destructuring-bind (&optional
(collector #'(lambda (decl) (push decl list))))
args
(map-declarations context selector collector)
(nreverse list)))
(defMethod element-declarations
()
(collect-declarations
t #'(lambda (d) (typep d 'element-declaration))))
(defMethod parameter-entity-declarations
()
(collect-declarations
t #'(lambda (d) (typep d 'parameter-entity-declaration))))
(defMethod general-entity-declarations
()
(collect-declarations
t #'(lambda (d) (typep d 'general-entity-declaration))))
(defMethod notation-declarations
()
(collect-declarations
t #'(lambda (d) (typep d 'notation-declaration))))
(defMethod attribute-declarations
(&aux list)
(collect-declarations
t #'element-declaration
#'(lambda (decl)
(setf list (append list (element-declaration.attdefs decl))))))
( xml-node.string ( make - instance ' general - entity - reference : name ' ) )
"XMLP"
|
d6afdf9ec0f202cbee099024e590b70b7a7fef9edd2da2cb914201a47650ead9
|
TyOverby/mono
|
focus.ml
|
open! Core
open! Bonsai_web
open! Bonsai.Let_syntax
module Collated = Incr_map_collate.Collated
module By_row = struct
type 'k t =
{ focused : 'k option
; unfocus : unit Effect.t
; focus_up : unit Effect.t
; focus_down : unit Effect.t
; page_up : unit Effect.t
; page_down : unit Effect.t
; focus : 'k -> unit Effect.t
}
[@@deriving fields]
end
module Kind = struct
type ('a, 'k) t =
| None : (unit, 'k) t
| By_row : { on_change : ('k option -> unit Effect.t) Value.t } -> ('k By_row.t, 'k) t
end
module Scroll = struct
Top scrolls to the first row in the table
Bottom scrolls to the last row in the table
To ( i d , ` Minimal ) scrolls to [ i d ] , moving the screen as little as possible .
To ( i d , ` To_top ) scrolls the table such that [ i d ] is at the top of the screen .
To ( i d , ` To_bottom ) scrolls the table such that [ i d ] is at the bottom of the screen .
Bottom scrolls to the last row in the table
To (id, `Minimal) scrolls to [id], moving the screen as little as possible.
To (id, `To_top) scrolls the table such that [id] is at the top of the screen.
To (id, `To_bottom) scrolls the table such that [id] is at the bottom of the screen. *)
type t = To of Int63.t * [ `Minimal | `To_top | `To_bottom ]
let control_test = function
| To (i, `Minimal) ->
Effect.print_s [%message "scrolling to" (i : Int63.t) "minimizing scrolling"]
| To (i, `To_bottom) ->
Effect.print_s
[%message
"scrolling to"
(i : Int63.t)
"such that it is positioned at the bottom of the screen"]
| To (i, `To_top) ->
Effect.print_s
[%message
"scrolling to"
(i : Int63.t)
"such that it is positioned at the top of the screen"]
;;
let scroll_into_view_options align smooth =
let open Js_of_ocaml in
Constructs the options object described here :
-US/docs/Web/API/Element/scrollIntoView
-US/docs/Web/API/Element/scrollIntoView *)
object%js
val behavior = Js.string smooth
val block =
match align with
| `Top -> Js.string "start"
| `Bottom -> Js.string "end"
end
;;
let the_effect =
let open Js_of_ocaml in
Effect.of_sync_fun (fun (row_id, kind, path) ->
let selector =
[%string ".partial-render-table-%{path} [data-row-id=\"key_%{row_id#Int63}\"]"]
in
Js.Opt.iter
(Dom_html.document##querySelector (Js.string selector))
(fun element ->
let scrollable =
(Js.Unsafe.coerce element
: < scrollIntoViewIfNeeded : bool Js.t -> unit Js.meth
; scrollIntoView : Js.Unsafe.any -> unit Js.meth >
Js.t)
in
match kind with
| `Minimal -> scrollable##scrollIntoViewIfNeeded (Js.bool false)
| `To_bottom ->
scrollable##scrollIntoView
(Js.Unsafe.inject (scroll_into_view_options `Bottom "smooth"))
| `To_top ->
scrollable##scrollIntoView
(Js.Unsafe.inject (scroll_into_view_options `Top "smooth"))))
;;
let control_browser path (To (i, k)) = the_effect (i, k, path)
let control path =
match Bonsai_web.am_running_how with
| `Browser | `Browser_benchmark -> control_browser path
| `Node_test -> control_test
| `Node | `Node_benchmark -> fun _ -> Effect.Ignore
;;
end
module Row_machine = struct
module Triple = struct
(** This type is pretty integral to the row selection state-machine. A
value of this type is stored as the "currently selected row" and also
as the result for "next row down" queries. *)
type 'k t =
{ key : 'k
; id : Int63.t
; index : int
}
[@@deriving sexp, equal]
end
module Range_response = struct
type 'k t =
| Yes
| No_but_this_one_is of 'k Triple.t
| Indeterminate
end
let collated_range collated =
( Collated.num_before_range collated
, Collated.num_before_range collated + Collated.length collated )
;;
let find_by collated ~f =
with_return_option (fun { return } ->
let i = ref (Collated.num_before_range collated) in
collated
|> Collated.to_map_list
|> Map.iteri ~f:(fun ~key:id ~data:(key, _) ->
if f ~key ~id ~index:!i
then return { Triple.key; id; index = !i }
else Int.incr i))
;;
let find_by_key collated ~key:needle ~key_equal =
find_by collated ~f:(fun ~key ~id:_ ~index:_ -> key_equal key needle)
;;
let find_by_id collated ~id:needle =
let map = Collated.to_map_list collated in
let r =
match Map.find map needle, Map.rank map needle with
| Some (key, _), Some rank ->
let index = Collated.num_before_range collated + rank in
Some { Triple.key; id = needle; index }
| _ -> None
in
r
;;
let find_by_index collated ~index:needle =
with_return (fun { return } ->
find_by collated ~f:(fun ~key:_ ~id:_ ~index ->
if index > needle then return None;
Int.equal index needle))
;;
let first_some list =
List.fold_until
list
~init:()
~f:(fun () opt ->
match Lazy.force opt with
| Some a -> Stop (Some a)
| None -> Continue ())
~finish:(fun () -> None)
;;
let fetch_or_fail collated ~index =
match find_by_index collated ~index with
| Some { Triple.key; id; index } ->
Range_response.No_but_this_one_is { key; id; index }
| None ->
eprint_s [%message [%here] "should be in range"];
Indeterminate
;;
Lookup for the value will first attempt to find the value in this order :
- lookup by key
- lookup by index
- lookup by i d
This function is potentially quite slow , but 99 % of the time , there will
be a hit on the first lookup , which is O(log n ) .
- lookup by key
- lookup by index
- lookup by id
This function is potentially quite slow, but 99% of the time, there will
be a hit on the first lookup, which is O(log n). *)
let find_in_range ~range:(range_start, range_end) ~collated ~key ~id ~index ~key_equal =
let col_start, col_end = collated_range collated in
if col_start > range_end || col_end < col_start
then Range_response.Indeterminate
else (
let attempt =
first_some
[ lazy (find_by_key collated ~key ~key_equal)
; lazy (find_by_index collated ~index)
; lazy (find_by_id collated ~id)
]
in
match attempt with
| Some ({ Triple.key = _; id = _; index } as triple) ->
if index >= range_start && index <= range_end
then Yes
else if index < range_start
then fetch_or_fail collated ~index:range_start
else if index > range_end
then fetch_or_fail collated ~index:range_end
else (
eprint_s [%message [%here] "unreachable" (triple : opaque Triple.t)];
Indeterminate)
| None ->
(match find_by_index collated ~index:range_start with
| Some r -> No_but_this_one_is r
| None -> Indeterminate))
;;
module Action = struct
type 'key t =
| Unfocus
| Up
| Down
| Page_up
| Page_down
| Recompute
| Select of 'key
[@@deriving sexp_of]
end
let component
(type key data cmp)
(key : (key, cmp) Bonsai.comparator)
~(on_change : (key option -> unit Effect.t) Value.t)
~(collated : (key, data) Incr_map_collate.Collated.t Value.t)
~(rows_covered_by_header : int Value.t)
~(range : (int * int) Value.t)
~(remapped : (key, Int63.t * data, cmp) Map.t Value.t)
~path
: key By_row.t Computation.t
=
let module Key = struct
include (val key)
let equal a b = comparator.compare a b = 0
end
in
let module Action = struct
include Action
type t = Key.t Action.t [@@deriving sexp_of]
end
in
let module Model = struct
(** [current] is the currently selected row.
[shadow] is the previously selected row.
Shadow is useful for computing "next row down" if the user previously
unfocused, or if the element that was previously selected has been
removed. *)
type t =
{ shadow : Key.t Triple.t option
; current : Key.t Triple.t option
}
[@@deriving sexp, equal]
let empty = { shadow = None; current = None }
end
in
let%sub input =
let%arr collated = collated
and path = path
and range = range
and rows_covered_by_header = rows_covered_by_header
and on_change = on_change in
collated, range, Scroll.control path, rows_covered_by_header, on_change
in
let apply_action
~inject:_
~schedule_event
( collated
, (range_start, range_end)
, scroll_control
, rows_covered_by_header
, on_change )
(model : Model.t)
action
=
let scroll_if_some triple ~how =
Option.iter triple ~f:(fun { Triple.id; index; _ } ->
let id =
if index < range_start + rows_covered_by_header
then (
match find_by_index collated ~index:(index - rows_covered_by_header) with
| Some { id; _ } -> id
| None -> id)
else id
in
schedule_event (scroll_control (how id)));
triple, None
in
let new_focus, new_shadow =
match (action : Action.t) with
| Select key ->
scroll_if_some (find_by_key ~key ~key_equal:Key.equal collated) ~how:(fun id ->
Scroll.To (id, `Minimal))
| Unfocus ->
(match model.current with
(* already unfocused *)
| None -> None, model.shadow
| Some current -> None, Some current)
| Down ->
scroll_if_some
(match model with
| { current = None; shadow = Some { index; _ } } ->
first_some
[ lazy (find_by_index collated ~index:(index + 1))
; lazy (find_by_index collated ~index)
]
| { current = None; shadow = None } ->
find_by_index collated ~index:range_start
| { current = Some { Triple.key; _ }; _ } ->
let%bind.Option { Triple.index; _ } =
find_by_key collated ~key ~key_equal:Key.equal
in
Option.first_some (find_by_index collated ~index:(index + 1)) model.current)
~how:(fun id -> To (id, `Minimal))
| Up ->
scroll_if_some
(match model with
| { current = None; shadow = Some { index; _ } } ->
find_by_index collated ~index:(index - 1)
| { current = None; shadow = None } ->
let index =
Int.min
range_end
(Collated.num_after_range collated + Collated.length collated)
in
first_some
[ lazy (find_by_index collated ~index:(index - 1))
; lazy (find_by_index collated ~index)
]
| { current = Some { Triple.key; _ }; _ } ->
let%bind.Option { Triple.index; _ } =
find_by_key collated ~key ~key_equal:Key.equal
in
Option.first_some (find_by_index collated ~index:(index - 1)) model.current)
~how:(fun id -> To (id, `Minimal))
| Page_down ->
scroll_if_some (find_by_index collated ~index:range_end) ~how:(fun id ->
To (id, `To_top))
| Page_up ->
scroll_if_some (find_by_index collated ~index:range_start) ~how:(fun id ->
To (id, `To_bottom))
| Recompute ->
let new_focus =
Option.bind model.current ~f:(fun { key; id; index } ->
match
find_in_range
~range:(range_start, range_end)
~collated
~key
~id
~index
~key_equal:Key.equal
with
| Yes -> model.current
| No_but_this_one_is triple -> Some triple
| Indeterminate -> None)
in
new_focus, model.shadow
in
let prev_key = model.current |> Option.map ~f:(fun t -> t.key)
and next_key = new_focus |> Option.map ~f:(fun t -> t.key) in
if not ([%equal: Key.t option] prev_key next_key)
then schedule_event (on_change next_key);
{ Model.current = new_focus; shadow = new_shadow }
in
let%sub ((model, inject) as machine) =
Bonsai.Incr.model_cutoff
@@ Bonsai.state_machine1
[%here]
(module Model)
(module Action)
~default_model:Model.empty
~apply_action
input
in
let module Forces_recalculation = struct
type t =
{ range : int * int
; num_before : int
; num_contained : int
}
[@@deriving equal, sexp]
end
in
let%sub () =
Bonsai.Edge.on_change
[%here]
(module Forces_recalculation)
(let%map range = range
and collated = collated in
{ Forces_recalculation.range
; num_before = Collated.num_before_range collated
; num_contained = Collated.num_filtered_rows collated
})
~callback:
(let%map inject = inject in
fun _ -> inject Recompute)
in
let%sub () =
The current focus being removed is a special case which requires unfocusing .
This has two effects :
- The model 's " current " will be set to None , which is what consumers
of the API will expect .
- Unfocus sets the " shadow " value , which is used to resume focus when the
user hits " up " or " down " .
This has two effects:
- The model's "current" will be set to None, which is what consumers
of the API will expect.
- Unfocus sets the "shadow" value, which is used to resume focus when the
user hits "up" or "down". *)
let%sub is_present =
Bonsai.Incr.compute (Bonsai.Value.both model remapped) ~f:(fun both ->
match%pattern_bind.Ui_incr both with
| { current = Some { key = current; _ }; _ }, map ->
let lookup = Ui_incr.Map.Lookup.create map ~comparator:Key.comparator in
let%bind.Ui_incr current = current in
Ui_incr.map (Ui_incr.Map.Lookup.find lookup current) ~f:Option.is_some
| { current = None; _ }, _ -> Ui_incr.return false)
in
Bonsai.Edge.on_change'
[%here]
(module Bool)
is_present
~callback:
(let%map _, inject = machine in
fun prev cur ->
match prev, cur with
The currently - focused value being removed causes an unfocus event .
| Some true, false -> inject Unfocus
| _ -> Effect.Ignore)
in
let%arr model, inject = machine in
{ By_row.focused = Option.map model.current ~f:(fun { key; _ } -> key)
; unfocus = inject Unfocus
; focus_up = inject Up
; focus_down = inject Down
; page_up = inject Page_up
; page_down = inject Page_down
; focus = (fun k -> inject (Select k))
}
;;
end
let component
: type kind key.
(kind, key) Kind.t
-> (key, _) Bonsai.comparator
-> collated:(key, _) Collated.t Value.t
-> rows_covered_by_header:int Value.t
-> range:_
-> remapped:(key, _, _) Map.t Value.t
-> path:_
-> kind Computation.t
=
fun kind ->
match kind with
| None ->
fun _ ~collated:_ ~rows_covered_by_header:_ ~range:_ ~remapped:_ ~path:_ ->
Bonsai.const ()
| By_row { on_change } -> Row_machine.component ~on_change
;;
let get_focused (type r k) : (r, k) Kind.t -> r Value.t -> k option Value.t =
fun kind value ->
match kind with
| None -> Bonsai.Value.return None
| By_row _ ->
let%map { focused; _ } = value in
focused
;;
let get_on_row_click (type r k) (kind : (r, k) Kind.t) (value : r Value.t)
: (k -> unit Effect.t) Value.t
=
match kind with
| None -> Value.return (fun _ -> Effect.Ignore)
| By_row _ ->
let%map { focus; _ } = value in
focus
;;
module For_testing = struct
module Range_response = Row_machine.Range_response
module Triple = Row_machine.Triple
let find_in_range = Row_machine.find_in_range
end
| null |
https://raw.githubusercontent.com/TyOverby/mono/7666c0328d194bf9a569fb65babc0486f2aaa40d/vendor/janestreet-bonsai/web_ui/partial_render_table/src/focus.ml
|
ocaml
|
* This type is pretty integral to the row selection state-machine. A
value of this type is stored as the "currently selected row" and also
as the result for "next row down" queries.
* [current] is the currently selected row.
[shadow] is the previously selected row.
Shadow is useful for computing "next row down" if the user previously
unfocused, or if the element that was previously selected has been
removed.
already unfocused
|
open! Core
open! Bonsai_web
open! Bonsai.Let_syntax
module Collated = Incr_map_collate.Collated
module By_row = struct
type 'k t =
{ focused : 'k option
; unfocus : unit Effect.t
; focus_up : unit Effect.t
; focus_down : unit Effect.t
; page_up : unit Effect.t
; page_down : unit Effect.t
; focus : 'k -> unit Effect.t
}
[@@deriving fields]
end
module Kind = struct
type ('a, 'k) t =
| None : (unit, 'k) t
| By_row : { on_change : ('k option -> unit Effect.t) Value.t } -> ('k By_row.t, 'k) t
end
module Scroll = struct
Top scrolls to the first row in the table
Bottom scrolls to the last row in the table
To ( i d , ` Minimal ) scrolls to [ i d ] , moving the screen as little as possible .
To ( i d , ` To_top ) scrolls the table such that [ i d ] is at the top of the screen .
To ( i d , ` To_bottom ) scrolls the table such that [ i d ] is at the bottom of the screen .
Bottom scrolls to the last row in the table
To (id, `Minimal) scrolls to [id], moving the screen as little as possible.
To (id, `To_top) scrolls the table such that [id] is at the top of the screen.
To (id, `To_bottom) scrolls the table such that [id] is at the bottom of the screen. *)
type t = To of Int63.t * [ `Minimal | `To_top | `To_bottom ]
let control_test = function
| To (i, `Minimal) ->
Effect.print_s [%message "scrolling to" (i : Int63.t) "minimizing scrolling"]
| To (i, `To_bottom) ->
Effect.print_s
[%message
"scrolling to"
(i : Int63.t)
"such that it is positioned at the bottom of the screen"]
| To (i, `To_top) ->
Effect.print_s
[%message
"scrolling to"
(i : Int63.t)
"such that it is positioned at the top of the screen"]
;;
let scroll_into_view_options align smooth =
let open Js_of_ocaml in
Constructs the options object described here :
-US/docs/Web/API/Element/scrollIntoView
-US/docs/Web/API/Element/scrollIntoView *)
object%js
val behavior = Js.string smooth
val block =
match align with
| `Top -> Js.string "start"
| `Bottom -> Js.string "end"
end
;;
let the_effect =
let open Js_of_ocaml in
Effect.of_sync_fun (fun (row_id, kind, path) ->
let selector =
[%string ".partial-render-table-%{path} [data-row-id=\"key_%{row_id#Int63}\"]"]
in
Js.Opt.iter
(Dom_html.document##querySelector (Js.string selector))
(fun element ->
let scrollable =
(Js.Unsafe.coerce element
: < scrollIntoViewIfNeeded : bool Js.t -> unit Js.meth
; scrollIntoView : Js.Unsafe.any -> unit Js.meth >
Js.t)
in
match kind with
| `Minimal -> scrollable##scrollIntoViewIfNeeded (Js.bool false)
| `To_bottom ->
scrollable##scrollIntoView
(Js.Unsafe.inject (scroll_into_view_options `Bottom "smooth"))
| `To_top ->
scrollable##scrollIntoView
(Js.Unsafe.inject (scroll_into_view_options `Top "smooth"))))
;;
let control_browser path (To (i, k)) = the_effect (i, k, path)
let control path =
match Bonsai_web.am_running_how with
| `Browser | `Browser_benchmark -> control_browser path
| `Node_test -> control_test
| `Node | `Node_benchmark -> fun _ -> Effect.Ignore
;;
end
module Row_machine = struct
module Triple = struct
type 'k t =
{ key : 'k
; id : Int63.t
; index : int
}
[@@deriving sexp, equal]
end
module Range_response = struct
type 'k t =
| Yes
| No_but_this_one_is of 'k Triple.t
| Indeterminate
end
let collated_range collated =
( Collated.num_before_range collated
, Collated.num_before_range collated + Collated.length collated )
;;
let find_by collated ~f =
with_return_option (fun { return } ->
let i = ref (Collated.num_before_range collated) in
collated
|> Collated.to_map_list
|> Map.iteri ~f:(fun ~key:id ~data:(key, _) ->
if f ~key ~id ~index:!i
then return { Triple.key; id; index = !i }
else Int.incr i))
;;
let find_by_key collated ~key:needle ~key_equal =
find_by collated ~f:(fun ~key ~id:_ ~index:_ -> key_equal key needle)
;;
let find_by_id collated ~id:needle =
let map = Collated.to_map_list collated in
let r =
match Map.find map needle, Map.rank map needle with
| Some (key, _), Some rank ->
let index = Collated.num_before_range collated + rank in
Some { Triple.key; id = needle; index }
| _ -> None
in
r
;;
let find_by_index collated ~index:needle =
with_return (fun { return } ->
find_by collated ~f:(fun ~key:_ ~id:_ ~index ->
if index > needle then return None;
Int.equal index needle))
;;
let first_some list =
List.fold_until
list
~init:()
~f:(fun () opt ->
match Lazy.force opt with
| Some a -> Stop (Some a)
| None -> Continue ())
~finish:(fun () -> None)
;;
let fetch_or_fail collated ~index =
match find_by_index collated ~index with
| Some { Triple.key; id; index } ->
Range_response.No_but_this_one_is { key; id; index }
| None ->
eprint_s [%message [%here] "should be in range"];
Indeterminate
;;
Lookup for the value will first attempt to find the value in this order :
- lookup by key
- lookup by index
- lookup by i d
This function is potentially quite slow , but 99 % of the time , there will
be a hit on the first lookup , which is O(log n ) .
- lookup by key
- lookup by index
- lookup by id
This function is potentially quite slow, but 99% of the time, there will
be a hit on the first lookup, which is O(log n). *)
let find_in_range ~range:(range_start, range_end) ~collated ~key ~id ~index ~key_equal =
let col_start, col_end = collated_range collated in
if col_start > range_end || col_end < col_start
then Range_response.Indeterminate
else (
let attempt =
first_some
[ lazy (find_by_key collated ~key ~key_equal)
; lazy (find_by_index collated ~index)
; lazy (find_by_id collated ~id)
]
in
match attempt with
| Some ({ Triple.key = _; id = _; index } as triple) ->
if index >= range_start && index <= range_end
then Yes
else if index < range_start
then fetch_or_fail collated ~index:range_start
else if index > range_end
then fetch_or_fail collated ~index:range_end
else (
eprint_s [%message [%here] "unreachable" (triple : opaque Triple.t)];
Indeterminate)
| None ->
(match find_by_index collated ~index:range_start with
| Some r -> No_but_this_one_is r
| None -> Indeterminate))
;;
module Action = struct
type 'key t =
| Unfocus
| Up
| Down
| Page_up
| Page_down
| Recompute
| Select of 'key
[@@deriving sexp_of]
end
let component
(type key data cmp)
(key : (key, cmp) Bonsai.comparator)
~(on_change : (key option -> unit Effect.t) Value.t)
~(collated : (key, data) Incr_map_collate.Collated.t Value.t)
~(rows_covered_by_header : int Value.t)
~(range : (int * int) Value.t)
~(remapped : (key, Int63.t * data, cmp) Map.t Value.t)
~path
: key By_row.t Computation.t
=
let module Key = struct
include (val key)
let equal a b = comparator.compare a b = 0
end
in
let module Action = struct
include Action
type t = Key.t Action.t [@@deriving sexp_of]
end
in
let module Model = struct
type t =
{ shadow : Key.t Triple.t option
; current : Key.t Triple.t option
}
[@@deriving sexp, equal]
let empty = { shadow = None; current = None }
end
in
let%sub input =
let%arr collated = collated
and path = path
and range = range
and rows_covered_by_header = rows_covered_by_header
and on_change = on_change in
collated, range, Scroll.control path, rows_covered_by_header, on_change
in
let apply_action
~inject:_
~schedule_event
( collated
, (range_start, range_end)
, scroll_control
, rows_covered_by_header
, on_change )
(model : Model.t)
action
=
let scroll_if_some triple ~how =
Option.iter triple ~f:(fun { Triple.id; index; _ } ->
let id =
if index < range_start + rows_covered_by_header
then (
match find_by_index collated ~index:(index - rows_covered_by_header) with
| Some { id; _ } -> id
| None -> id)
else id
in
schedule_event (scroll_control (how id)));
triple, None
in
let new_focus, new_shadow =
match (action : Action.t) with
| Select key ->
scroll_if_some (find_by_key ~key ~key_equal:Key.equal collated) ~how:(fun id ->
Scroll.To (id, `Minimal))
| Unfocus ->
(match model.current with
| None -> None, model.shadow
| Some current -> None, Some current)
| Down ->
scroll_if_some
(match model with
| { current = None; shadow = Some { index; _ } } ->
first_some
[ lazy (find_by_index collated ~index:(index + 1))
; lazy (find_by_index collated ~index)
]
| { current = None; shadow = None } ->
find_by_index collated ~index:range_start
| { current = Some { Triple.key; _ }; _ } ->
let%bind.Option { Triple.index; _ } =
find_by_key collated ~key ~key_equal:Key.equal
in
Option.first_some (find_by_index collated ~index:(index + 1)) model.current)
~how:(fun id -> To (id, `Minimal))
| Up ->
scroll_if_some
(match model with
| { current = None; shadow = Some { index; _ } } ->
find_by_index collated ~index:(index - 1)
| { current = None; shadow = None } ->
let index =
Int.min
range_end
(Collated.num_after_range collated + Collated.length collated)
in
first_some
[ lazy (find_by_index collated ~index:(index - 1))
; lazy (find_by_index collated ~index)
]
| { current = Some { Triple.key; _ }; _ } ->
let%bind.Option { Triple.index; _ } =
find_by_key collated ~key ~key_equal:Key.equal
in
Option.first_some (find_by_index collated ~index:(index - 1)) model.current)
~how:(fun id -> To (id, `Minimal))
| Page_down ->
scroll_if_some (find_by_index collated ~index:range_end) ~how:(fun id ->
To (id, `To_top))
| Page_up ->
scroll_if_some (find_by_index collated ~index:range_start) ~how:(fun id ->
To (id, `To_bottom))
| Recompute ->
let new_focus =
Option.bind model.current ~f:(fun { key; id; index } ->
match
find_in_range
~range:(range_start, range_end)
~collated
~key
~id
~index
~key_equal:Key.equal
with
| Yes -> model.current
| No_but_this_one_is triple -> Some triple
| Indeterminate -> None)
in
new_focus, model.shadow
in
let prev_key = model.current |> Option.map ~f:(fun t -> t.key)
and next_key = new_focus |> Option.map ~f:(fun t -> t.key) in
if not ([%equal: Key.t option] prev_key next_key)
then schedule_event (on_change next_key);
{ Model.current = new_focus; shadow = new_shadow }
in
let%sub ((model, inject) as machine) =
Bonsai.Incr.model_cutoff
@@ Bonsai.state_machine1
[%here]
(module Model)
(module Action)
~default_model:Model.empty
~apply_action
input
in
let module Forces_recalculation = struct
type t =
{ range : int * int
; num_before : int
; num_contained : int
}
[@@deriving equal, sexp]
end
in
let%sub () =
Bonsai.Edge.on_change
[%here]
(module Forces_recalculation)
(let%map range = range
and collated = collated in
{ Forces_recalculation.range
; num_before = Collated.num_before_range collated
; num_contained = Collated.num_filtered_rows collated
})
~callback:
(let%map inject = inject in
fun _ -> inject Recompute)
in
let%sub () =
The current focus being removed is a special case which requires unfocusing .
This has two effects :
- The model 's " current " will be set to None , which is what consumers
of the API will expect .
- Unfocus sets the " shadow " value , which is used to resume focus when the
user hits " up " or " down " .
This has two effects:
- The model's "current" will be set to None, which is what consumers
of the API will expect.
- Unfocus sets the "shadow" value, which is used to resume focus when the
user hits "up" or "down". *)
let%sub is_present =
Bonsai.Incr.compute (Bonsai.Value.both model remapped) ~f:(fun both ->
match%pattern_bind.Ui_incr both with
| { current = Some { key = current; _ }; _ }, map ->
let lookup = Ui_incr.Map.Lookup.create map ~comparator:Key.comparator in
let%bind.Ui_incr current = current in
Ui_incr.map (Ui_incr.Map.Lookup.find lookup current) ~f:Option.is_some
| { current = None; _ }, _ -> Ui_incr.return false)
in
Bonsai.Edge.on_change'
[%here]
(module Bool)
is_present
~callback:
(let%map _, inject = machine in
fun prev cur ->
match prev, cur with
The currently - focused value being removed causes an unfocus event .
| Some true, false -> inject Unfocus
| _ -> Effect.Ignore)
in
let%arr model, inject = machine in
{ By_row.focused = Option.map model.current ~f:(fun { key; _ } -> key)
; unfocus = inject Unfocus
; focus_up = inject Up
; focus_down = inject Down
; page_up = inject Page_up
; page_down = inject Page_down
; focus = (fun k -> inject (Select k))
}
;;
end
let component
: type kind key.
(kind, key) Kind.t
-> (key, _) Bonsai.comparator
-> collated:(key, _) Collated.t Value.t
-> rows_covered_by_header:int Value.t
-> range:_
-> remapped:(key, _, _) Map.t Value.t
-> path:_
-> kind Computation.t
=
fun kind ->
match kind with
| None ->
fun _ ~collated:_ ~rows_covered_by_header:_ ~range:_ ~remapped:_ ~path:_ ->
Bonsai.const ()
| By_row { on_change } -> Row_machine.component ~on_change
;;
let get_focused (type r k) : (r, k) Kind.t -> r Value.t -> k option Value.t =
fun kind value ->
match kind with
| None -> Bonsai.Value.return None
| By_row _ ->
let%map { focused; _ } = value in
focused
;;
let get_on_row_click (type r k) (kind : (r, k) Kind.t) (value : r Value.t)
: (k -> unit Effect.t) Value.t
=
match kind with
| None -> Value.return (fun _ -> Effect.Ignore)
| By_row _ ->
let%map { focus; _ } = value in
focus
;;
module For_testing = struct
module Range_response = Row_machine.Range_response
module Triple = Row_machine.Triple
let find_in_range = Row_machine.find_in_range
end
|
f03298869518601c5679df1f05e6d0f46706904dc828c423756721d46c563ea4
|
kind2-mc/kind2
|
lustreInput.mli
|
This file is part of the Kind 2 model checker .
Copyright ( c ) 2015 by the Board of Trustees of the University of Iowa
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 (c) 2015 by the Board of Trustees of the University of Iowa
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.
*)
* input into the intermediate Lustre format
An OCamllex lexer in { ! } and a Menhir parser in
{ ! } take the input and produce a sinlge { ! LustreAst.t }
value , which is a minimally processed representation of a Lustre
AST .
This AST is then translated into a simplified , see
{ ! } , and { ! } for the translation .
The main function { ! of_file } of this module returns a system for
the analysis strategies that can be turned into an internal
transition system { ! TransSys } by using functions in
{ ! } with relevant parameters .
The whole input file is parsed and type checked first , then one
node is designated as the main node . The returned { ! Subsystem.t }
has this main node at the top , and all called nodes as
children . Nodes that are in the input file , but not called by the
main node are discarded . No further cone of influence reduction is
peformed yet , this happens only in { ! } when the
parameters of the analysis are known .
The main node is chosen to be , in order of precedence :
- the node with the name given by the [ --lustre_main ] command - line
option ,
- the node with the annotation [ --%MAIN ] , or
- the last node in the input .
An exception [ Invalid_argument ] is raised if the node given by
[ --lustre_main ] is not found , there are two nodes with a [ --%MAIN ]
annotation , or the input contains no nodes .
In particular , the output of the entry point { ! LustreParser.main }
returns a file as a list of declarations of
- types [ type t = t ' ] ,
- global constants [ const c = v ] , and
- nodes [ node X ( ... ) returns ( ... ) ; let ... tel ] .
A node is viewed as a tuple of an identifier , a list of inputs , a
list of outputs , declarations of local constants and variables ,
and equations . An equation is either an assignment of an
expression to a variable , an assertion , a property annotation , or
flag to mark the node as the top node .
The function { ! LustreSimplify.declarations_to_nodes } is called
with this list of declarations as input and produces a list of
{ ! } that contains each node with expressions in a
normalized form , with structured fields unfolded , constants
propagated and type aliases substituted .
In detail , the process of normalizing an expression in a node
abstracts every non - variable expression under a [ pre ] operator
into a fresh local variable . All [ - > ] operators are lifted to the
top of the expression so that an expression can be represented as
a pair of expressions , one for the first instant and one for the
following . Each variable at the previous state i the left argument
to the [ - > ] operator in the resulting expression is replaced with
a fresh oracle constant per variable that is added to the inputs
of the node .
Node calls are factored out into assignments to fresh local
variables , where input expressions are further abstracted to fresh
local variables . A node call may be wrapped in a condact with an
activation condition and default values .
In detail , { ! } is a record representing a node with
- [ name ] an identifier
- [ inputs ] the list of input variables
After finding the designated main node with
{ ! LustreNode.find_main } , the definitions in the main node and list
of nodes is reduced to the nodes in the cone of influence of the
properties of the main node , see
{ ! LustreNode.reduce_to_property_coi } . Last , the equational
definitions of each node are ordered by their dependencies with
{ ! LustreNode.reduce_to_property_coi } .
The module { ! } turns the list of nodes into a
transition system { ! TransSys.t } by means of the functions
{ ! LustreTransSys.trans_sys_of_nodes } and
{ ! LustreTransSys.props_of_nodes } .
@author
An OCamllex lexer in {!LustreLexer} and a Menhir parser in
{!LustreParser} take the input and produce a sinlge {!LustreAst.t}
value, which is a minimally processed representation of a Lustre
AST.
This AST is then translated into a simplified Lustre, see
{!LustreNode}, and {!LustreDeclarations} for the translation.
The main function {!of_file} of this module returns a system for
the analysis strategies that can be turned into an internal
transition system {!TransSys} by using functions in
{!LustreTransSys} with relevant parameters.
The whole input file is parsed and type checked first, then one
node is designated as the main node. The returned {!Subsystem.t}
has this main node at the top, and all called nodes as
children. Nodes that are in the input file, but not called by the
main node are discarded. No further cone of influence reduction is
peformed yet, this happens only in {!LustreTransSys} when the
parameters of the analysis are known.
The main node is chosen to be, in order of precedence:
- the node with the name given by the [--lustre_main] command-line
option,
- the node with the annotation [--%MAIN], or
- the last node in the input.
An exception [Invalid_argument] is raised if the node given by
[--lustre_main] is not found, there are two nodes with a [--%MAIN]
annotation, or the input contains no nodes.
In particular, the output of the entry point {!LustreParser.main}
returns a Lustre file as a list of declarations of
- types [type t = t'],
- global constants [const c = v], and
- nodes [node X (...) returns (...); let ... tel].
A node is viewed as a tuple of an identifier, a list of inputs, a
list of outputs, declarations of local constants and variables,
and equations. An equation is either an assignment of an
expression to a variable, an assertion, a property annotation, or
flag to mark the node as the top node.
The function {!LustreSimplify.declarations_to_nodes} is called
with this list of declarations as input and produces a list of
{!LustreNode.t} that contains each node with expressions in a
normalized form, with structured fields unfolded, constants
propagated and type aliases substituted.
In detail, the process of normalizing an expression in a node
abstracts every non-variable expression under a [pre] operator
into a fresh local variable. All [->] operators are lifted to the
top of the expression so that an expression can be represented as
a pair of expressions, one for the first instant and one for the
following. Each variable at the previous state i the left argument
to the [->] operator in the resulting expression is replaced with
a fresh oracle constant per variable that is added to the inputs
of the node.
Node calls are factored out into assignments to fresh local
variables, where input expressions are further abstracted to fresh
local variables. A node call may be wrapped in a condact with an
activation condition and default values.
In detail, {!LustreNode.t} is a record representing a node with
- [name] an identifier
- [inputs] the list of input variables
After finding the designated main node with
{!LustreNode.find_main}, the definitions in the main node and list
of nodes is reduced to the nodes in the cone of influence of the
properties of the main node, see
{!LustreNode.reduce_to_property_coi}. Last, the equational
definitions of each node are ordered by their dependencies with
{!LustreNode.reduce_to_property_coi}.
The module {!LustreTransSys} turns the list of nodes into a
transition system {!TransSys.t} by means of the functions
{!LustreTransSys.trans_sys_of_nodes} and
{!LustreTransSys.props_of_nodes}.
@author Christoph Sticksel
*)
exception NoMainNode of string
type error = [
| `LustreArrayDependencies of Lib.position * LustreArrayDependencies.error_kind
| `LustreAstDependenciesError of Lib.position * LustreAstDependencies.error_kind
| `LustreAstInlineConstantsError of Lib.position * LustreAstInlineConstants.error_kind
| `LustreAstNormalizerError
| `LustreSyntaxChecksError of Lib.position * LustreSyntaxChecks.error_kind
| `LustreTypeCheckerError of Lib.position * LustreTypeChecker.error_kind
| `LustreUnguardedPreError of Lib.position * LustreAst.expr
| `LustreParserError of Lib.position * string
| `LustreDesugarIfBlocksError of Lib.position * LustreDesugarIfBlocks.error_kind
| `LustreDesugarFrameBlocksError of Lib.position * LustreDesugarFrameBlocks.error_kind
]
* [ of_file only_parse f ] parse Lustre model from file [ f ] , and
return [ None ] if [ only_parse ] is true , or an input system
otherwise .
If a syntax or semantic error is detected , it triggers
a [ Parser_error ] exception . If [ only_parse ] is false , and
the Lustre model does n't include a main node , it triggers a
{ ! NoMainNode } exception .
return [None] if [only_parse] is true, or an input system
otherwise.
If a syntax or semantic error is detected, it triggers
a [Parser_error] exception. If [only_parse] is false, and
the Lustre model doesn't include a main node, it triggers a
{!NoMainNode} exception.
*)
val of_file :
?old_frontend:bool -> bool -> string ->
((LustreNode.t SubSystem.t list * LustreGlobals.t * LustreAst.t) option, [> error]) result
* from the file , return the AST .
val ast_of_file : string -> (LustreAst.t, [> error]) result
Local Variables :
compile - command : " make -C .. -k "
tuareg - interactive - program : " ./kind2.top -I ./_build -I / SExpr "
indent - tabs - mode : nil
End :
Local Variables:
compile-command: "make -C .. -k"
tuareg-interactive-program: "./kind2.top -I ./_build -I ./_build/SExpr"
indent-tabs-mode: nil
End:
*)
| null |
https://raw.githubusercontent.com/kind2-mc/kind2/d34694b4461323322fdcc291aa3c3d9c453fc098/src/lustre/lustreInput.mli
|
ocaml
|
This file is part of the Kind 2 model checker .
Copyright ( c ) 2015 by the Board of Trustees of the University of Iowa
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 (c) 2015 by the Board of Trustees of the University of Iowa
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.
*)
* input into the intermediate Lustre format
An OCamllex lexer in { ! } and a Menhir parser in
{ ! } take the input and produce a sinlge { ! LustreAst.t }
value , which is a minimally processed representation of a Lustre
AST .
This AST is then translated into a simplified , see
{ ! } , and { ! } for the translation .
The main function { ! of_file } of this module returns a system for
the analysis strategies that can be turned into an internal
transition system { ! TransSys } by using functions in
{ ! } with relevant parameters .
The whole input file is parsed and type checked first , then one
node is designated as the main node . The returned { ! Subsystem.t }
has this main node at the top , and all called nodes as
children . Nodes that are in the input file , but not called by the
main node are discarded . No further cone of influence reduction is
peformed yet , this happens only in { ! } when the
parameters of the analysis are known .
The main node is chosen to be , in order of precedence :
- the node with the name given by the [ --lustre_main ] command - line
option ,
- the node with the annotation [ --%MAIN ] , or
- the last node in the input .
An exception [ Invalid_argument ] is raised if the node given by
[ --lustre_main ] is not found , there are two nodes with a [ --%MAIN ]
annotation , or the input contains no nodes .
In particular , the output of the entry point { ! LustreParser.main }
returns a file as a list of declarations of
- types [ type t = t ' ] ,
- global constants [ const c = v ] , and
- nodes [ node X ( ... ) returns ( ... ) ; let ... tel ] .
A node is viewed as a tuple of an identifier , a list of inputs , a
list of outputs , declarations of local constants and variables ,
and equations . An equation is either an assignment of an
expression to a variable , an assertion , a property annotation , or
flag to mark the node as the top node .
The function { ! LustreSimplify.declarations_to_nodes } is called
with this list of declarations as input and produces a list of
{ ! } that contains each node with expressions in a
normalized form , with structured fields unfolded , constants
propagated and type aliases substituted .
In detail , the process of normalizing an expression in a node
abstracts every non - variable expression under a [ pre ] operator
into a fresh local variable . All [ - > ] operators are lifted to the
top of the expression so that an expression can be represented as
a pair of expressions , one for the first instant and one for the
following . Each variable at the previous state i the left argument
to the [ - > ] operator in the resulting expression is replaced with
a fresh oracle constant per variable that is added to the inputs
of the node .
Node calls are factored out into assignments to fresh local
variables , where input expressions are further abstracted to fresh
local variables . A node call may be wrapped in a condact with an
activation condition and default values .
In detail , { ! } is a record representing a node with
- [ name ] an identifier
- [ inputs ] the list of input variables
After finding the designated main node with
{ ! LustreNode.find_main } , the definitions in the main node and list
of nodes is reduced to the nodes in the cone of influence of the
properties of the main node , see
{ ! LustreNode.reduce_to_property_coi } . Last , the equational
definitions of each node are ordered by their dependencies with
{ ! LustreNode.reduce_to_property_coi } .
The module { ! } turns the list of nodes into a
transition system { ! TransSys.t } by means of the functions
{ ! LustreTransSys.trans_sys_of_nodes } and
{ ! LustreTransSys.props_of_nodes } .
@author
An OCamllex lexer in {!LustreLexer} and a Menhir parser in
{!LustreParser} take the input and produce a sinlge {!LustreAst.t}
value, which is a minimally processed representation of a Lustre
AST.
This AST is then translated into a simplified Lustre, see
{!LustreNode}, and {!LustreDeclarations} for the translation.
The main function {!of_file} of this module returns a system for
the analysis strategies that can be turned into an internal
transition system {!TransSys} by using functions in
{!LustreTransSys} with relevant parameters.
The whole input file is parsed and type checked first, then one
node is designated as the main node. The returned {!Subsystem.t}
has this main node at the top, and all called nodes as
children. Nodes that are in the input file, but not called by the
main node are discarded. No further cone of influence reduction is
peformed yet, this happens only in {!LustreTransSys} when the
parameters of the analysis are known.
The main node is chosen to be, in order of precedence:
- the node with the name given by the [--lustre_main] command-line
option,
- the node with the annotation [--%MAIN], or
- the last node in the input.
An exception [Invalid_argument] is raised if the node given by
[--lustre_main] is not found, there are two nodes with a [--%MAIN]
annotation, or the input contains no nodes.
In particular, the output of the entry point {!LustreParser.main}
returns a Lustre file as a list of declarations of
- types [type t = t'],
- global constants [const c = v], and
- nodes [node X (...) returns (...); let ... tel].
A node is viewed as a tuple of an identifier, a list of inputs, a
list of outputs, declarations of local constants and variables,
and equations. An equation is either an assignment of an
expression to a variable, an assertion, a property annotation, or
flag to mark the node as the top node.
The function {!LustreSimplify.declarations_to_nodes} is called
with this list of declarations as input and produces a list of
{!LustreNode.t} that contains each node with expressions in a
normalized form, with structured fields unfolded, constants
propagated and type aliases substituted.
In detail, the process of normalizing an expression in a node
abstracts every non-variable expression under a [pre] operator
into a fresh local variable. All [->] operators are lifted to the
top of the expression so that an expression can be represented as
a pair of expressions, one for the first instant and one for the
following. Each variable at the previous state i the left argument
to the [->] operator in the resulting expression is replaced with
a fresh oracle constant per variable that is added to the inputs
of the node.
Node calls are factored out into assignments to fresh local
variables, where input expressions are further abstracted to fresh
local variables. A node call may be wrapped in a condact with an
activation condition and default values.
In detail, {!LustreNode.t} is a record representing a node with
- [name] an identifier
- [inputs] the list of input variables
After finding the designated main node with
{!LustreNode.find_main}, the definitions in the main node and list
of nodes is reduced to the nodes in the cone of influence of the
properties of the main node, see
{!LustreNode.reduce_to_property_coi}. Last, the equational
definitions of each node are ordered by their dependencies with
{!LustreNode.reduce_to_property_coi}.
The module {!LustreTransSys} turns the list of nodes into a
transition system {!TransSys.t} by means of the functions
{!LustreTransSys.trans_sys_of_nodes} and
{!LustreTransSys.props_of_nodes}.
@author Christoph Sticksel
*)
exception NoMainNode of string
type error = [
| `LustreArrayDependencies of Lib.position * LustreArrayDependencies.error_kind
| `LustreAstDependenciesError of Lib.position * LustreAstDependencies.error_kind
| `LustreAstInlineConstantsError of Lib.position * LustreAstInlineConstants.error_kind
| `LustreAstNormalizerError
| `LustreSyntaxChecksError of Lib.position * LustreSyntaxChecks.error_kind
| `LustreTypeCheckerError of Lib.position * LustreTypeChecker.error_kind
| `LustreUnguardedPreError of Lib.position * LustreAst.expr
| `LustreParserError of Lib.position * string
| `LustreDesugarIfBlocksError of Lib.position * LustreDesugarIfBlocks.error_kind
| `LustreDesugarFrameBlocksError of Lib.position * LustreDesugarFrameBlocks.error_kind
]
* [ of_file only_parse f ] parse Lustre model from file [ f ] , and
return [ None ] if [ only_parse ] is true , or an input system
otherwise .
If a syntax or semantic error is detected , it triggers
a [ Parser_error ] exception . If [ only_parse ] is false , and
the Lustre model does n't include a main node , it triggers a
{ ! NoMainNode } exception .
return [None] if [only_parse] is true, or an input system
otherwise.
If a syntax or semantic error is detected, it triggers
a [Parser_error] exception. If [only_parse] is false, and
the Lustre model doesn't include a main node, it triggers a
{!NoMainNode} exception.
*)
val of_file :
?old_frontend:bool -> bool -> string ->
((LustreNode.t SubSystem.t list * LustreGlobals.t * LustreAst.t) option, [> error]) result
* from the file , return the AST .
val ast_of_file : string -> (LustreAst.t, [> error]) result
Local Variables :
compile - command : " make -C .. -k "
tuareg - interactive - program : " ./kind2.top -I ./_build -I / SExpr "
indent - tabs - mode : nil
End :
Local Variables:
compile-command: "make -C .. -k"
tuareg-interactive-program: "./kind2.top -I ./_build -I ./_build/SExpr"
indent-tabs-mode: nil
End:
*)
|
|
52f4bd24d53ca0e15676e138f46baaae19398a22c11dfcd856002117b08ae6ef
|
IagoAbal/haskell-z3
|
Spec.hs
|
module Z3.Monad.Spec
( spec )
where
import Test.Hspec
import qualified Z3.Monad as Z3
import Control.Monad.IO.Class (liftIO)
import Example.Monad.IntList ( mkIntListDatatype )
assertFuncName :: Z3.FuncDecl -> String -> Z3.Z3 ()
assertFuncName f expected = do actual <- Z3.getDeclName f >>= Z3.getSymbolString
liftIO $ actual `shouldBe` expected
spec :: Spec
spec = do
context "Example using assert-soft" $ do
specify "model should satisfy hard constraint" $ do
(x3,x4) <- liftIO (Z3.evalZ3 (do
int <- Z3.mkIntSort
def <- Z3.mkStringSymbol "default"
x1 <- Z3.mkFreshIntVar "x1"
x2 <- Z3.mkFreshIntVar "x2"
x3 <- Z3.mkFreshIntVar "x3"
x4 <- Z3.mkFreshIntVar "x4"
i0 <- Z3.mkIntNum 0
i2 <- Z3.mkIntNum 2
i4 <- Z3.mkIntNum 4
i6 <- Z3.mkIntNum 6
i8 <- Z3.mkIntNum 8
Z3.optimizeAssert =<< Z3.mkNot =<< Z3.mkEq i0 =<< Z3.mkAdd [x1, x2]
Z3.optimizeAssert =<< Z3.mkNot =<< Z3.mkEq i0 =<< Z3.mkAdd [x2, x3]
Z3.optimizeAssert =<< Z3.mkEq i0 =<< Z3.mkAdd [x3, x4]
eq1 <- Z3.mkEq x1 i2
eq2 <- Z3.mkEq x2 i4
eq3 <- Z3.mkEq x3 i6
eq4 <- Z3.mkEq x4 i8
Z3.optimizeAssertSoft eq1 "1" def
Z3.optimizeAssertSoft eq2 "1" def
Z3.optimizeAssertSoft eq3 "1" def
Z3.optimizeAssertSoft eq4 "1" def
_ <- Z3.optimizeCheck []
model <- Z3.optimizeGetModel
x3v <- Z3.evalInt model x3
x4v <- Z3.evalInt model x4
return (x3v, x4v)
))
(x3,x4) `shouldSatisfy` (\(x3, x4) -> case (x3, x4) of
(Just x3, Just x4) -> x3 + x4 == 0
_ -> False)
context "IntList example with assertions" $ do
specify "should run" $ do
Z3.evalZ3 $ do
intList <- mkIntListDatatype
[nilC, consC] <- Z3.getDatatypeSortConstructors intList
[nilR, consR] <- Z3.getDatatypeSortRecognizers intList
[[],[hdA, tlA]] <- Z3.getDatatypeSortConstructorAccessors intList
assertFuncName nilC "nil"
assertFuncName consC "cons"
assertFuncName hdA "hd"
assertFuncName tlA "tl"
nil <- Z3.mkApp nilC []
fortyTwo <- Z3.mkInteger 42
fiftySeven <- Z3.mkInteger 57
l1 <- Z3.mkApp consC [ fortyTwo, nil]
l2 <- Z3.mkApp consC [ fiftySeven, nil]
eightyTwo <- Z3.mkInteger 82
l3 <- Z3.mkApp consC [ eightyTwo, l1]
l4 <- Z3.mkApp consC [ eightyTwo, l2]
Z3.push
Z3.assert =<< Z3.mkEq nil l1
r <- Z3.check
liftIO $ r `shouldBe` Z3.Unsat
Z3.pop 1
Z3.push
boolS <- Z3.mkBoolSort
-- Build the list-equiv function
listEquivSym <- Z3.mkStringSymbol "list-equiv"
listEquivF <- Z3.mkRecFuncDecl listEquivSym [intList, intList] boolS
l1s <- Z3.mkFreshConst "l1a" intList
l2s <- Z3.mkFreshConst "l2a" intList
rnil1 <- Z3.mkApp nilR [l1s]
rnil2 <- Z3.mkApp nilR [l2s]
nilPred <- Z3.mkAnd [rnil1, rnil2] -- Both lists are nil
First list is cons
Second list is cons
hd1 <- Z3.mkApp hdA [l1s]
one <- Z3.mkInteger 1
hd1' <- Z3.mkAdd [hd1, one]
hd2 <- Z3.mkApp hdA [l2s]
First head + 1 = second head
tl1 <- Z3.mkApp tlA [l1s]
tl2 <- Z3.mkApp tlA [l2s]
list - equiv tl1 tl2
consPred <- Z3.mkAnd [rcons1, rcons2, hdeq, tlequiv]
equivBody <- Z3.mkOr [nilPred, consPred] -- lists are nil or cons and equivalent
-- Define the body of the function
Z3.addRecDef listEquivF [l1s, l2s] equivBody
Z3.push
let listToAST [] = Z3.mkApp nilC []
listToAST (n:ns) = do
ns' <- listToAST ns
nn <- Z3.mkInteger n
Z3.mkApp consC [ nn, ns' ]
let twoListsEquiv l1 l2 = do Z3.push
l1' <- listToAST l1
l2' <- listToAST l2
Z3.mkApp listEquivF [l1', l2'] >>= Z3.mkNot >>= Z3.assert
r <- Z3.check
liftIO $ r `shouldBe` if map (+1) l1 == l2 then Z3.Unsat else Z3.Sat
Z3.pop 1
twoListsEquiv [] [] -- equiv
twoListsEquiv [1] [1] -- not equiv
twoListsEquiv [1] [2] -- equiv
twoListsEquiv [1] [2,2] -- not equiv
twoListsEquiv [1,2,3] [2,3,4] -- equiv
twoListsEquiv [1,2,3,4,5,6] [2,3,4,5,6,6] -- not equiv
twoListsEquiv [1,2,3,4] [2,3,4] -- not equiv
twoListsEquiv [1,2,3,4,5,5,6] [2,3,4,5,6,6,7] -- equiv
| null |
https://raw.githubusercontent.com/IagoAbal/haskell-z3/ba5c2907c06a7844a78cf1fb87dae60f9b6ee6df/test/Z3/Monad/Spec.hs
|
haskell
|
Build the list-equiv function
Both lists are nil
lists are nil or cons and equivalent
Define the body of the function
equiv
not equiv
equiv
not equiv
equiv
not equiv
not equiv
equiv
|
module Z3.Monad.Spec
( spec )
where
import Test.Hspec
import qualified Z3.Monad as Z3
import Control.Monad.IO.Class (liftIO)
import Example.Monad.IntList ( mkIntListDatatype )
assertFuncName :: Z3.FuncDecl -> String -> Z3.Z3 ()
assertFuncName f expected = do actual <- Z3.getDeclName f >>= Z3.getSymbolString
liftIO $ actual `shouldBe` expected
spec :: Spec
spec = do
context "Example using assert-soft" $ do
specify "model should satisfy hard constraint" $ do
(x3,x4) <- liftIO (Z3.evalZ3 (do
int <- Z3.mkIntSort
def <- Z3.mkStringSymbol "default"
x1 <- Z3.mkFreshIntVar "x1"
x2 <- Z3.mkFreshIntVar "x2"
x3 <- Z3.mkFreshIntVar "x3"
x4 <- Z3.mkFreshIntVar "x4"
i0 <- Z3.mkIntNum 0
i2 <- Z3.mkIntNum 2
i4 <- Z3.mkIntNum 4
i6 <- Z3.mkIntNum 6
i8 <- Z3.mkIntNum 8
Z3.optimizeAssert =<< Z3.mkNot =<< Z3.mkEq i0 =<< Z3.mkAdd [x1, x2]
Z3.optimizeAssert =<< Z3.mkNot =<< Z3.mkEq i0 =<< Z3.mkAdd [x2, x3]
Z3.optimizeAssert =<< Z3.mkEq i0 =<< Z3.mkAdd [x3, x4]
eq1 <- Z3.mkEq x1 i2
eq2 <- Z3.mkEq x2 i4
eq3 <- Z3.mkEq x3 i6
eq4 <- Z3.mkEq x4 i8
Z3.optimizeAssertSoft eq1 "1" def
Z3.optimizeAssertSoft eq2 "1" def
Z3.optimizeAssertSoft eq3 "1" def
Z3.optimizeAssertSoft eq4 "1" def
_ <- Z3.optimizeCheck []
model <- Z3.optimizeGetModel
x3v <- Z3.evalInt model x3
x4v <- Z3.evalInt model x4
return (x3v, x4v)
))
(x3,x4) `shouldSatisfy` (\(x3, x4) -> case (x3, x4) of
(Just x3, Just x4) -> x3 + x4 == 0
_ -> False)
context "IntList example with assertions" $ do
specify "should run" $ do
Z3.evalZ3 $ do
intList <- mkIntListDatatype
[nilC, consC] <- Z3.getDatatypeSortConstructors intList
[nilR, consR] <- Z3.getDatatypeSortRecognizers intList
[[],[hdA, tlA]] <- Z3.getDatatypeSortConstructorAccessors intList
assertFuncName nilC "nil"
assertFuncName consC "cons"
assertFuncName hdA "hd"
assertFuncName tlA "tl"
nil <- Z3.mkApp nilC []
fortyTwo <- Z3.mkInteger 42
fiftySeven <- Z3.mkInteger 57
l1 <- Z3.mkApp consC [ fortyTwo, nil]
l2 <- Z3.mkApp consC [ fiftySeven, nil]
eightyTwo <- Z3.mkInteger 82
l3 <- Z3.mkApp consC [ eightyTwo, l1]
l4 <- Z3.mkApp consC [ eightyTwo, l2]
Z3.push
Z3.assert =<< Z3.mkEq nil l1
r <- Z3.check
liftIO $ r `shouldBe` Z3.Unsat
Z3.pop 1
Z3.push
boolS <- Z3.mkBoolSort
listEquivSym <- Z3.mkStringSymbol "list-equiv"
listEquivF <- Z3.mkRecFuncDecl listEquivSym [intList, intList] boolS
l1s <- Z3.mkFreshConst "l1a" intList
l2s <- Z3.mkFreshConst "l2a" intList
rnil1 <- Z3.mkApp nilR [l1s]
rnil2 <- Z3.mkApp nilR [l2s]
First list is cons
Second list is cons
hd1 <- Z3.mkApp hdA [l1s]
one <- Z3.mkInteger 1
hd1' <- Z3.mkAdd [hd1, one]
hd2 <- Z3.mkApp hdA [l2s]
First head + 1 = second head
tl1 <- Z3.mkApp tlA [l1s]
tl2 <- Z3.mkApp tlA [l2s]
list - equiv tl1 tl2
consPred <- Z3.mkAnd [rcons1, rcons2, hdeq, tlequiv]
Z3.addRecDef listEquivF [l1s, l2s] equivBody
Z3.push
let listToAST [] = Z3.mkApp nilC []
listToAST (n:ns) = do
ns' <- listToAST ns
nn <- Z3.mkInteger n
Z3.mkApp consC [ nn, ns' ]
let twoListsEquiv l1 l2 = do Z3.push
l1' <- listToAST l1
l2' <- listToAST l2
Z3.mkApp listEquivF [l1', l2'] >>= Z3.mkNot >>= Z3.assert
r <- Z3.check
liftIO $ r `shouldBe` if map (+1) l1 == l2 then Z3.Unsat else Z3.Sat
Z3.pop 1
|
9da044f61aa2f9f18dcd73b18a93e790a9b50f2a5f25c5e047d3e62a9d36d27f
|
mewa/clojure-k8s
|
policy.clj
|
(ns kubernetes.api.policy
(:require [kubernetes.core :refer [call-api check-required-params with-collection-format]])
(:import (java.io File)))
(defn get-policy-api-group-with-http-info
"
get information of a group"
[]
(call-api "/apis/policy/" :get
{:path-params {}
:header-params {}
:query-params {}
:form-params {}
:content-types ["application/json" "application/yaml" "application/vnd.kubernetes.protobuf"]
:accepts ["application/json" "application/yaml" "application/vnd.kubernetes.protobuf"]
:auth-names ["BearerToken" "HTTPBasic"]}))
(defn get-policy-api-group
"
get information of a group"
[]
(:data (get-policy-api-group-with-http-info)))
| null |
https://raw.githubusercontent.com/mewa/clojure-k8s/a7e8d82f0e0bc47e5678c72d7d9b8216080ccffc/src/kubernetes/api/policy.clj
|
clojure
|
(ns kubernetes.api.policy
(:require [kubernetes.core :refer [call-api check-required-params with-collection-format]])
(:import (java.io File)))
(defn get-policy-api-group-with-http-info
"
get information of a group"
[]
(call-api "/apis/policy/" :get
{:path-params {}
:header-params {}
:query-params {}
:form-params {}
:content-types ["application/json" "application/yaml" "application/vnd.kubernetes.protobuf"]
:accepts ["application/json" "application/yaml" "application/vnd.kubernetes.protobuf"]
:auth-names ["BearerToken" "HTTPBasic"]}))
(defn get-policy-api-group
"
get information of a group"
[]
(:data (get-policy-api-group-with-http-info)))
|
|
05a8f6311d3c15a6204bdc13fdaa96e50ddf6ff9dc1a6cfac625358abf270cb6
|
bpanthi977/nlopt
|
package.lisp
|
package.lisp
(defpackage #:nlopt.cffi
(:use #:cl))
(defpackage #:nlopt
(:use #:cl)
(:local-nicknames (:c :nlopt.cffi))
(:export #:copy
#:algorithm
#:dimensions
#:algorithms
#:algorithm-name
#:create
#:set-min-objective
#:set-max-objective
#:set-precond-min-objective
#:set-precond-max-objective
#:add-inequality-constraint
#:add-equality-constraint
#:remove-inequality
#:remove-equality
#:add-inequality-mconstraints
#:add-equality-mconstraints
#:lower-bounds
#:upper-bounds
#:lower-bound
#:upper-bound
#:stopval
#:ftol-rel
#:ftol-abs
#:xtol-rel
#:x-weights
#:xtol-abs
#:maxeval
#:maxtime
#:numevals
#:force-stop
#:force-stop-value
#:optimize-nlopt
#:nloptimize
#:set-local-optimizer
#:initial-step
#:set-population
#:srand
#:srand-time
#:vector-storage
#:result-description
#:version))
| null |
https://raw.githubusercontent.com/bpanthi977/nlopt/675b4862cd3b3f54c91801f0a8e27b7ba32afbb5/package.lisp
|
lisp
|
package.lisp
(defpackage #:nlopt.cffi
(:use #:cl))
(defpackage #:nlopt
(:use #:cl)
(:local-nicknames (:c :nlopt.cffi))
(:export #:copy
#:algorithm
#:dimensions
#:algorithms
#:algorithm-name
#:create
#:set-min-objective
#:set-max-objective
#:set-precond-min-objective
#:set-precond-max-objective
#:add-inequality-constraint
#:add-equality-constraint
#:remove-inequality
#:remove-equality
#:add-inequality-mconstraints
#:add-equality-mconstraints
#:lower-bounds
#:upper-bounds
#:lower-bound
#:upper-bound
#:stopval
#:ftol-rel
#:ftol-abs
#:xtol-rel
#:x-weights
#:xtol-abs
#:maxeval
#:maxtime
#:numevals
#:force-stop
#:force-stop-value
#:optimize-nlopt
#:nloptimize
#:set-local-optimizer
#:initial-step
#:set-population
#:srand
#:srand-time
#:vector-storage
#:result-description
#:version))
|
|
4c2379cb196cffd9dc6e9b92ca2ad88e0cdd54fec5da9ea568e3d7135fe3ed50
|
input-output-hk/plutus
|
Lib.hs
|
-- editorconfig-checker-disable-file
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TypeApplications #
{-# LANGUAGE TypeOperators #-}
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -Wno - orphans #
module Lib where
import Control.Exception
import Control.Lens
import Control.Monad.Except
import Data.Either.Extras
import Data.Maybe (fromJust)
import Data.Text (Text)
import Flat (Flat)
import Test.Tasty.Extras
import PlutusPrelude
import PlutusCore.Test
import PlutusTx.Code
import PlutusCore qualified as PLC
import PlutusCore.Evaluation.Machine.ExBudgetingDefaults qualified as PLC
import PlutusCore.Pretty
import UntypedPlutusCore qualified as UPLC
import UntypedPlutusCore.Evaluation.Machine.Cek
instance (PLC.Closed uni, uni `PLC.Everywhere` Flat, Flat fun) =>
ToUPlc (CompiledCodeIn uni fun a) uni fun where
toUPlc v = do
v' <- catchAll $ getPlcNoAnn v
toUPlc v'
goldenPir
:: (PLC.Closed uni, uni `PLC.Everywhere` PrettyConst, uni `PLC.Everywhere` Flat, Pretty (PLC.SomeTypeIn uni), Pretty fun, Flat fun)
=> String -> CompiledCodeIn uni fun a -> TestNested
goldenPir name value = nestedGoldenVsDoc name $ pretty $ getPirNoAnn value
runPlcCek :: ToUPlc a PLC.DefaultUni PLC.DefaultFun => [a] -> ExceptT SomeException IO (UPLC.Term PLC.Name PLC.DefaultUni PLC.DefaultFun ())
runPlcCek values = do
ps <- traverse toUPlc values
let p = foldl1 (fromJust .* UPLC.applyProgram) ps
fromRightM (throwError . SomeException) $ evaluateCekNoEmit PLC.defaultCekParameters (p ^. UPLC.progTerm)
runPlcCekTrace ::
ToUPlc a PLC.DefaultUni PLC.DefaultFun =>
[a] ->
ExceptT SomeException IO ([Text], CekExTally PLC.DefaultFun, UPLC.Term PLC.Name PLC.DefaultUni PLC.DefaultFun ())
runPlcCekTrace values = do
ps <- traverse toUPlc values
let p = foldl1 (fromJust .* UPLC.applyProgram) ps
let (result, TallyingSt tally _, logOut) = runCek PLC.defaultCekParameters tallying logEmitter (p ^. UPLC.progTerm)
res <- fromRightM (throwError . SomeException) result
pure (logOut, tally, res)
goldenEvalCek :: ToUPlc a PLC.DefaultUni PLC.DefaultFun => String -> [a] -> TestNested
goldenEvalCek name values = nestedGoldenVsDocM name $ prettyPlcClassicDebug <$> (rethrow $ runPlcCek values)
goldenEvalCekLog :: ToUPlc a PLC.DefaultUni PLC.DefaultFun => String -> [a] -> TestNested
goldenEvalCekLog name values = nestedGoldenVsDocM name $ pretty . view _1 <$> (rethrow $ runPlcCekTrace values)
| null |
https://raw.githubusercontent.com/input-output-hk/plutus/bb9b5a18c26476fbf6b2f446ab267706426fec3a/plutus-tx-plugin/test/Lib.hs
|
haskell
|
editorconfig-checker-disable-file
# LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleContexts #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeOperators #
|
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeApplications #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -Wno - orphans #
module Lib where
import Control.Exception
import Control.Lens
import Control.Monad.Except
import Data.Either.Extras
import Data.Maybe (fromJust)
import Data.Text (Text)
import Flat (Flat)
import Test.Tasty.Extras
import PlutusPrelude
import PlutusCore.Test
import PlutusTx.Code
import PlutusCore qualified as PLC
import PlutusCore.Evaluation.Machine.ExBudgetingDefaults qualified as PLC
import PlutusCore.Pretty
import UntypedPlutusCore qualified as UPLC
import UntypedPlutusCore.Evaluation.Machine.Cek
instance (PLC.Closed uni, uni `PLC.Everywhere` Flat, Flat fun) =>
ToUPlc (CompiledCodeIn uni fun a) uni fun where
toUPlc v = do
v' <- catchAll $ getPlcNoAnn v
toUPlc v'
goldenPir
:: (PLC.Closed uni, uni `PLC.Everywhere` PrettyConst, uni `PLC.Everywhere` Flat, Pretty (PLC.SomeTypeIn uni), Pretty fun, Flat fun)
=> String -> CompiledCodeIn uni fun a -> TestNested
goldenPir name value = nestedGoldenVsDoc name $ pretty $ getPirNoAnn value
runPlcCek :: ToUPlc a PLC.DefaultUni PLC.DefaultFun => [a] -> ExceptT SomeException IO (UPLC.Term PLC.Name PLC.DefaultUni PLC.DefaultFun ())
runPlcCek values = do
ps <- traverse toUPlc values
let p = foldl1 (fromJust .* UPLC.applyProgram) ps
fromRightM (throwError . SomeException) $ evaluateCekNoEmit PLC.defaultCekParameters (p ^. UPLC.progTerm)
runPlcCekTrace ::
ToUPlc a PLC.DefaultUni PLC.DefaultFun =>
[a] ->
ExceptT SomeException IO ([Text], CekExTally PLC.DefaultFun, UPLC.Term PLC.Name PLC.DefaultUni PLC.DefaultFun ())
runPlcCekTrace values = do
ps <- traverse toUPlc values
let p = foldl1 (fromJust .* UPLC.applyProgram) ps
let (result, TallyingSt tally _, logOut) = runCek PLC.defaultCekParameters tallying logEmitter (p ^. UPLC.progTerm)
res <- fromRightM (throwError . SomeException) result
pure (logOut, tally, res)
goldenEvalCek :: ToUPlc a PLC.DefaultUni PLC.DefaultFun => String -> [a] -> TestNested
goldenEvalCek name values = nestedGoldenVsDocM name $ prettyPlcClassicDebug <$> (rethrow $ runPlcCek values)
goldenEvalCekLog :: ToUPlc a PLC.DefaultUni PLC.DefaultFun => String -> [a] -> TestNested
goldenEvalCekLog name values = nestedGoldenVsDocM name $ pretty . view _1 <$> (rethrow $ runPlcCekTrace values)
|
5157070d8c3e20482f85335451421e89af69050e30a459efc86c71d4f8221723
|
let-def/lrgrep
|
Tabulate.ml
|
(******************************************************************************)
(* *)
(* Fix *)
(* *)
, Paris
(* *)
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
(* special exception on linking, as described in the file LICENSE. *)
(* *)
(******************************************************************************)
open Sigs
module Make
(F : FINITE_TYPE)
(M : MINIMAL_IMPERATIVE_MAPS with type key = F.t)
= struct
type key = M.key
let tabulate (f : key -> 'a) : key -> 'a =
let table = M.create() in
F.foreach (fun x -> M.add x (f x) table);
fun x ->
try
M.find x table
with Not_found ->
(* This cannot happen if [foreach] is exhaustive. *)
let msg = Printf.sprintf "\n Fix.Tabulate says: \
please check that your \"foreach\" function is \
exhaustive.\n %s\n" __LOC__ in
raise (Invalid_argument msg)
end
module ForOrderedType
(F : FINITE_TYPE)
(T : OrderedType with type t = F.t)
=
Make(F)(Glue.PersistentMapsToImperativeMaps(Map.Make(T)))
module ForHashedType
(F : FINITE_TYPE)
(T : HashedType with type t = F.t)
=
Make(F)(Glue.HashTablesAsImperativeMaps(T))
module ForType (F : FINITE_TYPE) =
ForHashedType(F)(Glue.TrivialHashedType(F))
module ForIntSegment (K : sig val n: int end) = struct
type key = int
let tabulate (f : key -> 'a) : key -> 'a =
let table = Array.init K.n f in
fun x ->
table.(x)
end
| null |
https://raw.githubusercontent.com/let-def/lrgrep/29e64174dc9617bcd1871fd2e4fd712269568324/lib/fix/Tabulate.ml
|
ocaml
|
****************************************************************************
Fix
special exception on linking, as described in the file LICENSE.
****************************************************************************
This cannot happen if [foreach] is exhaustive.
|
, Paris
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
open Sigs
module Make
(F : FINITE_TYPE)
(M : MINIMAL_IMPERATIVE_MAPS with type key = F.t)
= struct
type key = M.key
let tabulate (f : key -> 'a) : key -> 'a =
let table = M.create() in
F.foreach (fun x -> M.add x (f x) table);
fun x ->
try
M.find x table
with Not_found ->
let msg = Printf.sprintf "\n Fix.Tabulate says: \
please check that your \"foreach\" function is \
exhaustive.\n %s\n" __LOC__ in
raise (Invalid_argument msg)
end
module ForOrderedType
(F : FINITE_TYPE)
(T : OrderedType with type t = F.t)
=
Make(F)(Glue.PersistentMapsToImperativeMaps(Map.Make(T)))
module ForHashedType
(F : FINITE_TYPE)
(T : HashedType with type t = F.t)
=
Make(F)(Glue.HashTablesAsImperativeMaps(T))
module ForType (F : FINITE_TYPE) =
ForHashedType(F)(Glue.TrivialHashedType(F))
module ForIntSegment (K : sig val n: int end) = struct
type key = int
let tabulate (f : key -> 'a) : key -> 'a =
let table = Array.init K.n f in
fun x ->
table.(x)
end
|
49deb8020778bd619be27de265f50cd3cd3365f2e0517d6d9a198f74fcb7b198
|
phoe-trash/gateway
|
standard-kernel.lisp
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; GATEWAY
" phoe " Herda 2017
;;;; classes/standard-kernel.lisp
(in-package :gateway/impl)
(in-readtable protest)
(defclass standard-kernel (kernel)
((%kernel :accessor %kernel)
(%channel :accessor channel)
(%cleaner :accessor cleaner)
(%handler :accessor handler
:initarg :handler
:initform (error "Must provide a handler function."))
(%name :accessor name))
(:documentation #.(format nil "A standard implementation of Gateway protocol ~
class KERNEL.
This kernel contains a lparallel kernel. The kernel workers each call the ~
handler function with the message as its argument. That function executes a ~
single iteration of the kernel's job and is not meant to loop.
TODO these below lines belong to the framework, not the class
The default implementation of the handler function is the exported function ~
#'STANDARD-KERNEL-OPERATION.
The messages are expected to be in form (CONNECTION COMMAND . REST), where ~
CONNECTION is a connection object from which MESSAGE came; REST is ignored ~
and reserved for future use.")))
(define-print (standard-kernel stream)
(if (alivep standard-kernel)
(format stream "(~D workers, ALIVE)"
(worker-count standard-kernel))
(format stream "(DEAD)")))
(defun worker-count (kernel)
(check-type kernel standard-kernel)
(let ((lparallel:*kernel* (%kernel kernel)))
(lparallel:kernel-worker-count)))
(define-constructor (standard-kernel threads)
(let* ((threads (or threads
(config :kernel-threads)
(cl-cpus:get-number-of-processors)))
(name "Gateway - Kernel, ~D threads" cpus))
(v:trace :gateway "Standard kernel starting with ~D threads." threads)
(setf (name standard-kernel) name
(%kernel standard-kernel)
(lparallel:make-kernel threads
:name (cat name " (lparallel kernel)")))
(let ((lparallel:*kernel* (%kernel standard-kernel)))
(setf (channel standard-kernel) (lparallel:make-channel)
(cleaner standard-kernel)
(make-thread
(lambda ()
(loop (lparallel:receive-result (channel standard-kernel))))
:name "Gateway - Kernel cleaner thread")))))
(defmethod deadp ((kernel standard-kernel))
(not (lparallel.kernel::alivep (%kernel kernel))))
(defmethod kill ((kernel standard-kernel))
(v:trace :gateway "Standard kernel was killed.")
(let ((lparallel:*kernel* (%kernel kernel)))
(lparallel:end-kernel :wait t))
(destroy-thread (cleaner kernel))
(values))
(defmethod enqueue ((kernel standard-kernel) message)
(lparallel:submit-task (channel kernel) (handler kernel) message)
t)
;;; TESTS
TODO separate tests from code
(define-test-case standard-kernel-death
(:description "Test of KILLABLE protocol for STANDARD-LISTENER."
:tags (:protocol :killable :kernel)
:type :protocol)
:arrange
1 "Create a kernel."
2 "Assert the kernel is alive."
:act
3 "Kill the kernel."
:assert
4 "Assert the kernel is dead.")
(define-test standard-kernel-death
(let* ((kernel #1?(make-instance 'standard-kernel :handler (constantly nil))))
#2?(is (alivep kernel))
#3?(kill kernel)
#4?(is (wait () (deadp kernel)))))
(define-test-case standard-kernel
(:description "Test the kernel's enqueueing functionality."
:tags (:implementation :kernel)
:type :implementation)
:arrange
1 "Create a handler that atomically (with a lock) increases a variable that ~
is initially 0."
2 "Create a kernel."
3 "Prepare a shuffled list of integers from 1 to 100."
:act
4 "Submit 100 tasks to the kernel which increase the variable by an integer."
:assert
5 "Assert the variable is = to 5050."
6 "Assert no more results are available in the channel.")
(define-test standard-kernel
(finalized-let*
((var 0)
(lock (make-lock "STANDARD-KERNEL test lock"))
(handler #1?(lambda (x) (with-lock-held (lock) (incf var x))))
(kernel #2?(make-instance 'standard-kernel :handler handler)
(kill kernel))
(tasks #3?(shuffle (iota 100 :start 1))))
#4?(dolist (i tasks)
(is (enqueue kernel i)))
#5?(is (wait () (with-lock-held (lock) (= var 5050))))
(sleep 0.1)
#6?(is (wait () (equal '(nil nil)
(multiple-value-list
(lparallel.queue:peek-queue
(lparallel.kernel::channel-queue
(channel kernel)))))))))
| null |
https://raw.githubusercontent.com/phoe-trash/gateway/a8d579ccbafcaee8678caf59d365ec2eab0b1a7e/impl/standard-kernel.lisp
|
lisp
|
GATEWAY
classes/standard-kernel.lisp
REST is ignored ~
TESTS
|
" phoe " Herda 2017
(in-package :gateway/impl)
(in-readtable protest)
(defclass standard-kernel (kernel)
((%kernel :accessor %kernel)
(%channel :accessor channel)
(%cleaner :accessor cleaner)
(%handler :accessor handler
:initarg :handler
:initform (error "Must provide a handler function."))
(%name :accessor name))
(:documentation #.(format nil "A standard implementation of Gateway protocol ~
class KERNEL.
This kernel contains a lparallel kernel. The kernel workers each call the ~
handler function with the message as its argument. That function executes a ~
single iteration of the kernel's job and is not meant to loop.
TODO these below lines belong to the framework, not the class
The default implementation of the handler function is the exported function ~
#'STANDARD-KERNEL-OPERATION.
The messages are expected to be in form (CONNECTION COMMAND . REST), where ~
and reserved for future use.")))
(define-print (standard-kernel stream)
(if (alivep standard-kernel)
(format stream "(~D workers, ALIVE)"
(worker-count standard-kernel))
(format stream "(DEAD)")))
(defun worker-count (kernel)
(check-type kernel standard-kernel)
(let ((lparallel:*kernel* (%kernel kernel)))
(lparallel:kernel-worker-count)))
(define-constructor (standard-kernel threads)
(let* ((threads (or threads
(config :kernel-threads)
(cl-cpus:get-number-of-processors)))
(name "Gateway - Kernel, ~D threads" cpus))
(v:trace :gateway "Standard kernel starting with ~D threads." threads)
(setf (name standard-kernel) name
(%kernel standard-kernel)
(lparallel:make-kernel threads
:name (cat name " (lparallel kernel)")))
(let ((lparallel:*kernel* (%kernel standard-kernel)))
(setf (channel standard-kernel) (lparallel:make-channel)
(cleaner standard-kernel)
(make-thread
(lambda ()
(loop (lparallel:receive-result (channel standard-kernel))))
:name "Gateway - Kernel cleaner thread")))))
(defmethod deadp ((kernel standard-kernel))
(not (lparallel.kernel::alivep (%kernel kernel))))
(defmethod kill ((kernel standard-kernel))
(v:trace :gateway "Standard kernel was killed.")
(let ((lparallel:*kernel* (%kernel kernel)))
(lparallel:end-kernel :wait t))
(destroy-thread (cleaner kernel))
(values))
(defmethod enqueue ((kernel standard-kernel) message)
(lparallel:submit-task (channel kernel) (handler kernel) message)
t)
TODO separate tests from code
(define-test-case standard-kernel-death
(:description "Test of KILLABLE protocol for STANDARD-LISTENER."
:tags (:protocol :killable :kernel)
:type :protocol)
:arrange
1 "Create a kernel."
2 "Assert the kernel is alive."
:act
3 "Kill the kernel."
:assert
4 "Assert the kernel is dead.")
(define-test standard-kernel-death
(let* ((kernel #1?(make-instance 'standard-kernel :handler (constantly nil))))
#2?(is (alivep kernel))
#3?(kill kernel)
#4?(is (wait () (deadp kernel)))))
(define-test-case standard-kernel
(:description "Test the kernel's enqueueing functionality."
:tags (:implementation :kernel)
:type :implementation)
:arrange
1 "Create a handler that atomically (with a lock) increases a variable that ~
is initially 0."
2 "Create a kernel."
3 "Prepare a shuffled list of integers from 1 to 100."
:act
4 "Submit 100 tasks to the kernel which increase the variable by an integer."
:assert
5 "Assert the variable is = to 5050."
6 "Assert no more results are available in the channel.")
(define-test standard-kernel
(finalized-let*
((var 0)
(lock (make-lock "STANDARD-KERNEL test lock"))
(handler #1?(lambda (x) (with-lock-held (lock) (incf var x))))
(kernel #2?(make-instance 'standard-kernel :handler handler)
(kill kernel))
(tasks #3?(shuffle (iota 100 :start 1))))
#4?(dolist (i tasks)
(is (enqueue kernel i)))
#5?(is (wait () (with-lock-held (lock) (= var 5050))))
(sleep 0.1)
#6?(is (wait () (equal '(nil nil)
(multiple-value-list
(lparallel.queue:peek-queue
(lparallel.kernel::channel-queue
(channel kernel)))))))))
|
54d6ac719fd4f44ff560592d0a0bfdfad85b74a4e6bb8bdba1373d0e87d8ba23
|
reborg/clojure-essential-reference
|
1.clj
|
(foldcat [coll])
(cat ([])
([ctor])
([left right]))
(append! [acc el])
| null |
https://raw.githubusercontent.com/reborg/clojure-essential-reference/c37fa19d45dd52b2995a191e3e96f0ebdc3f6d69/ReducersandTransducers/Reducers/foldcat%2Ccatandappend!/1.clj
|
clojure
|
(foldcat [coll])
(cat ([])
([ctor])
([left right]))
(append! [acc el])
|
|
f210f38574b323464a932b13cb68df5ed2c029e8c5913e3bad09d12064654f5e
|
bishboria/learnyouahaskell
|
15_zipping_lists.hs
|
type ListZipper a = ([a],[a])
goForward :: ListZipper a -> ListZipper a
goForward (x:xs, bs) = (xs, x:bs)
goBack :: ListZipper a -> ListZipper a
goBack (xs, b:bs) = (b:xs, bs)
xs = [1,2,3,4]
a = goForward (xs, [])
b = goForward ([2,3,4], [1])
c = goForward ([3,4],[2,1])
d = goBack ([4],[3,2,1])
| null |
https://raw.githubusercontent.com/bishboria/learnyouahaskell/d8c7b41398e9672db18c1b1360372fc4a4adefa8/15/15_zipping_lists.hs
|
haskell
|
type ListZipper a = ([a],[a])
goForward :: ListZipper a -> ListZipper a
goForward (x:xs, bs) = (xs, x:bs)
goBack :: ListZipper a -> ListZipper a
goBack (xs, b:bs) = (b:xs, bs)
xs = [1,2,3,4]
a = goForward (xs, [])
b = goForward ([2,3,4], [1])
c = goForward ([3,4],[2,1])
d = goBack ([4],[3,2,1])
|
|
8e885f6e3060fd2999fd9ba5dda45b99f4435acf42a5546efd0a234d90fc8efd
|
rizo/snowflake-os
|
fonts.ml
|
module BDF = struct
type bbox = {
width : int;
height : int;
x_offset : int;
y_offset : int;
}
type glyph = {
dwidth : int * int;
bbox : bbox;
data : bool array array;
}
type weight = Normal | Bold
type slant = Regular | Italic
type font = {
family : string;
weight : weight;
slant : slant;
size : int;
ascent : int;
descent : int;
glyphs : glyph option array;
global_bbox : bbox;
}
open ExtList;;
open ExtString;;
type bbox = {
width : int ;
height : int ;
x_offset : int ;
y_offset : int ;
} ; ;
type glyph = {
dwidth : int * int ;
bbox : bbox ;
data : bool array array ;
} ; ;
type weight = Normal | Bold ; ;
type slant = Regular | Italic ; ;
type font = {
family : string ;
weight : weight ;
slant : slant ;
size : int ;
ascent : int ;
descent : int ;
glyphs : glyph option array ;
global_bbox : bbox ;
} ; ;
type bbox = {
width: int;
height: int;
x_offset: int;
y_offset: int;
};;
type glyph = {
dwidth: int * int;
bbox: bbox;
data: bool array array;
};;
type weight = Normal | Bold;;
type slant = Regular | Italic;;
type font = {
family: string;
weight: weight;
slant: slant;
size: int;
ascent: int;
descent: int;
glyphs: glyph option array;
global_bbox: bbox;
};;*)
external id : 'a -> 'a = "%identity";;
let return a = a;;
let find_header headers string = List.find
(fun str -> String.starts_with str string) headers;;
let load_glyph_data_row data w =
let array = Array.create w false in
let arr2 = Array.create (String.length data / 2) 0 in
for i = 0 to String.length data / 2 - 1 do
arr2.(i) <- Scanf.sscanf (String.sub data (i * 2) 2) "%x" id
done;
for i = 0 to w - 1 do
array.(i) <- arr2.(i/8) land (1 lsl (7-(i mod 8))) <> 0;
done;
return array;;
let load_glyph_data data w h =
let glyph = Array.create_matrix h w false in
List.iteri (fun i s -> glyph.(i) <- load_glyph_data_row s w) data;
return glyph;;
let load_glyph list =
let header,data = List.takewhile ((<>) "BITMAP ") list, List.tl (List.dropwhile ((<>) "BITMAP ") list) in
let find_header = find_header header in
let dwidth = find_header "DWIDTH "
and bbx = find_header "BBX " in
let bbox = Scanf.sscanf bbx "BBX %d %d %d %d%!" (fun w h x y -> { width = w; height = h; x_offset = x; y_offset = y; }) in {
dwidth = Scanf.sscanf dwidth "DWIDTH %d %d%!" (fun w h -> w,h);
bbox = bbox;
data = load_glyph_data data bbox.width bbox.height;
};;
let load_glyphs list =
let list = List.tl list in
let glyphs = List.fold_right (fun string xl -> if string = "ENDCHAR" then []::xl else (string::(List.hd xl))::(List.tl xl)) list [[]] in
let array = Array.init 65536 (fun _ -> None) in
List.iter (fun glyph -> try Scanf.sscanf (List.hd (List.tl glyph)) "ENCODING %d" (fun i -> array.(i) <- Some (load_glyph glyph)) with _ -> ()) glyphs;
return array;;
let load data =
let header,data =
let ix = ref None and i = ref 0 in
while !ix = None do
if String.starts_with data.(!i) "CHARS " then ix := Some !i else incr i
done;
Array.to_list (Array.sub data 0 (Option.get !ix)), Array.to_list (Array.sub data (Option.get !ix) (Array.length data - (Option.get !ix))) in
let find_header = find_header header in
let family = find_header "FAMILY_NAME "
and weight = find_header "WEIGHT_NAME "
and slant = find_header "SLANT "
and ascent = find_header "FONT_ASCENT "
and descent = find_header "FONT_DESCENT "
and size = find_header "SIZE "
and bbx = find_header "FONTBOUNDINGBOX "
and glyphs = load_glyphs data in {
family = Scanf.sscanf family "FAMILY_NAME %S%!" id;
weight = Scanf.sscanf weight "WEIGHT_NAME %S%!" (function "Bold" -> Bold | _ -> Normal);
slant = Scanf.sscanf slant "SLANT %S%!" (function "I" -> Italic | _ -> Regular);
size = Scanf.sscanf size "SIZE %d %d %d%!" (fun pt _ _ -> pt);
ascent = Scanf.sscanf ascent "FONT_ASCENT %d%!" id;
descent = Scanf.sscanf descent "FONT_DESCENT %d%!" id;
global_bbox = Scanf.sscanf bbx "FONTBOUNDINGBOX %d %d %d %d%!" (fun w h x y -> { width = w; height = h; x_offset = x; y_offset = y; });
glyphs = glyphs;
};;
(* some reason, the slant field is always Regular, so hack around to fix it *)
let fonts =
let f1 = Marshal.from_string FontData.courO14 0 in
let f2 = Marshal.from_string FontData.courBO14 0 in
ref [
Marshal.from_string FontData.courR14 0;
Marshal.from_string FontData.courB14 0;
{ f1 with slant = Italic };
{ f2 with slant = Italic };
load (Marshal.from_string FontData.unifont 0);
]
let get family weight slant size =
List.find begin fun font ->
font.family = family && font.weight = weight && font.slant = slant && font.size = size
end !fonts
end
open BDF
open Bigarray
open ExtString
plots a pixel at coords [ x , y ] with colour [ r , , b ]
let plot fb x y (r,g,b) =
if y >= 0 && y < Array2.dim1 fb && x >= 0 && x < Array2.dim2 fb then
fb.{y,x} <- Int32.of_int ((r lsl 16) lor (g lsl 8) lor b)
let draw_uchar fb code font (px,py) fg bg =
match font.glyphs.(code) with
| None -> (px,py)
| Some g ->
for x = 0 to g.bbox.width - 1 do
for y = 0 to g.bbox.height - 1 do
if g.data.(y).(x) then
plot fb
(px + x + g.bbox.x_offset)
(py - (g.bbox.height - y) - g.bbox.y_offset)
fg
else
plot fb
(px + x + g.bbox.x_offset)
(py - (g.bbox.height - y) - g.bbox.y_offset)
bg;
done;
done;
fst g.dwidth, snd g.dwidth
(* draws the specified character from given font at [px,py] with [colour],
and returns the position to use for drawing the next character *)
let draw_char fb ch font (px,py) colour =
draw_uchar fb (int_of_char ch) font (px,py) colour (0,0,0)
match font.glyphs.(int_of_char ch ) with
| None - > ( px , py )
| Some g - >
for x = 0 to g.bbox.width - 1 do
for y = 0 to - 1 do
if g.data.(y).(x ) then
plot fb
( px + x + g.bbox.x_offset )
( py - ( g.bbox.height - y ) - g.bbox.y_offset )
colour ;
done ;
done ;
px + fst g.dwidth , py + snd g.dwidth
| None -> (px,py)
| Some g ->
for x = 0 to g.bbox.width - 1 do
for y = 0 to g.bbox.height - 1 do
if g.data.(y).(x) then
plot fb
(px + x + g.bbox.x_offset)
(py - (g.bbox.height - y) - g.bbox.y_offset)
colour;
done;
done;
px + fst g.dwidth, py + snd g.dwidth*)
let draw_text fb text font origin colour =
String.fold_left begin fun point ch ->
draw_char fb ch font point colour
end origin text
let measure_text text font =
String.fold_left begin fun width ch ->
match font.glyphs.(int_of_char ch) with
| None -> width
| Some g -> width + fst g.dwidth
end 0 text, font.ascent + font.descent
| null |
https://raw.githubusercontent.com/rizo/snowflake-os/51df43d9ba715532d325e8880d3b8b2c589cd075/kernel/fonts.ml
|
ocaml
|
some reason, the slant field is always Regular, so hack around to fix it
draws the specified character from given font at [px,py] with [colour],
and returns the position to use for drawing the next character
|
module BDF = struct
type bbox = {
width : int;
height : int;
x_offset : int;
y_offset : int;
}
type glyph = {
dwidth : int * int;
bbox : bbox;
data : bool array array;
}
type weight = Normal | Bold
type slant = Regular | Italic
type font = {
family : string;
weight : weight;
slant : slant;
size : int;
ascent : int;
descent : int;
glyphs : glyph option array;
global_bbox : bbox;
}
open ExtList;;
open ExtString;;
type bbox = {
width : int ;
height : int ;
x_offset : int ;
y_offset : int ;
} ; ;
type glyph = {
dwidth : int * int ;
bbox : bbox ;
data : bool array array ;
} ; ;
type weight = Normal | Bold ; ;
type slant = Regular | Italic ; ;
type font = {
family : string ;
weight : weight ;
slant : slant ;
size : int ;
ascent : int ;
descent : int ;
glyphs : glyph option array ;
global_bbox : bbox ;
} ; ;
type bbox = {
width: int;
height: int;
x_offset: int;
y_offset: int;
};;
type glyph = {
dwidth: int * int;
bbox: bbox;
data: bool array array;
};;
type weight = Normal | Bold;;
type slant = Regular | Italic;;
type font = {
family: string;
weight: weight;
slant: slant;
size: int;
ascent: int;
descent: int;
glyphs: glyph option array;
global_bbox: bbox;
};;*)
external id : 'a -> 'a = "%identity";;
let return a = a;;
let find_header headers string = List.find
(fun str -> String.starts_with str string) headers;;
let load_glyph_data_row data w =
let array = Array.create w false in
let arr2 = Array.create (String.length data / 2) 0 in
for i = 0 to String.length data / 2 - 1 do
arr2.(i) <- Scanf.sscanf (String.sub data (i * 2) 2) "%x" id
done;
for i = 0 to w - 1 do
array.(i) <- arr2.(i/8) land (1 lsl (7-(i mod 8))) <> 0;
done;
return array;;
let load_glyph_data data w h =
let glyph = Array.create_matrix h w false in
List.iteri (fun i s -> glyph.(i) <- load_glyph_data_row s w) data;
return glyph;;
let load_glyph list =
let header,data = List.takewhile ((<>) "BITMAP ") list, List.tl (List.dropwhile ((<>) "BITMAP ") list) in
let find_header = find_header header in
let dwidth = find_header "DWIDTH "
and bbx = find_header "BBX " in
let bbox = Scanf.sscanf bbx "BBX %d %d %d %d%!" (fun w h x y -> { width = w; height = h; x_offset = x; y_offset = y; }) in {
dwidth = Scanf.sscanf dwidth "DWIDTH %d %d%!" (fun w h -> w,h);
bbox = bbox;
data = load_glyph_data data bbox.width bbox.height;
};;
let load_glyphs list =
let list = List.tl list in
let glyphs = List.fold_right (fun string xl -> if string = "ENDCHAR" then []::xl else (string::(List.hd xl))::(List.tl xl)) list [[]] in
let array = Array.init 65536 (fun _ -> None) in
List.iter (fun glyph -> try Scanf.sscanf (List.hd (List.tl glyph)) "ENCODING %d" (fun i -> array.(i) <- Some (load_glyph glyph)) with _ -> ()) glyphs;
return array;;
let load data =
let header,data =
let ix = ref None and i = ref 0 in
while !ix = None do
if String.starts_with data.(!i) "CHARS " then ix := Some !i else incr i
done;
Array.to_list (Array.sub data 0 (Option.get !ix)), Array.to_list (Array.sub data (Option.get !ix) (Array.length data - (Option.get !ix))) in
let find_header = find_header header in
let family = find_header "FAMILY_NAME "
and weight = find_header "WEIGHT_NAME "
and slant = find_header "SLANT "
and ascent = find_header "FONT_ASCENT "
and descent = find_header "FONT_DESCENT "
and size = find_header "SIZE "
and bbx = find_header "FONTBOUNDINGBOX "
and glyphs = load_glyphs data in {
family = Scanf.sscanf family "FAMILY_NAME %S%!" id;
weight = Scanf.sscanf weight "WEIGHT_NAME %S%!" (function "Bold" -> Bold | _ -> Normal);
slant = Scanf.sscanf slant "SLANT %S%!" (function "I" -> Italic | _ -> Regular);
size = Scanf.sscanf size "SIZE %d %d %d%!" (fun pt _ _ -> pt);
ascent = Scanf.sscanf ascent "FONT_ASCENT %d%!" id;
descent = Scanf.sscanf descent "FONT_DESCENT %d%!" id;
global_bbox = Scanf.sscanf bbx "FONTBOUNDINGBOX %d %d %d %d%!" (fun w h x y -> { width = w; height = h; x_offset = x; y_offset = y; });
glyphs = glyphs;
};;
let fonts =
let f1 = Marshal.from_string FontData.courO14 0 in
let f2 = Marshal.from_string FontData.courBO14 0 in
ref [
Marshal.from_string FontData.courR14 0;
Marshal.from_string FontData.courB14 0;
{ f1 with slant = Italic };
{ f2 with slant = Italic };
load (Marshal.from_string FontData.unifont 0);
]
let get family weight slant size =
List.find begin fun font ->
font.family = family && font.weight = weight && font.slant = slant && font.size = size
end !fonts
end
open BDF
open Bigarray
open ExtString
plots a pixel at coords [ x , y ] with colour [ r , , b ]
let plot fb x y (r,g,b) =
if y >= 0 && y < Array2.dim1 fb && x >= 0 && x < Array2.dim2 fb then
fb.{y,x} <- Int32.of_int ((r lsl 16) lor (g lsl 8) lor b)
let draw_uchar fb code font (px,py) fg bg =
match font.glyphs.(code) with
| None -> (px,py)
| Some g ->
for x = 0 to g.bbox.width - 1 do
for y = 0 to g.bbox.height - 1 do
if g.data.(y).(x) then
plot fb
(px + x + g.bbox.x_offset)
(py - (g.bbox.height - y) - g.bbox.y_offset)
fg
else
plot fb
(px + x + g.bbox.x_offset)
(py - (g.bbox.height - y) - g.bbox.y_offset)
bg;
done;
done;
fst g.dwidth, snd g.dwidth
let draw_char fb ch font (px,py) colour =
draw_uchar fb (int_of_char ch) font (px,py) colour (0,0,0)
match font.glyphs.(int_of_char ch ) with
| None - > ( px , py )
| Some g - >
for x = 0 to g.bbox.width - 1 do
for y = 0 to - 1 do
if g.data.(y).(x ) then
plot fb
( px + x + g.bbox.x_offset )
( py - ( g.bbox.height - y ) - g.bbox.y_offset )
colour ;
done ;
done ;
px + fst g.dwidth , py + snd g.dwidth
| None -> (px,py)
| Some g ->
for x = 0 to g.bbox.width - 1 do
for y = 0 to g.bbox.height - 1 do
if g.data.(y).(x) then
plot fb
(px + x + g.bbox.x_offset)
(py - (g.bbox.height - y) - g.bbox.y_offset)
colour;
done;
done;
px + fst g.dwidth, py + snd g.dwidth*)
let draw_text fb text font origin colour =
String.fold_left begin fun point ch ->
draw_char fb ch font point colour
end origin text
let measure_text text font =
String.fold_left begin fun width ch ->
match font.glyphs.(int_of_char ch) with
| None -> width
| Some g -> width + fst g.dwidth
end 0 text, font.ascent + font.descent
|
de95aec952114953e3ff81a7b2b93a0562b0fff80c49fcb30c23b9767b215d84
|
ostinelli/misultin
|
misultin_cookies_example.erl
|
% ==========================================================================================================
MISULTIN - Example : Show how to set / retrieve cookies .
%
% >-|-|-(°>
%
Copyright ( C ) 2011 , < >
% All rights reserved.
%
% BSD License
%
% Redistribution and use in source and binary forms, with or without modification, are permitted provided
% that the following conditions are met:
%
% * Redistributions of source code must retain the above copyright notice, this list of conditions and the
% following disclaimer.
% * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
% the following disclaimer in the documentation and/or other materials provided with the distribution.
% * Neither the name of the authors nor the names of its contributors may be used to endorse or promote
% products derived from this software without specific prior written permission.
%
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR
% WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR FOR
ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION )
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
% NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
% ==========================================================================================================
-module(misultin_cookies_example).
-export([start/1, stop/0]).
start misultin http server
start(Port) ->
misultin:start_link([{port, Port}, {loop, fun(Req) -> handle_http(Req) end}]).
stop misultin
stop() ->
misultin:stop().
% callback on request received
handle_http(Req) ->
% get cookies
Cookies = Req:get_cookies(),
case Req:get_cookie_value("misultin_test_cookie", Cookies) of
undefined ->
no cookies preexists , create one that will expire in 365 days
Req:set_cookie("misultin_test_cookie", "value of the test cookie", [{max_age, 365*24*3600}]),
Req:ok("A cookie has been set. Refresh the browser to see it.");
CookieVal ->
Req:delete_cookie("misultin_test_cookie"),
Req:ok(["The set cookie value was set to \"", CookieVal,"\", and has now been removed. Refresh the browser to see this."])
end.
| null |
https://raw.githubusercontent.com/ostinelli/misultin/b9fe3125cf17f4415a6d7fc60642b670f5e18eb8/examples/misultin_cookies_example.erl
|
erlang
|
==========================================================================================================
>-|-|-(°>
All rights reserved.
BSD License
Redistribution and use in source and binary forms, with or without modification, are permitted provided
that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the authors nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
==========================================================================================================
callback on request received
get cookies
|
MISULTIN - Example : Show how to set / retrieve cookies .
Copyright ( C ) 2011 , < >
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR
PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR FOR
ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION )
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
-module(misultin_cookies_example).
-export([start/1, stop/0]).
start misultin http server
start(Port) ->
misultin:start_link([{port, Port}, {loop, fun(Req) -> handle_http(Req) end}]).
stop misultin
stop() ->
misultin:stop().
handle_http(Req) ->
Cookies = Req:get_cookies(),
case Req:get_cookie_value("misultin_test_cookie", Cookies) of
undefined ->
no cookies preexists , create one that will expire in 365 days
Req:set_cookie("misultin_test_cookie", "value of the test cookie", [{max_age, 365*24*3600}]),
Req:ok("A cookie has been set. Refresh the browser to see it.");
CookieVal ->
Req:delete_cookie("misultin_test_cookie"),
Req:ok(["The set cookie value was set to \"", CookieVal,"\", and has now been removed. Refresh the browser to see this."])
end.
|
9538e8b51f5476083f4b2822de1441854518dc4c6d770333dc2705f0aa8863e0
|
KaroshiBee/weevil
|
dap_commands.mli
|
(* NOTE autogenerated, do not manually edit *)
type 'a t
type disassemble
type writeMemory
type readMemory
type exceptionInfo
type completions
type gotoTargets
type stepInTargets
type setExpression
type evaluate
type loadedSources
type modules
type terminateThreads
type threads
type source
type setVariable
type variables
type scopes
type stackTrace
type pause
type goto
type restartFrame
type reverseContinue
type stepBack
type stepOut
type stepIn
type next
type continue
type setInstructionBreakpoints
type setDataBreakpoints
type dataBreakpointInfo
type setExceptionBreakpoints
type setFunctionBreakpoints
type setBreakpoints
type breakpointLocations
type terminate
type disconnect
type restart
type attach
type launch
type configurationDone
type initialize
type runInTerminal
type cancel
type error
val equal : 'a t -> 'b t -> bool
val disassemble : disassemble t
val writeMemory : writeMemory t
val readMemory : readMemory t
val exceptionInfo : exceptionInfo t
val completions : completions t
val gotoTargets : gotoTargets t
val stepInTargets : stepInTargets t
val setExpression : setExpression t
val evaluate : evaluate t
val loadedSources : loadedSources t
val modules : modules t
val terminateThreads : terminateThreads t
val threads : threads t
val source : source t
val setVariable : setVariable t
val variables : variables t
val scopes : scopes t
val stackTrace : stackTrace t
val pause : pause t
val goto : goto t
val restartFrame : restartFrame t
val reverseContinue : reverseContinue t
val stepBack : stepBack t
val stepOut : stepOut t
val stepIn : stepIn t
val next : next t
val continue : continue t
val setInstructionBreakpoints : setInstructionBreakpoints t
val setDataBreakpoints : setDataBreakpoints t
val dataBreakpointInfo : dataBreakpointInfo t
val setExceptionBreakpoints : setExceptionBreakpoints t
val setFunctionBreakpoints : setFunctionBreakpoints t
val setBreakpoints : setBreakpoints t
val breakpointLocations : breakpointLocations t
val terminate : terminate t
val disconnect : disconnect t
val restart : restart t
val attach : attach t
val launch : launch t
val configurationDone : configurationDone t
val initialize : initialize t
val runInTerminal : runInTerminal t
val cancel : cancel t
val error : error t
val to_string : 'a t -> string
val from_string : string -> 'a t
val enc : value:'a t -> 'a t Data_encoding.t
| null |
https://raw.githubusercontent.com/KaroshiBee/weevil/1b166ba053062498c1ec05c885e04fba4ae7d831/lib/dapper/dap_commands.mli
|
ocaml
|
NOTE autogenerated, do not manually edit
|
type 'a t
type disassemble
type writeMemory
type readMemory
type exceptionInfo
type completions
type gotoTargets
type stepInTargets
type setExpression
type evaluate
type loadedSources
type modules
type terminateThreads
type threads
type source
type setVariable
type variables
type scopes
type stackTrace
type pause
type goto
type restartFrame
type reverseContinue
type stepBack
type stepOut
type stepIn
type next
type continue
type setInstructionBreakpoints
type setDataBreakpoints
type dataBreakpointInfo
type setExceptionBreakpoints
type setFunctionBreakpoints
type setBreakpoints
type breakpointLocations
type terminate
type disconnect
type restart
type attach
type launch
type configurationDone
type initialize
type runInTerminal
type cancel
type error
val equal : 'a t -> 'b t -> bool
val disassemble : disassemble t
val writeMemory : writeMemory t
val readMemory : readMemory t
val exceptionInfo : exceptionInfo t
val completions : completions t
val gotoTargets : gotoTargets t
val stepInTargets : stepInTargets t
val setExpression : setExpression t
val evaluate : evaluate t
val loadedSources : loadedSources t
val modules : modules t
val terminateThreads : terminateThreads t
val threads : threads t
val source : source t
val setVariable : setVariable t
val variables : variables t
val scopes : scopes t
val stackTrace : stackTrace t
val pause : pause t
val goto : goto t
val restartFrame : restartFrame t
val reverseContinue : reverseContinue t
val stepBack : stepBack t
val stepOut : stepOut t
val stepIn : stepIn t
val next : next t
val continue : continue t
val setInstructionBreakpoints : setInstructionBreakpoints t
val setDataBreakpoints : setDataBreakpoints t
val dataBreakpointInfo : dataBreakpointInfo t
val setExceptionBreakpoints : setExceptionBreakpoints t
val setFunctionBreakpoints : setFunctionBreakpoints t
val setBreakpoints : setBreakpoints t
val breakpointLocations : breakpointLocations t
val terminate : terminate t
val disconnect : disconnect t
val restart : restart t
val attach : attach t
val launch : launch t
val configurationDone : configurationDone t
val initialize : initialize t
val runInTerminal : runInTerminal t
val cancel : cancel t
val error : error t
val to_string : 'a t -> string
val from_string : string -> 'a t
val enc : value:'a t -> 'a t Data_encoding.t
|
57513b4af99110b543094ab191d7f0c2d24177280008d16899968595dd8b968f
|
sordina/Deadpan-DDP
|
EJson.hs
|
|
Description : Internal definitions for EJson functionality
Currently EJson functionality is built on top of the
` Data . Aeson . Value ` type .
Functions are written to convert back and forth between
` Data . EJson . EJsonValue ` and ` Data . Aeson . Value ` .
The conversion functions from EJsonValue to Value are in a seperate
module : " Data . EJson . EJson2Value " .
This has some negative impact on performance , but aids simplicity .
Description : Internal definitions for EJson functionality
Currently EJson functionality is built on top of the
`Data.Aeson.Value` type.
Functions are written to convert back and forth between
`Data.EJson.EJsonValue` and `Data.Aeson.Value`.
The conversion functions from EJsonValue to Value are in a seperate
module: "Data.EJson.EJson2Value".
This has some negative impact on performance, but aids simplicity.
-}
# OPTIONS_GHC -fno - warn - orphans #
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeSynonymInstances #-}
# LANGUAGE MultiParamTypeClasses #
module Data.EJson.EJson (
EJsonValue(..)
-- Conversion functions
, value2EJson
Smart Constructors
, ejobject
, ejarray
, ejstring
, ejnumber
, ejbool
, ejdate
, ejbinary
, ejuser
, ejnull
Prisms
, _EJObject
, _EJObjectKey
, _EJObjectKeyString
, _EJArray
, _EJAraryIndex
, _EJString
, _EJNumber
, _EJBool
, _EJDate
, _EJBinary
, _EJUser
, _EJNull
) where
import Control.Monad
import Control.Applicative
import Data.Monoid
import Data.Aeson
import Data.Scientific
import Data.Time.Clock.POSIX
import Data.Time.Clock
import Data.Text.Internal
import Data.Text.Encoding
import Data.ByteString hiding (putStr, map)
import Data.ByteString.Base64
import Data.Maybe
import Data.String
import Control.Lens
import qualified Data.Vector
import qualified Data.HashMap.Strict as HM
import qualified Data.Text as T
data EJsonValue =
EJObject !(HM.HashMap Text EJsonValue)
| EJArray !(Data.Vector.Vector EJsonValue)
| EJString !Text
| EJNumber !Scientific
| EJBool !Bool
| EJDate !UTCTime
| EJBinary !ByteString
| EJUser !Text !EJsonValue
| EJNull
deriving (Eq)
-- Instances follow!
Prismo time !
--
makePrisms ''EJsonValue
Possibly access the value indicated by a key into a possible EJsonValue EJObject .
--
_EJObjectKey :: Text -> Traversal' EJsonValue (Maybe EJsonValue)
_EJObjectKey k = _EJObject . at k
-- | A helpful prism that looks up values of type EJ{"foo" : "bar", ...}
-- with a Text key "foo" and returns Just "bar", or Nothing.
-- Used frequently for checking message types and ids.
--
_EJObjectKeyString :: Applicative f
=> Text
-> (Text -> f Text)
-> EJsonValue
-> f EJsonValue
_EJObjectKeyString k = _EJObject . at k . _Just . _EJString
_EJAraryIndex :: Applicative f
=> Int
-> (EJsonValue -> f EJsonValue)
-> EJsonValue
-> f EJsonValue
_EJAraryIndex i = _EJArray . ix i
instance IsString EJsonValue
where
fromString = EJString . T.pack
instance Monoid EJsonValue
where
mempty = EJNull
EJObject o1 `mappend` EJObject o2 = EJObject $ mappend o1 o2
EJArray a1 `mappend` EJArray a2 = EJArray $ mappend a1 a2
_ `mappend` _ = error "TODO: Haven't considered what to do here yet..."
-- TODO: Decide what to do about these error cases
instance Num EJsonValue
where
fromInteger = EJNumber . fromIntegral
(EJNumber a) + (EJNumber b) = EJNumber (a + b)
_ + _ = error "don't add non-numbers"
(EJNumber a) * (EJNumber b) = EJNumber (a * b)
_ * _ = error "don't multiply non-numbers"
abs (EJNumber a) = EJNumber (abs a)
abs _ = error "don't abolute non-numbers"
signum (EJNumber a) = EJNumber (signum a)
signum _ = error "don't signum non-numbers"
negate (EJNumber a) = EJNumber (negate a)
negate _ = error "don't negate non-numbers"
Smart Constructors
# Inline ejobject #
ejobject :: [(Text, EJsonValue)] -> EJsonValue
ejobject = EJObject . HM.fromList
# Inline ejarray #
ejarray :: [EJsonValue] -> EJsonValue
ejarray = EJArray . Data.Vector.fromList
# Inline ejstring #
ejstring :: Text -> EJsonValue
ejstring = EJString
# Inline ejnumber #
ejnumber :: Scientific -> EJsonValue
ejnumber = EJNumber
# Inline ejbool #
ejbool :: Bool -> EJsonValue
ejbool = EJBool
# Inline ejdate #
ejdate :: Scientific -> EJsonValue
ejdate = EJDate . posixSecondsToUTCTime . realToFrac
# Inline ejbinary #
ejbinary :: ByteString -> EJsonValue
ejbinary = EJBinary
# Inline ejuser #
ejuser :: Text -> EJsonValue -> EJsonValue
ejuser = EJUser
# Inline ejnull #
ejnull :: EJsonValue
ejnull = EJNull
-- Conversion
value2EJson :: Value -> EJsonValue
value2EJson (Object o) = escapeObject o
value2EJson (Array a) = EJArray $ Data.Vector.map value2EJson a
value2EJson (String s) = EJString s
value2EJson (Number n) = EJNumber n
value2EJson (Bool b) = EJBool b
value2EJson Null = EJNull
-- Helpers
simpleKey :: Text -> Object -> Maybe Value
simpleKey = HM.lookup
parseDate :: Value -> Maybe EJsonValue
parseDate (Number n) = Just $ EJDate $ posixSecondsToUTCTime $ realToFrac n
parseDate _ = Nothing
parseBinary :: Value -> Maybe EJsonValue
parseBinary (String s) = Just (EJBinary (decodeLenient (encodeUtf8 s)))
parseBinary _ = Nothing
parseUser :: Value -> Value -> Maybe EJsonValue
parseUser (String k) v = Just $ EJUser k (value2EJson v)
parseUser _ _ = Nothing
parseEscaped :: Value -> Maybe EJsonValue
parseEscaped (Object o) = Just $ simpleObj o
parseEscaped _ = Nothing
getDate :: Int -> Object -> Maybe EJsonValue
getDate 1 o = parseDate =<< simpleKey "$date" o
getDate _ _ = Nothing
getBinary :: Int -> Object -> Maybe EJsonValue
getBinary 1 o = parseBinary =<< simpleKey "$binary" o
getBinary _ _ = Nothing
getUser :: Int -> Object -> Maybe EJsonValue
getUser 2 o = do t <- simpleKey "$type" o
v <- simpleKey "$value" o
parseUser t v
getUser _ _ = Nothing
getEscaped :: Int -> Object -> Maybe EJsonValue
getEscaped 1 o = parseEscaped =<< simpleKey "$escape" o
getEscaped _ _ = Nothing
simpleObj :: HM.HashMap Text Value -> EJsonValue
simpleObj o = EJObject $ HM.map value2EJson o
escapeObject :: Object -> EJsonValue
escapeObject o = fromMaybe (simpleObj o) $ msum
$ map (`uncurry` (HM.size o, o))
[getDate, getBinary, getUser, getEscaped]
| null |
https://raw.githubusercontent.com/sordina/Deadpan-DDP/d0f115cbc7132a87cababc587064d8f851165e85/src/Data/EJson/EJson.hs
|
haskell
|
# LANGUAGE RankNTypes #
# LANGUAGE TemplateHaskell #
# LANGUAGE OverloadedStrings #
# LANGUAGE TypeSynonymInstances #
Conversion functions
Instances follow!
| A helpful prism that looks up values of type EJ{"foo" : "bar", ...}
with a Text key "foo" and returns Just "bar", or Nothing.
Used frequently for checking message types and ids.
TODO: Decide what to do about these error cases
Conversion
Helpers
|
|
Description : Internal definitions for EJson functionality
Currently EJson functionality is built on top of the
` Data . Aeson . Value ` type .
Functions are written to convert back and forth between
` Data . EJson . EJsonValue ` and ` Data . Aeson . Value ` .
The conversion functions from EJsonValue to Value are in a seperate
module : " Data . EJson . EJson2Value " .
This has some negative impact on performance , but aids simplicity .
Description : Internal definitions for EJson functionality
Currently EJson functionality is built on top of the
`Data.Aeson.Value` type.
Functions are written to convert back and forth between
`Data.EJson.EJsonValue` and `Data.Aeson.Value`.
The conversion functions from EJsonValue to Value are in a seperate
module: "Data.EJson.EJson2Value".
This has some negative impact on performance, but aids simplicity.
-}
# OPTIONS_GHC -fno - warn - orphans #
# LANGUAGE MultiParamTypeClasses #
module Data.EJson.EJson (
EJsonValue(..)
, value2EJson
Smart Constructors
, ejobject
, ejarray
, ejstring
, ejnumber
, ejbool
, ejdate
, ejbinary
, ejuser
, ejnull
Prisms
, _EJObject
, _EJObjectKey
, _EJObjectKeyString
, _EJArray
, _EJAraryIndex
, _EJString
, _EJNumber
, _EJBool
, _EJDate
, _EJBinary
, _EJUser
, _EJNull
) where
import Control.Monad
import Control.Applicative
import Data.Monoid
import Data.Aeson
import Data.Scientific
import Data.Time.Clock.POSIX
import Data.Time.Clock
import Data.Text.Internal
import Data.Text.Encoding
import Data.ByteString hiding (putStr, map)
import Data.ByteString.Base64
import Data.Maybe
import Data.String
import Control.Lens
import qualified Data.Vector
import qualified Data.HashMap.Strict as HM
import qualified Data.Text as T
data EJsonValue =
EJObject !(HM.HashMap Text EJsonValue)
| EJArray !(Data.Vector.Vector EJsonValue)
| EJString !Text
| EJNumber !Scientific
| EJBool !Bool
| EJDate !UTCTime
| EJBinary !ByteString
| EJUser !Text !EJsonValue
| EJNull
deriving (Eq)
Prismo time !
makePrisms ''EJsonValue
Possibly access the value indicated by a key into a possible EJsonValue EJObject .
_EJObjectKey :: Text -> Traversal' EJsonValue (Maybe EJsonValue)
_EJObjectKey k = _EJObject . at k
_EJObjectKeyString :: Applicative f
=> Text
-> (Text -> f Text)
-> EJsonValue
-> f EJsonValue
_EJObjectKeyString k = _EJObject . at k . _Just . _EJString
_EJAraryIndex :: Applicative f
=> Int
-> (EJsonValue -> f EJsonValue)
-> EJsonValue
-> f EJsonValue
_EJAraryIndex i = _EJArray . ix i
instance IsString EJsonValue
where
fromString = EJString . T.pack
instance Monoid EJsonValue
where
mempty = EJNull
EJObject o1 `mappend` EJObject o2 = EJObject $ mappend o1 o2
EJArray a1 `mappend` EJArray a2 = EJArray $ mappend a1 a2
_ `mappend` _ = error "TODO: Haven't considered what to do here yet..."
instance Num EJsonValue
where
fromInteger = EJNumber . fromIntegral
(EJNumber a) + (EJNumber b) = EJNumber (a + b)
_ + _ = error "don't add non-numbers"
(EJNumber a) * (EJNumber b) = EJNumber (a * b)
_ * _ = error "don't multiply non-numbers"
abs (EJNumber a) = EJNumber (abs a)
abs _ = error "don't abolute non-numbers"
signum (EJNumber a) = EJNumber (signum a)
signum _ = error "don't signum non-numbers"
negate (EJNumber a) = EJNumber (negate a)
negate _ = error "don't negate non-numbers"
Smart Constructors
# Inline ejobject #
ejobject :: [(Text, EJsonValue)] -> EJsonValue
ejobject = EJObject . HM.fromList
# Inline ejarray #
ejarray :: [EJsonValue] -> EJsonValue
ejarray = EJArray . Data.Vector.fromList
# Inline ejstring #
ejstring :: Text -> EJsonValue
ejstring = EJString
# Inline ejnumber #
ejnumber :: Scientific -> EJsonValue
ejnumber = EJNumber
# Inline ejbool #
ejbool :: Bool -> EJsonValue
ejbool = EJBool
# Inline ejdate #
ejdate :: Scientific -> EJsonValue
ejdate = EJDate . posixSecondsToUTCTime . realToFrac
# Inline ejbinary #
ejbinary :: ByteString -> EJsonValue
ejbinary = EJBinary
# Inline ejuser #
ejuser :: Text -> EJsonValue -> EJsonValue
ejuser = EJUser
# Inline ejnull #
ejnull :: EJsonValue
ejnull = EJNull
value2EJson :: Value -> EJsonValue
value2EJson (Object o) = escapeObject o
value2EJson (Array a) = EJArray $ Data.Vector.map value2EJson a
value2EJson (String s) = EJString s
value2EJson (Number n) = EJNumber n
value2EJson (Bool b) = EJBool b
value2EJson Null = EJNull
simpleKey :: Text -> Object -> Maybe Value
simpleKey = HM.lookup
parseDate :: Value -> Maybe EJsonValue
parseDate (Number n) = Just $ EJDate $ posixSecondsToUTCTime $ realToFrac n
parseDate _ = Nothing
parseBinary :: Value -> Maybe EJsonValue
parseBinary (String s) = Just (EJBinary (decodeLenient (encodeUtf8 s)))
parseBinary _ = Nothing
parseUser :: Value -> Value -> Maybe EJsonValue
parseUser (String k) v = Just $ EJUser k (value2EJson v)
parseUser _ _ = Nothing
parseEscaped :: Value -> Maybe EJsonValue
parseEscaped (Object o) = Just $ simpleObj o
parseEscaped _ = Nothing
getDate :: Int -> Object -> Maybe EJsonValue
getDate 1 o = parseDate =<< simpleKey "$date" o
getDate _ _ = Nothing
getBinary :: Int -> Object -> Maybe EJsonValue
getBinary 1 o = parseBinary =<< simpleKey "$binary" o
getBinary _ _ = Nothing
getUser :: Int -> Object -> Maybe EJsonValue
getUser 2 o = do t <- simpleKey "$type" o
v <- simpleKey "$value" o
parseUser t v
getUser _ _ = Nothing
getEscaped :: Int -> Object -> Maybe EJsonValue
getEscaped 1 o = parseEscaped =<< simpleKey "$escape" o
getEscaped _ _ = Nothing
simpleObj :: HM.HashMap Text Value -> EJsonValue
simpleObj o = EJObject $ HM.map value2EJson o
escapeObject :: Object -> EJsonValue
escapeObject o = fromMaybe (simpleObj o) $ msum
$ map (`uncurry` (HM.size o, o))
[getDate, getBinary, getUser, getEscaped]
|
fa06743e6b8dd2a43a67169f1617b166699c6fadc658e37498585316eacdf38d
|
typelead/eta
|
tc229.hs
|
{ - # OPTIONS_GHC -Wno - simplifiable - class - constraints # - }
-- -Wno-redundant-constraints
trac # 1406 : Constraint does n't reduce in the presence of quantified
-- type variables
# LANGUAGE FlexibleInstances , UndecidableInstances , RankNTypes ,
MultiParamTypeClasses , FunctionalDependencies #
MultiParamTypeClasses, FunctionalDependencies #-}
module Problem where
data Z
data S a
class HPrefix l
instance (NSub (S Z) ndiff, HDrop ndiff l l) => HPrefix l
Weird test case : ( NSub ( S Z ) ndiff ) is simplifiable
class NSub n1 n3 | n1 -> n3
instance NSub Z Z
instance NSub n1 n3 => NSub (S n1) n3
class HDrop n l1 l2 | n l1 -> l2
instance HDrop Z l l
t_hPrefix :: HPrefix l => l -> ()
Weird test case : ( HPrefix l ) is simplifiable
t_hPrefix = undefined
In ghc 6.6.1 this works ...
thr' :: (forall r. l -> a) -> a
thr' f = f undefined
thP4' = thr' t_hPrefix
-- ... but this doesn't work...?
thr :: (forall r. r -> a) -> a
thr f = f undefined
thP4 = thr t_hPrefix
| null |
https://raw.githubusercontent.com/typelead/eta/97ee2251bbc52294efbf60fa4342ce6f52c0d25c/tests/suite/typecheck/compile/tc229.hs
|
haskell
|
-Wno-redundant-constraints
type variables
... but this doesn't work...?
|
{ - # OPTIONS_GHC -Wno - simplifiable - class - constraints # - }
trac # 1406 : Constraint does n't reduce in the presence of quantified
# LANGUAGE FlexibleInstances , UndecidableInstances , RankNTypes ,
MultiParamTypeClasses , FunctionalDependencies #
MultiParamTypeClasses, FunctionalDependencies #-}
module Problem where
data Z
data S a
class HPrefix l
instance (NSub (S Z) ndiff, HDrop ndiff l l) => HPrefix l
Weird test case : ( NSub ( S Z ) ndiff ) is simplifiable
class NSub n1 n3 | n1 -> n3
instance NSub Z Z
instance NSub n1 n3 => NSub (S n1) n3
class HDrop n l1 l2 | n l1 -> l2
instance HDrop Z l l
t_hPrefix :: HPrefix l => l -> ()
Weird test case : ( HPrefix l ) is simplifiable
t_hPrefix = undefined
In ghc 6.6.1 this works ...
thr' :: (forall r. l -> a) -> a
thr' f = f undefined
thP4' = thr' t_hPrefix
thr :: (forall r. r -> a) -> a
thr f = f undefined
thP4 = thr t_hPrefix
|
a2f1a6b0d9c94a6bd6e78a2a862bcc136ae3950351f522f48dc5b7b2d4e68e4f
|
ygrek/ocaml-extlib
|
util.ml
|
* ExtLib Testing Suite
* Copyright ( C ) 2004
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation ; either
* version 2.1 of the License , or ( at your option ) any later version ,
* 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 GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* ExtLib Testing Suite
* Copyright (C) 2004 Janne Hellsten
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version,
* 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 GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
module P = Printf
let log s =
P.printf "%s\n" s;
flush stdout
let random_char () =
char_of_int (Random.int 256)
let random_string () =
let len = Random.int 256 in
let str = Bytes.create len in
if len > 0 then
for i = 0 to (len-1) do
Bytes.set str i (random_char ())
done;
Bytes.unsafe_to_string str
let random_string_len len =
let len = len in
let str = Bytes.create len in
if len > 0 then
for i = 0 to (len-1) do
Bytes.set str i (random_char ())
done;
Bytes.unsafe_to_string str
(* For counting the success ratio *)
let test_run_count = ref 0
let test_success_count = ref 0
let g_test_run_count = ref 0
let g_test_success_count = ref 0
let test_module name f =
P.printf "%s\n" name;
flush stdout;
test_run_count := 0;
test_success_count := 0;
f ();
if !test_run_count <> 0 then
P.printf " %i/%i tests succeeded.\n"
!test_success_count !test_run_count
let run_test ~test_name f =
try
incr g_test_run_count;
incr test_run_count;
P.printf " %s" test_name;
flush stdout;
let () = f () in
incr g_test_success_count;
incr test_success_count;
P.printf " - OK\n"
with
Assert_failure (file,line,column) ->
P.printf " - FAILED\n reason: ";
P.printf " %s:%i:%i\n" file line column;
flush stdout
let all_tests = Hashtbl.create 10
let register modname l =
let existing = try Hashtbl.find all_tests modname with Not_found -> [] in
Hashtbl.replace all_tests modname (l @ existing)
let register1 modname name f = register modname [name,f]
let run_all filter =
let allowed name =
match filter with
| None -> true
| Some l -> List.mem (ExtString.String.lowercase name) l
in
g_test_run_count := 0;
g_test_success_count := 0;
Hashtbl.iter begin fun modname tests ->
let allowed_module = allowed modname in
test_module modname begin fun () ->
List.iter begin fun (test_name,f) ->
if allowed_module || allowed (modname^"."^test_name) then run_test ~test_name f
end tests
end
end all_tests;
if !g_test_run_count <> 0 then
P.printf "\nOverall %i/%i tests succeeded.\n"
!g_test_success_count !g_test_run_count;
!g_test_run_count = !g_test_success_count
| null |
https://raw.githubusercontent.com/ygrek/ocaml-extlib/0779f7a881c76f9aca3d5445e2f063ba38a76167/test/util.ml
|
ocaml
|
For counting the success ratio
|
* ExtLib Testing Suite
* Copyright ( C ) 2004
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation ; either
* version 2.1 of the License , or ( at your option ) any later version ,
* 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 GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* ExtLib Testing Suite
* Copyright (C) 2004 Janne Hellsten
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version,
* 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 GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
module P = Printf
let log s =
P.printf "%s\n" s;
flush stdout
let random_char () =
char_of_int (Random.int 256)
let random_string () =
let len = Random.int 256 in
let str = Bytes.create len in
if len > 0 then
for i = 0 to (len-1) do
Bytes.set str i (random_char ())
done;
Bytes.unsafe_to_string str
let random_string_len len =
let len = len in
let str = Bytes.create len in
if len > 0 then
for i = 0 to (len-1) do
Bytes.set str i (random_char ())
done;
Bytes.unsafe_to_string str
let test_run_count = ref 0
let test_success_count = ref 0
let g_test_run_count = ref 0
let g_test_success_count = ref 0
let test_module name f =
P.printf "%s\n" name;
flush stdout;
test_run_count := 0;
test_success_count := 0;
f ();
if !test_run_count <> 0 then
P.printf " %i/%i tests succeeded.\n"
!test_success_count !test_run_count
let run_test ~test_name f =
try
incr g_test_run_count;
incr test_run_count;
P.printf " %s" test_name;
flush stdout;
let () = f () in
incr g_test_success_count;
incr test_success_count;
P.printf " - OK\n"
with
Assert_failure (file,line,column) ->
P.printf " - FAILED\n reason: ";
P.printf " %s:%i:%i\n" file line column;
flush stdout
let all_tests = Hashtbl.create 10
let register modname l =
let existing = try Hashtbl.find all_tests modname with Not_found -> [] in
Hashtbl.replace all_tests modname (l @ existing)
let register1 modname name f = register modname [name,f]
let run_all filter =
let allowed name =
match filter with
| None -> true
| Some l -> List.mem (ExtString.String.lowercase name) l
in
g_test_run_count := 0;
g_test_success_count := 0;
Hashtbl.iter begin fun modname tests ->
let allowed_module = allowed modname in
test_module modname begin fun () ->
List.iter begin fun (test_name,f) ->
if allowed_module || allowed (modname^"."^test_name) then run_test ~test_name f
end tests
end
end all_tests;
if !g_test_run_count <> 0 then
P.printf "\nOverall %i/%i tests succeeded.\n"
!g_test_success_count !g_test_run_count;
!g_test_run_count = !g_test_success_count
|
3d391c2c1af60f7d659a1080f4a1ae966902f0d34dc0967f4cf8c9f791cc74c9
|
craigfe/ppx_effects
|
invalid_payload_type_in_match.ml
|
let () = match () with [%effect ()] -> ()
| null |
https://raw.githubusercontent.com/craigfe/ppx_effects/ea1b5b940ff9619cc242f974db9d31e51e4d89a5/test/errors/invalid_payload_type_in_match.ml
|
ocaml
|
let () = match () with [%effect ()] -> ()
|
|
a824d75b5e9d609ac4b49383110422523971861e58c6a3521f26bd59eff06e47
|
vodori/schema-forms
|
core_test.clj
|
(ns schema-forms.core-test
(:require [clojure.test :refer :all]
[schema-forms.core :refer :all]
[schema.core :as s]
[schema-forms.helpers :refer :all]))
(s/defschema RecursivePerson
{:firstName s/Str
:friends [(s/recursive #'RecursivePerson)]})
(deftest prismatic->json-schema-test
(testing "Simple schema"
(let [schema {:firstName s/Str :lastName s/Str :age s/Num}]
(check-expected (s/named schema "SimplePerson"))))
(testing "Optional fields"
(let [schema {:firstName s/Str
(s/optional-key :lastName) (s/maybe s/Str)}]
(check-expected (s/named schema "OptionalSurname"))))
(testing "Repeat unbounded list"
(let [schema {:favoriteDogs [{:name s/Str :breed (s/enum "Collie" "Husky")}]}]
(check-expected (s/named schema "RepeatList"))))
(testing "Optional position item list"
(let [schema {:favoriteDogs [(s/optional {:name s/Str :breed (s/enum "Collie" "Husky")} "Dog")]}]
(check-expected (s/named schema "Single Optional Position List"))))
(testing "Required position item list"
(let [schema {:favoriteDogs [(s/one {:name s/Str :breed (s/enum "Collie" "Husky")} "Dog")]}]
(check-expected (s/named schema "Single Required Position List"))))
(testing "Recursive schemas"
(check-expected RecursivePerson)))
(deftest prismatic-data->json-schema-data-test
(testing "optional structure bijection"
(let [schema {:options (s/maybe {:enabled s/Bool})}
original {:options {:enabled true}}
expected {:options [{:enabled true}]}]
(is (= expected (prismatic-data->json-schema-data schema original)))))
(testing "anything schema bijection"
(let [schema {:configuration s/Any}
original {:configuration ["Test"]}
expected {:configuration {:value ["Test"], :kind :STRING_ARRAY}}]
(is (= expected (prismatic-data->json-schema-data schema original))))))
(deftest json-schema-data->prismatic-data-test
(testing "optional structure bijection"
(let [schema {:options (s/maybe {:enabled s/Bool})}
original {:options [{:enabled true}]}
expected {:options {:enabled true}}]
(is (= expected (json-schema-data->prismatic-data schema original)))))
(testing "anything schema bijection"
(let [schema {:configuration s/Any}
original {:configuration {:value ["Test"], :kind :STRING_ARRAY}}
expected {:configuration ["Test"]}]
(is (= expected (json-schema-data->prismatic-data schema original))))))
| null |
https://raw.githubusercontent.com/vodori/schema-forms/876e13710f922c152a184c4cbe7bfd3c18990cce/test/schema_forms/core_test.clj
|
clojure
|
(ns schema-forms.core-test
(:require [clojure.test :refer :all]
[schema-forms.core :refer :all]
[schema.core :as s]
[schema-forms.helpers :refer :all]))
(s/defschema RecursivePerson
{:firstName s/Str
:friends [(s/recursive #'RecursivePerson)]})
(deftest prismatic->json-schema-test
(testing "Simple schema"
(let [schema {:firstName s/Str :lastName s/Str :age s/Num}]
(check-expected (s/named schema "SimplePerson"))))
(testing "Optional fields"
(let [schema {:firstName s/Str
(s/optional-key :lastName) (s/maybe s/Str)}]
(check-expected (s/named schema "OptionalSurname"))))
(testing "Repeat unbounded list"
(let [schema {:favoriteDogs [{:name s/Str :breed (s/enum "Collie" "Husky")}]}]
(check-expected (s/named schema "RepeatList"))))
(testing "Optional position item list"
(let [schema {:favoriteDogs [(s/optional {:name s/Str :breed (s/enum "Collie" "Husky")} "Dog")]}]
(check-expected (s/named schema "Single Optional Position List"))))
(testing "Required position item list"
(let [schema {:favoriteDogs [(s/one {:name s/Str :breed (s/enum "Collie" "Husky")} "Dog")]}]
(check-expected (s/named schema "Single Required Position List"))))
(testing "Recursive schemas"
(check-expected RecursivePerson)))
(deftest prismatic-data->json-schema-data-test
(testing "optional structure bijection"
(let [schema {:options (s/maybe {:enabled s/Bool})}
original {:options {:enabled true}}
expected {:options [{:enabled true}]}]
(is (= expected (prismatic-data->json-schema-data schema original)))))
(testing "anything schema bijection"
(let [schema {:configuration s/Any}
original {:configuration ["Test"]}
expected {:configuration {:value ["Test"], :kind :STRING_ARRAY}}]
(is (= expected (prismatic-data->json-schema-data schema original))))))
(deftest json-schema-data->prismatic-data-test
(testing "optional structure bijection"
(let [schema {:options (s/maybe {:enabled s/Bool})}
original {:options [{:enabled true}]}
expected {:options {:enabled true}}]
(is (= expected (json-schema-data->prismatic-data schema original)))))
(testing "anything schema bijection"
(let [schema {:configuration s/Any}
original {:configuration {:value ["Test"], :kind :STRING_ARRAY}}
expected {:configuration ["Test"]}]
(is (= expected (json-schema-data->prismatic-data schema original))))))
|
|
abe06a26d774e6c5f0fd455c8d7aa9da6f159945c5d38f6b64883bf31349067c
|
Gabriella439/Haskell-Succinct-Vector-Library
|
Primitives.hs
|
module Succinct.Vector.Primitives where
import Control.Monad.Primitive (PrimMonad, PrimState)
import Control.Monad.ST (ST)
import Data.Primitive.Types (Prim)
import qualified Data.Vector.Primitive
import qualified Data.Vector.Primitive.Mutable
{-@ measure plen :: Data.Vector.Primitive.Vector a -> Int @-}
@
assume Data.Vector.Primitive.length
: : Prim a
= > v : Data . Vector . Primitive . Vector a - > { n : Int | 0 < = n & & n = = plen v }
@
assume Data.Vector.Primitive.length
:: Prim a
=> v : Data.Vector.Primitive.Vector a -> { n : Int | 0 <= n && n == plen v }
@-}
@
Data . Vector . Primitive.unsafeIndex
: : Prim a
= > v : Data . Vector . Primitive . Vector a
- > { n : Int | 0 < = n & & n < plen v }
- > a
@
Data.Vector.Primitive.unsafeIndex
:: Prim a
=> v : Data.Vector.Primitive.Vector a
-> { n : Int | 0 <= n && n < plen v }
-> a
@-}
@
assume Data . Vector . Primitive.unsafeSlice
: : Prim a
= > n : { n : Int | 0 < = n }
- > l : { l : Int | 0 < = l }
- > i : { i : Data . Vector . Primitive . Vector a | n + l < = plen i }
- > { o : Data . Vector . Primitive . Vector a | plen o = l }
@
assume Data.Vector.Primitive.unsafeSlice
:: Prim a
=> n : { n : Int | 0 <= n }
-> l : { l : Int | 0 <= l }
-> i : { i : Data.Vector.Primitive.Vector a | n + l <= plen i }
-> { o : Data.Vector.Primitive.Vector a | plen o = l }
@-}
@ measure pmlen : : Data . Vector . Primitive . Mutable . MVector s a - > Int @
@
assume Data.Vector.Primitive.Mutable.length
: : Prim a
= > v : Data . Vector . Primitive . Mutable . MVector s a
- > { n : Int | 0 < = n & & n = = pmlen v }
@
assume Data.Vector.Primitive.Mutable.length
:: Prim a
=> v : Data.Vector.Primitive.Mutable.MVector s a
-> { n : Int | 0 <= n && n == pmlen v }
@-}
@
assume Data . Vector . Primitive . Mutable.unsafeWrite
: : ( PrimMonad m , Prim a )
= > v : Data . Vector . Primitive . Mutable . MVector ( PrimState m ) a
- > { n : Int | 0 < = n & & n < pmlen v }
- > a
- > m ( )
@
assume Data.Vector.Primitive.Mutable.unsafeWrite
:: (PrimMonad m, Prim a)
=> v : Data.Vector.Primitive.Mutable.MVector (PrimState m) a
-> { n : Int | 0 <= n && n < pmlen v }
-> a
-> m ()
@-}
@
assume primitiveNewST
: : Prim a
= > n : Int
- > ST s ( { v : Data . Vector . Primitive . Mutable . MVector s a | pmlen v = = n } )
@
assume primitiveNewST
:: Prim a
=> n : Int
-> ST s ({ v : Data.Vector.Primitive.Mutable.MVector s a | pmlen v == n })
@-}
primitiveNewST
:: Prim a => Int -> ST s (Data.Vector.Primitive.Mutable.MVector s a)
primitiveNewST = Data.Vector.Primitive.Mutable.new
# INLINE primitiveNewST #
@
qualif : Data . Vector . Primitive . Mutable . MVector s a , n : Int ) : pmlen v = = n
@
qualif New(v : Data.Vector.Primitive.Mutable.MVector s a, n : Int) : pmlen v == n
@-}
@
assume primitiveFreezeST
: : Prim a
= > mv : Data . Vector . Primitive . Mutable . MVector s a
- > ST s ( { v : Data . Vector . Primitive . Vector a | plen v = = pmlen mv } )
@
assume primitiveFreezeST
:: Prim a
=> mv : Data.Vector.Primitive.Mutable.MVector s a
-> ST s ({ v : Data.Vector.Primitive.Vector a | plen v == pmlen mv })
@-}
primitiveFreezeST
:: Prim a
=> Data.Vector.Primitive.Mutable.MVector s a
-> ST s (Data.Vector.Primitive.Vector a)
primitiveFreezeST = Data.Vector.Primitive.freeze
# INLINE primitiveFreezeST #
| Finds the last element in the vector that is less than or equal to ` x `
when transformed using function ` f `
TODO : This assumes that there is at least one element in the vector less
than or equal to ` x `
when transformed using function `f`
TODO: This assumes that there is at least one element in the vector less
than or equal to `x`
-}
@
search
: : ( Prim e , a )
= > x : a
- > f : ( e - > a )
- > v : Data . Vector . Primitive . Vector e
- > lo : { lo : Int | 0 < = lo & & lo < plen v }
- > hi : { hi : Int | lo < hi & & hi < = plen v }
- > { r : Int | lo < = r & & r < hi }
/ [ hi - lo ]
@
search
:: (Prim e, Ord a)
=> x : a
-> f : (e -> a)
-> v : Data.Vector.Primitive.Vector e
-> lo : { lo : Int | 0 <= lo && lo < plen v }
-> hi : { hi : Int | lo < hi && hi <= plen v }
-> { r : Int | lo <= r && r < hi }
/ [hi - lo]
@-}
search
:: (Ord a, Prim e)
=> a -> (e -> a) -> Data.Vector.Primitive.Vector e -> Int -> Int -> Int
search x f v lo hi = do
if lo + 1 == hi
then lo
else do
let mid = lo + (hi - lo) `div` 2
let x' = f (Data.Vector.Primitive.unsafeIndex v mid)
if x < x'
then search x f v lo mid
else search x f v mid hi
| null |
https://raw.githubusercontent.com/Gabriella439/Haskell-Succinct-Vector-Library/9538eb47a34905136fad79497f9539ffc1db3239/src/Succinct/Vector/Primitives.hs
|
haskell
|
@ measure plen :: Data.Vector.Primitive.Vector a -> Int @
|
module Succinct.Vector.Primitives where
import Control.Monad.Primitive (PrimMonad, PrimState)
import Control.Monad.ST (ST)
import Data.Primitive.Types (Prim)
import qualified Data.Vector.Primitive
import qualified Data.Vector.Primitive.Mutable
@
assume Data.Vector.Primitive.length
: : Prim a
= > v : Data . Vector . Primitive . Vector a - > { n : Int | 0 < = n & & n = = plen v }
@
assume Data.Vector.Primitive.length
:: Prim a
=> v : Data.Vector.Primitive.Vector a -> { n : Int | 0 <= n && n == plen v }
@-}
@
Data . Vector . Primitive.unsafeIndex
: : Prim a
= > v : Data . Vector . Primitive . Vector a
- > { n : Int | 0 < = n & & n < plen v }
- > a
@
Data.Vector.Primitive.unsafeIndex
:: Prim a
=> v : Data.Vector.Primitive.Vector a
-> { n : Int | 0 <= n && n < plen v }
-> a
@-}
@
assume Data . Vector . Primitive.unsafeSlice
: : Prim a
= > n : { n : Int | 0 < = n }
- > l : { l : Int | 0 < = l }
- > i : { i : Data . Vector . Primitive . Vector a | n + l < = plen i }
- > { o : Data . Vector . Primitive . Vector a | plen o = l }
@
assume Data.Vector.Primitive.unsafeSlice
:: Prim a
=> n : { n : Int | 0 <= n }
-> l : { l : Int | 0 <= l }
-> i : { i : Data.Vector.Primitive.Vector a | n + l <= plen i }
-> { o : Data.Vector.Primitive.Vector a | plen o = l }
@-}
@ measure pmlen : : Data . Vector . Primitive . Mutable . MVector s a - > Int @
@
assume Data.Vector.Primitive.Mutable.length
: : Prim a
= > v : Data . Vector . Primitive . Mutable . MVector s a
- > { n : Int | 0 < = n & & n = = pmlen v }
@
assume Data.Vector.Primitive.Mutable.length
:: Prim a
=> v : Data.Vector.Primitive.Mutable.MVector s a
-> { n : Int | 0 <= n && n == pmlen v }
@-}
@
assume Data . Vector . Primitive . Mutable.unsafeWrite
: : ( PrimMonad m , Prim a )
= > v : Data . Vector . Primitive . Mutable . MVector ( PrimState m ) a
- > { n : Int | 0 < = n & & n < pmlen v }
- > a
- > m ( )
@
assume Data.Vector.Primitive.Mutable.unsafeWrite
:: (PrimMonad m, Prim a)
=> v : Data.Vector.Primitive.Mutable.MVector (PrimState m) a
-> { n : Int | 0 <= n && n < pmlen v }
-> a
-> m ()
@-}
@
assume primitiveNewST
: : Prim a
= > n : Int
- > ST s ( { v : Data . Vector . Primitive . Mutable . MVector s a | pmlen v = = n } )
@
assume primitiveNewST
:: Prim a
=> n : Int
-> ST s ({ v : Data.Vector.Primitive.Mutable.MVector s a | pmlen v == n })
@-}
primitiveNewST
:: Prim a => Int -> ST s (Data.Vector.Primitive.Mutable.MVector s a)
primitiveNewST = Data.Vector.Primitive.Mutable.new
# INLINE primitiveNewST #
@
qualif : Data . Vector . Primitive . Mutable . MVector s a , n : Int ) : pmlen v = = n
@
qualif New(v : Data.Vector.Primitive.Mutable.MVector s a, n : Int) : pmlen v == n
@-}
@
assume primitiveFreezeST
: : Prim a
= > mv : Data . Vector . Primitive . Mutable . MVector s a
- > ST s ( { v : Data . Vector . Primitive . Vector a | plen v = = pmlen mv } )
@
assume primitiveFreezeST
:: Prim a
=> mv : Data.Vector.Primitive.Mutable.MVector s a
-> ST s ({ v : Data.Vector.Primitive.Vector a | plen v == pmlen mv })
@-}
primitiveFreezeST
:: Prim a
=> Data.Vector.Primitive.Mutable.MVector s a
-> ST s (Data.Vector.Primitive.Vector a)
primitiveFreezeST = Data.Vector.Primitive.freeze
# INLINE primitiveFreezeST #
| Finds the last element in the vector that is less than or equal to ` x `
when transformed using function ` f `
TODO : This assumes that there is at least one element in the vector less
than or equal to ` x `
when transformed using function `f`
TODO: This assumes that there is at least one element in the vector less
than or equal to `x`
-}
@
search
: : ( Prim e , a )
= > x : a
- > f : ( e - > a )
- > v : Data . Vector . Primitive . Vector e
- > lo : { lo : Int | 0 < = lo & & lo < plen v }
- > hi : { hi : Int | lo < hi & & hi < = plen v }
- > { r : Int | lo < = r & & r < hi }
/ [ hi - lo ]
@
search
:: (Prim e, Ord a)
=> x : a
-> f : (e -> a)
-> v : Data.Vector.Primitive.Vector e
-> lo : { lo : Int | 0 <= lo && lo < plen v }
-> hi : { hi : Int | lo < hi && hi <= plen v }
-> { r : Int | lo <= r && r < hi }
/ [hi - lo]
@-}
search
:: (Ord a, Prim e)
=> a -> (e -> a) -> Data.Vector.Primitive.Vector e -> Int -> Int -> Int
search x f v lo hi = do
if lo + 1 == hi
then lo
else do
let mid = lo + (hi - lo) `div` 2
let x' = f (Data.Vector.Primitive.unsafeIndex v mid)
if x < x'
then search x f v lo mid
else search x f v mid hi
|
225b37fd60b96e6e3c4233dfb6b14210ae9e5bd8818e9ff93bf725cda4ce5479
|
luciodale/fork
|
datepicker.cljs
|
(ns examples.datepicker
(:require
;; for CSS use:
;; [email protected]/lib/css/_datepicker.css
[cljsjs.react-dates]
[cljs.pprint :as pprint]
[fork.reagent :as fork]))
(defn react-dates-single-date-picker
[k {:keys [values state set-values]}]
[:> js/ReactDates.SingleDatePicker
{:date (get values k)
:display-format "DD MMM YYYY"
:on-focus-change (fn [e]
(swap! state #(assoc-in % [:focus k] (.-focused e))))
:focused (get-in @state [:focus k])
:on-date-change #(set-values {k %})}])
(defn react-dates-date-range-picker
[k {:keys [values state set-values]}]
[:> js/ReactDates.DateRangePicker
{:start-date (get-in values [k :startDate])
:end-date (get-in values [k :endDate])
:display-format "DD MMM YYYY"
:on-focus-change (fn [e]
(swap! state #(assoc-in % [:focus k] e)))
:focused-input (get-in @state [:focus k])
:on-dates-change #(set-values {k (js->clj % :keywordize-keys true)})}])
(defn view []
[:<>
[fork/form
{:keywordize-keys true
:prevent-default? true
:on-submit #(js/alert (:values %))
:initial-values {:dummy/input "Just an input"
:single-date-picker (js/moment)
:date-range-picker {:startDate (js/moment)}}}
(fn [{:keys [state
form-id
values
normalize-name
handle-change
handle-blur
handle-submit] :as props}]
[:div
[:pre (with-out-str (pprint/pprint @state))]
[:h3 "This is an example of how to wire up react dates to fork."]
[:p "The datepickers share very common APIs, so the implementation details can be easily ported"]
[:form
{:id form-id
:on-submit handle-submit}
[:div
[:div
[:label "Dummy input"]]
[:input
{:type "text"
:name (normalize-name :dummy/input)
:value (:dummy/input values)
:on-change handle-change
:on-blur handle-blur}]]
[:br]
[:div
[react-dates-single-date-picker :single-date-picker props]]
[:br]
[:div
[react-dates-date-range-picker :date-range-picker props]]
[:br]
[:button
{:type "submit"}
"Submit!"]]])]])
| null |
https://raw.githubusercontent.com/luciodale/fork/3c7a47abcd400406752c1f0c7391b6610008cfab/examples/datepicker.cljs
|
clojure
|
for CSS use:
[email protected]/lib/css/_datepicker.css
|
(ns examples.datepicker
(:require
[cljsjs.react-dates]
[cljs.pprint :as pprint]
[fork.reagent :as fork]))
(defn react-dates-single-date-picker
[k {:keys [values state set-values]}]
[:> js/ReactDates.SingleDatePicker
{:date (get values k)
:display-format "DD MMM YYYY"
:on-focus-change (fn [e]
(swap! state #(assoc-in % [:focus k] (.-focused e))))
:focused (get-in @state [:focus k])
:on-date-change #(set-values {k %})}])
(defn react-dates-date-range-picker
[k {:keys [values state set-values]}]
[:> js/ReactDates.DateRangePicker
{:start-date (get-in values [k :startDate])
:end-date (get-in values [k :endDate])
:display-format "DD MMM YYYY"
:on-focus-change (fn [e]
(swap! state #(assoc-in % [:focus k] e)))
:focused-input (get-in @state [:focus k])
:on-dates-change #(set-values {k (js->clj % :keywordize-keys true)})}])
(defn view []
[:<>
[fork/form
{:keywordize-keys true
:prevent-default? true
:on-submit #(js/alert (:values %))
:initial-values {:dummy/input "Just an input"
:single-date-picker (js/moment)
:date-range-picker {:startDate (js/moment)}}}
(fn [{:keys [state
form-id
values
normalize-name
handle-change
handle-blur
handle-submit] :as props}]
[:div
[:pre (with-out-str (pprint/pprint @state))]
[:h3 "This is an example of how to wire up react dates to fork."]
[:p "The datepickers share very common APIs, so the implementation details can be easily ported"]
[:form
{:id form-id
:on-submit handle-submit}
[:div
[:div
[:label "Dummy input"]]
[:input
{:type "text"
:name (normalize-name :dummy/input)
:value (:dummy/input values)
:on-change handle-change
:on-blur handle-blur}]]
[:br]
[:div
[react-dates-single-date-picker :single-date-picker props]]
[:br]
[:div
[react-dates-date-range-picker :date-range-picker props]]
[:br]
[:button
{:type "submit"}
"Submit!"]]])]])
|
43b9706880344c8f5bf3255090bc9b74000155827f803cfcceb544278f7c35c4
|
wilbowma/cur
|
sugar.rkt
|
#lang cur
(require
cur/stdlib/sugar
rackunit/turnstile+)
(define-datatype Nat : Type
[Z : Nat]
[S : (→ Nat Nat)])
(define/rec/match plus : Nat [n : Nat] -> Nat
[Z => n]
[(S x) => (S (plus x n))])
(define/rec/match minus : Nat Nat -> Nat
[Z _ => Z]
[(S n-1) z => (S n-1)]
[(S n-1) (S m-1) => (minus n-1 m-1)])
(define/rec/match mult : Nat [n : Nat] -> Nat
[Z => Z]
[(S x) => (plus n (mult x n))])
(check-type
(λ (x : (Type 1)) x)
: (-> (Type 1) (Type 1)))
(check-type
((λ (x : (Type 1)) x) Type)
: (Type 1))
(check-type
(λ (x : (Type 1)) (y : (Π (x : (Type 1)) (Type 1))) (y x))
: (-> (Type 1) (Π (x : (Type 1)) (Type 1)) (Type 1)))
;; TODO: Missing tests for match, others
(check-type
((λ (x : (Type 1)) (y : (Π (x : (Type 1)) (Type 1))) (y x))
Type
(λ (x : (Type 1)) x))
: (Type 1)
-> Type)
(check-type
((λ (x : (Type 1)) (y : (→ (Type 1) (Type 1))) (y x))
Type
(λ (x : (Type 1)) x))
: (Type 1)
-> Type)
(check-type
(let ([x Type]
[y (λ (x : (Type 1)) x)])
(y x))
: (Type 1)
-> Type)
with 1 anno
(let ([(x : (Type 1)) Type]
[y (λ (x : (Type 1)) x)])
(y x))
: (Type 1)
-> Type)
;; check that raises decent syntax error
(typecheck-fail
(let ([x : (Type 1) Type]
[y (λ (x : (Type 1)) x)])
(y x))
#:with-msg "unexpected term.*at: \\(Type 1\\)")
(typecheck-fail
(let ([x (λ x x)]
[y (λ (x : (Type 1)) x)])
(y x))
#:with-msg "λ: no expected type, add annotations")
;; the following tests that typecheck-relation properly restored
;; (even after err);
thanks to ( @pwang347 ) for finding the problem ( see pr#101 )
(require cur/stdlib/bool)
(typecheck-fail/toplvl
(define/rec/match sub1-bad2 : Nat -> Bool
[Z => Z]
[(S x) => x])
#:with-msg "expected Bool, given Nat.*expression: Z")
(begin-for-syntax
(require rackunit)
should ignore prop and succesfully
but fails if sub1 - bad2 def does not properly restore tycheck - relation
((current-typecheck-relation) #'Nat (syntax-property #'Nat 'recur #t))))
(define/rec/match multi-pat : Nat Nat Nat -> Nat
[_ _ Z => Z]
[n m (S l-1) => (multi-pat n m l-1)])
(begin-for-syntax
should ignore prop and succesfully
but fails if sub1 - bad2 def does not properly restore tycheck - relation
((current-typecheck-relation) #'Nat (syntax-property #'Nat 'recur #t))))
| null |
https://raw.githubusercontent.com/wilbowma/cur/e039c98941b3d272c6e462387df22846e10b0128/cur-test/cur/tests/stdlib/sugar.rkt
|
racket
|
TODO: Missing tests for match, others
check that raises decent syntax error
the following tests that typecheck-relation properly restored
(even after err);
|
#lang cur
(require
cur/stdlib/sugar
rackunit/turnstile+)
(define-datatype Nat : Type
[Z : Nat]
[S : (→ Nat Nat)])
(define/rec/match plus : Nat [n : Nat] -> Nat
[Z => n]
[(S x) => (S (plus x n))])
(define/rec/match minus : Nat Nat -> Nat
[Z _ => Z]
[(S n-1) z => (S n-1)]
[(S n-1) (S m-1) => (minus n-1 m-1)])
(define/rec/match mult : Nat [n : Nat] -> Nat
[Z => Z]
[(S x) => (plus n (mult x n))])
(check-type
(λ (x : (Type 1)) x)
: (-> (Type 1) (Type 1)))
(check-type
((λ (x : (Type 1)) x) Type)
: (Type 1))
(check-type
(λ (x : (Type 1)) (y : (Π (x : (Type 1)) (Type 1))) (y x))
: (-> (Type 1) (Π (x : (Type 1)) (Type 1)) (Type 1)))
(check-type
((λ (x : (Type 1)) (y : (Π (x : (Type 1)) (Type 1))) (y x))
Type
(λ (x : (Type 1)) x))
: (Type 1)
-> Type)
(check-type
((λ (x : (Type 1)) (y : (→ (Type 1) (Type 1))) (y x))
Type
(λ (x : (Type 1)) x))
: (Type 1)
-> Type)
(check-type
(let ([x Type]
[y (λ (x : (Type 1)) x)])
(y x))
: (Type 1)
-> Type)
with 1 anno
(let ([(x : (Type 1)) Type]
[y (λ (x : (Type 1)) x)])
(y x))
: (Type 1)
-> Type)
(typecheck-fail
(let ([x : (Type 1) Type]
[y (λ (x : (Type 1)) x)])
(y x))
#:with-msg "unexpected term.*at: \\(Type 1\\)")
(typecheck-fail
(let ([x (λ x x)]
[y (λ (x : (Type 1)) x)])
(y x))
#:with-msg "λ: no expected type, add annotations")
thanks to ( @pwang347 ) for finding the problem ( see pr#101 )
(require cur/stdlib/bool)
(typecheck-fail/toplvl
(define/rec/match sub1-bad2 : Nat -> Bool
[Z => Z]
[(S x) => x])
#:with-msg "expected Bool, given Nat.*expression: Z")
(begin-for-syntax
(require rackunit)
should ignore prop and succesfully
but fails if sub1 - bad2 def does not properly restore tycheck - relation
((current-typecheck-relation) #'Nat (syntax-property #'Nat 'recur #t))))
(define/rec/match multi-pat : Nat Nat Nat -> Nat
[_ _ Z => Z]
[n m (S l-1) => (multi-pat n m l-1)])
(begin-for-syntax
should ignore prop and succesfully
but fails if sub1 - bad2 def does not properly restore tycheck - relation
((current-typecheck-relation) #'Nat (syntax-property #'Nat 'recur #t))))
|
af896bfa999f4db6a2fb8a5678ab44c48094130ac18f72b33de71d6b2ed9bf33
|
craff/pacomb
|
lex.ml
|
let default : 'a -> 'a option -> 'a = fun d o ->
match o with
| None -> d
| Some e -> e
type buf = Input.buffer
type idx = Input.idx
(** Exception to be raised when the input is rejected *)
exception NoParse
exception Give_up of string
(** [give_up ()] rejects parsing from a corresponding semantic action. *)
let give_up : ?msg:string -> unit -> 'a = fun ?msg () ->
match msg with None -> raise NoParse
| Some s -> raise (Give_up s)
type 'a lexeme = buf -> idx -> 'a * buf * idx
type _ ast =
| Any : char ast
| Any_utf8 : Uchar.t ast
| Any_grapheme : string ast
| Eof : unit ast
| Char : char -> unit ast
| Grapheme : string -> unit ast
| String : string -> unit ast
| Nat : int ast
| Int : int ast
| Float : float ast
| CharLit : char ast
| StringLit : string ast
| Test : (char -> bool) -> char ast
| NotTest : (char -> bool) -> unit ast
| Seq : 'a t * 'b t * ('a -> 'b -> 'c) * 'c Assoc.key -> 'c ast
| Alt : 'a t * 'a t -> 'a ast
| Save : 'a t * (string -> 'a -> 'b) * 'b Assoc.key -> 'b ast
| Option : 'a * 'a t -> 'a ast
| Appl : 'a t * ('a -> 'b) * 'b Assoc.key -> 'b ast
| Star : 'a t * (unit -> 'b) * ('b -> 'a -> 'b) * 'b Assoc.key -> 'b ast
| Plus : 'a t * (unit -> 'b) * ('b -> 'a -> 'b) * 'b Assoc.key -> 'b ast
| Keyword : string * int -> unit ast
| Custom : 'a lexeme * 'a Assoc.key -> 'a ast
(** Terminal: same as blank with a value returned *)
and 'a terminal = { n : string (** name *)
; f : 'a lexeme (** the terminal itself *)
; a : 'a ast
; c : Charset.t (** the set of characters accepted
at the beginning of input *)
}
and 'a t = 'a terminal
let custom fn = Custom(fn, Assoc.new_key ())
let rec eq : type a b.a t -> b t -> (a,b) Assoc.eq =
fun a b ->
let open Assoc in
match (a.a, b.a) with
| Any, Any -> Eq
| Any_utf8, Any_utf8 -> Eq
| Any_grapheme, Any_grapheme -> Eq
| Eof, Eof -> Eq
| Char c1, Char c2 -> if c1 = c2 then Eq else NEq
| Grapheme s1, Grapheme s2 -> if s1 = s2 then Eq else NEq
| String s1, String s2 -> if s1 = s2 then Eq else NEq
| Nat, Nat -> Eq
| Int, Int -> Eq
| Float, Float -> Eq
| CharLit, CharLit -> Eq
| StringLit, StringLit -> Eq
| Test af, Test bf -> if af == bf then Eq else NEq
| NotTest af, NotTest bf -> if af == bf then Eq else NEq
| Seq(_,_,_,ak), Seq(_,_,_,bk) -> ak.eq bk.tok
| Alt(a1,a2), Alt(b1,b2) ->
begin
match eq a1 b1, eq a2 b2 with
| Eq, Eq -> Eq
| _ -> NEq
end
| Save(_,_,ak), Save(_,_,bk) -> ak.eq bk.tok
| Option(ad,a1), Option(bd,b1) ->
begin
match eq a1 b1 with
| Eq -> if ad == bd then Eq else NEq
| _ -> NEq
end
| Appl(_,_,ak), Appl(_,_,bk) -> ak.eq bk.tok
| Star(_,_,_,ak), Star(_,_,_,bk) -> ak.eq bk.tok
| Plus(_,_,_,ak), Plus(_,_,_,bk) -> ak.eq bk.tok
| Keyword(s1,uid1), Keyword(s2,uid2) ->
if s1 = s2 && uid1 = uid2 then Eq else NEq
| Custom(af,ak), Custom(bf,bk) ->
begin
match ak.eq bk.tok with
| Eq when af == bf -> Eq
| _ -> NEq
end
| _ -> NEq
let s0 = Input.from_string ""
let s1 = Input.from_string "\255 "(* for eof to passe the test *)
let accept_empty : type a. a t -> bool = fun t ->
try ignore(t.f s0 Input.init_idx);
try let (_,b,idx) = t.f s1 Input.init_idx in
Input.int_of_byte_pos (Input.byte_pos b idx) <> 1
with NoParse -> true
with NoParse -> false
let test_from_lex : bool t -> buf -> idx -> buf -> idx -> bool =
fun t _ _ buf idx ->
try let (r,_,_) = t.f buf idx in r
with NoParse | Give_up _ -> false
let blank_test_from_lex : bool t -> buf -> idx -> buf -> idx -> bool =
fun t buf idx _ _ ->
try let (r,_,_) = t.f buf idx in r
with NoParse | Give_up _ -> false
(** Combinators to create terminals *)
let any : ?name:string -> unit -> char t = fun ?(name="ANY") () ->
{ n = name
; c = Charset.full
; a = Any
; f = fun s n -> let (c,_,_ as res) = Input.read s n
in if c = '\255' then raise NoParse else res
}
(** Terminal accepting then end of a buffer only.
remark: [eof] is automatically added at the end of a grammar by
[Combinator.parse_buffer]. *)
let eof : ?name:string -> unit -> unit t = fun ?(name="EOF") () ->
{ n = name
; c = Charset.singleton '\255'
; a = Eof
; f = fun s n -> let (c,s,n) = Input.read s n in
if c = '\255' then ((),s,n) else raise NoParse
}
let sp = Printf.sprintf
(** Terminal accepting a given char, remark: [char '\255'] is equivalent to
[eof]. *)
let char : ?name:string -> char -> unit t = fun ?name c ->
{ n = default (sp "'%c'" c) name
; c = Charset.singleton c
; a = Char c
; f = fun s n ->
let (c',s,n) = Input.read s n in
if c = c' then ((),s,n) else raise NoParse
}
let charset_from_test f =
let l = ref Charset.empty in
for i = 0 to 255 do
let c = Char.chr i in
if f c then l := Charset.add !l c
done;
!l
let any_utf8 : ?name:string -> unit -> Uchar.t t = fun ?name () ->
{ n = default "UTF8" name
; c = Charset.full
; a = Any_utf8
; f = fun s n ->
let (c1,s,n) = Input.read s n in
if c1 = '\255' then raise NoParse;
let n1 = Char.code c1 in
let (n0,s,n) =
if n1 land 0b1000_0000 = 0 then (n1 land 0b0111_1111, s, n)
else if n1 land 0b1110_0000 = 0b1100_0000 then
begin
let (c2,s,n) = Input.read s n in
let n2 = Char.code c2 in
if n2 land 0b1100_0000 <> 0b1000_0000 then raise NoParse;
(((n1 land 0b0001_1111) lsl 6) lor
(n2 land 0b0011_1111), s , n)
end
else if n1 land 0b1111_0000 = 0b1110_0000 then
begin
let (c2,s,n) = Input.read s n in
let n2 = Char.code c2 in
if n2 land 0b1100_0000 <> 0b1000_0000 then raise NoParse;
let (c3,s,n) = Input.read s n in
let n3 = Char.code c3 in
if n3 land 0b1100_0000 <> 0b1000_0000 then raise NoParse;
(((n1 land 0b0000_1111) lsl 12) lor
((n2 land 0b0011_1111) lsl 6) lor
(n3 land 0b0011_1111), s, n)
end
else if n1 land 0b1111_1000 = 0b1111_0000 then
begin
let (c2,s,n) = Input.read s n in
let n2 = Char.code c2 in
if n2 land 0b1100_0000 <> 0b1000_0000 then raise NoParse;
let (c3,s,n) = Input.read s n in
let n3 = Char.code c3 in
if n3 land 0b1100_0000 <> 0b1000_0000 then raise NoParse;
let (c4,s,n) = Input.read s n in
let n4 = Char.code c4 in
if n4 land 0b1100_0000 <> 0b1000_0000 then raise NoParse;
(((n1 land 0b0000_0111) lsl 18) lor
((n2 land 0b0011_1111) lsl 12) lor
((n3 land 0b0011_1111) lsl 6) lor
(n4 land 0b0011_1111), s, n)
end
else raise NoParse
in
(Uchar.of_int n0,s,n)
}
(** [string s] Accepts only the given string.*)
let string : ?name:string -> string -> unit t = fun ?name k ->
if k = "" then invalid_arg "Lex.string: empty string";
{ n = default (sp "\"%s\"" k) name
; c = Charset.singleton k.[0]
; a = String k
; f = fun s n ->
let l = String.length k in
let rec fn i s n =
if i >= l then (s,n) else
let c,s,n = Input.read s n in
if c <> k.[i] then raise NoParse;
fn (i+1) s n
in
let (s,n) = fn 0 s n in
((),s,n) }
let utf8 : ?name:string -> Uchar.t -> unit t = fun ?name k ->
string ?name (Utf8.encode k)
let any_grapheme : ?name:string -> unit -> string t = fun ?name () ->
{ n = default "GRAPHEME" name
; c = Charset.full
; a = Any_grapheme
; f = fun s n ->
let rec fn acc s n =
try
let (c,s',n') = (any_utf8 ()).f s n in
if acc <> [] && Utf8.grapheme_break_after acc c then
(acc,s,n)
else
fn (c::acc) s' n'
with NoParse ->
if acc <> [] then (acc, s, n) else raise NoParse
in
try
let (l,s,n) = fn [] s n in
(String.concat "" (List.rev_map Utf8.encode l),s, n)
with Invalid_argument _ -> raise NoParse }
let grapheme : ?name:string -> string -> unit t = fun ?name k ->
if k = "" then invalid_arg "Lex.grapheme: empty string";
{ n = default ("GRAPHEME("^k^")") name
; c = Charset.singleton k.[0]
; a = Grapheme k
; f = fun s n ->
let (k',s,n) = (any_grapheme ()).f s n in
if k = k' then ((),s,n) else raise NoParse }
(** Accept a character for which the test returns [true] *)
let test : ?name:string -> (char -> bool) -> char t = fun ?name f ->
let cs = charset_from_test f in
{ n = default (Charset.show cs) name
; c = charset_from_test f
; a = Test f
; f = fun s n ->
let (c,s,n) = Input.read s n in
if f c then (c, s, n)
else raise NoParse
}
(** Accept a character in the given charset *)
let charset : ?name:string -> Charset.t -> char t = fun ?name cs ->
test ?name (Charset.mem cs)
* Reject the input ( raises [ ] ) if the first character of the input
passed the test . Does not read the character if the test fails .
passed the test. Does not read the character if the test fails. *)
let not_test : ?name:string -> (char -> bool) -> unit t =
fun ?name f ->
let cs = charset_from_test f in
{ n = default (sp "^%s" (Charset.show cs)) name
; c = Charset.complement cs
; a = NotTest f
; f = fun s n ->
let (c,_,_) = Input.read s n in
if (f c) then raise NoParse else ((), s, n)
}
* Reject the input ( raises [ ] ) if the first character of the input
is in the charset . Does not read the character if not in the charset .
is in the charset. Does not read the character if not in the charset. *)
let not_charset : ?name:string -> Charset.t -> unit t =
fun ?name cs -> not_test ?name (Charset.mem cs)
* Compose two terminals in sequence
let seq : ?name:string -> 'a t -> 'b t -> ('a -> 'b -> 'c) -> 'c t =
fun ?name t1 t2 f ->
{ n = default (sp "%s%s" t1.n t2.n) name
; c = if accept_empty t1 then Charset.union t1.c t2.c else t1.c
; a = Seq(t1, t2, f, Assoc.new_key ())
; f = fun s n ->
let (s1,s,n) = t1.f s n in
let (s2,s,n) = t2.f s n in
(f s1 s2,s,n)
}
let seq1 ?name t1 t2 = seq ?name t1 t2 (fun x _ -> x)
let seq2 ?name t1 t2 = seq ?name t1 t2 (fun _ x -> x)
(** multiple sequence *)
let seqs : 'a t list -> ('a -> 'a -> 'a) -> 'a t = fun l f ->
let rec fn = function
| [] -> invalid_arg "alts: empty list"
| [r] -> r
| r::l -> seq r (fn l) f
in fn l
(** [alt t1 t2] parses the input with [t1] or [t2]. *)
let alt : ?name:string -> 'a t -> 'a t -> 'a t =
fun ?name t1 t2 ->
{ n = default (sp "(%s)|(%s)" t1.n t2.n) name
; c = Charset.union t1.c t2.c
; a = Alt(t1, t2)
; f = fun s n ->
try
let (_,s1,n1 as r1) = t1.f s n in
try
let (_,s2,n2 as r2) = t2.f s n in
let l1 = Input.byte_pos s1 n1 in
let l2 = Input.byte_pos s2 n2 in
if l2 > l1 then r2 else r1
with NoParse -> r1
with NoParse -> t2.f s n
}
(** multiple alternatives *)
let rec alts : 'a t list -> 'a t = function
| [] -> invalid_arg "alts: empty list"
| [r] -> r
| r::l -> alt r (alts l)
(** save the content of the buffer in a string *)
let save : ?name:string -> 'a t -> (string -> 'a -> 'b) -> 'b t =
fun ?name t1 f ->
{ n = default t1.n name
; c = t1.c
; a = Save(t1,f, Assoc.new_key ())
; f = fun s n ->
let (l,s1,n1) = t1.f s n in
let len =
Input.int_of_byte_pos (Input.byte_pos s1 n1)
- Input.int_of_byte_pos (Input.byte_pos s n) in
let str = Input.sub s n len in
(f str l, s1, n1) }
* Parses the given terminal 0 or 1 time .
let option : ?name:string -> 'a -> 'a t -> 'a t =
fun ?name d t ->
{ n = default (sp "(%s)?" t.n) name
; c = Charset.full
; a = Option(d,t)
; f = fun s n ->
try let (x,s,n) = t.f s n in (x,s,n)
with NoParse -> (d,s,n) }
(** Applies a function to the result of the given terminal. *)
let appl : ?name: string -> ('a -> 'b) -> 'a t -> 'b t =
fun ?name f t ->
{ n = default t.n name
; c = t.c
; a = Appl(t, f, Assoc.new_key ())
; f = fun s n -> let (x,s,n) = t.f s n in (f x,s,n) }
* [ star t a f ] Repetition of a given terminal 0,1 or more times .
let star : ?name:string -> 'a t -> (unit -> 'b) -> ('b -> 'a -> 'b) -> 'b t =
fun ?name t a f ->
{ n = default (sp "(%s)*" t.n) name
; c = t.c
; a = Star(t,a,f, Assoc.new_key ())
; f = fun s n ->
let rec fn a s n =
(try
let (x,s',n') = t.f s n in
if Input.buffer_equal s s' && n = n' then
fun () -> (a,s,n)
else
fun () -> fn (f a x) s' n'
with NoParse ->
fun () -> (a,s,n)) ()
in
fn (a ()) s n }
(** Same as above but parses at least once .*)
let plus : ?name:string -> 'a t -> (unit -> 'b) -> ('b -> 'a -> 'b) -> 'b t =
fun ?name t a f ->
{ n = default (sp "(%s)*" t.n) name
; c = t.c
; a = Plus(t,a,f, Assoc.new_key ())
; f = fun s n ->
let rec fn a s n =
(try
let (x,s',n') = t.f s n in
if Input.buffer_equal s s' && n = n' then
fun () -> (a,s,n)
else
fun () -> fn (f a x) s' n'
with NoParse ->
fun () -> (a,s,n)) ()
in
let (x,s,n) = t.f s n in
fn (f (a ()) x) s n }
* Parses natura in base 10 . [ " +42 " ] is not accepted .
let nat : ?name:string -> unit -> int t = fun ?name () ->
{ n = default "NAT" name
; c = Charset.from_string "-+0-9"
; a = Nat
; f = fun s n ->
let r = ref 0 in
let (c,s,n) = Input.read s n in
if not (c >= '0' && c <= '9') then raise NoParse;
r := !r * 10 + (Char.code c - Char.code '0');
let rec fn s0 n0 =
let (c,s,n) = Input.read s0 n0 in
if (c >= '0' && c <= '9') then (
r := !r * 10 + (Char.code c - Char.code '0');
fn s n)
else (s0,n0)
in
let (s,n) = fn s n in
(!r,s,n) }
* Parses an integer in base 10 . [ " +42 " ] is accepted .
let int : ?name:string -> unit -> int t = fun ?name () ->
{ n = default "INT" name
; c = Charset.from_string "-+0-9"
; a = Int
; f = fun s n ->
let r = ref 0 in
let f = ref (fun x -> x) in
let (c,s,n) =
let (c,s,n as r) = Input.read s n in
if c = '+' then Input.read s n
else if c = '-' then
(f := (fun x -> -x); Input.read s n)
else r
in
if not (c >= '0' && c <= '9') then raise NoParse;
r := !r * 10 + (Char.code c - Char.code '0');
let rec fn s0 n0 =
let (c,s,n) = Input.read s0 n0 in
if (c >= '0' && c <= '9') then (
r := !r * 10 + (Char.code c - Char.code '0');
fn s n)
else (s0,n0)
in
let (s,n) = fn s n in
(!f !r,s,n) }
* Parses a float in base 10 . [ " .1 " ] is as [ " 0.1 " ] .
let float : ?name:string -> unit -> float t = fun ?name () ->
{ n = default "FLOAT" name
; c = Charset.from_string "-+0-9."
; a = Float
; f = fun s0 n0 ->
let sg = ref 1.0 in
let ve = ref 0.0 in
let found_digit = ref false in
let m = ref 0.0 in
let digit c = float (Char.code c - Char.code '0')
in
let rec fn s0 n0 =
let (c,s,n) = Input.read s0 n0 in
if (c >= '0' && c <= '9') then (
found_digit := true;
m := !m *. 10.0 +. digit c;
fn s n)
else (c,s,n,s0,n0)
in
let rec fne s0 n0 =
let (c,s,n) = Input.read s0 n0 in
if (c >= '0' && c <= '9') then (
found_digit := true;
m := !m *. 10.0 +. digit c;
ve := !ve +. 1.0;
fne s n)
else (c,s,n,s0,n0)
in
let (c,s,n,s0,n0) =
let (c,s,n) = Input.read s0 n0 in
if c = '+' then fn s n
else if c = '-' then (sg := -1.0; fn s n)
else if (c >= '0' && c <= '9') then (
found_digit := true;
m := digit c;
fn s n)
else (c,s,n,s0,n0)
in
let (c,s,n,s0,n0) =
if c <> '.' then (c,s,n,s0,n0) else
fne s n
in
if not !found_digit then raise NoParse;
let sge = ref 1.0 in
let e = ref 0.0 in
let rec hn s0 n0 =
let (c,s,n) = Input.read s0 n0 in
if (c >= '0' && c <= '9') then (
found_digit := true;
e := !e *. 10.0 +. digit c;
hn s n)
else (s0,n0)
in
let (s0,n0) =
if c <> 'E' && c <> 'e' then (s0,n0) else
begin
let (c,s,n) =
let (c,s,n as r) = Input.read s n in
if c = '+' then
Input.read s n
else if c = '-' then
(sge := -1.0; Input.read s n)
else r
in
if not (c >= '0' && c <= '9') then raise NoParse;
e := digit c;
hn s n
end
in
(!sg *. !m *. (10.0 ** (-. !ve)) *. (10.0 ** (!sge *. !e)), s0, n0) }
(** escaped char for string and char litteral below *)
exception Escaped
let escaped = fun c s n ->
if c = '\\' then
let (c,s,n) = Input.read s n in
match c with
| '\\' -> ('\\', s, n)
| '\'' -> ('\'', s, n)
| '\"' -> ('"', s, n)
| 'n' -> ('\n', s, n)
| 'r' -> ('\r', s, n)
| 't' -> ('\t', s, n)
| 'b' -> ('\b', s, n)
| '0'..'2' ->
let (c1,s,n) = Input.read s n in
let (c2,s,n) = Input.read s n in
if (c1 >= '0' && c1 <= '9' && c2 >= '0' && c2 <= '9') then
begin
let c = ( (Char.code c - Char.code '0') * 100
+ (Char.code c1 - Char.code '0') * 10
+ (Char.code c2 - Char.code '0'))
in
if c < 256 then (Char.chr c, s, n) else
raise NoParse
end
else raise NoParse
| 'o' ->
let (c1,s,n) = Input.read s n in
let (c2,s,n) = Input.read s n in
let (c3,s,n) = Input.read s n in
if (c1 >= '0' && c1 <= '3' && c2 >= '0' && c2 <= '7'
&& c3 >= '0' && c3 <= '7') then
let c = ( (Char.code c1 - Char.code '0') * 64
+ (Char.code c2 - Char.code '0') * 8
+ (Char.code c3 - Char.code '0'))
in
(Char.chr c, s, n)
else raise NoParse
| 'x' ->
let (c1,s,n) = Input.read s n in
let (c2,s,n) = Input.read s n in
let x1 = match c1 with
| '0'..'9' -> Char.code c1 - Char.code '0'
| 'a'..'f' -> Char.code c1 - Char.code 'a' + 10
| 'A'..'F' -> Char.code c1 - Char.code 'A' + 10
| _ -> raise NoParse
in
let x2 = match c2 with
| '0'..'9' -> Char.code c2 - Char.code '0'
| 'a'..'f' -> Char.code c2 - Char.code 'a' + 10
| 'A'..'F' -> Char.code c2 - Char.code 'A' + 10
| _ -> raise NoParse
in
(Char.chr (x1 * 16 + x2), s, n)
| _ -> raise NoParse
else raise Escaped
(** char literal *)
let char_lit : ?name:string -> unit -> char t = fun ?name () ->
{ n = default "CHARLIT" name
; c = Charset.singleton '\''
; a = CharLit
; f = fun s n ->
let (c,s,n) = Input.read s n in
if c <> '\'' then raise NoParse;
let (c,s,n as r) = Input.read s n in
if c = '\'' || c = '\255' then raise NoParse;
let (cr,s,n) = try escaped c s n with Escaped -> r in
let (c,s,n) = Input.read s n in
if c <> '\'' then raise NoParse;
(cr,s,n)
}
(** treatment of escaped newline in string literal *)
let rec skip_newline c s0 n0 =
let rec fn s0 n0 =
let (c,s,n) = Input.read s0 n0 in
if c = ' ' || c = '\t' then fn s n
else skip_newline c s n
in
if c = '\\' then
let (c1,s,n) = Input.read s0 n0 in
if c1 = '\n' then fn s n else (c,s0, n0)
else (c,s0,n0)
(** string literal *)
let string_lit : ?name:string -> unit -> string t = fun ?name () ->
{ n = default "STRINTLIT" name
; c = Charset.singleton '"'
; a = StringLit
; f = fun s n ->
let (c,s,n) = Input.read s n in
if c <> '"' then raise NoParse;
let b = Buffer.create 64 in
let rec fn s n =
let (c,s,n) = Input.read s n in
let (c,s,n as r) = skip_newline c s n in
if c = '"' then (s,n)
else if c = '\255' then raise NoParse
else
begin
let (cr,s,n) = try escaped c s n with Escaped -> r in
Buffer.add_char b cr;
fn s n
end
in
let (s,n) = fn s n in
(Buffer.contents b,s,n)
}
| null |
https://raw.githubusercontent.com/craff/pacomb/a83ac9ccae510008e64a77418c41760245aec967/lib/lex.ml
|
ocaml
|
* Exception to be raised when the input is rejected
* [give_up ()] rejects parsing from a corresponding semantic action.
* Terminal: same as blank with a value returned
* name
* the terminal itself
* the set of characters accepted
at the beginning of input
for eof to passe the test
* Combinators to create terminals
* Terminal accepting then end of a buffer only.
remark: [eof] is automatically added at the end of a grammar by
[Combinator.parse_buffer].
* Terminal accepting a given char, remark: [char '\255'] is equivalent to
[eof].
* [string s] Accepts only the given string.
* Accept a character for which the test returns [true]
* Accept a character in the given charset
* multiple sequence
* [alt t1 t2] parses the input with [t1] or [t2].
* multiple alternatives
* save the content of the buffer in a string
* Applies a function to the result of the given terminal.
* Same as above but parses at least once .
* escaped char for string and char litteral below
* char literal
* treatment of escaped newline in string literal
* string literal
|
let default : 'a -> 'a option -> 'a = fun d o ->
match o with
| None -> d
| Some e -> e
type buf = Input.buffer
type idx = Input.idx
exception NoParse
exception Give_up of string
let give_up : ?msg:string -> unit -> 'a = fun ?msg () ->
match msg with None -> raise NoParse
| Some s -> raise (Give_up s)
type 'a lexeme = buf -> idx -> 'a * buf * idx
type _ ast =
| Any : char ast
| Any_utf8 : Uchar.t ast
| Any_grapheme : string ast
| Eof : unit ast
| Char : char -> unit ast
| Grapheme : string -> unit ast
| String : string -> unit ast
| Nat : int ast
| Int : int ast
| Float : float ast
| CharLit : char ast
| StringLit : string ast
| Test : (char -> bool) -> char ast
| NotTest : (char -> bool) -> unit ast
| Seq : 'a t * 'b t * ('a -> 'b -> 'c) * 'c Assoc.key -> 'c ast
| Alt : 'a t * 'a t -> 'a ast
| Save : 'a t * (string -> 'a -> 'b) * 'b Assoc.key -> 'b ast
| Option : 'a * 'a t -> 'a ast
| Appl : 'a t * ('a -> 'b) * 'b Assoc.key -> 'b ast
| Star : 'a t * (unit -> 'b) * ('b -> 'a -> 'b) * 'b Assoc.key -> 'b ast
| Plus : 'a t * (unit -> 'b) * ('b -> 'a -> 'b) * 'b Assoc.key -> 'b ast
| Keyword : string * int -> unit ast
| Custom : 'a lexeme * 'a Assoc.key -> 'a ast
; a : 'a ast
}
and 'a t = 'a terminal
let custom fn = Custom(fn, Assoc.new_key ())
let rec eq : type a b.a t -> b t -> (a,b) Assoc.eq =
fun a b ->
let open Assoc in
match (a.a, b.a) with
| Any, Any -> Eq
| Any_utf8, Any_utf8 -> Eq
| Any_grapheme, Any_grapheme -> Eq
| Eof, Eof -> Eq
| Char c1, Char c2 -> if c1 = c2 then Eq else NEq
| Grapheme s1, Grapheme s2 -> if s1 = s2 then Eq else NEq
| String s1, String s2 -> if s1 = s2 then Eq else NEq
| Nat, Nat -> Eq
| Int, Int -> Eq
| Float, Float -> Eq
| CharLit, CharLit -> Eq
| StringLit, StringLit -> Eq
| Test af, Test bf -> if af == bf then Eq else NEq
| NotTest af, NotTest bf -> if af == bf then Eq else NEq
| Seq(_,_,_,ak), Seq(_,_,_,bk) -> ak.eq bk.tok
| Alt(a1,a2), Alt(b1,b2) ->
begin
match eq a1 b1, eq a2 b2 with
| Eq, Eq -> Eq
| _ -> NEq
end
| Save(_,_,ak), Save(_,_,bk) -> ak.eq bk.tok
| Option(ad,a1), Option(bd,b1) ->
begin
match eq a1 b1 with
| Eq -> if ad == bd then Eq else NEq
| _ -> NEq
end
| Appl(_,_,ak), Appl(_,_,bk) -> ak.eq bk.tok
| Star(_,_,_,ak), Star(_,_,_,bk) -> ak.eq bk.tok
| Plus(_,_,_,ak), Plus(_,_,_,bk) -> ak.eq bk.tok
| Keyword(s1,uid1), Keyword(s2,uid2) ->
if s1 = s2 && uid1 = uid2 then Eq else NEq
| Custom(af,ak), Custom(bf,bk) ->
begin
match ak.eq bk.tok with
| Eq when af == bf -> Eq
| _ -> NEq
end
| _ -> NEq
let s0 = Input.from_string ""
let accept_empty : type a. a t -> bool = fun t ->
try ignore(t.f s0 Input.init_idx);
try let (_,b,idx) = t.f s1 Input.init_idx in
Input.int_of_byte_pos (Input.byte_pos b idx) <> 1
with NoParse -> true
with NoParse -> false
let test_from_lex : bool t -> buf -> idx -> buf -> idx -> bool =
fun t _ _ buf idx ->
try let (r,_,_) = t.f buf idx in r
with NoParse | Give_up _ -> false
let blank_test_from_lex : bool t -> buf -> idx -> buf -> idx -> bool =
fun t buf idx _ _ ->
try let (r,_,_) = t.f buf idx in r
with NoParse | Give_up _ -> false
let any : ?name:string -> unit -> char t = fun ?(name="ANY") () ->
{ n = name
; c = Charset.full
; a = Any
; f = fun s n -> let (c,_,_ as res) = Input.read s n
in if c = '\255' then raise NoParse else res
}
let eof : ?name:string -> unit -> unit t = fun ?(name="EOF") () ->
{ n = name
; c = Charset.singleton '\255'
; a = Eof
; f = fun s n -> let (c,s,n) = Input.read s n in
if c = '\255' then ((),s,n) else raise NoParse
}
let sp = Printf.sprintf
let char : ?name:string -> char -> unit t = fun ?name c ->
{ n = default (sp "'%c'" c) name
; c = Charset.singleton c
; a = Char c
; f = fun s n ->
let (c',s,n) = Input.read s n in
if c = c' then ((),s,n) else raise NoParse
}
let charset_from_test f =
let l = ref Charset.empty in
for i = 0 to 255 do
let c = Char.chr i in
if f c then l := Charset.add !l c
done;
!l
let any_utf8 : ?name:string -> unit -> Uchar.t t = fun ?name () ->
{ n = default "UTF8" name
; c = Charset.full
; a = Any_utf8
; f = fun s n ->
let (c1,s,n) = Input.read s n in
if c1 = '\255' then raise NoParse;
let n1 = Char.code c1 in
let (n0,s,n) =
if n1 land 0b1000_0000 = 0 then (n1 land 0b0111_1111, s, n)
else if n1 land 0b1110_0000 = 0b1100_0000 then
begin
let (c2,s,n) = Input.read s n in
let n2 = Char.code c2 in
if n2 land 0b1100_0000 <> 0b1000_0000 then raise NoParse;
(((n1 land 0b0001_1111) lsl 6) lor
(n2 land 0b0011_1111), s , n)
end
else if n1 land 0b1111_0000 = 0b1110_0000 then
begin
let (c2,s,n) = Input.read s n in
let n2 = Char.code c2 in
if n2 land 0b1100_0000 <> 0b1000_0000 then raise NoParse;
let (c3,s,n) = Input.read s n in
let n3 = Char.code c3 in
if n3 land 0b1100_0000 <> 0b1000_0000 then raise NoParse;
(((n1 land 0b0000_1111) lsl 12) lor
((n2 land 0b0011_1111) lsl 6) lor
(n3 land 0b0011_1111), s, n)
end
else if n1 land 0b1111_1000 = 0b1111_0000 then
begin
let (c2,s,n) = Input.read s n in
let n2 = Char.code c2 in
if n2 land 0b1100_0000 <> 0b1000_0000 then raise NoParse;
let (c3,s,n) = Input.read s n in
let n3 = Char.code c3 in
if n3 land 0b1100_0000 <> 0b1000_0000 then raise NoParse;
let (c4,s,n) = Input.read s n in
let n4 = Char.code c4 in
if n4 land 0b1100_0000 <> 0b1000_0000 then raise NoParse;
(((n1 land 0b0000_0111) lsl 18) lor
((n2 land 0b0011_1111) lsl 12) lor
((n3 land 0b0011_1111) lsl 6) lor
(n4 land 0b0011_1111), s, n)
end
else raise NoParse
in
(Uchar.of_int n0,s,n)
}
let string : ?name:string -> string -> unit t = fun ?name k ->
if k = "" then invalid_arg "Lex.string: empty string";
{ n = default (sp "\"%s\"" k) name
; c = Charset.singleton k.[0]
; a = String k
; f = fun s n ->
let l = String.length k in
let rec fn i s n =
if i >= l then (s,n) else
let c,s,n = Input.read s n in
if c <> k.[i] then raise NoParse;
fn (i+1) s n
in
let (s,n) = fn 0 s n in
((),s,n) }
let utf8 : ?name:string -> Uchar.t -> unit t = fun ?name k ->
string ?name (Utf8.encode k)
let any_grapheme : ?name:string -> unit -> string t = fun ?name () ->
{ n = default "GRAPHEME" name
; c = Charset.full
; a = Any_grapheme
; f = fun s n ->
let rec fn acc s n =
try
let (c,s',n') = (any_utf8 ()).f s n in
if acc <> [] && Utf8.grapheme_break_after acc c then
(acc,s,n)
else
fn (c::acc) s' n'
with NoParse ->
if acc <> [] then (acc, s, n) else raise NoParse
in
try
let (l,s,n) = fn [] s n in
(String.concat "" (List.rev_map Utf8.encode l),s, n)
with Invalid_argument _ -> raise NoParse }
let grapheme : ?name:string -> string -> unit t = fun ?name k ->
if k = "" then invalid_arg "Lex.grapheme: empty string";
{ n = default ("GRAPHEME("^k^")") name
; c = Charset.singleton k.[0]
; a = Grapheme k
; f = fun s n ->
let (k',s,n) = (any_grapheme ()).f s n in
if k = k' then ((),s,n) else raise NoParse }
let test : ?name:string -> (char -> bool) -> char t = fun ?name f ->
let cs = charset_from_test f in
{ n = default (Charset.show cs) name
; c = charset_from_test f
; a = Test f
; f = fun s n ->
let (c,s,n) = Input.read s n in
if f c then (c, s, n)
else raise NoParse
}
let charset : ?name:string -> Charset.t -> char t = fun ?name cs ->
test ?name (Charset.mem cs)
* Reject the input ( raises [ ] ) if the first character of the input
passed the test . Does not read the character if the test fails .
passed the test. Does not read the character if the test fails. *)
let not_test : ?name:string -> (char -> bool) -> unit t =
fun ?name f ->
let cs = charset_from_test f in
{ n = default (sp "^%s" (Charset.show cs)) name
; c = Charset.complement cs
; a = NotTest f
; f = fun s n ->
let (c,_,_) = Input.read s n in
if (f c) then raise NoParse else ((), s, n)
}
* Reject the input ( raises [ ] ) if the first character of the input
is in the charset . Does not read the character if not in the charset .
is in the charset. Does not read the character if not in the charset. *)
let not_charset : ?name:string -> Charset.t -> unit t =
fun ?name cs -> not_test ?name (Charset.mem cs)
* Compose two terminals in sequence
let seq : ?name:string -> 'a t -> 'b t -> ('a -> 'b -> 'c) -> 'c t =
fun ?name t1 t2 f ->
{ n = default (sp "%s%s" t1.n t2.n) name
; c = if accept_empty t1 then Charset.union t1.c t2.c else t1.c
; a = Seq(t1, t2, f, Assoc.new_key ())
; f = fun s n ->
let (s1,s,n) = t1.f s n in
let (s2,s,n) = t2.f s n in
(f s1 s2,s,n)
}
let seq1 ?name t1 t2 = seq ?name t1 t2 (fun x _ -> x)
let seq2 ?name t1 t2 = seq ?name t1 t2 (fun _ x -> x)
let seqs : 'a t list -> ('a -> 'a -> 'a) -> 'a t = fun l f ->
let rec fn = function
| [] -> invalid_arg "alts: empty list"
| [r] -> r
| r::l -> seq r (fn l) f
in fn l
let alt : ?name:string -> 'a t -> 'a t -> 'a t =
fun ?name t1 t2 ->
{ n = default (sp "(%s)|(%s)" t1.n t2.n) name
; c = Charset.union t1.c t2.c
; a = Alt(t1, t2)
; f = fun s n ->
try
let (_,s1,n1 as r1) = t1.f s n in
try
let (_,s2,n2 as r2) = t2.f s n in
let l1 = Input.byte_pos s1 n1 in
let l2 = Input.byte_pos s2 n2 in
if l2 > l1 then r2 else r1
with NoParse -> r1
with NoParse -> t2.f s n
}
let rec alts : 'a t list -> 'a t = function
| [] -> invalid_arg "alts: empty list"
| [r] -> r
| r::l -> alt r (alts l)
let save : ?name:string -> 'a t -> (string -> 'a -> 'b) -> 'b t =
fun ?name t1 f ->
{ n = default t1.n name
; c = t1.c
; a = Save(t1,f, Assoc.new_key ())
; f = fun s n ->
let (l,s1,n1) = t1.f s n in
let len =
Input.int_of_byte_pos (Input.byte_pos s1 n1)
- Input.int_of_byte_pos (Input.byte_pos s n) in
let str = Input.sub s n len in
(f str l, s1, n1) }
* Parses the given terminal 0 or 1 time .
let option : ?name:string -> 'a -> 'a t -> 'a t =
fun ?name d t ->
{ n = default (sp "(%s)?" t.n) name
; c = Charset.full
; a = Option(d,t)
; f = fun s n ->
try let (x,s,n) = t.f s n in (x,s,n)
with NoParse -> (d,s,n) }
let appl : ?name: string -> ('a -> 'b) -> 'a t -> 'b t =
fun ?name f t ->
{ n = default t.n name
; c = t.c
; a = Appl(t, f, Assoc.new_key ())
; f = fun s n -> let (x,s,n) = t.f s n in (f x,s,n) }
* [ star t a f ] Repetition of a given terminal 0,1 or more times .
let star : ?name:string -> 'a t -> (unit -> 'b) -> ('b -> 'a -> 'b) -> 'b t =
fun ?name t a f ->
{ n = default (sp "(%s)*" t.n) name
; c = t.c
; a = Star(t,a,f, Assoc.new_key ())
; f = fun s n ->
let rec fn a s n =
(try
let (x,s',n') = t.f s n in
if Input.buffer_equal s s' && n = n' then
fun () -> (a,s,n)
else
fun () -> fn (f a x) s' n'
with NoParse ->
fun () -> (a,s,n)) ()
in
fn (a ()) s n }
let plus : ?name:string -> 'a t -> (unit -> 'b) -> ('b -> 'a -> 'b) -> 'b t =
fun ?name t a f ->
{ n = default (sp "(%s)*" t.n) name
; c = t.c
; a = Plus(t,a,f, Assoc.new_key ())
; f = fun s n ->
let rec fn a s n =
(try
let (x,s',n') = t.f s n in
if Input.buffer_equal s s' && n = n' then
fun () -> (a,s,n)
else
fun () -> fn (f a x) s' n'
with NoParse ->
fun () -> (a,s,n)) ()
in
let (x,s,n) = t.f s n in
fn (f (a ()) x) s n }
* Parses natura in base 10 . [ " +42 " ] is not accepted .
let nat : ?name:string -> unit -> int t = fun ?name () ->
{ n = default "NAT" name
; c = Charset.from_string "-+0-9"
; a = Nat
; f = fun s n ->
let r = ref 0 in
let (c,s,n) = Input.read s n in
if not (c >= '0' && c <= '9') then raise NoParse;
r := !r * 10 + (Char.code c - Char.code '0');
let rec fn s0 n0 =
let (c,s,n) = Input.read s0 n0 in
if (c >= '0' && c <= '9') then (
r := !r * 10 + (Char.code c - Char.code '0');
fn s n)
else (s0,n0)
in
let (s,n) = fn s n in
(!r,s,n) }
* Parses an integer in base 10 . [ " +42 " ] is accepted .
let int : ?name:string -> unit -> int t = fun ?name () ->
{ n = default "INT" name
; c = Charset.from_string "-+0-9"
; a = Int
; f = fun s n ->
let r = ref 0 in
let f = ref (fun x -> x) in
let (c,s,n) =
let (c,s,n as r) = Input.read s n in
if c = '+' then Input.read s n
else if c = '-' then
(f := (fun x -> -x); Input.read s n)
else r
in
if not (c >= '0' && c <= '9') then raise NoParse;
r := !r * 10 + (Char.code c - Char.code '0');
let rec fn s0 n0 =
let (c,s,n) = Input.read s0 n0 in
if (c >= '0' && c <= '9') then (
r := !r * 10 + (Char.code c - Char.code '0');
fn s n)
else (s0,n0)
in
let (s,n) = fn s n in
(!f !r,s,n) }
* Parses a float in base 10 . [ " .1 " ] is as [ " 0.1 " ] .
let float : ?name:string -> unit -> float t = fun ?name () ->
{ n = default "FLOAT" name
; c = Charset.from_string "-+0-9."
; a = Float
; f = fun s0 n0 ->
let sg = ref 1.0 in
let ve = ref 0.0 in
let found_digit = ref false in
let m = ref 0.0 in
let digit c = float (Char.code c - Char.code '0')
in
let rec fn s0 n0 =
let (c,s,n) = Input.read s0 n0 in
if (c >= '0' && c <= '9') then (
found_digit := true;
m := !m *. 10.0 +. digit c;
fn s n)
else (c,s,n,s0,n0)
in
let rec fne s0 n0 =
let (c,s,n) = Input.read s0 n0 in
if (c >= '0' && c <= '9') then (
found_digit := true;
m := !m *. 10.0 +. digit c;
ve := !ve +. 1.0;
fne s n)
else (c,s,n,s0,n0)
in
let (c,s,n,s0,n0) =
let (c,s,n) = Input.read s0 n0 in
if c = '+' then fn s n
else if c = '-' then (sg := -1.0; fn s n)
else if (c >= '0' && c <= '9') then (
found_digit := true;
m := digit c;
fn s n)
else (c,s,n,s0,n0)
in
let (c,s,n,s0,n0) =
if c <> '.' then (c,s,n,s0,n0) else
fne s n
in
if not !found_digit then raise NoParse;
let sge = ref 1.0 in
let e = ref 0.0 in
let rec hn s0 n0 =
let (c,s,n) = Input.read s0 n0 in
if (c >= '0' && c <= '9') then (
found_digit := true;
e := !e *. 10.0 +. digit c;
hn s n)
else (s0,n0)
in
let (s0,n0) =
if c <> 'E' && c <> 'e' then (s0,n0) else
begin
let (c,s,n) =
let (c,s,n as r) = Input.read s n in
if c = '+' then
Input.read s n
else if c = '-' then
(sge := -1.0; Input.read s n)
else r
in
if not (c >= '0' && c <= '9') then raise NoParse;
e := digit c;
hn s n
end
in
(!sg *. !m *. (10.0 ** (-. !ve)) *. (10.0 ** (!sge *. !e)), s0, n0) }
exception Escaped
let escaped = fun c s n ->
if c = '\\' then
let (c,s,n) = Input.read s n in
match c with
| '\\' -> ('\\', s, n)
| '\'' -> ('\'', s, n)
| '\"' -> ('"', s, n)
| 'n' -> ('\n', s, n)
| 'r' -> ('\r', s, n)
| 't' -> ('\t', s, n)
| 'b' -> ('\b', s, n)
| '0'..'2' ->
let (c1,s,n) = Input.read s n in
let (c2,s,n) = Input.read s n in
if (c1 >= '0' && c1 <= '9' && c2 >= '0' && c2 <= '9') then
begin
let c = ( (Char.code c - Char.code '0') * 100
+ (Char.code c1 - Char.code '0') * 10
+ (Char.code c2 - Char.code '0'))
in
if c < 256 then (Char.chr c, s, n) else
raise NoParse
end
else raise NoParse
| 'o' ->
let (c1,s,n) = Input.read s n in
let (c2,s,n) = Input.read s n in
let (c3,s,n) = Input.read s n in
if (c1 >= '0' && c1 <= '3' && c2 >= '0' && c2 <= '7'
&& c3 >= '0' && c3 <= '7') then
let c = ( (Char.code c1 - Char.code '0') * 64
+ (Char.code c2 - Char.code '0') * 8
+ (Char.code c3 - Char.code '0'))
in
(Char.chr c, s, n)
else raise NoParse
| 'x' ->
let (c1,s,n) = Input.read s n in
let (c2,s,n) = Input.read s n in
let x1 = match c1 with
| '0'..'9' -> Char.code c1 - Char.code '0'
| 'a'..'f' -> Char.code c1 - Char.code 'a' + 10
| 'A'..'F' -> Char.code c1 - Char.code 'A' + 10
| _ -> raise NoParse
in
let x2 = match c2 with
| '0'..'9' -> Char.code c2 - Char.code '0'
| 'a'..'f' -> Char.code c2 - Char.code 'a' + 10
| 'A'..'F' -> Char.code c2 - Char.code 'A' + 10
| _ -> raise NoParse
in
(Char.chr (x1 * 16 + x2), s, n)
| _ -> raise NoParse
else raise Escaped
let char_lit : ?name:string -> unit -> char t = fun ?name () ->
{ n = default "CHARLIT" name
; c = Charset.singleton '\''
; a = CharLit
; f = fun s n ->
let (c,s,n) = Input.read s n in
if c <> '\'' then raise NoParse;
let (c,s,n as r) = Input.read s n in
if c = '\'' || c = '\255' then raise NoParse;
let (cr,s,n) = try escaped c s n with Escaped -> r in
let (c,s,n) = Input.read s n in
if c <> '\'' then raise NoParse;
(cr,s,n)
}
let rec skip_newline c s0 n0 =
let rec fn s0 n0 =
let (c,s,n) = Input.read s0 n0 in
if c = ' ' || c = '\t' then fn s n
else skip_newline c s n
in
if c = '\\' then
let (c1,s,n) = Input.read s0 n0 in
if c1 = '\n' then fn s n else (c,s0, n0)
else (c,s0,n0)
let string_lit : ?name:string -> unit -> string t = fun ?name () ->
{ n = default "STRINTLIT" name
; c = Charset.singleton '"'
; a = StringLit
; f = fun s n ->
let (c,s,n) = Input.read s n in
if c <> '"' then raise NoParse;
let b = Buffer.create 64 in
let rec fn s n =
let (c,s,n) = Input.read s n in
let (c,s,n as r) = skip_newline c s n in
if c = '"' then (s,n)
else if c = '\255' then raise NoParse
else
begin
let (cr,s,n) = try escaped c s n with Escaped -> r in
Buffer.add_char b cr;
fn s n
end
in
let (s,n) = fn s n in
(Buffer.contents b,s,n)
}
|
23f6bf34688d72d60f1adafa1e1b4e120567bd6bcf98adada749dac93e81c753
|
Tim-ats-d/Suricate
|
handler.mli
|
(** Handler are used to make the link with logger. *)
(** {1 Handlers} *)
* { 2 Handler module type }
(** API used to describle a handler. *)
module type HANDLER = sig
(** The formatter used by handler to log message. *)
val formatter : Formatter.t
(** The function which called by [Logger] when it log *)
val emit : string -> unit
end
(** Full API used to describe a handler with its own log level. *)
module type LEVELED_HANDLER = sig
include HANDLER
(** The handler's log level *)
val level : Log_level.t
end
* { 2 API }
* [ Handler.create level ~formatter ~emit ] produces a fresh [ LEVELED_HANDLER ] .
It is a shorcut to facilitate custom handler construction .
It is a shorcut to facilitate custom handler construction.*)
val create :
Log_level.t ->
formatter:Formatter.t ->
emit:(string -> unit) ->
(module LEVELED_HANDLER)
* [ Handler.make level ( module H ) ] produces a [ LEVELED_HANDLER ] .
It is a shorcut to facilitate custom handler construction .
It is a shorcut to facilitate custom handler construction. *)
val make : Log_level.t -> (module HANDLER) -> (module LEVELED_HANDLER)
| null |
https://raw.githubusercontent.com/Tim-ats-d/Suricate/bef2bbc8f3cd4420213e6263e3e15a0fe90edb29/lib/handler.mli
|
ocaml
|
* Handler are used to make the link with logger.
* {1 Handlers}
* API used to describle a handler.
* The formatter used by handler to log message.
* The function which called by [Logger] when it log
* Full API used to describe a handler with its own log level.
* The handler's log level
|
* { 2 Handler module type }
module type HANDLER = sig
val formatter : Formatter.t
val emit : string -> unit
end
module type LEVELED_HANDLER = sig
include HANDLER
val level : Log_level.t
end
* { 2 API }
* [ Handler.create level ~formatter ~emit ] produces a fresh [ LEVELED_HANDLER ] .
It is a shorcut to facilitate custom handler construction .
It is a shorcut to facilitate custom handler construction.*)
val create :
Log_level.t ->
formatter:Formatter.t ->
emit:(string -> unit) ->
(module LEVELED_HANDLER)
* [ Handler.make level ( module H ) ] produces a [ LEVELED_HANDLER ] .
It is a shorcut to facilitate custom handler construction .
It is a shorcut to facilitate custom handler construction. *)
val make : Log_level.t -> (module HANDLER) -> (module LEVELED_HANDLER)
|
5e9132adb1511ffbd199506fc1e8d6c0572ceaf86db77c9fc7692699c4569d4c
|
flotsfacetieux/sorcery-es
|
sorcery.lisp
|
(in-package :sorcery-es)
(load-stencils)
(defun canvas-x ()
(setf *canvas-x*
(aref (sdl:video-dimensions) 0)))
(defun canvas-middle-x ()
(setf *canvas-middle-x*
(/ *canvas-x* 2)))
(defun canvas-origin-x ()
(setf *origin-x*
(/ (- *canvas-x* *area-width*) 2)))
(defun load-graphics ()
(setf *bg-sheet*
(make-sprites-sheet *bg-pathname*
800
600))
(setf *sprites-sheet*
(make-sprites-sheet *sprites-pathname*
(sprite-width)
(sprite-height)))
(setf *areas-sheet*
(make-sprites-sheet *areas-pathname*
(area-width)
(area-height))))
(let (areas)
(defun areas-id ()
(when (not areas)
(setf areas
(loop for k being the hash-keys in *entities*
collect k)))
areas))
(defun next-area-id (area-id)
(let ((areas-ids (areas-id)))
(when-let ((position (position area-id areas-ids)))
(if (= position (1- (length areas-ids)))
(car areas-ids)
(nth (1+ position) areas-ids)))))
(defun previous-area-id (area-id)
(let ((areas-ids (areas-id)))
(when-let ((position (position area-id areas-ids)))
(if (= position 0)
(last areas-ids)
(nth (1- position) areas-ids)))))
(defun area-entities (area-id)
(gethash area-id *entities*))
(defun update-swank ()
(let ((connection (or swank::*emacs-connection*
(swank::default-connection))))
(when connection
(swank::handle-requests connection t))))
(defun start ()
(sdl:with-init ()
(sdl:window 800
600
:title-caption "Sorcery"
:bpp 32 :any-format t :double-buffer t
:fps (make-instance 'sdl:fps-timestep)
;; (make-instance 'sdl:fps-fixed)
)
(setf *entities* (make-hash-table))
(load-graphics)
(canvas-x)
(canvas-origin-x)
(canvas-middle-x)
(sdl:initialise-default-font sdl:*font-10x20*)
(setf (sdl:frame-rate) 60)
(setf (game-render-system) (make-instance 'render-system))
(setf (game-costume-system) (make-instance 'costume-system))
(setf (dict-state :summary) (summary-state))
(setf (dict-state :game) (game-state))
(setf (dict-state :intro) (intro-state))
(init-intro (dict-state :intro))
(sdl:update-display)
(sdl:enable-key-repeat 500 20)
(sdl:with-events ()
(:quit-event () t)
(:key-down-event (:key key)
(key-event *current-state* :down key))
(:key-up-event (:key key)
(key-event *current-state* :up key))
(:idle ()
(sdl:clear-display sdl:*black*)
(run-state *current-state*)
(update-swank)
(sdl:update-display)))))
| null |
https://raw.githubusercontent.com/flotsfacetieux/sorcery-es/9780a31fa2b61451d294cc23775b30098fcd3b4d/sorcery.lisp
|
lisp
|
(make-instance 'sdl:fps-fixed)
|
(in-package :sorcery-es)
(load-stencils)
(defun canvas-x ()
(setf *canvas-x*
(aref (sdl:video-dimensions) 0)))
(defun canvas-middle-x ()
(setf *canvas-middle-x*
(/ *canvas-x* 2)))
(defun canvas-origin-x ()
(setf *origin-x*
(/ (- *canvas-x* *area-width*) 2)))
(defun load-graphics ()
(setf *bg-sheet*
(make-sprites-sheet *bg-pathname*
800
600))
(setf *sprites-sheet*
(make-sprites-sheet *sprites-pathname*
(sprite-width)
(sprite-height)))
(setf *areas-sheet*
(make-sprites-sheet *areas-pathname*
(area-width)
(area-height))))
(let (areas)
(defun areas-id ()
(when (not areas)
(setf areas
(loop for k being the hash-keys in *entities*
collect k)))
areas))
(defun next-area-id (area-id)
(let ((areas-ids (areas-id)))
(when-let ((position (position area-id areas-ids)))
(if (= position (1- (length areas-ids)))
(car areas-ids)
(nth (1+ position) areas-ids)))))
(defun previous-area-id (area-id)
(let ((areas-ids (areas-id)))
(when-let ((position (position area-id areas-ids)))
(if (= position 0)
(last areas-ids)
(nth (1- position) areas-ids)))))
(defun area-entities (area-id)
(gethash area-id *entities*))
(defun update-swank ()
(let ((connection (or swank::*emacs-connection*
(swank::default-connection))))
(when connection
(swank::handle-requests connection t))))
(defun start ()
(sdl:with-init ()
(sdl:window 800
600
:title-caption "Sorcery"
:bpp 32 :any-format t :double-buffer t
:fps (make-instance 'sdl:fps-timestep)
)
(setf *entities* (make-hash-table))
(load-graphics)
(canvas-x)
(canvas-origin-x)
(canvas-middle-x)
(sdl:initialise-default-font sdl:*font-10x20*)
(setf (sdl:frame-rate) 60)
(setf (game-render-system) (make-instance 'render-system))
(setf (game-costume-system) (make-instance 'costume-system))
(setf (dict-state :summary) (summary-state))
(setf (dict-state :game) (game-state))
(setf (dict-state :intro) (intro-state))
(init-intro (dict-state :intro))
(sdl:update-display)
(sdl:enable-key-repeat 500 20)
(sdl:with-events ()
(:quit-event () t)
(:key-down-event (:key key)
(key-event *current-state* :down key))
(:key-up-event (:key key)
(key-event *current-state* :up key))
(:idle ()
(sdl:clear-display sdl:*black*)
(run-state *current-state*)
(update-swank)
(sdl:update-display)))))
|
330233c21e671c3c7417cd999d3d03ae59c6a87066db06d2510d11b25653465c
|
BrunoBonacci/mulog
|
your_ns.clj
|
(ns your-ns
(:require [com.brunobonacci.mulog :as μ]))
(comment
(μ/log ::hello :to "New World!")
(μ/start-publisher! {:type :console})
(μ/log ::event-name, :key1 "value1", :key2 :value2, :keyN "valueN")
(μ/log ::system-started :version "0.1.0")
(μ/log ::user-logged :user-id "1234567" :remote-ip "1.2.3.4" :auth-method :password-login)
(μ/log ::http-request :path "/orders", :method :post, :remote-ip "1.2.3.4", :http-status 201)
(def x (RuntimeException. "Boom!"))
(μ/log ::invalid-request :exception x, :user-id "123456789", :items-requested 47)
(μ/log ::position-updated :poi "1234567" :location {:lat 51.4978128, :lng -0.1767122} )
(μ/log ::system-started :init-time 32)
(μ/set-global-context! {:app-name "mulog-demo", :version "0.1.0", :env "local"})
{ : / event - name : your - ns / system - started ,
: / timestamp 1587501375129 ,
: / trace - id # mulog / flake " 4VTCYUcCs5KRbiRibgulnns3l6ZW_yxk " ,
: / namespace " your - ns " ,
;; :app-name "mulog-demo",
;; :env "local",
: init - time 32 ,
: version " 0.1.0 " }
(μ/set-global-context! {})
(μ/with-context {:order "abc123"}
(μ/log ::process-item :item-id "sku-123" :qt 2))
{ : / event - name : your - ns / process - item ,
: / timestamp 1587501473472 ,
: / trace - id # mulog / flake " 4VTCdCz6T_TTM9bS5LCwqMG0FhvSybkN " ,
: / namespace " your - ns " ,
;; :app-name "mulog-demo",
;; :env "local",
;; :item-id "sku-123",
;; :order "abc123",
: qt 2 ,
: version " 0.1.0 " }
(μ/with-context {:transaction-id "tx-098765"}
(μ/with-context {:order "abc123"}
(μ/log ::process-item :item-id "sku-123" :qt 2)))
{ : / event - name : your - ns / process - item ,
: / timestamp 1587501492168 ,
: / trace - id # mulog / flake " 4VTCeIc_FNzCjegzQ0cMSLI09RqqC2FR " ,
: / namespace " your - ns " ,
;; :app-name "mulog-demo",
;; :env "local",
;; :item-id "sku-123",
;; :order "abc123",
: qt 2 ,
;; :transaction-id "tx-098765",
: version " 0.1.0 " }
(defn process-item [sku quantity]
;; ... do something
(μ/log ::item-processed :item-id "sku-123" :qt quantity)
;; ... do something
)
(μ/with-context {:order "abc123"}
(process-item "sku-123" 2))
{ : / event - name : your - ns / item - processed ,
: / timestamp 1587501555926 ,
: / trace - id # mulog / flake " 4VTCi08XrCWQLrR8vS2nP8sG1zDTGuY _ " ,
: / namespace " your - ns " ,
;; :app-name "mulog-demo",
;; :env "local",
;; :item-id "sku-123",
;; :order "abc123",
: qt 2 ,
: version " 0.1.0 " }
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ----==| Μ / T R A C E |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(comment
(defn product-availability [product-id]
(http/get availability-service {:product-id product-id}))
(defn product-availability [product-id]
(Thread/sleep (rand-int 500)))
(μ/trace ::availability
[]
(product-availability product-id))
{ : / event - name : your - ns / availability ,
: / timestamp 1587504242983 ,
: / trace - id # mulog / flake " 4VTF9QBbnef57vxVy - b4uKzh7dG7r7y4 " ,
: / root - trace # mulog / flake " 4VTF9QBbnef57vxVy - b4uKzh7dG7r7y4 " ,
: / duration 254402837 ,
: / namespace " your - ns " ,
: / outcome : ok ,
;; :app-name "mulog-demo",
;; :env "local",
: version " 0.1.0 " }
(def product-id "2345-23-545")
(def order-id "34896-34556")
(def user-id "709-6567567")
(μ/with-context {:order order-id, :user user-id}
(μ/trace ::availability
[:product-id product-id]
(product-availability product-id)))
{ : / event - name : your - ns / availability ,
: / timestamp 1587506497789 ,
: / trace - id # mulog / flake " 4VTHCez0rr3TpaBmUQrTb2DZaYmaWFkH " ,
: / root - trace # mulog / flake " 4VTHCez0rr3TpaBmUQrTb2DZaYmaWFkH " ,
: / duration 280510026 ,
: / namespace " your - ns " ,
: / outcome : ok ,
;; :app-name "mulog-demo",
;; :env "local",
: order " 34896 - 34556 " ,
: product - id " 2345 - 23 - 545 " ,
: user " 709 - 6567567 " ,
: version " 0.1.0 " }
)
;;
;; Nested trace example
;;
(comment
(defn warehouse-availability [product-id]
(Thread/sleep (rand-int 100))
(rand-int 100))
(defn shopping-carts [product-id mode]
(Thread/sleep (rand-int 100))
(rand-int 10))
(defn availability-estimator [warehouse in-flight-carts]
(Thread/sleep (rand-int 100))
(- warehouse in-flight-carts))
(defn product-availability [product-id]
(let [warehouse
(μ/trace ::warehouse-availability
[:product-id product-id :app-name "warehouse"]
(warehouse-availability product-id))
in-flight-carts
(μ/trace ::shopping-carts
[:product-id product-id :app-name "carts"]
(shopping-carts product-id :in-flight))
estimated
(μ/trace ::availability-estimator
[:product-id product-id :app-name "stock-mgmt"]
(availability-estimator warehouse in-flight-carts))]
{:availability estimated}))
(defn process-order [order-id items]
(Thread/sleep (rand-int 100))
{:order order-id
:items (mapv
(fn [product-id]
(μ/trace ::availability
[:product-id product-id :app-name "stock-mgmt"]
(product-availability product-id))) items)})
(def items ["2345-23-545" "6543-43-0032"])
(def order-id "34896-34556")
(def user-id "709-6567567")
(μ/with-context {:user user-id :order-id order-id}
(μ/trace ::process-order
[:order-type :premium :app-name "order-api"]
(process-order order-id items)))
)
(comment
(def stop-all
(μ/start-publisher!
{:type :multi
:publishers
[{:type :console}
{:type :simple-file :filename "/tmp/disk1/mulog/events1.log"}
{:type :simple-file :filename "/tmp/disk2/mulog/events2.log"}]}))
(μ/log ::hello :to "New World!")
(stop-all)
)
(comment
(require
'[com.brunobonacci.mulog.buffer :as rb]
'[clojure.pprint :refer [pprint]])
(deftype MyCustomPublisher [config buffer]
com.brunobonacci.mulog.publisher.PPublisher
(agent-buffer [_]
buffer)
(publish-delay [_]
500)
(publish [_ buffer]
;; check our printer option
(let [printer (if (:pretty-print config) pprint prn)]
;; items are pairs [offset <item>]
(doseq [item (map second (rb/items buffer))]
;; print the item
(printer item)))
;; return the buffer minus the published elements
(rb/clear buffer)))
(defn my-custom-publisher
[config]
(MyCustomPublisher. config (rb/agent-buffer 10000)))
(def st
(μ/start-publisher!
{:type :inline :publisher (my-custom-publisher {:pretty-print true})}))
(μ/log :test-event)
(defn- pprint-str
[v]
(with-out-str
(pprint v)))
(deftype MyCustomPublisher [config buffer ^java.io.Writer filewriter]
com.brunobonacci.mulog.publisher.PPublisher
(agent-buffer [_]
buffer)
(publish-delay [_]
500)
(publish [_ buffer]
;; check our printer option
(let [printer (if (:pretty-print config) pprint-str prn-str)
;; take at most `:max-items` items
items (take (:max-items config) (rb/items buffer))
;; save the offset of the last items
last-offset (-> items last first)]
;; write the items to the file
(doseq [item (map second items)]
;; print the item
(.write filewriter (printer item)))
;; flush the buffer
(.flush filewriter)
;; return the buffer minus the published elements
(rb/dequeue buffer last-offset))))
(defn my-custom-publisher
[{:keys [filename] :as config}]
(let [config (merge {:pretty-print false :max-items 1000} config)]
(MyCustomPublisher. config (rb/agent-buffer 10000)
(io/writer (io/file filename) :append true))))
)
| null |
https://raw.githubusercontent.com/BrunoBonacci/mulog/e31f84ccf6d62d43c1c620ef5584722886e0d8a5/mulog-core/dev/your_ns.clj
|
clojure
|
:app-name "mulog-demo",
:env "local",
:app-name "mulog-demo",
:env "local",
:item-id "sku-123",
:order "abc123",
:app-name "mulog-demo",
:env "local",
:item-id "sku-123",
:order "abc123",
:transaction-id "tx-098765",
... do something
... do something
:app-name "mulog-demo",
:env "local",
:item-id "sku-123",
:order "abc123",
;;
----==| Μ / T R A C E |==---- ;;
;;
:app-name "mulog-demo",
:env "local",
:app-name "mulog-demo",
:env "local",
Nested trace example
check our printer option
items are pairs [offset <item>]
print the item
return the buffer minus the published elements
check our printer option
take at most `:max-items` items
save the offset of the last items
write the items to the file
print the item
flush the buffer
return the buffer minus the published elements
|
(ns your-ns
(:require [com.brunobonacci.mulog :as μ]))
(comment
(μ/log ::hello :to "New World!")
(μ/start-publisher! {:type :console})
(μ/log ::event-name, :key1 "value1", :key2 :value2, :keyN "valueN")
(μ/log ::system-started :version "0.1.0")
(μ/log ::user-logged :user-id "1234567" :remote-ip "1.2.3.4" :auth-method :password-login)
(μ/log ::http-request :path "/orders", :method :post, :remote-ip "1.2.3.4", :http-status 201)
(def x (RuntimeException. "Boom!"))
(μ/log ::invalid-request :exception x, :user-id "123456789", :items-requested 47)
(μ/log ::position-updated :poi "1234567" :location {:lat 51.4978128, :lng -0.1767122} )
(μ/log ::system-started :init-time 32)
(μ/set-global-context! {:app-name "mulog-demo", :version "0.1.0", :env "local"})
{ : / event - name : your - ns / system - started ,
: / timestamp 1587501375129 ,
: / trace - id # mulog / flake " 4VTCYUcCs5KRbiRibgulnns3l6ZW_yxk " ,
: / namespace " your - ns " ,
: init - time 32 ,
: version " 0.1.0 " }
(μ/set-global-context! {})
(μ/with-context {:order "abc123"}
(μ/log ::process-item :item-id "sku-123" :qt 2))
{ : / event - name : your - ns / process - item ,
: / timestamp 1587501473472 ,
: / trace - id # mulog / flake " 4VTCdCz6T_TTM9bS5LCwqMG0FhvSybkN " ,
: / namespace " your - ns " ,
: qt 2 ,
: version " 0.1.0 " }
(μ/with-context {:transaction-id "tx-098765"}
(μ/with-context {:order "abc123"}
(μ/log ::process-item :item-id "sku-123" :qt 2)))
{ : / event - name : your - ns / process - item ,
: / timestamp 1587501492168 ,
: / trace - id # mulog / flake " 4VTCeIc_FNzCjegzQ0cMSLI09RqqC2FR " ,
: / namespace " your - ns " ,
: qt 2 ,
: version " 0.1.0 " }
(defn process-item [sku quantity]
(μ/log ::item-processed :item-id "sku-123" :qt quantity)
)
(μ/with-context {:order "abc123"}
(process-item "sku-123" 2))
{ : / event - name : your - ns / item - processed ,
: / timestamp 1587501555926 ,
: / trace - id # mulog / flake " 4VTCi08XrCWQLrR8vS2nP8sG1zDTGuY _ " ,
: / namespace " your - ns " ,
: qt 2 ,
: version " 0.1.0 " }
)
(comment
(defn product-availability [product-id]
(http/get availability-service {:product-id product-id}))
(defn product-availability [product-id]
(Thread/sleep (rand-int 500)))
(μ/trace ::availability
[]
(product-availability product-id))
{ : / event - name : your - ns / availability ,
: / timestamp 1587504242983 ,
: / trace - id # mulog / flake " 4VTF9QBbnef57vxVy - b4uKzh7dG7r7y4 " ,
: / root - trace # mulog / flake " 4VTF9QBbnef57vxVy - b4uKzh7dG7r7y4 " ,
: / duration 254402837 ,
: / namespace " your - ns " ,
: / outcome : ok ,
: version " 0.1.0 " }
(def product-id "2345-23-545")
(def order-id "34896-34556")
(def user-id "709-6567567")
(μ/with-context {:order order-id, :user user-id}
(μ/trace ::availability
[:product-id product-id]
(product-availability product-id)))
{ : / event - name : your - ns / availability ,
: / timestamp 1587506497789 ,
: / trace - id # mulog / flake " 4VTHCez0rr3TpaBmUQrTb2DZaYmaWFkH " ,
: / root - trace # mulog / flake " 4VTHCez0rr3TpaBmUQrTb2DZaYmaWFkH " ,
: / duration 280510026 ,
: / namespace " your - ns " ,
: / outcome : ok ,
: order " 34896 - 34556 " ,
: product - id " 2345 - 23 - 545 " ,
: user " 709 - 6567567 " ,
: version " 0.1.0 " }
)
(comment
(defn warehouse-availability [product-id]
(Thread/sleep (rand-int 100))
(rand-int 100))
(defn shopping-carts [product-id mode]
(Thread/sleep (rand-int 100))
(rand-int 10))
(defn availability-estimator [warehouse in-flight-carts]
(Thread/sleep (rand-int 100))
(- warehouse in-flight-carts))
(defn product-availability [product-id]
(let [warehouse
(μ/trace ::warehouse-availability
[:product-id product-id :app-name "warehouse"]
(warehouse-availability product-id))
in-flight-carts
(μ/trace ::shopping-carts
[:product-id product-id :app-name "carts"]
(shopping-carts product-id :in-flight))
estimated
(μ/trace ::availability-estimator
[:product-id product-id :app-name "stock-mgmt"]
(availability-estimator warehouse in-flight-carts))]
{:availability estimated}))
(defn process-order [order-id items]
(Thread/sleep (rand-int 100))
{:order order-id
:items (mapv
(fn [product-id]
(μ/trace ::availability
[:product-id product-id :app-name "stock-mgmt"]
(product-availability product-id))) items)})
(def items ["2345-23-545" "6543-43-0032"])
(def order-id "34896-34556")
(def user-id "709-6567567")
(μ/with-context {:user user-id :order-id order-id}
(μ/trace ::process-order
[:order-type :premium :app-name "order-api"]
(process-order order-id items)))
)
(comment
(def stop-all
(μ/start-publisher!
{:type :multi
:publishers
[{:type :console}
{:type :simple-file :filename "/tmp/disk1/mulog/events1.log"}
{:type :simple-file :filename "/tmp/disk2/mulog/events2.log"}]}))
(μ/log ::hello :to "New World!")
(stop-all)
)
(comment
(require
'[com.brunobonacci.mulog.buffer :as rb]
'[clojure.pprint :refer [pprint]])
(deftype MyCustomPublisher [config buffer]
com.brunobonacci.mulog.publisher.PPublisher
(agent-buffer [_]
buffer)
(publish-delay [_]
500)
(publish [_ buffer]
(let [printer (if (:pretty-print config) pprint prn)]
(doseq [item (map second (rb/items buffer))]
(printer item)))
(rb/clear buffer)))
(defn my-custom-publisher
[config]
(MyCustomPublisher. config (rb/agent-buffer 10000)))
(def st
(μ/start-publisher!
{:type :inline :publisher (my-custom-publisher {:pretty-print true})}))
(μ/log :test-event)
(defn- pprint-str
[v]
(with-out-str
(pprint v)))
(deftype MyCustomPublisher [config buffer ^java.io.Writer filewriter]
com.brunobonacci.mulog.publisher.PPublisher
(agent-buffer [_]
buffer)
(publish-delay [_]
500)
(publish [_ buffer]
(let [printer (if (:pretty-print config) pprint-str prn-str)
items (take (:max-items config) (rb/items buffer))
last-offset (-> items last first)]
(doseq [item (map second items)]
(.write filewriter (printer item)))
(.flush filewriter)
(rb/dequeue buffer last-offset))))
(defn my-custom-publisher
[{:keys [filename] :as config}]
(let [config (merge {:pretty-print false :max-items 1000} config)]
(MyCustomPublisher. config (rb/agent-buffer 10000)
(io/writer (io/file filename) :append true))))
)
|
898aa945968c861c360b035757943e355c53420381362ec23c70f15918b913dc
|
Rober-t/apxr_run
|
experiment_mgr_sup.erl
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright ( C ) 2018 ApproximateReality
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%----------------------------------------------------------------------------
@doc ExperimentMgr top supervisor .
%%% @end
%%%----------------------------------------------------------------------------
-module(experiment_mgr_sup).
-behaviour(supervisor).
Start / Stop
-export([
start_link/0
]).
%% Supervisor callbacks
-export([
init/1
]).
Xref
-ignore_xref([
start_link/0
]).
%%%============================================================================
%%% Types
%%%============================================================================
-type sup_flags() :: #{
intensity => non_neg_integer(),
period => pos_integer(),
strategy => one_for_all | one_for_one | rest_for_one | simple_one_for_one
}.
-type child_spec() :: [#{
id := _,
start := {atom(), atom(), undefined | [any()]},
modules => dynamic | [atom()],
restart => permanent | temporary | transient,
shutdown => brutal_kill | infinity | non_neg_integer(),
type => supervisor | worker
}].
-export_type([
sup_flags/0,
child_spec/0
]).
%%%============================================================================
%%% API
%%%============================================================================
%%-----------------------------------------------------------------------------
%% @doc Starts the supervisor.
%% @end
%%-----------------------------------------------------------------------------
-spec start_link() -> {ok, pid()}.
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
%%%============================================================================
%%% Supervisor callbacks
%%%============================================================================
%%-----------------------------------------------------------------------------
@private
@doc Whenever a supervisor is started using supervisor : start_link ,
%% this function is called by the new process to find out about restart
%% strategy, maximum restart frequency and child specifications. We also
%% make the supervisor the owner of the DB to improve fault tolerance.
%% @end
%%-----------------------------------------------------------------------------
-spec init([]) -> {ok, {sup_flags(), child_spec()}}.
init([]) ->
SupFlags = #{
strategy => one_for_one,
intensity => 4,
period => 20
},
ExperimentMgr = #{
id => experiment_mgr,
start => {experiment_mgr, start_link, []},
restart => permanent,
shutdown => 5000,
type => worker,
modules => [experiment_mgr]
},
ChildSpecs = [ExperimentMgr],
{ok, {SupFlags, ChildSpecs}}.
%%%============================================================================
Internal functions
%%%============================================================================
| null |
https://raw.githubusercontent.com/Rober-t/apxr_run/9c62ab028af7ff3768ffe3f27b8eef1799540f05/src/experiment_mgr/experiment_mgr_sup.erl
|
erlang
|
----------------------------------------------------------------------------
@end
----------------------------------------------------------------------------
Supervisor callbacks
============================================================================
Types
============================================================================
============================================================================
API
============================================================================
-----------------------------------------------------------------------------
@doc Starts the supervisor.
@end
-----------------------------------------------------------------------------
============================================================================
Supervisor callbacks
============================================================================
-----------------------------------------------------------------------------
this function is called by the new process to find out about restart
strategy, maximum restart frequency and child specifications. We also
make the supervisor the owner of the DB to improve fault tolerance.
@end
-----------------------------------------------------------------------------
============================================================================
============================================================================
|
Copyright ( C ) 2018 ApproximateReality
@doc ExperimentMgr top supervisor .
-module(experiment_mgr_sup).
-behaviour(supervisor).
Start / Stop
-export([
start_link/0
]).
-export([
init/1
]).
Xref
-ignore_xref([
start_link/0
]).
-type sup_flags() :: #{
intensity => non_neg_integer(),
period => pos_integer(),
strategy => one_for_all | one_for_one | rest_for_one | simple_one_for_one
}.
-type child_spec() :: [#{
id := _,
start := {atom(), atom(), undefined | [any()]},
modules => dynamic | [atom()],
restart => permanent | temporary | transient,
shutdown => brutal_kill | infinity | non_neg_integer(),
type => supervisor | worker
}].
-export_type([
sup_flags/0,
child_spec/0
]).
-spec start_link() -> {ok, pid()}.
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
@private
@doc Whenever a supervisor is started using supervisor : start_link ,
-spec init([]) -> {ok, {sup_flags(), child_spec()}}.
init([]) ->
SupFlags = #{
strategy => one_for_one,
intensity => 4,
period => 20
},
ExperimentMgr = #{
id => experiment_mgr,
start => {experiment_mgr, start_link, []},
restart => permanent,
shutdown => 5000,
type => worker,
modules => [experiment_mgr]
},
ChildSpecs = [ExperimentMgr],
{ok, {SupFlags, ChildSpecs}}.
Internal functions
|
d6ddd63e9303444c830ad5738e27aadd46e349aadb33cd8f1582ab29e203a724
|
austinhaas/goalie
|
stacktrace.clj
|
(ns pettomato.goalie.stacktrace
(:require
[pettomato.goalie.graph :refer (path)]))
;; I don't know the proper format for these fields; I just tried to
;; mimic what I saw in other stacktraces.
(defn stackelement [node]
(let [{:keys [name ns file line]} (meta (:gvar node))
decl-class (str (ns-name ns) "$" name)
method-name "invoke"]
(StackTraceElement. decl-class method-name file line)))
(defn stacktrace [node]
(into-array (map stackelement (path node))))
| null |
https://raw.githubusercontent.com/austinhaas/goalie/6166dd05c27f5abdf5c760687d6efc110846abf1/src/com/pettomato/goalie/stacktrace.clj
|
clojure
|
I don't know the proper format for these fields; I just tried to
mimic what I saw in other stacktraces.
|
(ns pettomato.goalie.stacktrace
(:require
[pettomato.goalie.graph :refer (path)]))
(defn stackelement [node]
(let [{:keys [name ns file line]} (meta (:gvar node))
decl-class (str (ns-name ns) "$" name)
method-name "invoke"]
(StackTraceElement. decl-class method-name file line)))
(defn stacktrace [node]
(into-array (map stackelement (path node))))
|
18ced3c1a80d8c502b514d932adfcf97cdfd021bb29b7ca72552d69671fffa8e
|
hjcapple/reading-sicp
|
exercise_3_37.scm
|
#lang racket
P205 - [ 练习 3.37 ]
(#%require "constraints.scm")
(define (c+ x y)
(let ((z (make-connector)))
(adder x y z)
z))
(define (c* x y)
(let ((z (make-connector)))
(multiplier x y z)
z))
(define (c/ x y)
(let ((z (make-connector)))
(multiplier z y x)
z))
(define (cv x)
(let ((z (make-connector)))
(constant x z)
z))
;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (celsius-fahrenheit-converter x)
(c+ (c* (c/ (cv 9) (cv 5))
x)
(cv 32)))
(define C (make-connector))
(define F (celsius-fahrenheit-converter C))
(probe "Celsius temp" C)
(probe "Fahrenheit temp" F)
(set-value! C 25 'user)
(forget-value! C 'user)
(set-value! F 212 'user)
| null |
https://raw.githubusercontent.com/hjcapple/reading-sicp/7051d55dde841c06cf9326dc865d33d656702ecc/chapter_3/exercise_3_37.scm
|
scheme
|
#lang racket
P205 - [ 练习 3.37 ]
(#%require "constraints.scm")
(define (c+ x y)
(let ((z (make-connector)))
(adder x y z)
z))
(define (c* x y)
(let ((z (make-connector)))
(multiplier x y z)
z))
(define (c/ x y)
(let ((z (make-connector)))
(multiplier z y x)
z))
(define (cv x)
(let ((z (make-connector)))
(constant x z)
z))
(define (celsius-fahrenheit-converter x)
(c+ (c* (c/ (cv 9) (cv 5))
x)
(cv 32)))
(define C (make-connector))
(define F (celsius-fahrenheit-converter C))
(probe "Celsius temp" C)
(probe "Fahrenheit temp" F)
(set-value! C 25 'user)
(forget-value! C 'user)
(set-value! F 212 'user)
|
|
edd4a40627d74b261e64a66bfac1969968fff0245d404e88fdd57b781628c203
|
mbj/stratosphere
|
AWSManagedRulesBotControlRuleSetProperty.hs
|
module Stratosphere.WAFv2.WebACL.AWSManagedRulesBotControlRuleSetProperty (
AWSManagedRulesBotControlRuleSetProperty(..),
mkAWSManagedRulesBotControlRuleSetProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data AWSManagedRulesBotControlRuleSetProperty
= AWSManagedRulesBotControlRuleSetProperty {inspectionLevel :: (Value Prelude.Text)}
mkAWSManagedRulesBotControlRuleSetProperty ::
Value Prelude.Text -> AWSManagedRulesBotControlRuleSetProperty
mkAWSManagedRulesBotControlRuleSetProperty inspectionLevel
= AWSManagedRulesBotControlRuleSetProperty
{inspectionLevel = inspectionLevel}
instance ToResourceProperties AWSManagedRulesBotControlRuleSetProperty where
toResourceProperties AWSManagedRulesBotControlRuleSetProperty {..}
= ResourceProperties
{awsType = "AWS::WAFv2::WebACL.AWSManagedRulesBotControlRuleSet",
supportsTags = Prelude.False,
properties = ["InspectionLevel" JSON..= inspectionLevel]}
instance JSON.ToJSON AWSManagedRulesBotControlRuleSetProperty where
toJSON AWSManagedRulesBotControlRuleSetProperty {..}
= JSON.object ["InspectionLevel" JSON..= inspectionLevel]
instance Property "InspectionLevel" AWSManagedRulesBotControlRuleSetProperty where
type PropertyType "InspectionLevel" AWSManagedRulesBotControlRuleSetProperty = Value Prelude.Text
set newValue AWSManagedRulesBotControlRuleSetProperty {}
= AWSManagedRulesBotControlRuleSetProperty
{inspectionLevel = newValue, ..}
| null |
https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/wafv2/gen/Stratosphere/WAFv2/WebACL/AWSManagedRulesBotControlRuleSetProperty.hs
|
haskell
|
module Stratosphere.WAFv2.WebACL.AWSManagedRulesBotControlRuleSetProperty (
AWSManagedRulesBotControlRuleSetProperty(..),
mkAWSManagedRulesBotControlRuleSetProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data AWSManagedRulesBotControlRuleSetProperty
= AWSManagedRulesBotControlRuleSetProperty {inspectionLevel :: (Value Prelude.Text)}
mkAWSManagedRulesBotControlRuleSetProperty ::
Value Prelude.Text -> AWSManagedRulesBotControlRuleSetProperty
mkAWSManagedRulesBotControlRuleSetProperty inspectionLevel
= AWSManagedRulesBotControlRuleSetProperty
{inspectionLevel = inspectionLevel}
instance ToResourceProperties AWSManagedRulesBotControlRuleSetProperty where
toResourceProperties AWSManagedRulesBotControlRuleSetProperty {..}
= ResourceProperties
{awsType = "AWS::WAFv2::WebACL.AWSManagedRulesBotControlRuleSet",
supportsTags = Prelude.False,
properties = ["InspectionLevel" JSON..= inspectionLevel]}
instance JSON.ToJSON AWSManagedRulesBotControlRuleSetProperty where
toJSON AWSManagedRulesBotControlRuleSetProperty {..}
= JSON.object ["InspectionLevel" JSON..= inspectionLevel]
instance Property "InspectionLevel" AWSManagedRulesBotControlRuleSetProperty where
type PropertyType "InspectionLevel" AWSManagedRulesBotControlRuleSetProperty = Value Prelude.Text
set newValue AWSManagedRulesBotControlRuleSetProperty {}
= AWSManagedRulesBotControlRuleSetProperty
{inspectionLevel = newValue, ..}
|
|
edb9b888e3d920350b8802368d334e91140ccb0625bcc2ae0a845710612507d9
|
jtdaugherty/vty
|
Classify.hs
|
{-# OPTIONS_HADDOCK hide #-}
-- This makes a kind of trie. Has space efficiency issues with large
-- input blocks. Likely building a parser and just applying that would
-- be better.
module Graphics.Vty.Input.Classify
( classify
, KClass(..)
, ClassifierState(..)
)
where
import Graphics.Vty.Input.Events
import Graphics.Vty.Input.Mouse
import Graphics.Vty.Input.Focus
import Graphics.Vty.Input.Paste
import Graphics.Vty.Input.Classify.Types
import Codec.Binary.UTF8.Generic (decode)
import Control.Arrow (first)
import qualified Data.Map as M( fromList, lookup )
import Data.Maybe ( mapMaybe )
import qualified Data.Set as S( fromList, member )
import Data.Word
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import Data.ByteString.Char8 (ByteString)
-- | Whether the classifier is currently processing a chunked format.
-- Currently, only bracketed pastes use this.
data ClassifierState
= ClassifierStart
-- ^ Not processing a chunked format.
| ClassifierInChunk ByteString [ByteString]
-- ^ Currently processing a chunked format. The initial chunk is in the
-- first argument and a reversed remainder of the chunks is collected in
the second argument . At the end of the processing , the chunks are
-- reversed and concatenated with the final chunk.
compile :: ClassifyMap -> ByteString -> KClass
compile table = cl' where
-- take all prefixes and create a set of these
prefixSet = S.fromList $ concatMap (init . BS.inits . BS8.pack . fst) table
maxValidInputLength = maximum (map (length . fst) table)
eventForInput = M.fromList $ map (first BS8.pack) table
cl' inputBlock | BS8.null inputBlock = Prefix
cl' inputBlock = case M.lookup inputBlock eventForInput of
-- if the inputBlock is exactly what is expected for an
-- event then consume the whole block and return the event
Just e -> Valid e BS8.empty
Nothing -> case S.member inputBlock prefixSet of
True -> Prefix
-- look up progressively smaller tails of the input
-- block until an event is found The assumption is that
-- the event that consumes the most input bytes should
-- be produced.
-- The test verifyFullSynInputToEvent2x verifies this.
H : There will always be one match . The prefixSet
-- contains, by definition, all prefixes of an event.
False ->
let inputPrefixes = reverse . take maxValidInputLength . tail . BS8.inits $ inputBlock
in case mapMaybe (\s -> (,) s `fmap` M.lookup s eventForInput) inputPrefixes of
(s,e) : _ -> Valid e (BS8.drop (BS8.length s) inputBlock)
-- neither a prefix or a full event.
[] -> Invalid
classify :: ClassifyMap -> ClassifierState -> ByteString -> KClass
classify table = process
where
standardClassifier = compile table
process ClassifierStart s =
case BS.uncons s of
_ | bracketedPasteStarted s ->
if bracketedPasteFinished s
then parseBracketedPaste s
else Chunk
_ | isMouseEvent s -> classifyMouseEvent s
_ | isFocusEvent s -> classifyFocusEvent s
Just (c,cs) | c >= 0xC2 -> classifyUtf8 c cs
_ -> standardClassifier s
process (ClassifierInChunk p ps) s | bracketedPasteStarted p =
if bracketedPasteFinished s
then parseBracketedPaste $ BS.concat $ p:reverse (s:ps)
else Chunk
process ClassifierInChunk{} _ = Invalid
classifyUtf8 :: Word8 -> ByteString -> KClass
classifyUtf8 c cs =
let n = utf8Length c
(codepoint,rest) = BS8.splitAt (n - 1) cs
codepoint8 :: [Word8]
codepoint8 = c:BS.unpack codepoint
in case decode codepoint8 of
_ | n < BS.length codepoint + 1 -> Prefix
Just (unicodeChar, _) -> Valid (EvKey (KChar unicodeChar) []) rest
-- something bad happened; just ignore and continue.
Nothing -> Invalid
utf8Length :: Word8 -> Int
utf8Length c
| c < 0x80 = 1
| c < 0xE0 = 2
| c < 0xF0 = 3
| otherwise = 4
| null |
https://raw.githubusercontent.com/jtdaugherty/vty/1f4926369eac21657888aaf64cad20006d6c68d6/src/Graphics/Vty/Input/Classify.hs
|
haskell
|
# OPTIONS_HADDOCK hide #
This makes a kind of trie. Has space efficiency issues with large
input blocks. Likely building a parser and just applying that would
be better.
| Whether the classifier is currently processing a chunked format.
Currently, only bracketed pastes use this.
^ Not processing a chunked format.
^ Currently processing a chunked format. The initial chunk is in the
first argument and a reversed remainder of the chunks is collected in
reversed and concatenated with the final chunk.
take all prefixes and create a set of these
if the inputBlock is exactly what is expected for an
event then consume the whole block and return the event
look up progressively smaller tails of the input
block until an event is found The assumption is that
the event that consumes the most input bytes should
be produced.
The test verifyFullSynInputToEvent2x verifies this.
contains, by definition, all prefixes of an event.
neither a prefix or a full event.
something bad happened; just ignore and continue.
|
module Graphics.Vty.Input.Classify
( classify
, KClass(..)
, ClassifierState(..)
)
where
import Graphics.Vty.Input.Events
import Graphics.Vty.Input.Mouse
import Graphics.Vty.Input.Focus
import Graphics.Vty.Input.Paste
import Graphics.Vty.Input.Classify.Types
import Codec.Binary.UTF8.Generic (decode)
import Control.Arrow (first)
import qualified Data.Map as M( fromList, lookup )
import Data.Maybe ( mapMaybe )
import qualified Data.Set as S( fromList, member )
import Data.Word
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import Data.ByteString.Char8 (ByteString)
data ClassifierState
= ClassifierStart
| ClassifierInChunk ByteString [ByteString]
the second argument . At the end of the processing , the chunks are
compile :: ClassifyMap -> ByteString -> KClass
compile table = cl' where
prefixSet = S.fromList $ concatMap (init . BS.inits . BS8.pack . fst) table
maxValidInputLength = maximum (map (length . fst) table)
eventForInput = M.fromList $ map (first BS8.pack) table
cl' inputBlock | BS8.null inputBlock = Prefix
cl' inputBlock = case M.lookup inputBlock eventForInput of
Just e -> Valid e BS8.empty
Nothing -> case S.member inputBlock prefixSet of
True -> Prefix
H : There will always be one match . The prefixSet
False ->
let inputPrefixes = reverse . take maxValidInputLength . tail . BS8.inits $ inputBlock
in case mapMaybe (\s -> (,) s `fmap` M.lookup s eventForInput) inputPrefixes of
(s,e) : _ -> Valid e (BS8.drop (BS8.length s) inputBlock)
[] -> Invalid
classify :: ClassifyMap -> ClassifierState -> ByteString -> KClass
classify table = process
where
standardClassifier = compile table
process ClassifierStart s =
case BS.uncons s of
_ | bracketedPasteStarted s ->
if bracketedPasteFinished s
then parseBracketedPaste s
else Chunk
_ | isMouseEvent s -> classifyMouseEvent s
_ | isFocusEvent s -> classifyFocusEvent s
Just (c,cs) | c >= 0xC2 -> classifyUtf8 c cs
_ -> standardClassifier s
process (ClassifierInChunk p ps) s | bracketedPasteStarted p =
if bracketedPasteFinished s
then parseBracketedPaste $ BS.concat $ p:reverse (s:ps)
else Chunk
process ClassifierInChunk{} _ = Invalid
classifyUtf8 :: Word8 -> ByteString -> KClass
classifyUtf8 c cs =
let n = utf8Length c
(codepoint,rest) = BS8.splitAt (n - 1) cs
codepoint8 :: [Word8]
codepoint8 = c:BS.unpack codepoint
in case decode codepoint8 of
_ | n < BS.length codepoint + 1 -> Prefix
Just (unicodeChar, _) -> Valid (EvKey (KChar unicodeChar) []) rest
Nothing -> Invalid
utf8Length :: Word8 -> Int
utf8Length c
| c < 0x80 = 1
| c < 0xE0 = 2
| c < 0xF0 = 3
| otherwise = 4
|
7093a69c069dc09aa4a05aa4556da0753f78f2cdd15a5ed0b7a9416a36fa8134
|
Dept24c/vivo
|
client.cljc
|
(ns com.dept24c.vivo.client
(:require
[clojure.core.async :as ca]
[com.dept24c.vivo.bristlecone.block-ids :as block-ids]
[com.dept24c.vivo.client.topic-subscriptions :as topic-subscriptions]
[com.dept24c.vivo.client.state-subscriptions :as state-subscriptions]
[com.dept24c.vivo.commands :as commands]
[com.dept24c.vivo.react :as react]
[com.dept24c.vivo.utils :as u]
[deercreeklabs.async-utils :as au]
[deercreeklabs.capsule.client :as cc]
[deercreeklabs.capsule.logging :as log]
[deercreeklabs.lancaster :as l]
[deercreeklabs.lancaster.utils :as lu]
[deercreeklabs.stockroom :as sr]))
(def default-send-msg-timeout-ms 30000)
(def max-commit-attempts 100)
(def update-state-timeout-ms 30000)
(defn make-update-info [update-cmds]
(reduce
(fn [acc cmd]
(let [{:keys [path op]} cmd
_ (when-not (sequential? path)
(throw (ex-info
(str "The `path` parameter of the update "
"command must be a sequence. Got: `"
path "`.")
(u/sym-map cmd path))))
[head & tail] path
_ (when-not ((set u/valid-ops) op)
(throw (ex-info
(str "The `op` parameter of the update command "
"is not a valid op. Got: `" op "`.")
(u/sym-map cmd op))))
k (case head
:local :local-cmds
:sys :sys-cmds
(u/throw-bad-path-root path))]
(update acc k conj (assoc cmd :path path))))
{:local-cmds []
:sys-cmds []}
update-cmds))
(defn get-sub-id [*last-sub-id]
(str (swap! *last-sub-id (fn [sub-id]
(let [new-sub-id (inc sub-id)]
(if (> new-sub-id 1e9)
0
new-sub-id))))))
(defn eval-cmds [initial-state cmds prefix]
(reduce (fn [{:keys [state] :as acc} cmd]
(let [ret (commands/eval-cmd state cmd prefix)]
(-> acc
(assoc :state (:state ret))
(update :update-infos conj (:update-info ret)))))
{:state initial-state
:update-infos []}
cmds))
(defn update-cmds-match? [ucs1 ucs2]
(if (not= (count ucs1) (count ucs2))
false
(reduce (fn [acc i]
(let [uc1 (nth ucs1 i)
uc2 (nth ucs2 i)]
(if (= (dissoc uc1 :value) (dissoc uc2 :value))
acc
(reduced false))))
true (range (count ucs1)))))
(defn do-sys-updates!
[capsule-client sys-cmds <update-cmd->suc <update-sys-state!]
(ca/go
(try
(when-not capsule-client
(throw (ex-info (str "Can't update :sys state because the "
":get-server-url option was not provided when the "
"vivo-client was created.")
{})))
(let [ch (ca/merge (map-indexed <update-cmd->suc sys-cmds))
;; Use i->v map to preserve original command order
sucs-map (au/<? (ca/reduce (fn [acc v]
(if (instance? #?(:cljs js/Error
:clj Throwable) v)
(reduced v)
(let [[i suc] v]
(assoc acc i suc))))
{} ch))
_ (when (instance? #?(:cljs js/Error :clj Throwable) sucs-map)
(throw sucs-map))
sucs (keep sucs-map (range (count sys-cmds)))]
(au/<? (<update-sys-state! sucs)))
(catch #?(:cljs js/Error :clj Throwable) e
(log/error (u/ex-msg-and-stacktrace e))))))
;; TODO: Handle failed sys update (offline data may obviate this need)
(defn do-state-updates!*
[vc update-info cb* subscription-state-update-ch <fp->schema
sys-state-schema subject-id *sys-db-info *local-state *state-sub-name->info ]
(let [{:keys [sys-cmds local-cmds]} update-info
cb (or cb* (constantly nil))
sys-ret (when (seq sys-cmds)
(let [eval-ret (eval-cmds (:db @*sys-db-info)
sys-cmds :sys)
{:keys [state update-infos]} eval-ret
<update-cmd->suc (partial
u/<update-cmd->serializable-update-cmd
vc)
<update-sys-state! #(u/<send-msg vc :update-state %)]
(do-sys-updates! (:capsule-client vc) sys-cmds
<update-cmd->suc <update-sys-state!)
{:db state
:update-infos update-infos}))]
(if (and (seq sys-cmds)
(or (not sys-ret)
(= :vivo/unauthorized sys-ret)))
Do n't do local / sub updates if sys updates failed
(loop [num-attempts 1]
(let [cur-local-state @*local-state
local-ret (eval-cmds cur-local-state local-cmds :local)
local-state (:state local-ret)]
(if (compare-and-set! *local-state cur-local-state local-state)
(let [update-infos (concat (:update-infos sys-ret)
(:update-infos local-ret))
db (or (:db sys-ret)
(:db @*sys-db-info))]
(swap! *sys-db-info assoc :db db)
(ca/put! subscription-state-update-ch
(u/sym-map db local-state subject-id
update-infos cb *state-sub-name->info)))
(if (< num-attempts max-commit-attempts)
(recur (inc num-attempts))
(cb (ex-info (str "Failed to commit updates after "
num-attempts " attempts.")
(u/sym-map max-commit-attempts
sys-cmds local-cmds)))))))))
nil)
(defn <wait-for-conn-init* [*stopped? *conn-initialized?]
(au/go
(loop [tries-remaining 600]
(when (zero? tries-remaining)
(throw (ex-info "Timed out waiting for connection to initialize."
{:cause :init-timeout})))
(cond
@*conn-initialized? true
@*stopped? false
:else (do
(ca/<! (ca/timeout 100))
(recur (dec tries-remaining)))))))
(defn <do-login!
[capsule-client identifier secret token wait-for-init? set-subject-id!
*token *stopped? *conn-initialized?]
(when secret
(u/check-secret-len secret))
(au/go
(when wait-for-init?
(au/<? (<wait-for-conn-init* *stopped? *conn-initialized?)))
(let [[msg-name arg] (if identifier
[:log-in {:identifier identifier
:secret secret}]
[:log-in-w-token token])
ret (au/<? (cc/<send-msg capsule-client msg-name arg))
{:keys [token subject-id]} ret]
(if-not subject-id
false
(do
(set-subject-id! subject-id)
(reset! *token token)
ret)))))
(defn <do-logout!
[capsule-client token set-subject-id! *token]
(au/go
(reset! *token nil)
(set-subject-id! nil) ; Do this explicitly in case we aren't connected
(au/<? (if token
(cc/<send-msg capsule-client :log-out-w-token token)
(cc/<send-msg capsule-client :log-out nil)))
;; Don't need to request a :db-changed msg here because :log-out will
;; generate one if we are connected. If we aren't connected,
;; the request would fail anyway.
))
(defn <handle-db-changed*
[arg metadata local-state local-db-id local-subject-id <fp->schema
sys-state-schema subscription-state-update-ch *conn-initialized?
*sys-db-info *state-sub-name->info *subject-id]
(ca/go
(try
(let [{:keys [db-id prev-db-id serialized-state subject-id]} arg
{:keys [fp bytes]} serialized-state
writer-schema (when fp
(au/<? (<fp->schema fp)))
missed-update? (and (not= local-db-id prev-db-id))
subject-id-changed? (not= local-subject-id subject-id)
update-infos (cond-> (:update-infos arg)
missed-update?
(conj {:norm-path [:sys]
:op :set})
subject-id-changed?
(conj {:norm-path [:vivo/subject-id]
:op :set}))
db (when (and writer-schema bytes)
(l/deserialize sys-state-schema writer-schema bytes))
cb (fn [_]
(reset! *conn-initialized? true))]
(log/info (str "Got :db-changed msg.\n"
(u/pprint-str (u/sym-map db-id subject-id))))
(swap! *sys-db-info (fn [old]
(cond-> (assoc old :db-id db-id)
;; If db is nil, it means it didn't change
db (assoc :db db))))
(when subject-id-changed?
(reset! *subject-id subject-id))
(ca/put! subscription-state-update-ch
(u/sym-map db local-state update-infos cb
*state-sub-name->info subject-id)))
(catch #?(:cljs js/Error :clj Throwable) e
(log/error (str "Exception in <handle-db-changed: "
(u/ex-msg-and-stacktrace e)))))))
(defrecord VivoClient [capsule-client
path->schema-cache
rpcs
set-subject-id!
subscription-state-update-ch
sys-state-schema
sys-state-source
*conn-initialized?
*fp->schema
*local-state
*next-instance-num
*next-topic-sub-id
*state-sub-name->info
*stopped?
*subject-id
*sys-db-info
*token
*topic-name->sub-id->cb]
u/ISchemaStore
(<fp->schema [this fp]
(when-not (int? fp)
(throw (ex-info (str "Given `fp` arg is not a `long`. Got `"
(or fp "nil") "`.")
{:given-fp fp})))
(au/go
(or (@*fp->schema fp)
(if-let [schema (some-> (cc/<send-msg capsule-client
:get-schema-pcf fp)
(au/<?)
(l/json->schema))]
(do
(swap! *fp->schema assoc fp schema)
schema)
(throw (ex-info
(str "Failed to get a schema for fp `" fp "`.")
(u/sym-map fp)))))))
(<schema->fp [this schema]
(when-not (l/schema? schema)
(throw (ex-info (str "Schema arg must be a Lancaster schema. Got `"
schema "`.")
{:given-schema schema})))
(au/go
(let [fp (l/fingerprint64 schema)]
(when-not (@*fp->schema fp)
(swap! *fp->schema assoc fp schema)
(au/<? (cc/<send-msg capsule-client
:store-schema-pcf (l/pcf schema))))
fp)))
u/IVivoClient
(next-instance-num! [this]
(swap! *next-instance-num inc))
(<deserialize-value [this path ret]
(au/go
(when ret
Ignore :
value-sch (u/path->schema path->schema-cache sys-state-schema
schema-path)]
(when value-sch
(let [writer-sch (au/<? (u/<fp->schema this (:fp ret)))]
(l/deserialize value-sch writer-sch (:bytes ret))))))))
(<log-in! [this identifier secret]
(<do-login! capsule-client identifier secret nil true set-subject-id! *token
*stopped? *conn-initialized?))
(<log-in-w-token! [this token]
(<do-login! capsule-client nil nil token true set-subject-id! *token
*stopped? *conn-initialized?))
(<log-out! [this]
(<do-logout! capsule-client nil set-subject-id! *token))
(<log-out-w-token! [this token]
(<do-logout! capsule-client token set-subject-id! *token))
(logged-in? [this]
(boolean @*subject-id))
(shutdown! [this]
(reset! *stopped? true)
(cc/shutdown capsule-client)
(log/info "Vivo client stopped."))
(get-subscription-info [this state-sub-name]
(when-let [info (@*state-sub-name->info state-sub-name)]
(select-keys info [:state :resolution-map])))
(subscribe-to-state! [this state-sub-name sub-map update-fn opts]
(state-subscriptions/subscribe-to-state!
state-sub-name sub-map update-fn opts @*sys-db-info @*local-state
@*subject-id *stopped? *state-sub-name->info))
(unsubscribe-from-state! [this state-sub-name]
(swap! *state-sub-name->info dissoc state-sub-name)
nil)
(subscribe-to-topic! [this scope topic-name cb]
(topic-subscriptions/subscribe-to-topic!
scope topic-name cb *next-topic-sub-id *topic-name->sub-id->cb))
(publish-to-topic! [this scope topic-name msg]
(topic-subscriptions/publish-to-topic!
scope topic-name msg *topic-name->sub-id->cb))
(<wait-for-conn-init [this]
(<wait-for-conn-init* *stopped? *conn-initialized?))
(update-state! [this update-cmds cb]
(when-not (sequential? update-cmds)
(when cb
(cb (ex-info "The update-cmds parameter must be a sequence."
(u/sym-map update-cmds)))))
(let [update-info (make-update-info update-cmds)]
(do-state-updates!* this update-info cb subscription-state-update-ch
#(u/<fp->schema this %) sys-state-schema
@*subject-id *sys-db-info *local-state
*state-sub-name->info))
nil)
(<update-cmd->serializable-update-cmd [this i cmd]
(au/go
(if-not (contains? cmd :arg)
[i cmd]
(let [{:keys [arg path]} cmd
arg-sch (u/path->schema path->schema-cache sys-state-schema
(rest path))]
(if-not arg-sch
[i nil]
(let [fp (au/<? (u/<schema->fp this arg-sch))
bytes (l/serialize arg-sch (:arg cmd))
scmd (assoc cmd :arg (u/sym-map fp bytes))]
(swap! *fp->schema assoc fp arg-sch)
[i scmd]))))))
(<handle-db-changed [this arg metadata]
(<handle-db-changed* arg metadata @*local-state (:db-id @*sys-db-info)
@*subject-id #(u/<fp->schema this %) sys-state-schema
subscription-state-update-ch *conn-initialized?
*sys-db-info *state-sub-name->info *subject-id))
(<send-msg [this msg-name msg]
(u/<send-msg this msg-name msg default-send-msg-timeout-ms))
(<send-msg [this msg-name msg timeout-ms]
(au/go
(when-not capsule-client
(throw
(ex-info (str "Can't perform network operation because the "
":get-server-url option was not provided when the "
"vivo-client was created.") {})))
(au/<? (u/<wait-for-conn-init this))
(au/<? (cc/<send-msg capsule-client msg-name msg timeout-ms))))
(<get-subject-id-for-identifier [this identifier]
(u/<send-msg this :get-subject-id-for-identifier identifier))
(<add-subject! [this identifier secret]
(u/<add-subject! this identifier secret nil))
(<add-subject! [this identifier secret subject-id]
(u/check-secret-len secret)
(u/<send-msg this :add-subject (u/sym-map identifier secret subject-id)))
(<add-subject-identifier! [this identifier]
(u/<send-msg this :add-subject-identifier identifier))
(<remove-subject-identifier! [this identifier]
(u/<send-msg this :remove-subject-identifier identifier))
(<change-secret! [this old-secret new-secret]
(u/check-secret-len old-secret)
(u/check-secret-len new-secret)
(u/<send-msg this :change-secret (u/sym-map old-secret new-secret)))
(<rpc [this rpc-name-kw arg timeout-ms]
(au/go
(when-not (keyword? rpc-name-kw)
(throw (ex-info (str "rpc-name-kw must be a keyword. Got`" rpc-name-kw
"`.")
(u/sym-map rpc-name-kw arg))))
(au/<? (u/<wait-for-conn-init this))
(let [rpc-info (get rpcs rpc-name-kw)
_ (when-not rpc-info
(throw (ex-info
(str "No RPC with name `" rpc-name-kw "` is registered."
" Either this is a typo or you need to add `"
rpc-name-kw "` to the `:rpcs map "
"when creating the Vivo client.")
{:known-rpcs (keys rpcs)
:given-rpc rpc-name-kw})))
{:keys [arg-schema ret-schema]} rpc-info
arg {:rpc-name-kw-ns (namespace rpc-name-kw)
:rpc-name-kw-name (name rpc-name-kw)
:arg {:fp (au/<? (u/<schema->fp this arg-schema))
:bytes (l/serialize arg-schema arg)}}
ret* (au/<? (u/<send-msg this :rpc arg timeout-ms))]
(cond
(nil? ret*)
nil
(= :vivo/unauthorized ret*)
(throw (ex-info
(str "RPC `" rpc-name-kw "` is unauthorized "
"for this user.")
{:rpc-name-kw rpc-name-kw
:subject-id @*subject-id}))
:else
(let [{:keys [fp bytes]} ret*
w-schema (au/<? (u/<fp->schema this fp))]
(l/deserialize ret-schema w-schema bytes)))))))
(defn <on-connect
[opts-on-connect sys-state-source set-subject-id! *conn-initialized? *vc
*stopped? *token capsule-client]
(when-not @*stopped?
(ca/go
(try
(au/<? (cc/<send-msg capsule-client :set-state-source sys-state-source))
(let [vc @*vc]
;; Either of these generate a :request-db-changed-msg.
(if-let [token @*token]
(au/<? (<do-login! capsule-client nil nil token false
set-subject-id! *token *stopped?
*conn-initialized?))
(au/<? (cc/<send-msg capsule-client :request-db-changed-msg nil)))
(au/<? (u/<wait-for-conn-init vc))
(when opts-on-connect
(let [ret (opts-on-connect vc)]
(when (au/channel? ret)
(au/<? ret)))) ;; Check for errors
(log/info "Vivo client connection initialized."))
(catch #?(:clj Exception :cljs js/Error) e
(log/error (str "Error in <on-connect: "
(u/ex-msg-and-stacktrace e))))))))
(defn on-disconnect
[on-disconnect* *conn-initialized? set-subject-id! capsule-client]
(reset! *conn-initialized? false)
(on-disconnect*))
(defn check-sys-state-source [sys-state-source]
;; sys-state-source must be either:
;; - {:branch/name <branch-name>}
;; - {:temp-branch/db-id <db-id> or nil}
(when-not (map? sys-state-source)
(throw (ex-info (str "sys-state-source must be a map. Got `"
sys-state-source "`.")
(u/sym-map sys-state-source))))
(if-let [branch-name (:branch/name sys-state-source)]
(when-not (string? branch-name)
(throw (ex-info (str "Bad :branch/name value in :sys-state-source. "
"Expected a string, got `" branch-name "`.")
(u/sym-map sys-state-source branch-name))))
(if (contains? sys-state-source :temp-branch/db-id)
(let [db-id (:temp-branch/db-id sys-state-source)]
(when-not (or (nil? db-id)
(string? db-id))
(throw (ex-info
(str "Bad :temp-branch/db-id value in :sys-state-source. "
"Expected a string or nil, got `" db-id "`.")
(u/sym-map sys-state-source db-id)))))
(throw (ex-info
(str ":sys-state-source must contain either a :branch/name key "
"or a :temp-branch/db-id key. Got `" sys-state-source "`.")
(u/sym-map sys-state-source))))))
(defn make-capsule-client
[get-server-url opts-on-connect opts-on-disconnect sys-state-schema
sys-state-source *sys-db-info *vc *conn-initialized? *stopped? *token
set-subject-id!]
(when-not sys-state-schema
(throw (ex-info (str "Missing `:sys-state-schema` option in vivo-client "
"constructor.")
{})))
(let [get-credentials (constantly {:subject-id "vivo-client"
:subject-secret ""})
opts {:on-connect (partial <on-connect opts-on-connect sys-state-source
set-subject-id! *conn-initialized? *vc
*stopped? *token)
:on-disconnect (partial on-disconnect opts-on-disconnect
*conn-initialized? set-subject-id!)}]
(cc/client get-server-url get-credentials
u/client-server-protocol :client opts)))
(defn set-handlers! [vc capsule-client *fp->schema]
(cc/set-handler capsule-client :db-changed
(partial u/<handle-db-changed vc))
(cc/set-handler capsule-client :get-schema-pcf
(fn [fp metadata]
(if-let [schema (@*fp->schema fp)]
(l/pcf schema)
(do
(log/error
(str "Could not find PCF for fingerprint `"
fp "`."))
nil)))))
(defn vivo-client [opts]
(let [{:keys [get-server-url
initial-local-state
on-connect
on-disconnect
rpcs
sys-state-source
sys-state-schema]} opts
*local-state (atom initial-local-state)
*sys-db-info (atom {:db-id nil
:db nil})
*conn-initialized? (atom (not get-server-url))
*stopped? (atom false)
*fp->schema (atom {})
*subject-id (atom nil)
*vc (atom nil)
*state-sub-name->info (atom {})
*token (atom nil)
*topic-name->sub-id->cb (atom {})
*next-instance-num (atom 0)
*next-topic-sub-id (atom 0)
on-disconnect* #(when on-disconnect
(on-disconnect @*vc @*local-state))
;; TODO: Think about this buffer size and dropping behavior under load
;; Perhaps disconnect and reconnect later if overloaded?
subscription-state-update-ch (ca/chan (ca/sliding-buffer 1000))
set-subject-id! (fn [subject-id]
(reset! *subject-id subject-id)
(let [update-infos [{:norm-path [:vivo/subject-id]
:op :set}]
db (:db @*sys-db-info)
local-state @*local-state]
(ca/put! subscription-state-update-ch
(u/sym-map db local-state update-infos
subject-id
*state-sub-name->info)))
nil)
_ (when rpcs
(u/check-rpcs rpcs))
path->schema-cache (sr/stockroom 1000)
capsule-client (when get-server-url
(check-sys-state-source sys-state-source)
(make-capsule-client
get-server-url on-connect on-disconnect*
sys-state-schema sys-state-source
*sys-db-info *vc *conn-initialized? *stopped?
*token set-subject-id!))
vc (->VivoClient capsule-client
path->schema-cache
rpcs
set-subject-id!
subscription-state-update-ch
sys-state-schema
sys-state-source
*conn-initialized?
*fp->schema
*local-state
*next-instance-num
*next-topic-sub-id
*state-sub-name->info
*stopped?
*subject-id
*sys-db-info
*token
*topic-name->sub-id->cb)]
(reset! *vc vc)
(state-subscriptions/start-subscription-update-loop!
subscription-state-update-ch)
(when get-server-url
(set-handlers! vc capsule-client *fp->schema))
vc))
| null |
https://raw.githubusercontent.com/Dept24c/vivo/19938827c92ff1d3d7f64ae0432b75fa2f8fc303/src/com/dept24c/vivo/client.cljc
|
clojure
|
Use i->v map to preserve original command order
TODO: Handle failed sys update (offline data may obviate this need)
Do this explicitly in case we aren't connected
Don't need to request a :db-changed msg here because :log-out will
generate one if we are connected. If we aren't connected,
the request would fail anyway.
If db is nil, it means it didn't change
Either of these generate a :request-db-changed-msg.
Check for errors
sys-state-source must be either:
- {:branch/name <branch-name>}
- {:temp-branch/db-id <db-id> or nil}
TODO: Think about this buffer size and dropping behavior under load
Perhaps disconnect and reconnect later if overloaded?
|
(ns com.dept24c.vivo.client
(:require
[clojure.core.async :as ca]
[com.dept24c.vivo.bristlecone.block-ids :as block-ids]
[com.dept24c.vivo.client.topic-subscriptions :as topic-subscriptions]
[com.dept24c.vivo.client.state-subscriptions :as state-subscriptions]
[com.dept24c.vivo.commands :as commands]
[com.dept24c.vivo.react :as react]
[com.dept24c.vivo.utils :as u]
[deercreeklabs.async-utils :as au]
[deercreeklabs.capsule.client :as cc]
[deercreeklabs.capsule.logging :as log]
[deercreeklabs.lancaster :as l]
[deercreeklabs.lancaster.utils :as lu]
[deercreeklabs.stockroom :as sr]))
(def default-send-msg-timeout-ms 30000)
(def max-commit-attempts 100)
(def update-state-timeout-ms 30000)
(defn make-update-info [update-cmds]
(reduce
(fn [acc cmd]
(let [{:keys [path op]} cmd
_ (when-not (sequential? path)
(throw (ex-info
(str "The `path` parameter of the update "
"command must be a sequence. Got: `"
path "`.")
(u/sym-map cmd path))))
[head & tail] path
_ (when-not ((set u/valid-ops) op)
(throw (ex-info
(str "The `op` parameter of the update command "
"is not a valid op. Got: `" op "`.")
(u/sym-map cmd op))))
k (case head
:local :local-cmds
:sys :sys-cmds
(u/throw-bad-path-root path))]
(update acc k conj (assoc cmd :path path))))
{:local-cmds []
:sys-cmds []}
update-cmds))
(defn get-sub-id [*last-sub-id]
(str (swap! *last-sub-id (fn [sub-id]
(let [new-sub-id (inc sub-id)]
(if (> new-sub-id 1e9)
0
new-sub-id))))))
(defn eval-cmds [initial-state cmds prefix]
(reduce (fn [{:keys [state] :as acc} cmd]
(let [ret (commands/eval-cmd state cmd prefix)]
(-> acc
(assoc :state (:state ret))
(update :update-infos conj (:update-info ret)))))
{:state initial-state
:update-infos []}
cmds))
(defn update-cmds-match? [ucs1 ucs2]
(if (not= (count ucs1) (count ucs2))
false
(reduce (fn [acc i]
(let [uc1 (nth ucs1 i)
uc2 (nth ucs2 i)]
(if (= (dissoc uc1 :value) (dissoc uc2 :value))
acc
(reduced false))))
true (range (count ucs1)))))
(defn do-sys-updates!
[capsule-client sys-cmds <update-cmd->suc <update-sys-state!]
(ca/go
(try
(when-not capsule-client
(throw (ex-info (str "Can't update :sys state because the "
":get-server-url option was not provided when the "
"vivo-client was created.")
{})))
(let [ch (ca/merge (map-indexed <update-cmd->suc sys-cmds))
sucs-map (au/<? (ca/reduce (fn [acc v]
(if (instance? #?(:cljs js/Error
:clj Throwable) v)
(reduced v)
(let [[i suc] v]
(assoc acc i suc))))
{} ch))
_ (when (instance? #?(:cljs js/Error :clj Throwable) sucs-map)
(throw sucs-map))
sucs (keep sucs-map (range (count sys-cmds)))]
(au/<? (<update-sys-state! sucs)))
(catch #?(:cljs js/Error :clj Throwable) e
(log/error (u/ex-msg-and-stacktrace e))))))
(defn do-state-updates!*
[vc update-info cb* subscription-state-update-ch <fp->schema
sys-state-schema subject-id *sys-db-info *local-state *state-sub-name->info ]
(let [{:keys [sys-cmds local-cmds]} update-info
cb (or cb* (constantly nil))
sys-ret (when (seq sys-cmds)
(let [eval-ret (eval-cmds (:db @*sys-db-info)
sys-cmds :sys)
{:keys [state update-infos]} eval-ret
<update-cmd->suc (partial
u/<update-cmd->serializable-update-cmd
vc)
<update-sys-state! #(u/<send-msg vc :update-state %)]
(do-sys-updates! (:capsule-client vc) sys-cmds
<update-cmd->suc <update-sys-state!)
{:db state
:update-infos update-infos}))]
(if (and (seq sys-cmds)
(or (not sys-ret)
(= :vivo/unauthorized sys-ret)))
Do n't do local / sub updates if sys updates failed
(loop [num-attempts 1]
(let [cur-local-state @*local-state
local-ret (eval-cmds cur-local-state local-cmds :local)
local-state (:state local-ret)]
(if (compare-and-set! *local-state cur-local-state local-state)
(let [update-infos (concat (:update-infos sys-ret)
(:update-infos local-ret))
db (or (:db sys-ret)
(:db @*sys-db-info))]
(swap! *sys-db-info assoc :db db)
(ca/put! subscription-state-update-ch
(u/sym-map db local-state subject-id
update-infos cb *state-sub-name->info)))
(if (< num-attempts max-commit-attempts)
(recur (inc num-attempts))
(cb (ex-info (str "Failed to commit updates after "
num-attempts " attempts.")
(u/sym-map max-commit-attempts
sys-cmds local-cmds)))))))))
nil)
(defn <wait-for-conn-init* [*stopped? *conn-initialized?]
(au/go
(loop [tries-remaining 600]
(when (zero? tries-remaining)
(throw (ex-info "Timed out waiting for connection to initialize."
{:cause :init-timeout})))
(cond
@*conn-initialized? true
@*stopped? false
:else (do
(ca/<! (ca/timeout 100))
(recur (dec tries-remaining)))))))
(defn <do-login!
[capsule-client identifier secret token wait-for-init? set-subject-id!
*token *stopped? *conn-initialized?]
(when secret
(u/check-secret-len secret))
(au/go
(when wait-for-init?
(au/<? (<wait-for-conn-init* *stopped? *conn-initialized?)))
(let [[msg-name arg] (if identifier
[:log-in {:identifier identifier
:secret secret}]
[:log-in-w-token token])
ret (au/<? (cc/<send-msg capsule-client msg-name arg))
{:keys [token subject-id]} ret]
(if-not subject-id
false
(do
(set-subject-id! subject-id)
(reset! *token token)
ret)))))
(defn <do-logout!
[capsule-client token set-subject-id! *token]
(au/go
(reset! *token nil)
(au/<? (if token
(cc/<send-msg capsule-client :log-out-w-token token)
(cc/<send-msg capsule-client :log-out nil)))
))
(defn <handle-db-changed*
[arg metadata local-state local-db-id local-subject-id <fp->schema
sys-state-schema subscription-state-update-ch *conn-initialized?
*sys-db-info *state-sub-name->info *subject-id]
(ca/go
(try
(let [{:keys [db-id prev-db-id serialized-state subject-id]} arg
{:keys [fp bytes]} serialized-state
writer-schema (when fp
(au/<? (<fp->schema fp)))
missed-update? (and (not= local-db-id prev-db-id))
subject-id-changed? (not= local-subject-id subject-id)
update-infos (cond-> (:update-infos arg)
missed-update?
(conj {:norm-path [:sys]
:op :set})
subject-id-changed?
(conj {:norm-path [:vivo/subject-id]
:op :set}))
db (when (and writer-schema bytes)
(l/deserialize sys-state-schema writer-schema bytes))
cb (fn [_]
(reset! *conn-initialized? true))]
(log/info (str "Got :db-changed msg.\n"
(u/pprint-str (u/sym-map db-id subject-id))))
(swap! *sys-db-info (fn [old]
(cond-> (assoc old :db-id db-id)
db (assoc :db db))))
(when subject-id-changed?
(reset! *subject-id subject-id))
(ca/put! subscription-state-update-ch
(u/sym-map db local-state update-infos cb
*state-sub-name->info subject-id)))
(catch #?(:cljs js/Error :clj Throwable) e
(log/error (str "Exception in <handle-db-changed: "
(u/ex-msg-and-stacktrace e)))))))
(defrecord VivoClient [capsule-client
path->schema-cache
rpcs
set-subject-id!
subscription-state-update-ch
sys-state-schema
sys-state-source
*conn-initialized?
*fp->schema
*local-state
*next-instance-num
*next-topic-sub-id
*state-sub-name->info
*stopped?
*subject-id
*sys-db-info
*token
*topic-name->sub-id->cb]
u/ISchemaStore
(<fp->schema [this fp]
(when-not (int? fp)
(throw (ex-info (str "Given `fp` arg is not a `long`. Got `"
(or fp "nil") "`.")
{:given-fp fp})))
(au/go
(or (@*fp->schema fp)
(if-let [schema (some-> (cc/<send-msg capsule-client
:get-schema-pcf fp)
(au/<?)
(l/json->schema))]
(do
(swap! *fp->schema assoc fp schema)
schema)
(throw (ex-info
(str "Failed to get a schema for fp `" fp "`.")
(u/sym-map fp)))))))
(<schema->fp [this schema]
(when-not (l/schema? schema)
(throw (ex-info (str "Schema arg must be a Lancaster schema. Got `"
schema "`.")
{:given-schema schema})))
(au/go
(let [fp (l/fingerprint64 schema)]
(when-not (@*fp->schema fp)
(swap! *fp->schema assoc fp schema)
(au/<? (cc/<send-msg capsule-client
:store-schema-pcf (l/pcf schema))))
fp)))
u/IVivoClient
(next-instance-num! [this]
(swap! *next-instance-num inc))
(<deserialize-value [this path ret]
(au/go
(when ret
Ignore :
value-sch (u/path->schema path->schema-cache sys-state-schema
schema-path)]
(when value-sch
(let [writer-sch (au/<? (u/<fp->schema this (:fp ret)))]
(l/deserialize value-sch writer-sch (:bytes ret))))))))
(<log-in! [this identifier secret]
(<do-login! capsule-client identifier secret nil true set-subject-id! *token
*stopped? *conn-initialized?))
(<log-in-w-token! [this token]
(<do-login! capsule-client nil nil token true set-subject-id! *token
*stopped? *conn-initialized?))
(<log-out! [this]
(<do-logout! capsule-client nil set-subject-id! *token))
(<log-out-w-token! [this token]
(<do-logout! capsule-client token set-subject-id! *token))
(logged-in? [this]
(boolean @*subject-id))
(shutdown! [this]
(reset! *stopped? true)
(cc/shutdown capsule-client)
(log/info "Vivo client stopped."))
(get-subscription-info [this state-sub-name]
(when-let [info (@*state-sub-name->info state-sub-name)]
(select-keys info [:state :resolution-map])))
(subscribe-to-state! [this state-sub-name sub-map update-fn opts]
(state-subscriptions/subscribe-to-state!
state-sub-name sub-map update-fn opts @*sys-db-info @*local-state
@*subject-id *stopped? *state-sub-name->info))
(unsubscribe-from-state! [this state-sub-name]
(swap! *state-sub-name->info dissoc state-sub-name)
nil)
(subscribe-to-topic! [this scope topic-name cb]
(topic-subscriptions/subscribe-to-topic!
scope topic-name cb *next-topic-sub-id *topic-name->sub-id->cb))
(publish-to-topic! [this scope topic-name msg]
(topic-subscriptions/publish-to-topic!
scope topic-name msg *topic-name->sub-id->cb))
(<wait-for-conn-init [this]
(<wait-for-conn-init* *stopped? *conn-initialized?))
(update-state! [this update-cmds cb]
(when-not (sequential? update-cmds)
(when cb
(cb (ex-info "The update-cmds parameter must be a sequence."
(u/sym-map update-cmds)))))
(let [update-info (make-update-info update-cmds)]
(do-state-updates!* this update-info cb subscription-state-update-ch
#(u/<fp->schema this %) sys-state-schema
@*subject-id *sys-db-info *local-state
*state-sub-name->info))
nil)
(<update-cmd->serializable-update-cmd [this i cmd]
(au/go
(if-not (contains? cmd :arg)
[i cmd]
(let [{:keys [arg path]} cmd
arg-sch (u/path->schema path->schema-cache sys-state-schema
(rest path))]
(if-not arg-sch
[i nil]
(let [fp (au/<? (u/<schema->fp this arg-sch))
bytes (l/serialize arg-sch (:arg cmd))
scmd (assoc cmd :arg (u/sym-map fp bytes))]
(swap! *fp->schema assoc fp arg-sch)
[i scmd]))))))
(<handle-db-changed [this arg metadata]
(<handle-db-changed* arg metadata @*local-state (:db-id @*sys-db-info)
@*subject-id #(u/<fp->schema this %) sys-state-schema
subscription-state-update-ch *conn-initialized?
*sys-db-info *state-sub-name->info *subject-id))
(<send-msg [this msg-name msg]
(u/<send-msg this msg-name msg default-send-msg-timeout-ms))
(<send-msg [this msg-name msg timeout-ms]
(au/go
(when-not capsule-client
(throw
(ex-info (str "Can't perform network operation because the "
":get-server-url option was not provided when the "
"vivo-client was created.") {})))
(au/<? (u/<wait-for-conn-init this))
(au/<? (cc/<send-msg capsule-client msg-name msg timeout-ms))))
(<get-subject-id-for-identifier [this identifier]
(u/<send-msg this :get-subject-id-for-identifier identifier))
(<add-subject! [this identifier secret]
(u/<add-subject! this identifier secret nil))
(<add-subject! [this identifier secret subject-id]
(u/check-secret-len secret)
(u/<send-msg this :add-subject (u/sym-map identifier secret subject-id)))
(<add-subject-identifier! [this identifier]
(u/<send-msg this :add-subject-identifier identifier))
(<remove-subject-identifier! [this identifier]
(u/<send-msg this :remove-subject-identifier identifier))
(<change-secret! [this old-secret new-secret]
(u/check-secret-len old-secret)
(u/check-secret-len new-secret)
(u/<send-msg this :change-secret (u/sym-map old-secret new-secret)))
(<rpc [this rpc-name-kw arg timeout-ms]
(au/go
(when-not (keyword? rpc-name-kw)
(throw (ex-info (str "rpc-name-kw must be a keyword. Got`" rpc-name-kw
"`.")
(u/sym-map rpc-name-kw arg))))
(au/<? (u/<wait-for-conn-init this))
(let [rpc-info (get rpcs rpc-name-kw)
_ (when-not rpc-info
(throw (ex-info
(str "No RPC with name `" rpc-name-kw "` is registered."
" Either this is a typo or you need to add `"
rpc-name-kw "` to the `:rpcs map "
"when creating the Vivo client.")
{:known-rpcs (keys rpcs)
:given-rpc rpc-name-kw})))
{:keys [arg-schema ret-schema]} rpc-info
arg {:rpc-name-kw-ns (namespace rpc-name-kw)
:rpc-name-kw-name (name rpc-name-kw)
:arg {:fp (au/<? (u/<schema->fp this arg-schema))
:bytes (l/serialize arg-schema arg)}}
ret* (au/<? (u/<send-msg this :rpc arg timeout-ms))]
(cond
(nil? ret*)
nil
(= :vivo/unauthorized ret*)
(throw (ex-info
(str "RPC `" rpc-name-kw "` is unauthorized "
"for this user.")
{:rpc-name-kw rpc-name-kw
:subject-id @*subject-id}))
:else
(let [{:keys [fp bytes]} ret*
w-schema (au/<? (u/<fp->schema this fp))]
(l/deserialize ret-schema w-schema bytes)))))))
(defn <on-connect
[opts-on-connect sys-state-source set-subject-id! *conn-initialized? *vc
*stopped? *token capsule-client]
(when-not @*stopped?
(ca/go
(try
(au/<? (cc/<send-msg capsule-client :set-state-source sys-state-source))
(let [vc @*vc]
(if-let [token @*token]
(au/<? (<do-login! capsule-client nil nil token false
set-subject-id! *token *stopped?
*conn-initialized?))
(au/<? (cc/<send-msg capsule-client :request-db-changed-msg nil)))
(au/<? (u/<wait-for-conn-init vc))
(when opts-on-connect
(let [ret (opts-on-connect vc)]
(when (au/channel? ret)
(log/info "Vivo client connection initialized."))
(catch #?(:clj Exception :cljs js/Error) e
(log/error (str "Error in <on-connect: "
(u/ex-msg-and-stacktrace e))))))))
(defn on-disconnect
[on-disconnect* *conn-initialized? set-subject-id! capsule-client]
(reset! *conn-initialized? false)
(on-disconnect*))
(defn check-sys-state-source [sys-state-source]
(when-not (map? sys-state-source)
(throw (ex-info (str "sys-state-source must be a map. Got `"
sys-state-source "`.")
(u/sym-map sys-state-source))))
(if-let [branch-name (:branch/name sys-state-source)]
(when-not (string? branch-name)
(throw (ex-info (str "Bad :branch/name value in :sys-state-source. "
"Expected a string, got `" branch-name "`.")
(u/sym-map sys-state-source branch-name))))
(if (contains? sys-state-source :temp-branch/db-id)
(let [db-id (:temp-branch/db-id sys-state-source)]
(when-not (or (nil? db-id)
(string? db-id))
(throw (ex-info
(str "Bad :temp-branch/db-id value in :sys-state-source. "
"Expected a string or nil, got `" db-id "`.")
(u/sym-map sys-state-source db-id)))))
(throw (ex-info
(str ":sys-state-source must contain either a :branch/name key "
"or a :temp-branch/db-id key. Got `" sys-state-source "`.")
(u/sym-map sys-state-source))))))
(defn make-capsule-client
[get-server-url opts-on-connect opts-on-disconnect sys-state-schema
sys-state-source *sys-db-info *vc *conn-initialized? *stopped? *token
set-subject-id!]
(when-not sys-state-schema
(throw (ex-info (str "Missing `:sys-state-schema` option in vivo-client "
"constructor.")
{})))
(let [get-credentials (constantly {:subject-id "vivo-client"
:subject-secret ""})
opts {:on-connect (partial <on-connect opts-on-connect sys-state-source
set-subject-id! *conn-initialized? *vc
*stopped? *token)
:on-disconnect (partial on-disconnect opts-on-disconnect
*conn-initialized? set-subject-id!)}]
(cc/client get-server-url get-credentials
u/client-server-protocol :client opts)))
(defn set-handlers! [vc capsule-client *fp->schema]
(cc/set-handler capsule-client :db-changed
(partial u/<handle-db-changed vc))
(cc/set-handler capsule-client :get-schema-pcf
(fn [fp metadata]
(if-let [schema (@*fp->schema fp)]
(l/pcf schema)
(do
(log/error
(str "Could not find PCF for fingerprint `"
fp "`."))
nil)))))
(defn vivo-client [opts]
(let [{:keys [get-server-url
initial-local-state
on-connect
on-disconnect
rpcs
sys-state-source
sys-state-schema]} opts
*local-state (atom initial-local-state)
*sys-db-info (atom {:db-id nil
:db nil})
*conn-initialized? (atom (not get-server-url))
*stopped? (atom false)
*fp->schema (atom {})
*subject-id (atom nil)
*vc (atom nil)
*state-sub-name->info (atom {})
*token (atom nil)
*topic-name->sub-id->cb (atom {})
*next-instance-num (atom 0)
*next-topic-sub-id (atom 0)
on-disconnect* #(when on-disconnect
(on-disconnect @*vc @*local-state))
subscription-state-update-ch (ca/chan (ca/sliding-buffer 1000))
set-subject-id! (fn [subject-id]
(reset! *subject-id subject-id)
(let [update-infos [{:norm-path [:vivo/subject-id]
:op :set}]
db (:db @*sys-db-info)
local-state @*local-state]
(ca/put! subscription-state-update-ch
(u/sym-map db local-state update-infos
subject-id
*state-sub-name->info)))
nil)
_ (when rpcs
(u/check-rpcs rpcs))
path->schema-cache (sr/stockroom 1000)
capsule-client (when get-server-url
(check-sys-state-source sys-state-source)
(make-capsule-client
get-server-url on-connect on-disconnect*
sys-state-schema sys-state-source
*sys-db-info *vc *conn-initialized? *stopped?
*token set-subject-id!))
vc (->VivoClient capsule-client
path->schema-cache
rpcs
set-subject-id!
subscription-state-update-ch
sys-state-schema
sys-state-source
*conn-initialized?
*fp->schema
*local-state
*next-instance-num
*next-topic-sub-id
*state-sub-name->info
*stopped?
*subject-id
*sys-db-info
*token
*topic-name->sub-id->cb)]
(reset! *vc vc)
(state-subscriptions/start-subscription-update-loop!
subscription-state-update-ch)
(when get-server-url
(set-handlers! vc capsule-client *fp->schema))
vc))
|
524b108f2c66106cc0ea4c514ef9f643c86ddc68e65f498efeea678b8eed3c29
|
kuchma19/hi
|
Main.hs
|
# LANGUAGE BlockArguments #
module Main where
import Control.Monad.Cont (liftIO)
import Control.Monad.Trans.Class (lift)
import GHC.Exts (fromList)
import HW3.Action
import HW3.Evaluator (eval)
import HW3.Parser (parse)
import HW3.Pretty (prettyValue, showError)
import Prettyprinter.Internal (line, pretty)
import Prettyprinter.Render.Terminal (putDoc)
import System.Console.Haskeline (InputT, defaultSettings, getInputLine, runInputT)
import Text.Megaparsec.Error (errorBundlePretty)
main :: IO ()
main = runInputT defaultSettings loop
where
loop :: InputT IO ()
loop = do
minput <- getInputLine "hi> "
case minput of
Nothing -> return ()
Just input -> do
case parse input of
Left err -> lift $ putDoc $ pretty $ errorBundlePretty err
Right expr -> do
res <- liftIO $ runHIO (eval expr) (fromList [AllowTime, AllowWrite, AllowRead])
lift $ putDoc case res of
Left err -> showError err <> line
Right expr' -> prettyValue expr' <> line
loop
| null |
https://raw.githubusercontent.com/kuchma19/hi/7d4d06acbd73deb625c48a91de269bebe9c2a3fb/hw3/app/Main.hs
|
haskell
|
# LANGUAGE BlockArguments #
module Main where
import Control.Monad.Cont (liftIO)
import Control.Monad.Trans.Class (lift)
import GHC.Exts (fromList)
import HW3.Action
import HW3.Evaluator (eval)
import HW3.Parser (parse)
import HW3.Pretty (prettyValue, showError)
import Prettyprinter.Internal (line, pretty)
import Prettyprinter.Render.Terminal (putDoc)
import System.Console.Haskeline (InputT, defaultSettings, getInputLine, runInputT)
import Text.Megaparsec.Error (errorBundlePretty)
main :: IO ()
main = runInputT defaultSettings loop
where
loop :: InputT IO ()
loop = do
minput <- getInputLine "hi> "
case minput of
Nothing -> return ()
Just input -> do
case parse input of
Left err -> lift $ putDoc $ pretty $ errorBundlePretty err
Right expr -> do
res <- liftIO $ runHIO (eval expr) (fromList [AllowTime, AllowWrite, AllowRead])
lift $ putDoc case res of
Left err -> showError err <> line
Right expr' -> prettyValue expr' <> line
loop
|
|
952f3e865fa9dc10494833ec2b1125147f833496bf448941db1ed6849ed6bc27
|
danieljharvey/mimsa
|
ModuleHash.hs
|
# LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE GeneralizedNewtypeDeriving #
module Language.Mimsa.Core.Types.Module.ModuleHash where
import qualified Data.Aeson as JSON
import Data.Hashable
import Data.OpenApi
import Data.Text (Text)
import qualified Data.Text as T
import GHC.Generics
import Language.Mimsa.Core.Printer
import Servant.API
-- because of the size of the ints
and JS 's limitations in the browser
-- we JSON encode these as strings
newtype ModuleHash = ModuleHash Text
deriving stock (Eq, Ord, Generic)
deriving newtype (ToParamSchema, ToSchema)
deriving newtype
( JSON.FromJSON,
JSON.FromJSONKey,
JSON.ToJSON,
JSON.ToJSONKey,
FromHttpApiData,
Hashable
)
instance Show ModuleHash where
show (ModuleHash a) = T.unpack a
instance Printer ModuleHash where
prettyPrint (ModuleHash a) = a
| null |
https://raw.githubusercontent.com/danieljharvey/mimsa/d6a5d1933b82268458b1489c1d087e96b0d8e8fc/core/src/Language/Mimsa/Core/Types/Module/ModuleHash.hs
|
haskell
|
because of the size of the ints
we JSON encode these as strings
|
# LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE GeneralizedNewtypeDeriving #
module Language.Mimsa.Core.Types.Module.ModuleHash where
import qualified Data.Aeson as JSON
import Data.Hashable
import Data.OpenApi
import Data.Text (Text)
import qualified Data.Text as T
import GHC.Generics
import Language.Mimsa.Core.Printer
import Servant.API
and JS 's limitations in the browser
newtype ModuleHash = ModuleHash Text
deriving stock (Eq, Ord, Generic)
deriving newtype (ToParamSchema, ToSchema)
deriving newtype
( JSON.FromJSON,
JSON.FromJSONKey,
JSON.ToJSON,
JSON.ToJSONKey,
FromHttpApiData,
Hashable
)
instance Show ModuleHash where
show (ModuleHash a) = T.unpack a
instance Printer ModuleHash where
prettyPrint (ModuleHash a) = a
|
65e2c61163b294264f11a0792f7a8bca3c20ec379613faed506e0264aea0fd98
|
tarides/opam-monorepo
|
test_git.ml
|
module Testable = struct
include Testable
let commit_pointed_by_error =
let equal err err' =
match (err, err') with
| `No_such_ref, `No_such_ref -> true
| `Multiple_such_refs, `Multiple_such_refs -> true
| `Msg s, `Msg s' -> String.equal s s'
| _ -> false
in
let pp fmt = function
| `Msg _ as m -> Rresult.R.pp_msg fmt m
| `No_such_ref -> Format.pp_print_string fmt "`No_such_ref"
| `Multiple_such_refs -> Format.pp_print_string fmt "Multiple_such_refs"
in
Alcotest.testable pp equal
let branch_of_symref_error =
let equal err err' =
match (err, err') with
| `Not_a_symref, `Not_a_symref -> true
| `Msg s, `Msg s' -> String.equal s s'
| _ -> false
in
let pp fmt = function
| `Msg _ as m -> Rresult.R.pp_msg fmt m
| `Not_a_symref -> Format.pp_print_string fmt "`Not_a_symref"
in
Alcotest.testable pp equal
end
module Ls_remote = struct
let test_parse_output_line =
let make_test ~name ~line ~expected () =
let test_name = Printf.sprintf "Ls_remote.parse_output_line: %s" name in
let test_fun () =
let actual = Duniverse_lib.Git.Ls_remote.parse_output_line line in
Alcotest.(check (result (pair string string) Testable.r_msg))
test_name expected actual
in
(test_name, `Quick, test_fun)
in
[
make_test ~name:"Ok" ~line:"12ab refs/tags/v1"
~expected:(Ok ("12ab", "refs/tags/v1"))
();
make_test ~name:"Error" ~line:"12ab refs/tags/v1 something"
~expected:
(Error
(`Msg
"Invalid git ls-remote output line: \"12ab refs/tags/v1 \
something\""))
();
]
let test_commit_pointed_by =
let make_test ~name ~ref ~lines ~expected () =
let test_name = Printf.sprintf "Ls_remote.commit_pointed_by: %s" name in
let test_fun () =
let actual = Duniverse_lib.Git.Ls_remote.commit_pointed_by ~ref lines in
Alcotest.(check (result string Testable.commit_pointed_by_error))
test_name expected actual
in
(test_name, `Quick, test_fun)
in
[
make_test ~name:"Empty output" ~ref:"v1" ~lines:[]
~expected:(Error `No_such_ref) ();
make_test ~name:"Not in output" ~ref:"v1"
~lines:[ "0001 refs/heads/master" ]
~expected:(Error `No_such_ref) ();
make_test ~name:"Invalid output" ~ref:"v1" ~lines:[ "invalid-output" ]
~expected:
(Error (`Msg "Invalid git ls-remote output line: \"invalid-output\""))
();
make_test ~name:"Regular repo" ~ref:"v1"
~lines:[ "0001 refs/heads/master"; "0002 refs/tags/v1" ]
~expected:(Ok "0002") ();
make_test ~name:"Repo with packed refs" ~ref:"v1"
~lines:
[
"0001 refs/heads/master";
"0002 refs/tags/v1";
"0003 refs/tags/v1^{}";
]
~expected:(Ok "0003") ();
make_test ~name:"Order doesn't matter" ~ref:"v1"
~lines:
[
"0003 refs/tags/v1^{}";
"0001 refs/heads/master";
"0002 refs/tags/v1";
]
~expected:(Ok "0003") ();
make_test ~name:"Works with branches" ~ref:"some-branch"
~lines:[ "0001 refs/heads/master"; "0002 refs/heads/some-branch" ]
~expected:(Ok "0002") ();
make_test ~name:"Points to several commits" ~ref:"abc"
~lines:[ "001 refs/heads/abc"; "002 refs/tags/abc" ]
~expected:(Error `Multiple_such_refs) ();
make_test ~name:"Points to several commits (with packed-refs)" ~ref:"abc"
~lines:
[
"001 refs/heads/abc";
"002 refs/heads/abc^{}";
"003 refs/tags/abc";
"004 refs/tags/abc^{}";
]
~expected:(Error `Multiple_such_refs) ();
make_test ~name:"Empty output" ~ref:"abc" ~lines:[ "" ]
~expected:(Error `No_such_ref) ();
make_test ~name:"Not branch or tag" ~ref:"abc"
~lines:
[
"001 refs/heads/master";
"002 refs/import/tags/abc";
"003 refs/tags/abc";
]
~expected:(Ok "003") ();
make_test ~name:"Same suffix" ~ref:"abc"
~lines:[ "001 refs/heads/xabc" ]
~expected:(Error `No_such_ref) ();
make_test ~name:"Ref is a commit" ~ref:"000456"
~lines:[ "00017f refs/heads/master"; "000456 refs/heads/abc" ]
~expected:(Ok "000456") ();
make_test ~name:"Ref looks like a commit"
~ref:"7af9de1c4c468d8fd0f2870b98355803bcfd76f7"
~lines:[ "000000 refs/heads/master" ]
~expected:(Ok "7af9de1c4c468d8fd0f2870b98355803bcfd76f7") ();
]
let test_branch_of_symref =
let make_test ~name ~symref ~lines ~expected () =
let test_name = Printf.sprintf "Ls_remote.branch_of_symref: %s" name in
let test_fun () =
let actual =
Duniverse_lib.Git.Ls_remote.branch_of_symref ~symref lines
in
Alcotest.(check (result string Testable.branch_of_symref_error))
test_name expected actual
in
(test_name, `Quick, test_fun)
in
[
make_test ~name:"Empty output" ~symref:"abc" ~lines:[ "" ]
~expected:(Error `Not_a_symref) ();
make_test ~name:"No output" ~symref:"abc" ~lines:[]
~expected:(Error `Not_a_symref) ();
make_test ~name:"Typical output" ~symref:"HEAD"
~lines:[ "ref: refs/heads/master HEAD"; "0000 HEAD" ]
~expected:(Ok "master") ();
make_test ~name:"Another typical output" ~symref:"HEAD"
~lines:[ "ref: refs/heads/main HEAD"; "0001 HEAD" ]
~expected:(Ok "main") ();
make_test ~name:"Local project" ~symref:"HEAD"
~lines:
[
"ref: refs/heads/mirage-4 HEAD";
"0002 HEAD";
"ref: refs/remotes/origin/master refs/remotes/origin/HEAD";
"0003 refs/remotes/origin/HEAD";
]
~expected:(Ok "mirage-4") ();
make_test ~name:"Error when HEAD points towards multiple branches"
~symref:"HEAD"
~lines:
[
"ref: refs/heads/master HEAD";
"ref: refs/heads/main HEAD";
"ref: refs/heads/trunk HEAD";
"0004 HEAD";
]
~expected:
(Error
(`Msg
"Invalid `git ls-remote --symref` output. Too many lines \
starting by `ref:`."))
();
make_test ~name:"Error when symref doesn't point to a branch"
~symref:"symref"
~lines:[ "ref: refs/tags/v0.1 symref"; "0005 symref" ]
~expected:
(Error
(`Msg
"Invalid `git ls-remote --symref` output. Failed to extract \
branch from ref `refs/tags/v0.1`."))
();
]
end
let suite =
( "Git",
Ls_remote.test_parse_output_line @ Ls_remote.test_commit_pointed_by
@ Ls_remote.test_branch_of_symref )
| null |
https://raw.githubusercontent.com/tarides/opam-monorepo/9262e7f71d749520b7e046fbd90a4732a43866e9/test/lib/test_git.ml
|
ocaml
|
module Testable = struct
include Testable
let commit_pointed_by_error =
let equal err err' =
match (err, err') with
| `No_such_ref, `No_such_ref -> true
| `Multiple_such_refs, `Multiple_such_refs -> true
| `Msg s, `Msg s' -> String.equal s s'
| _ -> false
in
let pp fmt = function
| `Msg _ as m -> Rresult.R.pp_msg fmt m
| `No_such_ref -> Format.pp_print_string fmt "`No_such_ref"
| `Multiple_such_refs -> Format.pp_print_string fmt "Multiple_such_refs"
in
Alcotest.testable pp equal
let branch_of_symref_error =
let equal err err' =
match (err, err') with
| `Not_a_symref, `Not_a_symref -> true
| `Msg s, `Msg s' -> String.equal s s'
| _ -> false
in
let pp fmt = function
| `Msg _ as m -> Rresult.R.pp_msg fmt m
| `Not_a_symref -> Format.pp_print_string fmt "`Not_a_symref"
in
Alcotest.testable pp equal
end
module Ls_remote = struct
let test_parse_output_line =
let make_test ~name ~line ~expected () =
let test_name = Printf.sprintf "Ls_remote.parse_output_line: %s" name in
let test_fun () =
let actual = Duniverse_lib.Git.Ls_remote.parse_output_line line in
Alcotest.(check (result (pair string string) Testable.r_msg))
test_name expected actual
in
(test_name, `Quick, test_fun)
in
[
make_test ~name:"Ok" ~line:"12ab refs/tags/v1"
~expected:(Ok ("12ab", "refs/tags/v1"))
();
make_test ~name:"Error" ~line:"12ab refs/tags/v1 something"
~expected:
(Error
(`Msg
"Invalid git ls-remote output line: \"12ab refs/tags/v1 \
something\""))
();
]
let test_commit_pointed_by =
let make_test ~name ~ref ~lines ~expected () =
let test_name = Printf.sprintf "Ls_remote.commit_pointed_by: %s" name in
let test_fun () =
let actual = Duniverse_lib.Git.Ls_remote.commit_pointed_by ~ref lines in
Alcotest.(check (result string Testable.commit_pointed_by_error))
test_name expected actual
in
(test_name, `Quick, test_fun)
in
[
make_test ~name:"Empty output" ~ref:"v1" ~lines:[]
~expected:(Error `No_such_ref) ();
make_test ~name:"Not in output" ~ref:"v1"
~lines:[ "0001 refs/heads/master" ]
~expected:(Error `No_such_ref) ();
make_test ~name:"Invalid output" ~ref:"v1" ~lines:[ "invalid-output" ]
~expected:
(Error (`Msg "Invalid git ls-remote output line: \"invalid-output\""))
();
make_test ~name:"Regular repo" ~ref:"v1"
~lines:[ "0001 refs/heads/master"; "0002 refs/tags/v1" ]
~expected:(Ok "0002") ();
make_test ~name:"Repo with packed refs" ~ref:"v1"
~lines:
[
"0001 refs/heads/master";
"0002 refs/tags/v1";
"0003 refs/tags/v1^{}";
]
~expected:(Ok "0003") ();
make_test ~name:"Order doesn't matter" ~ref:"v1"
~lines:
[
"0003 refs/tags/v1^{}";
"0001 refs/heads/master";
"0002 refs/tags/v1";
]
~expected:(Ok "0003") ();
make_test ~name:"Works with branches" ~ref:"some-branch"
~lines:[ "0001 refs/heads/master"; "0002 refs/heads/some-branch" ]
~expected:(Ok "0002") ();
make_test ~name:"Points to several commits" ~ref:"abc"
~lines:[ "001 refs/heads/abc"; "002 refs/tags/abc" ]
~expected:(Error `Multiple_such_refs) ();
make_test ~name:"Points to several commits (with packed-refs)" ~ref:"abc"
~lines:
[
"001 refs/heads/abc";
"002 refs/heads/abc^{}";
"003 refs/tags/abc";
"004 refs/tags/abc^{}";
]
~expected:(Error `Multiple_such_refs) ();
make_test ~name:"Empty output" ~ref:"abc" ~lines:[ "" ]
~expected:(Error `No_such_ref) ();
make_test ~name:"Not branch or tag" ~ref:"abc"
~lines:
[
"001 refs/heads/master";
"002 refs/import/tags/abc";
"003 refs/tags/abc";
]
~expected:(Ok "003") ();
make_test ~name:"Same suffix" ~ref:"abc"
~lines:[ "001 refs/heads/xabc" ]
~expected:(Error `No_such_ref) ();
make_test ~name:"Ref is a commit" ~ref:"000456"
~lines:[ "00017f refs/heads/master"; "000456 refs/heads/abc" ]
~expected:(Ok "000456") ();
make_test ~name:"Ref looks like a commit"
~ref:"7af9de1c4c468d8fd0f2870b98355803bcfd76f7"
~lines:[ "000000 refs/heads/master" ]
~expected:(Ok "7af9de1c4c468d8fd0f2870b98355803bcfd76f7") ();
]
let test_branch_of_symref =
let make_test ~name ~symref ~lines ~expected () =
let test_name = Printf.sprintf "Ls_remote.branch_of_symref: %s" name in
let test_fun () =
let actual =
Duniverse_lib.Git.Ls_remote.branch_of_symref ~symref lines
in
Alcotest.(check (result string Testable.branch_of_symref_error))
test_name expected actual
in
(test_name, `Quick, test_fun)
in
[
make_test ~name:"Empty output" ~symref:"abc" ~lines:[ "" ]
~expected:(Error `Not_a_symref) ();
make_test ~name:"No output" ~symref:"abc" ~lines:[]
~expected:(Error `Not_a_symref) ();
make_test ~name:"Typical output" ~symref:"HEAD"
~lines:[ "ref: refs/heads/master HEAD"; "0000 HEAD" ]
~expected:(Ok "master") ();
make_test ~name:"Another typical output" ~symref:"HEAD"
~lines:[ "ref: refs/heads/main HEAD"; "0001 HEAD" ]
~expected:(Ok "main") ();
make_test ~name:"Local project" ~symref:"HEAD"
~lines:
[
"ref: refs/heads/mirage-4 HEAD";
"0002 HEAD";
"ref: refs/remotes/origin/master refs/remotes/origin/HEAD";
"0003 refs/remotes/origin/HEAD";
]
~expected:(Ok "mirage-4") ();
make_test ~name:"Error when HEAD points towards multiple branches"
~symref:"HEAD"
~lines:
[
"ref: refs/heads/master HEAD";
"ref: refs/heads/main HEAD";
"ref: refs/heads/trunk HEAD";
"0004 HEAD";
]
~expected:
(Error
(`Msg
"Invalid `git ls-remote --symref` output. Too many lines \
starting by `ref:`."))
();
make_test ~name:"Error when symref doesn't point to a branch"
~symref:"symref"
~lines:[ "ref: refs/tags/v0.1 symref"; "0005 symref" ]
~expected:
(Error
(`Msg
"Invalid `git ls-remote --symref` output. Failed to extract \
branch from ref `refs/tags/v0.1`."))
();
]
end
let suite =
( "Git",
Ls_remote.test_parse_output_line @ Ls_remote.test_commit_pointed_by
@ Ls_remote.test_branch_of_symref )
|
|
1b51930b060d24834a105e8bd40913b4fb06c5922bc32a4a46963c96e666c907
|
logicblocks/cartus
|
project.clj
|
(defproject io.logicblocks/cartus.test "0.1.18-RC4"
:description "A test backend for cartus."
:plugins [[lein-modules "0.3.11"]]
:dependencies [[org.clojure/math.combinatorics "_"]
[nubank/matcher-combinators "_"]
[io.logicblocks/cartus.core :version]])
| null |
https://raw.githubusercontent.com/logicblocks/cartus/e8052399ec6e47aad52d3251ce7dd74a72d350ab/test/project.clj
|
clojure
|
(defproject io.logicblocks/cartus.test "0.1.18-RC4"
:description "A test backend for cartus."
:plugins [[lein-modules "0.3.11"]]
:dependencies [[org.clojure/math.combinatorics "_"]
[nubank/matcher-combinators "_"]
[io.logicblocks/cartus.core :version]])
|
|
0dbbfd0980e2f021b0b72d51ca3875187b7323adf26bc430302fac82a38f8738
|
unclechu/xlib-keys-hack
|
KeysActions.hs
|
Author :
License : -keys-hack/master/LICENSE
{-# LANGUAGE ScopedTypeVariables, DataKinds #-}
module Process.KeysActions
( processKeysActions
) where
import "base" Data.Proxy (Proxy (Proxy))
import "base" Control.Concurrent.Chan (readChan)
import "base" Control.Monad (unless, forever)
import "X11" Graphics.X11.Types (type KeyCode)
import "X11" Graphics.X11.Xlib (type Display)
-- local imports
import Utils (dieWith)
import Utils.Sugar ((.>))
import Bindings.MoreXlib (getLeds)
import Bindings.XTest (fakeKeyCodeEvent)
import Actions ( ActionType(Single, Sequence)
, KeyAction ( KeyCodePress
, KeyCodeRelease
, TurnCapsLock
, ResetKeyboardLayout
)
, seqHead
)
import Bindings.Xkb (xkbSetGroup)
import State (type CrossThreadVars, keysActionsChan)
import qualified State
import Keys (KeyName (CapsLockKey))
import Options (type Options, defaultKeyboardLayout)
processKeysActions
:: CrossThreadVars
-> Options
-> (Proxy 'CapsLockKey, KeyCode)
^ " KeyCode " of real Caps Lock key ( it must be not remapped ! )
-> Display
-> IO ()
processKeysActions ctVars opts (Proxy, capsLockKeyCode) dpy = forever $ do
(action :: ActionType KeyAction) <- readChan $ keysActionsChan ctVars
flip f action $ \case
KeyCodePress keyCode -> press keyCode
KeyCodeRelease keyCode -> release keyCode
ResetKeyboardLayout ->
xkbSetGroup dpy (fromIntegral $ defaultKeyboardLayout opts) >>=
(`unless` dieWith "xkbSetGroup error")
TurnCapsLock x ->
getLeds dpy >>= State.capsLockLed .> (== x) .> (`unless` toggleCapsLock)
where f :: (KeyAction -> IO ()) -> ActionType KeyAction -> IO ()
f m (Actions.Single a) = m a
f _ (Actions.Sequence []) = return () -- TODO NonEmpty
f m (Actions.seqHead -> (x, xs)) = m x >> f m xs
press keyCode = fakeKeyCodeEvent dpy keyCode True
release keyCode = fakeKeyCodeEvent dpy keyCode False
toggleCapsLock = press capsLockKeyCode >> release capsLockKeyCode
| null |
https://raw.githubusercontent.com/unclechu/xlib-keys-hack/33b49a9b1fc4bc87bdb95e2bb632a312ec2ebad0/src/Process/KeysActions.hs
|
haskell
|
# LANGUAGE ScopedTypeVariables, DataKinds #
local imports
TODO NonEmpty
|
Author :
License : -keys-hack/master/LICENSE
module Process.KeysActions
( processKeysActions
) where
import "base" Data.Proxy (Proxy (Proxy))
import "base" Control.Concurrent.Chan (readChan)
import "base" Control.Monad (unless, forever)
import "X11" Graphics.X11.Types (type KeyCode)
import "X11" Graphics.X11.Xlib (type Display)
import Utils (dieWith)
import Utils.Sugar ((.>))
import Bindings.MoreXlib (getLeds)
import Bindings.XTest (fakeKeyCodeEvent)
import Actions ( ActionType(Single, Sequence)
, KeyAction ( KeyCodePress
, KeyCodeRelease
, TurnCapsLock
, ResetKeyboardLayout
)
, seqHead
)
import Bindings.Xkb (xkbSetGroup)
import State (type CrossThreadVars, keysActionsChan)
import qualified State
import Keys (KeyName (CapsLockKey))
import Options (type Options, defaultKeyboardLayout)
processKeysActions
:: CrossThreadVars
-> Options
-> (Proxy 'CapsLockKey, KeyCode)
^ " KeyCode " of real Caps Lock key ( it must be not remapped ! )
-> Display
-> IO ()
processKeysActions ctVars opts (Proxy, capsLockKeyCode) dpy = forever $ do
(action :: ActionType KeyAction) <- readChan $ keysActionsChan ctVars
flip f action $ \case
KeyCodePress keyCode -> press keyCode
KeyCodeRelease keyCode -> release keyCode
ResetKeyboardLayout ->
xkbSetGroup dpy (fromIntegral $ defaultKeyboardLayout opts) >>=
(`unless` dieWith "xkbSetGroup error")
TurnCapsLock x ->
getLeds dpy >>= State.capsLockLed .> (== x) .> (`unless` toggleCapsLock)
where f :: (KeyAction -> IO ()) -> ActionType KeyAction -> IO ()
f m (Actions.Single a) = m a
f m (Actions.seqHead -> (x, xs)) = m x >> f m xs
press keyCode = fakeKeyCodeEvent dpy keyCode True
release keyCode = fakeKeyCodeEvent dpy keyCode False
toggleCapsLock = press capsLockKeyCode >> release capsLockKeyCode
|
2122be3712a3aa3a110e510439bfd93cd373abbcbddf5850a430fcdb5992566d
|
dnaeon/cl-jingle
|
cli-create-command.lisp
|
Copyright ( c ) 2022 Nikolov < >
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
1 . Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer
;; in this position and unchanged.
2 . Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;;
THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S ) ` ` AS IS '' AND ANY EXPRESS OR
;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
;; IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT
NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :jingle.demo.cli)
(defun create/handler (cmd)
"The handler for the `create' command"
(let* ((args (clingon:command-arguments cmd))
(client (make-api-client-from-opts cmd)))
(unless args
(error "Must specify product names to create"))
(display-products-table (mapcar (lambda (name)
(jingle.demo.client:create-new-product client name))
args))))
(defun create/command ()
"Returns the `create' command"
(clingon:make-command :name "create"
:usage "[name] ..."
:description "create new products"
:handler #'create/handler))
| null |
https://raw.githubusercontent.com/dnaeon/cl-jingle/b8edf9a9caccffa599262caf6a77a7b3f542bd6f/demo/src/cli-create-command.lisp
|
lisp
|
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer
in this position and unchanged.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
LOSS OF USE ,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
Copyright ( c ) 2022 Nikolov < >
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S ) ` ` AS IS '' AND ANY EXPRESS OR
INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
(in-package :jingle.demo.cli)
(defun create/handler (cmd)
"The handler for the `create' command"
(let* ((args (clingon:command-arguments cmd))
(client (make-api-client-from-opts cmd)))
(unless args
(error "Must specify product names to create"))
(display-products-table (mapcar (lambda (name)
(jingle.demo.client:create-new-product client name))
args))))
(defun create/command ()
"Returns the `create' command"
(clingon:make-command :name "create"
:usage "[name] ..."
:description "create new products"
:handler #'create/handler))
|
5a0c50e808ba013268325faff887108623bd018427a5090ab157fcd21bfe66d6
|
chef/chef-server
|
chef_objects_test_utils.erl
|
-*- erlang - indent - level : 4;indent - tabs - mode : nil ; fill - column : 92-*-
%% ex: ts=4 sw=4 et
@author < >
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_objects_test_utils).
-export([
mock/1,
mock/2,
unmock/1,
bcrypt_setup/0,
bcrypt_cleanup/1,
keygen_setup/0,
keygen_cleanup/1,
validate_modules/1,
versioned_desc/2,
make_deprecated_tests/1,
make_non_deprecated_tests/1,
make_all_versions_tests/1,
make_versioned_test_range/3,
read_file/1
]).
-include_lib("eunit/include/eunit.hrl").
-include("server_api_version.hrl").
%% helper functions for configuring mocking.
%%@doc setup mocking for a list of modules. This would normally be
called in the setup/0 method . You can optionally pass in a list of
%% meck options. See meck docs for details at
%% #new-2
mock(Modules) ->
mock(Modules, []).
mock(Modules, Opts) ->
[ meck:new(M, Opts) || M <- Modules ].
%%@doc Unload a list of mocked modules
unmock(Modules) ->
[ meck:unload(M) || M <-Modules ].
@doc Validate the state of the mock modules and raise
%% an eunit error if the modules have not been used according to
%% expectations
validate_modules(Modules) ->
[?assert(meck:validate(M)) || M <- Modules].
bcrypt_setup() ->
application:set_env(bcrypt, default_log_rounds, 4),
[ ensure_start(App) || App <- [crypto, bcrypt] ],
ok.
bcrypt_cleanup(_) ->
error_logger:tty(false),
application:stop(bcrypt),
error_logger:tty(true).
keygen_setup() ->
error_logger:tty(false),
[application:set_env(chef_authn, Field, Value) ||
{Field, Value} <- [ {keygen_cache_size, 4}, {keygen_start_size, 4},
{keygen_timeout, 1000}, {keygen_size, 1024}] ],
chef_keygen_worker_sup:start_link(),
chef_keygen_cache:start_link().
keygen_cleanup(_) ->
error_logger:tty(true).
ensure_start(App) ->
case application:start(App) of
ok ->
ok;
{error, {already_started, App}} ->
ok;
Error ->
error(Error)
end.
versioned_desc(Version, Desc) ->
iolist_to_binary( ["[v", integer_to_list(Version), "] ", Desc] ).
make_non_deprecated_tests(Generator) ->
make_versioned_test_range(?API_DEPRECATED_VER + 1, ?API_MAX_VER, Generator).
make_deprecated_tests(Generator) ->
T2 = make_versioned_test_range(?API_MIN_VER, ?API_DEPRECATED_VER, Generator),
T2.
make_all_versions_tests(Generator) ->
make_versioned_test_range(?API_MIN_VER, ?API_MAX_VER, Generator).
make_versioned_test_range(Min, Max, Generator) ->
[Generator(Version) || Version <- lists:seq(Min, Max)].
read_file(File) ->
case read_file(app, File) of
{error, enoent} ->
read_file(test, File);
{ok, Bin} ->
{ok, Bin}
end.
read_file(app, File) -> %% Rebar3
file:read_file(filename:join([".", "apps", "chef_objects", "test", File]));
read_file(test, File) -> %% Rebar2
file:read_file(filename:join(["..", "test", File])).
| null |
https://raw.githubusercontent.com/chef/chef-server/6d31841ecd73d984d819244add7ad6ebac284323/src/oc_erchef/apps/chef_objects/test/chef_objects_test_utils.erl
|
erlang
|
ex: ts=4 sw=4 et
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.
helper functions for configuring mocking.
@doc setup mocking for a list of modules. This would normally be
meck options. See meck docs for details at
#new-2
@doc Unload a list of mocked modules
an eunit error if the modules have not been used according to
expectations
Rebar3
Rebar2
|
-*- erlang - indent - level : 4;indent - tabs - mode : nil ; fill - column : 92-*-
@author < >
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_objects_test_utils).
-export([
mock/1,
mock/2,
unmock/1,
bcrypt_setup/0,
bcrypt_cleanup/1,
keygen_setup/0,
keygen_cleanup/1,
validate_modules/1,
versioned_desc/2,
make_deprecated_tests/1,
make_non_deprecated_tests/1,
make_all_versions_tests/1,
make_versioned_test_range/3,
read_file/1
]).
-include_lib("eunit/include/eunit.hrl").
-include("server_api_version.hrl").
called in the setup/0 method . You can optionally pass in a list of
mock(Modules) ->
mock(Modules, []).
mock(Modules, Opts) ->
[ meck:new(M, Opts) || M <- Modules ].
unmock(Modules) ->
[ meck:unload(M) || M <-Modules ].
@doc Validate the state of the mock modules and raise
validate_modules(Modules) ->
[?assert(meck:validate(M)) || M <- Modules].
bcrypt_setup() ->
application:set_env(bcrypt, default_log_rounds, 4),
[ ensure_start(App) || App <- [crypto, bcrypt] ],
ok.
bcrypt_cleanup(_) ->
error_logger:tty(false),
application:stop(bcrypt),
error_logger:tty(true).
keygen_setup() ->
error_logger:tty(false),
[application:set_env(chef_authn, Field, Value) ||
{Field, Value} <- [ {keygen_cache_size, 4}, {keygen_start_size, 4},
{keygen_timeout, 1000}, {keygen_size, 1024}] ],
chef_keygen_worker_sup:start_link(),
chef_keygen_cache:start_link().
keygen_cleanup(_) ->
error_logger:tty(true).
ensure_start(App) ->
case application:start(App) of
ok ->
ok;
{error, {already_started, App}} ->
ok;
Error ->
error(Error)
end.
versioned_desc(Version, Desc) ->
iolist_to_binary( ["[v", integer_to_list(Version), "] ", Desc] ).
make_non_deprecated_tests(Generator) ->
make_versioned_test_range(?API_DEPRECATED_VER + 1, ?API_MAX_VER, Generator).
make_deprecated_tests(Generator) ->
T2 = make_versioned_test_range(?API_MIN_VER, ?API_DEPRECATED_VER, Generator),
T2.
make_all_versions_tests(Generator) ->
make_versioned_test_range(?API_MIN_VER, ?API_MAX_VER, Generator).
make_versioned_test_range(Min, Max, Generator) ->
[Generator(Version) || Version <- lists:seq(Min, Max)].
read_file(File) ->
case read_file(app, File) of
{error, enoent} ->
read_file(test, File);
{ok, Bin} ->
{ok, Bin}
end.
file:read_file(filename:join([".", "apps", "chef_objects", "test", File]));
file:read_file(filename:join(["..", "test", File])).
|
0ee48b2ff73bfcffc5e9d2ef168641f9907197cc628c8b234bface9ef996ccbe
|
juhp/koji-tool
|
Builds.hs
|
# LANGUAGE BangPatterns , CPP #
SPDX - License - Identifier : BSD-3 - Clause
module Builds (
BuildReq(..),
Details(..),
buildsCmd,
parseBuildState,
fedoraKojiHub,
kojiBuildTypes,
latestCmd
)
where
import Control.Monad.Extra
import Data.Char (isDigit, toUpper)
import Data.List.Extra
import Data.Maybe
import Data.RPM.NVR
import Data.Time.Clock
import Data.Time.LocalTime
import Distribution.Koji
import Distribution.Koji.API
import SimpleCmd
import Text.Pretty.Simple
import Common
import Install
import qualified Tasks
import Time
import User
import Utils (buildOutputURL)
data BuildReq = BuildBuild String | BuildPackage String
| BuildQuery | BuildPattern String
deriving Eq
getTimedate :: Tasks.BeforeAfter -> String
getTimedate (Tasks.Before s) = s
getTimedate (Tasks.After s) = s
capitalize :: String -> String
capitalize "" = ""
capitalize (h:t) = toUpper h : t
data Details = DetailDefault | Detailed | DetailedTasks
deriving Eq
FIXME add --install
buildsCmd :: Maybe String -> Maybe UserOpt -> Int -> [BuildState]
-> Maybe Tasks.BeforeAfter -> Maybe String -> Details
-> Maybe Tasks.Select -> Bool -> BuildReq -> IO ()
buildsCmd mhub museropt limit !states mdate mtype details minstall debug buildreq = do
when (hub /= fedoraKojiHub && museropt == Just UserSelf) $
error' "--mine currently only works with Fedora Koji: use --user instead"
tz <- getCurrentTimeZone
case buildreq of
BuildBuild bld -> do
when (isJust mdate) $
error' "cannot use buildinfo together with timedate"
let bldinfo = if all isDigit bld
then InfoID (read bld)
else InfoString bld
mbld <- getBuild hub bldinfo
whenJust (mbld >>= maybeBuildResult) $ printBuild hub tz details minstall
BuildPackage pkg -> do
when (head pkg == '-') $
error' $ "bad combination: not a package: " ++ pkg
when (isJust mdate) $
error' "cannot use --package together with timedate"
mpkgid <- getPackageID hub pkg
case mpkgid of
Nothing -> error' $ "no package id found for " ++ pkg
Just pkgid -> do
query <- setupQuery
let fullquery = [("packageID", ValueInt pkgid),
commonBuildQueryOptions limit] ++ query
when debug $ print fullquery
builds <- listBuilds hub fullquery
when debug $ mapM_ pPrintCompact builds
if details /= DetailDefault || length builds == 1
then mapM_ (printBuild hub tz details minstall) $ mapMaybe maybeBuildResult builds
else mapM_ putStrLn $ mapMaybe (shortBuildResult tz) builds
_ -> do
query <- setupQuery
let fullquery = query ++ [commonBuildQueryOptions limit]
when debug $ print fullquery
builds <- listBuilds hub fullquery
when debug $ mapM_ pPrintCompact builds
if details /= DetailDefault || length builds == 1
then mapM_ (printBuild hub tz details minstall) $ mapMaybe maybeBuildResult builds
else mapM_ putStrLn $ mapMaybe (shortBuildResult tz) builds
where
hub = maybe fedoraKojiHub hubURL mhub
shortBuildResult :: TimeZone -> Struct -> Maybe String
shortBuildResult tz bld = do
nvr <- lookupStruct "nvr" bld
state <- readBuildState <$> lookupStruct "state" bld
let date =
case lookupTimes bld of
Nothing -> ""
Just (start,mend) ->
compactZonedTime tz $ fromMaybe start mend
mbid = lookupStruct "build_id" bld
return $ nvr +-+ show state +-+ date +-+ maybe "" (buildinfoUrl hub) mbid
setupQuery = do
mdatestring <-
case mdate of
Nothing -> return Nothing
Just date -> Just <$> cmd "date" ["+%F %T%z", "--date=" ++ dateString date]
-- FIXME better output including user
whenJust mdatestring $ \date ->
putStrLn $ maybe "" show mdate +-+ date
mowner <- maybeGetKojiUser hub museropt
return $
[("complete" ++ (capitalize . show) date, ValueString datestring) | Just date <- [mdate], Just datestring <- [mdatestring]]
++ [("userID", ValueInt (getID owner)) | Just owner <- [mowner]]
++ [("state", ValueArray (map buildStateToValue states)) | notNull states]
++ [("type", ValueString typ) | Just typ <- [mtype]]
++ case buildreq of
BuildPattern pat -> [("pattern", ValueString pat)]
_ -> []
dateString :: Tasks.BeforeAfter -> String
-- make time refer to past not future
dateString beforeAfter =
let timedate = getTimedate beforeAfter
in case words timedate of
[t] | t `elem` ["hour", "day", "week", "month", "year"] ->
"last " ++ t
[t] | t `elem` ["today", "yesterday"] ->
t ++ " 00:00"
[t] | any (lower t `isPrefixOf`) ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] ->
"last " ++ t ++ " 00:00"
[n,_unit] | all isDigit n -> timedate ++ " ago"
_ -> timedate
pPrintCompact =
#if MIN_VERSION_pretty_simple(4,0,0)
pPrintOpt CheckColorTty
(defaultOutputOptionsDarkBg {outputOptionsCompact = True,
outputOptionsCompactParens = True})
#else
pPrint
#endif
buildinfoUrl :: String -> Int -> String
buildinfoUrl hub bid =
webUrl hub ++ "/buildinfo?buildID=" ++ show bid
data BuildResult =
BuildResult {buildNVR :: NVR,
buildState :: BuildState,
_buildId :: Int,
mbuildTaskId :: Maybe Int,
_buildStartTime :: UTCTime,
mbuildEndTime :: Maybe UTCTime
}
maybeBuildResult :: Struct -> Maybe BuildResult
maybeBuildResult st = do
(start,mend) <- lookupTimes st
buildid <- lookupStruct "build_id" st
-- buildContainer has no task_id
let mtaskid = lookupStruct "task_id" st
state <- getBuildState st
nvr <- lookupStruct "nvr" st >>= maybeNVR
return $
BuildResult nvr state buildid mtaskid start mend
printBuild :: String -> TimeZone -> Details -> Maybe Tasks.Select
-> BuildResult -> IO ()
printBuild hub tz details minstall build = do
putStrLn ""
let mendtime = mbuildEndTime build
time <- maybe getCurrentTime return mendtime
(mapM_ putStrLn . formatBuildResult hub (isJust mendtime) tz) (build {mbuildEndTime = Just time})
when (buildState build == BuildComplete) $
putStrLn $ buildOutputURL hub $ buildNVR build
whenJust (mbuildTaskId build) $ \taskid -> do
when (details == DetailedTasks) $ do
putStrLn ""
Tasks.tasksCmd (Just hub) Nothing 7 [] [] Nothing Nothing False False Nothing False Nothing (Tasks.Parent taskid)
whenJust minstall $ \installopts -> do
putStrLn ""
installCmd False False No (Just hub) Nothing False False False Nothing ExistingUpdate Nothing installopts Nothing ReqName [show taskid]
formatBuildResult :: String -> Bool -> TimeZone -> BuildResult -> [String]
formatBuildResult hub ended tz (BuildResult nvr state buildid mtaskid start mendtime) =
[ showNVR nvr +-+ show state
, buildinfoUrl hub buildid]
++ [Tasks.taskinfoUrl hub taskid | Just taskid <- [mtaskid]]
++ [formatLocalTime True tz start]
++
case mendtime of
Nothing -> []
Just end ->
[formatLocalTime False tz end | ended]
#if MIN_VERSION_time(1,9,1)
++
let dur = diffUTCTime end start
in [(if not ended then "current " else "") ++ "duration: " ++ renderDuration False dur]
#endif
#if !MIN_VERSION_koji(0,0,3)
buildStateToValue :: BuildState -> Value
buildStateToValue = ValueInt . fromEnum
parseBuildState :: String -> BuildState
parseBuildState s =
case lower s of
"building" -> BuildBuilding
"complete" -> BuildComplete
"deleted" -> BuildDeleted
"fail" -> BuildFailed
"failed" -> BuildFailed
"cancel" -> BuildCanceled
"canceled" -> BuildCanceled
_ -> error' $! "unknown build state: " ++ s
#endif
getBuildState :: Struct -> Maybe BuildState
getBuildState st = readBuildState <$> lookup "state" st
kojiBuildTypes :: [String]
kojiBuildTypes = ["all", "image", "maven", "module", "rpm", "win"]
latestCmd :: Maybe String -> Bool -> String -> String -> IO ()
latestCmd mhub debug tag pkg = do
let hub = maybe fedoraKojiHub hubURL mhub
mbld <- kojiLatestBuild hub tag pkg
when debug $ print mbld
tz <- getCurrentTimeZone
whenJust (mbld >>= maybeBuildResult) $ printBuild hub tz Detailed Nothing
| null |
https://raw.githubusercontent.com/juhp/koji-tool/1878b6558546c19120d5eae077d6bf4580250074/src/Builds.hs
|
haskell
|
install
FIXME better output including user
make time refer to past not future
buildContainer has no task_id
|
# LANGUAGE BangPatterns , CPP #
SPDX - License - Identifier : BSD-3 - Clause
module Builds (
BuildReq(..),
Details(..),
buildsCmd,
parseBuildState,
fedoraKojiHub,
kojiBuildTypes,
latestCmd
)
where
import Control.Monad.Extra
import Data.Char (isDigit, toUpper)
import Data.List.Extra
import Data.Maybe
import Data.RPM.NVR
import Data.Time.Clock
import Data.Time.LocalTime
import Distribution.Koji
import Distribution.Koji.API
import SimpleCmd
import Text.Pretty.Simple
import Common
import Install
import qualified Tasks
import Time
import User
import Utils (buildOutputURL)
data BuildReq = BuildBuild String | BuildPackage String
| BuildQuery | BuildPattern String
deriving Eq
getTimedate :: Tasks.BeforeAfter -> String
getTimedate (Tasks.Before s) = s
getTimedate (Tasks.After s) = s
capitalize :: String -> String
capitalize "" = ""
capitalize (h:t) = toUpper h : t
data Details = DetailDefault | Detailed | DetailedTasks
deriving Eq
buildsCmd :: Maybe String -> Maybe UserOpt -> Int -> [BuildState]
-> Maybe Tasks.BeforeAfter -> Maybe String -> Details
-> Maybe Tasks.Select -> Bool -> BuildReq -> IO ()
buildsCmd mhub museropt limit !states mdate mtype details minstall debug buildreq = do
when (hub /= fedoraKojiHub && museropt == Just UserSelf) $
error' "--mine currently only works with Fedora Koji: use --user instead"
tz <- getCurrentTimeZone
case buildreq of
BuildBuild bld -> do
when (isJust mdate) $
error' "cannot use buildinfo together with timedate"
let bldinfo = if all isDigit bld
then InfoID (read bld)
else InfoString bld
mbld <- getBuild hub bldinfo
whenJust (mbld >>= maybeBuildResult) $ printBuild hub tz details minstall
BuildPackage pkg -> do
when (head pkg == '-') $
error' $ "bad combination: not a package: " ++ pkg
when (isJust mdate) $
error' "cannot use --package together with timedate"
mpkgid <- getPackageID hub pkg
case mpkgid of
Nothing -> error' $ "no package id found for " ++ pkg
Just pkgid -> do
query <- setupQuery
let fullquery = [("packageID", ValueInt pkgid),
commonBuildQueryOptions limit] ++ query
when debug $ print fullquery
builds <- listBuilds hub fullquery
when debug $ mapM_ pPrintCompact builds
if details /= DetailDefault || length builds == 1
then mapM_ (printBuild hub tz details minstall) $ mapMaybe maybeBuildResult builds
else mapM_ putStrLn $ mapMaybe (shortBuildResult tz) builds
_ -> do
query <- setupQuery
let fullquery = query ++ [commonBuildQueryOptions limit]
when debug $ print fullquery
builds <- listBuilds hub fullquery
when debug $ mapM_ pPrintCompact builds
if details /= DetailDefault || length builds == 1
then mapM_ (printBuild hub tz details minstall) $ mapMaybe maybeBuildResult builds
else mapM_ putStrLn $ mapMaybe (shortBuildResult tz) builds
where
hub = maybe fedoraKojiHub hubURL mhub
shortBuildResult :: TimeZone -> Struct -> Maybe String
shortBuildResult tz bld = do
nvr <- lookupStruct "nvr" bld
state <- readBuildState <$> lookupStruct "state" bld
let date =
case lookupTimes bld of
Nothing -> ""
Just (start,mend) ->
compactZonedTime tz $ fromMaybe start mend
mbid = lookupStruct "build_id" bld
return $ nvr +-+ show state +-+ date +-+ maybe "" (buildinfoUrl hub) mbid
setupQuery = do
mdatestring <-
case mdate of
Nothing -> return Nothing
Just date -> Just <$> cmd "date" ["+%F %T%z", "--date=" ++ dateString date]
whenJust mdatestring $ \date ->
putStrLn $ maybe "" show mdate +-+ date
mowner <- maybeGetKojiUser hub museropt
return $
[("complete" ++ (capitalize . show) date, ValueString datestring) | Just date <- [mdate], Just datestring <- [mdatestring]]
++ [("userID", ValueInt (getID owner)) | Just owner <- [mowner]]
++ [("state", ValueArray (map buildStateToValue states)) | notNull states]
++ [("type", ValueString typ) | Just typ <- [mtype]]
++ case buildreq of
BuildPattern pat -> [("pattern", ValueString pat)]
_ -> []
dateString :: Tasks.BeforeAfter -> String
dateString beforeAfter =
let timedate = getTimedate beforeAfter
in case words timedate of
[t] | t `elem` ["hour", "day", "week", "month", "year"] ->
"last " ++ t
[t] | t `elem` ["today", "yesterday"] ->
t ++ " 00:00"
[t] | any (lower t `isPrefixOf`) ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] ->
"last " ++ t ++ " 00:00"
[n,_unit] | all isDigit n -> timedate ++ " ago"
_ -> timedate
pPrintCompact =
#if MIN_VERSION_pretty_simple(4,0,0)
pPrintOpt CheckColorTty
(defaultOutputOptionsDarkBg {outputOptionsCompact = True,
outputOptionsCompactParens = True})
#else
pPrint
#endif
buildinfoUrl :: String -> Int -> String
buildinfoUrl hub bid =
webUrl hub ++ "/buildinfo?buildID=" ++ show bid
data BuildResult =
BuildResult {buildNVR :: NVR,
buildState :: BuildState,
_buildId :: Int,
mbuildTaskId :: Maybe Int,
_buildStartTime :: UTCTime,
mbuildEndTime :: Maybe UTCTime
}
maybeBuildResult :: Struct -> Maybe BuildResult
maybeBuildResult st = do
(start,mend) <- lookupTimes st
buildid <- lookupStruct "build_id" st
let mtaskid = lookupStruct "task_id" st
state <- getBuildState st
nvr <- lookupStruct "nvr" st >>= maybeNVR
return $
BuildResult nvr state buildid mtaskid start mend
printBuild :: String -> TimeZone -> Details -> Maybe Tasks.Select
-> BuildResult -> IO ()
printBuild hub tz details minstall build = do
putStrLn ""
let mendtime = mbuildEndTime build
time <- maybe getCurrentTime return mendtime
(mapM_ putStrLn . formatBuildResult hub (isJust mendtime) tz) (build {mbuildEndTime = Just time})
when (buildState build == BuildComplete) $
putStrLn $ buildOutputURL hub $ buildNVR build
whenJust (mbuildTaskId build) $ \taskid -> do
when (details == DetailedTasks) $ do
putStrLn ""
Tasks.tasksCmd (Just hub) Nothing 7 [] [] Nothing Nothing False False Nothing False Nothing (Tasks.Parent taskid)
whenJust minstall $ \installopts -> do
putStrLn ""
installCmd False False No (Just hub) Nothing False False False Nothing ExistingUpdate Nothing installopts Nothing ReqName [show taskid]
formatBuildResult :: String -> Bool -> TimeZone -> BuildResult -> [String]
formatBuildResult hub ended tz (BuildResult nvr state buildid mtaskid start mendtime) =
[ showNVR nvr +-+ show state
, buildinfoUrl hub buildid]
++ [Tasks.taskinfoUrl hub taskid | Just taskid <- [mtaskid]]
++ [formatLocalTime True tz start]
++
case mendtime of
Nothing -> []
Just end ->
[formatLocalTime False tz end | ended]
#if MIN_VERSION_time(1,9,1)
++
let dur = diffUTCTime end start
in [(if not ended then "current " else "") ++ "duration: " ++ renderDuration False dur]
#endif
#if !MIN_VERSION_koji(0,0,3)
buildStateToValue :: BuildState -> Value
buildStateToValue = ValueInt . fromEnum
parseBuildState :: String -> BuildState
parseBuildState s =
case lower s of
"building" -> BuildBuilding
"complete" -> BuildComplete
"deleted" -> BuildDeleted
"fail" -> BuildFailed
"failed" -> BuildFailed
"cancel" -> BuildCanceled
"canceled" -> BuildCanceled
_ -> error' $! "unknown build state: " ++ s
#endif
getBuildState :: Struct -> Maybe BuildState
getBuildState st = readBuildState <$> lookup "state" st
kojiBuildTypes :: [String]
kojiBuildTypes = ["all", "image", "maven", "module", "rpm", "win"]
latestCmd :: Maybe String -> Bool -> String -> String -> IO ()
latestCmd mhub debug tag pkg = do
let hub = maybe fedoraKojiHub hubURL mhub
mbld <- kojiLatestBuild hub tag pkg
when debug $ print mbld
tz <- getCurrentTimeZone
whenJust (mbld >>= maybeBuildResult) $ printBuild hub tz Detailed Nothing
|
83e0486ba26bc77a6510f3540a85bf221eb02536da3230c10088ed86672a3eeb
|
galdor/tungsten
|
pbkdf2.lisp
|
(in-package :openssl)
(defun pbkdf2 (password salt digest-algorithm nb-iterations key-length)
(declare (type core:octet-vector password salt)
(type symbol digest-algorithm)
(type (integer 1) nb-iterations))
(let* ((digest-name (digest-algorithm-name digest-algorithm))
(%kdf (evp-kdf-fetch (ffi:null-pointer) "PBKDF2" nil))
(%context (unwind-protect (evp-kdf-ctx-new %kdf)
;; The context keeps a reference to the key derivation
;; function object, we can (and must) free it no matter
;; what.
(evp-kdf-free %kdf))))
(core:abort-protect
(ffi:with-pinned-vector-data (%password password)
(ffi:with-pinned-vector-data (%salt salt)
(ffi:with-foreign-strings ((%digest digest-name)
(%pass-key "pass")
(%salt-key "salt")
(%iter-key "iter")
(%digest-key "digest"))
(ffi:with-foreign-values ((%nb-iterations :uint64)
(%parameters 'ossl-param :count 5))
(setf (ffi:foreign-value %nb-iterations :uint64) nb-iterations)
(macrolet ((%parameter (i)
`(ffi:pointer+
%parameters
,(* i (ffi:foreign-type-size 'ossl-param)))))
(initialize-parameter (%parameter 0) %digest-key
:ossl-param-utf8-string
%digest 0)
(initialize-parameter (%parameter 1) %pass-key
:ossl-param-octet-string
%password (length password))
(initialize-parameter (%parameter 2) %salt-key
:ossl-param-octet-string
%salt (length salt))
(initialize-parameter (%parameter 3) %iter-key
:ossl-param-unsigned-integer
%nb-iterations
(ffi:foreign-type-size :uint64))
(initialize-last-parameter (%parameter 4)))
(evp-kdf-derive %context key-length %parameters)))))
(evp-kdf-ctx-free %context))))
| null |
https://raw.githubusercontent.com/galdor/tungsten/5d6e71fb89af32ab3994c5b2daf8b902a5447447/tungsten-openssl/src/pbkdf2.lisp
|
lisp
|
The context keeps a reference to the key derivation
function object, we can (and must) free it no matter
what.
|
(in-package :openssl)
(defun pbkdf2 (password salt digest-algorithm nb-iterations key-length)
(declare (type core:octet-vector password salt)
(type symbol digest-algorithm)
(type (integer 1) nb-iterations))
(let* ((digest-name (digest-algorithm-name digest-algorithm))
(%kdf (evp-kdf-fetch (ffi:null-pointer) "PBKDF2" nil))
(%context (unwind-protect (evp-kdf-ctx-new %kdf)
(evp-kdf-free %kdf))))
(core:abort-protect
(ffi:with-pinned-vector-data (%password password)
(ffi:with-pinned-vector-data (%salt salt)
(ffi:with-foreign-strings ((%digest digest-name)
(%pass-key "pass")
(%salt-key "salt")
(%iter-key "iter")
(%digest-key "digest"))
(ffi:with-foreign-values ((%nb-iterations :uint64)
(%parameters 'ossl-param :count 5))
(setf (ffi:foreign-value %nb-iterations :uint64) nb-iterations)
(macrolet ((%parameter (i)
`(ffi:pointer+
%parameters
,(* i (ffi:foreign-type-size 'ossl-param)))))
(initialize-parameter (%parameter 0) %digest-key
:ossl-param-utf8-string
%digest 0)
(initialize-parameter (%parameter 1) %pass-key
:ossl-param-octet-string
%password (length password))
(initialize-parameter (%parameter 2) %salt-key
:ossl-param-octet-string
%salt (length salt))
(initialize-parameter (%parameter 3) %iter-key
:ossl-param-unsigned-integer
%nb-iterations
(ffi:foreign-type-size :uint64))
(initialize-last-parameter (%parameter 4)))
(evp-kdf-derive %context key-length %parameters)))))
(evp-kdf-ctx-free %context))))
|
8227c6fbe5c88e6f5326b2d45e6298bffe136eea05039ee400f60534d88982af
|
weavejester/ataraxy
|
project.clj
|
(defproject ataraxy "0.4.3"
:description "A data-driven Ring routing and destructuring library"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.9.0"]
[ring/ring-core "1.6.1"]]
:profiles
{:dev {:dependencies [[criterium "0.4.3"]]}
:1.10 {:dependencies [[org.clojure/clojure "1.10.0-alpha6"]]}}
:aliases
{"test-all" ["with-profile" "default:+1.10" "test"]})
| null |
https://raw.githubusercontent.com/weavejester/ataraxy/efadd2eaefa5a732811f4dc2885bad4d50c8d806/project.clj
|
clojure
|
(defproject ataraxy "0.4.3"
:description "A data-driven Ring routing and destructuring library"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.9.0"]
[ring/ring-core "1.6.1"]]
:profiles
{:dev {:dependencies [[criterium "0.4.3"]]}
:1.10 {:dependencies [[org.clojure/clojure "1.10.0-alpha6"]]}}
:aliases
{"test-all" ["with-profile" "default:+1.10" "test"]})
|
|
5542cd36c36afb8ea829a2d140ba40dcec972de3eed162ed7c97ea7c232a3bcd
|
smallhadroncollider/ascii-runner
|
Types.hs
|
# LANGUAGE TemplateHaskell #
module Types (
UI
, Tick(..)
, Direction(..)
, State(..)
, Player
, Obstacles
, Name
, create
, reset
, position
, dimensions
, player
, obstacles
, state
, speed
) where
import ClassyPrelude
import Control.Lens ((&), (^.), (.~), makeLenses)
import Window (Dimensions)
data Direction = Up | Down | Level
type Player = (Direction, Int)
type Obstacles = [Int]
data State = Playing | GameOver
data UI = UI {
_position :: Float
, _dimensions :: Dimensions
, _player :: Player
, _obstacles :: [Int]
, _state :: State
, _speed :: Int
}
$(makeLenses ''UI)
create :: Dimensions -> Int -> UI
create s sp = UI {
_position = 0
, _dimensions = s
, _player = (Level, 0)
, _obstacles = [fst s]
, _state = Playing
, _speed = sp
}
reset :: UI -> UI
reset ui = ui
& state .~ Playing
& player .~ (Level, 0)
& obstacles .~ [fst s]
& position .~ 0
where s = ui ^. dimensions
data Tick = Tick
type Name = ()
| null |
https://raw.githubusercontent.com/smallhadroncollider/ascii-runner/42eb674b4a997241a384c43f64e668e379519d97/src/Types.hs
|
haskell
|
# LANGUAGE TemplateHaskell #
module Types (
UI
, Tick(..)
, Direction(..)
, State(..)
, Player
, Obstacles
, Name
, create
, reset
, position
, dimensions
, player
, obstacles
, state
, speed
) where
import ClassyPrelude
import Control.Lens ((&), (^.), (.~), makeLenses)
import Window (Dimensions)
data Direction = Up | Down | Level
type Player = (Direction, Int)
type Obstacles = [Int]
data State = Playing | GameOver
data UI = UI {
_position :: Float
, _dimensions :: Dimensions
, _player :: Player
, _obstacles :: [Int]
, _state :: State
, _speed :: Int
}
$(makeLenses ''UI)
create :: Dimensions -> Int -> UI
create s sp = UI {
_position = 0
, _dimensions = s
, _player = (Level, 0)
, _obstacles = [fst s]
, _state = Playing
, _speed = sp
}
reset :: UI -> UI
reset ui = ui
& state .~ Playing
& player .~ (Level, 0)
& obstacles .~ [fst s]
& position .~ 0
where s = ui ^. dimensions
data Tick = Tick
type Name = ()
|
|
7975747c99361f3d932f046a55165debf21b586023bca9d6d939ba8e41920f8a
|
footprintanalytics/footprint-web
|
default.clj
|
(ns metabase.query-processor.context.default
(:require [clojure.core.async :as a]
[clojure.tools.logging :as log]
[metabase.config :as config]
[metabase.driver :as driver]
[metabase.query-processor.context :as qp.context]
[metabase.query-processor.error-type :as qp.error-type]
[metabase.util :as u]
[metabase.util.i18n :refer [trs tru]]))
(def query-timeout-ms
"Maximum amount of time to wait for a running query to complete before throwing an Exception."
;; I don't know if these numbers make sense, but my thinking is we want to enable (somewhat) long-running queries on
prod but for test and dev purposes we want to fail faster because it usually means I broke something in the QP
;; code
(cond
config/is-prod? (u/minutes->ms 20)
config/is-test? (u/seconds->ms 60)
config/is-dev? (u/minutes->ms 3)))
(defn default-rff
"Default function returning a reducing function. Results are returned in the 'standard' map format e.g.
{:data {:cols [...], :rows [...]}, :row_count ...}"
[metadata]
(let [row-count (volatile! 0)
rows (volatile! [])]
(fn default-rf
([]
{:data metadata})
([result]
{:pre [(map? (unreduced result))]}
;; if the result is a clojure.lang.Reduced, unwrap it so we always get back the standard-format map
(-> (unreduced result)
(assoc :row_count @row-count
:status :completed)
(assoc-in [:data :rows] @rows)))
([result row]
(vswap! row-count inc)
(vswap! rows conj row)
result))))
(defn- default-reducedf [reduced-result context]
(qp.context/resultf reduced-result context))
(defn default-reducef
"Default implementation of `reducef`. When using a custom implementation of `reducef` it's easiest to call this
function inside the custom impl instead of attempting to duplicate the logic. See
[[metabase.query-processor.reducible-test/write-rows-to-file-test]] for an example of a custom implementation."
[rff context metadata reducible-rows]
{:pre [(fn? rff)]}
(let [rf (rff (dissoc metadata :erorCallback))]
(assert (fn? rf))
(when-let [reduced-rows (try
(transduce identity rf reducible-rows)
(catch Throwable e
;;Data processing for cache async query error
(when (metadata :aysnc-refresh-cache?)
((metadata :erorCallback)))
(qp.context/raisef (ex-info (tru "Error reducing result rows")
{:type qp.error-type/qp}
e)
context)))]
(qp.context/reducedf reduced-rows context))))
(defn- default-runf [query rff context]
(try
(qp.context/executef driver/*driver* query context (fn respond* [metadata reducible-rows]
(qp.context/reducef rff context metadata reducible-rows)))
(catch Throwable e
;;Data processing for cache async query error
(when (query :aysnc-refresh-cache?)
((query :erorCallback)))
(qp.context/raisef e context))))
(defn- default-raisef [e context]
{:pre [(instance? Throwable e)]}
(qp.context/resultf e context))
(defn- default-resultf [result context]
(if (nil? result)
(do
(log/error (ex-info (trs "Unexpected nil result") {}))
(recur false context))
(let [out-chan (qp.context/out-chan context)]
(a/>!! out-chan result)
(a/close! out-chan))))
(defn- default-timeoutf
[context]
(let [timeout (qp.context/timeout context)]
(log/debug (trs "Query timed out after {0}, raising timeout exception." (u/format-milliseconds timeout)))
(qp.context/raisef (ex-info (tru "Timed out after {0}." (u/format-milliseconds timeout))
{:status :timed-out
:type qp.error-type/timed-out})
context)))
(defn default-context
"Return a new context for executing queries using the default values. These can be overrided as needed."
[]
{::complete? true
:timeout query-timeout-ms
:rff default-rff
:raisef default-raisef
:runf default-runf
:executef driver/execute-reducible-query
:reducef default-reducef
:reducedf default-reducedf
:timeoutf default-timeoutf
:resultf default-resultf
:canceled-chan (a/promise-chan)
:out-chan (a/promise-chan)})
| null |
https://raw.githubusercontent.com/footprintanalytics/footprint-web/790fdff545e2ed74097328102675df3bd56b83d1/src/metabase/query_processor/context/default.clj
|
clojure
|
I don't know if these numbers make sense, but my thinking is we want to enable (somewhat) long-running queries on
code
if the result is a clojure.lang.Reduced, unwrap it so we always get back the standard-format map
Data processing for cache async query error
Data processing for cache async query error
|
(ns metabase.query-processor.context.default
(:require [clojure.core.async :as a]
[clojure.tools.logging :as log]
[metabase.config :as config]
[metabase.driver :as driver]
[metabase.query-processor.context :as qp.context]
[metabase.query-processor.error-type :as qp.error-type]
[metabase.util :as u]
[metabase.util.i18n :refer [trs tru]]))
(def query-timeout-ms
"Maximum amount of time to wait for a running query to complete before throwing an Exception."
prod but for test and dev purposes we want to fail faster because it usually means I broke something in the QP
(cond
config/is-prod? (u/minutes->ms 20)
config/is-test? (u/seconds->ms 60)
config/is-dev? (u/minutes->ms 3)))
(defn default-rff
"Default function returning a reducing function. Results are returned in the 'standard' map format e.g.
{:data {:cols [...], :rows [...]}, :row_count ...}"
[metadata]
(let [row-count (volatile! 0)
rows (volatile! [])]
(fn default-rf
([]
{:data metadata})
([result]
{:pre [(map? (unreduced result))]}
(-> (unreduced result)
(assoc :row_count @row-count
:status :completed)
(assoc-in [:data :rows] @rows)))
([result row]
(vswap! row-count inc)
(vswap! rows conj row)
result))))
(defn- default-reducedf [reduced-result context]
(qp.context/resultf reduced-result context))
(defn default-reducef
"Default implementation of `reducef`. When using a custom implementation of `reducef` it's easiest to call this
function inside the custom impl instead of attempting to duplicate the logic. See
[[metabase.query-processor.reducible-test/write-rows-to-file-test]] for an example of a custom implementation."
[rff context metadata reducible-rows]
{:pre [(fn? rff)]}
(let [rf (rff (dissoc metadata :erorCallback))]
(assert (fn? rf))
(when-let [reduced-rows (try
(transduce identity rf reducible-rows)
(catch Throwable e
(when (metadata :aysnc-refresh-cache?)
((metadata :erorCallback)))
(qp.context/raisef (ex-info (tru "Error reducing result rows")
{:type qp.error-type/qp}
e)
context)))]
(qp.context/reducedf reduced-rows context))))
(defn- default-runf [query rff context]
(try
(qp.context/executef driver/*driver* query context (fn respond* [metadata reducible-rows]
(qp.context/reducef rff context metadata reducible-rows)))
(catch Throwable e
(when (query :aysnc-refresh-cache?)
((query :erorCallback)))
(qp.context/raisef e context))))
(defn- default-raisef [e context]
{:pre [(instance? Throwable e)]}
(qp.context/resultf e context))
(defn- default-resultf [result context]
(if (nil? result)
(do
(log/error (ex-info (trs "Unexpected nil result") {}))
(recur false context))
(let [out-chan (qp.context/out-chan context)]
(a/>!! out-chan result)
(a/close! out-chan))))
(defn- default-timeoutf
[context]
(let [timeout (qp.context/timeout context)]
(log/debug (trs "Query timed out after {0}, raising timeout exception." (u/format-milliseconds timeout)))
(qp.context/raisef (ex-info (tru "Timed out after {0}." (u/format-milliseconds timeout))
{:status :timed-out
:type qp.error-type/timed-out})
context)))
(defn default-context
"Return a new context for executing queries using the default values. These can be overrided as needed."
[]
{::complete? true
:timeout query-timeout-ms
:rff default-rff
:raisef default-raisef
:runf default-runf
:executef driver/execute-reducible-query
:reducef default-reducef
:reducedf default-reducedf
:timeoutf default-timeoutf
:resultf default-resultf
:canceled-chan (a/promise-chan)
:out-chan (a/promise-chan)})
|
28d6e34c78c4bdf9e3189981bf0e15d2e39950ee3f4decdadd716daffc4b4895
|
puppetlabs/trapperkeeper-metrics
|
metrics_service_test.clj
|
(ns puppetlabs.trapperkeeper.services.metrics.metrics-service-test
(:import (com.codahale.metrics MetricRegistry JmxReporter)
(clojure.lang ExceptionInfo)
(com.puppetlabs.trapperkeeper.metrics GraphiteReporter))
(:require [clojure.test :refer :all]
[cheshire.core :as json]
[clojure.string :as string]
[ring.util.codec :as codec]
[puppetlabs.http.client.sync :as http-client]
[puppetlabs.metrics :as metrics]
[puppetlabs.trapperkeeper.services.authorization.authorization-service :as authorization-service]
[puppetlabs.trapperkeeper.services.metrics.metrics-service :refer :all]
[puppetlabs.trapperkeeper.services.protocols.metrics :as metrics-protocol]
[schema.test :as schema-test]
[puppetlabs.trapperkeeper.services.webrouting.webrouting-service :as webrouting-service]
[puppetlabs.trapperkeeper.services.webserver.jetty9-service :as jetty9-service]
[puppetlabs.trapperkeeper.testutils.bootstrap :refer [with-app-with-config]]
[puppetlabs.trapperkeeper.testutils.logging :refer [with-test-logging]]
[puppetlabs.trapperkeeper.app :as app]
[puppetlabs.kitchensink.core :as ks]
[puppetlabs.trapperkeeper.testutils.logging :as logging]
[puppetlabs.trapperkeeper.core :as trapperkeeper]
[puppetlabs.trapperkeeper.services.metrics.metrics-testutils :as utils]
[puppetlabs.trapperkeeper.services :as tk-services]
[puppetlabs.trapperkeeper.services.metrics.metrics-core :as core]))
(use-fixtures :once schema-test/validate-schemas)
(defn parse-response
([resp]
(parse-response resp false))
([resp keywordize?]
(-> resp :body slurp (json/parse-string keywordize?))))
(defn jolokia-encode
"Encodes a MBean name according to the rules laid out in:
#escape-rules"
[mbean-name]
(-> mbean-name
(string/escape {\/ "!/" \! "!!" \" "!\""})
codec/url-encode))
(def test-resources-dir
(ks/absolute-path "./dev-resources/puppetlabs/trapperkeeper/services/metrics/metrics_service_test"))
(def services
[jetty9-service/jetty9-service
webrouting-service/webrouting-service
metrics-service
metrics-webservice])
(def ssl-opts
{:ssl-cert "./dev-resources/ssl/cert.pem"
:ssl-key "./dev-resources/ssl/key.pem"
:ssl-ca-cert "./dev-resources/ssl/ca.pem"})
(def ssl-webserver-config
{:webserver
(merge {:ssl-port 8180
:ssl-host "0.0.0.0"}
ssl-opts)})
(def metrics-service-config
{:metrics {:server-id "localhost"
:registries {:pl.test.reg {:reporters {:jmx {:enabled true}}}
:pl.other.reg {:reporters {:jmx {:enabled true}}}}}
:webserver {:port 8180
:host "0.0.0.0"}
:web-router-service {:puppetlabs.trapperkeeper.services.metrics.metrics-service/metrics-webservice
"/metrics"}})
(def auth-config
{:authorization
{:version 1
:rules
[{:match-request {:path "/metrics/v2/list" :type "path" :method ["get" "head" "post" "put"]}
:allow "localhost"
:sort-order 500
:name "list"}
{:match-request {:path "/metrics/v2" :type "path" :method ["get" "head" "post" "put"]}
:deny "localhost"
:sort-order 500
:name "metrics"}]}})
(deftest test-metrics-service-error
(testing "Metrics service throws an error if missing server-id"
(logging/with-test-logging
(is (thrown-with-msg?
ExceptionInfo
#"Value does not match schema: .*server-id missing-required-key.*"
(with-app-with-config
app
services
(ks/dissoc-in metrics-service-config [:metrics :server-id])))))))
(deftest test-metrics-service
(testing "Can boot metrics service and access registry"
(with-app-with-config
app
services
(assoc-in metrics-service-config [:metrics :metrics-webservice :mbeans :enabled] true)
(testing "metrics service functions"
(let [svc (app/get-service app :MetricsService)]
(testing "`get-metrics-registry` called without domain works"
(is (instance? MetricRegistry (metrics-protocol/get-metrics-registry svc))))
(testing "`get-metrics-registry` called with domain works"
(is (instance? MetricRegistry
(metrics-protocol/get-metrics-registry svc :pl.foo.reg))))
(testing "`get-server-id` works"
(is (= "localhost" (metrics-protocol/get-server-id svc))))))
(testing "returns latest status for all services"
(let [resp (http-client/get ":8180/metrics/v1/mbeans")
body (parse-response resp)]
(is (= 200 (:status resp)))
(doseq [[metric path] body
:let [resp (http-client/get (str ":8180/metrics/v1" path))]]
(is (= 200 (:status resp)))))
(let [resp (http-client/get ":8180/metrics/v2/list/java.lang")
body (parse-response resp)]
(is (= 200 (:status resp)))
(doseq [mbean (keys (get body "value"))
:let [url (str ":8180/metrics/v2/read/"
(jolokia-encode (str "java.lang:" mbean))
;; NOTE: Some memory pools intentionally don't
implement MBean attributes . This results
;; in an error being thrown when those
;; attributes are read and is expected.
"?ignoreErrors=true")
resp (http-client/get url)
body (parse-response resp)]]
NOTE : returns 200 OK for most responses . The actual
;; status code is in the JSON payload that makes up the body.
(is (= 200 (get body "status"))))))
(testing "register should add a metric to the registry with a keyword domain"
(let [svc (app/get-service app :MetricsService)
register-and-get-metric (fn [domain metric]
(metrics/register
(metrics-protocol/get-metrics-registry svc domain)
(metrics/host-metric-name "localhost" metric)
(metrics/gauge 2))
(http-client/get
(str ":8180/metrics/v1/mbeans/"
(codec/url-encode
(str (name domain) ":name=puppetlabs.localhost." metric)))))
resp (register-and-get-metric :pl.test.reg "foo")]
(is (= 200 (:status resp)))
(is (= {"Value" 2} (parse-response resp)))))
(testing "querying multiple metrics via POST should work"
(let [svc (app/get-service app :MetricsService)
registry (metrics-protocol/get-metrics-registry svc :pl.other.reg)]
(metrics/register registry
(metrics/host-metric-name "localhost" "foo")
(metrics/gauge 2))
(metrics/register registry
(metrics/host-metric-name "localhost" "bar")
(metrics/gauge 500))
(let [resp (http-client/post
":8180/metrics/v1/mbeans"
{:body (json/generate-string
["pl.other.reg:name=puppetlabs.localhost.foo"
"pl.other.reg:name=puppetlabs.localhost.bar"])})
body (parse-response resp)]
(is (= 200 (:status resp)))
(is (= [{"Value" 2} {"Value" 500}] body)))
(let [resp (http-client/post
":8180/metrics/v1/mbeans"
{:body (json/generate-string
{:foo "pl.other.reg:name=puppetlabs.localhost.foo"
:bar "pl.other.reg:name=puppetlabs.localhost.bar"})})
body (parse-response resp)]
(is (= 200 (:status resp)))
(is (= {"foo" {"Value" 2}
"bar" {"Value" 500}} body)))
(let [resp (http-client/post
":8180/metrics/v1/mbeans"
{:body (json/generate-string
"pl.other.reg:name=puppetlabs.localhost.foo")})
body (parse-response resp)]
(is (= 200 (:status resp)))
(is (= {"Value" 2} body)))
(let [resp (http-client/post
":8180/metrics/v1/mbeans"
{:body "{\"malformed json"})
body (slurp (:body resp))]
(is (= 400 (:status resp)))
(is (re-find #"Unexpected end-of-input" body)))
(let [resp (http-client/post
":8180/metrics/v2"
{:body (json/generate-string
[{:type "read" :mbean "pl.other.reg:name=puppetlabs.localhost.foo"}
{:type "read" :mbean "pl.other.reg:name=puppetlabs.localhost.bar"}])})
body (parse-response resp true)]
(is (= [200 200] (map :status body)))
(is (= [{:Value 2} {:Value 500}] (map :value body))))))
(testing "metrics/v2 should deny write requests"
(with-test-logging
(let [resp (http-client/get
(str ":8180/metrics/v2/write/"
(jolokia-encode "java.lang:type=Memory")
"/Verbose/true"))
body (parse-response resp)]
(is (= 403 (get body "status"))))))
(testing "metrics/v2 should deny exec requests"
(with-test-logging
(let [resp (http-client/get
(str ":8180/metrics/v2/exec/"
(jolokia-encode "java.util.logging:type=Logging")
"/getLoggerLevel/root"))
body (parse-response resp)]
(is (= 403 (get body "status")))))))))
(deftest metrics-service-with-tk-auth
(testing "tk-auth works when included in bootstrap"
(with-app-with-config
app
(conj services authorization-service/authorization-service)
(merge metrics-service-config auth-config ssl-webserver-config)
(let [resp (http-client/get ":8180/metrics/v2/list" ssl-opts)]
(is (= 200 (:status resp))))
(let [resp (http-client/get ":8180/metrics/v2" ssl-opts)]
(is (= 403 (:status resp)))))))
(deftest metrics-v1-endpoint-disabled-by-default
(testing "metrics/v1 is disabled by default, returns 404"
(with-app-with-config
app
[jetty9-service/jetty9-service
webrouting-service/webrouting-service
metrics-service
metrics-webservice]
metrics-service-config
(let [resp (http-client/get ":8180/metrics/v1/mbeans")]
(is (= 404 (:status resp)))))))
(deftest metrics-endpoint-with-jolokia-disabled-test
(testing "metrics/v2 returns 404 when Jolokia is not enabled"
(let [config (assoc-in metrics-service-config [:metrics :metrics-webservice :jolokia :enabled] false)]
(with-app-with-config
app
[jetty9-service/jetty9-service
webrouting-service/webrouting-service
metrics-service
metrics-webservice]
config
(let [resp (http-client/get ":8180/metrics/v2/version")]
(is (= 404 (:status resp))))))))
(deftest metrics-endpoint-with-permissive-jolokia-policy
(testing "metrics/v2 allows exec requests when configured with a permissive policy"
(let [config (assoc-in metrics-service-config
[:metrics :metrics-webservice :jolokia :servlet-init-params :policyLocation]
(str "file://" test-resources-dir "/jolokia-access-permissive.xml"))]
(with-app-with-config
app
[jetty9-service/jetty9-service
webrouting-service/webrouting-service
metrics-service
metrics-webservice]
config
(let [resp (http-client/get
(str ":8180/metrics/v2/exec/"
(jolokia-encode "java.util.logging:type=Logging")
"/getLoggerLevel/root"))
body (parse-response resp)]
(is (= 200 (get body "status"))))))))
(deftest metrics-endpoint-with-jmx-disabled-test
(testing "returns data for jvm even when jmx is not enabled"
(let [config (-> metrics-service-config
(assoc-in [:metrics :metrics-webservice :mbeans :enabled] true)
(assoc :registries
{:pl.no.jmx {:reporters
{:jmx
{:enabled false}}}}))]
(with-app-with-config
app
[jetty9-service/jetty9-service
webrouting-service/webrouting-service
metrics-service
metrics-webservice]
config
(testing "returns latest status for all services"
(let [resp (http-client/get ":8180/metrics/v1/mbeans")
body (parse-response resp)]
(is (= 200 (:status resp)))
(is (not (empty? body)))))
(testing "returns Memoory mbean information"
(let [resp (http-client/get ":8180/metrics/v1/mbeans/java.lang%3Atype%3DMemory")
body (parse-response resp)
heap-memory (get body "HeapMemoryUsage")]
(is (= 200 (:status resp)))
(is (= #{"committed" "init" "max" "used"} (ks/keyset heap-memory)))
(is (every? #(< 0 %) (vals heap-memory)))))))))
(deftest get-metrics-registry-service-function-test
(with-app-with-config
app
[metrics-service]
{:metrics {:server-id "localhost"}}
(let [svc (app/get-service app :MetricsService)]
(testing "Can access default registry"
(is (instance? MetricRegistry (metrics-protocol/get-metrics-registry svc))))
(testing "Can access other registries registry"
(is (instance? MetricRegistry (metrics-protocol/get-metrics-registry svc :my-domain)))))))
(deftest get-server-id-service-function-test
(with-app-with-config
app
[metrics-service]
{:metrics {:server-id "foo"}}
(let [svc (app/get-service app :MetricsService)]
(testing "Can access server-id"
(is (= "foo" (metrics-protocol/get-server-id svc)))))))
(deftest update-registry-settings-service-function-test
(testing "intialize-registry-settings adds settings for a registry"
(let [service (trapperkeeper/service
[[:MetricsService update-registry-settings]]
(init [this context]
(update-registry-settings :foo.bar {:default-metrics-allowed ["foo.bar"]})
context))
metrics-app (trapperkeeper/build-app [service metrics-service]
{:metrics utils/test-config})
metrics-svc (app/get-service metrics-app :MetricsService)]
(try
(app/init metrics-app)
(is (= {:foo.bar {:default-metrics-allowed ["foo.bar"]}}
@(:registry-settings (tk-services/service-context metrics-svc))))
(finally
(app/stop metrics-app)))))
(testing "update-registry-settings throws an error if called outside `init`"
(let [service (trapperkeeper/service
[[:MetricsService update-registry-settings]]
(start [this context]
(update-registry-settings :nope {:default-metrics-allowed ["fail"]})
context))
metrics-app (trapperkeeper/build-app [service metrics-service]
{:metrics utils/test-config})]
(with-test-logging
(try
(is (thrown? RuntimeException (app/check-for-errors! (app/start metrics-app))))
(finally
(app/stop metrics-app)))))))
(deftest jmx-enabled-globally-deprecated-test
(with-test-logging
(with-app-with-config
app
[metrics-service]
{:metrics {:server-id "localhost"
:reporters {:jmx {:enabled true}}}})
(is (logged? #"Enabling JMX globally is deprecated; JMX can only be enabled per-registry."))))
(deftest jmx-works-test
(with-app-with-config
app
[metrics-service]
{:metrics {:server-id "localhost"
:registries {:jmx.registry {:reporters {:jmx {:enabled true}}}
:no.jmx.registry {:reporters {:jmx {:enabled false}}}
:foo {:metrics-allowed ["foo"]}}}}
(let [svc (app/get-service app :MetricsService)
context (tk-services/service-context svc)
get-jmx-reporter (fn [domain] (get-in @(:registries context) [domain :jmx-reporter]))]
(testing "Registry with jmx enabled gets a jmx reporter"
(metrics-protocol/get-metrics-registry svc :jmx.registry)
(is (instance? JmxReporter (get-jmx-reporter :jmx.registry))))
(testing "Registry with jmx disabled does not get a jmx reporter"
(metrics-protocol/get-metrics-registry svc :jmx.registry)
(is (nil? (get-jmx-reporter :no.jmx.registry))))
(testing "Registry with no mention of jmx does not get a jmx reporter"
(metrics-protocol/get-metrics-registry svc :foo)
(is (nil? (get-jmx-reporter :foo))))
(testing "Registry not mentioned in config does not get a jmx reporter"
(metrics-protocol/get-metrics-registry svc :not.in.the.config)
(is (nil? (get-jmx-reporter :not.in.the.config)))))))
(defn create-meters!
[registries meter-names]
(doseq [{:keys [registry]} (vals registries)
meter meter-names]
(.meter registry meter )))
(defn report-to-graphite!
[registries]
(doseq [graphite-reporter (map :graphite-reporter (vals registries))]
(when graphite-reporter
(.report graphite-reporter))))
(def graphite-enabled
{:reporters {:graphite {:enabled true}}})
(def metrics-allowed
{:metrics-allowed ["not-default"]})
(def default-metrics-allowed
{:default-metrics-allowed ["default"]})
(deftest integration-test
(let [registries-config
{:graphite-enabled graphite-enabled
:graphite-with-default-metrics-allowed graphite-enabled
:graphite-with-metrics-allowed (merge metrics-allowed graphite-enabled)
:graphite-with-defaults-and-metrics-allowed (merge metrics-allowed graphite-enabled)}
config {:metrics (utils/build-config-with-registries registries-config)}
service (trapperkeeper/service
[[:MetricsService get-metrics-registry update-registry-settings]]
(init
[this context]
(get-metrics-registry :graphite-enabled)
(get-metrics-registry :graphite-with-default-metrics-allowed)
(update-registry-settings :graphite-with-default-metrics-allowed
default-metrics-allowed)
(get-metrics-registry :graphite-with-metrics-allowed)
;; shouldn't matter whether `get-metrics-registry` or
` update - registry - settings ` is called first
(update-registry-settings :graphite-with-defaults-and-metrics-allowed
default-metrics-allowed)
(get-metrics-registry :graphite-with-defaults-and-metrics-allowed)
context))
reported-metrics-atom (atom {})]
(with-redefs [core/build-graphite-sender
(fn [_ domain] (utils/make-graphite-sender reported-metrics-atom domain))]
(let [metrics-app (trapperkeeper/build-app
[metrics-service service]
config)
metrics-svc (app/get-service metrics-app :MetricsService)
get-context (fn [] (tk-services/service-context metrics-svc))]
(try
(testing "init phase of lifecycle"
(app/init metrics-app)
(let [context (get-context)
registries @(:registries context)
registry-settings @(:registry-settings context)]
(testing "all registries in config (plus default) get created"
(is (= #{:default
:graphite-enabled
:graphite-with-default-metrics-allowed
:graphite-with-metrics-allowed
:graphite-with-defaults-and-metrics-allowed}
(ks/keyset registries)))
(is (every? #(instance? MetricRegistry %)
(map :registry (vals registries)))))
(testing "graphite reporters are not created in it"
(is (every? nil? (map :graphite-reproter (vals registries)))))
(testing "registry settings are initialized in init"
(is (= {:graphite-with-default-metrics-allowed default-metrics-allowed
:graphite-with-defaults-and-metrics-allowed default-metrics-allowed}
registry-settings)))))
(testing "start phase of lifecycle"
(app/start metrics-app)
(let [context (get-context)
registries @(:registries context)
registry-settings @(:registry-settings context)]
(testing "graphite reporters are created in start"
(is (every? #(instance? MetricRegistry %)
(map :registry (vals registries))))
(is (every? #(instance? GraphiteReporter %)
(map :graphite-reporter (vals (dissoc registries :default)))))
(is (nil? (get-in registries [:default :graphite-reporter]))))
(testing "the right metrics are reported to graphite"
(create-meters! registries ["puppetlabs.localhost.default"
"puppetlabs.localhost.not-default"
"puppetlabs.localhost.foo"])
(report-to-graphite! registries)
(let [reported-metrics @reported-metrics-atom]
(is (= #{:graphite-enabled
:graphite-with-default-metrics-allowed
:graphite-with-metrics-allowed
:graphite-with-defaults-and-metrics-allowed}
(ks/keyset reported-metrics)))
(testing "without any metrics filter configured all metrics are reported"
(is (utils/reported? reported-metrics
:graphite-enabled
"puppetlabs.localhost.foo.count"))
(is (utils/reported? reported-metrics
:graphite-enabled
"puppetlabs.localhost.default.count"))
(is (utils/reported? reported-metrics
:graphite-enabled
"puppetlabs.localhost.not-default.count")))
(testing "default metrics are reported to graphite"
(is (not (utils/reported? reported-metrics
:graphite-with-default-metrics-allowed
"puppetlabs.localhost.foo.count")))
(is (utils/reported? reported-metrics
:graphite-with-default-metrics-allowed
"puppetlabs.localhost.default.count"))
(is (not (utils/reported? reported-metrics
:graphite-with-default-metrics-allowed
"puppetlabs.localhost.not-default.count"))))
(testing "configured metrics are reported to graphite"
(is (not (utils/reported? reported-metrics
:graphite-with-metrics-allowed
"puppetlabs.localhost.foo.count")))
(is (not (utils/reported? reported-metrics
:graphite-with-metrics-allowed
"puppetlabs.localhost.default.count")))
(is (utils/reported? reported-metrics
:graphite-with-metrics-allowed
"puppetlabs.localhost.not-default.count")))
(testing "configured metrics and default allowed metrics are reported to graphite"
(is (not (utils/reported? reported-metrics
:graphite-with-defaults-and-metrics-allowed
"localhost.foo.count")))
(is (utils/reported? reported-metrics
:graphite-with-defaults-and-metrics-allowed
"puppetlabs.localhost.default.count"))
(is (utils/reported? reported-metrics
:graphite-with-defaults-and-metrics-allowed
"puppetlabs.localhost.not-default.count")))))))
(finally
(app/stop metrics-app)))))))
| null |
https://raw.githubusercontent.com/puppetlabs/trapperkeeper-metrics/47f1534ebb75339eeb42e0de33fab0ec2f6cacdc/test/puppetlabs/trapperkeeper/services/metrics/metrics_service_test.clj
|
clojure
|
NOTE: Some memory pools intentionally don't
in an error being thrown when those
attributes are read and is expected.
status code is in the JSON payload that makes up the body.
shouldn't matter whether `get-metrics-registry` or
|
(ns puppetlabs.trapperkeeper.services.metrics.metrics-service-test
(:import (com.codahale.metrics MetricRegistry JmxReporter)
(clojure.lang ExceptionInfo)
(com.puppetlabs.trapperkeeper.metrics GraphiteReporter))
(:require [clojure.test :refer :all]
[cheshire.core :as json]
[clojure.string :as string]
[ring.util.codec :as codec]
[puppetlabs.http.client.sync :as http-client]
[puppetlabs.metrics :as metrics]
[puppetlabs.trapperkeeper.services.authorization.authorization-service :as authorization-service]
[puppetlabs.trapperkeeper.services.metrics.metrics-service :refer :all]
[puppetlabs.trapperkeeper.services.protocols.metrics :as metrics-protocol]
[schema.test :as schema-test]
[puppetlabs.trapperkeeper.services.webrouting.webrouting-service :as webrouting-service]
[puppetlabs.trapperkeeper.services.webserver.jetty9-service :as jetty9-service]
[puppetlabs.trapperkeeper.testutils.bootstrap :refer [with-app-with-config]]
[puppetlabs.trapperkeeper.testutils.logging :refer [with-test-logging]]
[puppetlabs.trapperkeeper.app :as app]
[puppetlabs.kitchensink.core :as ks]
[puppetlabs.trapperkeeper.testutils.logging :as logging]
[puppetlabs.trapperkeeper.core :as trapperkeeper]
[puppetlabs.trapperkeeper.services.metrics.metrics-testutils :as utils]
[puppetlabs.trapperkeeper.services :as tk-services]
[puppetlabs.trapperkeeper.services.metrics.metrics-core :as core]))
(use-fixtures :once schema-test/validate-schemas)
(defn parse-response
([resp]
(parse-response resp false))
([resp keywordize?]
(-> resp :body slurp (json/parse-string keywordize?))))
(defn jolokia-encode
"Encodes a MBean name according to the rules laid out in:
#escape-rules"
[mbean-name]
(-> mbean-name
(string/escape {\/ "!/" \! "!!" \" "!\""})
codec/url-encode))
(def test-resources-dir
(ks/absolute-path "./dev-resources/puppetlabs/trapperkeeper/services/metrics/metrics_service_test"))
(def services
[jetty9-service/jetty9-service
webrouting-service/webrouting-service
metrics-service
metrics-webservice])
(def ssl-opts
{:ssl-cert "./dev-resources/ssl/cert.pem"
:ssl-key "./dev-resources/ssl/key.pem"
:ssl-ca-cert "./dev-resources/ssl/ca.pem"})
(def ssl-webserver-config
{:webserver
(merge {:ssl-port 8180
:ssl-host "0.0.0.0"}
ssl-opts)})
(def metrics-service-config
{:metrics {:server-id "localhost"
:registries {:pl.test.reg {:reporters {:jmx {:enabled true}}}
:pl.other.reg {:reporters {:jmx {:enabled true}}}}}
:webserver {:port 8180
:host "0.0.0.0"}
:web-router-service {:puppetlabs.trapperkeeper.services.metrics.metrics-service/metrics-webservice
"/metrics"}})
(def auth-config
{:authorization
{:version 1
:rules
[{:match-request {:path "/metrics/v2/list" :type "path" :method ["get" "head" "post" "put"]}
:allow "localhost"
:sort-order 500
:name "list"}
{:match-request {:path "/metrics/v2" :type "path" :method ["get" "head" "post" "put"]}
:deny "localhost"
:sort-order 500
:name "metrics"}]}})
(deftest test-metrics-service-error
(testing "Metrics service throws an error if missing server-id"
(logging/with-test-logging
(is (thrown-with-msg?
ExceptionInfo
#"Value does not match schema: .*server-id missing-required-key.*"
(with-app-with-config
app
services
(ks/dissoc-in metrics-service-config [:metrics :server-id])))))))
(deftest test-metrics-service
(testing "Can boot metrics service and access registry"
(with-app-with-config
app
services
(assoc-in metrics-service-config [:metrics :metrics-webservice :mbeans :enabled] true)
(testing "metrics service functions"
(let [svc (app/get-service app :MetricsService)]
(testing "`get-metrics-registry` called without domain works"
(is (instance? MetricRegistry (metrics-protocol/get-metrics-registry svc))))
(testing "`get-metrics-registry` called with domain works"
(is (instance? MetricRegistry
(metrics-protocol/get-metrics-registry svc :pl.foo.reg))))
(testing "`get-server-id` works"
(is (= "localhost" (metrics-protocol/get-server-id svc))))))
(testing "returns latest status for all services"
(let [resp (http-client/get ":8180/metrics/v1/mbeans")
body (parse-response resp)]
(is (= 200 (:status resp)))
(doseq [[metric path] body
:let [resp (http-client/get (str ":8180/metrics/v1" path))]]
(is (= 200 (:status resp)))))
(let [resp (http-client/get ":8180/metrics/v2/list/java.lang")
body (parse-response resp)]
(is (= 200 (:status resp)))
(doseq [mbean (keys (get body "value"))
:let [url (str ":8180/metrics/v2/read/"
(jolokia-encode (str "java.lang:" mbean))
implement MBean attributes . This results
"?ignoreErrors=true")
resp (http-client/get url)
body (parse-response resp)]]
NOTE : returns 200 OK for most responses . The actual
(is (= 200 (get body "status"))))))
(testing "register should add a metric to the registry with a keyword domain"
(let [svc (app/get-service app :MetricsService)
register-and-get-metric (fn [domain metric]
(metrics/register
(metrics-protocol/get-metrics-registry svc domain)
(metrics/host-metric-name "localhost" metric)
(metrics/gauge 2))
(http-client/get
(str ":8180/metrics/v1/mbeans/"
(codec/url-encode
(str (name domain) ":name=puppetlabs.localhost." metric)))))
resp (register-and-get-metric :pl.test.reg "foo")]
(is (= 200 (:status resp)))
(is (= {"Value" 2} (parse-response resp)))))
(testing "querying multiple metrics via POST should work"
(let [svc (app/get-service app :MetricsService)
registry (metrics-protocol/get-metrics-registry svc :pl.other.reg)]
(metrics/register registry
(metrics/host-metric-name "localhost" "foo")
(metrics/gauge 2))
(metrics/register registry
(metrics/host-metric-name "localhost" "bar")
(metrics/gauge 500))
(let [resp (http-client/post
":8180/metrics/v1/mbeans"
{:body (json/generate-string
["pl.other.reg:name=puppetlabs.localhost.foo"
"pl.other.reg:name=puppetlabs.localhost.bar"])})
body (parse-response resp)]
(is (= 200 (:status resp)))
(is (= [{"Value" 2} {"Value" 500}] body)))
(let [resp (http-client/post
":8180/metrics/v1/mbeans"
{:body (json/generate-string
{:foo "pl.other.reg:name=puppetlabs.localhost.foo"
:bar "pl.other.reg:name=puppetlabs.localhost.bar"})})
body (parse-response resp)]
(is (= 200 (:status resp)))
(is (= {"foo" {"Value" 2}
"bar" {"Value" 500}} body)))
(let [resp (http-client/post
":8180/metrics/v1/mbeans"
{:body (json/generate-string
"pl.other.reg:name=puppetlabs.localhost.foo")})
body (parse-response resp)]
(is (= 200 (:status resp)))
(is (= {"Value" 2} body)))
(let [resp (http-client/post
":8180/metrics/v1/mbeans"
{:body "{\"malformed json"})
body (slurp (:body resp))]
(is (= 400 (:status resp)))
(is (re-find #"Unexpected end-of-input" body)))
(let [resp (http-client/post
":8180/metrics/v2"
{:body (json/generate-string
[{:type "read" :mbean "pl.other.reg:name=puppetlabs.localhost.foo"}
{:type "read" :mbean "pl.other.reg:name=puppetlabs.localhost.bar"}])})
body (parse-response resp true)]
(is (= [200 200] (map :status body)))
(is (= [{:Value 2} {:Value 500}] (map :value body))))))
(testing "metrics/v2 should deny write requests"
(with-test-logging
(let [resp (http-client/get
(str ":8180/metrics/v2/write/"
(jolokia-encode "java.lang:type=Memory")
"/Verbose/true"))
body (parse-response resp)]
(is (= 403 (get body "status"))))))
(testing "metrics/v2 should deny exec requests"
(with-test-logging
(let [resp (http-client/get
(str ":8180/metrics/v2/exec/"
(jolokia-encode "java.util.logging:type=Logging")
"/getLoggerLevel/root"))
body (parse-response resp)]
(is (= 403 (get body "status")))))))))
(deftest metrics-service-with-tk-auth
(testing "tk-auth works when included in bootstrap"
(with-app-with-config
app
(conj services authorization-service/authorization-service)
(merge metrics-service-config auth-config ssl-webserver-config)
(let [resp (http-client/get ":8180/metrics/v2/list" ssl-opts)]
(is (= 200 (:status resp))))
(let [resp (http-client/get ":8180/metrics/v2" ssl-opts)]
(is (= 403 (:status resp)))))))
(deftest metrics-v1-endpoint-disabled-by-default
(testing "metrics/v1 is disabled by default, returns 404"
(with-app-with-config
app
[jetty9-service/jetty9-service
webrouting-service/webrouting-service
metrics-service
metrics-webservice]
metrics-service-config
(let [resp (http-client/get ":8180/metrics/v1/mbeans")]
(is (= 404 (:status resp)))))))
(deftest metrics-endpoint-with-jolokia-disabled-test
(testing "metrics/v2 returns 404 when Jolokia is not enabled"
(let [config (assoc-in metrics-service-config [:metrics :metrics-webservice :jolokia :enabled] false)]
(with-app-with-config
app
[jetty9-service/jetty9-service
webrouting-service/webrouting-service
metrics-service
metrics-webservice]
config
(let [resp (http-client/get ":8180/metrics/v2/version")]
(is (= 404 (:status resp))))))))
(deftest metrics-endpoint-with-permissive-jolokia-policy
(testing "metrics/v2 allows exec requests when configured with a permissive policy"
(let [config (assoc-in metrics-service-config
[:metrics :metrics-webservice :jolokia :servlet-init-params :policyLocation]
(str "file://" test-resources-dir "/jolokia-access-permissive.xml"))]
(with-app-with-config
app
[jetty9-service/jetty9-service
webrouting-service/webrouting-service
metrics-service
metrics-webservice]
config
(let [resp (http-client/get
(str ":8180/metrics/v2/exec/"
(jolokia-encode "java.util.logging:type=Logging")
"/getLoggerLevel/root"))
body (parse-response resp)]
(is (= 200 (get body "status"))))))))
(deftest metrics-endpoint-with-jmx-disabled-test
(testing "returns data for jvm even when jmx is not enabled"
(let [config (-> metrics-service-config
(assoc-in [:metrics :metrics-webservice :mbeans :enabled] true)
(assoc :registries
{:pl.no.jmx {:reporters
{:jmx
{:enabled false}}}}))]
(with-app-with-config
app
[jetty9-service/jetty9-service
webrouting-service/webrouting-service
metrics-service
metrics-webservice]
config
(testing "returns latest status for all services"
(let [resp (http-client/get ":8180/metrics/v1/mbeans")
body (parse-response resp)]
(is (= 200 (:status resp)))
(is (not (empty? body)))))
(testing "returns Memoory mbean information"
(let [resp (http-client/get ":8180/metrics/v1/mbeans/java.lang%3Atype%3DMemory")
body (parse-response resp)
heap-memory (get body "HeapMemoryUsage")]
(is (= 200 (:status resp)))
(is (= #{"committed" "init" "max" "used"} (ks/keyset heap-memory)))
(is (every? #(< 0 %) (vals heap-memory)))))))))
(deftest get-metrics-registry-service-function-test
(with-app-with-config
app
[metrics-service]
{:metrics {:server-id "localhost"}}
(let [svc (app/get-service app :MetricsService)]
(testing "Can access default registry"
(is (instance? MetricRegistry (metrics-protocol/get-metrics-registry svc))))
(testing "Can access other registries registry"
(is (instance? MetricRegistry (metrics-protocol/get-metrics-registry svc :my-domain)))))))
(deftest get-server-id-service-function-test
(with-app-with-config
app
[metrics-service]
{:metrics {:server-id "foo"}}
(let [svc (app/get-service app :MetricsService)]
(testing "Can access server-id"
(is (= "foo" (metrics-protocol/get-server-id svc)))))))
(deftest update-registry-settings-service-function-test
(testing "intialize-registry-settings adds settings for a registry"
(let [service (trapperkeeper/service
[[:MetricsService update-registry-settings]]
(init [this context]
(update-registry-settings :foo.bar {:default-metrics-allowed ["foo.bar"]})
context))
metrics-app (trapperkeeper/build-app [service metrics-service]
{:metrics utils/test-config})
metrics-svc (app/get-service metrics-app :MetricsService)]
(try
(app/init metrics-app)
(is (= {:foo.bar {:default-metrics-allowed ["foo.bar"]}}
@(:registry-settings (tk-services/service-context metrics-svc))))
(finally
(app/stop metrics-app)))))
(testing "update-registry-settings throws an error if called outside `init`"
(let [service (trapperkeeper/service
[[:MetricsService update-registry-settings]]
(start [this context]
(update-registry-settings :nope {:default-metrics-allowed ["fail"]})
context))
metrics-app (trapperkeeper/build-app [service metrics-service]
{:metrics utils/test-config})]
(with-test-logging
(try
(is (thrown? RuntimeException (app/check-for-errors! (app/start metrics-app))))
(finally
(app/stop metrics-app)))))))
(deftest jmx-enabled-globally-deprecated-test
(with-test-logging
(with-app-with-config
app
[metrics-service]
{:metrics {:server-id "localhost"
:reporters {:jmx {:enabled true}}}})
(is (logged? #"Enabling JMX globally is deprecated; JMX can only be enabled per-registry."))))
(deftest jmx-works-test
(with-app-with-config
app
[metrics-service]
{:metrics {:server-id "localhost"
:registries {:jmx.registry {:reporters {:jmx {:enabled true}}}
:no.jmx.registry {:reporters {:jmx {:enabled false}}}
:foo {:metrics-allowed ["foo"]}}}}
(let [svc (app/get-service app :MetricsService)
context (tk-services/service-context svc)
get-jmx-reporter (fn [domain] (get-in @(:registries context) [domain :jmx-reporter]))]
(testing "Registry with jmx enabled gets a jmx reporter"
(metrics-protocol/get-metrics-registry svc :jmx.registry)
(is (instance? JmxReporter (get-jmx-reporter :jmx.registry))))
(testing "Registry with jmx disabled does not get a jmx reporter"
(metrics-protocol/get-metrics-registry svc :jmx.registry)
(is (nil? (get-jmx-reporter :no.jmx.registry))))
(testing "Registry with no mention of jmx does not get a jmx reporter"
(metrics-protocol/get-metrics-registry svc :foo)
(is (nil? (get-jmx-reporter :foo))))
(testing "Registry not mentioned in config does not get a jmx reporter"
(metrics-protocol/get-metrics-registry svc :not.in.the.config)
(is (nil? (get-jmx-reporter :not.in.the.config)))))))
(defn create-meters!
[registries meter-names]
(doseq [{:keys [registry]} (vals registries)
meter meter-names]
(.meter registry meter )))
(defn report-to-graphite!
[registries]
(doseq [graphite-reporter (map :graphite-reporter (vals registries))]
(when graphite-reporter
(.report graphite-reporter))))
(def graphite-enabled
{:reporters {:graphite {:enabled true}}})
(def metrics-allowed
{:metrics-allowed ["not-default"]})
(def default-metrics-allowed
{:default-metrics-allowed ["default"]})
(deftest integration-test
(let [registries-config
{:graphite-enabled graphite-enabled
:graphite-with-default-metrics-allowed graphite-enabled
:graphite-with-metrics-allowed (merge metrics-allowed graphite-enabled)
:graphite-with-defaults-and-metrics-allowed (merge metrics-allowed graphite-enabled)}
config {:metrics (utils/build-config-with-registries registries-config)}
service (trapperkeeper/service
[[:MetricsService get-metrics-registry update-registry-settings]]
(init
[this context]
(get-metrics-registry :graphite-enabled)
(get-metrics-registry :graphite-with-default-metrics-allowed)
(update-registry-settings :graphite-with-default-metrics-allowed
default-metrics-allowed)
(get-metrics-registry :graphite-with-metrics-allowed)
` update - registry - settings ` is called first
(update-registry-settings :graphite-with-defaults-and-metrics-allowed
default-metrics-allowed)
(get-metrics-registry :graphite-with-defaults-and-metrics-allowed)
context))
reported-metrics-atom (atom {})]
(with-redefs [core/build-graphite-sender
(fn [_ domain] (utils/make-graphite-sender reported-metrics-atom domain))]
(let [metrics-app (trapperkeeper/build-app
[metrics-service service]
config)
metrics-svc (app/get-service metrics-app :MetricsService)
get-context (fn [] (tk-services/service-context metrics-svc))]
(try
(testing "init phase of lifecycle"
(app/init metrics-app)
(let [context (get-context)
registries @(:registries context)
registry-settings @(:registry-settings context)]
(testing "all registries in config (plus default) get created"
(is (= #{:default
:graphite-enabled
:graphite-with-default-metrics-allowed
:graphite-with-metrics-allowed
:graphite-with-defaults-and-metrics-allowed}
(ks/keyset registries)))
(is (every? #(instance? MetricRegistry %)
(map :registry (vals registries)))))
(testing "graphite reporters are not created in it"
(is (every? nil? (map :graphite-reproter (vals registries)))))
(testing "registry settings are initialized in init"
(is (= {:graphite-with-default-metrics-allowed default-metrics-allowed
:graphite-with-defaults-and-metrics-allowed default-metrics-allowed}
registry-settings)))))
(testing "start phase of lifecycle"
(app/start metrics-app)
(let [context (get-context)
registries @(:registries context)
registry-settings @(:registry-settings context)]
(testing "graphite reporters are created in start"
(is (every? #(instance? MetricRegistry %)
(map :registry (vals registries))))
(is (every? #(instance? GraphiteReporter %)
(map :graphite-reporter (vals (dissoc registries :default)))))
(is (nil? (get-in registries [:default :graphite-reporter]))))
(testing "the right metrics are reported to graphite"
(create-meters! registries ["puppetlabs.localhost.default"
"puppetlabs.localhost.not-default"
"puppetlabs.localhost.foo"])
(report-to-graphite! registries)
(let [reported-metrics @reported-metrics-atom]
(is (= #{:graphite-enabled
:graphite-with-default-metrics-allowed
:graphite-with-metrics-allowed
:graphite-with-defaults-and-metrics-allowed}
(ks/keyset reported-metrics)))
(testing "without any metrics filter configured all metrics are reported"
(is (utils/reported? reported-metrics
:graphite-enabled
"puppetlabs.localhost.foo.count"))
(is (utils/reported? reported-metrics
:graphite-enabled
"puppetlabs.localhost.default.count"))
(is (utils/reported? reported-metrics
:graphite-enabled
"puppetlabs.localhost.not-default.count")))
(testing "default metrics are reported to graphite"
(is (not (utils/reported? reported-metrics
:graphite-with-default-metrics-allowed
"puppetlabs.localhost.foo.count")))
(is (utils/reported? reported-metrics
:graphite-with-default-metrics-allowed
"puppetlabs.localhost.default.count"))
(is (not (utils/reported? reported-metrics
:graphite-with-default-metrics-allowed
"puppetlabs.localhost.not-default.count"))))
(testing "configured metrics are reported to graphite"
(is (not (utils/reported? reported-metrics
:graphite-with-metrics-allowed
"puppetlabs.localhost.foo.count")))
(is (not (utils/reported? reported-metrics
:graphite-with-metrics-allowed
"puppetlabs.localhost.default.count")))
(is (utils/reported? reported-metrics
:graphite-with-metrics-allowed
"puppetlabs.localhost.not-default.count")))
(testing "configured metrics and default allowed metrics are reported to graphite"
(is (not (utils/reported? reported-metrics
:graphite-with-defaults-and-metrics-allowed
"localhost.foo.count")))
(is (utils/reported? reported-metrics
:graphite-with-defaults-and-metrics-allowed
"puppetlabs.localhost.default.count"))
(is (utils/reported? reported-metrics
:graphite-with-defaults-and-metrics-allowed
"puppetlabs.localhost.not-default.count")))))))
(finally
(app/stop metrics-app)))))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.