_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 |
|---|---|---|---|---|---|---|---|---|
2ac19f2d000d45a13766eced387b9bbfae553a142033dd5d013d4ba0b54a819c | wireless-net/erlang-nommu | instrument_SUITE.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1998 - 2011 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
-module(instrument_SUITE).
-export([all/0, suite/0,groups/0,init_per_suite/1, end_per_suite/1,
init_per_group/2,end_per_group/2,
init_per_testcase/2,end_per_testcase/2]).
-export(['+Mim true'/1, '+Mis true'/1]).
-include_lib("test_server/include/test_server.hrl").
init_per_testcase(_Case, Config) ->
?line Dog=?t:timetrap(10000),
[{watchdog, Dog}|Config].
end_per_testcase(_Case, Config) ->
Dog=?config(watchdog, Config),
?t:timetrap_cancel(Dog),
ok.
suite() -> [{ct_hooks,[ts_install_cth]}].
all() ->
['+Mim true', '+Mis true'].
groups() ->
[].
init_per_suite(Config) ->
Config.
end_per_suite(_Config) ->
ok.
init_per_group(_GroupName, Config) ->
Config.
end_per_group(_GroupName, Config) ->
Config.
'+Mim true'(doc) -> ["Check that memory data can be read and processed"];
'+Mim true'(suite) -> [];
'+Mim true'(Config) when is_list(Config) ->
?line Node = start_slave("+Mim true"),
?line MD = rpc:call(Node, instrument, memory_data, []),
?line [{total,[{sizes,S1,S2,S3},{blocks,B1,B2,B3}]}]
= rpc:call(Node, instrument, memory_status, [total]),
?line stop_slave(Node),
?line true = S1 =< S2,
?line true = S2 =< S3,
?line true = B1 =< B2,
?line true = B2 =< B3,
?line MDS = instrument:sort(MD),
?line {Low, High} = instrument:mem_limits(MDS),
?line true = Low < High,
?line {_, AL} = MDS,
?line SumBlocks = instrument:sum_blocks(MD),
?line case SumBlocks of
N when is_integer(N) ->
?line N = lists:foldl(fun ({_,_,Size,_}, Sum) ->
Size+Sum
end,
0,
AL),
?line N =< S3;
Other ->
?line ?t:fail(Other)
end,
?line lists:foldl(
fun ({TDescr,Addr,Size,Proc}, MinAddr) ->
?line true = TDescr /= invalid_type,
?line true = is_integer(TDescr),
?line true = is_integer(Addr),
?line true = is_integer(Size),
?line true = Addr >= MinAddr,
?line case Proc of
{0, Number, Serial} ->
?line true = is_integer(Number),
?line true = is_integer(Serial);
undefined ->
ok;
BadProc ->
?line ?t:fail({badproc, BadProc})
end,
?line NextMinAddr = Addr+Size,
?line true = NextMinAddr =< High,
?line NextMinAddr
end,
Low,
AL),
?line {_, DAL} = instrument:descr(MDS),
?line lists:foreach(
fun ({TDescr,_,_,Proc}) ->
?line true = TDescr /= invalid_type,
?line true = is_atom(TDescr) orelse is_list(TDescr),
?line true = is_pid(Proc) orelse Proc == undefined
end,
DAL),
?line ASL = lists:map(fun ({_,A,S,_}) -> {A,S} end, AL),
?line ASL = lists:map(fun ({_,A,S,_}) -> {A,S} end, DAL),
?line instrument:holes(MDS),
?line {comment,
"total status - sum of blocks = " ++ integer_to_list(S1-SumBlocks)}.
'+Mis true'(doc) -> ["Check that memory data can be read and processed"];
'+Mis true'(suite) -> [];
'+Mis true'(Config) when is_list(Config) ->
?line Node = start_slave("+Mis true"),
?line [{total,[{sizes,S1,S2,S3},{blocks,B1,B2,B3}]}]
= rpc:call(Node, instrument, memory_status, [total]),
?line true = S1 =< S2,
?line true = S2 =< S3,
?line true = B1 =< B2,
?line true = B2 =< B3,
?line true = is_list(rpc:call(Node,instrument,memory_status,[allocators])),
?line true = is_list(rpc:call(Node,instrument,memory_status,[classes])),
?line true = is_list(rpc:call(Node,instrument,memory_status,[types])),
?line ok.
start_slave(Args) ->
?line {A, B, C} = now(),
?line MicroSecs = A*1000000000000 + B*1000000 + C,
?line Name = "instr_" ++ integer_to_list(MicroSecs),
?line Pa = filename:dirname(code:which(?MODULE)),
?line {ok, Node} = ?t:start_node(list_to_atom(Name),
slave,
[{args, "-pa " ++ Pa ++ " " ++ Args}]),
?line Node.
stop_slave(Node) ->
?line true = ?t:stop_node(Node).
| null | https://raw.githubusercontent.com/wireless-net/erlang-nommu/79f32f81418e022d8ad8e0e447deaea407289926/lib/tools/test/instrument_SUITE.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
| Copyright Ericsson AB 1998 - 2011 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(instrument_SUITE).
-export([all/0, suite/0,groups/0,init_per_suite/1, end_per_suite/1,
init_per_group/2,end_per_group/2,
init_per_testcase/2,end_per_testcase/2]).
-export(['+Mim true'/1, '+Mis true'/1]).
-include_lib("test_server/include/test_server.hrl").
init_per_testcase(_Case, Config) ->
?line Dog=?t:timetrap(10000),
[{watchdog, Dog}|Config].
end_per_testcase(_Case, Config) ->
Dog=?config(watchdog, Config),
?t:timetrap_cancel(Dog),
ok.
suite() -> [{ct_hooks,[ts_install_cth]}].
all() ->
['+Mim true', '+Mis true'].
groups() ->
[].
init_per_suite(Config) ->
Config.
end_per_suite(_Config) ->
ok.
init_per_group(_GroupName, Config) ->
Config.
end_per_group(_GroupName, Config) ->
Config.
'+Mim true'(doc) -> ["Check that memory data can be read and processed"];
'+Mim true'(suite) -> [];
'+Mim true'(Config) when is_list(Config) ->
?line Node = start_slave("+Mim true"),
?line MD = rpc:call(Node, instrument, memory_data, []),
?line [{total,[{sizes,S1,S2,S3},{blocks,B1,B2,B3}]}]
= rpc:call(Node, instrument, memory_status, [total]),
?line stop_slave(Node),
?line true = S1 =< S2,
?line true = S2 =< S3,
?line true = B1 =< B2,
?line true = B2 =< B3,
?line MDS = instrument:sort(MD),
?line {Low, High} = instrument:mem_limits(MDS),
?line true = Low < High,
?line {_, AL} = MDS,
?line SumBlocks = instrument:sum_blocks(MD),
?line case SumBlocks of
N when is_integer(N) ->
?line N = lists:foldl(fun ({_,_,Size,_}, Sum) ->
Size+Sum
end,
0,
AL),
?line N =< S3;
Other ->
?line ?t:fail(Other)
end,
?line lists:foldl(
fun ({TDescr,Addr,Size,Proc}, MinAddr) ->
?line true = TDescr /= invalid_type,
?line true = is_integer(TDescr),
?line true = is_integer(Addr),
?line true = is_integer(Size),
?line true = Addr >= MinAddr,
?line case Proc of
{0, Number, Serial} ->
?line true = is_integer(Number),
?line true = is_integer(Serial);
undefined ->
ok;
BadProc ->
?line ?t:fail({badproc, BadProc})
end,
?line NextMinAddr = Addr+Size,
?line true = NextMinAddr =< High,
?line NextMinAddr
end,
Low,
AL),
?line {_, DAL} = instrument:descr(MDS),
?line lists:foreach(
fun ({TDescr,_,_,Proc}) ->
?line true = TDescr /= invalid_type,
?line true = is_atom(TDescr) orelse is_list(TDescr),
?line true = is_pid(Proc) orelse Proc == undefined
end,
DAL),
?line ASL = lists:map(fun ({_,A,S,_}) -> {A,S} end, AL),
?line ASL = lists:map(fun ({_,A,S,_}) -> {A,S} end, DAL),
?line instrument:holes(MDS),
?line {comment,
"total status - sum of blocks = " ++ integer_to_list(S1-SumBlocks)}.
'+Mis true'(doc) -> ["Check that memory data can be read and processed"];
'+Mis true'(suite) -> [];
'+Mis true'(Config) when is_list(Config) ->
?line Node = start_slave("+Mis true"),
?line [{total,[{sizes,S1,S2,S3},{blocks,B1,B2,B3}]}]
= rpc:call(Node, instrument, memory_status, [total]),
?line true = S1 =< S2,
?line true = S2 =< S3,
?line true = B1 =< B2,
?line true = B2 =< B3,
?line true = is_list(rpc:call(Node,instrument,memory_status,[allocators])),
?line true = is_list(rpc:call(Node,instrument,memory_status,[classes])),
?line true = is_list(rpc:call(Node,instrument,memory_status,[types])),
?line ok.
start_slave(Args) ->
?line {A, B, C} = now(),
?line MicroSecs = A*1000000000000 + B*1000000 + C,
?line Name = "instr_" ++ integer_to_list(MicroSecs),
?line Pa = filename:dirname(code:which(?MODULE)),
?line {ok, Node} = ?t:start_node(list_to_atom(Name),
slave,
[{args, "-pa " ++ Pa ++ " " ++ Args}]),
?line Node.
stop_slave(Node) ->
?line true = ?t:stop_node(Node).
|
6bb6f503b06b6bfef5cdb7193cb292c267e30b731c55ef9e2ba2e96c286b2902 | m4b/rdr | PEHeader.ml | open Binary
type dos_header =
{
5a4d
at offset 0x3c
}
let pp_dos_header ppf dos =
Format.fprintf ppf "@[DOS@ %x@ PE -> 0x%x@]"
dos.signature
dos.pe_pointer
let kDOS_MAGIC = 0x5a4d
let kDOS_CIGAM = 0x4d5a
let kPE_POINTER_OFFSET = 0x3c
(* COFF Header *)
type coff_header =
{
signature: int [@size 4, be]; (* 0x50450000 *)
machine: int [@size 2];
number_of_sections: int [@size 2];
time_date_stamp: int [@size 4];
pointer_to_symbol_table: int [@size 4];
number_of_symbol_table: int [@size 4];
size_of_optional_header: int [@size 2];
characteristics: int [@size 2];
}
let sizeof_coff_header = 24 (* bytes *)
let kCOFF_MAGIC = 0x50450000
let pp_coff_header ppf coff =
Format.fprintf ppf
"@[<v 2>@[<h>COFF@ 0x%x@]@ Machine: 0x%x@ NumberOfSections: %d@ TimeDateStamp: %d@ PointerToSymbolTable: 0x%x@ NumberOfSymbolTable: %d@ SizeOfOptionalHeader: 0x%x@ Characteristics: 0x%x@]"
coff.signature
coff.machine
coff.number_of_sections
coff.time_date_stamp
coff.pointer_to_symbol_table
coff.number_of_symbol_table
coff.size_of_optional_header
coff.characteristics
type t = {
dos_header: dos_header;
coff_header: coff_header;
optional_header: PEOptionalHeader.t option;
}
let pp ppf t =
Format.fprintf ppf "@[<v 2>@ ";
pp_dos_header ppf t.dos_header;
Format.fprintf ppf "@ ";
pp_coff_header ppf t.coff_header;
begin
match t.optional_header with
| Some header ->
PEOptionalHeader.pp ppf header;
| None ->
Format.fprintf ppf "@ **No Optional Headers**"
end;
Format.fprintf ppf "@]"
let show t =
pp Format.str_formatter t;
Format.flush_str_formatter()
let print t =
pp Format.std_formatter t;
Format.print_newline()
let get_dos_header binary offset :dos_header =
let signature,o = Binary.u16o binary offset in
let pe_pointer = Binary.u32 binary (offset+kPE_POINTER_OFFSET) in
{signature;pe_pointer;}
let get_coff_header binary offset :coff_header =
let signature,o = Binary.u32o binary offset in
let machine,o = Binary.u16o binary o in
let number_of_sections,o = Binary.u16o binary o in
let time_date_stamp,o = Binary.u32o binary o in
let pointer_to_symbol_table,o = Binary.u32o binary o in
let number_of_symbol_table,o = Binary.u32o binary o in
let size_of_optional_header,o = Binary.u16o binary o in
let characteristics = Binary.u16 binary o in
{signature;machine;number_of_sections;time_date_stamp;pointer_to_symbol_table;number_of_symbol_table;size_of_optional_header;characteristics;}
let get_header binary =
let dos_header = get_dos_header binary 0 in
let coff_header_offset = dos_header.pe_pointer in
let coff_header = get_coff_header binary coff_header_offset in
let optional_offset = sizeof_coff_header + coff_header_offset in
let optional_header =
if (coff_header.size_of_optional_header > 0) then
Some (PEOptionalHeader.get binary optional_offset)
else
None
in
{dos_header; coff_header;optional_header;}
let csrss_header = get_header @@ list_to_bytes [0x4d; 0x5a; 0x90; 0x00; 0x03; 0x00; 0x00; 0x00; 0x04; 0x00; 0x00; 0x00; 0xff; 0xff; 0x00; 0x00;
0xb8; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x40; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0xd0; 0x00; 0x00; 0x00;
0x0e; 0x1f; 0xba; 0x0e; 0x00; 0xb4; 0x09; 0xcd; 0x21; 0xb8; 0x01; 0x4c; 0xcd; 0x21; 0x54; 0x68;
0x69; 0x73; 0x20; 0x70; 0x72; 0x6f; 0x67; 0x72; 0x61; 0x6d; 0x20; 0x63; 0x61; 0x6e; 0x6e; 0x6f;
0x74; 0x20; 0x62; 0x65; 0x20; 0x72; 0x75; 0x6e; 0x20; 0x69; 0x6e; 0x20; 0x44; 0x4f; 0x53; 0x20;
0x6d; 0x6f; 0x64; 0x65; 0x2e; 0x0d; 0x0d; 0x0a; 0x24; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00;
0xaa; 0x4a; 0xc3; 0xeb; 0xee; 0x2b; 0xad; 0xb8; 0xee; 0x2b; 0xad; 0xb8; 0xee; 0x2b; 0xad; 0xb8;
0xee; 0x2b; 0xac; 0xb8; 0xfe; 0x2b; 0xad; 0xb8; 0x33; 0xd4; 0x66; 0xb8; 0xeb; 0x2b; 0xad; 0xb8;
0x33; 0xd4; 0x63; 0xb8; 0xea; 0x2b; 0xad; 0xb8; 0x33; 0xd4; 0x7a; 0xb8; 0xed; 0x2b; 0xad; 0xb8;
0x33; 0xd4; 0x64; 0xb8; 0xef; 0x2b; 0xad; 0xb8; 0x33; 0xd4; 0x61; 0xb8; 0xef; 0x2b; 0xad; 0xb8;
0x52; 0x69; 0x63; 0x68; 0xee; 0x2b; 0xad; 0xb8; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00;
0x50; 0x45; 0x00; 0x00; 0x4c; 0x01; 0x05; 0x00; 0xd9; 0x8f; 0x15; 0x52; 0x00; 0x00; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0xe0; 0x00; 0x02; 0x01; 0x0b; 0x01; 0x0b; 0x00; 0x00; 0x08; 0x00; 0x00;
0x00; 0x10; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x10; 0x11; 0x00; 0x00; 0x00; 0x10; 0x00; 0x00;
0x00; 0x20; 0x00; 0x00; 0x00; 0x00; 0x40; 0x00; 0x00; 0x10; 0x00; 0x00; 0x00; 0x02; 0x00; 0x00;
0x06; 0x00; 0x03; 0x00; 0x06; 0x00; 0x03; 0x00; 0x06; 0x00; 0x03; 0x00; 0x00; 0x00; 0x00; 0x00;
0x00; 0x60; 0x00; 0x00; 0x00; 0x04; 0x00; 0x00; 0xe4; 0xab; 0x00; 0x00; 0x01; 0x00; 0x40; 0x05;
0x00; 0x00; 0x04; 0x00; 0x00; 0x30; 0x00; 0x00; 0x00; 0x00; 0x10; 0x00; 0x00; 0x10; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x10; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00;
0x3c; 0x30; 0x00; 0x00; 0x3c; 0x00; 0x00; 0x00; 0x00; 0x40; 0x00; 0x00; 0x00; 0x08; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x1a; 0x00; 0x00; 0xb8; 0x22; 0x00; 0x00;
0x00; 0x50; 0x00; 0x00; 0x38; 0x00; 0x00; 0x00; 0x10; 0x10; 0x00; 0x00; 0x38; 0x00; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x68; 0x10; 0x00; 0x00; 0x5c; 0x00; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x30; 0x00; 0x00; 0x3c; 0x00; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x2e; 0x74; 0x65; 0x78; 0x74; 0x00; 0x00; 0x00;
0x24; 0x06; 0x00; 0x00; 0x00; 0x10; 0x00; 0x00; 0x00; 0x08; 0x00; 0x00; 0x00; 0x04; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x20; 0x00; 0x00; 0x60;
0x2e; 0x64; 0x61; 0x74; 0x61; 0x00; 0x00; 0x00; 0x3c; 0x03; 0x00; 0x00; 0x00; 0x20; 0x00; 0x00;
0x00; 0x02; 0x00; 0x00; 0x00; 0x0c; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x40; 0x00; 0x00; 0xc0; 0x2e; 0x69; 0x64; 0x61; 0x74; 0x61; 0x00; 0x00;
0xf8; 0x01; 0x00; 0x00; 0x00; 0x30; 0x00; 0x00; 0x00; 0x02; 0x00; 0x00; 0x00; 0x0e; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x40; 0x00; 0x00; 0x40;
0x2e; 0x72; 0x73; 0x72; 0x63; 0x00; 0x00; 0x00; 0x00; 0x08; 0x00; 0x00; 0x00; 0x40; 0x00; 0x00;
0x00; 0x08; 0x00; 0x00; 0x00; 0x10; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x40; 0x00; 0x00; 0x42; 0x2e; 0x72; 0x65; 0x6c; 0x6f; 0x63; 0x00; 0x00;
0x86; 0x01; 0x00; 0x00; 0x00; 0x50; 0x00; 0x00; 0x00; 0x02; 0x00; 0x00; 0x00; 0x18; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x40; 0x00; 0x00; 0x42;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00;]
let to_hex hex = Printf.printf "0x%x\n" hex
| null | https://raw.githubusercontent.com/m4b/rdr/2bf1f73fc317cd74f8c7cacd542889df729bd003/lib/pe/PEHeader.ml | ocaml | COFF Header
0x50450000
bytes | open Binary
type dos_header =
{
5a4d
at offset 0x3c
}
let pp_dos_header ppf dos =
Format.fprintf ppf "@[DOS@ %x@ PE -> 0x%x@]"
dos.signature
dos.pe_pointer
let kDOS_MAGIC = 0x5a4d
let kDOS_CIGAM = 0x4d5a
let kPE_POINTER_OFFSET = 0x3c
type coff_header =
{
machine: int [@size 2];
number_of_sections: int [@size 2];
time_date_stamp: int [@size 4];
pointer_to_symbol_table: int [@size 4];
number_of_symbol_table: int [@size 4];
size_of_optional_header: int [@size 2];
characteristics: int [@size 2];
}
let kCOFF_MAGIC = 0x50450000
let pp_coff_header ppf coff =
Format.fprintf ppf
"@[<v 2>@[<h>COFF@ 0x%x@]@ Machine: 0x%x@ NumberOfSections: %d@ TimeDateStamp: %d@ PointerToSymbolTable: 0x%x@ NumberOfSymbolTable: %d@ SizeOfOptionalHeader: 0x%x@ Characteristics: 0x%x@]"
coff.signature
coff.machine
coff.number_of_sections
coff.time_date_stamp
coff.pointer_to_symbol_table
coff.number_of_symbol_table
coff.size_of_optional_header
coff.characteristics
type t = {
dos_header: dos_header;
coff_header: coff_header;
optional_header: PEOptionalHeader.t option;
}
let pp ppf t =
Format.fprintf ppf "@[<v 2>@ ";
pp_dos_header ppf t.dos_header;
Format.fprintf ppf "@ ";
pp_coff_header ppf t.coff_header;
begin
match t.optional_header with
| Some header ->
PEOptionalHeader.pp ppf header;
| None ->
Format.fprintf ppf "@ **No Optional Headers**"
end;
Format.fprintf ppf "@]"
let show t =
pp Format.str_formatter t;
Format.flush_str_formatter()
let print t =
pp Format.std_formatter t;
Format.print_newline()
let get_dos_header binary offset :dos_header =
let signature,o = Binary.u16o binary offset in
let pe_pointer = Binary.u32 binary (offset+kPE_POINTER_OFFSET) in
{signature;pe_pointer;}
let get_coff_header binary offset :coff_header =
let signature,o = Binary.u32o binary offset in
let machine,o = Binary.u16o binary o in
let number_of_sections,o = Binary.u16o binary o in
let time_date_stamp,o = Binary.u32o binary o in
let pointer_to_symbol_table,o = Binary.u32o binary o in
let number_of_symbol_table,o = Binary.u32o binary o in
let size_of_optional_header,o = Binary.u16o binary o in
let characteristics = Binary.u16 binary o in
{signature;machine;number_of_sections;time_date_stamp;pointer_to_symbol_table;number_of_symbol_table;size_of_optional_header;characteristics;}
let get_header binary =
let dos_header = get_dos_header binary 0 in
let coff_header_offset = dos_header.pe_pointer in
let coff_header = get_coff_header binary coff_header_offset in
let optional_offset = sizeof_coff_header + coff_header_offset in
let optional_header =
if (coff_header.size_of_optional_header > 0) then
Some (PEOptionalHeader.get binary optional_offset)
else
None
in
{dos_header; coff_header;optional_header;}
let csrss_header = get_header @@ list_to_bytes [0x4d; 0x5a; 0x90; 0x00; 0x03; 0x00; 0x00; 0x00; 0x04; 0x00; 0x00; 0x00; 0xff; 0xff; 0x00; 0x00;
0xb8; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x40; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0xd0; 0x00; 0x00; 0x00;
0x0e; 0x1f; 0xba; 0x0e; 0x00; 0xb4; 0x09; 0xcd; 0x21; 0xb8; 0x01; 0x4c; 0xcd; 0x21; 0x54; 0x68;
0x69; 0x73; 0x20; 0x70; 0x72; 0x6f; 0x67; 0x72; 0x61; 0x6d; 0x20; 0x63; 0x61; 0x6e; 0x6e; 0x6f;
0x74; 0x20; 0x62; 0x65; 0x20; 0x72; 0x75; 0x6e; 0x20; 0x69; 0x6e; 0x20; 0x44; 0x4f; 0x53; 0x20;
0x6d; 0x6f; 0x64; 0x65; 0x2e; 0x0d; 0x0d; 0x0a; 0x24; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00;
0xaa; 0x4a; 0xc3; 0xeb; 0xee; 0x2b; 0xad; 0xb8; 0xee; 0x2b; 0xad; 0xb8; 0xee; 0x2b; 0xad; 0xb8;
0xee; 0x2b; 0xac; 0xb8; 0xfe; 0x2b; 0xad; 0xb8; 0x33; 0xd4; 0x66; 0xb8; 0xeb; 0x2b; 0xad; 0xb8;
0x33; 0xd4; 0x63; 0xb8; 0xea; 0x2b; 0xad; 0xb8; 0x33; 0xd4; 0x7a; 0xb8; 0xed; 0x2b; 0xad; 0xb8;
0x33; 0xd4; 0x64; 0xb8; 0xef; 0x2b; 0xad; 0xb8; 0x33; 0xd4; 0x61; 0xb8; 0xef; 0x2b; 0xad; 0xb8;
0x52; 0x69; 0x63; 0x68; 0xee; 0x2b; 0xad; 0xb8; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00;
0x50; 0x45; 0x00; 0x00; 0x4c; 0x01; 0x05; 0x00; 0xd9; 0x8f; 0x15; 0x52; 0x00; 0x00; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0xe0; 0x00; 0x02; 0x01; 0x0b; 0x01; 0x0b; 0x00; 0x00; 0x08; 0x00; 0x00;
0x00; 0x10; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x10; 0x11; 0x00; 0x00; 0x00; 0x10; 0x00; 0x00;
0x00; 0x20; 0x00; 0x00; 0x00; 0x00; 0x40; 0x00; 0x00; 0x10; 0x00; 0x00; 0x00; 0x02; 0x00; 0x00;
0x06; 0x00; 0x03; 0x00; 0x06; 0x00; 0x03; 0x00; 0x06; 0x00; 0x03; 0x00; 0x00; 0x00; 0x00; 0x00;
0x00; 0x60; 0x00; 0x00; 0x00; 0x04; 0x00; 0x00; 0xe4; 0xab; 0x00; 0x00; 0x01; 0x00; 0x40; 0x05;
0x00; 0x00; 0x04; 0x00; 0x00; 0x30; 0x00; 0x00; 0x00; 0x00; 0x10; 0x00; 0x00; 0x10; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x10; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00;
0x3c; 0x30; 0x00; 0x00; 0x3c; 0x00; 0x00; 0x00; 0x00; 0x40; 0x00; 0x00; 0x00; 0x08; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x1a; 0x00; 0x00; 0xb8; 0x22; 0x00; 0x00;
0x00; 0x50; 0x00; 0x00; 0x38; 0x00; 0x00; 0x00; 0x10; 0x10; 0x00; 0x00; 0x38; 0x00; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x68; 0x10; 0x00; 0x00; 0x5c; 0x00; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x30; 0x00; 0x00; 0x3c; 0x00; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x2e; 0x74; 0x65; 0x78; 0x74; 0x00; 0x00; 0x00;
0x24; 0x06; 0x00; 0x00; 0x00; 0x10; 0x00; 0x00; 0x00; 0x08; 0x00; 0x00; 0x00; 0x04; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x20; 0x00; 0x00; 0x60;
0x2e; 0x64; 0x61; 0x74; 0x61; 0x00; 0x00; 0x00; 0x3c; 0x03; 0x00; 0x00; 0x00; 0x20; 0x00; 0x00;
0x00; 0x02; 0x00; 0x00; 0x00; 0x0c; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x40; 0x00; 0x00; 0xc0; 0x2e; 0x69; 0x64; 0x61; 0x74; 0x61; 0x00; 0x00;
0xf8; 0x01; 0x00; 0x00; 0x00; 0x30; 0x00; 0x00; 0x00; 0x02; 0x00; 0x00; 0x00; 0x0e; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x40; 0x00; 0x00; 0x40;
0x2e; 0x72; 0x73; 0x72; 0x63; 0x00; 0x00; 0x00; 0x00; 0x08; 0x00; 0x00; 0x00; 0x40; 0x00; 0x00;
0x00; 0x08; 0x00; 0x00; 0x00; 0x10; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x40; 0x00; 0x00; 0x42; 0x2e; 0x72; 0x65; 0x6c; 0x6f; 0x63; 0x00; 0x00;
0x86; 0x01; 0x00; 0x00; 0x00; 0x50; 0x00; 0x00; 0x00; 0x02; 0x00; 0x00; 0x00; 0x18; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x40; 0x00; 0x00; 0x42;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00;
0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00; 0x00;]
let to_hex hex = Printf.printf "0x%x\n" hex
|
033322ae6100cc8f63c3e6867c8c9d9a6dd891cf2db87e513b6df86b6aed237f | broom-lang/broom | TypeEnv.mli | module T = Fc.Type
module FExpr = Fc.Term.Expr
type var = FExpr.var
module Tx = Transactional
type span = Util.span
type val_binding =
| White of {span : span; pat : Ast.Expr.t; expr : Ast.Expr.t}
| Grey of {span : span; pat : Ast.Expr.t; expr : Ast.Expr.t}
| Black of {span : span; pat : FExpr.pat; expr : FExpr.t option}
type row_binding =
| WhiteT of {span : span; pat : Ast.Expr.t; typ : Ast.Expr.t}
| GreyT of span
| BlackT of {span : span; typ : T.t}
type nonrec_scope = var Name.HashMap.t * val_binding Tx.Ref.t
type rec_scope = (var * val_binding Tx.Ref.t) Name.HashMap.t
type row_scope = (var * row_binding Tx.Ref.t) Name.HashMap.t
type scope =
| Hoisting of T.ov list Tx.Ref.t * T.level
| Rigid of T.ov Vector.t
| NonRec of nonrec_scope
| Rec of rec_scope
| Row of row_scope
type env
module NonRecScope : sig
type t = nonrec_scope
module Builder : sig
type scope = t
type t
val create : unit -> t
val var : env -> t -> Util.plicity -> Name.t -> var
val build : t -> span -> FExpr.pat -> FExpr.t option -> scope
end
end
module RecScope : sig
type t = rec_scope
module Builder : sig
type scope = t
type t
val create : unit -> t
val binding : t -> span -> Ast.Expr.t -> Ast.Expr.t -> val_binding Tx.Ref.t
val var : env -> t -> val_binding Tx.Ref.t -> Util.plicity -> Name.t -> var
val build : t -> scope
end
end
module RowScope : sig
type t = row_scope
module Builder : sig
type scope = t
type t
val create : unit -> t
val binding : t -> span -> Ast.Expr.t -> Ast.Expr.t -> row_binding Tx.Ref.t
val var : env -> t -> row_binding Tx.Ref.t -> Util.plicity -> Name.t -> var
val build : t -> scope
end
end
type t = env
val empty : t
val toplevel : Namespace.t -> t
val namespace : t -> Namespace.t option
val type_fns : t -> T.def Vector.t
type error_handler = TypeError.t -> unit
val report_error : t -> error_handler
val with_error_handler : t -> error_handler -> t
val scopes : t -> scope list
val push_param : t -> var -> FExpr.pat -> t
val push_nonrec : t -> NonRecScope.t -> t
val push_rec : t -> RecScope.t -> t
val push_row : t -> RowScope.t -> t
val find_val : t -> Name.t -> (var * val_binding Tx.Ref.t * t) option
val implicits : t -> FExpr.var Streaming.Stream.t
val push_existential : t -> t * T.ov list Transactional.Ref.t
val generate : t -> T.def -> T.ov
val reabstract : t -> T.t -> T.ov Vector.t * T.t
val push_abs_skolems : t -> T.kind Vector1.t -> T.t -> t * T.ov Vector1.t * T.t
val instantiate_abs : t -> T.kind Vector1.t -> T.t -> T.uv Vector1.t * T.t
val push_arrow_skolems : t -> T.kind Vector.t -> T.t -> T.t -> T.t
-> t * T.ov Vector.t * T.t * T.t * T.t
val instantiate_arrow : t -> T.kind Vector.t -> T.t -> T.t -> T.t
-> T.uv Vector.t * T.t * T.t * T.t
val push_impli_skolems : t -> T.kind Vector.t -> T.t -> T.t
-> t * T.ov Vector.t * T.t * T.t
val instantiate_impli : t -> T.kind Vector.t -> T.t -> T.t
-> T.uv Vector.t * T.t * T.t
val instantiate_primop : t -> T.kind Vector.t -> T.t Vector.t -> T.t -> T.t
-> T.uv Vector.t * T.t Vector.t * T.t * T.t
val instantiate_branch : t -> T.kind Vector.t -> T.t Vector.t -> T.t -> T.t Vector.t
-> T.uv Vector.t * T.t Vector.t * T.t * T.t Vector.t
val uv : t -> bool -> T.kind -> T.uv
val some_type_kind : t -> bool -> T.t
| null | https://raw.githubusercontent.com/broom-lang/broom/8cc1b19c1a5a40846b362963a71be0003f477238/compiler/lib/Typechecker/TypeEnv.mli | ocaml | module T = Fc.Type
module FExpr = Fc.Term.Expr
type var = FExpr.var
module Tx = Transactional
type span = Util.span
type val_binding =
| White of {span : span; pat : Ast.Expr.t; expr : Ast.Expr.t}
| Grey of {span : span; pat : Ast.Expr.t; expr : Ast.Expr.t}
| Black of {span : span; pat : FExpr.pat; expr : FExpr.t option}
type row_binding =
| WhiteT of {span : span; pat : Ast.Expr.t; typ : Ast.Expr.t}
| GreyT of span
| BlackT of {span : span; typ : T.t}
type nonrec_scope = var Name.HashMap.t * val_binding Tx.Ref.t
type rec_scope = (var * val_binding Tx.Ref.t) Name.HashMap.t
type row_scope = (var * row_binding Tx.Ref.t) Name.HashMap.t
type scope =
| Hoisting of T.ov list Tx.Ref.t * T.level
| Rigid of T.ov Vector.t
| NonRec of nonrec_scope
| Rec of rec_scope
| Row of row_scope
type env
module NonRecScope : sig
type t = nonrec_scope
module Builder : sig
type scope = t
type t
val create : unit -> t
val var : env -> t -> Util.plicity -> Name.t -> var
val build : t -> span -> FExpr.pat -> FExpr.t option -> scope
end
end
module RecScope : sig
type t = rec_scope
module Builder : sig
type scope = t
type t
val create : unit -> t
val binding : t -> span -> Ast.Expr.t -> Ast.Expr.t -> val_binding Tx.Ref.t
val var : env -> t -> val_binding Tx.Ref.t -> Util.plicity -> Name.t -> var
val build : t -> scope
end
end
module RowScope : sig
type t = row_scope
module Builder : sig
type scope = t
type t
val create : unit -> t
val binding : t -> span -> Ast.Expr.t -> Ast.Expr.t -> row_binding Tx.Ref.t
val var : env -> t -> row_binding Tx.Ref.t -> Util.plicity -> Name.t -> var
val build : t -> scope
end
end
type t = env
val empty : t
val toplevel : Namespace.t -> t
val namespace : t -> Namespace.t option
val type_fns : t -> T.def Vector.t
type error_handler = TypeError.t -> unit
val report_error : t -> error_handler
val with_error_handler : t -> error_handler -> t
val scopes : t -> scope list
val push_param : t -> var -> FExpr.pat -> t
val push_nonrec : t -> NonRecScope.t -> t
val push_rec : t -> RecScope.t -> t
val push_row : t -> RowScope.t -> t
val find_val : t -> Name.t -> (var * val_binding Tx.Ref.t * t) option
val implicits : t -> FExpr.var Streaming.Stream.t
val push_existential : t -> t * T.ov list Transactional.Ref.t
val generate : t -> T.def -> T.ov
val reabstract : t -> T.t -> T.ov Vector.t * T.t
val push_abs_skolems : t -> T.kind Vector1.t -> T.t -> t * T.ov Vector1.t * T.t
val instantiate_abs : t -> T.kind Vector1.t -> T.t -> T.uv Vector1.t * T.t
val push_arrow_skolems : t -> T.kind Vector.t -> T.t -> T.t -> T.t
-> t * T.ov Vector.t * T.t * T.t * T.t
val instantiate_arrow : t -> T.kind Vector.t -> T.t -> T.t -> T.t
-> T.uv Vector.t * T.t * T.t * T.t
val push_impli_skolems : t -> T.kind Vector.t -> T.t -> T.t
-> t * T.ov Vector.t * T.t * T.t
val instantiate_impli : t -> T.kind Vector.t -> T.t -> T.t
-> T.uv Vector.t * T.t * T.t
val instantiate_primop : t -> T.kind Vector.t -> T.t Vector.t -> T.t -> T.t
-> T.uv Vector.t * T.t Vector.t * T.t * T.t
val instantiate_branch : t -> T.kind Vector.t -> T.t Vector.t -> T.t -> T.t Vector.t
-> T.uv Vector.t * T.t Vector.t * T.t * T.t Vector.t
val uv : t -> bool -> T.kind -> T.uv
val some_type_kind : t -> bool -> T.t
| |
6796b2286a0dd85a8853f9c5c93eea5fa0e4cbb69548921f45a37d927cc514d8 | adomokos/haskell-katas | Ex28_TypesMoreDerivedInstancesSpec.hs | module Ex28_TypesMoreDerivedInstancesSpec
( spec
) where
import Test.Hspec
main :: IO ()
main = hspec spec
Day is an enumeration of each day in the week
spec :: Spec
spec = do
describe "Derived Instances" $ do
it "can compare two Bool fields" $ do
pending
-- Comparing True to False should be greater
_ _ _ _ _ _ False ` shouldBe ` GT
-- ___ > False `shouldBe` True
-- ___ < False `shouldBe` False
it "can compare Maybe values" $ do
pending
_ _ _ < Just 100 ` shouldBe ` True
Nothing > _ _ _ ( -49999 ) ` shouldBe ` False
_ _ _ 3 ` compare ` _ _ _ 2 ` shouldBe ` GT
it "can be part of Enum typeclass as all value constructors are nullary" $ do
pending
_ _ _ Wednesday ` shouldBe ` " Wednesday "
_ _ _ " Saturday " ` shouldBe ` Saturday
it "can be compared as it's part of Eq and Ord type classes" $ do
pending
_ _ _ = = Sunday ` shouldBe ` False
_ _ _ = = Monday ` shouldBe ` True
_ _ _ < Wednesday ` shouldBe ` True
_ _ _ _ _ _ Tuesday ` shouldBe ` LT
it "is also part of Bounded, can get lowest and highest value" $ do
pending
( _ _ _ : : Day ) ` shouldBe ` Monday
( _ _ _ : : Day ) ` shouldBe ` Sunday
it "is an instance of Enum, can get predecessor and successors" $ do
pending
-- Enums have predecessors and successors
_ _ _ Monday ` shouldBe ` Tuesday
_ _ _ Saturday ` shouldBe ` Friday
Calling predecessor for Monday will throw an error
_ _ _ ( _ _ _ Monday ) ` shouldThrow ` anyErrorCall
| null | https://raw.githubusercontent.com/adomokos/haskell-katas/be06d23192e6aca4297814455247fc74814ccbf1/test/Ex28_TypesMoreDerivedInstancesSpec.hs | haskell | Comparing True to False should be greater
___ > False `shouldBe` True
___ < False `shouldBe` False
Enums have predecessors and successors | module Ex28_TypesMoreDerivedInstancesSpec
( spec
) where
import Test.Hspec
main :: IO ()
main = hspec spec
Day is an enumeration of each day in the week
spec :: Spec
spec = do
describe "Derived Instances" $ do
it "can compare two Bool fields" $ do
pending
_ _ _ _ _ _ False ` shouldBe ` GT
it "can compare Maybe values" $ do
pending
_ _ _ < Just 100 ` shouldBe ` True
Nothing > _ _ _ ( -49999 ) ` shouldBe ` False
_ _ _ 3 ` compare ` _ _ _ 2 ` shouldBe ` GT
it "can be part of Enum typeclass as all value constructors are nullary" $ do
pending
_ _ _ Wednesday ` shouldBe ` " Wednesday "
_ _ _ " Saturday " ` shouldBe ` Saturday
it "can be compared as it's part of Eq and Ord type classes" $ do
pending
_ _ _ = = Sunday ` shouldBe ` False
_ _ _ = = Monday ` shouldBe ` True
_ _ _ < Wednesday ` shouldBe ` True
_ _ _ _ _ _ Tuesday ` shouldBe ` LT
it "is also part of Bounded, can get lowest and highest value" $ do
pending
( _ _ _ : : Day ) ` shouldBe ` Monday
( _ _ _ : : Day ) ` shouldBe ` Sunday
it "is an instance of Enum, can get predecessor and successors" $ do
pending
_ _ _ Monday ` shouldBe ` Tuesday
_ _ _ Saturday ` shouldBe ` Friday
Calling predecessor for Monday will throw an error
_ _ _ ( _ _ _ Monday ) ` shouldThrow ` anyErrorCall
|
6cf055805e7e758677d4ff9a567a06f278c5339f57e3f88123b3f426bf947750 | cram-code/cram_core | rete.lisp | ;;;
Copyright ( c ) 2009 , < >
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions are met:
;;;
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
* Neither the name of Willow Garage , Inc. nor the names of its
;;; contributors may be used to endorse or promote products derived from
;;; this software without specific prior written permission.
;;;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
;;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
;;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
;;; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN
;;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
;;; POSSIBILITY OF SUCH DAMAGE.
;;;
(in-package :crs-tests)
(def-production stacked
(on ?a ?b)
(on ?b ?c))
(def-production on
(on ?a ?b))
(define-test default-handler
(let ((triggered nil))
(with-productions
((is-identity (?op ?a ?a)))
(with-production-handlers
((is-identity (op &key ?a &allow-other-keys)
(declare (ignore ?a))
(push op triggered)))
(with-facts-asserted
('(x 1 1) '(x 1 2)))))
(assert-equality #'member :assert triggered)
(assert-equality #'member :retract triggered)))
(define-test with-productions
(let ((triggered nil))
(with-productions
((is-identity (?op ?a ?a)))
(with-production-handlers
((is-identity (op &key ?a &allow-other-keys)
(declare (ignore ?a))
(push op triggered)))
(with-facts-asserted
('(x 1 1) '(x 1 2)))))
(assert-equality #'member :assert triggered)
(assert-equality #'member :retract triggered)))
(define-test rete-prove
(let ((crs::*alpha-network* (make-instance 'crs::alpha-node :parent nil :key nil)))
(rete-assert '(on a b))
(rete-assert '(on b c))
(rete-assert '(on b d))
(assert-equality #'solutions-equal
'(((?x . b)))
(force-ll (rete-prove '((on a ?x) (on ?x c)))))
(assert-equality #'solutions-equal
'(((?x . b)))
(force-ll (rete-prove '((on a ?x) (on ?x d)))))
(assert-false (rete-prove '((on a ?x) (on ?x e))))
(assert-equality #'solutions-equal
'(((?x . b) (?y . c))
((?x . b) (?y . d)))
(force-ll (rete-prove '((on a ?x) (on ?x ?y)))))))
| null | https://raw.githubusercontent.com/cram-code/cram_core/984046abe2ec9e25b63e52007ed3b857c3d9a13c/cram_reasoning/tests/rete.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:
* 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.
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
| Copyright ( c ) 2009 , < >
* Neither the name of Willow Garage , Inc. nor the names of its
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN
(in-package :crs-tests)
(def-production stacked
(on ?a ?b)
(on ?b ?c))
(def-production on
(on ?a ?b))
(define-test default-handler
(let ((triggered nil))
(with-productions
((is-identity (?op ?a ?a)))
(with-production-handlers
((is-identity (op &key ?a &allow-other-keys)
(declare (ignore ?a))
(push op triggered)))
(with-facts-asserted
('(x 1 1) '(x 1 2)))))
(assert-equality #'member :assert triggered)
(assert-equality #'member :retract triggered)))
(define-test with-productions
(let ((triggered nil))
(with-productions
((is-identity (?op ?a ?a)))
(with-production-handlers
((is-identity (op &key ?a &allow-other-keys)
(declare (ignore ?a))
(push op triggered)))
(with-facts-asserted
('(x 1 1) '(x 1 2)))))
(assert-equality #'member :assert triggered)
(assert-equality #'member :retract triggered)))
(define-test rete-prove
(let ((crs::*alpha-network* (make-instance 'crs::alpha-node :parent nil :key nil)))
(rete-assert '(on a b))
(rete-assert '(on b c))
(rete-assert '(on b d))
(assert-equality #'solutions-equal
'(((?x . b)))
(force-ll (rete-prove '((on a ?x) (on ?x c)))))
(assert-equality #'solutions-equal
'(((?x . b)))
(force-ll (rete-prove '((on a ?x) (on ?x d)))))
(assert-false (rete-prove '((on a ?x) (on ?x e))))
(assert-equality #'solutions-equal
'(((?x . b) (?y . c))
((?x . b) (?y . d)))
(force-ll (rete-prove '((on a ?x) (on ?x ?y)))))))
|
0bb73ef6660b9a6de1e7c850c846579af26c1c9c6fa0ff6759fe72bfda57ce1e | puffnfresh/sonic2 | Palette.hs | module Game.Sega.Sonic.Palette (
loadPalette
) where
import Control.Lens (over, _head)
import Data.Array.Bounded (BoundedArray, accumArrayBounded)
import Data.List.Split (chunksOf)
import Data.Vector.Storable (Vector, fromList)
import Data.Word (Word8)
import SDL (V4 (..))
import Sega.MegaDrive.Palette (BGR (..), ColorNibble (..),
nibbleToByte)
fromBGR :: BGR ColorNibble -> V4 Word8
fromBGR (BGR b g r) =
V4 (nibbleToByte r) (nibbleToByte g) (nibbleToByte b) 0xFF
makeTransparent :: V4 Word8 -> V4 Word8
makeTransparent (V4 b g r _) =
V4 b g r 0
loadPalette :: [BGR ColorNibble] -> BoundedArray Word8 (Vector (V4 Word8))
loadPalette =
accumArrayBounded (flip const) mempty . zip [0..3] . fmap (fromList . over _head makeTransparent) . chunksOf 0x10 . fmap fromBGR
| null | https://raw.githubusercontent.com/puffnfresh/sonic2/0abc3e109a847582c2e16edb13e83e611419fc8a/src/Game/Sega/Sonic/Palette.hs | haskell | module Game.Sega.Sonic.Palette (
loadPalette
) where
import Control.Lens (over, _head)
import Data.Array.Bounded (BoundedArray, accumArrayBounded)
import Data.List.Split (chunksOf)
import Data.Vector.Storable (Vector, fromList)
import Data.Word (Word8)
import SDL (V4 (..))
import Sega.MegaDrive.Palette (BGR (..), ColorNibble (..),
nibbleToByte)
fromBGR :: BGR ColorNibble -> V4 Word8
fromBGR (BGR b g r) =
V4 (nibbleToByte r) (nibbleToByte g) (nibbleToByte b) 0xFF
makeTransparent :: V4 Word8 -> V4 Word8
makeTransparent (V4 b g r _) =
V4 b g r 0
loadPalette :: [BGR ColorNibble] -> BoundedArray Word8 (Vector (V4 Word8))
loadPalette =
accumArrayBounded (flip const) mempty . zip [0..3] . fmap (fromList . over _head makeTransparent) . chunksOf 0x10 . fmap fromBGR
| |
d3dcbf4adda3b050c453fe4fe41bdd0304b97bf6a9c408be2695425d062f4940 | lsevero/clj-curl | easy_test.clj | (ns clj-curl.easy-test
(:refer-clojure :exclude [send])
(:require [clojure.test :refer :all]
[clj-curl.easy :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
| null | https://raw.githubusercontent.com/lsevero/clj-curl/b4e209efd59c7095c610e42a639bfa3ac3356083/test/clj_curl/easy_test.clj | clojure | (ns clj-curl.easy-test
(:refer-clojure :exclude [send])
(:require [clojure.test :refer :all]
[clj-curl.easy :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
| |
f281d45362821de7bd17dddef8343e1cfa61fff04a7bcee53ca457d28e67a83f | eponai/sulolive | utils.clj | (ns env.client.utils)
(defmacro dev-machine-ip
"Is replaced with the ip to this computer."
[]
(.getHostAddress (java.net.InetAddress/getLocalHost))) | null | https://raw.githubusercontent.com/eponai/sulolive/7a70701bbd3df6bbb92682679dcedb53f8822c18/env/client/dev/env/client/utils.clj | clojure | (ns env.client.utils)
(defmacro dev-machine-ip
"Is replaced with the ip to this computer."
[]
(.getHostAddress (java.net.InetAddress/getLocalHost))) | |
637dc3095d502f40c92af83109025a56183b669dec2ed7b6f5405e63e9b5b23b | kappelmann/engaging-large-scale-functional-programming | Types.hs | module Types where
type Seconds = Double
type Sample = Double
type Signal = Seconds -> Sample
type SampledSignal = [Sample]
type Hz = Double
type Semitone = Integer
type Note = (Semitone, Seconds, Seconds)
type Oscillator = Semitone -> Seconds -> Double -> Double
type ADSR = (Seconds, Seconds, Sample, Seconds)
type DSPEffect = SampledSignal -> SampledSignal
sampleRate :: Double
sampleRate = 48000
samplesPerPeriod :: Hz -> Int
samplesPerPeriod hz = round $ sampleRate / hz
samplesPerSecond :: Seconds -> Int
samplesPerSecond duration = round $ duration * sampleRate
| null | https://raw.githubusercontent.com/kappelmann/engaging-large-scale-functional-programming/d098d6da71d4ef4d6d4c8a67bfb7f65c7c5abb0e/resources/synthesiser/solution/src/Types.hs | haskell | module Types where
type Seconds = Double
type Sample = Double
type Signal = Seconds -> Sample
type SampledSignal = [Sample]
type Hz = Double
type Semitone = Integer
type Note = (Semitone, Seconds, Seconds)
type Oscillator = Semitone -> Seconds -> Double -> Double
type ADSR = (Seconds, Seconds, Sample, Seconds)
type DSPEffect = SampledSignal -> SampledSignal
sampleRate :: Double
sampleRate = 48000
samplesPerPeriod :: Hz -> Int
samplesPerPeriod hz = round $ sampleRate / hz
samplesPerSecond :: Seconds -> Int
samplesPerSecond duration = round $ duration * sampleRate
| |
a350dba139d6ca93757e69f02b7d4aa5eb7a1dbcfb048319800d061b9d0dcdce | tamarit/edd | sum_digits.erl | -module(sum_digits).
-compile(export_all).
-include_lib("proper/include/proper.hrl").
-include_lib("eunit/include/eunit.hrl").
sum_digits(N) ->
sum_digits(N,10).
sum_digits(N,B) ->
sum_digits(N,B,0).
sum_digits(0,_,Acc) ->
Acc;
sum_digits(N,B,Acc) when N < B ->
%Acc+N; %RIGHT
Acc; %WRONG
sum_digits(N,B,Acc) ->
sum_digits(N div B, B, Acc + (N rem B)).
%% Tests %%
sum_digits_property_complete() ->
?FORALL({N, Acc},
{integer(0,9), non_neg_integer()},
sum_digits(N, 10, Acc) =:= N + Acc).
| null | https://raw.githubusercontent.com/tamarit/edd/867f287efe951bec6a8213743a218b86e4f5bbf7/examples/Unified_Framework/sum_digits/tests/sum_digits.erl | erlang | Acc+N; %RIGHT
WRONG
Tests %% | -module(sum_digits).
-compile(export_all).
-include_lib("proper/include/proper.hrl").
-include_lib("eunit/include/eunit.hrl").
sum_digits(N) ->
sum_digits(N,10).
sum_digits(N,B) ->
sum_digits(N,B,0).
sum_digits(0,_,Acc) ->
Acc;
sum_digits(N,B,Acc) when N < B ->
sum_digits(N,B,Acc) ->
sum_digits(N div B, B, Acc + (N rem B)).
sum_digits_property_complete() ->
?FORALL({N, Acc},
{integer(0,9), non_neg_integer()},
sum_digits(N, 10, Acc) =:= N + Acc).
|
27ef037917e1bbcaaeee164227ca537971945127dab57ed3aa35ada60ac41319 | drathier/elm-offline | UnionFind.hs | {-# OPTIONS_GHC -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns #-}
module Type.UnionFind
( Point
, fresh
, union
, equivalent
, redundant
, get
, set
, modify
)
where
This is based on the following implementations :
- -find-0.2/docs/src/Data-UnionFind-IO.html
- -gianas.org/public/mini/code_UnionFind.html
It seems like the OCaml one came first , but I am not sure .
Compared to the implementation , the major changes here include :
1 . No more reallocating PointInfo when changing the weight
2 . Using the strict modifyIORef
- -find-0.2/docs/src/Data-UnionFind-IO.html
- -gianas.org/public/mini/code_UnionFind.html
It seems like the OCaml one came first, but I am not sure.
Compared to the Haskell implementation, the major changes here include:
1. No more reallocating PointInfo when changing the weight
2. Using the strict modifyIORef
-}
import Control.Monad ( when )
import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)
import Data.Word (Word32)
-- POINT
newtype Point a =
Pt (IORef (PointInfo a))
deriving Eq
data PointInfo a
= Info {-# UNPACK #-} !(IORef Word32) {-# UNPACK #-} !(IORef a)
| Link {-# UNPACK #-} !(Point a)
-- HELPERS
fresh :: a -> IO (Point a)
fresh value =
do weight <- newIORef 1
desc <- newIORef value
link <- newIORef (Info weight desc)
return (Pt link)
repr :: Point a -> IO (Point a)
repr point@(Pt ref) =
do pInfo <- readIORef ref
case pInfo of
Info _ _ ->
return point
Link point1@(Pt ref1) ->
do point2 <- repr point1
when (point2 /= point1) $
do pInfo1 <- readIORef ref1
writeIORef ref pInfo1
return point2
get :: Point a -> IO a
get point@(Pt ref) =
do pInfo <- readIORef ref
case pInfo of
Info _ descRef ->
readIORef descRef
Link (Pt ref1) ->
do link' <- readIORef ref1
case link' of
Info _ descRef ->
readIORef descRef
Link _ ->
get =<< repr point
set :: Point a -> a -> IO ()
set point@(Pt ref) newDesc =
do pInfo <- readIORef ref
case pInfo of
Info _ descRef ->
writeIORef descRef newDesc
Link (Pt ref1) ->
do link' <- readIORef ref1
case link' of
Info _ descRef ->
writeIORef descRef newDesc
Link _ ->
do newPoint <- repr point
set newPoint newDesc
modify :: Point a -> (a -> a) -> IO ()
modify point@(Pt ref) func =
do pInfo <- readIORef ref
case pInfo of
Info _ descRef ->
modifyIORef' descRef func
Link (Pt ref1) ->
do link' <- readIORef ref1
case link' of
Info _ descRef ->
modifyIORef' descRef func
Link _ ->
do newPoint <- repr point
modify newPoint func
union :: Point a -> Point a -> a -> IO ()
union p1 p2 newDesc =
do point1@(Pt ref1) <- repr p1
point2@(Pt ref2) <- repr p2
Info w1 d1 <- readIORef ref1
Info w2 d2 <- readIORef ref2
if point1 == point2
then writeIORef d1 newDesc
else do
weight1 <- readIORef w1
weight2 <- readIORef w2
let !newWeight = weight1 + weight2
if weight1 >= weight2
then
do writeIORef ref2 (Link point1)
writeIORef w1 newWeight
writeIORef d1 newDesc
else
do writeIORef ref1 (Link point2)
writeIORef w2 newWeight
writeIORef d2 newDesc
equivalent :: Point a -> Point a -> IO Bool
equivalent p1 p2 =
do v1 <- repr p1
v2 <- repr p2
return (v1 == v2)
redundant :: Point a -> IO Bool
redundant (Pt ref) =
do pInfo <- readIORef ref
case pInfo of
Info _ _ ->
return False
Link _ ->
return True
| null | https://raw.githubusercontent.com/drathier/elm-offline/f562198cac29f4cda15b69fde7e66edde89b34fa/compiler/src/Type/UnionFind.hs | haskell | # OPTIONS_GHC -funbox-strict-fields #
# LANGUAGE BangPatterns #
POINT
# UNPACK #
# UNPACK #
# UNPACK #
HELPERS | module Type.UnionFind
( Point
, fresh
, union
, equivalent
, redundant
, get
, set
, modify
)
where
This is based on the following implementations :
- -find-0.2/docs/src/Data-UnionFind-IO.html
- -gianas.org/public/mini/code_UnionFind.html
It seems like the OCaml one came first , but I am not sure .
Compared to the implementation , the major changes here include :
1 . No more reallocating PointInfo when changing the weight
2 . Using the strict modifyIORef
- -find-0.2/docs/src/Data-UnionFind-IO.html
- -gianas.org/public/mini/code_UnionFind.html
It seems like the OCaml one came first, but I am not sure.
Compared to the Haskell implementation, the major changes here include:
1. No more reallocating PointInfo when changing the weight
2. Using the strict modifyIORef
-}
import Control.Monad ( when )
import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)
import Data.Word (Word32)
newtype Point a =
Pt (IORef (PointInfo a))
deriving Eq
data PointInfo a
fresh :: a -> IO (Point a)
fresh value =
do weight <- newIORef 1
desc <- newIORef value
link <- newIORef (Info weight desc)
return (Pt link)
repr :: Point a -> IO (Point a)
repr point@(Pt ref) =
do pInfo <- readIORef ref
case pInfo of
Info _ _ ->
return point
Link point1@(Pt ref1) ->
do point2 <- repr point1
when (point2 /= point1) $
do pInfo1 <- readIORef ref1
writeIORef ref pInfo1
return point2
get :: Point a -> IO a
get point@(Pt ref) =
do pInfo <- readIORef ref
case pInfo of
Info _ descRef ->
readIORef descRef
Link (Pt ref1) ->
do link' <- readIORef ref1
case link' of
Info _ descRef ->
readIORef descRef
Link _ ->
get =<< repr point
set :: Point a -> a -> IO ()
set point@(Pt ref) newDesc =
do pInfo <- readIORef ref
case pInfo of
Info _ descRef ->
writeIORef descRef newDesc
Link (Pt ref1) ->
do link' <- readIORef ref1
case link' of
Info _ descRef ->
writeIORef descRef newDesc
Link _ ->
do newPoint <- repr point
set newPoint newDesc
modify :: Point a -> (a -> a) -> IO ()
modify point@(Pt ref) func =
do pInfo <- readIORef ref
case pInfo of
Info _ descRef ->
modifyIORef' descRef func
Link (Pt ref1) ->
do link' <- readIORef ref1
case link' of
Info _ descRef ->
modifyIORef' descRef func
Link _ ->
do newPoint <- repr point
modify newPoint func
union :: Point a -> Point a -> a -> IO ()
union p1 p2 newDesc =
do point1@(Pt ref1) <- repr p1
point2@(Pt ref2) <- repr p2
Info w1 d1 <- readIORef ref1
Info w2 d2 <- readIORef ref2
if point1 == point2
then writeIORef d1 newDesc
else do
weight1 <- readIORef w1
weight2 <- readIORef w2
let !newWeight = weight1 + weight2
if weight1 >= weight2
then
do writeIORef ref2 (Link point1)
writeIORef w1 newWeight
writeIORef d1 newDesc
else
do writeIORef ref1 (Link point2)
writeIORef w2 newWeight
writeIORef d2 newDesc
equivalent :: Point a -> Point a -> IO Bool
equivalent p1 p2 =
do v1 <- repr p1
v2 <- repr p2
return (v1 == v2)
redundant :: Point a -> IO Bool
redundant (Pt ref) =
do pInfo <- readIORef ref
case pInfo of
Info _ _ ->
return False
Link _ ->
return True
|
b11fda53ee6353438640b484fee4c3be4ca75ab701464827a4e77199b71ddc3e | helpshift/hydrox | home.clj | (ns documentation.example.home
(:use midje.sweet))
[[:chapter {:title "Beating the Averages"}]]
"In the summer of 1995, my friend Robert Morris and I started a startup called Viaweb.
Our plan was to write software that would let end users build online stores. What was
novel about this software, at the time, was that it ran on our server, using ordinary
Web pages as the interface.
A lot of people could have been having this idea at the same time, of course, but as
far as I know, Viaweb was the first Web-based application. It seemed such a novel idea
to us that we named the company after it: Viaweb, because our software worked via the
Web, instead of running on your desktop computer.
Another unusual thing about this software was that it was written primarily in a programming
language called Lisp. It was one of the first big end-user applications to be written in Lisp,
which up till then had been used mostly in universities and research labs."
[[:section {:title "The Secret Weapon"}]]
"Eric Raymond has written an essay called \"How to Become a Hacker,\" and in it, among
other things, he tells would-be hackers what languages they should learn. He suggests
starting with Python and Java, because they are easy to learn. The serious hacker will
also want to learn C, in order to hack Unix, and Perl for system administration and cgi
scripts. Finally, the truly serious hacker should consider learning Lisp:
Lisp is worth learning for the profound enlightenment experience you will have when you
finally get it; that experience will make you a better programmer for the rest of your
days, even if you never actually use Lisp itself a lot.
This is the same argument you tend to hear for learning Latin. It won't get you a job,
except perhaps as a classics professor, but it will improve your mind, and make you a
better writer in languages you do want to use, like English.
But wait a minute. This metaphor doesn't stretch that far. The reason Latin won't get
you a job is that no one speaks it. If you write in Latin, no one can understand you.
But Lisp is a computer language, and computers speak whatever language you, the programmer,
tell them to.
So if Lisp makes you a better programmer, like he says, why wouldn't you want to use it?
If a painter were offered a brush that would make him a better painter, it seems to me
that he would want to use it in all his paintings, wouldn't he? I'm not trying to make
fun of Eric Raymond here. On the whole, his advice is good. What he says about Lisp is
pretty much the conventional wisdom. But there is a contradiction in the conventional
wisdom: Lisp will make you a better programmer, and yet you won't use it.
Why not? Programming languages are just tools, after all. If Lisp really does yield better
programs, you should use it. And if it doesn't, then who needs it?
This is not just a theoretical question. Software is a very competitive business, prone
to natural monopolies. A company that gets software written faster and better will, all
other things being equal, put its competitors out of business. And when you're starting
a startup, you feel this very keenly. Startups tend to be an all or nothing proposition.
You either get rich, or you get nothing. In a startup, if you bet on the wrong technology,
your competitors will crush you.
Robert and I both knew Lisp well, and we couldn't see any reason not to trust our instincts
and go with Lisp. We knew that everyone else was writing their software in C++ or Perl.
But we also knew that that didn't mean anything. If you chose technology that way, you'd
be running Windows. When you choose technology, you have to ignore what other people are
doing, and consider only what will work the best.
This is especially true in a startup. In a big company, you can do what all the other
big companies are doing. But a startup can't do what all the other startups do. I don't
think a lot of people realize this, even in startups.
The average big company grows at about ten percent a year. So if you're running a big
company and you do everything the way the average big company does it, you can expect
to do as well as the average big company-- that is, to grow about ten percent a year.
The same thing will happen if you're running a startup, of course. If you do everything
the way the average startup does it, you should expect average performance. The problem
here is, average performance means that you'll go out of business. The survival rate for
startups is way less than fifty percent. So if you're running a startup, you had better
be doing something odd. If not, you're in trouble.
Back in 1995, we knew something that I don't think our competitors understood, and few
understand even now: when you're writing software that only has to run on your own servers,
you can use any language you want. When you're writing desktop software, there's a strong
bias toward writing applications in the same language as the operating system. Ten years
ago, writing applications meant writing applications in C. But with Web-based software,
especially when you have the source code of both the language and the operating system,
you can use whatever language you want.
This new freedom is a double-edged sword, however. Now that you can use any language, you
have to think about which one to use. Companies that try to pretend nothing has changed
risk finding that their competitors do not.
If you can use any language, which do you use? We chose Lisp. For one thing, it was obvious
that rapid development would be important in this market. We were all starting from scratch,
so a company that could get new features done before its competitors would have a big
advantage. We knew Lisp was a really good language for writing software quickly, and
server-based applications magnify the effect of rapid development, because you can release
software the minute it's done.
If other companies didn't want to use Lisp, so much the better. It might give us a technological
edge, and we needed all the help we could get. When we started Viaweb, we had no experience
in business. We didn't know anything about marketing, or hiring people, or raising money, or
getting customers. Neither of us had ever even had what you would call a real job. The only
thing we were good at was writing software. We hoped that would save us. Any advantage we could
get in the software department, we would take.
So you could say that using Lisp was an experiment. Our hypothesis was that if we wrote our
software in Lisp, we'd be able to get features done faster than our competitors, and also to
do things in our software that they couldn't do. And because Lisp was so high-level, we wouldn't
need a big development team, so our costs would be lower. If this were so, we could offer a
better product for less money, and still make a profit. We would end up getting all the users,
and our competitors would get none, and eventually go out of business. That was what we hoped
would happen, anyway.
What were the results of this experiment? Somewhat surprisingly, it worked. We eventually had
many competitors, on the order of twenty to thirty of them, but none of their software could
compete with ours. We had a wysiwyg online store builder that ran on the server and yet felt
like a desktop application. Our competitors had cgi scripts. And we were always far ahead of
them in features. Sometimes, in desperation, competitors would try to introduce features that
we didn't have. But with Lisp our development cycle was so fast that we could sometimes duplicate
a new feature within a day or two of a competitor announcing it in a press release. By the time
journalists covering the press release got round to calling us, we would have the new feature too.
It must have seemed to our competitors that we had some kind of secret weapon-- that we were
decoding their Enigma traffic or something. In fact we did have a secret weapon, but it was
simpler than they realized. No one was leaking news of their features to us. We were just able
to develop software faster than anyone thought possible.
When I was about nine I happened to get hold of a copy of The Day of the Jackal, by Frederick
Forsyth. The main character is an assassin who is hired to kill the president of France. The
assassin has to get past the police to get up to an apartment that overlooks the president's
route. He walks right by them, dressed up as an old man on crutches, and they never suspect him.
Our secret weapon was similar. We wrote our software in a weird AI language, with a bizarre
syntax full of parentheses. For years it had annoyed me to hear Lisp described that way. But now
it worked to our advantage. In business, there is nothing more valuable than a technical advantage
your competitors don't understand. In business, as in war, surprise is worth as much as force.
And so, I'm a little embarrassed to say, I never said anything publicly about Lisp while we were
working on Viaweb. We never mentioned it to the press, and if you searched for Lisp on our Web site,
all you'd find were the titles of two books in my bio. This was no accident. A startup should give
its competitors as little information as possible. If they didn't know what language our software
was written in, or didn't care, I wanted to keep it that way.[2]
The people who understood our technology best were the customers. They didn't care what language
Viaweb was written in either, but they noticed that it worked really well. It let them build great
looking online stores literally in minutes. And so, by word of mouth mostly, we got more and more
users. By the end of 1996 we had about 70 stores online. At the end of 1997 we had 500. Six months
later, when Yahoo bought us, we had 1070 users. Today, as Yahoo Store, this software continues to
dominate its market. It's one of the more profitable pieces of Yahoo, and the stores built with it
are the foundation of Yahoo Shopping. I left Yahoo in 1999, so I don't know exactly how many users
they have now, but the last I heard there were about 20,000."
| null | https://raw.githubusercontent.com/helpshift/hydrox/2beb3c56fad43bbf16f07db7ee72c5862978350c/example/test/documentation/example/home.clj | clojure | that experience will make you a better programmer for the rest of your | (ns documentation.example.home
(:use midje.sweet))
[[:chapter {:title "Beating the Averages"}]]
"In the summer of 1995, my friend Robert Morris and I started a startup called Viaweb.
Our plan was to write software that would let end users build online stores. What was
novel about this software, at the time, was that it ran on our server, using ordinary
Web pages as the interface.
A lot of people could have been having this idea at the same time, of course, but as
far as I know, Viaweb was the first Web-based application. It seemed such a novel idea
to us that we named the company after it: Viaweb, because our software worked via the
Web, instead of running on your desktop computer.
Another unusual thing about this software was that it was written primarily in a programming
language called Lisp. It was one of the first big end-user applications to be written in Lisp,
which up till then had been used mostly in universities and research labs."
[[:section {:title "The Secret Weapon"}]]
"Eric Raymond has written an essay called \"How to Become a Hacker,\" and in it, among
other things, he tells would-be hackers what languages they should learn. He suggests
starting with Python and Java, because they are easy to learn. The serious hacker will
also want to learn C, in order to hack Unix, and Perl for system administration and cgi
scripts. Finally, the truly serious hacker should consider learning Lisp:
Lisp is worth learning for the profound enlightenment experience you will have when you
days, even if you never actually use Lisp itself a lot.
This is the same argument you tend to hear for learning Latin. It won't get you a job,
except perhaps as a classics professor, but it will improve your mind, and make you a
better writer in languages you do want to use, like English.
But wait a minute. This metaphor doesn't stretch that far. The reason Latin won't get
you a job is that no one speaks it. If you write in Latin, no one can understand you.
But Lisp is a computer language, and computers speak whatever language you, the programmer,
tell them to.
So if Lisp makes you a better programmer, like he says, why wouldn't you want to use it?
If a painter were offered a brush that would make him a better painter, it seems to me
that he would want to use it in all his paintings, wouldn't he? I'm not trying to make
fun of Eric Raymond here. On the whole, his advice is good. What he says about Lisp is
pretty much the conventional wisdom. But there is a contradiction in the conventional
wisdom: Lisp will make you a better programmer, and yet you won't use it.
Why not? Programming languages are just tools, after all. If Lisp really does yield better
programs, you should use it. And if it doesn't, then who needs it?
This is not just a theoretical question. Software is a very competitive business, prone
to natural monopolies. A company that gets software written faster and better will, all
other things being equal, put its competitors out of business. And when you're starting
a startup, you feel this very keenly. Startups tend to be an all or nothing proposition.
You either get rich, or you get nothing. In a startup, if you bet on the wrong technology,
your competitors will crush you.
Robert and I both knew Lisp well, and we couldn't see any reason not to trust our instincts
and go with Lisp. We knew that everyone else was writing their software in C++ or Perl.
But we also knew that that didn't mean anything. If you chose technology that way, you'd
be running Windows. When you choose technology, you have to ignore what other people are
doing, and consider only what will work the best.
This is especially true in a startup. In a big company, you can do what all the other
big companies are doing. But a startup can't do what all the other startups do. I don't
think a lot of people realize this, even in startups.
The average big company grows at about ten percent a year. So if you're running a big
company and you do everything the way the average big company does it, you can expect
to do as well as the average big company-- that is, to grow about ten percent a year.
The same thing will happen if you're running a startup, of course. If you do everything
the way the average startup does it, you should expect average performance. The problem
here is, average performance means that you'll go out of business. The survival rate for
startups is way less than fifty percent. So if you're running a startup, you had better
be doing something odd. If not, you're in trouble.
Back in 1995, we knew something that I don't think our competitors understood, and few
understand even now: when you're writing software that only has to run on your own servers,
you can use any language you want. When you're writing desktop software, there's a strong
bias toward writing applications in the same language as the operating system. Ten years
ago, writing applications meant writing applications in C. But with Web-based software,
especially when you have the source code of both the language and the operating system,
you can use whatever language you want.
This new freedom is a double-edged sword, however. Now that you can use any language, you
have to think about which one to use. Companies that try to pretend nothing has changed
risk finding that their competitors do not.
If you can use any language, which do you use? We chose Lisp. For one thing, it was obvious
that rapid development would be important in this market. We were all starting from scratch,
so a company that could get new features done before its competitors would have a big
advantage. We knew Lisp was a really good language for writing software quickly, and
server-based applications magnify the effect of rapid development, because you can release
software the minute it's done.
If other companies didn't want to use Lisp, so much the better. It might give us a technological
edge, and we needed all the help we could get. When we started Viaweb, we had no experience
in business. We didn't know anything about marketing, or hiring people, or raising money, or
getting customers. Neither of us had ever even had what you would call a real job. The only
thing we were good at was writing software. We hoped that would save us. Any advantage we could
get in the software department, we would take.
So you could say that using Lisp was an experiment. Our hypothesis was that if we wrote our
software in Lisp, we'd be able to get features done faster than our competitors, and also to
do things in our software that they couldn't do. And because Lisp was so high-level, we wouldn't
need a big development team, so our costs would be lower. If this were so, we could offer a
better product for less money, and still make a profit. We would end up getting all the users,
and our competitors would get none, and eventually go out of business. That was what we hoped
would happen, anyway.
What were the results of this experiment? Somewhat surprisingly, it worked. We eventually had
many competitors, on the order of twenty to thirty of them, but none of their software could
compete with ours. We had a wysiwyg online store builder that ran on the server and yet felt
like a desktop application. Our competitors had cgi scripts. And we were always far ahead of
them in features. Sometimes, in desperation, competitors would try to introduce features that
we didn't have. But with Lisp our development cycle was so fast that we could sometimes duplicate
a new feature within a day or two of a competitor announcing it in a press release. By the time
journalists covering the press release got round to calling us, we would have the new feature too.
It must have seemed to our competitors that we had some kind of secret weapon-- that we were
decoding their Enigma traffic or something. In fact we did have a secret weapon, but it was
simpler than they realized. No one was leaking news of their features to us. We were just able
to develop software faster than anyone thought possible.
When I was about nine I happened to get hold of a copy of The Day of the Jackal, by Frederick
Forsyth. The main character is an assassin who is hired to kill the president of France. The
assassin has to get past the police to get up to an apartment that overlooks the president's
route. He walks right by them, dressed up as an old man on crutches, and they never suspect him.
Our secret weapon was similar. We wrote our software in a weird AI language, with a bizarre
syntax full of parentheses. For years it had annoyed me to hear Lisp described that way. But now
it worked to our advantage. In business, there is nothing more valuable than a technical advantage
your competitors don't understand. In business, as in war, surprise is worth as much as force.
And so, I'm a little embarrassed to say, I never said anything publicly about Lisp while we were
working on Viaweb. We never mentioned it to the press, and if you searched for Lisp on our Web site,
all you'd find were the titles of two books in my bio. This was no accident. A startup should give
its competitors as little information as possible. If they didn't know what language our software
was written in, or didn't care, I wanted to keep it that way.[2]
The people who understood our technology best were the customers. They didn't care what language
Viaweb was written in either, but they noticed that it worked really well. It let them build great
looking online stores literally in minutes. And so, by word of mouth mostly, we got more and more
users. By the end of 1996 we had about 70 stores online. At the end of 1997 we had 500. Six months
later, when Yahoo bought us, we had 1070 users. Today, as Yahoo Store, this software continues to
dominate its market. It's one of the more profitable pieces of Yahoo, and the stores built with it
are the foundation of Yahoo Shopping. I left Yahoo in 1999, so I don't know exactly how many users
they have now, but the last I heard there were about 20,000."
|
211de50f7596fb72babfdd184dabce318c71c8e88fe24b91a091df8ec992f75b | jborden/leaderboard-api | handler_test.clj | (ns leaderboard-api.handler-test
(:require [clojure.test :refer :all]
[ring.mock.request :as mock]
[leaderboard-api.handler :refer :all]))
(deftest test-app
(testing "main route"
(let [response (app (mock/request :get "/"))]
(is (= (:status response) 200))
(is (= (:body response) "Hello World"))))
(testing "not-found route"
(let [response (app (mock/request :get "/invalid"))]
(is (= (:status response) 404)))))
| null | https://raw.githubusercontent.com/jborden/leaderboard-api/f5861c8a59eba634b95222cac3a04668afdcf66a/test/leaderboard_api/handler_test.clj | clojure | (ns leaderboard-api.handler-test
(:require [clojure.test :refer :all]
[ring.mock.request :as mock]
[leaderboard-api.handler :refer :all]))
(deftest test-app
(testing "main route"
(let [response (app (mock/request :get "/"))]
(is (= (:status response) 200))
(is (= (:body response) "Hello World"))))
(testing "not-found route"
(let [response (app (mock/request :get "/invalid"))]
(is (= (:status response) 404)))))
| |
eb24f71c34315c9de2bf053b5090e9431bb710c97f8d0141ebd1afa863d16670 | mhuebert/maria | page.cljc | (ns cljs-static.page
(:require [cljs-static.assets :as assets]
[hiccup.util :as hu]
[hiccup2.core :as hiccup]))
(defn map<> [f coll]
#?(:cljs
(into [:<>] (map f coll))
:clj
(doall (map f coll))))
;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; HTML generation
(defn update-some [m updaters]
(reduce-kv (fn [m k update-f]
(cond-> m
(contains? m k) (update k update-f))) m updaters))
(defn element-tag [kw-or-hiccup]
(cond-> kw-or-hiccup
(keyword? kw-or-hiccup) (vector)))
(defn script-tag
([opts content]
[:script
(update-some opts {:src assets/path*})
(some-> content hiccup/raw)])
([opts-or-content]
(if-let [value (:value opts-or-content)]
(script-tag (dissoc opts-or-content :value) value)
(if (string? opts-or-content)
(script-tag {} opts-or-content)
(script-tag opts-or-content nil)))))
(defn style-tag [str-or-map]
(if (string? str-or-map)
[:style str-or-map]
[:link (-> str-or-map
(assoc :rel "stylesheet")
(update-some {:href assets/path*}))]))
(defn meta-tag [k v]
[:meta {(if (some #{"Expires"
"Pragma"
"Cache-Control"
"imagetoolbar"
"x-dns-prefetch-control"} (name k))
:http-equiv
:name) (name k)
:content v}])
(def doctype "<!DOCTYPE html>\n")
(defn root
"Return html string for title and props"
([title page-props]
(root (assoc page-props :title title)))
([{:as page-props
:keys [lang
title
charset
styles
meta
head
body]
body-scripts :scripts/body
head-scripts :scripts/head
:or {lang "en"
charset "UTF-8"}}]
(hiccup/html {:mode :html}
(hu/raw-string doctype)
[:html (merge {:lang lang} (:props/html page-props))
[:head
(map<> (fn [[k v]] (meta-tag k v)) meta)
[:meta {:http-equiv "Content-Type"
:content (str "text/html; charset=" charset)}]
(when title
[:title title])
(map<> style-tag styles)
(map<> element-tag head)
(map<> script-tag head-scripts)]
[:body (:props/body page-props {})
(map<> element-tag body)
(map<> script-tag body-scripts)]])))
(comment
(html "Welcome"
{:styles [{:href "/some/styles.css"}
".black {color: #000}"]
:body [:div#app]
:scripts/body [{:src "/some/script.js"}
"alert('hi!')"]}))
| null | https://raw.githubusercontent.com/mhuebert/maria/9fc2e26ed7df16e82841e0127a56ae36fafa4e63/tools/src/cljs_static/page.cljc | clojure |
HTML generation | (ns cljs-static.page
(:require [cljs-static.assets :as assets]
[hiccup.util :as hu]
[hiccup2.core :as hiccup]))
(defn map<> [f coll]
#?(:cljs
(into [:<>] (map f coll))
:clj
(doall (map f coll))))
(defn update-some [m updaters]
(reduce-kv (fn [m k update-f]
(cond-> m
(contains? m k) (update k update-f))) m updaters))
(defn element-tag [kw-or-hiccup]
(cond-> kw-or-hiccup
(keyword? kw-or-hiccup) (vector)))
(defn script-tag
([opts content]
[:script
(update-some opts {:src assets/path*})
(some-> content hiccup/raw)])
([opts-or-content]
(if-let [value (:value opts-or-content)]
(script-tag (dissoc opts-or-content :value) value)
(if (string? opts-or-content)
(script-tag {} opts-or-content)
(script-tag opts-or-content nil)))))
(defn style-tag [str-or-map]
(if (string? str-or-map)
[:style str-or-map]
[:link (-> str-or-map
(assoc :rel "stylesheet")
(update-some {:href assets/path*}))]))
(defn meta-tag [k v]
[:meta {(if (some #{"Expires"
"Pragma"
"Cache-Control"
"imagetoolbar"
"x-dns-prefetch-control"} (name k))
:http-equiv
:name) (name k)
:content v}])
(def doctype "<!DOCTYPE html>\n")
(defn root
"Return html string for title and props"
([title page-props]
(root (assoc page-props :title title)))
([{:as page-props
:keys [lang
title
charset
styles
meta
head
body]
body-scripts :scripts/body
head-scripts :scripts/head
:or {lang "en"
charset "UTF-8"}}]
(hiccup/html {:mode :html}
(hu/raw-string doctype)
[:html (merge {:lang lang} (:props/html page-props))
[:head
(map<> (fn [[k v]] (meta-tag k v)) meta)
[:meta {:http-equiv "Content-Type"
:content (str "text/html; charset=" charset)}]
(when title
[:title title])
(map<> style-tag styles)
(map<> element-tag head)
(map<> script-tag head-scripts)]
[:body (:props/body page-props {})
(map<> element-tag body)
(map<> script-tag body-scripts)]])))
(comment
(html "Welcome"
{:styles [{:href "/some/styles.css"}
".black {color: #000}"]
:body [:div#app]
:scripts/body [{:src "/some/script.js"}
"alert('hi!')"]}))
|
21ee6ea201cd7a101d754f17aa891aead37dd3fefce6f20b7c151c1b04d1b3a6 | joewilliams/erl_geo_dns | couchbeam_util.erl | Copyright 2009 .
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.
%%%
Some code from michiweb project under BSD license
< >
copyright 2007 Mochi Media , Inc.
%%%
%%% Permission is hereby granted, free of charge, to any person obtaining a copy
%%% of this software and associated documentation files (the "Software"), to deal
in the Software without restriction , including without limitation the rights
%%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software , and to permit persons to whom the Software is
%%% furnished to do so, subject to the following conditions:
%%%
%%% The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software .
%%%
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
%%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
%%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
%%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
%%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
%%% THE SOFTWARE.
%%%
%%% Some code imported from ibrowse project
Copyright 2009 ,
%%% Permission is hereby granted, free of charge, to any person obtaining a copy
%%% of this software and associated documentation files (the "Software"), to deal
in the Software without restriction , including without limitation the rights
%%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software , and to permit persons to whom the Software is
%%% furnished to do so, subject to the following conditions:
%%%
%%% The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software .
%%%
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
%%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
%%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
%%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
%%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
%%% THE SOFTWARE.
%%%
@author < >
2009 .
%%
@author < >
copyright 2007 Mochi Media , Inc.
-module(couchbeam_util).
-export([generate_uuids/1, new_uuid/0, to_hex/1, to_digit/1,
join/2, revjoin/3, url_encode/1, quote_plus/1, split/2,
guess_mime/1, val/1, encodeBase64/1]).
-define(PERCENT, 37). % $\%
-define(FULLSTOP, 46). % $\.
-define(IS_HEX(C), ((C >= $0 andalso C =< $9) orelse
(C >= $a andalso C =< $f) orelse
(C >= $A andalso C =< $F))).
-define(QS_SAFE(C), ((C >= $a andalso C =< $z) orelse
(C >= $A andalso C =< $Z) orelse
(C >= $0 andalso C =< $9) orelse
(C =:= ?FULLSTOP orelse C =:= $- orelse C =:= $~ orelse
C =:= $_))).
hexdigit(C) when C < 10 -> $0 + C;
hexdigit(C) when C < 16 -> $A + (C - 10).
( ) ) - > UrlEncodedStr::string ( )
@doc URL - encodes a string based on RFC 1738 . Returns a flat list .
%% imported from ibrowse project :
%%
url_encode(Str) when is_list(Str) ->
url_encode_char(lists:reverse(Str), []).
url_encode_char([X | T], Acc) when X >= $0, X =< $9 ->
url_encode_char(T, [X | Acc]);
url_encode_char([X | T], Acc) when X >= $a, X =< $z ->
url_encode_char(T, [X | Acc]);
url_encode_char([X | T], Acc) when X >= $A, X =< $Z ->
url_encode_char(T, [X | Acc]);
url_encode_char([X | T], Acc) when X == $-; X == $_; X == $. ->
url_encode_char(T, [X | Acc]);
url_encode_char([32 | T], Acc) ->
url_encode_char(T, [$+ | Acc]);
url_encode_char([X | T], Acc) ->
url_encode_char(T, [$%, d2h(X bsr 4), d2h(X band 16#0f) | Acc]);
url_encode_char([], Acc) ->
Acc.
d2h(N) when N<10 -> N+$0;
d2h(N) -> N+$a-10.
( ) | integer ( ) | float ( ) | string ( ) | binary ( ) ) - > string ( )
%% @doc URL safe encoding of the given term.
quote_plus(Atom) when is_atom(Atom) ->
quote_plus(atom_to_list(Atom));
quote_plus(Int) when is_integer(Int) ->
quote_plus(integer_to_list(Int));
quote_plus(Binary) when is_binary(Binary) ->
quote_plus(binary_to_list(Binary));
quote_plus(Float) when is_float(Float) ->
quote_plus(couchbeam_mochinum:digits(Float));
quote_plus(String) ->
quote_plus(String, []).
quote_plus([], Acc) ->
lists:reverse(Acc);
quote_plus([C | Rest], Acc) when ?QS_SAFE(C) ->
quote_plus(Rest, [C | Acc]);
quote_plus([$\s | Rest], Acc) ->
quote_plus(Rest, [$+ | Acc]);
quote_plus([C | Rest], Acc) ->
<<Hi:4, Lo:4>> = <<C>>,
quote_plus(Rest, [hexdigit(Lo), hexdigit(Hi), ?PERCENT | Acc]).
generate_uuids(Count) ->
[ new_uuid() || _ <- lists:seq(1,Count)].
Code from Mochiweb /
%% @spec join([string()], Separator) -> string()
%% @doc Join a list of strings together with the given separator
%% string or char.
join([], _Separator) ->
[];
join([S], _Separator) ->
lists:flatten(S);
join(Strings, Separator) ->
lists:flatten(revjoin(lists:reverse(Strings), Separator, [])).
revjoin([], _Separator, Acc) ->
Acc;
revjoin([S | Rest], Separator, []) ->
revjoin(Rest, Separator, [S]);
revjoin([S | Rest], Separator, Acc) ->
revjoin(Rest, Separator, [S, Separator | Acc]).
%% code from CouchDB
new_uuid() ->
list_to_binary(to_hex(crypto:rand_bytes(16))).
to_hex([]) ->
[];
to_hex(Bin) when is_binary(Bin) ->
to_hex(binary_to_list(Bin));
to_hex([H|T]) ->
[to_digit(H div 16), to_digit(H rem 16) | to_hex(T)].
to_digit(N) when N < 10 -> $0 + N;
to_digit(N) -> $a + N-10.
@spec split(Bin::binary ( ) , Chars::string ( ) ) - > binary ( )
%% @doc split a binary
split(Bin, Chars) ->
split(Chars, Bin, 0, []).
split(Chars, Bin, Idx, Acc) ->
case Bin of
<<This:Idx/binary, Char, Tail/binary>> ->
case lists:member(Char, Chars) of
false ->
split(Chars, Bin, Idx+1, Acc);
true ->
split(Chars, Tail, 0, [This|Acc])
end;
<<This:Idx/binary>> ->
lists:reverse(Acc, [This])
end.
val(V) when is_list(V) ->
V;
val(V) when is_integer(V) ->
integer_to_list(V);
val(V) when is_binary(V) ->
binary_to_list(V);
val(V) ->
V.
guess_mime(string ( ) ) - > string ( )
%% @doc Guess the mime type of a file by the extension of its filename.
guess_mime(File) ->
case filename:extension(File) of
".html" ->
"text/html";
".xhtml" ->
"application/xhtml+xml";
".xml" ->
"application/xml";
".css" ->
"text/css";
".js" ->
"application/x-javascript";
".jpg" ->
"image/jpeg";
".gif" ->
"image/gif";
".png" ->
"image/png";
".swf" ->
"application/x-shockwave-flash";
".zip" ->
"application/zip";
".bz2" ->
"application/x-bzip2";
".gz" ->
"application/x-gzip";
".tar" ->
"application/x-tar";
".tgz" ->
"application/x-gzip";
".txt" ->
"text/plain";
".doc" ->
"application/msword";
".pdf" ->
"application/pdf";
".xls" ->
"application/vnd.ms-excel";
".rtf" ->
"application/rtf";
".mov" ->
"video/quicktime";
".mp3" ->
"audio/mpeg";
".z" ->
"application/x-compress";
".wav" ->
"audio/x-wav";
".ico" ->
"image/x-icon";
".bmp" ->
"image/bmp";
".m4a" ->
"audio/mpeg";
".m3u" ->
"audio/x-mpegurl";
".exe" ->
"application/octet-stream";
".csv" ->
"text/csv";
_ ->
"text/plain"
end.
%%% Purpose : Base 64 encoding
Copied from ssl_base_64 to avoid using the
%%% erlang ssl library
-define(st(X,A), ((X-A+256) div 256)).
%%
%% encode64(Bytes|Binary) -> binary
%%
Take 3 bytes a time ( 3 x 8 = 24 bits ) , and make 4 characters out of
them ( 4 x 6 = 24 bits ) .
%%
encodeBase64(Bs) when is_list(Bs) ->
encodeBase64(iolist_to_binary(Bs), <<>>);
encodeBase64(Bs) ->
encodeBase64(Bs, <<>>).
encodeBase64(<<B:3/binary, Bs/binary>>, Acc) ->
<<C1:6, C2:6, C3:6, C4:6>> = B,
encodeBase64(Bs, <<Acc/binary, (enc(C1)), (enc(C2)), (enc(C3)), (enc(C4))>>);
encodeBase64(<<B:2/binary>>, Acc) ->
<<C1:6, C2:6, C3:6, _:6>> = <<B/binary, 0>>,
<<Acc/binary, (enc(C1)), (enc(C2)), (enc(C3)), $=>>;
encodeBase64(<<B:1/binary>>, Acc) ->
<<C1:6, C2:6, _:12>> = <<B/binary, 0, 0>>,
<<Acc/binary, (enc(C1)), (enc(C2)), $=, $=>>;
encodeBase64(<<>>, Acc) ->
Acc.
%% enc/1
%%
Mapping : 0 - 25 - > A - Z , 26 - 51 - > a - z , 52 - 61 - > 0 - 9 , 62 - > + , 63 - > /
%%
enc(C) ->
65 + C + 6*?st(C,26) - 75*?st(C,52) -15*?st(C,62) + 3*?st(C,63). | null | https://raw.githubusercontent.com/joewilliams/erl_geo_dns/682c3925959db61ead99f13160ef8bd77486a871/apps/couchbeam/src/couchbeam_util.erl | erlang | you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Some code imported from ibrowse project
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
$\%
$\.
imported from ibrowse project :
, d2h(X bsr 4), d2h(X band 16#0f) | Acc]);
@doc URL safe encoding of the given term.
@spec join([string()], Separator) -> string()
@doc Join a list of strings together with the given separator
string or char.
code from CouchDB
@doc split a binary
@doc Guess the mime type of a file by the extension of its filename.
Purpose : Base 64 encoding
erlang ssl library
encode64(Bytes|Binary) -> binary
enc/1
| Copyright 2009 .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
Some code from michiweb project under BSD license
< >
copyright 2007 Mochi Media , Inc.
in the Software without restriction , including without limitation the rights
copies of the Software , and to permit persons to whom the Software is
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
Copyright 2009 ,
in the Software without restriction , including without limitation the rights
copies of the Software , and to permit persons to whom the Software is
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
@author < >
2009 .
@author < >
copyright 2007 Mochi Media , Inc.
-module(couchbeam_util).
-export([generate_uuids/1, new_uuid/0, to_hex/1, to_digit/1,
join/2, revjoin/3, url_encode/1, quote_plus/1, split/2,
guess_mime/1, val/1, encodeBase64/1]).
-define(IS_HEX(C), ((C >= $0 andalso C =< $9) orelse
(C >= $a andalso C =< $f) orelse
(C >= $A andalso C =< $F))).
-define(QS_SAFE(C), ((C >= $a andalso C =< $z) orelse
(C >= $A andalso C =< $Z) orelse
(C >= $0 andalso C =< $9) orelse
(C =:= ?FULLSTOP orelse C =:= $- orelse C =:= $~ orelse
C =:= $_))).
hexdigit(C) when C < 10 -> $0 + C;
hexdigit(C) when C < 16 -> $A + (C - 10).
( ) ) - > UrlEncodedStr::string ( )
@doc URL - encodes a string based on RFC 1738 . Returns a flat list .
url_encode(Str) when is_list(Str) ->
url_encode_char(lists:reverse(Str), []).
url_encode_char([X | T], Acc) when X >= $0, X =< $9 ->
url_encode_char(T, [X | Acc]);
url_encode_char([X | T], Acc) when X >= $a, X =< $z ->
url_encode_char(T, [X | Acc]);
url_encode_char([X | T], Acc) when X >= $A, X =< $Z ->
url_encode_char(T, [X | Acc]);
url_encode_char([X | T], Acc) when X == $-; X == $_; X == $. ->
url_encode_char(T, [X | Acc]);
url_encode_char([32 | T], Acc) ->
url_encode_char(T, [$+ | Acc]);
url_encode_char([X | T], Acc) ->
url_encode_char([], Acc) ->
Acc.
d2h(N) when N<10 -> N+$0;
d2h(N) -> N+$a-10.
( ) | integer ( ) | float ( ) | string ( ) | binary ( ) ) - > string ( )
quote_plus(Atom) when is_atom(Atom) ->
quote_plus(atom_to_list(Atom));
quote_plus(Int) when is_integer(Int) ->
quote_plus(integer_to_list(Int));
quote_plus(Binary) when is_binary(Binary) ->
quote_plus(binary_to_list(Binary));
quote_plus(Float) when is_float(Float) ->
quote_plus(couchbeam_mochinum:digits(Float));
quote_plus(String) ->
quote_plus(String, []).
quote_plus([], Acc) ->
lists:reverse(Acc);
quote_plus([C | Rest], Acc) when ?QS_SAFE(C) ->
quote_plus(Rest, [C | Acc]);
quote_plus([$\s | Rest], Acc) ->
quote_plus(Rest, [$+ | Acc]);
quote_plus([C | Rest], Acc) ->
<<Hi:4, Lo:4>> = <<C>>,
quote_plus(Rest, [hexdigit(Lo), hexdigit(Hi), ?PERCENT | Acc]).
generate_uuids(Count) ->
[ new_uuid() || _ <- lists:seq(1,Count)].
Code from Mochiweb /
join([], _Separator) ->
[];
join([S], _Separator) ->
lists:flatten(S);
join(Strings, Separator) ->
lists:flatten(revjoin(lists:reverse(Strings), Separator, [])).
revjoin([], _Separator, Acc) ->
Acc;
revjoin([S | Rest], Separator, []) ->
revjoin(Rest, Separator, [S]);
revjoin([S | Rest], Separator, Acc) ->
revjoin(Rest, Separator, [S, Separator | Acc]).
new_uuid() ->
list_to_binary(to_hex(crypto:rand_bytes(16))).
to_hex([]) ->
[];
to_hex(Bin) when is_binary(Bin) ->
to_hex(binary_to_list(Bin));
to_hex([H|T]) ->
[to_digit(H div 16), to_digit(H rem 16) | to_hex(T)].
to_digit(N) when N < 10 -> $0 + N;
to_digit(N) -> $a + N-10.
@spec split(Bin::binary ( ) , Chars::string ( ) ) - > binary ( )
split(Bin, Chars) ->
split(Chars, Bin, 0, []).
split(Chars, Bin, Idx, Acc) ->
case Bin of
<<This:Idx/binary, Char, Tail/binary>> ->
case lists:member(Char, Chars) of
false ->
split(Chars, Bin, Idx+1, Acc);
true ->
split(Chars, Tail, 0, [This|Acc])
end;
<<This:Idx/binary>> ->
lists:reverse(Acc, [This])
end.
val(V) when is_list(V) ->
V;
val(V) when is_integer(V) ->
integer_to_list(V);
val(V) when is_binary(V) ->
binary_to_list(V);
val(V) ->
V.
guess_mime(string ( ) ) - > string ( )
guess_mime(File) ->
case filename:extension(File) of
".html" ->
"text/html";
".xhtml" ->
"application/xhtml+xml";
".xml" ->
"application/xml";
".css" ->
"text/css";
".js" ->
"application/x-javascript";
".jpg" ->
"image/jpeg";
".gif" ->
"image/gif";
".png" ->
"image/png";
".swf" ->
"application/x-shockwave-flash";
".zip" ->
"application/zip";
".bz2" ->
"application/x-bzip2";
".gz" ->
"application/x-gzip";
".tar" ->
"application/x-tar";
".tgz" ->
"application/x-gzip";
".txt" ->
"text/plain";
".doc" ->
"application/msword";
".pdf" ->
"application/pdf";
".xls" ->
"application/vnd.ms-excel";
".rtf" ->
"application/rtf";
".mov" ->
"video/quicktime";
".mp3" ->
"audio/mpeg";
".z" ->
"application/x-compress";
".wav" ->
"audio/x-wav";
".ico" ->
"image/x-icon";
".bmp" ->
"image/bmp";
".m4a" ->
"audio/mpeg";
".m3u" ->
"audio/x-mpegurl";
".exe" ->
"application/octet-stream";
".csv" ->
"text/csv";
_ ->
"text/plain"
end.
Copied from ssl_base_64 to avoid using the
-define(st(X,A), ((X-A+256) div 256)).
Take 3 bytes a time ( 3 x 8 = 24 bits ) , and make 4 characters out of
them ( 4 x 6 = 24 bits ) .
encodeBase64(Bs) when is_list(Bs) ->
encodeBase64(iolist_to_binary(Bs), <<>>);
encodeBase64(Bs) ->
encodeBase64(Bs, <<>>).
encodeBase64(<<B:3/binary, Bs/binary>>, Acc) ->
<<C1:6, C2:6, C3:6, C4:6>> = B,
encodeBase64(Bs, <<Acc/binary, (enc(C1)), (enc(C2)), (enc(C3)), (enc(C4))>>);
encodeBase64(<<B:2/binary>>, Acc) ->
<<C1:6, C2:6, C3:6, _:6>> = <<B/binary, 0>>,
<<Acc/binary, (enc(C1)), (enc(C2)), (enc(C3)), $=>>;
encodeBase64(<<B:1/binary>>, Acc) ->
<<C1:6, C2:6, _:12>> = <<B/binary, 0, 0>>,
<<Acc/binary, (enc(C1)), (enc(C2)), $=, $=>>;
encodeBase64(<<>>, Acc) ->
Acc.
Mapping : 0 - 25 - > A - Z , 26 - 51 - > a - z , 52 - 61 - > 0 - 9 , 62 - > + , 63 - > /
enc(C) ->
65 + C + 6*?st(C,26) - 75*?st(C,52) -15*?st(C,62) + 3*?st(C,63). |
1218f5c0af35578e52dbdd3ec4275147886f37a7a9509877b442b807dcbe1c3c | horie-t/iacc-riscv | compiler.scm | (import (rnrs hashtables))
(load "test_cases.scm")
;;;; ユーティリティ関数
;;; 書式と引数を取って表示し、改行を付け加えます。
例 : ( emit " addi t0 , t0 , ~s " 1 )
addi t0 , t0 , 1
;; が表示されます。
(define (emit . args)
(apply format #t args)
(newline))
;;; ユニーク・ラベル生成
;; 重複のない、ラベルを返します。
(define unique-label
(let ((count 0))
(lambda ()
(let ((L (format "L_~s" count)))
(set! count (+ count 1))
L))))
;;;; オブジェクト型情報定義: タグ付きポインタ表現を使う
;;; 整数: 下位2ビットが00、上位30ビットが符号付き整数となっている
整数変換シフト量
(define fxmask #x03) ; 整数判定ビットマスク(ANDを取って0なら整数オブジェクト)
(define fxtag #0x0) ;
;;; boolean:
(define bool_f #x2f) ; #fの数値表現
(define bool_t #x6f) ; #t
(define boolmask #xbf) ; boolean判定ビットマスク(ANDを取ってis_boolならbooleanオブジェクト)
(define is_bool #x2f) ;
(define bool_bit 6) ; booleanの判定用ビット位置
;;; 空リスト:
(define empty_list #x3f) ;
(define emptymask #xff) ;
文字 :
(define charmask #xff) ; char判定ビットマスク(ANDを取って、chartagならchar)
(define chartag #x0f) ; charタグ
(define charshift 8) ; char変換シフト量
(define wordsize 4) ; 32bit(4バイト)
(define fixnum-bits (- (* wordsize 8) fxshift))
(define fxlower (- (expt 2 (- fixnum-bits 1))))
(define fxupper (- (expt 2 (- fixnum-bits 1))
1))
(define (fixnum? x)
(and (integer? x) (exact? x) (<= fxlower x fxupper)))
;;;; 即値関連関数
;;; 即値かどうかを返します。
(define (immediate? x)
(or (fixnum? x) (boolean? x) (char? x) (null? x)))
;;; Schemeの即値から、アセンブリ言語でのオブジェクト表現を返します。
(define (immediate-rep x)
(cond
((fixnum? x) (ash x fxshift))
((eq? x #f) bool_f)
((eq? x #t) bool_t)
((char? x) (logior (ash (char->integer x) charshift) chartag))
((null? x) empty_list)
(else (error "invalid immediate"))))
即値表現から、アセンブリ言語を出力します 。
(define (emit-immediate expr)
(emit " li a0, ~s" (immediate-rep expr)))
;;;; グローバル・プロバティ
(define *prop* (make-eq-hashtable))
(define (getprop x property)
(hashtable-ref
(hashtable-ref *prop* x #f)
property #f))
(define (putprop x property val)
(let ((entry (hashtable-ref *prop* x #f)))
(if entry
(hashtable-set! entry property val)
(hashtable-set! *prop*
x
(let ((entry (make-eq-hashtable)))
(hashtable-set! entry property val)
entry)))))
プリミティブ関連
;;; プリミティブ定義(*porp*にプリミティブ関連の情報を追加)
;; 例: (define-primitive (fxadd1 arg)
;; 出力内容 ...)
(define-syntax define-primitive
(syntax-rules ()
((_ (prime-name si arg* ...) body body* ...)
(begin
(putprop 'prime-name '*is-prime* #t)
(putprop 'prime-name '*arg-count
(length '(arg* ...)))
(putprop 'prime-name '*emmiter*
(lambda (si arg* ...)
body body* ...))))))
;;; 引数が基本演算かどうかを返します。
; xは、add1のようにシンボルで、*is-prime*が#tにセットされている必要がある
(define (primitive? x)
(and (symbol? x) (getprop x '*is-prime*)))
(define (primitive-emitter x)
(or (getprop x '*emmiter*) (error "primitive-emitter: not exist emmiter")))
;;;; 単項演算関連
;;; 単項演算呼び出し(単項演算処理)かどうかを返します。
;; 単項演算呼び出しは(op arg)の形式なので、最初はpairで、carがprimitive?がtrueを返すものでなければならない。
(define (primcall? expr)
(and (pair? expr) (primitive? (car expr))))
(define (emit-primcall si expr)
(let ((prim (car expr))
(args (cdr expr)))
(apply (primitive-emitter prim) si args)))
引数に1を加えた値を返します
(define-primitive (fxadd1 si arg)
(emit-expr si arg)
(emit " addi a0, a0, ~s" (immediate-rep 1)))
引数から1を引いた値を返します
(define-primitive (fxsub1 si arg)
(emit-expr si arg)
(emit " addi a0, a0, ~s" (immediate-rep -1)))
(define-primitive (fixnum->char si arg)
(emit-expr si arg)
(emit " slli a0, a0, ~s" (- charshift fxshift))
(emit " ori a0, a0, ~s" chartag))
;;; charからfixnumに変換します。
(define-primitive (char->fixnum si arg)
(emit-expr si arg)
(emit " srli a0, a0, ~s" (- charshift fxshift)))
;;; fixnumかどうかを返します
(define-primitive (fixnum? si arg)
(emit-expr si arg)
(emit " andi a0, a0, ~s" fxmask)
(emit " addi a0, a0, ~s" (- fxtag))
(emit " seqz a0, a0")
(emit " slli a0, a0, ~s" bool_bit)
(emit " ori a0, a0, ~s" bool_f))
;;; 空リストかどうかを返します
(define-primitive (null? si arg)
(emit-expr si arg)
(emit " andi a0, a0, ~s" emptymask)
(emit " addi a0, a0, ~s" (- empty_list))
(emit " seqz a0, a0")
(emit " slli a0, a0, ~s" bool_bit)
(emit " ori a0, a0, ~s" bool_f))
;;; booleanオブジェクトかどうかを返します
(define-primitive (boolean? si arg)
(emit-expr si arg)
(emit " andi a0, a0, ~s" boolmask)
(emit " addi a0, a0, ~s" (- is_bool))
(emit " seqz a0, a0")
(emit " slli a0, a0, ~s" bool_bit)
(emit " ori a0, a0, ~s" bool_f))
;;; 文字オブジェクトかどうかを返します
(define-primitive (char? si arg)
(emit-expr si arg)
(emit " andi a0, a0, ~s" charmask)
(emit " addi a0, a0, ~s" (- chartag))
(emit " seqz a0, a0")
(emit " slli a0, a0, ~s" bool_bit)
(emit " ori a0, a0, ~s" bool_f))
;;; #fなら#tを返し、それ以外は#fを返します。
(define-primitive (not si arg)
(emit-expr si arg)
(emit " addi a0, a0, ~s" (- bool_f))
(emit " seqz a0, a0")
(emit " slli a0, a0, ~s" bool_bit)
(emit " ori a0, a0, ~s" bool_f))
;;;
(define-primitive (fxlognot si arg)
(emit-expr si arg)
(emit " xori a0, a0, ~s" (immediate-rep -1)))
;;;; 二項基本演算
;;; 整数加算
siは、stack indexの略。siが指す先は、空き領域にしてから呼び出す事
(emit-expr si arg1)
(emit " sw a0, ~s(sp)" si) ; 結果をスタックに一時退避
(emit-expr (- si wordsize) arg2)
(emit " lw t0, ~s(sp)" si) ; スタックに退避した値をt0に復元
(emit " add a0, a0, t0"))
;;; 整数減算
(define-primitive (fx- si arg1 arg2)
(emit-expr si arg1)
(emit " sw a0, ~s(sp)" si)
(emit-expr (- si wordsize) arg2)
(emit " lw t0, ~s(sp)" si)
(emit " sub a0, t0, a0"))
;;; 整数ビット論理積
(define-primitive (fxlogand si arg1 arg2)
(emit-expr si arg1)
(emit " sw a0, ~s(sp)" si)
(emit-expr (- si wordsize) arg2)
(emit " lw t0, ~s(sp)" si)
(emit " and a0, a0, t0"))
;;; 整数ビット論理和
(define-primitive (fxlogor si arg1 arg2)
(emit-expr si arg1)
(emit " sw a0, ~s(sp)" si)
(emit-expr (- si wordsize) arg2)
(emit " lw t0, ~s(sp)" si)
(emit " or a0, a0, t0"))
整数等号
(define-primitive (fx= si arg1 arg2)
(emit-expr si arg1)
(emit " sw a0, ~s(sp)" si)
(emit-expr (- si wordsize) arg2)
(emit " lw t0, ~s(sp)" si)
(emit " sub a0, a0, t0")
(emit " seqz a0, a0")
(emit " slli a0, a0, ~s" bool_bit)
(emit " ori a0, a0, ~s" bool_f))
整数小なり
(define-primitive (fx< si arg1 arg2)
(emit-expr si arg1)
(emit " sw a0, ~s(sp)" si)
(emit-expr (- si wordsize) arg2)
(emit " lw t0, ~s(sp)" si)
(emit " slt a0, t0, a0")
(emit " slli a0, a0, ~s" bool_bit)
(emit " ori a0, a0, ~s" bool_f))
;;; 整数以下
(define-primitive (fx<= si arg1 arg2)
(emit-expr si (list 'fx< arg2 arg1)) ; 大なりを判定して、あとで否定する
(emit " xori a0, a0, ~s" (ash 1 bool_bit)))
;;; 整数大なり
(define-primitive (fx> si arg1 arg2)
(emit-expr si (list 'fx< arg2 arg1))) ; 引数を逆にして、小なりを使う
;;; 整数以上
(define-primitive (fx>= si arg1 arg2)
(emit-expr si (list 'fx< arg1 arg2)) ; 小なりを判定して、あとで否定する
(emit " xori a0, a0, ~s" (ash 1 bool_bit)))
;;;; 条件式
if形式
;;; if形式かどうかを返します
(define (if? expr)
(and (pair? expr) (eq? (car expr) 'if)))
;;; if形式の述部(predicate)を取り出します。
(define (if-test expr)
(cadr expr))
;;; if形式の帰結部(consequent)を取り出します。
(define (if-conseq expr)
(caddr expr))
;;; if形式の代替部(alternative)を取り出します。
(define (if-altern expr)
(cadddr expr))
;;; if形式の出力
(define (emit-if si expr)
(let ((alt-label (unique-label))
(end-label (unique-label)))
(emit-expr si (if-test expr))
(emit " addi a0, a0, ~s" (- bool_f))
(emit " beqz a0, ~a" alt-label)
(emit-expr si (if-conseq expr))
(emit " j ~a" end-label)
(emit "~a:" alt-label)
(emit-expr si (if-altern expr))
(emit "~a:" end-label)))
;;; and形式
(define (and? expr)
(and (pair? expr) (eq? (car expr) 'and)))
(define (emit-and si expr)
(let ((pred-len (length (cdr expr))))
(cond
((= pred-len 0)
引数なしなら常に真
((= pred-len 1)
(emit-primcall si (list 'not (cadr expr))) ; まず、(not test)の式に変換して評価する
(emit " xori a0, a0, ~s" (ash 1 bool_bit))) ; a0は偽かどうかの値なので、ビット反転でnotを演算する
(else
;; (and test test* ...) => (if test (and test* ...) #f)と変換して処理
(emit-if si (list 'if (cadr expr)
(cons 'and (cddr expr))
#f))))))
;;; or形式
(define (or? expr)
(and (pair? expr) (eq? (car expr) 'or)))
(define (emit-or si expr)
(let ((pred-len (length (cdr expr))))
(cond
((= pred-len 0)
(emit " li a0, ~s" bool_f)) ;引数なしなら常に偽
((= pred-len 1)
(emit-primcall si (list 'not (cadr expr))) ; まず、(not test)の式に変換して評価する
(emit " xori a0, a0, ~s" (ash 1 bool_bit))) ; a0は偽かどうかの値なので、ビット反転でnotを演算する
(else
;; (or test test* ...) => (if test #t (or test* ...))と変換して処理
(emit-if si (list 'if (cadr expr)
#t
(cons 'or (cddr expr))))))))
コンパイラ・メイン処理
(define (emit-expr si expr)
(cond
((immediate? expr) (emit-immediate expr)) ; 即値の場合は、siを必要としない。他はsiを必要とする処理を呼び出す可能性がある
((if? expr) (emit-if si expr))
((and? expr) (emit-and si expr))
((or? expr) (emit-or si expr))
((primcall? expr) (emit-primcall si expr))
(else (error "imvalid expr: ~a" expr))))
(define (emit-program expr)
(emit " .text")
(emit " .globl scheme_entry")
(emit " .type scheme_entry, @function")
(emit "scheme_entry:")
(emit-expr (- wordsize) expr)
(emit " ret"))
;;;; 自動テスト関連
Schemeプログラムのコンパイル
(define (compile-program expr)
(with-output-to-file (path "stst.s")
(lambda ()
(emit-program expr))))
実行ファイルの作成
(define (build)
(unless (zero? (process-exit-wait (run-process "make stst --quiet")))
(error "Could not build target.")))
;;; テスト・プログラムの実行
(define (execute)
(unless (zero? (process-exit-wait (run-process out-to: (path "./stst.out")
"spike pk ./stst > ./stst.out")))
(error "Produced program exited abnormally.")))
;;; テスト・プログラムの実行結果の検証
(define (validate expected-output)
(let ((executed-output (path-data (path "stst.out"))))
(unless (string=? expected-output executed-output)
(error "Output mismatch for expected ~s, got ~s."
expected-output executed-output))))
(define (test-one expr expected-output)
(compile-program expr)
(build)
(execute)
(validate expected-output))
;;; 全てのテストケースをテストします。
(define (test-all)
(for-each (lambda (test-case)
(format #t "TestCase: ~a ..." (car test-case))
(flush-output-port)
(test-one (cadr test-case) (caddr test-case))
(format #t " ok.\n"))
test-cases))
( test - one ' ( fx+ 4 2 ) " 6\n " )
| null | https://raw.githubusercontent.com/horie-t/iacc-riscv/2aea0b27f712f4b9354ecf04a7a0cb08f5c2117e/04_BinaryPrimitives/compiler.scm | scheme | ユーティリティ関数
書式と引数を取って表示し、改行を付け加えます。
が表示されます。
ユニーク・ラベル生成
重複のない、ラベルを返します。
オブジェクト型情報定義: タグ付きポインタ表現を使う
整数: 下位2ビットが00、上位30ビットが符号付き整数となっている
整数判定ビットマスク(ANDを取って0なら整数オブジェクト)
boolean:
#fの数値表現
#t
boolean判定ビットマスク(ANDを取ってis_boolならbooleanオブジェクト)
booleanの判定用ビット位置
空リスト:
char判定ビットマスク(ANDを取って、chartagならchar)
charタグ
char変換シフト量
32bit(4バイト)
即値関連関数
即値かどうかを返します。
Schemeの即値から、アセンブリ言語でのオブジェクト表現を返します。
グローバル・プロバティ
プリミティブ定義(*porp*にプリミティブ関連の情報を追加)
例: (define-primitive (fxadd1 arg)
出力内容 ...)
引数が基本演算かどうかを返します。
xは、add1のようにシンボルで、*is-prime*が#tにセットされている必要がある
単項演算関連
単項演算呼び出し(単項演算処理)かどうかを返します。
単項演算呼び出しは(op arg)の形式なので、最初はpairで、carがprimitive?がtrueを返すものでなければならない。
charからfixnumに変換します。
fixnumかどうかを返します
空リストかどうかを返します
booleanオブジェクトかどうかを返します
文字オブジェクトかどうかを返します
#fなら#tを返し、それ以外は#fを返します。
二項基本演算
整数加算
結果をスタックに一時退避
スタックに退避した値をt0に復元
整数減算
整数ビット論理積
整数ビット論理和
整数以下
大なりを判定して、あとで否定する
整数大なり
引数を逆にして、小なりを使う
整数以上
小なりを判定して、あとで否定する
条件式
if形式かどうかを返します
if形式の述部(predicate)を取り出します。
if形式の帰結部(consequent)を取り出します。
if形式の代替部(alternative)を取り出します。
if形式の出力
and形式
まず、(not test)の式に変換して評価する
a0は偽かどうかの値なので、ビット反転でnotを演算する
(and test test* ...) => (if test (and test* ...) #f)と変換して処理
or形式
引数なしなら常に偽
まず、(not test)の式に変換して評価する
a0は偽かどうかの値なので、ビット反転でnotを演算する
(or test test* ...) => (if test #t (or test* ...))と変換して処理
即値の場合は、siを必要としない。他はsiを必要とする処理を呼び出す可能性がある
自動テスト関連
テスト・プログラムの実行
テスト・プログラムの実行結果の検証
全てのテストケースをテストします。 | (import (rnrs hashtables))
(load "test_cases.scm")
例 : ( emit " addi t0 , t0 , ~s " 1 )
addi t0 , t0 , 1
(define (emit . args)
(apply format #t args)
(newline))
(define unique-label
(let ((count 0))
(lambda ()
(let ((L (format "L_~s" count)))
(set! count (+ count 1))
L))))
整数変換シフト量
文字 :
(define fixnum-bits (- (* wordsize 8) fxshift))
(define fxlower (- (expt 2 (- fixnum-bits 1))))
(define fxupper (- (expt 2 (- fixnum-bits 1))
1))
(define (fixnum? x)
(and (integer? x) (exact? x) (<= fxlower x fxupper)))
(define (immediate? x)
(or (fixnum? x) (boolean? x) (char? x) (null? x)))
(define (immediate-rep x)
(cond
((fixnum? x) (ash x fxshift))
((eq? x #f) bool_f)
((eq? x #t) bool_t)
((char? x) (logior (ash (char->integer x) charshift) chartag))
((null? x) empty_list)
(else (error "invalid immediate"))))
即値表現から、アセンブリ言語を出力します 。
(define (emit-immediate expr)
(emit " li a0, ~s" (immediate-rep expr)))
(define *prop* (make-eq-hashtable))
(define (getprop x property)
(hashtable-ref
(hashtable-ref *prop* x #f)
property #f))
(define (putprop x property val)
(let ((entry (hashtable-ref *prop* x #f)))
(if entry
(hashtable-set! entry property val)
(hashtable-set! *prop*
x
(let ((entry (make-eq-hashtable)))
(hashtable-set! entry property val)
entry)))))
プリミティブ関連
(define-syntax define-primitive
(syntax-rules ()
((_ (prime-name si arg* ...) body body* ...)
(begin
(putprop 'prime-name '*is-prime* #t)
(putprop 'prime-name '*arg-count
(length '(arg* ...)))
(putprop 'prime-name '*emmiter*
(lambda (si arg* ...)
body body* ...))))))
(define (primitive? x)
(and (symbol? x) (getprop x '*is-prime*)))
(define (primitive-emitter x)
(or (getprop x '*emmiter*) (error "primitive-emitter: not exist emmiter")))
(define (primcall? expr)
(and (pair? expr) (primitive? (car expr))))
(define (emit-primcall si expr)
(let ((prim (car expr))
(args (cdr expr)))
(apply (primitive-emitter prim) si args)))
引数に1を加えた値を返します
(define-primitive (fxadd1 si arg)
(emit-expr si arg)
(emit " addi a0, a0, ~s" (immediate-rep 1)))
引数から1を引いた値を返します
(define-primitive (fxsub1 si arg)
(emit-expr si arg)
(emit " addi a0, a0, ~s" (immediate-rep -1)))
(define-primitive (fixnum->char si arg)
(emit-expr si arg)
(emit " slli a0, a0, ~s" (- charshift fxshift))
(emit " ori a0, a0, ~s" chartag))
(define-primitive (char->fixnum si arg)
(emit-expr si arg)
(emit " srli a0, a0, ~s" (- charshift fxshift)))
(define-primitive (fixnum? si arg)
(emit-expr si arg)
(emit " andi a0, a0, ~s" fxmask)
(emit " addi a0, a0, ~s" (- fxtag))
(emit " seqz a0, a0")
(emit " slli a0, a0, ~s" bool_bit)
(emit " ori a0, a0, ~s" bool_f))
(define-primitive (null? si arg)
(emit-expr si arg)
(emit " andi a0, a0, ~s" emptymask)
(emit " addi a0, a0, ~s" (- empty_list))
(emit " seqz a0, a0")
(emit " slli a0, a0, ~s" bool_bit)
(emit " ori a0, a0, ~s" bool_f))
(define-primitive (boolean? si arg)
(emit-expr si arg)
(emit " andi a0, a0, ~s" boolmask)
(emit " addi a0, a0, ~s" (- is_bool))
(emit " seqz a0, a0")
(emit " slli a0, a0, ~s" bool_bit)
(emit " ori a0, a0, ~s" bool_f))
(define-primitive (char? si arg)
(emit-expr si arg)
(emit " andi a0, a0, ~s" charmask)
(emit " addi a0, a0, ~s" (- chartag))
(emit " seqz a0, a0")
(emit " slli a0, a0, ~s" bool_bit)
(emit " ori a0, a0, ~s" bool_f))
(define-primitive (not si arg)
(emit-expr si arg)
(emit " addi a0, a0, ~s" (- bool_f))
(emit " seqz a0, a0")
(emit " slli a0, a0, ~s" bool_bit)
(emit " ori a0, a0, ~s" bool_f))
(define-primitive (fxlognot si arg)
(emit-expr si arg)
(emit " xori a0, a0, ~s" (immediate-rep -1)))
siは、stack indexの略。siが指す先は、空き領域にしてから呼び出す事
(emit-expr si arg1)
(emit-expr (- si wordsize) arg2)
(emit " add a0, a0, t0"))
(define-primitive (fx- si arg1 arg2)
(emit-expr si arg1)
(emit " sw a0, ~s(sp)" si)
(emit-expr (- si wordsize) arg2)
(emit " lw t0, ~s(sp)" si)
(emit " sub a0, t0, a0"))
(define-primitive (fxlogand si arg1 arg2)
(emit-expr si arg1)
(emit " sw a0, ~s(sp)" si)
(emit-expr (- si wordsize) arg2)
(emit " lw t0, ~s(sp)" si)
(emit " and a0, a0, t0"))
(define-primitive (fxlogor si arg1 arg2)
(emit-expr si arg1)
(emit " sw a0, ~s(sp)" si)
(emit-expr (- si wordsize) arg2)
(emit " lw t0, ~s(sp)" si)
(emit " or a0, a0, t0"))
整数等号
(define-primitive (fx= si arg1 arg2)
(emit-expr si arg1)
(emit " sw a0, ~s(sp)" si)
(emit-expr (- si wordsize) arg2)
(emit " lw t0, ~s(sp)" si)
(emit " sub a0, a0, t0")
(emit " seqz a0, a0")
(emit " slli a0, a0, ~s" bool_bit)
(emit " ori a0, a0, ~s" bool_f))
整数小なり
(define-primitive (fx< si arg1 arg2)
(emit-expr si arg1)
(emit " sw a0, ~s(sp)" si)
(emit-expr (- si wordsize) arg2)
(emit " lw t0, ~s(sp)" si)
(emit " slt a0, t0, a0")
(emit " slli a0, a0, ~s" bool_bit)
(emit " ori a0, a0, ~s" bool_f))
(define-primitive (fx<= si arg1 arg2)
(emit " xori a0, a0, ~s" (ash 1 bool_bit)))
(define-primitive (fx> si arg1 arg2)
(define-primitive (fx>= si arg1 arg2)
(emit " xori a0, a0, ~s" (ash 1 bool_bit)))
if形式
(define (if? expr)
(and (pair? expr) (eq? (car expr) 'if)))
(define (if-test expr)
(cadr expr))
(define (if-conseq expr)
(caddr expr))
(define (if-altern expr)
(cadddr expr))
(define (emit-if si expr)
(let ((alt-label (unique-label))
(end-label (unique-label)))
(emit-expr si (if-test expr))
(emit " addi a0, a0, ~s" (- bool_f))
(emit " beqz a0, ~a" alt-label)
(emit-expr si (if-conseq expr))
(emit " j ~a" end-label)
(emit "~a:" alt-label)
(emit-expr si (if-altern expr))
(emit "~a:" end-label)))
(define (and? expr)
(and (pair? expr) (eq? (car expr) 'and)))
(define (emit-and si expr)
(let ((pred-len (length (cdr expr))))
(cond
((= pred-len 0)
引数なしなら常に真
((= pred-len 1)
(else
(emit-if si (list 'if (cadr expr)
(cons 'and (cddr expr))
#f))))))
(define (or? expr)
(and (pair? expr) (eq? (car expr) 'or)))
(define (emit-or si expr)
(let ((pred-len (length (cdr expr))))
(cond
((= pred-len 0)
((= pred-len 1)
(else
(emit-if si (list 'if (cadr expr)
#t
(cons 'or (cddr expr))))))))
コンパイラ・メイン処理
(define (emit-expr si expr)
(cond
((if? expr) (emit-if si expr))
((and? expr) (emit-and si expr))
((or? expr) (emit-or si expr))
((primcall? expr) (emit-primcall si expr))
(else (error "imvalid expr: ~a" expr))))
(define (emit-program expr)
(emit " .text")
(emit " .globl scheme_entry")
(emit " .type scheme_entry, @function")
(emit "scheme_entry:")
(emit-expr (- wordsize) expr)
(emit " ret"))
Schemeプログラムのコンパイル
(define (compile-program expr)
(with-output-to-file (path "stst.s")
(lambda ()
(emit-program expr))))
実行ファイルの作成
(define (build)
(unless (zero? (process-exit-wait (run-process "make stst --quiet")))
(error "Could not build target.")))
(define (execute)
(unless (zero? (process-exit-wait (run-process out-to: (path "./stst.out")
"spike pk ./stst > ./stst.out")))
(error "Produced program exited abnormally.")))
(define (validate expected-output)
(let ((executed-output (path-data (path "stst.out"))))
(unless (string=? expected-output executed-output)
(error "Output mismatch for expected ~s, got ~s."
expected-output executed-output))))
(define (test-one expr expected-output)
(compile-program expr)
(build)
(execute)
(validate expected-output))
(define (test-all)
(for-each (lambda (test-case)
(format #t "TestCase: ~a ..." (car test-case))
(flush-output-port)
(test-one (cadr test-case) (caddr test-case))
(format #t " ok.\n"))
test-cases))
( test - one ' ( fx+ 4 2 ) " 6\n " )
|
3cb69cbed34556d1639481824d7cedae5cffd7afa8f2aafb25d438a3351cca86 | Psi-Prod/Mehari | stream.ml | let count clock n =
Seq.unfold
(function
| None -> None
| Some i when Int.equal i n -> Some ("End", None)
| Some i ->
Eio.Time.sleep clock 1.;
Some (Printf.sprintf "%i\n" i, Some (i + 1)))
(Some 0)
let router clock req =
match Mehari.query req with
| None -> Mehari.(response input) "Enter a number"
| Some number -> (
match int_of_string_opt number with
| None -> Mehari.(response bad_request) "Enter a valid number!"
| Some n ->
let body = count clock n |> Mehari.seq ~flush:true in
Mehari.(response_body body plaintext))
let main ~clock ~cwd ~net =
let certchains =
Eio.Path.
[
X509_eio.private_of_pems ~cert:(cwd / "cert.pem")
~priv_key:(cwd / "key.pem");
]
in
Mehari_eio.run net ~certchains (router clock)
let () =
Eio_main.run @@ fun env ->
Mirage_crypto_rng_eio.run (module Mirage_crypto_rng.Fortuna) env @@ fun () ->
main ~clock:env#clock ~cwd:env#cwd ~net:env#net
| null | https://raw.githubusercontent.com/Psi-Prod/Mehari/e57202510dd43fa1ce75695cf1ab8f8caa49f0f0/examples/stream.ml | ocaml | let count clock n =
Seq.unfold
(function
| None -> None
| Some i when Int.equal i n -> Some ("End", None)
| Some i ->
Eio.Time.sleep clock 1.;
Some (Printf.sprintf "%i\n" i, Some (i + 1)))
(Some 0)
let router clock req =
match Mehari.query req with
| None -> Mehari.(response input) "Enter a number"
| Some number -> (
match int_of_string_opt number with
| None -> Mehari.(response bad_request) "Enter a valid number!"
| Some n ->
let body = count clock n |> Mehari.seq ~flush:true in
Mehari.(response_body body plaintext))
let main ~clock ~cwd ~net =
let certchains =
Eio.Path.
[
X509_eio.private_of_pems ~cert:(cwd / "cert.pem")
~priv_key:(cwd / "key.pem");
]
in
Mehari_eio.run net ~certchains (router clock)
let () =
Eio_main.run @@ fun env ->
Mirage_crypto_rng_eio.run (module Mirage_crypto_rng.Fortuna) env @@ fun () ->
main ~clock:env#clock ~cwd:env#cwd ~net:env#net
| |
73d9b7bbe5a371037bc6b163c2ea8e94b30d478e69ae1424e5f30cc9e8fadf9e | phadej/minicsv | MiniCSV.hs | module MiniCSV (
-- * Encoding
csvEncodeTable,
csvEncodeRow,
csvEncodeField,
-- * Decoding
csvDecodeTable,
) where
-------------------------------------------------------------------------------
-- Encoding
-------------------------------------------------------------------------------
csvEncodeTable :: [[String]] -> String
csvEncodeTable = concatMap (\r -> csvEncodeRow r ++ "\r\n")
csvEncodeRow :: [String] -> String
csvEncodeRow [] = ""
csvEncodeRow [x] = csvEncodeField x
csvEncodeRow (x:xs) = csvEncodeField x ++ "," ++ csvEncodeRow xs
csvEncodeField :: String -> String
csvEncodeField xs
| any (`elem` xs) ",\"\n\r"
= '"' : go xs -- opening quote
| otherwise = xs
where
go [] = '"' : []
go ('"' : ys) = '"' : '"' : go ys
go (y : ys) = y : go ys
-------------------------------------------------------------------------------
-- Decoding
-------------------------------------------------------------------------------
-- | Decode CSV trying to recover as much as possible.
csvDecodeTable :: String -> [[String]]
csvDecodeTable [] = []
csvDecodeTable ('\r' : '\n' : cs) = csvDecodeTable cs
csvDecodeTable ('\r' : cs) = csvDecodeTable cs
csvDecodeTable ('\n' : cs) = csvDecodeTable cs
csvDecodeTable (',' : cs) = csvDecodeField ("" :) cs
csvDecodeTable ('"' : cs) = csvDecodeEscapedField id id cs
csvDecodeTable (c : cs) = csvDecodeUnescapedField (c :) id cs
csvDecodeField :: ([String] -> [String]) -> String -> [[String]]
csvDecodeField accR ('\r' : '\n' : cs) = accR [""] : csvDecodeTable cs
csvDecodeField accR ('\r' : cs) = accR [""] : csvDecodeTable cs
csvDecodeField accR ('\n' : cs) = accR [""] : csvDecodeTable cs
csvDecodeField accR ('"' : cs) = csvDecodeEscapedField id accR cs
csvDecodeField accR (',' : cs) = csvDecodeField (accR . ("" :)) cs
csvDecodeField accR (c : cs) = csvDecodeUnescapedField (c :) accR cs
csvDecodeField accR [] = [accR []]
csvDecodeEscapedField :: (String -> String) -> ([String] -> [String]) -> String -> [[String]]
csvDecodeEscapedField accF accR ('"' : '"' : cs) = csvDecodeEscapedField (accF . ('"' :)) accR cs
csvDecodeEscapedField accF accR ('"' : cs) = csvDecodeAfterEscapedField (accR . (accF "" :)) cs
csvDecodeEscapedField accF accR (c : cs) = csvDecodeEscapedField (accF . (c :)) accR cs
csvDecodeEscapedField accF accR [] = [accR [accF ""]]
expected : EOF , EOL or ,
csvDecodeAfterEscapedField :: ([String] -> [String]) -> String -> [[String]]
csvDecodeAfterEscapedField accR [] = [accR []]
csvDecodeAfterEscapedField accR ('\r' : '\n' : cs) = accR [] : csvDecodeTable cs
csvDecodeAfterEscapedField accR ('\r' : cs) = accR [] : csvDecodeTable cs
csvDecodeAfterEscapedField accR ('\n' : cs) = accR [] : csvDecodeTable cs
csvDecodeAfterEscapedField accR (',' : cs) = csvDecodeField accR cs
csvDecodeAfterEscapedField accR (_ : cs) = csvDecodeAfterEscapedField accR cs
csvDecodeUnescapedField :: (String -> String) -> ([String] -> [String]) -> String -> [[String]]
csvDecodeUnescapedField accF accR (',' : cs) = csvDecodeField (accR . (accF "" :)) cs
csvDecodeUnescapedField accF accR ('\r' : '\n' : cs) = accR [accF ""] : csvDecodeTable cs
csvDecodeUnescapedField accF accR ('\r' : cs) = accR [accF ""] : csvDecodeTable cs
csvDecodeUnescapedField accF accR ('\n' : cs) = accR [accF ""] : csvDecodeTable cs
csvDecodeUnescapedField accF accR (c : cs) = csvDecodeUnescapedField (accF . (c :)) accR cs
csvDecodeUnescapedField accF accR [] = [accR [accF ""]]
| null | https://raw.githubusercontent.com/phadej/minicsv/8badfff03166d7e87974e4c9a4407c2df17340f0/src/MiniCSV.hs | haskell | * Encoding
* Decoding
-----------------------------------------------------------------------------
Encoding
-----------------------------------------------------------------------------
opening quote
-----------------------------------------------------------------------------
Decoding
-----------------------------------------------------------------------------
| Decode CSV trying to recover as much as possible. | module MiniCSV (
csvEncodeTable,
csvEncodeRow,
csvEncodeField,
csvDecodeTable,
) where
csvEncodeTable :: [[String]] -> String
csvEncodeTable = concatMap (\r -> csvEncodeRow r ++ "\r\n")
csvEncodeRow :: [String] -> String
csvEncodeRow [] = ""
csvEncodeRow [x] = csvEncodeField x
csvEncodeRow (x:xs) = csvEncodeField x ++ "," ++ csvEncodeRow xs
csvEncodeField :: String -> String
csvEncodeField xs
| any (`elem` xs) ",\"\n\r"
| otherwise = xs
where
go [] = '"' : []
go ('"' : ys) = '"' : '"' : go ys
go (y : ys) = y : go ys
csvDecodeTable :: String -> [[String]]
csvDecodeTable [] = []
csvDecodeTable ('\r' : '\n' : cs) = csvDecodeTable cs
csvDecodeTable ('\r' : cs) = csvDecodeTable cs
csvDecodeTable ('\n' : cs) = csvDecodeTable cs
csvDecodeTable (',' : cs) = csvDecodeField ("" :) cs
csvDecodeTable ('"' : cs) = csvDecodeEscapedField id id cs
csvDecodeTable (c : cs) = csvDecodeUnescapedField (c :) id cs
csvDecodeField :: ([String] -> [String]) -> String -> [[String]]
csvDecodeField accR ('\r' : '\n' : cs) = accR [""] : csvDecodeTable cs
csvDecodeField accR ('\r' : cs) = accR [""] : csvDecodeTable cs
csvDecodeField accR ('\n' : cs) = accR [""] : csvDecodeTable cs
csvDecodeField accR ('"' : cs) = csvDecodeEscapedField id accR cs
csvDecodeField accR (',' : cs) = csvDecodeField (accR . ("" :)) cs
csvDecodeField accR (c : cs) = csvDecodeUnescapedField (c :) accR cs
csvDecodeField accR [] = [accR []]
csvDecodeEscapedField :: (String -> String) -> ([String] -> [String]) -> String -> [[String]]
csvDecodeEscapedField accF accR ('"' : '"' : cs) = csvDecodeEscapedField (accF . ('"' :)) accR cs
csvDecodeEscapedField accF accR ('"' : cs) = csvDecodeAfterEscapedField (accR . (accF "" :)) cs
csvDecodeEscapedField accF accR (c : cs) = csvDecodeEscapedField (accF . (c :)) accR cs
csvDecodeEscapedField accF accR [] = [accR [accF ""]]
expected : EOF , EOL or ,
csvDecodeAfterEscapedField :: ([String] -> [String]) -> String -> [[String]]
csvDecodeAfterEscapedField accR [] = [accR []]
csvDecodeAfterEscapedField accR ('\r' : '\n' : cs) = accR [] : csvDecodeTable cs
csvDecodeAfterEscapedField accR ('\r' : cs) = accR [] : csvDecodeTable cs
csvDecodeAfterEscapedField accR ('\n' : cs) = accR [] : csvDecodeTable cs
csvDecodeAfterEscapedField accR (',' : cs) = csvDecodeField accR cs
csvDecodeAfterEscapedField accR (_ : cs) = csvDecodeAfterEscapedField accR cs
csvDecodeUnescapedField :: (String -> String) -> ([String] -> [String]) -> String -> [[String]]
csvDecodeUnescapedField accF accR (',' : cs) = csvDecodeField (accR . (accF "" :)) cs
csvDecodeUnescapedField accF accR ('\r' : '\n' : cs) = accR [accF ""] : csvDecodeTable cs
csvDecodeUnescapedField accF accR ('\r' : cs) = accR [accF ""] : csvDecodeTable cs
csvDecodeUnescapedField accF accR ('\n' : cs) = accR [accF ""] : csvDecodeTable cs
csvDecodeUnescapedField accF accR (c : cs) = csvDecodeUnescapedField (accF . (c :)) accR cs
csvDecodeUnescapedField accF accR [] = [accR [accF ""]]
|
a832ea9239f4f3c87b352aa578f47ddb614dca9f6284f167fbc852db5b05ed9f | tezos/tezos-mirror | baking_configuration.mli | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2021 Nomadic Labs < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
(** {1 Operations_source abstraction} *)
module Operations_source : sig
type t =
| Local of {filename : string}
(** local mempool resource located in [filename] *)
| Remote of {uri : Uri.t; http_headers : (string * string) list option}
(** remote resource located a [uri], with additional [http_headers]
parameters *)
val encoding : t Data_encoding.t
val pp : Format.formatter -> t -> unit
end
type fees_config = {
minimal_fees : Protocol.Alpha_context.Tez.t;
minimal_nanotez_per_gas_unit : Q.t;
minimal_nanotez_per_byte : Q.t;
}
type validation_config =
| Local of {context_path : string}
| Node
| ContextIndex of Abstract_context_index.t
type nonce_config = Deterministic | Random
type state_recorder_config = Filesystem | Disabled
type t = {
fees : fees_config;
nonce : nonce_config;
validation : validation_config;
retries_on_failure : int;
user_activated_upgrades : (int32 * Protocol_hash.t) list;
liquidity_baking_toggle_vote :
Protocol.Alpha_context.Liquidity_baking.liquidity_baking_toggle_vote;
per_block_vote_file : string option;
force_apply : bool;
force : bool;
state_recorder : state_recorder_config;
extra_operations : Operations_source.t option;
}
val default_fees_config : fees_config
val default_validation_config : validation_config
val default_nonce_config : nonce_config
val default_retries_on_failure_config : int
val default_user_activated_upgrades : (int32 * Protocol_hash.t) list
val default_liquidity_baking_toggle_vote :
Protocol.Alpha_context.Liquidity_baking.liquidity_baking_toggle_vote
val default_force_apply : bool
val default_force : bool
val default_state_recorder_config : state_recorder_config
val default_extra_operations : Operations_source.t option
val default_per_block_vote_file : string
val default_config : t
val make :
?minimal_fees:Protocol.Alpha_context.Tez.t ->
?minimal_nanotez_per_gas_unit:Q.t ->
?minimal_nanotez_per_byte:Q.t ->
?nonce:nonce_config ->
?context_path:string ->
?retries_on_failure:int ->
?user_activated_upgrades:(int32 * Protocol_hash.t) list ->
?liquidity_baking_toggle_vote:
Protocol.Alpha_context.Liquidity_baking.liquidity_baking_toggle_vote ->
?per_block_vote_file:string ->
?force_apply:bool ->
?force:bool ->
?state_recorder:state_recorder_config ->
?extra_operations:Operations_source.t ->
unit ->
t
val fees_config_encoding : fees_config Data_encoding.t
val validation_config_encoding : validation_config Data_encoding.t
val nonce_config_encoding : nonce_config Data_encoding.t
val retries_on_failure_config_encoding : int Data_encoding.t
val user_activate_upgrades_config_encoding :
(int32 * Protocol_hash.t) list Data_encoding.t
val liquidity_baking_toggle_vote_config_encoding :
Protocol.Alpha_context.Liquidity_baking.liquidity_baking_toggle_vote
Data_encoding.t
val encoding : t Data_encoding.t
val pp : Format.formatter -> t -> unit
| null | https://raw.githubusercontent.com/tezos/tezos-mirror/e5ca6c3e274939f1206426962aa4c02e1a1d5319/src/proto_016_PtMumbai/lib_delegate/baking_configuration.mli | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
* {1 Operations_source abstraction}
* local mempool resource located in [filename]
* remote resource located a [uri], with additional [http_headers]
parameters | Copyright ( c ) 2021 Nomadic Labs < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
module Operations_source : sig
type t =
| Local of {filename : string}
| Remote of {uri : Uri.t; http_headers : (string * string) list option}
val encoding : t Data_encoding.t
val pp : Format.formatter -> t -> unit
end
type fees_config = {
minimal_fees : Protocol.Alpha_context.Tez.t;
minimal_nanotez_per_gas_unit : Q.t;
minimal_nanotez_per_byte : Q.t;
}
type validation_config =
| Local of {context_path : string}
| Node
| ContextIndex of Abstract_context_index.t
type nonce_config = Deterministic | Random
type state_recorder_config = Filesystem | Disabled
type t = {
fees : fees_config;
nonce : nonce_config;
validation : validation_config;
retries_on_failure : int;
user_activated_upgrades : (int32 * Protocol_hash.t) list;
liquidity_baking_toggle_vote :
Protocol.Alpha_context.Liquidity_baking.liquidity_baking_toggle_vote;
per_block_vote_file : string option;
force_apply : bool;
force : bool;
state_recorder : state_recorder_config;
extra_operations : Operations_source.t option;
}
val default_fees_config : fees_config
val default_validation_config : validation_config
val default_nonce_config : nonce_config
val default_retries_on_failure_config : int
val default_user_activated_upgrades : (int32 * Protocol_hash.t) list
val default_liquidity_baking_toggle_vote :
Protocol.Alpha_context.Liquidity_baking.liquidity_baking_toggle_vote
val default_force_apply : bool
val default_force : bool
val default_state_recorder_config : state_recorder_config
val default_extra_operations : Operations_source.t option
val default_per_block_vote_file : string
val default_config : t
val make :
?minimal_fees:Protocol.Alpha_context.Tez.t ->
?minimal_nanotez_per_gas_unit:Q.t ->
?minimal_nanotez_per_byte:Q.t ->
?nonce:nonce_config ->
?context_path:string ->
?retries_on_failure:int ->
?user_activated_upgrades:(int32 * Protocol_hash.t) list ->
?liquidity_baking_toggle_vote:
Protocol.Alpha_context.Liquidity_baking.liquidity_baking_toggle_vote ->
?per_block_vote_file:string ->
?force_apply:bool ->
?force:bool ->
?state_recorder:state_recorder_config ->
?extra_operations:Operations_source.t ->
unit ->
t
val fees_config_encoding : fees_config Data_encoding.t
val validation_config_encoding : validation_config Data_encoding.t
val nonce_config_encoding : nonce_config Data_encoding.t
val retries_on_failure_config_encoding : int Data_encoding.t
val user_activate_upgrades_config_encoding :
(int32 * Protocol_hash.t) list Data_encoding.t
val liquidity_baking_toggle_vote_config_encoding :
Protocol.Alpha_context.Liquidity_baking.liquidity_baking_toggle_vote
Data_encoding.t
val encoding : t Data_encoding.t
val pp : Format.formatter -> t -> unit
|
3adee5cbb8d195ce1141fbe810afc2b07d002d796d41d6288bf453a0d55d7409 | aggieben/weblocks | test-template.lisp |
(in-package :weblocks-test)
;;; utilities for easier testing
(defun data-header-template (action body &key (data-class-name "employee") preslots
(postslots `((:div :class "submit"
,(link-action-template action "Modify"
:class "modify")))))
`(:div :class ,(format nil "view data ~A" data-class-name)
(:div :class "extra-top-1" "<!-- empty -->")
(:div :class "extra-top-2" "<!-- empty -->")
(:div :class "extra-top-3" "<!-- empty -->")
(:h1 (:span :class "action" "Viewing: ")
(:span :class "object" ,(humanize-name data-class-name)))
,@preslots
(:ul ,@body)
,@postslots
(:div :class "extra-bottom-1" "<!-- empty -->")
(:div :class "extra-bottom-2" "<!-- empty -->")
(:div :class "extra-bottom-3" "<!-- empty -->")))
| null | https://raw.githubusercontent.com/aggieben/weblocks/8d86be6a4fff8dde0b94181ba60d0dca2cbd9e25/test/views/dataview/test-template.lisp | lisp | utilities for easier testing |
(in-package :weblocks-test)
(defun data-header-template (action body &key (data-class-name "employee") preslots
(postslots `((:div :class "submit"
,(link-action-template action "Modify"
:class "modify")))))
`(:div :class ,(format nil "view data ~A" data-class-name)
(:div :class "extra-top-1" "<!-- empty -->")
(:div :class "extra-top-2" "<!-- empty -->")
(:div :class "extra-top-3" "<!-- empty -->")
(:h1 (:span :class "action" "Viewing: ")
(:span :class "object" ,(humanize-name data-class-name)))
,@preslots
(:ul ,@body)
,@postslots
(:div :class "extra-bottom-1" "<!-- empty -->")
(:div :class "extra-bottom-2" "<!-- empty -->")
(:div :class "extra-bottom-3" "<!-- empty -->")))
|
0e9bbffe4a880a13a096ac09f917e5b0e7ae4ea46a24475affe1ff8d6f10bd0d | herbelin/coq-hh | redexpr.mli | (************************************************************************)
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 *)
(************************************************************************)
open Names
open Term
open Closure
open Pattern
open Rawterm
open Reductionops
open Termops
type red_expr =
(constr, evaluable_global_reference, constr_pattern) red_expr_gen
val out_with_occurrences : 'a with_occurrences -> occurrences * 'a
val reduction_of_red_expr : red_expr -> reduction_function * cast_kind
(** [true] if we should use the vm to verify the reduction *)
* Adding a custom reduction ( function to be use at the ML level )
NB : the effect is permanent .
NB: the effect is permanent. *)
val declare_reduction : string -> reduction_function -> unit
* Adding a custom reduction ( function to be called a vernac command ) .
The boolean flag is the locality .
The boolean flag is the locality. *)
val declare_red_expr : bool -> string -> red_expr -> unit
(** Opaque and Transparent commands. *)
(** Sets the expansion strategy of a constant. When the boolean is
true, the effect is non-synchronous (i.e. it does not survive
section and module closure). *)
val set_strategy :
bool -> (Conv_oracle.level * evaluable_global_reference list) list -> unit
(** call by value normalisation function using the virtual machine *)
val cbv_vm : reduction_function
| null | https://raw.githubusercontent.com/herbelin/coq-hh/296d03d5049fea661e8bdbaf305ed4bf6d2001d2/proofs/redexpr.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
* [true] if we should use the vm to verify the reduction
* Opaque and Transparent commands.
* Sets the expansion strategy of a constant. When the boolean is
true, the effect is non-synchronous (i.e. it does not survive
section and module closure).
* call by value normalisation function using the virtual machine | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Names
open Term
open Closure
open Pattern
open Rawterm
open Reductionops
open Termops
type red_expr =
(constr, evaluable_global_reference, constr_pattern) red_expr_gen
val out_with_occurrences : 'a with_occurrences -> occurrences * 'a
val reduction_of_red_expr : red_expr -> reduction_function * cast_kind
* Adding a custom reduction ( function to be use at the ML level )
NB : the effect is permanent .
NB: the effect is permanent. *)
val declare_reduction : string -> reduction_function -> unit
* Adding a custom reduction ( function to be called a vernac command ) .
The boolean flag is the locality .
The boolean flag is the locality. *)
val declare_red_expr : bool -> string -> red_expr -> unit
val set_strategy :
bool -> (Conv_oracle.level * evaluable_global_reference list) list -> unit
val cbv_vm : reduction_function
|
5e7606cfeeb77ebedd4e3a213e21f93bb36ac50f4838da3f982758f0ce372fa0 | myuon/claire | Parser.hs | module Claire.Parser
( module Claire.Syntax
, pLaire
, pDecl
, pCommand
, pFormula
, pTerm
) where
import Claire.Syntax
import Claire.Parser.Lexer
import Claire.Parser.Parser
pLaire :: String -> Laire
pLaire = laireparser . alexScanTokens
pDecl :: String -> Decl
pDecl = declparser . alexScanTokens
pCommand :: String -> Command
pCommand = comparser . alexScanTokens
pFormula :: String -> Formula
pFormula = folparser . alexScanTokens
pTerm :: String -> Term
pTerm = termparser . alexScanTokens
| null | https://raw.githubusercontent.com/myuon/claire/e14268ced1bbab2f099a93feb0f2a129cf8b6a8b/src/Claire/Parser.hs | haskell | module Claire.Parser
( module Claire.Syntax
, pLaire
, pDecl
, pCommand
, pFormula
, pTerm
) where
import Claire.Syntax
import Claire.Parser.Lexer
import Claire.Parser.Parser
pLaire :: String -> Laire
pLaire = laireparser . alexScanTokens
pDecl :: String -> Decl
pDecl = declparser . alexScanTokens
pCommand :: String -> Command
pCommand = comparser . alexScanTokens
pFormula :: String -> Formula
pFormula = folparser . alexScanTokens
pTerm :: String -> Term
pTerm = termparser . alexScanTokens
| |
5a25a35c4a5772a5f5f2b462e82508a574e41b47fd2354cbe0b81e477c457020 | Happstack/happstack-server | Auth.hs | # LANGUAGE FlexibleContexts #
-- | Support for basic access authentication <>
module Happstack.Server.Auth where
import Data.Foldable (foldl')
import Data.Bits (xor, (.|.))
import Data.Maybe (fromMaybe)
import Control.Monad (MonadPlus(mzero, mplus))
import Data.ByteString.Base64 as Base64
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as B
import qualified Data.Map as M
import Happstack.Server.Monads (Happstack, escape, getHeaderM, setHeaderM)
import Happstack.Server.Response (unauthorized, toResponse)
-- | A simple HTTP basic authentication guard.
--
-- If authentication fails, this part will call 'mzero'.
--
-- example:
--
-- > main = simpleHTTP nullConf $
> msum [ basicAuth " 127.0.0.1 " ( fromList [ ( " happstack","rocks " ) ] ) $ ok " You are in the secret club "
-- > , ok "You are not in the secret club."
-- > ]
--
basicAuth :: (Happstack m) =>
String -- ^ the realm name
-> M.Map String String -- ^ the username password map
-> m a -- ^ the part to guard
-> m a
basicAuth realmName authMap = basicAuthBy (validLoginPlaintext authMap) realmName
-- | Generalized version of 'basicAuth'.
--
-- The function that checks the username password combination must be
supplied as first argument .
--
-- example:
--
-- > main = simpleHTTP nullConf $
> msum [ basicAuth ' ( validLoginPlaintext ( fromList [ ( " happstack","rocks " ) ] ) ) " 127.0.0.1 " $ ok " You are in the secret club "
-- > , ok "You are not in the secret club."
-- > ]
--
basicAuthBy :: (Happstack m) =>
(B.ByteString -> B.ByteString -> Bool) -- ^ function that returns true if the name password combination is valid
-> String -- ^ the realm name
-> m a -- ^ the part to guard
-> m a
basicAuthBy validLogin realmName xs = basicAuthImpl `mplus` xs
where
basicAuthImpl = do
aHeader <- getHeaderM "authorization"
case aHeader of
Nothing -> err
Just x ->
do (name, password) <- parseHeader x
if B.length password > 0
&& B.head password == ':'
&& validLogin name (B.tail password)
then mzero
else err
parseHeader h =
case Base64.decode . B.drop 6 $ h of
(Left _) -> err
(Right bs) -> return (B.break (':'==) bs)
headerName = "WWW-Authenticate"
headerValue = "Basic realm=\"" ++ realmName ++ "\""
err :: (Happstack m) => m a
err = escape $ do
setHeaderM headerName headerValue
unauthorized $ toResponse "Not authorized"
-- | Function that looks up the plain text password for username in a
-- Map and returns True if it matches with the given password.
--
-- Note: The implementation is hardened against timing attacks but not
-- completely safe. Ideally you should build your own predicate, using
-- a robust constant-time equality comparison from a cryptographic
-- library like sodium.
validLoginPlaintext ::
M.Map String String -- ^ the username password map
-> B.ByteString -- ^ the username
-> B.ByteString -- ^ the password
-> Bool
validLoginPlaintext authMap name password = fromMaybe False $ do
r <- M.lookup (B.unpack name) authMap
pure (constTimeEq (B.pack r) password)
where
-- (Mostly) constant time equality of bytestrings to prevent timing attacks by testing out passwords. This still
-- allows to extract the length of the configured password via timing attacks. This implementation is still brittle
in the sense that it relies on GHC not unrolling or vectorizing the loop .
# NOINLINE constTimeEq #
constTimeEq :: BS.ByteString -> BS.ByteString -> Bool
constTimeEq x y
| BS.length x /= BS.length y
= False
| otherwise
= foldl' (.|.) 0 (BS.zipWith xor x y) == 0
| null | https://raw.githubusercontent.com/Happstack/happstack-server/e5a5b12a8c0b0bd57f9501d6d5bf33baaa2740d6/src/Happstack/Server/Auth.hs | haskell | | Support for basic access authentication <>
| A simple HTTP basic authentication guard.
If authentication fails, this part will call 'mzero'.
example:
> main = simpleHTTP nullConf $
> , ok "You are not in the secret club."
> ]
^ the realm name
^ the username password map
^ the part to guard
| Generalized version of 'basicAuth'.
The function that checks the username password combination must be
example:
> main = simpleHTTP nullConf $
> , ok "You are not in the secret club."
> ]
^ function that returns true if the name password combination is valid
^ the realm name
^ the part to guard
| Function that looks up the plain text password for username in a
Map and returns True if it matches with the given password.
Note: The implementation is hardened against timing attacks but not
completely safe. Ideally you should build your own predicate, using
a robust constant-time equality comparison from a cryptographic
library like sodium.
^ the username password map
^ the username
^ the password
(Mostly) constant time equality of bytestrings to prevent timing attacks by testing out passwords. This still
allows to extract the length of the configured password via timing attacks. This implementation is still brittle | # LANGUAGE FlexibleContexts #
module Happstack.Server.Auth where
import Data.Foldable (foldl')
import Data.Bits (xor, (.|.))
import Data.Maybe (fromMaybe)
import Control.Monad (MonadPlus(mzero, mplus))
import Data.ByteString.Base64 as Base64
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as B
import qualified Data.Map as M
import Happstack.Server.Monads (Happstack, escape, getHeaderM, setHeaderM)
import Happstack.Server.Response (unauthorized, toResponse)
> msum [ basicAuth " 127.0.0.1 " ( fromList [ ( " happstack","rocks " ) ] ) $ ok " You are in the secret club "
basicAuth :: (Happstack m) =>
-> m a
basicAuth realmName authMap = basicAuthBy (validLoginPlaintext authMap) realmName
supplied as first argument .
> msum [ basicAuth ' ( validLoginPlaintext ( fromList [ ( " happstack","rocks " ) ] ) ) " 127.0.0.1 " $ ok " You are in the secret club "
basicAuthBy :: (Happstack m) =>
-> m a
basicAuthBy validLogin realmName xs = basicAuthImpl `mplus` xs
where
basicAuthImpl = do
aHeader <- getHeaderM "authorization"
case aHeader of
Nothing -> err
Just x ->
do (name, password) <- parseHeader x
if B.length password > 0
&& B.head password == ':'
&& validLogin name (B.tail password)
then mzero
else err
parseHeader h =
case Base64.decode . B.drop 6 $ h of
(Left _) -> err
(Right bs) -> return (B.break (':'==) bs)
headerName = "WWW-Authenticate"
headerValue = "Basic realm=\"" ++ realmName ++ "\""
err :: (Happstack m) => m a
err = escape $ do
setHeaderM headerName headerValue
unauthorized $ toResponse "Not authorized"
validLoginPlaintext ::
-> Bool
validLoginPlaintext authMap name password = fromMaybe False $ do
r <- M.lookup (B.unpack name) authMap
pure (constTimeEq (B.pack r) password)
where
in the sense that it relies on GHC not unrolling or vectorizing the loop .
# NOINLINE constTimeEq #
constTimeEq :: BS.ByteString -> BS.ByteString -> Bool
constTimeEq x y
| BS.length x /= BS.length y
= False
| otherwise
= foldl' (.|.) 0 (BS.zipWith xor x y) == 0
|
7e079623a6d5321deacff1d65410049c891c5bd590ce7d6dc1acba0381c499e3 | issuu/ocaml-protoc-plugin | protocol_test.ml | open Protocol
let%test "Last value kept" =
let messages = List.init 8 (fun i -> i) in
let oneof_messages = [] in
let t = Protocol.Old.{ messages; oneof_i = "Oneof_test"; oneof_j = 13; oneof_messages } in
let expect = Protocol.New.{ message = Some 7; oneof = `Oneof_j 13 } in
let writer = Protocol.Old.to_proto t in
let reader = Ocaml_protoc_plugin.Writer.contents writer |> Ocaml_protoc_plugin.Reader.create in
match Protocol.New.from_proto reader with
| Ok t ->
Protocol.New.equal t expect
| Error _ -> false
let%test "Last value kept - 2" =
let messages = List.init 8 (fun i -> i) in
let oneof_messages = [] in
let t = Protocol.Old.{ messages; oneof_i = "Oneof_test"; oneof_j = 13; oneof_messages } in
let expect = Protocol.New.{ message = Some 7; oneof = `Oneof_j 13 } in
let writer = Protocol.Old.to_proto t in
let reader = Ocaml_protoc_plugin.Writer.contents writer ^ Ocaml_protoc_plugin.Writer.contents writer |> Ocaml_protoc_plugin.Reader.create in
match Protocol.New.from_proto reader with
| Ok t ->
Protocol.New.equal t expect
| Error _ -> false
let%test "Repeated fields kept as it should" =
let is1 = List.init 8 (fun i -> i + 6) in
let is2 = List.init 8 (fun i -> i + 17) in
let t1 = is1 in
let t2 = is2 in
let expect = is1 @ is2 in
let writer1 = Protocol.List.to_proto t1 in
let writer2 = Protocol.List.to_proto t2 in
let reader = Ocaml_protoc_plugin.Writer.contents writer1 ^ Ocaml_protoc_plugin.Writer.contents writer2 |> Ocaml_protoc_plugin.Reader.create in
match Protocol.List.from_proto reader with
| Ok t ->
Protocol.List.equal t expect
| Error _ ->
false
| null | https://raw.githubusercontent.com/issuu/ocaml-protoc-plugin/3d8b3eeb48e2a58dc80fbfdf9d749e69676625ab/test/protocol_test.ml | ocaml | open Protocol
let%test "Last value kept" =
let messages = List.init 8 (fun i -> i) in
let oneof_messages = [] in
let t = Protocol.Old.{ messages; oneof_i = "Oneof_test"; oneof_j = 13; oneof_messages } in
let expect = Protocol.New.{ message = Some 7; oneof = `Oneof_j 13 } in
let writer = Protocol.Old.to_proto t in
let reader = Ocaml_protoc_plugin.Writer.contents writer |> Ocaml_protoc_plugin.Reader.create in
match Protocol.New.from_proto reader with
| Ok t ->
Protocol.New.equal t expect
| Error _ -> false
let%test "Last value kept - 2" =
let messages = List.init 8 (fun i -> i) in
let oneof_messages = [] in
let t = Protocol.Old.{ messages; oneof_i = "Oneof_test"; oneof_j = 13; oneof_messages } in
let expect = Protocol.New.{ message = Some 7; oneof = `Oneof_j 13 } in
let writer = Protocol.Old.to_proto t in
let reader = Ocaml_protoc_plugin.Writer.contents writer ^ Ocaml_protoc_plugin.Writer.contents writer |> Ocaml_protoc_plugin.Reader.create in
match Protocol.New.from_proto reader with
| Ok t ->
Protocol.New.equal t expect
| Error _ -> false
let%test "Repeated fields kept as it should" =
let is1 = List.init 8 (fun i -> i + 6) in
let is2 = List.init 8 (fun i -> i + 17) in
let t1 = is1 in
let t2 = is2 in
let expect = is1 @ is2 in
let writer1 = Protocol.List.to_proto t1 in
let writer2 = Protocol.List.to_proto t2 in
let reader = Ocaml_protoc_plugin.Writer.contents writer1 ^ Ocaml_protoc_plugin.Writer.contents writer2 |> Ocaml_protoc_plugin.Reader.create in
match Protocol.List.from_proto reader with
| Ok t ->
Protocol.List.equal t expect
| Error _ ->
false
| |
22c11626655fc7f3edbbc46a8856640f2f909a4fbf0c03b75b48eacbdb1e7256 | dharrigan/startrek | dev.clj | (ns dev
{:author "David Harrigan"}
(:require
[clojure.tools.logging :as log]
[donut.system :as ds]
[donut.system.repl :as donut]
[donut.system.repl.state :as state]
[startrek.system]) ;; required in order to load in the defmulti's that define the donut `named-system`'s.
(:import
[clojure.lang ExceptionInfo]))
(set! *warn-on-reflection* true)
(def ^:private environment (atom nil))
(defmethod ds/named-system ::ds/repl
[_]
(ds/system @environment))
(defn go
([] (go :local))
([env]
(reset! environment env)
(try
(donut/start)
:ready-to-rock-and-roll
(catch ExceptionInfo e
(log/error (ex-data e))
:bye-bye))))
(defn stop
[]
(donut/stop)
:bye-bye)
(defn reset
[]
(donut/restart))
(defn app-config
[]
(:app-config (::ds/instances state/system)))
(defn runtime-config
[]
(:env (::ds/instances state/system)))
| null | https://raw.githubusercontent.com/dharrigan/startrek/a91caa3f504ffea502b79cfd29d0499574aaced6/dev/src/dev.clj | clojure | required in order to load in the defmulti's that define the donut `named-system`'s. | (ns dev
{:author "David Harrigan"}
(:require
[clojure.tools.logging :as log]
[donut.system :as ds]
[donut.system.repl :as donut]
[donut.system.repl.state :as state]
(:import
[clojure.lang ExceptionInfo]))
(set! *warn-on-reflection* true)
(def ^:private environment (atom nil))
(defmethod ds/named-system ::ds/repl
[_]
(ds/system @environment))
(defn go
([] (go :local))
([env]
(reset! environment env)
(try
(donut/start)
:ready-to-rock-and-roll
(catch ExceptionInfo e
(log/error (ex-data e))
:bye-bye))))
(defn stop
[]
(donut/stop)
:bye-bye)
(defn reset
[]
(donut/restart))
(defn app-config
[]
(:app-config (::ds/instances state/system)))
(defn runtime-config
[]
(:env (::ds/instances state/system)))
|
dde840022a0ba1928996724d76d91fd5fbda20543357f1e1950036fc530f03d3 | bobzhang/fan | ginsert.ml |
(* open Util *)
open Format
let higher (s1 : Gdefs.symbol) (s2 : Gdefs.symbol) =
match (s1, s2) with
| Token (({descr ={word = A _ ; _ }}):Tokenf.pattern) ,
Token ({descr = {word = Any ; _ }} : Tokenf.pattern) -> false
| Token _ , _ -> true
| _ -> false
let rec derive_eps (s:Gdefs.symbol) =
match s with
| List0 _ | List0sep (_, _)| Peek _ -> true
| Try s -> derive_eps s (* it would consume if succeed *)
| List1 _ | List1sep (_, _) | Token _ ->
(* For sure we cannot derive epsilon from these *)
false
| Nterm _ | Snterml (_, _) | Self -> (* Approximation *)
false (* could be fixed *)
let empty_lev l lassoc : Gdefs.level =
{lassoc ;
level = Option.default 10 l ;
lsuffix = DeadEnd;
lprefix = DeadEnd;productions=[]}
(* let rec check_gram (entry : Gdefs.entry) (x:Gdefs.symbol) = *)
(* match x with *)
(* | Nterm e -> *)
(* (\* if entry.gram != e.gram then *\) *)
(* (\* failwithf "Fgram.extend: entries %S and %S do not belong to the same grammar.@." *\) *)
(* (\* entry.name e.name *\) *)
(* | Snterml (e, _) -> *)
(* (\* if e.gram != entry.gram then *\) *)
(* (\* failwithf *\) *)
(* (\* "Fgram.extend Error: entries %S and %S do not belong to the same grammar.@." *\) *)
(* (\* entry.name e.name *\) *)
(* | List0sep (s, t) -> begin check_gram entry t; check_gram entry s end *)
(* | List1sep (s, t) -> begin check_gram entry t; check_gram entry s end *)
| List0 s | List1 s | Try s | check_gram entry s
(* | Self | Token _ -> () *)
(* and tree_check_gram entry (x:Gdefs.tree) = *)
(* match x with *)
(* | Node {node ; brother; son } -> begin *)
(* check_gram entry node; *)
(* tree_check_gram entry brother; *)
(* tree_check_gram entry son *)
(* end *)
| LocAct _ | - > ( )
let get_initial = function
| (Self:Gdefs.symbol) :: symbols -> (true, symbols)
| symbols -> (false, symbols)
let rec using_symbols symbols acc =
List.fold_left (fun acc symbol -> using_symbol symbol acc) acc symbols
and using_symbol (symbol:Gdefs.symbol) acc =
match symbol with
| List0 s | List1 s | Try s | Peek s ->
using_symbol s acc
| List0sep (s, t) -> using_symbol t (using_symbol s acc)
| List1sep (s, t) -> using_symbol t (using_symbol s acc)
| Token ({descr = {tag = `Key; word = A kwd;_}} : Tokenf.pattern)
-> kwd :: acc
| Nterm _ | Snterml _ | Self | Token _ -> acc
and using_node node acc =
match (node:Gdefs.tree) with
| Node {node = s; brother = bro; son = son} ->
using_node son (using_node bro (using_symbol s acc))
| LocAct _ | DeadEnd -> acc
let add_production ({symbols = gsymbols; annot; fn = action}:Gdefs.production) tree =
let (anno_action : Gdefs.anno_action) =
{arity = List.length gsymbols; symbols = gsymbols;
annot= annot; fn = action} in
let rec try_insert s sl (tree:Gdefs.tree) : Gdefs.tree option =
match tree with
| Node ( {node ; son ; brother} as x) ->
if Gtools.eq_symbol s node then
Some (Node { x with son = insert sl son})
else
(match try_insert s sl brother with
| Some y -> Some (Node {x with brother=y})
| None ->
if higher node s || (derive_eps s && not (derive_eps node)) then
(* node has higher priority *)
Some (Node {x with brother = Node {(x) with node = s; son = insert sl DeadEnd}})
else None )
| LocAct _ | DeadEnd -> None
and insert_in_tree s sl tree =
match try_insert s sl tree with
| Some t -> t
| None -> Node {node = s; son = insert sl DeadEnd; brother = tree}
and insert symbols tree =
match symbols with
| s :: sl -> insert_in_tree s sl tree
| [] ->
match tree with
| Node ({ brother;_} as x) ->
Node {x with brother = insert [] brother }
| LocAct _ ->
(if !(Configf.gram_warning_verbose) then
(* the old action is discarded, and can not be recovered anymore *)
eprintf
"<W> Grammar extension: in @[%a@] some rule has been masked@."
Gprint.dump#rule symbols;
LocAct anno_action)
| DeadEnd -> LocAct anno_action in
insert gsymbols tree
let add_production_in_level (x : Gdefs.production) (slev : Gdefs.level) =
let (suffix,symbols1) = get_initial x.symbols in
if suffix then
{slev with
lsuffix = add_production {x with symbols = symbols1} slev.lsuffix;
productions = x::slev.productions }
else
{slev with
lprefix = add_production {x with symbols = symbols1} slev.lprefix;
productions = x::slev.productions }
let merge_level (la:Gdefs.level) (lb: Gdefs.olevel) =
let rules1 =
let y = Option.default 10 lb.label in
(if not ( la.level = y && la.lassoc = lb.lassoc) then
eprintf "<W> Grammar level merging: merge_level does not agree (%d:%d) (%a:%a)@."
la.level y
Gprint.pp_assoc la.lassoc Gprint.pp_assoc lb.lassoc;
lb.productions) in
(* added in reverse order *)
List.fold_right add_production_in_level rules1 la
let level_of_olevel (lb:Gdefs.olevel) =
let la = empty_lev lb.label lb.lassoc in
merge_level la lb
let insert_olevel (entry:Gdefs.entry) position olevel =
let elev = entry.levels in
let pos = Option.default 10 position in
let rec aux (ls:Gdefs.level list) =
match ls with
| [] -> [level_of_olevel olevel]
| x::xs ->
if x.level > pos then
level_of_olevel olevel :: ls
else if x.level = pos then
merge_level x olevel :: xs
else
x:: aux xs in
aux elev
(* let insert_olevels_in_levels (entry:Gdefs.entry) position olevels = *)
(* This function will be executed in the runtime
normalize nonterminals to [Self] if possible
*)
let rec scan_olevels entry (levels: Gdefs.olevel list ) =
List.map (scan_olevel entry) levels
and scan_olevel entry (lb:Gdefs.olevel) =
{lb with productions = List.map (scan_product entry) lb.productions}
and scan_product (entry:Gdefs.entry) ({symbols;_} as x : Gdefs.production) : Gdefs.production =
{x with symbols =
(List.map
(fun (symbol:Gdefs.symbol) ->
(* let keywords = using_symbol symbol [] in *)
(* let diff = *)
@@
( Setf . String.of_list keywords ) entry.gram.gfilter.kwds
(* in *)
(* let () = *)
(* if diff <> [] then *)
(* failwithf *)
(* "in grammar %s: keywords introduced: [ %s ] " entry.gram.annot *)
(* @@ Listf.reduce_left (^) diff in *)
(* let () = check_gram entry symbol in *)
match symbol with
|Nterm e when e == entry -> (Self:Gdefs.symbol) (* necessary?*)
| _ -> symbol
) symbols)}
let rec unsafe_scan_olevels entry (levels: Gdefs.olevel list ) =
List.map (unsafe_scan_olevel entry) levels
and unsafe_scan_olevel entry (lb:Gdefs.olevel) =
{lb with productions = List.map (unsafe_scan_product entry) lb.productions}
and unsafe_scan_product (entry:Gdefs.entry) ({symbols;_} as x : Gdefs.production)
: Gdefs.production =
{x with symbols =
(List.map
(fun (symbol: Gdefs.symbol) ->
(* let keywords = using_symbol symbol [] in *)
(* let () = entry.gram.gfilter.kwds <- *)
Setf . String.add_list entry.gram.gfilter.kwds keywords in
(* let () = check_gram entry symbol in *)
match symbol with
|Nterm e when e == entry -> (Self:Gdefs.symbol)
| _ -> symbol) symbols)}
(**
*)
(* buggy, it's very hard to inline recursive parsers, take care
with Self, and implicit Self
*)
(* let eoi_entry e = *)
(* let eoi_level l = *)
(* (\* FIXME: the annot seems to be inconsistent now *\) *)
(* let aux (prods:Gdefs.production list) = *)
List.map
(* (fun (symbs,(annot,act)) -> *)
(* let symbs = *)
List.map
(* (function *)
(* | Self -> Nterm e *)
(* | x -> x) symbs in *)
(* (symbs @ *)
(* [Token *)
(* ({pred = (function | `EOI _ -> true | _ -> false); *)
descr =
(* {tag = `EOI;word= Any;tag_name="EOI"}}:Tokenf.pattern)], *)
( annot , Gaction.mk ( fun _ - > act ) ) ) ) prods in
(* refresh_level ~f:aux l in *)
(* let result = *)
(* {e with *)
(* start = (fun _ -> assert false) ; *)
(* continue = fun _ -> assert false;} in *)
(* (result.levels <- List.map eoi_level result.levels ; *)
result.start < - Gparser.start_parser_of_entry result ;
(* result.continue <- Gparser.continue_parser_of_entry result; *)
(* result) *)
(**
{:extend|g:[g{x};`EOI -> x]|}
*)
(* let eoi (e:entry) : entry = *)
(* {:extend| a: [b ; `EOI ]|} *)
(* local variables: *)
(* compile-command: "pmake ginsert.cmo" *)
(* end: *)
| null | https://raw.githubusercontent.com/bobzhang/fan/7ed527d96c5a006da43d3813f32ad8a5baa31b7f/src/treeparser/ginsert.ml | ocaml | open Util
it would consume if succeed
For sure we cannot derive epsilon from these
Approximation
could be fixed
let rec check_gram (entry : Gdefs.entry) (x:Gdefs.symbol) =
match x with
| Nterm e ->
(\* if entry.gram != e.gram then *\)
(\* failwithf "Fgram.extend: entries %S and %S do not belong to the same grammar.@." *\)
(\* entry.name e.name *\)
| Snterml (e, _) ->
(\* if e.gram != entry.gram then *\)
(\* failwithf *\)
(\* "Fgram.extend Error: entries %S and %S do not belong to the same grammar.@." *\)
(\* entry.name e.name *\)
| List0sep (s, t) -> begin check_gram entry t; check_gram entry s end
| List1sep (s, t) -> begin check_gram entry t; check_gram entry s end
| Self | Token _ -> ()
and tree_check_gram entry (x:Gdefs.tree) =
match x with
| Node {node ; brother; son } -> begin
check_gram entry node;
tree_check_gram entry brother;
tree_check_gram entry son
end
node has higher priority
the old action is discarded, and can not be recovered anymore
added in reverse order
let insert_olevels_in_levels (entry:Gdefs.entry) position olevels =
This function will be executed in the runtime
normalize nonterminals to [Self] if possible
let keywords = using_symbol symbol [] in
let diff =
in
let () =
if diff <> [] then
failwithf
"in grammar %s: keywords introduced: [ %s ] " entry.gram.annot
@@ Listf.reduce_left (^) diff in
let () = check_gram entry symbol in
necessary?
let keywords = using_symbol symbol [] in
let () = entry.gram.gfilter.kwds <-
let () = check_gram entry symbol in
*
buggy, it's very hard to inline recursive parsers, take care
with Self, and implicit Self
let eoi_entry e =
let eoi_level l =
(\* FIXME: the annot seems to be inconsistent now *\)
let aux (prods:Gdefs.production list) =
(fun (symbs,(annot,act)) ->
let symbs =
(function
| Self -> Nterm e
| x -> x) symbs in
(symbs @
[Token
({pred = (function | `EOI _ -> true | _ -> false);
{tag = `EOI;word= Any;tag_name="EOI"}}:Tokenf.pattern)],
refresh_level ~f:aux l in
let result =
{e with
start = (fun _ -> assert false) ;
continue = fun _ -> assert false;} in
(result.levels <- List.map eoi_level result.levels ;
result.continue <- Gparser.continue_parser_of_entry result;
result)
*
{:extend|g:[g{x};`EOI -> x]|}
let eoi (e:entry) : entry =
{:extend| a: [b ; `EOI ]|}
local variables:
compile-command: "pmake ginsert.cmo"
end: |
open Format
let higher (s1 : Gdefs.symbol) (s2 : Gdefs.symbol) =
match (s1, s2) with
| Token (({descr ={word = A _ ; _ }}):Tokenf.pattern) ,
Token ({descr = {word = Any ; _ }} : Tokenf.pattern) -> false
| Token _ , _ -> true
| _ -> false
let rec derive_eps (s:Gdefs.symbol) =
match s with
| List0 _ | List0sep (_, _)| Peek _ -> true
| List1 _ | List1sep (_, _) | Token _ ->
false
let empty_lev l lassoc : Gdefs.level =
{lassoc ;
level = Option.default 10 l ;
lsuffix = DeadEnd;
lprefix = DeadEnd;productions=[]}
| List0 s | List1 s | Try s | check_gram entry s
| LocAct _ | - > ( )
let get_initial = function
| (Self:Gdefs.symbol) :: symbols -> (true, symbols)
| symbols -> (false, symbols)
let rec using_symbols symbols acc =
List.fold_left (fun acc symbol -> using_symbol symbol acc) acc symbols
and using_symbol (symbol:Gdefs.symbol) acc =
match symbol with
| List0 s | List1 s | Try s | Peek s ->
using_symbol s acc
| List0sep (s, t) -> using_symbol t (using_symbol s acc)
| List1sep (s, t) -> using_symbol t (using_symbol s acc)
| Token ({descr = {tag = `Key; word = A kwd;_}} : Tokenf.pattern)
-> kwd :: acc
| Nterm _ | Snterml _ | Self | Token _ -> acc
and using_node node acc =
match (node:Gdefs.tree) with
| Node {node = s; brother = bro; son = son} ->
using_node son (using_node bro (using_symbol s acc))
| LocAct _ | DeadEnd -> acc
let add_production ({symbols = gsymbols; annot; fn = action}:Gdefs.production) tree =
let (anno_action : Gdefs.anno_action) =
{arity = List.length gsymbols; symbols = gsymbols;
annot= annot; fn = action} in
let rec try_insert s sl (tree:Gdefs.tree) : Gdefs.tree option =
match tree with
| Node ( {node ; son ; brother} as x) ->
if Gtools.eq_symbol s node then
Some (Node { x with son = insert sl son})
else
(match try_insert s sl brother with
| Some y -> Some (Node {x with brother=y})
| None ->
if higher node s || (derive_eps s && not (derive_eps node)) then
Some (Node {x with brother = Node {(x) with node = s; son = insert sl DeadEnd}})
else None )
| LocAct _ | DeadEnd -> None
and insert_in_tree s sl tree =
match try_insert s sl tree with
| Some t -> t
| None -> Node {node = s; son = insert sl DeadEnd; brother = tree}
and insert symbols tree =
match symbols with
| s :: sl -> insert_in_tree s sl tree
| [] ->
match tree with
| Node ({ brother;_} as x) ->
Node {x with brother = insert [] brother }
| LocAct _ ->
(if !(Configf.gram_warning_verbose) then
eprintf
"<W> Grammar extension: in @[%a@] some rule has been masked@."
Gprint.dump#rule symbols;
LocAct anno_action)
| DeadEnd -> LocAct anno_action in
insert gsymbols tree
let add_production_in_level (x : Gdefs.production) (slev : Gdefs.level) =
let (suffix,symbols1) = get_initial x.symbols in
if suffix then
{slev with
lsuffix = add_production {x with symbols = symbols1} slev.lsuffix;
productions = x::slev.productions }
else
{slev with
lprefix = add_production {x with symbols = symbols1} slev.lprefix;
productions = x::slev.productions }
let merge_level (la:Gdefs.level) (lb: Gdefs.olevel) =
let rules1 =
let y = Option.default 10 lb.label in
(if not ( la.level = y && la.lassoc = lb.lassoc) then
eprintf "<W> Grammar level merging: merge_level does not agree (%d:%d) (%a:%a)@."
la.level y
Gprint.pp_assoc la.lassoc Gprint.pp_assoc lb.lassoc;
lb.productions) in
List.fold_right add_production_in_level rules1 la
let level_of_olevel (lb:Gdefs.olevel) =
let la = empty_lev lb.label lb.lassoc in
merge_level la lb
let insert_olevel (entry:Gdefs.entry) position olevel =
let elev = entry.levels in
let pos = Option.default 10 position in
let rec aux (ls:Gdefs.level list) =
match ls with
| [] -> [level_of_olevel olevel]
| x::xs ->
if x.level > pos then
level_of_olevel olevel :: ls
else if x.level = pos then
merge_level x olevel :: xs
else
x:: aux xs in
aux elev
let rec scan_olevels entry (levels: Gdefs.olevel list ) =
List.map (scan_olevel entry) levels
and scan_olevel entry (lb:Gdefs.olevel) =
{lb with productions = List.map (scan_product entry) lb.productions}
and scan_product (entry:Gdefs.entry) ({symbols;_} as x : Gdefs.production) : Gdefs.production =
{x with symbols =
(List.map
(fun (symbol:Gdefs.symbol) ->
@@
( Setf . String.of_list keywords ) entry.gram.gfilter.kwds
match symbol with
| _ -> symbol
) symbols)}
let rec unsafe_scan_olevels entry (levels: Gdefs.olevel list ) =
List.map (unsafe_scan_olevel entry) levels
and unsafe_scan_olevel entry (lb:Gdefs.olevel) =
{lb with productions = List.map (unsafe_scan_product entry) lb.productions}
and unsafe_scan_product (entry:Gdefs.entry) ({symbols;_} as x : Gdefs.production)
: Gdefs.production =
{x with symbols =
(List.map
(fun (symbol: Gdefs.symbol) ->
Setf . String.add_list entry.gram.gfilter.kwds keywords in
match symbol with
|Nterm e when e == entry -> (Self:Gdefs.symbol)
| _ -> symbol) symbols)}
List.map
List.map
descr =
( annot , Gaction.mk ( fun _ - > act ) ) ) ) prods in
result.start < - Gparser.start_parser_of_entry result ;
|
5cb106b0d0fb74ff8e97a89487f9805289ce95419c5f6b40c864b04683adb8bd | liyang/thyme | Calendar.hs | # LANGUAGE CPP #
# LANGUAGE RecordWildCards #
# LANGUAGE ViewPatterns #
# OPTIONS_GHC -fno - warn - orphans #
#include "thyme.h"
#if HLINT
#include "cabal_macros.h"
#endif
-- | Calendar calculations.
--
Note that ' UTCTime ' is not Y294K - compliant , and ' Bounded ' instances for
-- the various calendar types reflect this fact. That said, the calendar
-- calculations by themselves work perfectly fine for a wider range of
-- dates, subject to the size of 'Int' for your platform.
module Data.Thyme.Calendar
(
-- * Day
Day (..), modifiedJulianDay
-- * Calendar
, Year, Month, DayOfMonth
, YearMonthDay (..), _ymdYear, _ymdMonth, _ymdDay
, Years, Months, Days
-- * Gregorian calendar
-- $proleptic
, isLeapYear
, yearMonthDay, gregorian, gregorianValid, showGregorian
, module Data.Thyme.Calendar
) where
import Prelude hiding ((.))
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
#endif
import Control.Arrow
import Control.Category
import Control.Lens
import Control.Monad
import Data.AdditiveGroup
import Data.AffineSpace
import Data.Thyme.Calendar.Internal
import Data.Thyme.Clock.Internal
import System.Random
import Test.QuickCheck
-- "Data.Thyme.Calendar.Internal" cannot import "Data.Thyme.Clock.Internal",
-- therefore these orphan 'Bounded' instances must live here.
instance Bounded Day where
minBound = minBound ^. _utctDay
maxBound = maxBound ^. _utctDay
instance Bounded YearMonthDay where
minBound = minBound ^. gregorian
maxBound = maxBound ^. gregorian
instance Random Day where
randomR r = first (^. _utctDay) . randomR (range r) where
upper bound is one Micro second before the next day
range = toMidnight *** pred . toMidnight . succ
toMidnight day = utcTime # UTCView day zeroV
random = randomR (minBound, maxBound)
instance Random YearMonthDay where
randomR = randomIsoR gregorian
random = first (^. gregorian) . random
instance Arbitrary Day where
arbitrary = ModifiedJulianDay
<$> choose (join (***) toModifiedJulianDay (minBound, maxBound))
shrink (ModifiedJulianDay mjd) = ModifiedJulianDay <$> shrink mjd
instance Arbitrary YearMonthDay where
arbitrary = view gregorian <$> arbitrary
shrink ymd = view gregorian <$> shrink (gregorian # ymd)
instance CoArbitrary YearMonthDay where
coarbitrary (YearMonthDay y m d)
= coarbitrary y . coarbitrary m . coarbitrary d
------------------------------------------------------------------------
-- $proleptic
--
-- Note that using the
-- < Gregorian> calendar for
dates before its adoption ( from 1582 onwards , but varies from one country
-- to the next) produces
< #Proleptic_Gregorian_calendar a proleptic calendar > ,
-- which may cause some confusion.
| The number of days in a given month in the
-- < Gregorian> calendar.
--
-- @
> ' gregorianMonthLength ' 2005 2
28
-- @
# INLINE gregorianMonthLength #
gregorianMonthLength :: Year -> Month -> Days
gregorianMonthLength = monthLength . isLeapYear
| Add months , with days past the last day of the month clipped to the
last day .
--
-- See also 'addGregorianMonthsClip'.
--
-- @
> ' gregorianMonthsClip ' 1 ' $ ' ' YearMonthDay ' 2005 1 30
' YearMonthDay ' { ' ymdYear ' = 2005 , ' ymdMonth ' = 2 , ' ymdDay ' = 28 }
-- @
# INLINEABLE gregorianMonthsClip #
gregorianMonthsClip :: Months -> YearMonthDay -> YearMonthDay
gregorianMonthsClip n (YearMonthDay y m d) = YearMonthDay y' m'
$ min (gregorianMonthLength y' m') d where
((+) y -> y', (+) 1 -> m') = divMod (m + n - 1) 12
| Add months , with days past the last day of the month rolling over to
the next month .
--
-- See also 'addGregorianMonthsRollover'.
--
-- @
> ' gregorianMonthsRollover ' 1 $ ' YearMonthDay ' 2005 1 30
' YearMonthDay ' { ' ymdYear ' = 2005 , ' ymdMonth ' = 3 , ' ymdDay ' = 2 }
-- @
{-# ANN gregorianMonthsRollover "HLint: ignore Use if" #-}
{-# INLINEABLE gregorianMonthsRollover #-}
gregorianMonthsRollover :: Months -> YearMonthDay -> YearMonthDay
gregorianMonthsRollover n (YearMonthDay y m d) = case d <= len of
True -> YearMonthDay y' m' d
False -> case m' < 12 of
True -> YearMonthDay y' (m' + 1) (d - len)
False -> YearMonthDay (y' + 1) 1 (d - len)
where
((+) y -> y', (+) 1 -> m') = divMod (m + n - 1) 12
len = gregorianMonthLength y' m'
| Add years , matching month and day , with /February 29th/ clipped to the
-- /28th/ if necessary.
--
-- See also 'addGregorianYearsClip'.
--
-- @
> ' gregorianYearsClip ' 2 $ ' YearMonthDay ' 2004 2 29
' YearMonthDay ' { ' ymdYear ' = 2006 , ' ymdMonth ' = 2 , ' ymdDay ' = 28 }
-- @
{-# INLINEABLE gregorianYearsClip #-}
gregorianYearsClip :: Years -> YearMonthDay -> YearMonthDay
gregorianYearsClip n (YearMonthDay ((+) n -> y') 2 29)
| not (isLeapYear y') = YearMonthDay y' 2 28
gregorianYearsClip n (YearMonthDay y m d) = YearMonthDay (y + n) m d
| Add years , matching month and day , with /February 29th/ rolled over to
-- /March 1st/ if necessary.
--
-- See also 'addGregorianYearsRollover'.
--
-- @
> ' gregorianYearsRollover ' 2 $ ' YearMonthDay ' 2004 2 29
' YearMonthDay ' { ' ymdYear ' = 2006 , ' ymdMonth ' = 3 , ' ymdDay ' = 1 }
-- @
{-# INLINEABLE gregorianYearsRollover #-}
gregorianYearsRollover :: Years -> YearMonthDay -> YearMonthDay
gregorianYearsRollover n (YearMonthDay ((+) n -> y') 2 29)
| not (isLeapYear y') = YearMonthDay y' 3 1
gregorianYearsRollover n (YearMonthDay y m d) = YearMonthDay (y + n) m d
-- * Compatibility
-- | Add some 'Days' to a calendar 'Day' to get a new 'Day'.
--
-- @
-- 'addDays' = 'flip' ('.+^')
-- 'addDays' n d ≡ d '.+^' n
-- @
--
See also the ' AffineSpace ' instance for ' Day ' .
# INLINE addDays #
addDays :: Days -> Day -> Day
addDays = flip (.+^)
| Subtract two calendar ' Day 's for the difference in ' Days ' .
--
-- @
-- 'diffDays' = ('.-.')
-- 'diffDays' a b = a '.-.' b
-- @
--
See also the ' AffineSpace ' instance for ' Day ' .
# INLINE diffDays #
diffDays :: Day -> Day -> Days
diffDays = (.-.)
| Convert a ' Day ' to its Gregorian ' Year ' , ' Month ' , and ' DayOfMonth ' .
--
-- @
' toGregorian ' ( ' view ' ' gregorian ' - > ' YearMonthDay ' y m d ) = ( y , m , d )
-- @
# INLINE toGregorian #
toGregorian :: Day -> (Year, Month, DayOfMonth)
toGregorian (view gregorian -> YearMonthDay y m d) = (y, m, d)
| Construct a ' Day ' from a Gregorian calendar date .
-- Does not validate the input.
--
-- @
' fromGregorian ' y m d = ' gregorian ' ' Control . Lens . # ' ' YearMonthDay ' y m d
-- @
{-# INLINE fromGregorian #-}
fromGregorian :: Year -> Month -> DayOfMonth -> Day
fromGregorian y m d = gregorian # YearMonthDay y m d
| Construct a ' Day ' from a Gregorian calendar date .
-- Returns 'Nothing' for invalid input.
--
-- @
' fromGregorianValid ' y m d = ' gregorianValid ' ( ' YearMonthDay ' y m d )
-- @
# INLINE fromGregorianValid #
fromGregorianValid :: Year -> Month -> DayOfMonth -> Maybe Day
fromGregorianValid y m d = gregorianValid (YearMonthDay y m d)
-- | Add some number of 'Months' to the given 'Day'; if the original
-- 'DayOfMonth' exceeds that of the new 'Month', it will be clipped to the
last day of the new ' Month ' .
--
-- @
-- 'addGregorianMonthsClip' n = 'gregorian' '%~' 'gregorianMonthsClip' n
-- @
# INLINE addGregorianMonthsClip #
addGregorianMonthsClip :: Months -> Day -> Day
addGregorianMonthsClip n = gregorian %~ gregorianMonthsClip n
-- | Add some number of 'Months' to the given 'Day'; if the original
-- 'DayOfMonth' exceeds that of the new 'Month', it will be rolled over into
-- the following 'Month'.
--
-- @
-- 'addGregorianMonthsRollover' n = 'gregorian' '%~' 'gregorianMonthsRollover' n
-- @
# INLINE addGregorianMonthsRollover #
addGregorianMonthsRollover :: Months -> Day -> Day
addGregorianMonthsRollover n = gregorian %~ gregorianMonthsRollover n
-- | Add some number of 'Years' to the given 'Day', with /February 29th/
-- clipped to /February 28th/ if necessary.
--
-- @
-- 'addGregorianYearsClip' n = 'gregorian' '%~' 'gregorianYearsClip' n
-- @
# INLINE addGregorianYearsClip #
addGregorianYearsClip :: Years -> Day -> Day
addGregorianYearsClip n = gregorian %~ gregorianYearsClip n
-- | Add some number of 'Years' to the given 'Day', with /February 29th/
-- rolled over to /March 1st/ if necessary.
--
-- @
-- 'addGregorianYearsRollover' n = 'gregorian' '%~' 'gregorianYearsRollover' n
-- @
# INLINE addGregorianYearsRollover #
addGregorianYearsRollover :: Years -> Day -> Day
addGregorianYearsRollover n = gregorian %~ gregorianYearsRollover n
| null | https://raw.githubusercontent.com/liyang/thyme/c0dcc251ff4f843672987c80b73ec4808bc009e4/src/Data/Thyme/Calendar.hs | haskell | | Calendar calculations.
the various calendar types reflect this fact. That said, the calendar
calculations by themselves work perfectly fine for a wider range of
dates, subject to the size of 'Int' for your platform.
* Day
* Calendar
* Gregorian calendar
$proleptic
"Data.Thyme.Calendar.Internal" cannot import "Data.Thyme.Clock.Internal",
therefore these orphan 'Bounded' instances must live here.
----------------------------------------------------------------------
$proleptic
Note that using the
< Gregorian> calendar for
to the next) produces
which may cause some confusion.
< Gregorian> calendar.
@
@
See also 'addGregorianMonthsClip'.
@
@
See also 'addGregorianMonthsRollover'.
@
@
# ANN gregorianMonthsRollover "HLint: ignore Use if" #
# INLINEABLE gregorianMonthsRollover #
/28th/ if necessary.
See also 'addGregorianYearsClip'.
@
@
# INLINEABLE gregorianYearsClip #
/March 1st/ if necessary.
See also 'addGregorianYearsRollover'.
@
@
# INLINEABLE gregorianYearsRollover #
* Compatibility
| Add some 'Days' to a calendar 'Day' to get a new 'Day'.
@
'addDays' = 'flip' ('.+^')
'addDays' n d ≡ d '.+^' n
@
@
'diffDays' = ('.-.')
'diffDays' a b = a '.-.' b
@
@
@
Does not validate the input.
@
@
# INLINE fromGregorian #
Returns 'Nothing' for invalid input.
@
@
| Add some number of 'Months' to the given 'Day'; if the original
'DayOfMonth' exceeds that of the new 'Month', it will be clipped to the
@
'addGregorianMonthsClip' n = 'gregorian' '%~' 'gregorianMonthsClip' n
@
| Add some number of 'Months' to the given 'Day'; if the original
'DayOfMonth' exceeds that of the new 'Month', it will be rolled over into
the following 'Month'.
@
'addGregorianMonthsRollover' n = 'gregorian' '%~' 'gregorianMonthsRollover' n
@
| Add some number of 'Years' to the given 'Day', with /February 29th/
clipped to /February 28th/ if necessary.
@
'addGregorianYearsClip' n = 'gregorian' '%~' 'gregorianYearsClip' n
@
| Add some number of 'Years' to the given 'Day', with /February 29th/
rolled over to /March 1st/ if necessary.
@
'addGregorianYearsRollover' n = 'gregorian' '%~' 'gregorianYearsRollover' n
@ | # LANGUAGE CPP #
# LANGUAGE RecordWildCards #
# LANGUAGE ViewPatterns #
# OPTIONS_GHC -fno - warn - orphans #
#include "thyme.h"
#if HLINT
#include "cabal_macros.h"
#endif
Note that ' UTCTime ' is not Y294K - compliant , and ' Bounded ' instances for
module Data.Thyme.Calendar
(
Day (..), modifiedJulianDay
, Year, Month, DayOfMonth
, YearMonthDay (..), _ymdYear, _ymdMonth, _ymdDay
, Years, Months, Days
, isLeapYear
, yearMonthDay, gregorian, gregorianValid, showGregorian
, module Data.Thyme.Calendar
) where
import Prelude hiding ((.))
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
#endif
import Control.Arrow
import Control.Category
import Control.Lens
import Control.Monad
import Data.AdditiveGroup
import Data.AffineSpace
import Data.Thyme.Calendar.Internal
import Data.Thyme.Clock.Internal
import System.Random
import Test.QuickCheck
instance Bounded Day where
minBound = minBound ^. _utctDay
maxBound = maxBound ^. _utctDay
instance Bounded YearMonthDay where
minBound = minBound ^. gregorian
maxBound = maxBound ^. gregorian
instance Random Day where
randomR r = first (^. _utctDay) . randomR (range r) where
upper bound is one Micro second before the next day
range = toMidnight *** pred . toMidnight . succ
toMidnight day = utcTime # UTCView day zeroV
random = randomR (minBound, maxBound)
instance Random YearMonthDay where
randomR = randomIsoR gregorian
random = first (^. gregorian) . random
instance Arbitrary Day where
arbitrary = ModifiedJulianDay
<$> choose (join (***) toModifiedJulianDay (minBound, maxBound))
shrink (ModifiedJulianDay mjd) = ModifiedJulianDay <$> shrink mjd
instance Arbitrary YearMonthDay where
arbitrary = view gregorian <$> arbitrary
shrink ymd = view gregorian <$> shrink (gregorian # ymd)
instance CoArbitrary YearMonthDay where
coarbitrary (YearMonthDay y m d)
= coarbitrary y . coarbitrary m . coarbitrary d
dates before its adoption ( from 1582 onwards , but varies from one country
< #Proleptic_Gregorian_calendar a proleptic calendar > ,
| The number of days in a given month in the
> ' gregorianMonthLength ' 2005 2
28
# INLINE gregorianMonthLength #
gregorianMonthLength :: Year -> Month -> Days
gregorianMonthLength = monthLength . isLeapYear
| Add months , with days past the last day of the month clipped to the
last day .
> ' gregorianMonthsClip ' 1 ' $ ' ' YearMonthDay ' 2005 1 30
' YearMonthDay ' { ' ymdYear ' = 2005 , ' ymdMonth ' = 2 , ' ymdDay ' = 28 }
# INLINEABLE gregorianMonthsClip #
gregorianMonthsClip :: Months -> YearMonthDay -> YearMonthDay
gregorianMonthsClip n (YearMonthDay y m d) = YearMonthDay y' m'
$ min (gregorianMonthLength y' m') d where
((+) y -> y', (+) 1 -> m') = divMod (m + n - 1) 12
| Add months , with days past the last day of the month rolling over to
the next month .
> ' gregorianMonthsRollover ' 1 $ ' YearMonthDay ' 2005 1 30
' YearMonthDay ' { ' ymdYear ' = 2005 , ' ymdMonth ' = 3 , ' ymdDay ' = 2 }
gregorianMonthsRollover :: Months -> YearMonthDay -> YearMonthDay
gregorianMonthsRollover n (YearMonthDay y m d) = case d <= len of
True -> YearMonthDay y' m' d
False -> case m' < 12 of
True -> YearMonthDay y' (m' + 1) (d - len)
False -> YearMonthDay (y' + 1) 1 (d - len)
where
((+) y -> y', (+) 1 -> m') = divMod (m + n - 1) 12
len = gregorianMonthLength y' m'
| Add years , matching month and day , with /February 29th/ clipped to the
> ' gregorianYearsClip ' 2 $ ' YearMonthDay ' 2004 2 29
' YearMonthDay ' { ' ymdYear ' = 2006 , ' ymdMonth ' = 2 , ' ymdDay ' = 28 }
gregorianYearsClip :: Years -> YearMonthDay -> YearMonthDay
gregorianYearsClip n (YearMonthDay ((+) n -> y') 2 29)
| not (isLeapYear y') = YearMonthDay y' 2 28
gregorianYearsClip n (YearMonthDay y m d) = YearMonthDay (y + n) m d
| Add years , matching month and day , with /February 29th/ rolled over to
> ' gregorianYearsRollover ' 2 $ ' YearMonthDay ' 2004 2 29
' YearMonthDay ' { ' ymdYear ' = 2006 , ' ymdMonth ' = 3 , ' ymdDay ' = 1 }
gregorianYearsRollover :: Years -> YearMonthDay -> YearMonthDay
gregorianYearsRollover n (YearMonthDay ((+) n -> y') 2 29)
| not (isLeapYear y') = YearMonthDay y' 3 1
gregorianYearsRollover n (YearMonthDay y m d) = YearMonthDay (y + n) m d
See also the ' AffineSpace ' instance for ' Day ' .
# INLINE addDays #
addDays :: Days -> Day -> Day
addDays = flip (.+^)
| Subtract two calendar ' Day 's for the difference in ' Days ' .
See also the ' AffineSpace ' instance for ' Day ' .
# INLINE diffDays #
diffDays :: Day -> Day -> Days
diffDays = (.-.)
| Convert a ' Day ' to its Gregorian ' Year ' , ' Month ' , and ' DayOfMonth ' .
' toGregorian ' ( ' view ' ' gregorian ' - > ' YearMonthDay ' y m d ) = ( y , m , d )
# INLINE toGregorian #
toGregorian :: Day -> (Year, Month, DayOfMonth)
toGregorian (view gregorian -> YearMonthDay y m d) = (y, m, d)
| Construct a ' Day ' from a Gregorian calendar date .
' fromGregorian ' y m d = ' gregorian ' ' Control . Lens . # ' ' YearMonthDay ' y m d
fromGregorian :: Year -> Month -> DayOfMonth -> Day
fromGregorian y m d = gregorian # YearMonthDay y m d
| Construct a ' Day ' from a Gregorian calendar date .
' fromGregorianValid ' y m d = ' gregorianValid ' ( ' YearMonthDay ' y m d )
# INLINE fromGregorianValid #
fromGregorianValid :: Year -> Month -> DayOfMonth -> Maybe Day
fromGregorianValid y m d = gregorianValid (YearMonthDay y m d)
last day of the new ' Month ' .
# INLINE addGregorianMonthsClip #
addGregorianMonthsClip :: Months -> Day -> Day
addGregorianMonthsClip n = gregorian %~ gregorianMonthsClip n
# INLINE addGregorianMonthsRollover #
addGregorianMonthsRollover :: Months -> Day -> Day
addGregorianMonthsRollover n = gregorian %~ gregorianMonthsRollover n
# INLINE addGregorianYearsClip #
addGregorianYearsClip :: Years -> Day -> Day
addGregorianYearsClip n = gregorian %~ gregorianYearsClip n
# INLINE addGregorianYearsRollover #
addGregorianYearsRollover :: Years -> Day -> Day
addGregorianYearsRollover n = gregorian %~ gregorianYearsRollover n
|
def41b86149a97bca77f582a23406e4285de562168a0be599aab2082da314c94 | Kappa-Dev/KappaTools | counters_domain_static.mli | val compute_static:
Remanent_parameters_sig.parameters -> Exception.method_handler ->
Cckappa_sig.kappa_handler ->
Cckappa_sig.compil ->
Exception.method_handler * Counters_domain_type.static
val convert_view:
Remanent_parameters_sig.parameters -> Exception.method_handler ->
Cckappa_sig.kappa_handler ->
Cckappa_sig.compil ->
Ckappa_sig.Site_map_and_set.Set.t
Ckappa_sig.Site_type_nearly_Inf_Int_storage_Imperatif.t
Ckappa_sig.Agent_type_nearly_Inf_Int_storage_Imperatif.t ->
Ckappa_sig.c_agent_name ->
Cckappa_sig.agent option ->
Exception.method_handler *
((Ckappa_sig.Agent_type_nearly_Inf_Int_storage_Imperatif.key *
Ckappa_sig.Site_type_nearly_Inf_Int_storage_Imperatif.key) *
(Occu1.trans * int) list)
list
| null | https://raw.githubusercontent.com/Kappa-Dev/KappaTools/eef2337e8688018eda47ccc838aea809cae68de7/core/KaSa_rep/reachability_analysis/counters_domain_static.mli | ocaml | val compute_static:
Remanent_parameters_sig.parameters -> Exception.method_handler ->
Cckappa_sig.kappa_handler ->
Cckappa_sig.compil ->
Exception.method_handler * Counters_domain_type.static
val convert_view:
Remanent_parameters_sig.parameters -> Exception.method_handler ->
Cckappa_sig.kappa_handler ->
Cckappa_sig.compil ->
Ckappa_sig.Site_map_and_set.Set.t
Ckappa_sig.Site_type_nearly_Inf_Int_storage_Imperatif.t
Ckappa_sig.Agent_type_nearly_Inf_Int_storage_Imperatif.t ->
Ckappa_sig.c_agent_name ->
Cckappa_sig.agent option ->
Exception.method_handler *
((Ckappa_sig.Agent_type_nearly_Inf_Int_storage_Imperatif.key *
Ckappa_sig.Site_type_nearly_Inf_Int_storage_Imperatif.key) *
(Occu1.trans * int) list)
list
| |
cbb3ec208f6ee2e3b746bc881bc53c61a3e090f0df7cc4ca70602121a5ee07b4 | deadtrickster/cl-statsd | async.lisp | (in-package :cl-statsd)
(defconstant +async-client-reconnects-default+ 5)
(defparameter *throttle-threshold* 7000000)
(define-condition throttle-threshold-reached (error)
((threshold :initarg :threshold :reader throttle-threshold)))
(defclass async-client (statsd-client-with-transport)
((reconnects :initarg :reconnects :initform +async-client-reconnects-default+ :reader async-client-reconnects)
(state :initform :created :reader async-client-state)
(throttle-threshold :initarg :throttle-threshold :reader async-client-throttle-threshold)
(thread :reader async-client-thread)
(mailbox :initform (safe-queue:make-mailbox) :reader async-client-mailbox)))
(defun make-async-client (&key prefix (throttle-threshold *throttle-threshold*) (error-handler :ignore) (transport :usocket) (host "127.0.0.1") (port 8125) (reconnects +async-client-reconnects-default+) (tcp-p))
(make-instance 'async-client :prefix prefix
:throttle-threshold throttle-threshold
:error-handler error-handler
:reconnects reconnects
:transport (make-transport transport host port tcp-p)))
(defun async-client-thread-fun (client)
(setf (slot-value client 'state) :running)
(let ((max-reconnects (or (async-client-reconnects client) 1)))
(loop
as recv = (safe-queue:mailbox-receive-message (async-client-mailbox client)) do
(cond
((stringp recv)
(let ((retries 1)
(sleep 1))
(tagbody
:retry
(handler-bind
((transport-error
(lambda (e)
(declare (ignore e))
(if (and
(< retries max-reconnects)
(ignore-errors (transport.connect (client-transport client))))
(progn
(sleep (* sleep retries))
(incf retries)
(go :retry))
(setf (slot-value client 'state) :stopped))))
(t (lambda (e)
(declare (ignore e))
(setf (slot-value client 'state) :stopped)
(return))))
(transport.send (client-transport client) recv)))))
((eql recv :stop)
(setf (slot-value client 'state) :stopped)
(return))))))
(defun start-async-client (&optional (client *client*))
(setf (slot-value client 'thread)
(bt:make-thread (lambda () (async-client-thread-fun client))))
client)
(defmethod stop-client% ((client async-client) timeout)
(when (eql (async-client-state client) :running)
(safe-queue:mailbox-send-message (async-client-mailbox client) :stop)
(let ((thread (async-client-thread client)))
#-sbcl
(progn
(log:info "Careless abort")
(sleep timeout)
(when (bt:thread-alive-p thread)
(bt:destroy-thread thread)))
#+sbcl
(if (and thread
(sb-thread:thread-alive-p thread))
(progn
(handler-case
(sb-thread:join-thread thread :timeout timeout)
(sb-thread:join-thread-error (e)
(case (sb-thread::join-thread-problem e)
(:timeout (log:error "Async StatsD client thread stalled?")
(sb-thread:terminate-thread thread))
(:abort (log:error "Async StatsD client thread aborted"))
(t (log:error "Async StatsD client thread state is unknown"))))))))
(call-next-method)))
(defmethod send ((client async-client) metric key value rate)
(with-smart?-error-handling client
(maybe-send rate
(ecase (async-client-state client)
(:created (start-async-client client))
(:stopped (error "Async Statsd client stopped"))
(:running))
(let ((tt (async-client-throttle-threshold client)))
(when (and tt (< tt (safe-queue:mailbox-count (async-client-mailbox client))))
(error 'throttle-threshold-reached :threshole t)))
(safe-queue:mailbox-send-message (async-client-mailbox client) (serialize-metric metric key value rate))
value)))
| null | https://raw.githubusercontent.com/deadtrickster/cl-statsd/7790c95c097f690994256519d24106b53c3e5e37/src/clients/async.lisp | lisp | (in-package :cl-statsd)
(defconstant +async-client-reconnects-default+ 5)
(defparameter *throttle-threshold* 7000000)
(define-condition throttle-threshold-reached (error)
((threshold :initarg :threshold :reader throttle-threshold)))
(defclass async-client (statsd-client-with-transport)
((reconnects :initarg :reconnects :initform +async-client-reconnects-default+ :reader async-client-reconnects)
(state :initform :created :reader async-client-state)
(throttle-threshold :initarg :throttle-threshold :reader async-client-throttle-threshold)
(thread :reader async-client-thread)
(mailbox :initform (safe-queue:make-mailbox) :reader async-client-mailbox)))
(defun make-async-client (&key prefix (throttle-threshold *throttle-threshold*) (error-handler :ignore) (transport :usocket) (host "127.0.0.1") (port 8125) (reconnects +async-client-reconnects-default+) (tcp-p))
(make-instance 'async-client :prefix prefix
:throttle-threshold throttle-threshold
:error-handler error-handler
:reconnects reconnects
:transport (make-transport transport host port tcp-p)))
(defun async-client-thread-fun (client)
(setf (slot-value client 'state) :running)
(let ((max-reconnects (or (async-client-reconnects client) 1)))
(loop
as recv = (safe-queue:mailbox-receive-message (async-client-mailbox client)) do
(cond
((stringp recv)
(let ((retries 1)
(sleep 1))
(tagbody
:retry
(handler-bind
((transport-error
(lambda (e)
(declare (ignore e))
(if (and
(< retries max-reconnects)
(ignore-errors (transport.connect (client-transport client))))
(progn
(sleep (* sleep retries))
(incf retries)
(go :retry))
(setf (slot-value client 'state) :stopped))))
(t (lambda (e)
(declare (ignore e))
(setf (slot-value client 'state) :stopped)
(return))))
(transport.send (client-transport client) recv)))))
((eql recv :stop)
(setf (slot-value client 'state) :stopped)
(return))))))
(defun start-async-client (&optional (client *client*))
(setf (slot-value client 'thread)
(bt:make-thread (lambda () (async-client-thread-fun client))))
client)
(defmethod stop-client% ((client async-client) timeout)
(when (eql (async-client-state client) :running)
(safe-queue:mailbox-send-message (async-client-mailbox client) :stop)
(let ((thread (async-client-thread client)))
#-sbcl
(progn
(log:info "Careless abort")
(sleep timeout)
(when (bt:thread-alive-p thread)
(bt:destroy-thread thread)))
#+sbcl
(if (and thread
(sb-thread:thread-alive-p thread))
(progn
(handler-case
(sb-thread:join-thread thread :timeout timeout)
(sb-thread:join-thread-error (e)
(case (sb-thread::join-thread-problem e)
(:timeout (log:error "Async StatsD client thread stalled?")
(sb-thread:terminate-thread thread))
(:abort (log:error "Async StatsD client thread aborted"))
(t (log:error "Async StatsD client thread state is unknown"))))))))
(call-next-method)))
(defmethod send ((client async-client) metric key value rate)
(with-smart?-error-handling client
(maybe-send rate
(ecase (async-client-state client)
(:created (start-async-client client))
(:stopped (error "Async Statsd client stopped"))
(:running))
(let ((tt (async-client-throttle-threshold client)))
(when (and tt (< tt (safe-queue:mailbox-count (async-client-mailbox client))))
(error 'throttle-threshold-reached :threshole t)))
(safe-queue:mailbox-send-message (async-client-mailbox client) (serialize-metric metric key value rate))
value)))
| |
e4614fbb52b35ca20504353d807587335b4cc74ef0d9a4bfdc06adf93b6322b9 | ghollisjr/cl-ana | memoization.lisp | cl - ana is a Common Lisp data analysis library .
Copyright 2013 , 2014
;;;;
This file is part of cl - ana .
;;;;
;;;; cl-ana 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.
;;;;
;;;; cl-ana 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 cl-ana. If not, see </>.
;;;;
You may contact ( me ! ) via email at
;;;;
;;; Memoized functions remember the previous calls of the function and
;;; look-up the return value from the last time the function was
;;; called.
;;;
;;; This implementation uses hash tables to store the previous call values.
;;;
;;; I am still unsure whether or not to expose access to the
;;; memoization hash table, at the moment it is not exposed.
(in-package :cl-ana.memoization)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *memoized-map* (make-hash-table :test 'equal)
"Hash table mapping each memoized function to its value hash
table."))
(defun get-memo-map (memo-fn)
"Returns the memoized function's value hash table."
(gethash memo-fn *memoized-map*))
(defun reset-memo-map (memo-fn)
"Resets the memoization hash table for memo-fn"
(when (gethash memo-fn *memoized-map*)
(clrhash (gethash memo-fn *memoized-map*))))
(defmacro memoize (fn &key (test 'equal))
"Macro for memoizing any function; test argument allows you to
specify how arguments will be looked up."
(with-gensyms (memoized
lookup-value
lookup-stored-p
return-value
args
table
xs)
`(let* ((,table
(make-hash-table :test ',test))
(,memoized
(lambda (&rest ,xs)
(let ((,args ,xs)) ; for accidental capture
(multiple-value-bind
(,lookup-value ,lookup-stored-p)
(gethash ,args ,table)
(if ,lookup-stored-p
,lookup-value
(let ((,return-value
(apply ,fn ,args)))
(setf (gethash ,args ,table)
,return-value)
,return-value)))))))
(setf (gethash ,memoized *memoized-map*)
,table)
,memoized)))
(defmacro memolet (memo-fns &body body)
"A macro for defining mutually recursive memoized functions and
executing body with knowledge of them. Cannot access the lookup
tables via *memoized-map* in the body, since this would prevent
garbage collection of the memoized function hash tables."
(with-gensyms (tables lookup-value lookup-stored-p args)
(let ((tabs (loop for i in memo-fns
collecting '(make-hash-table :test 'equal)))
(gsyms (loop for i in memo-fns
collecting (gensym))))
`(let ,(loop for tab in tabs
for gsym in gsyms
collecting `(,gsym ,tab))
(labels
(,@(loop
for mf in memo-fns
for gsym in gsyms
collecting
(destructuring-bind (self args-list &body body)
mf
`(,self (&rest ,args)
(multiple-value-bind
(,lookup-value ,lookup-stored-p)
(gethash ,args ,gsym)
(if ,lookup-stored-p
,lookup-value
(setf (gethash ,args ,gsym)
(destructuring-bind ,args-list
,args
,@body))))))))
;; ,@(loop
for in
;; for mf in memo-fns
collecting ` ( setf ( gethash ( function , ( first mf ) )
;; *memoized-map*)
, ) )
,@body)))))
(defun unmemoize (fn)
"Removes fn from the memoization lookup table; this prevents access
to the lookup map from outside the function but allows the function to
be garbage collected if necessary."
(remhash fn *memoized-map*))
(defmacro defun-memoized (function-name arg-list &body body)
"Macro for defining a memoized function. Note that currently there
is a small inconvenience in that lambda-lists are not automatically
added to the documentation used by things like SLIME."
(with-gensyms (raw-function memoized defuned xs)
`(let* ((,raw-function
(lambda (&rest ,xs)
(destructuring-bind (,@arg-list)
,xs
,@body)))
(,memoized
(memoize ,raw-function))
(,defuned
(defun ,function-name (&rest ,xs)
(apply ,memoized ,xs))))
(setf (gethash (symbol-function ,defuned) *memoized-map*)
(gethash ,memoized *memoized-map*))
,memoized
,defuned)))
| null | https://raw.githubusercontent.com/ghollisjr/cl-ana/5cb4c0b0c9c4957452ad2a769d6ff9e8d5df0b10/memoization/memoization.lisp | lisp |
cl-ana is free software: you can redistribute it and/or modify it
(at your option) any later version.
cl-ana is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
along with cl-ana. If not, see </>.
Memoized functions remember the previous calls of the function and
look-up the return value from the last time the function was
called.
This implementation uses hash tables to store the previous call values.
I am still unsure whether or not to expose access to the
memoization hash table, at the moment it is not exposed.
test argument allows you to
for accidental capture
,@(loop
for mf in memo-fns
*memoized-map*)
this prevents access | cl - ana is a Common Lisp data analysis library .
Copyright 2013 , 2014
This file is part of cl - ana .
under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
You may contact ( me ! ) via email at
(in-package :cl-ana.memoization)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *memoized-map* (make-hash-table :test 'equal)
"Hash table mapping each memoized function to its value hash
table."))
(defun get-memo-map (memo-fn)
"Returns the memoized function's value hash table."
(gethash memo-fn *memoized-map*))
(defun reset-memo-map (memo-fn)
"Resets the memoization hash table for memo-fn"
(when (gethash memo-fn *memoized-map*)
(clrhash (gethash memo-fn *memoized-map*))))
(defmacro memoize (fn &key (test 'equal))
specify how arguments will be looked up."
(with-gensyms (memoized
lookup-value
lookup-stored-p
return-value
args
table
xs)
`(let* ((,table
(make-hash-table :test ',test))
(,memoized
(lambda (&rest ,xs)
(multiple-value-bind
(,lookup-value ,lookup-stored-p)
(gethash ,args ,table)
(if ,lookup-stored-p
,lookup-value
(let ((,return-value
(apply ,fn ,args)))
(setf (gethash ,args ,table)
,return-value)
,return-value)))))))
(setf (gethash ,memoized *memoized-map*)
,table)
,memoized)))
(defmacro memolet (memo-fns &body body)
"A macro for defining mutually recursive memoized functions and
executing body with knowledge of them. Cannot access the lookup
tables via *memoized-map* in the body, since this would prevent
garbage collection of the memoized function hash tables."
(with-gensyms (tables lookup-value lookup-stored-p args)
(let ((tabs (loop for i in memo-fns
collecting '(make-hash-table :test 'equal)))
(gsyms (loop for i in memo-fns
collecting (gensym))))
`(let ,(loop for tab in tabs
for gsym in gsyms
collecting `(,gsym ,tab))
(labels
(,@(loop
for mf in memo-fns
for gsym in gsyms
collecting
(destructuring-bind (self args-list &body body)
mf
`(,self (&rest ,args)
(multiple-value-bind
(,lookup-value ,lookup-stored-p)
(gethash ,args ,gsym)
(if ,lookup-stored-p
,lookup-value
(setf (gethash ,args ,gsym)
(destructuring-bind ,args-list
,args
,@body))))))))
for in
collecting ` ( setf ( gethash ( function , ( first mf ) )
, ) )
,@body)))))
(defun unmemoize (fn)
to the lookup map from outside the function but allows the function to
be garbage collected if necessary."
(remhash fn *memoized-map*))
(defmacro defun-memoized (function-name arg-list &body body)
"Macro for defining a memoized function. Note that currently there
is a small inconvenience in that lambda-lists are not automatically
added to the documentation used by things like SLIME."
(with-gensyms (raw-function memoized defuned xs)
`(let* ((,raw-function
(lambda (&rest ,xs)
(destructuring-bind (,@arg-list)
,xs
,@body)))
(,memoized
(memoize ,raw-function))
(,defuned
(defun ,function-name (&rest ,xs)
(apply ,memoized ,xs))))
(setf (gethash (symbol-function ,defuned) *memoized-map*)
(gethash ,memoized *memoized-map*))
,memoized
,defuned)))
|
03d42e375c5d43ec089bbb4a4e083befa000e88e2f7cc2b274d0aa161f2eac65 | arenadotio/pgx | pgx_aux.mli | * Helper functions since we do n't want a dependency on Core or Batteries .
module String : sig
include module type of String
val implode : char list -> string
val fold_left : ('a -> char -> 'a) -> 'a -> string -> 'a
end
module List : sig
include module type of List
* Like the built - in [ List.map ] , but tail - recursive
val map : ('a -> 'b) -> 'a list -> 'b list
end
(** Necessary for ppx_compare *)
val compare_bool : bool -> bool -> int
val compare_float : float -> float -> int
val compare_int : int -> int -> int
val compare_int32 : int32 -> int32 -> int
val compare_list : ('a -> 'a -> int) -> 'a list -> 'a list -> int
val compare_option : ('a -> 'a -> int) -> 'a option -> 'a option -> int
val compare_string : string -> string -> int
| null | https://raw.githubusercontent.com/arenadotio/pgx/8d5ca02213faa69e692c5d0dc3e81408db3774a1/pgx/src/pgx_aux.mli | ocaml | * Necessary for ppx_compare | * Helper functions since we do n't want a dependency on Core or Batteries .
module String : sig
include module type of String
val implode : char list -> string
val fold_left : ('a -> char -> 'a) -> 'a -> string -> 'a
end
module List : sig
include module type of List
* Like the built - in [ List.map ] , but tail - recursive
val map : ('a -> 'b) -> 'a list -> 'b list
end
val compare_bool : bool -> bool -> int
val compare_float : float -> float -> int
val compare_int : int -> int -> int
val compare_int32 : int32 -> int32 -> int
val compare_list : ('a -> 'a -> int) -> 'a list -> 'a list -> int
val compare_option : ('a -> 'a -> int) -> 'a option -> 'a option -> int
val compare_string : string -> string -> int
|
a7fb8a003bfc86c02994123124a2ac4cc3f7bdf248fc9bc21befac1af20d2c75 | gcv/cupboard | je_marshal.clj | (ns cupboard.bdb.je-marshal
(:import [org.joda.time DateTime LocalDate LocalTime LocalDateTime DateTimeZone])
(:import [com.sleepycat.je DatabaseEntry OperationStatus]
[com.sleepycat.bind.tuple TupleBinding TupleInput TupleOutput]))
(def ^:dynamic *clj-types*
[nil
java.lang.Boolean
java.lang.Character
java.lang.Byte
java.lang.Short
java.lang.Integer
java.lang.Long
java.math.BigInteger
clojure.lang.Ratio
clojure.lang.BigInt
java.lang.Double
java.lang.Float
java.lang.String
java.util.Date
org.joda.time.DateTime
org.joda.time.LocalDate
org.joda.time.LocalTime
org.joda.time.LocalDateTime
java.util.UUID
clojure.lang.Keyword
clojure.lang.Symbol
:list
:vector
:seq
:map
:set
(class (boolean-array []))
(class (byte-array []))
(class (char-array []))
(class (double-array []))
(class (float-array []))
(class (int-array []))
(class (long-array []))
(class (object-array []))
(class (short-array []))])
(def ^:dynamic *clj-type-codes* (zipmap *clj-types* (range 0 (count *clj-types*))))
(defn clj-type [data]
(condp #(%1 %2) data
map? :map
set? :set
list? :list
vector? :vector
seq? :seq
(class data)))
(defmulti marshal-write (fn [tuple-output data] (clj-type data)))
(defmacro def-marshal-write [java-type write-method]
`(defmethod marshal-write ~java-type [#^TupleOutput tuple-output#
#^{:tag ~java-type} data#]
(.writeUnsignedByte tuple-output# (*clj-type-codes* ~java-type))
(when-not (nil? data#) (~write-method tuple-output# data#))))
(def-marshal-write nil (fn [_] nil))
(def-marshal-write java.lang.Boolean .writeBoolean)
(def-marshal-write java.lang.Boolean .writeBoolean)
(def-marshal-write java.lang.Character
(fn [#^TupleOutput tuple-output #^java.lang.Character data]
(.writeChar tuple-output (int data))))
(def-marshal-write java.lang.Byte .writeByte)
(def-marshal-write java.lang.Short .writeShort)
(def-marshal-write java.lang.Integer .writeInt)
(def-marshal-write java.lang.Long .writeLong)
(def-marshal-write java.math.BigInteger .writeBigInteger)
(def-marshal-write clojure.lang.Ratio
(fn [#^TupleOutput tuple-output #^clojure.lang.Ratio data]
(marshal-write tuple-output (.numerator data))
(marshal-write tuple-output (.denominator data))))
(def-marshal-write clojure.lang.BigInt
(fn [#^TupleOutput tuple-output #^clojure.lang.BigInt data]
(marshal-write tuple-output (.toBigInteger data))))
(def-marshal-write java.lang.Double .writeSortedDouble)
(def-marshal-write java.lang.Float .writeSortedFloat)
(def-marshal-write java.lang.String .writeString)
(def-marshal-write java.util.Date
(fn [#^TupleOutput tuple-output #^java.util.Date data]
(.writeString tuple-output (str (.withZone (DateTime. data) DateTimeZone/UTC)))))
(def-marshal-write DateTime
(fn [#^TupleOutput tuple-output #^DateTime data]
(.writeString tuple-output (str (.withZone data DateTimeZone/UTC)))))
(def-marshal-write LocalDate
(fn [#^TupleOutput tuple-output #^LocalDate data]
(.writeString tuple-output (str data))))
(def-marshal-write LocalTime
(fn [#^TupleOutput tuple-output #^LocalTime data]
(.writeString tuple-output (str data))))
(def-marshal-write LocalDateTime
(fn [#^TupleOutput tuple-output #^LocalDateTime data]
(.writeString tuple-output (str data))))
(def-marshal-write java.util.UUID
(fn [#^TupleOutput tuple-output #^java.util.UUID uuid]
(.writeLong tuple-output (.getMostSignificantBits uuid))
(.writeLong tuple-output (.getLeastSignificantBits uuid))))
(def-marshal-write clojure.lang.Keyword
(fn [#^TupleOutput tuple-output #^clojure.lang.Keyword data]
(.writeString tuple-output (.substring (str data) 1))))
(def-marshal-write clojure.lang.Symbol
(fn [#^TupleOutput tuple-output #^clojure.lang.Symbol data]
(.writeString tuple-output (str data))))
(letfn [(seq-write [tuple-output data]
(marshal-write tuple-output (count data))
(doseq [e data] (marshal-write tuple-output e)))]
(def-marshal-write :list seq-write)
(def-marshal-write :vector seq-write)
(def-marshal-write :seq seq-write)
(def-marshal-write :set seq-write)
(def-marshal-write (class (boolean-array [])) seq-write)
(def-marshal-write (class (byte-array [])) seq-write)
(def-marshal-write (class (char-array [])) seq-write)
(def-marshal-write (class (double-array [])) seq-write)
(def-marshal-write (class (float-array [])) seq-write)
(def-marshal-write (class (int-array [])) seq-write)
(def-marshal-write (class (long-array [])) seq-write)
(def-marshal-write (class (object-array [])) seq-write)
(def-marshal-write (class (short-array [])) seq-write))
(def-marshal-write :map
(fn [tuple-output data]
(marshal-write tuple-output (count data))
(doseq [[key value] data]
(marshal-write tuple-output key)
(marshal-write tuple-output value))))
(defn marshal-db-entry
"A general way to get a database entry from data. If data is a DatabaseEntry
instance, just return it. If it is a supported type, convert it into a new
DatabaseEntry object. If the optional db-entry-arg is passed in, reuse it
as the target DatabaseEntry."
[data & [db-entry-arg]]
(if (instance? DatabaseEntry data)
data
(let [db-entry (if db-entry-arg db-entry-arg (DatabaseEntry.))
tuple-output (TupleOutput.)]
(marshal-write tuple-output data)
(TupleBinding/outputToEntry tuple-output db-entry)
db-entry)))
(defn marshal-db-entry*
"A helper function for making optionally-empty DatabaseEntry objects from
keyword argument maps."
[map-arg key-arg]
(if (contains? map-arg key-arg)
(marshal-db-entry (map-arg key-arg))
(DatabaseEntry.)))
(defmulti unmarshal-read
(fn [#^TupleInput tuple-input]
(let [type-byte (.readUnsignedByte tuple-input)]
(nth *clj-types* type-byte))))
(defmacro def-unmarshal-read [java-type read-method]
`(defmethod unmarshal-read ~java-type [#^TupleInput tuple-input#]
(~read-method tuple-input#)))
(def-unmarshal-read nil (fn [_] nil))
(def-unmarshal-read java.lang.Boolean .readBoolean)
(def-unmarshal-read java.lang.Character .readChar)
(def-unmarshal-read java.lang.Byte .readByte)
(def-unmarshal-read java.lang.Short .readShort)
(def-unmarshal-read java.lang.Integer .readInt)
(def-unmarshal-read java.lang.Long .readLong)
(def-unmarshal-read java.math.BigInteger .readBigInteger)
(def-unmarshal-read clojure.lang.Ratio
(fn [tuple-input] (clojure.lang.Ratio.
(unmarshal-read tuple-input)
(unmarshal-read tuple-input))))
(def-unmarshal-read clojure.lang.BigInt
(fn [tuple-input] (clojure.lang.BigInt/fromBigInteger
(unmarshal-read tuple-input))))
(def-unmarshal-read java.lang.Double .readSortedDouble)
(def-unmarshal-read java.lang.Float .readSortedFloat)
(def-unmarshal-read java.lang.String .readString)
(def-unmarshal-read java.util.Date
(fn [#^TupleInput tuple-input]
(java.util.Date. (long (.getMillis (DateTime. (.readString tuple-input)))))))
(def-unmarshal-read DateTime
(fn [#^TupleInput tuple-input] (DateTime. (.readString tuple-input))))
(def-unmarshal-read LocalDate
(fn [#^TupleInput tuple-input] (LocalDate. (.readString tuple-input))))
(def-unmarshal-read LocalTime
(fn [#^TupleInput tuple-input] (LocalTime. (.readString tuple-input))))
(def-unmarshal-read LocalDateTime
(fn [#^TupleInput tuple-input] (LocalDateTime. (.readString tuple-input))))
(def-unmarshal-read java.util.UUID
(fn [#^TupleInput tuple-input] (java.util.UUID.
(.readLong tuple-input)
(.readLong tuple-input))))
(def-unmarshal-read clojure.lang.Keyword
(fn [#^TupleInput tuple-input] (keyword (.readString tuple-input))))
;; XXX: Symbols get interned in the package which unmarshals the symbol!!!
(def-unmarshal-read clojure.lang.Symbol
(fn [#^TupleInput tuple-input] (symbol (.readString tuple-input))))
TODO : When available in a full Clojure release , use a transient data
;; structure to put together sequences in the loop (as is, it creates quite a
;; bit of garbage). Alternatively, maybe use a for form if it is more efficient?
;;
(letfn [(seq-read-fn [starting-value after-fn]
(fn [tuple-input]
(let [len (unmarshal-read tuple-input)]
(loop [i 0 res starting-value]
(if (>= i len)
(after-fn res)
(recur (inc i) (conj res (unmarshal-read tuple-input))))))))]
(def-unmarshal-read :list (seq-read-fn (list) reverse))
(def-unmarshal-read :seq (seq-read-fn (list) reverse))
(def-unmarshal-read :vector (seq-read-fn [] identity))
(def-unmarshal-read :set (seq-read-fn #{} identity))
(def-unmarshal-read (class (boolean-array [])) (seq-read-fn [] boolean-array))
(def-unmarshal-read (class (byte-array [])) (seq-read-fn [] byte-array))
(def-unmarshal-read (class (char-array [])) (seq-read-fn [] char-array))
(def-unmarshal-read (class (double-array []))(seq-read-fn [] double-array))
(def-unmarshal-read (class (float-array []))(seq-read-fn [] float-array))
(def-unmarshal-read (class (int-array []))(seq-read-fn [] int-array))
(def-unmarshal-read (class (long-array []))(seq-read-fn [] long-array))
(def-unmarshal-read (class (object-array []))(seq-read-fn [] object-array))
(def-unmarshal-read (class (short-array []))(seq-read-fn [] short-array)))
(def-unmarshal-read :map
(fn [tuple-input]
(let [len (unmarshal-read tuple-input)]
(loop [i 0 res (hash-map)]
(if (>= i len)
res
(recur (inc i) (assoc res
(unmarshal-read tuple-input)
(unmarshal-read tuple-input))))))))
(defn unmarshal-db-entry [#^DatabaseEntry db-entry]
(if (= 0 (.getSize db-entry))
nil
(let [tuple-input (TupleBinding/entryToInput db-entry)]
(unmarshal-read tuple-input))))
(defn unmarshal-db-entry*
"A helper function which returns a [key data] pair given the result of a
retrieval operation and the corresponding DatabaseEntry objects."
[result key-entry data-entry]
(if (= result OperationStatus/SUCCESS)
[(unmarshal-db-entry key-entry) (unmarshal-db-entry data-entry)]
[]))
| null | https://raw.githubusercontent.com/gcv/cupboard/bd264e3051bafacd8b12602e02819585b563c464/src/cupboard/bdb/je_marshal.clj | clojure | XXX: Symbols get interned in the package which unmarshals the symbol!!!
structure to put together sequences in the loop (as is, it creates quite a
bit of garbage). Alternatively, maybe use a for form if it is more efficient?
| (ns cupboard.bdb.je-marshal
(:import [org.joda.time DateTime LocalDate LocalTime LocalDateTime DateTimeZone])
(:import [com.sleepycat.je DatabaseEntry OperationStatus]
[com.sleepycat.bind.tuple TupleBinding TupleInput TupleOutput]))
(def ^:dynamic *clj-types*
[nil
java.lang.Boolean
java.lang.Character
java.lang.Byte
java.lang.Short
java.lang.Integer
java.lang.Long
java.math.BigInteger
clojure.lang.Ratio
clojure.lang.BigInt
java.lang.Double
java.lang.Float
java.lang.String
java.util.Date
org.joda.time.DateTime
org.joda.time.LocalDate
org.joda.time.LocalTime
org.joda.time.LocalDateTime
java.util.UUID
clojure.lang.Keyword
clojure.lang.Symbol
:list
:vector
:seq
:map
:set
(class (boolean-array []))
(class (byte-array []))
(class (char-array []))
(class (double-array []))
(class (float-array []))
(class (int-array []))
(class (long-array []))
(class (object-array []))
(class (short-array []))])
(def ^:dynamic *clj-type-codes* (zipmap *clj-types* (range 0 (count *clj-types*))))
(defn clj-type [data]
(condp #(%1 %2) data
map? :map
set? :set
list? :list
vector? :vector
seq? :seq
(class data)))
(defmulti marshal-write (fn [tuple-output data] (clj-type data)))
(defmacro def-marshal-write [java-type write-method]
`(defmethod marshal-write ~java-type [#^TupleOutput tuple-output#
#^{:tag ~java-type} data#]
(.writeUnsignedByte tuple-output# (*clj-type-codes* ~java-type))
(when-not (nil? data#) (~write-method tuple-output# data#))))
(def-marshal-write nil (fn [_] nil))
(def-marshal-write java.lang.Boolean .writeBoolean)
(def-marshal-write java.lang.Boolean .writeBoolean)
(def-marshal-write java.lang.Character
(fn [#^TupleOutput tuple-output #^java.lang.Character data]
(.writeChar tuple-output (int data))))
(def-marshal-write java.lang.Byte .writeByte)
(def-marshal-write java.lang.Short .writeShort)
(def-marshal-write java.lang.Integer .writeInt)
(def-marshal-write java.lang.Long .writeLong)
(def-marshal-write java.math.BigInteger .writeBigInteger)
(def-marshal-write clojure.lang.Ratio
(fn [#^TupleOutput tuple-output #^clojure.lang.Ratio data]
(marshal-write tuple-output (.numerator data))
(marshal-write tuple-output (.denominator data))))
(def-marshal-write clojure.lang.BigInt
(fn [#^TupleOutput tuple-output #^clojure.lang.BigInt data]
(marshal-write tuple-output (.toBigInteger data))))
(def-marshal-write java.lang.Double .writeSortedDouble)
(def-marshal-write java.lang.Float .writeSortedFloat)
(def-marshal-write java.lang.String .writeString)
(def-marshal-write java.util.Date
(fn [#^TupleOutput tuple-output #^java.util.Date data]
(.writeString tuple-output (str (.withZone (DateTime. data) DateTimeZone/UTC)))))
(def-marshal-write DateTime
(fn [#^TupleOutput tuple-output #^DateTime data]
(.writeString tuple-output (str (.withZone data DateTimeZone/UTC)))))
(def-marshal-write LocalDate
(fn [#^TupleOutput tuple-output #^LocalDate data]
(.writeString tuple-output (str data))))
(def-marshal-write LocalTime
(fn [#^TupleOutput tuple-output #^LocalTime data]
(.writeString tuple-output (str data))))
(def-marshal-write LocalDateTime
(fn [#^TupleOutput tuple-output #^LocalDateTime data]
(.writeString tuple-output (str data))))
(def-marshal-write java.util.UUID
(fn [#^TupleOutput tuple-output #^java.util.UUID uuid]
(.writeLong tuple-output (.getMostSignificantBits uuid))
(.writeLong tuple-output (.getLeastSignificantBits uuid))))
(def-marshal-write clojure.lang.Keyword
(fn [#^TupleOutput tuple-output #^clojure.lang.Keyword data]
(.writeString tuple-output (.substring (str data) 1))))
(def-marshal-write clojure.lang.Symbol
(fn [#^TupleOutput tuple-output #^clojure.lang.Symbol data]
(.writeString tuple-output (str data))))
(letfn [(seq-write [tuple-output data]
(marshal-write tuple-output (count data))
(doseq [e data] (marshal-write tuple-output e)))]
(def-marshal-write :list seq-write)
(def-marshal-write :vector seq-write)
(def-marshal-write :seq seq-write)
(def-marshal-write :set seq-write)
(def-marshal-write (class (boolean-array [])) seq-write)
(def-marshal-write (class (byte-array [])) seq-write)
(def-marshal-write (class (char-array [])) seq-write)
(def-marshal-write (class (double-array [])) seq-write)
(def-marshal-write (class (float-array [])) seq-write)
(def-marshal-write (class (int-array [])) seq-write)
(def-marshal-write (class (long-array [])) seq-write)
(def-marshal-write (class (object-array [])) seq-write)
(def-marshal-write (class (short-array [])) seq-write))
(def-marshal-write :map
(fn [tuple-output data]
(marshal-write tuple-output (count data))
(doseq [[key value] data]
(marshal-write tuple-output key)
(marshal-write tuple-output value))))
(defn marshal-db-entry
"A general way to get a database entry from data. If data is a DatabaseEntry
instance, just return it. If it is a supported type, convert it into a new
DatabaseEntry object. If the optional db-entry-arg is passed in, reuse it
as the target DatabaseEntry."
[data & [db-entry-arg]]
(if (instance? DatabaseEntry data)
data
(let [db-entry (if db-entry-arg db-entry-arg (DatabaseEntry.))
tuple-output (TupleOutput.)]
(marshal-write tuple-output data)
(TupleBinding/outputToEntry tuple-output db-entry)
db-entry)))
(defn marshal-db-entry*
"A helper function for making optionally-empty DatabaseEntry objects from
keyword argument maps."
[map-arg key-arg]
(if (contains? map-arg key-arg)
(marshal-db-entry (map-arg key-arg))
(DatabaseEntry.)))
(defmulti unmarshal-read
(fn [#^TupleInput tuple-input]
(let [type-byte (.readUnsignedByte tuple-input)]
(nth *clj-types* type-byte))))
(defmacro def-unmarshal-read [java-type read-method]
`(defmethod unmarshal-read ~java-type [#^TupleInput tuple-input#]
(~read-method tuple-input#)))
(def-unmarshal-read nil (fn [_] nil))
(def-unmarshal-read java.lang.Boolean .readBoolean)
(def-unmarshal-read java.lang.Character .readChar)
(def-unmarshal-read java.lang.Byte .readByte)
(def-unmarshal-read java.lang.Short .readShort)
(def-unmarshal-read java.lang.Integer .readInt)
(def-unmarshal-read java.lang.Long .readLong)
(def-unmarshal-read java.math.BigInteger .readBigInteger)
(def-unmarshal-read clojure.lang.Ratio
(fn [tuple-input] (clojure.lang.Ratio.
(unmarshal-read tuple-input)
(unmarshal-read tuple-input))))
(def-unmarshal-read clojure.lang.BigInt
(fn [tuple-input] (clojure.lang.BigInt/fromBigInteger
(unmarshal-read tuple-input))))
(def-unmarshal-read java.lang.Double .readSortedDouble)
(def-unmarshal-read java.lang.Float .readSortedFloat)
(def-unmarshal-read java.lang.String .readString)
(def-unmarshal-read java.util.Date
(fn [#^TupleInput tuple-input]
(java.util.Date. (long (.getMillis (DateTime. (.readString tuple-input)))))))
(def-unmarshal-read DateTime
(fn [#^TupleInput tuple-input] (DateTime. (.readString tuple-input))))
(def-unmarshal-read LocalDate
(fn [#^TupleInput tuple-input] (LocalDate. (.readString tuple-input))))
(def-unmarshal-read LocalTime
(fn [#^TupleInput tuple-input] (LocalTime. (.readString tuple-input))))
(def-unmarshal-read LocalDateTime
(fn [#^TupleInput tuple-input] (LocalDateTime. (.readString tuple-input))))
(def-unmarshal-read java.util.UUID
(fn [#^TupleInput tuple-input] (java.util.UUID.
(.readLong tuple-input)
(.readLong tuple-input))))
(def-unmarshal-read clojure.lang.Keyword
(fn [#^TupleInput tuple-input] (keyword (.readString tuple-input))))
(def-unmarshal-read clojure.lang.Symbol
(fn [#^TupleInput tuple-input] (symbol (.readString tuple-input))))
TODO : When available in a full Clojure release , use a transient data
(letfn [(seq-read-fn [starting-value after-fn]
(fn [tuple-input]
(let [len (unmarshal-read tuple-input)]
(loop [i 0 res starting-value]
(if (>= i len)
(after-fn res)
(recur (inc i) (conj res (unmarshal-read tuple-input))))))))]
(def-unmarshal-read :list (seq-read-fn (list) reverse))
(def-unmarshal-read :seq (seq-read-fn (list) reverse))
(def-unmarshal-read :vector (seq-read-fn [] identity))
(def-unmarshal-read :set (seq-read-fn #{} identity))
(def-unmarshal-read (class (boolean-array [])) (seq-read-fn [] boolean-array))
(def-unmarshal-read (class (byte-array [])) (seq-read-fn [] byte-array))
(def-unmarshal-read (class (char-array [])) (seq-read-fn [] char-array))
(def-unmarshal-read (class (double-array []))(seq-read-fn [] double-array))
(def-unmarshal-read (class (float-array []))(seq-read-fn [] float-array))
(def-unmarshal-read (class (int-array []))(seq-read-fn [] int-array))
(def-unmarshal-read (class (long-array []))(seq-read-fn [] long-array))
(def-unmarshal-read (class (object-array []))(seq-read-fn [] object-array))
(def-unmarshal-read (class (short-array []))(seq-read-fn [] short-array)))
(def-unmarshal-read :map
(fn [tuple-input]
(let [len (unmarshal-read tuple-input)]
(loop [i 0 res (hash-map)]
(if (>= i len)
res
(recur (inc i) (assoc res
(unmarshal-read tuple-input)
(unmarshal-read tuple-input))))))))
(defn unmarshal-db-entry [#^DatabaseEntry db-entry]
(if (= 0 (.getSize db-entry))
nil
(let [tuple-input (TupleBinding/entryToInput db-entry)]
(unmarshal-read tuple-input))))
(defn unmarshal-db-entry*
"A helper function which returns a [key data] pair given the result of a
retrieval operation and the corresponding DatabaseEntry objects."
[result key-entry data-entry]
(if (= result OperationStatus/SUCCESS)
[(unmarshal-db-entry key-entry) (unmarshal-db-entry data-entry)]
[]))
|
4406612abbe294e3419a97cb572b9fe76941b4b5c087cdccf113327eb3bf891a | LambdaHack/LambdaHack | SessionUI.hs | # LANGUAGE DeriveGeneric , GeneralizedNewtypeDeriving #
-- | The client UI session state.
module Game.LambdaHack.Client.UI.SessionUI
( SessionUI(..), ReqDelay(..), ItemDictUI, ItemRoles(..), AimMode(..)
, KeyMacro(..), KeyMacroFrame(..), RunParams(..), ChosenLore(..)
, emptySessionUI, emptyMacroFrame
, cycleMarkVision, toggleMarkSmell, cycleOverrideTut, getActorUI
) where
import Prelude ()
import Game.LambdaHack.Core.Prelude
import Data.Binary
import qualified Data.EnumMap.Strict as EM
import qualified Data.EnumSet as ES
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import Data.Time.Clock.POSIX
import GHC.Generics (Generic)
import qualified System.Random.SplitMix32 as SM
import Game.LambdaHack.Client.Request
import Game.LambdaHack.Client.State
import Game.LambdaHack.Client.UI.ActorUI
import Game.LambdaHack.Client.UI.ContentClientUI
import Game.LambdaHack.Client.UI.EffectDescription (DetailLevel (..))
import Game.LambdaHack.Client.UI.Frontend
import qualified Game.LambdaHack.Client.UI.Key as K
import Game.LambdaHack.Client.UI.Msg
import Game.LambdaHack.Client.UI.PointUI
import Game.LambdaHack.Client.UI.UIOptions
import Game.LambdaHack.Common.Actor
import Game.LambdaHack.Common.Faction
import Game.LambdaHack.Common.Item
import Game.LambdaHack.Common.Time
import Game.LambdaHack.Common.Types
import Game.LambdaHack.Content.ModeKind (ModeKind)
import Game.LambdaHack.Definition.Defs
-- | The information that is used across a human player playing session,
-- including many consecutive games in a single session,
-- including playing different teams. Some of it is saved, some is reset
-- when a new playing session starts. Nothing is tied to a faction/team,
-- but instead all to UI configuration and UI input and display history.
-- An important component is the frontend session.
data SessionUI = SessionUI
{ sreqPending :: Maybe RequestUI
-- ^ request created by a UI query
-- but not yet sent to the server
, sreqDelay :: ReqDelay -- ^ server delayed sending query to client
-- or receiving request from client
, sreqQueried :: Bool -- ^ player is now queried for a command
, sregainControl :: Bool -- ^ player requested to regain control
from AI ASAP
^ the common xhair
^ set for last GoTo
, sactorUI :: ActorDictUI -- ^ assigned actor UI presentations
^ assigned item first seen level
, sroles :: ItemRoles -- ^ assignment of roles to items
, slastItemMove :: Maybe (CStore, CStore)
-- ^ last item move stores
, schanF :: ChanFrontend -- ^ connection with the frontend
, sccui :: CCUI -- ^ UI client content
, sUIOptions :: UIOptions -- ^ UI options as set by the player
, saimMode :: Maybe AimMode -- ^ aiming mode
, sxhairMoused :: Bool -- ^ last mouse aiming not vacuus
, sitemSel :: Maybe (ItemId, CStore, Bool)
-- ^ selected item, if any, it's store and
-- whether to override suitability check
, sselected :: ES.EnumSet ActorId
-- ^ the set of currently selected actors
, srunning :: Maybe RunParams
-- ^ parameters of the current run, if any
, shistory :: History -- ^ history of messages
, svictories :: EM.EnumMap (ContentId ModeKind) (M.Map Challenge Int)
-- ^ the number of games won by the UI faction per game mode
-- and per difficulty level
, scampings :: ES.EnumSet (ContentId ModeKind) -- ^ camped games
, srestarts :: ES.EnumSet (ContentId ModeKind) -- ^ restarted games
, spointer :: PointUI -- ^ mouse pointer position
, sautoYes :: Bool -- ^ whether to auto-clear prompts
, smacroFrame :: KeyMacroFrame -- ^ the head of the key macro stack
, smacroStack :: [KeyMacroFrame]
-- ^ the tail of the key macro stack
, slastLost :: ES.EnumSet ActorId
-- ^ actors that just got out of sight
, swaitTimes :: Int -- ^ player just waited this many times
^ the player just exited AI automation
^ mark leader and party FOV
, smarkSmell :: Bool -- ^ mark smell, if the leader can smell
, snxtScenario :: Int -- ^ next game scenario number
, scurTutorial :: Bool -- ^ whether current game is a tutorial
, snxtTutorial :: Bool -- ^ whether next game is to be tutorial
, soverrideTut :: Maybe Bool -- ^ override display of tutorial hints
, susedHints :: S.Set Msg -- ^ tutorial hints already shown this game
, smuteMessages :: Bool -- ^ whether to mute all new messages
, smenuIxMap :: M.Map String Int
-- ^ indices of last used menu items
, schosenLore :: ChosenLore -- ^ last lore chosen to display
, sdisplayNeeded :: Bool -- ^ current level needs displaying
, sturnDisplayed :: Bool -- ^ a frame was already displayed this turn
, sreportNull :: Bool -- ^ whether no visible report created
-- last UI faction turn or the report
-- wiped out from screen since
, sstart :: POSIXTime -- ^ this session start time
, sgstart :: POSIXTime -- ^ this game start time
, sallTime :: Time -- ^ clips from start of session
-- to current game start
, snframes :: Int -- ^ this game current frame count
, sallNframes :: Int -- ^ frame count from start of session
-- to current game start
, srandomUI :: SM.SMGen -- ^ current random generator for UI
}
data ReqDelay = ReqDelayNot | ReqDelayHandled | ReqDelayAlarm
deriving Eq
-- | Local macro buffer frame. Predefined macros have their own in-game macro
-- buffer, allowing them to record in-game macro, queue actions and repeat
-- the last macro's action.
Running predefined macro pushes new @KeyMacroFrame@ onto the stack . We pop
-- buffers from the stack if locally there are no actions pending to be handled.
data KeyMacroFrame = KeyMacroFrame
{ keyMacroBuffer :: Either [K.KM] KeyMacro -- ^ record keystrokes in Left;
-- repeat from Right
, keyPending :: KeyMacro -- ^ actions pending to be handled
, keyLast :: Maybe K.KM -- ^ last pressed key
} deriving Show
-- This can stay a map forever, not a vector, because it's added to often,
-- but never read from, except when the user requests item details.
type ItemDictUI = EM.EnumMap ItemId LevelId
-- | A collection of item identifier sets indicating what roles (possibly many)
-- an item has assigned.
newtype ItemRoles = ItemRoles (EM.EnumMap SLore (ES.EnumSet ItemId))
deriving (Show, Binary)
-- | Current aiming mode of a client.
data AimMode = AimMode
{ aimLevelId :: LevelId
, detailLevel :: DetailLevel
}
deriving (Show, Eq, Generic)
instance Binary AimMode
-- | In-game macros. We record menu navigation keystrokes and keystrokes
bound to commands with one exception --- we exclude keys that invoke
the @Record@ command , to avoid surprises .
-- Keys are kept in the same order in which they're meant to be replayed,
i.e. the first element of the list is replayed also as the first one .
newtype KeyMacro = KeyMacro {unKeyMacro :: [K.KM]}
deriving (Show, Eq, Binary, Semigroup, Monoid)
-- | Parameters of the current run.
data RunParams = RunParams
{ runLeader :: ActorId -- ^ the original leader from run start
, runMembers :: [ActorId] -- ^ the list of actors that take part
, runInitial :: Bool -- ^ initial run continuation by any
-- run participant, including run leader
, runStopMsg :: Maybe Text -- ^ message with the next stop reason
, runWaiting :: Int -- ^ waiting for others to move out of the way
}
deriving Show
-- | Last lore being aimed at.
data ChosenLore =
ChosenLore [(ActorId, Actor)] [(ItemId, ItemQuant)]
| ChosenNothing
emptySessionUI :: UIOptions -> SessionUI
emptySessionUI sUIOptions =
SessionUI
{ sreqPending = Nothing
, sreqDelay = ReqDelayNot
, sreqQueried = False
, sregainControl = False
, sxhair = Nothing
, sxhairGoTo = Nothing
, sactorUI = EM.empty
, sitemUI = EM.empty
, sroles = ItemRoles $ EM.fromDistinctAscList
$ zip [minBound..maxBound] (repeat ES.empty)
, slastItemMove = Nothing
, schanF = ChanFrontend $ const $
error $ "emptySessionUI: ChanFrontend" `showFailure` ()
, sccui = emptyCCUI
, sUIOptions
, saimMode = Nothing
, sxhairMoused = True
, sitemSel = Nothing
, sselected = ES.empty
, srunning = Nothing
, shistory = emptyHistory 0
, svictories = EM.empty
, scampings = ES.empty
, srestarts = ES.empty
, spointer = PointUI 0 0
, sautoYes = False
, smacroFrame = emptyMacroFrame
, smacroStack = []
, slastLost = ES.empty
, swaitTimes = 0
, swasAutomated = False
, smarkVision = 1
, smarkSmell = True
, snxtScenario = 0
, scurTutorial = False
, snxtTutorial = True -- matches @snxtScenario = 0@
, soverrideTut = Nothing
, susedHints = S.empty
, smuteMessages = False
, smenuIxMap = M.empty
, schosenLore = ChosenNothing
, sdisplayNeeded = False
, sturnDisplayed = False
, sreportNull = True
, sstart = 0
, sgstart = 0
, sallTime = timeZero
, snframes = 0
, sallNframes = 0
, srandomUI = SM.mkSMGen 0
}
emptyMacroFrame :: KeyMacroFrame
emptyMacroFrame = KeyMacroFrame (Right mempty) mempty Nothing
cycleMarkVision :: Int -> SessionUI -> SessionUI
cycleMarkVision delta sess =
sess {smarkVision = (smarkVision sess + delta) `mod` 3}
toggleMarkSmell :: SessionUI -> SessionUI
toggleMarkSmell sess = sess {smarkSmell = not (smarkSmell sess)}
cycleOverrideTut :: Int -> SessionUI -> SessionUI
cycleOverrideTut delta sess =
let ordering = cycle [Nothing, Just False, Just True]
in sess {soverrideTut =
let ix = fromJust $ elemIndex (soverrideTut sess) ordering
in ordering !! (ix + delta)}
getActorUI :: ActorId -> SessionUI -> ActorUI
getActorUI aid sess =
EM.findWithDefault (error $ "" `showFailure` (aid, sactorUI sess)) aid
$ sactorUI sess
instance Binary SessionUI where
put SessionUI{..} = do
put sxhair
put sactorUI
put sitemUI
put sroles
put sUIOptions
put saimMode
put sitemSel
put sselected
put srunning
put $ archiveReport shistory
-- avoid displaying ending messages again at game start
put svictories
put scampings
put srestarts
put smarkVision
put smarkSmell
put snxtScenario
put scurTutorial
put snxtTutorial
put soverrideTut
put susedHints
put (show srandomUI)
get = do
sxhair <- get
sactorUI <- get
sitemUI <- get
sroles <- get
sUIOptions <- get -- is overwritten ASAP, but useful for, e.g., crash debug
saimMode <- get
sitemSel <- get
sselected <- get
srunning <- get
shistory <- get
svictories <- get
scampings <- get
srestarts <- get
smarkVision <- get
smarkSmell <- get
snxtScenario <- get
scurTutorial <- get
snxtTutorial <- get
soverrideTut <- get
susedHints <- get
g <- get
let sreqPending = Nothing
sreqDelay = ReqDelayNot
sreqQueried = False
sregainControl = False
sxhairGoTo = Nothing
slastItemMove = Nothing
schanF = ChanFrontend $ const $
error $ "Binary: ChanFrontend" `showFailure` ()
sccui = emptyCCUI
sxhairMoused = True
spointer = PointUI 0 0
sautoYes = False
smacroFrame = emptyMacroFrame
smacroStack = []
slastLost = ES.empty
swaitTimes = 0
swasAutomated = False
smuteMessages = False
smenuIxMap = M.empty
schosenLore = ChosenNothing
sdisplayNeeded = False -- displayed regardless
sturnDisplayed = False
sreportNull = True
sstart = 0
sgstart = 0
sallTime = timeZero
snframes = 0
sallNframes = 0
srandomUI = read g
return $! SessionUI{..}
instance Binary RunParams where
put RunParams{..} = do
put runLeader
put runMembers
put runInitial
put runStopMsg
put runWaiting
get = do
runLeader <- get
runMembers <- get
runInitial <- get
runStopMsg <- get
runWaiting <- get
return $! RunParams{..}
| null | https://raw.githubusercontent.com/LambdaHack/LambdaHack/100690c5d2eabaca985f44d220e6d660812e21d1/engine-src/Game/LambdaHack/Client/UI/SessionUI.hs | haskell | | The client UI session state.
| The information that is used across a human player playing session,
including many consecutive games in a single session,
including playing different teams. Some of it is saved, some is reset
when a new playing session starts. Nothing is tied to a faction/team,
but instead all to UI configuration and UI input and display history.
An important component is the frontend session.
^ request created by a UI query
but not yet sent to the server
^ server delayed sending query to client
or receiving request from client
^ player is now queried for a command
^ player requested to regain control
^ assigned actor UI presentations
^ assignment of roles to items
^ last item move stores
^ connection with the frontend
^ UI client content
^ UI options as set by the player
^ aiming mode
^ last mouse aiming not vacuus
^ selected item, if any, it's store and
whether to override suitability check
^ the set of currently selected actors
^ parameters of the current run, if any
^ history of messages
^ the number of games won by the UI faction per game mode
and per difficulty level
^ camped games
^ restarted games
^ mouse pointer position
^ whether to auto-clear prompts
^ the head of the key macro stack
^ the tail of the key macro stack
^ actors that just got out of sight
^ player just waited this many times
^ mark smell, if the leader can smell
^ next game scenario number
^ whether current game is a tutorial
^ whether next game is to be tutorial
^ override display of tutorial hints
^ tutorial hints already shown this game
^ whether to mute all new messages
^ indices of last used menu items
^ last lore chosen to display
^ current level needs displaying
^ a frame was already displayed this turn
^ whether no visible report created
last UI faction turn or the report
wiped out from screen since
^ this session start time
^ this game start time
^ clips from start of session
to current game start
^ this game current frame count
^ frame count from start of session
to current game start
^ current random generator for UI
| Local macro buffer frame. Predefined macros have their own in-game macro
buffer, allowing them to record in-game macro, queue actions and repeat
the last macro's action.
buffers from the stack if locally there are no actions pending to be handled.
^ record keystrokes in Left;
repeat from Right
^ actions pending to be handled
^ last pressed key
This can stay a map forever, not a vector, because it's added to often,
but never read from, except when the user requests item details.
| A collection of item identifier sets indicating what roles (possibly many)
an item has assigned.
| Current aiming mode of a client.
| In-game macros. We record menu navigation keystrokes and keystrokes
- we exclude keys that invoke
Keys are kept in the same order in which they're meant to be replayed,
| Parameters of the current run.
^ the original leader from run start
^ the list of actors that take part
^ initial run continuation by any
run participant, including run leader
^ message with the next stop reason
^ waiting for others to move out of the way
| Last lore being aimed at.
matches @snxtScenario = 0@
avoid displaying ending messages again at game start
is overwritten ASAP, but useful for, e.g., crash debug
displayed regardless | # LANGUAGE DeriveGeneric , GeneralizedNewtypeDeriving #
module Game.LambdaHack.Client.UI.SessionUI
( SessionUI(..), ReqDelay(..), ItemDictUI, ItemRoles(..), AimMode(..)
, KeyMacro(..), KeyMacroFrame(..), RunParams(..), ChosenLore(..)
, emptySessionUI, emptyMacroFrame
, cycleMarkVision, toggleMarkSmell, cycleOverrideTut, getActorUI
) where
import Prelude ()
import Game.LambdaHack.Core.Prelude
import Data.Binary
import qualified Data.EnumMap.Strict as EM
import qualified Data.EnumSet as ES
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import Data.Time.Clock.POSIX
import GHC.Generics (Generic)
import qualified System.Random.SplitMix32 as SM
import Game.LambdaHack.Client.Request
import Game.LambdaHack.Client.State
import Game.LambdaHack.Client.UI.ActorUI
import Game.LambdaHack.Client.UI.ContentClientUI
import Game.LambdaHack.Client.UI.EffectDescription (DetailLevel (..))
import Game.LambdaHack.Client.UI.Frontend
import qualified Game.LambdaHack.Client.UI.Key as K
import Game.LambdaHack.Client.UI.Msg
import Game.LambdaHack.Client.UI.PointUI
import Game.LambdaHack.Client.UI.UIOptions
import Game.LambdaHack.Common.Actor
import Game.LambdaHack.Common.Faction
import Game.LambdaHack.Common.Item
import Game.LambdaHack.Common.Time
import Game.LambdaHack.Common.Types
import Game.LambdaHack.Content.ModeKind (ModeKind)
import Game.LambdaHack.Definition.Defs
data SessionUI = SessionUI
{ sreqPending :: Maybe RequestUI
from AI ASAP
^ the common xhair
^ set for last GoTo
^ assigned item first seen level
, slastItemMove :: Maybe (CStore, CStore)
, sitemSel :: Maybe (ItemId, CStore, Bool)
, sselected :: ES.EnumSet ActorId
, srunning :: Maybe RunParams
, svictories :: EM.EnumMap (ContentId ModeKind) (M.Map Challenge Int)
, smacroStack :: [KeyMacroFrame]
, slastLost :: ES.EnumSet ActorId
^ the player just exited AI automation
^ mark leader and party FOV
, smenuIxMap :: M.Map String Int
}
data ReqDelay = ReqDelayNot | ReqDelayHandled | ReqDelayAlarm
deriving Eq
Running predefined macro pushes new @KeyMacroFrame@ onto the stack . We pop
data KeyMacroFrame = KeyMacroFrame
} deriving Show
type ItemDictUI = EM.EnumMap ItemId LevelId
newtype ItemRoles = ItemRoles (EM.EnumMap SLore (ES.EnumSet ItemId))
deriving (Show, Binary)
data AimMode = AimMode
{ aimLevelId :: LevelId
, detailLevel :: DetailLevel
}
deriving (Show, Eq, Generic)
instance Binary AimMode
the @Record@ command , to avoid surprises .
i.e. the first element of the list is replayed also as the first one .
newtype KeyMacro = KeyMacro {unKeyMacro :: [K.KM]}
deriving (Show, Eq, Binary, Semigroup, Monoid)
data RunParams = RunParams
}
deriving Show
data ChosenLore =
ChosenLore [(ActorId, Actor)] [(ItemId, ItemQuant)]
| ChosenNothing
emptySessionUI :: UIOptions -> SessionUI
emptySessionUI sUIOptions =
SessionUI
{ sreqPending = Nothing
, sreqDelay = ReqDelayNot
, sreqQueried = False
, sregainControl = False
, sxhair = Nothing
, sxhairGoTo = Nothing
, sactorUI = EM.empty
, sitemUI = EM.empty
, sroles = ItemRoles $ EM.fromDistinctAscList
$ zip [minBound..maxBound] (repeat ES.empty)
, slastItemMove = Nothing
, schanF = ChanFrontend $ const $
error $ "emptySessionUI: ChanFrontend" `showFailure` ()
, sccui = emptyCCUI
, sUIOptions
, saimMode = Nothing
, sxhairMoused = True
, sitemSel = Nothing
, sselected = ES.empty
, srunning = Nothing
, shistory = emptyHistory 0
, svictories = EM.empty
, scampings = ES.empty
, srestarts = ES.empty
, spointer = PointUI 0 0
, sautoYes = False
, smacroFrame = emptyMacroFrame
, smacroStack = []
, slastLost = ES.empty
, swaitTimes = 0
, swasAutomated = False
, smarkVision = 1
, smarkSmell = True
, snxtScenario = 0
, scurTutorial = False
, soverrideTut = Nothing
, susedHints = S.empty
, smuteMessages = False
, smenuIxMap = M.empty
, schosenLore = ChosenNothing
, sdisplayNeeded = False
, sturnDisplayed = False
, sreportNull = True
, sstart = 0
, sgstart = 0
, sallTime = timeZero
, snframes = 0
, sallNframes = 0
, srandomUI = SM.mkSMGen 0
}
emptyMacroFrame :: KeyMacroFrame
emptyMacroFrame = KeyMacroFrame (Right mempty) mempty Nothing
cycleMarkVision :: Int -> SessionUI -> SessionUI
cycleMarkVision delta sess =
sess {smarkVision = (smarkVision sess + delta) `mod` 3}
toggleMarkSmell :: SessionUI -> SessionUI
toggleMarkSmell sess = sess {smarkSmell = not (smarkSmell sess)}
cycleOverrideTut :: Int -> SessionUI -> SessionUI
cycleOverrideTut delta sess =
let ordering = cycle [Nothing, Just False, Just True]
in sess {soverrideTut =
let ix = fromJust $ elemIndex (soverrideTut sess) ordering
in ordering !! (ix + delta)}
getActorUI :: ActorId -> SessionUI -> ActorUI
getActorUI aid sess =
EM.findWithDefault (error $ "" `showFailure` (aid, sactorUI sess)) aid
$ sactorUI sess
instance Binary SessionUI where
put SessionUI{..} = do
put sxhair
put sactorUI
put sitemUI
put sroles
put sUIOptions
put saimMode
put sitemSel
put sselected
put srunning
put $ archiveReport shistory
put svictories
put scampings
put srestarts
put smarkVision
put smarkSmell
put snxtScenario
put scurTutorial
put snxtTutorial
put soverrideTut
put susedHints
put (show srandomUI)
get = do
sxhair <- get
sactorUI <- get
sitemUI <- get
sroles <- get
saimMode <- get
sitemSel <- get
sselected <- get
srunning <- get
shistory <- get
svictories <- get
scampings <- get
srestarts <- get
smarkVision <- get
smarkSmell <- get
snxtScenario <- get
scurTutorial <- get
snxtTutorial <- get
soverrideTut <- get
susedHints <- get
g <- get
let sreqPending = Nothing
sreqDelay = ReqDelayNot
sreqQueried = False
sregainControl = False
sxhairGoTo = Nothing
slastItemMove = Nothing
schanF = ChanFrontend $ const $
error $ "Binary: ChanFrontend" `showFailure` ()
sccui = emptyCCUI
sxhairMoused = True
spointer = PointUI 0 0
sautoYes = False
smacroFrame = emptyMacroFrame
smacroStack = []
slastLost = ES.empty
swaitTimes = 0
swasAutomated = False
smuteMessages = False
smenuIxMap = M.empty
schosenLore = ChosenNothing
sturnDisplayed = False
sreportNull = True
sstart = 0
sgstart = 0
sallTime = timeZero
snframes = 0
sallNframes = 0
srandomUI = read g
return $! SessionUI{..}
instance Binary RunParams where
put RunParams{..} = do
put runLeader
put runMembers
put runInitial
put runStopMsg
put runWaiting
get = do
runLeader <- get
runMembers <- get
runInitial <- get
runStopMsg <- get
runWaiting <- get
return $! RunParams{..}
|
4e008f7978e9f5c4cf44c172aebd673e6f16665227614ccf3d63b8499da128be | kpblc2000/KpblcLispLib | _kpblc-ent-create-layer.lsp | (defun _kpblc-ent-create-layer (name param-list / sub res tmp)
;|
* Ôóíêöèÿ ñîçäàíèÿ ñëîÿ ïî èìåíè è äîï.ïàðàìåòðàì
* Ïàðàìåòðû âûçîâà:
name ; Èìÿ ñîçäàâàåìîãî ñëîÿ
Ñïèñîê ñâîéñòâ ñîçäàâàåìîãî ñëîÿ
ICA . nil - > 7 . íàäî ïåðåäàâàòü ñïèñîê Red Green Blue
("lineweight" . <Âåñ>); nil -> 9
("linetype" . <Òèï>) ; nil -> "Continuous"
("linetypefile" . <Ôàéë, îòêóäà ãðóçèòü îïèñàíèÿ òèïîâ ëèíèé>) ; nil -> acadiso.lin
nil - > íå ìåíÿåòñÿ äëÿ ñóùåñòâóþùåãî èëè " " äëÿ íîâîãî ñëîÿ
("where" . <Óêàçàòåëü íà äîêóìåíò, â êîòîðîì íàäî ñîçäàâàòü ñëîé>) ; nil -> òåêóùèé äîêóìåíò
nil - > ïå÷àòàòüñÿ
nil - > Åñëè ñëîé ñóùåñòâóåò , îí " êàê åñòü " . t - > íàñòðîéêè ñëîÿ ê ïåðåäàííûì â param - list
)
* Ïðèìåðû âûçîâà:
(_kpblc-ent-create-layer "qwer" nil)
(_kpblc-ent-create-layer "qwer1" '(("color" . 8)))
(_kpblc-ent-create-layer "qwer2" '(("color" 120 80 30)))
(_kpblc-ent-create-layer "qwer2" '(("color" 120 80 50) ("update" . t)))
|;
(if (and name (= (type name) 'str))
(progn
(foreach elem (list '("color" . 7)
'("lineweight" . 9)
'("linetype" . "Continuous")
'("linetypefile" . "acadiso.lin")
(cons "where" *kpblc-adoc*)
) ;_ end of list
(if (not (cdr (assoc (car elem) param-list)))
(setq param-list (cons elem param-list))
) ;_ end of if
) ;_ end of foreach
(if (/= (type (vl-catch-all-apply
(function (lambda () (vla-item (vla-get-layers (cdr (assoc "where" param-list))) name)))
) ;_ end of vl-catch-all-apply
) ;_ end of type
'vla-object
) ;_ end of /=
(setq param-list (_kpblc-list-add-or-subst param-list "update" t))
) ;_ end of if
(_kpblc-error-catch
(function
(lambda ()
(setq res (vla-add (vla-get-layers (cdr (assoc "where" param-list))) name))
(if (cdr (assoc "update" param-list))
(progn
(if (= (type (cdr (assoc "color" param-list))) 'list)
(apply (function _kpblc-ent-modify-truecolor-set)
(cons res (cdr (assoc "color" param-list)))
) ;_ end of apply
(vla-put-color res (max 1 (_kpblc-conv-value-to-int (cdr (assoc "color" param-list)))))
) ;_ end of if
(vla-put-lineweight res (cdr (assoc "lineweight" param-list)))
(vla-put-linetype
res
(_kpblc-linetype-load
(cdr (assoc "where" param-list))
(cdr (assoc "linetype" param-list))
(cdr (assoc "linetypefile" param-list))
) ;_ end of _kpblc-linetype-load
) ;_ end of vla-put-linetype
(vla-put-plottable res (_kpblc-conv-value-bool-to-vla (not (cdr (assoc "noplot" param-list)))))
(if (cdr (assoc "description" param-list))
(vla-put-description res (cdr (assoc "description" param-list)))
) ;_ end of if
_ end of progn
) ;_ end of if
res
) ;_ end of lambda
) ;_ end of function
'(lambda (x)
(_kpblc-error-print (strcat "Ñîçäàíèå ñëîÿ " name) x)
(if res
(vl-catch-all-apply (function (lambda () (vla-delete res))))
) ;_ end of if
(setq res nil)
) ;_ end of lambda
) ;_ end of _kpblc-error-catch
_ end of progn
) ;_ end of if
res
) ;_ end of defun
| null | https://raw.githubusercontent.com/kpblc2000/KpblcLispLib/9d62aaa7d3888c71799f5ad3fd67bbdbd605fe23/lsp/ent/create/layer/_kpblc-ent-create-layer.lsp | lisp | |
Èìÿ ñîçäàâàåìîãî ñëîÿ
nil -> 9
nil -> "Continuous"
nil -> acadiso.lin
nil -> òåêóùèé äîêóìåíò
_ end of list
_ end of if
_ end of foreach
_ end of vl-catch-all-apply
_ end of type
_ end of /=
_ end of if
_ end of apply
_ end of if
_ end of _kpblc-linetype-load
_ end of vla-put-linetype
_ end of if
_ end of if
_ end of lambda
_ end of function
_ end of if
_ end of lambda
_ end of _kpblc-error-catch
_ end of if
_ end of defun
| (defun _kpblc-ent-create-layer (name param-list / sub res tmp)
* Ôóíêöèÿ ñîçäàíèÿ ñëîÿ ïî èìåíè è äîï.ïàðàìåòðàì
* Ïàðàìåòðû âûçîâà:
Ñïèñîê ñâîéñòâ ñîçäàâàåìîãî ñëîÿ
ICA . nil - > 7 . íàäî ïåðåäàâàòü ñïèñîê Red Green Blue
nil - > íå ìåíÿåòñÿ äëÿ ñóùåñòâóþùåãî èëè " " äëÿ íîâîãî ñëîÿ
nil - > ïå÷àòàòüñÿ
nil - > Åñëè ñëîé ñóùåñòâóåò , îí " êàê åñòü " . t - > íàñòðîéêè ñëîÿ ê ïåðåäàííûì â param - list
)
* Ïðèìåðû âûçîâà:
(_kpblc-ent-create-layer "qwer" nil)
(_kpblc-ent-create-layer "qwer1" '(("color" . 8)))
(_kpblc-ent-create-layer "qwer2" '(("color" 120 80 30)))
(_kpblc-ent-create-layer "qwer2" '(("color" 120 80 50) ("update" . t)))
(if (and name (= (type name) 'str))
(progn
(foreach elem (list '("color" . 7)
'("lineweight" . 9)
'("linetype" . "Continuous")
'("linetypefile" . "acadiso.lin")
(cons "where" *kpblc-adoc*)
(if (not (cdr (assoc (car elem) param-list)))
(setq param-list (cons elem param-list))
(if (/= (type (vl-catch-all-apply
(function (lambda () (vla-item (vla-get-layers (cdr (assoc "where" param-list))) name)))
'vla-object
(setq param-list (_kpblc-list-add-or-subst param-list "update" t))
(_kpblc-error-catch
(function
(lambda ()
(setq res (vla-add (vla-get-layers (cdr (assoc "where" param-list))) name))
(if (cdr (assoc "update" param-list))
(progn
(if (= (type (cdr (assoc "color" param-list))) 'list)
(apply (function _kpblc-ent-modify-truecolor-set)
(cons res (cdr (assoc "color" param-list)))
(vla-put-color res (max 1 (_kpblc-conv-value-to-int (cdr (assoc "color" param-list)))))
(vla-put-lineweight res (cdr (assoc "lineweight" param-list)))
(vla-put-linetype
res
(_kpblc-linetype-load
(cdr (assoc "where" param-list))
(cdr (assoc "linetype" param-list))
(cdr (assoc "linetypefile" param-list))
(vla-put-plottable res (_kpblc-conv-value-bool-to-vla (not (cdr (assoc "noplot" param-list)))))
(if (cdr (assoc "description" param-list))
(vla-put-description res (cdr (assoc "description" param-list)))
_ end of progn
res
'(lambda (x)
(_kpblc-error-print (strcat "Ñîçäàíèå ñëîÿ " name) x)
(if res
(vl-catch-all-apply (function (lambda () (vla-delete res))))
(setq res nil)
_ end of progn
res
|
a19a3f692e83e9595069281a9faa19e2eda4bf830ae942d994d20120dbbaf3aa | toddaaro/advanced-dan | test1.scm |
(define run
(lambda ()
(let (;[gk 'hukarz]
[eng (make-engine (lambda ()
(+ 5
(call/cc (lambda (k)
(set! gk k)
(engine-return k 'hukarz)
120)))))])
(eng 10000
(lambda (ticks . (cont . values))
(list ticks values
(let ([e (make-engine (lambda () (cont 1)))])
(e 25 list (lambda (x) x)))))
(lambda (x) x)))))
(define run2
(lambda ()
(let ([eng (make-engine (lambda ()
(+ 5 (begin
(engine-block)
120))))])
(eng 100
list
(lambda (x)
(call/cc (lambda (k)
(k 1)))))))) | null | https://raw.githubusercontent.com/toddaaro/advanced-dan/5d6c0762d998aa37774e0414a0f37404e804b536/amb/test1.scm | scheme | [gk 'hukarz] |
(define run
(lambda ()
[eng (make-engine (lambda ()
(+ 5
(call/cc (lambda (k)
(set! gk k)
(engine-return k 'hukarz)
120)))))])
(eng 10000
(lambda (ticks . (cont . values))
(list ticks values
(let ([e (make-engine (lambda () (cont 1)))])
(e 25 list (lambda (x) x)))))
(lambda (x) x)))))
(define run2
(lambda ()
(let ([eng (make-engine (lambda ()
(+ 5 (begin
(engine-block)
120))))])
(eng 100
list
(lambda (x)
(call/cc (lambda (k)
(k 1)))))))) |
ee345c9b328d3efe84c6cfe69c0ad946c8866ccd86dec02d3b5307f59a7e7685 | pelzlpj/orpie | interface_draw.ml | Orpie -- a fullscreen RPN calculator for the console
* Copyright ( C ) 2003 - 2004 , 2005 , 2006 - 2007 , 2010 , 2018
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU General Public License , Version 3 ,
* as published by the Free Software Foundation .
*
* 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 , see < / > .
*
* Please send bug reports , patches , etc . to at
* < > .
* Copyright (C) 2003-2004, 2005, 2006-2007, 2010, 2018 Paul Pelzl
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, Version 3,
* as published by the Free Software Foundation.
*
* 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, see </>.
*
* Please send bug reports, patches, etc. to Paul Pelzl at
* <>.
*)
(* interface_draw.ml
* This file has all code concerned with rendering the stack, help panel,
* and data entry line. *)
open Curses;;
open Printf;;
open Rpc_stack;;
open Operations;;
open Interface;;
type abbrev_help_display_t = {functions : string list;
modes : string list;
misc : string list}
(* display the stack, where the bottom line of the display
* corresponds to stack level 'stack_bottom_row' *)
let draw_stack (iface : interface_state_t) =
let print_numbered_line l_num =
let num_len =
String.length (string_of_int (pred (iface.stack_bottom_row +
iface.scr.sw_lines)))
in
if num_len <= 2 then
(sprintf "%2d: %s" l_num)
else if num_len = 3 then
(sprintf "%3d: %s" l_num)
else if num_len = 4 then
(sprintf "%4d: %s" l_num)
else
(* if the line number is really huge, truncate to least
* significant digits *)
let l_num_str = string_of_int l_num in
let str_len = String.length l_num_str in
let trunc_num = Str.string_after l_num_str (str_len - 4) in
(sprintf "%s: %s" trunc_num)
in
(* if there is no help window, then print the calculator mode
* information above the stack *)
let num_stack_lines =
begin match iface.scr.help_win with
|Some win ->
iface.scr.sw_lines
|None ->
let modes = iface.calc#get_modes () in
assert (wmove iface.scr.stack_win 0 0);
wclrtoeol iface.scr.stack_win;
wattron iface.scr.stack_win WA.bold;
assert (mvwaddstr iface.scr.stack_win 0 2 "angle: base: complex:");
wattroff iface.scr.stack_win WA.bold;
let angle_str = match modes.angle with
|Rad -> "RAD"
|Deg -> "DEG" in
assert (mvwaddstr iface.scr.stack_win 0 9 angle_str);
let base_str = match modes.base with
|Bin -> "BIN"
|Oct -> "OCT"
|Hex -> "HEX"
|Dec -> "DEC" in
assert (mvwaddstr iface.scr.stack_win 0 20 base_str);
let complex_str = match modes.complex with
|Rect -> "REC"
|Polar -> "POL" in
assert (mvwaddstr iface.scr.stack_win 0 34 complex_str);
assert (mvwaddstr iface.scr.stack_win 1 0 (String.make (iface.scr.sw_cols) '-'));
iface.scr.sw_lines - 2
end
in
(* display the stack data itself *)
for line = iface.stack_bottom_row to
pred (iface.stack_bottom_row + num_stack_lines) do
let s = iface.calc#get_display_line line in
let len = String.length s in
assert (wmove iface.scr.stack_win
(iface.scr.sw_lines + iface.stack_bottom_row - 1 - line) 0);
wclrtoeol iface.scr.stack_win;
if line = iface.stack_selection &&
iface.interface_mode = BrowsingMode then
wattron iface.scr.stack_win WA.reverse
else
();
if len > iface.scr.sw_cols - 7 then begin
(* need to truncate the string *)
let line_string =
if line = iface.stack_selection &&
iface.interface_mode = BrowsingMode then
let sub_s =
if iface.horiz_scroll < len - iface.scr.sw_cols + 7 then
String.sub s iface.horiz_scroll (iface.scr.sw_cols - 7)
else
String.sub s (len - iface.scr.sw_cols + 7)
(iface.scr.sw_cols - 7)
in
print_numbered_line line sub_s
else
let sub_s = String.sub s 0 (iface.scr.sw_cols - 10) in
print_numbered_line line (sub_s ^ "...")
in
assert (waddstr iface.scr.stack_win line_string)
end else begin
let spacer = String.make (iface.scr.sw_cols - 7 - len) ' ' in
let line_string = print_numbered_line line (spacer ^ s) in
assert (waddstr iface.scr.stack_win line_string)
end;
if line = iface.stack_selection &&
iface.interface_mode = BrowsingMode then
wattroff iface.scr.stack_win WA.reverse
else
();
done;
assert (wnoutrefresh iface.scr.stack_win);
assert (wmove iface.scr.entry_win (iface.scr.ew_lines - 1) (iface.scr.ew_cols - 1))
let draw_update_stack iface =
draw_stack iface;
assert (doupdate ())
(* display the data that the user is in the process of entering *)
let draw_entry (iface : interface_state_t) =
assert (mvwaddstr iface.scr.entry_win 0 0 (String.make iface.scr.ew_cols '-'));
assert (wmove iface.scr.entry_win 1 0);
wclrtoeol iface.scr.entry_win;
Safely draw a string into the entry window , with " ... " when
* truncation occurs . Highlight the first ' highlight_len '
* characters .
* truncation occurs. Highlight the first 'highlight_len'
* characters. *)
let draw_entry_string str highlight_len =
let len_str = String.length str in
begin
if len_str > iface.scr.ew_cols - 1 then
let trunc_str = String.sub str (len_str - iface.scr.ew_cols + 4)
(iface.scr.ew_cols - 4) in
assert (mvwaddstr iface.scr.entry_win 1 0 ("..." ^ trunc_str))
else
if highlight_len <= len_str then
begin
highlight the first ' highlight_len ' characters
wattron iface.scr.entry_win WA.bold;
assert (mvwaddstr iface.scr.entry_win 1 (iface.scr.ew_cols - len_str - 1)
(Str.string_before str (highlight_len)));
wattroff iface.scr.entry_win WA.bold;
assert (mvwaddstr iface.scr.entry_win 1 (iface.scr.ew_cols - len_str -
1 + highlight_len) (Str.string_after str (highlight_len)))
end
else
assert (mvwaddstr iface.scr.entry_win 1 (iface.scr.ew_cols - len_str - 1) str)
end;
assert (wnoutrefresh iface.scr.entry_win)
in
(* draw a string for a single floating-point number *)
let get_float_str is_current mantissa exponent =
let sign_space =
if String.length exponent > 0 then
match exponent.[0] with
|'-' -> ""
|'+' -> ""
|_ -> " "
else
" "
in
if (is_current && iface.is_entering_exponent) || String.length exponent > 0 then
mantissa ^ " x10^" ^ sign_space ^ exponent
else if is_current || String.length mantissa > 0 then
mantissa
else
"0"
in
(* get a string representation of the data that is in the entry buffer *)
let data_string =
match iface.entry_type with
|IntEntry ->
if iface.is_entering_base then
"# " ^ iface.int_entry_buffer ^ "`" ^ iface.int_base_string
else
"# " ^ iface.int_entry_buffer
|FloatEntry ->
let mantissa_str = iface.gen_buffer.(0).re_mantissa
and exponent_str = iface.gen_buffer.(0).re_exponent in
let ff = get_float_str true mantissa_str exponent_str in
if iface.is_entering_units then
ff ^ "_" ^ iface.units_entry_buffer
else
ff
|ComplexEntry ->
let buffer = iface.gen_buffer.(0) in
let cc =
if iface.is_entering_imag then
let temp = get_float_str false buffer.re_mantissa buffer.re_exponent in
let re_str =
if String.length temp > 0 then temp
else "0"
in
let im_str = get_float_str true buffer.im_mantissa buffer.im_exponent in
match buffer.is_polar with
|false ->
"(" ^ re_str ^ ", " ^ im_str ^ ")"
|true ->
"(" ^ re_str ^ " <" ^ im_str ^ ")"
else
let re_str = get_float_str true buffer.re_mantissa buffer.re_exponent in
"(" ^ re_str ^ ")"
in
if iface.is_entering_units then
cc ^ "_" ^ iface.units_entry_buffer
else
cc
|FloatMatrixEntry ->
let ss = ref "[[" in
for el = 0 to pred iface.curr_buf do
let temp_re = get_float_str false iface.gen_buffer.(el).re_mantissa
iface.gen_buffer.(el).re_exponent in
if iface.has_multiple_rows && ((succ el) mod iface.matrix_cols) = 0 then
ss := !ss ^ temp_re ^ "]["
else
ss := !ss ^ temp_re ^ ", "
done;
let temp_re = get_float_str true iface.gen_buffer.(iface.curr_buf).re_mantissa
iface.gen_buffer.(iface.curr_buf).re_exponent in
ss := !ss ^ temp_re ^ "]]";
if iface.is_entering_units then
!ss ^ "_" ^ iface.units_entry_buffer
else
!ss
|ComplexMatrixEntry ->
let ss = ref "[[" in
for el = 0 to pred iface.curr_buf do
let temp_re = get_float_str false iface.gen_buffer.(el).re_mantissa
iface.gen_buffer.(el).re_exponent and
temp_im = get_float_str false iface.gen_buffer.(el).im_mantissa
iface.gen_buffer.(el).im_exponent in
(if iface.has_multiple_rows && ((succ el) mod iface.matrix_cols) = 0 then
match iface.gen_buffer.(el).is_polar with
|false ->
ss := !ss ^ "(" ^ temp_re ^ ", " ^ temp_im ^ ")]["
|true ->
ss := !ss ^ "(" ^ temp_re ^ " <" ^ temp_im ^ ")]["
else
match iface.gen_buffer.(el).is_polar with
|false ->
ss := !ss ^ "(" ^ temp_re ^ ", " ^ temp_im ^ "), "
|true ->
ss := !ss ^ "(" ^ temp_re ^ " <" ^ temp_im ^ "), ")
done;
(if iface.is_entering_imag then
let temp_re = get_float_str false iface.gen_buffer.(iface.curr_buf).re_mantissa
iface.gen_buffer.(iface.curr_buf).re_exponent and
temp_im = get_float_str true iface.gen_buffer.(iface.curr_buf).im_mantissa
iface.gen_buffer.(iface.curr_buf).im_exponent in
match iface.gen_buffer.(iface.curr_buf).is_polar with
|false ->
ss := !ss ^ "(" ^ temp_re ^ ", " ^ temp_im ^ ")]]"
|true ->
ss := !ss ^ "(" ^ temp_re ^ " <" ^ temp_im ^ ")]]"
else
let temp_re = get_float_str true iface.gen_buffer.(iface.curr_buf).re_mantissa
iface.gen_buffer.(iface.curr_buf).re_exponent in
ss := !ss ^ "(" ^ temp_re ^ ")]]");
if iface.is_entering_units then
!ss ^ "_" ^ iface.units_entry_buffer
else
!ss
|VarEntry ->
"@ " ^ iface.variable_entry_buffer
in
begin match iface.interface_mode with
|StandardEditMode ->
draw_entry_string data_string 0
|IntEditMode ->
draw_entry_string data_string 0
|AbbrevEditMode ->
let first_abbrev_match =
if iface.matched_abbrev_list = [] then ""
else List.hd iface.matched_abbrev_list
in
let highlight_len = String.length iface.abbrev_entry_buffer in
if highlight_len = 0 then
begin match iface.abbrev_or_const with
|IsAbbrev -> draw_entry_string "<enter command abbreviation>" 0
|IsConst -> draw_entry_string "<enter constant symbol>" 0
end
else
begin match iface.abbrev_or_const with
|IsAbbrev ->
let is_function =
match (Rcfile.translate_abbrev first_abbrev_match) with
|Function ff -> true
|_ -> false
in
if is_function then
draw_entry_string (first_abbrev_match ^ "( )") highlight_len
else
draw_entry_string first_abbrev_match highlight_len
|IsConst ->
draw_entry_string first_abbrev_match highlight_len
end
|BrowsingMode ->
()
|VarEditMode ->
if String.length iface.variable_entry_buffer = 0 then
draw_entry_string "<enter variable name>" 0
else
draw_entry_string data_string 0
|UnitEditMode ->
draw_entry_string data_string 0
end;
assert (wmove iface.scr.entry_win (iface.scr.ew_lines - 1) (iface.scr.ew_cols - 1))
let draw_update_entry iface =
draw_entry iface;
assert (doupdate ())
(* create the lists of abbreviations to display in the abbrev command
* help screen *)
let generate_abbrev_help () =
let rec trunc_list lst n =
if n = 0 then
[]
else
match lst with
|[] ->
[]
|head :: tail ->
head :: (trunc_list tail (pred n))
in
let get_abbr op =
try Rcfile.abbrev_of_operation op
with Not_found -> ""
in
let functions_str =
(get_abbr (Function Sin)) ^ " " ^
(get_abbr (Function Asin)) ^ " " ^
(get_abbr (Function Cos)) ^ " " ^
(get_abbr (Function Acos)) ^ " " ^
(get_abbr (Function Tan)) ^ " " ^
(get_abbr (Function Atan)) ^ " " ^
(get_abbr (Function Exp)) ^ " " ^
(get_abbr (Function Ln)) ^ " " ^
(get_abbr (Function Ten_x)) ^ " " ^
(get_abbr (Function Log10)) ^ " " ^
(get_abbr (Function Sq)) ^ " " ^
(get_abbr (Function Sqrt)) ^ " " ^
(get_abbr (Function Inv)) ^ " " ^
(get_abbr (Function Gamma)) ^ " " ^
(get_abbr (Function LnGamma)) ^ " " ^
(get_abbr (Function Erf)) ^ " " ^
(get_abbr (Function Erfc)) ^ " " ^
(get_abbr (Function Transpose)) ^ " " ^
(get_abbr (Function Re)) ^ " " ^
(get_abbr (Function Im)) ^ " " ^
(get_abbr (Function Mod)) ^ " " ^
(get_abbr (Function Floor)) ^ " " ^
(get_abbr (Function Ceiling)) ^ " " ^
(get_abbr (Function ToInt)) ^ " " ^
(get_abbr (Function ToFloat)) ^ " " ^
(get_abbr (Function Eval)) ^ " " ^
(get_abbr (Function Store)) ^ " " ^
(get_abbr (Function Purge))
in
let functions_str_wrap = trunc_list
(Utility.wordwrap_nspace functions_str 34 2) 5 in
let modes_str =
(get_abbr (Command SetRadians)) ^ " " ^
(get_abbr (Command SetDegrees)) ^ " " ^
(get_abbr (Command SetBin)) ^ " " ^
(get_abbr (Command SetOct)) ^ " " ^
(get_abbr (Command SetDec)) ^ " " ^
(get_abbr (Command SetHex)) ^ " " ^
(get_abbr (Command SetRect)) ^ " " ^
(get_abbr (Command SetPolar))
in
let modes_str_wrap = trunc_list
(Utility.wordwrap_nspace modes_str 34 2) 2 in
let misc_str =
(get_abbr (Command EnterPi)) ^ " " ^
(get_abbr (Command Undo)) ^ " " ^
(get_abbr (Command View))
in
let misc_str_wrap = trunc_list
(Utility.wordwrap_nspace misc_str 34 2) 1 in
{functions = functions_str_wrap;
modes = modes_str_wrap;
misc = misc_str_wrap}
(* create the list of constants to display in the abbrev command
* help screen *)
let generate_const_help () =
let rec trunc_list lst n =
if n = 0 then
[]
else
match lst with
|[] ->
[]
|head :: tail ->
head :: (trunc_list tail (pred n))
in
let rec make_symbols_string symbols_list symbols_str =
match symbols_list with
| [] ->
symbols_str
| head :: tail ->
make_symbols_string tail (head ^ " " ^ symbols_str)
in
let symbols = make_symbols_string !Rcfile.constant_symbols "" in
trunc_list (Utility.wordwrap_nspace symbols 34 2) 5
(* draw the help page in standard entry mode *)
let draw_help_standard iface win mvwaddstr_safe try_find =
if iface.help_page = 0 then begin
wattron win WA.bold;
assert (mvwaddstr win 5 0 "Common Operations:");
wattroff win WA.bold;
mvwaddstr_safe win 6 2 ("enter : " ^
try_find (Edit Enter));
mvwaddstr_safe win 7 2 ("drop : " ^
try_find (Command Drop));
mvwaddstr_safe win 8 2 ("swap : " ^
try_find (Command Swap));
mvwaddstr_safe win 9 2 ("backspace: " ^
try_find (Edit Backspace));
mvwaddstr_safe win 10 2 ("add : " ^
try_find (Function Add));
mvwaddstr_safe win 11 2 ("subtract : " ^
try_find (Function Sub));
mvwaddstr_safe win 12 2 ("multiply : " ^
try_find (Function Mult));
mvwaddstr_safe win 13 2 ("divide : " ^
try_find (Function Div));
mvwaddstr_safe win 14 2 ("y^x : " ^
try_find (Function Pow));
mvwaddstr_safe win 15 2 ("negation : " ^
try_find (Function Neg));
wattron win WA.bold;
mvwaddstr_safe win 16 0 "Miscellaneous:";
wattroff win WA.bold;
mvwaddstr_safe win 17 2 ("scientific notation : " ^
try_find (Edit SciNotBase));
mvwaddstr_safe win 18 2 ("abbreviation entry mode : " ^
try_find (Command BeginAbbrev));
mvwaddstr_safe win 19 2 ("stack browsing mode : " ^
try_find (Command BeginBrowse));
mvwaddstr_safe win 20 2 ("refresh display : " ^
try_find (Command Refresh));
mvwaddstr_safe win 21 2 ("quit : " ^
try_find (Command Quit));
assert (wnoutrefresh win)
end else begin
let adjust_len s len =
if String.length s < len then
s ^ (String.make (len - (String.length s)) ' ')
else
Str.string_before s len
in
let make_string colon_pos key_string abbr =
(adjust_len key_string colon_pos) ^ ": " ^ abbr
in
wattron win WA.bold;
mvwaddstr_safe win 5 0 "Autobindings:";
wattroff win WA.bold;
if Array.length !Rcfile.autobind_keys <= 0 then
mvwaddstr_safe win 6 2 "(none)"
else
for i = 0 to pred (min (iface.scr.hw_lines - 6) (Array.length
!Rcfile.autobind_keys)) do
let (key, key_string, bound_f, age) = !Rcfile.autobind_keys.(i) in
let abbr = match bound_f with
|None -> "(none)"
|Some op -> Rcfile.abbrev_of_operation op
in
mvwaddstr_safe win (i + 6) 2 (make_string 12 key_string abbr)
done;
assert (wnoutrefresh win)
end
(* draw help page in integer editing mode *)
let draw_help_intedit iface win mvwaddstr_safe try_find =
wattron win WA.bold;
mvwaddstr_safe win 5 0 "Integer Editing Operations:";
wattroff win WA.bold;
mvwaddstr_safe win 6 2 ("enter : " ^
try_find (Edit Enter));
mvwaddstr_safe win 7 2 ("set base : " ^
try_find (Edit SciNotBase));
mvwaddstr_safe win 8 2 ("cancel : " ^
try_find (IntEdit IntEditExit));
assert (wnoutrefresh win)
(* draw help page in abbrev/constant entry mode *)
let draw_help_abbrev iface win mvwaddstr_safe try_find =
if String.length iface.abbrev_entry_buffer = 0 then begin
let abbr_strings = generate_abbrev_help () in
let const_strings = generate_const_help () in
let rec print_help_lines lines v_pos =
begin match lines with
|[] ->
()
|head :: tail ->
mvwaddstr_safe win v_pos 2 head;
print_help_lines tail (succ v_pos)
end
in
begin match iface.abbrev_or_const with
|IsAbbrev ->
wattron win WA.bold;
mvwaddstr_safe win 5 0 "Abbreviations:";
wattroff win WA.bold;
mvwaddstr_safe win 6 1 "Common Functions:";
print_help_lines abbr_strings.functions 7;
mvwaddstr_safe win 13 1 "Change Modes:";
print_help_lines abbr_strings.modes 14;
mvwaddstr_safe win 17 1 "Miscellaneous:";
print_help_lines abbr_strings.misc 18;
mvwaddstr_safe win 20 1 ("execute abbreviation : " ^
try_find (Abbrev AbbrevEnter));
mvwaddstr_safe win 21 1 ("cancel abbreviation : " ^
try_find (Abbrev AbbrevExit));
|IsConst ->
wattron win WA.bold;
mvwaddstr_safe win 5 0 "Constants:";
wattroff win WA.bold;
print_help_lines const_strings 7;
mvwaddstr_safe win 12 1 ("enter constant : " ^
try_find (Abbrev AbbrevEnter));
end;
assert (wnoutrefresh win)
end else begin
wattron win WA.bold;
assert (mvwaddstr win 5 0 "Matched Abbreviations:");
wattroff win WA.bold;
let highlight_len = String.length iface.abbrev_entry_buffer in
let rec draw_matches v_pos match_list =
if v_pos < iface.scr.hw_lines then
begin match match_list with
|[] ->
()
|m :: tail ->
begin
highlight the first ' highlight_len ' characters
wattron win WA.bold;
mvwaddstr_safe win v_pos 2
(Str.string_before m (highlight_len));
wattroff win WA.bold;
mvwaddstr_safe win v_pos (2 + highlight_len)
(Str.string_after m (highlight_len));
draw_matches (succ v_pos) tail
end
end
else
()
in
draw_matches 6 iface.matched_abbrev_list;
assert (wnoutrefresh win)
end
(* draw help page in variable editing mode *)
let draw_help_varedit iface win mvwaddstr_safe try_find =
wattron win WA.bold;
mvwaddstr_safe win 5 0 "Variable Mode Commands:";
wattroff win WA.bold;
mvwaddstr_safe win 6 2 ("enter variable : " ^
try_find (VarEdit VarEditEnter));
mvwaddstr_safe win 7 2 ("complete variable: " ^
try_find (VarEdit VarEditComplete));
mvwaddstr_safe win 8 2 ("cancel entry : " ^
try_find (VarEdit VarEditExit));
wattron win WA.bold;
mvwaddstr_safe win 10 0 "Matched variables:";
wattroff win WA.bold;
let highlight_len =
begin match iface.completion with
|None -> String.length iface.variable_entry_buffer
|Some _ -> 0
end
in
let rec draw_matches v_pos match_list count =
if v_pos < iface.scr.hw_lines then
begin match match_list with
|[] ->
()
|m :: tail ->
begin match iface.completion with
|None ->
highlight the first ' highlight_len ' characters
wattron win WA.bold;
mvwaddstr_safe win v_pos 2
(Str.string_before m (highlight_len));
wattroff win WA.bold;
mvwaddstr_safe win v_pos (2 + highlight_len)
(Str.string_after m (highlight_len));
|Some num ->
(* highlight the entire selected match *)
if count = num then begin
wattron win WA.bold;
mvwaddstr_safe win v_pos 2 m;
wattroff win WA.bold;
end else
mvwaddstr_safe win v_pos 2 m;
end;
draw_matches (succ v_pos) tail (succ count)
end
else
()
in
if List.length iface.matched_variables = 0 then
mvwaddstr_safe win 11 2 "(none)"
else
draw_matches 11 iface.matched_variables 0;
assert (wnoutrefresh win)
(* draw help page in stack browsing mode *)
let draw_help_browsing iface win mvwaddstr_safe try_find =
wattron win WA.bold;
mvwaddstr_safe win 5 0 "Browsing Operations:";
wattroff win WA.bold;
mvwaddstr_safe win 6 2 ("prev : " ^
try_find (Browse PrevLine));
mvwaddstr_safe win 7 2 ("next : " ^
try_find (Browse NextLine));
mvwaddstr_safe win 8 2 ("scroll left : " ^
try_find (Browse ScrollLeft));
mvwaddstr_safe win 9 2 ("scroll right: " ^
try_find (Browse ScrollRight));
mvwaddstr_safe win 10 2 ("roll down : " ^
try_find (Browse RollDown));
mvwaddstr_safe win 11 2 ("roll up : " ^
try_find (Browse RollUp));
mvwaddstr_safe win 12 2 ("dup : " ^
try_find (Command Dup));
mvwaddstr_safe win 13 2 ("view : " ^
try_find (Browse ViewEntry));
mvwaddstr_safe win 14 2 ("edit : " ^
try_find (Browse EditEntry));
mvwaddstr_safe win 15 2 ("drop : " ^
try_find (Browse Drop1));
mvwaddstr_safe win 16 2 ("dropn : " ^
try_find (Browse DropN));
mvwaddstr_safe win 17 2 ("keep : " ^
try_find (Browse Keep));
mvwaddstr_safe win 18 2 ("keepn : " ^
try_find (Browse KeepN));
mvwaddstr_safe win 20 1 ("exit browsing mode: " ^
try_find (Browse EndBrowse));
assert (wnoutrefresh win)
(* display the help window *)
let draw_help (iface : interface_state_t) =
let mvwaddstr_safe w vert horiz st =
let st_trunc =
if String.length st > 36 then
Str.string_before st 36
else
st
in
assert (mvwaddstr w vert horiz st_trunc)
in
let modes = iface.calc#get_modes () in
begin match iface.scr.help_win with
|None ->
()
|Some win ->
wclear win;
wattron win WA.bold;
let s = sprintf "Orpie v%s" iface.version in
mvwaddstr_safe win 0 0 s;
wattroff win WA.bold;
let h_pos = String.length s in
mvwaddstr_safe win 0 (h_pos + 1) ("-- " ^ iface.tagline);
assert (mvwaddstr win 1 0 "--------------------------------------");
for i = 0 to pred iface.scr.hw_lines do
assert (mvwaddch win i 38 (int_of_char '|'))
done;
wattron win WA.bold;
assert (mvwaddstr win 2 0 "Calculator Modes:");
assert (mvwaddstr win 3 2 "angle: base: complex:");
wattroff win WA.bold;
let angle_str = match modes.angle with
|Rad -> "RAD"
|Deg -> "DEG" in
assert (mvwaddstr win 3 9 angle_str);
let base_str = match modes.base with
|Bin -> "BIN"
|Oct -> "OCT"
|Hex -> "HEX"
|Dec -> "DEC" in
assert (mvwaddstr win 3 20 base_str);
let complex_str = match modes.complex with
|Rect -> "REC"
|Polar -> "POL" in
assert (mvwaddstr win 3 34 complex_str);
let try_find op =
try Rcfile.key_of_operation op
with Not_found -> "(N/A)"
in
begin match iface.interface_mode with
|StandardEditMode | UnitEditMode ->
draw_help_standard iface win mvwaddstr_safe try_find
|IntEditMode ->
draw_help_intedit iface win mvwaddstr_safe try_find
|AbbrevEditMode ->
draw_help_abbrev iface win mvwaddstr_safe try_find
|VarEditMode ->
draw_help_varedit iface win mvwaddstr_safe try_find
|BrowsingMode ->
draw_help_browsing iface win mvwaddstr_safe try_find
end
end;
assert (wmove iface.scr.entry_win (iface.scr.ew_lines - 1) (iface.scr.ew_cols - 1))
let draw_message (iface : interface_state_t) msg =
draw_stack iface;
let error_lines = Utility.wordwrap msg (iface.scr.sw_cols-2) in
let trunc_error_lines =
if List.length error_lines > 4 then
(List.nth error_lines 0) :: (List.nth error_lines 1) ::
(List.nth error_lines 2) :: (List.nth error_lines 3) :: []
else
error_lines
in
let top_line =
begin match iface.scr.help_win with
|Some win -> 0
|None -> 2
end
in
for i = 0 to pred (List.length trunc_error_lines) do
assert (wmove iface.scr.stack_win (i + top_line) 0);
wclrtoeol iface.scr.stack_win;
assert (mvwaddstr iface.scr.stack_win (i + top_line) 1 (List.nth trunc_error_lines i))
done;
let s = String.make iface.scr.sw_cols '-' in
assert (mvwaddstr iface.scr.stack_win ((List.length trunc_error_lines) +
top_line) 0 s);
assert (wnoutrefresh iface.scr.stack_win);
assert (wmove iface.scr.entry_win (iface.scr.ew_lines - 1) (iface.scr.ew_cols - 1))
(* write an error message to the stack window *)
let draw_error (iface : interface_state_t) msg =
draw_message iface ("Error: " ^ msg)
(* display the "about" screen *)
let draw_about (iface : interface_state_t) =
erase ();
(* draw the box outline *)
let horiz_line = String.make iface.scr.cols '*' in
let vert_line_piece = Bytes.make iface.scr.cols ' ' in
vert_line_piece.[0] <- '*';
vert_line_piece.[pred iface.scr.cols] <- '*';
assert (mvaddstr 0 0 horiz_line);
assert (mvaddstr (iface.scr.lines - 2) 0 horiz_line);
for i = 1 to iface.scr.lines - 3 do
assert (mvaddstr i 0 (Bytes.to_string vert_line_piece))
done;
(* draw the text *)
let vert_center = (iface.scr.lines - 2) / 2
and horiz_center = iface.scr.cols / 2 in
let left_shift = 17 in
attron A.bold;
assert (mvaddstr (vert_center - 6) (horiz_center - left_shift)
("Orpie v" ^ iface.version));
attroff A.bold;
assert (mvaddstr (vert_center - 5) (horiz_center - left_shift)
"Copyright (C) 2004 Paul Pelzl");
assert (mvaddstr (vert_center - 3) (horiz_center - left_shift)
"\"Because, frankly, GUI calculator");
assert (mvaddstr (vert_center - 2) (horiz_center - left_shift)
" programs are pure evil. ");
attron A.bold;
assert (mvaddstr (vert_center - 2) (horiz_center - left_shift + 26)
"Orpie");
attroff A.bold;
assert (mvaddstr (vert_center - 2) (horiz_center - left_shift + 31)
", on");
assert (mvaddstr (vert_center - 1) (horiz_center - left_shift)
" the other hand, is only a little");
assert (mvaddstr (vert_center + 0) (horiz_center - left_shift)
" bit evil.\"");
assert (mvaddstr (vert_center + 2) (horiz_center - left_shift)
"Orpie comes with ABSOLUTELY NO");
assert (mvaddstr (vert_center + 3) (horiz_center - left_shift)
"WARRANTY. This is free software,");
assert (mvaddstr (vert_center + 4) (horiz_center - left_shift)
"and you are welcome to redistribute");
assert (mvaddstr (vert_center + 5) (horiz_center - left_shift)
"it under certain conditions; see");
assert (mvaddstr (vert_center + 6) (horiz_center - left_shift)
"'COPYING' for details.");
assert (mvaddstr (iface.scr.lines - 4) (horiz_center - 12)
"Press any key to continue.");
assert (move (iface.scr.lines - 1) (iface.scr.cols - 1));
assert (refresh ())
(* arch-tag: DO_NOT_CHANGE_044cbd96-d20b-48c6-92e7-62709c2aa3df *)
| null | https://raw.githubusercontent.com/pelzlpj/orpie/8b3bb833cedad0125aa9e9cb01d253156993e20b/src/orpie/interface_draw.ml | ocaml | interface_draw.ml
* This file has all code concerned with rendering the stack, help panel,
* and data entry line.
display the stack, where the bottom line of the display
* corresponds to stack level 'stack_bottom_row'
if the line number is really huge, truncate to least
* significant digits
if there is no help window, then print the calculator mode
* information above the stack
display the stack data itself
need to truncate the string
display the data that the user is in the process of entering
draw a string for a single floating-point number
get a string representation of the data that is in the entry buffer
create the lists of abbreviations to display in the abbrev command
* help screen
create the list of constants to display in the abbrev command
* help screen
draw the help page in standard entry mode
draw help page in integer editing mode
draw help page in abbrev/constant entry mode
draw help page in variable editing mode
highlight the entire selected match
draw help page in stack browsing mode
display the help window
write an error message to the stack window
display the "about" screen
draw the box outline
draw the text
arch-tag: DO_NOT_CHANGE_044cbd96-d20b-48c6-92e7-62709c2aa3df | Orpie -- a fullscreen RPN calculator for the console
* Copyright ( C ) 2003 - 2004 , 2005 , 2006 - 2007 , 2010 , 2018
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU General Public License , Version 3 ,
* as published by the Free Software Foundation .
*
* 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 , see < / > .
*
* Please send bug reports , patches , etc . to at
* < > .
* Copyright (C) 2003-2004, 2005, 2006-2007, 2010, 2018 Paul Pelzl
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, Version 3,
* as published by the Free Software Foundation.
*
* 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, see </>.
*
* Please send bug reports, patches, etc. to Paul Pelzl at
* <>.
*)
open Curses;;
open Printf;;
open Rpc_stack;;
open Operations;;
open Interface;;
type abbrev_help_display_t = {functions : string list;
modes : string list;
misc : string list}
let draw_stack (iface : interface_state_t) =
let print_numbered_line l_num =
let num_len =
String.length (string_of_int (pred (iface.stack_bottom_row +
iface.scr.sw_lines)))
in
if num_len <= 2 then
(sprintf "%2d: %s" l_num)
else if num_len = 3 then
(sprintf "%3d: %s" l_num)
else if num_len = 4 then
(sprintf "%4d: %s" l_num)
else
let l_num_str = string_of_int l_num in
let str_len = String.length l_num_str in
let trunc_num = Str.string_after l_num_str (str_len - 4) in
(sprintf "%s: %s" trunc_num)
in
let num_stack_lines =
begin match iface.scr.help_win with
|Some win ->
iface.scr.sw_lines
|None ->
let modes = iface.calc#get_modes () in
assert (wmove iface.scr.stack_win 0 0);
wclrtoeol iface.scr.stack_win;
wattron iface.scr.stack_win WA.bold;
assert (mvwaddstr iface.scr.stack_win 0 2 "angle: base: complex:");
wattroff iface.scr.stack_win WA.bold;
let angle_str = match modes.angle with
|Rad -> "RAD"
|Deg -> "DEG" in
assert (mvwaddstr iface.scr.stack_win 0 9 angle_str);
let base_str = match modes.base with
|Bin -> "BIN"
|Oct -> "OCT"
|Hex -> "HEX"
|Dec -> "DEC" in
assert (mvwaddstr iface.scr.stack_win 0 20 base_str);
let complex_str = match modes.complex with
|Rect -> "REC"
|Polar -> "POL" in
assert (mvwaddstr iface.scr.stack_win 0 34 complex_str);
assert (mvwaddstr iface.scr.stack_win 1 0 (String.make (iface.scr.sw_cols) '-'));
iface.scr.sw_lines - 2
end
in
for line = iface.stack_bottom_row to
pred (iface.stack_bottom_row + num_stack_lines) do
let s = iface.calc#get_display_line line in
let len = String.length s in
assert (wmove iface.scr.stack_win
(iface.scr.sw_lines + iface.stack_bottom_row - 1 - line) 0);
wclrtoeol iface.scr.stack_win;
if line = iface.stack_selection &&
iface.interface_mode = BrowsingMode then
wattron iface.scr.stack_win WA.reverse
else
();
if len > iface.scr.sw_cols - 7 then begin
let line_string =
if line = iface.stack_selection &&
iface.interface_mode = BrowsingMode then
let sub_s =
if iface.horiz_scroll < len - iface.scr.sw_cols + 7 then
String.sub s iface.horiz_scroll (iface.scr.sw_cols - 7)
else
String.sub s (len - iface.scr.sw_cols + 7)
(iface.scr.sw_cols - 7)
in
print_numbered_line line sub_s
else
let sub_s = String.sub s 0 (iface.scr.sw_cols - 10) in
print_numbered_line line (sub_s ^ "...")
in
assert (waddstr iface.scr.stack_win line_string)
end else begin
let spacer = String.make (iface.scr.sw_cols - 7 - len) ' ' in
let line_string = print_numbered_line line (spacer ^ s) in
assert (waddstr iface.scr.stack_win line_string)
end;
if line = iface.stack_selection &&
iface.interface_mode = BrowsingMode then
wattroff iface.scr.stack_win WA.reverse
else
();
done;
assert (wnoutrefresh iface.scr.stack_win);
assert (wmove iface.scr.entry_win (iface.scr.ew_lines - 1) (iface.scr.ew_cols - 1))
let draw_update_stack iface =
draw_stack iface;
assert (doupdate ())
let draw_entry (iface : interface_state_t) =
assert (mvwaddstr iface.scr.entry_win 0 0 (String.make iface.scr.ew_cols '-'));
assert (wmove iface.scr.entry_win 1 0);
wclrtoeol iface.scr.entry_win;
Safely draw a string into the entry window , with " ... " when
* truncation occurs . Highlight the first ' highlight_len '
* characters .
* truncation occurs. Highlight the first 'highlight_len'
* characters. *)
let draw_entry_string str highlight_len =
let len_str = String.length str in
begin
if len_str > iface.scr.ew_cols - 1 then
let trunc_str = String.sub str (len_str - iface.scr.ew_cols + 4)
(iface.scr.ew_cols - 4) in
assert (mvwaddstr iface.scr.entry_win 1 0 ("..." ^ trunc_str))
else
if highlight_len <= len_str then
begin
highlight the first ' highlight_len ' characters
wattron iface.scr.entry_win WA.bold;
assert (mvwaddstr iface.scr.entry_win 1 (iface.scr.ew_cols - len_str - 1)
(Str.string_before str (highlight_len)));
wattroff iface.scr.entry_win WA.bold;
assert (mvwaddstr iface.scr.entry_win 1 (iface.scr.ew_cols - len_str -
1 + highlight_len) (Str.string_after str (highlight_len)))
end
else
assert (mvwaddstr iface.scr.entry_win 1 (iface.scr.ew_cols - len_str - 1) str)
end;
assert (wnoutrefresh iface.scr.entry_win)
in
let get_float_str is_current mantissa exponent =
let sign_space =
if String.length exponent > 0 then
match exponent.[0] with
|'-' -> ""
|'+' -> ""
|_ -> " "
else
" "
in
if (is_current && iface.is_entering_exponent) || String.length exponent > 0 then
mantissa ^ " x10^" ^ sign_space ^ exponent
else if is_current || String.length mantissa > 0 then
mantissa
else
"0"
in
let data_string =
match iface.entry_type with
|IntEntry ->
if iface.is_entering_base then
"# " ^ iface.int_entry_buffer ^ "`" ^ iface.int_base_string
else
"# " ^ iface.int_entry_buffer
|FloatEntry ->
let mantissa_str = iface.gen_buffer.(0).re_mantissa
and exponent_str = iface.gen_buffer.(0).re_exponent in
let ff = get_float_str true mantissa_str exponent_str in
if iface.is_entering_units then
ff ^ "_" ^ iface.units_entry_buffer
else
ff
|ComplexEntry ->
let buffer = iface.gen_buffer.(0) in
let cc =
if iface.is_entering_imag then
let temp = get_float_str false buffer.re_mantissa buffer.re_exponent in
let re_str =
if String.length temp > 0 then temp
else "0"
in
let im_str = get_float_str true buffer.im_mantissa buffer.im_exponent in
match buffer.is_polar with
|false ->
"(" ^ re_str ^ ", " ^ im_str ^ ")"
|true ->
"(" ^ re_str ^ " <" ^ im_str ^ ")"
else
let re_str = get_float_str true buffer.re_mantissa buffer.re_exponent in
"(" ^ re_str ^ ")"
in
if iface.is_entering_units then
cc ^ "_" ^ iface.units_entry_buffer
else
cc
|FloatMatrixEntry ->
let ss = ref "[[" in
for el = 0 to pred iface.curr_buf do
let temp_re = get_float_str false iface.gen_buffer.(el).re_mantissa
iface.gen_buffer.(el).re_exponent in
if iface.has_multiple_rows && ((succ el) mod iface.matrix_cols) = 0 then
ss := !ss ^ temp_re ^ "]["
else
ss := !ss ^ temp_re ^ ", "
done;
let temp_re = get_float_str true iface.gen_buffer.(iface.curr_buf).re_mantissa
iface.gen_buffer.(iface.curr_buf).re_exponent in
ss := !ss ^ temp_re ^ "]]";
if iface.is_entering_units then
!ss ^ "_" ^ iface.units_entry_buffer
else
!ss
|ComplexMatrixEntry ->
let ss = ref "[[" in
for el = 0 to pred iface.curr_buf do
let temp_re = get_float_str false iface.gen_buffer.(el).re_mantissa
iface.gen_buffer.(el).re_exponent and
temp_im = get_float_str false iface.gen_buffer.(el).im_mantissa
iface.gen_buffer.(el).im_exponent in
(if iface.has_multiple_rows && ((succ el) mod iface.matrix_cols) = 0 then
match iface.gen_buffer.(el).is_polar with
|false ->
ss := !ss ^ "(" ^ temp_re ^ ", " ^ temp_im ^ ")]["
|true ->
ss := !ss ^ "(" ^ temp_re ^ " <" ^ temp_im ^ ")]["
else
match iface.gen_buffer.(el).is_polar with
|false ->
ss := !ss ^ "(" ^ temp_re ^ ", " ^ temp_im ^ "), "
|true ->
ss := !ss ^ "(" ^ temp_re ^ " <" ^ temp_im ^ "), ")
done;
(if iface.is_entering_imag then
let temp_re = get_float_str false iface.gen_buffer.(iface.curr_buf).re_mantissa
iface.gen_buffer.(iface.curr_buf).re_exponent and
temp_im = get_float_str true iface.gen_buffer.(iface.curr_buf).im_mantissa
iface.gen_buffer.(iface.curr_buf).im_exponent in
match iface.gen_buffer.(iface.curr_buf).is_polar with
|false ->
ss := !ss ^ "(" ^ temp_re ^ ", " ^ temp_im ^ ")]]"
|true ->
ss := !ss ^ "(" ^ temp_re ^ " <" ^ temp_im ^ ")]]"
else
let temp_re = get_float_str true iface.gen_buffer.(iface.curr_buf).re_mantissa
iface.gen_buffer.(iface.curr_buf).re_exponent in
ss := !ss ^ "(" ^ temp_re ^ ")]]");
if iface.is_entering_units then
!ss ^ "_" ^ iface.units_entry_buffer
else
!ss
|VarEntry ->
"@ " ^ iface.variable_entry_buffer
in
begin match iface.interface_mode with
|StandardEditMode ->
draw_entry_string data_string 0
|IntEditMode ->
draw_entry_string data_string 0
|AbbrevEditMode ->
let first_abbrev_match =
if iface.matched_abbrev_list = [] then ""
else List.hd iface.matched_abbrev_list
in
let highlight_len = String.length iface.abbrev_entry_buffer in
if highlight_len = 0 then
begin match iface.abbrev_or_const with
|IsAbbrev -> draw_entry_string "<enter command abbreviation>" 0
|IsConst -> draw_entry_string "<enter constant symbol>" 0
end
else
begin match iface.abbrev_or_const with
|IsAbbrev ->
let is_function =
match (Rcfile.translate_abbrev first_abbrev_match) with
|Function ff -> true
|_ -> false
in
if is_function then
draw_entry_string (first_abbrev_match ^ "( )") highlight_len
else
draw_entry_string first_abbrev_match highlight_len
|IsConst ->
draw_entry_string first_abbrev_match highlight_len
end
|BrowsingMode ->
()
|VarEditMode ->
if String.length iface.variable_entry_buffer = 0 then
draw_entry_string "<enter variable name>" 0
else
draw_entry_string data_string 0
|UnitEditMode ->
draw_entry_string data_string 0
end;
assert (wmove iface.scr.entry_win (iface.scr.ew_lines - 1) (iface.scr.ew_cols - 1))
let draw_update_entry iface =
draw_entry iface;
assert (doupdate ())
let generate_abbrev_help () =
let rec trunc_list lst n =
if n = 0 then
[]
else
match lst with
|[] ->
[]
|head :: tail ->
head :: (trunc_list tail (pred n))
in
let get_abbr op =
try Rcfile.abbrev_of_operation op
with Not_found -> ""
in
let functions_str =
(get_abbr (Function Sin)) ^ " " ^
(get_abbr (Function Asin)) ^ " " ^
(get_abbr (Function Cos)) ^ " " ^
(get_abbr (Function Acos)) ^ " " ^
(get_abbr (Function Tan)) ^ " " ^
(get_abbr (Function Atan)) ^ " " ^
(get_abbr (Function Exp)) ^ " " ^
(get_abbr (Function Ln)) ^ " " ^
(get_abbr (Function Ten_x)) ^ " " ^
(get_abbr (Function Log10)) ^ " " ^
(get_abbr (Function Sq)) ^ " " ^
(get_abbr (Function Sqrt)) ^ " " ^
(get_abbr (Function Inv)) ^ " " ^
(get_abbr (Function Gamma)) ^ " " ^
(get_abbr (Function LnGamma)) ^ " " ^
(get_abbr (Function Erf)) ^ " " ^
(get_abbr (Function Erfc)) ^ " " ^
(get_abbr (Function Transpose)) ^ " " ^
(get_abbr (Function Re)) ^ " " ^
(get_abbr (Function Im)) ^ " " ^
(get_abbr (Function Mod)) ^ " " ^
(get_abbr (Function Floor)) ^ " " ^
(get_abbr (Function Ceiling)) ^ " " ^
(get_abbr (Function ToInt)) ^ " " ^
(get_abbr (Function ToFloat)) ^ " " ^
(get_abbr (Function Eval)) ^ " " ^
(get_abbr (Function Store)) ^ " " ^
(get_abbr (Function Purge))
in
let functions_str_wrap = trunc_list
(Utility.wordwrap_nspace functions_str 34 2) 5 in
let modes_str =
(get_abbr (Command SetRadians)) ^ " " ^
(get_abbr (Command SetDegrees)) ^ " " ^
(get_abbr (Command SetBin)) ^ " " ^
(get_abbr (Command SetOct)) ^ " " ^
(get_abbr (Command SetDec)) ^ " " ^
(get_abbr (Command SetHex)) ^ " " ^
(get_abbr (Command SetRect)) ^ " " ^
(get_abbr (Command SetPolar))
in
let modes_str_wrap = trunc_list
(Utility.wordwrap_nspace modes_str 34 2) 2 in
let misc_str =
(get_abbr (Command EnterPi)) ^ " " ^
(get_abbr (Command Undo)) ^ " " ^
(get_abbr (Command View))
in
let misc_str_wrap = trunc_list
(Utility.wordwrap_nspace misc_str 34 2) 1 in
{functions = functions_str_wrap;
modes = modes_str_wrap;
misc = misc_str_wrap}
let generate_const_help () =
let rec trunc_list lst n =
if n = 0 then
[]
else
match lst with
|[] ->
[]
|head :: tail ->
head :: (trunc_list tail (pred n))
in
let rec make_symbols_string symbols_list symbols_str =
match symbols_list with
| [] ->
symbols_str
| head :: tail ->
make_symbols_string tail (head ^ " " ^ symbols_str)
in
let symbols = make_symbols_string !Rcfile.constant_symbols "" in
trunc_list (Utility.wordwrap_nspace symbols 34 2) 5
let draw_help_standard iface win mvwaddstr_safe try_find =
if iface.help_page = 0 then begin
wattron win WA.bold;
assert (mvwaddstr win 5 0 "Common Operations:");
wattroff win WA.bold;
mvwaddstr_safe win 6 2 ("enter : " ^
try_find (Edit Enter));
mvwaddstr_safe win 7 2 ("drop : " ^
try_find (Command Drop));
mvwaddstr_safe win 8 2 ("swap : " ^
try_find (Command Swap));
mvwaddstr_safe win 9 2 ("backspace: " ^
try_find (Edit Backspace));
mvwaddstr_safe win 10 2 ("add : " ^
try_find (Function Add));
mvwaddstr_safe win 11 2 ("subtract : " ^
try_find (Function Sub));
mvwaddstr_safe win 12 2 ("multiply : " ^
try_find (Function Mult));
mvwaddstr_safe win 13 2 ("divide : " ^
try_find (Function Div));
mvwaddstr_safe win 14 2 ("y^x : " ^
try_find (Function Pow));
mvwaddstr_safe win 15 2 ("negation : " ^
try_find (Function Neg));
wattron win WA.bold;
mvwaddstr_safe win 16 0 "Miscellaneous:";
wattroff win WA.bold;
mvwaddstr_safe win 17 2 ("scientific notation : " ^
try_find (Edit SciNotBase));
mvwaddstr_safe win 18 2 ("abbreviation entry mode : " ^
try_find (Command BeginAbbrev));
mvwaddstr_safe win 19 2 ("stack browsing mode : " ^
try_find (Command BeginBrowse));
mvwaddstr_safe win 20 2 ("refresh display : " ^
try_find (Command Refresh));
mvwaddstr_safe win 21 2 ("quit : " ^
try_find (Command Quit));
assert (wnoutrefresh win)
end else begin
let adjust_len s len =
if String.length s < len then
s ^ (String.make (len - (String.length s)) ' ')
else
Str.string_before s len
in
let make_string colon_pos key_string abbr =
(adjust_len key_string colon_pos) ^ ": " ^ abbr
in
wattron win WA.bold;
mvwaddstr_safe win 5 0 "Autobindings:";
wattroff win WA.bold;
if Array.length !Rcfile.autobind_keys <= 0 then
mvwaddstr_safe win 6 2 "(none)"
else
for i = 0 to pred (min (iface.scr.hw_lines - 6) (Array.length
!Rcfile.autobind_keys)) do
let (key, key_string, bound_f, age) = !Rcfile.autobind_keys.(i) in
let abbr = match bound_f with
|None -> "(none)"
|Some op -> Rcfile.abbrev_of_operation op
in
mvwaddstr_safe win (i + 6) 2 (make_string 12 key_string abbr)
done;
assert (wnoutrefresh win)
end
let draw_help_intedit iface win mvwaddstr_safe try_find =
wattron win WA.bold;
mvwaddstr_safe win 5 0 "Integer Editing Operations:";
wattroff win WA.bold;
mvwaddstr_safe win 6 2 ("enter : " ^
try_find (Edit Enter));
mvwaddstr_safe win 7 2 ("set base : " ^
try_find (Edit SciNotBase));
mvwaddstr_safe win 8 2 ("cancel : " ^
try_find (IntEdit IntEditExit));
assert (wnoutrefresh win)
let draw_help_abbrev iface win mvwaddstr_safe try_find =
if String.length iface.abbrev_entry_buffer = 0 then begin
let abbr_strings = generate_abbrev_help () in
let const_strings = generate_const_help () in
let rec print_help_lines lines v_pos =
begin match lines with
|[] ->
()
|head :: tail ->
mvwaddstr_safe win v_pos 2 head;
print_help_lines tail (succ v_pos)
end
in
begin match iface.abbrev_or_const with
|IsAbbrev ->
wattron win WA.bold;
mvwaddstr_safe win 5 0 "Abbreviations:";
wattroff win WA.bold;
mvwaddstr_safe win 6 1 "Common Functions:";
print_help_lines abbr_strings.functions 7;
mvwaddstr_safe win 13 1 "Change Modes:";
print_help_lines abbr_strings.modes 14;
mvwaddstr_safe win 17 1 "Miscellaneous:";
print_help_lines abbr_strings.misc 18;
mvwaddstr_safe win 20 1 ("execute abbreviation : " ^
try_find (Abbrev AbbrevEnter));
mvwaddstr_safe win 21 1 ("cancel abbreviation : " ^
try_find (Abbrev AbbrevExit));
|IsConst ->
wattron win WA.bold;
mvwaddstr_safe win 5 0 "Constants:";
wattroff win WA.bold;
print_help_lines const_strings 7;
mvwaddstr_safe win 12 1 ("enter constant : " ^
try_find (Abbrev AbbrevEnter));
end;
assert (wnoutrefresh win)
end else begin
wattron win WA.bold;
assert (mvwaddstr win 5 0 "Matched Abbreviations:");
wattroff win WA.bold;
let highlight_len = String.length iface.abbrev_entry_buffer in
let rec draw_matches v_pos match_list =
if v_pos < iface.scr.hw_lines then
begin match match_list with
|[] ->
()
|m :: tail ->
begin
highlight the first ' highlight_len ' characters
wattron win WA.bold;
mvwaddstr_safe win v_pos 2
(Str.string_before m (highlight_len));
wattroff win WA.bold;
mvwaddstr_safe win v_pos (2 + highlight_len)
(Str.string_after m (highlight_len));
draw_matches (succ v_pos) tail
end
end
else
()
in
draw_matches 6 iface.matched_abbrev_list;
assert (wnoutrefresh win)
end
let draw_help_varedit iface win mvwaddstr_safe try_find =
wattron win WA.bold;
mvwaddstr_safe win 5 0 "Variable Mode Commands:";
wattroff win WA.bold;
mvwaddstr_safe win 6 2 ("enter variable : " ^
try_find (VarEdit VarEditEnter));
mvwaddstr_safe win 7 2 ("complete variable: " ^
try_find (VarEdit VarEditComplete));
mvwaddstr_safe win 8 2 ("cancel entry : " ^
try_find (VarEdit VarEditExit));
wattron win WA.bold;
mvwaddstr_safe win 10 0 "Matched variables:";
wattroff win WA.bold;
let highlight_len =
begin match iface.completion with
|None -> String.length iface.variable_entry_buffer
|Some _ -> 0
end
in
let rec draw_matches v_pos match_list count =
if v_pos < iface.scr.hw_lines then
begin match match_list with
|[] ->
()
|m :: tail ->
begin match iface.completion with
|None ->
highlight the first ' highlight_len ' characters
wattron win WA.bold;
mvwaddstr_safe win v_pos 2
(Str.string_before m (highlight_len));
wattroff win WA.bold;
mvwaddstr_safe win v_pos (2 + highlight_len)
(Str.string_after m (highlight_len));
|Some num ->
if count = num then begin
wattron win WA.bold;
mvwaddstr_safe win v_pos 2 m;
wattroff win WA.bold;
end else
mvwaddstr_safe win v_pos 2 m;
end;
draw_matches (succ v_pos) tail (succ count)
end
else
()
in
if List.length iface.matched_variables = 0 then
mvwaddstr_safe win 11 2 "(none)"
else
draw_matches 11 iface.matched_variables 0;
assert (wnoutrefresh win)
let draw_help_browsing iface win mvwaddstr_safe try_find =
wattron win WA.bold;
mvwaddstr_safe win 5 0 "Browsing Operations:";
wattroff win WA.bold;
mvwaddstr_safe win 6 2 ("prev : " ^
try_find (Browse PrevLine));
mvwaddstr_safe win 7 2 ("next : " ^
try_find (Browse NextLine));
mvwaddstr_safe win 8 2 ("scroll left : " ^
try_find (Browse ScrollLeft));
mvwaddstr_safe win 9 2 ("scroll right: " ^
try_find (Browse ScrollRight));
mvwaddstr_safe win 10 2 ("roll down : " ^
try_find (Browse RollDown));
mvwaddstr_safe win 11 2 ("roll up : " ^
try_find (Browse RollUp));
mvwaddstr_safe win 12 2 ("dup : " ^
try_find (Command Dup));
mvwaddstr_safe win 13 2 ("view : " ^
try_find (Browse ViewEntry));
mvwaddstr_safe win 14 2 ("edit : " ^
try_find (Browse EditEntry));
mvwaddstr_safe win 15 2 ("drop : " ^
try_find (Browse Drop1));
mvwaddstr_safe win 16 2 ("dropn : " ^
try_find (Browse DropN));
mvwaddstr_safe win 17 2 ("keep : " ^
try_find (Browse Keep));
mvwaddstr_safe win 18 2 ("keepn : " ^
try_find (Browse KeepN));
mvwaddstr_safe win 20 1 ("exit browsing mode: " ^
try_find (Browse EndBrowse));
assert (wnoutrefresh win)
let draw_help (iface : interface_state_t) =
let mvwaddstr_safe w vert horiz st =
let st_trunc =
if String.length st > 36 then
Str.string_before st 36
else
st
in
assert (mvwaddstr w vert horiz st_trunc)
in
let modes = iface.calc#get_modes () in
begin match iface.scr.help_win with
|None ->
()
|Some win ->
wclear win;
wattron win WA.bold;
let s = sprintf "Orpie v%s" iface.version in
mvwaddstr_safe win 0 0 s;
wattroff win WA.bold;
let h_pos = String.length s in
mvwaddstr_safe win 0 (h_pos + 1) ("-- " ^ iface.tagline);
assert (mvwaddstr win 1 0 "--------------------------------------");
for i = 0 to pred iface.scr.hw_lines do
assert (mvwaddch win i 38 (int_of_char '|'))
done;
wattron win WA.bold;
assert (mvwaddstr win 2 0 "Calculator Modes:");
assert (mvwaddstr win 3 2 "angle: base: complex:");
wattroff win WA.bold;
let angle_str = match modes.angle with
|Rad -> "RAD"
|Deg -> "DEG" in
assert (mvwaddstr win 3 9 angle_str);
let base_str = match modes.base with
|Bin -> "BIN"
|Oct -> "OCT"
|Hex -> "HEX"
|Dec -> "DEC" in
assert (mvwaddstr win 3 20 base_str);
let complex_str = match modes.complex with
|Rect -> "REC"
|Polar -> "POL" in
assert (mvwaddstr win 3 34 complex_str);
let try_find op =
try Rcfile.key_of_operation op
with Not_found -> "(N/A)"
in
begin match iface.interface_mode with
|StandardEditMode | UnitEditMode ->
draw_help_standard iface win mvwaddstr_safe try_find
|IntEditMode ->
draw_help_intedit iface win mvwaddstr_safe try_find
|AbbrevEditMode ->
draw_help_abbrev iface win mvwaddstr_safe try_find
|VarEditMode ->
draw_help_varedit iface win mvwaddstr_safe try_find
|BrowsingMode ->
draw_help_browsing iface win mvwaddstr_safe try_find
end
end;
assert (wmove iface.scr.entry_win (iface.scr.ew_lines - 1) (iface.scr.ew_cols - 1))
let draw_message (iface : interface_state_t) msg =
draw_stack iface;
let error_lines = Utility.wordwrap msg (iface.scr.sw_cols-2) in
let trunc_error_lines =
if List.length error_lines > 4 then
(List.nth error_lines 0) :: (List.nth error_lines 1) ::
(List.nth error_lines 2) :: (List.nth error_lines 3) :: []
else
error_lines
in
let top_line =
begin match iface.scr.help_win with
|Some win -> 0
|None -> 2
end
in
for i = 0 to pred (List.length trunc_error_lines) do
assert (wmove iface.scr.stack_win (i + top_line) 0);
wclrtoeol iface.scr.stack_win;
assert (mvwaddstr iface.scr.stack_win (i + top_line) 1 (List.nth trunc_error_lines i))
done;
let s = String.make iface.scr.sw_cols '-' in
assert (mvwaddstr iface.scr.stack_win ((List.length trunc_error_lines) +
top_line) 0 s);
assert (wnoutrefresh iface.scr.stack_win);
assert (wmove iface.scr.entry_win (iface.scr.ew_lines - 1) (iface.scr.ew_cols - 1))
let draw_error (iface : interface_state_t) msg =
draw_message iface ("Error: " ^ msg)
let draw_about (iface : interface_state_t) =
erase ();
let horiz_line = String.make iface.scr.cols '*' in
let vert_line_piece = Bytes.make iface.scr.cols ' ' in
vert_line_piece.[0] <- '*';
vert_line_piece.[pred iface.scr.cols] <- '*';
assert (mvaddstr 0 0 horiz_line);
assert (mvaddstr (iface.scr.lines - 2) 0 horiz_line);
for i = 1 to iface.scr.lines - 3 do
assert (mvaddstr i 0 (Bytes.to_string vert_line_piece))
done;
let vert_center = (iface.scr.lines - 2) / 2
and horiz_center = iface.scr.cols / 2 in
let left_shift = 17 in
attron A.bold;
assert (mvaddstr (vert_center - 6) (horiz_center - left_shift)
("Orpie v" ^ iface.version));
attroff A.bold;
assert (mvaddstr (vert_center - 5) (horiz_center - left_shift)
"Copyright (C) 2004 Paul Pelzl");
assert (mvaddstr (vert_center - 3) (horiz_center - left_shift)
"\"Because, frankly, GUI calculator");
assert (mvaddstr (vert_center - 2) (horiz_center - left_shift)
" programs are pure evil. ");
attron A.bold;
assert (mvaddstr (vert_center - 2) (horiz_center - left_shift + 26)
"Orpie");
attroff A.bold;
assert (mvaddstr (vert_center - 2) (horiz_center - left_shift + 31)
", on");
assert (mvaddstr (vert_center - 1) (horiz_center - left_shift)
" the other hand, is only a little");
assert (mvaddstr (vert_center + 0) (horiz_center - left_shift)
" bit evil.\"");
assert (mvaddstr (vert_center + 2) (horiz_center - left_shift)
"Orpie comes with ABSOLUTELY NO");
assert (mvaddstr (vert_center + 3) (horiz_center - left_shift)
"WARRANTY. This is free software,");
assert (mvaddstr (vert_center + 4) (horiz_center - left_shift)
"and you are welcome to redistribute");
assert (mvaddstr (vert_center + 5) (horiz_center - left_shift)
"it under certain conditions; see");
assert (mvaddstr (vert_center + 6) (horiz_center - left_shift)
"'COPYING' for details.");
assert (mvaddstr (iface.scr.lines - 4) (horiz_center - 12)
"Press any key to continue.");
assert (move (iface.scr.lines - 1) (iface.scr.cols - 1));
assert (refresh ())
|
0da1f77a5c6353846d21f47aa76692a5ad795601666b8d386924330906d8b197 | rfindler/lindenmayer | seaweed.rkt | #lang lindenmayer racket
## axiom ##
abF
## rules ##
a → FFf
b → c
c → Fddde[+++++m][-----m]ddfc
d → e
e → g
g → h
h → i
i → j
j → k
k → FF
m → nofF
n → fFF
o → p
p → fF[------A][++++++H]Fq
q → ff[-----B][+++++I]Fr
r → fF[----C][++++J]Fs
s → fF[---D][+++K]Ft
t → fF[--E][++L]F
A → BF
B → Ff+C
C → Ff+D
D → Ff+E
E → Ff+G
G → Ff+
H → IF
I → Ff-J
J → Ff-I
K → Ff-L
L → FF-M
M → Ff-
## variables ##
θ=10
n=11
w=300
h=300
-----------------------
## axiom ##
abF
## rules ##
a → Ff
b → c
c → FFFQ[++++A][----I]FFfd
d → +FFFQ[++++A][----I]FFfe
e → FFFQ[++++A][----I]FFfg
g → -FFFQ[++++A][----I]FFfh
h → FFFQ[++++A][----I]FFfi
i → FFFQ[+++fp]FFfj
j → FFFQ[++++A][----I]FFfk
k → +FFQ[++++A][----I]FFfl
l → FFFQ[++++A][----I]FFfm
m → -FFFQ[++++A][----I]FFfn
n → FFFQ[++++A][----I]FFfo
o → FFFQ[---fp]FFfc
p → abF
A → BCfFFF
B → fF
C → D
D → fFFFE
E → fFF[-P]FG
G → fFF[-P]FH
H → fFF[-P]F
I → JKfFFF
J → fF
K → L
L → fFFFM
M → fFF[+P]FN
N → fFF[+P]FO
O → fFF[+P]F
P → fFfF
Q → FQ
## variables ##
θ=20
n=24
w=300
h=300
=================
#|
From:
COMPUTER SIMULATION OF THE MORPHOLOGY AND
DEVELOPMENT OF SEVERAL SPECIES OF SEAWEED
USING LINDENMAYER SYSTEMS
|#
(require lindenmayer/turtle)
(provide (all-from-out lindenmayer/turtle) (all-defined-out))
(define (a state . v) state)
(define (b state . v) state)
(define (c state . v) state)
(define (d state . v) state)
(define (e state . v) state)
(define (g state . v) state)
(define (h state . v) state)
(define (i state . v) state)
(define (j state . v) state)
(define (k state . v) state)
(define (l state . v) state)
(define (m state . v) state)
(define (n state . v) state)
(define (o state . v) state)
(define (p state . v) state)
(define (q state . v) state)
(define (r state . v) state)
(define (s state . v) state)
(define (t state . v) state)
(define (A state . v) state)
(define (B state . v) state)
(define (C state . v) state)
(define (D state . v) state)
(define (E state . v) state)
(define (G state . v) state)
(define (H state . v) state)
(define (I state . v) state)
(define (J state . v) state)
(define (K state . v) state)
(define (L state . v) state)
(define (M state . v) state)
(define (N state . v) state)
(define (O state . v) state)
(define (P state . v) state)
(define (Q state . v) state)
| null | https://raw.githubusercontent.com/rfindler/lindenmayer/2ef7b4535d8ae1eb7cc2e16e2b630c30a4b9a34d/examples/seaweed.rkt | racket |
From:
COMPUTER SIMULATION OF THE MORPHOLOGY AND
DEVELOPMENT OF SEVERAL SPECIES OF SEAWEED
USING LINDENMAYER SYSTEMS
| #lang lindenmayer racket
## axiom ##
abF
## rules ##
a → FFf
b → c
c → Fddde[+++++m][-----m]ddfc
d → e
e → g
g → h
h → i
i → j
j → k
k → FF
m → nofF
n → fFF
o → p
p → fF[------A][++++++H]Fq
q → ff[-----B][+++++I]Fr
r → fF[----C][++++J]Fs
s → fF[---D][+++K]Ft
t → fF[--E][++L]F
A → BF
B → Ff+C
C → Ff+D
D → Ff+E
E → Ff+G
G → Ff+
H → IF
I → Ff-J
J → Ff-I
K → Ff-L
L → FF-M
M → Ff-
## variables ##
θ=10
n=11
w=300
h=300
-----------------------
## axiom ##
abF
## rules ##
a → Ff
b → c
c → FFFQ[++++A][----I]FFfd
d → +FFFQ[++++A][----I]FFfe
e → FFFQ[++++A][----I]FFfg
g → -FFFQ[++++A][----I]FFfh
h → FFFQ[++++A][----I]FFfi
i → FFFQ[+++fp]FFfj
j → FFFQ[++++A][----I]FFfk
k → +FFQ[++++A][----I]FFfl
l → FFFQ[++++A][----I]FFfm
m → -FFFQ[++++A][----I]FFfn
n → FFFQ[++++A][----I]FFfo
o → FFFQ[---fp]FFfc
p → abF
A → BCfFFF
B → fF
C → D
D → fFFFE
E → fFF[-P]FG
G → fFF[-P]FH
H → fFF[-P]F
I → JKfFFF
J → fF
K → L
L → fFFFM
M → fFF[+P]FN
N → fFF[+P]FO
O → fFF[+P]F
P → fFfF
Q → FQ
## variables ##
θ=20
n=24
w=300
h=300
=================
(require lindenmayer/turtle)
(provide (all-from-out lindenmayer/turtle) (all-defined-out))
(define (a state . v) state)
(define (b state . v) state)
(define (c state . v) state)
(define (d state . v) state)
(define (e state . v) state)
(define (g state . v) state)
(define (h state . v) state)
(define (i state . v) state)
(define (j state . v) state)
(define (k state . v) state)
(define (l state . v) state)
(define (m state . v) state)
(define (n state . v) state)
(define (o state . v) state)
(define (p state . v) state)
(define (q state . v) state)
(define (r state . v) state)
(define (s state . v) state)
(define (t state . v) state)
(define (A state . v) state)
(define (B state . v) state)
(define (C state . v) state)
(define (D state . v) state)
(define (E state . v) state)
(define (G state . v) state)
(define (H state . v) state)
(define (I state . v) state)
(define (J state . v) state)
(define (K state . v) state)
(define (L state . v) state)
(define (M state . v) state)
(define (N state . v) state)
(define (O state . v) state)
(define (P state . v) state)
(define (Q state . v) state)
|
069f2b682207a63841e4ade0c80dc5ae8c01ae03205cbd65c8ac5b07fb1d0630 | Beluga-lang/Beluga | synint.ml | open Support.Equality
(* Internal Syntax *)
open Support
open Id
Internal LF Syntax
module LF = struct
include Syncom.LF
type kind =
| Typ
| PiKind of (typ_decl * Plicity.t) * kind
and typ_decl = (* LF Declarations *)
| TypDecl of Name.t * typ (* D := x:A *)
| TypDeclOpt of Name.t (* | x:_ *)
and cltyp =
| MTyp of typ
| PTyp of typ
| STyp of svar_class * dctx
and ctyp =
| ClTyp of cltyp * dctx
| CTyp of cid_schema option
and ctyp_decl = (* Contextual Declarations *)
| Decl of Name.t * ctyp * Plicity.t * Inductivity.t
| DeclOpt of Name.t * Plicity.t
and typ = (* LF level *)
A : : = a M1 ... Mn
| Pi x :
| Sigma of typ_rec
| TClo of (typ * sub) (* | TClo(A,s) *)
(* The plicity annotation is set to `implicit when reconstructing an
a hole (_) so that when printing, it can be reproduced correctly.
*)
and normal = (* normal terms *)
M : : = \x . M
| Root of Location.t * head * spine * Plicity.t (* | h . S *)
| LFHole of Location.t * HoleId.t * HoleId.name
| Clo of (normal * sub) (* | Clo(N,s) *)
| Tuple of Location.t * tuple
TODO : Heads ought to carry their location .
currently needs to invent / pretend that a different
location is the correct one .
Erasure currently needs to invent / pretend that a different
location is the correct one.
*)
and head =
| BVar of offset (* H ::= x *)
| Const of cid_term (* | c *)
| MMVar of mm_var_inst (* | u[t ; s] *)
| MPVar of mm_var_inst (* | p[t ; s] *)
| MVar of (cvar * sub) (* | u[s] *)
| PVar of (offset * sub) (* | p[s] *)
| AnnH of head * typ (* | (H:A) *)
| Proj of head * int (* | x.k | #p.k s *)
| FVar of Name.t (* free variable for type
reconstruction *)
| FMVar of fvarsub (* free meta-variable for type
reconstruction *)
| FPVar of fvarsub (* free parameter variable for type
reconstruction *)
| HClo(x , # S[sigma ] )
| HMClo of offset * mm_var_inst (* | HMClo(x, #S[theta;sigma]) *)
and fvarsub = Name.t * sub
and spine = (* spine *)
S : : =
| App of normal * spine (* | M . S *)
| SClo of (spine * sub) (* | SClo(S,s) *)
and sub =
sigma : : = , n )
BEWARE : offset and int are both ints ,
and in the opposite order compared to FSVar and MSVar .
offset is the index into Delta and describes the SVar .
This is a pain to fix
and in the opposite order compared to FSVar and MSVar.
offset is the index into Delta and describes the SVar.
This is a pain to fix *)
| FSVar of offset * fvarsub (* | s[sigma] *)
| Dot of front * sub (* | Ft . s *)
| MSVar of offset * mm_var_inst (* | u[t ; s] *)
| EmptySub
| Undefs
Fronts :
| Head of head (* Ft ::= H *)
| Obj of normal (* | N *)
| Undef (* | _ *)
(* Contextual substitutions *)
Fronts :
| ClObj of dctx_hat * clobj
| CObj of dctx (* | Psi *)
| MV of offset (* | u//u | p//p | psi/psi *)
| MUndef (* This shouldn't be here, we should use a different datastructure for
partial inverse substitutions *)
and clobj = (* ContextuaL objects *)
| MObj of normal (* Mft::= Psihat.N *)
| PObj of head (* | Psihat.p[s] | Psihat.x *)
| SObj of sub
and msub = (* Contextual substitutions *)
theta : : =
| MDot of mfront * msub (* | MFt . theta *)
and cvar = (* Contextual Variables *)
| Offset of offset (* Bound Variables *)
| Inst of mm_var (* D ; Psi |- M <= A provided constraint *)
and mm_var =
{ name : Name.t
; instantiation : iterm option ref
; cD : mctx
unique to each MMVar
; typ : ctyp
; constraints : cnstr list ref (* not really used *)
; plicity : Plicity.t
; inductivity : Inductivity.t
}
and mm_var_inst' = mm_var * msub
and mm_var_inst = mm_var_inst' * sub
and iterm =
| INorm of normal
| IHead of head
| ISub of sub
| ICtx of dctx
and tvar =
| TInst of typ option ref * dctx * kind * cnstr list ref
(* unique identifiers attached to constraints, used for debugging *)
and constrnt_id = int
and constrnt = (* Constraint *)
| Queued of constrnt_id (* constraint ::= Queued *)
| Delta ; Psi |-(M1 = = M2 )
and cnstr = constrnt ref
and dctx = (* LF Context *)
| Null (* Psi ::= . *)
| CtxVar of ctx_var (* | psi *)
| DDec of dctx * typ_decl (* | Psi, x:A or x:block ... *)
and ctx_var =
| CtxName of Name.t
| CtxOffset of offset
| CInst of mm_var_inst'
(* D |- Psi : schema *)
and sch_elem = (* Schema Element *)
| SchElem of typ_decl ctx * typ_rec (* Pi x1:A1 ... xn:An.
Sigma y1:B1 ... yk:Bk. B *)
Sigma - types not allowed in Ai
and schema =
| Schema of sch_elem list
and dctx_hat = ctx_var option * offset (* Psihat ::= *)
(* | psi *)
(* | . *)
(* | Psihat, x *)
and typ_rec = (* Sigma x1:A1 ... xn:An. B *)
| SigmaLast of Name.t option * typ (* ... . B *)
| SigmaElem of Name.t * typ * typ_rec (* xk : Ak, ... *)
and tuple =
| Last of normal
| Cons of normal * tuple
Modal Context D : CDec ctx
let map_plicity f =
function
| Root (loc, tH, tS, plicity) ->
Root (loc, tH, tS, f plicity)
| tM -> tM
let proj_maybe (h : head) : int option -> head =
function
| None -> h
| Some k -> Proj (h, k)
* Helper for forming TClo LF types , which avoids doing so if the
substitution is the identity .
substitution is the identity.
*)
let tclo tA s =
match s with
| Shift 0 -> tA
| _ -> TClo (tA, s)
(** Forms an MMVar instantiation by attaching an LF substitution and
a meta-substituation to the variable.
*)
let mm_var_inst (u : mm_var) (t : msub) (s : sub): mm_var_inst = (u, t), s
let is_mmvar_instantiated mmvar = Option.is_some (mmvar.instantiation.contents)
let type_of_mmvar_instantiated mmvar = (mmvar.typ)
let rename_ctyp_decl f =
function
| Decl (x, tA, plicity, inductivity) -> Decl (f x, tA, plicity, inductivity)
| DeclOpt (x, plicity) -> DeclOpt (f x, plicity)
* a head into a normal by using an empty spine .
Very useful for constructing variables as normals .
Note that the normal will have a ghost location , as heads do n't
carry a location .
Very useful for constructing variables as normals.
Note that the normal will have a ghost location, as heads don't
carry a location.
*)
let head (tH : head) : normal =
Root (Location.ghost, tH, Nil, Plicity.explicit)
let mvar cvar sub : head =
MVar (cvar, sub)
let mmvar inst = MMVar inst
let mpvar inst = MPVar inst
* Assert that the contextual type declaration be a real , and
not a DeclOpt .
Raises a violation if it is a DeclOpt .
not a DeclOpt.
Raises a violation if it is a DeclOpt.
*)
let require_decl : ctyp_decl -> Name.t * ctyp * Plicity.t * Inductivity.t =
function
| Decl (u, cU, plicity, inductivity) -> (u, cU, plicity, inductivity)
| DeclOpt _ ->
Error.violation "[require_decl] DeclOpt is forbidden"
Hatted version of LF.Null
let null_hat : dctx_hat = (None, 0)
let rec loc_of_normal =
function
| Lam (loc, _, _) -> loc
| Root (loc, _, _, _) -> loc
| LFHole (loc, _, _) -> loc
| Clo (tM, _) -> loc_of_normal tM
| Tuple (loc, _) -> loc
(**********************)
(* Type Abbreviations *)
(**********************)
Ns = [ s]N
type sclo = spine * sub (* Ss = [s]S *)
type tclo = typ * sub (* As = [s]A *)
[
type prag =
| NamePrag of cid_typ
| NotPrag
| OpenPrag of module_id
| DefaultAssocPrag of Associativity.t
| FixPrag of Name.t * Fixity.t * int * Associativity.t option
| AbbrevPrag of string list * string
(**********************)
(* Helpers *)
(**********************)
let rec blockLength =
function
| SigmaLast _ -> 1
| SigmaElem(_x, _tA, recA) -> 1 + blockLength recA
getType traverses the typ_rec from left to right ;
target is relative to the remaining suffix of the type
s_recA target j = ( tA , s ' )
if Psi(head ) = Sigma recA '
and [ s]recA is a suffix of recA '
then
Psi |- [ s']tA < = type
val getType : head - > trec_clo - > int - > tclo
target is relative to the remaining suffix of the type
getType head s_recA target j = (tA, s')
if Psi(head) = Sigma recA'
and [s]recA is a suffix of recA'
then
Psi |- [s']tA <= type
val getType : head -> trec_clo -> int -> tclo
*)
let getType =
let rec getType head s_recA target j =
match (s_recA, target) with
| ((SigmaLast (_, lastA), s), 1) ->
(lastA, s)
| ((SigmaElem (_x, tA, _recA), s), 1) ->
(tA, s)
| ((SigmaElem (_x, _tA, recA), s), target) ->
let tPj = Proj (head, j) in
getType head (recA, Dot (Head tPj, s)) (target - 1) (j + 1)
| _ -> raise Not_found
in
fun head s_recA target -> getType head s_recA target 1
(* getIndex traverses the typ_rec from left to right;
target is the name of the projection we're looking for
*)
let getIndex =
let rec getIndex' trec target acc =
match trec with
| SigmaLast (None, _) -> raise Not_found
| ( SigmaLast (Some name, _)
| SigmaElem (name, _, _)
) when Name.(name = target) -> acc
| SigmaLast (Some _, _) -> failwith "Projection Not found"
| SigmaElem (_, _, trec') -> getIndex' trec' target (acc + 1)
in fun trec target -> getIndex' trec target 1
let is_explicit =
function
| Decl (_, _, _, Inductivity.Inductive)
| Decl (_, _, Plicity.Explicit, _) -> true
| _ -> false
let name_of_ctyp_decl (d : ctyp_decl) =
match d with
| Decl (n, _, _, _) -> n
| DeclOpt (n, _) -> n
* Decides whether the given mfront is a variable ,
viz . [ projection of a ] pattern variable , metavariable , or
context variable .
Returns the offset of the variable , and optionally the
projection offset .
viz. [projection of a] pattern variable, metavariable, or
context variable.
Returns the offset of the variable, and optionally the
projection offset.
*)
let variable_of_mfront (mf : mfront) : (offset * offset option) option =
match mf with
| ClObj (_, MObj (Root (_, MVar (Offset x, _), _, _)))
| CObj (CtxVar (CtxOffset x))
| ClObj (_ , MObj (Root (_, PVar (x, _), _, _)))
| ClObj (_ , PObj (PVar (x, _))) ->
Some (x, None)
| ClObj (_, MObj (Root (_, Proj (PVar (x, _), k ), _, _)))
| ClObj (_, PObj (Proj (PVar (x, _), k))) ->
Some (x, Some k)
| _ -> None
let get_constraint_id =
function
| Eqn (id, _, _, _, _) -> id
| Queued id -> id
let rec drop_spine k =
function
| tS when k = 0 -> tS
| Nil -> Nil
| App (_, tS') -> drop_spine (k - 1) tS'
| SClo (tS', _) -> drop_spine (k - 1) tS'
end
Internal Computation Syntax
module Comp = struct
include Syncom.Harpoon
include Syncom.Comp
type kind =
| Ctype of Location.t
| PiKind of Location.t * LF.ctyp_decl * kind
type meta_typ = LF.ctyp
type meta_obj = Location.t * LF.mfront
type meta_spine =
| MetaNil
| MetaApp of meta_obj * meta_typ (* annotation for pretty printing*)
* meta_spine * Plicity.t
type typ =
| TypBase of Location.t * cid_comp_typ * meta_spine
| TypCobase of Location.t * cid_comp_cotyp * meta_spine
| TypDef of Location.t * cid_comp_typ * meta_spine
| TypBox of Location.t * meta_typ
| TypArr of Location.t * typ * typ
| TypCross of Location.t * typ List2.t
| TypPiBox of Location.t * LF.ctyp_decl * typ
| TypClo of typ * LF.msub
| TypInd of typ
type suffices_typ = typ generic_suffices_typ
let rec loc_of_typ : typ -> Location.t =
function
| TypBase (l, _, _) | TypCobase (l, _, _) | TypDef (l, _, _)
| TypBox (l, _) | TypArr (l, _, _) | TypCross (l, _)
| TypPiBox (l, _, _) ->
l
| TypClo (tau, _) | TypInd tau -> loc_of_typ tau
let loc_of_suffices_typ : suffices_typ -> Location.t =
function
| `exact tau -> loc_of_typ tau
| `infer loc -> loc
type ih_arg =
| M of meta_obj * meta_typ
| V of offset
| E (* what is E? -je *)
| DC
^ For arguments that not constrained in the IH call . Stands
for do n't care .
for don't care. *)
type wf_tag = bool (* indicates whether the argument is smaller *)
type ctyp_decl =
| CTypDecl of Name.t * typ * wf_tag
(** Used during pretty-printing when going under lambdas. *)
| CTypDeclOpt of Name.t
type ih_decl =
| WfRec of Name.t * ih_arg list * typ
let rename_ctyp_decl f =
function
| CTypDecl (x, tau, tag) -> CTypDecl (f x, tau, tag)
| CTypDeclOpt x -> CTypDeclOpt (f x)
type gctx = ctyp_decl LF.ctx
type ihctx = ih_decl LF.ctx
(** Normal computational terms *)
and exp = (* e := *)
| \x . e '
| Fun of Location.t * fun_branches (* | b_1...b_k *)
| MLam of Location.t * Name.t * exp * Plicity.t (* | Pi X.e' *)
| Tuple of Location.t * exp List2.t (* | (e1, e2, ..., en) *)
| let ( x1 = i.1 , x2 = i.2 , ... , xn ) = i in e
| Let of Location.t * exp * (Name.t * exp) (* | let x = e' in e'' *)
| Box of Location.t * meta_obj * meta_typ (* for printing *) (* | Box (C) : [U] *)
| Case of Location.t * case_pragma * exp * branch list (* | case e of branches *)
| Impossible of Location.t * exp (* | impossible e *)
| Hole of Location.t * HoleId.t * HoleId.name (* | _ *)
| Var of Location.t * offset (* | x:tau in cG *)
| DataConst of Location.t * cid_comp_const (* | c:tau in Comp. Sig. *)
| Obs of Location.t * exp * LF.msub * cid_comp_dest (* | observation (e, ms, destructor={typ, ret_typ} *)
| Const of Location.t * cid_prog (* | theorem cp *)
| ( n : tau_1 - > tau_2 ) ( e : )
| MApp of Location.t * exp * meta_obj * meta_typ (* for printing *) * Plicity.t (* | (Pi X:U. e': tau) (C : U) *)
| [ cPsihat ] : [ cPsi |- tA ]
and pattern =
| PatMetaObj of Location.t * meta_obj
| PatConst of Location.t * cid_comp_const * pattern_spine
| PatFVar of Location.t * Name.t (* used only _internally_ by coverage *)
| PatVar of Location.t * offset
| PatTuple of Location.t * pattern List2.t
| PatAnn of Location.t * pattern * typ * Plicity.t
and pattern_spine =
| PatNil
| PatApp of Location.t * pattern * pattern_spine
| PatObs of Location.t * cid_comp_dest * LF.msub * pattern_spine
and branch =
| Branch
of Location.t
* LF.mctx (* branch prefix *)
* (LF.mctx * gctx) (* branch contexts *)
* pattern
* LF.msub (* refinement substitution for the branch *)
* exp
and fun_branches =
| NilFBranch of Location.t
| ConsFBranch of Location.t * (LF.mctx * gctx * pattern_spine * exp) * fun_branches
type tclo = typ * LF.msub
type order = int generic_order
type 'order total_dec_kind =
[ `inductive of 'order
| `not_recursive
| `trust (* trusted *)
| `partial (* not total *)
]
let map_total_dec_kind (f : 'o1 -> 'o2) : 'o1 total_dec_kind -> 'o2 total_dec_kind =
function
| `inductive o -> `inductive (f o)
| x -> x
let option_of_total_dec_kind =
function
| `inductive o -> Some o
| _ -> None
(** Applies a spine of checkable terms to a synthesizable term, from
left to right. *)
let rec apply_many i =
function
| [] -> i
| e :: es -> apply_many (Apply (Location.ghost, i, e)) es
let loc_of_exp =
function
| Fn (loc, _, _)
| Fun (loc, _)
| MLam (loc, _, _, _)
| Tuple (loc, _)
| LetTuple (loc, _, _)
| Let (loc, _, _)
| Box (loc, _, _)
| Case (loc, _, _, _)
| Impossible (loc, _)
| Hole (loc, _, _)
| Var (loc, _)
| DataConst (loc, _)
| Obs (loc, _, _, _)
| Const (loc, _)
| Apply (loc, _, _)
| MApp (loc, _, _, _, _)
| AnnBox (loc, _, _) -> loc
type total_dec =
{ name : Name.t
; tau : typ
; order: order total_dec_kind
}
let make_total_dec name tau order =
{ name; tau; order }
(** Decides whether this synthesizable expression is actually an
annotated box.
*)
let is_meta_obj : exp -> meta_obj option =
function
| AnnBox (_, m, _) -> Some m
| _ -> None
let head_of_meta_obj : meta_obj -> (LF.dctx_hat * LF.head) option =
let open LF in
function
| (_, ClObj (phat, MObj (Root (_, h, _, _)))) -> Some (phat, h)
| _ -> None
let itermToClObj =
function
| LF.INorm n -> LF.MObj n
| LF.IHead h -> LF.PObj h
| LF.ISub s -> LF.SObj s
| _ -> failwith "can't convert iterm to clobj"
let metaObjToMFront (_loc, x) = x
(** Finds the head of an application. Chases meta-applications and
computation applications.
*)
let rec head_of_application : exp -> exp =
function
| Apply (_, i, _) -> head_of_application i
| MApp (_, i, _, _, _) -> head_of_application i
| i -> i
(** Removes all type annotations from a pattern. *)
let rec strip_pattern : pattern -> pattern =
function
| PatTuple (loc, ps) ->
PatTuple (loc, List2.map strip_pattern ps)
| PatAnn (loc, p, _, _) -> p
| PatConst (loc, c, pS) ->
PatConst (loc, c, strip_pattern_spine pS)
| p -> p (* no subpatterns *)
and strip_pattern_spine : pattern_spine -> pattern_spine =
function
| PatNil -> PatNil
| PatApp (loc, p, pS) ->
PatApp (loc, strip_pattern p, strip_pattern_spine pS)
(* Bundle of LF and computational hypotheses. *)
type hypotheses =
Delta / meta context / LF assumptions
Gamma / computation assumptions
; cIH : ihctx (* Generated induction hypotheses. *)
}
let no_hypotheses = { cD = LF.Empty; cG = LF.Empty; cIH = LF.Empty }
type meta_branch_label =
[ `ctor of cid_term
| `pvar of int option
(* used when matching on a pvar in a nonempty context; this means
the pvar is actually the head variable in the context. *)
| `bvar
]
module SubgoalPath = struct
type t =
| Here
| Intros of t
| Suffices of exp * int * t
| MetaSplit of exp * meta_branch_label * t
| CompSplit of exp * cid_comp_const * t
| ContextSplit of exp * context_case * t
let equals p1 p2 = assert false
type builder = t -> t
let start = fun p -> p
let append (b1 : builder) (b2 : builder) : builder =
fun p -> b1 (b2 p)
let build_here (b : builder) : t =
b Here
let build_intros = fun p -> Intros p
let build_suffices i k = fun p -> Suffices (i, k, p)
let build_meta_split i lbl = fun p -> MetaSplit (i, lbl, p)
let build_comp_split i lbl = fun p -> CompSplit (i, lbl, p)
let build_context_split i lbl = fun p -> ContextSplit (i, lbl, p)
end
(* A proof is a sequence of statements ending either as a complete proof or an incomplete proof.*)
type proof =
| Incomplete (* hole *)
of Location.t * proof_state
| Command of command * proof
| Directive of directive (* which can end proofs or split into subgoals *)
and command =
| By of exp * Name.t * typ
| Unbox of exp * Name.t * LF.ctyp * unbox_modifier option
(* ^ The stored ctyp is the type synthesized for the exp, BEFORE
the application of any unbox_modifier *)
and proof_state =
{ context : hypotheses (* all the assumptions *)
(* The full context in scope at this point. *)
; label : SubgoalPath.builder
(* A list of labels representing where we are in the proof.
Used to generate a label for the state by assembling them. *)
; goal : tclo
The goal of this proof state . Contains a type with a delayed msub .
; solution : proof option ref
(* The solution to this proof obligation. Filled in by a tactic later. *)
}
and directive =
| Intros (* Prove a function type by a hypothetical derivation. *)
of hypothetical
| Solve (* End the proof with the given term *)
of exp
| ImpossibleSplit
of exp
| Suffices
of exp (* i -- the function to invoke *)
* suffices_arg list
(* ^ the arguments of the function *)
| MetaSplit (* Splitting on an LF object *)
of exp (* The object to split on *)
* typ (* The type of the object that we're splitting on *)
* meta_branch list
| CompSplit (* Splitting on an inductive type *)
of exp (* THe computational term to split on *)
* typ (* The type of the object to split on *)
* comp_branch list
| ContextSplit (* Splitting on a context *)
of exp (* The scrutinee *)
* typ (* The type of the scrutinee *)
* context_branch list
and suffices_arg = Location.t * typ * proof
and context_branch = context_case split_branch
and meta_branch = meta_branch_label split_branch
and comp_branch = cid_comp_const split_branch
(** A general branch of a case analysis. *)
and 'b split_branch =
| SplitBranch
(* the case label for this branch *)
of 'b
(* the full pattern generated for this branch *)
* (gctx * pattern)
(* refinement substitution for this branch *)
* LF.msub
(* the derivation for this case *)
* hypothetical
and cG are the contexts when checking a split .
Suppose we have a branch b = SplitBranch ( lbl , t , ; cG = cG_b ; _ } ) .
Then t : cD
and the context cG_b to use to check inside the branch is obtained
from cG ' = [ t]cG
Suppose we have a branch b = SplitBranch (lbl, t, { cD = cD_b; cG = cG_b; _ }).
Then cD_b |- t : cD
and the context cG_b to use to check inside the branch is obtained
from cG' = [t]cG
*)
(** A hypothetical derivation lists meta-hypotheses and hypotheses,
then proceeds with a proof.
*)
and hypothetical =
Hypothetical
of Location.t
* hypotheses (* the full contexts *)
* proof (* the proof; should make sense in `hypotheses`. *)
* An open subgoal is a proof state together with a reference ot the
theorem in which it occurs .
theorem in which it occurs.
*)
type open_subgoal = cid_prog * proof_state
* Generates a unsolved subgoal with the given goal in an empty
context , with no label .
context, with no label.
*)
let make_proof_state label (t : tclo) : proof_state =
{ context = no_hypotheses
; goal = t
; label
; solution = ref None
}
(** Smart constructor for an unfinished proof ending. *)
let incomplete_proof (l : Location.t) (s : proof_state) : proof =
Incomplete (l, s)
(** Smart constructor for the intros directive. *)
let intros (h : hypotheses) (proof : proof) : proof =
Directive (Intros (Hypothetical (Location.ghost, h, proof)))
let suffices (i : exp) (ps : suffices_arg list) : proof =
Directive (Suffices (i, ps))
let proof_cons (stmt : command) (proof : proof) = Command (stmt, proof)
let solve (t : exp) : proof =
Directive (Solve t)
let context_split (i : exp) (tau : typ) (bs : context_branch list)
: proof =
Directive (ContextSplit (i, tau, bs))
let context_branch (c : context_case) (cG_p, pat) (t : LF.msub) (h : hypotheses) (p : proof)
: context_branch =
SplitBranch (c, (cG_p, pat), t, (Hypothetical (Location.ghost, h, p)))
let meta_split (m : exp) (a : typ) (bs : meta_branch list)
: proof =
Directive (MetaSplit (m, a, bs))
let impossible_split (i : exp) : proof =
Directive (ImpossibleSplit i)
let meta_branch
(c : meta_branch_label)
(cG_p, pat)
(t : LF.msub)
(h : hypotheses)
(p : proof)
: meta_branch =
SplitBranch (c, (cG_p, pat), t, (Hypothetical (Location.ghost, h, p)))
let comp_split (t : exp) (tau : typ) (bs : comp_branch list)
: proof =
Directive (CompSplit (t, tau, bs))
let comp_branch
(c : cid_comp_const)
(cG_p, pat)
(t : LF.msub)
(h : hypotheses)
(d : proof)
: comp_branch =
SplitBranch (c, (cG_p, pat), t, (Hypothetical (Location.ghost, h, d)))
(** Gives a more convenient way of writing complex proofs by using list syntax. *)
let prepend_commands (cmds : command list) (proof : proof)
: proof =
List.fold_right proof_cons cmds proof
let name_of_ctyp_decl =
function
| CTypDecl (name, _, _) -> name
| CTypDeclOpt name -> name
(** Decides whether the computational term is actually a variable
index object.
See `LF.variable_of_mfront`.
*)
let metavariable_of_exp : exp -> (offset * offset option) option =
function
| AnnBox (_, (_, mf), _) -> LF.variable_of_mfront mf
| _ -> None
(* Decides whether the given term is a computational variable.
Returns the offset of the variable.
*)
let variable_of_exp : exp -> offset option =
function
| Var (_, k) -> Some k
| _ -> None
type thm =
| Proof of proof
| Program of exp
type env =
| Empty
| Cons of value * env
(* Syntax of values, used by the operational semantics *)
and value =
| FnValue of Name.t * exp * LF.msub * env
| FunValue of fun_branches_value
| ThmValue of cid_prog * thm * LF.msub * env
| MLamValue of Name.t * exp * LF.msub * env
| CtxValue of Name.t * exp * LF.msub * env
| BoxValue of meta_obj
| ConstValue of cid_prog
| DataValue of cid_comp_const * data_spine
| TupleValue of value List2.t
(* Arguments in data spines are accumulated in reverse order, to
allow applications of data values in constant time. *)
and data_spine =
| DataNil
| DataApp of value * data_spine
and fun_branches_value =
| NilValBranch
| ConsValBranch of (pattern_spine * exp * LF.msub * env) * fun_branches_value
end
(* Internal Signature Syntax *)
module Sgn = struct
(* type positivity_flag = *)
(* | Noflag *)
(* | Positivity *)
(* | Stratify of Location.t * Comp.order * Name.t * (Name.t option) list *)
type positivity_flag =
| Nocheck
| Positivity
| Stratify of Location.t * int
| StratifyAll of Location.t
type thm_decl =
| Theorem of
{ name : cid_prog
; typ : Comp.typ
; body : Comp.thm
; location : Location.t
}
(** Reconstructed signature element *)
type decl =
| Typ of
{ location: Location.t
; identifier: cid_typ
; kind: LF.kind
} (** LF type family declaration *)
| Const of
{ location: Location.t
; identifier: cid_term
; typ: LF.typ
} (** LF type constant decalaration *)
| CompTyp of
{ location: Location.t
; identifier: Name.t
; kind: Comp.kind
; positivity_flag: positivity_flag
} (** Computation-level data type constant declaration *)
| CompCotyp of
{ location: Location.t
; identifier: Name.t
; kind: Comp.kind
} (** Computation-level codata type constant declaration *)
| CompConst of
{ location: Location.t
; identifier: Name.t
; typ: Comp.typ
} (** Computation-level type constructor declaration *)
| CompDest of
{ location: Location.t
; identifier: Name.t
; mctx: LF.mctx
; observation_typ: Comp.typ
; return_typ: Comp.typ
} (** Computation-level type destructor declaration *)
| CompTypAbbrev of
{ location: Location.t
; identifier: Name.t
; kind: Comp.kind
; typ: Comp.typ
} (** Synonym declaration for computation-level type *)
| Schema of
{ location: Location.t
; identifier: cid_schema
; schema: LF.schema
} (** Declaration of a specification for a set of contexts *)
| Theorems of
{ location: Location.t
; theorems: thm_decl List1.t
} (** Mutually recursive theorem declaration(s) *)
| Pragma of
{ pragma: LF.prag
} (** Compiler directive *)
| Val of
{ location: Location.t
; identifier: Name.t
; typ: Comp.typ
; expression: Comp.exp
; expression_value: Comp.value option
} (** Computation-level value declaration *)
| MRecTyp of
{ location: Location.t
; declarations: decl list List1.t
} (** Mutually-recursive LF type family declaration *)
| Module of
{ location: Location.t
; identifier: string
; declarations: decl list
} (** Namespace declaration for other declarations *)
| Query of
{ location: Location.t
; name: Name.t option
; mctx: LF.mctx
; typ: (LF.typ * Id.offset)
; expected_solutions: int option
; maximum_tries: int option
} (** Logic programming query on LF type *)
| MQuery of
{ location: Location.t
; typ: (Comp.typ * Id.offset)
; expected_solutions: int option
; search_tries: int option
; search_depth: int option
} (** Logic programming mquery on Comp. type *)
| Comment of
{ location: Location.t
; content: string
} (** Documentation comment *)
(** Reconstructed Beluga project *)
type sgn = decl list
end
| null | https://raw.githubusercontent.com/Beluga-lang/Beluga/db2213de17924adffe8a1c2a25458db031eb0778/src/core/synint.ml | ocaml | Internal Syntax
LF Declarations
D := x:A
| x:_
Contextual Declarations
LF level
| TClo(A,s)
The plicity annotation is set to `implicit when reconstructing an
a hole (_) so that when printing, it can be reproduced correctly.
normal terms
| h . S
| Clo(N,s)
H ::= x
| c
| u[t ; s]
| p[t ; s]
| u[s]
| p[s]
| (H:A)
| x.k | #p.k s
free variable for type
reconstruction
free meta-variable for type
reconstruction
free parameter variable for type
reconstruction
| HMClo(x, #S[theta;sigma])
spine
| M . S
| SClo(S,s)
| s[sigma]
| Ft . s
| u[t ; s]
Ft ::= H
| N
| _
Contextual substitutions
| Psi
| u//u | p//p | psi/psi
This shouldn't be here, we should use a different datastructure for
partial inverse substitutions
ContextuaL objects
Mft::= Psihat.N
| Psihat.p[s] | Psihat.x
Contextual substitutions
| MFt . theta
Contextual Variables
Bound Variables
D ; Psi |- M <= A provided constraint
not really used
unique identifiers attached to constraints, used for debugging
Constraint
constraint ::= Queued
LF Context
Psi ::= .
| psi
| Psi, x:A or x:block ...
D |- Psi : schema
Schema Element
Pi x1:A1 ... xn:An.
Sigma y1:B1 ... yk:Bk. B
Psihat ::=
| psi
| .
| Psihat, x
Sigma x1:A1 ... xn:An. B
... . B
xk : Ak, ...
* Forms an MMVar instantiation by attaching an LF substitution and
a meta-substituation to the variable.
********************
Type Abbreviations
********************
Ss = [s]S
As = [s]A
********************
Helpers
********************
getIndex traverses the typ_rec from left to right;
target is the name of the projection we're looking for
annotation for pretty printing
what is E? -je
indicates whether the argument is smaller
* Used during pretty-printing when going under lambdas.
* Normal computational terms
e :=
| b_1...b_k
| Pi X.e'
| (e1, e2, ..., en)
| let x = e' in e''
for printing
| Box (C) : [U]
| case e of branches
| impossible e
| _
| x:tau in cG
| c:tau in Comp. Sig.
| observation (e, ms, destructor={typ, ret_typ}
| theorem cp
for printing
| (Pi X:U. e': tau) (C : U)
used only _internally_ by coverage
branch prefix
branch contexts
refinement substitution for the branch
trusted
not total
* Applies a spine of checkable terms to a synthesizable term, from
left to right.
* Decides whether this synthesizable expression is actually an
annotated box.
* Finds the head of an application. Chases meta-applications and
computation applications.
* Removes all type annotations from a pattern.
no subpatterns
Bundle of LF and computational hypotheses.
Generated induction hypotheses.
used when matching on a pvar in a nonempty context; this means
the pvar is actually the head variable in the context.
A proof is a sequence of statements ending either as a complete proof or an incomplete proof.
hole
which can end proofs or split into subgoals
^ The stored ctyp is the type synthesized for the exp, BEFORE
the application of any unbox_modifier
all the assumptions
The full context in scope at this point.
A list of labels representing where we are in the proof.
Used to generate a label for the state by assembling them.
The solution to this proof obligation. Filled in by a tactic later.
Prove a function type by a hypothetical derivation.
End the proof with the given term
i -- the function to invoke
^ the arguments of the function
Splitting on an LF object
The object to split on
The type of the object that we're splitting on
Splitting on an inductive type
THe computational term to split on
The type of the object to split on
Splitting on a context
The scrutinee
The type of the scrutinee
* A general branch of a case analysis.
the case label for this branch
the full pattern generated for this branch
refinement substitution for this branch
the derivation for this case
* A hypothetical derivation lists meta-hypotheses and hypotheses,
then proceeds with a proof.
the full contexts
the proof; should make sense in `hypotheses`.
* Smart constructor for an unfinished proof ending.
* Smart constructor for the intros directive.
* Gives a more convenient way of writing complex proofs by using list syntax.
* Decides whether the computational term is actually a variable
index object.
See `LF.variable_of_mfront`.
Decides whether the given term is a computational variable.
Returns the offset of the variable.
Syntax of values, used by the operational semantics
Arguments in data spines are accumulated in reverse order, to
allow applications of data values in constant time.
Internal Signature Syntax
type positivity_flag =
| Noflag
| Positivity
| Stratify of Location.t * Comp.order * Name.t * (Name.t option) list
* Reconstructed signature element
* LF type family declaration
* LF type constant decalaration
* Computation-level data type constant declaration
* Computation-level codata type constant declaration
* Computation-level type constructor declaration
* Computation-level type destructor declaration
* Synonym declaration for computation-level type
* Declaration of a specification for a set of contexts
* Mutually recursive theorem declaration(s)
* Compiler directive
* Computation-level value declaration
* Mutually-recursive LF type family declaration
* Namespace declaration for other declarations
* Logic programming query on LF type
* Logic programming mquery on Comp. type
* Documentation comment
* Reconstructed Beluga project | open Support.Equality
open Support
open Id
Internal LF Syntax
module LF = struct
include Syncom.LF
type kind =
| Typ
| PiKind of (typ_decl * Plicity.t) * kind
and cltyp =
| MTyp of typ
| PTyp of typ
| STyp of svar_class * dctx
and ctyp =
| ClTyp of cltyp * dctx
| CTyp of cid_schema option
| Decl of Name.t * ctyp * Plicity.t * Inductivity.t
| DeclOpt of Name.t * Plicity.t
A : : = a M1 ... Mn
| Pi x :
| Sigma of typ_rec
M : : = \x . M
| LFHole of Location.t * HoleId.t * HoleId.name
| Tuple of Location.t * tuple
TODO : Heads ought to carry their location .
currently needs to invent / pretend that a different
location is the correct one .
Erasure currently needs to invent / pretend that a different
location is the correct one.
*)
and head =
| HClo(x , # S[sigma ] )
and fvarsub = Name.t * sub
S : : =
and sub =
sigma : : = , n )
BEWARE : offset and int are both ints ,
and in the opposite order compared to FSVar and MSVar .
offset is the index into Delta and describes the SVar .
This is a pain to fix
and in the opposite order compared to FSVar and MSVar.
offset is the index into Delta and describes the SVar.
This is a pain to fix *)
| EmptySub
| Undefs
Fronts :
Fronts :
| ClObj of dctx_hat * clobj
| SObj of sub
theta : : =
and mm_var =
{ name : Name.t
; instantiation : iterm option ref
; cD : mctx
unique to each MMVar
; typ : ctyp
; plicity : Plicity.t
; inductivity : Inductivity.t
}
and mm_var_inst' = mm_var * msub
and mm_var_inst = mm_var_inst' * sub
and iterm =
| INorm of normal
| IHead of head
| ISub of sub
| ICtx of dctx
and tvar =
| TInst of typ option ref * dctx * kind * cnstr list ref
and constrnt_id = int
| Delta ; Psi |-(M1 = = M2 )
and cnstr = constrnt ref
and ctx_var =
| CtxName of Name.t
| CtxOffset of offset
| CInst of mm_var_inst'
Sigma - types not allowed in Ai
and schema =
| Schema of sch_elem list
and tuple =
| Last of normal
| Cons of normal * tuple
Modal Context D : CDec ctx
let map_plicity f =
function
| Root (loc, tH, tS, plicity) ->
Root (loc, tH, tS, f plicity)
| tM -> tM
let proj_maybe (h : head) : int option -> head =
function
| None -> h
| Some k -> Proj (h, k)
* Helper for forming TClo LF types , which avoids doing so if the
substitution is the identity .
substitution is the identity.
*)
let tclo tA s =
match s with
| Shift 0 -> tA
| _ -> TClo (tA, s)
let mm_var_inst (u : mm_var) (t : msub) (s : sub): mm_var_inst = (u, t), s
let is_mmvar_instantiated mmvar = Option.is_some (mmvar.instantiation.contents)
let type_of_mmvar_instantiated mmvar = (mmvar.typ)
let rename_ctyp_decl f =
function
| Decl (x, tA, plicity, inductivity) -> Decl (f x, tA, plicity, inductivity)
| DeclOpt (x, plicity) -> DeclOpt (f x, plicity)
* a head into a normal by using an empty spine .
Very useful for constructing variables as normals .
Note that the normal will have a ghost location , as heads do n't
carry a location .
Very useful for constructing variables as normals.
Note that the normal will have a ghost location, as heads don't
carry a location.
*)
let head (tH : head) : normal =
Root (Location.ghost, tH, Nil, Plicity.explicit)
let mvar cvar sub : head =
MVar (cvar, sub)
let mmvar inst = MMVar inst
let mpvar inst = MPVar inst
* Assert that the contextual type declaration be a real , and
not a DeclOpt .
Raises a violation if it is a DeclOpt .
not a DeclOpt.
Raises a violation if it is a DeclOpt.
*)
let require_decl : ctyp_decl -> Name.t * ctyp * Plicity.t * Inductivity.t =
function
| Decl (u, cU, plicity, inductivity) -> (u, cU, plicity, inductivity)
| DeclOpt _ ->
Error.violation "[require_decl] DeclOpt is forbidden"
Hatted version of LF.Null
let null_hat : dctx_hat = (None, 0)
let rec loc_of_normal =
function
| Lam (loc, _, _) -> loc
| Root (loc, _, _, _) -> loc
| LFHole (loc, _, _) -> loc
| Clo (tM, _) -> loc_of_normal tM
| Tuple (loc, _) -> loc
Ns = [ s]N
[
type prag =
| NamePrag of cid_typ
| NotPrag
| OpenPrag of module_id
| DefaultAssocPrag of Associativity.t
| FixPrag of Name.t * Fixity.t * int * Associativity.t option
| AbbrevPrag of string list * string
let rec blockLength =
function
| SigmaLast _ -> 1
| SigmaElem(_x, _tA, recA) -> 1 + blockLength recA
getType traverses the typ_rec from left to right ;
target is relative to the remaining suffix of the type
s_recA target j = ( tA , s ' )
if Psi(head ) = Sigma recA '
and [ s]recA is a suffix of recA '
then
Psi |- [ s']tA < = type
val getType : head - > trec_clo - > int - > tclo
target is relative to the remaining suffix of the type
getType head s_recA target j = (tA, s')
if Psi(head) = Sigma recA'
and [s]recA is a suffix of recA'
then
Psi |- [s']tA <= type
val getType : head -> trec_clo -> int -> tclo
*)
let getType =
let rec getType head s_recA target j =
match (s_recA, target) with
| ((SigmaLast (_, lastA), s), 1) ->
(lastA, s)
| ((SigmaElem (_x, tA, _recA), s), 1) ->
(tA, s)
| ((SigmaElem (_x, _tA, recA), s), target) ->
let tPj = Proj (head, j) in
getType head (recA, Dot (Head tPj, s)) (target - 1) (j + 1)
| _ -> raise Not_found
in
fun head s_recA target -> getType head s_recA target 1
let getIndex =
let rec getIndex' trec target acc =
match trec with
| SigmaLast (None, _) -> raise Not_found
| ( SigmaLast (Some name, _)
| SigmaElem (name, _, _)
) when Name.(name = target) -> acc
| SigmaLast (Some _, _) -> failwith "Projection Not found"
| SigmaElem (_, _, trec') -> getIndex' trec' target (acc + 1)
in fun trec target -> getIndex' trec target 1
let is_explicit =
function
| Decl (_, _, _, Inductivity.Inductive)
| Decl (_, _, Plicity.Explicit, _) -> true
| _ -> false
let name_of_ctyp_decl (d : ctyp_decl) =
match d with
| Decl (n, _, _, _) -> n
| DeclOpt (n, _) -> n
* Decides whether the given mfront is a variable ,
viz . [ projection of a ] pattern variable , metavariable , or
context variable .
Returns the offset of the variable , and optionally the
projection offset .
viz. [projection of a] pattern variable, metavariable, or
context variable.
Returns the offset of the variable, and optionally the
projection offset.
*)
let variable_of_mfront (mf : mfront) : (offset * offset option) option =
match mf with
| ClObj (_, MObj (Root (_, MVar (Offset x, _), _, _)))
| CObj (CtxVar (CtxOffset x))
| ClObj (_ , MObj (Root (_, PVar (x, _), _, _)))
| ClObj (_ , PObj (PVar (x, _))) ->
Some (x, None)
| ClObj (_, MObj (Root (_, Proj (PVar (x, _), k ), _, _)))
| ClObj (_, PObj (Proj (PVar (x, _), k))) ->
Some (x, Some k)
| _ -> None
let get_constraint_id =
function
| Eqn (id, _, _, _, _) -> id
| Queued id -> id
let rec drop_spine k =
function
| tS when k = 0 -> tS
| Nil -> Nil
| App (_, tS') -> drop_spine (k - 1) tS'
| SClo (tS', _) -> drop_spine (k - 1) tS'
end
Internal Computation Syntax
module Comp = struct
include Syncom.Harpoon
include Syncom.Comp
type kind =
| Ctype of Location.t
| PiKind of Location.t * LF.ctyp_decl * kind
type meta_typ = LF.ctyp
type meta_obj = Location.t * LF.mfront
type meta_spine =
| MetaNil
* meta_spine * Plicity.t
type typ =
| TypBase of Location.t * cid_comp_typ * meta_spine
| TypCobase of Location.t * cid_comp_cotyp * meta_spine
| TypDef of Location.t * cid_comp_typ * meta_spine
| TypBox of Location.t * meta_typ
| TypArr of Location.t * typ * typ
| TypCross of Location.t * typ List2.t
| TypPiBox of Location.t * LF.ctyp_decl * typ
| TypClo of typ * LF.msub
| TypInd of typ
type suffices_typ = typ generic_suffices_typ
let rec loc_of_typ : typ -> Location.t =
function
| TypBase (l, _, _) | TypCobase (l, _, _) | TypDef (l, _, _)
| TypBox (l, _) | TypArr (l, _, _) | TypCross (l, _)
| TypPiBox (l, _, _) ->
l
| TypClo (tau, _) | TypInd tau -> loc_of_typ tau
let loc_of_suffices_typ : suffices_typ -> Location.t =
function
| `exact tau -> loc_of_typ tau
| `infer loc -> loc
type ih_arg =
| M of meta_obj * meta_typ
| V of offset
| DC
^ For arguments that not constrained in the IH call . Stands
for do n't care .
for don't care. *)
type ctyp_decl =
| CTypDecl of Name.t * typ * wf_tag
| CTypDeclOpt of Name.t
type ih_decl =
| WfRec of Name.t * ih_arg list * typ
let rename_ctyp_decl f =
function
| CTypDecl (x, tau, tag) -> CTypDecl (f x, tau, tag)
| CTypDeclOpt x -> CTypDeclOpt (f x)
type gctx = ctyp_decl LF.ctx
type ihctx = ih_decl LF.ctx
| \x . e '
| let ( x1 = i.1 , x2 = i.2 , ... , xn ) = i in e
| ( n : tau_1 - > tau_2 ) ( e : )
| [ cPsihat ] : [ cPsi |- tA ]
and pattern =
| PatMetaObj of Location.t * meta_obj
| PatConst of Location.t * cid_comp_const * pattern_spine
| PatVar of Location.t * offset
| PatTuple of Location.t * pattern List2.t
| PatAnn of Location.t * pattern * typ * Plicity.t
and pattern_spine =
| PatNil
| PatApp of Location.t * pattern * pattern_spine
| PatObs of Location.t * cid_comp_dest * LF.msub * pattern_spine
and branch =
| Branch
of Location.t
* pattern
* exp
and fun_branches =
| NilFBranch of Location.t
| ConsFBranch of Location.t * (LF.mctx * gctx * pattern_spine * exp) * fun_branches
type tclo = typ * LF.msub
type order = int generic_order
type 'order total_dec_kind =
[ `inductive of 'order
| `not_recursive
]
let map_total_dec_kind (f : 'o1 -> 'o2) : 'o1 total_dec_kind -> 'o2 total_dec_kind =
function
| `inductive o -> `inductive (f o)
| x -> x
let option_of_total_dec_kind =
function
| `inductive o -> Some o
| _ -> None
let rec apply_many i =
function
| [] -> i
| e :: es -> apply_many (Apply (Location.ghost, i, e)) es
let loc_of_exp =
function
| Fn (loc, _, _)
| Fun (loc, _)
| MLam (loc, _, _, _)
| Tuple (loc, _)
| LetTuple (loc, _, _)
| Let (loc, _, _)
| Box (loc, _, _)
| Case (loc, _, _, _)
| Impossible (loc, _)
| Hole (loc, _, _)
| Var (loc, _)
| DataConst (loc, _)
| Obs (loc, _, _, _)
| Const (loc, _)
| Apply (loc, _, _)
| MApp (loc, _, _, _, _)
| AnnBox (loc, _, _) -> loc
type total_dec =
{ name : Name.t
; tau : typ
; order: order total_dec_kind
}
let make_total_dec name tau order =
{ name; tau; order }
let is_meta_obj : exp -> meta_obj option =
function
| AnnBox (_, m, _) -> Some m
| _ -> None
let head_of_meta_obj : meta_obj -> (LF.dctx_hat * LF.head) option =
let open LF in
function
| (_, ClObj (phat, MObj (Root (_, h, _, _)))) -> Some (phat, h)
| _ -> None
let itermToClObj =
function
| LF.INorm n -> LF.MObj n
| LF.IHead h -> LF.PObj h
| LF.ISub s -> LF.SObj s
| _ -> failwith "can't convert iterm to clobj"
let metaObjToMFront (_loc, x) = x
let rec head_of_application : exp -> exp =
function
| Apply (_, i, _) -> head_of_application i
| MApp (_, i, _, _, _) -> head_of_application i
| i -> i
let rec strip_pattern : pattern -> pattern =
function
| PatTuple (loc, ps) ->
PatTuple (loc, List2.map strip_pattern ps)
| PatAnn (loc, p, _, _) -> p
| PatConst (loc, c, pS) ->
PatConst (loc, c, strip_pattern_spine pS)
and strip_pattern_spine : pattern_spine -> pattern_spine =
function
| PatNil -> PatNil
| PatApp (loc, p, pS) ->
PatApp (loc, strip_pattern p, strip_pattern_spine pS)
type hypotheses =
Delta / meta context / LF assumptions
Gamma / computation assumptions
}
let no_hypotheses = { cD = LF.Empty; cG = LF.Empty; cIH = LF.Empty }
type meta_branch_label =
[ `ctor of cid_term
| `pvar of int option
| `bvar
]
module SubgoalPath = struct
type t =
| Here
| Intros of t
| Suffices of exp * int * t
| MetaSplit of exp * meta_branch_label * t
| CompSplit of exp * cid_comp_const * t
| ContextSplit of exp * context_case * t
let equals p1 p2 = assert false
type builder = t -> t
let start = fun p -> p
let append (b1 : builder) (b2 : builder) : builder =
fun p -> b1 (b2 p)
let build_here (b : builder) : t =
b Here
let build_intros = fun p -> Intros p
let build_suffices i k = fun p -> Suffices (i, k, p)
let build_meta_split i lbl = fun p -> MetaSplit (i, lbl, p)
let build_comp_split i lbl = fun p -> CompSplit (i, lbl, p)
let build_context_split i lbl = fun p -> ContextSplit (i, lbl, p)
end
type proof =
of Location.t * proof_state
| Command of command * proof
and command =
| By of exp * Name.t * typ
| Unbox of exp * Name.t * LF.ctyp * unbox_modifier option
and proof_state =
; label : SubgoalPath.builder
; goal : tclo
The goal of this proof state . Contains a type with a delayed msub .
; solution : proof option ref
}
and directive =
of hypothetical
of exp
| ImpossibleSplit
of exp
| Suffices
* suffices_arg list
* meta_branch list
* comp_branch list
* context_branch list
and suffices_arg = Location.t * typ * proof
and context_branch = context_case split_branch
and meta_branch = meta_branch_label split_branch
and comp_branch = cid_comp_const split_branch
and 'b split_branch =
| SplitBranch
of 'b
* (gctx * pattern)
* LF.msub
* hypothetical
and cG are the contexts when checking a split .
Suppose we have a branch b = SplitBranch ( lbl , t , ; cG = cG_b ; _ } ) .
Then t : cD
and the context cG_b to use to check inside the branch is obtained
from cG ' = [ t]cG
Suppose we have a branch b = SplitBranch (lbl, t, { cD = cD_b; cG = cG_b; _ }).
Then cD_b |- t : cD
and the context cG_b to use to check inside the branch is obtained
from cG' = [t]cG
*)
and hypothetical =
Hypothetical
of Location.t
* An open subgoal is a proof state together with a reference ot the
theorem in which it occurs .
theorem in which it occurs.
*)
type open_subgoal = cid_prog * proof_state
* Generates a unsolved subgoal with the given goal in an empty
context , with no label .
context, with no label.
*)
let make_proof_state label (t : tclo) : proof_state =
{ context = no_hypotheses
; goal = t
; label
; solution = ref None
}
let incomplete_proof (l : Location.t) (s : proof_state) : proof =
Incomplete (l, s)
let intros (h : hypotheses) (proof : proof) : proof =
Directive (Intros (Hypothetical (Location.ghost, h, proof)))
let suffices (i : exp) (ps : suffices_arg list) : proof =
Directive (Suffices (i, ps))
let proof_cons (stmt : command) (proof : proof) = Command (stmt, proof)
let solve (t : exp) : proof =
Directive (Solve t)
let context_split (i : exp) (tau : typ) (bs : context_branch list)
: proof =
Directive (ContextSplit (i, tau, bs))
let context_branch (c : context_case) (cG_p, pat) (t : LF.msub) (h : hypotheses) (p : proof)
: context_branch =
SplitBranch (c, (cG_p, pat), t, (Hypothetical (Location.ghost, h, p)))
let meta_split (m : exp) (a : typ) (bs : meta_branch list)
: proof =
Directive (MetaSplit (m, a, bs))
let impossible_split (i : exp) : proof =
Directive (ImpossibleSplit i)
let meta_branch
(c : meta_branch_label)
(cG_p, pat)
(t : LF.msub)
(h : hypotheses)
(p : proof)
: meta_branch =
SplitBranch (c, (cG_p, pat), t, (Hypothetical (Location.ghost, h, p)))
let comp_split (t : exp) (tau : typ) (bs : comp_branch list)
: proof =
Directive (CompSplit (t, tau, bs))
let comp_branch
(c : cid_comp_const)
(cG_p, pat)
(t : LF.msub)
(h : hypotheses)
(d : proof)
: comp_branch =
SplitBranch (c, (cG_p, pat), t, (Hypothetical (Location.ghost, h, d)))
let prepend_commands (cmds : command list) (proof : proof)
: proof =
List.fold_right proof_cons cmds proof
let name_of_ctyp_decl =
function
| CTypDecl (name, _, _) -> name
| CTypDeclOpt name -> name
let metavariable_of_exp : exp -> (offset * offset option) option =
function
| AnnBox (_, (_, mf), _) -> LF.variable_of_mfront mf
| _ -> None
let variable_of_exp : exp -> offset option =
function
| Var (_, k) -> Some k
| _ -> None
type thm =
| Proof of proof
| Program of exp
type env =
| Empty
| Cons of value * env
and value =
| FnValue of Name.t * exp * LF.msub * env
| FunValue of fun_branches_value
| ThmValue of cid_prog * thm * LF.msub * env
| MLamValue of Name.t * exp * LF.msub * env
| CtxValue of Name.t * exp * LF.msub * env
| BoxValue of meta_obj
| ConstValue of cid_prog
| DataValue of cid_comp_const * data_spine
| TupleValue of value List2.t
and data_spine =
| DataNil
| DataApp of value * data_spine
and fun_branches_value =
| NilValBranch
| ConsValBranch of (pattern_spine * exp * LF.msub * env) * fun_branches_value
end
module Sgn = struct
type positivity_flag =
| Nocheck
| Positivity
| Stratify of Location.t * int
| StratifyAll of Location.t
type thm_decl =
| Theorem of
{ name : cid_prog
; typ : Comp.typ
; body : Comp.thm
; location : Location.t
}
type decl =
| Typ of
{ location: Location.t
; identifier: cid_typ
; kind: LF.kind
| Const of
{ location: Location.t
; identifier: cid_term
; typ: LF.typ
| CompTyp of
{ location: Location.t
; identifier: Name.t
; kind: Comp.kind
; positivity_flag: positivity_flag
| CompCotyp of
{ location: Location.t
; identifier: Name.t
; kind: Comp.kind
| CompConst of
{ location: Location.t
; identifier: Name.t
; typ: Comp.typ
| CompDest of
{ location: Location.t
; identifier: Name.t
; mctx: LF.mctx
; observation_typ: Comp.typ
; return_typ: Comp.typ
| CompTypAbbrev of
{ location: Location.t
; identifier: Name.t
; kind: Comp.kind
; typ: Comp.typ
| Schema of
{ location: Location.t
; identifier: cid_schema
; schema: LF.schema
| Theorems of
{ location: Location.t
; theorems: thm_decl List1.t
| Pragma of
{ pragma: LF.prag
| Val of
{ location: Location.t
; identifier: Name.t
; typ: Comp.typ
; expression: Comp.exp
; expression_value: Comp.value option
| MRecTyp of
{ location: Location.t
; declarations: decl list List1.t
| Module of
{ location: Location.t
; identifier: string
; declarations: decl list
| Query of
{ location: Location.t
; name: Name.t option
; mctx: LF.mctx
; typ: (LF.typ * Id.offset)
; expected_solutions: int option
; maximum_tries: int option
| MQuery of
{ location: Location.t
; typ: (Comp.typ * Id.offset)
; expected_solutions: int option
; search_tries: int option
; search_depth: int option
| Comment of
{ location: Location.t
; content: string
type sgn = decl list
end
|
ad3108d9a96c584702cb758ad99f71c37a1776c4363b63a6acc18142a2352d3c | serhiip/org2any | Logging.hs | |
Module : Data . . Sync . Logging
Description : Logging utilities
License : GPL-3
Maintainer : < >
Stability : experimental
Log meassages of various log levels either via main transfromer stack
or via just IO . Uses
< -yamamoto/logger kazu - yamamoto / logger >
Module : Data.OrgMode.Sync.Logging
Description : Logging utilities
License : GPL-3
Maintainer : Serhii <>
Stability : experimental
Log meassages of various log levels either via main transfromer stack
or via just IO. Uses
<-yamamoto/logger kazu-yamamoto/logger>
-}
# LANGUAGE FlexibleContexts #
# LANGUAGE UndecidableInstances #
module Data.OrgMode.Sync.Logging
( initLogging
, logInfo'
, logError'
, logDebug'
, logInfoM
, logErrorM
, logDebugM
, MonadLogger(..)
)
where
import qualified Data.Text.Lazy as TL
import System.Log.FastLogger ( ToLogStr
, toLogStr
, newTimedFastLogger
, LogType(..)
, TimedFastLogger
)
import System.Log.FastLogger.Date ( newTimeCache
, simpleTimeFormat'
)
import Data.OrgMode.Sync.Types
import Universum
instance ToLogStr Severity where
toLogStr Debug = toLogStr $ TL.pack "[DEBUG]"
toLogStr Info = toLogStr $ TL.pack "[INFO] "
toLogStr Error = toLogStr $ TL.pack "[ERROR]"
-- | Logging severity and destination (STDOUT / STDERR)
data Severity
= Debug
| Info
| Error
deriving (Show, Eq, Ord)
-- | Helper function to initialize stderr and stdout loggers
initLogging :: IO (TimedFastLogger, TimedFastLogger, IO ())
initLogging = do
timeCache <- newTimeCache simpleTimeFormat'
(stdoutLogger, stdoutCleanUp ) <- newTimedFastLogger timeCache (LogStdout 1)
(stderrLogger, stderrCleanUp') <- newTimedFastLogger timeCache (LogStderr 1)
return (stdoutLogger, stderrLogger, stdoutCleanUp >> stderrCleanUp')
-- | Generic function to log messages. Logs messages of @Error@
-- severity to stderr. Will not emit any messages to stdout when
` Data . . Sync . Types . Verbosity ` is
` Data . . Sync . Types . Quiet `
logMessage'
:: ToLogStr a
=> Severity
-> (TimedFastLogger, TimedFastLogger)
-> Verbosity
-> a
-> IO ()
logMessage' severity (stdo, stde) verbosity message = do
let logger = if severity == Error then stde else stdo
when canLog $ logger
(\time ->
toLogStr time
<> toLogStr " "
<> toLogStr severity
<> toLogStr " "
<> toLogStr message
<> toLogStr "\n"
)
where
canLog = case (verbosity, severity) of
(_ , Error) -> True
(Normal, Debug) -> False
(Quiet , _ ) -> False
_ -> True
-- | Print informatic message to STDOUT. Will not emit anything if
verbosity is ` Data . . Sync . Types . Quiet `
logInfo' :: ToLogStr a => (TimedFastLogger, TimedFastLogger) -> Verbosity -> a -> IO ()
logInfo' = logMessage' Info
-- | Print error to STDERR. Ignores verbosity parameter
logError' :: ToLogStr a => (TimedFastLogger, TimedFastLogger) -> Verbosity -> a -> IO ()
logError' = logMessage' Error
-- | Print debug message to STDOUT when verbosity is
` Data . . Sync . Types .
logDebug' :: ToLogStr a => (TimedFastLogger, TimedFastLogger) -> Verbosity -> a -> IO ()
logDebug' = logMessage' Debug
logMessageM
:: (MonadReader Bootstrapped m, MonadIO m, ToLogStr a) => Severity -> a -> m ()
logMessageM severity message = do
loggers <- bootstrappedLoggers <$> ask
verbosity <- configVerbosity . bootstrappedConfig <$> ask
liftIO $ logMessage' severity loggers verbosity message
logDebugM :: (MonadReader Bootstrapped m, MonadIO m, ToLogStr a) => a -> m ()
logDebugM = logMessageM Debug
logInfoM :: (MonadReader Bootstrapped m, MonadIO m, ToLogStr a) => a -> m ()
logInfoM = logMessageM Info
logErrorM :: (MonadReader Bootstrapped m, MonadIO m, ToLogStr a) => a -> m ()
logErrorM = logMessageM Error
class Monad m => MonadLogger m where
logDebug :: ToLogStr a => a -> m ()
logInfo :: ToLogStr a => a -> m ()
logError :: ToLogStr a => a -> m ()
| null | https://raw.githubusercontent.com/serhiip/org2any/06dae386defe693ecc5ef169de3accc9a8267685/src/Data/OrgMode/Sync/Logging.hs | haskell | | Logging severity and destination (STDOUT / STDERR)
| Helper function to initialize stderr and stdout loggers
| Generic function to log messages. Logs messages of @Error@
severity to stderr. Will not emit any messages to stdout when
| Print informatic message to STDOUT. Will not emit anything if
| Print error to STDERR. Ignores verbosity parameter
| Print debug message to STDOUT when verbosity is | |
Module : Data . . Sync . Logging
Description : Logging utilities
License : GPL-3
Maintainer : < >
Stability : experimental
Log meassages of various log levels either via main transfromer stack
or via just IO . Uses
< -yamamoto/logger kazu - yamamoto / logger >
Module : Data.OrgMode.Sync.Logging
Description : Logging utilities
License : GPL-3
Maintainer : Serhii <>
Stability : experimental
Log meassages of various log levels either via main transfromer stack
or via just IO. Uses
<-yamamoto/logger kazu-yamamoto/logger>
-}
# LANGUAGE FlexibleContexts #
# LANGUAGE UndecidableInstances #
module Data.OrgMode.Sync.Logging
( initLogging
, logInfo'
, logError'
, logDebug'
, logInfoM
, logErrorM
, logDebugM
, MonadLogger(..)
)
where
import qualified Data.Text.Lazy as TL
import System.Log.FastLogger ( ToLogStr
, toLogStr
, newTimedFastLogger
, LogType(..)
, TimedFastLogger
)
import System.Log.FastLogger.Date ( newTimeCache
, simpleTimeFormat'
)
import Data.OrgMode.Sync.Types
import Universum
instance ToLogStr Severity where
toLogStr Debug = toLogStr $ TL.pack "[DEBUG]"
toLogStr Info = toLogStr $ TL.pack "[INFO] "
toLogStr Error = toLogStr $ TL.pack "[ERROR]"
data Severity
= Debug
| Info
| Error
deriving (Show, Eq, Ord)
initLogging :: IO (TimedFastLogger, TimedFastLogger, IO ())
initLogging = do
timeCache <- newTimeCache simpleTimeFormat'
(stdoutLogger, stdoutCleanUp ) <- newTimedFastLogger timeCache (LogStdout 1)
(stderrLogger, stderrCleanUp') <- newTimedFastLogger timeCache (LogStderr 1)
return (stdoutLogger, stderrLogger, stdoutCleanUp >> stderrCleanUp')
` Data . . Sync . Types . Verbosity ` is
` Data . . Sync . Types . Quiet `
logMessage'
:: ToLogStr a
=> Severity
-> (TimedFastLogger, TimedFastLogger)
-> Verbosity
-> a
-> IO ()
logMessage' severity (stdo, stde) verbosity message = do
let logger = if severity == Error then stde else stdo
when canLog $ logger
(\time ->
toLogStr time
<> toLogStr " "
<> toLogStr severity
<> toLogStr " "
<> toLogStr message
<> toLogStr "\n"
)
where
canLog = case (verbosity, severity) of
(_ , Error) -> True
(Normal, Debug) -> False
(Quiet , _ ) -> False
_ -> True
verbosity is ` Data . . Sync . Types . Quiet `
logInfo' :: ToLogStr a => (TimedFastLogger, TimedFastLogger) -> Verbosity -> a -> IO ()
logInfo' = logMessage' Info
logError' :: ToLogStr a => (TimedFastLogger, TimedFastLogger) -> Verbosity -> a -> IO ()
logError' = logMessage' Error
` Data . . Sync . Types .
logDebug' :: ToLogStr a => (TimedFastLogger, TimedFastLogger) -> Verbosity -> a -> IO ()
logDebug' = logMessage' Debug
logMessageM
:: (MonadReader Bootstrapped m, MonadIO m, ToLogStr a) => Severity -> a -> m ()
logMessageM severity message = do
loggers <- bootstrappedLoggers <$> ask
verbosity <- configVerbosity . bootstrappedConfig <$> ask
liftIO $ logMessage' severity loggers verbosity message
logDebugM :: (MonadReader Bootstrapped m, MonadIO m, ToLogStr a) => a -> m ()
logDebugM = logMessageM Debug
logInfoM :: (MonadReader Bootstrapped m, MonadIO m, ToLogStr a) => a -> m ()
logInfoM = logMessageM Info
logErrorM :: (MonadReader Bootstrapped m, MonadIO m, ToLogStr a) => a -> m ()
logErrorM = logMessageM Error
class Monad m => MonadLogger m where
logDebug :: ToLogStr a => a -> m ()
logInfo :: ToLogStr a => a -> m ()
logError :: ToLogStr a => a -> m ()
|
1ccfdb21f07abd121614a18be4594576f3818093b71fe113895d44464016dac5 | zippy/anansi | channel.clj |
(ns anansi.test.streamscapes.channel
(:use [anansi.streamscapes.channel] :reload)
(:use [anansi.ceptr]
[anansi.streamscapes.streamscapes]
[anansi.receptor.scape]
[anansi.receptor.user :only [user-def]]
[anansi.receptor.host :only [host-def]])
(:use [midje.sweet])
(:use [clojure.test])
(:use [clj-time.core :only [now]]))
(defmethod manifest :test-send-bridge [_r & args]
{}
)
(signal channel deliver [_r _f {droplet-address :droplet-address error :error}] ;; use the error param to simulate errors or not
error)
(deftest channel
(let [m (make-receptor user-def nil "eric")
h (make-receptor host-def nil {})
r (make-receptor streamscapes-def h {:matrice-addr (address-of m) :attributes {:_password "password" :data {:datax "x"}}})
cc-addr (s-> matrice->make-channel r {:name :email-stream})
cc (get-receptor r cc-addr)]
(fact (receptor-state cc false) => (contains {:name :email-stream
:fingerprint :anansi.streamscapes.channel.channel
:scapes {:controller-scape {:values {}, :relationship {:key nil, :address nil}}, :deliverer-scape {:values {}, :relationship {:key nil, :address nil}}, :receiver-scape {:values {}, :relationship {:key nil, :address nil}}}
}))
(testing "receive"
(--> key->set r (get-scape r :channel-type) cc-addr :email)
(let [sent-date (str (now))
droplet-address (s-> stream->receive cc {:id "some-id" :to "to-addr" :from "from-addr" :sent sent-date :envelope {:from "rfc-822-email" :subject "text/plain" :body "text/html"} :content {:from "" :subject "Hi there!" :body "<b>Hello world!</b>"}})
droplet2-address (s-> stream->receive cc {:id "some-other-id" :to "to-addr" :from "from-addr" :sent (str (now)) :envelope { :message "text/plain"} :content {:from "" :message "Hello world!"}})
d (get-receptor r droplet-address)
receipts (get-scape r :receipt)
deliveries (get-scape r :delivery)]
(fact (receptor-state d true) => (contains {:id "some-id", :envelope {:from "rfc-822-email", :subject "text/plain", :body "text/html"}, :channel :email-stream, :content {:from "", :subject "Hi there!", :body "<b>Hello world!</b>"}, :to "to-addr", :from "from-addr", :fingerprint :anansi.streamscapes.droplet.droplet}))
(let [[time] (s-> address->resolve receipts droplet-address)]
(fact (= time sent-date) => false)
(fact (subs (str (now)) 0 19) => (subs time 0 19)) ;hack off the milliseconds
)
(let [[time] (s-> address->resolve deliveries droplet-address)]
(facts time => sent-date))
(facts "about groove matching on receive"
(s-> key->resolve (get-scape r :subject-body-message-groove) droplet-address) => true
(s-> key->resolve (get-scape r :droplet-grooves) droplet-address) => [:subject-body-message]
(s-> key->resolve (get-scape r :subject-body-message-groove) droplet2-address) => nil
(s-> key->resolve (get-scape r :simple-message-groove) droplet-address) => (throws RuntimeException ":simple-message-groove scape doesn't exist")
(scape-relationship (get-scape r :subject-body-message-groove) :key) => "droplet-address"
(scape-relationship (get-scape r :subject-body-message-groove) :address) => "boolean"
(s-> query->all (get-scape r :subject-body-message-groove)) => [[droplet-address true]]
)
(is (= "from-addr" (contents d :from) ))
(is (= "some-id" (contents d :id) ))
(is (= :email-stream (contents d :channel) ))
(is (= "to-addr" (contents d :to)))
(is (= {:from "rfc-822-email" :subject "text/plain" :body "text/html"} (contents d :envelope)))
(is (= {:from "" :subject "Hi there!" :body "<b>Hello world!</b>"} (contents d :content)))))
(testing "send"
(let [b (make-receptor (receptor-def "test-send-bridge-email") cc {})
_ (s-> key->set (get-scape cc :deliverer) :deliverer [(address-of b) ["anansi.test.streamscapes.channel" "channel" "deliver"]])
i-to (s-> matrice->identify r {:identifiers {:email-address ""} :attributes {:name "Eric"}})
i-from (s-> matrice->identify r {:identifiers {:email-address ""} :attributes {:name "Me"}})
droplet-address (s-> matrice->incorporate r {:to i-to :from i-from :envelope {:subject "text/plain" :body "text/html"} :content {:subject "Hi there!" :body "<b>Hello world!</b>"}})
result (s-> stream->send cc {:droplet-address droplet-address :error "Failed"})
d (get-receptor r droplet-address)
deliveries (get-scape r :delivery)]
(is (= "Failed" result))
(is (= [] (s-> address->resolve deliveries droplet-address)))
(s-> stream->send cc {:droplet-address droplet-address :error nil})
(let [[time] (s-> address->resolve deliveries droplet-address)]
(is (= (subs (str (now)) 0 19) (subs time 0 19))) ; hack off the milliseconds
)))
(facts "about restoring serialized channel receptor"
(let [channel-state (receptor-state cc true)]
channel-state => (receptor-state (receptor-restore channel-state nil) true)
)
)
(testing "restore"
(is (= (receptor-state cc true) (receptor-state (receptor-restore (receptor-state cc true) nil) true))))))
| null | https://raw.githubusercontent.com/zippy/anansi/881aa279e5e7836f3002fc2ef7623f2ee1860c9a/test/anansi/test/streamscapes/channel.clj | clojure | use the error param to simulate errors or not
hack off the milliseconds
hack off the milliseconds |
(ns anansi.test.streamscapes.channel
(:use [anansi.streamscapes.channel] :reload)
(:use [anansi.ceptr]
[anansi.streamscapes.streamscapes]
[anansi.receptor.scape]
[anansi.receptor.user :only [user-def]]
[anansi.receptor.host :only [host-def]])
(:use [midje.sweet])
(:use [clojure.test])
(:use [clj-time.core :only [now]]))
(defmethod manifest :test-send-bridge [_r & args]
{}
)
error)
(deftest channel
(let [m (make-receptor user-def nil "eric")
h (make-receptor host-def nil {})
r (make-receptor streamscapes-def h {:matrice-addr (address-of m) :attributes {:_password "password" :data {:datax "x"}}})
cc-addr (s-> matrice->make-channel r {:name :email-stream})
cc (get-receptor r cc-addr)]
(fact (receptor-state cc false) => (contains {:name :email-stream
:fingerprint :anansi.streamscapes.channel.channel
:scapes {:controller-scape {:values {}, :relationship {:key nil, :address nil}}, :deliverer-scape {:values {}, :relationship {:key nil, :address nil}}, :receiver-scape {:values {}, :relationship {:key nil, :address nil}}}
}))
(testing "receive"
(--> key->set r (get-scape r :channel-type) cc-addr :email)
(let [sent-date (str (now))
droplet-address (s-> stream->receive cc {:id "some-id" :to "to-addr" :from "from-addr" :sent sent-date :envelope {:from "rfc-822-email" :subject "text/plain" :body "text/html"} :content {:from "" :subject "Hi there!" :body "<b>Hello world!</b>"}})
droplet2-address (s-> stream->receive cc {:id "some-other-id" :to "to-addr" :from "from-addr" :sent (str (now)) :envelope { :message "text/plain"} :content {:from "" :message "Hello world!"}})
d (get-receptor r droplet-address)
receipts (get-scape r :receipt)
deliveries (get-scape r :delivery)]
(fact (receptor-state d true) => (contains {:id "some-id", :envelope {:from "rfc-822-email", :subject "text/plain", :body "text/html"}, :channel :email-stream, :content {:from "", :subject "Hi there!", :body "<b>Hello world!</b>"}, :to "to-addr", :from "from-addr", :fingerprint :anansi.streamscapes.droplet.droplet}))
(let [[time] (s-> address->resolve receipts droplet-address)]
(fact (= time sent-date) => false)
)
(let [[time] (s-> address->resolve deliveries droplet-address)]
(facts time => sent-date))
(facts "about groove matching on receive"
(s-> key->resolve (get-scape r :subject-body-message-groove) droplet-address) => true
(s-> key->resolve (get-scape r :droplet-grooves) droplet-address) => [:subject-body-message]
(s-> key->resolve (get-scape r :subject-body-message-groove) droplet2-address) => nil
(s-> key->resolve (get-scape r :simple-message-groove) droplet-address) => (throws RuntimeException ":simple-message-groove scape doesn't exist")
(scape-relationship (get-scape r :subject-body-message-groove) :key) => "droplet-address"
(scape-relationship (get-scape r :subject-body-message-groove) :address) => "boolean"
(s-> query->all (get-scape r :subject-body-message-groove)) => [[droplet-address true]]
)
(is (= "from-addr" (contents d :from) ))
(is (= "some-id" (contents d :id) ))
(is (= :email-stream (contents d :channel) ))
(is (= "to-addr" (contents d :to)))
(is (= {:from "rfc-822-email" :subject "text/plain" :body "text/html"} (contents d :envelope)))
(is (= {:from "" :subject "Hi there!" :body "<b>Hello world!</b>"} (contents d :content)))))
(testing "send"
(let [b (make-receptor (receptor-def "test-send-bridge-email") cc {})
_ (s-> key->set (get-scape cc :deliverer) :deliverer [(address-of b) ["anansi.test.streamscapes.channel" "channel" "deliver"]])
i-to (s-> matrice->identify r {:identifiers {:email-address ""} :attributes {:name "Eric"}})
i-from (s-> matrice->identify r {:identifiers {:email-address ""} :attributes {:name "Me"}})
droplet-address (s-> matrice->incorporate r {:to i-to :from i-from :envelope {:subject "text/plain" :body "text/html"} :content {:subject "Hi there!" :body "<b>Hello world!</b>"}})
result (s-> stream->send cc {:droplet-address droplet-address :error "Failed"})
d (get-receptor r droplet-address)
deliveries (get-scape r :delivery)]
(is (= "Failed" result))
(is (= [] (s-> address->resolve deliveries droplet-address)))
(s-> stream->send cc {:droplet-address droplet-address :error nil})
(let [[time] (s-> address->resolve deliveries droplet-address)]
)))
(facts "about restoring serialized channel receptor"
(let [channel-state (receptor-state cc true)]
channel-state => (receptor-state (receptor-restore channel-state nil) true)
)
)
(testing "restore"
(is (= (receptor-state cc true) (receptor-state (receptor-restore (receptor-state cc true) nil) true))))))
|
e679834a3e8e3e079068c67e627ad9da23a076dfd7b2d03949cdfe22c23477e8 | jeaye/safepaste | home.clj | (ns safepaste.home
(:require [safepaste.css :as css]
[hiccup.page :as page]))
(def default-expiry "day")
(defn render [id request]
(let [placeholder "Enter your paste here…"]
(page/html5
[:head
; Have search engines ignore everything but the home page
(when (not-empty id)
[:meta {:name "robots" :content "noindex"}])
[:style (css/main)]
(page/include-js "/js/safepaste.js")
[:title "safepaste"]]
[:body
[:div.header
[:p#status.status-error
[:noscript
"JavaScript is required for client-side encryption."]]
[:div.expiry
[:select#expiry
[:option {:value "burn"} "Burn after reading"]
(for [o ["hour" "day" "week" "month"]]
[:option
(conj {:value o}
(when (= o default-expiry)
{:selected "selected"}))
(str "Expires after 1 " o)])]]
[:nav
(for [a ["new" "fork" #_"about" "paste"]]
[:a {:id a} a])]]
[:div.input
[:textarea#input {:placeholder placeholder
:autofocus "autofocus"}]]])))
| null | https://raw.githubusercontent.com/jeaye/safepaste/646232d1adb1ed9a6b76f26636753e196145c43c/src/clj/safepaste/home.clj | clojure | Have search engines ignore everything but the home page | (ns safepaste.home
(:require [safepaste.css :as css]
[hiccup.page :as page]))
(def default-expiry "day")
(defn render [id request]
(let [placeholder "Enter your paste here…"]
(page/html5
[:head
(when (not-empty id)
[:meta {:name "robots" :content "noindex"}])
[:style (css/main)]
(page/include-js "/js/safepaste.js")
[:title "safepaste"]]
[:body
[:div.header
[:p#status.status-error
[:noscript
"JavaScript is required for client-side encryption."]]
[:div.expiry
[:select#expiry
[:option {:value "burn"} "Burn after reading"]
(for [o ["hour" "day" "week" "month"]]
[:option
(conj {:value o}
(when (= o default-expiry)
{:selected "selected"}))
(str "Expires after 1 " o)])]]
[:nav
(for [a ["new" "fork" #_"about" "paste"]]
[:a {:id a} a])]]
[:div.input
[:textarea#input {:placeholder placeholder
:autofocus "autofocus"}]]])))
|
bea1833f3f67cb47c0552400d49a6623bb343a68dd9fa1a4deb006d6f3d9fb01 | ghc/ghc | T21605d.hs | module T21605d where
f (x :: Prelude.id) = x | null | https://raw.githubusercontent.com/ghc/ghc/b3be0d185b6e597fa517859430cf6d54df04ca46/testsuite/tests/rename/should_fail/T21605d.hs | haskell | module T21605d where
f (x :: Prelude.id) = x | |
4062757df1cbd35e3fc53676ed1187ffc2325cec9878aed779b50ec3f78f544a | iskandr/parakeet-retired | Int.ml | open BaseCommon
module IntOrd = struct
type t = int
let compare = compare
end
include IntOrd
module Map = BaseMap.Make(IntOrd)
module Set = BaseSet.Make(IntOrd)
module Graph = Graph.Make(IntOrd)
let add = (+)
let sub = (-)
let mul = ( * )
let div = ( / )
let zero = 0
let one = 1
let neg x = - x
let succ x = x + 1
let pred x = x - 1
let of_float = int_of_float
let to_float = float_of_int
let to_string = string_of_int
let from_string = int_of_string
let of_bool b = if b then 1 else 0
let to_bool i = i <> 0
let of_char c = Char.code c
| null | https://raw.githubusercontent.com/iskandr/parakeet-retired/3d7e6e5b699f83ce8a1c01290beed0b78c0d0945/Base/Int.ml | ocaml | open BaseCommon
module IntOrd = struct
type t = int
let compare = compare
end
include IntOrd
module Map = BaseMap.Make(IntOrd)
module Set = BaseSet.Make(IntOrd)
module Graph = Graph.Make(IntOrd)
let add = (+)
let sub = (-)
let mul = ( * )
let div = ( / )
let zero = 0
let one = 1
let neg x = - x
let succ x = x + 1
let pred x = x - 1
let of_float = int_of_float
let to_float = float_of_int
let to_string = string_of_int
let from_string = int_of_string
let of_bool b = if b then 1 else 0
let to_bool i = i <> 0
let of_char c = Char.code c
| |
9b3dad6cd3b8b57bd514213079b9d8ecce9461a4cba760bc84af58bb7ae1cd73 | zalando-stups/essentials | api_test.clj | (ns org.zalando.stups.essentials.api-test
(:require [midje.sweet :refer :all]
[clojure.test :refer :all]
[org.zalando.stups.essentials.api :refer :all]
[org.zalando.stups.essentials.test-utils :refer :all]
[clj-http.client :as http]
[org.zalando.stups.friboo.zalando-internal.auth :as auth]
[org.zalando.stups.essentials.sql :as sql])
(:import (clojure.lang ExceptionInfo)))
(deftest wrap-midje-facts
(facts "about extract-app-id"
(extract-app-id "user-filtering.module") => "user-filtering"
(extract-app-id "user-procurement") => "user-procurement")
(facts "about strip-prefix"
(strip-prefix {:rt_id 1 :s_summary "aaa"})
=> {:id 1, :summary "aaa"})
(facts "about parse-csv-set"
(parse-csv-set "a,b,a") => #{"a" "b"})
(facts "about require-special-uid"
(require-special-uid {:configuration {:allowed-uids "abob,cdale"}} {"uid" "abob"}) => nil
(require-special-uid {:configuration {:allowed-uids "abob,cdale"}} {"uid" "mjackson"}) => (throws ExceptionInfo))
(facts "about require-write-access"
(let [tokeninfo {"access_token" "token"
"uid" "abob"}
this {:configuration {:kio-url "kio-url"
:allowed-uids "abob,cdale"}
:auth ..auth..}]
(fact "for scopes that are application ids"
(require-write-access this "zmon" {:tokeninfo tokeninfo})
=> nil
(provided
(http/get "kio-url/apps/zmon" (contains {:oauth-token "token"})) => {:status 200 :body {:team_id "team-zmon"}}
(auth/require-auth ..auth.. tokeninfo {:team "team-zmon"}) => nil))
(fact "for other scopes"
(require-write-access this "application" {:tokeninfo tokeninfo})
=> nil
(provided
(http/get "kio-url/apps/application" (contains {:oauth-token "token"})) => {:status 404}))
(fact "When tokeninfo-url is not set, do nothing"
(require-write-access {} "foo" {}) => nil
(provided
(http/get anything anything) => nil :times 0))
(fact "When tokeninfo-url is not set, do nothing"
(require-write-access this "" {:tokeninfo tokeninfo}) => (throws ExceptionInfo)
(provided
(http/get anything anything) => nil :times 0))))
(facts "about require-realms"
(require-realms {:configuration {:allowed-realms "foos"}} {:tokeninfo {"realm" "foos"}})
=> anything
(fact "When there is no tokeninfo in the request, do nothing"
(require-realms {:configuration {:allowed-realms "foos"}} {})
=> nil))
(facts "about validate-resource-owners"
"When resource owners list is not empty, just check it against the list"
(validate-resource-owners {:configuration {:valid-resource-owners "foos,bars"}}
["bros"]
anything) => (throws ExceptionInfo)
(fact "When the list is empty, check in the database"
(validate-resource-owners {}
[]
"foo") => (throws ExceptionInfo)
(provided
(sql/cmd-read-scopes {:resource_type_id "foo"} anything) => [{:s_is_resource_owner_scope true}])))
(facts "Component test"
(with-db [db]
(let [this {:db db
:auth ..auth..
:configuration {:allowed-realms "bros"
:allowed-uids "abob,cdale"
:valid-resource-owners "bros"
:kio-url "kio-url"}}]
(wipe-db db)
(fact "Unallowed realms not allowed"
(read-resource-types this {} {:tokeninfo {"realm" "robots"}})
=> (throws ExceptionInfo))
(fact "Allowed realm, no resource types in the DB yet"
(read-resource-types this {} {:tokeninfo {"realm" "bros"}})
=> (contains {:status 200 :body []}))
(fact "Can create resource type"
(create-or-update-resource-type this
{:resource_type_id "application"
:resource_type {:name "Application name"
:description "Application description"
:resource_owners []}}
{:tokeninfo {"access_token" "token"
"uid" "abob"
"realm" "bros"}})
=> (contains {:status 200})
(provided
(http/get "kio-url/apps/application" (contains {:oauth-token "token"})) => {:status 404}))
(fact "Resource type is in the DB now"
(read-resource-types this {} {:tokeninfo {"realm" "bros"}})
=> (contains {:status 200 :body [{:id "application", :name "Application name"}]}))
(fact "Can get resource type by id"
(read-resource-type this {:resource_type_id "application"} {:tokeninfo {"realm" "bros"}})
=> (contains {:status 200 :body {:id "application"
:name "Application name"
:description "Application description"
:resource_owners []}}))
(fact "No scopes for the resource type yet"
(read-scopes this {:resource_type_id "application"} {:tokeninfo {"realm" "bros"}})
=> (contains {:status 200 :body []}))
(fact "Can create a scope for the resource type (use a non-special uid to check how require-auth is called)"
(create-or-update-scope this
{:resource_type_id "application"
:scope_id "write"
:scope {:summary "Allow write"}}
{:tokeninfo {"access_token" "token"
"uid" "mjackson"
"realm" "bros"}})
=> (contains {:status 200})
(provided
(http/get "kio-url/apps/application" (contains {:oauth-token "token"}))
=> {:status 200 :body {:team_id "broforce"}}
(auth/require-auth ..auth..
{"uid" "mjackson" "access_token" "token" "realm" "bros"}
{:team "broforce"})
=> nil))
(fact "Created scope is visible"
(read-scopes this {:resource_type_id "application"} {:tokeninfo {"realm" "bros"}})
=> (contains {:status 200 :body [{:criticality_level 2
:description nil
:id "write"
:is_resource_owner_scope false
:summary "Allow write"
:user_information nil}]}))
(fact "Can read scope by ID"
(read-scope this {:resource_type_id "application" :scope_id "write"} {:tokeninfo {"realm" "bros"}})
=> (contains {:status 200 :body {:criticality_level 2
:description nil
:id "write"
:is_resource_owner_scope false
:summary "Allow write"
:user_information nil}}))
(fact "Cannot create resource owner scope when resource type has no resource owners"
(create-or-update-scope this
{:resource_type_id "application"
:scope_id "write_all"
:scope {:summary "Allow write"
:is_resource_owner_scope true}}
{:tokeninfo {"access_token" "token"
"uid" "abob"
"realm" "bros"}})
=> (throws ExceptionInfo)
(provided
(http/get "kio-url/apps/application" (contains {:oauth-token "token"}))
=> {:status 200 :body {:team_id "broforce"}}))
(fact "Cannot create scope in a nonfound resource type"
(create-or-update-scope this
{:resource_type_id "foo"
:scope_id "write_all"
:scope {:summary "Allow write"}}
{:tokeninfo {"access_token" "token"
"uid" "abob"
"realm" "bros"}})
=> (contains {:status 404})
(provided
(http/get "kio-url/apps/foo" (contains {:oauth-token "token"}))
=> {:status 200 :body {:team_id "broforce"}}))
(fact "Can delete scope"
(delete-scope this {:resource_type_id "application" :scope_id "write"} {:tokeninfo {"access_token" "token"
"uid" "abob"
"realm" "bros"}})
=> (contains {:status 200})
(provided
(http/get "kio-url/apps/application" (contains {:oauth-token "token"})) => {:status 404}))
(fact "Deleting a scope from unfound resource yields 404"
(delete-scope this {:resource_type_id "bar" :scope_id "write"} {:tokeninfo {"access_token" "token"
"uid" "abob"
"realm" "bros"}})
=> (contains {:status 404})
(provided
(http/get "kio-url/apps/bar" (contains {:oauth-token "token"})) => {:status 404}))
(fact "Deleted scope is gone"
(read-scope this {:resource_type_id "application" :scope_id "write"} {:tokeninfo {"realm" "bros"}})
=> (contains {:status 404}))
(fact "Can delete resource type"
(delete-resource-type this {:resource_type_id "application"} {:tokeninfo {"access_token" "token"
"uid" "abob"
"realm" "bros"}})
=> (contains {:status 200})
(provided
(http/get "kio-url/apps/application" (contains {:oauth-token "token"})) => {:status 404}))
(fact "Deleting unfound resource type yields 404"
(delete-resource-type this {:resource_type_id "application"} {:tokeninfo {"access_token" "token"
"uid" "abob"
"realm" "bros"}})
=> (contains {:status 404})
(provided
(http/get "kio-url/apps/application" (contains {:oauth-token "token"})) => {:status 404}))
(fact "Resource type is gone"
(read-resource-type this {:resource_type_id "application"} {:tokeninfo {"realm" "bros"}})
=> (contains {:status 404})))
))
)
| null | https://raw.githubusercontent.com/zalando-stups/essentials/f61111a0b76e9d90d161abdc6cbe9c280c717edb/test/org/zalando/stups/essentials/api_test.clj | clojure | (ns org.zalando.stups.essentials.api-test
(:require [midje.sweet :refer :all]
[clojure.test :refer :all]
[org.zalando.stups.essentials.api :refer :all]
[org.zalando.stups.essentials.test-utils :refer :all]
[clj-http.client :as http]
[org.zalando.stups.friboo.zalando-internal.auth :as auth]
[org.zalando.stups.essentials.sql :as sql])
(:import (clojure.lang ExceptionInfo)))
(deftest wrap-midje-facts
(facts "about extract-app-id"
(extract-app-id "user-filtering.module") => "user-filtering"
(extract-app-id "user-procurement") => "user-procurement")
(facts "about strip-prefix"
(strip-prefix {:rt_id 1 :s_summary "aaa"})
=> {:id 1, :summary "aaa"})
(facts "about parse-csv-set"
(parse-csv-set "a,b,a") => #{"a" "b"})
(facts "about require-special-uid"
(require-special-uid {:configuration {:allowed-uids "abob,cdale"}} {"uid" "abob"}) => nil
(require-special-uid {:configuration {:allowed-uids "abob,cdale"}} {"uid" "mjackson"}) => (throws ExceptionInfo))
(facts "about require-write-access"
(let [tokeninfo {"access_token" "token"
"uid" "abob"}
this {:configuration {:kio-url "kio-url"
:allowed-uids "abob,cdale"}
:auth ..auth..}]
(fact "for scopes that are application ids"
(require-write-access this "zmon" {:tokeninfo tokeninfo})
=> nil
(provided
(http/get "kio-url/apps/zmon" (contains {:oauth-token "token"})) => {:status 200 :body {:team_id "team-zmon"}}
(auth/require-auth ..auth.. tokeninfo {:team "team-zmon"}) => nil))
(fact "for other scopes"
(require-write-access this "application" {:tokeninfo tokeninfo})
=> nil
(provided
(http/get "kio-url/apps/application" (contains {:oauth-token "token"})) => {:status 404}))
(fact "When tokeninfo-url is not set, do nothing"
(require-write-access {} "foo" {}) => nil
(provided
(http/get anything anything) => nil :times 0))
(fact "When tokeninfo-url is not set, do nothing"
(require-write-access this "" {:tokeninfo tokeninfo}) => (throws ExceptionInfo)
(provided
(http/get anything anything) => nil :times 0))))
(facts "about require-realms"
(require-realms {:configuration {:allowed-realms "foos"}} {:tokeninfo {"realm" "foos"}})
=> anything
(fact "When there is no tokeninfo in the request, do nothing"
(require-realms {:configuration {:allowed-realms "foos"}} {})
=> nil))
(facts "about validate-resource-owners"
"When resource owners list is not empty, just check it against the list"
(validate-resource-owners {:configuration {:valid-resource-owners "foos,bars"}}
["bros"]
anything) => (throws ExceptionInfo)
(fact "When the list is empty, check in the database"
(validate-resource-owners {}
[]
"foo") => (throws ExceptionInfo)
(provided
(sql/cmd-read-scopes {:resource_type_id "foo"} anything) => [{:s_is_resource_owner_scope true}])))
(facts "Component test"
(with-db [db]
(let [this {:db db
:auth ..auth..
:configuration {:allowed-realms "bros"
:allowed-uids "abob,cdale"
:valid-resource-owners "bros"
:kio-url "kio-url"}}]
(wipe-db db)
(fact "Unallowed realms not allowed"
(read-resource-types this {} {:tokeninfo {"realm" "robots"}})
=> (throws ExceptionInfo))
(fact "Allowed realm, no resource types in the DB yet"
(read-resource-types this {} {:tokeninfo {"realm" "bros"}})
=> (contains {:status 200 :body []}))
(fact "Can create resource type"
(create-or-update-resource-type this
{:resource_type_id "application"
:resource_type {:name "Application name"
:description "Application description"
:resource_owners []}}
{:tokeninfo {"access_token" "token"
"uid" "abob"
"realm" "bros"}})
=> (contains {:status 200})
(provided
(http/get "kio-url/apps/application" (contains {:oauth-token "token"})) => {:status 404}))
(fact "Resource type is in the DB now"
(read-resource-types this {} {:tokeninfo {"realm" "bros"}})
=> (contains {:status 200 :body [{:id "application", :name "Application name"}]}))
(fact "Can get resource type by id"
(read-resource-type this {:resource_type_id "application"} {:tokeninfo {"realm" "bros"}})
=> (contains {:status 200 :body {:id "application"
:name "Application name"
:description "Application description"
:resource_owners []}}))
(fact "No scopes for the resource type yet"
(read-scopes this {:resource_type_id "application"} {:tokeninfo {"realm" "bros"}})
=> (contains {:status 200 :body []}))
(fact "Can create a scope for the resource type (use a non-special uid to check how require-auth is called)"
(create-or-update-scope this
{:resource_type_id "application"
:scope_id "write"
:scope {:summary "Allow write"}}
{:tokeninfo {"access_token" "token"
"uid" "mjackson"
"realm" "bros"}})
=> (contains {:status 200})
(provided
(http/get "kio-url/apps/application" (contains {:oauth-token "token"}))
=> {:status 200 :body {:team_id "broforce"}}
(auth/require-auth ..auth..
{"uid" "mjackson" "access_token" "token" "realm" "bros"}
{:team "broforce"})
=> nil))
(fact "Created scope is visible"
(read-scopes this {:resource_type_id "application"} {:tokeninfo {"realm" "bros"}})
=> (contains {:status 200 :body [{:criticality_level 2
:description nil
:id "write"
:is_resource_owner_scope false
:summary "Allow write"
:user_information nil}]}))
(fact "Can read scope by ID"
(read-scope this {:resource_type_id "application" :scope_id "write"} {:tokeninfo {"realm" "bros"}})
=> (contains {:status 200 :body {:criticality_level 2
:description nil
:id "write"
:is_resource_owner_scope false
:summary "Allow write"
:user_information nil}}))
(fact "Cannot create resource owner scope when resource type has no resource owners"
(create-or-update-scope this
{:resource_type_id "application"
:scope_id "write_all"
:scope {:summary "Allow write"
:is_resource_owner_scope true}}
{:tokeninfo {"access_token" "token"
"uid" "abob"
"realm" "bros"}})
=> (throws ExceptionInfo)
(provided
(http/get "kio-url/apps/application" (contains {:oauth-token "token"}))
=> {:status 200 :body {:team_id "broforce"}}))
(fact "Cannot create scope in a nonfound resource type"
(create-or-update-scope this
{:resource_type_id "foo"
:scope_id "write_all"
:scope {:summary "Allow write"}}
{:tokeninfo {"access_token" "token"
"uid" "abob"
"realm" "bros"}})
=> (contains {:status 404})
(provided
(http/get "kio-url/apps/foo" (contains {:oauth-token "token"}))
=> {:status 200 :body {:team_id "broforce"}}))
(fact "Can delete scope"
(delete-scope this {:resource_type_id "application" :scope_id "write"} {:tokeninfo {"access_token" "token"
"uid" "abob"
"realm" "bros"}})
=> (contains {:status 200})
(provided
(http/get "kio-url/apps/application" (contains {:oauth-token "token"})) => {:status 404}))
(fact "Deleting a scope from unfound resource yields 404"
(delete-scope this {:resource_type_id "bar" :scope_id "write"} {:tokeninfo {"access_token" "token"
"uid" "abob"
"realm" "bros"}})
=> (contains {:status 404})
(provided
(http/get "kio-url/apps/bar" (contains {:oauth-token "token"})) => {:status 404}))
(fact "Deleted scope is gone"
(read-scope this {:resource_type_id "application" :scope_id "write"} {:tokeninfo {"realm" "bros"}})
=> (contains {:status 404}))
(fact "Can delete resource type"
(delete-resource-type this {:resource_type_id "application"} {:tokeninfo {"access_token" "token"
"uid" "abob"
"realm" "bros"}})
=> (contains {:status 200})
(provided
(http/get "kio-url/apps/application" (contains {:oauth-token "token"})) => {:status 404}))
(fact "Deleting unfound resource type yields 404"
(delete-resource-type this {:resource_type_id "application"} {:tokeninfo {"access_token" "token"
"uid" "abob"
"realm" "bros"}})
=> (contains {:status 404})
(provided
(http/get "kio-url/apps/application" (contains {:oauth-token "token"})) => {:status 404}))
(fact "Resource type is gone"
(read-resource-type this {:resource_type_id "application"} {:tokeninfo {"realm" "bros"}})
=> (contains {:status 404})))
))
)
| |
c607a84214e6b994997725311d37c1af51f1fcda8765c6a7a21167d5cca09e61 | AccelerateHS/accelerate-examples | Config.hs | # LANGUAGE TemplateHaskell #
module Config where
import Data.Label
import System.Console.GetOpt
data Config
= Config
{ _configRandomSize :: Maybe Int
}
$(mkLabels [''Config])
defaults :: Config
defaults = Config Nothing
options :: [OptDescr (Config -> Config)]
options =
[ Option [] ["size"] (ReqArg (set configRandomSize . Just . read) "INT") "number of elements for a random input"
]
header :: [String]
header =
[ "accelerate-quicksort (c) [2019] The Accelerate Team"
, ""
, "Usage: accelerate-quicksort input.txt"
, " where input.txt is a file containing a list of integers seperated by spaces"
, ""
, "Usage: accelerate-quicksort --size n"
, " where n is a number, denoting the size of a random input"
, ""
]
footer :: [String]
footer = [ "" ]
| null | https://raw.githubusercontent.com/AccelerateHS/accelerate-examples/a973ee423b5eadda6ef2e2504d2383f625e49821/examples/quicksort/Config.hs | haskell | # LANGUAGE TemplateHaskell #
module Config where
import Data.Label
import System.Console.GetOpt
data Config
= Config
{ _configRandomSize :: Maybe Int
}
$(mkLabels [''Config])
defaults :: Config
defaults = Config Nothing
options :: [OptDescr (Config -> Config)]
options =
[ Option [] ["size"] (ReqArg (set configRandomSize . Just . read) "INT") "number of elements for a random input"
]
header :: [String]
header =
[ "accelerate-quicksort (c) [2019] The Accelerate Team"
, ""
, "Usage: accelerate-quicksort input.txt"
, " where input.txt is a file containing a list of integers seperated by spaces"
, ""
, "Usage: accelerate-quicksort --size n"
, " where n is a number, denoting the size of a random input"
, ""
]
footer :: [String]
footer = [ "" ]
| |
4624c8a19d824a00a248d38a60d7ca3bd82725d818592c5405ed43309556d86a | making/clj-gae-blank | project.clj | (defproject clj-gae-blank "0.1.1"
:description "a blank project for clojure on GAE"
:repositories {"maven.seasar.org" ""}
:dependencies [[org.clojure/clojure "1.1.0"]
[org.clojure/clojure-contrib "1.1.0"]
[compojure "0.4.0"]
[am.ik/clj-gae-ds "0.2.1"]
[am.ik/clj-gae-users "0.1.1"]
[com.google.appengine/appengine-api-1.0-sdk "1.3.5"]
[ring/ring-core "0.2.3"]
[ring/ring-servlet "0.2.3"]
[ring/ring-jetty-adapter "0.2.3"]
[hiccup/hiccup "0.2.6"]]
if you use - swank , delete jars which depends on lein - swank before deploy GAE or launch Dev Server .
[ leiningen / lein - swank " 1.1.0 " ]
[am.ik/clj-gae-testing "0.2.0-SNAPSHOT"]]
you should make symbolic link at project home directory to add classpath in " repl " ( ln -s war / WEB - INF / classes/ )
:compile-path "war/WEB-INF/classes/"
you should make symbolic link at project home directory to add classpath in " repl " ( ln -s war / WEB - INF / lib/ )
:library-path "war/WEB-INF/lib/"
:namespaces [clj-gae-blank])
| null | https://raw.githubusercontent.com/making/clj-gae-blank/45b7b702cbfb2f83fc9ad1d7836d06e2a6b953f6/project.clj | clojure | (defproject clj-gae-blank "0.1.1"
:description "a blank project for clojure on GAE"
:repositories {"maven.seasar.org" ""}
:dependencies [[org.clojure/clojure "1.1.0"]
[org.clojure/clojure-contrib "1.1.0"]
[compojure "0.4.0"]
[am.ik/clj-gae-ds "0.2.1"]
[am.ik/clj-gae-users "0.1.1"]
[com.google.appengine/appengine-api-1.0-sdk "1.3.5"]
[ring/ring-core "0.2.3"]
[ring/ring-servlet "0.2.3"]
[ring/ring-jetty-adapter "0.2.3"]
[hiccup/hiccup "0.2.6"]]
if you use - swank , delete jars which depends on lein - swank before deploy GAE or launch Dev Server .
[ leiningen / lein - swank " 1.1.0 " ]
[am.ik/clj-gae-testing "0.2.0-SNAPSHOT"]]
you should make symbolic link at project home directory to add classpath in " repl " ( ln -s war / WEB - INF / classes/ )
:compile-path "war/WEB-INF/classes/"
you should make symbolic link at project home directory to add classpath in " repl " ( ln -s war / WEB - INF / lib/ )
:library-path "war/WEB-INF/lib/"
:namespaces [clj-gae-blank])
| |
77d1d7ff6584e1379f63b8a26494258ffcca0fc47d08a8c8c2f4485e2bbaf73b | hdevtools/hdevtools | Info.hs | # LANGUAGE CPP #
{-# LANGUAGE RankNTypes #-}
module Info
( getIdentifierInfo
, getType
) where
import Data.Generics (GenericQ, mkQ, extQ, gmapQ)
import Data.List (find, sortBy, intersperse)
import Data.Maybe (catMaybes, fromMaybe)
import Data.Typeable (Typeable)
import MonadUtils (liftIO)
import qualified CoreUtils
import qualified Desugar
#if __GLASGOW_HASKELL__ >= 706
import qualified DynFlags
#endif
#if __GLASGOW_HASKELL__ >= 708
import qualified HsExpr
#else
import qualified TcRnTypes
#endif
import qualified GHC
import qualified HscTypes
import qualified NameSet
import qualified Outputable
import qualified PprTyThing
import qualified Pretty
import qualified TcHsSyn
import GhcTypes (getModSummaries, TypecheckI)
getIdentifierInfo :: FilePath -> String -> GHC.Ghc (Either String String)
getIdentifierInfo file identifier =
withModSummary file $ \m -> do
#if __GLASGOW_HASKELL__ >= 706
GHC.setContext [GHC.IIModule (GHC.moduleName (GHC.ms_mod m))]
#elif __GLASGOW_HASKELL__ >= 704
GHC.setContext [GHC.IIModule (GHC.ms_mod m)]
#else
GHC.setContext [GHC.ms_mod m] []
#endif
GHC.handleSourceError (return . Left . show) $
fmap Right (infoThing identifier)
getType :: FilePath -> (Int, Int) -> GHC.Ghc (Either String [((Int, Int, Int, Int), String)])
getType file (line, col) =
withModSummary file $ \m -> do
p <- GHC.parseModule m
typechecked <- GHC.typecheckModule p
types <- processTypeCheckedModule typechecked (line, col)
return (Right types)
withModSummary :: String -> (HscTypes.ModSummary -> GHC.Ghc (Either String a)) -> GHC.Ghc (Either String a)
withModSummary file action = do
modSummary <- getModuleSummary file
case modSummary of
Nothing -> return (Left "Module not found in module graph")
Just m -> action m
getModuleSummary :: FilePath -> GHC.Ghc (Maybe GHC.ModSummary)
getModuleSummary file = do
modSummaries <- getModSummaries
case find (moduleSummaryMatchesFilePath file) modSummaries of
Nothing -> return Nothing
Just moduleSummary -> return (Just moduleSummary)
moduleSummaryMatchesFilePath :: FilePath -> GHC.ModSummary -> Bool
moduleSummaryMatchesFilePath file moduleSummary =
let location = GHC.ms_location moduleSummary
location_file = GHC.ml_hs_file location
in case location_file of
Just f -> f == file
Nothing -> False
------------------------------------------------------------------------------
-- Most of the following code was taken from the source code of 'ghc-mod' (with
-- some stylistic changes)
--
ghc - mod :
-- /~kazu/proj/ghc-mod/
-- -yamamoto/ghc-mod/
processTypeCheckedModule :: GHC.TypecheckedModule -> (Int, Int) -> GHC.Ghc [((Int, Int, Int, Int), String)]
processTypeCheckedModule tcm (line, col) = do
let tcs = GHC.tm_typechecked_source tcm
bs = listifySpans tcs (line, col) :: [GHC.LHsBind TypecheckI]
es = listifySpans tcs (line, col) :: [GHC.LHsExpr TypecheckI]
ps = listifySpans tcs (line, col) :: [GHC.LPat TypecheckI]
bts <- mapM (getTypeLHsBind tcm) bs
ets <- mapM (getTypeLHsExpr tcm) es
pts <- mapM (getTypeLPat tcm) ps
#if __GLASGOW_HASKELL__ >= 706
dflags <- DynFlags.getDynFlags
return $ map (toTup dflags) $
#else
return $ map toTup $
#endif
sortBy cmp $ catMaybes $ concat [ets, bts, pts]
where
cmp (a, _) (b, _)
| a `GHC.isSubspanOf` b = LT
| b `GHC.isSubspanOf` a = GT
| otherwise = EQ
#if __GLASGOW_HASKELL__ >= 706
toTup :: GHC.DynFlags -> (GHC.SrcSpan, GHC.Type) -> ((Int, Int, Int, Int), String)
toTup dflags (spn, typ) = (fourInts spn, pretty dflags typ)
#else
toTup :: (GHC.SrcSpan, GHC.Type) -> ((Int, Int, Int, Int), String)
toTup (spn, typ) = (fourInts spn, pretty typ)
#endif
fourInts :: GHC.SrcSpan -> (Int, Int, Int, Int)
fourInts = fromMaybe (0, 0, 0, 0) . getSrcSpan
getSrcSpan :: GHC.SrcSpan -> Maybe (Int, Int, Int, Int)
getSrcSpan (GHC.RealSrcSpan spn) =
Just (GHC.srcSpanStartLine spn
, GHC.srcSpanStartCol spn
, GHC.srcSpanEndLine spn
, GHC.srcSpanEndCol spn)
getSrcSpan _ = Nothing
getTypeLHsBind :: GHC.TypecheckedModule -> GHC.LHsBind TypecheckI -> GHC.Ghc (Maybe (GHC.SrcSpan, GHC.Type))
#if __GLASGOW_HASKELL__ >= 806
getTypeLHsBind _ (GHC.L spn GHC.FunBind{GHC.fun_matches = grp}) = return $ Just (spn, HsExpr.mg_res_ty $ HsExpr.mg_ext grp)
#else
#if __GLASGOW_HASKELL__ >= 708
getTypeLHsBind _ (GHC.L spn GHC.FunBind{GHC.fun_matches = grp}) = return $ Just (spn, HsExpr.mg_res_ty grp)
#else
getTypeLHsBind _ (GHC.L spn GHC.FunBind{GHC.fun_matches = GHC.MatchGroup _ typ}) = return $ Just (spn, typ)
#endif
#endif
getTypeLHsBind _ _ = return Nothing
getTypeLHsExpr :: GHC.TypecheckedModule -> GHC.LHsExpr TypecheckI -> GHC.Ghc (Maybe (GHC.SrcSpan, GHC.Type))
#if __GLASGOW_HASKELL__ >= 708
getTypeLHsExpr _ e = do
#else
getTypeLHsExpr tcm e = do
#endif
hs_env <- GHC.getSession
#if __GLASGOW_HASKELL__ >= 708
(_, mbe) <- liftIO $ Desugar.deSugarExpr hs_env e
#else
let modu = GHC.ms_mod $ GHC.pm_mod_summary $ GHC.tm_parsed_module tcm
rn_env = TcRnTypes.tcg_rdr_env $ fst $ GHC.tm_internals_ tcm
ty_env = TcRnTypes.tcg_type_env $ fst $ GHC.tm_internals_ tcm
(_, mbe) <- liftIO $ Desugar.deSugarExpr hs_env modu rn_env ty_env e
#endif
return ()
case mbe of
Nothing -> return Nothing
Just expr -> return $ Just (GHC.getLoc e, CoreUtils.exprType expr)
getTypeLPat :: GHC.TypecheckedModule -> GHC.LPat TypecheckI -> GHC.Ghc (Maybe (GHC.SrcSpan, GHC.Type))
getTypeLPat _ (GHC.L spn pat) = return $ Just (spn, TcHsSyn.hsPatType pat)
listifySpans :: Typeable a => GHC.TypecheckedSource -> (Int, Int) -> [GHC.Located a]
listifySpans tcs lc = listifyStaged TypeChecker p tcs
where
p (GHC.L spn _) = GHC.isGoodSrcSpan spn && spn `GHC.spans` lc
listifyStaged :: Typeable r => Stage -> (r -> Bool) -> GenericQ [r]
listifyStaged s p = everythingStaged s (++) [] ([] `mkQ` (\x -> [x | p x]))
#if __GLASGOW_HASKELL__ >= 706
pretty :: GHC.DynFlags -> GHC.Type -> String
pretty dflags =
#else
pretty :: GHC.Type -> String
pretty =
#endif
#if __GLASGOW_HASKELL__ >= 800
Pretty.renderStyle
Pretty.style{ Pretty.lineLength = 0, Pretty.mode = Pretty.OneLineMode }
#elif __GLASGOW_HASKELL__ >= 708
Pretty.showDoc Pretty.OneLineMode 0
#else
Pretty.showDocWith Pretty.OneLineMode
#endif
#if __GLASGOW_HASKELL__ >= 706
. Outputable.withPprStyleDoc dflags
#else
. Outputable.withPprStyleDoc
#endif
#if __GLASGOW_HASKELL__ >= 802
(Outputable.mkUserStyle dflags Outputable.neverQualify Outputable.AllTheWay)
#else
(Outputable.mkUserStyle Outputable.neverQualify Outputable.AllTheWay)
#endif
#if __GLASGOW_HASKELL__ >= 708
. PprTyThing.pprTypeForUser
#else
. PprTyThing.pprTypeForUser False
#endif
------------------------------------------------------------------------------
-- The following was taken from 'ghc-syb-utils'
--
ghc - syb - utils :
-- -syb
| types tend to have undefined holes , to be filled
by later compiler phases . We tag Asts with their source ,
so that we can avoid such holes based on who generated the Asts .
data Stage = Parser | Renamer | TypeChecker deriving (Eq,Ord,Show)
-- | Like 'everything', but avoid known potholes, based on the 'Stage' that
-- generated the Ast.
everythingStaged :: Stage -> (r -> r -> r) -> r -> GenericQ r -> GenericQ r
everythingStaged stage k z f x
#if __GLASGOW_HASKELL__ >= 806
This is a hack , ghc 8.6 changed representation from PostTc
-- to a whole bunch of individial types and I don't really want
-- to handle all of them, at least for the moment since I'm not using
-- this functionality
| (const False `extQ` fixity `extQ` nameSet) x = z
#else
| (const False `extQ` postTcType `extQ` fixity `extQ` nameSet) x = z
#endif
| otherwise = foldl k (f x) (gmapQ (everythingStaged stage k z f) x)
where nameSet = const (stage `elem` [Parser,TypeChecker]) :: NameSet.NameSet -> Bool
#if __GLASGOW_HASKELL__ >= 806
there 's no more " simple " PostTc type in ghc 8.6
#elif __GLASGOW_HASKELL__ >= 709
postTcType = const (stage<TypeChecker) :: GHC.PostTc TypecheckI GHC.Type -> Bool
#else
postTcType = const (stage<TypeChecker) :: GHC.PostTcType -> Bool
#endif
fixity = const (stage<Renamer) :: GHC.Fixity -> Bool
------------------------------------------------------------------------------
The following code was taken from GHC 's ghc / InteractiveUI.hs ( with some
-- stylistic changes)
infoThing :: String -> GHC.Ghc String
infoThing str = do
names <- GHC.parseName str
#if __GLASGOW_HASKELL__ >= 803
mb_stuffs <- mapM (GHC.getInfo False) names
let filtered = filterOutChildren (\(t,_f,_i,_,_) -> t) (catMaybes mb_stuffs)
#elif __GLASGOW_HASKELL__ >= 708
mb_stuffs <- mapM (GHC.getInfo False) names
let filtered = filterOutChildren (\(t,_f,_i,_) -> t) (catMaybes mb_stuffs)
#else
mb_stuffs <- mapM GHC.getInfo names
let filtered = filterOutChildren (\(t,_f,_i) -> t) (catMaybes mb_stuffs)
#endif
unqual <- GHC.getPrintUnqual
#if __GLASGOW_HASKELL__ >= 706
dflags <- DynFlags.getDynFlags
return $ Outputable.showSDocForUser dflags unqual $
#else
return $ Outputable.showSDocForUser unqual $
#endif
#if __GLASGOW_HASKELL__ >= 708
Outputable.vcat (intersperse (Outputable.text "") $ map pprInfo filtered)
#else
Outputable.vcat (intersperse (Outputable.text "") $ map (pprInfo False) filtered)
#endif
-- Filter out names whose parent is also there Good
-- example is '[]', which is both a type and data
-- constructor in the same type
filterOutChildren :: (a -> HscTypes.TyThing) -> [a] -> [a]
filterOutChildren get_thing xs
= filter (not . has_parent) xs
where
all_names = NameSet.mkNameSet (map (GHC.getName . get_thing) xs)
#if __GLASGOW_HASKELL__ >= 704
has_parent x = case HscTypes.tyThingParent_maybe (get_thing x) of
#else
has_parent x = case PprTyThing.pprTyThingParent_maybe (get_thing x) of
#endif
Just p -> GHC.getName p `NameSet.elemNameSet` all_names
Nothing -> False
#if __GLASGOW_HASKELL__ >= 803
pprInfo :: (HscTypes.TyThing, GHC.Fixity, [GHC.ClsInst], [GHC.FamInst], Outputable.SDoc) -> Outputable.SDoc
pprInfo (thing, fixity, insts, _, _) =
PprTyThing.pprTyThingInContextLoc thing
#elif __GLASGOW_HASKELL__ >= 708
pprInfo :: (HscTypes.TyThing, GHC.Fixity, [GHC.ClsInst], [GHC.FamInst]) -> Outputable.SDoc
pprInfo (thing, fixity, insts, _) =
PprTyThing.pprTyThingInContextLoc thing
#elif __GLASGOW_HASKELL__ >= 706
pprInfo :: PprTyThing.PrintExplicitForalls -> (HscTypes.TyThing, GHC.Fixity, [GHC.ClsInst]) -> Outputable.SDoc
pprInfo pefas (thing, fixity, insts) =
PprTyThing.pprTyThingInContextLoc pefas thing
#else
pprInfo :: PprTyThing.PrintExplicitForalls -> (HscTypes.TyThing, GHC.Fixity, [GHC.Instance]) -> Outputable.SDoc
pprInfo pefas (thing, fixity, insts) =
PprTyThing.pprTyThingInContextLoc pefas thing
#endif
Outputable.$$ show_fixity fixity
Outputable.$$ Outputable.vcat (map GHC.pprInstance insts)
where
show_fixity fix
| fix == GHC.defaultFixity = Outputable.empty
| otherwise = Outputable.ppr fix Outputable.<+> Outputable.ppr (GHC.getName thing)
| null | https://raw.githubusercontent.com/hdevtools/hdevtools/a866f017b74f4b27fabda0861f635da82e43d9fe/src/Info.hs | haskell | # LANGUAGE RankNTypes #
----------------------------------------------------------------------------
Most of the following code was taken from the source code of 'ghc-mod' (with
some stylistic changes)
/~kazu/proj/ghc-mod/
-yamamoto/ghc-mod/
----------------------------------------------------------------------------
The following was taken from 'ghc-syb-utils'
-syb
| Like 'everything', but avoid known potholes, based on the 'Stage' that
generated the Ast.
to a whole bunch of individial types and I don't really want
to handle all of them, at least for the moment since I'm not using
this functionality
----------------------------------------------------------------------------
stylistic changes)
Filter out names whose parent is also there Good
example is '[]', which is both a type and data
constructor in the same type | # LANGUAGE CPP #
module Info
( getIdentifierInfo
, getType
) where
import Data.Generics (GenericQ, mkQ, extQ, gmapQ)
import Data.List (find, sortBy, intersperse)
import Data.Maybe (catMaybes, fromMaybe)
import Data.Typeable (Typeable)
import MonadUtils (liftIO)
import qualified CoreUtils
import qualified Desugar
#if __GLASGOW_HASKELL__ >= 706
import qualified DynFlags
#endif
#if __GLASGOW_HASKELL__ >= 708
import qualified HsExpr
#else
import qualified TcRnTypes
#endif
import qualified GHC
import qualified HscTypes
import qualified NameSet
import qualified Outputable
import qualified PprTyThing
import qualified Pretty
import qualified TcHsSyn
import GhcTypes (getModSummaries, TypecheckI)
getIdentifierInfo :: FilePath -> String -> GHC.Ghc (Either String String)
getIdentifierInfo file identifier =
withModSummary file $ \m -> do
#if __GLASGOW_HASKELL__ >= 706
GHC.setContext [GHC.IIModule (GHC.moduleName (GHC.ms_mod m))]
#elif __GLASGOW_HASKELL__ >= 704
GHC.setContext [GHC.IIModule (GHC.ms_mod m)]
#else
GHC.setContext [GHC.ms_mod m] []
#endif
GHC.handleSourceError (return . Left . show) $
fmap Right (infoThing identifier)
getType :: FilePath -> (Int, Int) -> GHC.Ghc (Either String [((Int, Int, Int, Int), String)])
getType file (line, col) =
withModSummary file $ \m -> do
p <- GHC.parseModule m
typechecked <- GHC.typecheckModule p
types <- processTypeCheckedModule typechecked (line, col)
return (Right types)
withModSummary :: String -> (HscTypes.ModSummary -> GHC.Ghc (Either String a)) -> GHC.Ghc (Either String a)
withModSummary file action = do
modSummary <- getModuleSummary file
case modSummary of
Nothing -> return (Left "Module not found in module graph")
Just m -> action m
getModuleSummary :: FilePath -> GHC.Ghc (Maybe GHC.ModSummary)
getModuleSummary file = do
modSummaries <- getModSummaries
case find (moduleSummaryMatchesFilePath file) modSummaries of
Nothing -> return Nothing
Just moduleSummary -> return (Just moduleSummary)
moduleSummaryMatchesFilePath :: FilePath -> GHC.ModSummary -> Bool
moduleSummaryMatchesFilePath file moduleSummary =
let location = GHC.ms_location moduleSummary
location_file = GHC.ml_hs_file location
in case location_file of
Just f -> f == file
Nothing -> False
ghc - mod :
processTypeCheckedModule :: GHC.TypecheckedModule -> (Int, Int) -> GHC.Ghc [((Int, Int, Int, Int), String)]
processTypeCheckedModule tcm (line, col) = do
let tcs = GHC.tm_typechecked_source tcm
bs = listifySpans tcs (line, col) :: [GHC.LHsBind TypecheckI]
es = listifySpans tcs (line, col) :: [GHC.LHsExpr TypecheckI]
ps = listifySpans tcs (line, col) :: [GHC.LPat TypecheckI]
bts <- mapM (getTypeLHsBind tcm) bs
ets <- mapM (getTypeLHsExpr tcm) es
pts <- mapM (getTypeLPat tcm) ps
#if __GLASGOW_HASKELL__ >= 706
dflags <- DynFlags.getDynFlags
return $ map (toTup dflags) $
#else
return $ map toTup $
#endif
sortBy cmp $ catMaybes $ concat [ets, bts, pts]
where
cmp (a, _) (b, _)
| a `GHC.isSubspanOf` b = LT
| b `GHC.isSubspanOf` a = GT
| otherwise = EQ
#if __GLASGOW_HASKELL__ >= 706
toTup :: GHC.DynFlags -> (GHC.SrcSpan, GHC.Type) -> ((Int, Int, Int, Int), String)
toTup dflags (spn, typ) = (fourInts spn, pretty dflags typ)
#else
toTup :: (GHC.SrcSpan, GHC.Type) -> ((Int, Int, Int, Int), String)
toTup (spn, typ) = (fourInts spn, pretty typ)
#endif
fourInts :: GHC.SrcSpan -> (Int, Int, Int, Int)
fourInts = fromMaybe (0, 0, 0, 0) . getSrcSpan
getSrcSpan :: GHC.SrcSpan -> Maybe (Int, Int, Int, Int)
getSrcSpan (GHC.RealSrcSpan spn) =
Just (GHC.srcSpanStartLine spn
, GHC.srcSpanStartCol spn
, GHC.srcSpanEndLine spn
, GHC.srcSpanEndCol spn)
getSrcSpan _ = Nothing
getTypeLHsBind :: GHC.TypecheckedModule -> GHC.LHsBind TypecheckI -> GHC.Ghc (Maybe (GHC.SrcSpan, GHC.Type))
#if __GLASGOW_HASKELL__ >= 806
getTypeLHsBind _ (GHC.L spn GHC.FunBind{GHC.fun_matches = grp}) = return $ Just (spn, HsExpr.mg_res_ty $ HsExpr.mg_ext grp)
#else
#if __GLASGOW_HASKELL__ >= 708
getTypeLHsBind _ (GHC.L spn GHC.FunBind{GHC.fun_matches = grp}) = return $ Just (spn, HsExpr.mg_res_ty grp)
#else
getTypeLHsBind _ (GHC.L spn GHC.FunBind{GHC.fun_matches = GHC.MatchGroup _ typ}) = return $ Just (spn, typ)
#endif
#endif
getTypeLHsBind _ _ = return Nothing
getTypeLHsExpr :: GHC.TypecheckedModule -> GHC.LHsExpr TypecheckI -> GHC.Ghc (Maybe (GHC.SrcSpan, GHC.Type))
#if __GLASGOW_HASKELL__ >= 708
getTypeLHsExpr _ e = do
#else
getTypeLHsExpr tcm e = do
#endif
hs_env <- GHC.getSession
#if __GLASGOW_HASKELL__ >= 708
(_, mbe) <- liftIO $ Desugar.deSugarExpr hs_env e
#else
let modu = GHC.ms_mod $ GHC.pm_mod_summary $ GHC.tm_parsed_module tcm
rn_env = TcRnTypes.tcg_rdr_env $ fst $ GHC.tm_internals_ tcm
ty_env = TcRnTypes.tcg_type_env $ fst $ GHC.tm_internals_ tcm
(_, mbe) <- liftIO $ Desugar.deSugarExpr hs_env modu rn_env ty_env e
#endif
return ()
case mbe of
Nothing -> return Nothing
Just expr -> return $ Just (GHC.getLoc e, CoreUtils.exprType expr)
getTypeLPat :: GHC.TypecheckedModule -> GHC.LPat TypecheckI -> GHC.Ghc (Maybe (GHC.SrcSpan, GHC.Type))
getTypeLPat _ (GHC.L spn pat) = return $ Just (spn, TcHsSyn.hsPatType pat)
listifySpans :: Typeable a => GHC.TypecheckedSource -> (Int, Int) -> [GHC.Located a]
listifySpans tcs lc = listifyStaged TypeChecker p tcs
where
p (GHC.L spn _) = GHC.isGoodSrcSpan spn && spn `GHC.spans` lc
listifyStaged :: Typeable r => Stage -> (r -> Bool) -> GenericQ [r]
listifyStaged s p = everythingStaged s (++) [] ([] `mkQ` (\x -> [x | p x]))
#if __GLASGOW_HASKELL__ >= 706
pretty :: GHC.DynFlags -> GHC.Type -> String
pretty dflags =
#else
pretty :: GHC.Type -> String
pretty =
#endif
#if __GLASGOW_HASKELL__ >= 800
Pretty.renderStyle
Pretty.style{ Pretty.lineLength = 0, Pretty.mode = Pretty.OneLineMode }
#elif __GLASGOW_HASKELL__ >= 708
Pretty.showDoc Pretty.OneLineMode 0
#else
Pretty.showDocWith Pretty.OneLineMode
#endif
#if __GLASGOW_HASKELL__ >= 706
. Outputable.withPprStyleDoc dflags
#else
. Outputable.withPprStyleDoc
#endif
#if __GLASGOW_HASKELL__ >= 802
(Outputable.mkUserStyle dflags Outputable.neverQualify Outputable.AllTheWay)
#else
(Outputable.mkUserStyle Outputable.neverQualify Outputable.AllTheWay)
#endif
#if __GLASGOW_HASKELL__ >= 708
. PprTyThing.pprTypeForUser
#else
. PprTyThing.pprTypeForUser False
#endif
ghc - syb - utils :
| types tend to have undefined holes , to be filled
by later compiler phases . We tag Asts with their source ,
so that we can avoid such holes based on who generated the Asts .
data Stage = Parser | Renamer | TypeChecker deriving (Eq,Ord,Show)
everythingStaged :: Stage -> (r -> r -> r) -> r -> GenericQ r -> GenericQ r
everythingStaged stage k z f x
#if __GLASGOW_HASKELL__ >= 806
This is a hack , ghc 8.6 changed representation from PostTc
| (const False `extQ` fixity `extQ` nameSet) x = z
#else
| (const False `extQ` postTcType `extQ` fixity `extQ` nameSet) x = z
#endif
| otherwise = foldl k (f x) (gmapQ (everythingStaged stage k z f) x)
where nameSet = const (stage `elem` [Parser,TypeChecker]) :: NameSet.NameSet -> Bool
#if __GLASGOW_HASKELL__ >= 806
there 's no more " simple " PostTc type in ghc 8.6
#elif __GLASGOW_HASKELL__ >= 709
postTcType = const (stage<TypeChecker) :: GHC.PostTc TypecheckI GHC.Type -> Bool
#else
postTcType = const (stage<TypeChecker) :: GHC.PostTcType -> Bool
#endif
fixity = const (stage<Renamer) :: GHC.Fixity -> Bool
The following code was taken from GHC 's ghc / InteractiveUI.hs ( with some
infoThing :: String -> GHC.Ghc String
infoThing str = do
names <- GHC.parseName str
#if __GLASGOW_HASKELL__ >= 803
mb_stuffs <- mapM (GHC.getInfo False) names
let filtered = filterOutChildren (\(t,_f,_i,_,_) -> t) (catMaybes mb_stuffs)
#elif __GLASGOW_HASKELL__ >= 708
mb_stuffs <- mapM (GHC.getInfo False) names
let filtered = filterOutChildren (\(t,_f,_i,_) -> t) (catMaybes mb_stuffs)
#else
mb_stuffs <- mapM GHC.getInfo names
let filtered = filterOutChildren (\(t,_f,_i) -> t) (catMaybes mb_stuffs)
#endif
unqual <- GHC.getPrintUnqual
#if __GLASGOW_HASKELL__ >= 706
dflags <- DynFlags.getDynFlags
return $ Outputable.showSDocForUser dflags unqual $
#else
return $ Outputable.showSDocForUser unqual $
#endif
#if __GLASGOW_HASKELL__ >= 708
Outputable.vcat (intersperse (Outputable.text "") $ map pprInfo filtered)
#else
Outputable.vcat (intersperse (Outputable.text "") $ map (pprInfo False) filtered)
#endif
filterOutChildren :: (a -> HscTypes.TyThing) -> [a] -> [a]
filterOutChildren get_thing xs
= filter (not . has_parent) xs
where
all_names = NameSet.mkNameSet (map (GHC.getName . get_thing) xs)
#if __GLASGOW_HASKELL__ >= 704
has_parent x = case HscTypes.tyThingParent_maybe (get_thing x) of
#else
has_parent x = case PprTyThing.pprTyThingParent_maybe (get_thing x) of
#endif
Just p -> GHC.getName p `NameSet.elemNameSet` all_names
Nothing -> False
#if __GLASGOW_HASKELL__ >= 803
pprInfo :: (HscTypes.TyThing, GHC.Fixity, [GHC.ClsInst], [GHC.FamInst], Outputable.SDoc) -> Outputable.SDoc
pprInfo (thing, fixity, insts, _, _) =
PprTyThing.pprTyThingInContextLoc thing
#elif __GLASGOW_HASKELL__ >= 708
pprInfo :: (HscTypes.TyThing, GHC.Fixity, [GHC.ClsInst], [GHC.FamInst]) -> Outputable.SDoc
pprInfo (thing, fixity, insts, _) =
PprTyThing.pprTyThingInContextLoc thing
#elif __GLASGOW_HASKELL__ >= 706
pprInfo :: PprTyThing.PrintExplicitForalls -> (HscTypes.TyThing, GHC.Fixity, [GHC.ClsInst]) -> Outputable.SDoc
pprInfo pefas (thing, fixity, insts) =
PprTyThing.pprTyThingInContextLoc pefas thing
#else
pprInfo :: PprTyThing.PrintExplicitForalls -> (HscTypes.TyThing, GHC.Fixity, [GHC.Instance]) -> Outputable.SDoc
pprInfo pefas (thing, fixity, insts) =
PprTyThing.pprTyThingInContextLoc pefas thing
#endif
Outputable.$$ show_fixity fixity
Outputable.$$ Outputable.vcat (map GHC.pprInstance insts)
where
show_fixity fix
| fix == GHC.defaultFixity = Outputable.empty
| otherwise = Outputable.ppr fix Outputable.<+> Outputable.ppr (GHC.getName thing)
|
12586281362729d14a9a4a102215fa153bc71b9704da2373b09a0ae968edcf0c | hidaris/thinking-dumps | 2-5.rkt | #lang eopl
;;; A data-structure representation of environments
;;; Env = (empty-env) | (extend-env Var SchemeVal Env)
;;; Var = Sym
;;; empty-env : () -> Env
(define empty-env
(lambda ()'()))
extend - env : SchemeVal x Env - > Env
(define extend-env
(lambda (var val env)
(cons `(,var ,val) env)))
;;; apply-env : Env x Var -> SchemeVal
(define apply-env
(lambda (env search-var)
(cond
((null? env)
(report-no-binding-found search-var))
((and (pair? env) (pair? (car env)))
(let ((saved-var (caar env))
(saved-val (cdar env))
(saved-env (cdr env)))
(if (eqv? search-var saved-var)
saved-val
(apply-env saved-env search-var))))
(else
(report-invalid-env env)))))
(define report-no-binding-found
(lambda (search-var)
(eopl:error 'apply-env
"No binding for ~s" search-var)))
(define report-invalid-env
(lambda (env)
(eopl:error 'apply-env
"Bad environment: ~s" env)))
| null | https://raw.githubusercontent.com/hidaris/thinking-dumps/3fceaf9e6195ab99c8315749814a7377ef8baf86/eopl-solutions/chap2/2-5.rkt | racket | A data-structure representation of environments
Env = (empty-env) | (extend-env Var SchemeVal Env)
Var = Sym
empty-env : () -> Env
apply-env : Env x Var -> SchemeVal | #lang eopl
(define empty-env
(lambda ()'()))
extend - env : SchemeVal x Env - > Env
(define extend-env
(lambda (var val env)
(cons `(,var ,val) env)))
(define apply-env
(lambda (env search-var)
(cond
((null? env)
(report-no-binding-found search-var))
((and (pair? env) (pair? (car env)))
(let ((saved-var (caar env))
(saved-val (cdar env))
(saved-env (cdr env)))
(if (eqv? search-var saved-var)
saved-val
(apply-env saved-env search-var))))
(else
(report-invalid-env env)))))
(define report-no-binding-found
(lambda (search-var)
(eopl:error 'apply-env
"No binding for ~s" search-var)))
(define report-invalid-env
(lambda (env)
(eopl:error 'apply-env
"Bad environment: ~s" env)))
|
4bcb40aa3fc9a9bed3f3c7ad8998968721131137ffb4e3d1b1b36f05885e2b7a | eholk/harlan | specialize-string-equality.scm | (library
(harlan middle specialize-string-equality)
(export specialize-string-equality)
(import (rnrs)
(nanopass)
(harlan middle languages M9))
(define (type-of e)
(nanopass-case
(M9.3 Expr) e
((int ,i) 'int)
((bool ,b) 'bool)
((var ,t ,x) t)
((call (var (fn (,t* ...) ,-> ,t) ,x) ,e* ...) t)
((,op ,e1 ,e2) (guard (eq? '= op)) 'bool)
((,op ,e1 ,e2) (type-of e1))
((deref ,[t])
(nanopass-case
(M9.3 Rho-Type) t
((ptr ,t^) t^)
(else (error 'type-of "unexpected type in deref"
(unparse-M9.3 t)))))
((region-ref ,t ,e1 ,e2) t)
((vector-ref ,t ,e1 ,e2) t)
(else (error 'type-of "I don't know how to find this type"
(unparse-M9.3 e)))))
(define-pass specialize-string-equality : M9.3 (m) -> M9.3 ()
(Expr
: Expr (e) -> Expr ()
[(,op ,e1 ,[e2])
(guard (and (eq? op '=) (eq? 'str (type-of e1))))
`(call (c-expr (fn (str str) -> bool) hstrcmp) ,(Expr e1) ,e2)])))
| null | https://raw.githubusercontent.com/eholk/harlan/3afd95b1c3ad02a354481774585e866857a687b8/harlan/middle/specialize-string-equality.scm | scheme | (library
(harlan middle specialize-string-equality)
(export specialize-string-equality)
(import (rnrs)
(nanopass)
(harlan middle languages M9))
(define (type-of e)
(nanopass-case
(M9.3 Expr) e
((int ,i) 'int)
((bool ,b) 'bool)
((var ,t ,x) t)
((call (var (fn (,t* ...) ,-> ,t) ,x) ,e* ...) t)
((,op ,e1 ,e2) (guard (eq? '= op)) 'bool)
((,op ,e1 ,e2) (type-of e1))
((deref ,[t])
(nanopass-case
(M9.3 Rho-Type) t
((ptr ,t^) t^)
(else (error 'type-of "unexpected type in deref"
(unparse-M9.3 t)))))
((region-ref ,t ,e1 ,e2) t)
((vector-ref ,t ,e1 ,e2) t)
(else (error 'type-of "I don't know how to find this type"
(unparse-M9.3 e)))))
(define-pass specialize-string-equality : M9.3 (m) -> M9.3 ()
(Expr
: Expr (e) -> Expr ()
[(,op ,e1 ,[e2])
(guard (and (eq? op '=) (eq? 'str (type-of e1))))
`(call (c-expr (fn (str str) -> bool) hstrcmp) ,(Expr e1) ,e2)])))
| |
48c083eb11077110fe1bf7a3b3e6402c5d161d7b9dc48d26ef626e4356847802 | TorXakis/TorXakis | HelperToSMT.hs |
TorXakis - Model Based Testing
Copyright ( c ) 2015 - 2017 TNO and Radboud University
See LICENSE at root directory of this repository .
TorXakis - Model Based Testing
Copyright (c) 2015-2017 TNO and Radboud University
See LICENSE at root directory of this repository.
-}
module HelperToSMT
where
import Data.Char
import Numeric (showHex)
escape :: String -> String
escape [] = []
escape (x:xs)
| x == '"' = "\"\"" ++ escape xs
| x == '\\' = "\\\\" ++ escape xs
| ord x < 16 = "\\x0" ++ showHex (ord x) (escape xs)
| ord x < 32 || ord x >= 127 = "\\x" ++ showHex (ord x) (escape xs)
| otherwise = x:escape xs | null | https://raw.githubusercontent.com/TorXakis/TorXakis/038463824b3d358df6b6b3ff08732335b7dbdb53/sys/solve/test/HelperToSMT.hs | haskell |
TorXakis - Model Based Testing
Copyright ( c ) 2015 - 2017 TNO and Radboud University
See LICENSE at root directory of this repository .
TorXakis - Model Based Testing
Copyright (c) 2015-2017 TNO and Radboud University
See LICENSE at root directory of this repository.
-}
module HelperToSMT
where
import Data.Char
import Numeric (showHex)
escape :: String -> String
escape [] = []
escape (x:xs)
| x == '"' = "\"\"" ++ escape xs
| x == '\\' = "\\\\" ++ escape xs
| ord x < 16 = "\\x0" ++ showHex (ord x) (escape xs)
| ord x < 32 || ord x >= 127 = "\\x" ++ showHex (ord x) (escape xs)
| otherwise = x:escape xs | |
713baab36683474a03d82e7670333e513d1e29743c41fc6e114c8cf652d66aeb | tov/dssl2 | comment.rkt | #lang racket/base
(provide do-comment
do-uncomment
do-toggle-comment)
(require "line-summary.rkt"
"editor-helpers.rkt"
(only-in racket/class send))
(define *indent-size* 4)
text% ( [ listof Line - summary ] ) - >
(define (do-toggle-comment text [summaries (summarize-span text)])
(case (classify-span summaries)
[(code) (do-comment text summaries)]
[(comment) (do-uncomment text summaries)]
[else (void)]))
text% ( [ listof Line - summary ] ) - >
(define (do-comment text [summaries (summarize-span text)])
(let ([indent (find-span-indent summaries)])
(with-edit-sequence (text)
(for/fold ([adjust 0])
([summary (in-list summaries)])
(cond
[(line-summary-blank? summary)
adjust]
[else
(define text-start (+ (line-summary-start summary) indent adjust))
(send text insert 2 "# " text-start)
(+ adjust 2)])))))
text% ( [ listof Line - summary ] ) - >
(define (do-uncomment text [summaries (summarize-span text)])
(let ([indent (find-span-indent summaries)])
(with-edit-sequence (text)
(for/fold ([adjust 0])
([summary (in-list summaries)])
(cond
[(line-summary-hash summary)
=>
(λ (hash-start)
(define hash-limit (line-summary-hash-limit summary))
(define adj-hash-start (- hash-start adjust))
(define pre-comment-gap
(cond
[(and (= (add1 hash-start) hash-limit)
(line-summary-comm summary))
=>
(λ (comm-start) (- comm-start hash-limit))]
[else 0]))
(define change (add1 (modulo pre-comment-gap *indent-size*)))
(send text delete adj-hash-start (+ adj-hash-start change))
(+ adjust change))]
[else adjust])))))
| null | https://raw.githubusercontent.com/tov/dssl2/105d18069465781bd9b87466f8336d5ce9e9a0f3/private/drracket/comment.rkt | racket | #lang racket/base
(provide do-comment
do-uncomment
do-toggle-comment)
(require "line-summary.rkt"
"editor-helpers.rkt"
(only-in racket/class send))
(define *indent-size* 4)
text% ( [ listof Line - summary ] ) - >
(define (do-toggle-comment text [summaries (summarize-span text)])
(case (classify-span summaries)
[(code) (do-comment text summaries)]
[(comment) (do-uncomment text summaries)]
[else (void)]))
text% ( [ listof Line - summary ] ) - >
(define (do-comment text [summaries (summarize-span text)])
(let ([indent (find-span-indent summaries)])
(with-edit-sequence (text)
(for/fold ([adjust 0])
([summary (in-list summaries)])
(cond
[(line-summary-blank? summary)
adjust]
[else
(define text-start (+ (line-summary-start summary) indent adjust))
(send text insert 2 "# " text-start)
(+ adjust 2)])))))
text% ( [ listof Line - summary ] ) - >
(define (do-uncomment text [summaries (summarize-span text)])
(let ([indent (find-span-indent summaries)])
(with-edit-sequence (text)
(for/fold ([adjust 0])
([summary (in-list summaries)])
(cond
[(line-summary-hash summary)
=>
(λ (hash-start)
(define hash-limit (line-summary-hash-limit summary))
(define adj-hash-start (- hash-start adjust))
(define pre-comment-gap
(cond
[(and (= (add1 hash-start) hash-limit)
(line-summary-comm summary))
=>
(λ (comm-start) (- comm-start hash-limit))]
[else 0]))
(define change (add1 (modulo pre-comment-gap *indent-size*)))
(send text delete adj-hash-start (+ adj-hash-start change))
(+ adjust change))]
[else adjust])))))
| |
e865b17a3534f6368c331ee4bfb1cfb65edf7b30ea5280cb64a24fc85c43789b | may-liu/qtalk | http_muc_session.erl | -module(http_muc_session).
-include("ejabberd.hrl").
-include("logger.hrl").
-include("http_req.hrl").
-include("jlib.hrl").
-export([clean_session_list/1,make_muc_presence/0,update_user_presence_a/4,update_user_presence_a/5,update_pg_muc_register/3,kick_muc_user/2]).
-export([remove_presence_a/4,get_value/3,delete_unavailable_user/4,remove_muc_users/4,make_muc_persistent/0,make_invite_iq/2]).
-export([handle_add_muc_users/4,make_create_muc_iq/0,make_register_muc_iq/0,make_del_register_muc_iq/0]).
-export([check_muc_exist/2]).
-record(session, {sid, usr, us, priority, info, show}).
-record(muc_online_room,
{name_host = {<<"">>, <<"">>} :: {binary(), binary()} | '$1' |
{'_', binary()} | '_',
pid = self() :: pid() | '$2' | '_' | '$1'}).
clean_session_list(Ss) ->
clean_session_list(lists:keysort(#session.usr, Ss), []).
clean_session_list([], Res) -> Res;
clean_session_list([S], Res) -> [S | Res];
clean_session_list([S1, S2 | Rest], Res) ->
if S1#session.usr == S2#session.usr ->
if S1#session.sid > S2#session.sid ->
clean_session_list([S1 | Rest], Res);
true -> clean_session_list([S2 | Rest], Res)
end;
true -> clean_session_list([S2 | Rest], [S1 | Res])
end.
make_muc_presence() ->
#xmlel{name = <<"presence">>,attrs = [{<<"priority">>,<<"5">>}],
children = [#xmlel{name = <<"x">>, attrs =[{<<"xmlns">>, ?NS_MUC}], children = []}]}.
send_muc_opts(Server , Owner , ) - >
%% ok.
update_user_presence_a(Server,User,Muc,Domain) ->
case catch mnesia:dirty_index_read(session,{User,Server}, #session.us) of
{'EXIT', _Reason} -> [];
Ss when is_list(Ss) ->
[ element(2, S#session.sid) ! {update_presence_a,{Muc,Domain,User}} || S <- clean_session_list(Ss), is_integer(S#session.priority)];
_ ->
[]
end.
update_user_presence_a(Server,User,R,Muc,Domain) ->
case catch mnesia:dirty_index_read(session,{User,Server,R}, #session.usr) of
{'EXIT', _Reason} -> [];
[S] when is_record(S,session) ->
element(2, S#session.sid) ! {update_presence_a,{Muc,Domain,User}};
_ ->
[]
end.
update_pg_muc_register(Server,Muc_id,Muc_member) ->
lists:foreach(fun(U) ->
case catch odbc_queries:insert_muc_users(Server,<<"muc_room_users">>,Muc_id,U,Server) of
{updated,1} ->
ok;
Error ->
?DEBUG("Update Reason ~p ~n",[Error])
end end,Muc_member).
kick_muc_user(Server,User) ->
jlib:iq_to_xml(
#iq{type = set, sub_el = [
#xmlel{name = <<"query">>,
attrs = [{<<"xmlns">>,?NS_MUC_ADMIN}], children = [
#xmlel{name = <<"item">>,attrs = [{<<"nick">>,User},{<<"role">>,<<"none">>}], children = [{<<"reason">>,<<"ads">>}]}]}]}).
remove_presence_a(Server,User,Muc,Domain) ->
case catch mnesia:dirty_index_read(session,{User,Server}, #session.us) of
{'EXIT', _Reason} -> [];
Ss when is_list(Ss) ->
[ element(2, S#session.sid) ! {remove_presence_a,{Muc,Domain,User}} || S <- clean_session_list(Ss), is_integer(S#session.priority)];
_ ->
[]
end.
get_value(Key,Args,Default) ->
case proplists:get_value(Key,Args) of
undefined ->
Default;
V ->
V
end.
delete_unavailable_user(Server,Muc_id,Domain,User) ->
case mnesia:dirty_read(muc_online_room, {Muc_id, Domain}) of
[] ->
ok;
[Muc] ->
Muc#muc_online_room.pid ! {delete_unavailable_user,{User,Server,<<"">>}}
end.
remove_muc_users(Server,Users,Muc_id,Domain) ->
case catch mnesia:dirty_read(muc_online_room, {Muc_id, Domain}) of
[] ->
lists:foreach(fun(U) ->
catch odbc_queries:del_muc_user(Server,<<"muc_room_users">>,Muc_id,U) end,Users);
[Muc] ->
lists:foreach(fun(U) ->
case jlib:make_jid(U,Server,<<"">>) of
error ->
ok;
Muc_user ->
Muc#muc_online_room.pid ! {http_del_user,Muc_user}
end,
catch remove_presence_a(Server,U,Muc_id,Domain)
end,Users)
end.
make_muc_persistent() ->
jlib:iq_to_xml(
#iq{type = set, sub_el = [
#xmlel{name = <<"query">>,
attrs = [{<<"xmlns">>,?NS_MUC_OWNER}], children = [
#xmlel{name = <<"x">>,attrs = [{<<"xmlns">>,?NS_XDATA},{<<"type">>,<<"submit">>}],
children = [
#xmlel{name = <<"field">>,attrs = [{<<"var">>,<<"FORM_TYPE">>}],
children = [#xmlel{name = <<"value">>,attrs = [],children = [{xmlcdata,<<"#roomconfig">>}]}]},
#xmlel{name = <<"field">>,attrs = [{<<"var">>,<<"muc#roomconfig_persistentroom">>}],
children = [#xmlel{name = <<"value">>,attrs = [],children = [{xmlcdata,<<"1">>}]}]},
#xmlel{name = <<"field">>,attrs = [{<<"var">>,<<"muc#roomconfig_publicroom">>}],
children = [#xmlel{name = <<"value">>,attrs = [],children = [{xmlcdata,<<"1">>}]}]}
]}]}]}).
[ { xmlel,<<"value">>,[],[{xmlcdata,<<" / protocol / muc#roomconfig " > > } ] } ]
# xmlel{name = < < " value">>,attrs = [ ] , children = [ { xmlcdata,<<" / protocol / muc#roomconfig " > > } ] }
make_invite_iq(Users,Server) ->
jlib:iq_to_xml(
#iq{type = set, sub_el = [
#xmlel{name = <<"query">>,
attrs = [{<<"xmlns">>,?NS_MUC_INVITE_V2}], children =
lists:map(fun(U) ->
JID = jlib:jid_to_string({U,Server,<<"">>}),
#xmlel{name = <<"invite">>,attrs = [{<<"jid">>,JID}], children = []} end,Users) }]}).
make_create_muc_iq() ->
jlib:iq_to_xml(
#iq{type = set, sub_el = [
#xmlel{name = <<"query">>,
attrs = [{<<"xmlns">>,?NS_CREATE_MUC}], children = []}]}).
make_register_muc_iq() ->
jlib:iq_to_xml(
#iq{type = set, sub_el = [
#xmlel{name = <<"query">>,
attrs = [{<<"xmlns">>,?NS_MUC_REGISTER}], children = []}]}).
make_del_register_muc_iq() ->
jlib:iq_to_xml(
#iq{type = set, sub_el = [
#xmlel{name = <<"query">>,
attrs = [{<<"xmlns">>,?NS_MUC_DEL_REGISTER}], children = []}]}).
handle_add_muc_users(Server,Muc_id,Domain,Jid) ->
case catch mnesia:dirty_read(muc_online_room, {Muc_id, Domain}) of
[] ->
catch odbc_queries:insert_muc_users(Server,<<"muc_room_users">>,Muc_id,Jid#jid.luser,Jid#jid.lserver);
[Muc] ->
Muc#muc_online_room.pid ! {http_add_user,Jid}
end.
check_muc_exist(Server,Muc) ->
case catch ejabberd_odbc:sql_query(Server,
[<<"select name from muc_room where name = '">>,Muc,<<"';">>]) of
{selected,[<<"name">>],[[Muc]]} ->
true;
_ ->
false
end.
| null | https://raw.githubusercontent.com/may-liu/qtalk/f5431e5a7123975e9656e7ab239e674ce33713cd/qtalk_opensource/src/http_muc_session.erl | erlang | ok. | -module(http_muc_session).
-include("ejabberd.hrl").
-include("logger.hrl").
-include("http_req.hrl").
-include("jlib.hrl").
-export([clean_session_list/1,make_muc_presence/0,update_user_presence_a/4,update_user_presence_a/5,update_pg_muc_register/3,kick_muc_user/2]).
-export([remove_presence_a/4,get_value/3,delete_unavailable_user/4,remove_muc_users/4,make_muc_persistent/0,make_invite_iq/2]).
-export([handle_add_muc_users/4,make_create_muc_iq/0,make_register_muc_iq/0,make_del_register_muc_iq/0]).
-export([check_muc_exist/2]).
-record(session, {sid, usr, us, priority, info, show}).
-record(muc_online_room,
{name_host = {<<"">>, <<"">>} :: {binary(), binary()} | '$1' |
{'_', binary()} | '_',
pid = self() :: pid() | '$2' | '_' | '$1'}).
clean_session_list(Ss) ->
clean_session_list(lists:keysort(#session.usr, Ss), []).
clean_session_list([], Res) -> Res;
clean_session_list([S], Res) -> [S | Res];
clean_session_list([S1, S2 | Rest], Res) ->
if S1#session.usr == S2#session.usr ->
if S1#session.sid > S2#session.sid ->
clean_session_list([S1 | Rest], Res);
true -> clean_session_list([S2 | Rest], Res)
end;
true -> clean_session_list([S2 | Rest], [S1 | Res])
end.
make_muc_presence() ->
#xmlel{name = <<"presence">>,attrs = [{<<"priority">>,<<"5">>}],
children = [#xmlel{name = <<"x">>, attrs =[{<<"xmlns">>, ?NS_MUC}], children = []}]}.
send_muc_opts(Server , Owner , ) - >
update_user_presence_a(Server,User,Muc,Domain) ->
case catch mnesia:dirty_index_read(session,{User,Server}, #session.us) of
{'EXIT', _Reason} -> [];
Ss when is_list(Ss) ->
[ element(2, S#session.sid) ! {update_presence_a,{Muc,Domain,User}} || S <- clean_session_list(Ss), is_integer(S#session.priority)];
_ ->
[]
end.
update_user_presence_a(Server,User,R,Muc,Domain) ->
case catch mnesia:dirty_index_read(session,{User,Server,R}, #session.usr) of
{'EXIT', _Reason} -> [];
[S] when is_record(S,session) ->
element(2, S#session.sid) ! {update_presence_a,{Muc,Domain,User}};
_ ->
[]
end.
update_pg_muc_register(Server,Muc_id,Muc_member) ->
lists:foreach(fun(U) ->
case catch odbc_queries:insert_muc_users(Server,<<"muc_room_users">>,Muc_id,U,Server) of
{updated,1} ->
ok;
Error ->
?DEBUG("Update Reason ~p ~n",[Error])
end end,Muc_member).
kick_muc_user(Server,User) ->
jlib:iq_to_xml(
#iq{type = set, sub_el = [
#xmlel{name = <<"query">>,
attrs = [{<<"xmlns">>,?NS_MUC_ADMIN}], children = [
#xmlel{name = <<"item">>,attrs = [{<<"nick">>,User},{<<"role">>,<<"none">>}], children = [{<<"reason">>,<<"ads">>}]}]}]}).
remove_presence_a(Server,User,Muc,Domain) ->
case catch mnesia:dirty_index_read(session,{User,Server}, #session.us) of
{'EXIT', _Reason} -> [];
Ss when is_list(Ss) ->
[ element(2, S#session.sid) ! {remove_presence_a,{Muc,Domain,User}} || S <- clean_session_list(Ss), is_integer(S#session.priority)];
_ ->
[]
end.
get_value(Key,Args,Default) ->
case proplists:get_value(Key,Args) of
undefined ->
Default;
V ->
V
end.
delete_unavailable_user(Server,Muc_id,Domain,User) ->
case mnesia:dirty_read(muc_online_room, {Muc_id, Domain}) of
[] ->
ok;
[Muc] ->
Muc#muc_online_room.pid ! {delete_unavailable_user,{User,Server,<<"">>}}
end.
remove_muc_users(Server,Users,Muc_id,Domain) ->
case catch mnesia:dirty_read(muc_online_room, {Muc_id, Domain}) of
[] ->
lists:foreach(fun(U) ->
catch odbc_queries:del_muc_user(Server,<<"muc_room_users">>,Muc_id,U) end,Users);
[Muc] ->
lists:foreach(fun(U) ->
case jlib:make_jid(U,Server,<<"">>) of
error ->
ok;
Muc_user ->
Muc#muc_online_room.pid ! {http_del_user,Muc_user}
end,
catch remove_presence_a(Server,U,Muc_id,Domain)
end,Users)
end.
make_muc_persistent() ->
jlib:iq_to_xml(
#iq{type = set, sub_el = [
#xmlel{name = <<"query">>,
attrs = [{<<"xmlns">>,?NS_MUC_OWNER}], children = [
#xmlel{name = <<"x">>,attrs = [{<<"xmlns">>,?NS_XDATA},{<<"type">>,<<"submit">>}],
children = [
#xmlel{name = <<"field">>,attrs = [{<<"var">>,<<"FORM_TYPE">>}],
children = [#xmlel{name = <<"value">>,attrs = [],children = [{xmlcdata,<<"#roomconfig">>}]}]},
#xmlel{name = <<"field">>,attrs = [{<<"var">>,<<"muc#roomconfig_persistentroom">>}],
children = [#xmlel{name = <<"value">>,attrs = [],children = [{xmlcdata,<<"1">>}]}]},
#xmlel{name = <<"field">>,attrs = [{<<"var">>,<<"muc#roomconfig_publicroom">>}],
children = [#xmlel{name = <<"value">>,attrs = [],children = [{xmlcdata,<<"1">>}]}]}
]}]}]}).
[ { xmlel,<<"value">>,[],[{xmlcdata,<<" / protocol / muc#roomconfig " > > } ] } ]
# xmlel{name = < < " value">>,attrs = [ ] , children = [ { xmlcdata,<<" / protocol / muc#roomconfig " > > } ] }
make_invite_iq(Users,Server) ->
jlib:iq_to_xml(
#iq{type = set, sub_el = [
#xmlel{name = <<"query">>,
attrs = [{<<"xmlns">>,?NS_MUC_INVITE_V2}], children =
lists:map(fun(U) ->
JID = jlib:jid_to_string({U,Server,<<"">>}),
#xmlel{name = <<"invite">>,attrs = [{<<"jid">>,JID}], children = []} end,Users) }]}).
make_create_muc_iq() ->
jlib:iq_to_xml(
#iq{type = set, sub_el = [
#xmlel{name = <<"query">>,
attrs = [{<<"xmlns">>,?NS_CREATE_MUC}], children = []}]}).
make_register_muc_iq() ->
jlib:iq_to_xml(
#iq{type = set, sub_el = [
#xmlel{name = <<"query">>,
attrs = [{<<"xmlns">>,?NS_MUC_REGISTER}], children = []}]}).
make_del_register_muc_iq() ->
jlib:iq_to_xml(
#iq{type = set, sub_el = [
#xmlel{name = <<"query">>,
attrs = [{<<"xmlns">>,?NS_MUC_DEL_REGISTER}], children = []}]}).
handle_add_muc_users(Server,Muc_id,Domain,Jid) ->
case catch mnesia:dirty_read(muc_online_room, {Muc_id, Domain}) of
[] ->
catch odbc_queries:insert_muc_users(Server,<<"muc_room_users">>,Muc_id,Jid#jid.luser,Jid#jid.lserver);
[Muc] ->
Muc#muc_online_room.pid ! {http_add_user,Jid}
end.
check_muc_exist(Server,Muc) ->
case catch ejabberd_odbc:sql_query(Server,
[<<"select name from muc_room where name = '">>,Muc,<<"';">>]) of
{selected,[<<"name">>],[[Muc]]} ->
true;
_ ->
false
end.
|
872ebcfc37106017f085c7877e1066c02ac9315ac18f219c8e33c2f47428c3da | shirok/Gauche | skew-list.scm | ;;;
;;; data.skew-list - Skewed Binary Random Access List
;;;
Copyright ( c ) 2019 - 2022 < >
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; 2. Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
;;; 3. Neither the name of the 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 IMPLIED WARRANTIES , INCLUDING , BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;
Implements SkewList as described in
: Purely Functional Data Structures
;;
;; Tree a = Leaf a | Node a (Tree a) (Tree a)
SkewList a = SL [ ( Int , Tree a ) ]
(define-module data.skew-list
(use gauche.record)
(use gauche.sequence)
(use util.match)
(use util.queue)
(export <skew-list>
skew-list?
skew-list-empty?
skew-list-null
skew-list-cons
skew-list-car
skew-list-cdr
skew-list-ref
skew-list-set
skew-list-fold
skew-list-map
skew-list-length
skew-list-length<=?
list*->skew-list
list->skew-list
skew-list->list
skew-list->generator
skew-list->lseq
skew-list-take
skew-list-drop
skew-list-split-at
skew-list-append)
)
(select-module data.skew-list)
(define-class <skew-list-meta> (<record-meta>) ())
(define-record-type (<skew-list> #f :mixins (<sequence>)
:metaclass <skew-list-meta>)
%make-sl skew-list?
(elements skew-list-elements)) ; [(Int, Tree)]]
(define (SL elts)
(if (null? elts)
skew-list-null ;singleton to save allocation
(%make-sl elts)))
We use these frequently . NB : n is always 2^k-1 .
(define-inline (/2 n) (ash n -1))
(define-inline (/4 n) (ash n -2))
;;;
;;; Primitives
;;;
(define (skew-list-empty? sl)
(assume-type sl <skew-list>)
(null? (skew-list-elements sl)))
(define skew-list-null (%make-sl '()))
(define (skew-list-cons x y)
(assume-type y <skew-list>)
(match (skew-list-elements y)
[([w1 . t1] [w2 . t2] . ts)
(if (= w1 w2)
(SL `([,(+ 1 w1 w2) . (Node ,x ,t1 ,t2)] ,@ts))
(SL `([1 . (Leaf ,x)] ,@(skew-list-elements y))))]
[_ (SL `([1 . (Leaf ,x)] ,@(skew-list-elements y)))]))
(define (skew-list-car sl)
(assume-type sl <skew-list>)
(match (skew-list-elements sl)
[() (error "Attempt to take skew-list-car of empty skew-list")]
[([_ . ('Leaf x)] . _) x]
[([_ . ('Node x _ _)] . _) x]))
(define (skew-list-cdr sl)
(assume-type sl <skew-list>)
(match (skew-list-elements sl)
[() (error "Attempt to take skew-list-cdr of empty skew-list")]
[([_ . ('Leaf _)] . ts) (SL ts)]
[([w . ('Node x t1 t2)] . ts)
(SL `([,(/2 w) . ,t1] [,(/2 w) . ,t2] ,@ts))]))
(define (skew-list-ref sl n :optional fallback)
(define (tree-ref w i t)
(if (= i 0)
(cadr t)
(if (= w 1)
(if (undefined? fallback)
(error "index out of range" n)
fallback)
(match-let1 ('Node x t1 t2) t
(let1 w2 (/2 w)
(if (<= i w2)
(tree-ref w2 (- i 1) t1)
(tree-ref w2 (- i 1 w2) t2)))))))
(define (ref i ts)
(match ts
[() (if (undefined? fallback)
(error "index out of range" n)
fallback)]
[((w . t) . ts)
(if (< i w) (tree-ref w i t) (ref (- i w) ts))]))
(assume-type sl <skew-list>)
(ref n (skew-list-elements sl)))
(define (skew-list-set sl n v)
(define (tree-set w i t)
(if (= i 0)
(match t
[('Leaf _) `(Leaf ,v)]
[(`Node _ t1 t2) `(Node ,v ,t1 ,t2)])
(if (= w 1)
(error "index out of range" n)
(match-let1 ('Node x t1 t2) t
(let1 w2 (/2 w)
(if (<= i w2)
`(Node ,x ,(tree-set w2 (- i 1) t1) ,t2)
`(Node ,x ,t1 ,(tree-set w2 (- i 1 w2) t2))))))))
(define (set i ts)
(match ts
[() (error "index out of range" n)]
[((w . t) . ts)
(if (< i w)
`((,w . ,(tree-set w i t)) ,@ts)
`((,w . ,t) ,@(set (- i w) ts)))]))
(assume-type sl <skew-list>)
(SL (set n (skew-list-elements sl))))
;;;
;;; Conversion
;;;
Input may be an improper list . Returns SL and the last cdr .
(define (list*->skew-list lis)
(if (pair? lis)
(let1 spine-len (let loop ((lis lis) (n 0))
(if (pair? lis) (loop (cdr lis) (+ n 1)) n))
divide n into ( k0 k1 ... ) where each k is 2^j-1 and decreasing order
(define (series-2^n-1 n)
(cond [(= n 0) '()]
[(= n 1) '(1)]
[else (let1 k (- (ash 1 (- (integer-length (+ n 1)) 1)) 1)
(cons k (series-2^n-1 (- n k))))]))
make tree from first n elts of lis ( n = 2^j-1 )
;; returns the rest of the lis as well,
;; being careful not to copy the spine of lis.
(define (make-tree n lis)
(if (= n 1)
(values `(Leaf ,(car lis)) (cdr lis))
(let1 n2 (ash (- n 1) -1)
(receive (t1 rest) (make-tree n2 (cdr lis))
(receive (t2 rest) (make-tree n2 rest)
(values `(Node ,(car lis) ,t1 ,t2) rest))))))
;; get reversed series-2^n-1
;; returns [(Size . Tree)] and the last cdr of lis
(define (make-forest ns lis)
(if (null? ns)
(values '() lis)
(receive (tree rest) (make-tree (car ns) lis)
(receive (forest last-cdr) (make-forest (cdr ns) rest)
(values (acons (car ns) tree forest) last-cdr)))))
;; Build one.
(receive (forest last-cdr)
(make-forest (reverse (series-2^n-1 spine-len)) lis)
(values (SL forest) last-cdr)))
(values skew-list-null lis)))
(define (list->skew-list lis)
(receive (sl last-cdr) (list*->skew-list lis)
(unless (null? last-cdr)
(error "proper list required, but got" lis))
sl))
(define (skew-list->list sl)
(assume-type sl <skew-list>)
(reverse (skew-list-fold sl cons '())))
;;;
Comparison
;;;
(define-method object-equal? ((a <skew-list>) (b <skew-list>))
(equal? (skew-list-elements a)
(skew-list-elements b)))
;;;
Utilities
;;;
(define (skew-list-fold sl proc seed)
(define (tree-fold tree seed)
(match tree
[('Leaf x) (proc x seed)]
[('Node x t1 t2)
(tree-fold t2 (tree-fold t1 (proc x seed)))]))
(assume-type sl <skew-list>)
(fold (^[p s] (tree-fold (cdr p) s)) seed (skew-list-elements sl)))
NB : We do n't support general ( n - ary ) map ; it can be done via
sequence framework . One arg map is worth to support , for we can take
;; advantage of isomorphism of input and output.
(define (skew-list-map sl f)
(define (tmap tree)
(match tree
[('Leaf x) `(Leaf ,(f x))]
[('Node x t0 t1) `(Node ,(f x) ,(tmap t0) ,(tmap t1))]))
(SL (map (^p `(,(car p) . ,(tmap (cdr p)))) (skew-list-elements sl))))
(define (skew-list-length sl)
(assume-type sl <skew-list>)
(fold (^[p s] (+ (car p) s)) 0 (skew-list-elements sl)))
(define (skew-list-length<=? sl k)
(assume-type sl <skew-list>)
(let loop ([es (skew-list-elements sl)] [s 0])
(cond [(< k s) #f]
[(null? es) #t]
[else (loop (cdr es) (+ s (caar es)))])))
;; Tree, Int, Int, [Tree] -> [Tree]
;; Given Tree of size N, returns [Tree] which includes the K-th element
;; and after. The last input is the tail of the output.
(define (tree-kth-and-after t n k tail)
(if (zero? k)
(cons t tail)
(match-let1 ('Node _ t1 t2) t
(let1 m (/2 n)
(if (<= k m)
(tree-kth-and-after t1 m (- k 1) (cons t2 tail))
(tree-kth-and-after t2 m (- k m 1) tail))))))
;; [(Int, Tree)], Int -> [(Int, Tree)], Int
in seq that does n't contain K - th element . Returns offset as well .
(define (skip-seq seq k)
(if (< k (caar seq))
(values seq k)
(skip-seq (cdr seq) (- k (caar seq)))))
(define (%skew-list-iterator sl start end_)
(define seq (skew-list-elements sl))
(define stack '()) ; [Tree]
(define end (or end_ (skew-list-length sl)))
(define pos start)
(define (next)
(if (= pos end)
(values #f #t)
(match stack
[() (set! stack (list (cdr (pop! seq)))) (next)]
[(('Leaf x) . xs) (set! stack xs) (inc! pos)(values x #f)]
[(('Node x t1 t2) . xs) (set! stack (list* t1 t2 xs)) (inc! pos) (values x #f)])))
;; Adjust start point
(unless (<= start end) (errorf "start ~s is greater than end ~s" start end))
(when (< 0 start)
(receive (seq_ k) (skip-seq seq start)
(set! stack (tree-kth-and-after (cdar seq_) (caar seq_) k '()))
(set! seq (cdr seq_))))
next)
(define (skew-list->generator sl :optional start end)
(define iter (%skew-list-iterator sl
(if (undefined? start) 0 start)
(if (undefined? end) #f end)))
(^[] (receive (x eof?) (iter)
(if eof? (eof-object) x))))
(define (skew-list->lseq sl :optional start end)
(define iter (%skew-list-iterator sl
(if (undefined? start) 0 start)
(if (undefined? end) #f end)))
((rec (loop)
(receive (x eof?) (iter)
(if eof?
'()
(lcons x (loop)))))))
take / drop first k elements
;; In some cases we can share the some of the trees in the original skew-list.
;; Other than the obvious cases when k is the sum of prefix of the original
seq , there are some nontrivial cases . Suppose 1 < n and n = 2m+1 .
;; If original seq begins with:
[ 1 n ... ] - > We can take 2 and 2+m if m>1
( e.g. from [ 1 7 .. ] we can take [ 1 1 ] and [ 1 1 3 ]
[ n ... ] - > We can take 1 , 2 , 1+m , 2+m ' ( where m = 2m'+1 )
( e.g. from [ 15 ... ] we can take [ 1 7 ] , [ 1 1 3 ]
(define (%skew-list-splitter sl k rettype)
;; The branch logic is common among take, drop and split-at. This macro
;; dispatches the return value.
(define-syntax ret
(syntax-rules ()
[(_ taken dropped)
(case rettype
[(take) (SL taken)]
[(drop) (SL dropped)]
[(split) (cons (SL taken) (SL dropped))])]))
(define elts (skew-list-elements sl))
(define (trivial-prefix)
(let loop ([seq elts] [sum 0] [i 0])
(cond [(= k sum) (ret (take elts i) (drop elts i))]
[(> k sum) (loop (cdr seq) (+ sum (caar seq)) (+ i 1))]
[else #f])))
(define (special-prefix)
(match (skew-list-elements sl)
[((1 . x) (n . ('Node y t1 t2)) . zs)
(if (= k 2)
(ret `((1 . ,x) (1 . (Leaf ,y)))
`((,(/2 n) . ,t1) (,(/2 n) . ,t2) ,@zs))
(and (> n 3)
(= k (+ 2 (/2 n)))
(ret `((1 . ,x) (1 . (Leaf ,y)) (,(/2 n) . ,t1))
`((,(/2 n) . ,t2) ,@zs))))]
[((n . ('Node x (and ('Node y t11 t12) t1) t2)) . zs)
(cond [(= k 1) (ret `((1 . (Leaf ,x)))
`((,(/2 n) . ,t1) (,(/2 n) . ,t2) ,@zs))]
[(= k 2) (ret `((1 . (Leaf ,x)) (1 . (Leaf ,y)))
`((,(/4 n) . ,t11) (,(/4 n) . ,t12) (,(/2 n) . ,t2) ,@zs))]
[(= k (+ 1 (/2 n)))
(ret `((1 . (Leaf ,x)) (,(/2 n) . ,t1))
`((,(/2 n) . ,t2) ,@zs))]
[(and (> k 3) (= k (+ 2 (/4 n))) )
(ret `((1 . (Leaf ,x)) (1 . (Leaf ,y)) (,(/4 n) . ,t11))
`((,(/4 n) . ,t12) (,(/2 n) . ,t2) ,@zs))]
[else #f])]
[((n . ('Node x ('Leaf y) t2)) . zs)
(cond [(= k 1) (ret `((1 . (Leaf ,x)))
`((1 . (Leaf ,y)) (,(/2 n) . ,t2) ,@zs))]
[(= k 2) (ret `((1 . (Leaf ,x)) (1 . (Leaf ,y)))
`((,(/2 n) . ,t2) ,@zs))]
[else #f])]))
(define (fallback)
(case rettype
[(take) (list->skew-list (skew-list->lseq sl 0 k))]
[(drop) (list->skew-list (skew-list->lseq sl k))]
[(split) (let1 lis (skew-list->list sl)
(receive (t d) (split-at lis k)
(cons (list->skew-list t) (list->skew-list d))))]))
(or (trivial-prefix)
(special-prefix)
(fallback)))
(define (skew-list-take sl k) (%skew-list-splitter sl k 'take))
(define (skew-list-drop sl k) (%skew-list-splitter sl k 'drop))
(define (skew-list-split-at sl k)
(let1 r (%skew-list-splitter sl k 'split)
(values (car r) (cdr r))))
(define (skew-list-append sl . sls)
(cond [(null? sls) sl]
[(skew-list-empty? sl) (apply skew-list-append sls)]
[(not (skew-list? sl)) (error "argument must be a skew list:" sl)]
[else (%skew-list-append2 sl (apply skew-list-append sls))]))
(define (%skew-list-append2 sl1 sl2)
(define (slow-append sl1 sl2)
(list->skew-list (append (skew-list->list sl1) (skew-list->list sl2))))
(match (skew-list-elements sl1)
[((1 . ('Leaf x))) (skew-list-cons x sl2)]
[((w0 . t0))
(match-let1 ((w1 . t1) . ts) (skew-list-elements sl2)
(if (= w0 w1)
(SL (cons (car (skew-list-elements sl1)) (skew-list-elements sl2)))
(slow-append sl1 sl2)))]
[_
(match-let1 (wz . tz) (last (skew-list-elements sl1))
(match-let1 ((w1 . t1) . ts) (skew-list-elements sl2)
(if (< wz w1)
(SL (append (skew-list-elements sl1) (skew-list-elements sl2)))
(slow-append sl1 sl2))))]))
;;;
;;; Collection & sequence protocol
;;;
(define-method call-with-iterator ((sl <skew-list>) proc)
(define iter (%skew-list-iterator sl 0 #f))
(define-values (item end) (iter))
(define (end?) end)
(define (next) (begin0 item
(set!-values (item end) (iter))))
(proc end? next))
(define-method call-with-builder ((slc <skew-list-meta>) proc :allow-other-keys)
(let1 q (make-queue)
(proc (cut enqueue! q <>)
(cut list->skew-list (dequeue-all! q)))))
(define-method fold (proc knil (sl <skew-list>))
(skew-list-fold sl proc knil))
(define-method size-of ((sl <skew-list>)) (skew-list-length sl))
(define-method referencer ((sl <skew-list>))
(^[o i] (skew-list-ref o i)))
| null | https://raw.githubusercontent.com/shirok/Gauche/b773899dbe0b2955e1c4f1daa066da874070c1e4/lib/data/skew-list.scm | scheme |
data.skew-list - Skewed Binary Random Access List
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the 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
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Tree a = Leaf a | Node a (Tree a) (Tree a)
[(Int, Tree)]]
singleton to save allocation
Primitives
Conversion
returns the rest of the lis as well,
being careful not to copy the spine of lis.
get reversed series-2^n-1
returns [(Size . Tree)] and the last cdr of lis
Build one.
it can be done via
advantage of isomorphism of input and output.
Tree, Int, Int, [Tree] -> [Tree]
Given Tree of size N, returns [Tree] which includes the K-th element
and after. The last input is the tail of the output.
[(Int, Tree)], Int -> [(Int, Tree)], Int
[Tree]
Adjust start point
In some cases we can share the some of the trees in the original skew-list.
Other than the obvious cases when k is the sum of prefix of the original
If original seq begins with:
The branch logic is common among take, drop and split-at. This macro
dispatches the return value.
Collection & sequence protocol
| Copyright ( c ) 2019 - 2022 < >
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
Implements SkewList as described in
: Purely Functional Data Structures
SkewList a = SL [ ( Int , Tree a ) ]
(define-module data.skew-list
(use gauche.record)
(use gauche.sequence)
(use util.match)
(use util.queue)
(export <skew-list>
skew-list?
skew-list-empty?
skew-list-null
skew-list-cons
skew-list-car
skew-list-cdr
skew-list-ref
skew-list-set
skew-list-fold
skew-list-map
skew-list-length
skew-list-length<=?
list*->skew-list
list->skew-list
skew-list->list
skew-list->generator
skew-list->lseq
skew-list-take
skew-list-drop
skew-list-split-at
skew-list-append)
)
(select-module data.skew-list)
(define-class <skew-list-meta> (<record-meta>) ())
(define-record-type (<skew-list> #f :mixins (<sequence>)
:metaclass <skew-list-meta>)
%make-sl skew-list?
(define (SL elts)
(if (null? elts)
(%make-sl elts)))
We use these frequently . NB : n is always 2^k-1 .
(define-inline (/2 n) (ash n -1))
(define-inline (/4 n) (ash n -2))
(define (skew-list-empty? sl)
(assume-type sl <skew-list>)
(null? (skew-list-elements sl)))
(define skew-list-null (%make-sl '()))
(define (skew-list-cons x y)
(assume-type y <skew-list>)
(match (skew-list-elements y)
[([w1 . t1] [w2 . t2] . ts)
(if (= w1 w2)
(SL `([,(+ 1 w1 w2) . (Node ,x ,t1 ,t2)] ,@ts))
(SL `([1 . (Leaf ,x)] ,@(skew-list-elements y))))]
[_ (SL `([1 . (Leaf ,x)] ,@(skew-list-elements y)))]))
(define (skew-list-car sl)
(assume-type sl <skew-list>)
(match (skew-list-elements sl)
[() (error "Attempt to take skew-list-car of empty skew-list")]
[([_ . ('Leaf x)] . _) x]
[([_ . ('Node x _ _)] . _) x]))
(define (skew-list-cdr sl)
(assume-type sl <skew-list>)
(match (skew-list-elements sl)
[() (error "Attempt to take skew-list-cdr of empty skew-list")]
[([_ . ('Leaf _)] . ts) (SL ts)]
[([w . ('Node x t1 t2)] . ts)
(SL `([,(/2 w) . ,t1] [,(/2 w) . ,t2] ,@ts))]))
(define (skew-list-ref sl n :optional fallback)
(define (tree-ref w i t)
(if (= i 0)
(cadr t)
(if (= w 1)
(if (undefined? fallback)
(error "index out of range" n)
fallback)
(match-let1 ('Node x t1 t2) t
(let1 w2 (/2 w)
(if (<= i w2)
(tree-ref w2 (- i 1) t1)
(tree-ref w2 (- i 1 w2) t2)))))))
(define (ref i ts)
(match ts
[() (if (undefined? fallback)
(error "index out of range" n)
fallback)]
[((w . t) . ts)
(if (< i w) (tree-ref w i t) (ref (- i w) ts))]))
(assume-type sl <skew-list>)
(ref n (skew-list-elements sl)))
(define (skew-list-set sl n v)
(define (tree-set w i t)
(if (= i 0)
(match t
[('Leaf _) `(Leaf ,v)]
[(`Node _ t1 t2) `(Node ,v ,t1 ,t2)])
(if (= w 1)
(error "index out of range" n)
(match-let1 ('Node x t1 t2) t
(let1 w2 (/2 w)
(if (<= i w2)
`(Node ,x ,(tree-set w2 (- i 1) t1) ,t2)
`(Node ,x ,t1 ,(tree-set w2 (- i 1 w2) t2))))))))
(define (set i ts)
(match ts
[() (error "index out of range" n)]
[((w . t) . ts)
(if (< i w)
`((,w . ,(tree-set w i t)) ,@ts)
`((,w . ,t) ,@(set (- i w) ts)))]))
(assume-type sl <skew-list>)
(SL (set n (skew-list-elements sl))))
Input may be an improper list . Returns SL and the last cdr .
(define (list*->skew-list lis)
(if (pair? lis)
(let1 spine-len (let loop ((lis lis) (n 0))
(if (pair? lis) (loop (cdr lis) (+ n 1)) n))
divide n into ( k0 k1 ... ) where each k is 2^j-1 and decreasing order
(define (series-2^n-1 n)
(cond [(= n 0) '()]
[(= n 1) '(1)]
[else (let1 k (- (ash 1 (- (integer-length (+ n 1)) 1)) 1)
(cons k (series-2^n-1 (- n k))))]))
make tree from first n elts of lis ( n = 2^j-1 )
(define (make-tree n lis)
(if (= n 1)
(values `(Leaf ,(car lis)) (cdr lis))
(let1 n2 (ash (- n 1) -1)
(receive (t1 rest) (make-tree n2 (cdr lis))
(receive (t2 rest) (make-tree n2 rest)
(values `(Node ,(car lis) ,t1 ,t2) rest))))))
(define (make-forest ns lis)
(if (null? ns)
(values '() lis)
(receive (tree rest) (make-tree (car ns) lis)
(receive (forest last-cdr) (make-forest (cdr ns) rest)
(values (acons (car ns) tree forest) last-cdr)))))
(receive (forest last-cdr)
(make-forest (reverse (series-2^n-1 spine-len)) lis)
(values (SL forest) last-cdr)))
(values skew-list-null lis)))
(define (list->skew-list lis)
(receive (sl last-cdr) (list*->skew-list lis)
(unless (null? last-cdr)
(error "proper list required, but got" lis))
sl))
(define (skew-list->list sl)
(assume-type sl <skew-list>)
(reverse (skew-list-fold sl cons '())))
Comparison
(define-method object-equal? ((a <skew-list>) (b <skew-list>))
(equal? (skew-list-elements a)
(skew-list-elements b)))
Utilities
(define (skew-list-fold sl proc seed)
(define (tree-fold tree seed)
(match tree
[('Leaf x) (proc x seed)]
[('Node x t1 t2)
(tree-fold t2 (tree-fold t1 (proc x seed)))]))
(assume-type sl <skew-list>)
(fold (^[p s] (tree-fold (cdr p) s)) seed (skew-list-elements sl)))
sequence framework . One arg map is worth to support , for we can take
(define (skew-list-map sl f)
(define (tmap tree)
(match tree
[('Leaf x) `(Leaf ,(f x))]
[('Node x t0 t1) `(Node ,(f x) ,(tmap t0) ,(tmap t1))]))
(SL (map (^p `(,(car p) . ,(tmap (cdr p)))) (skew-list-elements sl))))
(define (skew-list-length sl)
(assume-type sl <skew-list>)
(fold (^[p s] (+ (car p) s)) 0 (skew-list-elements sl)))
(define (skew-list-length<=? sl k)
(assume-type sl <skew-list>)
(let loop ([es (skew-list-elements sl)] [s 0])
(cond [(< k s) #f]
[(null? es) #t]
[else (loop (cdr es) (+ s (caar es)))])))
(define (tree-kth-and-after t n k tail)
(if (zero? k)
(cons t tail)
(match-let1 ('Node _ t1 t2) t
(let1 m (/2 n)
(if (<= k m)
(tree-kth-and-after t1 m (- k 1) (cons t2 tail))
(tree-kth-and-after t2 m (- k m 1) tail))))))
in seq that does n't contain K - th element . Returns offset as well .
(define (skip-seq seq k)
(if (< k (caar seq))
(values seq k)
(skip-seq (cdr seq) (- k (caar seq)))))
(define (%skew-list-iterator sl start end_)
(define seq (skew-list-elements sl))
(define end (or end_ (skew-list-length sl)))
(define pos start)
(define (next)
(if (= pos end)
(values #f #t)
(match stack
[() (set! stack (list (cdr (pop! seq)))) (next)]
[(('Leaf x) . xs) (set! stack xs) (inc! pos)(values x #f)]
[(('Node x t1 t2) . xs) (set! stack (list* t1 t2 xs)) (inc! pos) (values x #f)])))
(unless (<= start end) (errorf "start ~s is greater than end ~s" start end))
(when (< 0 start)
(receive (seq_ k) (skip-seq seq start)
(set! stack (tree-kth-and-after (cdar seq_) (caar seq_) k '()))
(set! seq (cdr seq_))))
next)
(define (skew-list->generator sl :optional start end)
(define iter (%skew-list-iterator sl
(if (undefined? start) 0 start)
(if (undefined? end) #f end)))
(^[] (receive (x eof?) (iter)
(if eof? (eof-object) x))))
(define (skew-list->lseq sl :optional start end)
(define iter (%skew-list-iterator sl
(if (undefined? start) 0 start)
(if (undefined? end) #f end)))
((rec (loop)
(receive (x eof?) (iter)
(if eof?
'()
(lcons x (loop)))))))
take / drop first k elements
seq , there are some nontrivial cases . Suppose 1 < n and n = 2m+1 .
[ 1 n ... ] - > We can take 2 and 2+m if m>1
( e.g. from [ 1 7 .. ] we can take [ 1 1 ] and [ 1 1 3 ]
[ n ... ] - > We can take 1 , 2 , 1+m , 2+m ' ( where m = 2m'+1 )
( e.g. from [ 15 ... ] we can take [ 1 7 ] , [ 1 1 3 ]
(define (%skew-list-splitter sl k rettype)
(define-syntax ret
(syntax-rules ()
[(_ taken dropped)
(case rettype
[(take) (SL taken)]
[(drop) (SL dropped)]
[(split) (cons (SL taken) (SL dropped))])]))
(define elts (skew-list-elements sl))
(define (trivial-prefix)
(let loop ([seq elts] [sum 0] [i 0])
(cond [(= k sum) (ret (take elts i) (drop elts i))]
[(> k sum) (loop (cdr seq) (+ sum (caar seq)) (+ i 1))]
[else #f])))
(define (special-prefix)
(match (skew-list-elements sl)
[((1 . x) (n . ('Node y t1 t2)) . zs)
(if (= k 2)
(ret `((1 . ,x) (1 . (Leaf ,y)))
`((,(/2 n) . ,t1) (,(/2 n) . ,t2) ,@zs))
(and (> n 3)
(= k (+ 2 (/2 n)))
(ret `((1 . ,x) (1 . (Leaf ,y)) (,(/2 n) . ,t1))
`((,(/2 n) . ,t2) ,@zs))))]
[((n . ('Node x (and ('Node y t11 t12) t1) t2)) . zs)
(cond [(= k 1) (ret `((1 . (Leaf ,x)))
`((,(/2 n) . ,t1) (,(/2 n) . ,t2) ,@zs))]
[(= k 2) (ret `((1 . (Leaf ,x)) (1 . (Leaf ,y)))
`((,(/4 n) . ,t11) (,(/4 n) . ,t12) (,(/2 n) . ,t2) ,@zs))]
[(= k (+ 1 (/2 n)))
(ret `((1 . (Leaf ,x)) (,(/2 n) . ,t1))
`((,(/2 n) . ,t2) ,@zs))]
[(and (> k 3) (= k (+ 2 (/4 n))) )
(ret `((1 . (Leaf ,x)) (1 . (Leaf ,y)) (,(/4 n) . ,t11))
`((,(/4 n) . ,t12) (,(/2 n) . ,t2) ,@zs))]
[else #f])]
[((n . ('Node x ('Leaf y) t2)) . zs)
(cond [(= k 1) (ret `((1 . (Leaf ,x)))
`((1 . (Leaf ,y)) (,(/2 n) . ,t2) ,@zs))]
[(= k 2) (ret `((1 . (Leaf ,x)) (1 . (Leaf ,y)))
`((,(/2 n) . ,t2) ,@zs))]
[else #f])]))
(define (fallback)
(case rettype
[(take) (list->skew-list (skew-list->lseq sl 0 k))]
[(drop) (list->skew-list (skew-list->lseq sl k))]
[(split) (let1 lis (skew-list->list sl)
(receive (t d) (split-at lis k)
(cons (list->skew-list t) (list->skew-list d))))]))
(or (trivial-prefix)
(special-prefix)
(fallback)))
(define (skew-list-take sl k) (%skew-list-splitter sl k 'take))
(define (skew-list-drop sl k) (%skew-list-splitter sl k 'drop))
(define (skew-list-split-at sl k)
(let1 r (%skew-list-splitter sl k 'split)
(values (car r) (cdr r))))
(define (skew-list-append sl . sls)
(cond [(null? sls) sl]
[(skew-list-empty? sl) (apply skew-list-append sls)]
[(not (skew-list? sl)) (error "argument must be a skew list:" sl)]
[else (%skew-list-append2 sl (apply skew-list-append sls))]))
(define (%skew-list-append2 sl1 sl2)
(define (slow-append sl1 sl2)
(list->skew-list (append (skew-list->list sl1) (skew-list->list sl2))))
(match (skew-list-elements sl1)
[((1 . ('Leaf x))) (skew-list-cons x sl2)]
[((w0 . t0))
(match-let1 ((w1 . t1) . ts) (skew-list-elements sl2)
(if (= w0 w1)
(SL (cons (car (skew-list-elements sl1)) (skew-list-elements sl2)))
(slow-append sl1 sl2)))]
[_
(match-let1 (wz . tz) (last (skew-list-elements sl1))
(match-let1 ((w1 . t1) . ts) (skew-list-elements sl2)
(if (< wz w1)
(SL (append (skew-list-elements sl1) (skew-list-elements sl2)))
(slow-append sl1 sl2))))]))
(define-method call-with-iterator ((sl <skew-list>) proc)
(define iter (%skew-list-iterator sl 0 #f))
(define-values (item end) (iter))
(define (end?) end)
(define (next) (begin0 item
(set!-values (item end) (iter))))
(proc end? next))
(define-method call-with-builder ((slc <skew-list-meta>) proc :allow-other-keys)
(let1 q (make-queue)
(proc (cut enqueue! q <>)
(cut list->skew-list (dequeue-all! q)))))
(define-method fold (proc knil (sl <skew-list>))
(skew-list-fold sl proc knil))
(define-method size-of ((sl <skew-list>)) (skew-list-length sl))
(define-method referencer ((sl <skew-list>))
(^[o i] (skew-list-ref o i)))
|
54d6598512b0d12ca89e2d3395df84ad25251a4dcdefcd259c5b349cb5f0c197 | gfour/gic | LAR.hs | -- | Implementation with lazy activation records (LARs), C back-end.
--
-- The main module that compiles the LAR language to C code.
--
-- Memory allocation:
--
( 1 ) The stack is used for C function calls ( trivially ) and calls that
-- escape analysis shows they can allocate their LAR on the stack.
--
( 2 ) A second memory area is allocated in the heap for the rest of the
-- activation records.
--
module SLIC.LAR.LAR (compileModL, createSemiGCARInfra,
declarationsBuiltins, epilogue,
genInitMod, headersC, macrosC, mainFunc, makeC,
prologue) where
import Data.List (nub)
import Data.Map (elems, filter, lookup, keys, toList, union)
import Data.Set (empty, member, toList)
import SLIC.AuxFun (foldDot, ierr, insCommIfMore, pathOf)
import SLIC.Constants
import SLIC.DFI (DFC(dfcN), DFI(dfiDfInfo), DfInfo(diDfcs, diEApps),
ExtAppFuns, dfiFile)
import SLIC.Front.CAF
import SLIC.Front.Defunc (genNApp)
import SLIC.LAR.LARAux
import SLIC.LAR.LARBuiltins
import SLIC.LAR.LARDebug
import SLIC.LAR.LARGraph
import SLIC.LAR.SMacrosAux (MutInfo, declF, nameGCAF, namegenv, protoFunc,
mkAllocAR, mkDefineVar, mkGETSTRICTARG, mkLARMacro, mkLARMacroOpt,
mkMainCall, mkMutAR, mkNESTED, mkPUSHAR, mkRETVAL, mkVALS, nameMutAR,smFun)
import SLIC.LAR.SyntaxLAR
import SLIC.State
import SLIC.SyntaxAux
import SLIC.SyntaxFL
import SLIC.Tags
import SLIC.Types
-- | Compiles a program to C, given the variable types and the compilation flags.
-- The constructor enumeration is also used for the pretty printer.
-- A LAR module is given, to configure aspects of the runtime.
makeC :: ProgL -> TEnv -> ConfigLAR -> (DFI, ImportedNames, CIDs) -> ShowS
makeC (Prog dTypes defs) env config (dfi, imports, extCIDs) =
let strictVars = getStricts config
cbns = getCBNVars config
arities = getArities config
pmDepths = getPMDepths config
cids = getCIDs config
importFuns = keys imports
opts = getOptions config
larStyle = optLARStyle opts
gc = gcFor larStyle
modName = getModName config
cMode = optCMode opts
arityCAF = length (getCAFnmsids config)
defs' = case cMode of
Whole -> defs
CompileModule ->
-- remove external constructors and functions (this includes closure
-- constructors and defunctionalization functions, they should be
stored separately in the DFI )
Prelude.filter (blockIsLocal modName) defs
in headersC larStyle.
macrosC opts modName arities pmDepths arityCAF.
prologue opts modName arityCAF.
predeclarations defs' config.
(if optTCO opts then
genMutARs larStyle arities pmDepths defs'
else id).
pdeclGCAF config arityCAF.nl.
declarations dTypes defs'.
argDefs larStyle defs env strictVars cbns.nl.
declarationsBuiltins opts.nl.
(case cMode of
Whole -> id
CompileModule ->
(case gc of
SemiGC -> id
LibGC ->
pdeclExts opts imports.
pdeclExtApps opts (diEApps $ dfiDfInfo dfi)).
defInterface larStyle (dfiDfInfo dfi) importFuns extCIDs.nl).
initMod modName config.nl. -- module initializer
(case cMode of
Whole ->
debugPrintSymbol (optDebug opts) (map getBlockName defs).
mainFunc env opts (depthOfMainDef defs) [modName].nl
CompileModule -> id).
mainProg defs' env config.
(case cMode of
Whole -> prettyPrintersC larStyle.epilogue opts
CompileModule -> id).
prettyPrintersFor dTypes cids.nl
-- | Tests if a block is local. Non-local functions are those from another module
-- (so far only the closure dispatchers of defunctionalization satisfy this
-- condition).
blockIsLocal :: MName -> BlockL -> Bool
blockIsLocal m (DefL f@(QN (Just m') _) _ _) =
if m==m' then True -- local function
else if m' == dfMod then False -- defunctionalization function
else ierr $ "Found non-local function "++(qName f)
blockIsLocal _ (ActualL {}) = True
blockIsLocal _ _ = ierr "blockIsLocal: found unqualified block definition"
-- | The C headers of the generated code.
headersC :: LARStyle -> ShowS
headersC larStyle =
let gc = ("#include \"c/gc.h\""++).nl
in (case larStyle of
LAROPT ->
("#include \"c/lar_opt.h\""++).nl.
("#include \"gc.h\""++).nl
LAR64 -> ("#include \"c/lar_compact.h\""++).nl.gc
LAR -> ("#include \"c/lar.h\""++).nl.gc).nl.
("#include <c/gic_builtins.h>"++).nl.
wrapIfGMP (("#include <gmp.h>"++).nl) id.nl
-- | The C macros of the generated code.
macrosC :: Options -> MName -> Arities -> PMDepths -> Int -> ShowS
macrosC opts modName arities pmDepths arityCAF =
let larStyle = optLARStyle opts
gc = gcFor larStyle
dbg = optDebug opts
in ("// Macros"++).nl.nl.
(if optTag opts then
("#ifndef USE_TAGS"++).nl.
("#error you must enable the USE_TAGS macro for tags to work"++).nl.
("#endif /* USE_TAGS */"++).nl
else id).
(case gc of
SemiGC ->
-- The memory allocator used by the semi-space collector.
("#define GC_MALLOC MM_alloc"++).nl.
-- Use an explicit stack for function calls.
wrapIfGC
(("// pointer stack maximum size"++).nl.
("#define SSTACK_MAX_SIZE "++).shows (optEStackSz opts).nl.
mkPUSHAR dbg.
mkRETVAL dbg)
-- No pointer stack, dummy macros (use for testing the allocator).
(("#define PUSHAR(a) (a)"++).nl.
("#define RETVAL(x) (x)"++).nl)
LibGC -> id).nl.
defineGCAF modName gc arityCAF.nl.
(case gc of
LibGC -> createLibGCARInfra opts modName pmDepths.nl
SemiGC ->
createSemiGCARInfra modName larStyle arities pmDepths arityCAF.nl).nl
-- | Create the necessary macros for handling the optimized LARs. To be used
by the libgc garbage collector .
createLibGCARInfra :: Options -> MName -> PMDepths -> ShowS
createLibGCARInfra opts m pmds =
add libgc handlers for the GMP library
wrapIfGMP
(("void *GMP_GC_malloc(size_t sz) { return GC_malloc(sz); }"++).nl.
("void *GMP_GC_realloc(void *p, size_t old, size_t new) { return GC_realloc(p, new); }"++).nl.
("void GMP_GC_free(void *p, size_t sz) { GC_free(p); }"++).nl) id.
mkMainAR opts m pmds.nl
mkMainAR :: Options -> MName -> PMDepths -> ShowS
mkMainAR opts m pmds =
let mainDef = mainDefQName m
in case Data.Map.lookup mainDef pmds of
Just mainDepth ->
mkLARMacroOpt opts (qName mainDef) 0 0 mainDepth
_ -> id
-- | Create all possible activation record shapes (to be allocated in the heap).
-- Not to be used with the optimized LARs (that omit the size fields).
createSemiGCARInfra :: MName -> LARStyle -> Arities -> PMDepths -> Int -> ShowS
createSemiGCARInfra m larStyle fArities pmDepths arityCAF =
let arities = nub $ elems fArities
nestings = nub $ elems pmDepths
maxArity = maximum (arityCAF:arities)
minNesting =
case Data.Map.lookup (mainDefQName m) pmDepths of
Just mainN -> mainN -- default nesting of main
Nothing -> 0 -- default max for [] is 0
maxNestings = maximum (minNesting:nestings)
hAR_COPY 0 = ("#define AR_COPY_0(lar, n) do { } while(0)"++).nl
hAR_COPY a =
("#define AR_COPY_"++).shows a.("(lar, n, a0, ...) do { \\"++).nl.
tab.tab.("ARGS(n, lar) = ARGC(a0); \\"++).nl.
tab.tab.("AR_COPY_"++).shows (a-1).("(lar, n+1, ## __VA_ARGS__); \\"++).nl.
tab.("} while(0)"++).nl
AR_CLEAR , simple representation
hAR_CLEAR 0 = ("#define AR_CLEAR_0(lar, n) do { } while(0)"++).nl
hAR_CLEAR d =
("#define AR_CLEAR_"++).shows d.("(lar, n) do { \\"++).nl.
(case gcFor larStyle of
SemiGC -> tab.tab.("NESTED(n, lar) = NULL; \\"++).nl
LibGC -> id).
tab.tab.("AR_CLEAR_"++).shows (d-1).("(lar, n+1); \\"++).nl.
tab.tab.("} while(0)"++).nl
AR_CLEAR , compact representation
hAR_CLEARc 0 = ("#define AR_CLEAR_0(lar, ar, n) do { } while(0)"++).nl
hAR_CLEARc d =
("#define AR_CLEAR_"++).shows d.("(lar, ar, n) do { \\"++).nl.
(case gcFor larStyle of
SemiGC -> tab.tab.("NESTED(n, ar, lar) = NULL; \\"++).nl
LibGC -> id).
tab.tab.("AR_CLEAR_"++).shows (d-1).("(lar, ar, n+1); \\"++).nl.
tab.tab.("} while(0)"++).nl
in if maxArity > maxLARArity then
error $ "Maximum function/LAR arity exceeded: "++(show maxArity)++", maximum is "++(show maxLARArity)
else if maxNestings > maxNestedLARs then
error $ "Maximum function/LAR nesting exceeded: "++(show maxNestings)++", maximum is "++(show maxNestedLARs)
else
(foldDot hAR_COPY [0..maxArity]).nl.
(if larStyle==LAR64 then
foldDot hAR_CLEARc [0..maxNestings]
else
foldDot hAR_CLEAR [0..maxNestings]).nl
-- | Generates the "extern" declarations that link to the defunctionalization
-- interface and to functions in other modules. The CIDs table given is used
-- to generate declarations for bound variables from other modules.
defInterface :: LARStyle -> DfInfo -> [QName] -> CIDs -> ShowS
defInterface larStyle dfInfo importFuns extCIDs =
let externF v = ("extern "++).protoFunc v
-- generate the constructor variables accessing macros
macrosConstr (c, (_, ar)) =
let bvs = cArgsC c ar
stricts = empty -- TODO: stricts information for imported constructors
cbns = [] -- bound variables are never call-by-name
in foldDot (protoF larStyle stricts cbns c) (enumNames bvs)
extConstrs = map dfcN $ Data.Set.toList $ diDfcs dfInfo
in foldDot externF extConstrs.
foldDot externF (map genNApp $ Data.Set.toList $ diEApps dfInfo).
foldDot externF importFuns.
foldDot macrosConstr (Data.Map.toList extCIDs)
-- | Generates specialized macros for LARs used by the functions defined
-- in the current module.
predeclarations :: [BlockL] -> ConfigLAR -> ShowS
predeclarations lblockList config =
let opts = getOptions config
predeclF (DefL fname _ bind) =
let arityA = length bind
arityV = arityA
nesting = findPMDepthSafe fname (getPMDepths config)
in smFun opts fname arityA arityV nesting
predeclF (ActualL {}) = ierr "predeclF: found actual"
lblockListF = Prelude.filter isFun lblockList
in foldDot predeclF lblockListF.nl
-- | Generates specialized macros for LARs used by the imported functions.
pdeclExts :: Options -> ImportedNames -> ShowS
pdeclExts opts imports =
extConstrs = opts dfcs
-- extApps = mkApplyFuns opts dfcs
predeclE nst ( DefF vname _ ) =
let fArity = length frml
in smFun ( qName vname ) fArity fArity
predeclEC = predeclE 0
predeclED = predeclE 1
imports' = Data.Map.filter (\iinfo->(impC iinfo)/=NDType) imports
predeclEF fname =
let (Just iinfo) = Data.Map.lookup fname imports
(Just nesting) = impD iinfo
Just fArity = impA iinfo
in smFun opts fname fArity fArity nesting
pdecls = foldDot predeclEF (Data.Map.keys imports').nl
in case gcFor $ optLARStyle opts of
SemiGC -> ierr "pdeclExts: not to be used with semiGC"
LibGC -> pdecls
-- | Generates specialized macros for LARs used by dispatchers
-- for (unknown) external constructors
pdeclExtApps :: Options -> ExtAppFuns -> ShowS
pdeclExtApps opts extApps =
let mkSmFun ar = smFun opts (genNApp ar) (1+ar) (1+ar) 1
in foldDot mkSmFun $ Data.Set.toList extApps
-- | Generates macros for the LAR mutators of the program tail calls.
genMutARs :: LARStyle -> Arities -> PMDepths -> [BlockL] -> ShowS
genMutARs larStyle localArities localPmdepths defs =
let arities = union localArities builtinArities
pmdepths = union localPmdepths builtinPmDepths
findCIsB (DefL _ e _) = findCIsE e
findCIsB (ActualL _ _ e) = findCIsE e
findCIsE (LARCall _ _ NoCI) = []
findCIsE (LARCall _ _ (Mut _ Nothing)) =
ierr "mutation index not set"
findCIsE (LARCall f qns (Mut mut (Just iidx))) =
case (Data.Map.lookup f arities, Data.Map.lookup f pmdepths) of
(Just a, Just n) -> [(f, (mut, iidx), qns, (a, n))]
_ -> ierr $ "findCIsE: Missing information for "++(qName f)
findCIsE (LARC _ el) = concatMap findCIsE el
findCIsE (ConstrL{}) = []
findCIsE (BVL{}) = []
findCIsE (CaseL _ _ pats) = concatMap findCIsP pats
findCIsP (PatB _ e) = findCIsE e
allMutInfo :: [MutInfo]
allMutInfo = concatMap findCIsB defs
in foldDot (mkMutAR larStyle) allMutInfo
| Generates specialized macros for a module 's global CAF .
pdeclGCAF :: ConfigLAR -> Int -> ShowS
pdeclGCAF config arityCAF =
let m = getModName config
opts = getOptions config
in case (gcFor $ optLARStyle $ getOptions config) of
SemiGC -> id
LibGC -> mkLARMacro opts ("GCAF_"++m) arityCAF arityCAF 0
-- | Generates the C declarations of the LAR blocks and the forcing
-- functions for the module data types.
declarations :: [Data] -> [BlockL] -> ShowS
declarations dts ds =
let proto (DefL n _ _) = protoFunc n
proto (ActualL n _ _) = protoVar (qName n)
idDefs = foldDot proto ds
protoDT d = pprinterSig d.(";"++).nl
forcingFuncs = foldDot (\(Data d _ _)->protoDT d) dts.
foldDot protoDT builtinDTypes
in idDefs.forcingFuncs
-- | The prototype of a formal variable.
protoVar :: String -> ShowS
protoVar v = ("VAR("++).(v++).(");"++).nl
-- | Generates the C declarations of the native functions of the run-time.
declarationsBuiltins :: Options -> ShowS
declarationsBuiltins opts =
foldDot (declF opts) bfsLARInfo.nl.
builtinConstrsDecls opts.nl
-- builtinTCs opts.nl
-- | Generates the C code for each LAR block.
mainProg :: [BlockL] -> TEnv -> ConfigLAR -> ShowS
mainProg ds env config = foldDot (\x -> (mkCBlock x env config).nl) ds
-- | Generates auxiliary functions that go in the end of
-- the generated C file (pretty printers, forcing
-- functions, built-in functions, memory management code).
epilogue :: Options -> ShowS
epilogue opts = builtins opts.nl
-- | Generates C code for a block.
mkCBlock :: BlockL -> TEnv -> ConfigLAR -> ShowS
mkCBlock (DefL f e bind) env config =
let fArity = length bind
opts = getOptions config
larStyle = optLARStyle opts
gc = gcFor larStyle
in ("FUNC("++).pprint f.("){"++).nl.
(case gc of
LibGC | fArity > 0 ->
("INIT_ARG_LOCKS("++).shows fArity.(");"++).nl
_ -> id).
debugFuncPrologue (optDebug opts) f.
(case Data.Map.lookup f (getStricts config) of
Nothing -> id
Just strictFrms -> forceStricts larStyle strictFrms fArity).
logPrev opts.
mkCFuncBody config env f e.
("}"++).nl
mkCBlock (ActualL v act e) env config =
let opts = getOptions config
in ("VAR("++).pprint v.("){"++).nl.
debugVarPrologue (optDebug opts) v.
mkAct act opts.
("return "++).(mkCExp env config e).semi.nl.
("}"++).nl
-- | Generate C code for a function body.
mkCFuncBody :: ConfigLAR -> TEnv -> QName -> ExprL -> ShowS
mkCFuncBody config env f e =
let -- the number of nested pattern matching clauses
pmds = getPMDepths config
patD = case Data.Map.lookup f pmds of
Just d -> d
Nothing -> ierr $ "Function "++(qName f)++" has no depth in:\n"++(pprintPD pmds "")
patDS = shows patD
in -- keep the nested pointers in the heap if the function is data,
else keep it in the stack ( important for GC )
-- allocate space for patDepth * suspensions
(if patD > maxNestedLARs then
error $ "Too deep pattern matching detected: "++(show patD)++", maximum depth allowed is "++(show maxNestedLARs)
else id).
(if patD > 0 then tab.("Susp cl["++).patDS.("];"++).nl else id).
(mkCStmBody e env config)
-- | Forces the strict parameters of a function call. It only works for ground
-- values, otherwise will just force until the constructor head.
forceStricts :: LARStyle -> StrictInds -> Arity -> ShowS
forceStricts larStyle strictInds fArity =
let aux x =
mkVALS larStyle x fArity "T0".
(" = ((LarArg)CODE("++).shows x.(", T0))(T0); // strict "++).nl
in foldDot aux $ Data.Set.toList strictInds
-- | Generates the C code for an expression that is assumed to be the body
-- of a definition.
mkCStmBody :: ExprL -> TEnv -> ConfigLAR -> ShowS
mkCStmBody e@(CaseL {}) env config =
tab.("Susp Res;"++).nl.
-- evaluate the pattern matching clause expression
mkCExp env config e.nl.
("return Res;"++).nl
-- For thunk constructors, the constructor id is returned paired with the
-- current context (for nullary constructors the context is 0).
mkCStmBody (ConstrL (CC c cId cArity)) _ config =
let opts = getOptions config
in logConstr opts c.
mkSusp opts cId uTag (cArity>0).nl
mkCStmBody e env config = ("return "++).mkCExp env config e.semi.nl
-- | Generates C code for a LAR expression. Takes the name of the containing
-- function (for custom LAR access), the typing environment, the
-- configuration, and the LAR expression.
mkCExp :: TEnv -> ConfigLAR -> ExprL -> ShowS
mkCExp env config (LARC (CN c) exps) =
let opts = getOptions config
larStyle = optLARStyle opts
useFastOps = (larStyle==LAR64) && (optFastOp opts)
in case c of
CIf -> ("(PVAL_R("++).mkCExp env config (exps !! 0).(")?"++).
("("++).mkCExp env config (exps !! 1).("):"++).
("("++).mkCExp env config (exps !! 2).("))"++)
c' | c' `elem` [ CMinus, CPlus, CMult, CDivide, CEqu, CLe, CGe
, CGt, CLt, CAnd, COr, CMulI, CNEq, CMod, CDiv] ->
mkBinOp c' exps env config
CNeg ->
let nExp = mkCExp env config (exps !! 0)
in if useFastOps then
("PVAL_NEG("++).nExp.(")"++)
else
("PVAL_C(-(PVAL_R("++).nExp.("))"++).mIntTag config.(")"++)
CTrue -> intSusp larStyle "True"
CFalse -> intSusp larStyle "False"
_ -> error $ "mkCExp: unknown built-in constant "++(pprint c "")
mkCExp _ config (LARC (LitInt i) exps) =
case exps of
[] -> intSusp (optLARStyle $ getOptions config) (show i)
(_:_) -> ierr "Integer literal applied to expressions."
mkCExp _ config (LARCall n _ (Mut _ iidx)) | optTCO (getOptions config) =
case iidx of
Just i -> pprint n.("("++).nameMutAR n i.(")"++)
Nothing -> ierr "mkCExp: missing intensional index"
mkCExp env config (LARCall n acts _) =
if n `elem` (nmsids2nms (getCAFnmsids config)) then
let Just n' = (getCAFid n (getCAFnmsids config))
in ("("++).nameGCAF (getModName config).(("("++(show n')++"))")++)
else makeActs n acts env config
mkCExp env config (CaseL (cn, efunc) e pats) =
let matchedExpr = mkCExp env config e
cases = foldDot mkCPat pats
opts = getOptions config
sConstrID = case cn of
CLoc Nothing -> ierrCLoc
CLoc (Just (c, _)) -> ("CONSTR(cl["++).shows c.("])"++)
CFrm _ -> ("CONSTR("++).matchedExpr.(")"++)
defaultCase = tab.("default: printf(\"Pattern matching on "++).pprint e.
(" failed: constructor %d encountered.\\n\", "++).
sConstrID.("); exit(0);"++).nl
-- | Generates C code for a pattern. /case/ bodies are contained
-- in {...} as they may contain declarations.
mkCPat (PatB (CC c cId _, bindsVars) eP) =
tab.("case "++).shows cId.(": { /* "++).pprint c.(" */ "++).
mkPatBody eP bindsVars.
("; break; }"++).nl
mkPatBody ePB _ =
let opts = getOptions config
-- in -- if explicit deallocation is enabled and the constructor
-- -- does not bind any variables, ignore the nested context
-- -- TODO: remove
-- {-
( if ( stGC opts ) & & ( not bindsVars ) then
-- id
-- -- TODO: enable this and see if it makes any difference, or
-- -- make it accessible by some command line switch
-- -- ("NESTED("++).(shows d).(", T0) = 0; "++)
-- else id).
-- -}
(case ePB of
CaseL {} -> id
_ -> ("Res = "++)).
mkCExp env config ePB
larStyle = optLARStyle opts
argsN = getFuncArity efunc (getArities config)
ierrCLoc = ierr $ "mkCExp: non-enumerated case expression: "++(pprint e "")
in (case cn of
CLoc Nothing -> ierrCLoc
CLoc (Just (counter, _)) ->
let dS = shows counter
in tab.("cl["++).dS.("] = "++).matchedExpr.semi.nl.
-- TODO: eliminate this when all patterns are nullary constructors
-- (or are used as such, see 'bindsVars')
tab.mkNESTED larStyle efunc counter argsN.(" = CPTR(cl["++).dS.("]);"++).nl.
logDict opts counter ;
CFrm _ -> id).
-- if debug mode is off, optimize away constructor choice when there is
only one pattern ( will segfault / misbehave if the constructor
-- reached is missing)
(if null pats then
-- pattern matching without any patterns, does not get compiled
("/* Empty pattern matching */"++)
else if (length pats == 1) && (not (optDebug opts)) then
one pattern only ; skip the branching
let [PatB (_, bindsVars) patE] = pats
in -- If using a formal scrutinee, evaluate it now (since the
-- 'switch' that evaluates it will be skipped).
(case cn of
CFrm _ -> matchedExpr.(";"++).nl
CLoc _ -> id).
tab.mkPatBody patE bindsVars.semi
else
tab.("switch ("++).sConstrID.(") {"++).nl.
cases.
-- only add "default:" when debugging
(if optDebug opts then defaultCase else id).
tab.("}"++).nl)
mkCExp _ _ (ConstrL _) =
ierr "LAR: ConstrL can only occur as the first symbol of a definition"
mkCExp _ _ e@(BVL _ (CLoc Nothing, _)) =
ierr $ "mkCExp: found non-enumerated bound variable: "++(pprint e "")
mkCExp _ config bv@(BVL v (cloc, fname)) =
let larStyle = optLARStyle $ getOptions config
argsN = getFuncArity fname (getArities config)
gc = gcFor larStyle
in case cloc of
CLoc Nothing -> ierr $ "non-enumerated bound variable: "++(pprint bv "")
CLoc (Just (counter, _)) ->
mkCall gc v (mkNESTED larStyle fname counter argsN)
CFrm i ->
-- Read the nested context directly from a formal (no thunk flag check).
mkCall (gcFor larStyle) v (("FRM_NESTED("++).shows i.(")"++))
getFuncArity :: QName -> Arities -> Arity
getFuncArity f ars =
case Data.Map.lookup f ars of
Just n -> n
Nothing -> ierr $ "mkCExp: BV: no arity of enclosing function "++(lName f)
-- | Generates C code for a built-in binary operator.
-- All the supported operators are on integers.
mkBinOp :: COp -> [ExprL] -> TEnv -> ConfigLAR -> ShowS
mkBinOp c [e1, e2] env config =
let e1' = mkCExp env config e1
e2' = mkCExp env config e2
val1 = ("PVAL_R("++).e1'.(")"++)
val2 = ("PVAL_R("++).e2'.(")"++)
cBin cOp tagFunc =
("(PVAL_C("++).val1.(cOp++).val2.tagFunc config.("))"++)
opts = getOptions config
useFastOps = (optLARStyle opts==LAR64) && (optFastOp opts)
-- This is used by the fast arithmetic ops.
fastOp opN = (opN++).("(("++).e1'.("), ("++).e2'.("))"++)
in case c of
-- If using compact LARs, do faster integer arithmetic for some operators.
CPlus | useFastOps -> fastOp "PVAL_ADD"
CMinus | useFastOps -> fastOp "PVAL_SUB"
CMult | useFastOps -> fastOp "PVAL_MUL"
CDiv | useFastOps -> fastOp "PVAL_DIV"
CDivide| useFastOps -> fastOp "PVAL_DIV"
CMod | useFastOps -> fastOp "PVAL_MOD"
CAnd | useFastOps - > fastOp " PVAL_AND "
COr | useFastOps -> fastOp "PVAL_OR"
CEqu | useFastOps -> fastOp "PVAL_EQU"
CNEq | useFastOps -> fastOp "PVAL_NEQ"
CLt | useFastOps -> fastOp "PVAL_LT"
CGt | useFastOps -> fastOp "PVAL_GT"
CLe | useFastOps -> fastOp "PVAL_LE"
CGe | useFastOps -> fastOp "PVAL_GE"
C operators that are different from Haskell
CMulI -> lparen.(pprint CMulI).lparen.e1'.comma.e2'.rparen.rparen
CNEq -> cBin "!=" mBoolTag
CMod -> cBin "%" mIntTag
CDiv -> cBin "/" mIntTag
-- C operators that return Int values
iResOp | iResOp `elem` [ CMinus, CPlus, CMult, CDivide, CMod, CDiv] ->
cBin (pprint c "") mIntTag
C operators that return values
bResOp | bResOp `elem` [ CEqu, CLe, CGe, CGt, CLt, CAnd, COr, CNEq] ->
cBin (pprint c "") mBoolTag
_ -> ierr $ "mkBinOp: unhandled operator " ++ (pprint c "")
mkBinOp _ _ _ _ =
ierr "mkBinOp: called with wrong arguments"
-- | An integer value or equivalent (nullary constructor or ground value).
intSusp :: LARStyle -> String -> ShowS
intSusp LAR64 c = ("PVAL_C("++).(c++).(")"++)
intSusp _ c = ("(SUSP("++).(c++).(", "++).intTag.(", NULL))"++)
-- | Generates C macros for accessing function arguments in a LAR block.
-- Takes into consideration strictness/call-by-name information.
protoB :: LARStyle -> BlockL -> TEnv -> Stricts -> CBNVars -> ShowS
protoB larStyle (DefL fName _ bind) _ stricts cbnVars =
let Just cbns = Data.Map.lookup fName cbnVars
Just strs = Data.Map.lookup fName stricts
in foldDot (protoF larStyle strs cbns fName) (enumNames bind)
protoB _ (ActualL {}) _ _ _ = id
-- | Generates the access macros for the formal variables of a function.
protoF :: LARStyle -> StrictInds -> [QName] -> QName -> (Int, QName) -> ShowS
protoF larStyle strs cbns fName (n, x)
| n `member` strs =
("#define " ++).pprint x.("(T0) "++).mkGETSTRICTARG larStyle fName n.nl
| x `elem` cbns =
("#define " ++).pprint x.("(T0) GETCBNARG(" ++).(shows n).(", T0)"++).nl
| otherwise =
case gcFor larStyle of
SemiGC ->
("#define " ++).pprint x.("(T0) "++).
("GETARG("++).(shows n).(", T0)"++).nl
LibGC -> mkDefineVar larStyle x fName n
-- | The macro that accesses a CAF LAR.
defineGCAF :: MName -> GC -> Int -> ShowS
defineGCAF modName gc arityCAF =
case gc of
SemiGC ->
("#define "++).nameGCAF modName.("(x) GETARG(x, "++).namegenv modName.(")"++)
LibGC ->
("#define "++).nameGCAF modName.("(x) GETARG(x, "++).
shows arityCAF.(", "++).namegenv modName.(")"++)
| Creates the global LAR for CAFs .
genv :: MName -> Int -> ShowS
genv m arityCAF =
if arityCAF > 0 then
wrapIfGC
(("static TP_ *"++).namegenv m.(";"++).nl)
(("static TP_ "++).namegenv m.(";"++).nl)
else id
| Generates : ( a ) the CAF of a module , ( b ) the C declarations of the memory
management subsystem , ( c ) the Graphviz declarations .
prologue :: Options -> MName -> Int -> ShowS
prologue opts modName arityCAF =
let gc = gcFor $ optLARStyle opts
prototype for module CAF
(case gc of
SemiGC ->
(case optCMode opts of
Whole ->
("/* Memory management */"++).nl.
("#define DEFAULT_MAXMEM "++).shows (optMaxMem opts).nl.
("unsigned long MAXMEM = DEFAULT_MAXMEM;"++).nl.
("unsigned long MAXMEMSPACE = DEFAULT_MAXMEM / 2;"++).nl.
("// Function prototypes for the allocator"++).nl.
(if optLink opts then
("inline byte* MM_alloc(size_t bytes);"++)
else
("static inline byte* MM_alloc(size_t bytes);"++)).nl.
("byte *space, *space1, *space2, *spaceStart, *spaceEnd;"++).nl
CompileModule ->
("extern inline byte* MM_alloc(size_t bytes);"++).nl).
wrapIfGC
(("// Memory management: pointer stack pointers (base/current)"++).nl.
("static TP_ *sstack_bottom;"++).nl.
("static TP_ *sstack_ptr;"++).nl)
id
LibGC -> id).
(if (optVerbose opts) then
("// Graphviz output functionality"++).nl.
("int counter; FILE *p; /* file for graph output */"++).nl
else id)
-- | The main() of the generated C code. Takes a typing environment, the
-- user options, the pattern matching depth of the main function, and
-- the list of modules (to initialize at runtime).
mainFunc :: TEnv -> Options -> PMDepth -> [MName] -> ShowS
mainFunc env opts mainNesting modules =
let m = case modules of [m'] -> m' ; _ -> "Main"
mainDef = mainDefQName m
printResDT dt = tab.pprinterName dt.("(res); printf(\" \");"++).nl
dbg = optDebug opts
larStyle= optLARStyle opts
gc = gcFor larStyle
in ("int main(int argc, char* argv[]){\n"++).
tab.("clock_t t1, t2;"++).nl.
tab.("Susp res;"++).nl.
tab.("t1 = clock();\n"++).
(case gc of
SemiGC ->
tab.("/* allocate space in the heap */"++).nl.
tab.("if (argc > 1) {"++).nl.
tab.tab.("MAXMEM = strtoul(argv[1], NULL, 10);"++).nl.
tab.tab.("MAXMEMSPACE = MAXMEM / 2;"++).nl.
tab.tab.("printf(\"heap size = 2 x %lu bytes\\n\", MAXMEMSPACE);"++).nl.
tab.("}"++).nl.
tab.("space1 = (byte *) malloc((size_t)MAXMEMSPACE);"++).nl.
tab.("space2 = (byte *) malloc((size_t)MAXMEMSPACE);"++).nl.
tab.("if (space1==NULL || space2==NULL) {"++).nl.
tab.tab.("printf(\"Cannot allocate memory to start program, \""++).nl.
tab.tab.(" \"tried 2 x %lu bytes.\\n\", MAXMEMSPACE);"++).nl.
tab.tab.("exit(EXIT_FAILURE);"++).nl.
tab.("}"++).nl.
tab.("space = spaceStart = space1;"++).nl.
tab.("spaceEnd = space + MAXMEMSPACE;"++).nl.
Initialize the explicit pointer stack .
wrapIfGC
(("sstack_bottom = (TP_*)malloc(sizeof(TP_)*SSTACK_MAX_SIZE);"++).nl.
("if (sstack_bottom == 0) { printf(\"No space for pointer stack.\\n\"); exit(0); };"++).nl.
("sstack_ptr = sstack_bottom;"++).nl
) id
LibGC ->
tab.("GC_init();"++).nl.
wrapIfOMP (tab.("GC_thr_init();"++).nl) id.
wrapIfGMP (tab.("mp_set_memory_functions(GMP_GC_malloc, GMP_GC_realloc, GMP_GC_free);"++).nl) id
tab.("GC_enable_incremental();"++).nl -- incremental GC
).
tab.("// initial activation record"++).nl.
tab.("TP_ T0_ = NULL;"++).nl.
tab.("TP_ AR_TP(T0) = AR_REF(T0_);"++).nl.
(case gc of
LibGC -> id
SemiGC ->
tab.debugCreateTopLAR dbg.
tab.("TP_ AR_TP(t0) = PUSHAR(AR(0,"++).shows mainNesting.("));"++).nl).
initModules modules.
logGraphStart opts.
mkMainCall gc m.
tab.("t2 = clock();"++).nl.
(case (findType mainDef env) of
Tg (T dt) | dt==dtInteger ->
wrapIfGMP
(tab.("printf(\"Integer result=%s\\n\", mpz_get_str(0, 10, *((mpz_t*)(CPTR(res)))));"++).nl)
(tab.("printf(\"cannot compute 'result', gic must be built with libgmp support\\n\");"++).nl)
Tg (T dt) ->
if (dt==dtInt || dt==dtBool) then
if larStyle==LAR64 then
-- compact mode, special int representation
tab.("printf(\"%ld, \", PVAL_R(res));"++).nl
else
-- normal mode, ints are isomorphic to nullary constructors
tab.("if ((CPTR(res)) == 0) printf(\"%d, \", CONSTR(res));"++).nl.
tab.("else printf(\"Thunk{%d, %p}\", CONSTR(res), CPTR(res));"++).nl
else
printResDT dt
typ@(Tg (TDF _ _)) ->
error $ "Can not determine pretty printer for higher-order variable result of type "++(pprint typ "")
Tv _ -> ierr "result variable is polymorphic"
Ta (Tg (T dt)) _ -> printResDT dt
t ->
ierr $ "result variable has unsupported type: "++(pprint t "")
).
tab.("printf(\"c time = %.10f sec\\n\", ((double)(t2 - t1)/CLOCKS_PER_SEC));"++).nl.
debugMainFinish dbg.
logGraphEnd opts.
tab.("return 0;"++).nl.
("}"++).nl
-- | Generates the calls to the modules initializers.
initModules :: [MName] -> ShowS
initModules [] = id
initModules (m:ms) = tab.genInitMod m.("(T0);"++).nl.initModules ms
-- | The code for a module initializer. So far, it only initializes the module
LAR containing the top - level CAFs of the module .
initMod :: MName -> ConfigLAR -> ShowS
initMod m config =
let arityCAF = length (getCAFnmsids config)
opts = getOptions config
nms = map pprint $ nmsids2nms (getCAFnmsids config)
cafName = namegenv m
in ("void "++).genInitMod m.("(TP_ AR_TP(T0)) {"++).nl.
(if arityCAF > 0 then
debugCreateCAF (optDebug opts) cafName.
tab.cafName.(" = "++).
(case gcFor (optLARStyle opts) of
SemiGC ->
("PUSHAR(AR("++).shows arityCAF.
(", 0"++).((foldl (\x -> \y -> x ++ ", " ++ (y "")) "" nms)++).
("));"++).nl
LibGC ->
(nameGCAF m).("_AR("++).insCommIfMore nms.(");"++)).nl
else id).
("}"++).nl.nl
-- | Generates the name of a module initializer.
genInitMod :: MName -> ShowS
genInitMod m = ("__initModule_"++).(m++)
-- | Generates C macros for accessing the variables of each LAR block.
argDefs :: LARStyle -> [BlockL] -> TEnv -> Stricts -> CBNVars -> ShowS
argDefs larStyle ds env stricts cbnVars =
foldDot (\def -> (protoB larStyle def env stricts cbnVars)) ds
-- | Returns the LAR with the actuals of a function call.
makeActs :: QName -> [QName] -> TEnv -> ConfigLAR -> ShowS
makeActs f args env config =
let fNesting = findPMDepthSafe f (getPMDepths config)
isVar = case args of { [] | fNesting==0 -> True ; _ -> False }
allocHeap = optHeap (getOptions config) || (returnsThunk env f)
larStyle = optLARStyle (getOptions config)
-- nullary functions don't create a new LAR but use the current one (T0)
-- unless they have nesting > 0
fLAR =
if isVar then ("AR_TP(T0)"++)
else
let fArity = length args
in mkAllocAR larStyle allocHeap f fArity fNesting (map pprint args)
simpleCall = pprint f.("("++).fLAR.(")"++)
in case larStyle of
LAROPT -> simpleCall
_ -> ("RETVAL("++).pprint f.("(PUSHAR("++).fLAR.(")))"++)
-- | Finds the pattern-matching depth of the 'result' definition.
depthOfMainDef :: [BlockL] -> Int
depthOfMainDef blocks =
let findRes (DefL v _ _) = (lName v)==mainDefName
findRes (ActualL {}) = False
res = Prelude.filter findRes blocks
in case res of
[DefL _ e _] -> countPMDepthL e
_ -> ierr "No (unique) result definition was found."
| Main entry point for separate module compilation from " SLIC.Driver " .
-- Takes the full module name, the compilation configuration, the typing
-- environment of the module, the DFI of the module, the compilation
-- information for imported names, the compile constructor information,
-- and the actual LAR intermediate code to compile to C.
compileModL :: MNameF -> ConfigLAR -> TEnv -> DFI -> ImportedNames ->
CIDs -> ProgL -> IO ()
compileModL fm config env dfi allImps cidsExt finalProgLAR =
let (moduleName, f) = fm
fPath = pathOf f
moduleC = fPath++[dirSeparator]++moduleName++".c"
moduleDFI = fPath++[dirSeparator]++(dfiFile moduleName)
in writeFile moduleC (makeC
finalProgLAR env config (dfi, allImps, cidsExt) "") >>
writeFile moduleDFI (show dfi)
| null | https://raw.githubusercontent.com/gfour/gic/d5f2e506b31a1a28e02ca54af9610b3d8d618e9a/SLIC/LAR/LAR.hs | haskell | | Implementation with lazy activation records (LARs), C back-end.
The main module that compiles the LAR language to C code.
Memory allocation:
escape analysis shows they can allocate their LAR on the stack.
activation records.
| Compiles a program to C, given the variable types and the compilation flags.
The constructor enumeration is also used for the pretty printer.
A LAR module is given, to configure aspects of the runtime.
remove external constructors and functions (this includes closure
constructors and defunctionalization functions, they should be
module initializer
| Tests if a block is local. Non-local functions are those from another module
(so far only the closure dispatchers of defunctionalization satisfy this
condition).
local function
defunctionalization function
| The C headers of the generated code.
| The C macros of the generated code.
The memory allocator used by the semi-space collector.
Use an explicit stack for function calls.
No pointer stack, dummy macros (use for testing the allocator).
| Create the necessary macros for handling the optimized LARs. To be used
| Create all possible activation record shapes (to be allocated in the heap).
Not to be used with the optimized LARs (that omit the size fields).
default nesting of main
default max for [] is 0
| Generates the "extern" declarations that link to the defunctionalization
interface and to functions in other modules. The CIDs table given is used
to generate declarations for bound variables from other modules.
generate the constructor variables accessing macros
TODO: stricts information for imported constructors
bound variables are never call-by-name
| Generates specialized macros for LARs used by the functions defined
in the current module.
| Generates specialized macros for LARs used by the imported functions.
extApps = mkApplyFuns opts dfcs
| Generates specialized macros for LARs used by dispatchers
for (unknown) external constructors
| Generates macros for the LAR mutators of the program tail calls.
| Generates the C declarations of the LAR blocks and the forcing
functions for the module data types.
| The prototype of a formal variable.
| Generates the C declarations of the native functions of the run-time.
builtinTCs opts.nl
| Generates the C code for each LAR block.
| Generates auxiliary functions that go in the end of
the generated C file (pretty printers, forcing
functions, built-in functions, memory management code).
| Generates C code for a block.
| Generate C code for a function body.
the number of nested pattern matching clauses
keep the nested pointers in the heap if the function is data,
allocate space for patDepth * suspensions
| Forces the strict parameters of a function call. It only works for ground
values, otherwise will just force until the constructor head.
| Generates the C code for an expression that is assumed to be the body
of a definition.
evaluate the pattern matching clause expression
For thunk constructors, the constructor id is returned paired with the
current context (for nullary constructors the context is 0).
| Generates C code for a LAR expression. Takes the name of the containing
function (for custom LAR access), the typing environment, the
configuration, and the LAR expression.
| Generates C code for a pattern. /case/ bodies are contained
in {...} as they may contain declarations.
in -- if explicit deallocation is enabled and the constructor
-- does not bind any variables, ignore the nested context
-- TODO: remove
{-
id
-- TODO: enable this and see if it makes any difference, or
-- make it accessible by some command line switch
-- ("NESTED("++).(shows d).(", T0) = 0; "++)
else id).
-}
TODO: eliminate this when all patterns are nullary constructors
(or are used as such, see 'bindsVars')
if debug mode is off, optimize away constructor choice when there is
reached is missing)
pattern matching without any patterns, does not get compiled
If using a formal scrutinee, evaluate it now (since the
'switch' that evaluates it will be skipped).
only add "default:" when debugging
Read the nested context directly from a formal (no thunk flag check).
| Generates C code for a built-in binary operator.
All the supported operators are on integers.
This is used by the fast arithmetic ops.
If using compact LARs, do faster integer arithmetic for some operators.
C operators that return Int values
| An integer value or equivalent (nullary constructor or ground value).
| Generates C macros for accessing function arguments in a LAR block.
Takes into consideration strictness/call-by-name information.
| Generates the access macros for the formal variables of a function.
| The macro that accesses a CAF LAR.
| The main() of the generated C code. Takes a typing environment, the
user options, the pattern matching depth of the main function, and
the list of modules (to initialize at runtime).
incremental GC
compact mode, special int representation
normal mode, ints are isomorphic to nullary constructors
| Generates the calls to the modules initializers.
| The code for a module initializer. So far, it only initializes the module
| Generates the name of a module initializer.
| Generates C macros for accessing the variables of each LAR block.
| Returns the LAR with the actuals of a function call.
nullary functions don't create a new LAR but use the current one (T0)
unless they have nesting > 0
| Finds the pattern-matching depth of the 'result' definition.
Takes the full module name, the compilation configuration, the typing
environment of the module, the DFI of the module, the compilation
information for imported names, the compile constructor information,
and the actual LAR intermediate code to compile to C. | ( 1 ) The stack is used for C function calls ( trivially ) and calls that
( 2 ) A second memory area is allocated in the heap for the rest of the
module SLIC.LAR.LAR (compileModL, createSemiGCARInfra,
declarationsBuiltins, epilogue,
genInitMod, headersC, macrosC, mainFunc, makeC,
prologue) where
import Data.List (nub)
import Data.Map (elems, filter, lookup, keys, toList, union)
import Data.Set (empty, member, toList)
import SLIC.AuxFun (foldDot, ierr, insCommIfMore, pathOf)
import SLIC.Constants
import SLIC.DFI (DFC(dfcN), DFI(dfiDfInfo), DfInfo(diDfcs, diEApps),
ExtAppFuns, dfiFile)
import SLIC.Front.CAF
import SLIC.Front.Defunc (genNApp)
import SLIC.LAR.LARAux
import SLIC.LAR.LARBuiltins
import SLIC.LAR.LARDebug
import SLIC.LAR.LARGraph
import SLIC.LAR.SMacrosAux (MutInfo, declF, nameGCAF, namegenv, protoFunc,
mkAllocAR, mkDefineVar, mkGETSTRICTARG, mkLARMacro, mkLARMacroOpt,
mkMainCall, mkMutAR, mkNESTED, mkPUSHAR, mkRETVAL, mkVALS, nameMutAR,smFun)
import SLIC.LAR.SyntaxLAR
import SLIC.State
import SLIC.SyntaxAux
import SLIC.SyntaxFL
import SLIC.Tags
import SLIC.Types
makeC :: ProgL -> TEnv -> ConfigLAR -> (DFI, ImportedNames, CIDs) -> ShowS
makeC (Prog dTypes defs) env config (dfi, imports, extCIDs) =
let strictVars = getStricts config
cbns = getCBNVars config
arities = getArities config
pmDepths = getPMDepths config
cids = getCIDs config
importFuns = keys imports
opts = getOptions config
larStyle = optLARStyle opts
gc = gcFor larStyle
modName = getModName config
cMode = optCMode opts
arityCAF = length (getCAFnmsids config)
defs' = case cMode of
Whole -> defs
CompileModule ->
stored separately in the DFI )
Prelude.filter (blockIsLocal modName) defs
in headersC larStyle.
macrosC opts modName arities pmDepths arityCAF.
prologue opts modName arityCAF.
predeclarations defs' config.
(if optTCO opts then
genMutARs larStyle arities pmDepths defs'
else id).
pdeclGCAF config arityCAF.nl.
declarations dTypes defs'.
argDefs larStyle defs env strictVars cbns.nl.
declarationsBuiltins opts.nl.
(case cMode of
Whole -> id
CompileModule ->
(case gc of
SemiGC -> id
LibGC ->
pdeclExts opts imports.
pdeclExtApps opts (diEApps $ dfiDfInfo dfi)).
defInterface larStyle (dfiDfInfo dfi) importFuns extCIDs.nl).
(case cMode of
Whole ->
debugPrintSymbol (optDebug opts) (map getBlockName defs).
mainFunc env opts (depthOfMainDef defs) [modName].nl
CompileModule -> id).
mainProg defs' env config.
(case cMode of
Whole -> prettyPrintersC larStyle.epilogue opts
CompileModule -> id).
prettyPrintersFor dTypes cids.nl
blockIsLocal :: MName -> BlockL -> Bool
blockIsLocal m (DefL f@(QN (Just m') _) _ _) =
else ierr $ "Found non-local function "++(qName f)
blockIsLocal _ (ActualL {}) = True
blockIsLocal _ _ = ierr "blockIsLocal: found unqualified block definition"
headersC :: LARStyle -> ShowS
headersC larStyle =
let gc = ("#include \"c/gc.h\""++).nl
in (case larStyle of
LAROPT ->
("#include \"c/lar_opt.h\""++).nl.
("#include \"gc.h\""++).nl
LAR64 -> ("#include \"c/lar_compact.h\""++).nl.gc
LAR -> ("#include \"c/lar.h\""++).nl.gc).nl.
("#include <c/gic_builtins.h>"++).nl.
wrapIfGMP (("#include <gmp.h>"++).nl) id.nl
macrosC :: Options -> MName -> Arities -> PMDepths -> Int -> ShowS
macrosC opts modName arities pmDepths arityCAF =
let larStyle = optLARStyle opts
gc = gcFor larStyle
dbg = optDebug opts
in ("// Macros"++).nl.nl.
(if optTag opts then
("#ifndef USE_TAGS"++).nl.
("#error you must enable the USE_TAGS macro for tags to work"++).nl.
("#endif /* USE_TAGS */"++).nl
else id).
(case gc of
SemiGC ->
("#define GC_MALLOC MM_alloc"++).nl.
wrapIfGC
(("// pointer stack maximum size"++).nl.
("#define SSTACK_MAX_SIZE "++).shows (optEStackSz opts).nl.
mkPUSHAR dbg.
mkRETVAL dbg)
(("#define PUSHAR(a) (a)"++).nl.
("#define RETVAL(x) (x)"++).nl)
LibGC -> id).nl.
defineGCAF modName gc arityCAF.nl.
(case gc of
LibGC -> createLibGCARInfra opts modName pmDepths.nl
SemiGC ->
createSemiGCARInfra modName larStyle arities pmDepths arityCAF.nl).nl
by the libgc garbage collector .
createLibGCARInfra :: Options -> MName -> PMDepths -> ShowS
createLibGCARInfra opts m pmds =
add libgc handlers for the GMP library
wrapIfGMP
(("void *GMP_GC_malloc(size_t sz) { return GC_malloc(sz); }"++).nl.
("void *GMP_GC_realloc(void *p, size_t old, size_t new) { return GC_realloc(p, new); }"++).nl.
("void GMP_GC_free(void *p, size_t sz) { GC_free(p); }"++).nl) id.
mkMainAR opts m pmds.nl
mkMainAR :: Options -> MName -> PMDepths -> ShowS
mkMainAR opts m pmds =
let mainDef = mainDefQName m
in case Data.Map.lookup mainDef pmds of
Just mainDepth ->
mkLARMacroOpt opts (qName mainDef) 0 0 mainDepth
_ -> id
createSemiGCARInfra :: MName -> LARStyle -> Arities -> PMDepths -> Int -> ShowS
createSemiGCARInfra m larStyle fArities pmDepths arityCAF =
let arities = nub $ elems fArities
nestings = nub $ elems pmDepths
maxArity = maximum (arityCAF:arities)
minNesting =
case Data.Map.lookup (mainDefQName m) pmDepths of
maxNestings = maximum (minNesting:nestings)
hAR_COPY 0 = ("#define AR_COPY_0(lar, n) do { } while(0)"++).nl
hAR_COPY a =
("#define AR_COPY_"++).shows a.("(lar, n, a0, ...) do { \\"++).nl.
tab.tab.("ARGS(n, lar) = ARGC(a0); \\"++).nl.
tab.tab.("AR_COPY_"++).shows (a-1).("(lar, n+1, ## __VA_ARGS__); \\"++).nl.
tab.("} while(0)"++).nl
AR_CLEAR , simple representation
hAR_CLEAR 0 = ("#define AR_CLEAR_0(lar, n) do { } while(0)"++).nl
hAR_CLEAR d =
("#define AR_CLEAR_"++).shows d.("(lar, n) do { \\"++).nl.
(case gcFor larStyle of
SemiGC -> tab.tab.("NESTED(n, lar) = NULL; \\"++).nl
LibGC -> id).
tab.tab.("AR_CLEAR_"++).shows (d-1).("(lar, n+1); \\"++).nl.
tab.tab.("} while(0)"++).nl
AR_CLEAR , compact representation
hAR_CLEARc 0 = ("#define AR_CLEAR_0(lar, ar, n) do { } while(0)"++).nl
hAR_CLEARc d =
("#define AR_CLEAR_"++).shows d.("(lar, ar, n) do { \\"++).nl.
(case gcFor larStyle of
SemiGC -> tab.tab.("NESTED(n, ar, lar) = NULL; \\"++).nl
LibGC -> id).
tab.tab.("AR_CLEAR_"++).shows (d-1).("(lar, ar, n+1); \\"++).nl.
tab.tab.("} while(0)"++).nl
in if maxArity > maxLARArity then
error $ "Maximum function/LAR arity exceeded: "++(show maxArity)++", maximum is "++(show maxLARArity)
else if maxNestings > maxNestedLARs then
error $ "Maximum function/LAR nesting exceeded: "++(show maxNestings)++", maximum is "++(show maxNestedLARs)
else
(foldDot hAR_COPY [0..maxArity]).nl.
(if larStyle==LAR64 then
foldDot hAR_CLEARc [0..maxNestings]
else
foldDot hAR_CLEAR [0..maxNestings]).nl
defInterface :: LARStyle -> DfInfo -> [QName] -> CIDs -> ShowS
defInterface larStyle dfInfo importFuns extCIDs =
let externF v = ("extern "++).protoFunc v
macrosConstr (c, (_, ar)) =
let bvs = cArgsC c ar
in foldDot (protoF larStyle stricts cbns c) (enumNames bvs)
extConstrs = map dfcN $ Data.Set.toList $ diDfcs dfInfo
in foldDot externF extConstrs.
foldDot externF (map genNApp $ Data.Set.toList $ diEApps dfInfo).
foldDot externF importFuns.
foldDot macrosConstr (Data.Map.toList extCIDs)
predeclarations :: [BlockL] -> ConfigLAR -> ShowS
predeclarations lblockList config =
let opts = getOptions config
predeclF (DefL fname _ bind) =
let arityA = length bind
arityV = arityA
nesting = findPMDepthSafe fname (getPMDepths config)
in smFun opts fname arityA arityV nesting
predeclF (ActualL {}) = ierr "predeclF: found actual"
lblockListF = Prelude.filter isFun lblockList
in foldDot predeclF lblockListF.nl
pdeclExts :: Options -> ImportedNames -> ShowS
pdeclExts opts imports =
extConstrs = opts dfcs
predeclE nst ( DefF vname _ ) =
let fArity = length frml
in smFun ( qName vname ) fArity fArity
predeclEC = predeclE 0
predeclED = predeclE 1
imports' = Data.Map.filter (\iinfo->(impC iinfo)/=NDType) imports
predeclEF fname =
let (Just iinfo) = Data.Map.lookup fname imports
(Just nesting) = impD iinfo
Just fArity = impA iinfo
in smFun opts fname fArity fArity nesting
pdecls = foldDot predeclEF (Data.Map.keys imports').nl
in case gcFor $ optLARStyle opts of
SemiGC -> ierr "pdeclExts: not to be used with semiGC"
LibGC -> pdecls
pdeclExtApps :: Options -> ExtAppFuns -> ShowS
pdeclExtApps opts extApps =
let mkSmFun ar = smFun opts (genNApp ar) (1+ar) (1+ar) 1
in foldDot mkSmFun $ Data.Set.toList extApps
genMutARs :: LARStyle -> Arities -> PMDepths -> [BlockL] -> ShowS
genMutARs larStyle localArities localPmdepths defs =
let arities = union localArities builtinArities
pmdepths = union localPmdepths builtinPmDepths
findCIsB (DefL _ e _) = findCIsE e
findCIsB (ActualL _ _ e) = findCIsE e
findCIsE (LARCall _ _ NoCI) = []
findCIsE (LARCall _ _ (Mut _ Nothing)) =
ierr "mutation index not set"
findCIsE (LARCall f qns (Mut mut (Just iidx))) =
case (Data.Map.lookup f arities, Data.Map.lookup f pmdepths) of
(Just a, Just n) -> [(f, (mut, iidx), qns, (a, n))]
_ -> ierr $ "findCIsE: Missing information for "++(qName f)
findCIsE (LARC _ el) = concatMap findCIsE el
findCIsE (ConstrL{}) = []
findCIsE (BVL{}) = []
findCIsE (CaseL _ _ pats) = concatMap findCIsP pats
findCIsP (PatB _ e) = findCIsE e
allMutInfo :: [MutInfo]
allMutInfo = concatMap findCIsB defs
in foldDot (mkMutAR larStyle) allMutInfo
| Generates specialized macros for a module 's global CAF .
pdeclGCAF :: ConfigLAR -> Int -> ShowS
pdeclGCAF config arityCAF =
let m = getModName config
opts = getOptions config
in case (gcFor $ optLARStyle $ getOptions config) of
SemiGC -> id
LibGC -> mkLARMacro opts ("GCAF_"++m) arityCAF arityCAF 0
declarations :: [Data] -> [BlockL] -> ShowS
declarations dts ds =
let proto (DefL n _ _) = protoFunc n
proto (ActualL n _ _) = protoVar (qName n)
idDefs = foldDot proto ds
protoDT d = pprinterSig d.(";"++).nl
forcingFuncs = foldDot (\(Data d _ _)->protoDT d) dts.
foldDot protoDT builtinDTypes
in idDefs.forcingFuncs
protoVar :: String -> ShowS
protoVar v = ("VAR("++).(v++).(");"++).nl
declarationsBuiltins :: Options -> ShowS
declarationsBuiltins opts =
foldDot (declF opts) bfsLARInfo.nl.
builtinConstrsDecls opts.nl
mainProg :: [BlockL] -> TEnv -> ConfigLAR -> ShowS
mainProg ds env config = foldDot (\x -> (mkCBlock x env config).nl) ds
epilogue :: Options -> ShowS
epilogue opts = builtins opts.nl
mkCBlock :: BlockL -> TEnv -> ConfigLAR -> ShowS
mkCBlock (DefL f e bind) env config =
let fArity = length bind
opts = getOptions config
larStyle = optLARStyle opts
gc = gcFor larStyle
in ("FUNC("++).pprint f.("){"++).nl.
(case gc of
LibGC | fArity > 0 ->
("INIT_ARG_LOCKS("++).shows fArity.(");"++).nl
_ -> id).
debugFuncPrologue (optDebug opts) f.
(case Data.Map.lookup f (getStricts config) of
Nothing -> id
Just strictFrms -> forceStricts larStyle strictFrms fArity).
logPrev opts.
mkCFuncBody config env f e.
("}"++).nl
mkCBlock (ActualL v act e) env config =
let opts = getOptions config
in ("VAR("++).pprint v.("){"++).nl.
debugVarPrologue (optDebug opts) v.
mkAct act opts.
("return "++).(mkCExp env config e).semi.nl.
("}"++).nl
mkCFuncBody :: ConfigLAR -> TEnv -> QName -> ExprL -> ShowS
mkCFuncBody config env f e =
pmds = getPMDepths config
patD = case Data.Map.lookup f pmds of
Just d -> d
Nothing -> ierr $ "Function "++(qName f)++" has no depth in:\n"++(pprintPD pmds "")
patDS = shows patD
else keep it in the stack ( important for GC )
(if patD > maxNestedLARs then
error $ "Too deep pattern matching detected: "++(show patD)++", maximum depth allowed is "++(show maxNestedLARs)
else id).
(if patD > 0 then tab.("Susp cl["++).patDS.("];"++).nl else id).
(mkCStmBody e env config)
forceStricts :: LARStyle -> StrictInds -> Arity -> ShowS
forceStricts larStyle strictInds fArity =
let aux x =
mkVALS larStyle x fArity "T0".
(" = ((LarArg)CODE("++).shows x.(", T0))(T0); // strict "++).nl
in foldDot aux $ Data.Set.toList strictInds
mkCStmBody :: ExprL -> TEnv -> ConfigLAR -> ShowS
mkCStmBody e@(CaseL {}) env config =
tab.("Susp Res;"++).nl.
mkCExp env config e.nl.
("return Res;"++).nl
mkCStmBody (ConstrL (CC c cId cArity)) _ config =
let opts = getOptions config
in logConstr opts c.
mkSusp opts cId uTag (cArity>0).nl
mkCStmBody e env config = ("return "++).mkCExp env config e.semi.nl
mkCExp :: TEnv -> ConfigLAR -> ExprL -> ShowS
mkCExp env config (LARC (CN c) exps) =
let opts = getOptions config
larStyle = optLARStyle opts
useFastOps = (larStyle==LAR64) && (optFastOp opts)
in case c of
CIf -> ("(PVAL_R("++).mkCExp env config (exps !! 0).(")?"++).
("("++).mkCExp env config (exps !! 1).("):"++).
("("++).mkCExp env config (exps !! 2).("))"++)
c' | c' `elem` [ CMinus, CPlus, CMult, CDivide, CEqu, CLe, CGe
, CGt, CLt, CAnd, COr, CMulI, CNEq, CMod, CDiv] ->
mkBinOp c' exps env config
CNeg ->
let nExp = mkCExp env config (exps !! 0)
in if useFastOps then
("PVAL_NEG("++).nExp.(")"++)
else
("PVAL_C(-(PVAL_R("++).nExp.("))"++).mIntTag config.(")"++)
CTrue -> intSusp larStyle "True"
CFalse -> intSusp larStyle "False"
_ -> error $ "mkCExp: unknown built-in constant "++(pprint c "")
mkCExp _ config (LARC (LitInt i) exps) =
case exps of
[] -> intSusp (optLARStyle $ getOptions config) (show i)
(_:_) -> ierr "Integer literal applied to expressions."
mkCExp _ config (LARCall n _ (Mut _ iidx)) | optTCO (getOptions config) =
case iidx of
Just i -> pprint n.("("++).nameMutAR n i.(")"++)
Nothing -> ierr "mkCExp: missing intensional index"
mkCExp env config (LARCall n acts _) =
if n `elem` (nmsids2nms (getCAFnmsids config)) then
let Just n' = (getCAFid n (getCAFnmsids config))
in ("("++).nameGCAF (getModName config).(("("++(show n')++"))")++)
else makeActs n acts env config
mkCExp env config (CaseL (cn, efunc) e pats) =
let matchedExpr = mkCExp env config e
cases = foldDot mkCPat pats
opts = getOptions config
sConstrID = case cn of
CLoc Nothing -> ierrCLoc
CLoc (Just (c, _)) -> ("CONSTR(cl["++).shows c.("])"++)
CFrm _ -> ("CONSTR("++).matchedExpr.(")"++)
defaultCase = tab.("default: printf(\"Pattern matching on "++).pprint e.
(" failed: constructor %d encountered.\\n\", "++).
sConstrID.("); exit(0);"++).nl
mkCPat (PatB (CC c cId _, bindsVars) eP) =
tab.("case "++).shows cId.(": { /* "++).pprint c.(" */ "++).
mkPatBody eP bindsVars.
("; break; }"++).nl
mkPatBody ePB _ =
let opts = getOptions config
( if ( stGC opts ) & & ( not bindsVars ) then
(case ePB of
CaseL {} -> id
_ -> ("Res = "++)).
mkCExp env config ePB
larStyle = optLARStyle opts
argsN = getFuncArity efunc (getArities config)
ierrCLoc = ierr $ "mkCExp: non-enumerated case expression: "++(pprint e "")
in (case cn of
CLoc Nothing -> ierrCLoc
CLoc (Just (counter, _)) ->
let dS = shows counter
in tab.("cl["++).dS.("] = "++).matchedExpr.semi.nl.
tab.mkNESTED larStyle efunc counter argsN.(" = CPTR(cl["++).dS.("]);"++).nl.
logDict opts counter ;
CFrm _ -> id).
only one pattern ( will segfault / misbehave if the constructor
(if null pats then
("/* Empty pattern matching */"++)
else if (length pats == 1) && (not (optDebug opts)) then
one pattern only ; skip the branching
let [PatB (_, bindsVars) patE] = pats
(case cn of
CFrm _ -> matchedExpr.(";"++).nl
CLoc _ -> id).
tab.mkPatBody patE bindsVars.semi
else
tab.("switch ("++).sConstrID.(") {"++).nl.
cases.
(if optDebug opts then defaultCase else id).
tab.("}"++).nl)
mkCExp _ _ (ConstrL _) =
ierr "LAR: ConstrL can only occur as the first symbol of a definition"
mkCExp _ _ e@(BVL _ (CLoc Nothing, _)) =
ierr $ "mkCExp: found non-enumerated bound variable: "++(pprint e "")
mkCExp _ config bv@(BVL v (cloc, fname)) =
let larStyle = optLARStyle $ getOptions config
argsN = getFuncArity fname (getArities config)
gc = gcFor larStyle
in case cloc of
CLoc Nothing -> ierr $ "non-enumerated bound variable: "++(pprint bv "")
CLoc (Just (counter, _)) ->
mkCall gc v (mkNESTED larStyle fname counter argsN)
CFrm i ->
mkCall (gcFor larStyle) v (("FRM_NESTED("++).shows i.(")"++))
getFuncArity :: QName -> Arities -> Arity
getFuncArity f ars =
case Data.Map.lookup f ars of
Just n -> n
Nothing -> ierr $ "mkCExp: BV: no arity of enclosing function "++(lName f)
mkBinOp :: COp -> [ExprL] -> TEnv -> ConfigLAR -> ShowS
mkBinOp c [e1, e2] env config =
let e1' = mkCExp env config e1
e2' = mkCExp env config e2
val1 = ("PVAL_R("++).e1'.(")"++)
val2 = ("PVAL_R("++).e2'.(")"++)
cBin cOp tagFunc =
("(PVAL_C("++).val1.(cOp++).val2.tagFunc config.("))"++)
opts = getOptions config
useFastOps = (optLARStyle opts==LAR64) && (optFastOp opts)
fastOp opN = (opN++).("(("++).e1'.("), ("++).e2'.("))"++)
in case c of
CPlus | useFastOps -> fastOp "PVAL_ADD"
CMinus | useFastOps -> fastOp "PVAL_SUB"
CMult | useFastOps -> fastOp "PVAL_MUL"
CDiv | useFastOps -> fastOp "PVAL_DIV"
CDivide| useFastOps -> fastOp "PVAL_DIV"
CMod | useFastOps -> fastOp "PVAL_MOD"
CAnd | useFastOps - > fastOp " PVAL_AND "
COr | useFastOps -> fastOp "PVAL_OR"
CEqu | useFastOps -> fastOp "PVAL_EQU"
CNEq | useFastOps -> fastOp "PVAL_NEQ"
CLt | useFastOps -> fastOp "PVAL_LT"
CGt | useFastOps -> fastOp "PVAL_GT"
CLe | useFastOps -> fastOp "PVAL_LE"
CGe | useFastOps -> fastOp "PVAL_GE"
C operators that are different from Haskell
CMulI -> lparen.(pprint CMulI).lparen.e1'.comma.e2'.rparen.rparen
CNEq -> cBin "!=" mBoolTag
CMod -> cBin "%" mIntTag
CDiv -> cBin "/" mIntTag
iResOp | iResOp `elem` [ CMinus, CPlus, CMult, CDivide, CMod, CDiv] ->
cBin (pprint c "") mIntTag
C operators that return values
bResOp | bResOp `elem` [ CEqu, CLe, CGe, CGt, CLt, CAnd, COr, CNEq] ->
cBin (pprint c "") mBoolTag
_ -> ierr $ "mkBinOp: unhandled operator " ++ (pprint c "")
mkBinOp _ _ _ _ =
ierr "mkBinOp: called with wrong arguments"
intSusp :: LARStyle -> String -> ShowS
intSusp LAR64 c = ("PVAL_C("++).(c++).(")"++)
intSusp _ c = ("(SUSP("++).(c++).(", "++).intTag.(", NULL))"++)
protoB :: LARStyle -> BlockL -> TEnv -> Stricts -> CBNVars -> ShowS
protoB larStyle (DefL fName _ bind) _ stricts cbnVars =
let Just cbns = Data.Map.lookup fName cbnVars
Just strs = Data.Map.lookup fName stricts
in foldDot (protoF larStyle strs cbns fName) (enumNames bind)
protoB _ (ActualL {}) _ _ _ = id
protoF :: LARStyle -> StrictInds -> [QName] -> QName -> (Int, QName) -> ShowS
protoF larStyle strs cbns fName (n, x)
| n `member` strs =
("#define " ++).pprint x.("(T0) "++).mkGETSTRICTARG larStyle fName n.nl
| x `elem` cbns =
("#define " ++).pprint x.("(T0) GETCBNARG(" ++).(shows n).(", T0)"++).nl
| otherwise =
case gcFor larStyle of
SemiGC ->
("#define " ++).pprint x.("(T0) "++).
("GETARG("++).(shows n).(", T0)"++).nl
LibGC -> mkDefineVar larStyle x fName n
defineGCAF :: MName -> GC -> Int -> ShowS
defineGCAF modName gc arityCAF =
case gc of
SemiGC ->
("#define "++).nameGCAF modName.("(x) GETARG(x, "++).namegenv modName.(")"++)
LibGC ->
("#define "++).nameGCAF modName.("(x) GETARG(x, "++).
shows arityCAF.(", "++).namegenv modName.(")"++)
| Creates the global LAR for CAFs .
genv :: MName -> Int -> ShowS
genv m arityCAF =
if arityCAF > 0 then
wrapIfGC
(("static TP_ *"++).namegenv m.(";"++).nl)
(("static TP_ "++).namegenv m.(";"++).nl)
else id
| Generates : ( a ) the CAF of a module , ( b ) the C declarations of the memory
management subsystem , ( c ) the Graphviz declarations .
prologue :: Options -> MName -> Int -> ShowS
prologue opts modName arityCAF =
let gc = gcFor $ optLARStyle opts
prototype for module CAF
(case gc of
SemiGC ->
(case optCMode opts of
Whole ->
("/* Memory management */"++).nl.
("#define DEFAULT_MAXMEM "++).shows (optMaxMem opts).nl.
("unsigned long MAXMEM = DEFAULT_MAXMEM;"++).nl.
("unsigned long MAXMEMSPACE = DEFAULT_MAXMEM / 2;"++).nl.
("// Function prototypes for the allocator"++).nl.
(if optLink opts then
("inline byte* MM_alloc(size_t bytes);"++)
else
("static inline byte* MM_alloc(size_t bytes);"++)).nl.
("byte *space, *space1, *space2, *spaceStart, *spaceEnd;"++).nl
CompileModule ->
("extern inline byte* MM_alloc(size_t bytes);"++).nl).
wrapIfGC
(("// Memory management: pointer stack pointers (base/current)"++).nl.
("static TP_ *sstack_bottom;"++).nl.
("static TP_ *sstack_ptr;"++).nl)
id
LibGC -> id).
(if (optVerbose opts) then
("// Graphviz output functionality"++).nl.
("int counter; FILE *p; /* file for graph output */"++).nl
else id)
mainFunc :: TEnv -> Options -> PMDepth -> [MName] -> ShowS
mainFunc env opts mainNesting modules =
let m = case modules of [m'] -> m' ; _ -> "Main"
mainDef = mainDefQName m
printResDT dt = tab.pprinterName dt.("(res); printf(\" \");"++).nl
dbg = optDebug opts
larStyle= optLARStyle opts
gc = gcFor larStyle
in ("int main(int argc, char* argv[]){\n"++).
tab.("clock_t t1, t2;"++).nl.
tab.("Susp res;"++).nl.
tab.("t1 = clock();\n"++).
(case gc of
SemiGC ->
tab.("/* allocate space in the heap */"++).nl.
tab.("if (argc > 1) {"++).nl.
tab.tab.("MAXMEM = strtoul(argv[1], NULL, 10);"++).nl.
tab.tab.("MAXMEMSPACE = MAXMEM / 2;"++).nl.
tab.tab.("printf(\"heap size = 2 x %lu bytes\\n\", MAXMEMSPACE);"++).nl.
tab.("}"++).nl.
tab.("space1 = (byte *) malloc((size_t)MAXMEMSPACE);"++).nl.
tab.("space2 = (byte *) malloc((size_t)MAXMEMSPACE);"++).nl.
tab.("if (space1==NULL || space2==NULL) {"++).nl.
tab.tab.("printf(\"Cannot allocate memory to start program, \""++).nl.
tab.tab.(" \"tried 2 x %lu bytes.\\n\", MAXMEMSPACE);"++).nl.
tab.tab.("exit(EXIT_FAILURE);"++).nl.
tab.("}"++).nl.
tab.("space = spaceStart = space1;"++).nl.
tab.("spaceEnd = space + MAXMEMSPACE;"++).nl.
Initialize the explicit pointer stack .
wrapIfGC
(("sstack_bottom = (TP_*)malloc(sizeof(TP_)*SSTACK_MAX_SIZE);"++).nl.
("if (sstack_bottom == 0) { printf(\"No space for pointer stack.\\n\"); exit(0); };"++).nl.
("sstack_ptr = sstack_bottom;"++).nl
) id
LibGC ->
tab.("GC_init();"++).nl.
wrapIfOMP (tab.("GC_thr_init();"++).nl) id.
wrapIfGMP (tab.("mp_set_memory_functions(GMP_GC_malloc, GMP_GC_realloc, GMP_GC_free);"++).nl) id
).
tab.("// initial activation record"++).nl.
tab.("TP_ T0_ = NULL;"++).nl.
tab.("TP_ AR_TP(T0) = AR_REF(T0_);"++).nl.
(case gc of
LibGC -> id
SemiGC ->
tab.debugCreateTopLAR dbg.
tab.("TP_ AR_TP(t0) = PUSHAR(AR(0,"++).shows mainNesting.("));"++).nl).
initModules modules.
logGraphStart opts.
mkMainCall gc m.
tab.("t2 = clock();"++).nl.
(case (findType mainDef env) of
Tg (T dt) | dt==dtInteger ->
wrapIfGMP
(tab.("printf(\"Integer result=%s\\n\", mpz_get_str(0, 10, *((mpz_t*)(CPTR(res)))));"++).nl)
(tab.("printf(\"cannot compute 'result', gic must be built with libgmp support\\n\");"++).nl)
Tg (T dt) ->
if (dt==dtInt || dt==dtBool) then
if larStyle==LAR64 then
tab.("printf(\"%ld, \", PVAL_R(res));"++).nl
else
tab.("if ((CPTR(res)) == 0) printf(\"%d, \", CONSTR(res));"++).nl.
tab.("else printf(\"Thunk{%d, %p}\", CONSTR(res), CPTR(res));"++).nl
else
printResDT dt
typ@(Tg (TDF _ _)) ->
error $ "Can not determine pretty printer for higher-order variable result of type "++(pprint typ "")
Tv _ -> ierr "result variable is polymorphic"
Ta (Tg (T dt)) _ -> printResDT dt
t ->
ierr $ "result variable has unsupported type: "++(pprint t "")
).
tab.("printf(\"c time = %.10f sec\\n\", ((double)(t2 - t1)/CLOCKS_PER_SEC));"++).nl.
debugMainFinish dbg.
logGraphEnd opts.
tab.("return 0;"++).nl.
("}"++).nl
initModules :: [MName] -> ShowS
initModules [] = id
initModules (m:ms) = tab.genInitMod m.("(T0);"++).nl.initModules ms
LAR containing the top - level CAFs of the module .
initMod :: MName -> ConfigLAR -> ShowS
initMod m config =
let arityCAF = length (getCAFnmsids config)
opts = getOptions config
nms = map pprint $ nmsids2nms (getCAFnmsids config)
cafName = namegenv m
in ("void "++).genInitMod m.("(TP_ AR_TP(T0)) {"++).nl.
(if arityCAF > 0 then
debugCreateCAF (optDebug opts) cafName.
tab.cafName.(" = "++).
(case gcFor (optLARStyle opts) of
SemiGC ->
("PUSHAR(AR("++).shows arityCAF.
(", 0"++).((foldl (\x -> \y -> x ++ ", " ++ (y "")) "" nms)++).
("));"++).nl
LibGC ->
(nameGCAF m).("_AR("++).insCommIfMore nms.(");"++)).nl
else id).
("}"++).nl.nl
genInitMod :: MName -> ShowS
genInitMod m = ("__initModule_"++).(m++)
argDefs :: LARStyle -> [BlockL] -> TEnv -> Stricts -> CBNVars -> ShowS
argDefs larStyle ds env stricts cbnVars =
foldDot (\def -> (protoB larStyle def env stricts cbnVars)) ds
makeActs :: QName -> [QName] -> TEnv -> ConfigLAR -> ShowS
makeActs f args env config =
let fNesting = findPMDepthSafe f (getPMDepths config)
isVar = case args of { [] | fNesting==0 -> True ; _ -> False }
allocHeap = optHeap (getOptions config) || (returnsThunk env f)
larStyle = optLARStyle (getOptions config)
fLAR =
if isVar then ("AR_TP(T0)"++)
else
let fArity = length args
in mkAllocAR larStyle allocHeap f fArity fNesting (map pprint args)
simpleCall = pprint f.("("++).fLAR.(")"++)
in case larStyle of
LAROPT -> simpleCall
_ -> ("RETVAL("++).pprint f.("(PUSHAR("++).fLAR.(")))"++)
depthOfMainDef :: [BlockL] -> Int
depthOfMainDef blocks =
let findRes (DefL v _ _) = (lName v)==mainDefName
findRes (ActualL {}) = False
res = Prelude.filter findRes blocks
in case res of
[DefL _ e _] -> countPMDepthL e
_ -> ierr "No (unique) result definition was found."
| Main entry point for separate module compilation from " SLIC.Driver " .
compileModL :: MNameF -> ConfigLAR -> TEnv -> DFI -> ImportedNames ->
CIDs -> ProgL -> IO ()
compileModL fm config env dfi allImps cidsExt finalProgLAR =
let (moduleName, f) = fm
fPath = pathOf f
moduleC = fPath++[dirSeparator]++moduleName++".c"
moduleDFI = fPath++[dirSeparator]++(dfiFile moduleName)
in writeFile moduleC (makeC
finalProgLAR env config (dfi, allImps, cidsExt) "") >>
writeFile moduleDFI (show dfi)
|
edb10397bb4c91fb23dc61c3fb662d2db5c641c862b3a1884b490b6737e68d32 | ghc/packages-Cabal | setup-reexport.test.hs | import Test.Cabal.Prelude
-- Test that we can resolve a module name ambiguity when reexporting
-- by explicitly specifying what package we want.
main = setupAndCabalTest $ do
skipUnless =<< ghcVersionIs (>= mkVersion [7,9])
withPackageDb $ do
withDirectory "p" $ setup_install []
withDirectory "q" $ setup_install []
withDirectory "reexport" $ setup_install []
withDirectory "reexport-test" $ do
setup_build []
runExe' "reexport-test" [] >>= assertOutputContains "p q"
| null | https://raw.githubusercontent.com/ghc/packages-Cabal/6f22f2a789fa23edb210a2591d74ea6a5f767872/cabal-testsuite/PackageTests/Ambiguity/setup-reexport.test.hs | haskell | Test that we can resolve a module name ambiguity when reexporting
by explicitly specifying what package we want. | import Test.Cabal.Prelude
main = setupAndCabalTest $ do
skipUnless =<< ghcVersionIs (>= mkVersion [7,9])
withPackageDb $ do
withDirectory "p" $ setup_install []
withDirectory "q" $ setup_install []
withDirectory "reexport" $ setup_install []
withDirectory "reexport-test" $ do
setup_build []
runExe' "reexport-test" [] >>= assertOutputContains "p q"
|
7f63942b9f7dd76a84ed3156b8b6087aa3b3e4c0719bd5ba130fc64b7cce6d22 | sbcl/sbcl | move.lisp | the ARM VM definition of operand loading / saving and the Move VOP
This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
;;;; public domain. The software is in the public domain and is
;;;; provided with absolutely no warranty. See the COPYING and CREDITS
;;;; files for more information.
(in-package "SB-VM")
(defun load-immediate-word (y val &optional single-instruction)
(let (single-mov
ffff-count
zero-count
(val (ldb (byte 64 0) val)))
(flet ((single-mov ()
(loop for i below 64 by 16
for part = (ldb (byte 16 i) val)
count (/= part #xFFFF) into ffff
count (plusp part) into zero
finally
(setf ffff-count ffff
zero-count zero
single-mov (or (= ffff 1)
(= zero 1))))))
(cond ((typep val '(unsigned-byte 16))
(inst movz y val)
y)
((typep (ldb (byte 64 0) (lognot val)) '(unsigned-byte 16))
(inst movn y (ldb (byte 64 0) (lognot val)))
y)
((encode-logical-immediate val)
(inst orr y zr-tn val)
y)
((and
(not (single-mov))
(not single-instruction)
(let ((descriptorp (memq (tn-offset y) descriptor-regs)))
(flet ((try (i part fill)
(let ((filled (dpb fill (byte 16 i) val)))
(cond ((and (encode-logical-immediate filled)
(not (and descriptorp
(logtest filled fixnum-tag-mask))))
(inst orr y zr-tn filled)
(inst movk y part i)
t)))))
(loop for i below 64 by 16
for part = (ldb (byte 16 i) val)
thereis (or (try i part #xFFFF)
(try i part 0)
(try i part
(ldb (byte 16 (mod (+ i 16) 64))
val)))))))
y)
((and (not single-mov)
(not single-instruction)
(let ((a (ldb (byte 16 0) val))
(b (ldb (byte 16 16) val))
(c (ldb (byte 16 32) val))
(d (ldb (byte 16 48) val)))
(let ((descriptorp (memq (tn-offset y) descriptor-regs)))
(flet ((try (part val1 hole1 val2 hole2)
(let* ((whole (dpb part (byte 16 16) part))
(whole (dpb whole (byte 32 32) whole)))
(when (and (encode-logical-immediate whole)
(not (and descriptorp
(logtest whole fixnum-tag-mask))))
(inst orr y zr-tn whole)
(inst movk y val1 hole1)
(inst movk y val2 hole2)
t))))
(cond ((= a b)
(try a c 32 d 48))
((= a c)
(try a b 16 d 48))
((= a d)
(try a b 16 c 32))
((= b c)
(try b a 0 d 48))
((= b d)
(try b a 0 c 32))
((= c d)
(try c a 0 b 16)))))))
y)
((and (< ffff-count zero-count)
(or single-mov
(not single-instruction)))
(loop with first = t
for i below 64 by 16
for part = (ldb (byte 16 i) val)
unless (= part #xFFFF)
do
(if (shiftf first nil)
(inst movn y (ldb (byte 16 0) (lognot part)) i)
(inst movk y part i)))
y)
((or single-mov
(not single-instruction))
(loop with first = t
for i below 64 by 16
for part = (ldb (byte 16 i) val)
when (plusp part)
do
(if (shiftf first nil)
(inst movz y part i)
(inst movk y part i)))
y)))))
(defun add-sub-immediate (x &optional (temp tmp-tn))
(cond ((not (integerp x))
x)
((add-sub-immediate-p x)
x)
(t
(load-immediate-word temp x))))
(defun ccmp-immediate (x &optional (temp tmp-tn))
(cond ((not (integerp x))
x)
((typep x '(unsigned-byte 5))
x)
(t
(load-immediate-word temp x))))
(define-move-fun (load-immediate 1) (vop x y)
((immediate)
(any-reg descriptor-reg))
(let ((val (tn-value x)))
(etypecase val
(integer
;; This is a FIXNUM, as IMMEDIATE-CONSTANT-SC only
;; accepts integers if they are FIXNUMs.
(load-immediate-word y (fixnumize val)))
(character
(let* ((codepoint (char-code val))
(tagged (dpb codepoint (byte 24 8) character-widetag)))
(load-immediate-word y tagged)))
(single-float
(let* ((bits (single-float-bits val))
(tagged (dpb bits (byte 32 32) single-float-widetag)))
(load-immediate-word y tagged)))
(symbol
(load-symbol y val))
(structure-object
(if (eq val sb-lockless:+tail+)
(inst add y null-tn (- sb-vm::lockfree-list-tail-value sb-vm:nil-value))
(bug "immediate structure-object ~S" val))))))
(define-move-fun (load-number 1) (vop x y)
((immediate)
(signed-reg unsigned-reg))
(load-immediate-word y (tn-value x)))
(define-move-fun (load-character 1) (vop x y)
((immediate) (character-reg))
(load-immediate-word y (char-code (tn-value x))))
(define-move-fun (load-system-area-pointer 1) (vop x y)
((immediate) (sap-reg))
(let ((immediate-label (gen-label)))
(assemble (:elsewhere)
(emit-label immediate-label)
(inst dword (sap-int (tn-value x))))
(inst ldr y (@ immediate-label))))
(define-move-fun (load-constant 5) (vop x y)
((constant) (descriptor-reg))
(inst load-constant y (tn-byte-offset x)))
(define-move-fun (load-stack 5) (vop x y)
((control-stack) (any-reg descriptor-reg))
(load-stack-tn y x))
(define-move-fun (load-number-stack 5) (vop x y)
((character-stack) (character-reg)
(sap-stack) (sap-reg)
(signed-stack) (signed-reg)
(unsigned-stack) (unsigned-reg))
(load-stack-offset y (current-nfp-tn vop) x))
(define-move-fun (store-stack 5) (vop x y)
((any-reg descriptor-reg) (control-stack))
(store-stack-tn y x))
(define-move-fun (store-number-stack 5) (vop x y)
((character-reg) (character-stack)
(sap-reg) (sap-stack)
(signed-reg) (signed-stack)
(unsigned-reg) (unsigned-stack))
(store-stack-offset x (current-nfp-tn vop) y))
The Move VOP :
(define-vop (move)
(:args (x :target y
:scs (any-reg descriptor-reg zero)
:load-if (not (location= x y))))
(:results (y :scs (any-reg descriptor-reg control-stack)
:load-if (not (location= x y))))
(:generator 0
(cond ((location= x y))
((sc-is y control-stack)
(store-stack-tn y x))
((and (sc-is x any-reg)
(eql (tn-offset x) zr-offset))
(inst mov y 0))
(t
(move y x)))))
(define-move-vop move :move
(any-reg descriptor-reg)
(any-reg descriptor-reg))
The MOVE - ARG VOP is used for moving descriptor values into another
;;; frame for argument or known value passing.
(define-vop (move-arg)
(:args (x :target y
:scs (any-reg descriptor-reg zero))
(fp :scs (any-reg)
:load-if (not (sc-is y any-reg descriptor-reg))))
(:results (y))
(:generator 0
(sc-case y
((any-reg descriptor-reg)
(if (and (sc-is x any-reg)
(eql (tn-offset x) zr-offset))
(inst mov y 0)
(move y x)))
(control-stack
(store-stack-offset x fp y)))))
;;;
(define-move-vop move-arg :move-arg
(any-reg descriptor-reg)
(any-reg descriptor-reg))
Use LDP / STP when possible
(defun load-store-two-words (vop1 vop2)
(let ((register-sb (sb-or-lose 'sb-vm::registers))
used-load-tn)
(labels ((register-p (tn)
(and (tn-p tn)
(eq (sc-sb (tn-sc tn)) register-sb)))
(stack-p (tn)
(and (tn-p tn)
(sc-is tn control-stack)))
(source (vop)
(tn-ref-tn (vop-args vop)))
(dest (vop)
(tn-ref-tn (vop-results vop)))
(load-tn (vop)
(tn-ref-load-tn (vop-args vop)))
(suitable-offsets-p (tn1 tn2)
(and (= (abs (- (tn-offset tn1)
(tn-offset tn2)))
1)
(ldp-stp-offset-p (* (min (tn-offset tn1)
(tn-offset tn2))
n-word-bytes)
n-word-bits)))
(load-arg (x load-tn)
(sc-case x
((constant immediate control-stack)
(let ((load-tn (cond ((not (and used-load-tn
(location= used-load-tn load-tn)))
load-tn)
((sb-c::tn-reads load-tn)
(return-from load-arg))
(t
tmp-tn))))
(setf used-load-tn load-tn)
(sc-case x
(constant
(when (eq load-tn tmp-tn)
TMP - TN is not a descriptor
(return-from load-arg))
(lambda ()
(load-constant vop1 x load-tn)
load-tn))
(control-stack
(when (eq load-tn tmp-tn)
(return-from load-arg))
(lambda ()
(load-stack vop1 x load-tn)
load-tn))
(immediate
(cond ((eql (tn-value x) 0)
(setf used-load-tn nil)
(lambda () zr-tn))
(t
(lambda ()
(load-immediate vop1 x load-tn)
load-tn)))))))
(t
(setf used-load-tn x)
(lambda () x))))
(do-moves (source1 source2 dest1 dest2 &optional (fp cfp-tn)
fp-load-tn)
(cond ((and (stack-p dest1)
(stack-p dest2)
(not (location= dest1 source1))
(not (location= dest2 source2))
(or (not (eq fp cfp-tn))
(and (not (location= dest1 source2))
(not (location= dest2 source1))))
(suitable-offsets-p dest1 dest2))
;; Load the source registers
(let (new-source1 new-source2)
(if (and (stack-p source1)
(stack-p source2)
Can load using LDP
(do-moves source1 source2
(setf new-source1 (load-tn vop1))
(setf new-source2
(cond ((not (location= (load-tn vop1) (load-tn vop2)))
(load-tn vop2))
((sc-is (load-tn vop2) descriptor-reg)
(return-from do-moves))
(t
tmp-tn)))))
(setf source1 new-source1
source2 new-source2)
Load one by one
(let ((load1 (load-arg source1 (load-tn vop1)))
(load2 (load-arg source2 (load-tn vop2))))
(unless (and load1 load2)
(return-from do-moves))
(setf source1 (funcall load1)
source2 (funcall load2)))))
(when (> (tn-offset dest1)
(tn-offset dest2))
(rotatef dest1 dest2)
(rotatef source1 source2))
(when fp-load-tn
(load-stack-tn fp-load-tn fp)
(setf fp fp-load-tn))
(inst stp source1 source2
(@ fp (tn-byte-offset dest1)))
t)
((and (stack-p source1)
(stack-p source2)
(register-p dest1)
(register-p dest2)
(not (location= dest1 dest2))
(suitable-offsets-p source1 source2))
(when (> (tn-offset source1)
(tn-offset source2))
(rotatef dest1 dest2)
(rotatef source1 source2))
(inst ldp dest1 dest2
(@ fp (tn-byte-offset source1)))
t))))
(case (sb-c::vop-name vop1)
(move
(do-moves (source vop1) (source vop2) (dest vop1) (dest vop2)))
(sb-c::move-operand
(cond ((and (equal (sb-c::vop-codegen-info vop1)
(sb-c::vop-codegen-info vop2))
(memq (car (sb-c::vop-codegen-info vop1))
'(load-stack store-stack)))
(do-moves (source vop1) (source vop2) (dest vop1) (dest vop2)))))
(move-arg
(let ((fp1 (tn-ref-tn (tn-ref-across (vop-args vop1))))
(fp2 (tn-ref-tn (tn-ref-across (vop-args vop2))))
(dest1 (dest vop1))
(dest2 (dest vop2)))
(when (eq fp1 fp2)
(do-moves (source vop1) (source vop2) (dest vop1) (dest vop2)
(if (and (stack-p dest1)
(stack-p dest2))
fp1
cfp-tn)
(tn-ref-load-tn (tn-ref-across (vop-args vop1)))))))))))
;;;; ILLEGAL-MOVE
This VOP exists just to begin the lifetime of a TN that could n't
;;; be written legally due to a type error. An error is signalled
before this VOP is so we do n't need to do anything ( not that there
;;; would be anything sensible to do anyway.)
(define-vop (illegal-move)
(:args (x) (type))
(:results (y))
(:ignore y)
(:vop-var vop)
(:save-p :compute-only)
(:generator 666
(error-call vop 'object-not-type-error x type)))
;;;; Moves and coercions:
;;; These MOVE-TO-WORD VOPs move a tagged integer to a raw full-word
;;; representation. Similarly, the MOVE-FROM-WORD VOPs converts a raw integer
;;; to a tagged bignum or fixnum.
ARG is a fixnum , so just shift it . We need a type restriction because some
;;; possible arg SCs (control-stack) overlap with possible bignum arg SCs.
(define-vop (move-to-word/fixnum)
(:args (x :scs (any-reg descriptor-reg)))
(:results (y :scs (signed-reg unsigned-reg)))
(:arg-types tagged-num)
(:note "fixnum untagging")
(:generator 1
(inst asr y x n-fixnum-tag-bits)))
(define-move-vop move-to-word/fixnum :move
(any-reg descriptor-reg) (signed-reg unsigned-reg))
ARG is a non - immediate constant ; load it .
(define-vop (move-to-word-c)
(:args (x :scs (constant)))
(:results (y :scs (signed-reg unsigned-reg)))
(:vop-var vop)
(:note "constant load")
(:generator 1
(cond ((sb-c::tn-leaf x)
(load-immediate-word y (tn-value x)))
(t
(load-constant vop x y)
(inst asr y y n-fixnum-tag-bits)))))
(define-move-vop move-to-word-c :move
(constant) (signed-reg unsigned-reg))
ARG is a fixnum or bignum ; figure out which and load if necessary .
(define-vop (move-to-word/integer)
(:args (x :scs (descriptor-reg)))
(:result-refs results)
(:results (y :scs (signed-reg unsigned-reg)))
(:note "integer to untagged word coercion")
(:generator 4
#.(assert (= fixnum-tag-mask 1))
(when (types-equal-or-intersect (tn-ref-type results) (specifier-type 'fixnum))
(sc-case y
(signed-reg
(inst asr y x n-fixnum-tag-bits))
(unsigned-reg
(inst lsr y x n-fixnum-tag-bits)))
(inst tbz x 0 DONE))
(loadw y x bignum-digits-offset other-pointer-lowtag)
DONE))
(define-move-vop move-to-word/integer :move
(descriptor-reg) (signed-reg unsigned-reg))
;;; RESULT is a fixnum, so we can just shift. We need the result type
;;; restriction because of the control-stack ambiguity noted above.
(define-vop (move-from-word/fixnum)
(:args (x :scs (signed-reg unsigned-reg)))
(:results (y :scs (any-reg descriptor-reg)))
(:result-types tagged-num)
(:note "fixnum tagging")
(:generator 1
(inst lsl y x n-fixnum-tag-bits)))
(define-move-vop move-from-word/fixnum :move
(signed-reg unsigned-reg) (any-reg descriptor-reg))
;;; RESULT may be a bignum, so we have to check. Use a worst-case
;;; cost to make sure people know they may be number consing.
(define-vop (move-from-signed)
(:args (arg :scs (signed-reg unsigned-reg) :target x))
(:results (y :scs (any-reg descriptor-reg)))
(:temporary (:scs (non-descriptor-reg) :from (:argument 0)) x)
(:temporary (:sc non-descriptor-reg :offset lr-offset) lr)
(:note "signed word to integer coercion")
(:generator 20
(move x arg)
(inst adds y x x)
(inst b :vc DONE)
(with-fixed-allocation (y lr bignum-widetag (1+ bignum-digits-offset)
:store-type-code nil)
TMP - TN has the untagged address coming from ALLOCATION
that way STP can be used on an aligned address .
LR has the widetag computed by WITH - FIXED - ALLOCATION
(storew-pair lr 0 x bignum-digits-offset tmp-tn))
DONE))
(define-move-vop move-from-signed :move
(signed-reg) (descriptor-reg))
(define-vop (move-from-fixnum+1)
(:args (x :scs (signed-reg unsigned-reg)))
(:results (y :scs (any-reg descriptor-reg)))
(:vop-var vop)
(:generator 4
(inst adds y x x)
(inst b :vc DONE)
(load-constant vop (emit-constant (1+ most-positive-fixnum))
y)
DONE))
(define-vop (move-from-fixnum-1 move-from-fixnum+1)
(:generator 4
(inst adds y x x)
(inst b :vc DONE)
(load-constant vop (emit-constant (1- most-negative-fixnum))
y)
DONE))
Check for fixnum , and possibly allocate one or two word bignum
;;; result. Use a worst-case cost to make sure people know they may
;;; be number consing.
(define-vop (move-from-unsigned)
(:args (arg :scs (signed-reg unsigned-reg) :target x))
(:results (y :scs (any-reg descriptor-reg)))
(:temporary (:scs (non-descriptor-reg) :from (:argument 0)) x)
(:temporary (:sc non-descriptor-reg :offset lr-offset) lr)
(:note "unsigned word to integer coercion")
(:generator 20
(move x arg)
(inst tst x (ash (1- (ash 1 (- n-word-bits
n-positive-fixnum-bits)))
n-positive-fixnum-bits))
(inst lsl y x n-fixnum-tag-bits)
(inst b :eq DONE)
(with-fixed-allocation
(y lr bignum-widetag (+ 2 bignum-digits-offset)
:store-type-code nil)
;; WITH-FIXED-ALLOCATION, when using a supplied type-code,
leaves LR containing the computed header value . In our
case , configured for a 2 - word bignum . If the sign bit in the
;; value we're boxing is CLEAR, we need to shrink the bignum by
;; one word, hence the following:
(inst tbnz x (1- n-word-bits) STORE)
(load-immediate-word lr (bignum-header-for-length 1))
STORE
;; See the comment in move-from-signed
(storew-pair lr 0 x bignum-digits-offset tmp-tn))
DONE))
(define-move-vop move-from-unsigned :move
(unsigned-reg) (descriptor-reg))
;;; Move untagged numbers.
(define-vop (word-move)
(:args (x :target y
:scs (signed-reg unsigned-reg)
:load-if (not (location= x y))))
(:results (y :scs (signed-reg unsigned-reg)
:load-if (not (location= x y))))
(:note "word integer move")
(:generator 0
(move y x)))
(define-move-vop word-move :move
(signed-reg unsigned-reg) (signed-reg unsigned-reg))
;;; Move untagged number arguments/return-values.
(define-vop (move-word-arg)
(:args (x :target y
:scs (signed-reg unsigned-reg))
(fp :scs (any-reg)
:load-if (not (sc-is y signed-reg unsigned-reg))))
(:results (y))
(:note "word integer argument move")
(:generator 0
(sc-case y
((signed-reg unsigned-reg)
(move y x))
((signed-stack unsigned-stack)
(store-stack-offset x fp y)))))
(define-move-vop move-word-arg :move-arg
(descriptor-reg any-reg signed-reg unsigned-reg) (signed-reg unsigned-reg))
;;; Use standard MOVE-ARG + coercion to move an untagged number to a
;;; descriptor passing location.
(define-move-vop move-arg :move-arg
(signed-reg unsigned-reg) (any-reg descriptor-reg))
(define-vop (move-conditional-result)
(:results (res :scs (descriptor-reg)))
(:info true)
(:generator 1
(move res null-tn)
(inst b done)
(emit-label true)
(load-symbol res t)
done))
| null | https://raw.githubusercontent.com/sbcl/sbcl/7d26a6a80cfc290ac044b98f20c1f211048c10e8/src/compiler/arm64/move.lisp | lisp | more information.
public domain. The software is in the public domain and is
provided with absolutely no warranty. See the COPYING and CREDITS
files for more information.
This is a FIXNUM, as IMMEDIATE-CONSTANT-SC only
accepts integers if they are FIXNUMs.
frame for argument or known value passing.
Load the source registers
ILLEGAL-MOVE
be written legally due to a type error. An error is signalled
would be anything sensible to do anyway.)
Moves and coercions:
These MOVE-TO-WORD VOPs move a tagged integer to a raw full-word
representation. Similarly, the MOVE-FROM-WORD VOPs converts a raw integer
to a tagged bignum or fixnum.
possible arg SCs (control-stack) overlap with possible bignum arg SCs.
load it .
figure out which and load if necessary .
RESULT is a fixnum, so we can just shift. We need the result type
restriction because of the control-stack ambiguity noted above.
RESULT may be a bignum, so we have to check. Use a worst-case
cost to make sure people know they may be number consing.
result. Use a worst-case cost to make sure people know they may
be number consing.
WITH-FIXED-ALLOCATION, when using a supplied type-code,
value we're boxing is CLEAR, we need to shrink the bignum by
one word, hence the following:
See the comment in move-from-signed
Move untagged numbers.
Move untagged number arguments/return-values.
Use standard MOVE-ARG + coercion to move an untagged number to a
descriptor passing location. | the ARM VM definition of operand loading / saving and the Move VOP
This software is part of the SBCL system . See the README file for
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
(in-package "SB-VM")
(defun load-immediate-word (y val &optional single-instruction)
(let (single-mov
ffff-count
zero-count
(val (ldb (byte 64 0) val)))
(flet ((single-mov ()
(loop for i below 64 by 16
for part = (ldb (byte 16 i) val)
count (/= part #xFFFF) into ffff
count (plusp part) into zero
finally
(setf ffff-count ffff
zero-count zero
single-mov (or (= ffff 1)
(= zero 1))))))
(cond ((typep val '(unsigned-byte 16))
(inst movz y val)
y)
((typep (ldb (byte 64 0) (lognot val)) '(unsigned-byte 16))
(inst movn y (ldb (byte 64 0) (lognot val)))
y)
((encode-logical-immediate val)
(inst orr y zr-tn val)
y)
((and
(not (single-mov))
(not single-instruction)
(let ((descriptorp (memq (tn-offset y) descriptor-regs)))
(flet ((try (i part fill)
(let ((filled (dpb fill (byte 16 i) val)))
(cond ((and (encode-logical-immediate filled)
(not (and descriptorp
(logtest filled fixnum-tag-mask))))
(inst orr y zr-tn filled)
(inst movk y part i)
t)))))
(loop for i below 64 by 16
for part = (ldb (byte 16 i) val)
thereis (or (try i part #xFFFF)
(try i part 0)
(try i part
(ldb (byte 16 (mod (+ i 16) 64))
val)))))))
y)
((and (not single-mov)
(not single-instruction)
(let ((a (ldb (byte 16 0) val))
(b (ldb (byte 16 16) val))
(c (ldb (byte 16 32) val))
(d (ldb (byte 16 48) val)))
(let ((descriptorp (memq (tn-offset y) descriptor-regs)))
(flet ((try (part val1 hole1 val2 hole2)
(let* ((whole (dpb part (byte 16 16) part))
(whole (dpb whole (byte 32 32) whole)))
(when (and (encode-logical-immediate whole)
(not (and descriptorp
(logtest whole fixnum-tag-mask))))
(inst orr y zr-tn whole)
(inst movk y val1 hole1)
(inst movk y val2 hole2)
t))))
(cond ((= a b)
(try a c 32 d 48))
((= a c)
(try a b 16 d 48))
((= a d)
(try a b 16 c 32))
((= b c)
(try b a 0 d 48))
((= b d)
(try b a 0 c 32))
((= c d)
(try c a 0 b 16)))))))
y)
((and (< ffff-count zero-count)
(or single-mov
(not single-instruction)))
(loop with first = t
for i below 64 by 16
for part = (ldb (byte 16 i) val)
unless (= part #xFFFF)
do
(if (shiftf first nil)
(inst movn y (ldb (byte 16 0) (lognot part)) i)
(inst movk y part i)))
y)
((or single-mov
(not single-instruction))
(loop with first = t
for i below 64 by 16
for part = (ldb (byte 16 i) val)
when (plusp part)
do
(if (shiftf first nil)
(inst movz y part i)
(inst movk y part i)))
y)))))
(defun add-sub-immediate (x &optional (temp tmp-tn))
(cond ((not (integerp x))
x)
((add-sub-immediate-p x)
x)
(t
(load-immediate-word temp x))))
(defun ccmp-immediate (x &optional (temp tmp-tn))
(cond ((not (integerp x))
x)
((typep x '(unsigned-byte 5))
x)
(t
(load-immediate-word temp x))))
(define-move-fun (load-immediate 1) (vop x y)
((immediate)
(any-reg descriptor-reg))
(let ((val (tn-value x)))
(etypecase val
(integer
(load-immediate-word y (fixnumize val)))
(character
(let* ((codepoint (char-code val))
(tagged (dpb codepoint (byte 24 8) character-widetag)))
(load-immediate-word y tagged)))
(single-float
(let* ((bits (single-float-bits val))
(tagged (dpb bits (byte 32 32) single-float-widetag)))
(load-immediate-word y tagged)))
(symbol
(load-symbol y val))
(structure-object
(if (eq val sb-lockless:+tail+)
(inst add y null-tn (- sb-vm::lockfree-list-tail-value sb-vm:nil-value))
(bug "immediate structure-object ~S" val))))))
(define-move-fun (load-number 1) (vop x y)
((immediate)
(signed-reg unsigned-reg))
(load-immediate-word y (tn-value x)))
(define-move-fun (load-character 1) (vop x y)
((immediate) (character-reg))
(load-immediate-word y (char-code (tn-value x))))
(define-move-fun (load-system-area-pointer 1) (vop x y)
((immediate) (sap-reg))
(let ((immediate-label (gen-label)))
(assemble (:elsewhere)
(emit-label immediate-label)
(inst dword (sap-int (tn-value x))))
(inst ldr y (@ immediate-label))))
(define-move-fun (load-constant 5) (vop x y)
((constant) (descriptor-reg))
(inst load-constant y (tn-byte-offset x)))
(define-move-fun (load-stack 5) (vop x y)
((control-stack) (any-reg descriptor-reg))
(load-stack-tn y x))
(define-move-fun (load-number-stack 5) (vop x y)
((character-stack) (character-reg)
(sap-stack) (sap-reg)
(signed-stack) (signed-reg)
(unsigned-stack) (unsigned-reg))
(load-stack-offset y (current-nfp-tn vop) x))
(define-move-fun (store-stack 5) (vop x y)
((any-reg descriptor-reg) (control-stack))
(store-stack-tn y x))
(define-move-fun (store-number-stack 5) (vop x y)
((character-reg) (character-stack)
(sap-reg) (sap-stack)
(signed-reg) (signed-stack)
(unsigned-reg) (unsigned-stack))
(store-stack-offset x (current-nfp-tn vop) y))
The Move VOP :
(define-vop (move)
(:args (x :target y
:scs (any-reg descriptor-reg zero)
:load-if (not (location= x y))))
(:results (y :scs (any-reg descriptor-reg control-stack)
:load-if (not (location= x y))))
(:generator 0
(cond ((location= x y))
((sc-is y control-stack)
(store-stack-tn y x))
((and (sc-is x any-reg)
(eql (tn-offset x) zr-offset))
(inst mov y 0))
(t
(move y x)))))
(define-move-vop move :move
(any-reg descriptor-reg)
(any-reg descriptor-reg))
The MOVE - ARG VOP is used for moving descriptor values into another
(define-vop (move-arg)
(:args (x :target y
:scs (any-reg descriptor-reg zero))
(fp :scs (any-reg)
:load-if (not (sc-is y any-reg descriptor-reg))))
(:results (y))
(:generator 0
(sc-case y
((any-reg descriptor-reg)
(if (and (sc-is x any-reg)
(eql (tn-offset x) zr-offset))
(inst mov y 0)
(move y x)))
(control-stack
(store-stack-offset x fp y)))))
(define-move-vop move-arg :move-arg
(any-reg descriptor-reg)
(any-reg descriptor-reg))
Use LDP / STP when possible
(defun load-store-two-words (vop1 vop2)
(let ((register-sb (sb-or-lose 'sb-vm::registers))
used-load-tn)
(labels ((register-p (tn)
(and (tn-p tn)
(eq (sc-sb (tn-sc tn)) register-sb)))
(stack-p (tn)
(and (tn-p tn)
(sc-is tn control-stack)))
(source (vop)
(tn-ref-tn (vop-args vop)))
(dest (vop)
(tn-ref-tn (vop-results vop)))
(load-tn (vop)
(tn-ref-load-tn (vop-args vop)))
(suitable-offsets-p (tn1 tn2)
(and (= (abs (- (tn-offset tn1)
(tn-offset tn2)))
1)
(ldp-stp-offset-p (* (min (tn-offset tn1)
(tn-offset tn2))
n-word-bytes)
n-word-bits)))
(load-arg (x load-tn)
(sc-case x
((constant immediate control-stack)
(let ((load-tn (cond ((not (and used-load-tn
(location= used-load-tn load-tn)))
load-tn)
((sb-c::tn-reads load-tn)
(return-from load-arg))
(t
tmp-tn))))
(setf used-load-tn load-tn)
(sc-case x
(constant
(when (eq load-tn tmp-tn)
TMP - TN is not a descriptor
(return-from load-arg))
(lambda ()
(load-constant vop1 x load-tn)
load-tn))
(control-stack
(when (eq load-tn tmp-tn)
(return-from load-arg))
(lambda ()
(load-stack vop1 x load-tn)
load-tn))
(immediate
(cond ((eql (tn-value x) 0)
(setf used-load-tn nil)
(lambda () zr-tn))
(t
(lambda ()
(load-immediate vop1 x load-tn)
load-tn)))))))
(t
(setf used-load-tn x)
(lambda () x))))
(do-moves (source1 source2 dest1 dest2 &optional (fp cfp-tn)
fp-load-tn)
(cond ((and (stack-p dest1)
(stack-p dest2)
(not (location= dest1 source1))
(not (location= dest2 source2))
(or (not (eq fp cfp-tn))
(and (not (location= dest1 source2))
(not (location= dest2 source1))))
(suitable-offsets-p dest1 dest2))
(let (new-source1 new-source2)
(if (and (stack-p source1)
(stack-p source2)
Can load using LDP
(do-moves source1 source2
(setf new-source1 (load-tn vop1))
(setf new-source2
(cond ((not (location= (load-tn vop1) (load-tn vop2)))
(load-tn vop2))
((sc-is (load-tn vop2) descriptor-reg)
(return-from do-moves))
(t
tmp-tn)))))
(setf source1 new-source1
source2 new-source2)
Load one by one
(let ((load1 (load-arg source1 (load-tn vop1)))
(load2 (load-arg source2 (load-tn vop2))))
(unless (and load1 load2)
(return-from do-moves))
(setf source1 (funcall load1)
source2 (funcall load2)))))
(when (> (tn-offset dest1)
(tn-offset dest2))
(rotatef dest1 dest2)
(rotatef source1 source2))
(when fp-load-tn
(load-stack-tn fp-load-tn fp)
(setf fp fp-load-tn))
(inst stp source1 source2
(@ fp (tn-byte-offset dest1)))
t)
((and (stack-p source1)
(stack-p source2)
(register-p dest1)
(register-p dest2)
(not (location= dest1 dest2))
(suitable-offsets-p source1 source2))
(when (> (tn-offset source1)
(tn-offset source2))
(rotatef dest1 dest2)
(rotatef source1 source2))
(inst ldp dest1 dest2
(@ fp (tn-byte-offset source1)))
t))))
(case (sb-c::vop-name vop1)
(move
(do-moves (source vop1) (source vop2) (dest vop1) (dest vop2)))
(sb-c::move-operand
(cond ((and (equal (sb-c::vop-codegen-info vop1)
(sb-c::vop-codegen-info vop2))
(memq (car (sb-c::vop-codegen-info vop1))
'(load-stack store-stack)))
(do-moves (source vop1) (source vop2) (dest vop1) (dest vop2)))))
(move-arg
(let ((fp1 (tn-ref-tn (tn-ref-across (vop-args vop1))))
(fp2 (tn-ref-tn (tn-ref-across (vop-args vop2))))
(dest1 (dest vop1))
(dest2 (dest vop2)))
(when (eq fp1 fp2)
(do-moves (source vop1) (source vop2) (dest vop1) (dest vop2)
(if (and (stack-p dest1)
(stack-p dest2))
fp1
cfp-tn)
(tn-ref-load-tn (tn-ref-across (vop-args vop1)))))))))))
This VOP exists just to begin the lifetime of a TN that could n't
before this VOP is so we do n't need to do anything ( not that there
(define-vop (illegal-move)
(:args (x) (type))
(:results (y))
(:ignore y)
(:vop-var vop)
(:save-p :compute-only)
(:generator 666
(error-call vop 'object-not-type-error x type)))
ARG is a fixnum , so just shift it . We need a type restriction because some
(define-vop (move-to-word/fixnum)
(:args (x :scs (any-reg descriptor-reg)))
(:results (y :scs (signed-reg unsigned-reg)))
(:arg-types tagged-num)
(:note "fixnum untagging")
(:generator 1
(inst asr y x n-fixnum-tag-bits)))
(define-move-vop move-to-word/fixnum :move
(any-reg descriptor-reg) (signed-reg unsigned-reg))
(define-vop (move-to-word-c)
(:args (x :scs (constant)))
(:results (y :scs (signed-reg unsigned-reg)))
(:vop-var vop)
(:note "constant load")
(:generator 1
(cond ((sb-c::tn-leaf x)
(load-immediate-word y (tn-value x)))
(t
(load-constant vop x y)
(inst asr y y n-fixnum-tag-bits)))))
(define-move-vop move-to-word-c :move
(constant) (signed-reg unsigned-reg))
(define-vop (move-to-word/integer)
(:args (x :scs (descriptor-reg)))
(:result-refs results)
(:results (y :scs (signed-reg unsigned-reg)))
(:note "integer to untagged word coercion")
(:generator 4
#.(assert (= fixnum-tag-mask 1))
(when (types-equal-or-intersect (tn-ref-type results) (specifier-type 'fixnum))
(sc-case y
(signed-reg
(inst asr y x n-fixnum-tag-bits))
(unsigned-reg
(inst lsr y x n-fixnum-tag-bits)))
(inst tbz x 0 DONE))
(loadw y x bignum-digits-offset other-pointer-lowtag)
DONE))
(define-move-vop move-to-word/integer :move
(descriptor-reg) (signed-reg unsigned-reg))
(define-vop (move-from-word/fixnum)
(:args (x :scs (signed-reg unsigned-reg)))
(:results (y :scs (any-reg descriptor-reg)))
(:result-types tagged-num)
(:note "fixnum tagging")
(:generator 1
(inst lsl y x n-fixnum-tag-bits)))
(define-move-vop move-from-word/fixnum :move
(signed-reg unsigned-reg) (any-reg descriptor-reg))
(define-vop (move-from-signed)
(:args (arg :scs (signed-reg unsigned-reg) :target x))
(:results (y :scs (any-reg descriptor-reg)))
(:temporary (:scs (non-descriptor-reg) :from (:argument 0)) x)
(:temporary (:sc non-descriptor-reg :offset lr-offset) lr)
(:note "signed word to integer coercion")
(:generator 20
(move x arg)
(inst adds y x x)
(inst b :vc DONE)
(with-fixed-allocation (y lr bignum-widetag (1+ bignum-digits-offset)
:store-type-code nil)
TMP - TN has the untagged address coming from ALLOCATION
that way STP can be used on an aligned address .
LR has the widetag computed by WITH - FIXED - ALLOCATION
(storew-pair lr 0 x bignum-digits-offset tmp-tn))
DONE))
(define-move-vop move-from-signed :move
(signed-reg) (descriptor-reg))
(define-vop (move-from-fixnum+1)
(:args (x :scs (signed-reg unsigned-reg)))
(:results (y :scs (any-reg descriptor-reg)))
(:vop-var vop)
(:generator 4
(inst adds y x x)
(inst b :vc DONE)
(load-constant vop (emit-constant (1+ most-positive-fixnum))
y)
DONE))
(define-vop (move-from-fixnum-1 move-from-fixnum+1)
(:generator 4
(inst adds y x x)
(inst b :vc DONE)
(load-constant vop (emit-constant (1- most-negative-fixnum))
y)
DONE))
Check for fixnum , and possibly allocate one or two word bignum
(define-vop (move-from-unsigned)
(:args (arg :scs (signed-reg unsigned-reg) :target x))
(:results (y :scs (any-reg descriptor-reg)))
(:temporary (:scs (non-descriptor-reg) :from (:argument 0)) x)
(:temporary (:sc non-descriptor-reg :offset lr-offset) lr)
(:note "unsigned word to integer coercion")
(:generator 20
(move x arg)
(inst tst x (ash (1- (ash 1 (- n-word-bits
n-positive-fixnum-bits)))
n-positive-fixnum-bits))
(inst lsl y x n-fixnum-tag-bits)
(inst b :eq DONE)
(with-fixed-allocation
(y lr bignum-widetag (+ 2 bignum-digits-offset)
:store-type-code nil)
leaves LR containing the computed header value . In our
case , configured for a 2 - word bignum . If the sign bit in the
(inst tbnz x (1- n-word-bits) STORE)
(load-immediate-word lr (bignum-header-for-length 1))
STORE
(storew-pair lr 0 x bignum-digits-offset tmp-tn))
DONE))
(define-move-vop move-from-unsigned :move
(unsigned-reg) (descriptor-reg))
(define-vop (word-move)
(:args (x :target y
:scs (signed-reg unsigned-reg)
:load-if (not (location= x y))))
(:results (y :scs (signed-reg unsigned-reg)
:load-if (not (location= x y))))
(:note "word integer move")
(:generator 0
(move y x)))
(define-move-vop word-move :move
(signed-reg unsigned-reg) (signed-reg unsigned-reg))
(define-vop (move-word-arg)
(:args (x :target y
:scs (signed-reg unsigned-reg))
(fp :scs (any-reg)
:load-if (not (sc-is y signed-reg unsigned-reg))))
(:results (y))
(:note "word integer argument move")
(:generator 0
(sc-case y
((signed-reg unsigned-reg)
(move y x))
((signed-stack unsigned-stack)
(store-stack-offset x fp y)))))
(define-move-vop move-word-arg :move-arg
(descriptor-reg any-reg signed-reg unsigned-reg) (signed-reg unsigned-reg))
(define-move-vop move-arg :move-arg
(signed-reg unsigned-reg) (any-reg descriptor-reg))
(define-vop (move-conditional-result)
(:results (res :scs (descriptor-reg)))
(:info true)
(:generator 1
(move res null-tn)
(inst b done)
(emit-label true)
(load-symbol res t)
done))
|
df711dadbccef83b7b298c1e5a1a10fcefec120db8e3cee099533858aadf2e82 | timbod7/haskell-chart | Bars.hs | -----------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.Chart.Plot.Bars
Copyright : ( c ) 2006 , 2014
-- License : BSD-style (see chart/COPYRIGHT)
--
-- Bar Charts
--
# LANGUAGE TemplateHaskell #
module Graphics.Rendering.Chart.Plot.Bars(
PlotBars(..),
PlotBarsStyle(..),
PlotBarsSpacing(..),
PlotBarsAlignment(..),
BarsPlotValue(..),
plotBars,
plot_bars_style,
plot_bars_item_styles,
plot_bars_titles,
plot_bars_spacing,
plot_bars_alignment,
plot_bars_reference,
plot_bars_singleton_width,
plot_bars_values,
) where
import Control.Lens
import Control.Monad
import Data.List(nub,sort)
import Graphics.Rendering.Chart.Geometry hiding (x0, y0)
import Graphics.Rendering.Chart.Drawing
import Graphics.Rendering.Chart.Plot.Types
import Graphics.Rendering.Chart.Axis
import Data.Colour (opaque)
import Data.Colour.Names (black)
import Data.Default.Class
class PlotValue a => BarsPlotValue a where
barsReference :: a
barsAdd :: a -> a -> a
instance BarsPlotValue Double where
barsReference = 0
barsAdd = (+)
instance BarsPlotValue Int where
barsReference = 0
barsAdd = (+)
data PlotBarsStyle
= BarsStacked -- ^ Bars for a fixed x are stacked vertically
-- on top of each other.
| BarsClustered -- ^ Bars for a fixed x are put horizontally
-- beside each other.
deriving (Show)
data PlotBarsSpacing
= BarsFixWidth Double -- ^ All bars have the same width in pixels.
^ ( mw ) means make the gaps between
-- the bars equal to g, but with a minimum bar width
-- of mw
deriving (Show)
-- | How bars for a given (x,[y]) are aligned with respect to screen
-- coordinate corresponding to x (deviceX).
data PlotBarsAlignment = BarsLeft -- ^ The left edge of bars is at deviceX
| BarsCentered -- ^ Bars are centered around deviceX
| BarsRight -- ^ The right edge of bars is at deviceX
deriving (Show)
-- | Value describing how to plot a set of bars.
-- Note that the input data is typed [(x,[y])], ie for each x value
-- we plot several y values. Typically the size of each [y] list would
-- be the same.
data PlotBars x y = PlotBars {
-- | This value specifies whether each value from [y] should be
-- shown beside or above the previous value.
_plot_bars_style :: PlotBarsStyle,
-- | The style in which to draw each element of [y]. A fill style
-- is required, and if a linestyle is given, each bar will be
-- outlined.
_plot_bars_item_styles :: [ (FillStyle,Maybe LineStyle) ],
-- | The title of each element of [y]. These will be shown in the legend.
_plot_bars_titles :: [String],
-- | This value controls how the widths of the bars are
-- calculated. Either the widths of the bars, or the gaps between
-- them can be fixed.
_plot_bars_spacing :: PlotBarsSpacing,
-- | This value controls how bars for a fixed x are aligned with
-- respect to the device coordinate corresponding to x.
_plot_bars_alignment :: PlotBarsAlignment,
-- | The starting level for the chart (normally 0).
_plot_bars_reference :: y,
_plot_bars_singleton_width :: Double,
-- | The actual points to be plotted.
_plot_bars_values :: [ (x,[y]) ]
}
instance BarsPlotValue y => Default (PlotBars x y) where
def = PlotBars
{ _plot_bars_style = BarsClustered
, _plot_bars_item_styles = cycle istyles
, _plot_bars_titles = []
, _plot_bars_spacing = BarsFixGap 10 2
, _plot_bars_alignment = BarsCentered
, _plot_bars_values = []
, _plot_bars_singleton_width = 20
, _plot_bars_reference = barsReference
}
where
istyles = map mkstyle defaultColorSeq
mkstyle c = (solidFillStyle c, Just (solidLine 1.0 $ opaque black))
plotBars :: (BarsPlotValue y) => PlotBars x y -> Plot x y
plotBars p = Plot {
_plot_render = renderPlotBars p,
_plot_legend = zip (_plot_bars_titles p)
(map renderPlotLegendBars
(_plot_bars_item_styles p)),
_plot_all_points = allBarPoints p
}
renderPlotBars :: (BarsPlotValue y) => PlotBars x y -> PointMapFn x y -> BackendProgram ()
renderPlotBars p pmap = case _plot_bars_style p of
BarsClustered -> forM_ vals clusteredBars
BarsStacked -> forM_ vals stackedBars
where
clusteredBars (x,ys) = do
forM_ (zip3 [0,1..] ys styles) $ \(i, y, (fstyle,_)) ->
withFillStyle fstyle $
alignFillPath (barPath (offset i) x yref0 y)
>>= fillPath
forM_ (zip3 [0,1..] ys styles) $ \(i, y, (_,mlstyle)) ->
whenJust mlstyle $ \lstyle ->
withLineStyle lstyle $
alignStrokePath (barPath (offset i) x yref0 y)
>>= strokePath
offset = case _plot_bars_alignment p of
BarsLeft -> \i -> fromIntegral i * width
BarsRight -> \i -> fromIntegral (i-nys) * width
BarsCentered -> \i -> fromIntegral (2*i-nys) * width/2
stackedBars (x,ys) = do
let y2s = zip (yref0:stack ys) (stack ys)
let ofs = case _plot_bars_alignment p of
BarsLeft -> 0
BarsRight -> -width
BarsCentered -> -(width/2)
forM_ (zip y2s styles) $ \((y0,y1), (fstyle,_)) ->
withFillStyle fstyle $
alignFillPath (barPath ofs x y0 y1)
>>= fillPath
forM_ (zip y2s styles) $ \((y0,y1), (_,mlstyle)) ->
whenJust mlstyle $ \lstyle ->
withLineStyle lstyle $
alignStrokePath (barPath ofs x y0 y1)
>>= strokePath
barPath xos x y0 y1 = do
let (Point x' y') = pmap' (x,y1)
let (Point _ y0') = pmap' (x,y0)
rectPath (Rect (Point (x'+xos) y0') (Point (x'+xos+width) y'))
yref0 = _plot_bars_reference p
vals = _plot_bars_values p
width = case _plot_bars_spacing p of
BarsFixGap gap minw -> let w = max (minXInterval - gap) minw in
case _plot_bars_style p of
BarsClustered -> w / fromIntegral nys
BarsStacked -> w
BarsFixWidth width' -> width'
styles = _plot_bars_item_styles p
minXInterval = let diffs = zipWith (-) (tail mxs) mxs
in if null diffs
then _plot_bars_singleton_width p
else minimum diffs
where
xs = fst (allBarPoints p)
mxs = nub $ sort $ map mapX xs
nys = maximum [ length ys | (_,ys) <- vals ]
pmap' = mapXY pmap
mapX x = p_x (pmap' (x,barsReference))
whenJust :: (Monad m) => Maybe a -> (a -> m ()) -> m ()
whenJust (Just a) f = f a
whenJust _ _ = return ()
allBarPoints :: (BarsPlotValue y) => PlotBars x y -> ([x],[y])
allBarPoints p = case _plot_bars_style p of
BarsClustered -> ( [x| (x,_) <- pts], y0:concat [ys| (_,ys) <- pts] )
BarsStacked -> ( [x| (x,_) <- pts], y0:concat [stack ys | (_,ys) <- pts] )
where
pts = _plot_bars_values p
y0 = _plot_bars_reference p
stack :: (BarsPlotValue y) => [y] -> [y]
stack = scanl1 barsAdd
renderPlotLegendBars :: (FillStyle,Maybe LineStyle) -> Rect -> BackendProgram ()
renderPlotLegendBars (fstyle,_) r =
withFillStyle fstyle $
fillPath (rectPath r)
$( makeLenses ''PlotBars )
| null | https://raw.githubusercontent.com/timbod7/haskell-chart/8c5a823652ea1b4ec2adbced4a92a8161065ead6/chart/Graphics/Rendering/Chart/Plot/Bars.hs | haskell | ---------------------------------------------------------------------------
|
Module : Graphics.Rendering.Chart.Plot.Bars
License : BSD-style (see chart/COPYRIGHT)
Bar Charts
^ Bars for a fixed x are stacked vertically
on top of each other.
^ Bars for a fixed x are put horizontally
beside each other.
^ All bars have the same width in pixels.
the bars equal to g, but with a minimum bar width
of mw
| How bars for a given (x,[y]) are aligned with respect to screen
coordinate corresponding to x (deviceX).
^ The left edge of bars is at deviceX
^ Bars are centered around deviceX
^ The right edge of bars is at deviceX
| Value describing how to plot a set of bars.
Note that the input data is typed [(x,[y])], ie for each x value
we plot several y values. Typically the size of each [y] list would
be the same.
| This value specifies whether each value from [y] should be
shown beside or above the previous value.
| The style in which to draw each element of [y]. A fill style
is required, and if a linestyle is given, each bar will be
outlined.
| The title of each element of [y]. These will be shown in the legend.
| This value controls how the widths of the bars are
calculated. Either the widths of the bars, or the gaps between
them can be fixed.
| This value controls how bars for a fixed x are aligned with
respect to the device coordinate corresponding to x.
| The starting level for the chart (normally 0).
| The actual points to be plotted. | Copyright : ( c ) 2006 , 2014
# LANGUAGE TemplateHaskell #
module Graphics.Rendering.Chart.Plot.Bars(
PlotBars(..),
PlotBarsStyle(..),
PlotBarsSpacing(..),
PlotBarsAlignment(..),
BarsPlotValue(..),
plotBars,
plot_bars_style,
plot_bars_item_styles,
plot_bars_titles,
plot_bars_spacing,
plot_bars_alignment,
plot_bars_reference,
plot_bars_singleton_width,
plot_bars_values,
) where
import Control.Lens
import Control.Monad
import Data.List(nub,sort)
import Graphics.Rendering.Chart.Geometry hiding (x0, y0)
import Graphics.Rendering.Chart.Drawing
import Graphics.Rendering.Chart.Plot.Types
import Graphics.Rendering.Chart.Axis
import Data.Colour (opaque)
import Data.Colour.Names (black)
import Data.Default.Class
class PlotValue a => BarsPlotValue a where
barsReference :: a
barsAdd :: a -> a -> a
instance BarsPlotValue Double where
barsReference = 0
barsAdd = (+)
instance BarsPlotValue Int where
barsReference = 0
barsAdd = (+)
data PlotBarsStyle
deriving (Show)
data PlotBarsSpacing
^ ( mw ) means make the gaps between
deriving (Show)
deriving (Show)
data PlotBars x y = PlotBars {
_plot_bars_style :: PlotBarsStyle,
_plot_bars_item_styles :: [ (FillStyle,Maybe LineStyle) ],
_plot_bars_titles :: [String],
_plot_bars_spacing :: PlotBarsSpacing,
_plot_bars_alignment :: PlotBarsAlignment,
_plot_bars_reference :: y,
_plot_bars_singleton_width :: Double,
_plot_bars_values :: [ (x,[y]) ]
}
instance BarsPlotValue y => Default (PlotBars x y) where
def = PlotBars
{ _plot_bars_style = BarsClustered
, _plot_bars_item_styles = cycle istyles
, _plot_bars_titles = []
, _plot_bars_spacing = BarsFixGap 10 2
, _plot_bars_alignment = BarsCentered
, _plot_bars_values = []
, _plot_bars_singleton_width = 20
, _plot_bars_reference = barsReference
}
where
istyles = map mkstyle defaultColorSeq
mkstyle c = (solidFillStyle c, Just (solidLine 1.0 $ opaque black))
plotBars :: (BarsPlotValue y) => PlotBars x y -> Plot x y
plotBars p = Plot {
_plot_render = renderPlotBars p,
_plot_legend = zip (_plot_bars_titles p)
(map renderPlotLegendBars
(_plot_bars_item_styles p)),
_plot_all_points = allBarPoints p
}
renderPlotBars :: (BarsPlotValue y) => PlotBars x y -> PointMapFn x y -> BackendProgram ()
renderPlotBars p pmap = case _plot_bars_style p of
BarsClustered -> forM_ vals clusteredBars
BarsStacked -> forM_ vals stackedBars
where
clusteredBars (x,ys) = do
forM_ (zip3 [0,1..] ys styles) $ \(i, y, (fstyle,_)) ->
withFillStyle fstyle $
alignFillPath (barPath (offset i) x yref0 y)
>>= fillPath
forM_ (zip3 [0,1..] ys styles) $ \(i, y, (_,mlstyle)) ->
whenJust mlstyle $ \lstyle ->
withLineStyle lstyle $
alignStrokePath (barPath (offset i) x yref0 y)
>>= strokePath
offset = case _plot_bars_alignment p of
BarsLeft -> \i -> fromIntegral i * width
BarsRight -> \i -> fromIntegral (i-nys) * width
BarsCentered -> \i -> fromIntegral (2*i-nys) * width/2
stackedBars (x,ys) = do
let y2s = zip (yref0:stack ys) (stack ys)
let ofs = case _plot_bars_alignment p of
BarsLeft -> 0
BarsRight -> -width
BarsCentered -> -(width/2)
forM_ (zip y2s styles) $ \((y0,y1), (fstyle,_)) ->
withFillStyle fstyle $
alignFillPath (barPath ofs x y0 y1)
>>= fillPath
forM_ (zip y2s styles) $ \((y0,y1), (_,mlstyle)) ->
whenJust mlstyle $ \lstyle ->
withLineStyle lstyle $
alignStrokePath (barPath ofs x y0 y1)
>>= strokePath
barPath xos x y0 y1 = do
let (Point x' y') = pmap' (x,y1)
let (Point _ y0') = pmap' (x,y0)
rectPath (Rect (Point (x'+xos) y0') (Point (x'+xos+width) y'))
yref0 = _plot_bars_reference p
vals = _plot_bars_values p
width = case _plot_bars_spacing p of
BarsFixGap gap minw -> let w = max (minXInterval - gap) minw in
case _plot_bars_style p of
BarsClustered -> w / fromIntegral nys
BarsStacked -> w
BarsFixWidth width' -> width'
styles = _plot_bars_item_styles p
minXInterval = let diffs = zipWith (-) (tail mxs) mxs
in if null diffs
then _plot_bars_singleton_width p
else minimum diffs
where
xs = fst (allBarPoints p)
mxs = nub $ sort $ map mapX xs
nys = maximum [ length ys | (_,ys) <- vals ]
pmap' = mapXY pmap
mapX x = p_x (pmap' (x,barsReference))
whenJust :: (Monad m) => Maybe a -> (a -> m ()) -> m ()
whenJust (Just a) f = f a
whenJust _ _ = return ()
allBarPoints :: (BarsPlotValue y) => PlotBars x y -> ([x],[y])
allBarPoints p = case _plot_bars_style p of
BarsClustered -> ( [x| (x,_) <- pts], y0:concat [ys| (_,ys) <- pts] )
BarsStacked -> ( [x| (x,_) <- pts], y0:concat [stack ys | (_,ys) <- pts] )
where
pts = _plot_bars_values p
y0 = _plot_bars_reference p
stack :: (BarsPlotValue y) => [y] -> [y]
stack = scanl1 barsAdd
renderPlotLegendBars :: (FillStyle,Maybe LineStyle) -> Rect -> BackendProgram ()
renderPlotLegendBars (fstyle,_) r =
withFillStyle fstyle $
fillPath (rectPath r)
$( makeLenses ''PlotBars )
|
ac366cd24fe6c6d26041a91b3b14a48f6c401e1a6933a5fc525e1140659bba5f | malcolmsparks/clj-logging-config | test_log4j.clj | clj - logging - config - Logging configuration for Clojure .
by
Copyright ( c ) . All rights reserved .
The use and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (-1.0.php) which can
;; be found in the file epl-v10.html at the root of this distribution. By using
;; this software in any fashion, you are agreeing to be bound by the terms of
;; this license. You must not remove this notice, or any other, from this
;; software.
(ns clj-logging-config.log4j.test-log4j
(:use clojure.test
clojure.tools.logging
clj-logging-config.log4j)
(:require [clojure.java.io :as io]))
Copied from clojure.contrib.with - ns
(defmacro with-ns
"Evaluates body in another namespace. ns is either a namespace
object or a symbol. This makes it possible to define functions in
namespaces other than the current one."
[ns & body]
`(binding [*ns* (the-ns ~ns)]
~@(map (fn [form] `(eval '~form)) body)))
Copied from clojure.contrib.with - ns
(defmacro with-temp-ns
"Evaluates body in an anonymous namespace, which is then immediately
removed. The temporary namespace will 'refer' clojure.core."
[& body]
`(do (create-ns 'sym#)
(let [result# (with-ns 'sym#
(clojure.core/refer-clojure)
~@body)]
(remove-ns 'sym#)
result#)))
(defmacro capture-stdout [& body]
`(let [out# System/out
baos# (java.io.ByteArrayOutputStream.)
tempout# (java.io.PrintStream. baos#)]
(try
(System/setOut tempout#)
~@body
(String. (.toByteArray baos#))
(finally
(System/setOut out#)))))
(defmacro dolog [& body]
`(do (reset-logging!)
(let [ns# (create-ns (symbol "test"))]
(with-ns ns#
(clojure.core/refer-clojure)
(use 'clojure.tools.logging 'clj-logging-config.log4j)
~@body))))
(defmacro expect [expected & body]
`(is (= ~expected (capture-stdout (dolog ~@body)))))
(use-fixtures :each (fn [f]
(reset-logging!)
(f)))
(deftest test-logging
(testing "Default logging"
(expect "INFO - Here is a log message\n"
(set-logger!)
(info "Here is a log message"))
(expect "WARN - Here is a warning\n"
(set-logger!)
(warn "Here is a warning"))
(expect ""
(set-logger!)
(debug "Debug messages are hidden by default")))
(testing "Logging at the DEBUG level"
(expect "DEBUG - Debug level messages are now shown\n"
(set-logger! "test" :level org.apache.log4j.Level/DEBUG)
(debug "Debug level messages are now shown")))
(testing "Levels can also be specified with keywords"
(expect ""
(set-logger! "test" :level :warn)
(debug "Debug messages are hidden"))
(expect ""
(set-logger! "test" :level :warn)
(info "So are log messages"))
(expect "WARN - Only warnings\n"
(set-logger! "test" :level :warn)
(warn "Only warnings"))
(expect "ERROR - And errors\n"
(set-logger! "test" :level :warn)
(error "And errors")))
(testing "Setting a pattern for the PatternLayout"
(expect "Here is a log message\n"
(set-logger! "test"
:pattern org.apache.log4j.PatternLayout/DEFAULT_CONVERSION_PATTERN)
(info "Here is a log message")))
(testing "Setting a custom pattern for the PatternLayout"
(expect "[INFO] - Here is a log message"
(set-logger! "test" :pattern "[%p] - %m")
(info "Here is a log message")))
(testing "Setting a custom layout"
(expect "INFO - Here is a log message\n"
(set-logger! "test" :layout (org.apache.log4j.SimpleLayout.))
(info "Here is a log message")))
(comment (testing "We can even use a Clojure function as a layout"
(expect "INFO: Try doing this in log4j.properties!"
(set-logger! "test" :layout (fn [ev]
(format "%s: %s" (:level ev) (:message ev))))
(info "Try doing this in log4j.properties!"))))
(testing "But we can't set a :layout and a :pattern (because a :pattern implies a org.apache.log4j.PatternLayout)"
(is (thrown? Exception (set-logger! "test" :pattern "%m" :layout (org.apache.log4j.SimpleLayout.)))))
One of the advantages of hosting Clojure on the JVM is that you can ( and
;; should) make use of functionality that already exists rather than
re - implementing it in Clojure .
(testing "Setting an appender"
(expect ""
(set-logger! "test" :out (org.apache.log4j.RollingFileAppender.))))
But sometimes we want to quickly implement our own custom appender in Clojure
which is painful to do in Java . This example uses println for testing
;; purposes but there's no reason it couldn't do something more complex (like
;; send a tweet).
(testing "Set a custom appender in Clojure"
(is (= ">>> WARN - Alert!"
(dolog
(let [out (java.io.StringWriter.)]
(binding [*out* out]
(set-logger! "test"
:out (fn [ev]
(println (format ">>> %s - %s" (:level ev) (:message ev)))))
(warn "Alert!"))
(.readLine ^java.io.BufferedReader (clojure.java.io/reader (java.io.StringReader. (str out)))))))))
;; Filtering logging messages based on some complex criteria is something
;; that's much easier in a functional language.
(testing "Filter out messages that contain 'password'"
(expect "The user is billy\nThe name is fred\n"
(set-logger! "test"
:pattern "%m%n"
:filter (fn [ev] (not (.contains ^String (:message ev) "password"))))
(info "The user is billy")
(info "The password is nighthawk")
(info "The name is fred")))
(testing "with-logging-context with null values does not throw exception"
(set-logger! "test")
(with-logging-context {:kikka 123
:kukka nil}
(info "safe logging here"))))
| null | https://raw.githubusercontent.com/malcolmsparks/clj-logging-config/d474a3cda79890bd8a8d41edb51f7c1b2ec40523/src/test/clojure/clj_logging_config/log4j/test_log4j.clj | clojure | Public License 1.0 (-1.0.php) which can
be found in the file epl-v10.html at the root of this distribution. By using
this software in any fashion, you are agreeing to be bound by the terms of
this license. You must not remove this notice, or any other, from this
software.
should) make use of functionality that already exists rather than
purposes but there's no reason it couldn't do something more complex (like
send a tweet).
Filtering logging messages based on some complex criteria is something
that's much easier in a functional language. | clj - logging - config - Logging configuration for Clojure .
by
Copyright ( c ) . All rights reserved .
The use and distribution terms for this software are covered by the Eclipse
(ns clj-logging-config.log4j.test-log4j
(:use clojure.test
clojure.tools.logging
clj-logging-config.log4j)
(:require [clojure.java.io :as io]))
Copied from clojure.contrib.with - ns
(defmacro with-ns
"Evaluates body in another namespace. ns is either a namespace
object or a symbol. This makes it possible to define functions in
namespaces other than the current one."
[ns & body]
`(binding [*ns* (the-ns ~ns)]
~@(map (fn [form] `(eval '~form)) body)))
Copied from clojure.contrib.with - ns
(defmacro with-temp-ns
"Evaluates body in an anonymous namespace, which is then immediately
removed. The temporary namespace will 'refer' clojure.core."
[& body]
`(do (create-ns 'sym#)
(let [result# (with-ns 'sym#
(clojure.core/refer-clojure)
~@body)]
(remove-ns 'sym#)
result#)))
(defmacro capture-stdout [& body]
`(let [out# System/out
baos# (java.io.ByteArrayOutputStream.)
tempout# (java.io.PrintStream. baos#)]
(try
(System/setOut tempout#)
~@body
(String. (.toByteArray baos#))
(finally
(System/setOut out#)))))
(defmacro dolog [& body]
`(do (reset-logging!)
(let [ns# (create-ns (symbol "test"))]
(with-ns ns#
(clojure.core/refer-clojure)
(use 'clojure.tools.logging 'clj-logging-config.log4j)
~@body))))
(defmacro expect [expected & body]
`(is (= ~expected (capture-stdout (dolog ~@body)))))
(use-fixtures :each (fn [f]
(reset-logging!)
(f)))
(deftest test-logging
(testing "Default logging"
(expect "INFO - Here is a log message\n"
(set-logger!)
(info "Here is a log message"))
(expect "WARN - Here is a warning\n"
(set-logger!)
(warn "Here is a warning"))
(expect ""
(set-logger!)
(debug "Debug messages are hidden by default")))
(testing "Logging at the DEBUG level"
(expect "DEBUG - Debug level messages are now shown\n"
(set-logger! "test" :level org.apache.log4j.Level/DEBUG)
(debug "Debug level messages are now shown")))
(testing "Levels can also be specified with keywords"
(expect ""
(set-logger! "test" :level :warn)
(debug "Debug messages are hidden"))
(expect ""
(set-logger! "test" :level :warn)
(info "So are log messages"))
(expect "WARN - Only warnings\n"
(set-logger! "test" :level :warn)
(warn "Only warnings"))
(expect "ERROR - And errors\n"
(set-logger! "test" :level :warn)
(error "And errors")))
(testing "Setting a pattern for the PatternLayout"
(expect "Here is a log message\n"
(set-logger! "test"
:pattern org.apache.log4j.PatternLayout/DEFAULT_CONVERSION_PATTERN)
(info "Here is a log message")))
(testing "Setting a custom pattern for the PatternLayout"
(expect "[INFO] - Here is a log message"
(set-logger! "test" :pattern "[%p] - %m")
(info "Here is a log message")))
(testing "Setting a custom layout"
(expect "INFO - Here is a log message\n"
(set-logger! "test" :layout (org.apache.log4j.SimpleLayout.))
(info "Here is a log message")))
(comment (testing "We can even use a Clojure function as a layout"
(expect "INFO: Try doing this in log4j.properties!"
(set-logger! "test" :layout (fn [ev]
(format "%s: %s" (:level ev) (:message ev))))
(info "Try doing this in log4j.properties!"))))
(testing "But we can't set a :layout and a :pattern (because a :pattern implies a org.apache.log4j.PatternLayout)"
(is (thrown? Exception (set-logger! "test" :pattern "%m" :layout (org.apache.log4j.SimpleLayout.)))))
One of the advantages of hosting Clojure on the JVM is that you can ( and
re - implementing it in Clojure .
(testing "Setting an appender"
(expect ""
(set-logger! "test" :out (org.apache.log4j.RollingFileAppender.))))
But sometimes we want to quickly implement our own custom appender in Clojure
which is painful to do in Java . This example uses println for testing
(testing "Set a custom appender in Clojure"
(is (= ">>> WARN - Alert!"
(dolog
(let [out (java.io.StringWriter.)]
(binding [*out* out]
(set-logger! "test"
:out (fn [ev]
(println (format ">>> %s - %s" (:level ev) (:message ev)))))
(warn "Alert!"))
(.readLine ^java.io.BufferedReader (clojure.java.io/reader (java.io.StringReader. (str out)))))))))
(testing "Filter out messages that contain 'password'"
(expect "The user is billy\nThe name is fred\n"
(set-logger! "test"
:pattern "%m%n"
:filter (fn [ev] (not (.contains ^String (:message ev) "password"))))
(info "The user is billy")
(info "The password is nighthawk")
(info "The name is fred")))
(testing "with-logging-context with null values does not throw exception"
(set-logger! "test")
(with-logging-context {:kikka 123
:kukka nil}
(info "safe logging here"))))
|
a3f08289510287dc8d22ecd13d8f1e13455ea53dda497c8cabab06bd43f74351 | openmusic-project/openmusic | cocoa.lisp | -*- Mode : Lisp ; rcs - header : " $ Header : /hope / lwhope1 - cam / hope.0 / compound/61 / LISPopengl / RCS / cocoa.lisp , v 1.8.2.2 2021/11/22 20:35:11 " -*-
Copyright ( c ) 1987 - -2021 LispWorks Ltd. All rights reserved .
Support for OpenGL with CAPI / Cocoa .
;; Symbols in the CAPI-COCOA-LIB package are not part of a supported API.
(in-package "OPENGL")
(defun opengl-pane-representation-view (rep)
(capi-cocoa-lib::representation-main-view rep))
(defstruct cocoa-context
context
pixel-format
set-view)
(defmethod %make-context ((rep capi-cocoa-lib::output-pane-representation)
opengl-configuration)
(let* ((view (opengl-pane-representation-view rep))
(pixel-format (choose-cocoa-pixel-format
view
opengl-configuration)))
(if pixel-format
(let ((nscontext (objc:invoke (objc:invoke "NSOpenGLContext" "alloc")
"initWithFormat:shareContext:"
pixel-format
nil)))
;; Invoking setView here does not work for some reason so do it in
;; %start-rendering using the set-view slot instead.
#+comment
(objc:invoke nscontext "setView:" view)
(make-cocoa-context :context nscontext
:pixel-format pixel-format
:set-view view))
(error "Can't make context for ~s.~%Pixel-format not set"
opengl-configuration))))
(defmethod %start-rendering ((rep capi-cocoa-lib::output-pane-representation)
context)
(let ((nscontext (cocoa-context-context context)))
(when (objc:null-objc-pointer-p (objc:invoke nscontext "view"))
(objc:invoke nscontext "setView:" (cocoa-context-set-view context)))
(objc:invoke nscontext "makeCurrentContext")
t))
(defmethod %stop-rendering ((rep capi-cocoa-lib::output-pane-representation))
(objc:invoke "NSOpenGLContext" "clearCurrentContext")
t)
(defmethod %swap-buffers ((rep capi-cocoa-lib::output-pane-representation)
context)
(let ((nscontext (cocoa-context-context context)))
(objc:invoke nscontext "flushBuffer")
t))
(defmethod %free-opengl-resources ((rep capi-cocoa-lib::output-pane-representation)
context)
(when context
(let ((nscontext (cocoa-context-context context)))
(objc:invoke nscontext "clearDrawable")
(objc:release nscontext)
(objc:release (cocoa-context-pixel-format context))))
t)
(defmethod %resize-opengl-context ((rep capi-cocoa-lib::output-pane-representation)
context width height)
(declare (ignore width height))
(when context
(let ((nscontext (cocoa-context-context context)))
(objc:invoke nscontext "update"))))
By returning NIL , this method blocks any redisplay calls , which
otherwise errors .
(defmethod capi-cocoa-lib::output-pane-representation-draws-p
((pane opengl-pane) representation &optional force-p)
nil)
(defun cocoa-full-gl-viewport-bounds (rep)
;; This assumes all view transformations are translations.
(let* ((view (opengl-pane-representation-view rep))
(frame (objc:invoke view "frame"))
(dx (aref frame 0))
(dy (aref frame 1)))
(let ((superview view))
(loop (setq superview (objc:invoke superview "superview"))
(when (objc:null-objc-pointer-p superview) (return))
(let ((bounds (objc:invoke superview "bounds")))
(decf dx (aref bounds 0))
(decf dy (aref bounds 1)))))
(values (min 0 (floor dx))
(min 0 (floor dy))
(floor (aref frame 2))
(floor (aref frame 3)))))
(defmethod %update-opengl-pane-after-scrolling ((rep capi-cocoa-lib::output-pane-representation)
context)
(when context
(let ((nscontext (cocoa-context-context context)))
(objc:invoke nscontext "update")))
(multiple-value-bind (x y width height)
(cocoa-full-gl-viewport-bounds rep)
(opengl:gl-viewport x y width height)
(opengl:gl-matrix-mode opengl:*gl-projection*)
(opengl:gl-load-identity)))
(defmethod %describe-configuration ((rep capi-cocoa-lib::output-pane-representation)
context &optional (stream *standard-output*) collectp)
(let ((results (descibe-cocoa-pixel-format
(cocoa-context-pixel-format context))))
(if collectp
results
(format stream
"~&Color buffer size : ~d~%Uses ~:[Color Index~;RGBA~]~%Is ~:[single~;double~]-buffered~@[~%Accumulator buffer size (per channel) = ~d bits~]~@[~%Depth buffer size = ~d bits~]~@[~%Stencil buffer size = ~d bits~]~@[~%Has ~d aux buffers~]"
(getf results :buffer-size)
(getf results :rgba)
(getf results :double-buffer)
(getf results :accum)
(getf results :depth-buffer)
(getf results :stencil-size)
(getf results :aux)))))
;; NSOpenGLPixelFormatAttribute
(defconstant ns-open-gl-pfa-all-renderers 1)
(defconstant ns-open-gl-pfa-double-buffer 5)
(defconstant ns-open-gl-pfa-stereo 6)
(defconstant ns-open-gl-pfa-aux-buffers 7)
(defconstant ns-open-gl-pfa-color-size 8)
(defconstant ns-open-gl-pfa-alpha-size 11)
(defconstant ns-open-gl-pfa-depth-size 12)
(defconstant ns-open-gl-pfa-stencil-size 13)
(defconstant ns-open-gl-pfa-accum-size 14)
(defconstant ns-open-gl-pfa-minimum-policy 51)
(defconstant ns-open-gl-pfa-maximum-policy 52)
(defconstant ns-open-gl-pfa-off-screen 53)
(defconstant ns-open-gl-pfa-full-screen 54)
(defconstant ns-open-gl-pfa-sample-buffers 55)
(defconstant ns-open-gl-pfa-samples 56)
(defconstant ns-open-gl-pfa-aux-depth-stencil 57)
> = 10.4
> = 10.4
> = 10.4
> = 10.4
(defconstant ns-open-gl-pfa-renderer-id 70)
(defconstant ns-open-gl-pfa-single-renderer 71)
(defconstant ns-open-gl-pfa-no-recovery 72)
(defconstant ns-open-gl-pfa-accelerated 73)
(defconstant ns-open-gl-pfa-closest-policy 74)
(defconstant ns-open-gl-pfa-robust 75)
(defconstant ns-open-gl-pfa-backing-store 76)
(defconstant ns-open-gl-pfa-mp-safe 78)
(defconstant ns-open-gl-pfa-window 80)
(defconstant ns-open-gl-pfa-multi-screen 81)
(defconstant ns-open-gl-pfa-compliant 83)
(defconstant ns-open-gl-pfa-screen-mask 84)
> = 10.3
> = 10.6
> = 10.5
> = 10.6
(defconstant ns-open-gl-pfa-virtual-screen-count 128)
(defun ns-open-gl-pixel-format-attribute-type ()
(if (> (floor (cocoa:ns-app-kit-version-number))
cocoa:ns-app-kit-version-number-10_4)
'(:unsigned :int)
':int))
(defun choose-cocoa-pixel-format (view configuration)
"Returns the NSOpenGLPixelFormat for rep which supports the
requested configuration. Returns NIL if it fails.
Configuration is a plist with the following allowed
indicators:
:double-buffer, :double-buffered, - synonyms, value T or NIL."
(declare (ignorable view))
(fli:with-dynamic-foreign-objects ()
(let* ((attributes-list
(nconc (and (or (getf configuration :double-buffer)
(getf configuration :double-buffered))
(list ns-open-gl-pfa-double-buffer))
(let ((depth-buffer (getf configuration :depth-buffer)))
(and depth-buffer
(list ns-open-gl-pfa-depth-size depth-buffer)))
(list 0)))
(attributes (fli:allocate-dynamic-foreign-object
:type (ns-open-gl-pixel-format-attribute-type)
:initial-contents attributes-list)))
(let ((format (objc:invoke (objc:invoke "NSOpenGLPixelFormat" "alloc")
"initWithAttributes:"
attributes)))
(if (objc:null-objc-pointer-p format)
nil
format)))))
(defun pixel-format-attribute-value (pixel-format
attribute
&optional screen)
(fli:with-dynamic-foreign-objects ()
(let ((value (fli:allocate-dynamic-foreign-object
:type :int)))
(objc:invoke pixel-format "getValues:forAttribute:forVirtualScreen:"
value ; this is an out parameter
attribute
(or screen 0))
(fli:dereference value))))
(defun descibe-cocoa-pixel-format (pixel-format)
(list :double-buffer (not (zerop (pixel-format-attribute-value
pixel-format
ns-open-gl-pfa-double-buffer)))
:depth-buffer (pixel-format-attribute-value
pixel-format
ns-open-gl-pfa-depth-size)
))
| null | https://raw.githubusercontent.com/openmusic-project/openmusic/02d1ffa81d096df1006c38c145918480f1b78065/OPENMUSIC/code/api/externals/OpenGL/opengl-lw/cocoa.lisp | lisp | rcs - header : " $ Header : /hope / lwhope1 - cam / hope.0 / compound/61 / LISPopengl / RCS / cocoa.lisp , v 1.8.2.2 2021/11/22 20:35:11 " -*-
Symbols in the CAPI-COCOA-LIB package are not part of a supported API.
Invoking setView here does not work for some reason so do it in
%start-rendering using the set-view slot instead.
This assumes all view transformations are translations.
NSOpenGLPixelFormatAttribute
this is an out parameter |
Copyright ( c ) 1987 - -2021 LispWorks Ltd. All rights reserved .
Support for OpenGL with CAPI / Cocoa .
(in-package "OPENGL")
(defun opengl-pane-representation-view (rep)
(capi-cocoa-lib::representation-main-view rep))
(defstruct cocoa-context
context
pixel-format
set-view)
(defmethod %make-context ((rep capi-cocoa-lib::output-pane-representation)
opengl-configuration)
(let* ((view (opengl-pane-representation-view rep))
(pixel-format (choose-cocoa-pixel-format
view
opengl-configuration)))
(if pixel-format
(let ((nscontext (objc:invoke (objc:invoke "NSOpenGLContext" "alloc")
"initWithFormat:shareContext:"
pixel-format
nil)))
#+comment
(objc:invoke nscontext "setView:" view)
(make-cocoa-context :context nscontext
:pixel-format pixel-format
:set-view view))
(error "Can't make context for ~s.~%Pixel-format not set"
opengl-configuration))))
(defmethod %start-rendering ((rep capi-cocoa-lib::output-pane-representation)
context)
(let ((nscontext (cocoa-context-context context)))
(when (objc:null-objc-pointer-p (objc:invoke nscontext "view"))
(objc:invoke nscontext "setView:" (cocoa-context-set-view context)))
(objc:invoke nscontext "makeCurrentContext")
t))
(defmethod %stop-rendering ((rep capi-cocoa-lib::output-pane-representation))
(objc:invoke "NSOpenGLContext" "clearCurrentContext")
t)
(defmethod %swap-buffers ((rep capi-cocoa-lib::output-pane-representation)
context)
(let ((nscontext (cocoa-context-context context)))
(objc:invoke nscontext "flushBuffer")
t))
(defmethod %free-opengl-resources ((rep capi-cocoa-lib::output-pane-representation)
context)
(when context
(let ((nscontext (cocoa-context-context context)))
(objc:invoke nscontext "clearDrawable")
(objc:release nscontext)
(objc:release (cocoa-context-pixel-format context))))
t)
(defmethod %resize-opengl-context ((rep capi-cocoa-lib::output-pane-representation)
context width height)
(declare (ignore width height))
(when context
(let ((nscontext (cocoa-context-context context)))
(objc:invoke nscontext "update"))))
By returning NIL , this method blocks any redisplay calls , which
otherwise errors .
(defmethod capi-cocoa-lib::output-pane-representation-draws-p
((pane opengl-pane) representation &optional force-p)
nil)
(defun cocoa-full-gl-viewport-bounds (rep)
(let* ((view (opengl-pane-representation-view rep))
(frame (objc:invoke view "frame"))
(dx (aref frame 0))
(dy (aref frame 1)))
(let ((superview view))
(loop (setq superview (objc:invoke superview "superview"))
(when (objc:null-objc-pointer-p superview) (return))
(let ((bounds (objc:invoke superview "bounds")))
(decf dx (aref bounds 0))
(decf dy (aref bounds 1)))))
(values (min 0 (floor dx))
(min 0 (floor dy))
(floor (aref frame 2))
(floor (aref frame 3)))))
(defmethod %update-opengl-pane-after-scrolling ((rep capi-cocoa-lib::output-pane-representation)
context)
(when context
(let ((nscontext (cocoa-context-context context)))
(objc:invoke nscontext "update")))
(multiple-value-bind (x y width height)
(cocoa-full-gl-viewport-bounds rep)
(opengl:gl-viewport x y width height)
(opengl:gl-matrix-mode opengl:*gl-projection*)
(opengl:gl-load-identity)))
(defmethod %describe-configuration ((rep capi-cocoa-lib::output-pane-representation)
context &optional (stream *standard-output*) collectp)
(let ((results (descibe-cocoa-pixel-format
(cocoa-context-pixel-format context))))
(if collectp
results
(format stream
"~&Color buffer size : ~d~%Uses ~:[Color Index~;RGBA~]~%Is ~:[single~;double~]-buffered~@[~%Accumulator buffer size (per channel) = ~d bits~]~@[~%Depth buffer size = ~d bits~]~@[~%Stencil buffer size = ~d bits~]~@[~%Has ~d aux buffers~]"
(getf results :buffer-size)
(getf results :rgba)
(getf results :double-buffer)
(getf results :accum)
(getf results :depth-buffer)
(getf results :stencil-size)
(getf results :aux)))))
(defconstant ns-open-gl-pfa-all-renderers 1)
(defconstant ns-open-gl-pfa-double-buffer 5)
(defconstant ns-open-gl-pfa-stereo 6)
(defconstant ns-open-gl-pfa-aux-buffers 7)
(defconstant ns-open-gl-pfa-color-size 8)
(defconstant ns-open-gl-pfa-alpha-size 11)
(defconstant ns-open-gl-pfa-depth-size 12)
(defconstant ns-open-gl-pfa-stencil-size 13)
(defconstant ns-open-gl-pfa-accum-size 14)
(defconstant ns-open-gl-pfa-minimum-policy 51)
(defconstant ns-open-gl-pfa-maximum-policy 52)
(defconstant ns-open-gl-pfa-off-screen 53)
(defconstant ns-open-gl-pfa-full-screen 54)
(defconstant ns-open-gl-pfa-sample-buffers 55)
(defconstant ns-open-gl-pfa-samples 56)
(defconstant ns-open-gl-pfa-aux-depth-stencil 57)
> = 10.4
> = 10.4
> = 10.4
> = 10.4
(defconstant ns-open-gl-pfa-renderer-id 70)
(defconstant ns-open-gl-pfa-single-renderer 71)
(defconstant ns-open-gl-pfa-no-recovery 72)
(defconstant ns-open-gl-pfa-accelerated 73)
(defconstant ns-open-gl-pfa-closest-policy 74)
(defconstant ns-open-gl-pfa-robust 75)
(defconstant ns-open-gl-pfa-backing-store 76)
(defconstant ns-open-gl-pfa-mp-safe 78)
(defconstant ns-open-gl-pfa-window 80)
(defconstant ns-open-gl-pfa-multi-screen 81)
(defconstant ns-open-gl-pfa-compliant 83)
(defconstant ns-open-gl-pfa-screen-mask 84)
> = 10.3
> = 10.6
> = 10.5
> = 10.6
(defconstant ns-open-gl-pfa-virtual-screen-count 128)
(defun ns-open-gl-pixel-format-attribute-type ()
(if (> (floor (cocoa:ns-app-kit-version-number))
cocoa:ns-app-kit-version-number-10_4)
'(:unsigned :int)
':int))
(defun choose-cocoa-pixel-format (view configuration)
"Returns the NSOpenGLPixelFormat for rep which supports the
requested configuration. Returns NIL if it fails.
Configuration is a plist with the following allowed
indicators:
:double-buffer, :double-buffered, - synonyms, value T or NIL."
(declare (ignorable view))
(fli:with-dynamic-foreign-objects ()
(let* ((attributes-list
(nconc (and (or (getf configuration :double-buffer)
(getf configuration :double-buffered))
(list ns-open-gl-pfa-double-buffer))
(let ((depth-buffer (getf configuration :depth-buffer)))
(and depth-buffer
(list ns-open-gl-pfa-depth-size depth-buffer)))
(list 0)))
(attributes (fli:allocate-dynamic-foreign-object
:type (ns-open-gl-pixel-format-attribute-type)
:initial-contents attributes-list)))
(let ((format (objc:invoke (objc:invoke "NSOpenGLPixelFormat" "alloc")
"initWithAttributes:"
attributes)))
(if (objc:null-objc-pointer-p format)
nil
format)))))
(defun pixel-format-attribute-value (pixel-format
attribute
&optional screen)
(fli:with-dynamic-foreign-objects ()
(let ((value (fli:allocate-dynamic-foreign-object
:type :int)))
(objc:invoke pixel-format "getValues:forAttribute:forVirtualScreen:"
attribute
(or screen 0))
(fli:dereference value))))
(defun descibe-cocoa-pixel-format (pixel-format)
(list :double-buffer (not (zerop (pixel-format-attribute-value
pixel-format
ns-open-gl-pfa-double-buffer)))
:depth-buffer (pixel-format-attribute-value
pixel-format
ns-open-gl-pfa-depth-size)
))
|
5dd1f57e5368f6b080095e3e0b83c6ddd626a3135082a19032465ec876026587 | sharkdp/yinsh | Floyd.hs | | Simply the best AI for Yinsh , seriously .
module Floyd ( aiFloyd
, mhNumber
, rhRingMoves
, rhConnected
, rhControlledMarkers
, rhCombined
, rhZero
)
where
import AI
import Yinsh
TODO : adjust numbers : 5 , 10
floydHeuristic :: Floyd -> AIValue
floydHeuristic ai | points' W >= pointsForWin = hugeNumber
| points' B >= pointsForWin = -hugeNumber
| otherwise = value W - value B
where gs' = getGamestate ai
board' = board gs'
ap' = activePlayer gs'
tm' = turnMode gs'
points W = pointsW gs'
points B = pointsB gs'
points' p = points p + futurePoints p
If we are in RemoveRun phase , already include the point for the
-- active player.
If we are is WaitRemoveRun , the * opponent * of the current player
will necessarily have one more point next turn .
futurePoints p = case tm' of
(RemoveRun _) -> if ap' == p then 1 else 0
(WaitRemoveRun _) -> if ap' == p then 0 else 1
_ -> 0
valuePoints p = 100000 * points' p
valueMarkers = markerH ai
valueRings = ringH ai
value p = valuePoints p
+ valueMarkers board' p
+ valueRings board' p
type MarkerHeuristic = Board -> Player -> AIValue
type RingHeuristic = Board -> Player -> AIValue
mhNumber :: MarkerHeuristic
mhNumber b p = (10 *) $ length $ markers p b
rhRingMoves :: RingHeuristic
rhRingMoves b p = (1 *) $ sum $ map (length . ringMoves b) $ rings p b
rhConnected :: RingHeuristic
rhConnected b p = (1 *) $ length $ filter connectedToRings coords
where connectedToRings c = any (c `connected`) (rings p b)
rhControlledMarkers :: RingHeuristic
rhControlledMarkers b p = sum $ map controlledM (rings p b)
where controlledM :: YCoord -> Int
controlledM start = sum $ map markersBetween endPos
where endPos = ringMoves b start
markersBetween end = length $ filter (isMarker b) $ coordLine start end
rhCombined :: [(Int, RingHeuristic)] -> RingHeuristic
rhCombined list b p = sum $ zipWith (*) points vs
where (vs, hs) = unzip list
points = map (\h -> h b p) hs
rhZero :: RingHeuristic
rhZero _ _ = 0
data Floyd = Floyd { gs :: GameState
, plies :: Int
, markerH :: MarkerHeuristic
, ringH :: RingHeuristic
}
instance AIPlayer Floyd where
valueForWhite = floydHeuristic
getGamestate = gs
getPlies = plies
update ai gs' = ai { gs = gs' }
mkFloyd :: Int -> MarkerHeuristic -> RingHeuristic -> GameState -> Floyd
mkFloyd plies' mh' rh' gs' = Floyd { gs = gs'
, plies = plies'
, markerH = mh'
, ringH = rh'
}
aiFloyd :: Int -> MarkerHeuristic -> RingHeuristic -> AIFunction
aiFloyd plies' mh' rh' gs' = aiTurn $ mkFloyd plies' mh' rh' gs'
| null | https://raw.githubusercontent.com/sharkdp/yinsh/8139baf6a0dc7d1fc8a07b152b6c6420694e3108/src/Floyd.hs | haskell | active player. | | Simply the best AI for Yinsh , seriously .
module Floyd ( aiFloyd
, mhNumber
, rhRingMoves
, rhConnected
, rhControlledMarkers
, rhCombined
, rhZero
)
where
import AI
import Yinsh
TODO : adjust numbers : 5 , 10
floydHeuristic :: Floyd -> AIValue
floydHeuristic ai | points' W >= pointsForWin = hugeNumber
| points' B >= pointsForWin = -hugeNumber
| otherwise = value W - value B
where gs' = getGamestate ai
board' = board gs'
ap' = activePlayer gs'
tm' = turnMode gs'
points W = pointsW gs'
points B = pointsB gs'
points' p = points p + futurePoints p
If we are in RemoveRun phase , already include the point for the
If we are is WaitRemoveRun , the * opponent * of the current player
will necessarily have one more point next turn .
futurePoints p = case tm' of
(RemoveRun _) -> if ap' == p then 1 else 0
(WaitRemoveRun _) -> if ap' == p then 0 else 1
_ -> 0
valuePoints p = 100000 * points' p
valueMarkers = markerH ai
valueRings = ringH ai
value p = valuePoints p
+ valueMarkers board' p
+ valueRings board' p
type MarkerHeuristic = Board -> Player -> AIValue
type RingHeuristic = Board -> Player -> AIValue
mhNumber :: MarkerHeuristic
mhNumber b p = (10 *) $ length $ markers p b
rhRingMoves :: RingHeuristic
rhRingMoves b p = (1 *) $ sum $ map (length . ringMoves b) $ rings p b
rhConnected :: RingHeuristic
rhConnected b p = (1 *) $ length $ filter connectedToRings coords
where connectedToRings c = any (c `connected`) (rings p b)
rhControlledMarkers :: RingHeuristic
rhControlledMarkers b p = sum $ map controlledM (rings p b)
where controlledM :: YCoord -> Int
controlledM start = sum $ map markersBetween endPos
where endPos = ringMoves b start
markersBetween end = length $ filter (isMarker b) $ coordLine start end
rhCombined :: [(Int, RingHeuristic)] -> RingHeuristic
rhCombined list b p = sum $ zipWith (*) points vs
where (vs, hs) = unzip list
points = map (\h -> h b p) hs
rhZero :: RingHeuristic
rhZero _ _ = 0
data Floyd = Floyd { gs :: GameState
, plies :: Int
, markerH :: MarkerHeuristic
, ringH :: RingHeuristic
}
instance AIPlayer Floyd where
valueForWhite = floydHeuristic
getGamestate = gs
getPlies = plies
update ai gs' = ai { gs = gs' }
mkFloyd :: Int -> MarkerHeuristic -> RingHeuristic -> GameState -> Floyd
mkFloyd plies' mh' rh' gs' = Floyd { gs = gs'
, plies = plies'
, markerH = mh'
, ringH = rh'
}
aiFloyd :: Int -> MarkerHeuristic -> RingHeuristic -> AIFunction
aiFloyd plies' mh' rh' gs' = aiTurn $ mkFloyd plies' mh' rh' gs'
|
7727943a0156ea6f4e3b481e56cbd1ffe116600e61b93c4674fe9277bd2a8d2a | den1k/vimsical | views.cljs | (ns vimsical.frontend.landing.views
(:require [vimsical.frontend.views.icons :as icons]
[vimsical.frontend.ui.views :as ui.views]
[vimsical.frontend.util.dom :refer-macros [e>]]
[goog.net.XhrIo]
[reagent.core :as reagent]
[vimsical.common.util.core :as util]
[re-frame.interop :as interop]
[vimsical.frontend.util.dom :as util.dom]
[vimsical.frontend.util.re-frame :refer [<sub]]
[vimsical.frontend.ui.subs :as ui.subs]
[vimsical.frontend.vims.subs :as vims.subs]
[vimsical.frontend.vcs.subs :as vcs.subs]
[vimsical.frontend.live-preview.handlers :as live-preview.handlers]
[vimsical.frontend.live-preview.views :as live-preview.views]
[vimsical.frontend.player.views.player :as player]
[vimsical.frontend.vims.handlers :as vims.handlers]
[re-frame.core :as re-frame]
[re-com.core :as re-com]
[vimsical.user :as user]
[vimsical.vims :as vims]
[vimsical.vcs.branch :as vcs.branch]
[vimsical.frontend.landing.handlers :as handlers]
[vimsical.frontend.router.routes :as router.routes]
[vimsical.frontend.styles.color :refer [colors]]
[vimsical.frontend.config :as config]))
(def on-prod? (not config/debug?))
(def vims-kw->info
(->>
{:bezier {:vims-uid nil
:title "Bézier Curve"
:author {::user/first-name "Kynd"
::user/twitter ""}
:original-src ""
:img-src "-06-24%2010.41.39.png?dl=1"}
:fireworks {:vims-uid nil
:title "Anime.js Fireworks"
:author {::user/first-name "Julian" ::user/last-name "Garnier"
::user/twitter ""}
:original-src ""
:img-src "-06-24%2010.33.03.png?dl=1"}
:strandbeast {:vims-uid (uuid "5956e2fe-f747-4efb-86a6-20c39d0a38b1")
:vims-uid-prod (uuid "5954f930-a46a-437a-8307-936671d30465")
:title "The Mighty Strandbeest"
:author {::user/first-name "Brandel" ::user/last-name "Zachernuk"
::user/twitter ""}
:original-src ""
:img-src "-06-24%2019.19.24.png?dl=1"}
:trail {:vims-uid nil
:title "Trail"
:video-poster-src "/video/explore-still.png"
:video-src "/video/explore.m4v"
:author {::user/first-name "Hakim" ::user/middle-name "El" ::user/last-name "Hattab"
::user/twitter ""}
:original-src ""}
:hello-vimsical {:vims-uid-prod (uuid "5969777d-8dae-48a6-8b6c-838928b59382")
:vims-uid (uuid "5969743d-3ab1-49e9-b95f-894190369986")
:player-opts {:autoplay-from (util/time-units->ms 1 10)}
:player-opts-prod {:autoplay-from (util/time-units->ms 5 36)}
:title "Montserrat"
:explore? true
:author {::user/first-name "Claire" ::user/last-name "Larsen"
::user/twitter "/"}
:original-src "/"}
:tree {:vims-uid nil
:title "Fractal Tree (L-System)"
:video-poster-src "/video/create-still.png"
:video-src "/video/create.m4v"
:author {::user/first-name "Patrick" ::user/last-name "Stillhart"
::user/website "/"}
:original-src "/"}
:joy-division {:vims-uid nil
:title "Interactive Joy Division"
:author {::user/first-name "Mark" ::user/last-name "Benzan"
::user/twitter ""}
:original-src ""
:img-src "-06-24%2020.51.57.png?dl=1"}
:test {:vims-uid (uuid "5956de33-b46c-48dc-83d5-ea60eeef7d83")
:title "Test test test"
:author {::user/first-name "Test" ::user/last-name "Best"
::user/twitter ""}
:original-src ""
:img-src "-06-24%2020.51.57.png?dl=1"}}
(util/map-vals
(fn [{:keys [vims-uid vims-uid-prod] :as info}]
(cond-> info
on-prod? (assoc :vims-uid vims-uid-prod))))))
;;
;; * Waitlist Form
;;
(def endpoint "-api.us-west-2.amazonaws.com/prod/handler")
(defn post-data [email]
(str "email=" (js/encodeURIComponent email)))
(defn handle-success [state _]
(swap! state assoc :success true))
(defn handle-error [state _]
(swap! state assoc :error true))
(defn submit! [state]
(let [email (:email @state)
data (post-data email)
headers #js {"Content-Type" "application/x-www-form-urlencoded"}]
(doto (goog.net.XhrIo.)
(goog.events.listen goog.net.EventType.SUCCESS (partial handle-success state))
;; handling as success also, b/c we're getting
;; an error even tough the email gets logged
(goog.events.listen goog.net.EventType.ERROR (partial handle-success state))
(.send endpoint "POST" data headers))))
(def ^:private waitlist-signup-id "waitlist")
(defn scroll-to-waitlist []
(-> (.getElementById js/document waitlist-signup-id)
(util.dom/scroll-to)))
;;
;; Wrappers
;;
(defn credit [{:keys [title author original-src vims-uid explore?] :as vims-info}]
TODO add links to author 's sites
[:div.credit
"Adapted from " [:span.title
{:on-click (e> (util.dom/open original-src))}
title] " by "
[:span.author
{:on-click (e> (util.dom/open (or (::user/twitter author) (::user/website author))))}
(user/full-name author)]
(when explore?
[:span
" ∙ "
[:span.explore
{:on-click (e> (util.dom/open (router.routes/vims-uri {:db/uid vims-uid})))}
"explore"]])])
(defn credit-wrapper [vims-info child {:keys [above?]}]
(let [credit-view [credit vims-info]]
[:div.credit-wrapper
(when above? credit-view)
child
(when-not above? credit-view)]))
;;
Vims Preview
;;
(defn- vims-preview [{:keys [class vims-title-kw] :as opts}]
(let [{:keys [img-src vims-uid] :as vims-info} (get vims-kw->info vims-title-kw)
lp-opts {:ui-key vims-title-kw :static? true :vims {:db/uid vims-uid}}]
(when vims-uid (re-frame/dispatch [::vims.handlers/vims vims-uid]))
(fn []
(when (<sub [::vcs.subs/snapshots {:db/uid vims-uid}])
[ui.views/visibility
{:range-pred
(fn [ratio]
(or #_(<= 0 ratio 0.2)
(<= 0.5 ratio 1)))
:on-visibility-change
(fn [visible?]
(when vims-uid
(re-frame/dispatch
[(if visible? ::live-preview.handlers/defreeze
::live-preview.handlers/freeze) lp-opts])))}
[:div.vims-preview
{:class class}
(if vims-uid
[live-preview.views/live-preview lp-opts]
[:img.live-preview ;; temp
{:src img-src}])]]))))
(defn vims-preview-section [{:keys [class vims-title-kw] :as opts} child]
(let [{:keys [img-src vims-uid] :as vims-info} (get vims-kw->info vims-title-kw)
lp-opts {:ui-key vims-title-kw :static? true :vims {:db/uid vims-uid}}]
(when vims-uid (re-frame/dispatch [::vims.handlers/vims vims-uid]))
(fn []
(when (<sub [::vcs.subs/snapshots {:db/uid vims-uid}])
(re-frame.loggers/console :log :snap (<sub [::vcs.subs/snapshots {:db/uid vims-uid}]))
[ui.views/visibility
{:range-pred
(fn [ratio]
(or #_(<= 0 ratio 0.2)
(<= 0.5 ratio 1)))
:on-visibility-change
(fn [visible?]
(when vims-uid
(re-frame/dispatch
[(if visible? ::live-preview.handlers/defreeze
::live-preview.handlers/freeze) lp-opts])))}
[:div.section.vims-preview-section
{:class class}
child
[:div.vims-preview
(if vims-uid
[live-preview.views/live-preview
lp-opts]
[:img.live-preview ;; temp
{:src img-src}])]]]))))
;;
;; Video Player
;;
(defn video-player [{:keys [class loop? vims-kw]
:or {loop? true}}]
(let [node (interop/ratom nil)
{:keys [video-src video-poster-src]} (get vims-kw->info vims-kw)
on-vis-change (fn [visible?]
(when-not (<sub [::ui.subs/on-mobile?])
(if visible?
(doto @node
(aset "currentTime" 0)
(.play))
(.pause @node))))]
(fn []
[ui.views/visibility {:on-visibility-change on-vis-change}
[:video.video
{:class class
:ref (fn [vid-node]
(reset! node vid-node))
:controls false
;:auto-play false
;; necessary to autoplay on iOS
:muted true
necesssary to not enter full - screen mode in iOS
;; but seeming not currently supported in react
;:plays-inline true
:loop loop?
:preload "auto"
:poster video-poster-src
:src video-src}]])))
(defn video-player-wrapper [{:keys [class vims-kw] :as opts}]
[:div.video-wrapper
[credit-wrapper
(get vims-kw->info vims-kw)
[video-player opts]]])
;;
;; Scroll Player
;;
(defn scroll-player [{:keys [ui-key vims-uid scroll-skim?]}]
(let [scroll-skim-ratio (when scroll-skim? (interop/ratom 0))]
(fn []
(when-let [vims (<sub [::vims.subs/vcs-vims vims-uid])]
(let [view [player/player {:vims vims
:orientation :landscape
:show-info? false
:read-only? true
:ui-key ui-key}]]
(if-not scroll-skim?
view
(letfn [(dispatch-fn [ratio]
(re-frame/dispatch
[::handlers/set-player-preview vims ratio]))]
[ui.views/viewport-ratio dispatch-fn true view])))))))
;;
;; Landing Sections
;;
(defn page-header []
[:div.page-header-section.jc.section
[:div.sub-section.aifs
[:div.vimsical-stmt.dc.jc
[:h1.header.vimsical "Vimsical"]
[:h2.subheader
"Your learning playground"]
[:div.join
{:on-click (e> (scroll-to-waitlist))}
"Join our Journey"]]
(let [{:keys [img-src] :as vims-info} (:strandbeast vims-kw->info)]
[:div.preview-wrapper
[credit-wrapper vims-info
[vims-preview {:vims-title-kw :strandbeast}]]])]])
(defn create-section []
[:div.create-section.section
[:div.sub-section.aife
[:h2.header "Create"]
[:h3.subheader
;"You do the work, we make the tutorial. Automatically.
"Vimsical turns your coding process into an interactive tutorial. Automatically."]
[ui.views/visibility {}
[video-player-wrapper
{:class "create-video"
:vims-kw :tree}]]]])
(defn explore-section []
[:div.explore-section.section
[:div.sub-section
[:h2.header "Explore"]
[:h3.subheader
"See how projects come together. And make edits with one click."]
[ui.views/visibility {}
[video-player-wrapper
{:class "explore-video"
:vims-kw :trail}]]]])
(defn mission-section []
[:div.mission-section.dc.ac.section
[ui.views/visibility
{:once? true}
;{}
#_[:div.logo-and-slogan.ac.jsb
[icons/logo-and-type]
[:div.stretcher]
[:h2.learnable "make it learnable."]]]
[:p.stmt
"Our mission is to nurture understanding, accelerate learning and ease teaching"
[:br]
"by providing tools to record, share and explore our process."]])
(defn player-load-vims [{vims-uid :db/uid :as vims} player-opts]
(re-frame/dispatch [::vims.handlers/load-vims vims-uid :player-vims])
(fn []
(when-let [vims (<sub [::vims.subs/vcs-vims vims-uid])]
[player/player
(cond-> {:vims {:db/uid vims-uid}
:show-info? false
:read-only? true}
true (merge player-opts)
(not (<sub [::ui.subs/on-mobile?])) (assoc :orientation :landscape))])))
(def coder-emojis-str "\uD83D\uDC69\u200D\uD83D\uDCBB \uD83D\uDC68\u200D\uD83D\uDCBB")
(defn coder-emojis [] [:span.coder-emojis coder-emojis-str])
(defn player-section []
[:div.player-section.section
[ui.views/visibility {}
[:div.dc.ac.sub-section
;[:h2.header "Create. Watch. Explore."]
[:h2.header "You do the work,\nVimsical makes the tutorial."]
(when-not (<sub [::ui.subs/on-mobile?])
[re-com/h-box
:class "try-cta-box"
:gap "4px"
:children [[:span.try-cta.ac "It's automagic! Try changing the code"]
[:span.pointer-wrapper [:span.pointer "☟"]]
[coder-emojis]]])
;; todo credit
[:div.player-wrapper
(let [{:keys [vims-uid player-opts player-opts-prod]} (:hello-vimsical vims-kw->info)]
[player-load-vims
{:db/uid vims-uid}
(if on-prod? player-opts-prod player-opts)])]
#_[:p.sub-stmt
"Embed"
[:span.bold " Player "]
"and bring powerful learning experiences"
[:br]
"to your website, blog and classroom."]
[credit (:hello-vimsical vims-kw->info)]
]]])
(defn waitlist []
(let [state (reagent/atom {:success nil :error nil :email ""})]
(fn []
(let [{:keys [success error email]} @state]
[:div.waitlist
{:id waitlist-signup-id}
[:div.form.ac
[:input.email {:type "email"
:name "email"
:placeholder "Email address"
:on-change (e> (swap! state assoc :email value))}]
[:div.button
{:on-click (fn [_] (submit! state))}
[:div.btn-content "Sign up"]]]
(cond
success [:div.result.success
"Thanks! We'll reach out to you soon."]
error [:div.result.error
"Oh no!"
[:br] "Something went wrong. Please try again."])]))))
(defn product-stmts []
[:div.product-stmts-section.section
[re-com/v-box
:class "product-stmts sub-section"
:gap "60px"
:children
[[:div.product-stmt-wrapper.ac
[icons/deer {:class "stmt-icon deer"}]
[:div.product-stmt.dc.jc
[:div.title "Code and Create."]
[:div.stmt "Vimsical turns your coding process into an interactive tutorial. Automatically."]]]
[:div.product-stmt-wrapper.ac
[icons/monkey {:class "stmt-icon monkey"}]
[:div.product-stmt.dc.jc
[:div.title "Beyond Video: \uD83D\uDCAF Interactive."]
[:div.stmt "See how your favorite projects come together. And make edits with one click."]]]
[:div.product-stmt-wrapper.ac
[icons/crane {:class "stmt-icon crane"}]
[:div.product-stmt.dc.jc
[:div.title "Explore Anywhere, Teach Everywhere."]
[:div.stmt "Vimsical's Embedded Player brings powerful learning experiences to your website, company and classroom."]]]]]])
(defn contact-us []
[:span.contact
{:on-click (e> (util.dom/open "mailto:?subject=Vimsical%20Demo"))}
"Contact us"])
;;
;; * Component
;;
(defn landing []
[:div.landing.asc.dc.ac.ais
;[page-header]
[player-section]
[product-stmts]
;[create-section]
;[explore-section]
;; Todo Education section?
#_[vims-preview-section {:vims-title-kw :trail :class "teach-by-doing"}
[:div.sub-stmt
"Teach, by doing."]]
#_[vims-preview-section {:vims-title-kw :fireworks :class "create-watch-explore"}
[:div.sub-stmt
"Create. Watch. Explore."]]
#_[vims-preview-section {:vims-title-kw :test :class "create-watch-explore"}
[:div.sub-stmt
"Create. Watch. Explore."]]
[:div.bottom-waitlist.dc.ac.section
[:div.sub-section.aic
[:h2.join "Interested in how Vimsical could help you or your company?"]
[re-com/h-box
:class "get-demo-box"
:gap "30px"
:align :center
:style {:flex-flow :wrap}
:children [[:span.get-demo "Get a demo:"] [waitlist]]]]]
;[mission-section]
(if (<sub [::ui.subs/on-mobile?])
[:footer.footer.jsb.ac.dc
[re-com/h-box
:class "built-contact mobile"
:justify :around
:children
[[:span "Built in NYC"]
[contact-us]]]
[icons/logo-and-type {:class :footer-logo}]]
[:footer.footer.jsb.ac
[:div.footer-box [:span "Copyright © 2017 Vimsical Inc."]]
[icons/logo-and-type
{:class :footer-logo}]
[re-com/h-box
:class "built-contact footer-box"
:justify :end
:gap "10px"
:children
[[:span "Built in NYC"]
[contact-us]]]])]) | null | https://raw.githubusercontent.com/den1k/vimsical/1e4a1f1297849b1121baf24bdb7a0c6ba3558954/src/frontend/vimsical/frontend/landing/views.cljs | clojure |
* Waitlist Form
handling as success also, b/c we're getting
an error even tough the email gets logged
Wrappers
temp
temp
Video Player
:auto-play false
necessary to autoplay on iOS
but seeming not currently supported in react
:plays-inline true
Scroll Player
Landing Sections
"You do the work, we make the tutorial. Automatically.
{}
[:h2.header "Create. Watch. Explore."]
todo credit
* Component
[page-header]
[create-section]
[explore-section]
Todo Education section?
[mission-section] | (ns vimsical.frontend.landing.views
(:require [vimsical.frontend.views.icons :as icons]
[vimsical.frontend.ui.views :as ui.views]
[vimsical.frontend.util.dom :refer-macros [e>]]
[goog.net.XhrIo]
[reagent.core :as reagent]
[vimsical.common.util.core :as util]
[re-frame.interop :as interop]
[vimsical.frontend.util.dom :as util.dom]
[vimsical.frontend.util.re-frame :refer [<sub]]
[vimsical.frontend.ui.subs :as ui.subs]
[vimsical.frontend.vims.subs :as vims.subs]
[vimsical.frontend.vcs.subs :as vcs.subs]
[vimsical.frontend.live-preview.handlers :as live-preview.handlers]
[vimsical.frontend.live-preview.views :as live-preview.views]
[vimsical.frontend.player.views.player :as player]
[vimsical.frontend.vims.handlers :as vims.handlers]
[re-frame.core :as re-frame]
[re-com.core :as re-com]
[vimsical.user :as user]
[vimsical.vims :as vims]
[vimsical.vcs.branch :as vcs.branch]
[vimsical.frontend.landing.handlers :as handlers]
[vimsical.frontend.router.routes :as router.routes]
[vimsical.frontend.styles.color :refer [colors]]
[vimsical.frontend.config :as config]))
(def on-prod? (not config/debug?))
(def vims-kw->info
(->>
{:bezier {:vims-uid nil
:title "Bézier Curve"
:author {::user/first-name "Kynd"
::user/twitter ""}
:original-src ""
:img-src "-06-24%2010.41.39.png?dl=1"}
:fireworks {:vims-uid nil
:title "Anime.js Fireworks"
:author {::user/first-name "Julian" ::user/last-name "Garnier"
::user/twitter ""}
:original-src ""
:img-src "-06-24%2010.33.03.png?dl=1"}
:strandbeast {:vims-uid (uuid "5956e2fe-f747-4efb-86a6-20c39d0a38b1")
:vims-uid-prod (uuid "5954f930-a46a-437a-8307-936671d30465")
:title "The Mighty Strandbeest"
:author {::user/first-name "Brandel" ::user/last-name "Zachernuk"
::user/twitter ""}
:original-src ""
:img-src "-06-24%2019.19.24.png?dl=1"}
:trail {:vims-uid nil
:title "Trail"
:video-poster-src "/video/explore-still.png"
:video-src "/video/explore.m4v"
:author {::user/first-name "Hakim" ::user/middle-name "El" ::user/last-name "Hattab"
::user/twitter ""}
:original-src ""}
:hello-vimsical {:vims-uid-prod (uuid "5969777d-8dae-48a6-8b6c-838928b59382")
:vims-uid (uuid "5969743d-3ab1-49e9-b95f-894190369986")
:player-opts {:autoplay-from (util/time-units->ms 1 10)}
:player-opts-prod {:autoplay-from (util/time-units->ms 5 36)}
:title "Montserrat"
:explore? true
:author {::user/first-name "Claire" ::user/last-name "Larsen"
::user/twitter "/"}
:original-src "/"}
:tree {:vims-uid nil
:title "Fractal Tree (L-System)"
:video-poster-src "/video/create-still.png"
:video-src "/video/create.m4v"
:author {::user/first-name "Patrick" ::user/last-name "Stillhart"
::user/website "/"}
:original-src "/"}
:joy-division {:vims-uid nil
:title "Interactive Joy Division"
:author {::user/first-name "Mark" ::user/last-name "Benzan"
::user/twitter ""}
:original-src ""
:img-src "-06-24%2020.51.57.png?dl=1"}
:test {:vims-uid (uuid "5956de33-b46c-48dc-83d5-ea60eeef7d83")
:title "Test test test"
:author {::user/first-name "Test" ::user/last-name "Best"
::user/twitter ""}
:original-src ""
:img-src "-06-24%2020.51.57.png?dl=1"}}
(util/map-vals
(fn [{:keys [vims-uid vims-uid-prod] :as info}]
(cond-> info
on-prod? (assoc :vims-uid vims-uid-prod))))))
(def endpoint "-api.us-west-2.amazonaws.com/prod/handler")
(defn post-data [email]
(str "email=" (js/encodeURIComponent email)))
(defn handle-success [state _]
(swap! state assoc :success true))
(defn handle-error [state _]
(swap! state assoc :error true))
(defn submit! [state]
(let [email (:email @state)
data (post-data email)
headers #js {"Content-Type" "application/x-www-form-urlencoded"}]
(doto (goog.net.XhrIo.)
(goog.events.listen goog.net.EventType.SUCCESS (partial handle-success state))
(goog.events.listen goog.net.EventType.ERROR (partial handle-success state))
(.send endpoint "POST" data headers))))
(def ^:private waitlist-signup-id "waitlist")
(defn scroll-to-waitlist []
(-> (.getElementById js/document waitlist-signup-id)
(util.dom/scroll-to)))
(defn credit [{:keys [title author original-src vims-uid explore?] :as vims-info}]
TODO add links to author 's sites
[:div.credit
"Adapted from " [:span.title
{:on-click (e> (util.dom/open original-src))}
title] " by "
[:span.author
{:on-click (e> (util.dom/open (or (::user/twitter author) (::user/website author))))}
(user/full-name author)]
(when explore?
[:span
" ∙ "
[:span.explore
{:on-click (e> (util.dom/open (router.routes/vims-uri {:db/uid vims-uid})))}
"explore"]])])
(defn credit-wrapper [vims-info child {:keys [above?]}]
(let [credit-view [credit vims-info]]
[:div.credit-wrapper
(when above? credit-view)
child
(when-not above? credit-view)]))
Vims Preview
(defn- vims-preview [{:keys [class vims-title-kw] :as opts}]
(let [{:keys [img-src vims-uid] :as vims-info} (get vims-kw->info vims-title-kw)
lp-opts {:ui-key vims-title-kw :static? true :vims {:db/uid vims-uid}}]
(when vims-uid (re-frame/dispatch [::vims.handlers/vims vims-uid]))
(fn []
(when (<sub [::vcs.subs/snapshots {:db/uid vims-uid}])
[ui.views/visibility
{:range-pred
(fn [ratio]
(or #_(<= 0 ratio 0.2)
(<= 0.5 ratio 1)))
:on-visibility-change
(fn [visible?]
(when vims-uid
(re-frame/dispatch
[(if visible? ::live-preview.handlers/defreeze
::live-preview.handlers/freeze) lp-opts])))}
[:div.vims-preview
{:class class}
(if vims-uid
[live-preview.views/live-preview lp-opts]
{:src img-src}])]]))))
(defn vims-preview-section [{:keys [class vims-title-kw] :as opts} child]
(let [{:keys [img-src vims-uid] :as vims-info} (get vims-kw->info vims-title-kw)
lp-opts {:ui-key vims-title-kw :static? true :vims {:db/uid vims-uid}}]
(when vims-uid (re-frame/dispatch [::vims.handlers/vims vims-uid]))
(fn []
(when (<sub [::vcs.subs/snapshots {:db/uid vims-uid}])
(re-frame.loggers/console :log :snap (<sub [::vcs.subs/snapshots {:db/uid vims-uid}]))
[ui.views/visibility
{:range-pred
(fn [ratio]
(or #_(<= 0 ratio 0.2)
(<= 0.5 ratio 1)))
:on-visibility-change
(fn [visible?]
(when vims-uid
(re-frame/dispatch
[(if visible? ::live-preview.handlers/defreeze
::live-preview.handlers/freeze) lp-opts])))}
[:div.section.vims-preview-section
{:class class}
child
[:div.vims-preview
(if vims-uid
[live-preview.views/live-preview
lp-opts]
{:src img-src}])]]]))))
(defn video-player [{:keys [class loop? vims-kw]
:or {loop? true}}]
(let [node (interop/ratom nil)
{:keys [video-src video-poster-src]} (get vims-kw->info vims-kw)
on-vis-change (fn [visible?]
(when-not (<sub [::ui.subs/on-mobile?])
(if visible?
(doto @node
(aset "currentTime" 0)
(.play))
(.pause @node))))]
(fn []
[ui.views/visibility {:on-visibility-change on-vis-change}
[:video.video
{:class class
:ref (fn [vid-node]
(reset! node vid-node))
:controls false
:muted true
necesssary to not enter full - screen mode in iOS
:loop loop?
:preload "auto"
:poster video-poster-src
:src video-src}]])))
(defn video-player-wrapper [{:keys [class vims-kw] :as opts}]
[:div.video-wrapper
[credit-wrapper
(get vims-kw->info vims-kw)
[video-player opts]]])
(defn scroll-player [{:keys [ui-key vims-uid scroll-skim?]}]
(let [scroll-skim-ratio (when scroll-skim? (interop/ratom 0))]
(fn []
(when-let [vims (<sub [::vims.subs/vcs-vims vims-uid])]
(let [view [player/player {:vims vims
:orientation :landscape
:show-info? false
:read-only? true
:ui-key ui-key}]]
(if-not scroll-skim?
view
(letfn [(dispatch-fn [ratio]
(re-frame/dispatch
[::handlers/set-player-preview vims ratio]))]
[ui.views/viewport-ratio dispatch-fn true view])))))))
(defn page-header []
[:div.page-header-section.jc.section
[:div.sub-section.aifs
[:div.vimsical-stmt.dc.jc
[:h1.header.vimsical "Vimsical"]
[:h2.subheader
"Your learning playground"]
[:div.join
{:on-click (e> (scroll-to-waitlist))}
"Join our Journey"]]
(let [{:keys [img-src] :as vims-info} (:strandbeast vims-kw->info)]
[:div.preview-wrapper
[credit-wrapper vims-info
[vims-preview {:vims-title-kw :strandbeast}]]])]])
(defn create-section []
[:div.create-section.section
[:div.sub-section.aife
[:h2.header "Create"]
[:h3.subheader
"Vimsical turns your coding process into an interactive tutorial. Automatically."]
[ui.views/visibility {}
[video-player-wrapper
{:class "create-video"
:vims-kw :tree}]]]])
(defn explore-section []
[:div.explore-section.section
[:div.sub-section
[:h2.header "Explore"]
[:h3.subheader
"See how projects come together. And make edits with one click."]
[ui.views/visibility {}
[video-player-wrapper
{:class "explore-video"
:vims-kw :trail}]]]])
(defn mission-section []
[:div.mission-section.dc.ac.section
[ui.views/visibility
{:once? true}
#_[:div.logo-and-slogan.ac.jsb
[icons/logo-and-type]
[:div.stretcher]
[:h2.learnable "make it learnable."]]]
[:p.stmt
"Our mission is to nurture understanding, accelerate learning and ease teaching"
[:br]
"by providing tools to record, share and explore our process."]])
(defn player-load-vims [{vims-uid :db/uid :as vims} player-opts]
(re-frame/dispatch [::vims.handlers/load-vims vims-uid :player-vims])
(fn []
(when-let [vims (<sub [::vims.subs/vcs-vims vims-uid])]
[player/player
(cond-> {:vims {:db/uid vims-uid}
:show-info? false
:read-only? true}
true (merge player-opts)
(not (<sub [::ui.subs/on-mobile?])) (assoc :orientation :landscape))])))
(def coder-emojis-str "\uD83D\uDC69\u200D\uD83D\uDCBB \uD83D\uDC68\u200D\uD83D\uDCBB")
(defn coder-emojis [] [:span.coder-emojis coder-emojis-str])
(defn player-section []
[:div.player-section.section
[ui.views/visibility {}
[:div.dc.ac.sub-section
[:h2.header "You do the work,\nVimsical makes the tutorial."]
(when-not (<sub [::ui.subs/on-mobile?])
[re-com/h-box
:class "try-cta-box"
:gap "4px"
:children [[:span.try-cta.ac "It's automagic! Try changing the code"]
[:span.pointer-wrapper [:span.pointer "☟"]]
[coder-emojis]]])
[:div.player-wrapper
(let [{:keys [vims-uid player-opts player-opts-prod]} (:hello-vimsical vims-kw->info)]
[player-load-vims
{:db/uid vims-uid}
(if on-prod? player-opts-prod player-opts)])]
#_[:p.sub-stmt
"Embed"
[:span.bold " Player "]
"and bring powerful learning experiences"
[:br]
"to your website, blog and classroom."]
[credit (:hello-vimsical vims-kw->info)]
]]])
(defn waitlist []
(let [state (reagent/atom {:success nil :error nil :email ""})]
(fn []
(let [{:keys [success error email]} @state]
[:div.waitlist
{:id waitlist-signup-id}
[:div.form.ac
[:input.email {:type "email"
:name "email"
:placeholder "Email address"
:on-change (e> (swap! state assoc :email value))}]
[:div.button
{:on-click (fn [_] (submit! state))}
[:div.btn-content "Sign up"]]]
(cond
success [:div.result.success
"Thanks! We'll reach out to you soon."]
error [:div.result.error
"Oh no!"
[:br] "Something went wrong. Please try again."])]))))
(defn product-stmts []
[:div.product-stmts-section.section
[re-com/v-box
:class "product-stmts sub-section"
:gap "60px"
:children
[[:div.product-stmt-wrapper.ac
[icons/deer {:class "stmt-icon deer"}]
[:div.product-stmt.dc.jc
[:div.title "Code and Create."]
[:div.stmt "Vimsical turns your coding process into an interactive tutorial. Automatically."]]]
[:div.product-stmt-wrapper.ac
[icons/monkey {:class "stmt-icon monkey"}]
[:div.product-stmt.dc.jc
[:div.title "Beyond Video: \uD83D\uDCAF Interactive."]
[:div.stmt "See how your favorite projects come together. And make edits with one click."]]]
[:div.product-stmt-wrapper.ac
[icons/crane {:class "stmt-icon crane"}]
[:div.product-stmt.dc.jc
[:div.title "Explore Anywhere, Teach Everywhere."]
[:div.stmt "Vimsical's Embedded Player brings powerful learning experiences to your website, company and classroom."]]]]]])
(defn contact-us []
[:span.contact
{:on-click (e> (util.dom/open "mailto:?subject=Vimsical%20Demo"))}
"Contact us"])
(defn landing []
[:div.landing.asc.dc.ac.ais
[player-section]
[product-stmts]
#_[vims-preview-section {:vims-title-kw :trail :class "teach-by-doing"}
[:div.sub-stmt
"Teach, by doing."]]
#_[vims-preview-section {:vims-title-kw :fireworks :class "create-watch-explore"}
[:div.sub-stmt
"Create. Watch. Explore."]]
#_[vims-preview-section {:vims-title-kw :test :class "create-watch-explore"}
[:div.sub-stmt
"Create. Watch. Explore."]]
[:div.bottom-waitlist.dc.ac.section
[:div.sub-section.aic
[:h2.join "Interested in how Vimsical could help you or your company?"]
[re-com/h-box
:class "get-demo-box"
:gap "30px"
:align :center
:style {:flex-flow :wrap}
:children [[:span.get-demo "Get a demo:"] [waitlist]]]]]
(if (<sub [::ui.subs/on-mobile?])
[:footer.footer.jsb.ac.dc
[re-com/h-box
:class "built-contact mobile"
:justify :around
:children
[[:span "Built in NYC"]
[contact-us]]]
[icons/logo-and-type {:class :footer-logo}]]
[:footer.footer.jsb.ac
[:div.footer-box [:span "Copyright © 2017 Vimsical Inc."]]
[icons/logo-and-type
{:class :footer-logo}]
[re-com/h-box
:class "built-contact footer-box"
:justify :end
:gap "10px"
:children
[[:span "Built in NYC"]
[contact-us]]]])]) |
8fdf77eafc6e1e3688c4572d8804b5218f4afb4b7460c15c85f6280e58ee6960 | VisionsGlobalEmpowerment/webchange | views.cljs | (ns webchange.ui.components.panel.views
(:require
[reagent.core :as r]
[webchange.ui.components.available-values :as available-values]
[webchange.ui.components.icon.views :refer [system-icon]]
[webchange.ui.utils.get-class-name :refer [get-class-name]]))
(defn panel
[{:keys [class-name class-name-content color title icon]}]
{:pre [(or (nil? class-name) (string? class-name))
(or (nil? class-name-content) (string? class-name-content))
(or (nil? color) (some #{color} available-values/color))
(or (nil? title) (string? title))
(or (nil? icon)
(some #{icon} available-values/icon-system))]}
(let [show-title? (or (some? title)
(some? icon))]
[:div {:class-name (get-class-name {"bbs--panel" true
(str "bbs--panel--color-" color) (some? color)
class-name (some? class-name)})}
(when show-title?
[:h3.bbs--panel--title
(when (some? icon)
[system-icon {:icon icon
:class-name "bbs--panel--title-icon"}])
title])
(->> (r/current-component)
(r/children)
(into [:div {:class-name (get-class-name {"bbs--panel--content" true
class-name-content (some? class-name-content)})}]))]))
| null | https://raw.githubusercontent.com/VisionsGlobalEmpowerment/webchange/e5747e187937d85e9c92c728d52a704f323f00ef/src/cljs/webchange/ui/components/panel/views.cljs | clojure | (ns webchange.ui.components.panel.views
(:require
[reagent.core :as r]
[webchange.ui.components.available-values :as available-values]
[webchange.ui.components.icon.views :refer [system-icon]]
[webchange.ui.utils.get-class-name :refer [get-class-name]]))
(defn panel
[{:keys [class-name class-name-content color title icon]}]
{:pre [(or (nil? class-name) (string? class-name))
(or (nil? class-name-content) (string? class-name-content))
(or (nil? color) (some #{color} available-values/color))
(or (nil? title) (string? title))
(or (nil? icon)
(some #{icon} available-values/icon-system))]}
(let [show-title? (or (some? title)
(some? icon))]
[:div {:class-name (get-class-name {"bbs--panel" true
(str "bbs--panel--color-" color) (some? color)
class-name (some? class-name)})}
(when show-title?
[:h3.bbs--panel--title
(when (some? icon)
[system-icon {:icon icon
:class-name "bbs--panel--title-icon"}])
title])
(->> (r/current-component)
(r/children)
(into [:div {:class-name (get-class-name {"bbs--panel--content" true
class-name-content (some? class-name-content)})}]))]))
| |
24b852d41c60bd1461d318489e49eb3387e9d52809409bd3f19abae4e3aaffd8 | KavehYousefi/Esoteric-programming-languages | main.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Line numbering
;; ==============
;; Yielded as a conjecture by perusal of the infinite loop example,
instructions are enumerated starting at one ( 1 ) ; a fact endowed with
;; pertinence in regard to the goto or jump command "^".
;;
;; Confrontend with a deficiency regarding the behavior of a goto
destination outside of the range [ 1 , number_of_instructions ] , the
;; adjudgment have been concluded that an infringement upon the lower
bound , that is , a destination less than or equal to zero , shall
default to one ( 1 ) , whereas a contralateral transgression terminates
;; the program in the exact same manner as a usual progression of the
;; instruction pointer beyond the desinent instruction would incur.
;;
;; --------------------------------------------------------------------
;;
Author :
Date : 2022 - 05 - 28
;;
;; Sources:
;; -> ""
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; -- Declaration of types. -- ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(deftype command ()
"The ``command'' type enumerates the recognized Xaxa command names."
'(member
:move-right
:decrement
:move-left
:start-skip
:end-skip
:jump
:output
:input))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; -- Implementation of parser. -- ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun extract-instructions (code)
"Extracts from the piece of Xaxa CODE the incorporated instructions
and returns these in a one-dimensional simple array."
(declare (type string code))
(let ((instructions NIL))
(declare (type list instructions))
(loop for token of-type character across code do
(case token
(#\> (push :move-right instructions))
(#\- (push :decrement instructions))
(#\< (push :move-left instructions))
(#\? (push :start-skip instructions))
(#\! (push :end-skip instructions))
(#\^ (push :jump instructions))
(#\. (push :output instructions))
(#\, (push :input instructions))
((#\Space #\Tab #\Newline) NIL)
(otherwise (error "Invalid character '~c'." token))))
(the (simple-array command (*))
(coerce (nreverse instructions) '(simple-array command (*))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; -- Implementation of interpreter. -- ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun process-instructions (instructions)
"Processes and interprets the Xaxa INSTRUCTIONS and returns no value."
(declare (type (vector command *) instructions))
(when (plusp (length instructions))
(let ((ip 0)
(instruction (aref instructions 0))
(memory (make-hash-table :test #'eql))
(pointer 0))
(declare (type fixnum ip))
(declare (type (or null command) instruction))
(declare (type hash-table memory))
(declare (type fixnum pointer))
(labels
((advance ()
"Moves the instruction pointer IP to the next instruction,
if possible, updates the current INSTRUCTION, and returns
no value."
(setf instruction
(when (array-in-bounds-p instructions (1+ ip))
(aref instructions (incf ip))))
(values))
(jump-to (new-position)
"Moves the instruction pointer IP to the one-based
NEW-POSITION, updates the current INSTRUCTION, and returns
no value."
(declare (type fixnum new-position))
(setf ip (1- (max 1 new-position)))
(setf instruction
(when (array-in-bounds-p instructions ip)
(aref instructions ip)))
(values))
(current-cell ()
"Returns the value stored in the active cell."
(the integer (gethash pointer memory 0)))
((setf current-cell) (new-value)
"Sets the active cell's content to the NEW-VALUE and returns
no value."
(declare (type integer new-value))
(setf (gethash pointer memory 0) new-value)
(values)))
(setf (current-cell) 0)
(loop while instruction do
(case instruction
((NIL)
(loop-finish))
;; Move the cell pointer one cell to the right and increment
;; the active cell's value.
(:move-right
(incf pointer)
(incf (current-cell))
(advance))
;; Decrement the active cell's value.
(:decrement
(decf (current-cell))
(advance))
;; Move the cell pointer one cell to the left.
(:move-left
(decf pointer)
(advance))
If the active cell value equals zero , skip the
;; instructions up until and including the next "!".
(:start-skip
(cond
((zerop (current-cell))
(advance)
(loop do
(case instruction
((NIL)
(error "Unterminated '?'. No matching '!' ~
found."))
(:end-skip
(advance)
(loop-finish))
(otherwise
(advance)))))
(T
(advance))))
;; Only significant in conjunction with the "?" instruction
;; as a demarcation of the section to skip.
(:end-skip
(advance))
Jump to the instruction whose one - based index in the
;; INSTRUCTIONS vector equals the active cell's value.
(:jump
(jump-to (current-cell)))
;; Output the active cell's value verbatim.
(:output
(format T "~d" (current-cell))
(advance))
;; Input an integer number and store it in the active cell.
(:input
(format T "~&Please input an integer: ")
(let ((input (parse-integer (read-line))))
(declare (type integer input))
(clear-input)
(setf (current-cell) input))
(advance))
Invalid instruction encountered ? = > Error .
(otherwise
(error "Invalid instruction '~s' at position ~d."
instruction ip)))))))
(values))
;;; -------------------------------------------------------
(defun interpret-Xaxa (code)
"Interprets the piece of Xaxa CODE and returns no value."
(declare (type string code))
(process-instructions
(extract-instructions code))
(values))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; -- Test cases. -- ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Move one cell to the right, increment its value, and print it.
(process-instructions
(extract-instructions ">."))
;;; -------------------------------------------------------
;; Move one cell to the right, increment its value, and print it.
(interpret-Xaxa ">.")
;;; -------------------------------------------------------
Infinite loop .
(interpret-Xaxa ">^")
;;; -------------------------------------------------------
Infinite cat program .
;; Please note that for each user query a new cell is appended to the
;; memory, thus elicitating a contingency for the environment memory's
;; exhaustion.
(interpret-Xaxa ",.>^")
;;; -------------------------------------------------------
;; Skip the printing of the active cell's value as its content equals
zero .
(interpret-Xaxa "?.!")
;;; -------------------------------------------------------
;; Prompt the user for an integer number. If the input does not equal
zero , print it , otherwise abstain from any further actions .
(interpret-Xaxa ",?.!")
;;; -------------------------------------------------------
;; Truth-machine.
(interpret-Xaxa ",?><>-.<>^!")
| null | https://raw.githubusercontent.com/KavehYousefi/Esoteric-programming-languages/39ae5aaa27c8949fe4b64190b81c21501da5b783/Xaxa/Xaxa_001/main.lisp | lisp |
Line numbering
==============
Yielded as a conjecture by perusal of the infinite loop example,
a fact endowed with
pertinence in regard to the goto or jump command "^".
Confrontend with a deficiency regarding the behavior of a goto
adjudgment have been concluded that an infringement upon the lower
the program in the exact same manner as a usual progression of the
instruction pointer beyond the desinent instruction would incur.
--------------------------------------------------------------------
Sources:
-> ""
-- Declaration of types. -- ;;
-- Implementation of parser. -- ;;
-- Implementation of interpreter. -- ;;
Move the cell pointer one cell to the right and increment
the active cell's value.
Decrement the active cell's value.
Move the cell pointer one cell to the left.
instructions up until and including the next "!".
Only significant in conjunction with the "?" instruction
as a demarcation of the section to skip.
INSTRUCTIONS vector equals the active cell's value.
Output the active cell's value verbatim.
Input an integer number and store it in the active cell.
-------------------------------------------------------
-- Test cases. -- ;;
Move one cell to the right, increment its value, and print it.
-------------------------------------------------------
Move one cell to the right, increment its value, and print it.
-------------------------------------------------------
-------------------------------------------------------
Please note that for each user query a new cell is appended to the
memory, thus elicitating a contingency for the environment memory's
exhaustion.
-------------------------------------------------------
Skip the printing of the active cell's value as its content equals
-------------------------------------------------------
Prompt the user for an integer number. If the input does not equal
-------------------------------------------------------
Truth-machine. | destination outside of the range [ 1 , number_of_instructions ] , the
bound , that is , a destination less than or equal to zero , shall
default to one ( 1 ) , whereas a contralateral transgression terminates
Author :
Date : 2022 - 05 - 28
(deftype command ()
"The ``command'' type enumerates the recognized Xaxa command names."
'(member
:move-right
:decrement
:move-left
:start-skip
:end-skip
:jump
:output
:input))
(defun extract-instructions (code)
"Extracts from the piece of Xaxa CODE the incorporated instructions
and returns these in a one-dimensional simple array."
(declare (type string code))
(let ((instructions NIL))
(declare (type list instructions))
(loop for token of-type character across code do
(case token
(#\> (push :move-right instructions))
(#\- (push :decrement instructions))
(#\< (push :move-left instructions))
(#\? (push :start-skip instructions))
(#\! (push :end-skip instructions))
(#\^ (push :jump instructions))
(#\. (push :output instructions))
(#\, (push :input instructions))
((#\Space #\Tab #\Newline) NIL)
(otherwise (error "Invalid character '~c'." token))))
(the (simple-array command (*))
(coerce (nreverse instructions) '(simple-array command (*))))))
(defun process-instructions (instructions)
"Processes and interprets the Xaxa INSTRUCTIONS and returns no value."
(declare (type (vector command *) instructions))
(when (plusp (length instructions))
(let ((ip 0)
(instruction (aref instructions 0))
(memory (make-hash-table :test #'eql))
(pointer 0))
(declare (type fixnum ip))
(declare (type (or null command) instruction))
(declare (type hash-table memory))
(declare (type fixnum pointer))
(labels
((advance ()
"Moves the instruction pointer IP to the next instruction,
if possible, updates the current INSTRUCTION, and returns
no value."
(setf instruction
(when (array-in-bounds-p instructions (1+ ip))
(aref instructions (incf ip))))
(values))
(jump-to (new-position)
"Moves the instruction pointer IP to the one-based
NEW-POSITION, updates the current INSTRUCTION, and returns
no value."
(declare (type fixnum new-position))
(setf ip (1- (max 1 new-position)))
(setf instruction
(when (array-in-bounds-p instructions ip)
(aref instructions ip)))
(values))
(current-cell ()
"Returns the value stored in the active cell."
(the integer (gethash pointer memory 0)))
((setf current-cell) (new-value)
"Sets the active cell's content to the NEW-VALUE and returns
no value."
(declare (type integer new-value))
(setf (gethash pointer memory 0) new-value)
(values)))
(setf (current-cell) 0)
(loop while instruction do
(case instruction
((NIL)
(loop-finish))
(:move-right
(incf pointer)
(incf (current-cell))
(advance))
(:decrement
(decf (current-cell))
(advance))
(:move-left
(decf pointer)
(advance))
If the active cell value equals zero , skip the
(:start-skip
(cond
((zerop (current-cell))
(advance)
(loop do
(case instruction
((NIL)
(error "Unterminated '?'. No matching '!' ~
found."))
(:end-skip
(advance)
(loop-finish))
(otherwise
(advance)))))
(T
(advance))))
(:end-skip
(advance))
Jump to the instruction whose one - based index in the
(:jump
(jump-to (current-cell)))
(:output
(format T "~d" (current-cell))
(advance))
(:input
(format T "~&Please input an integer: ")
(let ((input (parse-integer (read-line))))
(declare (type integer input))
(clear-input)
(setf (current-cell) input))
(advance))
Invalid instruction encountered ? = > Error .
(otherwise
(error "Invalid instruction '~s' at position ~d."
instruction ip)))))))
(values))
(defun interpret-Xaxa (code)
"Interprets the piece of Xaxa CODE and returns no value."
(declare (type string code))
(process-instructions
(extract-instructions code))
(values))
(process-instructions
(extract-instructions ">."))
(interpret-Xaxa ">.")
Infinite loop .
(interpret-Xaxa ">^")
Infinite cat program .
(interpret-Xaxa ",.>^")
zero .
(interpret-Xaxa "?.!")
zero , print it , otherwise abstain from any further actions .
(interpret-Xaxa ",?.!")
(interpret-Xaxa ",?><>-.<>^!")
|
a5120fcb9814785915ea5b1662dcd126ee1d84e098cdd0839a6f657622fe9824 | xapi-project/xen-api | xen_api_lwt_unix.mli |
* Copyright ( C ) 2012 Citrix Systems Inc.
*
* 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 ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* 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 .
* Copyright (C) 2012 Citrix Systems Inc.
*
* 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; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* 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.
*)
val make : ?timeout:float -> string -> Rpc.call -> Rpc.response Lwt.t
(** [make ?timeout uri] returns an 'rpc' function which can be
passed to Client.* functions *)
val make_json : ?timeout:float -> string -> Rpc.call -> Rpc.response Lwt.t
(** [make ?timeout uri] returns an 'rpc' function which can be
passed to Client.* functions *)
include module type of Client.ClientF (Lwt)
module Lwt_unix_IO : sig
type ic = (unit -> unit Lwt.t) * Lwt_io.input_channel
type oc = (unit -> unit Lwt.t) * Lwt_io.output_channel
val open_connection : Uri.t -> (ic * oc, exn) Xen_api.result Lwt.t
end
| null | https://raw.githubusercontent.com/xapi-project/xen-api/5c2fb7b8de6b511cf17f141f3d03895c6d767b55/ocaml/xen-api-client/lwt/xen_api_lwt_unix.mli | ocaml | * [make ?timeout uri] returns an 'rpc' function which can be
passed to Client.* functions
* [make ?timeout uri] returns an 'rpc' function which can be
passed to Client.* functions |
* Copyright ( C ) 2012 Citrix Systems Inc.
*
* 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 ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* 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 .
* Copyright (C) 2012 Citrix Systems Inc.
*
* 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; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* 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.
*)
val make : ?timeout:float -> string -> Rpc.call -> Rpc.response Lwt.t
val make_json : ?timeout:float -> string -> Rpc.call -> Rpc.response Lwt.t
include module type of Client.ClientF (Lwt)
module Lwt_unix_IO : sig
type ic = (unit -> unit Lwt.t) * Lwt_io.input_channel
type oc = (unit -> unit Lwt.t) * Lwt_io.output_channel
val open_connection : Uri.t -> (ic * oc, exn) Xen_api.result Lwt.t
end
|
f98130ffb848291f844065a600018c06ae101abf0f60cd0ab2e8cb3c1529dea1 | Eduap-com/WordMat | dcpose.lisp | ;;; Compiled by f2cl version:
( " f2cl1.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ "
" f2cl2.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ "
" f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl5.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ "
" f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ "
" macros.l , v 1409c1352feb 2013/03/24 20:44:50 toy $ " )
;;; Using Lisp CMU Common Lisp snapshot-2020-04 (21D Unicode)
;;;
;;; 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 "HOMPACK")
(defun dcpose (ndim n qr alpha pivot ierr y sum)
(declare (type (array double-float (*)) sum y)
(type (array f2cl-lib:integer4 (*)) pivot)
(type (array double-float (*)) alpha qr)
(type (f2cl-lib:integer4) ierr n ndim))
(f2cl-lib:with-multi-array-data
((qr double-float qr-%data% qr-%offset%)
(alpha double-float alpha-%data% alpha-%offset%)
(pivot f2cl-lib:integer4 pivot-%data% pivot-%offset%)
(y double-float y-%data% y-%offset%)
(sum double-float sum-%data% sum-%offset%))
(prog ((beta 0.0) (sigma 0.0) (alphak 0.0) (qrkk 0.0) (i 0) (j 0) (jbar 0)
(k 0) (kp1 0) (np1 0))
(declare (type (f2cl-lib:integer4) np1 kp1 k jbar j i)
(type (double-float) qrkk alphak sigma beta))
(setf ierr 0)
(setf np1 (f2cl-lib:int-add n 1))
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j np1) nil)
(tagbody
(setf (f2cl-lib:fref sum-%data% (j) ((1 1)) sum-%offset%)
(ddot n
(f2cl-lib:array-slice qr-%data%
double-float
(1 j)
((1 ndim) (1 1))
qr-%offset%)
1
(f2cl-lib:array-slice qr-%data%
double-float
(1 j)
((1 ndim) (1 1))
qr-%offset%)
1))
label20
(setf (f2cl-lib:fref pivot-%data% (j) ((1 1)) pivot-%offset%) j)))
(f2cl-lib:fdo (k 1 (f2cl-lib:int-add k 1))
((> k n) nil)
(tagbody
(setf sigma (f2cl-lib:fref sum-%data% (k) ((1 1)) sum-%offset%))
(setf jbar k)
(setf kp1 (f2cl-lib:int-add k 1))
(f2cl-lib:fdo (j kp1 (f2cl-lib:int-add j 1))
((> j np1) nil)
(tagbody
(if
(>= sigma (f2cl-lib:fref sum-%data% (j) ((1 1)) sum-%offset%))
(go label40))
(setf sigma (f2cl-lib:fref sum-%data% (j) ((1 1)) sum-%offset%))
(setf jbar j)
label40))
(if (= jbar k) (go label70))
(setf i (f2cl-lib:fref pivot-%data% (k) ((1 1)) pivot-%offset%))
(setf (f2cl-lib:fref pivot-%data% (k) ((1 1)) pivot-%offset%)
(f2cl-lib:fref pivot-%data% (jbar) ((1 1)) pivot-%offset%))
(setf (f2cl-lib:fref pivot-%data% (jbar) ((1 1)) pivot-%offset%) i)
(setf (f2cl-lib:fref sum-%data% (jbar) ((1 1)) sum-%offset%)
(f2cl-lib:fref sum-%data% (k) ((1 1)) sum-%offset%))
(setf (f2cl-lib:fref sum-%data% (k) ((1 1)) sum-%offset%) sigma)
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf sigma
(f2cl-lib:fref qr-%data%
(i k)
((1 ndim) (1 1))
qr-%offset%))
(setf (f2cl-lib:fref qr-%data%
(i k)
((1 ndim) (1 1))
qr-%offset%)
(f2cl-lib:fref qr-%data%
(i jbar)
((1 ndim) (1 1))
qr-%offset%))
(setf (f2cl-lib:fref qr-%data%
(i jbar)
((1 ndim) (1 1))
qr-%offset%)
sigma)
label50))
label70
(setf sigma
(ddot (f2cl-lib:int-add (f2cl-lib:int-sub n k) 1)
(f2cl-lib:array-slice qr-%data%
double-float
(k k)
((1 ndim) (1 1))
qr-%offset%)
1
(f2cl-lib:array-slice qr-%data%
double-float
(k k)
((1 ndim) (1 1))
qr-%offset%)
1))
(if (/= sigma 0.0f0) (go label60))
(setf ierr 1)
(go end_label)
label60
(if (= k n) (go label500))
(setf qrkk
(f2cl-lib:fref qr-%data% (k k) ((1 ndim) (1 1)) qr-%offset%))
(setf alphak (- (f2cl-lib:fsqrt sigma)))
(if (< qrkk 0.0f0) (setf alphak (- alphak)))
(setf (f2cl-lib:fref alpha-%data% (k) ((1 n)) alpha-%offset%) alphak)
(setf beta (/ 1.0f0 (- sigma (* qrkk alphak))))
(setf (f2cl-lib:fref qr-%data% (k k) ((1 ndim) (1 1)) qr-%offset%)
(- qrkk alphak))
(f2cl-lib:fdo (j kp1 (f2cl-lib:int-add j 1))
((> j np1) nil)
(tagbody
label80
(setf (f2cl-lib:fref y-%data% (j) ((1 1)) y-%offset%)
(* beta
(ddot (f2cl-lib:int-add (f2cl-lib:int-sub n k) 1)
(f2cl-lib:array-slice qr-%data%
double-float
(k k)
((1 ndim) (1 1))
qr-%offset%)
1
(f2cl-lib:array-slice qr-%data%
double-float
(k j)
((1 ndim) (1 1))
qr-%offset%)
1)))))
(f2cl-lib:fdo (j kp1 (f2cl-lib:int-add j 1))
((> j np1) nil)
(tagbody
(f2cl-lib:fdo (i k (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf (f2cl-lib:fref qr-%data%
(i j)
((1 ndim) (1 1))
qr-%offset%)
(-
(f2cl-lib:fref qr-%data%
(i j)
((1 ndim) (1 1))
qr-%offset%)
(*
(f2cl-lib:fref qr-%data%
(i k)
((1 ndim) (1 1))
qr-%offset%)
(f2cl-lib:fref y-%data% (j) ((1 1)) y-%offset%))))
label90))
(setf (f2cl-lib:fref sum-%data% (j) ((1 1)) sum-%offset%)
(- (f2cl-lib:fref sum-%data% (j) ((1 1)) sum-%offset%)
(expt
(f2cl-lib:fref qr-%data%
(k j)
((1 ndim) (1 1))
qr-%offset%)
2)))
label100))
label500))
(setf (f2cl-lib:fref alpha-%data% (n) ((1 n)) alpha-%offset%)
(f2cl-lib:fref qr-%data% (n n) ((1 ndim) (1 1)) qr-%offset%))
(go end_label)
end_label
(return (values nil nil nil nil nil ierr 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::dcpose
fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((fortran-to-lisp::integer4) (fortran-to-lisp::integer4)
(array double-float (*)) (array double-float (*))
(array fortran-to-lisp::integer4 (*))
(fortran-to-lisp::integer4) (array double-float (*))
(array double-float (*)))
:return-values '(nil nil nil nil nil fortran-to-lisp::ierr nil nil)
:calls '(fortran-to-lisp::ddot))))
| null | https://raw.githubusercontent.com/Eduap-com/WordMat/83c9336770067f54431cc42c7147dc6ed640a339/Windows/ExternalPrograms/maxima-5.45.1/share/maxima/5.45.1/share/hompack/lisp/dcpose.lisp | lisp | Compiled by f2cl version:
Using Lisp CMU Common Lisp snapshot-2020-04 (21D Unicode)
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 95098eb54f13 2013/04/01 00:45:16 toy $ "
" f2cl2.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ "
" f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl5.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ "
" f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ "
" macros.l , v 1409c1352feb 2013/03/24 20:44:50 toy $ " )
(in-package "HOMPACK")
(defun dcpose (ndim n qr alpha pivot ierr y sum)
(declare (type (array double-float (*)) sum y)
(type (array f2cl-lib:integer4 (*)) pivot)
(type (array double-float (*)) alpha qr)
(type (f2cl-lib:integer4) ierr n ndim))
(f2cl-lib:with-multi-array-data
((qr double-float qr-%data% qr-%offset%)
(alpha double-float alpha-%data% alpha-%offset%)
(pivot f2cl-lib:integer4 pivot-%data% pivot-%offset%)
(y double-float y-%data% y-%offset%)
(sum double-float sum-%data% sum-%offset%))
(prog ((beta 0.0) (sigma 0.0) (alphak 0.0) (qrkk 0.0) (i 0) (j 0) (jbar 0)
(k 0) (kp1 0) (np1 0))
(declare (type (f2cl-lib:integer4) np1 kp1 k jbar j i)
(type (double-float) qrkk alphak sigma beta))
(setf ierr 0)
(setf np1 (f2cl-lib:int-add n 1))
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j np1) nil)
(tagbody
(setf (f2cl-lib:fref sum-%data% (j) ((1 1)) sum-%offset%)
(ddot n
(f2cl-lib:array-slice qr-%data%
double-float
(1 j)
((1 ndim) (1 1))
qr-%offset%)
1
(f2cl-lib:array-slice qr-%data%
double-float
(1 j)
((1 ndim) (1 1))
qr-%offset%)
1))
label20
(setf (f2cl-lib:fref pivot-%data% (j) ((1 1)) pivot-%offset%) j)))
(f2cl-lib:fdo (k 1 (f2cl-lib:int-add k 1))
((> k n) nil)
(tagbody
(setf sigma (f2cl-lib:fref sum-%data% (k) ((1 1)) sum-%offset%))
(setf jbar k)
(setf kp1 (f2cl-lib:int-add k 1))
(f2cl-lib:fdo (j kp1 (f2cl-lib:int-add j 1))
((> j np1) nil)
(tagbody
(if
(>= sigma (f2cl-lib:fref sum-%data% (j) ((1 1)) sum-%offset%))
(go label40))
(setf sigma (f2cl-lib:fref sum-%data% (j) ((1 1)) sum-%offset%))
(setf jbar j)
label40))
(if (= jbar k) (go label70))
(setf i (f2cl-lib:fref pivot-%data% (k) ((1 1)) pivot-%offset%))
(setf (f2cl-lib:fref pivot-%data% (k) ((1 1)) pivot-%offset%)
(f2cl-lib:fref pivot-%data% (jbar) ((1 1)) pivot-%offset%))
(setf (f2cl-lib:fref pivot-%data% (jbar) ((1 1)) pivot-%offset%) i)
(setf (f2cl-lib:fref sum-%data% (jbar) ((1 1)) sum-%offset%)
(f2cl-lib:fref sum-%data% (k) ((1 1)) sum-%offset%))
(setf (f2cl-lib:fref sum-%data% (k) ((1 1)) sum-%offset%) sigma)
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf sigma
(f2cl-lib:fref qr-%data%
(i k)
((1 ndim) (1 1))
qr-%offset%))
(setf (f2cl-lib:fref qr-%data%
(i k)
((1 ndim) (1 1))
qr-%offset%)
(f2cl-lib:fref qr-%data%
(i jbar)
((1 ndim) (1 1))
qr-%offset%))
(setf (f2cl-lib:fref qr-%data%
(i jbar)
((1 ndim) (1 1))
qr-%offset%)
sigma)
label50))
label70
(setf sigma
(ddot (f2cl-lib:int-add (f2cl-lib:int-sub n k) 1)
(f2cl-lib:array-slice qr-%data%
double-float
(k k)
((1 ndim) (1 1))
qr-%offset%)
1
(f2cl-lib:array-slice qr-%data%
double-float
(k k)
((1 ndim) (1 1))
qr-%offset%)
1))
(if (/= sigma 0.0f0) (go label60))
(setf ierr 1)
(go end_label)
label60
(if (= k n) (go label500))
(setf qrkk
(f2cl-lib:fref qr-%data% (k k) ((1 ndim) (1 1)) qr-%offset%))
(setf alphak (- (f2cl-lib:fsqrt sigma)))
(if (< qrkk 0.0f0) (setf alphak (- alphak)))
(setf (f2cl-lib:fref alpha-%data% (k) ((1 n)) alpha-%offset%) alphak)
(setf beta (/ 1.0f0 (- sigma (* qrkk alphak))))
(setf (f2cl-lib:fref qr-%data% (k k) ((1 ndim) (1 1)) qr-%offset%)
(- qrkk alphak))
(f2cl-lib:fdo (j kp1 (f2cl-lib:int-add j 1))
((> j np1) nil)
(tagbody
label80
(setf (f2cl-lib:fref y-%data% (j) ((1 1)) y-%offset%)
(* beta
(ddot (f2cl-lib:int-add (f2cl-lib:int-sub n k) 1)
(f2cl-lib:array-slice qr-%data%
double-float
(k k)
((1 ndim) (1 1))
qr-%offset%)
1
(f2cl-lib:array-slice qr-%data%
double-float
(k j)
((1 ndim) (1 1))
qr-%offset%)
1)))))
(f2cl-lib:fdo (j kp1 (f2cl-lib:int-add j 1))
((> j np1) nil)
(tagbody
(f2cl-lib:fdo (i k (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf (f2cl-lib:fref qr-%data%
(i j)
((1 ndim) (1 1))
qr-%offset%)
(-
(f2cl-lib:fref qr-%data%
(i j)
((1 ndim) (1 1))
qr-%offset%)
(*
(f2cl-lib:fref qr-%data%
(i k)
((1 ndim) (1 1))
qr-%offset%)
(f2cl-lib:fref y-%data% (j) ((1 1)) y-%offset%))))
label90))
(setf (f2cl-lib:fref sum-%data% (j) ((1 1)) sum-%offset%)
(- (f2cl-lib:fref sum-%data% (j) ((1 1)) sum-%offset%)
(expt
(f2cl-lib:fref qr-%data%
(k j)
((1 ndim) (1 1))
qr-%offset%)
2)))
label100))
label500))
(setf (f2cl-lib:fref alpha-%data% (n) ((1 n)) alpha-%offset%)
(f2cl-lib:fref qr-%data% (n n) ((1 ndim) (1 1)) qr-%offset%))
(go end_label)
end_label
(return (values nil nil nil nil nil ierr 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::dcpose
fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((fortran-to-lisp::integer4) (fortran-to-lisp::integer4)
(array double-float (*)) (array double-float (*))
(array fortran-to-lisp::integer4 (*))
(fortran-to-lisp::integer4) (array double-float (*))
(array double-float (*)))
:return-values '(nil nil nil nil nil fortran-to-lisp::ierr nil nil)
:calls '(fortran-to-lisp::ddot))))
|
76e1ba35a6e3676a405e3cd1a756519f28b8f2cea7ee101a76eb5153b5f42c29 | sru-systems/protobuf-simple | DoubleListPacked.hs | -- Generated by protobuf-simple. DO NOT EDIT!
module Types.DoubleListPacked where
import Control.Applicative ((<$>))
import Prelude ()
import qualified Data.ProtoBufInt as PB
newtype DoubleListPacked = DoubleListPacked
{ value :: PB.Seq PB.Double
} deriving (PB.Show, PB.Eq, PB.Ord)
instance PB.Default DoubleListPacked where
defaultVal = DoubleListPacked
{ value = PB.defaultVal
}
instance PB.Mergeable DoubleListPacked where
merge a b = DoubleListPacked
{ value = PB.merge (value a) (value b)
}
instance PB.Required DoubleListPacked where
reqTags _ = PB.fromList []
instance PB.WireMessage DoubleListPacked where
fieldToValue (PB.WireTag 1 PB.LenDelim) self = (\v -> self{value = PB.merge (value self) v}) <$> PB.getDoublePacked
fieldToValue (PB.WireTag 1 PB.Bit64) self = (\v -> self{value = PB.append (value self) v}) <$> PB.getDouble
fieldToValue tag self = PB.getUnknown tag self
messageToFields self = do
PB.putDoublePacked (PB.WireTag 1 PB.LenDelim) (value self)
| null | https://raw.githubusercontent.com/sru-systems/protobuf-simple/ee0f26b6a8588ed9f105bc9ee72c38943133ed4d/test/Types/DoubleListPacked.hs | haskell | Generated by protobuf-simple. DO NOT EDIT! | module Types.DoubleListPacked where
import Control.Applicative ((<$>))
import Prelude ()
import qualified Data.ProtoBufInt as PB
newtype DoubleListPacked = DoubleListPacked
{ value :: PB.Seq PB.Double
} deriving (PB.Show, PB.Eq, PB.Ord)
instance PB.Default DoubleListPacked where
defaultVal = DoubleListPacked
{ value = PB.defaultVal
}
instance PB.Mergeable DoubleListPacked where
merge a b = DoubleListPacked
{ value = PB.merge (value a) (value b)
}
instance PB.Required DoubleListPacked where
reqTags _ = PB.fromList []
instance PB.WireMessage DoubleListPacked where
fieldToValue (PB.WireTag 1 PB.LenDelim) self = (\v -> self{value = PB.merge (value self) v}) <$> PB.getDoublePacked
fieldToValue (PB.WireTag 1 PB.Bit64) self = (\v -> self{value = PB.append (value self) v}) <$> PB.getDouble
fieldToValue tag self = PB.getUnknown tag self
messageToFields self = do
PB.putDoublePacked (PB.WireTag 1 PB.LenDelim) (value self)
|
aae61df78ad8bc2e486b72384ae2657ea1afc3a4039d267491e76e4d940b751f | glutamate/bugpan | PlotGnuplot.hs | # LANGUAGE GeneralizedNewtypeDeriving , FlexibleInstances , ExistentialQuantification #
# LANGUAGE TypeOperators , FlexibleContexts , GADTs , ScopedTypeVariables , DeriveDataTypeable #
module PlotGnuplot where
import EvalM
import System.IO
import System.Cmd
import System.Exit
--import Math.Probably.FoldingStats hiding (F)
import Control.Monad
import Data.Unique
import Data.List
import Control.Monad.Trans
import TNUtils
import System.Directory
import System . . Files
import Data.Array.Unboxed
import System.Random
stolen from gnuplot-0.3.3 ( )
import qualified System.Process as Proc
import Control.Concurrent
import Control.Exception
myForkIO :: IO () -> IO ()
myForkIO io = do
mvar <- newEmptyMVar
forkIO (io `finally` putMVar mvar ())
takeMVar mvar
putStrLn program
h@(inp,o,e,pid) <- Proc.runInteractiveCommand "gnuplot"
threadDelay $ 100*1000
myForkIO $ do tellInteractivePlot h "set terminal wxt noraise"
ma h
hClose o
hClose e
hClose inp
Proc.terminateProcess pid
Proc.waitForProcess pid
return ()
tellInteractivePlot (inp,o,e,p) s = do
hPutStr inp $ s++"\n"
hFlush inp
execGPPipe ::
^ The lines of the gnuplot script to be piped into gnuplot
-> IO ExitCode
execGPPipe program =
putStrLn program
(inp,_out,_err,pid) <-
Proc.runInteractiveProcess "gnuplot" [""] Nothing Nothing
hPutStr inp program
--print pid
Proc.waitForProcess pid
execGPSh ::
^ The lines of the gnuplot script to be piped into gnuplot
-- -> [String] {-^ Options for gnuplot -}
-> IO ExitCode
execGPSh program =
let cmd =
"sh -c 'echo " ++ quote ( program) ++
" | gnuplot '"
in do putStrLn cmd
system cmd
execGPPersist ::
^ The lines of the gnuplot script to be piped into gnuplot
-- -> [String] {-^ Options for gnuplot -}
-> IO ()
execGPPersist cmds = do
x <- randomRIO (0,99999999::Int)
let fnm = "/tmp/gnuplotCmds"++show x
writeFile fnm cmds
system $ "gnuplot -persist "++fnm
removeFile $ fnm
execGPTmp cmds = do
x <- randomRIO (0,99999999::Int)
let fnm = "/tmp/gnuplotCmds"++show x
writeFile fnm cmds
system $ "gnuplot "++fnm
removeFile $ fnm
execGP = execGPTmp
semiColonConcat = concat . intersperse "; "
quote :: String -> String
quote = show
--quote s =
{- end of theft -}
--histArr :: (Int,Int) -> [Double] -> UArray Int Double
histArr :: (Int, Int) -> [Int] -> UArray Int Double
histArr bnds is = accumArray (+) 0 bnds [( i, 1) | i<-is, inRange bnds i]
histValues :: Int -> [Double] -> [(Double,Double)]
histValues nbins vls =
let (hArr, lo, hi, binSize) = histList nbins vls
in zip [lo, lo+binSize..hi] hArr
histList :: Int -> [Double] -> ([Double] , Double, Double, Double)
histList _ [] = ([], 0, 0, 1)
histList nbins vls = let lo = foldl1' min vls
hi = foldl1' max vls
num = realToFrac $ length vls
binSize = (hi-lo)/(realToFrac nbins+1)
ixs = map (\v-> floor $! (v-lo)/binSize ) vls
hArr = histArr (0,nbins-1) $ ixs
in ((/num) `fmap` elems hArr, lo, hi, binSize)
histListBZ :: Double -> [Double] -> ([Double] , Double, Double, Double)
histListBZ _ [] = ([], 0, 0, 1)
histListBZ bz vls = let lo = foldl1' min vls
hi = foldl1' max vls
binSize = bz
nbins = round $ (hi-lo)/bz
ixs = map (\v-> floor $! (v-lo)/binSize ) vls
hArr = histArr (0,nbins) $ ixs
in (elems hArr, lo, hi, binSize)
histListFixed :: Double -> Double -> Double -> [Double] -> [Double]
histListFixed t1 t2 dt [] = take (round $ (t2-t1)/dt) $ repeat 0
histListFixed t1 t2 dt vls = let nbins = round $ (t2-t1)/dt
ixs = map (\v-> floor $! (v-t1)/dt ) vls
hArr = histArr (0,nbins-1) $ ixs
in elems hArr
uniqueIntStr = (show. hashUnique) `fmap` newUnique
type GnuplotCmd = [PlotLine]
data PlotLine = PL {plotData :: String,
plotTitle :: String,
plotWith :: String,
cleanUp :: IO () }
| TopLevelGnuplotCmd String String
plOnly pls = [pl | pl@(PL _ _ _ _) <- pls]
tlOnlyUnset pls = [s2 | pl@(TopLevelGnuplotCmd s1 s2) <- pls]
tlOnly pls = [s1 | pl@(TopLevelGnuplotCmd s1 s2) <- pls]
cleanupCmds :: [GnuplotCmd] -> IO ()
cleanupCmds cmds = forM_ cmds $ \plines -> sequence_ $ map cleanUp $ plOnly plines
setWith :: String -> GnuplotCmd -> GnuplotCmd
setWith sty = map f
where f pl@(PL _ _ _ _) = pl {plotWith = sty }
f tlcmd = tlcmd
showPlotCmd :: GnuplotCmd -> String
showPlotCmd [] = ""
showPlotCmd [TopLevelGnuplotCmd s s2] = s ++ "\n"++ s2
showPlotCmd plines = tls++"\nplot "++(intercalate ", " $ map s $ plOnly $ plines)++"\n"++untls
where s (PL dat tit wth _) = dat++title tit++withStr wth
title "" = " notitle"
title tit = " title '"++tit++"'"
withStr "" = ""
withStr s = " with "++s
tls = unlines $ tlOnly plines
untls = unlines $ tlOnlyUnset plines
showMultiPlot :: [(Rectangle, GnuplotCmd)] -> String
showMultiPlot rpls = "set multiplot\n" ++ concatMap pl rpls ++"\nunset multiplot\n"
where pl (r@(Rect (x0,y0) (x1,y1)), plines)=concat ["#"++show r++"\n",
"set origin ",
show x0, ",", show y0, "\n",
"set size ", show (x1-x0),
",", show (y1-y0), "\n",
showPlotCmd plines]
data Rectangle = Rect (Double, Double) (Double,Double) deriving Show
unitRect = Rect (0,0) (1,1)
rectTopLeft (Rect (x1,y1) (x2,y2)) = (x1+0.035,y2-0.010)
class PlotWithGnuplot a where
getGnuplotCmd :: a -> IO GnuplotCmd
getGnuplotCmd a = (snd . head) `fmap` multiPlot unitRect a
multiPlot :: Rectangle -> a -> IO [(Rectangle, GnuplotCmd)]
multiPlot r a = (\x->[(r, x)]) `fmap` getGnuplotCmd a
data GnuplotBox = forall a. PlotWithGnuplot a => GnuplotBox a
data Noplot = Noplot
instance PlotWithGnuplot Noplot where
getGnuplotCmd _ = return [PL "x" "" "lines lc rgb \"white\"" (return () ),
TopLevelGnuplotCmd "unset border; unset tics" "set border; set tics"]
instance PlotWithGnuplot GnuplotBox where
getGnuplotCmd (GnuplotBox x) = getGnuplotCmd x
instance PlotWithGnuplot [GnuplotBox] where
getGnuplotCmd xs = concat `fmap` mapM getGnuplotCmd xs
gnuplotOnScreen :: PlotWithGnuplot a => a -> IO ()
gnuplotOnScreen x = do
plines <- multiPlot unitRect x
let cmdLines = "set datafile missing \"NaN\"\n"++
(showMultiPlot plines)
writeFile "/tmp/gnuplotCmds" cmdLines
system "gnuplot -persist /tmp/gnuplotCmds"
--removeFile "/tmp/gnuplotCmds"
cleanupCmds $ map snd plines
return ()
gnuplotToPNG :: PlotWithGnuplot a => String -> a -> IO ()
gnuplotToPNG fp x = do
plines <- multiPlot unitRect x
let cmdLines = "set datafile missing \"NaN\"\n"++
"set terminal png\n"++
"set output '"++fp++"'\n"++
(showMultiPlot plines)
putStrLn cmdLines
execGP cmdLines
writeFile " /tmp / gnuplotCmds " cmdLines
system " gnuplot /tmp / gnuplotCmds "
removeFile " /tmp / gnuplotCmds "
system "gnuplot /tmp/gnuplotCmds"
removeFile "/tmp/gnuplotCmds" -}
cleanupCmds $ map snd plines
return ()
gnuplotToSparklinePNG :: PlotWithGnuplot a => String -> a -> IO ()
gnuplotToSparklinePNG fp x = do
plines <- multiPlot unitRect x
let cmdLines = "set datafile missing \"NaN\"\n"++
"set terminal png size 100,50 crop\n"++
"unset xtics\n"++
"unset ytics\n"++
"set border 0\n"++
"set output '"++fp++"'\n"++
(showMultiPlot plines)
execGP cmdLines
writeFile " /tmp / gnuplotCmds " cmdLines
system " gnuplot /tmp / gnuplotCmds 2>/dev / null "
removeFile " /tmp / gnuplotCmds "
system "gnuplot /tmp/gnuplotCmds 2>/dev/null"
removeFile "/tmp/gnuplotCmds"-}
cleanupCmds $ map snd plines
return ()
gnuplotToPDF:: PlotWithGnuplot a => String -> a -> IO ()
gnuplotToPDF fp x = do
gnuplotToPS fp x
system $ "ps2pdf "++fp
return ()
gnuplotToPS:: PlotWithGnuplot a => String-> a -> IO ()
gnuplotToPS fp x = do
plines <- multiPlot unitRect x
let cmdLines = "set datafile missing \"NaN\"\n"++
"set terminal postscript eps enhanced color \"Helvetica\" 8\n"++
"set output '"++fp++"'\n"++
(showMultiPlot plines)
execGP cmdLines
writeFile " /tmp / gnuplotCmds " cmdLines
system " gnuplot /tmp / gnuplotCmds "
removeFile " /tmp / gnuplotCmds "
system "gnuplot /tmp/gnuplotCmds"
removeFile "/tmp/gnuplotCmds"-}
cleanupCmds $ map snd plines
return ()
gnuplotMany :: [String] -> [(String, GnuplotBox)] -> IO ()
gnuplotMany opts nmbxs = do
nmcmds <- forM nmbxs $ \(nm, GnuplotBox x) -> do
cmd <- multiPlot unitRect x
cmd
return (nm,cmd)
let start = "set datafile missing \"NaN\"\n"
let h = optVal 'h' 480 opts
let w = optVal 'w' 640 opts
let term = "set terminal png size "++ show w++","++show h++" crop\n"
let cmds = start++term ++concatMap plotOne nmcmds
execGP cmds
forM_ nmcmds $ \(_,cmd) -> cleanupCmds $ map snd cmd
return ()
where plotOne (fp, plines) = "set output '"++fp++"'\n"++
(showMultiPlot plines)
gnuplotManyLatex :: [String] -> [(String, GnuplotBox)] -> IO ()
gnuplotManyLatex opts nmbxs = do
nmcmds <- forM nmbxs $ \(nm, GnuplotBox x) -> do
cmd <- multiPlot unitRect x
cmd
return (nm,cmd)
let start = "set datafile missing \"NaN\"\n"
let h::Double = (/10) $ realToFrac $ optVal 'h' (35::Int) opts
let w::Double = (/10) $ realToFrac $ optVal 'w' (50::Int) opts
let fs = optVal 'f' 16 opts
let term = "set terminal postscript eps enhanced color \"Helvetica\" "++show fs++" size "++ show w++","++show h++"\n"-- crop\n"
let cmds = start++term ++concatMap plotOne nmcmds
execGP cmds
forM_ nmcmds $ \(nm,cmd) -> do
system $ "epstopdf "++nm++".eps"
cleanupCmds $ map snd cmd
return ()
where plotOne (fp, plines) = "set output '"++fp++".eps'\n"++
(showMultiPlot plines)
infixl 4 %
infixr 3 :+:
infixr 2 :|:
infixr 1 :--:
data a :+: b = a :+: b
data a :||: b = a :||: b
data a :|: b = PcntDiv a :|: PcntDiv b
: b = PcntDiv a : -- : PcntDiv b
data a :==: b = a :==: b
data Hplots a = Hplots [a]
data Vplots a = Vplots [a]
data PcntDiv a = Pcnt Double a
data WithColour a = WithColour String a
x % a = Pcnt x a
data SubLabel a =
A a | Ai a | Aii a | Aiii a
| B a | Bi a | Bii a | Biii a
| C a | Ci a | Cii a | Ciii a
| D a | Di a | Dii a | Diii a
| E a | Ei a | Eii a
| SubNum Int a
subLabSplit :: SubLabel a -> (String, a)
subLabSplit (A x) = ("A",x)
subLabSplit (Ai x) = ("Ai",x)
subLabSplit (Aii x) = ("Aii",x)
subLabSplit (Aiii x) = ("Aiii",x)
subLabSplit (B x) = ("B",x)
subLabSplit (Bi x) = ("Bi",x)
subLabSplit (Bii x) = ("Bii",x)
subLabSplit (Biii x) = ("Biii",x)
subLabSplit (C x) = ("C",x)
subLabSplit (Ci x) = ("Ci",x)
subLabSplit (Cii x) = ("Cii",x)
subLabSplit (Ciii x) = ("Ciii",x)
subLabSplit (D x) = ("D",x)
subLabSplit (Di x) = ("Di",x)
subLabSplit (Dii x) = ("Dii",x)
subLabSplit (Diii x) = ("Diii",x)
subLabSplit (E x) = ("E",x)
subLabSplit (SubNum n x) = (show n, x)
newtype Lines a = Lines { unLines : : a }
--newtype Dashed a = Dashed {unDashed :: a }
newtype Boxes a = Boxes {unBoxes :: a }
data Lines a = Lines [StyleOpt] a
data LinesPoints a = LinesPoints [StyleOpt] a
data Points a = Points [StyleOpt] a
data StyleOpt = LineWidth Double
| LineType Int
| LineStyle Int
| LineColor String
| PointType Int
| PointSize Double
styleOptsToString :: [StyleOpt] -> String
styleOptsToString = intercalate " " . map g
where g (LineType lt) = "lt "++show lt
g (LineWidth lt) = "lw "++show lt
g (LineStyle lt) = "ls "++show lt
g (LineColor lc) = "lc rgb "++show lc
g (PointType lt) = "pt "++show lt
g (PointSize lt) = "ps "++show lt
instance PlotWithGnuplot a => PlotWithGnuplot (Lines a) where
multiPlot r (Lines sos x) = do
px <- multiPlot r x
let wstr = styleOptsToString sos
return $ map (\(r', pls) -> (r', setWith ("lines "++wstr) pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (LinesPoints a) where
multiPlot r (LinesPoints sos x) = do
px <- multiPlot r x
let wstr = styleOptsToString sos
return $ map (\(r', pls) -> (r', setWith ("linespoints "++wstr) pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (Points a) where
multiPlot r (Points sos x) = do
px <- multiPlot r x
let wstr = styleOptsToString sos
return $ map (\(r', pls) -> (r', setWith ("points "++wstr) pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (Boxes a) where
multiPlot r (Boxes x) = do
px <- multiPlot r x
return $ map (\(r', pls) -> (r', setWith "boxes" pls)) px
data GnuplotTest = GnuplotTest
instance PlotWithGnuplot (GnuplotTest) where
multiPlot r _ = do
return $ [(r, [TopLevelGnuplotCmd "test" ""])]
data Margin a = Margin Double Double Double Double a
data XRange a = XRange Double Double a
data YRange a = YRange Double Double a
data XTics a = XTics [Double] a | XTicLabel [(String, Double)] a
data YTics a = YTics [Double] a
data TicFormat a = TicFormat XY String a
data XY = X | Y | XY
data Noaxis a = Noaxis a
| NoXaxis a
| NoYaxis a
| NoTRaxis a
data Key a = KeyTopLeft Bool a
| KeyTopRight Bool a
| KeyLowRight Bool a
setMargin (Margin b t l r _) = unlines ["set bmargin "++show b,
"set lmargin "++show l,
"set rmargin "++show r,
"set tmargin "++show t]
unsetMargin = unlines ["unset bmargin ",
"unset lmargin ",
"unset rmargin ",
"unset tmargin "]
instance PlotWithGnuplot a => PlotWithGnuplot (Margin a) where
multiPlot r m@(Margin _ _ _ _ x) = do
px <- multiPlot r x
let setit = setMargin m
return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit unsetMargin):pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (XRange a) where
multiPlot r m@(XRange lo hi x) = do
px <- multiPlot r x
let setit = "set xrange ["++show lo++":"++show hi++"]\n"
return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "set xrange [*:*]"):pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (TicFormat a) where
multiPlot r m@(TicFormat xy s x) = do
px <- multiPlot r x
let whereStr X = "x"
whereStr Y = "y"
whereStr XY = "xy"
let setit = "set format "++whereStr xy++" "++show s++"\n"
return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "unset format"):pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (Key a) where
multiPlot r m@(KeyTopLeft box x) = do
px <- multiPlot r x
let boxs = if box then "box" else ""
let setit = "set key top left "++boxs++"\n"
return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "set key default"):pls)) px
multiPlot r m@(KeyLowRight box x) = do
px <- multiPlot r x
let boxs = if box then "box" else ""
let setit = "set key bottom right "++boxs++"\n"
return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "set key default"):pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (Noaxis a) where
multiPlot r m@(Noaxis x) = do
px <- multiPlot r x
let cmd = TopLevelGnuplotCmd "unset border; unset tics" "set border; set tics"
return $ map (\(r', pls) -> (r', cmd:pls)) px
multiPlot r m@(NoYaxis x) = do
px <- multiPlot r x
let cmd = TopLevelGnuplotCmd "set border 1; set tics" "set border; set tics"
return $ map (\(r', pls) -> (r', cmd:pls)) px
multiPlot r m@(NoXaxis x) = do
px <- multiPlot r x
let cmd = TopLevelGnuplotCmd "set border 2; set tics" "set border; set tics"
return $ map (\(r', pls) -> (r', cmd:pls)) px
multiPlot r m@(NoTRaxis x) = do
px <- multiPlot r x
let cmd = TopLevelGnuplotCmd "set border 3; set tics; set xtics nomirror; set ytics nomirror" "set border; set tics"
return $ map (\(r', pls) -> (r', cmd:pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (XTics a) where
multiPlot r m@(XTics tics x) = do
px <- multiPlot r x
let setit = "set xtics "++ (intercalate ", " $ map show tics) ++"\n"
return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "set xtics autofreq"):pls)) px
multiPlot r m@(XTicLabel tics x) = do
px <- multiPlot r x
let showTic (lab, loc) = show lab++" "++show loc
let setit = "set xtics ("++ (intercalate ", " $ map showTic tics) ++")\n"
return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "set xtics autofreq"):pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (YTics a) where
multiPlot r m@(YTics tics x) = do
px <- multiPlot r x
let setit = "set ytics "++ (intercalate ", " $ map show tics) ++"\n"
return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "set xtics autofreq"):pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (YRange a) where
multiPlot r m@(YRange lo hi x) = do
px <- multiPlot r x
let setit = "set yrange ["++show lo++":"++show hi++"]\n"
return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "set yrange [*:*]"):pls)) px
lineWidth w = Lines [LineWidth w]
lineType t = Lines [LineType t]
pointSize t = Points [PointSize t]
pointType t = Points [PointType t]
data CustAxis = CustAxis {
caOrigin :: (Double,Double),
caLength :: Double,
caVertical :: Bool,
caTicLen :: Double,
caTicOffset :: Double,
caTics :: [(Double, String)]
}
data WithAxis a = WithAxis CustAxis a
instance PlotWithGnuplot a => PlotWithGnuplot (WithAxis a) where
multiPlot r (WithAxis (CustAxis (x0,y0) len True tlen toff tics) x) = do
let ticCmds (y,txt) =
[TopLevelGnuplotCmd ("set arrow from first "++show x0++","++show (y0+y)++
" to first "++show (x0-tlen)++","++show (y0+y)++" nohead front")
"unset arrow",
TopLevelGnuplotCmd ("set label "++show txt++" at first "++
show (x0-toff)++","++show (y0+y)++" right front")
"unset label"
]
let cmds = TopLevelGnuplotCmd ("set arrow from first "++show x0++","++show y0++
" to first "++show x0++","++show (y0+len)++" nohead front")
"unset arrow" : concatMap ticCmds tics
px <- multiPlot r $ x
return $ map (\(r', pls) -> (r', cmds++pls)) px
data ScaleBars a = ScaleBars (Double, Double) (Double,String) (Double,String) a
| XScaleBar (Double, Double) (Double,String) Double a
| YScaleBar (Double, Double) (Double,String) Double a
data LineAt a = LineAt (Double, Double) (Double, Double) a
data ArrowAt a = ArrowAt (Double, Double) (Double, Double) a
data TextAt a = TextAt (Double, Double) String a
| TextAtLeft (Double, Double) String a
| TextAtRot (Double,Double) String a
instance PlotWithGnuplot a => PlotWithGnuplot (TextAt a) where
multiPlot r (TextAt (x0,y0) s x) = do
let mklab = TopLevelGnuplotCmd ("set label "++show s++" at first "++show x0++","++show y0++" center front")
"unset label"
px <- multiPlot r x
return $ map (\(r', pls) -> (r', mklab:pls)) px
multiPlot r (TextAtRot (x0,y0) s x) = do
let mklab = TopLevelGnuplotCmd ("set label "++show s++" at first "++show x0++","++show y0++" center front rotate")
"unset label"
px <- multiPlot r x
return $ map (\(r', pls) -> (r', mklab:pls)) px
multiPlot r (TextAtLeft (x0,y0) s x) = do
let mklab = TopLevelGnuplotCmd ("set label "++show s++" at first "++show x0++","++show y0++" left front")
"unset label"
px <- multiPlot r x
return $ map (\(r', pls) -> (r', mklab:pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (LineAt a) where
multiPlot r (LineAt (x0,y0) (x1, y1) x) = do
let mklab = TopLevelGnuplotCmd ("set arrow from first "++show x0++","++show y0++" to first "++show x1++","++show y1++" nohead front")
"unset arrow"
px <- multiPlot r x
return $ map (\(r', pls) -> (r', mklab:pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (ArrowAt a) where
multiPlot r (ArrowAt (x0,y0) (x1, y1) x) = do
let mklab = TopLevelGnuplotCmd ("set arrow from first "++show x0++","++show y0++" to first "++show x1++","++show y1++" heads front")
"unset arrow"
px <- multiPlot r x
return $ map (\(r', pls) -> (r', mklab:pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (ScaleBars a) where
multiPlot r (ScaleBars p0 (xsz, xtxt) (ysz, ytxt) x) = do
multiPlot r $ XScaleBar p0 (xsz, xtxt) (ysz/4) $ YScaleBar p0 (ysz, ytxt) (xsz/2) x
multiPlot r (XScaleBar (x0,y0) (xsz, xtxt) yo x) = do
let xtxtpos = (x0+xsz/2, y0 - yo)
multiPlot r $ LineAt (x0, y0) (x0+xsz, y0)
$ TextAt xtxtpos xtxt x
multiPlot r (YScaleBar (x0,y0) (ysz, ytxt) yo x) = do
let ytxtpos = (x0+yo, y0 + ysz/2)
multiPlot r $ LineAt (x0, y0) (x0, y0+ysz)
$ TextAt ytxtpos ytxt x
data TicFont a = TicFont String a
data CanvasScale a = CanvasScale Double Double a
instance PlotWithGnuplot a => PlotWithGnuplot (CanvasScale a) where
multiPlot r (CanvasScale xsz ysz x) = do
let mklab = TopLevelGnuplotCmd ("set size "++show xsz++","++show ysz)
""
px <- multiPlot r x
return $ map (\(r', pls) -> (r', mklab:pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (TicFont a) where
multiPlot r (TicFont str x) = do
let mklab = TopLevelGnuplotCmd ("set tics font "++show str)
""
px <- multiPlot r x
return $ map (\(r', pls) -> (r', mklab:pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (SubLabel a) where
multiPlot r sl = do
let (lab, x ) = subLabSplit sl
(xpos, ypos) = rectTopLeft r
let mklab = TopLevelGnuplotCmd ("set label "++show lab++" at screen "++show xpos++","++show ypos++" front")
"unset label"
px <- multiPlot r x
return $ map (\(r', pls) -> (r', mklab:pls)) px
data CentreLabel = CentreLabel String
instance PlotWithGnuplot CentreLabel where
multiPlot r (CentreLabel str) = do
let mklab = TopLevelGnuplotCmd ("set label "++show str++" at graph 0.5,0.5 center front") "unset label"
nop::[GnuplotCmd] <- fmap (map snd) $ multiPlot r Noplot
return [(r, mklab:concat nop)]
data AxisLabels a = AxisLabels String String a
| XLabel String a
| YLabel String a
instance PlotWithGnuplot a => PlotWithGnuplot (AxisLabels a) where
multiPlot r (AxisLabels xlab ylab x) = do
let mklabs = [TopLevelGnuplotCmd ("set xlabel "++show xlab) "unset xlabel",
TopLevelGnuplotCmd ("set ylabel "++show ylab) "unset ylabel"]
px <- multiPlot r x
return $ map (\(r', pls) -> (r', mklabs++pls)) px
multiPlot r (XLabel xlab x) = do
let mklabs = [TopLevelGnuplotCmd ("set xlabel "++show xlab) "unset xlabel"]
px <- multiPlot r x
return $ map (\(r', pls) -> (r', mklabs++pls)) px
multiPlot r (YLabel xlab x) = do
let mklabs = [TopLevelGnuplotCmd ("set ylabel "++show xlab) "unset ylabel"]
px <- multiPlot r x
return $ map (\(r', pls) -> (r', mklabs++pls)) px
data Pad a = Pad Double a
| PadX Double Double a
| PadY Double Double a
instance (PlotWithGnuplot a) => PlotWithGnuplot (Pad a) where
multiPlot r (Pad p x) = multiPlot r $ PadX p p $ PadY p p x
multiPlot (Rect (x0, y0) (x1,y1)) (PadX p1 p2 x) = do
let xw = (x1 - x0)
px <- multiPlot (Rect (x0+xw*p1,y0) (x1-xw*p2, y1) ) x
return $ px
multiPlot (Rect (x0, y0) (x1,y1)) (PadY p1 p2 x) = do
let yh = (y1 - y0)
px <- multiPlot ( Rect (x0,y0+yh*p1) (x1, y1-yh*p2) ) x
return $ px
instance (PlotWithGnuplot a, PlotWithGnuplot b) => PlotWithGnuplot (a :||: b) where
multiPlot r (xs :||: ys) = multiPlot r (50% xs :|: 50% ys)
instance (PlotWithGnuplot a, PlotWithGnuplot b) => PlotWithGnuplot (a :==: b) where
: 50 % ys )
instance (PlotWithGnuplot a, PlotWithGnuplot b) => PlotWithGnuplot ( a :|: b) where
multiPlot (Rect (x0, y0) (x1,y1)) (Pcnt pcp p :|: Pcnt pcq q) = do
let xsep = x0+(pcp/(pcp+pcq))*(x1-x0)
px <- multiPlot ( Rect (x0,y0) (xsep, y1) ) p
py <- multiPlot ( Rect (xsep,y0) (x1, y1) ) q
return $ px++py
instance (PlotWithGnuplot a, PlotWithGnuplot b) => PlotWithGnuplot ( a :--: b) where
: Pcnt pcq q ) = do
let ysep = y0+(pcq/(pcp+pcq))*(y1-y0)
px <- multiPlot ( Rect (x0,y0) (x1, ysep) ) q
py <- multiPlot ( Rect (x0, ysep) (x1, y1) ) p
return $ py++px
instance (PlotWithGnuplot a, PlotWithGnuplot b) => PlotWithGnuplot (a :+: b) where
multiPlot r (xs :+: ys) = do
px <- getGnuplotCmd xs
py <- getGnuplotCmd ys
return $ [(r,px++py)]
instance (PlotWithGnuplot a, PlotWithGnuplot b) => PlotWithGnuplot (Either a b) where
multiPlot r (Left xs) = multiPlot r xs
multiPlot r (Right xs) = multiPlot r xs
instance (PlotWithGnuplot a) => PlotWithGnuplot (Hplots a) where
multiPlot (Rect (x0, y0) (x1,y1)) (Hplots ps) = do
let n = realToFrac $ length ps
let xeach = (x1-x0)/n
pls <- forM (zip ps [0..]) $ \(p,i) ->
multiPlot ( Rect (x0+(i*xeach),y0) (x0+((i+1)*xeach), y1) ) p
return $ concat pls
instance (PlotWithGnuplot a) => PlotWithGnuplot (Vplots a) where
multiPlot (Rect (x0, y0) (x1,y1)) (Vplots ps) = do
let n = realToFrac $ length ps
let yeach = (y1-y0)/n
pls <- forM (zip ps [0..]) $ \(p,i) ->
multiPlot ( Rect (x0,y0+(i*yeach)) (x1, y0+((i+1)*yeach)) ) p
return $ concat pls
instance PlotWithGnuplot a => PlotWithGnuplot (String, a) where
multiPlot r (title, x) = do
pls <- multiPlot r x
return $ map (\(r', plines) -> (r' ,map (addTitle title) plines)) pls
where addTitle title (PL x _ y clean) = PL x title y clean
newtype LabelConsecutively a = LabelConsecutively a
instance PlotWithGnuplot a => PlotWithGnuplot (LabelConsecutively [a]) where
getGnuplotCmd (LabelConsecutively xs) = do
pls::[ GnuplotCmd] <- mapM (getGnuplotCmd) xs
return $ concatMap (\(rs,i)-> (addTitleMany (show i)) rs) $ zip pls [0..]
where addTitle title (PL x _ y clean) = PL x title y clean
addTitleMany :: String -> ( GnuplotCmd) -> ( GnuplotCmd)
addTitleMany title (cmd) = ( map (addTitle title) cmd)
--tilePlots :: PlotWithGnuplot a => Int -> [a] -> Vplots (Hplots a)
tilePlots :: Int -> [t] -> Vplots (Hplots (SubLabel (Either t Noplot)))
tilePlots n ps = let nps = (length ps)
nfinal = if nps `mod` n == 0
then nps
else ((nps `div` n)+1)*n
allps = ensureLength (nfinal) Noplot ps
in Vplots $ map Hplots $ map (map (\(p,i) -> SubNum i p)) $ groupsOf n (zip allps [0..])
gridPlot :: [[GnuplotBox]] -> Vplots (Hplots GnuplotBox)
gridPlot plots = Vplots $ map Hplots plots
groupsOf n [] = []
groupsOf n xs = let (mine, rest) = splitAt n xs
in mine: groupsOf n rest
ensureLength n filler xs = map Left xs++replicate (n - length xs) (Right filler)
instance a = > PlotWithR ( Hist a ) where
getRPlotCmd ( Histogram tgs ) =
plotHisto $ map
getRPlotCmd (Histogram tgs) =
plotHisto $ map getTag tgs
-} | null | https://raw.githubusercontent.com/glutamate/bugpan/d0983152f5afce306049262cba296df00e52264b/PlotGnuplot.hs | haskell | import Math.Probably.FoldingStats hiding (F)
print pid
-> [String] {-^ Options for gnuplot -}
-> [String] {-^ Options for gnuplot -}
quote s =
end of theft
histArr :: (Int,Int) -> [Double] -> UArray Int Double
removeFile "/tmp/gnuplotCmds"
crop\n"
:
: PcntDiv b
newtype Dashed a = Dashed {unDashed :: a }
: b) where
tilePlots :: PlotWithGnuplot a => Int -> [a] -> Vplots (Hplots a) | # LANGUAGE GeneralizedNewtypeDeriving , FlexibleInstances , ExistentialQuantification #
# LANGUAGE TypeOperators , FlexibleContexts , GADTs , ScopedTypeVariables , DeriveDataTypeable #
module PlotGnuplot where
import EvalM
import System.IO
import System.Cmd
import System.Exit
import Control.Monad
import Data.Unique
import Data.List
import Control.Monad.Trans
import TNUtils
import System.Directory
import System . . Files
import Data.Array.Unboxed
import System.Random
stolen from gnuplot-0.3.3 ( )
import qualified System.Process as Proc
import Control.Concurrent
import Control.Exception
myForkIO :: IO () -> IO ()
myForkIO io = do
mvar <- newEmptyMVar
forkIO (io `finally` putMVar mvar ())
takeMVar mvar
putStrLn program
h@(inp,o,e,pid) <- Proc.runInteractiveCommand "gnuplot"
threadDelay $ 100*1000
myForkIO $ do tellInteractivePlot h "set terminal wxt noraise"
ma h
hClose o
hClose e
hClose inp
Proc.terminateProcess pid
Proc.waitForProcess pid
return ()
tellInteractivePlot (inp,o,e,p) s = do
hPutStr inp $ s++"\n"
hFlush inp
execGPPipe ::
^ The lines of the gnuplot script to be piped into gnuplot
-> IO ExitCode
execGPPipe program =
putStrLn program
(inp,_out,_err,pid) <-
Proc.runInteractiveProcess "gnuplot" [""] Nothing Nothing
hPutStr inp program
Proc.waitForProcess pid
execGPSh ::
^ The lines of the gnuplot script to be piped into gnuplot
-> IO ExitCode
execGPSh program =
let cmd =
"sh -c 'echo " ++ quote ( program) ++
" | gnuplot '"
in do putStrLn cmd
system cmd
execGPPersist ::
^ The lines of the gnuplot script to be piped into gnuplot
-> IO ()
execGPPersist cmds = do
x <- randomRIO (0,99999999::Int)
let fnm = "/tmp/gnuplotCmds"++show x
writeFile fnm cmds
system $ "gnuplot -persist "++fnm
removeFile $ fnm
execGPTmp cmds = do
x <- randomRIO (0,99999999::Int)
let fnm = "/tmp/gnuplotCmds"++show x
writeFile fnm cmds
system $ "gnuplot "++fnm
removeFile $ fnm
execGP = execGPTmp
semiColonConcat = concat . intersperse "; "
quote :: String -> String
quote = show
histArr :: (Int, Int) -> [Int] -> UArray Int Double
histArr bnds is = accumArray (+) 0 bnds [( i, 1) | i<-is, inRange bnds i]
histValues :: Int -> [Double] -> [(Double,Double)]
histValues nbins vls =
let (hArr, lo, hi, binSize) = histList nbins vls
in zip [lo, lo+binSize..hi] hArr
histList :: Int -> [Double] -> ([Double] , Double, Double, Double)
histList _ [] = ([], 0, 0, 1)
histList nbins vls = let lo = foldl1' min vls
hi = foldl1' max vls
num = realToFrac $ length vls
binSize = (hi-lo)/(realToFrac nbins+1)
ixs = map (\v-> floor $! (v-lo)/binSize ) vls
hArr = histArr (0,nbins-1) $ ixs
in ((/num) `fmap` elems hArr, lo, hi, binSize)
histListBZ :: Double -> [Double] -> ([Double] , Double, Double, Double)
histListBZ _ [] = ([], 0, 0, 1)
histListBZ bz vls = let lo = foldl1' min vls
hi = foldl1' max vls
binSize = bz
nbins = round $ (hi-lo)/bz
ixs = map (\v-> floor $! (v-lo)/binSize ) vls
hArr = histArr (0,nbins) $ ixs
in (elems hArr, lo, hi, binSize)
histListFixed :: Double -> Double -> Double -> [Double] -> [Double]
histListFixed t1 t2 dt [] = take (round $ (t2-t1)/dt) $ repeat 0
histListFixed t1 t2 dt vls = let nbins = round $ (t2-t1)/dt
ixs = map (\v-> floor $! (v-t1)/dt ) vls
hArr = histArr (0,nbins-1) $ ixs
in elems hArr
uniqueIntStr = (show. hashUnique) `fmap` newUnique
type GnuplotCmd = [PlotLine]
data PlotLine = PL {plotData :: String,
plotTitle :: String,
plotWith :: String,
cleanUp :: IO () }
| TopLevelGnuplotCmd String String
plOnly pls = [pl | pl@(PL _ _ _ _) <- pls]
tlOnlyUnset pls = [s2 | pl@(TopLevelGnuplotCmd s1 s2) <- pls]
tlOnly pls = [s1 | pl@(TopLevelGnuplotCmd s1 s2) <- pls]
cleanupCmds :: [GnuplotCmd] -> IO ()
cleanupCmds cmds = forM_ cmds $ \plines -> sequence_ $ map cleanUp $ plOnly plines
setWith :: String -> GnuplotCmd -> GnuplotCmd
setWith sty = map f
where f pl@(PL _ _ _ _) = pl {plotWith = sty }
f tlcmd = tlcmd
showPlotCmd :: GnuplotCmd -> String
showPlotCmd [] = ""
showPlotCmd [TopLevelGnuplotCmd s s2] = s ++ "\n"++ s2
showPlotCmd plines = tls++"\nplot "++(intercalate ", " $ map s $ plOnly $ plines)++"\n"++untls
where s (PL dat tit wth _) = dat++title tit++withStr wth
title "" = " notitle"
title tit = " title '"++tit++"'"
withStr "" = ""
withStr s = " with "++s
tls = unlines $ tlOnly plines
untls = unlines $ tlOnlyUnset plines
showMultiPlot :: [(Rectangle, GnuplotCmd)] -> String
showMultiPlot rpls = "set multiplot\n" ++ concatMap pl rpls ++"\nunset multiplot\n"
where pl (r@(Rect (x0,y0) (x1,y1)), plines)=concat ["#"++show r++"\n",
"set origin ",
show x0, ",", show y0, "\n",
"set size ", show (x1-x0),
",", show (y1-y0), "\n",
showPlotCmd plines]
data Rectangle = Rect (Double, Double) (Double,Double) deriving Show
unitRect = Rect (0,0) (1,1)
rectTopLeft (Rect (x1,y1) (x2,y2)) = (x1+0.035,y2-0.010)
class PlotWithGnuplot a where
getGnuplotCmd :: a -> IO GnuplotCmd
getGnuplotCmd a = (snd . head) `fmap` multiPlot unitRect a
multiPlot :: Rectangle -> a -> IO [(Rectangle, GnuplotCmd)]
multiPlot r a = (\x->[(r, x)]) `fmap` getGnuplotCmd a
data GnuplotBox = forall a. PlotWithGnuplot a => GnuplotBox a
data Noplot = Noplot
instance PlotWithGnuplot Noplot where
getGnuplotCmd _ = return [PL "x" "" "lines lc rgb \"white\"" (return () ),
TopLevelGnuplotCmd "unset border; unset tics" "set border; set tics"]
instance PlotWithGnuplot GnuplotBox where
getGnuplotCmd (GnuplotBox x) = getGnuplotCmd x
instance PlotWithGnuplot [GnuplotBox] where
getGnuplotCmd xs = concat `fmap` mapM getGnuplotCmd xs
gnuplotOnScreen :: PlotWithGnuplot a => a -> IO ()
gnuplotOnScreen x = do
plines <- multiPlot unitRect x
let cmdLines = "set datafile missing \"NaN\"\n"++
(showMultiPlot plines)
writeFile "/tmp/gnuplotCmds" cmdLines
system "gnuplot -persist /tmp/gnuplotCmds"
cleanupCmds $ map snd plines
return ()
gnuplotToPNG :: PlotWithGnuplot a => String -> a -> IO ()
gnuplotToPNG fp x = do
plines <- multiPlot unitRect x
let cmdLines = "set datafile missing \"NaN\"\n"++
"set terminal png\n"++
"set output '"++fp++"'\n"++
(showMultiPlot plines)
putStrLn cmdLines
execGP cmdLines
writeFile " /tmp / gnuplotCmds " cmdLines
system " gnuplot /tmp / gnuplotCmds "
removeFile " /tmp / gnuplotCmds "
system "gnuplot /tmp/gnuplotCmds"
removeFile "/tmp/gnuplotCmds" -}
cleanupCmds $ map snd plines
return ()
gnuplotToSparklinePNG :: PlotWithGnuplot a => String -> a -> IO ()
gnuplotToSparklinePNG fp x = do
plines <- multiPlot unitRect x
let cmdLines = "set datafile missing \"NaN\"\n"++
"set terminal png size 100,50 crop\n"++
"unset xtics\n"++
"unset ytics\n"++
"set border 0\n"++
"set output '"++fp++"'\n"++
(showMultiPlot plines)
execGP cmdLines
writeFile " /tmp / gnuplotCmds " cmdLines
system " gnuplot /tmp / gnuplotCmds 2>/dev / null "
removeFile " /tmp / gnuplotCmds "
system "gnuplot /tmp/gnuplotCmds 2>/dev/null"
removeFile "/tmp/gnuplotCmds"-}
cleanupCmds $ map snd plines
return ()
gnuplotToPDF:: PlotWithGnuplot a => String -> a -> IO ()
gnuplotToPDF fp x = do
gnuplotToPS fp x
system $ "ps2pdf "++fp
return ()
gnuplotToPS:: PlotWithGnuplot a => String-> a -> IO ()
gnuplotToPS fp x = do
plines <- multiPlot unitRect x
let cmdLines = "set datafile missing \"NaN\"\n"++
"set terminal postscript eps enhanced color \"Helvetica\" 8\n"++
"set output '"++fp++"'\n"++
(showMultiPlot plines)
execGP cmdLines
writeFile " /tmp / gnuplotCmds " cmdLines
system " gnuplot /tmp / gnuplotCmds "
removeFile " /tmp / gnuplotCmds "
system "gnuplot /tmp/gnuplotCmds"
removeFile "/tmp/gnuplotCmds"-}
cleanupCmds $ map snd plines
return ()
gnuplotMany :: [String] -> [(String, GnuplotBox)] -> IO ()
gnuplotMany opts nmbxs = do
nmcmds <- forM nmbxs $ \(nm, GnuplotBox x) -> do
cmd <- multiPlot unitRect x
cmd
return (nm,cmd)
let start = "set datafile missing \"NaN\"\n"
let h = optVal 'h' 480 opts
let w = optVal 'w' 640 opts
let term = "set terminal png size "++ show w++","++show h++" crop\n"
let cmds = start++term ++concatMap plotOne nmcmds
execGP cmds
forM_ nmcmds $ \(_,cmd) -> cleanupCmds $ map snd cmd
return ()
where plotOne (fp, plines) = "set output '"++fp++"'\n"++
(showMultiPlot plines)
gnuplotManyLatex :: [String] -> [(String, GnuplotBox)] -> IO ()
gnuplotManyLatex opts nmbxs = do
nmcmds <- forM nmbxs $ \(nm, GnuplotBox x) -> do
cmd <- multiPlot unitRect x
cmd
return (nm,cmd)
let start = "set datafile missing \"NaN\"\n"
let h::Double = (/10) $ realToFrac $ optVal 'h' (35::Int) opts
let w::Double = (/10) $ realToFrac $ optVal 'w' (50::Int) opts
let fs = optVal 'f' 16 opts
let cmds = start++term ++concatMap plotOne nmcmds
execGP cmds
forM_ nmcmds $ \(nm,cmd) -> do
system $ "epstopdf "++nm++".eps"
cleanupCmds $ map snd cmd
return ()
where plotOne (fp, plines) = "set output '"++fp++".eps'\n"++
(showMultiPlot plines)
infixl 4 %
infixr 3 :+:
infixr 2 :|:
data a :+: b = a :+: b
data a :||: b = a :||: b
data a :|: b = PcntDiv a :|: PcntDiv b
data a :==: b = a :==: b
data Hplots a = Hplots [a]
data Vplots a = Vplots [a]
data PcntDiv a = Pcnt Double a
data WithColour a = WithColour String a
x % a = Pcnt x a
data SubLabel a =
A a | Ai a | Aii a | Aiii a
| B a | Bi a | Bii a | Biii a
| C a | Ci a | Cii a | Ciii a
| D a | Di a | Dii a | Diii a
| E a | Ei a | Eii a
| SubNum Int a
subLabSplit :: SubLabel a -> (String, a)
subLabSplit (A x) = ("A",x)
subLabSplit (Ai x) = ("Ai",x)
subLabSplit (Aii x) = ("Aii",x)
subLabSplit (Aiii x) = ("Aiii",x)
subLabSplit (B x) = ("B",x)
subLabSplit (Bi x) = ("Bi",x)
subLabSplit (Bii x) = ("Bii",x)
subLabSplit (Biii x) = ("Biii",x)
subLabSplit (C x) = ("C",x)
subLabSplit (Ci x) = ("Ci",x)
subLabSplit (Cii x) = ("Cii",x)
subLabSplit (Ciii x) = ("Ciii",x)
subLabSplit (D x) = ("D",x)
subLabSplit (Di x) = ("Di",x)
subLabSplit (Dii x) = ("Dii",x)
subLabSplit (Diii x) = ("Diii",x)
subLabSplit (E x) = ("E",x)
subLabSplit (SubNum n x) = (show n, x)
newtype Lines a = Lines { unLines : : a }
newtype Boxes a = Boxes {unBoxes :: a }
data Lines a = Lines [StyleOpt] a
data LinesPoints a = LinesPoints [StyleOpt] a
data Points a = Points [StyleOpt] a
data StyleOpt = LineWidth Double
| LineType Int
| LineStyle Int
| LineColor String
| PointType Int
| PointSize Double
styleOptsToString :: [StyleOpt] -> String
styleOptsToString = intercalate " " . map g
where g (LineType lt) = "lt "++show lt
g (LineWidth lt) = "lw "++show lt
g (LineStyle lt) = "ls "++show lt
g (LineColor lc) = "lc rgb "++show lc
g (PointType lt) = "pt "++show lt
g (PointSize lt) = "ps "++show lt
instance PlotWithGnuplot a => PlotWithGnuplot (Lines a) where
multiPlot r (Lines sos x) = do
px <- multiPlot r x
let wstr = styleOptsToString sos
return $ map (\(r', pls) -> (r', setWith ("lines "++wstr) pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (LinesPoints a) where
multiPlot r (LinesPoints sos x) = do
px <- multiPlot r x
let wstr = styleOptsToString sos
return $ map (\(r', pls) -> (r', setWith ("linespoints "++wstr) pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (Points a) where
multiPlot r (Points sos x) = do
px <- multiPlot r x
let wstr = styleOptsToString sos
return $ map (\(r', pls) -> (r', setWith ("points "++wstr) pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (Boxes a) where
multiPlot r (Boxes x) = do
px <- multiPlot r x
return $ map (\(r', pls) -> (r', setWith "boxes" pls)) px
data GnuplotTest = GnuplotTest
instance PlotWithGnuplot (GnuplotTest) where
multiPlot r _ = do
return $ [(r, [TopLevelGnuplotCmd "test" ""])]
data Margin a = Margin Double Double Double Double a
data XRange a = XRange Double Double a
data YRange a = YRange Double Double a
data XTics a = XTics [Double] a | XTicLabel [(String, Double)] a
data YTics a = YTics [Double] a
data TicFormat a = TicFormat XY String a
data XY = X | Y | XY
data Noaxis a = Noaxis a
| NoXaxis a
| NoYaxis a
| NoTRaxis a
data Key a = KeyTopLeft Bool a
| KeyTopRight Bool a
| KeyLowRight Bool a
setMargin (Margin b t l r _) = unlines ["set bmargin "++show b,
"set lmargin "++show l,
"set rmargin "++show r,
"set tmargin "++show t]
unsetMargin = unlines ["unset bmargin ",
"unset lmargin ",
"unset rmargin ",
"unset tmargin "]
instance PlotWithGnuplot a => PlotWithGnuplot (Margin a) where
multiPlot r m@(Margin _ _ _ _ x) = do
px <- multiPlot r x
let setit = setMargin m
return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit unsetMargin):pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (XRange a) where
multiPlot r m@(XRange lo hi x) = do
px <- multiPlot r x
let setit = "set xrange ["++show lo++":"++show hi++"]\n"
return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "set xrange [*:*]"):pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (TicFormat a) where
multiPlot r m@(TicFormat xy s x) = do
px <- multiPlot r x
let whereStr X = "x"
whereStr Y = "y"
whereStr XY = "xy"
let setit = "set format "++whereStr xy++" "++show s++"\n"
return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "unset format"):pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (Key a) where
multiPlot r m@(KeyTopLeft box x) = do
px <- multiPlot r x
let boxs = if box then "box" else ""
let setit = "set key top left "++boxs++"\n"
return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "set key default"):pls)) px
multiPlot r m@(KeyLowRight box x) = do
px <- multiPlot r x
let boxs = if box then "box" else ""
let setit = "set key bottom right "++boxs++"\n"
return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "set key default"):pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (Noaxis a) where
multiPlot r m@(Noaxis x) = do
px <- multiPlot r x
let cmd = TopLevelGnuplotCmd "unset border; unset tics" "set border; set tics"
return $ map (\(r', pls) -> (r', cmd:pls)) px
multiPlot r m@(NoYaxis x) = do
px <- multiPlot r x
let cmd = TopLevelGnuplotCmd "set border 1; set tics" "set border; set tics"
return $ map (\(r', pls) -> (r', cmd:pls)) px
multiPlot r m@(NoXaxis x) = do
px <- multiPlot r x
let cmd = TopLevelGnuplotCmd "set border 2; set tics" "set border; set tics"
return $ map (\(r', pls) -> (r', cmd:pls)) px
multiPlot r m@(NoTRaxis x) = do
px <- multiPlot r x
let cmd = TopLevelGnuplotCmd "set border 3; set tics; set xtics nomirror; set ytics nomirror" "set border; set tics"
return $ map (\(r', pls) -> (r', cmd:pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (XTics a) where
multiPlot r m@(XTics tics x) = do
px <- multiPlot r x
let setit = "set xtics "++ (intercalate ", " $ map show tics) ++"\n"
return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "set xtics autofreq"):pls)) px
multiPlot r m@(XTicLabel tics x) = do
px <- multiPlot r x
let showTic (lab, loc) = show lab++" "++show loc
let setit = "set xtics ("++ (intercalate ", " $ map showTic tics) ++")\n"
return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "set xtics autofreq"):pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (YTics a) where
multiPlot r m@(YTics tics x) = do
px <- multiPlot r x
let setit = "set ytics "++ (intercalate ", " $ map show tics) ++"\n"
return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "set xtics autofreq"):pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (YRange a) where
multiPlot r m@(YRange lo hi x) = do
px <- multiPlot r x
let setit = "set yrange ["++show lo++":"++show hi++"]\n"
return $ map (\(r', pls) -> (r', (TopLevelGnuplotCmd setit "set yrange [*:*]"):pls)) px
lineWidth w = Lines [LineWidth w]
lineType t = Lines [LineType t]
pointSize t = Points [PointSize t]
pointType t = Points [PointType t]
data CustAxis = CustAxis {
caOrigin :: (Double,Double),
caLength :: Double,
caVertical :: Bool,
caTicLen :: Double,
caTicOffset :: Double,
caTics :: [(Double, String)]
}
data WithAxis a = WithAxis CustAxis a
instance PlotWithGnuplot a => PlotWithGnuplot (WithAxis a) where
multiPlot r (WithAxis (CustAxis (x0,y0) len True tlen toff tics) x) = do
let ticCmds (y,txt) =
[TopLevelGnuplotCmd ("set arrow from first "++show x0++","++show (y0+y)++
" to first "++show (x0-tlen)++","++show (y0+y)++" nohead front")
"unset arrow",
TopLevelGnuplotCmd ("set label "++show txt++" at first "++
show (x0-toff)++","++show (y0+y)++" right front")
"unset label"
]
let cmds = TopLevelGnuplotCmd ("set arrow from first "++show x0++","++show y0++
" to first "++show x0++","++show (y0+len)++" nohead front")
"unset arrow" : concatMap ticCmds tics
px <- multiPlot r $ x
return $ map (\(r', pls) -> (r', cmds++pls)) px
data ScaleBars a = ScaleBars (Double, Double) (Double,String) (Double,String) a
| XScaleBar (Double, Double) (Double,String) Double a
| YScaleBar (Double, Double) (Double,String) Double a
data LineAt a = LineAt (Double, Double) (Double, Double) a
data ArrowAt a = ArrowAt (Double, Double) (Double, Double) a
data TextAt a = TextAt (Double, Double) String a
| TextAtLeft (Double, Double) String a
| TextAtRot (Double,Double) String a
instance PlotWithGnuplot a => PlotWithGnuplot (TextAt a) where
multiPlot r (TextAt (x0,y0) s x) = do
let mklab = TopLevelGnuplotCmd ("set label "++show s++" at first "++show x0++","++show y0++" center front")
"unset label"
px <- multiPlot r x
return $ map (\(r', pls) -> (r', mklab:pls)) px
multiPlot r (TextAtRot (x0,y0) s x) = do
let mklab = TopLevelGnuplotCmd ("set label "++show s++" at first "++show x0++","++show y0++" center front rotate")
"unset label"
px <- multiPlot r x
return $ map (\(r', pls) -> (r', mklab:pls)) px
multiPlot r (TextAtLeft (x0,y0) s x) = do
let mklab = TopLevelGnuplotCmd ("set label "++show s++" at first "++show x0++","++show y0++" left front")
"unset label"
px <- multiPlot r x
return $ map (\(r', pls) -> (r', mklab:pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (LineAt a) where
multiPlot r (LineAt (x0,y0) (x1, y1) x) = do
let mklab = TopLevelGnuplotCmd ("set arrow from first "++show x0++","++show y0++" to first "++show x1++","++show y1++" nohead front")
"unset arrow"
px <- multiPlot r x
return $ map (\(r', pls) -> (r', mklab:pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (ArrowAt a) where
multiPlot r (ArrowAt (x0,y0) (x1, y1) x) = do
let mklab = TopLevelGnuplotCmd ("set arrow from first "++show x0++","++show y0++" to first "++show x1++","++show y1++" heads front")
"unset arrow"
px <- multiPlot r x
return $ map (\(r', pls) -> (r', mklab:pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (ScaleBars a) where
multiPlot r (ScaleBars p0 (xsz, xtxt) (ysz, ytxt) x) = do
multiPlot r $ XScaleBar p0 (xsz, xtxt) (ysz/4) $ YScaleBar p0 (ysz, ytxt) (xsz/2) x
multiPlot r (XScaleBar (x0,y0) (xsz, xtxt) yo x) = do
let xtxtpos = (x0+xsz/2, y0 - yo)
multiPlot r $ LineAt (x0, y0) (x0+xsz, y0)
$ TextAt xtxtpos xtxt x
multiPlot r (YScaleBar (x0,y0) (ysz, ytxt) yo x) = do
let ytxtpos = (x0+yo, y0 + ysz/2)
multiPlot r $ LineAt (x0, y0) (x0, y0+ysz)
$ TextAt ytxtpos ytxt x
data TicFont a = TicFont String a
data CanvasScale a = CanvasScale Double Double a
instance PlotWithGnuplot a => PlotWithGnuplot (CanvasScale a) where
multiPlot r (CanvasScale xsz ysz x) = do
let mklab = TopLevelGnuplotCmd ("set size "++show xsz++","++show ysz)
""
px <- multiPlot r x
return $ map (\(r', pls) -> (r', mklab:pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (TicFont a) where
multiPlot r (TicFont str x) = do
let mklab = TopLevelGnuplotCmd ("set tics font "++show str)
""
px <- multiPlot r x
return $ map (\(r', pls) -> (r', mklab:pls)) px
instance PlotWithGnuplot a => PlotWithGnuplot (SubLabel a) where
multiPlot r sl = do
let (lab, x ) = subLabSplit sl
(xpos, ypos) = rectTopLeft r
let mklab = TopLevelGnuplotCmd ("set label "++show lab++" at screen "++show xpos++","++show ypos++" front")
"unset label"
px <- multiPlot r x
return $ map (\(r', pls) -> (r', mklab:pls)) px
data CentreLabel = CentreLabel String
instance PlotWithGnuplot CentreLabel where
multiPlot r (CentreLabel str) = do
let mklab = TopLevelGnuplotCmd ("set label "++show str++" at graph 0.5,0.5 center front") "unset label"
nop::[GnuplotCmd] <- fmap (map snd) $ multiPlot r Noplot
return [(r, mklab:concat nop)]
data AxisLabels a = AxisLabels String String a
| XLabel String a
| YLabel String a
instance PlotWithGnuplot a => PlotWithGnuplot (AxisLabels a) where
multiPlot r (AxisLabels xlab ylab x) = do
let mklabs = [TopLevelGnuplotCmd ("set xlabel "++show xlab) "unset xlabel",
TopLevelGnuplotCmd ("set ylabel "++show ylab) "unset ylabel"]
px <- multiPlot r x
return $ map (\(r', pls) -> (r', mklabs++pls)) px
multiPlot r (XLabel xlab x) = do
let mklabs = [TopLevelGnuplotCmd ("set xlabel "++show xlab) "unset xlabel"]
px <- multiPlot r x
return $ map (\(r', pls) -> (r', mklabs++pls)) px
multiPlot r (YLabel xlab x) = do
let mklabs = [TopLevelGnuplotCmd ("set ylabel "++show xlab) "unset ylabel"]
px <- multiPlot r x
return $ map (\(r', pls) -> (r', mklabs++pls)) px
data Pad a = Pad Double a
| PadX Double Double a
| PadY Double Double a
instance (PlotWithGnuplot a) => PlotWithGnuplot (Pad a) where
multiPlot r (Pad p x) = multiPlot r $ PadX p p $ PadY p p x
multiPlot (Rect (x0, y0) (x1,y1)) (PadX p1 p2 x) = do
let xw = (x1 - x0)
px <- multiPlot (Rect (x0+xw*p1,y0) (x1-xw*p2, y1) ) x
return $ px
multiPlot (Rect (x0, y0) (x1,y1)) (PadY p1 p2 x) = do
let yh = (y1 - y0)
px <- multiPlot ( Rect (x0,y0+yh*p1) (x1, y1-yh*p2) ) x
return $ px
instance (PlotWithGnuplot a, PlotWithGnuplot b) => PlotWithGnuplot (a :||: b) where
multiPlot r (xs :||: ys) = multiPlot r (50% xs :|: 50% ys)
instance (PlotWithGnuplot a, PlotWithGnuplot b) => PlotWithGnuplot (a :==: b) where
: 50 % ys )
instance (PlotWithGnuplot a, PlotWithGnuplot b) => PlotWithGnuplot ( a :|: b) where
multiPlot (Rect (x0, y0) (x1,y1)) (Pcnt pcp p :|: Pcnt pcq q) = do
let xsep = x0+(pcp/(pcp+pcq))*(x1-x0)
px <- multiPlot ( Rect (x0,y0) (xsep, y1) ) p
py <- multiPlot ( Rect (xsep,y0) (x1, y1) ) q
return $ px++py
: Pcnt pcq q ) = do
let ysep = y0+(pcq/(pcp+pcq))*(y1-y0)
px <- multiPlot ( Rect (x0,y0) (x1, ysep) ) q
py <- multiPlot ( Rect (x0, ysep) (x1, y1) ) p
return $ py++px
instance (PlotWithGnuplot a, PlotWithGnuplot b) => PlotWithGnuplot (a :+: b) where
multiPlot r (xs :+: ys) = do
px <- getGnuplotCmd xs
py <- getGnuplotCmd ys
return $ [(r,px++py)]
instance (PlotWithGnuplot a, PlotWithGnuplot b) => PlotWithGnuplot (Either a b) where
multiPlot r (Left xs) = multiPlot r xs
multiPlot r (Right xs) = multiPlot r xs
instance (PlotWithGnuplot a) => PlotWithGnuplot (Hplots a) where
multiPlot (Rect (x0, y0) (x1,y1)) (Hplots ps) = do
let n = realToFrac $ length ps
let xeach = (x1-x0)/n
pls <- forM (zip ps [0..]) $ \(p,i) ->
multiPlot ( Rect (x0+(i*xeach),y0) (x0+((i+1)*xeach), y1) ) p
return $ concat pls
instance (PlotWithGnuplot a) => PlotWithGnuplot (Vplots a) where
multiPlot (Rect (x0, y0) (x1,y1)) (Vplots ps) = do
let n = realToFrac $ length ps
let yeach = (y1-y0)/n
pls <- forM (zip ps [0..]) $ \(p,i) ->
multiPlot ( Rect (x0,y0+(i*yeach)) (x1, y0+((i+1)*yeach)) ) p
return $ concat pls
instance PlotWithGnuplot a => PlotWithGnuplot (String, a) where
multiPlot r (title, x) = do
pls <- multiPlot r x
return $ map (\(r', plines) -> (r' ,map (addTitle title) plines)) pls
where addTitle title (PL x _ y clean) = PL x title y clean
newtype LabelConsecutively a = LabelConsecutively a
instance PlotWithGnuplot a => PlotWithGnuplot (LabelConsecutively [a]) where
getGnuplotCmd (LabelConsecutively xs) = do
pls::[ GnuplotCmd] <- mapM (getGnuplotCmd) xs
return $ concatMap (\(rs,i)-> (addTitleMany (show i)) rs) $ zip pls [0..]
where addTitle title (PL x _ y clean) = PL x title y clean
addTitleMany :: String -> ( GnuplotCmd) -> ( GnuplotCmd)
addTitleMany title (cmd) = ( map (addTitle title) cmd)
tilePlots :: Int -> [t] -> Vplots (Hplots (SubLabel (Either t Noplot)))
tilePlots n ps = let nps = (length ps)
nfinal = if nps `mod` n == 0
then nps
else ((nps `div` n)+1)*n
allps = ensureLength (nfinal) Noplot ps
in Vplots $ map Hplots $ map (map (\(p,i) -> SubNum i p)) $ groupsOf n (zip allps [0..])
gridPlot :: [[GnuplotBox]] -> Vplots (Hplots GnuplotBox)
gridPlot plots = Vplots $ map Hplots plots
groupsOf n [] = []
groupsOf n xs = let (mine, rest) = splitAt n xs
in mine: groupsOf n rest
ensureLength n filler xs = map Left xs++replicate (n - length xs) (Right filler)
instance a = > PlotWithR ( Hist a ) where
getRPlotCmd ( Histogram tgs ) =
plotHisto $ map
getRPlotCmd (Histogram tgs) =
plotHisto $ map getTag tgs
-} |
e9e7c52971a2e36e294f66337adf53ea7ae1133c7288c89c447d04116aa8b720 | dongcarl/guix | gnome.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2017 , 2019 , 2021 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (guix import gnome)
#:use-module (guix upstream)
#:use-module (guix utils)
#:use-module (guix packages)
#:use-module (guix http-client)
#:use-module (json)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-11)
#:use-module (srfi srfi-34)
#:use-module (web uri)
#:use-module (ice-9 match)
#:export (%gnome-updater))
;;; Commentary:
;;;
;;; This package provides not an actual importer but simply an updater for
;;; GNOME packages. It grabs package meta-data from 'cache.json' files
;;; available on ftp.gnome.org.
;;;
;;; Code:
(define (jsonish->upstream-source name jsonish)
"Return an <upstream-source> object for package NAME, using JSONISH as the
source for metadata."
(match jsonish
((version . dictionary)
(upstream-source
(package name)
(version version)
(urls (filter-map (lambda (extension)
(match (assoc-ref dictionary extension)
(#f
#f)
((? string? relative-url)
(string-append "mirror/"
name "/" relative-url))))
'("tar.lz" "tar.xz" "tar.bz2" "tar.gz")))))))
(define (latest-gnome-release package)
"Return the latest release of PACKAGE, a GNOME package, or #f if it could
not be determined."
(define %not-dot
(char-set-complement (char-set #\.)))
(define (even-minor-version? version)
(match (string-tokenize version %not-dot)
(((= string->number major) (= string->number minor) . rest)
(and minor (even? minor)))
(((= string->number major) . _)
;; It should at last start with a digit.
major)))
(define upstream-name
;; Some packages like "NetworkManager" have camel-case names.
(package-upstream-name package))
(guard (c ((http-get-error? c)
(if (= 404 (http-get-error-code c))
#f
(raise c))))
(let* ((port (http-fetch/cached
(string->uri (string-append
"/"
upstream-name "/cache.json"))
;; ftp.gnome.org supports 'if-Modified-Since', so the local
;; cache can expire early.
#:ttl (* 60 10)
;; Hide messages about URL redirects.
#:log-port (%make-void-port "w")))
(json (json->scm port)))
(close-port port)
(match json
(#(4 releases _ ...)
(let* ((releases (assoc-ref releases upstream-name))
(latest (fold (match-lambda*
(((key . value) result)
(cond ((even-minor-version? key)
(match result
(#f
(cons key value))
((newest . _)
(if (version>? key newest)
(cons key value)
result))))
(else
result))))
#f
releases)))
(and latest
(jsonish->upstream-source upstream-name latest))))))))
(define %gnome-updater
(upstream-updater
(name 'gnome)
(description "Updater for GNOME packages")
(pred (url-prefix-predicate "mirror/"))
(latest latest-gnome-release)))
| null | https://raw.githubusercontent.com/dongcarl/guix/82543e9649da2da9a5285ede4ec4f718fd740fcb/guix/import/gnome.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Commentary:
This package provides not an actual importer but simply an updater for
GNOME packages. It grabs package meta-data from 'cache.json' files
available on ftp.gnome.org.
Code:
It should at last start with a digit.
Some packages like "NetworkManager" have camel-case names.
ftp.gnome.org supports 'if-Modified-Since', so the local
cache can expire early.
Hide messages about URL redirects. | Copyright © 2017 , 2019 , 2021 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (guix import gnome)
#:use-module (guix upstream)
#:use-module (guix utils)
#:use-module (guix packages)
#:use-module (guix http-client)
#:use-module (json)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-11)
#:use-module (srfi srfi-34)
#:use-module (web uri)
#:use-module (ice-9 match)
#:export (%gnome-updater))
(define (jsonish->upstream-source name jsonish)
"Return an <upstream-source> object for package NAME, using JSONISH as the
source for metadata."
(match jsonish
((version . dictionary)
(upstream-source
(package name)
(version version)
(urls (filter-map (lambda (extension)
(match (assoc-ref dictionary extension)
(#f
#f)
((? string? relative-url)
(string-append "mirror/"
name "/" relative-url))))
'("tar.lz" "tar.xz" "tar.bz2" "tar.gz")))))))
(define (latest-gnome-release package)
"Return the latest release of PACKAGE, a GNOME package, or #f if it could
not be determined."
(define %not-dot
(char-set-complement (char-set #\.)))
(define (even-minor-version? version)
(match (string-tokenize version %not-dot)
(((= string->number major) (= string->number minor) . rest)
(and minor (even? minor)))
(((= string->number major) . _)
major)))
(define upstream-name
(package-upstream-name package))
(guard (c ((http-get-error? c)
(if (= 404 (http-get-error-code c))
#f
(raise c))))
(let* ((port (http-fetch/cached
(string->uri (string-append
"/"
upstream-name "/cache.json"))
#:ttl (* 60 10)
#:log-port (%make-void-port "w")))
(json (json->scm port)))
(close-port port)
(match json
(#(4 releases _ ...)
(let* ((releases (assoc-ref releases upstream-name))
(latest (fold (match-lambda*
(((key . value) result)
(cond ((even-minor-version? key)
(match result
(#f
(cons key value))
((newest . _)
(if (version>? key newest)
(cons key value)
result))))
(else
result))))
#f
releases)))
(and latest
(jsonish->upstream-source upstream-name latest))))))))
(define %gnome-updater
(upstream-updater
(name 'gnome)
(description "Updater for GNOME packages")
(pred (url-prefix-predicate "mirror/"))
(latest latest-gnome-release)))
|
1386a984eb2406c02bc67c77ac3c1cd3c8b7019f92df2bf538fd19d5a8371ad4 | tmcgilchrist/ocaml-gitlab | runner.ml | open Cmdliner
open Config
let envs = Gitlab.Env.envs
let json =
let doc = "Print output as formatted json" in
Arg.(value & flag & info [ "json" ] ~doc)
let list_cmd config =
let pp f r =
Fmt.pf f "%-20i %-20s" r.Gitlab_j.runner_id r.Gitlab_j.runner_description
in
let printer runners json =
if json then
Fmt.pr "%s\n" (Yojson.Basic.prettify @@ Gitlab_j.string_of_runners runners)
else
Fmt.pr "%-20s %-20s\n%s" "runner_id" "description"
(Fmt.str "%a\n" (Fmt.list ~sep:(Fmt.any "\n") pp) runners)
in
let list json =
let cmd =
let open Gitlab in
let open Monad in
let config = config () in
Runners.list ~token:config.token () >|~ fun runners ->
printer runners json
in
Lwt_main.run @@ Gitlab.Monad.run cmd
in
let doc = "List all runners available to the user." in
let info = Cmd.info ~envs ~doc "list" in
let term = Term.(const list $ json) in
Cmd.v info term
let cmd config =
let doc = "Manage runners." in
let default = Term.(ret (const (`Help (`Pager, None)))) in
let man = [] in
let info = Cmd.info ~envs "runner" ~doc ~man in
Cmd.group ~default info [ list_cmd config ]
| null | https://raw.githubusercontent.com/tmcgilchrist/ocaml-gitlab/de4d1cc31d172e599943fe712269f165f1c88909/cli/runner.ml | ocaml | open Cmdliner
open Config
let envs = Gitlab.Env.envs
let json =
let doc = "Print output as formatted json" in
Arg.(value & flag & info [ "json" ] ~doc)
let list_cmd config =
let pp f r =
Fmt.pf f "%-20i %-20s" r.Gitlab_j.runner_id r.Gitlab_j.runner_description
in
let printer runners json =
if json then
Fmt.pr "%s\n" (Yojson.Basic.prettify @@ Gitlab_j.string_of_runners runners)
else
Fmt.pr "%-20s %-20s\n%s" "runner_id" "description"
(Fmt.str "%a\n" (Fmt.list ~sep:(Fmt.any "\n") pp) runners)
in
let list json =
let cmd =
let open Gitlab in
let open Monad in
let config = config () in
Runners.list ~token:config.token () >|~ fun runners ->
printer runners json
in
Lwt_main.run @@ Gitlab.Monad.run cmd
in
let doc = "List all runners available to the user." in
let info = Cmd.info ~envs ~doc "list" in
let term = Term.(const list $ json) in
Cmd.v info term
let cmd config =
let doc = "Manage runners." in
let default = Term.(ret (const (`Help (`Pager, None)))) in
let man = [] in
let info = Cmd.info ~envs "runner" ~doc ~man in
Cmd.group ~default info [ list_cmd config ]
| |
a6d88e1ecae12b774fb1c03c793465804bfecdd899d7fc8cd952f44a9ac73023 | lexi-lambda/racket-commonmark | pro-git.rkt | #lang racket/base
;; This module benchmarks commonmark against markdown, using an input corpus
derived by concatenating the sources of all the localizations of the
first edition of by . ( This is the benchmarking technique
used by cmark < > . )
(require benchmark
net/git-checkout
racket/file
racket/format
racket/list
racket/match
racket/path
racket/port
(prefix-in cm: commonmark)
(prefix-in md: markdown))
(define-logger cm-bench)
(define current-build-directory (make-parameter "build"))
(define (bench-path . sub)
(simplify-path (apply build-path (current-build-directory) "bench" sub)))
(define (clone-progit)
(define dest-dir (bench-path "progit"))
(cond
[(directory-exists? dest-dir)
(log-cm-bench-debug "clone-progit: ‘~a’ already exists, skipping" dest-dir)]
[else
(log-cm-bench-info "clone-progit: cloning into ‘~a’" dest-dir)
(make-parent-directory* dest-dir)
(git-checkout #:transport 'https "github.com" "progit/progit.git"
#:dest-dir dest-dir)])
dest-dir)
(define document-sizes #(tiny small medium large))
(define (build-bench-inputs)
(define progit-dir (clone-progit))
(define langs '("ar" "az" "be" "ca" "cs" "de" "en" "eo" "es" "es-ni"
"fa" "fi" "fr" "hi" "hu" "id" "it" "ja" "ko"
"mk" "nl" "no-nb" "pl" "pt-br" "ro" "ru" "sr"
"th" "tr" "uk" "vi" "zh" "zh-tw"))
(for/vector #:length (vector-length document-sizes) ([size (in-vector document-sizes)])
(define out-path (bench-path "input" (~a size ".md")))
(cond
[(file-exists? out-path)
(log-cm-bench-debug "build-bench-input: ‘~a’ already exists, skipping" out-path)
(file->string out-path)]
[else
(log-cm-bench-info "build-bench-input: writing ‘~a’" out-path)
(make-parent-directory* out-path)
(define str-out (open-output-string))
(call-with-output-file* #:mode 'text out-path
(λ (out)
(for* ([lang (in-list (match size
[(or 'tiny 'small) '("en")]
['medium (take langs 15)]
['large langs]))]
[in-path (in-directory (match size
['tiny (build-path progit-dir lang "01-introduction")]
[_ (build-path progit-dir lang)]))]
#:when (file-exists? in-path)
#:when (equal? (path-get-extension in-path) #".markdown"))
(call-with-input-file* #:mode 'text in-path
(λ (in) (copy-port in str-out out))))))
(get-output-string str-out)])))
(define (benchmark-results-path)
(bench-path "results" "result"))
(define (size->string bytes)
(define Ki 1024)
(define Mi (* Ki Ki))
(cond
[(< bytes Ki) (~a (~r (/ bytes Ki) #:precision 1) " KiB")]
[(< bytes Mi) (~a (~r (/ bytes Ki) #:precision 0) " KiB")]
[else (~a (~r (/ bytes Mi) #:precision 0) " MiB")]))
(define (do-run-benchmarks #:num-trials [num-trials 1])
(define bench-inputs (build-bench-inputs))
(define results-file (benchmark-results-path))
(make-parent-directory* results-file)
(log-cm-bench-info "running benchmarks...")
(run-benchmarks
#:extract-time 'delta-time
#:num-trials num-trials
#:make-name (λ (size)
(define bytes (string-utf-8-length (vector-ref bench-inputs size)))
(~a (vector-ref document-sizes size) " (" (size->string bytes) ")"))
#:results-file results-file
(range (vector-length document-sizes))
'([commonmark markdown])
(λ (size impl)
(define input (vector-ref bench-inputs size))
(match impl
['commonmark (cm:document->html (cm:string->document input))]
['markdown (map md:xexpr->string (md:parse-markdown input))]))))
(module+ main
(require plot
racket/class)
(define (visualize-benchmark-results [results (get-past-results (benchmark-results-path))])
(parameterize ([plot-x-ticks no-ticks]
[current-benchmark-color-scheme (cons '("white" "black") '(solid))])
(define frame
(plot-frame
#:title "commonmark vs markdown"
#:x-label "input size"
#:y-label "normalized time"
(render-benchmark-alts '(commonmark) results)))
(send frame show #t)))
(visualize-benchmark-results (do-run-benchmarks)))
| null | https://raw.githubusercontent.com/lexi-lambda/racket-commonmark/1d7f1d5fc70bedfbe201c2e794da69dc7afe6e63/commonmark-bench/benchmarks/commonmark/pro-git.rkt | racket | This module benchmarks commonmark against markdown, using an input corpus | #lang racket/base
derived by concatenating the sources of all the localizations of the
first edition of by . ( This is the benchmarking technique
used by cmark < > . )
(require benchmark
net/git-checkout
racket/file
racket/format
racket/list
racket/match
racket/path
racket/port
(prefix-in cm: commonmark)
(prefix-in md: markdown))
(define-logger cm-bench)
(define current-build-directory (make-parameter "build"))
(define (bench-path . sub)
(simplify-path (apply build-path (current-build-directory) "bench" sub)))
(define (clone-progit)
(define dest-dir (bench-path "progit"))
(cond
[(directory-exists? dest-dir)
(log-cm-bench-debug "clone-progit: ‘~a’ already exists, skipping" dest-dir)]
[else
(log-cm-bench-info "clone-progit: cloning into ‘~a’" dest-dir)
(make-parent-directory* dest-dir)
(git-checkout #:transport 'https "github.com" "progit/progit.git"
#:dest-dir dest-dir)])
dest-dir)
(define document-sizes #(tiny small medium large))
(define (build-bench-inputs)
(define progit-dir (clone-progit))
(define langs '("ar" "az" "be" "ca" "cs" "de" "en" "eo" "es" "es-ni"
"fa" "fi" "fr" "hi" "hu" "id" "it" "ja" "ko"
"mk" "nl" "no-nb" "pl" "pt-br" "ro" "ru" "sr"
"th" "tr" "uk" "vi" "zh" "zh-tw"))
(for/vector #:length (vector-length document-sizes) ([size (in-vector document-sizes)])
(define out-path (bench-path "input" (~a size ".md")))
(cond
[(file-exists? out-path)
(log-cm-bench-debug "build-bench-input: ‘~a’ already exists, skipping" out-path)
(file->string out-path)]
[else
(log-cm-bench-info "build-bench-input: writing ‘~a’" out-path)
(make-parent-directory* out-path)
(define str-out (open-output-string))
(call-with-output-file* #:mode 'text out-path
(λ (out)
(for* ([lang (in-list (match size
[(or 'tiny 'small) '("en")]
['medium (take langs 15)]
['large langs]))]
[in-path (in-directory (match size
['tiny (build-path progit-dir lang "01-introduction")]
[_ (build-path progit-dir lang)]))]
#:when (file-exists? in-path)
#:when (equal? (path-get-extension in-path) #".markdown"))
(call-with-input-file* #:mode 'text in-path
(λ (in) (copy-port in str-out out))))))
(get-output-string str-out)])))
(define (benchmark-results-path)
(bench-path "results" "result"))
(define (size->string bytes)
(define Ki 1024)
(define Mi (* Ki Ki))
(cond
[(< bytes Ki) (~a (~r (/ bytes Ki) #:precision 1) " KiB")]
[(< bytes Mi) (~a (~r (/ bytes Ki) #:precision 0) " KiB")]
[else (~a (~r (/ bytes Mi) #:precision 0) " MiB")]))
(define (do-run-benchmarks #:num-trials [num-trials 1])
(define bench-inputs (build-bench-inputs))
(define results-file (benchmark-results-path))
(make-parent-directory* results-file)
(log-cm-bench-info "running benchmarks...")
(run-benchmarks
#:extract-time 'delta-time
#:num-trials num-trials
#:make-name (λ (size)
(define bytes (string-utf-8-length (vector-ref bench-inputs size)))
(~a (vector-ref document-sizes size) " (" (size->string bytes) ")"))
#:results-file results-file
(range (vector-length document-sizes))
'([commonmark markdown])
(λ (size impl)
(define input (vector-ref bench-inputs size))
(match impl
['commonmark (cm:document->html (cm:string->document input))]
['markdown (map md:xexpr->string (md:parse-markdown input))]))))
(module+ main
(require plot
racket/class)
(define (visualize-benchmark-results [results (get-past-results (benchmark-results-path))])
(parameterize ([plot-x-ticks no-ticks]
[current-benchmark-color-scheme (cons '("white" "black") '(solid))])
(define frame
(plot-frame
#:title "commonmark vs markdown"
#:x-label "input size"
#:y-label "normalized time"
(render-benchmark-alts '(commonmark) results)))
(send frame show #t)))
(visualize-benchmark-results (do-run-benchmarks)))
|
8a965d8e19699d6c4d736daa7f9c255fe8a2e1c90a7bd03053943e9776bb449e | LexiFi/landmarks | test.ml | let _ =
let[@landmark] test1 x = x
in test1 "marc", test1 2
let _ =
let[@landmark] test2 (type t) (x : t) = x
in test2 "marc", test2 2
let _ =
let obj = object method[@landmark] test3 x = x end
in obj # test3 "marc", obj # test3 2
let () =
let open Landmark in
if profiling () then begin
let open Landmark.Graph in
let cg = export () in
let agg = aggregate_landmarks cg in
let all_nodes = nodes agg in
print_endline "\nLandmark reached:";
all_nodes
|> List.map (fun {name; _} -> name)
|> List.sort compare
|> List.iter print_endline
end
| null | https://raw.githubusercontent.com/LexiFi/landmarks/ea90c657f39d03d14d892732ad58123711eb9457/tests/poly/test.ml | ocaml | let _ =
let[@landmark] test1 x = x
in test1 "marc", test1 2
let _ =
let[@landmark] test2 (type t) (x : t) = x
in test2 "marc", test2 2
let _ =
let obj = object method[@landmark] test3 x = x end
in obj # test3 "marc", obj # test3 2
let () =
let open Landmark in
if profiling () then begin
let open Landmark.Graph in
let cg = export () in
let agg = aggregate_landmarks cg in
let all_nodes = nodes agg in
print_endline "\nLandmark reached:";
all_nodes
|> List.map (fun {name; _} -> name)
|> List.sort compare
|> List.iter print_endline
end
| |
cb5e9b376f7098ed7f81952434e38bf65c67779994c714ddf43fa334cde24ed5 | spurious/sagittarius-scheme-mirror | %3a49.scm | ;;; -*- Scheme -*-
;;;
;;; SRFI-49: Indentation-sensitive syntax
;;;
Copyright ( c ) 2010 - 2012 < >
;;;
;;; 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 COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;
(library (srfi :49)
(export group
srfi-49-read
srfi-49-load
:export-reader
)
(import (rnrs)
(rnrs eval)
(core errors)
(sagittarius)
(sagittarius reader)
(srfi :1))
(define group 'group)
(define (read-quote level port qt)
(read-char port)
(let ((char (peek-char port)))
(if (or (eqv? char #\space)
(eqv? char #\newline)
(eqv? char #\tab))
(list qt)
(list qt (read port)))))
(define (read-item level port)
(let ((char (peek-char port)))
(cond ((eqv? char #\`) (read-quote level port 'quasiquote))
((eqv? char #\') (read-quote level port 'quote))
((eqv? char #\,) (read-quote level port 'unquote))
(else (read port)))))
(define (indentation>? indentation1 indentation2)
(let ((len1 (string-length indentation1))
(len2 (string-length indentation2)))
(and (> len1 len2)
(string=? indentation2 (substring indentation1 0 len2)))))
(define (indentation-level port)
(define (indentationlevel)
(if (or (eqv? (peek-char port) #\space)
(eqv? (peek-char port) #\tab))
(cons (read-char port) (indentationlevel))
'()))
(list->string (indentationlevel)))
(define (clean line)
(cond ((not (pair? line)) line)
((null? line) line)
((eq? (car line) 'group) (cdr line))
((null? (car line)) (cdr line))
((list? (car line))
(if (memq (caar line) '(quote quasiquote unquote))
(if (and (list? (cdr line))
(null? (cddr line)))
(cons (car line) (cdr line))
(list (car line) (cdr line)))
(cons (clean (car line)) (cdr line))))
(else line)))
(define (read-blocks level port)
(let* ((read (read-block-clean level port))
(next-level (car read))
(block (cdr read)))
(cond ((eqv? next-level -1)
FIXME the last line is not empty but with some expression
;; this case should not raise error just return expression
(raise-i/o-read-error 'read-blocks
"unexpected EOF"
(let ((info (port-info port)))
`((port ,port)
(file ,(car info))
(line ,(cadr info))))))
((string=? next-level level)
(let* ((reads (read-blocks level port))
(next-next-level (car reads))
(next-blocks (cdr reads)))
(if (eq? block '|.|)
(if (pair? next-blocks)
(cons next-next-level (car next-blocks))
(cons next-next-level next-blocks))
(cons next-next-level (cons block next-blocks)))))
(else (cons next-level (list block))))))
(define (read-block level port)
(let ((char (peek-char port)))
(cond ((eof-object? char) (cons -1 char))
((eqv? char #\newline)
(read-char port)
(let ((next-level (indentation-level port)))
(if (indentation>? next-level level)
(read-blocks next-level port)
(cons next-level '()))))
((or (eqv? char #\space) (eqv? char #\tab))
(read-char port)
(read-block level port))
(else
(let* ((first (read-item level port))
(rest (read-block level port))
(level (car rest))
(block (cdr rest)))
(if (eq? first '|.|)
(if (pair? block)
(cons level (car block))
rest)
(cons level (cons first block))))))))
(define (read-block-clean level port)
(let* ((read (read-block level port))
(next-level (car read))
(block (cdr read)))
(cond ((or (not (pair? block))
(and (pair? block)
(not (null? (cdr block)))))
(cons next-level (clean block)))
((null? block) (cons next-level '|.|))
(else (cons next-level (car block))))))
(define-reader (srfi-49-read p)
(let* ((block (read-block-clean "" p))
(level (car block))
(block (cdr block)))
(if (eq? block '|.|)
'()
block)))
(define (srfi-49-load filename)
(call-with-input-file filename
(lambda (p)
(do ((expr (srfi-49-read p) (srfi-49-read p)))
((eof-object? expr) #t)
(eval expr (current-library))))))
) | null | https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/sitelib/srfi/%253a49.scm | scheme | -*- Scheme -*-
SRFI-49: Indentation-sensitive syntax
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 COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
this case should not raise error just return expression | Copyright ( c ) 2010 - 2012 < >
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
(library (srfi :49)
(export group
srfi-49-read
srfi-49-load
:export-reader
)
(import (rnrs)
(rnrs eval)
(core errors)
(sagittarius)
(sagittarius reader)
(srfi :1))
(define group 'group)
(define (read-quote level port qt)
(read-char port)
(let ((char (peek-char port)))
(if (or (eqv? char #\space)
(eqv? char #\newline)
(eqv? char #\tab))
(list qt)
(list qt (read port)))))
(define (read-item level port)
(let ((char (peek-char port)))
(cond ((eqv? char #\`) (read-quote level port 'quasiquote))
((eqv? char #\') (read-quote level port 'quote))
((eqv? char #\,) (read-quote level port 'unquote))
(else (read port)))))
(define (indentation>? indentation1 indentation2)
(let ((len1 (string-length indentation1))
(len2 (string-length indentation2)))
(and (> len1 len2)
(string=? indentation2 (substring indentation1 0 len2)))))
(define (indentation-level port)
(define (indentationlevel)
(if (or (eqv? (peek-char port) #\space)
(eqv? (peek-char port) #\tab))
(cons (read-char port) (indentationlevel))
'()))
(list->string (indentationlevel)))
(define (clean line)
(cond ((not (pair? line)) line)
((null? line) line)
((eq? (car line) 'group) (cdr line))
((null? (car line)) (cdr line))
((list? (car line))
(if (memq (caar line) '(quote quasiquote unquote))
(if (and (list? (cdr line))
(null? (cddr line)))
(cons (car line) (cdr line))
(list (car line) (cdr line)))
(cons (clean (car line)) (cdr line))))
(else line)))
(define (read-blocks level port)
(let* ((read (read-block-clean level port))
(next-level (car read))
(block (cdr read)))
(cond ((eqv? next-level -1)
FIXME the last line is not empty but with some expression
(raise-i/o-read-error 'read-blocks
"unexpected EOF"
(let ((info (port-info port)))
`((port ,port)
(file ,(car info))
(line ,(cadr info))))))
((string=? next-level level)
(let* ((reads (read-blocks level port))
(next-next-level (car reads))
(next-blocks (cdr reads)))
(if (eq? block '|.|)
(if (pair? next-blocks)
(cons next-next-level (car next-blocks))
(cons next-next-level next-blocks))
(cons next-next-level (cons block next-blocks)))))
(else (cons next-level (list block))))))
(define (read-block level port)
(let ((char (peek-char port)))
(cond ((eof-object? char) (cons -1 char))
((eqv? char #\newline)
(read-char port)
(let ((next-level (indentation-level port)))
(if (indentation>? next-level level)
(read-blocks next-level port)
(cons next-level '()))))
((or (eqv? char #\space) (eqv? char #\tab))
(read-char port)
(read-block level port))
(else
(let* ((first (read-item level port))
(rest (read-block level port))
(level (car rest))
(block (cdr rest)))
(if (eq? first '|.|)
(if (pair? block)
(cons level (car block))
rest)
(cons level (cons first block))))))))
(define (read-block-clean level port)
(let* ((read (read-block level port))
(next-level (car read))
(block (cdr read)))
(cond ((or (not (pair? block))
(and (pair? block)
(not (null? (cdr block)))))
(cons next-level (clean block)))
((null? block) (cons next-level '|.|))
(else (cons next-level (car block))))))
(define-reader (srfi-49-read p)
(let* ((block (read-block-clean "" p))
(level (car block))
(block (cdr block)))
(if (eq? block '|.|)
'()
block)))
(define (srfi-49-load filename)
(call-with-input-file filename
(lambda (p)
(do ((expr (srfi-49-read p) (srfi-49-read p)))
((eof-object? expr) #t)
(eval expr (current-library))))))
) |
2499cab68ef6959966ce87f15c452d30bfac2f94a6089e09c1d7fb5097cffb2c | jayunit100/RudolF | mysqlscript.clj | ;(ns src.dojo.mysqlscript)
(import java.io.File)
(use 'clojure.stacktrace)
(defn read-dir
"String -> [String]"
[string]
(map #(.getAbsolutePath %)
(.listFiles (File. string))))
(defn make-command
"String -> MySQL String"
[filename]
(str "load data local infile '" filename "' into table assignedshifts;\n"))
(defn make-script
"warning: this could produce extra WRONG statements in the mysql file because of hidden files !!!"
[script-path]
(let [all-files (read-dir "shift_data/cleaned")
command-lines (map make-command all-files)]
(spit script-path
(apply str (cons "use dojo;\n" command-lines)))))
(defn example-make
""
[]
(make-script "mysqlscript.txt"))
(defn run-mysql
""
[]
(.. Runtime
(getRuntime)
(exec "mysql --user=root --password='' < mysqlscript.txt")))
| null | https://raw.githubusercontent.com/jayunit100/RudolF/8936bafbb30c65c78b820062dec550ceeea4b3a4/dojo/src/dojo/mysqlscript.clj | clojure | (ns src.dojo.mysqlscript) |
(import java.io.File)
(use 'clojure.stacktrace)
(defn read-dir
"String -> [String]"
[string]
(map #(.getAbsolutePath %)
(.listFiles (File. string))))
(defn make-command
"String -> MySQL String"
[filename]
(str "load data local infile '" filename "' into table assignedshifts;\n"))
(defn make-script
"warning: this could produce extra WRONG statements in the mysql file because of hidden files !!!"
[script-path]
(let [all-files (read-dir "shift_data/cleaned")
command-lines (map make-command all-files)]
(spit script-path
(apply str (cons "use dojo;\n" command-lines)))))
(defn example-make
""
[]
(make-script "mysqlscript.txt"))
(defn run-mysql
""
[]
(.. Runtime
(getRuntime)
(exec "mysql --user=root --password='' < mysqlscript.txt")))
|
74e006bd99fbd126a4fd69744486ea7e601b1db96a87bb6700c80e852df72f84 | tomgr/libcspm | Prelude.hs | | This module contains all the builtin definitions for the input CSPM
-- language.
{-# LANGUAGE OverloadedStrings #-}
module CSPM.Prelude (
BuiltIn(..),
builtins,
builtInName,
builtInWithName,
transparentFunctionForOccName,
externalFunctionForOccName,
locatedBuiltins,
)
where
import qualified Data.ByteString.Char8 as B
import qualified Data.Map as M
import qualified Data.Set as S
import System.IO.Unsafe
import CSPM.Syntax.Names
import CSPM.Syntax.Types
import Util.Exception
data BuiltIn =
BuiltIn {
name :: Name,
stringName :: B.ByteString,
isDeprecated :: Bool,
deprecatedReplacement :: Maybe Name,
typeScheme :: TypeScheme,
isTypeUnsafe :: Bool,
isExternal :: Bool,
isHidden :: Bool,
isTransparent :: Bool
}
instance Eq BuiltIn where
b1 == b2 = name b1 == name b2
bMap = M.fromList [(stringName b, name b) | b <- builtins True]
builtinMap = M.fromList [(name b, b) | b <- builtins True]
builtInName s = M.findWithDefault (panic "builtin not found") s bMap
builtInWithName s = M.findWithDefault (panic "builtin not found") s builtinMap
builtins :: Bool -> [BuiltIn]
builtins includeHidden =
if includeHidden then allBuiltins
else [b | b <- allBuiltins, not (isHidden b), not (isExternal b),
not (isTransparent b)]
transparentFunctionForOccName :: OccName -> Maybe BuiltIn
transparentFunctionForOccName (OccName s) =
let bs = [b | b <- allBuiltins, isTransparent b, stringName b == s] in
if bs == [] then Nothing else Just (head bs)
externalFunctionForOccName :: OccName -> Maybe BuiltIn
externalFunctionForOccName (OccName s) =
let bs = [b | b <- allBuiltins, isExternal b, stringName b == s] in
if bs == [] then Nothing else Just (head bs)
locatedBuiltins :: S.Set Name
locatedBuiltins = S.fromList $ map builtInName [
"head",
"tail",
"error",
"mapLookup",
"prioritise",
"prioritise_nocache",
"prioritisepo",
"BUFFER",
"WEAK_BUFFER",
"SIGNAL_BUFFER"
]
allBuiltins :: [BuiltIn]
allBuiltins = unsafePerformIO makeBuiltins
# NOINLINE allBuiltins #
makeBuiltins :: IO [BuiltIn]
makeBuiltins = do
let
cspm_union fv = ("union", [TSet fv, TSet fv], TSet fv)
cspm_inter fv = ("inter", [TSet fv, TSet fv], TSet fv)
cspm_diff fv = ("diff", [TSet fv, TSet fv], TSet fv)
cspm_Union fv = ("Union", [TSet (TSet fv)], TSet fv)
cspm_Inter fv = ("Inter", [TSet (TSet fv)], TSet fv)
cspm_member fv = ("member", [fv, TSet fv], TBool)
cspm_card fv = ("card", [TSet fv], TInt)
cspm_empty fv = ("empty", [TSet fv], TBool)
cspm_set fv = ("set", [TSeq fv], TSet fv)
cspm_Set fv = ("Set", [TSet fv], TSet (TSet fv))
cspm_Seq fv = ("Seq", [TSet fv], TSet (TSeq fv))
cspm_seq fv = ("seq", [TSet fv], TSeq fv)
setsSets = [cspm_union, cspm_inter, cspm_diff, cspm_Union, cspm_Inter,
cspm_set, cspm_Set, cspm_Seq]
The following require as they allowing queries to be made about
-- the set. In particular, the following all allow holes to be punched
-- through the type checker and process values to be compared. For
instance , member(P , { STOP } ) card({STOP , P } ) = = 1 ,
empty(diff({STOP } , { P } ) ) , length(seq({STOP , P } ) ) = = 1 all test if
-- P == STOP.
eqSets = [cspm_empty, cspm_card, cspm_member, cspm_seq]
cspm_length fv = ("length", [TSeq fv], TInt)
cspm_null fv = ("null", [TSeq fv], TBool)
cspm_head fv = ("head", [TSeq fv], fv)
cspm_tail fv = ("tail", [TSeq fv], TSeq fv)
cspm_concat fv = ("concat", [TSeq (TSeq fv)], TSeq fv)
cspm_elem fv = ("elem", [fv, TSeq fv], TBool)
seqs = [cspm_length, cspm_null, cspm_head, cspm_tail, cspm_concat]
eqSeqs = [cspm_elem]
cspm_STOP = ("STOP", TProc)
cspm_SKIP = ("SKIP", TProc)
cspm_DIV = ("DIV", TProc)
cspm_CHAOS = ("CHAOS", TFunction [TSet TEvent] TProc)
cspm_RUN = ("RUN", TFunction [TSet TEvent] TProc)
csp_tskip = ("TSKIP", TFunction [] TProc)
csp_tstop = ("TSTOP", TFunction [] TProc)
csp_wait = ("WAIT", TFunction [TInt] TProc)
cspm_refusing_buffer = ("BUFFER", TFunction [TInt, TSet (TTuple [TEvent, TEvent])] TProc)
cspm_exploding_buffer = ("WEAK_BUFFER", TFunction [TInt, TEvent, TSet (TTuple [TEvent, TEvent])] TProc)
cspm_signal_buffer = ("SIGNAL_BUFFER", TFunction [TInt, TEvent, TEvent, TSet (TTuple [TEvent, TEvent])] TProc)
builtInProcs :: [(B.ByteString, Type)]
builtInProcs = [cspm_STOP, cspm_SKIP, cspm_CHAOS, cspm_RUN, csp_tstop,
csp_tskip, csp_wait, cspm_DIV, cspm_refusing_buffer, cspm_exploding_buffer, cspm_signal_buffer]
cspm_Int = ("Int", TSet TInt)
cspm_Bool = ("Bool", TSet TBool)
cspm_Proc = ("Proc", TSet TProc)
cspm_Events = ("Events", TSet TEvent)
cspm_Char = ("Char", TSet TChar)
cspm_true = ("true", TBool)
cspm_false = ("false", TBool)
cspm_True = ("True", TBool)
cspm_False = ("False", TBool)
typeConstructors :: [(B.ByteString, Type)]
typeConstructors = [cspm_Int, cspm_Bool, cspm_Proc, cspm_Events,
cspm_Char, cspm_true, cspm_false, cspm_True, cspm_False]
cspm_emptyMap k v = ("emptyMap", TMap k v)
cspm_mapFromList k v =
("mapFromList", TFunction [TSeq (TTuple [k, v])] (TMap k v))
cspm_mapLookup k v = ("mapLookup", TFunction [TMap k v, k] v)
cspm_mapMember k v = ("mapMember", TFunction [TMap k v, k] TBool)
cspm_mapToList k v =
("mapToList", TFunction [TMap k v] (TSeq (TTuple [k, v])))
cspm_mapUpdate k v =
("mapUpdate", TFunction [TMap k v, k, v] (TMap k v))
cspm_mapUpdateMultiple k v =
("mapUpdateMultiple",
TFunction [TMap k v, TSeq (TTuple [k, v])] (TMap k v))
cspm_mapDelete k v = ("mapDelete", TFunction [TMap k v, k] (TMap k v))
cspm_Map k v = ("Map", TFunction [TSet k, TSet v] (TSet (TMap k v)))
mapFunctions :: [Type -> Type -> (B.ByteString, Type)]
mapFunctions = [cspm_emptyMap, cspm_mapFromList, cspm_mapLookup,
cspm_mapMember, cspm_mapToList, cspm_mapUpdate,
cspm_mapUpdateMultiple, cspm_mapDelete]
externalAndTransparentFunctions :: [(B.ByteString, Type)]
externalAndTransparentFunctions = [
("chase", TFunction [TProc] TProc),
("chase_nocache", TFunction [TProc] TProc)
]
externalFunctions :: [(B.ByteString, Type)]
externalFunctions = [
("deter", TFunction [TProc] TProc),
("failure_watchdog", TFunction [TProc, TSet TEvent, TEvent] TProc),
("loop", TFunction [TProc] TProc),
("prioritise", TFunction [TProc, TSeq (TSet TEvent)] TProc),
("prioritise_nocache", TFunction [TProc, TSeq (TSet TEvent)] TProc),
("prioritisepo", TFunction [TProc, TSet TEvent,
TSet (TTuple [TEvent, TEvent]), TSet TEvent] TProc),
("trace_watchdog", TFunction [TProc, TSet TEvent, TEvent] TProc)
]
complexExternalFunctions :: IO [(B.ByteString, TypeScheme)]
complexExternalFunctions = do
mtransclose <- do
fv @ (TVar (TypeVarRef tv _ _)) <- freshTypeVarWithConstraints [CEq]
return $ ForAll [(tv, [CEq])]
(TFunction [TSet (TTuple [fv,fv]), TSet fv] (TSet (TTuple [fv,fv])))
relational_image <- do
fv1 @ (TVar (TypeVarRef tv1 _ _)) <- freshTypeVarWithConstraints [CEq]
fv2 @ (TVar (TypeVarRef tv2 _ _)) <- freshTypeVarWithConstraints [CSet]
return $ ForAll [(tv1, [CEq]), (tv2, [CSet])]
(TFunction [TSet (TTuple [fv1,fv2])] (TFunction [fv1] (TSet fv2)))
relational_inverse_image <- do
fv1 @ (TVar (TypeVarRef tv1 _ _)) <- freshTypeVarWithConstraints [CEq]
fv2 @ (TVar (TypeVarRef tv2 _ _)) <- freshTypeVarWithConstraints [CSet]
return $ ForAll [(tv2, [CEq]), (tv1, [CSet])]
(TFunction [TSet (TTuple [fv1,fv2])] (TFunction [fv2] (TSet fv1)))
transpose <- do
fv1 @ (TVar (TypeVarRef tv1 _ _)) <- freshTypeVarWithConstraints [CSet]
fv2 @ (TVar (TypeVarRef tv2 _ _)) <- freshTypeVarWithConstraints [CSet]
return $ ForAll [(tv1, [CSet]), (tv2, [CSet])]
(TFunction [TSet (TTuple [fv1,fv2])] (TSet (TTuple [fv2,fv1])))
return [
("mtransclose", mtransclose),
("relational_image", relational_image),
("relational_inverse_image", relational_inverse_image),
("transpose", transpose)
]
transparentFunctions :: [(B.ByteString, Type)]
transparentFunctions = [
("explicate", TFunction [TProc] TProc),
("lazyenumerate", TFunction [TProc] TProc),
("diamond", TFunction [TProc] TProc),
("normal", TFunction [TProc] TProc),
("lazynorm", TFunction [TProc] TProc),
("sbisim", TFunction [TProc] TProc),
("tau_loop_factor", TFunction [TProc] TProc),
("model_compress", TFunction [TProc] TProc),
("wbisim", TFunction [TProc] TProc),
("dbisim", TFunction [TProc] TProc)
]
csp_timed_priority = ("timed_priority", TFunction [TProc] TProc)
cspm_error fv = ("error", [TSeq TChar], fv)
cspm_show fv = ("show", [fv], TSeq TChar)
fdr3Extensions = [cspm_error, cspm_show]
complexExternals <- complexExternalFunctions
let
externalNames =
map fst externalAndTransparentFunctions
++map fst externalFunctions++map fst complexExternals
transparentNames =
map fst transparentFunctions
++map fst externalAndTransparentFunctions
hiddenNames = ["TSKIP", "TSTOP", "timed_priority", "WAIT"]
mkFuncType cs func = do
fv @ (TVar (TypeVarRef tv _ _)) <- freshTypeVarWithConstraints cs
let (n, args, ret) = func fv
let t = ForAll [(tv, cs)] (TFunction args ret)
return (n, t)
mkUnsafeFuncType n = do
fv1 @ (TVar (TypeVarRef tv1 _ _)) <- freshTypeVarWithConstraints []
fv2 @ (TVar (TypeVarRef tv2 _ _)) <- freshTypeVarWithConstraints []
let t = ForAll [(tv1, []), (tv2, [])] (TFunction [fv1] fv2)
return (n, t)
mkPatternType func = do
let (n, t) = func
return (n, ForAll [] t)
mkMapFunction f = do
fv1 @ (TVar (TypeVarRef tv1 _ _)) <- freshTypeVarWithConstraints [CSet]
fv2 @ (TVar (TypeVarRef tv2 _ _)) <- freshTypeVarWithConstraints []
let (n, t) = f fv1 fv2
return (n, ForAll [(tv1, [CSet]), (tv2, [])] t)
mkMapFunction' f = do
fv1 @ (TVar (TypeVarRef tv1 _ _)) <- freshTypeVarWithConstraints [CSet]
fv2 @ (TVar (TypeVarRef tv2 _ _)) <- freshTypeVarWithConstraints [CSet]
let (n, t) = f fv1 fv2
return (n, ForAll [(tv1, [CSet]), (tv2, [CSet])] t)
unsafeFunctionNames :: [B.ByteString]
unsafeFunctionNames = []
deprecatedNames :: [B.ByteString]
deprecatedNames = []
replacementForDeprecatedName :: B.ByteString -> Maybe B.ByteString
replacementForDeprecatedName _ = Nothing
makeBuiltIn :: (B.ByteString, TypeScheme) -> IO BuiltIn
makeBuiltIn (s, ts) = do
n <- mkWiredInName (UnQual (OccName s)) False
return $ BuiltIn {
name = n,
stringName = s,
isDeprecated = s `elem` deprecatedNames,
deprecatedReplacement = Nothing,
typeScheme = ts,
isHidden = s `elem` hiddenNames,
isTypeUnsafe = s `elem` unsafeFunctionNames,
isExternal = s `elem` externalNames,
isTransparent = s `elem` transparentNames
}
makeReplacements :: [BuiltIn] -> BuiltIn -> IO BuiltIn
makeReplacements bs b | isDeprecated b =
case replacementForDeprecatedName (stringName b) of
Just s' ->
case filter (\b' -> stringName b' == s') bs of
[b'] -> return $ b { deprecatedReplacement = Just (name b') }
[] -> return b
Nothing -> return b
makeReplacements _ b = return b
makeExtensionType = do
fv1 @ (TVar (TypeVarRef tv1 _ _)) <- freshTypeVarWithConstraints []
fv2 @ (TVar (TypeVarRef tv2 _ _)) <- freshTypeVarWithConstraints []
return $ ForAll [(tv1, []), (tv2, [CYieldable])]
(TFunction [TDotable fv1 fv2] (TSet fv1))
makeProductionsType = do
fv1 @ (TVar (TypeVarRef tv1 _ _)) <- freshTypeVarWithConstraints []
fv2 @ (TVar (fv2ref@(TypeVarRef tv2 _ _))) <-
freshTypeVarWithConstraints []
return $ ForAll [(tv1, [CYieldable]), (tv2, [])]
(TFunction [TExtendable fv1 fv2ref] (TSet fv1))
makeExtensionsProductions = do
t1 <- makeExtensionType
t2 <- makeProductionsType
return [("extensions", t1), ("productions", t2)]
bs1 <- mapM (mkFuncType []) seqs
bs2 <- mapM (mkFuncType [CSet]) setsSets
bs2' <- mapM (mkFuncType [CEq]) (eqSets ++ eqSeqs)
bs3 <- mapM mkPatternType typeConstructors
bs4 <- mapM mkPatternType builtInProcs
bs5 <- makeExtensionsProductions
bs6 <- mapM mkPatternType (externalFunctions++[csp_timed_priority])
bs7 <- mapM mkPatternType transparentFunctions
bs8 <- mapM mkPatternType externalAndTransparentFunctions
bs9 <- mapM (mkFuncType []) fdr3Extensions
bs10 <- mapM mkMapFunction mapFunctions
bs11 <- mapM mkMapFunction' [cspm_Map]
let bs = bs1++bs2++bs2'++bs3++bs4++bs5++bs6++bs7++complexExternals++bs8++bs9
++bs10++bs11
bs' <- mapM makeBuiltIn bs
bs'' <- mapM (makeReplacements bs') bs'
return bs''
| null | https://raw.githubusercontent.com/tomgr/libcspm/24d1b41954191a16e3b5e388e35f5ba0915d671e/src/CSPM/Prelude.hs | haskell | language.
# LANGUAGE OverloadedStrings #
the set. In particular, the following all allow holes to be punched
through the type checker and process values to be compared. For
P == STOP. | | This module contains all the builtin definitions for the input CSPM
module CSPM.Prelude (
BuiltIn(..),
builtins,
builtInName,
builtInWithName,
transparentFunctionForOccName,
externalFunctionForOccName,
locatedBuiltins,
)
where
import qualified Data.ByteString.Char8 as B
import qualified Data.Map as M
import qualified Data.Set as S
import System.IO.Unsafe
import CSPM.Syntax.Names
import CSPM.Syntax.Types
import Util.Exception
data BuiltIn =
BuiltIn {
name :: Name,
stringName :: B.ByteString,
isDeprecated :: Bool,
deprecatedReplacement :: Maybe Name,
typeScheme :: TypeScheme,
isTypeUnsafe :: Bool,
isExternal :: Bool,
isHidden :: Bool,
isTransparent :: Bool
}
instance Eq BuiltIn where
b1 == b2 = name b1 == name b2
bMap = M.fromList [(stringName b, name b) | b <- builtins True]
builtinMap = M.fromList [(name b, b) | b <- builtins True]
builtInName s = M.findWithDefault (panic "builtin not found") s bMap
builtInWithName s = M.findWithDefault (panic "builtin not found") s builtinMap
builtins :: Bool -> [BuiltIn]
builtins includeHidden =
if includeHidden then allBuiltins
else [b | b <- allBuiltins, not (isHidden b), not (isExternal b),
not (isTransparent b)]
transparentFunctionForOccName :: OccName -> Maybe BuiltIn
transparentFunctionForOccName (OccName s) =
let bs = [b | b <- allBuiltins, isTransparent b, stringName b == s] in
if bs == [] then Nothing else Just (head bs)
externalFunctionForOccName :: OccName -> Maybe BuiltIn
externalFunctionForOccName (OccName s) =
let bs = [b | b <- allBuiltins, isExternal b, stringName b == s] in
if bs == [] then Nothing else Just (head bs)
locatedBuiltins :: S.Set Name
locatedBuiltins = S.fromList $ map builtInName [
"head",
"tail",
"error",
"mapLookup",
"prioritise",
"prioritise_nocache",
"prioritisepo",
"BUFFER",
"WEAK_BUFFER",
"SIGNAL_BUFFER"
]
allBuiltins :: [BuiltIn]
allBuiltins = unsafePerformIO makeBuiltins
# NOINLINE allBuiltins #
makeBuiltins :: IO [BuiltIn]
makeBuiltins = do
let
cspm_union fv = ("union", [TSet fv, TSet fv], TSet fv)
cspm_inter fv = ("inter", [TSet fv, TSet fv], TSet fv)
cspm_diff fv = ("diff", [TSet fv, TSet fv], TSet fv)
cspm_Union fv = ("Union", [TSet (TSet fv)], TSet fv)
cspm_Inter fv = ("Inter", [TSet (TSet fv)], TSet fv)
cspm_member fv = ("member", [fv, TSet fv], TBool)
cspm_card fv = ("card", [TSet fv], TInt)
cspm_empty fv = ("empty", [TSet fv], TBool)
cspm_set fv = ("set", [TSeq fv], TSet fv)
cspm_Set fv = ("Set", [TSet fv], TSet (TSet fv))
cspm_Seq fv = ("Seq", [TSet fv], TSet (TSeq fv))
cspm_seq fv = ("seq", [TSet fv], TSeq fv)
setsSets = [cspm_union, cspm_inter, cspm_diff, cspm_Union, cspm_Inter,
cspm_set, cspm_Set, cspm_Seq]
The following require as they allowing queries to be made about
instance , member(P , { STOP } ) card({STOP , P } ) = = 1 ,
empty(diff({STOP } , { P } ) ) , length(seq({STOP , P } ) ) = = 1 all test if
eqSets = [cspm_empty, cspm_card, cspm_member, cspm_seq]
cspm_length fv = ("length", [TSeq fv], TInt)
cspm_null fv = ("null", [TSeq fv], TBool)
cspm_head fv = ("head", [TSeq fv], fv)
cspm_tail fv = ("tail", [TSeq fv], TSeq fv)
cspm_concat fv = ("concat", [TSeq (TSeq fv)], TSeq fv)
cspm_elem fv = ("elem", [fv, TSeq fv], TBool)
seqs = [cspm_length, cspm_null, cspm_head, cspm_tail, cspm_concat]
eqSeqs = [cspm_elem]
cspm_STOP = ("STOP", TProc)
cspm_SKIP = ("SKIP", TProc)
cspm_DIV = ("DIV", TProc)
cspm_CHAOS = ("CHAOS", TFunction [TSet TEvent] TProc)
cspm_RUN = ("RUN", TFunction [TSet TEvent] TProc)
csp_tskip = ("TSKIP", TFunction [] TProc)
csp_tstop = ("TSTOP", TFunction [] TProc)
csp_wait = ("WAIT", TFunction [TInt] TProc)
cspm_refusing_buffer = ("BUFFER", TFunction [TInt, TSet (TTuple [TEvent, TEvent])] TProc)
cspm_exploding_buffer = ("WEAK_BUFFER", TFunction [TInt, TEvent, TSet (TTuple [TEvent, TEvent])] TProc)
cspm_signal_buffer = ("SIGNAL_BUFFER", TFunction [TInt, TEvent, TEvent, TSet (TTuple [TEvent, TEvent])] TProc)
builtInProcs :: [(B.ByteString, Type)]
builtInProcs = [cspm_STOP, cspm_SKIP, cspm_CHAOS, cspm_RUN, csp_tstop,
csp_tskip, csp_wait, cspm_DIV, cspm_refusing_buffer, cspm_exploding_buffer, cspm_signal_buffer]
cspm_Int = ("Int", TSet TInt)
cspm_Bool = ("Bool", TSet TBool)
cspm_Proc = ("Proc", TSet TProc)
cspm_Events = ("Events", TSet TEvent)
cspm_Char = ("Char", TSet TChar)
cspm_true = ("true", TBool)
cspm_false = ("false", TBool)
cspm_True = ("True", TBool)
cspm_False = ("False", TBool)
typeConstructors :: [(B.ByteString, Type)]
typeConstructors = [cspm_Int, cspm_Bool, cspm_Proc, cspm_Events,
cspm_Char, cspm_true, cspm_false, cspm_True, cspm_False]
cspm_emptyMap k v = ("emptyMap", TMap k v)
cspm_mapFromList k v =
("mapFromList", TFunction [TSeq (TTuple [k, v])] (TMap k v))
cspm_mapLookup k v = ("mapLookup", TFunction [TMap k v, k] v)
cspm_mapMember k v = ("mapMember", TFunction [TMap k v, k] TBool)
cspm_mapToList k v =
("mapToList", TFunction [TMap k v] (TSeq (TTuple [k, v])))
cspm_mapUpdate k v =
("mapUpdate", TFunction [TMap k v, k, v] (TMap k v))
cspm_mapUpdateMultiple k v =
("mapUpdateMultiple",
TFunction [TMap k v, TSeq (TTuple [k, v])] (TMap k v))
cspm_mapDelete k v = ("mapDelete", TFunction [TMap k v, k] (TMap k v))
cspm_Map k v = ("Map", TFunction [TSet k, TSet v] (TSet (TMap k v)))
mapFunctions :: [Type -> Type -> (B.ByteString, Type)]
mapFunctions = [cspm_emptyMap, cspm_mapFromList, cspm_mapLookup,
cspm_mapMember, cspm_mapToList, cspm_mapUpdate,
cspm_mapUpdateMultiple, cspm_mapDelete]
externalAndTransparentFunctions :: [(B.ByteString, Type)]
externalAndTransparentFunctions = [
("chase", TFunction [TProc] TProc),
("chase_nocache", TFunction [TProc] TProc)
]
externalFunctions :: [(B.ByteString, Type)]
externalFunctions = [
("deter", TFunction [TProc] TProc),
("failure_watchdog", TFunction [TProc, TSet TEvent, TEvent] TProc),
("loop", TFunction [TProc] TProc),
("prioritise", TFunction [TProc, TSeq (TSet TEvent)] TProc),
("prioritise_nocache", TFunction [TProc, TSeq (TSet TEvent)] TProc),
("prioritisepo", TFunction [TProc, TSet TEvent,
TSet (TTuple [TEvent, TEvent]), TSet TEvent] TProc),
("trace_watchdog", TFunction [TProc, TSet TEvent, TEvent] TProc)
]
complexExternalFunctions :: IO [(B.ByteString, TypeScheme)]
complexExternalFunctions = do
mtransclose <- do
fv @ (TVar (TypeVarRef tv _ _)) <- freshTypeVarWithConstraints [CEq]
return $ ForAll [(tv, [CEq])]
(TFunction [TSet (TTuple [fv,fv]), TSet fv] (TSet (TTuple [fv,fv])))
relational_image <- do
fv1 @ (TVar (TypeVarRef tv1 _ _)) <- freshTypeVarWithConstraints [CEq]
fv2 @ (TVar (TypeVarRef tv2 _ _)) <- freshTypeVarWithConstraints [CSet]
return $ ForAll [(tv1, [CEq]), (tv2, [CSet])]
(TFunction [TSet (TTuple [fv1,fv2])] (TFunction [fv1] (TSet fv2)))
relational_inverse_image <- do
fv1 @ (TVar (TypeVarRef tv1 _ _)) <- freshTypeVarWithConstraints [CEq]
fv2 @ (TVar (TypeVarRef tv2 _ _)) <- freshTypeVarWithConstraints [CSet]
return $ ForAll [(tv2, [CEq]), (tv1, [CSet])]
(TFunction [TSet (TTuple [fv1,fv2])] (TFunction [fv2] (TSet fv1)))
transpose <- do
fv1 @ (TVar (TypeVarRef tv1 _ _)) <- freshTypeVarWithConstraints [CSet]
fv2 @ (TVar (TypeVarRef tv2 _ _)) <- freshTypeVarWithConstraints [CSet]
return $ ForAll [(tv1, [CSet]), (tv2, [CSet])]
(TFunction [TSet (TTuple [fv1,fv2])] (TSet (TTuple [fv2,fv1])))
return [
("mtransclose", mtransclose),
("relational_image", relational_image),
("relational_inverse_image", relational_inverse_image),
("transpose", transpose)
]
transparentFunctions :: [(B.ByteString, Type)]
transparentFunctions = [
("explicate", TFunction [TProc] TProc),
("lazyenumerate", TFunction [TProc] TProc),
("diamond", TFunction [TProc] TProc),
("normal", TFunction [TProc] TProc),
("lazynorm", TFunction [TProc] TProc),
("sbisim", TFunction [TProc] TProc),
("tau_loop_factor", TFunction [TProc] TProc),
("model_compress", TFunction [TProc] TProc),
("wbisim", TFunction [TProc] TProc),
("dbisim", TFunction [TProc] TProc)
]
csp_timed_priority = ("timed_priority", TFunction [TProc] TProc)
cspm_error fv = ("error", [TSeq TChar], fv)
cspm_show fv = ("show", [fv], TSeq TChar)
fdr3Extensions = [cspm_error, cspm_show]
complexExternals <- complexExternalFunctions
let
externalNames =
map fst externalAndTransparentFunctions
++map fst externalFunctions++map fst complexExternals
transparentNames =
map fst transparentFunctions
++map fst externalAndTransparentFunctions
hiddenNames = ["TSKIP", "TSTOP", "timed_priority", "WAIT"]
mkFuncType cs func = do
fv @ (TVar (TypeVarRef tv _ _)) <- freshTypeVarWithConstraints cs
let (n, args, ret) = func fv
let t = ForAll [(tv, cs)] (TFunction args ret)
return (n, t)
mkUnsafeFuncType n = do
fv1 @ (TVar (TypeVarRef tv1 _ _)) <- freshTypeVarWithConstraints []
fv2 @ (TVar (TypeVarRef tv2 _ _)) <- freshTypeVarWithConstraints []
let t = ForAll [(tv1, []), (tv2, [])] (TFunction [fv1] fv2)
return (n, t)
mkPatternType func = do
let (n, t) = func
return (n, ForAll [] t)
mkMapFunction f = do
fv1 @ (TVar (TypeVarRef tv1 _ _)) <- freshTypeVarWithConstraints [CSet]
fv2 @ (TVar (TypeVarRef tv2 _ _)) <- freshTypeVarWithConstraints []
let (n, t) = f fv1 fv2
return (n, ForAll [(tv1, [CSet]), (tv2, [])] t)
mkMapFunction' f = do
fv1 @ (TVar (TypeVarRef tv1 _ _)) <- freshTypeVarWithConstraints [CSet]
fv2 @ (TVar (TypeVarRef tv2 _ _)) <- freshTypeVarWithConstraints [CSet]
let (n, t) = f fv1 fv2
return (n, ForAll [(tv1, [CSet]), (tv2, [CSet])] t)
unsafeFunctionNames :: [B.ByteString]
unsafeFunctionNames = []
deprecatedNames :: [B.ByteString]
deprecatedNames = []
replacementForDeprecatedName :: B.ByteString -> Maybe B.ByteString
replacementForDeprecatedName _ = Nothing
makeBuiltIn :: (B.ByteString, TypeScheme) -> IO BuiltIn
makeBuiltIn (s, ts) = do
n <- mkWiredInName (UnQual (OccName s)) False
return $ BuiltIn {
name = n,
stringName = s,
isDeprecated = s `elem` deprecatedNames,
deprecatedReplacement = Nothing,
typeScheme = ts,
isHidden = s `elem` hiddenNames,
isTypeUnsafe = s `elem` unsafeFunctionNames,
isExternal = s `elem` externalNames,
isTransparent = s `elem` transparentNames
}
makeReplacements :: [BuiltIn] -> BuiltIn -> IO BuiltIn
makeReplacements bs b | isDeprecated b =
case replacementForDeprecatedName (stringName b) of
Just s' ->
case filter (\b' -> stringName b' == s') bs of
[b'] -> return $ b { deprecatedReplacement = Just (name b') }
[] -> return b
Nothing -> return b
makeReplacements _ b = return b
makeExtensionType = do
fv1 @ (TVar (TypeVarRef tv1 _ _)) <- freshTypeVarWithConstraints []
fv2 @ (TVar (TypeVarRef tv2 _ _)) <- freshTypeVarWithConstraints []
return $ ForAll [(tv1, []), (tv2, [CYieldable])]
(TFunction [TDotable fv1 fv2] (TSet fv1))
makeProductionsType = do
fv1 @ (TVar (TypeVarRef tv1 _ _)) <- freshTypeVarWithConstraints []
fv2 @ (TVar (fv2ref@(TypeVarRef tv2 _ _))) <-
freshTypeVarWithConstraints []
return $ ForAll [(tv1, [CYieldable]), (tv2, [])]
(TFunction [TExtendable fv1 fv2ref] (TSet fv1))
makeExtensionsProductions = do
t1 <- makeExtensionType
t2 <- makeProductionsType
return [("extensions", t1), ("productions", t2)]
bs1 <- mapM (mkFuncType []) seqs
bs2 <- mapM (mkFuncType [CSet]) setsSets
bs2' <- mapM (mkFuncType [CEq]) (eqSets ++ eqSeqs)
bs3 <- mapM mkPatternType typeConstructors
bs4 <- mapM mkPatternType builtInProcs
bs5 <- makeExtensionsProductions
bs6 <- mapM mkPatternType (externalFunctions++[csp_timed_priority])
bs7 <- mapM mkPatternType transparentFunctions
bs8 <- mapM mkPatternType externalAndTransparentFunctions
bs9 <- mapM (mkFuncType []) fdr3Extensions
bs10 <- mapM mkMapFunction mapFunctions
bs11 <- mapM mkMapFunction' [cspm_Map]
let bs = bs1++bs2++bs2'++bs3++bs4++bs5++bs6++bs7++complexExternals++bs8++bs9
++bs10++bs11
bs' <- mapM makeBuiltIn bs
bs'' <- mapM (makeReplacements bs') bs'
return bs''
|
1d5c5cdc29696e4118d7889a0ec60e797d918423f3b27fd2dd649b6ca25cc327 | maximk/zergling | toppage_handler.erl | -module(toppage_handler).
-export([init/3]).
-export([handle/2,terminate/3]).
init({tcp,http}, Req, []) ->
TsProxyReceived = zergling_app:timestamp(),
keeper ! {get,self()},
OtherVars = receive {vars,X} -> X end,
TsReqReceived = proplists:get_value(ts_req_received, OtherVars),
TsLingStarted = proplists:get_value(ts_ling_started, OtherVars),
TsBootStarted = proplists:get_value(ts_boot_started, OtherVars),
TsAppStarted = proplists:get_value(ts_app_started, OtherVars),
TsCowboyStarted = proplists:get_value(ts_cowboy_started, OtherVars),
TsSpawnerNotified = proplists:get_value(ts_spawner_notified, OtherVars),
IntLingStarted = (TsLingStarted - TsReqReceived) *1000,
IntBootStarted = (TsBootStarted - TsLingStarted) *1000,
IntAppStarted = (TsAppStarted - TsBootStarted) *1000,
IntCowboyStarted = (TsCowboyStarted - TsAppStarted) *1000,
IntSpawnerNotified = (TsSpawnerNotified - TsCowboyStarted) *1000,
IntProxyReceived = (TsProxyReceived - TsSpawnerNotified) *1000,
TotalSec = TsProxyReceived - TsReqReceived,
CmdLine = io_lib:format("~p", [init:get_arguments()]),
Vars = [{cmd_line,CmdLine},
{ts_proxy_received,TsProxyReceived},
{int_ling_started,IntLingStarted},
{int_boot_started,IntBootStarted},
{int_app_started,IntAppStarted},
{int_cowboy_started,IntCowboyStarted},
{int_spawner_notified,IntSpawnerNotified},
{int_proxy_received,IntProxyReceived},
{total_sec,TotalSec}]
++ OtherVars,
{ok,Body} = welcome_dtl:render(Vars),
{ok,Reply} = cowboy_req:reply(200, [{<<"connection">>,<<"close">>}], Body, Req),
{shutdown,Reply,undefined}.
handle(Req, St) ->
{ok,Req,St}. %% never reached
terminate(_What, _Req, _St) ->
%% A single request per instance
init:stop().
EOF
| null | https://raw.githubusercontent.com/maximk/zergling/0e45a9bd401543f187f2a33ef764576ade3686ac/src/toppage_handler.erl | erlang | never reached
A single request per instance | -module(toppage_handler).
-export([init/3]).
-export([handle/2,terminate/3]).
init({tcp,http}, Req, []) ->
TsProxyReceived = zergling_app:timestamp(),
keeper ! {get,self()},
OtherVars = receive {vars,X} -> X end,
TsReqReceived = proplists:get_value(ts_req_received, OtherVars),
TsLingStarted = proplists:get_value(ts_ling_started, OtherVars),
TsBootStarted = proplists:get_value(ts_boot_started, OtherVars),
TsAppStarted = proplists:get_value(ts_app_started, OtherVars),
TsCowboyStarted = proplists:get_value(ts_cowboy_started, OtherVars),
TsSpawnerNotified = proplists:get_value(ts_spawner_notified, OtherVars),
IntLingStarted = (TsLingStarted - TsReqReceived) *1000,
IntBootStarted = (TsBootStarted - TsLingStarted) *1000,
IntAppStarted = (TsAppStarted - TsBootStarted) *1000,
IntCowboyStarted = (TsCowboyStarted - TsAppStarted) *1000,
IntSpawnerNotified = (TsSpawnerNotified - TsCowboyStarted) *1000,
IntProxyReceived = (TsProxyReceived - TsSpawnerNotified) *1000,
TotalSec = TsProxyReceived - TsReqReceived,
CmdLine = io_lib:format("~p", [init:get_arguments()]),
Vars = [{cmd_line,CmdLine},
{ts_proxy_received,TsProxyReceived},
{int_ling_started,IntLingStarted},
{int_boot_started,IntBootStarted},
{int_app_started,IntAppStarted},
{int_cowboy_started,IntCowboyStarted},
{int_spawner_notified,IntSpawnerNotified},
{int_proxy_received,IntProxyReceived},
{total_sec,TotalSec}]
++ OtherVars,
{ok,Body} = welcome_dtl:render(Vars),
{ok,Reply} = cowboy_req:reply(200, [{<<"connection">>,<<"close">>}], Body, Req),
{shutdown,Reply,undefined}.
handle(Req, St) ->
terminate(_What, _Req, _St) ->
init:stop().
EOF
|
7df6d2d1523c9290fd74acd89b1cbd41d51dcf96f870ab5dfb40f19935073168 | ucsd-progsys/dsolve | common.ml |
* Copyright © 2008 The Regents of the University of California . All rights reserved .
*
* Permission is hereby granted , without written agreement and without
* license or royalty fees , to use , copy , modify , and distribute this
* software and its documentation for any purpose , provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software .
*
* IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
* FOR DIRECT , INDIRECT , SPECIAL , INCIDENTAL , OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION , EVEN
* IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE .
*
* THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES ,
* INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE . THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN " AS IS " BASIS , AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION
* TO PROVIDE MAINTENANCE , SUPPORT , UPDATES , ENHANCEMENTS , OR MODIFICATIONS .
*
* Copyright © 2008 The Regents of the University of California. All rights reserved.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software.
*
* IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
* FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION
* TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
*)
open Types
module F = Format
module BS = Bstats
module StringMap = Map.Make(String)
module ComparablePath = struct
type t = Path.t
let compare = compare
let equal = Path.same
let hash = Hashtbl.hash
end
module PathMap = Map.Make(ComparablePath)
let qual_test_var = Path.Pident (Ident.create_persistent "AA")
let dummy_id = Ident.create_persistent ""
let incpp ir =
incr ir;!ir
let array_to_index_list a =
List.rev (snd
(Array.fold_left (fun (i,rv) v -> (i+1,(i,v)::rv)) (0,[]) a))
let rec pprint_many brk s f ppf = function
| [] -> ()
| x::[] -> F.fprintf ppf "%a" f x
| x::xs' -> ((if brk then F.fprintf ppf "%a %s@ " f x s else F.fprintf ppf "%a %s" f x s);
pprint_many brk s f ppf xs')
let pprint_list sepstr pp =
(fun ppf -> Oprint.print_list pp
(fun ppf -> F.fprintf ppf "%s@;<1 2>" sepstr) ppf)
let pprint_str ppf s =
F.fprintf ppf "%s" s
let rec is_unique xs =
match xs with
x :: xs -> if List.mem x xs then false else is_unique xs
| [] -> true
let resl_opt f = function
| Some o -> f o
| None -> []
let resi_opt f = function
| Some o -> f o
| None -> ()
let opt_iter f l =
List.iter (resi_opt f) l
let add il i = il := i::!il
let addl il i = il := List.rev_append i !il
let same_type q p = (Types.TypeOps.equal q p)
let dummy () = Path.mk_ident ""
let same_name_id id =
Ident.create (Ident.name id)
let same_path_i p i = Path.unique_name p = Ident.unique_name i
let i2p i = Path.Pident i
let p2i p = match p with
Path.Pident id -> id
| _ -> assert false
let lookup_path s env =
fst (Env.lookup_value (Longident.parse s) env)
let lookup_type p env =
(Env.find_value p env).Types.val_type
let tmpstring s = if String.length s >= 2 then (s.[0] = '_' && s.[1] = '\'') || (s.[0] = 'A' && s.[1] = 'A') else false
let path_is_temp p = match Path.ident_name p with Some s -> tmpstring s | None -> false
let tuple_elem_id i =
Ident.create ("e" ^ string_of_int i)
let abstr_elem_id () =
Ident.create "supr" (*^ string_of_int (get_unique ()))*)
let rec maybe_list_from_singles = function
x :: xs -> (match x with [a] -> Some a | _ -> None) :: (maybe_list_from_singles xs)
| [] -> []
let maybe_bool = function
Some _ -> true
| None -> false
let all_defined xs =
List.for_all maybe_bool xs
let has_prefix pre s =
try String.sub s 0 ( String.length pre ) = pre
with Invalid_argument _ - > false
let has_prefix pre s =
try String.sub s 0 (String.length pre) = pre
with Invalid_argument _ -> false
*)
let sub_from_list subs s =
try List.assoc s subs with Not_found -> s
let strip_meas s =
let start = try 1 + (String.rindex s '.') with Not_found -> 0 in
try
if String.sub s start 6 = "_meas_" then
let pre = String.sub s 0 start in
let post = String.sub s (start + 6) ((String.length s) - start - 6) in
pre ^ post
else s
with Invalid_argument _ -> s
let sub_from s c =
try
let x = String.rindex s c in
String.sub s x ( ( String.length s ) - x )
with Not_found - > s
let sub_to_r s c =
let x = String.rindex s c in
String.sub s 0 x
let strip_meas_whole s =
if ! then s else
try
let start = try String.rindex s ' . '
if String.sub s 0 6 = " _ meas _ " then
String.sub s 6 ( String.length s - 6 )
else s with Invalid_argument _ - > s
let rw_suff f s c =
let suff = f ( sub_from s c ) in
try ( sub_to_r s c ) ^ suff with Not_found - > suff
let strip_meas s =
rw_suff strip_meas_whole s ' . '
let sub_from s c =
try
let x = String.rindex s c in
String.sub s x ((String.length s) - x)
with Not_found -> s
let sub_to_r s c =
let x = String.rindex s c in
String.sub s 0 x
let strip_meas_whole s =
if !Clflags.dsmeasures then s else
try
let start = try String.rindex s '.'
if String.sub s 0 6 = "_meas_" then
String.sub s 6 (String.length s - 6)
else s with Invalid_argument _ -> s
let rw_suff f s c =
let suff = f (sub_from s c) in
try (sub_to_r s c) ^ suff with Not_found -> suff
let strip_meas s =
rw_suff strip_meas_whole s '.'
*)
let append_pref p s =
(p ^ "." ^ s)
let app_fst f ( a , b ) = ( f a , b )
let app_snd f ( a , b ) = ( a , f b )
let app_pr f ( a , b ) = ( f a , f b )
let app_triple f ( a , b , c ) = ( f a , f b , f c )
let app_snd f (a, b) = (a, f b)
let app_pr f (a, b) = (f a, f b)
let app_triple f (a, b, c) = (f a, f b, f c)
*)
let l_to_s l = String.concat "." (Longident.flatten l)
let s_to_l s = Longident.parse s
let l_is_id id = function
| Longident.Lident s -> s = id
| _ -> false
let s_to_p s = Path.Pident (Ident.create s)
let int_of_tag = function
Cstr_constant n -> 2*n
| Cstr_block n -> 2*n+1
| Cstr_exception _-> assert false
let tag_of_int n =
if 2*(n/2) = n then
Cstr_constant (n/2)
else
Cstr_block ((n-1)/2)
let sort_and_compact xs =
let rec f = function
| x1::(x2::_ as xs') ->
if x1 = x2 then (f xs') else x1::(f xs')
| xs' -> xs' in
f (List.sort compare xs)
(****************************************************************)
(************* Output levels ************************************)
(****************************************************************)
(* verbosity levels by purpose *)
let ol_always = 0
let ol_solve_error = 1
let ol_warning = 1
let ol_solve_master = 2
let ol_solve_stats = 2
let ol_timing = 2
let ol_default = 2
let ol_warn_mlqs = 3
let ol_normalized = 3
let ol_dquals = 4
let ol_unique_names = 5 (* must be > ol_dquals *)
let ol_solve = 10
let ol_refine = 11
let ol_scc = 12
let ol_dump_env = 10
let ol_axioms = 5
let ol_dump_prover = 20
let ol_verb_constrs = 21
let ol_dump_wfs = 22
let ol_dump_meas = 30
let ol_dump_quals = 50
let ol_insane = 200
let verbose_level = ref ol_default
let verb_stack = ref []
let null_formatter = F.make_formatter (fun a b c -> ()) ignore
let nprintf a = F.fprintf null_formatter a
let ck_olev l = l <= !verbose_level
let cprintf l = if ck_olev l then F.printf else nprintf
let ecprintf l = if ck_olev l then F.eprintf else nprintf
let fcprintf ppf l = if ck_olev l then F.fprintf ppf else nprintf
let icprintf printer l ppf = if ck_olev l then printer ppf else printer null_formatter
let cprintln l s = if ck_olev l then Printf.ksprintf (F.printf "@[%s@\n@]") s else nprintf
let ident_name i = if ck_olev ol_unique_names then Ident.unique_name i else Ident.name i
let path_name p = if ck_olev ol_unique_names then Path.unique_name p else Path.name p
let elevate_olev l = if ck_olev l then () else verb_stack := !verbose_level :: !verb_stack; verbose_level := l
let restore_olev = match !verb_stack with x :: xs -> verbose_level := x; verb_stack := xs | _ -> ()
(****************************************************************)
(************* SCC Ranking **************************************)
(****************************************************************)
module Int : Graph.Sig.COMPARABLE with type t = int * string =
struct
type t = int * string
let compare = compare
let hash = Hashtbl.hash
let equal = (=)
end
module G = Graph.Imperative.Digraph.Concrete(Int)
module SCC = Graph.Components.Make(G)
(* Use of Graphviz *)
let io_to_string = function
| Some i -> string_of_int i
| None -> "*"
let xs_to_string f xs =
"["^(String.concat "," (List.map f xs))^"]"
module DotGraph =
struct
type t = G.t
module V = G.V
module E = G.E
let iter_vertex = G.iter_vertex
let iter_edges_e = G.iter_edges_e
let graph_attributes g = []
let default_vertex_attributes g = [`Shape `Box]
let vertex_name (i,s) = Printf.sprintf "V_%d_%s" i s
let vertex_attributes v = [`Label (vertex_name v)]
let default_edge_attributes g = []
let edge_attributes e = []
let get_subgraph v = None
end
module Dot = Graph.Graphviz.Dot(DotGraph)
let dump_graph g =
let oc = open_out "constraints.dot" in
Dot.output_graph oc g;
close_out oc
Given list [ ( u , v ) ] returns a numbering [ ( ui , ri ) ] s.t .
* 1 . if ui , uj in same SCC then ri = rj
* 2 . if ui - > uj then ui > = uj
* 1. if ui,uj in same SCC then ri = rj
* 2. if ui -> uj then ui >= uj *)
let scc_rank f ijs =
let g = G.create () in
let _ = Bstats.time "making graph" (List.iter (fun (i,j) -> G.add_edge g (i,(f i)) (j,(f j)))) ijs in
let _ = if !Clflags.dump_graph then dump_graph g in
let a = SCC.scc_array g in
let _ = cprintf ol_scc "@[dep@ graph:@ vertices@ =@ @ %d,@ sccs@ =@ %d@ @\n@]"
(G.nb_vertex g) (Array.length a);
cprintf ol_scc "@[scc@ sizes:@\n@]";
let int_s_to_string (i,s) = Printf.sprintf "(%d,%s)" i s in
Array.iteri
(fun i xs ->
cprintf ol_scc "@[%d@ :@ %s@ @\n@]"
i (xs_to_string int_s_to_string xs)) a;
cprintf ol_scc "@[@\n@]" in
let sccs = array_to_index_list a in
Misc.flap (fun (i,vs) -> List.map (fun (j,_) -> (j,i)) vs) sccs
let g1 = [ ( ) ] ; ;
let = [ ( 0,1);(1,2);(2,0);(1,3);(4,3 ) ;
( 5,6);(5,7);(6,9);(7,9);(7,8);(8,5 ) ] ; ;
let g3 = ( 6,2)::g2 ; ;
let g4 = ( 2,6)::g2 ; ;
let n1 = ; ;
let n2 = ; ;
let n3 = ; ;
let n4 = ; ;
let g1 = [(1,2);(2,3);(3,1);(2,4);(3,4);(4,5)];;
let g2 = [(0,1);(1,2);(2,0);(1,3);(4,3);
(5,6);(5,7);(6,9);(7,9);(7,8);(8,5)];;
let g3 = (6,2)::g2;;
let g4 = (2,6)::g2;;
let n1 = make_scc_num g1 ;;
let n2 = make_scc_num g2 ;;
let n3 = make_scc_num g3 ;;
let n4 = make_scc_num g4 ;; *)
let asserts s b =
try assert b with ex ->
Printf.printf "Common.asserts failure: %s " s; raise ex
let append_to_file f s =
let oc = Unix.openfile f [Unix.O_WRONLY; Unix.O_APPEND; Unix.O_CREAT] 420 in
ignore (Unix.write oc s 0 ((String.length s)-1) );
Unix.close oc
let write_to_file f s =
let oc = open_out f in
output_string oc s;
close_out oc
(**************************************************************************)
(****************** Type Specific to_string routines **********************)
(**************************************************************************)
let fsprintf f p =
F.fprintf F.str_formatter "@[%a@]" f p;
F.flush_str_formatter ()
let pred_to_string p =
fsprintf Predicate.pprint
let pred_to_string p =
fsprintf Predicate.pprint p
*)
(*************************************************************************)
let map_cnt f m =
let cnt a b n = n + 1 in
f cnt m 0
let set_cnt f s =
List.length (f s)
(******************************************************************************)
(********************************* Fting *********************************)
(******************************************************************************)
let space ppf =
F.fprintf ppf "@;<1 0>"
let rec same_length l1 l2 = match l1, l2 with
| [], [] -> true
| _ :: xs, _ :: ys -> same_length xs ys
| _ -> false
(******************************************************************************)
(********************************* Mem Management *****************************)
(******************************************************************************)
open Gc
(* open Format *)
let pprint_gc s =
printf " @[Gc@ " ;
printf " @[minor@ words:@ % f@]@. " s.minor_words ;
printf " @[promoted@ words:@ % f@]@. " s.promoted_words ;
printf " @[major@ words:@ % f@]@. " s.major_words ;
printf "@[minor@ words:@ %f@]@." s.minor_words;
printf "@[promoted@ words:@ %f@]@." s.promoted_words;
printf "@[major@ words:@ %f@]@." s.major_words;*)
printf " @[total allocated:@ % fMB@]@. " ( floor ( ( s.major_words + . s.minor_words - . s.promoted_words ) * . ( 4.0 ) /. ( 1024.0 * . 1024.0 ) ) ) ;
F.printf "@[total allocated:@ %fMB@]@." (floor ((allocated_bytes ()) /. (1024.0 *. 1024.0)));
F.printf "@[minor@ collections:@ %i@]@." s.minor_collections;
F.printf "@[major@ collections:@ %i@]@." s.major_collections;
F.printf "@[heap@ size:@ %iMB@]@." (s.heap_words * 4 / (1024 * 1024));
printf " @[heap@ chunks:@ % i@]@. " s.heap_chunks ;
( * printf " @[live@ words:@ % i@]@. " s.live_words ;
printf " @[live@ blocks:@ % i@]@. " s.live_blocks ;
printf " @[free@ words:@ % i@]@. " s.free_words ;
printf " @[free@ blocks:@ % i@]@. " s.free_blocks ;
printf " @[largest@ free:@ % i@]@. " s.largest_free ;
printf " @[fragments:@ % i@]@. " s.fragments ;
(*printf "@[live@ words:@ %i@]@." s.live_words;
printf "@[live@ blocks:@ %i@]@." s.live_blocks;
printf "@[free@ words:@ %i@]@." s.free_words;
printf "@[free@ blocks:@ %i@]@." s.free_blocks;
printf "@[largest@ free:@ %i@]@." s.largest_free;
printf "@[fragments:@ %i@]@." s.fragments;*)*)
F.printf "@[compactions:@ %i@]@." s.compactions;
(*printf "@[top@ heap@ words:@ %i@]@." s.top_heap_words*) ()
let dump_gc s =
F.printf "@[%s@]@." s;
pprint_gc (Gc.quick_stat ())
(* ************************************************************* *)
(* ************************ ml_types *************************** *)
(* ************************************************************* *)
let rec copy_type = function
| {desc = Tlink t} -> copy_type t (* Ensures copied types gets target's id/level, not link's *)
| t -> {t with desc = Btype.copy_type_desc copy_type t.desc}
(* ************************************************************* *)
(* ************************ core_types ************************* *)
(* ************************************************************* *)
open Parsetree
let map_core_type_constrs f t =
let rec map_rec t =
let wrap a = {ptyp_desc = a; ptyp_loc = t.ptyp_loc} in
match t.ptyp_desc with
| Ptyp_arrow (l, t, t') -> wrap (Ptyp_arrow (l, map_rec t, map_rec t'))
| Ptyp_tuple ts -> wrap (Ptyp_tuple (List.map map_rec ts))
| Ptyp_constr (l, ts) -> wrap (Ptyp_constr (f l, List.map map_rec ts))
| Ptyp_alias (t, s) -> wrap (Ptyp_alias (map_rec t, s))
| t -> wrap t in
map_rec t
let rec prover_t_to_s = function
| Pprover_abs s -> s
| Pprover_array (s, t) -> "[ " ^ (prover_t_to_s s) ^ "; " ^ (prover_t_to_s t) ^ " ]"
| Pprover_fun ss -> "( " ^ (String.concat " -> " (List.map prover_t_to_s ss)) ^ " )"
| null | https://raw.githubusercontent.com/ucsd-progsys/dsolve/bfbbb8ed9bbf352d74561e9f9127ab07b7882c0c/typing/common.ml | ocaml | ^ string_of_int (get_unique ()))
**************************************************************
************ Output levels ***********************************
**************************************************************
verbosity levels by purpose
must be > ol_dquals
**************************************************************
************ SCC Ranking *************************************
**************************************************************
Use of Graphviz
************************************************************************
***************** Type Specific to_string routines *********************
************************************************************************
***********************************************************************
****************************************************************************
******************************** Fting ********************************
****************************************************************************
****************************************************************************
******************************** Mem Management ****************************
****************************************************************************
open Format
printf "@[live@ words:@ %i@]@." s.live_words;
printf "@[live@ blocks:@ %i@]@." s.live_blocks;
printf "@[free@ words:@ %i@]@." s.free_words;
printf "@[free@ blocks:@ %i@]@." s.free_blocks;
printf "@[largest@ free:@ %i@]@." s.largest_free;
printf "@[fragments:@ %i@]@." s.fragments;
printf "@[top@ heap@ words:@ %i@]@." s.top_heap_words
*************************************************************
************************ ml_types ***************************
*************************************************************
Ensures copied types gets target's id/level, not link's
*************************************************************
************************ core_types *************************
************************************************************* |
* Copyright © 2008 The Regents of the University of California . All rights reserved .
*
* Permission is hereby granted , without written agreement and without
* license or royalty fees , to use , copy , modify , and distribute this
* software and its documentation for any purpose , provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software .
*
* IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
* FOR DIRECT , INDIRECT , SPECIAL , INCIDENTAL , OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION , EVEN
* IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE .
*
* THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES ,
* INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE . THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN " AS IS " BASIS , AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION
* TO PROVIDE MAINTENANCE , SUPPORT , UPDATES , ENHANCEMENTS , OR MODIFICATIONS .
*
* Copyright © 2008 The Regents of the University of California. All rights reserved.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software.
*
* IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
* FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION
* TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
*)
open Types
module F = Format
module BS = Bstats
module StringMap = Map.Make(String)
module ComparablePath = struct
type t = Path.t
let compare = compare
let equal = Path.same
let hash = Hashtbl.hash
end
module PathMap = Map.Make(ComparablePath)
let qual_test_var = Path.Pident (Ident.create_persistent "AA")
let dummy_id = Ident.create_persistent ""
let incpp ir =
incr ir;!ir
let array_to_index_list a =
List.rev (snd
(Array.fold_left (fun (i,rv) v -> (i+1,(i,v)::rv)) (0,[]) a))
let rec pprint_many brk s f ppf = function
| [] -> ()
| x::[] -> F.fprintf ppf "%a" f x
| x::xs' -> ((if brk then F.fprintf ppf "%a %s@ " f x s else F.fprintf ppf "%a %s" f x s);
pprint_many brk s f ppf xs')
let pprint_list sepstr pp =
(fun ppf -> Oprint.print_list pp
(fun ppf -> F.fprintf ppf "%s@;<1 2>" sepstr) ppf)
let pprint_str ppf s =
F.fprintf ppf "%s" s
let rec is_unique xs =
match xs with
x :: xs -> if List.mem x xs then false else is_unique xs
| [] -> true
let resl_opt f = function
| Some o -> f o
| None -> []
let resi_opt f = function
| Some o -> f o
| None -> ()
let opt_iter f l =
List.iter (resi_opt f) l
let add il i = il := i::!il
let addl il i = il := List.rev_append i !il
let same_type q p = (Types.TypeOps.equal q p)
let dummy () = Path.mk_ident ""
let same_name_id id =
Ident.create (Ident.name id)
let same_path_i p i = Path.unique_name p = Ident.unique_name i
let i2p i = Path.Pident i
let p2i p = match p with
Path.Pident id -> id
| _ -> assert false
let lookup_path s env =
fst (Env.lookup_value (Longident.parse s) env)
let lookup_type p env =
(Env.find_value p env).Types.val_type
let tmpstring s = if String.length s >= 2 then (s.[0] = '_' && s.[1] = '\'') || (s.[0] = 'A' && s.[1] = 'A') else false
let path_is_temp p = match Path.ident_name p with Some s -> tmpstring s | None -> false
let tuple_elem_id i =
Ident.create ("e" ^ string_of_int i)
let abstr_elem_id () =
let rec maybe_list_from_singles = function
x :: xs -> (match x with [a] -> Some a | _ -> None) :: (maybe_list_from_singles xs)
| [] -> []
let maybe_bool = function
Some _ -> true
| None -> false
let all_defined xs =
List.for_all maybe_bool xs
let has_prefix pre s =
try String.sub s 0 ( String.length pre ) = pre
with Invalid_argument _ - > false
let has_prefix pre s =
try String.sub s 0 (String.length pre) = pre
with Invalid_argument _ -> false
*)
let sub_from_list subs s =
try List.assoc s subs with Not_found -> s
let strip_meas s =
let start = try 1 + (String.rindex s '.') with Not_found -> 0 in
try
if String.sub s start 6 = "_meas_" then
let pre = String.sub s 0 start in
let post = String.sub s (start + 6) ((String.length s) - start - 6) in
pre ^ post
else s
with Invalid_argument _ -> s
let sub_from s c =
try
let x = String.rindex s c in
String.sub s x ( ( String.length s ) - x )
with Not_found - > s
let sub_to_r s c =
let x = String.rindex s c in
String.sub s 0 x
let strip_meas_whole s =
if ! then s else
try
let start = try String.rindex s ' . '
if String.sub s 0 6 = " _ meas _ " then
String.sub s 6 ( String.length s - 6 )
else s with Invalid_argument _ - > s
let rw_suff f s c =
let suff = f ( sub_from s c ) in
try ( sub_to_r s c ) ^ suff with Not_found - > suff
let strip_meas s =
rw_suff strip_meas_whole s ' . '
let sub_from s c =
try
let x = String.rindex s c in
String.sub s x ((String.length s) - x)
with Not_found -> s
let sub_to_r s c =
let x = String.rindex s c in
String.sub s 0 x
let strip_meas_whole s =
if !Clflags.dsmeasures then s else
try
let start = try String.rindex s '.'
if String.sub s 0 6 = "_meas_" then
String.sub s 6 (String.length s - 6)
else s with Invalid_argument _ -> s
let rw_suff f s c =
let suff = f (sub_from s c) in
try (sub_to_r s c) ^ suff with Not_found -> suff
let strip_meas s =
rw_suff strip_meas_whole s '.'
*)
let append_pref p s =
(p ^ "." ^ s)
let app_fst f ( a , b ) = ( f a , b )
let app_snd f ( a , b ) = ( a , f b )
let app_pr f ( a , b ) = ( f a , f b )
let app_triple f ( a , b , c ) = ( f a , f b , f c )
let app_snd f (a, b) = (a, f b)
let app_pr f (a, b) = (f a, f b)
let app_triple f (a, b, c) = (f a, f b, f c)
*)
let l_to_s l = String.concat "." (Longident.flatten l)
let s_to_l s = Longident.parse s
let l_is_id id = function
| Longident.Lident s -> s = id
| _ -> false
let s_to_p s = Path.Pident (Ident.create s)
let int_of_tag = function
Cstr_constant n -> 2*n
| Cstr_block n -> 2*n+1
| Cstr_exception _-> assert false
let tag_of_int n =
if 2*(n/2) = n then
Cstr_constant (n/2)
else
Cstr_block ((n-1)/2)
let sort_and_compact xs =
let rec f = function
| x1::(x2::_ as xs') ->
if x1 = x2 then (f xs') else x1::(f xs')
| xs' -> xs' in
f (List.sort compare xs)
let ol_always = 0
let ol_solve_error = 1
let ol_warning = 1
let ol_solve_master = 2
let ol_solve_stats = 2
let ol_timing = 2
let ol_default = 2
let ol_warn_mlqs = 3
let ol_normalized = 3
let ol_dquals = 4
let ol_solve = 10
let ol_refine = 11
let ol_scc = 12
let ol_dump_env = 10
let ol_axioms = 5
let ol_dump_prover = 20
let ol_verb_constrs = 21
let ol_dump_wfs = 22
let ol_dump_meas = 30
let ol_dump_quals = 50
let ol_insane = 200
let verbose_level = ref ol_default
let verb_stack = ref []
let null_formatter = F.make_formatter (fun a b c -> ()) ignore
let nprintf a = F.fprintf null_formatter a
let ck_olev l = l <= !verbose_level
let cprintf l = if ck_olev l then F.printf else nprintf
let ecprintf l = if ck_olev l then F.eprintf else nprintf
let fcprintf ppf l = if ck_olev l then F.fprintf ppf else nprintf
let icprintf printer l ppf = if ck_olev l then printer ppf else printer null_formatter
let cprintln l s = if ck_olev l then Printf.ksprintf (F.printf "@[%s@\n@]") s else nprintf
let ident_name i = if ck_olev ol_unique_names then Ident.unique_name i else Ident.name i
let path_name p = if ck_olev ol_unique_names then Path.unique_name p else Path.name p
let elevate_olev l = if ck_olev l then () else verb_stack := !verbose_level :: !verb_stack; verbose_level := l
let restore_olev = match !verb_stack with x :: xs -> verbose_level := x; verb_stack := xs | _ -> ()
module Int : Graph.Sig.COMPARABLE with type t = int * string =
struct
type t = int * string
let compare = compare
let hash = Hashtbl.hash
let equal = (=)
end
module G = Graph.Imperative.Digraph.Concrete(Int)
module SCC = Graph.Components.Make(G)
let io_to_string = function
| Some i -> string_of_int i
| None -> "*"
let xs_to_string f xs =
"["^(String.concat "," (List.map f xs))^"]"
module DotGraph =
struct
type t = G.t
module V = G.V
module E = G.E
let iter_vertex = G.iter_vertex
let iter_edges_e = G.iter_edges_e
let graph_attributes g = []
let default_vertex_attributes g = [`Shape `Box]
let vertex_name (i,s) = Printf.sprintf "V_%d_%s" i s
let vertex_attributes v = [`Label (vertex_name v)]
let default_edge_attributes g = []
let edge_attributes e = []
let get_subgraph v = None
end
module Dot = Graph.Graphviz.Dot(DotGraph)
let dump_graph g =
let oc = open_out "constraints.dot" in
Dot.output_graph oc g;
close_out oc
Given list [ ( u , v ) ] returns a numbering [ ( ui , ri ) ] s.t .
* 1 . if ui , uj in same SCC then ri = rj
* 2 . if ui - > uj then ui > = uj
* 1. if ui,uj in same SCC then ri = rj
* 2. if ui -> uj then ui >= uj *)
let scc_rank f ijs =
let g = G.create () in
let _ = Bstats.time "making graph" (List.iter (fun (i,j) -> G.add_edge g (i,(f i)) (j,(f j)))) ijs in
let _ = if !Clflags.dump_graph then dump_graph g in
let a = SCC.scc_array g in
let _ = cprintf ol_scc "@[dep@ graph:@ vertices@ =@ @ %d,@ sccs@ =@ %d@ @\n@]"
(G.nb_vertex g) (Array.length a);
cprintf ol_scc "@[scc@ sizes:@\n@]";
let int_s_to_string (i,s) = Printf.sprintf "(%d,%s)" i s in
Array.iteri
(fun i xs ->
cprintf ol_scc "@[%d@ :@ %s@ @\n@]"
i (xs_to_string int_s_to_string xs)) a;
cprintf ol_scc "@[@\n@]" in
let sccs = array_to_index_list a in
Misc.flap (fun (i,vs) -> List.map (fun (j,_) -> (j,i)) vs) sccs
let g1 = [ ( ) ] ; ;
let = [ ( 0,1);(1,2);(2,0);(1,3);(4,3 ) ;
( 5,6);(5,7);(6,9);(7,9);(7,8);(8,5 ) ] ; ;
let g3 = ( 6,2)::g2 ; ;
let g4 = ( 2,6)::g2 ; ;
let n1 = ; ;
let n2 = ; ;
let n3 = ; ;
let n4 = ; ;
let g1 = [(1,2);(2,3);(3,1);(2,4);(3,4);(4,5)];;
let g2 = [(0,1);(1,2);(2,0);(1,3);(4,3);
(5,6);(5,7);(6,9);(7,9);(7,8);(8,5)];;
let g3 = (6,2)::g2;;
let g4 = (2,6)::g2;;
let n1 = make_scc_num g1 ;;
let n2 = make_scc_num g2 ;;
let n3 = make_scc_num g3 ;;
let n4 = make_scc_num g4 ;; *)
let asserts s b =
try assert b with ex ->
Printf.printf "Common.asserts failure: %s " s; raise ex
let append_to_file f s =
let oc = Unix.openfile f [Unix.O_WRONLY; Unix.O_APPEND; Unix.O_CREAT] 420 in
ignore (Unix.write oc s 0 ((String.length s)-1) );
Unix.close oc
let write_to_file f s =
let oc = open_out f in
output_string oc s;
close_out oc
let fsprintf f p =
F.fprintf F.str_formatter "@[%a@]" f p;
F.flush_str_formatter ()
let pred_to_string p =
fsprintf Predicate.pprint
let pred_to_string p =
fsprintf Predicate.pprint p
*)
let map_cnt f m =
let cnt a b n = n + 1 in
f cnt m 0
let set_cnt f s =
List.length (f s)
let space ppf =
F.fprintf ppf "@;<1 0>"
let rec same_length l1 l2 = match l1, l2 with
| [], [] -> true
| _ :: xs, _ :: ys -> same_length xs ys
| _ -> false
open Gc
let pprint_gc s =
printf " @[Gc@ " ;
printf " @[minor@ words:@ % f@]@. " s.minor_words ;
printf " @[promoted@ words:@ % f@]@. " s.promoted_words ;
printf " @[major@ words:@ % f@]@. " s.major_words ;
printf "@[minor@ words:@ %f@]@." s.minor_words;
printf "@[promoted@ words:@ %f@]@." s.promoted_words;
printf "@[major@ words:@ %f@]@." s.major_words;*)
printf " @[total allocated:@ % fMB@]@. " ( floor ( ( s.major_words + . s.minor_words - . s.promoted_words ) * . ( 4.0 ) /. ( 1024.0 * . 1024.0 ) ) ) ;
F.printf "@[total allocated:@ %fMB@]@." (floor ((allocated_bytes ()) /. (1024.0 *. 1024.0)));
F.printf "@[minor@ collections:@ %i@]@." s.minor_collections;
F.printf "@[major@ collections:@ %i@]@." s.major_collections;
F.printf "@[heap@ size:@ %iMB@]@." (s.heap_words * 4 / (1024 * 1024));
printf " @[heap@ chunks:@ % i@]@. " s.heap_chunks ;
( * printf " @[live@ words:@ % i@]@. " s.live_words ;
printf " @[live@ blocks:@ % i@]@. " s.live_blocks ;
printf " @[free@ words:@ % i@]@. " s.free_words ;
printf " @[free@ blocks:@ % i@]@. " s.free_blocks ;
printf " @[largest@ free:@ % i@]@. " s.largest_free ;
printf " @[fragments:@ % i@]@. " s.fragments ;
F.printf "@[compactions:@ %i@]@." s.compactions;
let dump_gc s =
F.printf "@[%s@]@." s;
pprint_gc (Gc.quick_stat ())
let rec copy_type = function
| t -> {t with desc = Btype.copy_type_desc copy_type t.desc}
open Parsetree
let map_core_type_constrs f t =
let rec map_rec t =
let wrap a = {ptyp_desc = a; ptyp_loc = t.ptyp_loc} in
match t.ptyp_desc with
| Ptyp_arrow (l, t, t') -> wrap (Ptyp_arrow (l, map_rec t, map_rec t'))
| Ptyp_tuple ts -> wrap (Ptyp_tuple (List.map map_rec ts))
| Ptyp_constr (l, ts) -> wrap (Ptyp_constr (f l, List.map map_rec ts))
| Ptyp_alias (t, s) -> wrap (Ptyp_alias (map_rec t, s))
| t -> wrap t in
map_rec t
let rec prover_t_to_s = function
| Pprover_abs s -> s
| Pprover_array (s, t) -> "[ " ^ (prover_t_to_s s) ^ "; " ^ (prover_t_to_s t) ^ " ]"
| Pprover_fun ss -> "( " ^ (String.concat " -> " (List.map prover_t_to_s ss)) ^ " )"
|
f571e55cc7903930dbc50f94cb21c46f28f2d576fc759acb1823f33c2a71dc19 | eguven/erlsna | gatekeeper.erl | -module(gatekeeper).
-behaviour(gen_server).
-export([start_gatekeeper/0, add_agent/2, remove_agent/1, clean/0, agent_exists/1,
find_agent/1, find_multi/1, all_agents/0, all_agents/1, all_relations/0]).
-export([start_link/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
%%%---------------------------------------------------------------------
%%% Description module gatekeeper
%%%---------------------------------------------------------------------
%%% Gatekeeper is a gen_server process responsible of doing record
keeping , matching real - world IDs of agents to PIDs in Erlang runtime
%%%---------------------------------------------------------------------
%% to start gatekeeper outside supervision tree in development
gatekeeper : start_link/0 calls this
start_gatekeeper() ->
gen_server:start_link(?MODULE, [], []).
%%%---------------------------------------------------------------------
%%% Asynchronous calls to gatekeeper
%%%---------------------------------------------------------------------
%% Add an agent to records
: I d of agent process ( real - world identifier )
%% PID of agent process
add_agent(Id, Pid) ->
gen_server:cast(whereis(gatekeeper), {add, Id, Pid}).
%% Remove an agent from records
: I d of agent process
remove_agent(Id) ->
gen_server:cast(whereis(gatekeeper), {remove, Id}).
%% Remove all records in gatekeeper
clean() ->
gen_server:cast(whereis(gatekeeper), clean).
%%%---------------------------------------------------------------------
%%% Synchronous calls to gatekeeper
%%%---------------------------------------------------------------------
%% Check if agent with given Id exists
: ID of agent process
%% Returns: true | false
agent_exists(Id) ->
gen_server:call(whereis(gatekeeper), {exists, Id}).
%% Find the PID of agent process denoted by given ID
: ID of agent process
%% Returns: {ok, PID} | {error, not_found}
find_agent(Id) ->
gen_server:call(whereis(gatekeeper), {find, Id}).
%% Find multiple agents from an ID list or PID list
: list of IDs or PIDs
Returns : { from_ids , [ { Idx , Pidx } | ... ] }
{ from_pids , [ { Pidx , Idx } | ... ] }
where the second element of the tagged tuple is an orddict
find_multi([HList|TList]) ->
case is_pid(HList) of
true -> gen_server:call(whereis(gatekeeper), {find_multi_from_pids, [HList|TList]});
false -> gen_server:call(whereis(gatekeeper), {find_multi_from_ids, [HList|TList]})
end.
%% Retrieve a dict of all agents which is the state of gatekeeper
all_agents() ->
gen_server:call(whereis(gatekeeper), all).
%% Retrieve a list of IDs of all agents
: i d ( atom )
%% Returns: [Idx | ...]
all_agents(id) ->
lists:map(fun({Id,_Pid}) -> Id end, dict:to_list(all_agents()));
%% Retrieve a list of PIDs of all agents
: pid ( atom )
%% Returns: [Pidx | ...]
all_agents(pid) ->
lists:map(fun({_Id,Pid}) -> Pid end, dict:to_list(all_agents())).
%% This function is shit.
%% Returns a list-of-list-of-tuples where each inner list contains
%% tuples in the form of {SourcePID, DestPID, Value} for all relations that
%% source agent has.
There is one list per agent . Empty lists ( no relations ) are not filtered out
all_relations() ->
AgentPids = all_agents(pid), % get a list of PIDs
% {PID, #agent.outdegrees}
F = fun(P,{{indegrees, _I}, {outdegrees, O}}) -> {P,O} end,
% [ {PID, #agent.outdegrees} | ...]
RL = [F(P,agent:get_relations(P)) || P <- AgentPids],
% S: SourcePID, DList: DestinationList
BigL = lists:map(fun({S, DList}) ->
: DestionationPID , V : RelationValue
lists:map(fun({DPid, V}) -> {S, DPid, V} end, DList) end, RL),
{relations, BigL}.
%%%---------------------------------------------------------------------
%%% Gatekeeper Process
%%%---------------------------------------------------------------------
init([]) ->
% register self PID
register(gatekeeper, self()),
{ok, dict:new()}.
start_link() ->
start_gatekeeper().
% extra callbacks
handle_info(Msg, Agent) ->
io:format("Unexpected message: ~p~n",[Msg]),
{noreply, Agent}.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%% terminate function. Just print debug.
terminate(Reason, State) ->
io:format("Gatekeeper terminated~nReason: ~p~nState:~p~n",[Reason,State]),
ok.
%%%---------------------------------------------------------------------
%%% Handling Asynchoronous Calls
%%%---------------------------------------------------------------------
called from gatekeeper : add_agent/2
handle_cast({add, Id, Pid}, Agents) ->
{noreply, dict:store(Id, Pid, Agents)};
called from gatekeeper :
handle_cast({remove, Id}, Agents) ->
{noreply, dict:erase(Id, Agents)};
%% called from gatekeeper:clean/0
handle_cast(clean, _) ->
{noreply, dict:new()}.
%%%---------------------------------------------------------------------
%%% Handling Synchoronous Calls
%%%---------------------------------------------------------------------
%% called from gatekeeper:agent_exists/1
handle_call({exists, Id}, _From, Agents) ->
{reply, dict:is_key(Id, Agents), Agents};
%% called from gatekeeper:find_agent/1
handle_call({find, Id}, _From, Agents) ->
case dict:find(Id, Agents) of
{ok, Pid} -> {reply, {ok, Pid}, Agents};
error -> {reply, {error, not_found}, Agents}
end;
called from gatekeeper : find_multi/1 . find multiple agents from PidList
handle_call({find_multi_from_pids, PidList}, _From, Agents) ->
AList = dict:to_list(Agents), % list of {Id, PID}
lookup by values , reverse the orddict K / V eg . { Id , Pid } transformed into { Pid , Id }
F = fun() -> lists:foldl(fun(I,Acc) -> {P,_I} = element(2,lists:keysearch(I,2,AList)),
orddict:store(I,P,Acc) end, orddict:new(), PidList) end,
try F() of
RetVal -> {reply, {from_pids, RetVal}, Agents}
catch
Type:Exception -> {reply, {error, [Type, Exception]}, Agents}
end;
called from gatekeeper : find_multi/1 . find multiple agents from IdList
handle_call({find_multi_from_ids, IdList}, _From, Agents) ->
function to foldl over IdList and build orddict of { Id , Pid }
F = fun() -> lists:foldl(fun(P,Acc) -> orddict:store(P,dict:fetch(P,Agents),Acc) end,
orddict:new(), IdList) end,
try F() of
RetVal -> {reply, {from_ids, RetVal}, Agents}
catch
Type:Exception -> {reply, {error, [Type, Exception]}, Agents}
end;
%% called from gatekeeper:all_agents/0
handle_call(all, _From, Agents) ->
{reply, Agents, Agents}.
| null | https://raw.githubusercontent.com/eguven/erlsna/ec82682db69f29cb0eeef65471773519f0176340/src/gatekeeper.erl | erlang | ---------------------------------------------------------------------
Description module gatekeeper
---------------------------------------------------------------------
Gatekeeper is a gen_server process responsible of doing record
---------------------------------------------------------------------
to start gatekeeper outside supervision tree in development
---------------------------------------------------------------------
Asynchronous calls to gatekeeper
---------------------------------------------------------------------
Add an agent to records
PID of agent process
Remove an agent from records
Remove all records in gatekeeper
---------------------------------------------------------------------
Synchronous calls to gatekeeper
---------------------------------------------------------------------
Check if agent with given Id exists
Returns: true | false
Find the PID of agent process denoted by given ID
Returns: {ok, PID} | {error, not_found}
Find multiple agents from an ID list or PID list
Retrieve a dict of all agents which is the state of gatekeeper
Retrieve a list of IDs of all agents
Returns: [Idx | ...]
Retrieve a list of PIDs of all agents
Returns: [Pidx | ...]
This function is shit.
Returns a list-of-list-of-tuples where each inner list contains
tuples in the form of {SourcePID, DestPID, Value} for all relations that
source agent has.
get a list of PIDs
{PID, #agent.outdegrees}
[ {PID, #agent.outdegrees} | ...]
S: SourcePID, DList: DestinationList
---------------------------------------------------------------------
Gatekeeper Process
---------------------------------------------------------------------
register self PID
extra callbacks
terminate function. Just print debug.
---------------------------------------------------------------------
Handling Asynchoronous Calls
---------------------------------------------------------------------
called from gatekeeper:clean/0
---------------------------------------------------------------------
Handling Synchoronous Calls
---------------------------------------------------------------------
called from gatekeeper:agent_exists/1
called from gatekeeper:find_agent/1
list of {Id, PID}
called from gatekeeper:all_agents/0 | -module(gatekeeper).
-behaviour(gen_server).
-export([start_gatekeeper/0, add_agent/2, remove_agent/1, clean/0, agent_exists/1,
find_agent/1, find_multi/1, all_agents/0, all_agents/1, all_relations/0]).
-export([start_link/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
keeping , matching real - world IDs of agents to PIDs in Erlang runtime
gatekeeper : start_link/0 calls this
start_gatekeeper() ->
gen_server:start_link(?MODULE, [], []).
: I d of agent process ( real - world identifier )
add_agent(Id, Pid) ->
gen_server:cast(whereis(gatekeeper), {add, Id, Pid}).
: I d of agent process
remove_agent(Id) ->
gen_server:cast(whereis(gatekeeper), {remove, Id}).
clean() ->
gen_server:cast(whereis(gatekeeper), clean).
: ID of agent process
agent_exists(Id) ->
gen_server:call(whereis(gatekeeper), {exists, Id}).
: ID of agent process
find_agent(Id) ->
gen_server:call(whereis(gatekeeper), {find, Id}).
: list of IDs or PIDs
Returns : { from_ids , [ { Idx , Pidx } | ... ] }
{ from_pids , [ { Pidx , Idx } | ... ] }
where the second element of the tagged tuple is an orddict
find_multi([HList|TList]) ->
case is_pid(HList) of
true -> gen_server:call(whereis(gatekeeper), {find_multi_from_pids, [HList|TList]});
false -> gen_server:call(whereis(gatekeeper), {find_multi_from_ids, [HList|TList]})
end.
all_agents() ->
gen_server:call(whereis(gatekeeper), all).
: i d ( atom )
all_agents(id) ->
lists:map(fun({Id,_Pid}) -> Id end, dict:to_list(all_agents()));
: pid ( atom )
all_agents(pid) ->
lists:map(fun({_Id,Pid}) -> Pid end, dict:to_list(all_agents())).
There is one list per agent . Empty lists ( no relations ) are not filtered out
all_relations() ->
F = fun(P,{{indegrees, _I}, {outdegrees, O}}) -> {P,O} end,
RL = [F(P,agent:get_relations(P)) || P <- AgentPids],
BigL = lists:map(fun({S, DList}) ->
: DestionationPID , V : RelationValue
lists:map(fun({DPid, V}) -> {S, DPid, V} end, DList) end, RL),
{relations, BigL}.
init([]) ->
register(gatekeeper, self()),
{ok, dict:new()}.
start_link() ->
start_gatekeeper().
handle_info(Msg, Agent) ->
io:format("Unexpected message: ~p~n",[Msg]),
{noreply, Agent}.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
terminate(Reason, State) ->
io:format("Gatekeeper terminated~nReason: ~p~nState:~p~n",[Reason,State]),
ok.
called from gatekeeper : add_agent/2
handle_cast({add, Id, Pid}, Agents) ->
{noreply, dict:store(Id, Pid, Agents)};
called from gatekeeper :
handle_cast({remove, Id}, Agents) ->
{noreply, dict:erase(Id, Agents)};
handle_cast(clean, _) ->
{noreply, dict:new()}.
handle_call({exists, Id}, _From, Agents) ->
{reply, dict:is_key(Id, Agents), Agents};
handle_call({find, Id}, _From, Agents) ->
case dict:find(Id, Agents) of
{ok, Pid} -> {reply, {ok, Pid}, Agents};
error -> {reply, {error, not_found}, Agents}
end;
called from gatekeeper : find_multi/1 . find multiple agents from PidList
handle_call({find_multi_from_pids, PidList}, _From, Agents) ->
lookup by values , reverse the orddict K / V eg . { Id , Pid } transformed into { Pid , Id }
F = fun() -> lists:foldl(fun(I,Acc) -> {P,_I} = element(2,lists:keysearch(I,2,AList)),
orddict:store(I,P,Acc) end, orddict:new(), PidList) end,
try F() of
RetVal -> {reply, {from_pids, RetVal}, Agents}
catch
Type:Exception -> {reply, {error, [Type, Exception]}, Agents}
end;
called from gatekeeper : find_multi/1 . find multiple agents from IdList
handle_call({find_multi_from_ids, IdList}, _From, Agents) ->
function to foldl over IdList and build orddict of { Id , Pid }
F = fun() -> lists:foldl(fun(P,Acc) -> orddict:store(P,dict:fetch(P,Agents),Acc) end,
orddict:new(), IdList) end,
try F() of
RetVal -> {reply, {from_ids, RetVal}, Agents}
catch
Type:Exception -> {reply, {error, [Type, Exception]}, Agents}
end;
handle_call(all, _From, Agents) ->
{reply, Agents, Agents}.
|
7a4eb749aaa78f10aed4aa3809a490cdf0cc050273c3fff448a3b1f6a1474776 | pa-ba/compdata | HOAS.hs | # LANGUAGE
TemplateHaskell ,
MultiParamTypeClasses ,
FlexibleInstances ,
FlexibleContexts ,
UndecidableInstances ,
TypeOperators ,
ScopedTypeVariables ,
TypeSynonymInstances #
TemplateHaskell,
MultiParamTypeClasses,
FlexibleInstances,
FlexibleContexts,
UndecidableInstances,
TypeOperators,
ScopedTypeVariables,
TypeSynonymInstances #-}
module Functions.Comp.Desugar where
import DataTypes.Comp
import Data.Comp.ExpFunctor
import Data.Comp
import Data.Foldable
import Prelude hiding (foldr)
ex1 :: HOASExpr
ex1 = iLam (\x -> case project x of
Just (VInt _) -> x
_ -> x `iPlus` x)
ex2 :: HOASExpr
ex2 = iLam (\x -> case x of
Term t -> case proj t of
Just (VInt _) -> x
_ -> x `iPlus` x)
class Vars f where
varsAlg :: Alg f Int
instance (Vars f, Vars g) => Vars (g :+: f) where
varsAlg (Inl v) = varsAlg v
varsAlg (Inr v) = varsAlg v
instance Vars Lam where
varsAlg (Lam f) = f 1
instance Vars App where
varsAlg = foldr (+) 0
instance Vars Value where
varsAlg = foldr (+) 0
instance Vars Op where
varsAlg = foldr (+) 0
instance Vars Sugar where
varsAlg = foldr (+) 0
vars :: (ExpFunctor f, Vars f) => Term f -> Int
vars = cataE varsAlg
| null | https://raw.githubusercontent.com/pa-ba/compdata/5783d0e11129097e045cabba61643114b154e3f2/benchmark/Functions/Comp/HOAS.hs | haskell | # LANGUAGE
TemplateHaskell ,
MultiParamTypeClasses ,
FlexibleInstances ,
FlexibleContexts ,
UndecidableInstances ,
TypeOperators ,
ScopedTypeVariables ,
TypeSynonymInstances #
TemplateHaskell,
MultiParamTypeClasses,
FlexibleInstances,
FlexibleContexts,
UndecidableInstances,
TypeOperators,
ScopedTypeVariables,
TypeSynonymInstances #-}
module Functions.Comp.Desugar where
import DataTypes.Comp
import Data.Comp.ExpFunctor
import Data.Comp
import Data.Foldable
import Prelude hiding (foldr)
ex1 :: HOASExpr
ex1 = iLam (\x -> case project x of
Just (VInt _) -> x
_ -> x `iPlus` x)
ex2 :: HOASExpr
ex2 = iLam (\x -> case x of
Term t -> case proj t of
Just (VInt _) -> x
_ -> x `iPlus` x)
class Vars f where
varsAlg :: Alg f Int
instance (Vars f, Vars g) => Vars (g :+: f) where
varsAlg (Inl v) = varsAlg v
varsAlg (Inr v) = varsAlg v
instance Vars Lam where
varsAlg (Lam f) = f 1
instance Vars App where
varsAlg = foldr (+) 0
instance Vars Value where
varsAlg = foldr (+) 0
instance Vars Op where
varsAlg = foldr (+) 0
instance Vars Sugar where
varsAlg = foldr (+) 0
vars :: (ExpFunctor f, Vars f) => Term f -> Int
vars = cataE varsAlg
| |
409cd2c082767c311f36cc0298a27b06495b573d15d0643879b9fb41312ad6ef | chef/mixer | import_test.erl | -module(import_test).
-include_lib("eunit/include/eunit.hrl").
-define(EXPORTS(Mod), Mod:module_info(exports)).
single_test_() ->
[{<<"All functions on 'single' stubbed properly">>,
[?_assert(lists:member({doit, 0}, ?EXPORTS(single))),
?_assert(lists:member({doit, 1}, ?EXPORTS(single))),
?_assert(lists:member({doit, 2}, ?EXPORTS(single)))]},
{<<"All functions on 'single' work correctly">>,
[?_assertMatch(doit, single:doit()),
?_assertMatch([doit, 1], single:doit(1)),
?_assertMatch([doit, 1, 2], single:doit(1, 2))]}].
multiple_test_() ->
[{<<"All functions stubbed">>,
[?_assert(lists:member({doit, 0}, ?EXPORTS(multiple))),
?_assert(lists:member({doit, 1}, ?EXPORTS(multiple))),
?_assert(lists:member({doit, 2}, ?EXPORTS(multiple))),
?_assert(lists:member({canhas, 0}, ?EXPORTS(multiple))),
?_assert(lists:member({canhas, 1}, ?EXPORTS(multiple)))]},
{<<"All stubbed functions work">>,
[?_assertMatch(doit, multiple:doit()),
?_assertMatch({doit, one}, multiple:doit(one)),
?_assertMatch([doit, one, two], multiple:doit(one, two)),
?_assert(multiple:canhas()),
?_assertMatch(cheezburger, multiple:canhas(cheezburger))]}].
alias_test_() ->
[{<<"Function stubbed with alias">>,
[?_assert(lists:member({blah, 0}, ?EXPORTS(alias))),
?_assert(lists:member({can_has, 0}, ?EXPORTS(alias)))]},
{<<"All stubbed functions work">>,
[?_assertMatch(doit, alias:blah()),
?_assertMatch(true, alias:can_has())]}].
| null | https://raw.githubusercontent.com/chef/mixer/0d1322433e7e2237eb1270dc5a028fa014335134/test/import_test.erl | erlang | -module(import_test).
-include_lib("eunit/include/eunit.hrl").
-define(EXPORTS(Mod), Mod:module_info(exports)).
single_test_() ->
[{<<"All functions on 'single' stubbed properly">>,
[?_assert(lists:member({doit, 0}, ?EXPORTS(single))),
?_assert(lists:member({doit, 1}, ?EXPORTS(single))),
?_assert(lists:member({doit, 2}, ?EXPORTS(single)))]},
{<<"All functions on 'single' work correctly">>,
[?_assertMatch(doit, single:doit()),
?_assertMatch([doit, 1], single:doit(1)),
?_assertMatch([doit, 1, 2], single:doit(1, 2))]}].
multiple_test_() ->
[{<<"All functions stubbed">>,
[?_assert(lists:member({doit, 0}, ?EXPORTS(multiple))),
?_assert(lists:member({doit, 1}, ?EXPORTS(multiple))),
?_assert(lists:member({doit, 2}, ?EXPORTS(multiple))),
?_assert(lists:member({canhas, 0}, ?EXPORTS(multiple))),
?_assert(lists:member({canhas, 1}, ?EXPORTS(multiple)))]},
{<<"All stubbed functions work">>,
[?_assertMatch(doit, multiple:doit()),
?_assertMatch({doit, one}, multiple:doit(one)),
?_assertMatch([doit, one, two], multiple:doit(one, two)),
?_assert(multiple:canhas()),
?_assertMatch(cheezburger, multiple:canhas(cheezburger))]}].
alias_test_() ->
[{<<"Function stubbed with alias">>,
[?_assert(lists:member({blah, 0}, ?EXPORTS(alias))),
?_assert(lists:member({can_has, 0}, ?EXPORTS(alias)))]},
{<<"All stubbed functions work">>,
[?_assertMatch(doit, alias:blah()),
?_assertMatch(true, alias:can_has())]}].
| |
9f045d52030a5749bc4a5e3d4cf6ba111f2d8ebf8bb1fe9dd7fbd9e8977cd54e | tweag/ormolu | Module.hs | # LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
-- | Rendering of modules.
module Ormolu.Printer.Meat.Module
( p_hsModule,
)
where
import Control.Monad
import GHC.Hs hiding (comment)
import GHC.Types.SrcLoc
import Ormolu.Parser.CommentStream
import Ormolu.Parser.Pragma
import Ormolu.Printer.Combinators
import Ormolu.Printer.Comments
import Ormolu.Printer.Meat.Common
import Ormolu.Printer.Meat.Declaration
import Ormolu.Printer.Meat.Declaration.Warning
import Ormolu.Printer.Meat.ImportExport
import Ormolu.Printer.Meat.Pragma
-- | Render a module-like entity (either a regular module or a backpack
-- signature).
p_hsModule ::
-- | Stack header
Maybe (RealLocated Comment) ->
-- | Pragmas and the associated comments
[([RealLocated Comment], Pragma)] ->
-- | AST to print
HsModule ->
R ()
p_hsModule mstackHeader pragmas HsModule {..} = do
let deprecSpan = maybe [] (pure . getLocA) hsmodDeprecMessage
exportSpans = maybe [] (pure . getLocA) hsmodExports
switchLayout (deprecSpan <> exportSpans) $ do
forM_ mstackHeader $ \(L spn comment) -> do
spitCommentNow spn comment
newline
newline
p_pragmas pragmas
newline
case hsmodName of
Nothing -> return ()
Just hsmodName' -> do
located hsmodName' $ \name -> do
forM_ hsmodHaddockModHeader (p_hsDoc Pipe True)
p_hsmodName name
breakpoint
forM_ hsmodDeprecMessage $ \w -> do
located' p_moduleWarning w
breakpoint
case hsmodExports of
Nothing -> return ()
Just l -> do
located l $ \exports -> do
inci (p_hsmodExports exports)
breakpoint
txt "where"
newline
newline
forM_ hsmodImports (located' p_hsmodImport)
newline
switchLayout (getLocA <$> hsmodDecls) $ do
p_hsDecls Free hsmodDecls
newline
spitRemainingComments
| null | https://raw.githubusercontent.com/tweag/ormolu/54642a7966d1d0787ba84636a2eb52f6729f600e/src/Ormolu/Printer/Meat/Module.hs | haskell | # LANGUAGE OverloadedStrings #
| Rendering of modules.
| Render a module-like entity (either a regular module or a backpack
signature).
| Stack header
| Pragmas and the associated comments
| AST to print | # LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
module Ormolu.Printer.Meat.Module
( p_hsModule,
)
where
import Control.Monad
import GHC.Hs hiding (comment)
import GHC.Types.SrcLoc
import Ormolu.Parser.CommentStream
import Ormolu.Parser.Pragma
import Ormolu.Printer.Combinators
import Ormolu.Printer.Comments
import Ormolu.Printer.Meat.Common
import Ormolu.Printer.Meat.Declaration
import Ormolu.Printer.Meat.Declaration.Warning
import Ormolu.Printer.Meat.ImportExport
import Ormolu.Printer.Meat.Pragma
p_hsModule ::
Maybe (RealLocated Comment) ->
[([RealLocated Comment], Pragma)] ->
HsModule ->
R ()
p_hsModule mstackHeader pragmas HsModule {..} = do
let deprecSpan = maybe [] (pure . getLocA) hsmodDeprecMessage
exportSpans = maybe [] (pure . getLocA) hsmodExports
switchLayout (deprecSpan <> exportSpans) $ do
forM_ mstackHeader $ \(L spn comment) -> do
spitCommentNow spn comment
newline
newline
p_pragmas pragmas
newline
case hsmodName of
Nothing -> return ()
Just hsmodName' -> do
located hsmodName' $ \name -> do
forM_ hsmodHaddockModHeader (p_hsDoc Pipe True)
p_hsmodName name
breakpoint
forM_ hsmodDeprecMessage $ \w -> do
located' p_moduleWarning w
breakpoint
case hsmodExports of
Nothing -> return ()
Just l -> do
located l $ \exports -> do
inci (p_hsmodExports exports)
breakpoint
txt "where"
newline
newline
forM_ hsmodImports (located' p_hsmodImport)
newline
switchLayout (getLocA <$> hsmodDecls) $ do
p_hsDecls Free hsmodDecls
newline
spitRemainingComments
|
0893769a9dc94a8c7c2dd4c7299b08fde307ab2e63c799952b094538aec361dc | MinaProtocol/mina | transaction_validator.ml | open Base
open Mina_base
module Ledger = Mina_ledger.Ledger
let within_mask l ~f =
let mask =
Ledger.register_mask l (Ledger.Mask.create ~depth:(Ledger.depth l) ())
in
let r = f mask in
if Result.is_ok r then Ledger.commit mask ;
ignore
(Ledger.unregister_mask_exn ~loc:Caml.__LOC__ mask : Ledger.unattached_mask) ;
r
let apply_user_command ~constraint_constants ~txn_global_slot l uc =
within_mask l ~f:(fun l' ->
Result.map
~f:(fun applied_txn ->
applied_txn.Ledger.Transaction_applied.Signed_command_applied.common
.user_command
.status )
(Ledger.apply_user_command l' ~constraint_constants ~txn_global_slot uc) )
let apply_transactions' ~constraint_constants ~global_slot ~txn_state_view l t =
O1trace.sync_thread "apply_transaction" (fun () ->
within_mask l ~f:(fun l' ->
Ledger.apply_transactions ~constraint_constants ~global_slot
~txn_state_view l' t ) )
let apply_transactions ~constraint_constants ~global_slot ~txn_state_view l txn
=
apply_transactions' l ~constraint_constants ~global_slot ~txn_state_view txn
let apply_transaction_first_pass ~constraint_constants ~global_slot
~txn_state_view l txn : Ledger.Transaction_partially_applied.t Or_error.t =
O1trace.sync_thread "apply_transaction_first_pass" (fun () ->
within_mask l ~f:(fun l' ->
Ledger.apply_transaction_first_pass l' ~constraint_constants
~global_slot ~txn_state_view txn ) )
let%test_unit "invalid transactions do not dirty the ledger" =
let open Core in
let open Mina_numbers in
let open Currency in
let open Signature_lib in
let constraint_constants = Genesis_constants.Constraint_constants.compiled in
let ledger = Ledger.create_ephemeral ~depth:4 () in
let sender_sk, receiver_sk =
Quickcheck.Generator.generate ~size:0
~random:(Splittable_random.State.of_int 100)
(Quickcheck.Generator.tuple2 Signature_lib.Private_key.gen
Signature_lib.Private_key.gen )
in
let sender_pk =
Public_key.compress (Public_key.of_private_key_exn sender_sk)
in
let sender_id = Account_id.create sender_pk Token_id.default in
let sender_account : Account.t =
Or_error.ok_exn
(Account.create_timed sender_id
(Balance.of_nanomina_int_exn 20)
~initial_minimum_balance:(Balance.of_nanomina_int_exn 20)
~cliff_time:(Global_slot.of_int 1)
~cliff_amount:(Amount.of_nanomina_int_exn 10)
~vesting_period:(Global_slot.of_int 1)
~vesting_increment:(Amount.of_nanomina_int_exn 1) )
in
let receiver_pk =
Public_key.compress (Public_key.of_private_key_exn receiver_sk)
in
let receiver_id = Account_id.create receiver_pk Token_id.default in
let receiver_account : Account.t =
Account.create receiver_id (Balance.of_nanomina_int_exn 20)
in
let invalid_command =
let payment : Payment_payload.t =
{ source_pk = sender_pk
; receiver_pk
; amount = Amount.of_nanomina_int_exn 15
}
in
let payload =
Signed_command_payload.create
~fee:(Fee.of_nanomina_int_exn 1)
~fee_payer_pk:sender_pk ~nonce:(Account_nonce.of_int 0)
~valid_until:None ~memo:Signed_command_memo.dummy
~body:(Signed_command_payload.Body.Payment payment)
in
Option.value_exn
(Signed_command.create_with_signature_checked
(Signed_command.sign_payload sender_sk payload)
sender_pk payload )
in
Ledger.create_new_account_exn ledger sender_id sender_account ;
Ledger.create_new_account_exn ledger receiver_id receiver_account ;
( match
apply_user_command ~constraint_constants
~txn_global_slot:(Global_slot.of_int 1) ledger invalid_command
with
| Ok _ ->
failwith "successfully applied an invalid transaction"
| Error err ->
if
String.equal (Error.to_string_hum err)
"The source account requires a minimum balance"
then ()
else
failwithf "transaction failed for an unexpected reason: %s\n"
(Error.to_string_hum err) () ) ;
let account_after_apply =
Option.value_exn
(Option.bind
(Ledger.location_of_account ledger sender_id)
~f:(Ledger.get ledger) )
in
assert (Account_nonce.equal account_after_apply.nonce (Account_nonce.of_int 0))
| null | https://raw.githubusercontent.com/MinaProtocol/mina/57e2ea1b87fe1a24517e1c62f51cc59fe9bc87cd/src/lib/transaction_snark/transaction_validator.ml | ocaml | open Base
open Mina_base
module Ledger = Mina_ledger.Ledger
let within_mask l ~f =
let mask =
Ledger.register_mask l (Ledger.Mask.create ~depth:(Ledger.depth l) ())
in
let r = f mask in
if Result.is_ok r then Ledger.commit mask ;
ignore
(Ledger.unregister_mask_exn ~loc:Caml.__LOC__ mask : Ledger.unattached_mask) ;
r
let apply_user_command ~constraint_constants ~txn_global_slot l uc =
within_mask l ~f:(fun l' ->
Result.map
~f:(fun applied_txn ->
applied_txn.Ledger.Transaction_applied.Signed_command_applied.common
.user_command
.status )
(Ledger.apply_user_command l' ~constraint_constants ~txn_global_slot uc) )
let apply_transactions' ~constraint_constants ~global_slot ~txn_state_view l t =
O1trace.sync_thread "apply_transaction" (fun () ->
within_mask l ~f:(fun l' ->
Ledger.apply_transactions ~constraint_constants ~global_slot
~txn_state_view l' t ) )
let apply_transactions ~constraint_constants ~global_slot ~txn_state_view l txn
=
apply_transactions' l ~constraint_constants ~global_slot ~txn_state_view txn
let apply_transaction_first_pass ~constraint_constants ~global_slot
~txn_state_view l txn : Ledger.Transaction_partially_applied.t Or_error.t =
O1trace.sync_thread "apply_transaction_first_pass" (fun () ->
within_mask l ~f:(fun l' ->
Ledger.apply_transaction_first_pass l' ~constraint_constants
~global_slot ~txn_state_view txn ) )
let%test_unit "invalid transactions do not dirty the ledger" =
let open Core in
let open Mina_numbers in
let open Currency in
let open Signature_lib in
let constraint_constants = Genesis_constants.Constraint_constants.compiled in
let ledger = Ledger.create_ephemeral ~depth:4 () in
let sender_sk, receiver_sk =
Quickcheck.Generator.generate ~size:0
~random:(Splittable_random.State.of_int 100)
(Quickcheck.Generator.tuple2 Signature_lib.Private_key.gen
Signature_lib.Private_key.gen )
in
let sender_pk =
Public_key.compress (Public_key.of_private_key_exn sender_sk)
in
let sender_id = Account_id.create sender_pk Token_id.default in
let sender_account : Account.t =
Or_error.ok_exn
(Account.create_timed sender_id
(Balance.of_nanomina_int_exn 20)
~initial_minimum_balance:(Balance.of_nanomina_int_exn 20)
~cliff_time:(Global_slot.of_int 1)
~cliff_amount:(Amount.of_nanomina_int_exn 10)
~vesting_period:(Global_slot.of_int 1)
~vesting_increment:(Amount.of_nanomina_int_exn 1) )
in
let receiver_pk =
Public_key.compress (Public_key.of_private_key_exn receiver_sk)
in
let receiver_id = Account_id.create receiver_pk Token_id.default in
let receiver_account : Account.t =
Account.create receiver_id (Balance.of_nanomina_int_exn 20)
in
let invalid_command =
let payment : Payment_payload.t =
{ source_pk = sender_pk
; receiver_pk
; amount = Amount.of_nanomina_int_exn 15
}
in
let payload =
Signed_command_payload.create
~fee:(Fee.of_nanomina_int_exn 1)
~fee_payer_pk:sender_pk ~nonce:(Account_nonce.of_int 0)
~valid_until:None ~memo:Signed_command_memo.dummy
~body:(Signed_command_payload.Body.Payment payment)
in
Option.value_exn
(Signed_command.create_with_signature_checked
(Signed_command.sign_payload sender_sk payload)
sender_pk payload )
in
Ledger.create_new_account_exn ledger sender_id sender_account ;
Ledger.create_new_account_exn ledger receiver_id receiver_account ;
( match
apply_user_command ~constraint_constants
~txn_global_slot:(Global_slot.of_int 1) ledger invalid_command
with
| Ok _ ->
failwith "successfully applied an invalid transaction"
| Error err ->
if
String.equal (Error.to_string_hum err)
"The source account requires a minimum balance"
then ()
else
failwithf "transaction failed for an unexpected reason: %s\n"
(Error.to_string_hum err) () ) ;
let account_after_apply =
Option.value_exn
(Option.bind
(Ledger.location_of_account ledger sender_id)
~f:(Ledger.get ledger) )
in
assert (Account_nonce.equal account_after_apply.nonce (Account_nonce.of_int 0))
| |
a0b803ad4ed95e0e61bf3cc094da00954d3ad8332215438daa15b0d5c4b7cd25 | kitlang/kit | Toolchain.hs | module Kit.Toolchain (
module Kit.Toolchain.CCompiler,
) where
import Kit.Toolchain.CCompiler
| null | https://raw.githubusercontent.com/kitlang/kit/2769a7a8e51fe4466c50439d1a1ebdad0fb79710/src/Kit/Toolchain.hs | haskell | module Kit.Toolchain (
module Kit.Toolchain.CCompiler,
) where
import Kit.Toolchain.CCompiler
| |
8dcad3d05ba2f371d88a18cdff7708b7eef44feb65a5b67bf9d89b33350ad013 | askvortsov1/nittany_market | csv.ml | module LoadCsv (M : Models.Model_intf.Model) = struct
let load ?(transform = fun x -> x) file_name
(module Db : Caqti_lwt.CONNECTION) =
let module CsvUtil = Csvfields.Csv.Record (M) in
let module Repo = Models.Model_intf.Make_ModelRepository (M) in
let data = CsvUtil.csv_load file_name in
Lwt_list.iter_s
(fun raw_entry ->
let entry = transform raw_entry in
Repo.add entry (module Db))
data
end
module CategoryCsv = LoadCsv (Models.Category.Category)
module ZipcodeInfoCsv = LoadCsv (Models.Zipcodeinfo.ZipcodeInfo)
module AddressCsv = LoadCsv (Models.Address.Address)
module UserCsv = LoadCsv (Models.User.User)
module BuyerCsv = LoadCsv (Models.Buyer.Buyer)
module SellerCsv = LoadCsv (Models.Seller.Seller)
module LocalVendorCsv = LoadCsv (Models.Localvendor.LocalVendor)
module CreditCardCsv = LoadCsv (Models.Creditcard.CreditCard)
module RatingCsv = LoadCsv (Models.Rating.Rating)
module ProductListingCsv = LoadCsv (Models.Productlisting.ProductListing)
module OrderCsv = LoadCsv (Models.Order.Order)
module ReviewCsv = LoadCsv (Models.Review.Review)
let load_funcs =
[
CategoryCsv.load "data/Categories.csv";
ZipcodeInfoCsv.load "data/Zipcode_Info.csv";
AddressCsv.load "data/Address.csv";
UserCsv.load
~transform:(fun u ->
{ email = u.email; password = Auth.Hasher.hash u.password })
"data/Users.csv";
BuyerCsv.load "data/Buyers.csv";
SellerCsv.load "data/Sellers.csv";
LocalVendorCsv.load "data/Local_Vendors.csv";
CreditCardCsv.load "data/Credit_Cards.csv";
RatingCsv.load "data/Ratings.csv";
ProductListingCsv.load "data/Product_Listing.csv";
OrderCsv.load "data/Orders.csv";
ReviewCsv.load "data/Reviews.csv";
]
let run_load (module Db : Caqti_lwt.CONNECTION) =
Lwt_list.iter_s
(fun (load_func : (module Caqti_lwt.CONNECTION) -> unit Lwt.t) ->
load_func (module Db))
load_funcs
| null | https://raw.githubusercontent.com/askvortsov1/nittany_market/08ffcad2bb2ead9aaeb85b22b88aa2af879e36ad/lib/csv.ml | ocaml | module LoadCsv (M : Models.Model_intf.Model) = struct
let load ?(transform = fun x -> x) file_name
(module Db : Caqti_lwt.CONNECTION) =
let module CsvUtil = Csvfields.Csv.Record (M) in
let module Repo = Models.Model_intf.Make_ModelRepository (M) in
let data = CsvUtil.csv_load file_name in
Lwt_list.iter_s
(fun raw_entry ->
let entry = transform raw_entry in
Repo.add entry (module Db))
data
end
module CategoryCsv = LoadCsv (Models.Category.Category)
module ZipcodeInfoCsv = LoadCsv (Models.Zipcodeinfo.ZipcodeInfo)
module AddressCsv = LoadCsv (Models.Address.Address)
module UserCsv = LoadCsv (Models.User.User)
module BuyerCsv = LoadCsv (Models.Buyer.Buyer)
module SellerCsv = LoadCsv (Models.Seller.Seller)
module LocalVendorCsv = LoadCsv (Models.Localvendor.LocalVendor)
module CreditCardCsv = LoadCsv (Models.Creditcard.CreditCard)
module RatingCsv = LoadCsv (Models.Rating.Rating)
module ProductListingCsv = LoadCsv (Models.Productlisting.ProductListing)
module OrderCsv = LoadCsv (Models.Order.Order)
module ReviewCsv = LoadCsv (Models.Review.Review)
let load_funcs =
[
CategoryCsv.load "data/Categories.csv";
ZipcodeInfoCsv.load "data/Zipcode_Info.csv";
AddressCsv.load "data/Address.csv";
UserCsv.load
~transform:(fun u ->
{ email = u.email; password = Auth.Hasher.hash u.password })
"data/Users.csv";
BuyerCsv.load "data/Buyers.csv";
SellerCsv.load "data/Sellers.csv";
LocalVendorCsv.load "data/Local_Vendors.csv";
CreditCardCsv.load "data/Credit_Cards.csv";
RatingCsv.load "data/Ratings.csv";
ProductListingCsv.load "data/Product_Listing.csv";
OrderCsv.load "data/Orders.csv";
ReviewCsv.load "data/Reviews.csv";
]
let run_load (module Db : Caqti_lwt.CONNECTION) =
Lwt_list.iter_s
(fun (load_func : (module Caqti_lwt.CONNECTION) -> unit Lwt.t) ->
load_func (module Db))
load_funcs
| |
2781454b81adf6f1ff73bdfde0e78839b0bb42cf8a98864e808a2fe745fe2e0c | mrkkrp/megaparsec | Megaparsec.hs | {-# LANGUAGE OverloadedStrings #-}
module ParsersBench.CSV.Megaparsec
( parseCSV,
)
where
import Control.Monad
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Vector (Vector)
import qualified Data.Vector as V
import Data.Void
import Text.Megaparsec
import Text.Megaparsec.Byte
type Parser = Parsec Void ByteString
type Record = Vector Field
type Field = ByteString
-- | Parse a CSV file without conversion of individual records.
parseCSV :: ByteString -> [Record]
parseCSV bs =
case parse csv "" bs of
Left err -> error (errorBundlePretty err)
Right x -> x
csv :: Parser [Record]
csv = do
xs <- sepEndBy1 record eol
eof
return xs
record :: Parser Record
record = do
notFollowedBy eof -- to prevent reading empty line at the end of file
V.fromList <$!> (sepBy1 field (char 44) <?> "record")
field :: Parser Field
field = label "field" (escapedField <|> unescapedField)
escapedField :: Parser ByteString
escapedField =
B.pack <$!> between (char 34) (char 34) (many $ normalChar <|> escapedDq)
where
normalChar = anySingleBut 34 <?> "unescaped character"
escapedDq = label "escaped double-quote" (34 <$ string "\"\"")
unescapedField :: Parser ByteString
unescapedField =
takeWhileP
(Just "unescaped char")
(`notElem` [44, 34, 10, 13])
# INLINE unescapedField #
| null | https://raw.githubusercontent.com/mrkkrp/megaparsec/a804c07ff3887c3c60ab41bfb3faa71291ef82dc/parsers-bench/ParsersBench/CSV/Megaparsec.hs | haskell | # LANGUAGE OverloadedStrings #
| Parse a CSV file without conversion of individual records.
to prevent reading empty line at the end of file |
module ParsersBench.CSV.Megaparsec
( parseCSV,
)
where
import Control.Monad
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Vector (Vector)
import qualified Data.Vector as V
import Data.Void
import Text.Megaparsec
import Text.Megaparsec.Byte
type Parser = Parsec Void ByteString
type Record = Vector Field
type Field = ByteString
parseCSV :: ByteString -> [Record]
parseCSV bs =
case parse csv "" bs of
Left err -> error (errorBundlePretty err)
Right x -> x
csv :: Parser [Record]
csv = do
xs <- sepEndBy1 record eol
eof
return xs
record :: Parser Record
record = do
V.fromList <$!> (sepBy1 field (char 44) <?> "record")
field :: Parser Field
field = label "field" (escapedField <|> unescapedField)
escapedField :: Parser ByteString
escapedField =
B.pack <$!> between (char 34) (char 34) (many $ normalChar <|> escapedDq)
where
normalChar = anySingleBut 34 <?> "unescaped character"
escapedDq = label "escaped double-quote" (34 <$ string "\"\"")
unescapedField :: Parser ByteString
unescapedField =
takeWhileP
(Just "unescaped char")
(`notElem` [44, 34, 10, 13])
# INLINE unescapedField #
|
fe9f80794735e9d2c51be58694acc0a0919cd8895df1122a13fd20bfac78b65f | Quviq/quickcheck-contractmodel | Utils.hs | module Test.QuickCheck.ContractModel.Internal.Utils where
import Test.QuickCheck.ContractModel.Internal.Common
import Data.Map qualified as Map
import Cardano.Api
getTxOuts :: Tx Era -> [TxOut CtxTx Era]
getTxOuts (getTxBody -> TxBody content) = txOuts content
getTxInputs :: Tx Era -> UTxO Era -> [TxOut CtxUTxO Era]
getTxInputs (getTxBody -> TxBody content) (UTxO utxo) =
[ txOut
| (txIn, _) <- txIns content
, Just txOut <- [Map.lookup txIn utxo]
]
bucket :: (Num a, Ord a, Show a, Integral a) => a -> a -> [String]
bucket _ 0 = ["0"]
bucket size n | n < size = [ "<" ++ show size ]
| size <= n, n < size*10 = [bucketIn size n]
| otherwise = bucket (size*10) n
where bucketIn size n = let b = n `div` size in show (b*size) ++ "-" ++ show (b*size+(size - 1))
| null | https://raw.githubusercontent.com/Quviq/quickcheck-contractmodel/071628000ad391ba6849b4d8407b5375228d235d/quickcheck-contractmodel/src/Test/QuickCheck/ContractModel/Internal/Utils.hs | haskell | module Test.QuickCheck.ContractModel.Internal.Utils where
import Test.QuickCheck.ContractModel.Internal.Common
import Data.Map qualified as Map
import Cardano.Api
getTxOuts :: Tx Era -> [TxOut CtxTx Era]
getTxOuts (getTxBody -> TxBody content) = txOuts content
getTxInputs :: Tx Era -> UTxO Era -> [TxOut CtxUTxO Era]
getTxInputs (getTxBody -> TxBody content) (UTxO utxo) =
[ txOut
| (txIn, _) <- txIns content
, Just txOut <- [Map.lookup txIn utxo]
]
bucket :: (Num a, Ord a, Show a, Integral a) => a -> a -> [String]
bucket _ 0 = ["0"]
bucket size n | n < size = [ "<" ++ show size ]
| size <= n, n < size*10 = [bucketIn size n]
| otherwise = bucket (size*10) n
where bucketIn size n = let b = n `div` size in show (b*size) ++ "-" ++ show (b*size+(size - 1))
| |
b60d5ad76316a87754d70b15cdd4761e2a0aa25786475d19dea7c2be608a1511 | haroldcarr/learn-haskell-coq-ml-etc | Common.hs | {-# LANGUAGE OverloadedStrings #-}
module Common where
import Data.Attoparsec.ByteString.Char8
import Data.ByteString.Char8 as BSC
parseFully :: Result r -> Either String (String, r)
parseFully r0 = case handlePartial r0 of
Fail u ctxs msg -> Left (BSC.unpack u ++ " " ++ show ctxs ++ " " ++ msg)
Done u r -> Right (BSC.unpack u, r)
_ -> error "impossible"
where
handlePartial r = case r of
Partial f -> f "" -- tell the parser there is no more input
failOrDone -> failOrDone
| null | https://raw.githubusercontent.com/haroldcarr/learn-haskell-coq-ml-etc/b4e83ec7c7af730de688b7376497b9f49dc24a0e/haskell/topic/fix-free/2016-01-benjamin-hodgson-parsing-to-free-monads/Common.hs | haskell | # LANGUAGE OverloadedStrings #
tell the parser there is no more input |
module Common where
import Data.Attoparsec.ByteString.Char8
import Data.ByteString.Char8 as BSC
parseFully :: Result r -> Either String (String, r)
parseFully r0 = case handlePartial r0 of
Fail u ctxs msg -> Left (BSC.unpack u ++ " " ++ show ctxs ++ " " ++ msg)
Done u r -> Right (BSC.unpack u, r)
_ -> error "impossible"
where
handlePartial r = case r of
failOrDone -> failOrDone
|
8f82bf6bfbb13316d1794d5a3f0b9d617ed8feaff38ca3da1eaaa6e529c44c86 | finnishtransportagency/harja | integraatioloki_test.clj | (ns harja.palvelin.integraatiot.integraatioloki-test
(:require [clojure.test :refer [deftest is use-fixtures]]
[com.stuartsierra.component :as component]
[harja.testi :refer :all]
[harja.palvelin.komponentit.tietokanta :as tietokanta]
[harja.palvelin.integraatiot.integraatioloki :refer [->Integraatioloki] :as integraatioloki]))
(def +testiviesti+ {:suunta "ulos" :sisaltotyyppi "application/xml" :siirtotyyppi "jms" :sisalto "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" :otsikko nil :parametrit nil})
(defn jarjestelma-fixture [testit]
(alter-var-root #'jarjestelma
(fn [_]
(component/start
(component/system-map
:db (tietokanta/luo-tietokanta testitietokanta)
:integraatioloki (component/using (->Integraatioloki nil) [:db])))))
(testit)
(alter-var-root #'jarjestelma component/stop))
(use-fixtures :once jarjestelma-fixture)
(defn poista-testitapahtuma [tapahtuma-id]
(u "DELETE FROM integraatioviesti WHERE integraatiotapahtuma = " tapahtuma-id ";")
(u "DELETE FROM integraatiotapahtuma WHERE id = " tapahtuma-id ";"))
(deftest tarkista-integraation-aloituksen-kirjaaminen
(let [tapahtuma-id (integraatioloki/kirjaa-alkanut-integraatio (:integraatioloki jarjestelma) "sampo" "sisaanluku" nil nil)]
(is tapahtuma-id "Tapahtumalle palautettiin id.")
(is (first (first (q "SELECT exists(SELECT id FROM integraatiotapahtuma WHERE id = " tapahtuma-id ");")))
"Tietokannasta löytyy integraatiotapahtuma integraation aloituksen jälkeen.")
(poista-testitapahtuma tapahtuma-id)))
(deftest tarkista-onnistuneen-integraation-kirjaaminen
(let [tapahtuma-id (integraatioloki/kirjaa-alkanut-integraatio (:integraatioloki jarjestelma) "sampo" "sisaanluku" nil nil)]
(integraatioloki/kirjaa-onnistunut-integraatio (:integraatioloki jarjestelma) nil nil tapahtuma-id nil)
(is (first (first (q "SELECT exists(SELECT id FROM integraatiotapahtuma WHERE id = " tapahtuma-id " AND onnistunut is true AND paattynyt is not null);")))
"Tietokannasta löytyy integraatiotapahtuma joka on merkitty onnistuneeksi.")
(poista-testitapahtuma tapahtuma-id)))
(deftest tarkista-viestin-kirjaaminen
(let [tapahtuma-id (integraatioloki/kirjaa-alkanut-integraatio (:integraatioloki jarjestelma) "sampo" "sisaanluku" nil +testiviesti+)]
(is (= 1 (count (q "SELECT id FROM integraatioviesti WHERE integraatiotapahtuma = " tapahtuma-id ";"))))
(poista-testitapahtuma tapahtuma-id)))
| null | https://raw.githubusercontent.com/finnishtransportagency/harja/488b1e096f0611e175221d74ba4f2ffed6bea8f1/test/clj/harja/palvelin/integraatiot/integraatioloki_test.clj | clojure | (ns harja.palvelin.integraatiot.integraatioloki-test
(:require [clojure.test :refer [deftest is use-fixtures]]
[com.stuartsierra.component :as component]
[harja.testi :refer :all]
[harja.palvelin.komponentit.tietokanta :as tietokanta]
[harja.palvelin.integraatiot.integraatioloki :refer [->Integraatioloki] :as integraatioloki]))
(def +testiviesti+ {:suunta "ulos" :sisaltotyyppi "application/xml" :siirtotyyppi "jms" :sisalto "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" :otsikko nil :parametrit nil})
(defn jarjestelma-fixture [testit]
(alter-var-root #'jarjestelma
(fn [_]
(component/start
(component/system-map
:db (tietokanta/luo-tietokanta testitietokanta)
:integraatioloki (component/using (->Integraatioloki nil) [:db])))))
(testit)
(alter-var-root #'jarjestelma component/stop))
(use-fixtures :once jarjestelma-fixture)
(defn poista-testitapahtuma [tapahtuma-id]
(u "DELETE FROM integraatioviesti WHERE integraatiotapahtuma = " tapahtuma-id ";")
(u "DELETE FROM integraatiotapahtuma WHERE id = " tapahtuma-id ";"))
(deftest tarkista-integraation-aloituksen-kirjaaminen
(let [tapahtuma-id (integraatioloki/kirjaa-alkanut-integraatio (:integraatioloki jarjestelma) "sampo" "sisaanluku" nil nil)]
(is tapahtuma-id "Tapahtumalle palautettiin id.")
(is (first (first (q "SELECT exists(SELECT id FROM integraatiotapahtuma WHERE id = " tapahtuma-id ");")))
"Tietokannasta löytyy integraatiotapahtuma integraation aloituksen jälkeen.")
(poista-testitapahtuma tapahtuma-id)))
(deftest tarkista-onnistuneen-integraation-kirjaaminen
(let [tapahtuma-id (integraatioloki/kirjaa-alkanut-integraatio (:integraatioloki jarjestelma) "sampo" "sisaanluku" nil nil)]
(integraatioloki/kirjaa-onnistunut-integraatio (:integraatioloki jarjestelma) nil nil tapahtuma-id nil)
(is (first (first (q "SELECT exists(SELECT id FROM integraatiotapahtuma WHERE id = " tapahtuma-id " AND onnistunut is true AND paattynyt is not null);")))
"Tietokannasta löytyy integraatiotapahtuma joka on merkitty onnistuneeksi.")
(poista-testitapahtuma tapahtuma-id)))
(deftest tarkista-viestin-kirjaaminen
(let [tapahtuma-id (integraatioloki/kirjaa-alkanut-integraatio (:integraatioloki jarjestelma) "sampo" "sisaanluku" nil +testiviesti+)]
(is (= 1 (count (q "SELECT id FROM integraatioviesti WHERE integraatiotapahtuma = " tapahtuma-id ";"))))
(poista-testitapahtuma tapahtuma-id)))
| |
da56a5cbe94b9e65d073c8375f32078319cf6c115bb4bb95429383eae17d6ba5 | BitGameEN/bitgamex | ecrn_agent.erl | , LLC . All Rights Reserved .
%%%
This file is provided to you under the BSD License ; you may not use
%%% this file except in compliance with the License.
%%%-------------------------------------------------------------------
%%% @doc
%%% Agent for cronish testing
-module(ecrn_agent).
-behaviour(gen_server).
%% API
-export([start_link/2,
cancel/1,
get_datetime/1,
set_datetime/3,
recalculate/1,
validate/1]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-include("internal.hrl").
-record(state, {job,
alarm_ref,
referenced_seconds,
seconds_at_reference,
timeout_type,
fast_forward=false}).
-define(MILLISECONDS, 1000).
-define(WAIT_BEFORE_RUN, 2000).
%%%===================================================================
%%% Types
%%%===================================================================
-type state() :: #state{}.
%%%===================================================================
%%% API
%%%===================================================================
%% @doc
%% Starts the server with the apropriate job and the appropriate ref
-spec start_link(erlcron:job_ref(), erlcron:job()) ->
ignore | {error, Reason::term()} | {ok, pid()}.
start_link(JobRef, Job) ->
gen_server:start_link(?MODULE, [JobRef, Job], []).
-spec get_datetime(pid()) -> calendar:datetime().
get_datetime(Pid) ->
gen_server:call(Pid, get_datetime).
-spec cancel(pid()) -> ok.
cancel(Pid) ->
gen_server:cast(Pid, shutdown).
-spec set_datetime(pid(), calendar:datetime(), erlcron:seconds()) -> ok.
set_datetime(Pid, DateTime, Actual) ->
gen_server:cast(Pid, {set_datetime, DateTime, Actual}).
-spec recalculate(pid()) -> ok.
recalculate(Pid) ->
gen_server:cast(Pid, recalculate).
%% @doc
Validate that a run_when spec specified is correct .
-spec validate(erlcron:run_when()) -> valid | invalid.
validate(Spec) ->
State = #state{job=undefined,
alarm_ref=undefined},
{DateTime, Actual} = ecrn_control:datetime(),
NewState = set_internal_time(State, DateTime, Actual),
try
until_next_time(NewState, {Spec, undefined}),
valid
catch
_Error:_Reason ->
invalid
end.
%%%===================================================================
%%% gen_server callbacks
%%%===================================================================
@private
init([JobRef, Job]) ->
State = #state{job=Job,
alarm_ref=JobRef},
{DateTime, Actual} = ecrn_control:datetime(),
NewState = set_internal_time(State, DateTime, Actual),
case until_next_milliseconds(NewState, Job) of
{ok, Millis} when is_integer(Millis) ->
ecrn_reg:register(JobRef, self()),
{ok, NewState, Millis};
{error, _} ->
{stop, normal}
end.
@private
handle_call(_Msg, _From, State) ->
case until_next_milliseconds(State, State#state.job) of
{ok, Millis} ->
{reply, ok, State, Millis};
{error, _} ->
{stop, normal, ok, State}
end.
@private
handle_cast(shutdown, State) ->
{stop, normal, State};
handle_cast({set_datetime, DateTime, Actual}, State) ->
fast_forward(State#state{fast_forward=true}, DateTime),
NewState = set_internal_time(State, DateTime, Actual),
case until_next_milliseconds(NewState, NewState#state.job) of
{ok, Millis} ->
{noreply, NewState, Millis};
{error, _} ->
{stop, normal, NewState}
end.
@private
handle_info(timeout, State = #state{job = {{once, _}, _}}) ->
do_job_run(State, State#state.job),
{stop, normal, State};
handle_info(timeout, State = #state{timeout_type=wait_before_run}) ->
NewState = State#state{timeout_type=normal},
case until_next_milliseconds(NewState, NewState#state.job) of
{ok, Millis} ->
{noreply, NewState, Millis};
{error, _} ->
{stop, normal, NewState}
end;
handle_info(timeout, State = #state{job = Job}) ->
do_job_run(State, Job),
NewState = State#state{timeout_type=wait_before_run},
{noreply, NewState, ?WAIT_BEFORE_RUN}.
@private
terminate(_Reason, #state{alarm_ref=Ref}) ->
ecrn_reg:unregister(Ref),
ok.
@private
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%%===================================================================
Internal functions
%%%===================================================================
do_job_run(State, {_, Job})
when is_record(State, state), is_function(Job) ->
RunFun = fun() ->
Job(State#state.alarm_ref, current_date(State))
end,
proc_lib:spawn(RunFun);
do_job_run(State, {_, {M, F, A}})
when is_record(State, state) ->
proc_lib:spawn(M, F, A).
@doc Returns the current time , in seconds past midnight .
-spec current_time(state()) -> erlcron:seconds().
current_time(State) ->
{_, {H,M,S}} = current_date(State),
S + M * 60 + H * 3600.
current_date(State = #state{fast_forward=true}) ->
calendar:gregorian_seconds_to_datetime(State#state.referenced_seconds);
current_date(State) ->
Elapsed = ecrn_util:epoch_seconds() - State#state.seconds_at_reference,
calendar:gregorian_seconds_to_datetime(ceiling(Elapsed +
State#state.referenced_seconds)).
%% @doc Calculates the duration in milliseconds until the next time
%% a job is to be run.
-spec until_next_milliseconds(state(), erlcron:job()) ->
{ok, erlcron:seconds()} | {error, invalid_one_exception}.
until_next_milliseconds(State, Job) ->
try
Millis = until_next_time(State, Job) * ?MILLISECONDS,
{ok, Millis}
catch
throw:invalid_once_exception ->
{error, invalid_once_exception}
end.
normalize_seconds(State, Seconds) ->
case Seconds - current_time(State) of
Value when Value >= 0 ->
Value;
_ ->
erlang:display(erlang:get_stacktrace()),
throw(invalid_once_exception)
end.
@doc Calculates the duration in seconds until the next time
%% a job is to be run.
-spec until_next_time(state(), {erlcron:run_when(), term()}) ->
erlcron:seconds().
until_next_time(_State, {{once, Seconds}, _What}) when is_integer(Seconds) ->
Seconds;
until_next_time(State, {{once, {H, M, S}}, _What})
when is_integer(H), is_integer(M), is_integer(S) ->
normalize_seconds(State, S + (M + (H * 60)) * 60);
until_next_time(State, {{once, Period}, _What}) ->
normalize_seconds(State, resolve_time(Period));
until_next_time(State, {{daily, Period}, _What}) ->
until_next_daytime(State, Period);
until_next_time(State, {{weekly, DoW, Period}, _What}) ->
OnDay = resolve_dow(DoW),
{Date, _} = current_date(State),
Today = calendar:day_of_the_week(Date),
case Today of
OnDay ->
until_next_daytime_or_days_from_now(State, Period, 7);
Today when Today < OnDay ->
until_days_from_now(State, Period, OnDay - Today);
Today when Today > OnDay ->
until_days_from_now(State, Period, (OnDay+7) - Today)
end;
until_next_time(State, {{monthly, DoM, Period}, _What}) ->
{{ThisYear, ThisMonth, Today}, _} = current_date(State),
{NextYear, NextMonth} =
case ThisMonth of
12 ->
{ThisYear + 1, 1};
_ ->
{ThisYear, ThisMonth + 1}
end,
D1 = calendar:date_to_gregorian_days(ThisYear, ThisMonth, Today),
D2 = calendar:date_to_gregorian_days(NextYear, NextMonth, DoM),
Days = D2 - D1,
case Today of
DoM ->
until_next_daytime_or_days_from_now(State, Period, Days);
_ ->
until_days_from_now(State, Period, Days)
end.
@doc Calculates the duration in seconds until the next time this
period is to occur during the day .
-spec until_next_daytime(state(), erlcron:period()) -> erlcron:seconds().
until_next_daytime(State, Period) ->
StartTime = first_time(Period),
EndTime = last_time(Period),
case current_time(State) of
T when T > EndTime ->
until_tomorrow(State, StartTime);
T ->
next_time(Period, T) - T
end.
%% @doc Calculates the last time in a given period.
-spec last_time(erlcron:period()) -> erlcron:seconds().
last_time(Period) ->
hd(lists:reverse(lists:sort(resolve_period(Period)))).
@doc Calculates the first time in a given period .
-spec first_time(erlcron:period()) -> erlcron:seconds().
first_time(Period) ->
hd(lists:sort(resolve_period(Period))).
@doc Calculates the first time in the given period after the given time .
-spec next_time(erlcron:period(), erlcron:seconds()) -> erlcron:seconds().
next_time(Period, Time) ->
R = lists:sort(resolve_period(Period)),
lists:foldl(fun(X, A) ->
case X of
T when T >= Time, T < A ->
T;
_ ->
A
end
end, 24*3600, R).
%% @doc Returns a list of times given a periodic specification.
-spec resolve_period([erlcron:period()] | erlcron:period()) -> [erlcron:seconds()].
resolve_period([]) ->
[];
resolve_period([H | T]) ->
resolve_period(H) ++ resolve_period(T);
resolve_period({every, Duration, {between, TimeA, TimeB}}) ->
Period = resolve_dur(Duration),
StartTime = resolve_time(TimeA),
EndTime = resolve_time(TimeB),
resolve_period0(Period, StartTime, EndTime, []);
resolve_period(Time) ->
[resolve_time(Time)].
resolve_period0(_, Time, EndTime, Acc) when Time >= EndTime ->
Acc;
resolve_period0(Period, Time, EndTime, Acc) ->
resolve_period0(Period, Time + Period, EndTime, [Time | Acc]).
@doc Returns seconds past midnight for a given time .
-spec resolve_time(erlcron:cron_time()) -> erlcron:seconds().
resolve_time({H, M, S}) when H < 24, M < 60, S < 60 ->
S + M * 60 + H * 3600;
resolve_time({H, M, S, X}) when H < 24, M < 60, S < 60, is_atom(X) ->
resolve_time({H, X}) + M * 60 + S;
resolve_time({H, M, X}) when H < 24, M < 60, is_atom(X) ->
resolve_time({H, X}) + M * 60;
resolve_time({12, am}) ->
0;
resolve_time({H, am}) when H < 12 ->
H * 3600;
resolve_time({12, pm}) ->
12 * 3600;
resolve_time({H, pm}) when H < 12->
(H + 12) * 3600.
%% @doc Returns seconds for a given duration.
-spec resolve_dur(erlcron:duration()) -> erlcron:seconds().
resolve_dur({Hour, hr}) ->
Hour * 3600;
resolve_dur({Min, min}) ->
Min * 60;
resolve_dur({Sec, sec}) ->
Sec.
@doc Returns the number of the given day of the week . See the calendar
module for day numbers .
-spec resolve_dow(erlcron:dow()) -> integer().
resolve_dow(mon) ->
1;
resolve_dow(tue) ->
2;
resolve_dow(wed) ->
3;
resolve_dow(thu) ->
4;
resolve_dow(fri) ->
5;
resolve_dow(sat) ->
6;
resolve_dow(sun) ->
7.
@doc Calculates the duration in seconds until the given time occurs
tomorrow .
-spec until_tomorrow(state(), erlcron:seconds()) -> erlcron:seconds().
until_tomorrow(State, StartTime) ->
(StartTime + 24*3600) - current_time(State).
@doc Calculates the duration in seconds until the given period
occurs several days from now .
-spec until_days_from_now(state(), erlcron:period(), integer()) ->
erlcron:seconds().
until_days_from_now(State, Period, Days) ->
Days * 24 * 3600 + until_next_daytime(State, Period).
@doc Calculates the duration in seconds until the given period
occurs , which may be today or several days from now .
-spec until_next_daytime_or_days_from_now(state(), erlcron:period(), integer()) ->
erlcron:seconds().
until_next_daytime_or_days_from_now(State, Period, Days) ->
CurrentTime = current_time(State),
case last_time(Period) of
T when T < CurrentTime ->
until_days_from_now(State, Period, Days-1);
_ ->
until_next_daytime(State, Period)
end.
set_internal_time(State, RefDate, CurrentSeconds) ->
NewSeconds = calendar:datetime_to_gregorian_seconds(RefDate),
State#state{referenced_seconds=NewSeconds,
seconds_at_reference=CurrentSeconds}.
ceiling(X) ->
T = erlang:trunc(X),
case (X - T) of
Neg when Neg < 0 -> T;
Pos when Pos > 0 -> T + 1;
_ -> T
end.
fast_forward(State, NewDate) ->
try
Seconds = until_next_time(State, State#state.job),
NewSeconds = calendar:datetime_to_gregorian_seconds(NewDate),
Span = NewSeconds - State#state.referenced_seconds,
case Span > Seconds of
true ->
RefSecs = State#state.referenced_seconds,
NewState = State#state{referenced_seconds = RefSecs + Seconds + 2},
do_job_run(State, State#state.job),
fast_forward(NewState, NewDate);
false ->
ok
end
catch
throw:invalid_once_exception ->
{error, invalid_once_exception}
end.
| null | https://raw.githubusercontent.com/BitGameEN/bitgamex/151ba70a481615379f9648581a5d459b503abe19/src/deps/erlcron/src/ecrn_agent.erl | erlang |
this file except in compliance with the License.
-------------------------------------------------------------------
@doc
Agent for cronish testing
API
gen_server callbacks
===================================================================
Types
===================================================================
===================================================================
API
===================================================================
@doc
Starts the server with the apropriate job and the appropriate ref
@doc
===================================================================
gen_server callbacks
===================================================================
===================================================================
===================================================================
@doc Calculates the duration in milliseconds until the next time
a job is to be run.
a job is to be run.
@doc Calculates the last time in a given period.
@doc Returns a list of times given a periodic specification.
@doc Returns seconds for a given duration. | , LLC . All Rights Reserved .
This file is provided to you under the BSD License ; you may not use
-module(ecrn_agent).
-behaviour(gen_server).
-export([start_link/2,
cancel/1,
get_datetime/1,
set_datetime/3,
recalculate/1,
validate/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-include("internal.hrl").
-record(state, {job,
alarm_ref,
referenced_seconds,
seconds_at_reference,
timeout_type,
fast_forward=false}).
-define(MILLISECONDS, 1000).
-define(WAIT_BEFORE_RUN, 2000).
-type state() :: #state{}.
-spec start_link(erlcron:job_ref(), erlcron:job()) ->
ignore | {error, Reason::term()} | {ok, pid()}.
start_link(JobRef, Job) ->
gen_server:start_link(?MODULE, [JobRef, Job], []).
-spec get_datetime(pid()) -> calendar:datetime().
get_datetime(Pid) ->
gen_server:call(Pid, get_datetime).
-spec cancel(pid()) -> ok.
cancel(Pid) ->
gen_server:cast(Pid, shutdown).
-spec set_datetime(pid(), calendar:datetime(), erlcron:seconds()) -> ok.
set_datetime(Pid, DateTime, Actual) ->
gen_server:cast(Pid, {set_datetime, DateTime, Actual}).
-spec recalculate(pid()) -> ok.
recalculate(Pid) ->
gen_server:cast(Pid, recalculate).
Validate that a run_when spec specified is correct .
-spec validate(erlcron:run_when()) -> valid | invalid.
validate(Spec) ->
State = #state{job=undefined,
alarm_ref=undefined},
{DateTime, Actual} = ecrn_control:datetime(),
NewState = set_internal_time(State, DateTime, Actual),
try
until_next_time(NewState, {Spec, undefined}),
valid
catch
_Error:_Reason ->
invalid
end.
@private
init([JobRef, Job]) ->
State = #state{job=Job,
alarm_ref=JobRef},
{DateTime, Actual} = ecrn_control:datetime(),
NewState = set_internal_time(State, DateTime, Actual),
case until_next_milliseconds(NewState, Job) of
{ok, Millis} when is_integer(Millis) ->
ecrn_reg:register(JobRef, self()),
{ok, NewState, Millis};
{error, _} ->
{stop, normal}
end.
@private
handle_call(_Msg, _From, State) ->
case until_next_milliseconds(State, State#state.job) of
{ok, Millis} ->
{reply, ok, State, Millis};
{error, _} ->
{stop, normal, ok, State}
end.
@private
handle_cast(shutdown, State) ->
{stop, normal, State};
handle_cast({set_datetime, DateTime, Actual}, State) ->
fast_forward(State#state{fast_forward=true}, DateTime),
NewState = set_internal_time(State, DateTime, Actual),
case until_next_milliseconds(NewState, NewState#state.job) of
{ok, Millis} ->
{noreply, NewState, Millis};
{error, _} ->
{stop, normal, NewState}
end.
@private
handle_info(timeout, State = #state{job = {{once, _}, _}}) ->
do_job_run(State, State#state.job),
{stop, normal, State};
handle_info(timeout, State = #state{timeout_type=wait_before_run}) ->
NewState = State#state{timeout_type=normal},
case until_next_milliseconds(NewState, NewState#state.job) of
{ok, Millis} ->
{noreply, NewState, Millis};
{error, _} ->
{stop, normal, NewState}
end;
handle_info(timeout, State = #state{job = Job}) ->
do_job_run(State, Job),
NewState = State#state{timeout_type=wait_before_run},
{noreply, NewState, ?WAIT_BEFORE_RUN}.
@private
terminate(_Reason, #state{alarm_ref=Ref}) ->
ecrn_reg:unregister(Ref),
ok.
@private
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
do_job_run(State, {_, Job})
when is_record(State, state), is_function(Job) ->
RunFun = fun() ->
Job(State#state.alarm_ref, current_date(State))
end,
proc_lib:spawn(RunFun);
do_job_run(State, {_, {M, F, A}})
when is_record(State, state) ->
proc_lib:spawn(M, F, A).
@doc Returns the current time , in seconds past midnight .
-spec current_time(state()) -> erlcron:seconds().
current_time(State) ->
{_, {H,M,S}} = current_date(State),
S + M * 60 + H * 3600.
current_date(State = #state{fast_forward=true}) ->
calendar:gregorian_seconds_to_datetime(State#state.referenced_seconds);
current_date(State) ->
Elapsed = ecrn_util:epoch_seconds() - State#state.seconds_at_reference,
calendar:gregorian_seconds_to_datetime(ceiling(Elapsed +
State#state.referenced_seconds)).
-spec until_next_milliseconds(state(), erlcron:job()) ->
{ok, erlcron:seconds()} | {error, invalid_one_exception}.
until_next_milliseconds(State, Job) ->
try
Millis = until_next_time(State, Job) * ?MILLISECONDS,
{ok, Millis}
catch
throw:invalid_once_exception ->
{error, invalid_once_exception}
end.
normalize_seconds(State, Seconds) ->
case Seconds - current_time(State) of
Value when Value >= 0 ->
Value;
_ ->
erlang:display(erlang:get_stacktrace()),
throw(invalid_once_exception)
end.
@doc Calculates the duration in seconds until the next time
-spec until_next_time(state(), {erlcron:run_when(), term()}) ->
erlcron:seconds().
until_next_time(_State, {{once, Seconds}, _What}) when is_integer(Seconds) ->
Seconds;
until_next_time(State, {{once, {H, M, S}}, _What})
when is_integer(H), is_integer(M), is_integer(S) ->
normalize_seconds(State, S + (M + (H * 60)) * 60);
until_next_time(State, {{once, Period}, _What}) ->
normalize_seconds(State, resolve_time(Period));
until_next_time(State, {{daily, Period}, _What}) ->
until_next_daytime(State, Period);
until_next_time(State, {{weekly, DoW, Period}, _What}) ->
OnDay = resolve_dow(DoW),
{Date, _} = current_date(State),
Today = calendar:day_of_the_week(Date),
case Today of
OnDay ->
until_next_daytime_or_days_from_now(State, Period, 7);
Today when Today < OnDay ->
until_days_from_now(State, Period, OnDay - Today);
Today when Today > OnDay ->
until_days_from_now(State, Period, (OnDay+7) - Today)
end;
until_next_time(State, {{monthly, DoM, Period}, _What}) ->
{{ThisYear, ThisMonth, Today}, _} = current_date(State),
{NextYear, NextMonth} =
case ThisMonth of
12 ->
{ThisYear + 1, 1};
_ ->
{ThisYear, ThisMonth + 1}
end,
D1 = calendar:date_to_gregorian_days(ThisYear, ThisMonth, Today),
D2 = calendar:date_to_gregorian_days(NextYear, NextMonth, DoM),
Days = D2 - D1,
case Today of
DoM ->
until_next_daytime_or_days_from_now(State, Period, Days);
_ ->
until_days_from_now(State, Period, Days)
end.
@doc Calculates the duration in seconds until the next time this
period is to occur during the day .
-spec until_next_daytime(state(), erlcron:period()) -> erlcron:seconds().
until_next_daytime(State, Period) ->
StartTime = first_time(Period),
EndTime = last_time(Period),
case current_time(State) of
T when T > EndTime ->
until_tomorrow(State, StartTime);
T ->
next_time(Period, T) - T
end.
-spec last_time(erlcron:period()) -> erlcron:seconds().
last_time(Period) ->
hd(lists:reverse(lists:sort(resolve_period(Period)))).
@doc Calculates the first time in a given period .
-spec first_time(erlcron:period()) -> erlcron:seconds().
first_time(Period) ->
hd(lists:sort(resolve_period(Period))).
@doc Calculates the first time in the given period after the given time .
-spec next_time(erlcron:period(), erlcron:seconds()) -> erlcron:seconds().
next_time(Period, Time) ->
R = lists:sort(resolve_period(Period)),
lists:foldl(fun(X, A) ->
case X of
T when T >= Time, T < A ->
T;
_ ->
A
end
end, 24*3600, R).
-spec resolve_period([erlcron:period()] | erlcron:period()) -> [erlcron:seconds()].
resolve_period([]) ->
[];
resolve_period([H | T]) ->
resolve_period(H) ++ resolve_period(T);
resolve_period({every, Duration, {between, TimeA, TimeB}}) ->
Period = resolve_dur(Duration),
StartTime = resolve_time(TimeA),
EndTime = resolve_time(TimeB),
resolve_period0(Period, StartTime, EndTime, []);
resolve_period(Time) ->
[resolve_time(Time)].
resolve_period0(_, Time, EndTime, Acc) when Time >= EndTime ->
Acc;
resolve_period0(Period, Time, EndTime, Acc) ->
resolve_period0(Period, Time + Period, EndTime, [Time | Acc]).
@doc Returns seconds past midnight for a given time .
-spec resolve_time(erlcron:cron_time()) -> erlcron:seconds().
resolve_time({H, M, S}) when H < 24, M < 60, S < 60 ->
S + M * 60 + H * 3600;
resolve_time({H, M, S, X}) when H < 24, M < 60, S < 60, is_atom(X) ->
resolve_time({H, X}) + M * 60 + S;
resolve_time({H, M, X}) when H < 24, M < 60, is_atom(X) ->
resolve_time({H, X}) + M * 60;
resolve_time({12, am}) ->
0;
resolve_time({H, am}) when H < 12 ->
H * 3600;
resolve_time({12, pm}) ->
12 * 3600;
resolve_time({H, pm}) when H < 12->
(H + 12) * 3600.
-spec resolve_dur(erlcron:duration()) -> erlcron:seconds().
resolve_dur({Hour, hr}) ->
Hour * 3600;
resolve_dur({Min, min}) ->
Min * 60;
resolve_dur({Sec, sec}) ->
Sec.
@doc Returns the number of the given day of the week . See the calendar
module for day numbers .
-spec resolve_dow(erlcron:dow()) -> integer().
resolve_dow(mon) ->
1;
resolve_dow(tue) ->
2;
resolve_dow(wed) ->
3;
resolve_dow(thu) ->
4;
resolve_dow(fri) ->
5;
resolve_dow(sat) ->
6;
resolve_dow(sun) ->
7.
@doc Calculates the duration in seconds until the given time occurs
tomorrow .
-spec until_tomorrow(state(), erlcron:seconds()) -> erlcron:seconds().
until_tomorrow(State, StartTime) ->
(StartTime + 24*3600) - current_time(State).
@doc Calculates the duration in seconds until the given period
occurs several days from now .
-spec until_days_from_now(state(), erlcron:period(), integer()) ->
erlcron:seconds().
until_days_from_now(State, Period, Days) ->
Days * 24 * 3600 + until_next_daytime(State, Period).
@doc Calculates the duration in seconds until the given period
occurs , which may be today or several days from now .
-spec until_next_daytime_or_days_from_now(state(), erlcron:period(), integer()) ->
erlcron:seconds().
until_next_daytime_or_days_from_now(State, Period, Days) ->
CurrentTime = current_time(State),
case last_time(Period) of
T when T < CurrentTime ->
until_days_from_now(State, Period, Days-1);
_ ->
until_next_daytime(State, Period)
end.
set_internal_time(State, RefDate, CurrentSeconds) ->
NewSeconds = calendar:datetime_to_gregorian_seconds(RefDate),
State#state{referenced_seconds=NewSeconds,
seconds_at_reference=CurrentSeconds}.
ceiling(X) ->
T = erlang:trunc(X),
case (X - T) of
Neg when Neg < 0 -> T;
Pos when Pos > 0 -> T + 1;
_ -> T
end.
fast_forward(State, NewDate) ->
try
Seconds = until_next_time(State, State#state.job),
NewSeconds = calendar:datetime_to_gregorian_seconds(NewDate),
Span = NewSeconds - State#state.referenced_seconds,
case Span > Seconds of
true ->
RefSecs = State#state.referenced_seconds,
NewState = State#state{referenced_seconds = RefSecs + Seconds + 2},
do_job_run(State, State#state.job),
fast_forward(NewState, NewDate);
false ->
ok
end
catch
throw:invalid_once_exception ->
{error, invalid_once_exception}
end.
|
9ce4e00980526fa12a7c0cbbc9ac19574f288f0fa8799f3eb09d7163df5068a8 | SevereOverfl0w/bukkure | blocks.clj | ;; TODO: Check this file manually
(ns bukkure.blocks
(:require [bukkure.logging :as log]
[bukkure.items :as i]
[bukkure.player :as plr]
[bukkure.bukkit :as bk]))
(defn left-face
"Get the face 270deg from the given one. Stays the same for up/down"
[key]
({:up :up, :down :down
:north :east, :east :south
:south :west, :west :north} key))
(defn right-face
"Get the face 90deg from the given one. Stays the same for up/down"
[key]
({:up :up, :down :down
:north :west, :west :south
:south :east, :east :north} key))
(defn opposite-face
"Get the opposite facing direction"
[key]
({:up :down, :down :up
:north :south, :south :north
:east :west, :west :east} key))
(defn find-relative-dir
"Find relative direction, where forward is north, and left is west"
[d r]
({:north d :south (opposite-face d) :east (left-face d) :west (right-face d) :up :up :down :down} r))
(defmulti run-action (fn [ctx a] (:action a)))
(defn run-actions [ctx & actions]
(loop [a (first actions)
r (rest actions)
context ctx]
(cond
(nil? a) context
(and (coll? a) (not (map? a))) (recur (first a) (concat (rest a) r) context)
:else
(recur (first r) (rest r) (run-action context a)))))
(defmacro defaction
[name docstring ctx-binding params & method-body]
(let [params (map #(symbol (.getName (symbol %))) params)]
`(do
(defn ~name ~docstring [~@params]
(zipmap [:action ~@(map keyword params)] [~(keyword name) ~@params]))
(defmethod run-action ~(keyword name) [~ctx-binding {:keys [~@params]}]
~@method-body))))
(defaction move
"Move the current point in a direction"
{:keys [origin material painting?] :as ctx} [direction distance]
(let [[direction distance]
(if (neg? distance) ;; If we're negative, do the opposite thing.
[(opposite-face direction) (Math/abs distance)]
[direction distance])
d (find-relative-dir (:direction ctx) direction)
startblock (.getBlock origin)
m (i/get-material material)]
(when painting?
(doseq [i (range (or distance 1))]
(doto (.getRelative startblock (get i/blockfaces d) i)
(.setData 0)
(.setType (.getItemType m))
(.setData (.getData m)))))
(assoc ctx :origin (.getLocation (.getRelative startblock (get i/blockfaces d) (or distance 1))))))
(defn forward
"See [[move]] :north x"
[& [x]]
(move :north x))
(defn back
"See [[move]] :south x"
[& [x]]
(move :south x))
(defn left
"See [[move]] :east x"
[& [x]]
(move :east x))
(defn right
"See [[move]] :west x"
[& [x]]
(move :west x))
(defn up
"See [[move]] :up x"
[& [x]]
(move :up x))
(defn down
"See [[move]] :down x"
[& [x]]
(move :down x))
(defaction turn
"Turn the direction the current context is facing"
{:keys [direction] :as ctx} [relativedir]
(assoc ctx :direction (find-relative-dir direction relativedir)))
(defn turn-left []
(turn :east))
(defn turn-right []
(turn :west))
(defn turn-around []
(turn :south))
(defaction pen
"Do something with the 'pen', set whether it should paint as you move or not"
ctx [type]
(case type
:up (assoc ctx :painting? false)
:down (assoc ctx :painting? true)
:toggle (assoc ctx :painting? (not (:painting? ctx)))))
(defn pen-up []
(pen :up))
(defn pen-down []
(pen :down))
(defn pen-toggle []
(pen :toggle))
(defaction pen-from-mark
"Restore the pen state from mark"
ctx [mark]
(assoc :ctx :painting? (get-in ctx [:marks mark :painting?] true)))
(defaction material
"Set the current material to paint with"
ctx [material-key]
(assoc ctx :material material-key))
(defaction fork
"Run actions with ctx but don't update current ctx - effectively a subprocess"
ctx [actions]
(run-actions ctx actions)
ctx)
(defaction mark
"Stow away the state of a context into a given key"
{:keys [marks] :as ctx} [mark]
(assoc ctx :marks (assoc marks mark (dissoc ctx marks))))
(defn gen-mark
"Returns a random UUID as a string"
[]
(.toString (java.util.UUID/randomUUID)))
(defaction jump
"Jump your pointer to a given mark"
{:keys [marks] :as ctx} [mark]
(merge ctx (get marks mark {})))
(defaction copy
"Copy a sphere of a given radius into a mark"
{:keys [marks origin] :as ctx} [mark radius]
(let [distance (* radius radius)
copy-blob
(doall
(for [x (range (- 0 radius) (inc radius))
y (range (- 0 radius) (inc radius))
z (range (- 0 radius) (inc radius))
:when (<= (+ (* x x) (* y y) (* z z)) distance)]
[x y z (.getData (.getState (.getRelative (.getBlock origin) x y z)))]))
m (get-in ctx [:marks mark] {})]
(assoc ctx :marks (assoc marks mark (assoc m :copy {:blob (doall copy-blob)})))))
(defaction cut
"Cut a sphere of a given radius into a mark"
ctx [mark radius]
(let [{:keys [origin material] :as ctx} (run-action ctx (copy mark radius))
mat (i/get-material material)
distance (* radius radius)]
(doseq [x (range (- 0 radius) (inc radius))
y (range (- 0 radius) (inc radius))
z (range (- 0 radius) (inc radius))
:when (<= (+ (* x x) (* y y) (* z z)) distance)]
(let [block (.getRelative (.getBlock origin) x y z)]
(.setTypeIdAndData block (.getItemTypeId mat) (.getData mat) false)))
ctx))
(defaction paste
"Paste a previously copied or cut block against a mark"
{:keys [origin] :as ctx} [mark]
(let [{:keys [blob]} (get-in ctx [:marks mark :copy] {})]
(doseq [[x y z data] blob]
(let [block (.getRelative (.getBlock origin) x y z)]
(.setTypeIdAndData block (.getItemTypeId data) (.getData data) false)))
ctx))
(defn location-to-point [origin point]
[(- (.getX point) (.getX origin))
(- (.getY point) (.getY origin))
(- (.getZ point) (.getZ origin))])
(defaction copy-to-mark
"Copy a block to a mark"
{:keys [origin marks] :as ctx} [mark]
(let [[px py pz] (location-to-point origin (:origin (get marks mark)))
copy-blob
(doall
(for [x (range (min px 0) (max px 0))
y (range (min py 0) (max py 0))
z (range (min pz 0) (max pz 0))]
[x y z (.getData (.getState (.getRelative (.getBlock origin) x y z)))]))
m (get-in ctx [:marks mark] {})]
(assoc ctx :marks (assoc marks mark (assoc m :copy {:blob (doall copy-blob)})))))
(defaction cut-to-mark
"Cut a block to a mark, replacing everything with a given material or air if not provided"
ctx [mark]
(let [{:keys [origin marks material] :as ctx} (run-action ctx (copy-to-mark mark))
mat (i/get-material material)
[px py pz] (location-to-point origin (:origin (get marks mark)))]
(doseq [x (range (min px 0) (max px 0))
y (range (min py 0) (max py 0))
z (range (min pz 0) (max pz 0))]
(let [block (.getRelative (.getBlock origin) x y z)]
(.setTypeIdAndData block (.getItemTypeId mat) (.getData mat) false)))
ctx))
(defaction clear-mark
"Clears a mark"
ctx [mark]
(update-in ctx [:marks mark] {}))
(defn calcline
"This returns a set of points for a line"
[xt yt zt]
(if (= [xt yt zt] [0 0 0])
'([0 0 0])
(let [q (max (Math/abs xt) (Math/abs yt) (Math/abs zt))
m (/ yt q)
n (/ zt q)
o (/ xt q)]
(for [qi (range q)]
[(Math/round (double (* o qi)))
(Math/round (double (* m qi)))
(Math/round (double (* n qi)))]))))
;; to be finished......
(defaction line-to-mark
"Draw a line directly to a given mark from current point"
{:keys [origin material marks] :as ctx} [mark]
(let [originblock (.getBlock origin)
mat (i/get-material material)
point (location-to-point origin (:origin (get marks mark)))
linepoints (apply calcline point)]
(doseq [[x y z] linepoints]
(let [block (.getRelative originblock x y z)]
(.setTypeIdAndData block (.getItemTypeId mat) (.getData mat) false)))
ctx))
(defn line
"Draw a line, relative to current position and direction"
[fwd lft u]
(let [m (gen-mark)]
[(mark m)
(pen :up)
(forward fwd)
(left lft)
(up u)
(pen :down)
(line-to-mark m)
(clear-mark m)]))
(defn extrude
[direction x & actions]
(for [c (range x)]
(fork
{:action :move :direction direction :distance c}
actions)))
(defn setup-context [player-name]
{:origin (.getLocation (plr/get-player player-name))
:direction :north
:material :wool
:painting? true
:marks {}})
(comment
(def ctx (setup-context (first (.getOnlinePlayers (bk/server)))))
(defn floor-part []
[(forward 5) (turn-right) (forward 1) (turn-right) (forward 5) (turn-left) (forward 1) (turn-left)])
(defn floor []
[(floor-part) (floor-part) (floor-part) (floor-part) (floor-part) (floor-part) (floor-part) (floor-part)])
(run-actions ctx
(material :air)
(floor) (turn-around) (up) (floor))
(run-actions
ctx
(material :air)
(extrude
:up 10
(forward 10) (right 10) (back 8) (left 2) (back 2) (left 8))
)
(run-actions
ctx
;(material :air)
(line 10 10 10)
(line 1 2 3)
(line -5 0 0)
(line 0 -5 0)
(line 0 0 -5))
(bk/ui-sync
@bukkure.core/clj-plugin
#(run-actions ctx (material :air) (mark :start) (left 100) (forward 100) (up 40) (cut-to-mark :start) (clear-mark :start))))
| null | https://raw.githubusercontent.com/SevereOverfl0w/bukkure/2091d70191127e617c1a7ce12f1c7b96585f124e/src/bukkure/blocks.clj | clojure | TODO: Check this file manually
If we're negative, do the opposite thing.
to be finished......
(material :air) | (ns bukkure.blocks
(:require [bukkure.logging :as log]
[bukkure.items :as i]
[bukkure.player :as plr]
[bukkure.bukkit :as bk]))
(defn left-face
"Get the face 270deg from the given one. Stays the same for up/down"
[key]
({:up :up, :down :down
:north :east, :east :south
:south :west, :west :north} key))
(defn right-face
"Get the face 90deg from the given one. Stays the same for up/down"
[key]
({:up :up, :down :down
:north :west, :west :south
:south :east, :east :north} key))
(defn opposite-face
"Get the opposite facing direction"
[key]
({:up :down, :down :up
:north :south, :south :north
:east :west, :west :east} key))
(defn find-relative-dir
"Find relative direction, where forward is north, and left is west"
[d r]
({:north d :south (opposite-face d) :east (left-face d) :west (right-face d) :up :up :down :down} r))
(defmulti run-action (fn [ctx a] (:action a)))
(defn run-actions [ctx & actions]
(loop [a (first actions)
r (rest actions)
context ctx]
(cond
(nil? a) context
(and (coll? a) (not (map? a))) (recur (first a) (concat (rest a) r) context)
:else
(recur (first r) (rest r) (run-action context a)))))
(defmacro defaction
[name docstring ctx-binding params & method-body]
(let [params (map #(symbol (.getName (symbol %))) params)]
`(do
(defn ~name ~docstring [~@params]
(zipmap [:action ~@(map keyword params)] [~(keyword name) ~@params]))
(defmethod run-action ~(keyword name) [~ctx-binding {:keys [~@params]}]
~@method-body))))
(defaction move
"Move the current point in a direction"
{:keys [origin material painting?] :as ctx} [direction distance]
(let [[direction distance]
[(opposite-face direction) (Math/abs distance)]
[direction distance])
d (find-relative-dir (:direction ctx) direction)
startblock (.getBlock origin)
m (i/get-material material)]
(when painting?
(doseq [i (range (or distance 1))]
(doto (.getRelative startblock (get i/blockfaces d) i)
(.setData 0)
(.setType (.getItemType m))
(.setData (.getData m)))))
(assoc ctx :origin (.getLocation (.getRelative startblock (get i/blockfaces d) (or distance 1))))))
(defn forward
"See [[move]] :north x"
[& [x]]
(move :north x))
(defn back
"See [[move]] :south x"
[& [x]]
(move :south x))
(defn left
"See [[move]] :east x"
[& [x]]
(move :east x))
(defn right
"See [[move]] :west x"
[& [x]]
(move :west x))
(defn up
"See [[move]] :up x"
[& [x]]
(move :up x))
(defn down
"See [[move]] :down x"
[& [x]]
(move :down x))
(defaction turn
"Turn the direction the current context is facing"
{:keys [direction] :as ctx} [relativedir]
(assoc ctx :direction (find-relative-dir direction relativedir)))
(defn turn-left []
(turn :east))
(defn turn-right []
(turn :west))
(defn turn-around []
(turn :south))
(defaction pen
"Do something with the 'pen', set whether it should paint as you move or not"
ctx [type]
(case type
:up (assoc ctx :painting? false)
:down (assoc ctx :painting? true)
:toggle (assoc ctx :painting? (not (:painting? ctx)))))
(defn pen-up []
(pen :up))
(defn pen-down []
(pen :down))
(defn pen-toggle []
(pen :toggle))
(defaction pen-from-mark
"Restore the pen state from mark"
ctx [mark]
(assoc :ctx :painting? (get-in ctx [:marks mark :painting?] true)))
(defaction material
"Set the current material to paint with"
ctx [material-key]
(assoc ctx :material material-key))
(defaction fork
"Run actions with ctx but don't update current ctx - effectively a subprocess"
ctx [actions]
(run-actions ctx actions)
ctx)
(defaction mark
"Stow away the state of a context into a given key"
{:keys [marks] :as ctx} [mark]
(assoc ctx :marks (assoc marks mark (dissoc ctx marks))))
(defn gen-mark
"Returns a random UUID as a string"
[]
(.toString (java.util.UUID/randomUUID)))
(defaction jump
"Jump your pointer to a given mark"
{:keys [marks] :as ctx} [mark]
(merge ctx (get marks mark {})))
(defaction copy
"Copy a sphere of a given radius into a mark"
{:keys [marks origin] :as ctx} [mark radius]
(let [distance (* radius radius)
copy-blob
(doall
(for [x (range (- 0 radius) (inc radius))
y (range (- 0 radius) (inc radius))
z (range (- 0 radius) (inc radius))
:when (<= (+ (* x x) (* y y) (* z z)) distance)]
[x y z (.getData (.getState (.getRelative (.getBlock origin) x y z)))]))
m (get-in ctx [:marks mark] {})]
(assoc ctx :marks (assoc marks mark (assoc m :copy {:blob (doall copy-blob)})))))
(defaction cut
"Cut a sphere of a given radius into a mark"
ctx [mark radius]
(let [{:keys [origin material] :as ctx} (run-action ctx (copy mark radius))
mat (i/get-material material)
distance (* radius radius)]
(doseq [x (range (- 0 radius) (inc radius))
y (range (- 0 radius) (inc radius))
z (range (- 0 radius) (inc radius))
:when (<= (+ (* x x) (* y y) (* z z)) distance)]
(let [block (.getRelative (.getBlock origin) x y z)]
(.setTypeIdAndData block (.getItemTypeId mat) (.getData mat) false)))
ctx))
(defaction paste
"Paste a previously copied or cut block against a mark"
{:keys [origin] :as ctx} [mark]
(let [{:keys [blob]} (get-in ctx [:marks mark :copy] {})]
(doseq [[x y z data] blob]
(let [block (.getRelative (.getBlock origin) x y z)]
(.setTypeIdAndData block (.getItemTypeId data) (.getData data) false)))
ctx))
(defn location-to-point [origin point]
[(- (.getX point) (.getX origin))
(- (.getY point) (.getY origin))
(- (.getZ point) (.getZ origin))])
(defaction copy-to-mark
"Copy a block to a mark"
{:keys [origin marks] :as ctx} [mark]
(let [[px py pz] (location-to-point origin (:origin (get marks mark)))
copy-blob
(doall
(for [x (range (min px 0) (max px 0))
y (range (min py 0) (max py 0))
z (range (min pz 0) (max pz 0))]
[x y z (.getData (.getState (.getRelative (.getBlock origin) x y z)))]))
m (get-in ctx [:marks mark] {})]
(assoc ctx :marks (assoc marks mark (assoc m :copy {:blob (doall copy-blob)})))))
(defaction cut-to-mark
"Cut a block to a mark, replacing everything with a given material or air if not provided"
ctx [mark]
(let [{:keys [origin marks material] :as ctx} (run-action ctx (copy-to-mark mark))
mat (i/get-material material)
[px py pz] (location-to-point origin (:origin (get marks mark)))]
(doseq [x (range (min px 0) (max px 0))
y (range (min py 0) (max py 0))
z (range (min pz 0) (max pz 0))]
(let [block (.getRelative (.getBlock origin) x y z)]
(.setTypeIdAndData block (.getItemTypeId mat) (.getData mat) false)))
ctx))
(defaction clear-mark
"Clears a mark"
ctx [mark]
(update-in ctx [:marks mark] {}))
(defn calcline
"This returns a set of points for a line"
[xt yt zt]
(if (= [xt yt zt] [0 0 0])
'([0 0 0])
(let [q (max (Math/abs xt) (Math/abs yt) (Math/abs zt))
m (/ yt q)
n (/ zt q)
o (/ xt q)]
(for [qi (range q)]
[(Math/round (double (* o qi)))
(Math/round (double (* m qi)))
(Math/round (double (* n qi)))]))))
(defaction line-to-mark
"Draw a line directly to a given mark from current point"
{:keys [origin material marks] :as ctx} [mark]
(let [originblock (.getBlock origin)
mat (i/get-material material)
point (location-to-point origin (:origin (get marks mark)))
linepoints (apply calcline point)]
(doseq [[x y z] linepoints]
(let [block (.getRelative originblock x y z)]
(.setTypeIdAndData block (.getItemTypeId mat) (.getData mat) false)))
ctx))
(defn line
"Draw a line, relative to current position and direction"
[fwd lft u]
(let [m (gen-mark)]
[(mark m)
(pen :up)
(forward fwd)
(left lft)
(up u)
(pen :down)
(line-to-mark m)
(clear-mark m)]))
(defn extrude
[direction x & actions]
(for [c (range x)]
(fork
{:action :move :direction direction :distance c}
actions)))
(defn setup-context [player-name]
{:origin (.getLocation (plr/get-player player-name))
:direction :north
:material :wool
:painting? true
:marks {}})
(comment
(def ctx (setup-context (first (.getOnlinePlayers (bk/server)))))
(defn floor-part []
[(forward 5) (turn-right) (forward 1) (turn-right) (forward 5) (turn-left) (forward 1) (turn-left)])
(defn floor []
[(floor-part) (floor-part) (floor-part) (floor-part) (floor-part) (floor-part) (floor-part) (floor-part)])
(run-actions ctx
(material :air)
(floor) (turn-around) (up) (floor))
(run-actions
ctx
(material :air)
(extrude
:up 10
(forward 10) (right 10) (back 8) (left 2) (back 2) (left 8))
)
(run-actions
ctx
(line 10 10 10)
(line 1 2 3)
(line -5 0 0)
(line 0 -5 0)
(line 0 0 -5))
(bk/ui-sync
@bukkure.core/clj-plugin
#(run-actions ctx (material :air) (mark :start) (left 100) (forward 100) (up 40) (cut-to-mark :start) (clear-mark :start))))
|
69978b4816dd8722e30ef01c5eda8a599e2faeb84ef146c546838e4b318cd623 | pjotrp/guix | algebra.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2012 , 2013 , 2014 , 2015 < >
Copyright © 2013 , 2015 < >
Copyright © 2014 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages algebra)
#:use-module (gnu packages)
#:use-module (gnu packages compression)
#:use-module (gnu packages multiprecision)
#:use-module (gnu packages mpi)
#:use-module (gnu packages perl)
#:use-module (gnu packages readline)
#:use-module (gnu packages flex)
#:use-module (gnu packages xorg)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix build-system gnu)
#:use-module (guix build-system cmake)
#:use-module (guix utils))
(define-public mpfrcx
(package
(name "mpfrcx")
(version "0.4.2")
(source (origin
(method url-fetch)
(uri (string-append
"-"
version ".tar.gz"))
(sha256
(base32
"0grw66b255r574lvll1bqccm5myj2m8ajzsjaygcyq9zjnnbnhhy"))))
(build-system gnu-build-system)
(propagated-inputs
`(("gmp" ,gmp)
("mpfr" ,mpfr)
Header files are included by mpfrcx.h .
(synopsis "Arithmetic of polynomials over arbitrary precision numbers")
(description
"Mpfrcx is a library for the arithmetic of univariate polynomials over
arbitrary precision real (mpfr) or complex (mpc) numbers, without control
on the rounding. For the time being, only the few functions needed to
implement the floating point approach to complex multiplication are
implemented. On the other hand, these comprise asymptotically fast
multiplication routines such as Toom–Cook and the FFT.")
(license license:lgpl2.1+)
(home-page "/")))
(define-public cm
(package
(name "cm")
(version "0.2.1")
(source (origin
(method url-fetch)
(uri (string-append
"-"
version ".tar.gz"))
(sha256
(base32
"1r5dx5qy0ka2sq26n9jll9iy4sjqg0jp5r3jnbjhpgxvmj8jbhq8"))))
(build-system gnu-build-system)
(propagated-inputs
`(("mpfrcx" ,mpfrcx)
("zlib" ,zlib))) ; Header files included from cm_common.h.
(inputs
`(("pari-gp" ,pari-gp)))
(synopsis "CM constructions for elliptic curves")
(description
"The CM software implements the construction of ring class fields of
imaginary quadratic number fields and of elliptic curves with complex
multiplication via floating point approximations. It consists of libraries
that can be called from within a C program and of executable command
line applications.")
(license license:gpl2+)
(home-page "/")))
(define-public fplll
(package
(name "fplll")
(version "4.0.4")
(source (origin
(method url-fetch)
(uri (string-append
"-lyon.fr/damien.stehle/fplll/libfplll-"
version ".tar.gz"))
(sha256 (base32
"1cbiby7ykis4z84swclpysrljmqhfcllpkcbll1m08rzskgb1a6b"))))
(build-system gnu-build-system)
(inputs `(("gmp" ,gmp)
("mpfr" ,mpfr)))
(synopsis "Library for LLL-reduction of euclidean lattices")
(description
"fplll LLL-reduces euclidean lattices. Since version 3, it can also
solve the shortest vector problem.")
(license license:lgpl2.1+)
(home-page "-lyon.fr/damien.stehle/fplll/")))
(define-public pari-gp
(package
(name "pari-gp")
(version "2.7.5")
(source (origin
(method url-fetch)
(uri (string-append
"-bordeaux.fr/pub/pari/unix/pari-"
version ".tar.gz"))
(sha256
(base32
"0c8l83a0gjq73r9hndsrzkypwxvnnm4pxkkzbg6jm95m80nzwh11"))))
(build-system gnu-build-system)
(inputs `(("gmp" ,gmp)
("libx11" ,libx11)
("perl" ,perl)
("readline" ,readline)))
(arguments
'(#:make-flags '("gp")
;; FIXME: building the documentation requires tex; once this is
;; available, replace "gp" by "all"
#:test-target "dobench"
#:phases
(alist-replace
'configure
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(zero?
(system* "./Configure" (string-append "--prefix=" out)))))
%standard-phases)))
(synopsis "PARI/GP, a computer algebra system for number theory")
(description
"PARI/GP is a widely used computer algebra system designed for fast
computations in number theory (factorisations, algebraic number theory,
elliptic curves...), but it also contains a large number of other useful
functions to compute with mathematical entities such as matrices,
polynomials, power series, algebraic numbers, etc., and a lot of
transcendental functions.
PARI is also available as a C library to allow for faster computations.")
(license license:gpl2+)
(home-page "-bordeaux.fr/")))
(define-public gp2c
(package
(name "gp2c")
(version "0.0.9pl4")
(source (origin
(method url-fetch)
(uri (string-append
"-bordeaux.fr/pub/pari/GP2C/gp2c-"
version ".tar.gz"))
(sha256
(base32
"079qq4yyxpc53a2kn08gg9pcfgdyffbl14c2hqsic11q8pnsr08z"))))
(build-system gnu-build-system)
(native-inputs `(("perl" ,perl)))
(inputs `(("pari-gp" ,pari-gp)))
(arguments
'(#:configure-flags
(list (string-append "--with-paricfg="
(assoc-ref %build-inputs "pari-gp")
"/lib/pari/pari.cfg"))))
(synopsis "PARI/GP, a computer algebra system for number theory")
(description
"PARI/GP is a widely used computer algebra system designed for fast
computations in number theory (factorisations, algebraic number theory,
elliptic curves...), but it also contains a large number of other useful
functions to compute with mathematical entities such as matrices,
polynomials, power series, algebraic numbers, etc., and a lot of
transcendental functions.
PARI is also available as a C library to allow for faster computations.
GP2C, the GP to C compiler, translates GP scripts to PARI programs.")
(license license:gpl2)
(home-page "-bordeaux.fr/")))
(define-public flint
(package
(name "flint")
(version "2.5.2")
(source (origin
(method url-fetch)
(uri (string-append
"-"
version ".tar.gz"))
(sha256 (base32
"11syazv1a8rrnac3wj3hnyhhflpqcmq02q8pqk2m6g2k6h0gxwfb"))
(patches (map search-patch '("flint-ldconfig.patch")))))
(build-system gnu-build-system)
(propagated-inputs
`(("gmp" ,gmp)
("mpfr" ,mpfr))) ; header files from both are included by flint/arith.h
(arguments
`(#:parallel-tests? #f ; seems to be necessary on arm
#:phases
(modify-phases %standard-phases
(replace 'configure
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out"))
(gmp (assoc-ref inputs "gmp"))
(mpfr (assoc-ref inputs "mpfr")))
;; do not pass "--enable-fast-install", which makes the
;; homebrew configure process fail
(zero? (system*
"./configure"
(string-append "--prefix=" out)
(string-append "--with-gmp=" gmp)
(string-append "--with-mpfr=" mpfr)))))))))
(synopsis "Fast library for number theory")
(description
"FLINT is a C library for number theory. It supports arithmetic
with numbers, polynomials, power series and matrices over many base
rings, including multiprecision integers and rationals, integers
modulo n, p-adic numbers, finite fields (prime and non-prime order)
and real and complex numbers (via the Arb extension library).
Operations that can be performed include conversions, arithmetic,
GCDs, factoring, solving linear systems, and evaluating special
functions. In addition, FLINT provides various low-level routines for
fast arithmetic.")
(license license:gpl2+)
(home-page "/")))
(define-public arb
(package
(name "arb")
(version "2.7.0")
(source (origin
(method url-fetch)
(uri (string-append
"-johansson/arb/archive/"
version ".tar.gz"))
(file-name (string-append name "-" version ".tar.gz"))
(sha256
(base32
"1rwkffs57v8mry63rq8l2dyw69zfs9rg5fpbfllqp3nkjnkp1fly"))))
(build-system gnu-build-system)
(propagated-inputs
`(("flint" ,flint))) ; flint.h is included by arf.h
(inputs
`(("gmp" ,gmp)
("mpfr" ,mpfr)))
(arguments
`(#:phases
(alist-replace
'configure
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out"))
(flint (assoc-ref inputs "flint"))
(gmp (assoc-ref inputs "gmp"))
(mpfr (assoc-ref inputs "mpfr")))
;; do not pass "--enable-fast-install", which makes the
;; homebrew configure process fail
(zero? (system*
"./configure"
(string-append "--prefix=" out)
(string-append "--with-flint=" flint)
(string-append "--with-gmp=" gmp)
(string-append "--with-mpfr=" mpfr)))))
%standard-phases)))
(synopsis "Arbitrary precision floating-point ball arithmetic")
(description
"Arb is a C library for arbitrary-precision floating-point ball
arithmetic. It supports efficient high-precision computation with
polynomials, power series, matrices and special functions over the
real and complex numbers, with automatic, rigorous error control.")
(license license:gpl2+)
(home-page "/")))
(define-public bc
(package
(name "bc")
(version "1.06")
(source (origin
(method url-fetch)
(uri (string-append "mirror-" version ".tar.gz"))
(sha256
(base32
"0cqf5jkwx6awgd2xc2a0mkpxilzcfmhncdcfg7c9439wgkqxkxjf"))))
(build-system gnu-build-system)
(inputs `(("readline" ,readline)))
(native-inputs `(("flex" ,flex)))
(arguments
'(#:phases
(alist-replace 'configure
(lambda* (#:key outputs #:allow-other-keys)
;; This old `configure' script doesn't support
;; variables passed as arguments.
(let ((out (assoc-ref outputs "out")))
(setenv "CONFIG_SHELL" (which "bash"))
(zero?
(system*
"./configure"
(string-append "--prefix=" out)
;; By default, man and info pages are put in
;; PREFIX/{man,info}, but we want them in
;; PREFIX/share/{man,info}.
(string-append "--mandir=" out "/share/man")
(string-append "--infodir=" out "/share/info")))))
%standard-phases)))
(home-page "/")
(synopsis "Arbitrary precision numeric processing language")
(description
"bc is an arbitrary precision numeric processing language. It includes
an interactive environment for evaluating mathematical statements. Its
syntax is similar to that of C, so basic usage is familiar. It also includes
\"dc\", a reverse-polish calculator.")
(license license:gpl2+)))
(define-public fftw
(package
(name "fftw")
(version "3.3.4")
(source (origin
(method url-fetch)
(uri (string-append "ftp-"
version".tar.gz"))
(sha256
(base32
"10h9mzjxnwlsjziah4lri85scc05rlajz39nqf3mbh4vja8dw34g"))))
(build-system gnu-build-system)
(arguments
'(#:configure-flags '("--enable-shared" "--enable-openmp")
#:phases (alist-cons-before
'build 'no-native
(lambda _
By default ' -mtune = native ' is used . However , that may
cause the use of ISA extensions ( SSE2 , etc . ) that are
;; not necessarily available on the user's machine when
;; that package is built on a different machine.
(substitute* (find-files "." "Makefile$")
(("-mtune=native") "")))
%standard-phases)))
(native-inputs `(("perl" ,perl)))
(home-page "")
(synopsis "Computing the discrete Fourier transform")
(description
"FFTW is a C subroutine library for computing the discrete Fourier
transform (DFT) in one or more dimensions, of arbitrary input size, and of
both real and complex data (as well as of even/odd data---i.e. the discrete
cosine/ sine transforms or DCT/DST).")
(license license:gpl2+)))
(define-public fftwf
(package (inherit fftw)
(name "fftwf")
(arguments
(substitute-keyword-arguments (package-arguments fftw)
((#:configure-flags cf)
`(cons "--enable-float" ,cf))))
(description
(string-append (package-description fftw)
" Single-precision version."))))
(define-public fftw-openmpi
(package (inherit fftw)
(name "fftw-openmpi")
(inputs
`(("openmpi" ,openmpi)
,@(package-inputs fftw)))
(arguments
(substitute-keyword-arguments (package-arguments fftw)
((#:configure-flags cf)
`(cons "--enable-mpi" ,cf))))
(description
(string-append (package-description fftw)
" With OpenMPI parallelism support."))))
(define-public eigen
(package
(name "eigen")
(version "3.2.7")
(source (origin
(method url-fetch)
(uri (string-append "/"
version ".tar.bz2"))
(sha256
(base32
"0gigbjjdlw2q0gvcnyiwc6in314a647rkidk6977bwiwn88im3p5"))
(file-name (string-append name "-" version ".tar.bz2"))
(modules '((guix build utils)))
(snippet
There are 3 test failures in the " unsupported " directory ,
;; but maintainers say it's a known issue and it's unsupported
;; anyway, so just skip them.
'(substitute* "CMakeLists.txt"
(("add_subdirectory\\(unsupported\\)")
"# Do not build the tests for unsupported features.\n")
;; Work around
;; <>.
(("\"include/eigen3\"")
"\"${CMAKE_INSTALL_PREFIX}/include/eigen3\"")))))
(build-system cmake-build-system)
(arguments
'(;; Turn off debugging symbols to save space.
#:build-type "Release"
#:phases (modify-phases %standard-phases
(replace 'check
(lambda _
(let* ((cores (parallel-job-count))
(dash-j (format #f "-j~a" cores)))
First build the tests , in parallel . See
< > .
(and (zero? (system* "make" "buildtests" dash-j))
Then run ' CTest ' with -V so we get more
;; details upon failure.
(zero? (system* "ctest" "-V" dash-j)))))))))
(home-page "")
(synopsis "C++ template library for linear algebra")
(description
"Eigen is a C++ template library for linear algebra: matrices, vectors,
numerical solvers, and related algorithms. It provides an elegant API based
on \"expression templates\". It is versatile: it supports all matrix sizes,
all standard numeric types, various matrix decompositions and geometry
features, and more.")
Most of the code is MPLv2 , with a few files under + or BSD-3 .
;; See 'COPYING.README' for details.
(license license:mpl2.0)))
| null | https://raw.githubusercontent.com/pjotrp/guix/96250294012c2f1520b67f12ea80bfd6b98075a2/gnu/packages/algebra.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Header files included from cm_common.h.
FIXME: building the documentation requires tex; once this is
available, replace "gp" by "all"
header files from both are included by flint/arith.h
seems to be necessary on arm
do not pass "--enable-fast-install", which makes the
homebrew configure process fail
flint.h is included by arf.h
do not pass "--enable-fast-install", which makes the
homebrew configure process fail
This old `configure' script doesn't support
variables passed as arguments.
By default, man and info pages are put in
PREFIX/{man,info}, but we want them in
PREFIX/share/{man,info}.
not necessarily available on the user's machine when
that package is built on a different machine.
but maintainers say it's a known issue and it's unsupported
anyway, so just skip them.
Work around
<>.
Turn off debugging symbols to save space.
details upon failure.
See 'COPYING.README' for details. | Copyright © 2012 , 2013 , 2014 , 2015 < >
Copyright © 2013 , 2015 < >
Copyright © 2014 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages algebra)
#:use-module (gnu packages)
#:use-module (gnu packages compression)
#:use-module (gnu packages multiprecision)
#:use-module (gnu packages mpi)
#:use-module (gnu packages perl)
#:use-module (gnu packages readline)
#:use-module (gnu packages flex)
#:use-module (gnu packages xorg)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix build-system gnu)
#:use-module (guix build-system cmake)
#:use-module (guix utils))
(define-public mpfrcx
(package
(name "mpfrcx")
(version "0.4.2")
(source (origin
(method url-fetch)
(uri (string-append
"-"
version ".tar.gz"))
(sha256
(base32
"0grw66b255r574lvll1bqccm5myj2m8ajzsjaygcyq9zjnnbnhhy"))))
(build-system gnu-build-system)
(propagated-inputs
`(("gmp" ,gmp)
("mpfr" ,mpfr)
Header files are included by mpfrcx.h .
(synopsis "Arithmetic of polynomials over arbitrary precision numbers")
(description
"Mpfrcx is a library for the arithmetic of univariate polynomials over
arbitrary precision real (mpfr) or complex (mpc) numbers, without control
on the rounding. For the time being, only the few functions needed to
implement the floating point approach to complex multiplication are
implemented. On the other hand, these comprise asymptotically fast
multiplication routines such as Toom–Cook and the FFT.")
(license license:lgpl2.1+)
(home-page "/")))
(define-public cm
(package
(name "cm")
(version "0.2.1")
(source (origin
(method url-fetch)
(uri (string-append
"-"
version ".tar.gz"))
(sha256
(base32
"1r5dx5qy0ka2sq26n9jll9iy4sjqg0jp5r3jnbjhpgxvmj8jbhq8"))))
(build-system gnu-build-system)
(propagated-inputs
`(("mpfrcx" ,mpfrcx)
(inputs
`(("pari-gp" ,pari-gp)))
(synopsis "CM constructions for elliptic curves")
(description
"The CM software implements the construction of ring class fields of
imaginary quadratic number fields and of elliptic curves with complex
multiplication via floating point approximations. It consists of libraries
that can be called from within a C program and of executable command
line applications.")
(license license:gpl2+)
(home-page "/")))
(define-public fplll
(package
(name "fplll")
(version "4.0.4")
(source (origin
(method url-fetch)
(uri (string-append
"-lyon.fr/damien.stehle/fplll/libfplll-"
version ".tar.gz"))
(sha256 (base32
"1cbiby7ykis4z84swclpysrljmqhfcllpkcbll1m08rzskgb1a6b"))))
(build-system gnu-build-system)
(inputs `(("gmp" ,gmp)
("mpfr" ,mpfr)))
(synopsis "Library for LLL-reduction of euclidean lattices")
(description
"fplll LLL-reduces euclidean lattices. Since version 3, it can also
solve the shortest vector problem.")
(license license:lgpl2.1+)
(home-page "-lyon.fr/damien.stehle/fplll/")))
(define-public pari-gp
(package
(name "pari-gp")
(version "2.7.5")
(source (origin
(method url-fetch)
(uri (string-append
"-bordeaux.fr/pub/pari/unix/pari-"
version ".tar.gz"))
(sha256
(base32
"0c8l83a0gjq73r9hndsrzkypwxvnnm4pxkkzbg6jm95m80nzwh11"))))
(build-system gnu-build-system)
(inputs `(("gmp" ,gmp)
("libx11" ,libx11)
("perl" ,perl)
("readline" ,readline)))
(arguments
'(#:make-flags '("gp")
#:test-target "dobench"
#:phases
(alist-replace
'configure
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(zero?
(system* "./Configure" (string-append "--prefix=" out)))))
%standard-phases)))
(synopsis "PARI/GP, a computer algebra system for number theory")
(description
"PARI/GP is a widely used computer algebra system designed for fast
computations in number theory (factorisations, algebraic number theory,
elliptic curves...), but it also contains a large number of other useful
functions to compute with mathematical entities such as matrices,
polynomials, power series, algebraic numbers, etc., and a lot of
transcendental functions.
PARI is also available as a C library to allow for faster computations.")
(license license:gpl2+)
(home-page "-bordeaux.fr/")))
(define-public gp2c
(package
(name "gp2c")
(version "0.0.9pl4")
(source (origin
(method url-fetch)
(uri (string-append
"-bordeaux.fr/pub/pari/GP2C/gp2c-"
version ".tar.gz"))
(sha256
(base32
"079qq4yyxpc53a2kn08gg9pcfgdyffbl14c2hqsic11q8pnsr08z"))))
(build-system gnu-build-system)
(native-inputs `(("perl" ,perl)))
(inputs `(("pari-gp" ,pari-gp)))
(arguments
'(#:configure-flags
(list (string-append "--with-paricfg="
(assoc-ref %build-inputs "pari-gp")
"/lib/pari/pari.cfg"))))
(synopsis "PARI/GP, a computer algebra system for number theory")
(description
"PARI/GP is a widely used computer algebra system designed for fast
computations in number theory (factorisations, algebraic number theory,
elliptic curves...), but it also contains a large number of other useful
functions to compute with mathematical entities such as matrices,
polynomials, power series, algebraic numbers, etc., and a lot of
transcendental functions.
PARI is also available as a C library to allow for faster computations.
GP2C, the GP to C compiler, translates GP scripts to PARI programs.")
(license license:gpl2)
(home-page "-bordeaux.fr/")))
(define-public flint
(package
(name "flint")
(version "2.5.2")
(source (origin
(method url-fetch)
(uri (string-append
"-"
version ".tar.gz"))
(sha256 (base32
"11syazv1a8rrnac3wj3hnyhhflpqcmq02q8pqk2m6g2k6h0gxwfb"))
(patches (map search-patch '("flint-ldconfig.patch")))))
(build-system gnu-build-system)
(propagated-inputs
`(("gmp" ,gmp)
(arguments
#:phases
(modify-phases %standard-phases
(replace 'configure
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out"))
(gmp (assoc-ref inputs "gmp"))
(mpfr (assoc-ref inputs "mpfr")))
(zero? (system*
"./configure"
(string-append "--prefix=" out)
(string-append "--with-gmp=" gmp)
(string-append "--with-mpfr=" mpfr)))))))))
(synopsis "Fast library for number theory")
(description
"FLINT is a C library for number theory. It supports arithmetic
with numbers, polynomials, power series and matrices over many base
rings, including multiprecision integers and rationals, integers
modulo n, p-adic numbers, finite fields (prime and non-prime order)
and real and complex numbers (via the Arb extension library).
Operations that can be performed include conversions, arithmetic,
GCDs, factoring, solving linear systems, and evaluating special
functions. In addition, FLINT provides various low-level routines for
fast arithmetic.")
(license license:gpl2+)
(home-page "/")))
(define-public arb
(package
(name "arb")
(version "2.7.0")
(source (origin
(method url-fetch)
(uri (string-append
"-johansson/arb/archive/"
version ".tar.gz"))
(file-name (string-append name "-" version ".tar.gz"))
(sha256
(base32
"1rwkffs57v8mry63rq8l2dyw69zfs9rg5fpbfllqp3nkjnkp1fly"))))
(build-system gnu-build-system)
(propagated-inputs
(inputs
`(("gmp" ,gmp)
("mpfr" ,mpfr)))
(arguments
`(#:phases
(alist-replace
'configure
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out"))
(flint (assoc-ref inputs "flint"))
(gmp (assoc-ref inputs "gmp"))
(mpfr (assoc-ref inputs "mpfr")))
(zero? (system*
"./configure"
(string-append "--prefix=" out)
(string-append "--with-flint=" flint)
(string-append "--with-gmp=" gmp)
(string-append "--with-mpfr=" mpfr)))))
%standard-phases)))
(synopsis "Arbitrary precision floating-point ball arithmetic")
(description
"Arb is a C library for arbitrary-precision floating-point ball
arithmetic. It supports efficient high-precision computation with
polynomials, power series, matrices and special functions over the
real and complex numbers, with automatic, rigorous error control.")
(license license:gpl2+)
(home-page "/")))
(define-public bc
(package
(name "bc")
(version "1.06")
(source (origin
(method url-fetch)
(uri (string-append "mirror-" version ".tar.gz"))
(sha256
(base32
"0cqf5jkwx6awgd2xc2a0mkpxilzcfmhncdcfg7c9439wgkqxkxjf"))))
(build-system gnu-build-system)
(inputs `(("readline" ,readline)))
(native-inputs `(("flex" ,flex)))
(arguments
'(#:phases
(alist-replace 'configure
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(setenv "CONFIG_SHELL" (which "bash"))
(zero?
(system*
"./configure"
(string-append "--prefix=" out)
(string-append "--mandir=" out "/share/man")
(string-append "--infodir=" out "/share/info")))))
%standard-phases)))
(home-page "/")
(synopsis "Arbitrary precision numeric processing language")
(description
"bc is an arbitrary precision numeric processing language. It includes
an interactive environment for evaluating mathematical statements. Its
syntax is similar to that of C, so basic usage is familiar. It also includes
\"dc\", a reverse-polish calculator.")
(license license:gpl2+)))
(define-public fftw
(package
(name "fftw")
(version "3.3.4")
(source (origin
(method url-fetch)
(uri (string-append "ftp-"
version".tar.gz"))
(sha256
(base32
"10h9mzjxnwlsjziah4lri85scc05rlajz39nqf3mbh4vja8dw34g"))))
(build-system gnu-build-system)
(arguments
'(#:configure-flags '("--enable-shared" "--enable-openmp")
#:phases (alist-cons-before
'build 'no-native
(lambda _
By default ' -mtune = native ' is used . However , that may
cause the use of ISA extensions ( SSE2 , etc . ) that are
(substitute* (find-files "." "Makefile$")
(("-mtune=native") "")))
%standard-phases)))
(native-inputs `(("perl" ,perl)))
(home-page "")
(synopsis "Computing the discrete Fourier transform")
(description
"FFTW is a C subroutine library for computing the discrete Fourier
transform (DFT) in one or more dimensions, of arbitrary input size, and of
both real and complex data (as well as of even/odd data---i.e. the discrete
cosine/ sine transforms or DCT/DST).")
(license license:gpl2+)))
(define-public fftwf
(package (inherit fftw)
(name "fftwf")
(arguments
(substitute-keyword-arguments (package-arguments fftw)
((#:configure-flags cf)
`(cons "--enable-float" ,cf))))
(description
(string-append (package-description fftw)
" Single-precision version."))))
(define-public fftw-openmpi
(package (inherit fftw)
(name "fftw-openmpi")
(inputs
`(("openmpi" ,openmpi)
,@(package-inputs fftw)))
(arguments
(substitute-keyword-arguments (package-arguments fftw)
((#:configure-flags cf)
`(cons "--enable-mpi" ,cf))))
(description
(string-append (package-description fftw)
" With OpenMPI parallelism support."))))
(define-public eigen
(package
(name "eigen")
(version "3.2.7")
(source (origin
(method url-fetch)
(uri (string-append "/"
version ".tar.bz2"))
(sha256
(base32
"0gigbjjdlw2q0gvcnyiwc6in314a647rkidk6977bwiwn88im3p5"))
(file-name (string-append name "-" version ".tar.bz2"))
(modules '((guix build utils)))
(snippet
There are 3 test failures in the " unsupported " directory ,
'(substitute* "CMakeLists.txt"
(("add_subdirectory\\(unsupported\\)")
"# Do not build the tests for unsupported features.\n")
(("\"include/eigen3\"")
"\"${CMAKE_INSTALL_PREFIX}/include/eigen3\"")))))
(build-system cmake-build-system)
(arguments
#:build-type "Release"
#:phases (modify-phases %standard-phases
(replace 'check
(lambda _
(let* ((cores (parallel-job-count))
(dash-j (format #f "-j~a" cores)))
First build the tests , in parallel . See
< > .
(and (zero? (system* "make" "buildtests" dash-j))
Then run ' CTest ' with -V so we get more
(zero? (system* "ctest" "-V" dash-j)))))))))
(home-page "")
(synopsis "C++ template library for linear algebra")
(description
"Eigen is a C++ template library for linear algebra: matrices, vectors,
numerical solvers, and related algorithms. It provides an elegant API based
on \"expression templates\". It is versatile: it supports all matrix sizes,
all standard numeric types, various matrix decompositions and geometry
features, and more.")
Most of the code is MPLv2 , with a few files under + or BSD-3 .
(license license:mpl2.0)))
|
57a6cd71bc9166fef3e48528caef4005d5e9544e861d815348c9f5efc39b89ef | omcljs/om | core.cljs | (ns examples.verify.core
(:require [om.core :as om :include-macros true]
[om.dom :as dom :include-macros true]))
(enable-console-print!)
(defn mincase [data owner]
(reify
om/IWillUpdate
(will-update [this next-props next-state]
(.log js/console "om/IWillUpdate invoked"))
om/IRender
(render [_]
(dom/div #js {:className "mincase"}
(when (:click-to-fail data) (dom/span nil "Clicked!"))
(dom/a
#js {:onClick #(om/update! data :click-to-fail :done)}
"Click me to trigger failure")))))
(om/root mincase
(atom {})
{:target (.getElementById js/document "app")})
| null | https://raw.githubusercontent.com/omcljs/om/3a1fbe9c0e282646fc58550139b491ff9869f96d/examples/verify/src/core.cljs | clojure | (ns examples.verify.core
(:require [om.core :as om :include-macros true]
[om.dom :as dom :include-macros true]))
(enable-console-print!)
(defn mincase [data owner]
(reify
om/IWillUpdate
(will-update [this next-props next-state]
(.log js/console "om/IWillUpdate invoked"))
om/IRender
(render [_]
(dom/div #js {:className "mincase"}
(when (:click-to-fail data) (dom/span nil "Clicked!"))
(dom/a
#js {:onClick #(om/update! data :click-to-fail :done)}
"Click me to trigger failure")))))
(om/root mincase
(atom {})
{:target (.getElementById js/document "app")})
| |
4008ff000ff3d158b264fb830669dd651eee28539bd6d7a36667d9cd1f4ec4e4 | Oblosys/proxima | GrammarInfo.hs | module GrammarInfo where
import SequentialTypes
import CodeSyntax
import Data.Map(Map)
import qualified Data.Map as Map
import Data.Set(Set)
import qualified Data.Set as Set
import CommonTypes
import Data.List(intersect,(\\))
type LMH = (Vertex,Vertex,Vertex)
data Info = Info { tdpToTds :: Table Vertex
, tdsToTdp :: Table [Vertex]
, attrTable :: Table NTAttr
, ruleTable :: Table CRule
, lmh :: [LMH]
, nonts :: [(NontermIdent,[ConstructorIdent])]
, wraps :: Set NontermIdent
}
deriving Show
instance Show CRule
where show (CRule name isIn hasCode nt con field childnt tp pattern rhs defines owrt origin uses)
= "CRule " ++ show name ++ " nt: " ++ show nt ++ " con: " ++ show con ++ " field: " ++ show field
++ " childnt: " ++ show childnt ++ " rhs: " ++ concat rhs ++ " uses: " ++ show [ attrname True fld nm | (fld,nm) <- Set.toList uses ]
type CInterfaceMap = Map NontermIdent CInterface
type CVisitsMap = Map NontermIdent (Map ConstructorIdent CVisits)
data CycleStatus
= CycleFree CInterfaceMap CVisitsMap
| LocalCycle [Route]
| InstCycle [Route]
| DirectCycle [EdgeRoutes]
| InducedCycle CInterfaceMap [EdgeRoutes]
showsSegment :: CSegment -> [String]
showsSegment (CSegment inh syn)
= let syn' = map toString (Map.toList syn)
inh' = map toString (Map.toList inh)
toString (a,t) = (getName a, case t of (NT nt tps) -> getName nt ++ " " ++ unwords tps; Haskell t -> t)
chnn = inh' `intersect` syn'
inhn = inh' \\ chnn
synn = syn' \\ chnn
disp name [] = []
disp name as = (name ++ if length as == 1 then " attribute:" else " attributes:") :
map (\(x,y) -> ind x ++ replicate ((20 - length x) `max` 0) ' ' ++ " : " ++ y) as
in disp "inherited" inhn
++ disp "chained" chnn
++ disp "synthesized" synn
| null | https://raw.githubusercontent.com/Oblosys/proxima/f154dff2ccb8afe00eeb325d9d06f5e2a5ee7589/uuagc/src/GrammarInfo.hs | haskell | module GrammarInfo where
import SequentialTypes
import CodeSyntax
import Data.Map(Map)
import qualified Data.Map as Map
import Data.Set(Set)
import qualified Data.Set as Set
import CommonTypes
import Data.List(intersect,(\\))
type LMH = (Vertex,Vertex,Vertex)
data Info = Info { tdpToTds :: Table Vertex
, tdsToTdp :: Table [Vertex]
, attrTable :: Table NTAttr
, ruleTable :: Table CRule
, lmh :: [LMH]
, nonts :: [(NontermIdent,[ConstructorIdent])]
, wraps :: Set NontermIdent
}
deriving Show
instance Show CRule
where show (CRule name isIn hasCode nt con field childnt tp pattern rhs defines owrt origin uses)
= "CRule " ++ show name ++ " nt: " ++ show nt ++ " con: " ++ show con ++ " field: " ++ show field
++ " childnt: " ++ show childnt ++ " rhs: " ++ concat rhs ++ " uses: " ++ show [ attrname True fld nm | (fld,nm) <- Set.toList uses ]
type CInterfaceMap = Map NontermIdent CInterface
type CVisitsMap = Map NontermIdent (Map ConstructorIdent CVisits)
data CycleStatus
= CycleFree CInterfaceMap CVisitsMap
| LocalCycle [Route]
| InstCycle [Route]
| DirectCycle [EdgeRoutes]
| InducedCycle CInterfaceMap [EdgeRoutes]
showsSegment :: CSegment -> [String]
showsSegment (CSegment inh syn)
= let syn' = map toString (Map.toList syn)
inh' = map toString (Map.toList inh)
toString (a,t) = (getName a, case t of (NT nt tps) -> getName nt ++ " " ++ unwords tps; Haskell t -> t)
chnn = inh' `intersect` syn'
inhn = inh' \\ chnn
synn = syn' \\ chnn
disp name [] = []
disp name as = (name ++ if length as == 1 then " attribute:" else " attributes:") :
map (\(x,y) -> ind x ++ replicate ((20 - length x) `max` 0) ' ' ++ " : " ++ y) as
in disp "inherited" inhn
++ disp "chained" chnn
++ disp "synthesized" synn
| |
d462ed96205a5e66cd9d7409ee8491046a0c169d0a3ac508cf195f05d83006ea | brianhempel/maniposynth | map.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
module type OrderedType =
sig
type t
val compare: t -> t -> int
end
module type S =
sig
type key
type +'a t
val empty: 'a t
val is_empty: 'a t -> bool
val mem: key -> 'a t -> bool
val add: key -> 'a -> 'a t -> 'a t
val update: key -> ('a option -> 'a option) -> 'a t -> 'a t
val singleton: key -> 'a -> 'a t
val remove: key -> 'a t -> 'a t
val merge:
(key -> 'a option -> 'b option -> 'c option) -> 'a t -> 'b t -> 'c t
val union: (key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t
val compare: ('a -> 'a -> int) -> 'a t -> 'a t -> int
val equal: ('a -> 'a -> bool) -> 'a t -> 'a t -> bool
val iter: (key -> 'a -> unit) -> 'a t -> unit
val fold: (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
val for_all: (key -> 'a -> bool) -> 'a t -> bool
val exists: (key -> 'a -> bool) -> 'a t -> bool
val filter: (key -> 'a -> bool) -> 'a t -> 'a t
val partition: (key -> 'a -> bool) -> 'a t -> 'a t * 'a t
val cardinal: 'a t -> int
val bindings: 'a t -> (key * 'a) list
val min_binding: 'a t -> (key * 'a)
val min_binding_opt: 'a t -> (key * 'a) option
val max_binding: 'a t -> (key * 'a)
val max_binding_opt: 'a t -> (key * 'a) option
val choose: 'a t -> (key * 'a)
val choose_opt: 'a t -> (key * 'a) option
val split: key -> 'a t -> 'a t * 'a option * 'a t
val find: key -> 'a t -> 'a
val find_opt: key -> 'a t -> 'a option
val find_first: (key -> bool) -> 'a t -> key * 'a
val find_first_opt: (key -> bool) -> 'a t -> (key * 'a) option
val find_last: (key -> bool) -> 'a t -> key * 'a
val find_last_opt: (key -> bool) -> 'a t -> (key * 'a) option
val map: ('a -> 'b) -> 'a t -> 'b t
val mapi: (key -> 'a -> 'b) -> 'a t -> 'b t
val to_seq : 'a t -> (key * 'a) Seq.t
val to_seq_from : key -> 'a t -> (key * 'a) Seq.t
val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t
val of_seq : (key * 'a) Seq.t -> 'a t
end
module Make(Ord: OrderedType) = struct
type key = Ord.t
type 'a t =
Empty
| Node of {l:'a t; v:key; d:'a; r:'a t; h:int}
let height = function
Empty -> 0
| Node {h} -> h
let create l x d r =
let hl = height l and hr = height r in
Node{l; v=x; d; r; h=(if hl >= hr then hl + 1 else hr + 1)}
let singleton x d = Node{l=Empty; v=x; d; r=Empty; h=1}
let bal l x d r =
let hl = match l with Empty -> 0 | Node {h} -> h in
let hr = match r with Empty -> 0 | Node {h} -> h in
if hl > hr + 2 then begin
match l with
Empty -> invalid_arg "Map.bal"
| Node{l=ll; v=lv; d=ld; r=lr} ->
if height ll >= height lr then
create ll lv ld (create lr x d r)
else begin
match lr with
Empty -> invalid_arg "Map.bal"
| Node{l=lrl; v=lrv; d=lrd; r=lrr}->
create (create ll lv ld lrl) lrv lrd (create lrr x d r)
end
end else if hr > hl + 2 then begin
match r with
Empty -> invalid_arg "Map.bal"
| Node{l=rl; v=rv; d=rd; r=rr} ->
if height rr >= height rl then
create (create l x d rl) rv rd rr
else begin
match rl with
Empty -> invalid_arg "Map.bal"
| Node{l=rll; v=rlv; d=rld; r=rlr} ->
create (create l x d rll) rlv rld (create rlr rv rd rr)
end
end else
Node{l; v=x; d; r; h=(if hl >= hr then hl + 1 else hr + 1)}
let empty = Empty
let is_empty = function Empty -> true | _ -> false
let rec add x data = function
Empty ->
Node{l=Empty; v=x; d=data; r=Empty; h=1}
| Node {l; v; d; r; h} as m ->
let c = Ord.compare x v in
if c = 0 then
if d == data then m else Node{l; v=x; d=data; r; h}
else if c < 0 then
let ll = add x data l in
if l == ll then m else bal ll v d r
else
let rr = add x data r in
if r == rr then m else bal l v d rr
let rec find x = function
Empty ->
raise Not_found
| Node {l; v; d; r} ->
let c = Ord.compare x v in
if c = 0 then d
else find x (if c < 0 then l else r)
let rec find_first_aux v0 d0 f = function
Empty ->
(v0, d0)
| Node {l; v; d; r} ->
if f v then
find_first_aux v d f l
else
find_first_aux v0 d0 f r
let rec find_first f = function
Empty ->
raise Not_found
| Node {l; v; d; r} ->
if f v then
find_first_aux v d f l
else
find_first f r
let rec find_first_opt_aux v0 d0 f = function
Empty ->
Some (v0, d0)
| Node {l; v; d; r} ->
if f v then
find_first_opt_aux v d f l
else
find_first_opt_aux v0 d0 f r
let rec find_first_opt f = function
Empty ->
None
| Node {l; v; d; r} ->
if f v then
find_first_opt_aux v d f l
else
find_first_opt f r
let rec find_last_aux v0 d0 f = function
Empty ->
(v0, d0)
| Node {l; v; d; r} ->
if f v then
find_last_aux v d f r
else
find_last_aux v0 d0 f l
let rec find_last f = function
Empty ->
raise Not_found
| Node {l; v; d; r} ->
if f v then
find_last_aux v d f r
else
find_last f l
let rec find_last_opt_aux v0 d0 f = function
Empty ->
Some (v0, d0)
| Node {l; v; d; r} ->
if f v then
find_last_opt_aux v d f r
else
find_last_opt_aux v0 d0 f l
let rec find_last_opt f = function
Empty ->
None
| Node {l; v; d; r} ->
if f v then
find_last_opt_aux v d f r
else
find_last_opt f l
let rec find_opt x = function
Empty ->
None
| Node {l; v; d; r} ->
let c = Ord.compare x v in
if c = 0 then Some d
else find_opt x (if c < 0 then l else r)
let rec mem x = function
Empty ->
false
| Node {l; v; r} ->
let c = Ord.compare x v in
c = 0 || mem x (if c < 0 then l else r)
let rec min_binding = function
Empty -> raise Not_found
| Node {l=Empty; v; d} -> (v, d)
| Node {l} -> min_binding l
let rec min_binding_opt = function
Empty -> None
| Node {l=Empty; v; d} -> Some (v, d)
| Node {l}-> min_binding_opt l
let rec max_binding = function
Empty -> raise Not_found
| Node {v; d; r=Empty} -> (v, d)
| Node {r} -> max_binding r
let rec max_binding_opt = function
Empty -> None
| Node {v; d; r=Empty} -> Some (v, d)
| Node {r} -> max_binding_opt r
let rec remove_min_binding = function
Empty -> invalid_arg "Map.remove_min_elt"
| Node {l=Empty; r} -> r
| Node {l; v; d; r} -> bal (remove_min_binding l) v d r
let merge t1 t2 =
match (t1, t2) with
(Empty, t) -> t
| (t, Empty) -> t
| (_, _) ->
let (x, d) = min_binding t2 in
bal t1 x d (remove_min_binding t2)
let rec remove x = function
Empty ->
Empty
| (Node {l; v; d; r} as m) ->
let c = Ord.compare x v in
if c = 0 then merge l r
else if c < 0 then
let ll = remove x l in if l == ll then m else bal ll v d r
else
let rr = remove x r in if r == rr then m else bal l v d rr
let rec update x f = function
Empty ->
begin match f None with
| None -> Empty
| Some data -> Node{l=Empty; v=x; d=data; r=Empty; h=1}
end
| Node {l; v; d; r; h} as m ->
let c = Ord.compare x v in
if c = 0 then begin
match f (Some d) with
| None -> merge l r
| Some data ->
if d == data then m else Node{l; v=x; d=data; r; h}
end else if c < 0 then
let ll = update x f l in
if l == ll then m else bal ll v d r
else
let rr = update x f r in
if r == rr then m else bal l v d rr
let rec iter f = function
Empty -> ()
| Node {l; v; d; r} ->
iter f l; f v d; iter f r
let rec map f = function
Empty ->
Empty
| Node {l; v; d; r; h} ->
let l' = map f l in
let d' = f d in
let r' = map f r in
Node{l=l'; v; d=d'; r=r'; h}
let rec mapi f = function
Empty ->
Empty
| Node {l; v; d; r; h} ->
let l' = mapi f l in
let d' = f v d in
let r' = mapi f r in
Node{l=l'; v; d=d'; r=r'; h}
let rec fold f m accu =
match m with
Empty -> accu
| Node {l; v; d; r} ->
fold f r (f v d (fold f l accu))
let rec for_all p = function
Empty -> true
| Node {l; v; d; r} -> p v d && for_all p l && for_all p r
let rec exists p = function
Empty -> false
| Node {l; v; d; r} -> p v d || exists p l || exists p r
Beware : those two functions assume that the added k is * strictly *
smaller ( or bigger ) than all the present keys in the tree ; it
does not test for equality with the current min ( or ) key .
Indeed , they are only used during the " join " operation which
respects this precondition .
smaller (or bigger) than all the present keys in the tree; it
does not test for equality with the current min (or max) key.
Indeed, they are only used during the "join" operation which
respects this precondition.
*)
let rec add_min_binding k x = function
| Empty -> singleton k x
| Node {l; v; d; r} ->
bal (add_min_binding k x l) v d r
let rec add_max_binding k x = function
| Empty -> singleton k x
| Node {l; v; d; r} ->
bal l v d (add_max_binding k x r)
Same as create and bal , but no assumptions are made on the
relative heights of l and r.
relative heights of l and r. *)
let rec join l v d r =
match (l, r) with
(Empty, _) -> add_min_binding v d r
| (_, Empty) -> add_max_binding v d l
| (Node{l=ll; v=lv; d=ld; r=lr; h=lh}, Node{l=rl; v=rv; d=rd; r=rr; h=rh}) ->
if lh > rh + 2 then bal ll lv ld (join lr v d r) else
if rh > lh + 2 then bal (join l v d rl) rv rd rr else
create l v d r
Merge two trees l and r into one .
All elements of l must precede the elements of r.
No assumption on the heights of l and r.
All elements of l must precede the elements of r.
No assumption on the heights of l and r. *)
let concat t1 t2 =
match (t1, t2) with
(Empty, t) -> t
| (t, Empty) -> t
| (_, _) ->
let (x, d) = min_binding t2 in
join t1 x d (remove_min_binding t2)
let concat_or_join t1 v d t2 =
match d with
| Some d -> join t1 v d t2
| None -> concat t1 t2
let rec split x = function
Empty ->
(Empty, None, Empty)
| Node {l; v; d; r} ->
let c = Ord.compare x v in
if c = 0 then (l, Some d, r)
else if c < 0 then
let (ll, pres, rl) = split x l in (ll, pres, join rl v d r)
else
let (lr, pres, rr) = split x r in (join l v d lr, pres, rr)
let rec merge f s1 s2 =
match (s1, s2) with
(Empty, Empty) -> Empty
| (Node {l=l1; v=v1; d=d1; r=r1; h=h1}, _) when h1 >= height s2 ->
let (l2, d2, r2) = split v1 s2 in
concat_or_join (merge f l1 l2) v1 (f v1 (Some d1) d2) (merge f r1 r2)
| (_, Node {l=l2; v=v2; d=d2; r=r2}) ->
let (l1, d1, r1) = split v2 s1 in
concat_or_join (merge f l1 l2) v2 (f v2 d1 (Some d2)) (merge f r1 r2)
| _ ->
assert false
let rec union f s1 s2 =
match (s1, s2) with
| (Empty, s) | (s, Empty) -> s
| (Node {l=l1; v=v1; d=d1; r=r1; h=h1}, Node {l=l2; v=v2; d=d2; r=r2; h=h2}) ->
if h1 >= h2 then
let (l2, d2, r2) = split v1 s2 in
let l = union f l1 l2 and r = union f r1 r2 in
match d2 with
| None -> join l v1 d1 r
| Some d2 -> concat_or_join l v1 (f v1 d1 d2) r
else
let (l1, d1, r1) = split v2 s1 in
let l = union f l1 l2 and r = union f r1 r2 in
match d1 with
| None -> join l v2 d2 r
| Some d1 -> concat_or_join l v2 (f v2 d1 d2) r
let rec filter p = function
Empty -> Empty
| Node {l; v; d; r} as m ->
(* call [p] in the expected left-to-right order *)
let l' = filter p l in
let pvd = p v d in
let r' = filter p r in
if pvd then if l==l' && r==r' then m else join l' v d r'
else concat l' r'
let rec partition p = function
Empty -> (Empty, Empty)
| Node {l; v; d; r} ->
(* call [p] in the expected left-to-right order *)
let (lt, lf) = partition p l in
let pvd = p v d in
let (rt, rf) = partition p r in
if pvd
then (join lt v d rt, concat lf rf)
else (concat lt rt, join lf v d rf)
type 'a enumeration = End | More of key * 'a * 'a t * 'a enumeration
let rec cons_enum m e =
match m with
Empty -> e
| Node {l; v; d; r} -> cons_enum l (More(v, d, r, e))
let compare cmp m1 m2 =
let rec compare_aux e1 e2 =
match (e1, e2) with
(End, End) -> 0
| (End, _) -> -1
| (_, End) -> 1
| (More(v1, d1, r1, e1), More(v2, d2, r2, e2)) ->
let c = Ord.compare v1 v2 in
if c <> 0 then c else
let c = cmp d1 d2 in
if c <> 0 then c else
compare_aux (cons_enum r1 e1) (cons_enum r2 e2)
in compare_aux (cons_enum m1 End) (cons_enum m2 End)
let equal cmp m1 m2 =
let rec equal_aux e1 e2 =
match (e1, e2) with
(End, End) -> true
| (End, _) -> false
| (_, End) -> false
| (More(v1, d1, r1, e1), More(v2, d2, r2, e2)) ->
Ord.compare v1 v2 = 0 && cmp d1 d2 &&
equal_aux (cons_enum r1 e1) (cons_enum r2 e2)
in equal_aux (cons_enum m1 End) (cons_enum m2 End)
let rec cardinal = function
Empty -> 0
| Node {l; r} -> cardinal l + 1 + cardinal r
let rec bindings_aux accu = function
Empty -> accu
| Node {l; v; d; r} -> bindings_aux ((v, d) :: bindings_aux accu r) l
let bindings s =
bindings_aux [] s
let choose = min_binding
let choose_opt = min_binding_opt
let add_seq i m =
Seq.fold_left (fun m (k,v) -> add k v m) m i
let of_seq i = add_seq i empty
let rec seq_of_enum_ c () = match c with
| End -> Seq.Nil
| More (k,v,t,rest) -> Seq.Cons ((k,v), seq_of_enum_ (cons_enum t rest))
let to_seq m =
seq_of_enum_ (cons_enum m End)
let to_seq_from low m =
let rec aux low m c = match m with
| Empty -> c
| Node {l; v; d; r; _} ->
begin match Ord.compare v low with
| 0 -> More (v, d, r, c)
| n when n<0 -> aux low r c
| _ -> aux low l (More (v, d, r, c))
end
in
seq_of_enum_ (aux low m End)
end
| null | https://raw.githubusercontent.com/brianhempel/maniposynth/8c8e72f2459f1ec05fefcb994253f99620e377f3/ocaml-4.07.1/stdlib/map.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
call [p] in the expected left-to-right order
call [p] in the expected left-to-right order | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
module type OrderedType =
sig
type t
val compare: t -> t -> int
end
module type S =
sig
type key
type +'a t
val empty: 'a t
val is_empty: 'a t -> bool
val mem: key -> 'a t -> bool
val add: key -> 'a -> 'a t -> 'a t
val update: key -> ('a option -> 'a option) -> 'a t -> 'a t
val singleton: key -> 'a -> 'a t
val remove: key -> 'a t -> 'a t
val merge:
(key -> 'a option -> 'b option -> 'c option) -> 'a t -> 'b t -> 'c t
val union: (key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t
val compare: ('a -> 'a -> int) -> 'a t -> 'a t -> int
val equal: ('a -> 'a -> bool) -> 'a t -> 'a t -> bool
val iter: (key -> 'a -> unit) -> 'a t -> unit
val fold: (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
val for_all: (key -> 'a -> bool) -> 'a t -> bool
val exists: (key -> 'a -> bool) -> 'a t -> bool
val filter: (key -> 'a -> bool) -> 'a t -> 'a t
val partition: (key -> 'a -> bool) -> 'a t -> 'a t * 'a t
val cardinal: 'a t -> int
val bindings: 'a t -> (key * 'a) list
val min_binding: 'a t -> (key * 'a)
val min_binding_opt: 'a t -> (key * 'a) option
val max_binding: 'a t -> (key * 'a)
val max_binding_opt: 'a t -> (key * 'a) option
val choose: 'a t -> (key * 'a)
val choose_opt: 'a t -> (key * 'a) option
val split: key -> 'a t -> 'a t * 'a option * 'a t
val find: key -> 'a t -> 'a
val find_opt: key -> 'a t -> 'a option
val find_first: (key -> bool) -> 'a t -> key * 'a
val find_first_opt: (key -> bool) -> 'a t -> (key * 'a) option
val find_last: (key -> bool) -> 'a t -> key * 'a
val find_last_opt: (key -> bool) -> 'a t -> (key * 'a) option
val map: ('a -> 'b) -> 'a t -> 'b t
val mapi: (key -> 'a -> 'b) -> 'a t -> 'b t
val to_seq : 'a t -> (key * 'a) Seq.t
val to_seq_from : key -> 'a t -> (key * 'a) Seq.t
val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t
val of_seq : (key * 'a) Seq.t -> 'a t
end
module Make(Ord: OrderedType) = struct
type key = Ord.t
type 'a t =
Empty
| Node of {l:'a t; v:key; d:'a; r:'a t; h:int}
let height = function
Empty -> 0
| Node {h} -> h
let create l x d r =
let hl = height l and hr = height r in
Node{l; v=x; d; r; h=(if hl >= hr then hl + 1 else hr + 1)}
let singleton x d = Node{l=Empty; v=x; d; r=Empty; h=1}
let bal l x d r =
let hl = match l with Empty -> 0 | Node {h} -> h in
let hr = match r with Empty -> 0 | Node {h} -> h in
if hl > hr + 2 then begin
match l with
Empty -> invalid_arg "Map.bal"
| Node{l=ll; v=lv; d=ld; r=lr} ->
if height ll >= height lr then
create ll lv ld (create lr x d r)
else begin
match lr with
Empty -> invalid_arg "Map.bal"
| Node{l=lrl; v=lrv; d=lrd; r=lrr}->
create (create ll lv ld lrl) lrv lrd (create lrr x d r)
end
end else if hr > hl + 2 then begin
match r with
Empty -> invalid_arg "Map.bal"
| Node{l=rl; v=rv; d=rd; r=rr} ->
if height rr >= height rl then
create (create l x d rl) rv rd rr
else begin
match rl with
Empty -> invalid_arg "Map.bal"
| Node{l=rll; v=rlv; d=rld; r=rlr} ->
create (create l x d rll) rlv rld (create rlr rv rd rr)
end
end else
Node{l; v=x; d; r; h=(if hl >= hr then hl + 1 else hr + 1)}
let empty = Empty
let is_empty = function Empty -> true | _ -> false
let rec add x data = function
Empty ->
Node{l=Empty; v=x; d=data; r=Empty; h=1}
| Node {l; v; d; r; h} as m ->
let c = Ord.compare x v in
if c = 0 then
if d == data then m else Node{l; v=x; d=data; r; h}
else if c < 0 then
let ll = add x data l in
if l == ll then m else bal ll v d r
else
let rr = add x data r in
if r == rr then m else bal l v d rr
let rec find x = function
Empty ->
raise Not_found
| Node {l; v; d; r} ->
let c = Ord.compare x v in
if c = 0 then d
else find x (if c < 0 then l else r)
let rec find_first_aux v0 d0 f = function
Empty ->
(v0, d0)
| Node {l; v; d; r} ->
if f v then
find_first_aux v d f l
else
find_first_aux v0 d0 f r
let rec find_first f = function
Empty ->
raise Not_found
| Node {l; v; d; r} ->
if f v then
find_first_aux v d f l
else
find_first f r
let rec find_first_opt_aux v0 d0 f = function
Empty ->
Some (v0, d0)
| Node {l; v; d; r} ->
if f v then
find_first_opt_aux v d f l
else
find_first_opt_aux v0 d0 f r
let rec find_first_opt f = function
Empty ->
None
| Node {l; v; d; r} ->
if f v then
find_first_opt_aux v d f l
else
find_first_opt f r
let rec find_last_aux v0 d0 f = function
Empty ->
(v0, d0)
| Node {l; v; d; r} ->
if f v then
find_last_aux v d f r
else
find_last_aux v0 d0 f l
let rec find_last f = function
Empty ->
raise Not_found
| Node {l; v; d; r} ->
if f v then
find_last_aux v d f r
else
find_last f l
let rec find_last_opt_aux v0 d0 f = function
Empty ->
Some (v0, d0)
| Node {l; v; d; r} ->
if f v then
find_last_opt_aux v d f r
else
find_last_opt_aux v0 d0 f l
let rec find_last_opt f = function
Empty ->
None
| Node {l; v; d; r} ->
if f v then
find_last_opt_aux v d f r
else
find_last_opt f l
let rec find_opt x = function
Empty ->
None
| Node {l; v; d; r} ->
let c = Ord.compare x v in
if c = 0 then Some d
else find_opt x (if c < 0 then l else r)
let rec mem x = function
Empty ->
false
| Node {l; v; r} ->
let c = Ord.compare x v in
c = 0 || mem x (if c < 0 then l else r)
let rec min_binding = function
Empty -> raise Not_found
| Node {l=Empty; v; d} -> (v, d)
| Node {l} -> min_binding l
let rec min_binding_opt = function
Empty -> None
| Node {l=Empty; v; d} -> Some (v, d)
| Node {l}-> min_binding_opt l
let rec max_binding = function
Empty -> raise Not_found
| Node {v; d; r=Empty} -> (v, d)
| Node {r} -> max_binding r
let rec max_binding_opt = function
Empty -> None
| Node {v; d; r=Empty} -> Some (v, d)
| Node {r} -> max_binding_opt r
let rec remove_min_binding = function
Empty -> invalid_arg "Map.remove_min_elt"
| Node {l=Empty; r} -> r
| Node {l; v; d; r} -> bal (remove_min_binding l) v d r
let merge t1 t2 =
match (t1, t2) with
(Empty, t) -> t
| (t, Empty) -> t
| (_, _) ->
let (x, d) = min_binding t2 in
bal t1 x d (remove_min_binding t2)
let rec remove x = function
Empty ->
Empty
| (Node {l; v; d; r} as m) ->
let c = Ord.compare x v in
if c = 0 then merge l r
else if c < 0 then
let ll = remove x l in if l == ll then m else bal ll v d r
else
let rr = remove x r in if r == rr then m else bal l v d rr
let rec update x f = function
Empty ->
begin match f None with
| None -> Empty
| Some data -> Node{l=Empty; v=x; d=data; r=Empty; h=1}
end
| Node {l; v; d; r; h} as m ->
let c = Ord.compare x v in
if c = 0 then begin
match f (Some d) with
| None -> merge l r
| Some data ->
if d == data then m else Node{l; v=x; d=data; r; h}
end else if c < 0 then
let ll = update x f l in
if l == ll then m else bal ll v d r
else
let rr = update x f r in
if r == rr then m else bal l v d rr
let rec iter f = function
Empty -> ()
| Node {l; v; d; r} ->
iter f l; f v d; iter f r
let rec map f = function
Empty ->
Empty
| Node {l; v; d; r; h} ->
let l' = map f l in
let d' = f d in
let r' = map f r in
Node{l=l'; v; d=d'; r=r'; h}
let rec mapi f = function
Empty ->
Empty
| Node {l; v; d; r; h} ->
let l' = mapi f l in
let d' = f v d in
let r' = mapi f r in
Node{l=l'; v; d=d'; r=r'; h}
let rec fold f m accu =
match m with
Empty -> accu
| Node {l; v; d; r} ->
fold f r (f v d (fold f l accu))
let rec for_all p = function
Empty -> true
| Node {l; v; d; r} -> p v d && for_all p l && for_all p r
let rec exists p = function
Empty -> false
| Node {l; v; d; r} -> p v d || exists p l || exists p r
Beware : those two functions assume that the added k is * strictly *
smaller ( or bigger ) than all the present keys in the tree ; it
does not test for equality with the current min ( or ) key .
Indeed , they are only used during the " join " operation which
respects this precondition .
smaller (or bigger) than all the present keys in the tree; it
does not test for equality with the current min (or max) key.
Indeed, they are only used during the "join" operation which
respects this precondition.
*)
let rec add_min_binding k x = function
| Empty -> singleton k x
| Node {l; v; d; r} ->
bal (add_min_binding k x l) v d r
let rec add_max_binding k x = function
| Empty -> singleton k x
| Node {l; v; d; r} ->
bal l v d (add_max_binding k x r)
Same as create and bal , but no assumptions are made on the
relative heights of l and r.
relative heights of l and r. *)
let rec join l v d r =
match (l, r) with
(Empty, _) -> add_min_binding v d r
| (_, Empty) -> add_max_binding v d l
| (Node{l=ll; v=lv; d=ld; r=lr; h=lh}, Node{l=rl; v=rv; d=rd; r=rr; h=rh}) ->
if lh > rh + 2 then bal ll lv ld (join lr v d r) else
if rh > lh + 2 then bal (join l v d rl) rv rd rr else
create l v d r
Merge two trees l and r into one .
All elements of l must precede the elements of r.
No assumption on the heights of l and r.
All elements of l must precede the elements of r.
No assumption on the heights of l and r. *)
let concat t1 t2 =
match (t1, t2) with
(Empty, t) -> t
| (t, Empty) -> t
| (_, _) ->
let (x, d) = min_binding t2 in
join t1 x d (remove_min_binding t2)
let concat_or_join t1 v d t2 =
match d with
| Some d -> join t1 v d t2
| None -> concat t1 t2
let rec split x = function
Empty ->
(Empty, None, Empty)
| Node {l; v; d; r} ->
let c = Ord.compare x v in
if c = 0 then (l, Some d, r)
else if c < 0 then
let (ll, pres, rl) = split x l in (ll, pres, join rl v d r)
else
let (lr, pres, rr) = split x r in (join l v d lr, pres, rr)
let rec merge f s1 s2 =
match (s1, s2) with
(Empty, Empty) -> Empty
| (Node {l=l1; v=v1; d=d1; r=r1; h=h1}, _) when h1 >= height s2 ->
let (l2, d2, r2) = split v1 s2 in
concat_or_join (merge f l1 l2) v1 (f v1 (Some d1) d2) (merge f r1 r2)
| (_, Node {l=l2; v=v2; d=d2; r=r2}) ->
let (l1, d1, r1) = split v2 s1 in
concat_or_join (merge f l1 l2) v2 (f v2 d1 (Some d2)) (merge f r1 r2)
| _ ->
assert false
let rec union f s1 s2 =
match (s1, s2) with
| (Empty, s) | (s, Empty) -> s
| (Node {l=l1; v=v1; d=d1; r=r1; h=h1}, Node {l=l2; v=v2; d=d2; r=r2; h=h2}) ->
if h1 >= h2 then
let (l2, d2, r2) = split v1 s2 in
let l = union f l1 l2 and r = union f r1 r2 in
match d2 with
| None -> join l v1 d1 r
| Some d2 -> concat_or_join l v1 (f v1 d1 d2) r
else
let (l1, d1, r1) = split v2 s1 in
let l = union f l1 l2 and r = union f r1 r2 in
match d1 with
| None -> join l v2 d2 r
| Some d1 -> concat_or_join l v2 (f v2 d1 d2) r
let rec filter p = function
Empty -> Empty
| Node {l; v; d; r} as m ->
let l' = filter p l in
let pvd = p v d in
let r' = filter p r in
if pvd then if l==l' && r==r' then m else join l' v d r'
else concat l' r'
let rec partition p = function
Empty -> (Empty, Empty)
| Node {l; v; d; r} ->
let (lt, lf) = partition p l in
let pvd = p v d in
let (rt, rf) = partition p r in
if pvd
then (join lt v d rt, concat lf rf)
else (concat lt rt, join lf v d rf)
type 'a enumeration = End | More of key * 'a * 'a t * 'a enumeration
let rec cons_enum m e =
match m with
Empty -> e
| Node {l; v; d; r} -> cons_enum l (More(v, d, r, e))
let compare cmp m1 m2 =
let rec compare_aux e1 e2 =
match (e1, e2) with
(End, End) -> 0
| (End, _) -> -1
| (_, End) -> 1
| (More(v1, d1, r1, e1), More(v2, d2, r2, e2)) ->
let c = Ord.compare v1 v2 in
if c <> 0 then c else
let c = cmp d1 d2 in
if c <> 0 then c else
compare_aux (cons_enum r1 e1) (cons_enum r2 e2)
in compare_aux (cons_enum m1 End) (cons_enum m2 End)
let equal cmp m1 m2 =
let rec equal_aux e1 e2 =
match (e1, e2) with
(End, End) -> true
| (End, _) -> false
| (_, End) -> false
| (More(v1, d1, r1, e1), More(v2, d2, r2, e2)) ->
Ord.compare v1 v2 = 0 && cmp d1 d2 &&
equal_aux (cons_enum r1 e1) (cons_enum r2 e2)
in equal_aux (cons_enum m1 End) (cons_enum m2 End)
let rec cardinal = function
Empty -> 0
| Node {l; r} -> cardinal l + 1 + cardinal r
let rec bindings_aux accu = function
Empty -> accu
| Node {l; v; d; r} -> bindings_aux ((v, d) :: bindings_aux accu r) l
let bindings s =
bindings_aux [] s
let choose = min_binding
let choose_opt = min_binding_opt
let add_seq i m =
Seq.fold_left (fun m (k,v) -> add k v m) m i
let of_seq i = add_seq i empty
let rec seq_of_enum_ c () = match c with
| End -> Seq.Nil
| More (k,v,t,rest) -> Seq.Cons ((k,v), seq_of_enum_ (cons_enum t rest))
let to_seq m =
seq_of_enum_ (cons_enum m End)
let to_seq_from low m =
let rec aux low m c = match m with
| Empty -> c
| Node {l; v; d; r; _} ->
begin match Ord.compare v low with
| 0 -> More (v, d, r, c)
| n when n<0 -> aux low r c
| _ -> aux low l (More (v, d, r, c))
end
in
seq_of_enum_ (aux low m End)
end
|
dcd085bc3df399054e1ee21f59cb8b37ec7f8c4a7bd7d349363289438c8311c8 | skanev/playground | 22.scm | EOPL exercise 3.22
;
; The concrete syntax of this section uses different syntax for a built-in
; operation, such as difference, from a procedure call. Modify the concrete
; syntax so that the user of this language need not know which operations are
; built-in and which are defined procedures. The exercise may range from very
; easy to hard, depending on the parsing technology being used.
This is quite annoying using SLLGEN . I 'm doing it with a particularly nasty
; function var-or-call that takes an ugly parse result and classifies it as a
; var-exp or a call-exp.
;
; If I was less lazy, I could get foo(1)(2) to work. I'm not.
(load-relative "cases/proc/env.scm")
; The parser
(define-datatype expression expression?
(const-exp
(num number?))
(diff-exp
(minuend expression?)
(subtrahend expression?))
(zero?-exp
(expr expression?))
(if-exp
(predicate expression?)
(consequent expression?)
(alternative expression?))
(var-exp
(var symbol?))
(let-exp
(var symbol?)
(value expression?)
(body expression?))
(proc-exp
(var (list-of symbol?))
(body expression?))
(call-exp
(rator expression?)
(rand (list-of expression?))))
(define (var-or-call id args)
(cond ((null? args) (var-exp id))
((= (length args) 1) (call-exp (var-exp id) (car args)))
(else (eopl:error 'parse "Can't parse this"))))
(define scanner-spec
'((white-sp (whitespace) skip)
(comment ("%" (arbno (not #\newline))) skip)
(identifier (letter (arbno (or letter digit))) symbol)
(number (digit (arbno digit)) number)))
(define grammar
'((expression (number) const-exp)
(expression ("-" "(" expression "," expression ")") diff-exp)
(expression (identifier (arbno "(" (separated-list expression ",") ")")) var-or-call)
(expression ("zero?" "(" expression ")") zero?-exp)
(expression ("if" expression "then" expression "else" expression) if-exp)
(expression ("proc" "(" (separated-list identifier ",") ")" expression) proc-exp)
(expression ("let" identifier "=" expression "in" expression) let-exp)))
(define scan&parse
(sllgen:make-string-parser scanner-spec grammar))
; The evaluator
(define-datatype proc proc?
(procedure
(var (list-of symbol?))
(body expression?)
(saved-env environment?)))
(define (apply-procedure proc1 vals)
(cases proc proc1
(procedure (vars body saved-env)
(value-of body (extend-env* vars vals saved-env)))))
(define-datatype expval expval?
(num-val
(num number?))
(bool-val
(bool boolean?))
(proc-val
(proc proc?)))
(define (expval->num val)
(cases expval val
(num-val (num) num)
(else (eopl:error 'expval->num "Invalid number: ~s" val))))
(define (expval->bool val)
(cases expval val
(bool-val (bool) bool)
(else (eopl:error 'expval->bool "Invalid boolean: ~s" val))))
(define (expval->proc val)
(cases expval val
(proc-val (proc) proc)
(else (eopl:error 'expval->proc "Invalid procedure: ~s" val))))
(define (value-of expr env)
(cases expression expr
(const-exp (num) (num-val num))
(var-exp (var) (apply-env env var))
(diff-exp (minuend subtrahend)
(let ((minuend-val (value-of minuend env))
(subtrahend-val (value-of subtrahend env)))
(let ((minuend-num (expval->num minuend-val))
(subtrahend-num (expval->num subtrahend-val)))
(num-val
(- minuend-num subtrahend-num)))))
(zero?-exp (arg)
(let ((value (value-of arg env)))
(let ((number (expval->num value)))
(if (zero? number)
(bool-val #t)
(bool-val #f)))))
(if-exp (predicate consequent alternative)
(let ((value (value-of predicate env)))
(if (expval->bool value)
(value-of consequent env)
(value-of alternative env))))
(let-exp (var value-exp body)
(let ((value (value-of value-exp env)))
(value-of body
(extend-env var value env))))
(proc-exp (vars body)
(proc-val (procedure vars body env)))
(call-exp (rator rands)
(let ((proc (expval->proc (value-of rator env)))
(args (map (lambda (rand) (value-of rand env))
rands)))
(apply-procedure proc args)))))
| null | https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/eopl/03/22.scm | scheme |
The concrete syntax of this section uses different syntax for a built-in
operation, such as difference, from a procedure call. Modify the concrete
syntax so that the user of this language need not know which operations are
built-in and which are defined procedures. The exercise may range from very
easy to hard, depending on the parsing technology being used.
function var-or-call that takes an ugly parse result and classifies it as a
var-exp or a call-exp.
If I was less lazy, I could get foo(1)(2) to work. I'm not.
The parser
The evaluator | EOPL exercise 3.22
This is quite annoying using SLLGEN . I 'm doing it with a particularly nasty
(load-relative "cases/proc/env.scm")
(define-datatype expression expression?
(const-exp
(num number?))
(diff-exp
(minuend expression?)
(subtrahend expression?))
(zero?-exp
(expr expression?))
(if-exp
(predicate expression?)
(consequent expression?)
(alternative expression?))
(var-exp
(var symbol?))
(let-exp
(var symbol?)
(value expression?)
(body expression?))
(proc-exp
(var (list-of symbol?))
(body expression?))
(call-exp
(rator expression?)
(rand (list-of expression?))))
(define (var-or-call id args)
(cond ((null? args) (var-exp id))
((= (length args) 1) (call-exp (var-exp id) (car args)))
(else (eopl:error 'parse "Can't parse this"))))
(define scanner-spec
'((white-sp (whitespace) skip)
(comment ("%" (arbno (not #\newline))) skip)
(identifier (letter (arbno (or letter digit))) symbol)
(number (digit (arbno digit)) number)))
(define grammar
'((expression (number) const-exp)
(expression ("-" "(" expression "," expression ")") diff-exp)
(expression (identifier (arbno "(" (separated-list expression ",") ")")) var-or-call)
(expression ("zero?" "(" expression ")") zero?-exp)
(expression ("if" expression "then" expression "else" expression) if-exp)
(expression ("proc" "(" (separated-list identifier ",") ")" expression) proc-exp)
(expression ("let" identifier "=" expression "in" expression) let-exp)))
(define scan&parse
(sllgen:make-string-parser scanner-spec grammar))
(define-datatype proc proc?
(procedure
(var (list-of symbol?))
(body expression?)
(saved-env environment?)))
(define (apply-procedure proc1 vals)
(cases proc proc1
(procedure (vars body saved-env)
(value-of body (extend-env* vars vals saved-env)))))
(define-datatype expval expval?
(num-val
(num number?))
(bool-val
(bool boolean?))
(proc-val
(proc proc?)))
(define (expval->num val)
(cases expval val
(num-val (num) num)
(else (eopl:error 'expval->num "Invalid number: ~s" val))))
(define (expval->bool val)
(cases expval val
(bool-val (bool) bool)
(else (eopl:error 'expval->bool "Invalid boolean: ~s" val))))
(define (expval->proc val)
(cases expval val
(proc-val (proc) proc)
(else (eopl:error 'expval->proc "Invalid procedure: ~s" val))))
(define (value-of expr env)
(cases expression expr
(const-exp (num) (num-val num))
(var-exp (var) (apply-env env var))
(diff-exp (minuend subtrahend)
(let ((minuend-val (value-of minuend env))
(subtrahend-val (value-of subtrahend env)))
(let ((minuend-num (expval->num minuend-val))
(subtrahend-num (expval->num subtrahend-val)))
(num-val
(- minuend-num subtrahend-num)))))
(zero?-exp (arg)
(let ((value (value-of arg env)))
(let ((number (expval->num value)))
(if (zero? number)
(bool-val #t)
(bool-val #f)))))
(if-exp (predicate consequent alternative)
(let ((value (value-of predicate env)))
(if (expval->bool value)
(value-of consequent env)
(value-of alternative env))))
(let-exp (var value-exp body)
(let ((value (value-of value-exp env)))
(value-of body
(extend-env var value env))))
(proc-exp (vars body)
(proc-val (procedure vars body env)))
(call-exp (rator rands)
(let ((proc (expval->proc (value-of rator env)))
(args (map (lambda (rand) (value-of rand env))
rands)))
(apply-procedure proc args)))))
|
96a7c1909287e05ff8cfc5eb8cbd7b750d06c20d4f138f622de387a59579444c | footprintanalytics/footprint-web | pulse_channel_test.clj | (ns metabase.models.pulse-channel-test
(:require [clojure.test :refer :all]
[medley.core :as m]
[metabase.models.collection :refer [Collection]]
[metabase.models.pulse :refer [Pulse]]
[metabase.models.pulse-channel :as pulse-channel :refer [PulseChannel]]
[metabase.models.pulse-channel-recipient :refer [PulseChannelRecipient]]
[metabase.models.serialization.hash :as serdes.hash]
[metabase.models.user :refer [User]]
[metabase.test :as mt]
[metabase.util :as u]
[toucan.db :as db]
[toucan.hydrate :refer [hydrate]])
(:import java.time.LocalDateTime))
;; Test out our predicate functions
(deftest day-of-week?-test
(doseq [[x expected] {nil false
[] false
{} false
"abc" false
"mon" true
:mon false}]
(testing x
(is (= expected
(pulse-channel/day-of-week? x))))))
(deftest hour-of-day?-test
(doseq [[x expected] {nil false
500 false
-12 false
8.5 false
"abc" false
11 true
0 true
23 true}]
(testing x
(is (= expected
(pulse-channel/hour-of-day? x))))))
(deftest schedule-type?-test
(doseq [[x expected] {nil false
"abc" false
123 false
"daily" false
:hourly true
:daily true
:weekly true}]
(testing x
(is (= expected
(pulse-channel/schedule-type? x))))))
(deftest schedule-frame?-test
(doseq [[x expected] {nil false
"abc" false
123 false
"first" false
:first true
:mid true
:last true}]
(testing x
(is (= expected
(pulse-channel/schedule-frame? x))))))
(deftest valid-schedule?-test
(doseq [[group args->expected] {"nil"
{[nil nil nil nil] false
[:foo nil nil nil] false}
"hourly"
{[:hourly nil nil nil] true
[:hourly 12 "abc" nil] true}
"daily"
{[:daily nil nil nil] false
[:daily 35 nil nil] false
[:daily 12 nil nil] true}
"weekly"
{[:weekly nil nil nil] false
[:weekly 12 nil nil] false
[:weekly 12 "blah" nil] false
[:weekly 12 "wed" nil] true}
"monthly"
{[:monthly nil nil nil] false
[:monthly 12 nil nil] false
[:monthly 12 "wed" nil] false
[:monthly 12 nil "abc"] false
[:monthly 12 nil 123] false
[:monthly 12 nil :mid] true
[:monthly 12 nil :first] true
[:monthly 12 nil :last] true
[:monthly 12 "mon" :first] true
[:monthly 12 "fri" :last] true}}
[args expected] args->expected]
(testing group
(testing (cons 'valid-schedule? args)
(is (= expected
(apply pulse-channel/valid-schedule? args)))))))
(deftest channel-type?-test
(doseq [[x expected] {nil false
"abc" false
123 false
:sms false
"email" false
:email true
:slack true}]
(testing x
(is (= expected
(pulse-channel/channel-type? x))))))
(deftest supports-recipients?-test
(doseq [[x expected] {nil false
"abc" false
:email true
:slack false}]
(testing x
(is (= expected
(pulse-channel/supports-recipients? x))))))
;; helper functions
;; format user details like they would come back for a channel recipient
(defn user-details
[username]
(-> (mt/fetch-user username)
(dissoc :date_joined :last_login :is_superuser :is_qbnewb :locale)
mt/derecordize))
;; create a channel then select its details
(defn- create-channel-then-select!
[channel]
(when-let [new-channel-id (pulse-channel/create-pulse-channel! channel)]
(-> (db/select-one PulseChannel :id new-channel-id)
(hydrate :recipients)
(update :recipients #(sort-by :email %))
(dissoc :id :pulse_id :created_at :updated_at)
(update :entity_id boolean)
(m/dissoc-in [:details :emails])
mt/derecordize)))
(defn- update-channel-then-select!
[{:keys [id] :as channel}]
(pulse-channel/update-pulse-channel! channel)
(-> (db/select-one PulseChannel :id id)
(hydrate :recipients)
(dissoc :id :pulse_id :created_at :updated_at)
(update :entity_id boolean)
(m/dissoc-in [:details :emails])
mt/derecordize))
;; create-pulse-channel!
(deftest create-pulse-channel!-test
(mt/with-temp Pulse [{:keys [id]}]
(mt/with-model-cleanup [Pulse]
(testing "disabled"
(is (= {:enabled false
:entity_id true
:channel_type :email
:schedule_type :daily
:schedule_hour 18
:schedule_day nil
:schedule_frame nil
:recipients [(user-details :crowberto)
{:email ""}
(user-details :rasta)]}
(create-channel-then-select!
{:pulse_id id
:enabled false
:channel_type :email
:schedule_type :daily
:schedule_hour 18
:recipients [{:email ""}
{:id (mt/user->id :rasta)}
{:id (mt/user->id :crowberto)}]}))))
(testing "email"
(is (= {:enabled true
:entity_id true
:channel_type :email
:schedule_type :daily
:schedule_hour 18
:schedule_day nil
:schedule_frame nil
:recipients [(user-details :crowberto)
{:email ""}
(user-details :rasta)]}
(create-channel-then-select!
{:pulse_id id
:enabled true
:channel_type :email
:schedule_type :daily
:schedule_hour 18
:recipients [{:email ""}
{:id (mt/user->id :rasta)}
{:id (mt/user->id :crowberto)}]}))))
(testing "slack"
(is (= {:enabled true
:entity_id true
:channel_type :slack
:schedule_type :hourly
:schedule_hour nil
:schedule_day nil
:schedule_frame nil
:recipients []
:details {:something "random"}}
(create-channel-then-select!
{:pulse_id id
:enabled true
:channel_type :slack
:schedule_type :hourly
:details {:something "random"}
:recipients [{:email ""}
{:id (mt/user->id :rasta)}
{:id (mt/user->id :crowberto)}]})))))))
(deftest update-pulse-channel!-test
(mt/with-temp Pulse [{pulse-id :id}]
(testing "simple starting case where we modify the schedule hour and add a recipient"
(mt/with-temp PulseChannel [{channel-id :id} {:pulse_id pulse-id}]
(is (= {:enabled true
:entity_id true
:channel_type :email
:schedule_type :daily
:schedule_hour 18
:schedule_day nil
:schedule_frame nil
:recipients [{:email ""}]}
(update-channel-then-select!
{:id channel-id
:enabled true
:channel_type :email
:schedule_type :daily
:schedule_hour 18
:recipients [{:email ""}]})))))
(testing "monthly schedules require a schedule_frame and can optionally omit they schedule_day"
(mt/with-temp PulseChannel [{channel-id :id} {:pulse_id pulse-id}]
(is (= {:enabled true
:entity_id true
:channel_type :email
:schedule_type :monthly
:schedule_hour 8
:schedule_day nil
:schedule_frame :mid
:recipients [{:email ""} (user-details :rasta)]}
(update-channel-then-select!
{:id channel-id
:enabled true
:channel_type :email
:schedule_type :monthly
:schedule_hour 8
:schedule_day nil
:schedule_frame :mid
:recipients [{:email ""} {:id (mt/user->id :rasta)}]})))))
(testing "weekly schedule should have a day in it, show that we can get full users"
(mt/with-temp PulseChannel [{channel-id :id} {:pulse_id pulse-id}]
(is (= {:enabled true
:entity_id true
:channel_type :email
:schedule_type :weekly
:schedule_hour 8
:schedule_day "mon"
:schedule_frame nil
:recipients [{:email ""} (user-details :rasta)]}
(update-channel-then-select!
{:id channel-id
:enabled true
:channel_type :email
:schedule_type :weekly
:schedule_hour 8
:schedule_day "mon"
:recipients [{:email ""} {:id (mt/user->id :rasta)}]})))))
(testing "hourly schedules don't require day/hour settings (should be nil), fully change recipients"
(mt/with-temp PulseChannel [{channel-id :id} {:pulse_id pulse-id, :details {:emails [""]}}]
(pulse-channel/update-recipients! channel-id [(mt/user->id :rasta)])
(is (= {:enabled true
:entity_id true
:channel_type :email
:schedule_type :hourly
:schedule_hour nil
:schedule_day nil
:schedule_frame nil
:recipients [(user-details :crowberto)]}
(update-channel-then-select!
{:id channel-id
:enabled true
:channel_type :email
:schedule_type :hourly
:schedule_hour 12
:schedule_day "tue"
:recipients [{:id (mt/user->id :crowberto)}]})))))
(testing "custom details for channels that need it"
(mt/with-temp PulseChannel [{channel-id :id} {:pulse_id pulse-id}]
(is (= {:enabled true
:entity_id true
:channel_type :email
:schedule_type :daily
:schedule_hour 12
:schedule_day nil
:schedule_frame nil
:recipients [{:email ""} {:email ""}]
:details {:channel "#metabaserocks"}}
(update-channel-then-select!
{:id channel-id
:enabled true
:channel_type :email
:schedule_type :daily
:schedule_hour 12
:schedule_day "tue"
:recipients [{:email ""} {:email ""}]
:details {:channel "#metabaserocks"}})))))))
(deftest update-recipients!-test
(mt/with-temp* [Pulse [{pulse-id :id}]
PulseChannel [{channel-id :id} {:pulse_id pulse-id}]]
(letfn [(upd-recipients! [recipients]
(pulse-channel/update-recipients! channel-id recipients)
(db/select-field :user_id PulseChannelRecipient, :pulse_channel_id channel-id))]
(doseq [[new-recipients expected] {[] nil
[:rasta] [:rasta]
[:crowberto] [:crowberto]
[:crowberto :rasta] [:crowberto :rasta]
[:rasta :trashbird] [:rasta :trashbird]}]
(testing new-recipients
(is (= (not-empty (set (map mt/user->id expected)))
(upd-recipients! (map mt/user->id new-recipients)))))))))
(deftest retrieve-scheduled-channels-test
(letfn [(retrieve-channels [hour day]
(for [channel (pulse-channel/retrieve-scheduled-channels hour day :other :other)]
(dissoc (into {} channel) :id :pulse_id)))]
(testing "test a simple scenario with a single Pulse and 2 channels on hourly/daily schedules"
(mt/with-temp* [Pulse [{pulse-id :id}]
- > schedule_type = daily , schedule_hour = 15 , channel_type = email
PulseChannel [_ {:pulse_id pulse-id, :channel_type :slack, :schedule_type :hourly}]
PulseChannel [_ {:pulse_id pulse-id, :channel_type :email, :schedule_type :hourly, :enabled false}]]
(doseq [[[hour day] expected] {[nil nil] #{{:schedule_type :hourly, :channel_type :slack}}
[12 nil] #{{:schedule_type :hourly, :channel_type :slack}}
[15 nil] #{{:schedule_type :hourly, :channel_type :slack}
{:schedule_type :daily, :channel_type :email}}
[15 "wed"] #{{:schedule_type :hourly, :channel_type :slack}
{:schedule_type :daily, :channel_type :email}}}]
(testing (cons 'retrieve-scheduled-channels [hour day])
(is (= expected
(set (retrieve-channels hour day))))))))
(testing "more complex scenario with 2 Pulses, including weekly scheduling"
(mt/with-temp* [Pulse [{pulse-1-id :id}]
Pulse [{pulse-2-id :id}]
PulseChannel [_ {:pulse_id pulse-1-id, :enabled true, :channel_type :email, :schedule_type :daily}]
PulseChannel [_ {:pulse_id pulse-1-id, :enabled true, :channel_type :slack, :schedule_type :hourly}]
PulseChannel [_ {:pulse_id pulse-2-id, :enabled true, :channel_type :slack, :schedule_type :daily :schedule_hour 10, :schedule_day "wed"}]
PulseChannel [_ {:pulse_id pulse-2-id, :enabled true, :channel_type :email, :schedule_type :weekly, :schedule_hour 8, :schedule_day "mon"}]]
(doseq [[[hour day] expected] {[nil nil] #{{:schedule_type :hourly, :channel_type :slack}}
[10 nil] #{{:schedule_type :daily, :channel_type :slack}
{:schedule_type :hourly, :channel_type :slack}}
[15 nil] #{{:schedule_type :hourly, :channel_type :slack}
{:schedule_type :daily, :channel_type :email}}
[8 "mon"] #{{:schedule_type :weekly, :channel_type :email}
{:schedule_type :hourly, :channel_type :slack}}}]
(testing (cons 'retrieve-scheduled-channels [hour day])
(is (= expected
(set (retrieve-channels hour day))))))))))
(deftest retrive-monthly-scheduled-pulses-test
(testing "specific test for various monthly scheduling permutations"
(letfn [(retrieve-channels [& args]
(for [channel (apply pulse-channel/retrieve-scheduled-channels args)]
(dissoc (into {} channel) :id :pulse_id)))]
(mt/with-temp* [Pulse [{pulse-1-id :id}]
Pulse [{pulse-2-id :id}]
PulseChannel [_ {:pulse_id pulse-1-id, :channel_type :email, :schedule_type :monthly, :schedule_hour 12, :schedule_frame :first}]
PulseChannel [_ {:pulse_id pulse-1-id, :channel_type :slack, :schedule_type :monthly, :schedule_hour 12, :schedule_day "mon", :schedule_frame :first}]
PulseChannel [_ {:pulse_id pulse-2-id, :channel_type :slack, :schedule_type :monthly, :schedule_hour 16, :schedule_frame :mid}]
PulseChannel [_ {:pulse_id pulse-2-id, :channel_type :email, :schedule_type :monthly, :schedule_hour 8, :schedule_day "fri", :schedule_frame :last}]]
(doseq [{:keys [message args expected]}
[{:message "simple starter which should be empty"
:args [nil nil :other :other]
:expected #{}}
{:message "this should capture BOTH first absolute day of month + first monday of month schedules"
:args [12 "mon" :first :first]
:expected #{{:schedule_type :monthly, :channel_type :email}
{:schedule_type :monthly, :channel_type :slack}}}
{:message "this should only capture the first monday of the month"
:args [12 "mon" :other :first]
:expected #{{:schedule_type :monthly, :channel_type :slack}}},
{:message "this makes sure hour checking is being enforced"
:args [8 "mon" :first :first]
:expected #{}}
{:message "middle of the month"
:args [16 "fri" :mid :other]
:expected #{{:schedule_type :monthly, :channel_type :slack}}}
{:message "last friday of the month (but not the last day of month)"
:args [8 "fri" :other :last]
:expected #{{:schedule_type :monthly, :channel_type :email}}}]]
(testing message
(testing (cons 'retrieve-scheduled-channels args)
(is (= expected
(set (apply retrieve-channels args)))))))))))
(deftest inactive-users-test
(testing "Inactive users shouldn't get Pulses"
(mt/with-temp* [Pulse [{pulse-id :id}]
PulseChannel [{channel-id :id, :as channel} {:pulse_id pulse-id
:details {:emails [""]}}]
User [{inactive-user-id :id} {:is_active false}]
PulseChannelRecipient [_ {:pulse_channel_id channel-id, :user_id inactive-user-id}]
PulseChannelRecipient [_ {:pulse_channel_id channel-id, :user_id (mt/user->id :rasta)}]
PulseChannelRecipient [_ {:pulse_channel_id channel-id, :user_id (mt/user->id :lucky)}]]
(is (= (cons
{:email ""}
(sort-by
:id
[{:id (mt/user->id :lucky)
:email ""
:first_name "Lucky"
:last_name "Pigeon"
:common_name "Lucky Pigeon"}
{:id (mt/user->id :rasta)
:email ""
:first_name "Rasta"
:last_name "Toucan"
:common_name "Rasta Toucan"}]))
(:recipients (hydrate channel :recipients)))))))
(deftest validate-email-domains-check-user-ids-match-emails
(testing `pulse-channel/validate-email-domains
(testing "should check that User `:id` and `:email`s match for User `:recipients`"
(let [input {:recipients [{:email ""
:id (mt/user->id :rasta)}]}]
(is (= input
(pulse-channel/validate-email-domains input))))
(testing "Throw Exception if User does not exist"
;; should validate even if `:email` isn't specified
(doseq [input [{:id Integer/MAX_VALUE}
{:email ""
:id Integer/MAX_VALUE}]]
(testing (format "\ninput = %s" (u/pprint-to-str input))
(is (thrown-with-msg?
clojure.lang.ExceptionInfo
#"User [\d,]+ does not exist"
(pulse-channel/validate-email-domains {:recipients [input]}))))))
(is (thrown-with-msg?
clojure.lang.ExceptionInfo
#"Wrong email address for User [\d,]+"
(pulse-channel/validate-email-domains {:recipients [{:email ""
:id (mt/user->id :rasta)}]}))))))
(deftest identity-hash-test
(testing "Pulse channel hashes are composed of the pulse's hash, the channel type, and the details and the collection hash"
(let [now (LocalDateTime/of 2022 9 1 12 34 56)]
(mt/with-temp* [Collection [coll {:name "field-db" :location "/" :created_at now}]
Pulse [pulse {:name "my pulse" :collection_id (:id coll) :created_at now}]
PulseChannel [chan {:pulse_id (:id pulse)
:channel_type :email
:details {:emails [""]}
:created_at now}]]
(is (= "2f5f0269"
(serdes.hash/raw-hash [(serdes.hash/identity-hash pulse) :email {:emails [""]} now])
(serdes.hash/identity-hash chan)))))))
| null | https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/test/metabase/models/pulse_channel_test.clj | clojure | Test out our predicate functions
helper functions
format user details like they would come back for a channel recipient
create a channel then select its details
create-pulse-channel!
should validate even if `:email` isn't specified | (ns metabase.models.pulse-channel-test
(:require [clojure.test :refer :all]
[medley.core :as m]
[metabase.models.collection :refer [Collection]]
[metabase.models.pulse :refer [Pulse]]
[metabase.models.pulse-channel :as pulse-channel :refer [PulseChannel]]
[metabase.models.pulse-channel-recipient :refer [PulseChannelRecipient]]
[metabase.models.serialization.hash :as serdes.hash]
[metabase.models.user :refer [User]]
[metabase.test :as mt]
[metabase.util :as u]
[toucan.db :as db]
[toucan.hydrate :refer [hydrate]])
(:import java.time.LocalDateTime))
(deftest day-of-week?-test
(doseq [[x expected] {nil false
[] false
{} false
"abc" false
"mon" true
:mon false}]
(testing x
(is (= expected
(pulse-channel/day-of-week? x))))))
(deftest hour-of-day?-test
(doseq [[x expected] {nil false
500 false
-12 false
8.5 false
"abc" false
11 true
0 true
23 true}]
(testing x
(is (= expected
(pulse-channel/hour-of-day? x))))))
(deftest schedule-type?-test
(doseq [[x expected] {nil false
"abc" false
123 false
"daily" false
:hourly true
:daily true
:weekly true}]
(testing x
(is (= expected
(pulse-channel/schedule-type? x))))))
(deftest schedule-frame?-test
(doseq [[x expected] {nil false
"abc" false
123 false
"first" false
:first true
:mid true
:last true}]
(testing x
(is (= expected
(pulse-channel/schedule-frame? x))))))
(deftest valid-schedule?-test
(doseq [[group args->expected] {"nil"
{[nil nil nil nil] false
[:foo nil nil nil] false}
"hourly"
{[:hourly nil nil nil] true
[:hourly 12 "abc" nil] true}
"daily"
{[:daily nil nil nil] false
[:daily 35 nil nil] false
[:daily 12 nil nil] true}
"weekly"
{[:weekly nil nil nil] false
[:weekly 12 nil nil] false
[:weekly 12 "blah" nil] false
[:weekly 12 "wed" nil] true}
"monthly"
{[:monthly nil nil nil] false
[:monthly 12 nil nil] false
[:monthly 12 "wed" nil] false
[:monthly 12 nil "abc"] false
[:monthly 12 nil 123] false
[:monthly 12 nil :mid] true
[:monthly 12 nil :first] true
[:monthly 12 nil :last] true
[:monthly 12 "mon" :first] true
[:monthly 12 "fri" :last] true}}
[args expected] args->expected]
(testing group
(testing (cons 'valid-schedule? args)
(is (= expected
(apply pulse-channel/valid-schedule? args)))))))
(deftest channel-type?-test
(doseq [[x expected] {nil false
"abc" false
123 false
:sms false
"email" false
:email true
:slack true}]
(testing x
(is (= expected
(pulse-channel/channel-type? x))))))
(deftest supports-recipients?-test
(doseq [[x expected] {nil false
"abc" false
:email true
:slack false}]
(testing x
(is (= expected
(pulse-channel/supports-recipients? x))))))
(defn user-details
[username]
(-> (mt/fetch-user username)
(dissoc :date_joined :last_login :is_superuser :is_qbnewb :locale)
mt/derecordize))
(defn- create-channel-then-select!
[channel]
(when-let [new-channel-id (pulse-channel/create-pulse-channel! channel)]
(-> (db/select-one PulseChannel :id new-channel-id)
(hydrate :recipients)
(update :recipients #(sort-by :email %))
(dissoc :id :pulse_id :created_at :updated_at)
(update :entity_id boolean)
(m/dissoc-in [:details :emails])
mt/derecordize)))
(defn- update-channel-then-select!
[{:keys [id] :as channel}]
(pulse-channel/update-pulse-channel! channel)
(-> (db/select-one PulseChannel :id id)
(hydrate :recipients)
(dissoc :id :pulse_id :created_at :updated_at)
(update :entity_id boolean)
(m/dissoc-in [:details :emails])
mt/derecordize))
(deftest create-pulse-channel!-test
(mt/with-temp Pulse [{:keys [id]}]
(mt/with-model-cleanup [Pulse]
(testing "disabled"
(is (= {:enabled false
:entity_id true
:channel_type :email
:schedule_type :daily
:schedule_hour 18
:schedule_day nil
:schedule_frame nil
:recipients [(user-details :crowberto)
{:email ""}
(user-details :rasta)]}
(create-channel-then-select!
{:pulse_id id
:enabled false
:channel_type :email
:schedule_type :daily
:schedule_hour 18
:recipients [{:email ""}
{:id (mt/user->id :rasta)}
{:id (mt/user->id :crowberto)}]}))))
(testing "email"
(is (= {:enabled true
:entity_id true
:channel_type :email
:schedule_type :daily
:schedule_hour 18
:schedule_day nil
:schedule_frame nil
:recipients [(user-details :crowberto)
{:email ""}
(user-details :rasta)]}
(create-channel-then-select!
{:pulse_id id
:enabled true
:channel_type :email
:schedule_type :daily
:schedule_hour 18
:recipients [{:email ""}
{:id (mt/user->id :rasta)}
{:id (mt/user->id :crowberto)}]}))))
(testing "slack"
(is (= {:enabled true
:entity_id true
:channel_type :slack
:schedule_type :hourly
:schedule_hour nil
:schedule_day nil
:schedule_frame nil
:recipients []
:details {:something "random"}}
(create-channel-then-select!
{:pulse_id id
:enabled true
:channel_type :slack
:schedule_type :hourly
:details {:something "random"}
:recipients [{:email ""}
{:id (mt/user->id :rasta)}
{:id (mt/user->id :crowberto)}]})))))))
(deftest update-pulse-channel!-test
(mt/with-temp Pulse [{pulse-id :id}]
(testing "simple starting case where we modify the schedule hour and add a recipient"
(mt/with-temp PulseChannel [{channel-id :id} {:pulse_id pulse-id}]
(is (= {:enabled true
:entity_id true
:channel_type :email
:schedule_type :daily
:schedule_hour 18
:schedule_day nil
:schedule_frame nil
:recipients [{:email ""}]}
(update-channel-then-select!
{:id channel-id
:enabled true
:channel_type :email
:schedule_type :daily
:schedule_hour 18
:recipients [{:email ""}]})))))
(testing "monthly schedules require a schedule_frame and can optionally omit they schedule_day"
(mt/with-temp PulseChannel [{channel-id :id} {:pulse_id pulse-id}]
(is (= {:enabled true
:entity_id true
:channel_type :email
:schedule_type :monthly
:schedule_hour 8
:schedule_day nil
:schedule_frame :mid
:recipients [{:email ""} (user-details :rasta)]}
(update-channel-then-select!
{:id channel-id
:enabled true
:channel_type :email
:schedule_type :monthly
:schedule_hour 8
:schedule_day nil
:schedule_frame :mid
:recipients [{:email ""} {:id (mt/user->id :rasta)}]})))))
(testing "weekly schedule should have a day in it, show that we can get full users"
(mt/with-temp PulseChannel [{channel-id :id} {:pulse_id pulse-id}]
(is (= {:enabled true
:entity_id true
:channel_type :email
:schedule_type :weekly
:schedule_hour 8
:schedule_day "mon"
:schedule_frame nil
:recipients [{:email ""} (user-details :rasta)]}
(update-channel-then-select!
{:id channel-id
:enabled true
:channel_type :email
:schedule_type :weekly
:schedule_hour 8
:schedule_day "mon"
:recipients [{:email ""} {:id (mt/user->id :rasta)}]})))))
(testing "hourly schedules don't require day/hour settings (should be nil), fully change recipients"
(mt/with-temp PulseChannel [{channel-id :id} {:pulse_id pulse-id, :details {:emails [""]}}]
(pulse-channel/update-recipients! channel-id [(mt/user->id :rasta)])
(is (= {:enabled true
:entity_id true
:channel_type :email
:schedule_type :hourly
:schedule_hour nil
:schedule_day nil
:schedule_frame nil
:recipients [(user-details :crowberto)]}
(update-channel-then-select!
{:id channel-id
:enabled true
:channel_type :email
:schedule_type :hourly
:schedule_hour 12
:schedule_day "tue"
:recipients [{:id (mt/user->id :crowberto)}]})))))
(testing "custom details for channels that need it"
(mt/with-temp PulseChannel [{channel-id :id} {:pulse_id pulse-id}]
(is (= {:enabled true
:entity_id true
:channel_type :email
:schedule_type :daily
:schedule_hour 12
:schedule_day nil
:schedule_frame nil
:recipients [{:email ""} {:email ""}]
:details {:channel "#metabaserocks"}}
(update-channel-then-select!
{:id channel-id
:enabled true
:channel_type :email
:schedule_type :daily
:schedule_hour 12
:schedule_day "tue"
:recipients [{:email ""} {:email ""}]
:details {:channel "#metabaserocks"}})))))))
(deftest update-recipients!-test
(mt/with-temp* [Pulse [{pulse-id :id}]
PulseChannel [{channel-id :id} {:pulse_id pulse-id}]]
(letfn [(upd-recipients! [recipients]
(pulse-channel/update-recipients! channel-id recipients)
(db/select-field :user_id PulseChannelRecipient, :pulse_channel_id channel-id))]
(doseq [[new-recipients expected] {[] nil
[:rasta] [:rasta]
[:crowberto] [:crowberto]
[:crowberto :rasta] [:crowberto :rasta]
[:rasta :trashbird] [:rasta :trashbird]}]
(testing new-recipients
(is (= (not-empty (set (map mt/user->id expected)))
(upd-recipients! (map mt/user->id new-recipients)))))))))
(deftest retrieve-scheduled-channels-test
(letfn [(retrieve-channels [hour day]
(for [channel (pulse-channel/retrieve-scheduled-channels hour day :other :other)]
(dissoc (into {} channel) :id :pulse_id)))]
(testing "test a simple scenario with a single Pulse and 2 channels on hourly/daily schedules"
(mt/with-temp* [Pulse [{pulse-id :id}]
- > schedule_type = daily , schedule_hour = 15 , channel_type = email
PulseChannel [_ {:pulse_id pulse-id, :channel_type :slack, :schedule_type :hourly}]
PulseChannel [_ {:pulse_id pulse-id, :channel_type :email, :schedule_type :hourly, :enabled false}]]
(doseq [[[hour day] expected] {[nil nil] #{{:schedule_type :hourly, :channel_type :slack}}
[12 nil] #{{:schedule_type :hourly, :channel_type :slack}}
[15 nil] #{{:schedule_type :hourly, :channel_type :slack}
{:schedule_type :daily, :channel_type :email}}
[15 "wed"] #{{:schedule_type :hourly, :channel_type :slack}
{:schedule_type :daily, :channel_type :email}}}]
(testing (cons 'retrieve-scheduled-channels [hour day])
(is (= expected
(set (retrieve-channels hour day))))))))
(testing "more complex scenario with 2 Pulses, including weekly scheduling"
(mt/with-temp* [Pulse [{pulse-1-id :id}]
Pulse [{pulse-2-id :id}]
PulseChannel [_ {:pulse_id pulse-1-id, :enabled true, :channel_type :email, :schedule_type :daily}]
PulseChannel [_ {:pulse_id pulse-1-id, :enabled true, :channel_type :slack, :schedule_type :hourly}]
PulseChannel [_ {:pulse_id pulse-2-id, :enabled true, :channel_type :slack, :schedule_type :daily :schedule_hour 10, :schedule_day "wed"}]
PulseChannel [_ {:pulse_id pulse-2-id, :enabled true, :channel_type :email, :schedule_type :weekly, :schedule_hour 8, :schedule_day "mon"}]]
(doseq [[[hour day] expected] {[nil nil] #{{:schedule_type :hourly, :channel_type :slack}}
[10 nil] #{{:schedule_type :daily, :channel_type :slack}
{:schedule_type :hourly, :channel_type :slack}}
[15 nil] #{{:schedule_type :hourly, :channel_type :slack}
{:schedule_type :daily, :channel_type :email}}
[8 "mon"] #{{:schedule_type :weekly, :channel_type :email}
{:schedule_type :hourly, :channel_type :slack}}}]
(testing (cons 'retrieve-scheduled-channels [hour day])
(is (= expected
(set (retrieve-channels hour day))))))))))
(deftest retrive-monthly-scheduled-pulses-test
(testing "specific test for various monthly scheduling permutations"
(letfn [(retrieve-channels [& args]
(for [channel (apply pulse-channel/retrieve-scheduled-channels args)]
(dissoc (into {} channel) :id :pulse_id)))]
(mt/with-temp* [Pulse [{pulse-1-id :id}]
Pulse [{pulse-2-id :id}]
PulseChannel [_ {:pulse_id pulse-1-id, :channel_type :email, :schedule_type :monthly, :schedule_hour 12, :schedule_frame :first}]
PulseChannel [_ {:pulse_id pulse-1-id, :channel_type :slack, :schedule_type :monthly, :schedule_hour 12, :schedule_day "mon", :schedule_frame :first}]
PulseChannel [_ {:pulse_id pulse-2-id, :channel_type :slack, :schedule_type :monthly, :schedule_hour 16, :schedule_frame :mid}]
PulseChannel [_ {:pulse_id pulse-2-id, :channel_type :email, :schedule_type :monthly, :schedule_hour 8, :schedule_day "fri", :schedule_frame :last}]]
(doseq [{:keys [message args expected]}
[{:message "simple starter which should be empty"
:args [nil nil :other :other]
:expected #{}}
{:message "this should capture BOTH first absolute day of month + first monday of month schedules"
:args [12 "mon" :first :first]
:expected #{{:schedule_type :monthly, :channel_type :email}
{:schedule_type :monthly, :channel_type :slack}}}
{:message "this should only capture the first monday of the month"
:args [12 "mon" :other :first]
:expected #{{:schedule_type :monthly, :channel_type :slack}}},
{:message "this makes sure hour checking is being enforced"
:args [8 "mon" :first :first]
:expected #{}}
{:message "middle of the month"
:args [16 "fri" :mid :other]
:expected #{{:schedule_type :monthly, :channel_type :slack}}}
{:message "last friday of the month (but not the last day of month)"
:args [8 "fri" :other :last]
:expected #{{:schedule_type :monthly, :channel_type :email}}}]]
(testing message
(testing (cons 'retrieve-scheduled-channels args)
(is (= expected
(set (apply retrieve-channels args)))))))))))
(deftest inactive-users-test
(testing "Inactive users shouldn't get Pulses"
(mt/with-temp* [Pulse [{pulse-id :id}]
PulseChannel [{channel-id :id, :as channel} {:pulse_id pulse-id
:details {:emails [""]}}]
User [{inactive-user-id :id} {:is_active false}]
PulseChannelRecipient [_ {:pulse_channel_id channel-id, :user_id inactive-user-id}]
PulseChannelRecipient [_ {:pulse_channel_id channel-id, :user_id (mt/user->id :rasta)}]
PulseChannelRecipient [_ {:pulse_channel_id channel-id, :user_id (mt/user->id :lucky)}]]
(is (= (cons
{:email ""}
(sort-by
:id
[{:id (mt/user->id :lucky)
:email ""
:first_name "Lucky"
:last_name "Pigeon"
:common_name "Lucky Pigeon"}
{:id (mt/user->id :rasta)
:email ""
:first_name "Rasta"
:last_name "Toucan"
:common_name "Rasta Toucan"}]))
(:recipients (hydrate channel :recipients)))))))
(deftest validate-email-domains-check-user-ids-match-emails
(testing `pulse-channel/validate-email-domains
(testing "should check that User `:id` and `:email`s match for User `:recipients`"
(let [input {:recipients [{:email ""
:id (mt/user->id :rasta)}]}]
(is (= input
(pulse-channel/validate-email-domains input))))
(testing "Throw Exception if User does not exist"
(doseq [input [{:id Integer/MAX_VALUE}
{:email ""
:id Integer/MAX_VALUE}]]
(testing (format "\ninput = %s" (u/pprint-to-str input))
(is (thrown-with-msg?
clojure.lang.ExceptionInfo
#"User [\d,]+ does not exist"
(pulse-channel/validate-email-domains {:recipients [input]}))))))
(is (thrown-with-msg?
clojure.lang.ExceptionInfo
#"Wrong email address for User [\d,]+"
(pulse-channel/validate-email-domains {:recipients [{:email ""
:id (mt/user->id :rasta)}]}))))))
(deftest identity-hash-test
(testing "Pulse channel hashes are composed of the pulse's hash, the channel type, and the details and the collection hash"
(let [now (LocalDateTime/of 2022 9 1 12 34 56)]
(mt/with-temp* [Collection [coll {:name "field-db" :location "/" :created_at now}]
Pulse [pulse {:name "my pulse" :collection_id (:id coll) :created_at now}]
PulseChannel [chan {:pulse_id (:id pulse)
:channel_type :email
:details {:emails [""]}
:created_at now}]]
(is (= "2f5f0269"
(serdes.hash/raw-hash [(serdes.hash/identity-hash pulse) :email {:emails [""]} now])
(serdes.hash/identity-hash chan)))))))
|
7bb55541f35d8ac28a4599d28e4a5439af2a42e7bea1343b28bbecb0948701c7 | TerrorJack/ghc-alter | Internals.hs | # LANGUAGE NoImplicitPrelude #
# LANGUAGE MagicHash #
# LANGUAGE UnboxedTuples #
# LANGUAGE CPP #
{-# OPTIONS_HADDOCK hide #-}
#include "MachDeps.h"
#if WORD_SIZE_IN_BITS == 32
# define WSHIFT 5
# define MMASK 31
#elif WORD_SIZE_IN_BITS == 64
# define WSHIFT 6
# define MMASK 63
#else
# error unsupported WORD_SIZE_IN_BITS
#endif
| Fast ' Integer ' logarithms to base 2 . ' integerLog2 # ' and
-- 'wordLog2#' are of general usefulness, the others are only needed
-- for a fast implementation of 'fromRational'. Since they are needed
in " GHC.Float " , we must expose this module , but it should not show
-- up in the docs.
--
-- See
-- for the origin of the code in this module
module GHC.Integer.Logarithms.Internals
( wordLog2#
, integerLog2IsPowerOf2#
, integerLog2#
, roundingMode#
) where
import GHC.Integer.Type
import GHC.Integer.Logarithms
import GHC.Types
import GHC.Prim
default ()
-- | Extended version of 'integerLog2#'
--
-- Assumption: Integer is strictly positive
--
First component of result is @log2 n@ , second is @0#@ iff /n/ is a
power of two .
integerLog2IsPowerOf2# :: Integer -> (# Int#, Int# #)
The power of 2 test is n&(n-1 ) = = 0 , thus powers of 2
are indicated bythe second component being zero .
integerLog2IsPowerOf2# (S# i#) = case int2Word# i# of
w -> (# wordLog2# w, word2Int# (w `and#` (w `minusWord#` 1##)) #)
integerLog2IsPowerOf2# (Jn# _) = (# -1#, -1# #)
-- Find the log2 as above, test whether that word is a power
of 2 , if so , check whether only zero bits follow .
integerLog2IsPowerOf2# (Jp# bn) = check (s -# 1#)
where
s = sizeofBigNat# bn
check :: Int# -> (# Int#, Int# #)
check i = case indexBigNat# bn i of
0## -> check (i -# 1#)
w -> (# wordLog2# w +# (uncheckedIShiftL# i WSHIFT#)
, case w `and#` (w `minusWord#` 1##) of
0## -> test (i -# 1#)
_ -> 1# #)
test :: Int# -> Int#
test i = if isTrue# (i <# 0#)
then 0#
else case indexBigNat# bn i of
0## -> test (i -# 1#)
_ -> 1#
-- Assumption: Integer and Int# are strictly positive, Int# is less
than logBase 2 of Integer , otherwise havoc ensues .
-- Used only for the numerator in fromRational when the denominator
is a power of 2 .
-- The Int# argument is log2 n minus the number of bits in the mantissa
of the target type , i.e. the index of the first non - integral bit in
-- the quotient.
--
0 # means round down ( towards zero )
1 # means we have a half - integer , round to even
2 # means round up ( away from zero )
roundingMode# :: Integer -> Int# -> Int#
roundingMode# (S# i#) t =
case int2Word# i# `and#` ((uncheckedShiftL# 2## t) `minusWord#` 1##) of
k -> case uncheckedShiftL# 1## t of
c -> if isTrue# (c `gtWord#` k)
then 0#
else if isTrue# (c `ltWord#` k)
then 2#
else 1#
roundingMode# (Jn# bn) t = roundingMode# (Jp# bn) t -- dummy
roundingMode# (Jp# bn) t =
case word2Int# (int2Word# t `and#` MMASK##) of
j -> -- index of relevant bit in word
case uncheckedIShiftRA# t WSHIFT# of
k -> -- index of relevant word
case indexBigNat# bn k `and#`
((uncheckedShiftL# 2## j) `minusWord#` 1##) of
r ->
case uncheckedShiftL# 1## j of
c -> if isTrue# (c `gtWord#` r)
then 0#
else if isTrue# (c `ltWord#` r)
then 2#
else test (k -# 1#)
where
test i = if isTrue# (i <# 0#)
then 1#
else case indexBigNat# bn i of
0## -> test (i -# 1#)
_ -> 2#
| null | https://raw.githubusercontent.com/TerrorJack/ghc-alter/db736f34095eef416b7e077f9b26fc03aa78c311/ghc-alter/boot-lib/integer-gmp/src/GHC/Integer/Logarithms/Internals.hs | haskell | # OPTIONS_HADDOCK hide #
'wordLog2#' are of general usefulness, the others are only needed
for a fast implementation of 'fromRational'. Since they are needed
up in the docs.
See
for the origin of the code in this module
| Extended version of 'integerLog2#'
Assumption: Integer is strictly positive
Find the log2 as above, test whether that word is a power
Assumption: Integer and Int# are strictly positive, Int# is less
Used only for the numerator in fromRational when the denominator
The Int# argument is log2 n minus the number of bits in the mantissa
the quotient.
dummy
index of relevant bit in word
index of relevant word | # LANGUAGE NoImplicitPrelude #
# LANGUAGE MagicHash #
# LANGUAGE UnboxedTuples #
# LANGUAGE CPP #
#include "MachDeps.h"
#if WORD_SIZE_IN_BITS == 32
# define WSHIFT 5
# define MMASK 31
#elif WORD_SIZE_IN_BITS == 64
# define WSHIFT 6
# define MMASK 63
#else
# error unsupported WORD_SIZE_IN_BITS
#endif
| Fast ' Integer ' logarithms to base 2 . ' integerLog2 # ' and
in " GHC.Float " , we must expose this module , but it should not show
module GHC.Integer.Logarithms.Internals
( wordLog2#
, integerLog2IsPowerOf2#
, integerLog2#
, roundingMode#
) where
import GHC.Integer.Type
import GHC.Integer.Logarithms
import GHC.Types
import GHC.Prim
default ()
First component of result is @log2 n@ , second is @0#@ iff /n/ is a
power of two .
integerLog2IsPowerOf2# :: Integer -> (# Int#, Int# #)
The power of 2 test is n&(n-1 ) = = 0 , thus powers of 2
are indicated bythe second component being zero .
integerLog2IsPowerOf2# (S# i#) = case int2Word# i# of
w -> (# wordLog2# w, word2Int# (w `and#` (w `minusWord#` 1##)) #)
integerLog2IsPowerOf2# (Jn# _) = (# -1#, -1# #)
of 2 , if so , check whether only zero bits follow .
integerLog2IsPowerOf2# (Jp# bn) = check (s -# 1#)
where
s = sizeofBigNat# bn
check :: Int# -> (# Int#, Int# #)
check i = case indexBigNat# bn i of
0## -> check (i -# 1#)
w -> (# wordLog2# w +# (uncheckedIShiftL# i WSHIFT#)
, case w `and#` (w `minusWord#` 1##) of
0## -> test (i -# 1#)
_ -> 1# #)
test :: Int# -> Int#
test i = if isTrue# (i <# 0#)
then 0#
else case indexBigNat# bn i of
0## -> test (i -# 1#)
_ -> 1#
than logBase 2 of Integer , otherwise havoc ensues .
is a power of 2 .
of the target type , i.e. the index of the first non - integral bit in
0 # means round down ( towards zero )
1 # means we have a half - integer , round to even
2 # means round up ( away from zero )
roundingMode# :: Integer -> Int# -> Int#
roundingMode# (S# i#) t =
case int2Word# i# `and#` ((uncheckedShiftL# 2## t) `minusWord#` 1##) of
k -> case uncheckedShiftL# 1## t of
c -> if isTrue# (c `gtWord#` k)
then 0#
else if isTrue# (c `ltWord#` k)
then 2#
else 1#
roundingMode# (Jp# bn) t =
case word2Int# (int2Word# t `and#` MMASK##) of
case uncheckedIShiftRA# t WSHIFT# of
case indexBigNat# bn k `and#`
((uncheckedShiftL# 2## j) `minusWord#` 1##) of
r ->
case uncheckedShiftL# 1## j of
c -> if isTrue# (c `gtWord#` r)
then 0#
else if isTrue# (c `ltWord#` r)
then 2#
else test (k -# 1#)
where
test i = if isTrue# (i <# 0#)
then 1#
else case indexBigNat# bn i of
0## -> test (i -# 1#)
_ -> 2#
|
3372c245007545a0c8c72a5f42f0789effc3ceaed0300c17e7768a5a0e823185 | HeinrichApfelmus/reactive-banana | CRUDIncremental.hs | ----------------------------------------------------------------------------
reactive - banana - wx
Example : ListBox with CRUD operations
-----------------------------------------------------------------------------
reactive-banana-wx
Example: ListBox with CRUD operations
------------------------------------------------------------------------------}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE RecursiveDo #
import Control.Monad (join)
import qualified Data.List
import Data.Maybe
import qualified Data.Map as Map
import Graphics.UI.WX as WX hiding (Event)
import Reactive.Banana
import Reactive.Banana.WX
{-----------------------------------------------------------------------------
Main
------------------------------------------------------------------------------}
main = start $ do
-- GUI layout
f <- frame [ text := "CRUD Example" ]
listBox <- singleListBox f []
create <- button f [ text := "Create" ]
delete <- button f [ text := "Delete" ]
filter <- entry f [ processEnter := True ]
name <- entry f [ processEnter := True ]
surname <- entry f [ processEnter := True ]
let dataItem = grid 10 10 [[label "Name:", widget name]
,[label "Surname:", widget surname]]
set f [layout := margin 10 $
grid 10 5
[[row 5 [label "Filter prefix:", widget filter], glue]
,[minsize (sz 200 300) $ widget listBox, dataItem]
,[row 10 [widget create, widget delete], glue]
]]
-- event network
let networkDescription :: forall t. NetworkDescription t ()
networkDescription = mdo
-- events from buttons
eDelete <- event0 delete command
eCreate <- event0 create command
-- time-varying value corresponding to the filter string
(bFilter, eFilter) <- reactimateTextEntry filter (pure "")
let dFilter = stepperD "" $ bFilter <@ eFilter
-- list box with selection
dSelectedItem <- reactimateListBox listBox database dFilter
-- data corresponding to the selected item in the list box
(inDataItem, changeDataItem)
<- reactimateDataItem (name, surname) outDataItem
let
-- update the database whenever
-- a data item is created, updated or deleted
database :: DatabaseTime DataItem
database = accumDatabase $
(Create Nothing ("Emil","Example") <$ eCreate)
`union` (Update <$> dSelectedItem <@>
(inDataItem <@ changeDataItem))
`union` (Delete <$> dSelectedItem <@ eDelete )
-- display the data item whenever the selection changes
outDataItem = stepperD ("","") $
lookup <$> valueDB database <@> changes dSelectedItem
where
lookup database m = fromMaybe ("","") $
readDatabase database =<< m
-- automatically enable / disable editing
let dDisplayItem = isJust <$> dSelectedItem
sink delete [ enabled :== dDisplayItem ]
sink name [ enabled :== dDisplayItem ]
sink surname [ enabled :== dDisplayItem ]
network <- compile networkDescription
actuate network
{-----------------------------------------------------------------------------
Database Model
------------------------------------------------------------------------------}
-- Create/Update/Delete data type for efficient updates
data CUD key a
= Create { getKey :: key, getItem :: a }
| Update { getKey :: key, getItem :: a }
| Delete { getKey :: key }
instance Functor (CUD key) where
fmap f (Delete x) = Delete x
fmap f cud = cud { getItem = f $ getItem cud }
isDelete (Delete _) = True
isDelete _ = False
-- Database type
type DatabaseKey = Int
data Database a = Database { nextKey :: !Int, db :: Map.Map DatabaseKey a }
emptyDatabase = Database 0 Map.empty
Time - varying database ,
-- similar to the Discrete type
data DatabaseTime a = DatabaseTime
{ valueDB :: Behavior (Database a)
, initialDB :: Database a
, changesDB :: Event (CUD DatabaseKey a)
}
accumulate a database from CUD operations
accumDatabase :: Event (CUD (Maybe DatabaseKey) a) -> DatabaseTime a
accumDatabase e = DatabaseTime valueDB initialDB changesDB
where
(changesDB, valueDB) = mapAccum initialDB $ acc <$> filterE valid e
initialDB = emptyDatabase
valid (Create Nothing _) = True
valid cud = isJust $ getKey cud
-- accumulation function
acc (Create Nothing x) (Database newkey db)
= (Create newkey x, Database (newkey+1) $ Map.insert newkey x db)
acc (Update (Just key) x) (Database newkey db)
= (Update key x, Database newkey $ Map.insert key x db)
acc (Delete (Just key)) (Database newkey db)
= (Delete key , Database newkey $ Map.delete key db)
-- read a value from the database
readDatabase :: Database a -> DatabaseKey -> Maybe a
readDatabase (Database _ db) = flip Map.lookup db
{-----------------------------------------------------------------------------
Data items that are stored in the data base
------------------------------------------------------------------------------}
type DataItem = (String, String)
-- text entry widgets in terms of discrete time-varying values
reactimateTextEntry
:: TextCtrl a
-> Discrete String -- set text programmatically (view)
-> NetworkDescription
(Behavior String -- current text (both view & controller)
,Event ()) -- user changes (controller)
reactimateTextEntry entry input = do
sink entry [ text :== input ]
-- event: Enter key
eEnter <- event0 entry command
-- event: text entry loses focus
eLeave <- (() <$) . filterE not <$> event1 entry focus
b <- behavior entry text
return (b, eEnter `union` eLeave)
whole data item ( consisting of two text entries )
reactimateDataItem
:: (TextCtrl a, TextCtrl b)
-> Discrete DataItem
-> NetworkDescription
(Behavior DataItem, Event ())
reactimateDataItem (name,surname) input = do
(d1,e1) <- reactimateTextEntry name (fst <$> input)
(d2,e2) <- reactimateTextEntry surname (snd <$> input)
return ( (,) <$> d1 <*> d2 , e1 `union` e2 )
-- custom show function
showDataItem (name, surname) = surname ++ ", " ++ name
{-----------------------------------------------------------------------------
List Box View
------------------------------------------------------------------------------}
-- Display the data base in a list box (view).
-- Also keep track of the currently selected item (controller).
reactimateListBox
:: SingleListBox b -- list box widget
-> DatabaseTime DataItem -- database
-> Discrete String -- filter string
-> NetworkDescription
(Discrete (Maybe DatabaseKey)) -- current selection as database key
reactimateListBox listBox database filter = do
-- The list box keeps track
-- of which data items are displayed, at which positions
let (eListBoxUpdates, bDisplayMap)
= mapAccum Map.empty
$ (cudUpdate . fmap showDataItem <$> changesDB database)
`union` (filterUpdate <$> valueDB database <@> changes filter)
-- "animate" changes to the list box
reactimate eListBoxUpdates
-- debug: reactimate $ fmap print $ bDisplayMap <@ eListBoxUpdates
-- event: item selection, maps to database key
fixSelectionEvent listBox
bSelection <- behavior listBox selection
eSelect <- event0 listBox select
let eDelete = filterE isDelete $ changesDB database
return $ stepperD Nothing $
-- event: item deleted
(Nothing <$ eDelete) `union`
-- event: filter string changed
(Nothing <$ changes filter) `union`
-- event: user changes selection
(lookupPositon <$> bSelection <*> bDisplayMap <@ eSelect)
where
turn CUD into a function that updates
-- ( the graphics of the list box
-- , the map from database keys to list positions )
cudUpdate
:: CUD DatabaseKey String -> DisplayMap -> (IO (), DisplayMap)
cudUpdate (Create key str) display
= (itemAppend listBox str, appendKey key display)
cudUpdate (Update key str) display
= case lookupKey key display of
Just position -> (set listBox [ item position := str ], display)
Nothing -> (return (), display)
cudUpdate (Delete key) display
= case lookupKey key display of
Just position -> (itemDelete listBox position
,deleteKey key position display)
Nothing -> (return (), display)
-- rebuild listBox when filter string changes
filterUpdate database s _ = (set listBox [ items := xs ], display)
where
dat = Map.filter (s `Data.List.isPrefixOf`)
. Map.map showDataItem . db $ database
xs = Map.elems dat
display = Map.fromList $ zip (Map.keys dat) [0..]
-- Map between database keys and their position in the list box
type DisplayMap = Map.Map DatabaseKey Int
lookupKey = Map.lookup
lookupPositon pos = fmap fst . Data.List.find ((pos ==) . snd) . Map.toList
appendKey key display = Map.insert key (Map.size display) display
deleteKey key position display
= Map.delete key
-- recalculate positions of the other elements
. Map.map (\pos -> if pos > position then pos - 1 else pos)
$ display
{-----------------------------------------------------------------------------
wxHaskell bug fixes
------------------------------------------------------------------------------}
-- Fix @select@ event not being fired when items are *un*selected
fixSelectionEvent listbox =
liftIO $ set listbox [ on unclick := handler ]
where
handler _ = do
propagateEvent
s <- get listbox selection
when (s == -1) $ join $ get listbox (on select)
| null | https://raw.githubusercontent.com/HeinrichApfelmus/reactive-banana/79482f3e9bfab493e2d2197f70cdb11787b33a03/reactive-banana-wx/src/CRUDIncremental.hs | haskell | --------------------------------------------------------------------------
---------------------------------------------------------------------------
----------------------------------------------------------------------------}
----------------------------------------------------------------------------
Main
-----------------------------------------------------------------------------
GUI layout
event network
events from buttons
time-varying value corresponding to the filter string
list box with selection
data corresponding to the selected item in the list box
update the database whenever
a data item is created, updated or deleted
display the data item whenever the selection changes
automatically enable / disable editing
----------------------------------------------------------------------------
Database Model
-----------------------------------------------------------------------------
Create/Update/Delete data type for efficient updates
Database type
similar to the Discrete type
accumulation function
read a value from the database
----------------------------------------------------------------------------
Data items that are stored in the data base
-----------------------------------------------------------------------------
text entry widgets in terms of discrete time-varying values
set text programmatically (view)
current text (both view & controller)
user changes (controller)
event: Enter key
event: text entry loses focus
custom show function
----------------------------------------------------------------------------
List Box View
-----------------------------------------------------------------------------
Display the data base in a list box (view).
Also keep track of the currently selected item (controller).
list box widget
database
filter string
current selection as database key
The list box keeps track
of which data items are displayed, at which positions
"animate" changes to the list box
debug: reactimate $ fmap print $ bDisplayMap <@ eListBoxUpdates
event: item selection, maps to database key
event: item deleted
event: filter string changed
event: user changes selection
( the graphics of the list box
, the map from database keys to list positions )
rebuild listBox when filter string changes
Map between database keys and their position in the list box
recalculate positions of the other elements
----------------------------------------------------------------------------
wxHaskell bug fixes
-----------------------------------------------------------------------------
Fix @select@ event not being fired when items are *un*selected | reactive - banana - wx
Example : ListBox with CRUD operations
reactive-banana-wx
Example: ListBox with CRUD operations
# LANGUAGE ScopedTypeVariables #
# LANGUAGE RecursiveDo #
import Control.Monad (join)
import qualified Data.List
import Data.Maybe
import qualified Data.Map as Map
import Graphics.UI.WX as WX hiding (Event)
import Reactive.Banana
import Reactive.Banana.WX
main = start $ do
f <- frame [ text := "CRUD Example" ]
listBox <- singleListBox f []
create <- button f [ text := "Create" ]
delete <- button f [ text := "Delete" ]
filter <- entry f [ processEnter := True ]
name <- entry f [ processEnter := True ]
surname <- entry f [ processEnter := True ]
let dataItem = grid 10 10 [[label "Name:", widget name]
,[label "Surname:", widget surname]]
set f [layout := margin 10 $
grid 10 5
[[row 5 [label "Filter prefix:", widget filter], glue]
,[minsize (sz 200 300) $ widget listBox, dataItem]
,[row 10 [widget create, widget delete], glue]
]]
let networkDescription :: forall t. NetworkDescription t ()
networkDescription = mdo
eDelete <- event0 delete command
eCreate <- event0 create command
(bFilter, eFilter) <- reactimateTextEntry filter (pure "")
let dFilter = stepperD "" $ bFilter <@ eFilter
dSelectedItem <- reactimateListBox listBox database dFilter
(inDataItem, changeDataItem)
<- reactimateDataItem (name, surname) outDataItem
let
database :: DatabaseTime DataItem
database = accumDatabase $
(Create Nothing ("Emil","Example") <$ eCreate)
`union` (Update <$> dSelectedItem <@>
(inDataItem <@ changeDataItem))
`union` (Delete <$> dSelectedItem <@ eDelete )
outDataItem = stepperD ("","") $
lookup <$> valueDB database <@> changes dSelectedItem
where
lookup database m = fromMaybe ("","") $
readDatabase database =<< m
let dDisplayItem = isJust <$> dSelectedItem
sink delete [ enabled :== dDisplayItem ]
sink name [ enabled :== dDisplayItem ]
sink surname [ enabled :== dDisplayItem ]
network <- compile networkDescription
actuate network
data CUD key a
= Create { getKey :: key, getItem :: a }
| Update { getKey :: key, getItem :: a }
| Delete { getKey :: key }
instance Functor (CUD key) where
fmap f (Delete x) = Delete x
fmap f cud = cud { getItem = f $ getItem cud }
isDelete (Delete _) = True
isDelete _ = False
type DatabaseKey = Int
data Database a = Database { nextKey :: !Int, db :: Map.Map DatabaseKey a }
emptyDatabase = Database 0 Map.empty
Time - varying database ,
data DatabaseTime a = DatabaseTime
{ valueDB :: Behavior (Database a)
, initialDB :: Database a
, changesDB :: Event (CUD DatabaseKey a)
}
accumulate a database from CUD operations
accumDatabase :: Event (CUD (Maybe DatabaseKey) a) -> DatabaseTime a
accumDatabase e = DatabaseTime valueDB initialDB changesDB
where
(changesDB, valueDB) = mapAccum initialDB $ acc <$> filterE valid e
initialDB = emptyDatabase
valid (Create Nothing _) = True
valid cud = isJust $ getKey cud
acc (Create Nothing x) (Database newkey db)
= (Create newkey x, Database (newkey+1) $ Map.insert newkey x db)
acc (Update (Just key) x) (Database newkey db)
= (Update key x, Database newkey $ Map.insert key x db)
acc (Delete (Just key)) (Database newkey db)
= (Delete key , Database newkey $ Map.delete key db)
readDatabase :: Database a -> DatabaseKey -> Maybe a
readDatabase (Database _ db) = flip Map.lookup db
type DataItem = (String, String)
reactimateTextEntry
:: TextCtrl a
-> NetworkDescription
reactimateTextEntry entry input = do
sink entry [ text :== input ]
eEnter <- event0 entry command
eLeave <- (() <$) . filterE not <$> event1 entry focus
b <- behavior entry text
return (b, eEnter `union` eLeave)
whole data item ( consisting of two text entries )
reactimateDataItem
:: (TextCtrl a, TextCtrl b)
-> Discrete DataItem
-> NetworkDescription
(Behavior DataItem, Event ())
reactimateDataItem (name,surname) input = do
(d1,e1) <- reactimateTextEntry name (fst <$> input)
(d2,e2) <- reactimateTextEntry surname (snd <$> input)
return ( (,) <$> d1 <*> d2 , e1 `union` e2 )
showDataItem (name, surname) = surname ++ ", " ++ name
reactimateListBox
-> NetworkDescription
reactimateListBox listBox database filter = do
let (eListBoxUpdates, bDisplayMap)
= mapAccum Map.empty
$ (cudUpdate . fmap showDataItem <$> changesDB database)
`union` (filterUpdate <$> valueDB database <@> changes filter)
reactimate eListBoxUpdates
fixSelectionEvent listBox
bSelection <- behavior listBox selection
eSelect <- event0 listBox select
let eDelete = filterE isDelete $ changesDB database
return $ stepperD Nothing $
(Nothing <$ eDelete) `union`
(Nothing <$ changes filter) `union`
(lookupPositon <$> bSelection <*> bDisplayMap <@ eSelect)
where
turn CUD into a function that updates
cudUpdate
:: CUD DatabaseKey String -> DisplayMap -> (IO (), DisplayMap)
cudUpdate (Create key str) display
= (itemAppend listBox str, appendKey key display)
cudUpdate (Update key str) display
= case lookupKey key display of
Just position -> (set listBox [ item position := str ], display)
Nothing -> (return (), display)
cudUpdate (Delete key) display
= case lookupKey key display of
Just position -> (itemDelete listBox position
,deleteKey key position display)
Nothing -> (return (), display)
filterUpdate database s _ = (set listBox [ items := xs ], display)
where
dat = Map.filter (s `Data.List.isPrefixOf`)
. Map.map showDataItem . db $ database
xs = Map.elems dat
display = Map.fromList $ zip (Map.keys dat) [0..]
type DisplayMap = Map.Map DatabaseKey Int
lookupKey = Map.lookup
lookupPositon pos = fmap fst . Data.List.find ((pos ==) . snd) . Map.toList
appendKey key display = Map.insert key (Map.size display) display
deleteKey key position display
= Map.delete key
. Map.map (\pos -> if pos > position then pos - 1 else pos)
$ display
fixSelectionEvent listbox =
liftIO $ set listbox [ on unclick := handler ]
where
handler _ = do
propagateEvent
s <- get listbox selection
when (s == -1) $ join $ get listbox (on select)
|
66306183a34b49417454e42957401d7ee84125165d05faa2abc268e6fea565bb | PEZ/rich4clojure | problem_134.clj | (ns rich4clojure.elementary.problem-134
(:require [hyperfiddle.rcf :refer [tests]]))
;; = A nil key =
By 4Clojure user :
;; Difficulty: Elementary
;; Tags: [maps]
;;
;; Write a function which, given a key and map, returns
;; true iff the map contains an entry with that key and
;; its value is nil.
(def __ :tests-will-fail)
(comment
)
(tests
(__ :a {:a nil :b 2}) :=
(__ :b {:a nil :b 2}) :=
(__ :c {:a nil :b 2}) :=)
;; Share your solution, and/or check how others did it:
| null | https://raw.githubusercontent.com/PEZ/rich4clojure/2ccfac041840e9b1550f0a69b9becbdb03f9525b/src/rich4clojure/elementary/problem_134.clj | clojure | = A nil key =
Difficulty: Elementary
Tags: [maps]
Write a function which, given a key and map, returns
true iff the map contains an entry with that key and
its value is nil.
Share your solution, and/or check how others did it: | (ns rich4clojure.elementary.problem-134
(:require [hyperfiddle.rcf :refer [tests]]))
By 4Clojure user :
(def __ :tests-will-fail)
(comment
)
(tests
(__ :a {:a nil :b 2}) :=
(__ :b {:a nil :b 2}) :=
(__ :c {:a nil :b 2}) :=)
|
aebe5d21d7cf4ce941a4c23a0afd4c4f5e55f8cd76dfc09512b11e040ee72601 | MalloZup/fullrocketmetal | core_test.clj | (ns fullrocketmetal.core-test
(:require [clojure.test :refer :all]
[fullrocketmetal.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
| null | https://raw.githubusercontent.com/MalloZup/fullrocketmetal/6029a2d2bf6c59910611650e7adaaf7b4c3697ae/test/fullrocketmetal/core_test.clj | clojure | (ns fullrocketmetal.core-test
(:require [clojure.test :refer :all]
[fullrocketmetal.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
| |
89ecb615262cac8213620ab520aef0153d14c6c73f639ec5964af0a52f1907ab | bravit/bob19-tutorial-types | 11-phantoms.hs | # LANGUAGE GeneralizedNewtypeDeriving #
-- Does it make sense to have types without values? Absolutely!
-- 'unit' is called a phantom type
newtype Weight unit = Weight Double
deriving (Num, Show)
data Kg
data Lb
w1 :: Weight Kg
w1 = Weight 81
w2 :: Weight Lb
w2 = Weight 120
--ghci
-- >>> w1 + w2
-- <TYPE ERROR!>
-- >>> :back
kg2lb :: Weight Kg -> Weight Lb
kg2lb (Weight wkg) =
Weight (wkg * 2.205)
--ghci
-- $
-- >>> kg2lb w1 + w2
-- Weight 298.605
-- >>> :☛ This is type level!
-- >>> :☛ Unfortunately, this works too:
-- $
> > > let w3 = Weight 0 : :
-- >>> w3
-- Weight 0.0
main = undefined
| null | https://raw.githubusercontent.com/bravit/bob19-tutorial-types/ba2a575e36b97ec01a18a39115e8a96a8543a53f/code/11-phantoms.hs | haskell | Does it make sense to have types without values? Absolutely!
'unit' is called a phantom type
ghci
>>> w1 + w2
<TYPE ERROR!>
>>> :back
ghci
$
>>> kg2lb w1 + w2
Weight 298.605
>>> :☛ This is type level!
>>> :☛ Unfortunately, this works too:
$
>>> w3
Weight 0.0 | # LANGUAGE GeneralizedNewtypeDeriving #
newtype Weight unit = Weight Double
deriving (Num, Show)
data Kg
data Lb
w1 :: Weight Kg
w1 = Weight 81
w2 :: Weight Lb
w2 = Weight 120
kg2lb :: Weight Kg -> Weight Lb
kg2lb (Weight wkg) =
Weight (wkg * 2.205)
> > > let w3 = Weight 0 : :
main = undefined
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.